gnomonlearn
Docs/Build & infra/RFC-0032

RFC-0032 · `rules_gnomon` — Bazel Build Rules for Gnomon Modules

Versioned draft snapshot

RFCs, reference catalogs, and evidence reflect Spec 3b2e3e7a114fb826b1445d39a48756b8fff629cd. Counts and pending/status notes belong to that snapshot. Read the dated project update for later progress.

Source repositories are private during staging. Links marked “repository access required” need access to the linked repository.

Status Draft corpus. Reference catalogs and RDF projections have generation drift checks; Gnomon proofs and projection semantics remain unverified for release.

View the generated reference catalog →

Read design questions and decisions →


Reference catalog: the diagnostics, linked-RFC graph, defined terms, and normative-rule index for this RFC are in the reference catalog, generated from the structured Lean module. This document carries the prose: design rationale, entity-shape definitions in context, and migration notes.


1. Purpose

This RFC defines rules_gnomon, the Bazel rule set for building, testing, and deploying gnomon modules. It specifies:

  1. The core build rules (gnomon_module, gnomon_kernel, gnomon_test, gnomon_migration)
  2. The gnomon compiler toolchain declaration
  3. Integration with rules_rust (kernel WASM compilation) and rules_proto + Buf (gRPC service schemas)
  4. The Gazelle extension that auto-generates BUILD files from project.gnm
  5. Remote execution and caching configuration

rules_gnomon is the build layer. It does not define the gnomon language (RFC-0008), the compiler internals (RFC-0018), or the runtime (RFC-0010). It defines how Bazel understands gnomon artifacts as build targets.


2. Context and Motivation

Why Bazel

Gnomon modules have several properties that make Bazel a strong fit:

  • Hermetic compilation — the gnomon compiler takes .gnm sources and imported module bundles as inputs and produces a deterministic compiled bundle (RFC-0002). Bazel’s strict input/output model enforces hermeticity without additional tooling.
  • Multi-language outputs — a single gnomon_module target produces: a compiled bundle (rkyv binary), a kernel WASM artifact (Rust), gRPC service stubs (protobuf/Rust/TypeScript), and a JSON IR for tooling. Bazel’s provider system handles multi-output targets cleanly.
  • Incremental builds across the IR boundary — the rkyv IR (RFC-0010 §4.6) is a stable, content-addressed artifact. Bazel’s caching means unchanged modules are never recompiled, and the kernel is only re-linked when its input bundle changes.
  • Remote execution — the compiler and Rust/WASM linker steps are compute-intensive and benefit from remote execution (RBE). Bazel’s RBE support is mature.

Toolchain stack

rules_gnomon sits above three existing rule sets:

Rule setRole in gnomon build
rules_rustCompiles generated Rust kernel reducers to WASM
rules_proto + BufGenerates gRPC stubs for compiler services and IO adapter contracts
rules_gnomon (this RFC)Orchestrates the full gnomon compile pipeline; owns gnomon_* rules

No Cap’n Proto rules are required. The rkyv IR format is a Rust library dependency (Cargo.toml), not a Bazel code-generation step.


3. The Gnomon Compiler Toolchain

Before any gnomon_* rule can run, the gnomon compiler must be declared as a Bazel toolchain. This follows the standard Bazel toolchain pattern.

# In rules_gnomon/toolchain.bzl

GnomonCompilerInfo = provider(
    doc = "Gnomon compiler toolchain metadata.",
    fields = {
        "compiler": "File: the gnomon compiler binary",
        "version":  "string: semver of the compiler",
        "target_abi": "string: kernel WASM ABI version (RFC-0010 §6.9)",
    },
)

def _gnomon_toolchain_impl(ctx):
    return [
        platform_common.ToolchainInfo(
            gnomon = GnomonCompilerInfo(
                compiler   = ctx.executable.compiler,
                version    = ctx.attr.version,
                target_abi = ctx.attr.target_abi,
            ),
        ),
    ]

gnomon_toolchain = rule(
    implementation = _gnomon_toolchain_impl,
    attrs = {
        "compiler":   attr.label(executable = True, cfg = "exec", mandatory = True),
        "version":    attr.string(mandatory = True),
        "target_abi": attr.string(default = "1"),
    },
)

The toolchain is registered in the project’s WORKSPACE or MODULE.bazel:

# MODULE.bazel
bazel_dep(name = "rules_gnomon", version = "0.1.0")

gnomon = use_extension("@rules_gnomon//gnomon:extensions.bzl", "gnomon")
gnomon.toolchain(version = "0.1.0")
use_repo(gnomon, "gnomon_toolchain")
register_toolchains("@gnomon_toolchain//:toolchain")

4. Core Build Rules

4.1 gnomon_module

Compiles a set of .gnm source files into a compiled bundle (RFC-0002). This is the primary build rule — every other gnomon_* rule depends on an gnomon_module target.

gnomon_module(
    name = "household",
    srcs = [
        "household.gnm",
        "household-mutations.gnm",
        "actions.gnm",
        "household-procedures.gnm",
        "household-events.gnm",
    ],
    manifest = "module.gnm",        # module manifest (RFC-0001); not in srcs
    project = "//:project",          # the project.gnm target
    deps = [
        "//modules/auth:user",       # imported gnomon_module targets
    ],
    visibility = ["//visibility:public"],
)

Outputs:

OutputFormatDescription
<name>.bundlerkyv binaryCompiled bundle (RFC-0002); input to gnomon_kernel
<name>.ir.jsonserde JSONIR for LSP, Gnomon Studio, migration tooling (RFC-0010 §4.6)
<name>.schema.sqlSQL DDLStorage manifest (RFC-0002 §7); input to gnomon_migration

Attributes:

AttributeTypeDescription
srcslabel_list.gnm source files; MUST all be in the same module directory
manifestLabelpath to module.gnm for this target; passed as a manifest, not in srcs
projectlabelThe gnomon_project target for this workspace
depslabel_listUpstream gnomon_module targets this module imports
clientslabel_listgnomon_client targets declaring external API contracts (RFC-0024)
visibility—Standard Bazel visibility

Note on clients: Each gnomon_client target provides an GnomonClientInfo provider. The gnomon_module action uses the src and specs depsets from these providers as additional hermetic inputs to the compile action.

Provider emitted: GnomonModuleInfo (consumed by gnomon_kernel, gnomon_migration, gnomon_test).


4.2 gnomon_project

Declares the project root (project.gnm). There is exactly one gnomon_project per workspace.

gnomon_project(
    name = "project",
    project_file = "project.gnm",
    visibility = ["//visibility:public"],
)

4.3 gnomon_kernel

Compiles an gnomon_module’s bundle into a WASM kernel artifact (RFC-0010 §6). Internally invokes rules_rust to compile the generated Rust reducer code to wasm32-unknown-unknown.

gnomon_kernel(
    name = "household_kernel",
    module = ":household",      # gnomon_module target
    opt_level = "release",      # debug | release
    visibility = ["//visibility:public"],
)

Outputs:

OutputDescription
<name>.wasmCompiled WASM kernel artifact; loaded by gnomon_kernel_init (RFC-0010 §6.9)
<name>.wasm.fingerprintSHA-256 of the WASM artifact; checked against storage manifest at runtime (M10040)

Build steps (internal):

  1. Invoke gnomon_module to get the compiled bundle
  2. Invoke the gnomon compiler’s codegen subcommand to emit Rust reducer source from the bundle
  3. Compile the generated Rust via rules_rust rust_binary with --target wasm32-unknown-unknown
  4. Strip WASM and emit fingerprint

4.4 gnomon_test

Runs the test declarations in an gnomon_module (RFC-0013). Test execution is hermetic: the kernel under test is loaded from the module’s compiled bundle; no network access.

gnomon_test(
    name = "household_test",
    module = ":household",
    size = "small",
)

Outputs: Standard Bazel test result XML. Tests are run via bazel test //modules/household:household_test.

Each test declaration in the module’s .gnm files becomes an individual test case. The test runner loads the kernel from the compiled bundle, seeds state from the test declaration’s given {} block, submits the command, and asserts the expected events or state.


4.5 gnomon_migration

Produces and optionally applies a schema migration plan (RFC-0016) from one bundle version to another.

gnomon_migration(
    name = "household_migration",
    module = ":household",
    from_version = "1.2.0",     # optional; omit to diff against installed schema
    env = "staging",            # target environment label
)

Running bazel run //modules/household:household_migration executes the migration against the configured environment. Running bazel build //modules/household:household_migration produces the migration plan as a JSON artifact without applying it.

Outputs:

OutputDescription
<name>.migration.jsonMigration plan: ordered list of DDL operations (RFC-0016 §3)
<name>.migration.sqlSQL representation of the migration plan

4.6 gnomon_client

Declares an external API client (RFC-0024) for use in gnomon_module targets. Spec-backed clients pull in their schema file as a Bazel input; the compiler resolves the adapter at build time.

gnomon_client(
    name = "yodlee_client",
    src = "clients.gnm",
    # For spec-backed clients, declare the spec file so Bazel tracks it as an input:
    specs = [],                     # hand-authored; no external spec file
)

gnomon_client(
    name = "workos_client",
    src = "workos-client.gnm",
    specs = ["//specs:workos-v2.yaml"],   # Bazel tracks this; rebuild if spec changes
)

Listing specs ensures Bazel correctly invalidates the gnomon_module cache when the spec file changes — without this, the spec file is an untracked input and the compiler’s output would not be reproducibly cached.

Provider emitted:

GnomonClientInfo = provider(
    doc = "gnomon_client target — provides spec file inputs and client name to gnomon_module.",
    fields = {
        "client_name": "string: the client name as declared in the .gnm source",
        "src":         "File: the .gnm source file containing the client declaration",
        "specs":       "depset: spec files tracked as Bazel inputs (may be empty)",
    },
)

5. gRPC Service Integration

Gnomon compiler services (RFC-0018), the module registry (RFC-0019), and LSP extensions (RFC-0017) expose gRPC APIs defined with Protocol Buffers. These use standard rules_proto with Buf:

# In compiler/BUILD
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_buf//buf:defs.bzl", "buf_lint_test", "buf_breaking_test")

proto_library(
    name = "compiler_proto",
    srcs = ["compiler_service.proto"],
    deps = ["@com_google_protobuf//:any_proto"],
)

buf_lint_test(
    name = "compiler_proto_lint",
    targets = [":compiler_proto"],
    config = "//:buf.yaml",
)

buf_breaking_test(
    name = "compiler_proto_breaking",
    targets = [":compiler_proto"],
    against = "//:.git",
    config = "//:buf.yaml",
)

rules_gnomon does not wrap rules_proto. gRPC service targets are plain rules_proto targets. The gnomon_module rule does not depend on them — service definitions are separate from module compilation.


6. Gazelle Extension

The rules_gnomon Gazelle extension reads project.gnm and the modules [] list to auto-generate BUILD files for all module directories. This eliminates the need to hand-author gnomon_module targets.

# In WORKSPACE or MODULE.bazel
bazel_dep(name = "bazel_gazelle", version = "0.35.0")

gazelle_dependencies()

# In the root BUILD file:
load("@bazel_gazelle//:def.bzl", "gazelle")

gazelle(
    name = "gazelle",
    languages = ["@rules_gnomon//gazelle:gnomon"],
)

Running bazel run //:gazelle scans the module directories listed in project.gnm, reads each directory’s .gnm files, infers deps from imports {} declarations, and writes or updates BUILD files.

Folder-based module inference. The Gazelle extension uses a leaf-directory model: one gnomon_module target is generated per leaf directory. A leaf directory is a directory that contains .gnm files but has no subdirectories that also contain .gnm files. This mirrors the folder-based module convention in project.gnm (RFC-0008 §7): each concept folder is a leaf directory and maps to exactly one gnomon_module target.

The generated gnomon_module target is named after the leaf directory. Its srcs attribute is set to the glob of all .gnm files in that directory excluding module.gnm, which is treated as a manifest and passed separately via the manifest attribute. Its deps are inferred from the imports {} block in module.gnm (the authoritative source); if module.gnm is absent, Gazelle falls back to scanning imports {} across all source files in the directory. Gazelle MUST emit a build warning when module.gnm is absent from a concept folder.

Gazelle inference rules:

SourceGenerated target
Leaf directory (contains .gnm files, no .gnm-containing subdirectories)gnomon_module named after the leaf directory
*.gnm file with client declarationsgnomon_client
test declarations in any .gnm filegnomon_test
project.gnm at workspace rootgnomon_project
migrations {} block in any .gnm filegnomon_migration

The Gazelle extension generates one gnomon_migration target per module that contains a migrations {} block. The from_version attribute is left empty by default; users must set it manually when targeting a specific prior version.


7. Remote Execution Configuration

The two expensive build steps in the gnomon pipeline are the compiler invocation and the Rust→WASM compilation. Both are suitable for remote execution.

# In .bazelrc
build --remote_executor=grpcs://rbe.example.com
build --remote_cache=grpcs://cache.example.com

# Compiler actions are pure functions of their inputs; always cacheable.
# Tag gnomon_module actions with no-sandbox to enable RBE.
build --strategy=GnomonCompile=remote,local

# Rust WASM compilation via rules_rust — use the standard remote strategy.
build --strategy=Rustc=remote,local
build --strategy=RustWasm=remote,local

Hermeticity requirements for caching:

The gnomon compiler MUST be fully hermetic:

  • No filesystem reads outside declared srcs and deps
  • No network access during compilation (spec-backed clients must have their spec files declared in specs on the gnomon_client target so Bazel tracks them as inputs)
  • Deterministic output: same inputs → identical output bytes (rkyv archives MUST be byte-for-byte reproducible)

Determinism of rkyv output requires that CanonicalIr struct fields are serialized in declaration order and that Vec fields are populated in stable order (alphabetically by symbol id). The gnomon compiler MUST enforce this.


8. Dependency Graph

A typical module build graph:

project.gnm
    │
    ▼
gnomon_project(:project)
    │
    ├─► gnomon_module(:household) ──────────────────────────► gnomon_test(:household_test)
    │       │                                                       │
    │       │  [.bundle]                                            │
    │       ▼                                                       │
    │   gnomon_kernel(:household_kernel)                              │
    │       │                                                       │
    │       │  [generated Rust source]                              │
    │       ▼                                                       │
    │   rules_rust rust_binary(:household_kernel_rs)                │
    │       │                                                       │
    │       ▼                                                       │
    │   household_kernel.wasm ◄──────────────────────────────────── ┘
    │
    └─► gnomon_migration(:household_migration)
            │
            ▼
        household_migration.sql

9. File Layout Convention

Each concept folder is a leaf directory containing all .gnm files for one logical module concept. Gazelle generates one BUILD file per leaf directory. Intermediate domain directories (e.g., planning/, auth/) contain no .gnm files of their own and receive no BUILD file.

WORKSPACE  (or MODULE.bazel)
BUILD                         ← root; contains gnomon_project(:project), gazelle(:gazelle)
project.gnm
buf.yaml                      ← Buf config for proto linting/breaking detection
.bazelrc

modules/
  planning/
    proposal/
      BUILD                   ← generated by Gazelle; gnomon_module(name = "proposal", ...)
      module.gnm             ← module manifest (RFC-0001)
      schema.gnm
      actions.gnm
      queries.gnm
      mutations.gnm
      events.gnm
      procedures.gnm

  auth/
    user/
      BUILD                   ← generated by Gazelle; gnomon_module(name = "user", ...)
      module.gnm             ← module manifest (RFC-0001)
      schema.gnm
      actions.gnm
      queries.gnm
    agreement/
      BUILD                   ← generated by Gazelle; gnomon_module(name = "agreement", ...)
      module.gnm             ← module manifest (RFC-0001)
      schema.gnm
      actions.gnm
      queries.gnm

  connections/
    yodlee/
      BUILD                   ← generated by Gazelle; gnomon_module(name = "yodlee", ...)
      module.gnm             ← module manifest (RFC-0001)
      schema.gnm
      clients.gnm            ← gnomon_client targets

specs/
  workos-v2.yaml              ← tracked by gnomon_client specs = [...]
  BUILD

compiler/
  compiler_service.proto      ← gRPC service; rules_proto target
  BUILD

governance/
  authorization.gnm
  ai-participation.gnm
  draftable.gnm
  BUILD

10. Failure Modes

CodeDescriptionSeverity
M32000gnomon_module srcs contains a file outside the module directoryError
M32001gnomon_client specs missing a file referenced by spec: in the .gnm sourceError — Bazel will not track the file as an input, breaking caching
M32002Gazelle cannot resolve an imports {} reference to an gnomon_module targetWarning — generates commented-out deps entry
M32003Compiler output is not byte-for-byte reproducible across two builds with identical inputsError — breaks remote caching
M32004gnomon_kernel WASM fingerprint does not match gnomon_module bundle fingerprintError — M10040 at runtime; caught here at build time
M32005gnomon_migration plan references a schema object not present in the target environmentError