gnomonlearn

RFC-0008 · Gnomon Language Authoring Surface

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 →

Status: Draft Owners: DX, Compiler

1. Scope

Defines the authoring language surface for Gnomon: the file extension, project layout convention, DSL syntax, and normative EBNF grammar. This RFC specifies what authors write in .gnm files; RFC-0001 specifies the module.gnm manifest structure; RFC-0002 specifies what the compiler produces.

All Gnomon source files use the .gnm extension. The top-level declaration keyword within a file determines its semantic kind; no separate extension per kind is needed or permitted.

The language surface is a single unified DSL. Every declaration kind is authored in the same block-based syntax; declaration bodies consist of unordered optional properties. Non-technical domain authors write the properties they know; engineers add invariants, aspects, and composition; AI-assisted authoring fills gaps. All declarations compile to the same canonical IR (RFC-0010).

Related RFCs:

  • RFC-0011 defines the annotation system (annotation facet, annotation aspect, @ decorators) which extends the base grammar defined here.
  • RFC-0012 defines Gnomon tooling: the canonical formatter (gnomon fmt), compiler flags, and CI integration.

2. Goals

  1. Non-technical domain authors can read and write declarations without engineering assistance
  2. All declaration bodies use a single open block-property syntax; authoring depth is additive, not modal
  3. File purpose is inferrable from the top-level declaration keyword, not the file extension
  4. Syntax is structured enough to be parsed deterministically, readable enough to be reviewed without tooling
  5. UI and app declarations are projections over the semantic model, not independent layers
  6. A single file extension eliminates per-kind extension proliferation and simplifies tooling

Linked References

The cross-RFC dependency graph is rendered in reference catalog § Linked References. Out-of-KG pointers to legacy code or external resources, when present, remain in this document under “Source-tree references” below.

3. Invariants

  1. Every source file MUST use the .gnm extension. Files with any other extension MUST produce error M08700.
  2. A file MUST contain declarations of exactly one declaration class; files mixing declarations from different classes are a compiler error (M08701). Every declaration kind belongs to exactly one class: Schema (entity, type, variant, flow, invariant, facet, mutation, compute, extend, claim, config, config-set), Operations (action, query, task, integration, procedure, actuator, event, client, saga, workflow, api, serve), Relations (relation), Governance (policy, agent, compose, aspect, model), Migrations (transform, migration), Surface (app, view), Tests (test). A Schema class file MAY co-locate type, variant, flow, and invariant declarations exclusively consumed by the primary entity or facet in that file; if any such co-located declaration is referenced from another file it MUST be extracted (error M08702). A Migrations class file MUST be named migrations.gnm or transforms.gnm within a concept folder.
  3. Every entity declaration MUST include a meaning property.
  4. Every facet declaration MUST include a meaning property.
  5. Every agent declaration MUST enumerate explicit permissions and prohibitions.
  6. UI view declarations MUST NOT contain business rules; authorization and invariants belong in policy declarations.
  7. The project manifest (project.gnm) MUST NOT contain declaration content other than the project { } block.

4. File Extension

The single canonical extension for all Gnomon source files is .gnm.

The top-level keyword of the first declaration in the file signals its semantic kind:

Top-level keywordDeclaration classRFC-0006 primitive / derivation
typeSchemaVocabulary / primitive type aliases (no RFC-0006 primitive)
entitySchemaEntity (§4.1)
facetSchemaFacet (§4.2)
variantSchemaDiscriminated union value type (Proposal 1)
flowSchemaLifecycle state machine (§4.6)
invariantSchemaNamed parametric constraint; derives from Policy (§4.7)
mutationSchemaNamed pure transactional state change (§6.21)
computeSchemaNamed pure derived value (§6.27)
extendSchemaCross-module facet contribution (§6.28)
configSchemaTyped runtime configuration declaration (RFC-0046 §4)
config-setSchemaPure override-file value binding (RFC-0046 §3.2)
relationRelationsNamed association between entities (§4.3)
actionOperationsComposes mutations and emits events (§6.10)
queryOperationsNamed read accessor over gnomon query API (RFC-0007 §7)
taskOperationsNamed background computation triggered by event (§6.23)
integrationOperationsNamed external push protocol (Proposal 7)
procedureOperationsAPI binding: auth + action delegation (§6.25)
actuatorOperationsEvent-driven side-effect handler (§6.22)
eventOperationsNamed domain event with typed fields (§6.24)
clientOperationsTyped outbound API contract (§6.29)
sagaOperationsMulti-step fallible external API saga (§6.30)
workflowOperationsMulti-agent orchestration with human-in-the-loop gates (RFC-0022)
apiOperationsProtocol-agnostic public service surface (RFC-0033)
serveOperationsWire-protocol binding for an api declaration (RFC-0034)
claimSchemaEvidenceType — declares a named Claim<T> type (§4.5)
transformMigrationsPure data migration function; maps entity instances between versions (RFC-0016 §3)
migrationMigrationsSchema + data evolution step with forward and rollback paths (RFC-0016 §2)
policyGovernancePolicy (§4.7)
agentGovernanceParticipation contract (RFC-0009; not a semantic primitive)
composeGovernancePolicy composition mechanism (RFC-0004)
aspectGovernanceCross-cutting contribution mechanism (RFC-0004)
viewSurfaceProjection layer (RFC-0007 §5.3); compiles via RFC-0003 §5a
appSurfaceBundle declaration; compiles to RFC-0002 bundle
testTestsExecutable policy/safety assertions (no RFC-0006 primitive)
modelGovernanceAI model declaration; pinned model reference for agents, rule compilation, and runtime prompts
project—Project manifest (file MUST be named project.gnm)

Files MUST NOT use generic names like common, misc, utils, or defs. Each file MUST be named after the concept it defines.

5. Project Layout

The canonical layout for all Gnomon projects is module-based. No other layout is supported.

<project>/
  project.gnm

  modules/
    <domain>/
      <name>.gnm      ← entity, facet, relation, flow, view, etc.
      <name>.gnm
      ...
    <domain>/
      ...

  governance/
    <name>.gnm        ← policy, agent declarations
    ...

  examples/
    <name>.gnm        ← example declarations

  tests/
    <name>.gnm        ← test declarations

Top-level folders:

  • modules/ — domain-partitioned source files containing entity, facet, relation, flow, and view declarations
  • governance/ — cross-cutting policy and agent declarations
  • examples/ — concrete instance examples
  • tests/ — executable policy/safety assertions

Tooling MUST support this layout. Tooling MUST NOT recognize or scaffold any other layout.

6. Language Syntax

The Gnomon DSL is a single keyword-driven block syntax. Most declaration kinds share an open-body pattern: a keyword, a name, and a block of unordered optional properties. Authors include only the properties they need; the compiler fills semantic defaults.

6.0 The Declaration Form

All gnomon constructs are declarations. A declaration has the form:

declaration ::= keyword Name '{' slot* '}'

Where:

  • keyword selects the declaration kind (e.g., entity, action, compute)
  • Name is a unique identifier within the module, written in PascalCase for most kinds (see §10.3 for casing rules per kind)
  • slot* is a sequence of zero or more slots

A slot is one of four forms:

slot ::= key ':' value              // property slot   — static, author-written
       | key '{' slot* '}'          // block slot      — structural, contains child slots
       | key '=' expr               // expression slot — dynamic, compiler-visible
       | key 'script' lang '{' '}'  // script slot     — opaque escape hatch, LSP switches language

Property slots (key: value) carry static values: strings, identifiers, type references, list literals. meaning: "..." is the canonical property slot.

Block slots (key { slot* }) carry structured sub-declarations: fields { }, preconditions { }, transitions { }.

Expression slots (key = expr) carry expressions evaluated against entity state at compile time or runtime. The compiler type-checks expression slots and validates that referenced fields and functions are declared in scope. The sigil = distinguishes an expression slot from a property slot: meaning: "text" is a static string; rule = count(Person ...) <= 1 is an expression.

Script slots (key script lang { }) carry logic in an embedded host language. The compiler enforces the declared input/output contract at the slot boundary but treats the body as opaque. The LSP MUST switch language mode at the script lang { boundary, providing full IntelliSense for the named language inside. Supported lang values: typescript, python, sql. Any other value is error M06033.

Universal slots available in every declaration kind:

  • meaning: Text — (required; property slot) human-readable description of what this declaration represents
  • deprecated: Boolean — (optional; property slot) signals that this declaration should not be used in new code; equivalent to the deprecated epistemic modifier at the slot level
  • owner: Text — (optional; property slot) team or person responsible for maintaining this declaration

Exceptions to the open-body model — five declaration kinds have structural requirements that deviate from the open-property bag:

KindStructural constraint
invariantRequires a parameter list in the header and a bare expression body — not a property block
aspectBody is a statement list (emit, mutate, assert), not key-value properties
testRequires ordered mandatory blocks: given, when, then
flowstates block MUST appear before transitions for the compiler to resolve state references
facetmeaning property is required (not optional); the compiler does not supply a default

These exceptions are normative. The “open unordered property bag” description applies to entity, type, action, policy, agent, claim, query, view, model, annotation facet, and annotation aspect declarations only.

6.1 Vocabulary file

type Person {
  label: "Person"
  meaning: "A human individual recognized by the system."
}

type Organization {
  label: "Organization"
  meaning: "A legal or operational entity such as an employer or carrier."
}

6.2 Facet file

facet Auditable {
  meaning: "All changes must be attributable and traceable."

  rules {
    every change must record actor
    every change must record timestamp
    every change must record source
  }
}

facet AIDraftable {
  meaning: "AI may create draft instances but not finalize them."

  rules {
    ai can create state Draft
    ai cannot create state Final
    ai must attach rationale
    ai must attach confidence
  }
}

6.3 Entity file

entity Employee {
  is Person

  includes [
    Contactable,
    EligibleForBenefits,
    Auditable,
    Sensitive
  ]

  fields {
    employeeId: Identifier required
    fullName:   Text       required
    email:      Text
    employer:   Organization required
    hireDate:   Date
    tier:       Text       default("standard")
    badge:      Text       deprecated
  }

  meaning: "A person employed by an organization and eligible to participate in benefits."

  examples [
    "A full-time employee of Acme Corp enrolled in medical and dental plans."
  ]
}

§6.3a — Field Modifier Syntax (Normative)

A field declaration inside any fields {} block has the form:

field-decl ::= NAME ":" type-expr { modifier } NEWLINE
modifier   ::= "required"
             | "default" "(" literal ")"
             | "deprecated"
             | "sensitive"
             | "indexed"
             | "unique"
             | "path"
             | "query" [ "(" STRING ")" ]
             | "header" "(" STRING ")"
             | "body"
             | IDENT "(" literal ")"    (* extension modifier from adapter module *)

Modifiers are space-separated bare keywords or keyword(arg) forms appearing after the type expression. Order is not significant; gnomon fmt normalizes to canonical order: required/default(v) first, then semantic modifiers (deprecated, sensitive, indexed, unique), then binding modifiers (path, query, header, body), then extension modifiers.

Built-in modifiers:

ModifierValid contextsMeaning
requiredfields {}, input {}, output {}Field MUST be present in every record or input; absence is a validation error
default(v)fields {}When absent from a stored record, the runtime synthesizes value v at read time. v must be a literal of the field’s type. Mutually exclusive with required.
deprecatedfields {}Field is scheduled for removal. Compiler emits M08781 at every write site.
sensitivefields {}Field contains PII or sensitive data. Excluded from default query projections; requires @SensitiveData annotation (RFC-0011).
indexedfields {}Hint to the storage layer that this field is frequently used in filters; may create a secondary index.
uniquefields {}All values of this field must be distinct within the entity’s scope.

Binding modifiers (path, query, header, body) are defined by protocol adapter modules and are valid only inside input {} blocks of operation {} declarations (RFC-0025/RFC-0034). See RFC-0025 §4a for normative binding rules.

Extension modifiers — adapter modules may register additional modifiers via their manifest (RFC-0024 §7). An extension modifier not recognized by any imported adapter produces warning M06060.

Diagnostic codes:

  • M06060 — unrecognized field modifier (neither built-in nor registered by an imported adapter)
  • M06061 — required and default(v) both declared on the same field (mutually exclusive)
  • M06062 — default(v) value is not a literal of the field’s declared type

### 6.4 Relation file

```gnomon
relation elects {
  from: Employee
  to: Plan
  meaning: "An employee selects a plan for enrollment."

  constraints {
    must occur within Enrollment
    must satisfy Eligibility
  }
}

6.5 Flow file

flow PlanRecommendationLifecycle for PlanRecommendation {
  states [
    Draft,
    Reviewed,
    Approved,
    Sent
  ]

  transitions {
    Draft -> Reviewed by HumanReviewer
    Reviewed -> Approved by LicensedAdvisor
    Approved -> Sent by System
  }

  rules {
    ai may create Draft
    ai may not transition to Reviewed
    only LicensedAdvisor may approve
    Sent requires Approved
  }
}

6.6 Policy file

policy AIGuardrails {
  applies to [AIDraftable]

  rules {
    ai outputs must include rationale
    ai outputs must include confidence
    ai outputs must include evidence links
    ai outputs must be marked as AI-generated
    ai outputs require human review before finalization
  }
}

6.7 Agent file

agent RecommendationAgent {
  purpose: "Draft plan recommendations for employees."

  inputs {
    employee: Employee
    availablePlans: List<Plan>
    supportingDocuments: List<Document>
  }

  outputs {
    produces: PlanRecommendation in Draft
  }

  permissions {
    can classify documents
    can extract fields
    can draft rationale
    can propose plans
  }

  prohibitions {
    cannot approve recommendation
    cannot submit enrollment
    cannot disclose sensitive information outside policy
  }

  requirements {
    must provide confidence
    must cite evidence
    must flag ambiguity
  }
}

6.8 View file

view PlanRecommendationSummary for PlanRecommendation {
  show [
    subject.fullName,
    recommendedPlans,
    rationale,
    confidence,
    evidence,
    state
  ]

  explain {
    state as "Current review stage"
    confidence as "How certain the system is"
    evidence as "Documents and claims supporting this recommendation"
  }

  actions {
    reviewer can mark Reviewed
    advisor can mark Approved
  }
}

6.9 Test file

test "AI cannot approve recommendation" {
  given {
    recommendation: PlanRecommendation in Draft
    actor: RecommendationAgent
  }

  when {
    actor attempts transition recommendation -> Approved
  }

  expect {
    denied
    reason: "Only LicensedAdvisor may approve"
  }
}

6.10 Action file

An action composes one or more mutation declarations into a unit of work and declares what domain events to emit after the mutations commit. An action has no actor and no authorization logic — those belong to procedure (§6.25). An action has no effects block of its own — state changes are declared in the mutations it composes (§6.21). The return value of an action is implicitly the return value of its last declared mutation.

Slots: input {}, execute {} (optional), mutations {}, after {}. No preconditions, no effects, no actor, no returns directly.

The execute {} block — external I/O bindings

An action MAY declare an execute {} block to call external APIs before running mutations. Each line in the block is a named binding:

<name> = <Client>.<operation> using { <input bindings> }

The execute {} block is analogous to a Haskell do-block in the IO monad: each line performs an effectful external call and binds its result to a name that is in scope for all subsequent lines in the block and for the mutations {} and after {} blocks below. Execution is sequential by declaration order, except where the compiler can prove that two calls have no data dependency — in that case the runtime MAY issue them concurrently.

The execute {} block always runs before mutations {}. This is structurally required: mutations reference bindings produced by execute, so no reordering is possible. The full action phase order is:

execute {}   →   mutations {}   →   commit   →   after {}

If any execute call fails (based on its client’s error classification), the action fails before any mutations run. No partial state is written.

action AuthenticateUser {
  meaning: "Exchange an OAuth code for a WorkOS session, provision the user in the graph, and emit UserAuthenticated."

  input {
    code: Text required
  }

  execute {
    authResponse = WorkOS.authenticateWithCode using { code: code }
    orgMetadata  = WorkOS.getOrganizationMetadata using { orgId: authResponse.organizationId }
  }

  mutations {
    UpsertUser using {
      workosId: authResponse.user.id
      email:    authResponse.user.email
      orgType:  orgMetadata.org_type
    }
    CreateSession using {
      sessionToken: authResponse.sealedSession
      userId:       UpsertUser.returns.id
    }
  }

  after {
    emits UserAuthenticated using {
      userId: UpsertUser.returns.id
      orgId:  authResponse.organizationId
    }
  }
}

authResponse must complete before orgMetadata (data dependency on authResponse.organizationId). The compiler derives this dependency graph statically from binding references.

Actions without external I/O omit execute {} entirely:

action RequestProposal {
  meaning: "Compose mutations to create a Case and Proposal, then emit ProposalRequested."

  input {
    householdId: Identifier required
    scenarioId: Identifier required
  }

  mutations {
    CreateProposal using {
      householdId: householdId
      scenarioId: scenarioId
    }
  }

  after {
    emits ProposalRequested using {
      proposalId: CreateProposal.returns.id
      caseId: CreateProposal.returns.caseId
      householdId: householdId
      scenarioId: scenarioId
    }
  }
}

mutations {} block: Lists the mutations to compose, in declaration order. Each entry names a declared mutation and binds input fields (and execute bindings) via a using { } clause. Mutations run in the order declared, within a single transaction. The return value of each mutation is available to subsequent mutations and to the after {} block as <MutationName>.returns.

after {} block: Contains only emits statements. Each emits statement names a declared event (§6.24) and populates its fields via a using { } clause. No state changes, dispatches, or external calls are valid here — those belong in actuator (§6.22) and task (§6.23) declarations triggered by the emitted events.

Compiler rules:

  • An action MUST NOT declare preconditions, effects, or returns directly (error M07100)
  • The mutations {} block MUST list only declared mutation names (error M07101)
  • The after {} block MUST contain only emits statements (error M07102)
  • Every event named in an emits statement MUST be declared in scope (error M07108)
  • Every execute binding MUST reference a declared client and a declared operation on that client (error M07109)
  • An execute binding that references an undeclared prior binding MUST produce a dependency error (error M07110)
  • execute {} MUST NOT contain mutation calls, event emission, or any state-changing expression (error M07111)

6.11 Claim file

Claim declarations express EvidenceType (RFC-0006 §4.5). Each named claim declares a typed Claim<T> field wrapper with its evidence requirements and confidence policies.

claim diagnosisCode {
  wraps: String
  meaning: "A diagnosis code that may be AI-extracted from a clinical document."

  requiredEvidence [confidence, source, assertedBy, evidenceLinks]

  allowedStatus [inferred, observed, asserted, disputed]

  policies {
    minConfidenceToUse: 0.80
    requiresHumanReviewBelow: 0.90
  }
}

claim recommendedPlan {
  wraps: Plan
  meaning: "A plan proposed for an employee by the recommendation agent."

  requiredEvidence [confidence, rationale, evidenceLinks]

  allowedStatus [estimated, asserted]
}

6.12 Invariant declaration

Invariants are named, parametric constraints referenceable from action mustSatisfy blocks and policy rules.

invariant Balanced(t: Transaction) {
  sum(t.entries.debits.amount) == sum(t.entries.credits.amount)
}

invariant ActiveEmployeeHasHireDate(e: Employee) {
  e.status == "active" -> e.hireDate != null
}

6.13 Aspect declaration

Aspects are cross-cutting contributions that push structure or behavior into target kinds via selectors. The aspect controls targeting; the target entity does not opt in.

aspect AuditTrail on any write(Transaction) {
  emit AuditEvent {
    entity: Transaction.id
    action: "write"
    timestamp: now()
    actor: context.user
  }
}

aspect PIIAccess on field(User.ssn, User.dob) {
  require context.user.hasRole("admin")
  log access with sensitivity = HIGH
}

6.14 Compose and apply declarations

compose TransactionPolicy {
  include BalanceInvariant
  include AuditTrail
  include PIIAccess

  resolve conflicts by precedence:
    BalanceInvariant > PIIAccess > AuditTrail
}

apply TransactionPolicy to Transaction

§6.14a — apply for Retroactive Annotation Attachment

The apply statement has a second, distinct form: retroactively attaching an annotation facet (RFC-0011) to a declaration defined in another module, without modifying the target declaration’s structure. This is distinct from extend (RFC-0004), which adds structural fields.

Syntax:

apply-annotation ::= "apply" fqn { "@" annotation-ref [ annotation-arg-block ] }
fqn              ::= QUALIFIED | NAME
annotation-ref   ::= QUALIFIED | NAME
annotation-arg-block ::= "{" { NAME ":" literal NEWLINE } "}"

Example:

// In governance/gdpr.gnm — adding GDPR annotation to Employee from another module

apply org.hr.employees#Employee @GDPR { region: "EU" }
apply org.hr.employees#Employee @SOXGoverned
apply org.hr.employees#Employee.ssn @SensitiveData { sensitivity: "PII" }

Semantics:

  • apply with @ forms is annotation-only: it cannot add fields, change types, or alter the target declaration’s behavior.
  • Multiple @ forms may appear on a single apply statement; they are applied in declaration order.
  • The annotation-arg-block provides required annotation facet field values for this application site.
  • apply at the member level (apply Namespace#Entity.field @Annotation) attaches the annotation to the named field, not the enclosing entity.
  • apply is valid in any Governance-class file. Compilers MUST NOT permit apply in Schema or Operations files.

Invariants:

  1. The target FQN MUST resolve to a declared entity, field, query, or operation (error M06070 if not).
  2. Each @ annotation MUST reference a declared annotation facet, not a semantic facet (error M08770).
  3. apply MUST NOT duplicate an annotation already declared inline on the target (error M06071 — use annotations { } override at the source instead).
  4. apply MUST NOT appear in the same module that declares the target (error M06072 — use inline annotations { } instead).

Diagnostic codes:

  • M06070 — apply target FQN does not resolve to a declared declaration
  • M06071 — apply annotation duplicates an annotation already declared inline on the target
  • M06072 — apply in same module as target; use inline annotations { } instead

6.15 Query declaration

Queries are named read accessors over the gnomon query API (RFC-0007 §7). They may be declared in shorthand one-line form or as a full block.

query getEmployee(id: ID) -> Employee

query listEmployees {
  meaning: "Return all employees in a given department."
  input { department: Department }
  returns: List<Employee>
}

6.16 App declaration

An app is a curated bundle of models, policies, flows, UI projections, and capabilities:

app benefitsAdminApp {
  version: "1.0.0"
  audience: [HRAdmin, BenefitsAdvisor]

  includes models [Employee, Plan, Enrollment, PlanRecommendation]
  includes policies [PrivacyPolicy, AIGuardrails, ApprovalsPolicy]
  includes flows [EnrollmentLifecycle, RecommendationLifecycle]
  includes views [EmployeeDetailPage, EnrollmentSummaryPage, RecommendationReviewPage]
  includes agents [RecommendationAgent]
}

6.17 Entities with inline fields

Entities that do not yet have a meaning authored, or that are defined in a purely structural context, may omit semantic properties. The compiler emits warning M08705 for missing meaning.

entity Transaction {
  entries: List<Entry>
  effectiveAt: Instant
}

entity Entry {
  account: Account
  amount: Money
  direction: Debit | Credit
}

6.18 Import declaration

import "benefits.entities.Employee"
import "benefits.entities.Plan"

6.19 Extending a declaration from another file

When adding invariants or aspects to a declaration defined elsewhere, import it and add the additional declarations in the same file:

import "benefits.entities.Employee"

invariant ActiveEmployeeHasHireDate(e: Employee) {
  e.status == "active" -> e.hireDate != null
}

aspect EnrichEmployeeForAI on Employee {
  contribution:
    properties:
      aiSummary: Claim<Text>
}

6.20 Model declaration

A model declaration pins an AI model reference. Model declarations are first-class: they may be defined in any .gnm file, imported from another module, and referenced by name from agent declarations, compiler { } blocks, and individual rule "..." with ModelName / prompt "..." with ModelName statements.

model Gemma3Local {
  meaning: "Local Gemma 3 4B model for rule compilation and lightweight inference."

  provider: "ollama"
  name:     "gemma3:4b"
  digest:   "sha256:a1b2c3d4e5f6..."   // exact version pin; required for reproducibility

  parameters {
    temperature:   0.0
    topP:          1.0
    contextWindow: 8192
  }

  roles [rule-compiler, runtime-agent]
}

model GPT4o {
  meaning: "OpenAI GPT-4o for complex advisory prompt evaluation."

  provider: "openai"
  name:     "gpt-4o"
  version:  "2024-08-06"

  parameters {
    temperature: 0.2
    contextWindow: 128000
  }

  roles [runtime-agent]
}

A model declaration MUST specify provider, name, and either digest (for content-addressed model registries such as Ollama) or version (for API-versioned providers such as OpenAI). Omitting both produces error M08795. The roles field restricts where the model may be used:

RoleDescription
rule-compilerMay be used by the compiler to lower rule "..." statements to constraint expressions
runtime-agentMay be used by an agent declaration or prompt "..." statement at runtime

A model referenced in a compiler { ruleCompiler: ... } block MUST have rule-compiler in its roles. A model referenced from an agent declaration or runtime prompt statement MUST have runtime-agent in its roles. Violations produce error M08796.

Model declarations are importable:

// In modules/governance/models.gnm
import { Gemma3Local, GPT4o } from "org.shared-models"

// Reference in an agent declaration
agent RecommendationEngine {
  purpose: "..."
  model: GPT4o
  // ...
}

6.21 Mutation file

A mutation is a pure transactional function: given typed inputs and current graph state, it produces a declared set of state changes and commits them atomically. It has no actor, no authorization logic, and no post-commit side effects. Mutations are composable — an action (§6.10) composes one or more mutations into a unit of work.

Declaration class: Schema. A mutation SHOULD be co-located with the entities it primarily operates on.

Slots: input {}, returns (optional), effects {}.

mutation CreateProposal {
  meaning: "Create a Case and a Proposal in the Requested state for a given scenario."

  input {
    householdId: Identifier required
    scenarioId: Identifier required
  }

  returns: Proposal

  effects {
    creates Case
    creates Proposal in Requested
  }
}

mutation TransitionProposalToApproved {
  meaning: "Move a Proposal from Reviewing to Approved."

  input {
    proposalId: Identifier required
  }

  returns: Proposal

  effects {
    transitions Proposal(proposalId) -> Approved
  }
}

effects {} grammar (normative). The effects block MUST use only the following statement forms:

// Creation
creates <Entity> [in <StateName>]
creates <Entity> for each <inputField>

// Field mutation
mutates <Entity>[.<fieldPath>]
replaces <Entity>

// Deletion
deletes <Entity>
deletes <Entity> if <condition>
deletes all <Entity> where <fieldPath> == <inputField>

// State transition
transitions <Entity> -> <StateName>
transitions <Entity> -> <StateName> if <condition>

// Relation
creates <Relation> linking <Entity> to <Entity>
deletes <Relation> between <ref> and <ref>

// Conditional wrapper
if <condition> { <effect-statement>+ }

No dispatches, sends, emits, or calls statements are valid inside a mutation effects block — those belong in the after {} block of an action (error M06614).

Compiler rules: Every entity named in a mutation effects block MUST be declared in scope (error M06610). A transitions -> <StateName> statement MUST name a state declared in the entity’s flow (error M06611). A creates <Entity> in <StateName> MUST name a valid initial state (error M06612). A mutates <Entity>.<fieldPath> MUST name a declared field (error M06613). A mutation with no effects block produces warning M06615.


6.22 Actuator file

An actuator is a named, event-driven side-effect handler. It subscribes to a domain event and produces a side effect — sends an email, posts a message, calls an outbound API, triggers a notification. An actuator does NOT touch the persistence graph; state changes belong in mutation and task. Actuators are independently retryable: if one fails it does not affect other actuators subscribed to the same event and does not roll back the originating commit.

Declaration class: Operations.

Slots: on (required), side-effect verb, retry {} (optional), onFailure {} (optional).

Side-effect verbs:

  • sends: email — email delivery; requires template and to
  • sends: sms — SMS delivery; requires to
  • calls: <client>.<operation> — outbound API call (see §6.29 client declaration)
  • notifies: push — push notification; requires to
  • posts: webhook — outbound webhook; requires url
actuator SendProposalApprovedEmail {
  meaning: "Send an email to the household's primary contact when a proposal is approved."

  on: ProposalApproved

  sends: email
  template: "proposal-approved"
  to = Household(event.householdId).primaryContact.email

  retry {
    attempts: 5
    backoff: exponential
    on: [DeliveryFailure, Timeout]
  }

  onFailure {
    emits EmailDeliveryFailed using { eventId: event.id, reason: error.message }
  }
}

The to, channel, message, and similar binding slots support expression syntax (§6.0 expression slots) for binding event payload fields. The onFailure {} block accepts emits and log statements. If omitted, failures are logged and dead-lettered silently.

Compiler rules: An actuator MUST declare on naming a declared event (error M07106). An actuator MUST NOT declare effects {} (error M07107).


6.23 Task file

A task is an asynchronous mutation: it performs the same transactional state changes as a mutation (§6.21), but executes in the background, is always performed by System, and is triggered by a domain event subscription rather than being called directly. Tasks run after the triggering commit has already succeeded.

Declaration class: Operations.

Slots: triggeredBy (required), input {}, effects {}, onError {}, retry {}, after {}.

task GenerateProposal {
  meaning: "Run the decision engine to produce a financial plan for a household scenario."

  triggeredBy: ProposalRequested

  input {
    proposal: Proposal in Requested
    case: Case
  }

  effects {
    transitions Proposal(input.proposalId) -> Processing
    mutates Proposal.data
    mutates Proposal.completedAt
    transitions Proposal(input.proposalId) -> Ready
  }

  onError {
    transitions Proposal(input.proposalId) -> Error
  }

  retry {
    attempts: 3
    backoff: exponential
    on: [TransientError, Timeout]
  }

  after {
    emits ProposalGenerated
  }
}

Key properties: triggeredBy subscribes the task to a domain event; the runtime delivers the event payload as input. effects uses the same grammar as mutation.effects (§6.21). onError declares the state transitions to perform if the task’s effects block fails after all retries are exhausted. after {} fires post-commit; only emits statements are valid there.

task vs mutation:

mutationtask
ExecutionSynchronous, in-transactionAsynchronous, post-event
Triggered byComposed into actionDomain event (triggeredBy)
ActorNoneSystem
Can emit eventsNoYes (after {})
Declaration classSchemaOperations

Compiler rules: A task MUST declare triggeredBy (error M09000). The event named MUST be declared in scope (error M09001). State names in effects transitions MUST be declared in the referenced entity’s flow (error M09002). onError transition target MUST be declared in the entity’s flow (error M09003). A task MUST NOT declare preconditions (error M09004). The after {} block MUST contain only emits statements (error M09005).


6.24 Event file

An event is a named, immutable, typed record of something that happened in the domain. It is the contract between the action layer (which emits, §6.10) and the actuator (§6.22) / task (§6.23) layer (which subscribes).

Declaration class: Operations.

Slots: fields {}, emittedBy: [...], subscribedBy: [...].

event ProposalRequested {
  meaning: "Emitted when a household requests a new financial proposal."

  fields {
    proposalId: Identifier required
    caseId: Identifier required
    householdId: Identifier required
    scenarioId: Identifier required
    requestedAt: Timestamp required
  }

  emittedBy: [RequestProposal]
  subscribedBy: [GenerateProposal]
}

event ProposalApproved {
  meaning: "Emitted when an advisor approves a financial proposal."

  fields {
    proposalId: Identifier required
    householdId: Identifier required
    approvedAt: Timestamp required
  }

  emittedBy: [ApproveProposal]
  subscribedBy: [SendProposalApprovedEmail]
}

Event fields capture values at emission time. They MUST NOT be mutable references. The runtime serializes event fields to the event store at commit time, before any actuators or tasks run.

emittedBy and subscribedBy are documentation-and-validation slots: the compiler warns M07200 if emittedBy names a declaration that has no corresponding emits statement for this event.


6.25 Procedure file

A procedure is the API binding layer. It owns actor authorization, input validation, and the typed return contract. It delegates all state-change logic to a named action. A procedure has no effects block and no after block — those concerns live in the action and in actuators.

Declaration class: Operations.

Slots: input {}, preconditions {}, runs: ActionName using {}, returns: Type.

procedure RequestProposal {
  meaning: "API entry point for requesting a new financial proposal. Validates auth then delegates to the RequestProposal action."

  input {
    householdId: Identifier required
    scenarioId: Identifier required
  }

  preconditions {
    session has group:edit on Household(householdId)
    Scenario(scenarioId).status == Active
  }

  runs: RequestProposal using {
    householdId: householdId
    scenarioId: scenarioId
  }

  returns: Proposal
}

procedure ApproveProposal {
  meaning: "API entry point for approving a reviewed proposal."

  input {
    proposalId: Identifier required
  }

  preconditions {
    session has group:edit on Proposal(proposalId).household
    Proposal(proposalId).status in [Reviewing]
  }

  runs: ApproveProposal using { proposalId: proposalId }

  returns: Proposal
}

runs names the action to delegate to and binds the procedure’s input fields. Required. A procedure MUST NOT declare effects {} or after {} (error M07103).

returns — the typed return value. MUST be compatible with the return type of the named action’s last mutation; the compiler validates this at compile time (error M07105).

Return semantics: The return value is the committed return of the action’s last mutation, delivered synchronously to the caller. Post-commit consequences (actuators, tasks) fire asynchronously after the return.

Compiler rules: A procedure MUST declare runs naming a declared action (error M07104). A procedure MUST NOT declare effects {} or after {} (error M07103). The returns type MUST be compatible with the action’s last mutation return type (error M07105).


6.26 Four-layer operations model summary

The four layers relate as follows:

procedure ──(auth passes)──► action ──► execute {} ──► mutation(s) ──► commit
                                        (external IO)                       │
                                                                     events emitted
                                                                            │
                                       ┌────────────────────────────────────┴────────────────────┐
                                       ▼                                                         ▼
                                   actuator                                                    task
                             (email, notification,                                    (async mutation,
                              outbound call)                                           event-triggered)
mutationactionactuatortaskprocedurequery
Has actorNoNoNoSystemYesYes
Has preconditionsNoNoNoNoYesYes
Owns state changesYesNo (delegates)NoYes (async)NoNo
Calls external APIsNoYes (execute {})YesNoNoNo
Emits eventsNoYes (after)NoYes (after)NoNo
Triggered byAction compositionProcedure (runs)Event (on)Event (triggeredBy)ActorActor
Has returnsOptionalImplicit (last mutation)NoNoYesYes
Declaration classSchemaOperationsOperationsOperationsOperationsOperations

6.27 Compute file

A compute declaration is a named pure function from declared inputs to a typed output. It has no actor, no preconditions, and no side effects. It is a Schema-class declaration — it defines what can be derived from entity state, not what actors may do. A compute SHOULD be co-located with the entity schema file it primarily operates on.

Declaration class: Schema.

Slots: input {}, returns, and either expr = <expression> or script <lang> { }.

compute NetWorth {
  meaning: "The household's total net worth: asset balances minus liability balances."

  input {
    household: Household
  }

  returns: Money

  expr = sum(Account where householdId == household.id and type in AssetAccountTypes, balance)
       - sum(Account where householdId == household.id and type in LiabilityAccountTypes, balance)
}

When the logic cannot be expressed in the expression language, a script slot replaces expr:

compute CreditScore {
  meaning: "Estimated credit score derived from the household's debt profile."

  input {
    household: Household
  }

  returns: Integer

  script typescript {
    const debtRatio = inputs.household.totalDebt / inputs.household.totalIncome;
    return Math.round(850 - (debtRatio * 300));
  }
}

The compiler enforces: inputs is typed as declared in input {}; the return value MUST be assignable to the declared returns type. The body of a script block is opaque to the compiler.

compute vs query:

querycompute
Has actorYesNo
Has preconditionsYes (access control)No
Declaration classOperationsSchema
Has side effectsNoNo
Co-located with entityNo (operations file)Yes (schema file)

Compiler rules: An expression slot MUST reference only fields and functions declared in scope (error M06030). Return type MUST be compatible with declared returns (error M06031). Script lang MUST be typescript, python, or sql (error M06033). A compute MUST NOT have side effects (error M06034).


6.28 Extend declaration

The extend keyword adds a facet to a target entity from a different module. This is the normative pattern for cross-module field contribution: declare a facet containing the additional fields and use extend to apply it to the base entity.

Declaration class: Schema. An extend MUST appear in a file that imports the entity being extended (error M04800 if not). Two modules MAY both extend the same entity with different facets; field names MUST NOT conflict (error M04802).

import "household.Household"

facet SelectSmartContext {
  meaning: "Employer-sponsored benefits guidance context for a household enrolled in SelectSmart."

  fields {
    employerId: Identifier
    hireDate: Date
    incomeLevel: Integer
    stateOfResidence: USState
    guidanceMode: GuidanceMode
    planYear: Integer
  }
}

extend Household includes [SelectSmartContext]

extend syntax:

extend <EntityName> includes [<FacetName>, ...]

The compiler adds the listed facets to the target entity’s includes at the module boundary. The extended entity remains a single entity in the graph; only its declared field set grows.

Compiler rules: extend MUST be in a Schema class file (error M08704). A facet contributed via extend MUST NOT redeclare fields already present on the base entity (error M04801). Circular extend chains MUST produce error M04800.


6.29 Client file

A client declares an external API as a typed, named resource in the gnomon model. It is the first-class API contract that execute {} blocks in actions (§6.10), actuator declarations (§6.22), and saga steps (§6.30) reference by name. The compiler validates operation names, input bindings, and return types against the client’s declared contract.

A client declares its contract in one of two forms: spec-backed (preferred) or hand-authored.

Declaration class: Operations.


Spec-backed client

A spec-backed client points to a machine-readable API schema. The compiler and LSP load the schema at compile time to derive operation names, input types, and return types. Authors do not hand-author the operation list.

The spec: slot takes an adapter function call. Adapter functions are not language keywords — they are functions exported by adapter modules that must be listed in the project’s imports {} block. The adapter protocol is defined in RFC-0024 §6.

Standard adapters shipped by the gnomon project:

ModuleFunctionSchema sourceRFC
gnomon.io.openapiopenapi(path)OpenAPI 3.x YAML or JSON fileRFC-0028
gnomon.io.protobufprotobuf(path)Protocol Buffer .proto fileRFC-0030
gnomon.io.graphql-introspectgraphqlIntrospect(url)GraphQL introspection endpointRFC-0031
gnomon.io.graphql-introspectgraphqlSchema(path)GraphQL SDL fileRFC-0031
gnomon.io.trpctrpc(import)tRPC router type (TypeScript)RFC-0029

Third-party adapters implement the same protocol and are imported the same way. The language has no hardcoded list of valid adapter names.

client WorkOS {
  meaning: "WorkOS user management and organization API."
  spec: openapi("./specs/workos-v2.yaml")
  baseUrl: "https://api.workos.com"
  auth: bearer-token
  errors {
    429: transient
    5xx: transient
    timeout: transient
  }
}

client InternalAPI {
  meaning: "Internal tRPC application router."
  spec: trpc("@savvi/api#AppRouter")
}

client DataWarehouse {
  meaning: "Analytics GraphQL API."
  spec: graphqlIntrospect("https://analytics.internal/graphql")
  auth: bearer-token
}

When a spec-backed client is in scope, the LSP provides autocomplete for operation names and their input/output shapes directly from the schema. The errors {} block on a spec-backed client declares the default error classification for all operations; individual operations may override this in the spec adapter’s error mapping configuration (advisory; adapter-specific).


Hand-authored client

A hand-authored client explicitly declares each operation, its input and return types, and its error classification. Use this form for APIs with no machine-readable schema or when precise control over the gnomon type surface is required.

client Yodlee {
  meaning: "Yodlee account aggregation API."

  baseUrl: "https://api.yodlee.com/ysl"
  auth: bearer-token

  operations {
    registerUser {
      meaning: "Register a new user in Yodlee's system."
      method: POST
      path: "/user/register"
      input {
        loginName: Text required
        email: Text required
        currency: Text
      }
      returns {
        userId: Text required
        loginName: Text required
      }
      errors {
        400: terminal
        409: terminal
        429: transient
        5xx: transient
        timeout: transient
      }
    }

    deleteUser {
      meaning: "Delete a Yodlee user and all their data."
      method: DELETE
      path: "/user/{loginName}"
      input { loginName: Text required }
      returns: Unit
      errors {
        404: ignore
        5xx: transient
        timeout: transient
      }
    }
  }
}

Error classes (both forms):

  • terminal — will not resolve on retry; fail immediately
  • transient — may resolve on retry; apply declared retry policy
  • ignore — treat as success (idempotent operations where the desired state already exists)

Compiler rules:

  • A hand-authored client MUST declare at least one operation (error M08100)
  • Every hand-authored operation MUST declare method, path, input, and returns (error M08100)
  • Every errors entry MUST use a recognized class: terminal, transient, ignore (error M08101)
  • A client referenced in an execute {} binding MUST be declared in scope (error M08102)
  • The operation named in an execute {} binding MUST be declared on the referenced client or present in its spec (error M08103)
  • The using {} bindings in an execute {} call MUST match the operation’s declared or spec-derived input fields (error M08104)
  • A spec-backed client with an unreachable or unparseable spec source MUST produce a compile-time error (error M08105)
  • A spec-backed client MUST NOT also declare operations {} (error M08106)

6.30 Saga file

A saga declares a multi-step fallible process involving external API calls. It tracks its own state in the persistence graph via a declared flow, executes named steps in declared dependency order, and declares compensation logic for steps that can be reversed if a later step fails.

Note: RFC-0022 defines a separate workflow declaration kind for composing AI agents with human-in-the-loop gates. saga is the primitive for external API orchestration; workflow is the primitive for agent orchestration. They are distinct declaration kinds and cannot be mixed.

Structural constraint: A saga step MUST NOT contain a human_gate directive. Presence of human_gate inside any saga step MUST produce error M07116 (saga step contains human_gate — use workflow for human-in-the-loop orchestration).

Declaration class: Operations.

Slots: state: FlowName, input {}, steps {}, compensations {}.

Each step has: calls: client.operation using {}, requires: [steps], retry {}, on success {}, on failure(terminal) {}.

saga ProvisionYodleeAccount {
  meaning: "Register a household with Yodlee, link their accounts, and trigger initial data synchronization. Implements the saga pattern with compensation for partial failures."

  state: YodleeProvisioningFlow

  input {
    householdId: Identifier required
    loginName: Text required
    email: Text required
    providerId: Integer required
    credentials: JSON required
  }

  steps {
    step RegisterUser {
      meaning: "Create the household's user record in Yodlee."

      calls: Yodlee.registerUser using {
        loginName: loginName
        email: email
      }

      retry {
        attempts: 3
        backoff: exponential
        on: [transient]
      }

      on success {
        mutation CreateYodleeUser using {
          householdId: householdId
          yodleeUserId: result.userId
        }
        transitions -> RegisteringUser
      }

      on failure(terminal) {
        transitions -> Failed
        emits YodleeProvisioningFailed using {
          householdId: householdId
          step: "RegisterUser"
          reason: error.message
        }
      }
    }

    step CreateProviderAccount {
      meaning: "Link the provider account for the household."

      requires: [RegisterUser]

      calls: Yodlee.createProviderAccount using {
        providerId: providerId
        credentials: credentials
      }

      retry {
        attempts: 3
        backoff: exponential
        on: [transient]
      }

      on success {
        mutation CreateYodleeProviderAccount using {
          householdId: householdId
          providerAccountId: result.providerAccountId
        }
        transitions -> CreatingProviderAccount
      }

      on failure(terminal) {
        compensate [RegisterUser]
        transitions -> Compensating
        emits YodleeProvisioningFailed using {
          householdId: householdId
          step: "CreateProviderAccount"
          reason: error.message
        }
      }
    }
  }

  compensations {
    compensate RegisterUser {
      meaning: "Delete the Yodlee user if later steps fail."

      calls: Yodlee.deleteUser using {
        loginName: RegisterUser.input.loginName
      }

      retry {
        attempts: 5
        backoff: exponential
        on: [transient]
      }

      on success {
        mutation DeleteYodleeUser using { householdId: householdId }
        transitions -> Failed
      }

      on failure {
        transitions -> Failed
        emits CompensationFailed using {
          householdId: householdId
          step: "RegisterUser"
          compensationFor: "ProvisionYodleeAccount"
        }
      }
    }
  }
}

Key concepts:

  • state — a declared flow tracking saga progress. Every transitions -> statement MUST reference states in this flow. Required (error M08200).
  • steps — named units of work executed in dependency order. A step calls a client operation (calls:) or triggers internal async work.
  • requires — step dependencies. Steps with no requires run immediately. Steps with requires: [A, B] run only after both A and B succeed.
  • on success { } / on failure(terminal) { } — per-step handlers. on success MUST contain a mutation call to record the result in the persistence graph and a transitions statement advancing workflow state.
  • compensate [steps] — triggers compensation for already-completed steps in reverse order.
  • compensations { } — declares compensation logic for each reversible step. A step referenced in compensate but with no corresponding compensate declaration is error M08202.

Compiler rules: A saga MUST declare state referencing a declared flow (error M08200). Every transitions -> MUST name a state in the workflow’s flow (error M08201). Every mutation in a step on success MUST be declared in scope (error M08203). A step on failure block missing transitions produces warning M08204. A workflow flow missing a terminal success state, terminal failure state, or Compensating state produces warning M08001.


6.31 Workflow file

A workflow declaration defines a multi-agent orchestration process that may include human-in-the-loop review gates. Each step in a workflow either binds an AI agent model (via model:) or declares a human_gate directive requiring human approval before proceeding. A workflow references a flow to track its progress state and uses the same state:, steps {}, and compensations {} slots as saga, but operates on agent outputs rather than external API calls.

workflow is defined in full in RFC-0022. The authoring surface follows the same block-property syntax as all other declaration kinds; the workflow keyword signals the declaration class to the compiler.

workflow ReviewAndApproveRecommendation {
  meaning: "Orchestrate AI drafting and human approval of a plan recommendation."

  state: RecommendationReviewFlow

  steps {
    step DraftRecommendation {
      meaning: "AI agent drafts the initial plan recommendation."
      model: RecommendationAgent
    }

    step HumanReview {
      meaning: "Licensed advisor reviews and approves or rejects the draft."
      human_gate: LicensedAdvisor
      requires: [DraftRecommendation]
    }
  }
}

Declaration class: Operations. A workflow MUST NOT contain saga steps and MUST NOT be mixed with saga declarations in the same file.


6.32 Transform file

A transform is a pure data migration function. It maps entity instances at a declared source version to a new value at a declared target version using the Gnomon expression language (RFC-0021). It has no side effects, no actor, and no authorization logic. Transforms are used in migration declarations (RFC-0016 §3) as the data-layer component of a schema evolution step.

Declaration class: Migrations.

Slots: meaning, for: EntityName, from: version-range, to: version, apply {}.

transform NormalizeTierCase for Household {
  meaning: "Normalize legacy tier field values to lowercase standard form."
  from: "1.1.x"
  to:   "1.2.0"

  apply {
    tier = source.tier.toLowerCase() ?? "standard"
  }
}

transform BackfillTierFromLegacy for Household {
  meaning: "Populate the new tier field from legacy_tier, falling back to 'standard'."
  from: "1.0.x"
  to:   "1.1.0"

  apply {
    tier = source.legacy_tier ?? "standard"
  }
}

apply {} block: An ordered sequence of assignment expressions. Each line has the form fieldName = expr, where expr is evaluated against the source entity instance (accessible as source) using the expression language (RFC-0021). The result must be assignable to the field’s declared type in the to version of the entity. The full set of fields not mentioned in apply {} are passed through unchanged from source to target.

from and to: Version ranges use the same x-wildcard syntax as migration from ranges (RFC-0016 §1.1). The compiler validates that the from range and to version are consistent with the enclosing module’s version history.

Purity contract: A transform body MUST NOT call external APIs, emit events, read from the gnomon persistence graph (beyond the provided source instance), or produce side effects. Violations produce error M16020. The compiler statically enforces this through the expression language’s purity type.

Totality: Every expr in the apply {} block MUST be a total function over the declared type of the source field. If the compiler cannot prove totality, it emits error M16021. This mirrors the requirement on migration.changeType transform expressions.

Compiler rules:

  • for MUST name a declared entity in scope (error M16010)
  • to MUST name a valid semver string (error M16011)
  • apply {} MUST NOT reference fields not declared on the entity at the from version (error M16012)
  • Return types MUST be compatible with the entity’s to-version field types (error M16013)

Diagnostic codes:

  • M16010 — for references undeclared entity
  • M16011 — to is not a valid semantic version string
  • M16012 — apply {} references field absent from the entity at the from version
  • M16013 — expression return type incompatible with target field type
  • M16020 — transform body has side effects (external call, event emission, or persistence read)
  • M16021 — expression in transform is not provably total over the source field’s type domain

6.33 Inline input/output struct syntax (:=)

When an operation {} block within a client declaration, or a query or procedure declaration, has a simple one-off input or output schema that is not reused elsewhere, an inline anonymous struct may be declared with := rather than giving it a name. The compiler synthesizes a name of the form DeclarationName$Input or DeclarationName$Output for IR purposes; the synthesized name is addressable via FQN (RFC-0006 §4.C) but is never visible to authors.

Syntax:

inline-input  ::= "input"   ":=" "{" field-decl* "}"
inline-returns ::= "returns" ":=" "{" field-decl* "}"

Example — query with inline output:

query getRepositorySummary {
  meaning: "Return name, owner, and star count for a single repository."

  input {
    repoId: Identifier required
  }

  returns := {
    name:       Text    required
    owner:      Text    required
    starCount:  Integer required
  }
}

Example — client operation with inline input and output:

client GitHub {
  meaning: "GitHub REST API."
  baseUrl: "https://api.github.com"
  auth: bearer-token

  operations {
    createIssue {
      meaning: "Open a new issue on a repository."
      method: POST
      path:   "/repos/{owner}/{repo}/issues"

      input := {
        owner: Text required path
        repo:  Text required path
        title: Text required body
        body:  Text          body
      }

      returns := {
        id:     Integer required
        number: Integer required
        url:    Text    required
      }

      errors {
        422: terminal
      }
    }
  }
}

returns is optional and defaults to Unit: When returns is omitted from any declaration that supports it (operation {}, query, procedure, mutation), the compiler treats it as returns: Unit. This mirrors Smithy’s convention and eliminates boilerplate for operations that produce no meaningful output (e.g., HTTP DELETE, state transition procedures). Explicitly writing returns: Unit is forbidden: the compiler MUST produce error M06083 (“explicit returns: Unit is not permitted — omit returns to signal no return value”). Unit only appears in the compiler’s internal IR and in diagnostic messages.

Constraints:

  1. A named input {} and inline input := {} MUST NOT both appear on the same declaration (error M06080).
  2. A named returns: TypeName and inline returns := {} MUST NOT both appear (error M06081).
  3. Inline structs are not importable or referenceable by name from other declarations. If reuse is needed, extract to a named entity.

Diagnostic codes:

  • M06080 — both named input {} and inline input := {} declared on the same operation
  • M06081 — both named returns: TypeName and inline returns := {} declared on the same operation
  • M06083 — explicit returns: Unit is forbidden; omit returns to signal no return value

7. Manifest Files

Two reserved-name manifest files exist in the Gnomon authoring system. Both use standard .gnm DSL syntax; neither is YAML.

  • project.gnm — one per project, at the project root. Declares the project name, version, compiler settings, and the set of module directories to compile.
  • module.gnm — one per module, at the module root. Declares the module’s FQN, version, type, dependencies, and references to all source files in the module. Specified in RFC-0001; grammar in §8.19.

The naming convention (fixed filenames for tooling discovery) separates the manifest’s role as a filesystem entry point from the declared identity inside the file. A project declaration names a human-readable project label; a module declaration names the canonical graph FQN.

Project Manifest (project.gnm)

The project manifest MUST be named project.gnm and placed at the project root. It MUST be small and declarative. It MAY include a compiler { } block that configures build-time behavior including the rule compiler model.

Folder-based module entries

The modules [] list contains folder paths, not individual file paths. Each entry is the path to a concept folder — one logical module concept lives in one folder (e.g., "modules/planning/proposal"). The compiler discovers all .gnm files within that folder automatically; no explicit file listing is required.

All .gnm files found inside a given concept folder MUST belong to the same gnomon module. The compiler enforces this via declaration class rules: if any file in the folder declares a module FQN that differs from the others, error M07901 is produced (see below).

Within a concept folder, two files have reserved manifest roles and are never treated as declaration source files:

File nameRole
module.gnmModule manifest — FQN, version, type, imports (RFC-0001). REQUIRED.
project.gnmProject manifest — project root only. MUST NOT appear in concept folders.

All other files are named by declaration class. The compiler auto-discovers them by name; no explicit listing in module.gnm is required.

File nameDeclaration classKinds permitted
schema.gnmSchemaentity, type, variant, flow, invariant, facet, mutation, compute, claim, extend
actions.gnmOperationsaction
queries.gnmOperationsquery
mutations.gnmOperationsmutation
events.gnmOperationsevent
procedures.gnmOperationsprocedure
tasks.gnmOperationstask
integrations.gnmOperationsintegration
clients.gnmOperationsclient
saga.gnmOperationssaga
agents.gnmGovernanceagent
policies.gnmGovernancepolicy, compose
views.gnmSurfaceapp, view
tests.gnmTeststest
migrations.gnm(Migration)migration

Files that are absent or empty are silently ignored. A file present in a concept folder whose name does not appear in either table above MUST produce warning M07902 — the file will not be compiled. A concept folder MUST contain at least module.gnm and one declaration file; a folder with only module.gnm and no declaration files MUST produce warning M07903.

project "benefits-demo" {
  version: "0.1.0"

  modules [
    "modules/planning/proposal"
    "modules/auth/user"
    "modules/auth/agreement"
    "modules/connections/yodlee"
  ]

  compiler {
    ruleCompiler: Gemma3Local       // named model; must have role rule-compiler
    promptTemplate: "gnomon-rules-v1" // pinned prompt template version
  }
}

The compiler { } block is optional. When absent, rule "..." statements that cannot be statically resolved produce error M08791 (uncompiled rule with no rule compiler configured). The compiler block is a project-level setting and MUST NOT appear in individual .gnm files.

The manifest MUST NOT contain declarations other than the project { } block and the compiler { } sub-block. Presence of any non-project top-level declaration in project.gnm MUST produce error M08722.

Error M07901 — cross-module folder violation. If a concept folder contains .gnm files that belong to more than one gnomon module (i.e., files whose module FQN declarations differ), the compiler MUST produce error M07901. Each concept folder MUST map to exactly one module FQN. Cross-module imports MUST be expressed via the imports {} block in module.gnm, not by co-locating files from different modules in the same folder.

Warning M07902 — unrecognized filename in concept folder. A file present in a concept folder whose name does not appear in the predefined file name table (§7) and for which no explicit listing override is active will not be compiled. The compiler MUST produce warning M07902 identifying the filename so authors do not silently lose declarations.

Warning M07903 — concept folder contains no declaration files. A concept folder that contains module.gnm but no recognized declaration files (schema.gnm, actions.gnm, etc.) MUST produce warning M07903. Such a folder compiles to an empty module, which is likely an authoring mistake.

8. Normative EBNF Grammar

The grammar in this section is the authoritative parser specification. Implementations MUST parse conforming .gnm files and MUST reject non-conforming files with location-aware diagnostics. Any divergence between this grammar and the compiler is a compiler defect.

8.0 Grammar Notation and Verification

Notation. The grammar uses a strict subset of ISO 14977 Extended BNF:

FormMeaning
rule ::= ...Production definition
"x"Literal terminal
UPPERTerminal token class (§8.1)
a bConcatenation
a | bOrdered alternation (first match wins)
[ a ]Zero or one occurrence
{ a }Zero or more occurrences
( a )Grouping

No other notation is used. The grammar MUST be expressible as a PEG grammar without modification; ambiguous productions are a defect in this RFC.

CI verification. The grammar in §8 MUST be extracted from this document and validated by a PEG parser generator (e.g., pest, peg.js, or equivalent) as part of the RFC repository’s CI pipeline. The extracted grammar file is a derived artifact of this RFC; the source of truth is the grammar blocks below.

Conformance test fixtures. Each non-trivial production in §8 MUST have at least one corresponding parse fixture: a concrete .gnm snippet paired with its expected canonical AST. These fixtures are co-located with the grammar and run as part of both RFC CI and compiler CI. A production with no fixture is considered incomplete.

8.1 Terminal Tokens

(* Source identifiers — camelCase or PascalCase; no hyphens *)
IDENT       ::= [a-zA-Z_][a-zA-Z0-9_]*
QUALIFIED   ::= IDENT { "." IDENT }

(* NAME — a single lowercase kebab-case label; used for file names, folder names *)
(* Equivalent to DNS Label per RFC 1123 §2.1; max 63 characters *)
NAME        ::= [a-z][a-z0-9]* { "-" [a-z0-9]+ }

(* FQN — a dot-separated fully-qualified name; used for module namespaces and canonical paths *)
(* Equivalent to DNS Subdomain per RFC 1123 / Kubernetes naming; max 253 characters *)
FQN         ::= NAME { "." NAME }

STRING      ::= '"' { UNICODE_CHAR - '"' } '"'
NUMBER      ::= [0-9]+ [ "." [0-9]+ ]
BOOL        ::= "true" | "false"
NEWLINE     ::= "\n" | "\r\n"
(* // and /* */ chosen over # because # is a CommonMark heading prefix — using # in .gnm source *)
(* would be visually ambiguous in documentation contexts and conflicts with YAML compiled artifacts (RFC-0002) *)
BLOCK-COMMENT ::= "/*" { UNICODE_CHAR - "*/" } "*/"
LINE-COMMENT  ::= "//" { UNICODE_CHAR - NEWLINE } NEWLINE
DOC-COMMENT   ::= "///" { UNICODE_CHAR - NEWLINE } NEWLINE
WHITESPACE  ::= { " " | "\t" | NEWLINE }

UNICODE_CHAR is any Unicode scalar value. Tokens are separated by WHITESPACE, BLOCK-COMMENT, and LINE-COMMENT; all three are ignored by the parser. DOC-COMMENT lines are NOT discarded: they are attached to the immediately following top-level declaration and preserved in the compiled bundle as doc metadata. One or more consecutive DOC-COMMENT lines form a single doc comment block; their content is treated as CommonMark and MUST be valid CommonMark (warning M08760 on violation). IDENT MUST NOT contain hyphens; hyphenated names belong in file and folder names where NAME applies. NAME and FQN follow RFC 1123 §2.1 and Kubernetes naming conventions; implementations MUST enforce the 63-character limit on NAME segments and the 253-character limit on FQN values.

8.2 Top-Level Structure

gnomon-file ::= { top-level-decl }

top-level-decl ::= bare-top-level-decl | decorated-decl

bare-top-level-decl ::=
    import-decl
  | types-decl
  | entity-decl
  | facet-decl
  | relation-decl
  | action-decl
  | mutation-decl
  | actuator-decl
  | procedure-decl
  | event-decl
  | task-decl
  | compute-decl
  | extend-decl
  | client-decl
  | saga-decl
  | workflow-decl
  | claim-decl
  | flow-decl
  | policy-decl
  | invariant-decl
  | aspect-decl
  | compose-decl
  | apply-stmt
  | query-decl
  | view-decl
  | app-decl
  | agent-decl
  | model-decl
  | test-decl
  | project-decl
  | module-decl
  | enum-decl
  | annotation-facet-decl
  | annotation-aspect-decl
  | config-decl
  | config-set-decl

(* RFC-0011 defines decorated-decl and the annotation declaration productions. *)
(* A decorator targets one bare declaration; it cannot recursively decorate a decorator. *)

8.3 Type Expressions

type-expr    ::= base-type [ "required" | "optional" ]
base-type    ::= "List" "<" type-expr ">"
               | "Claim" "<" type-expr ">"
               | union-type
               | inline-enum

union-type   ::= atomic-type { "|" atomic-type }
atomic-type  ::= QUALIFIED

(* Inline anonymous enum — scoped to the enclosing field declaration *)
inline-enum  ::= "enum" "{" IDENT { "," IDENT } "}"

Note: although the grammar permits recursive Claim<type-expr>, nesting Claim<Claim<T>> is prohibited by RFC-0006 §4.5 (M06524).

8.4 Vocabulary Declarations

types-decl   ::= "type" IDENT "{" type-body "}"
type-body    ::= { type-prop }
type-prop    ::= "label" ":" STRING
               | "meaning" ":" STRING
               | annotation-block

8.5 Facet Declarations

facet-decl   ::= { decl-modifier } "facet" IDENT "{" facet-body "}"
facet-body   ::= "meaning" ":" STRING
                 [ "requires" ident-set ]
                 [ "rules" rule-block ]

8.6 Entity Declarations

entity-decl  ::= { decl-modifier } "entity" IDENT "{" { entity-prop } "}"
entity-prop  ::= "meaning"     ":" STRING NEWLINE
               | "is"          QUALIFIED NEWLINE
               | "includes"    ident-set NEWLINE
               | "flow"        QUALIFIED NEWLINE
               | "examples"    string-seq NEWLINE
               | "fields"      "{" { field-decl } "}"
               | field-decl
               | annotation-block

All entity-prop entries are optional and may appear in any order. meaning is required by invariant (§3.3); its absence produces M08705. Bare field-decl entries (without a fields block) are shorthand for structural-only entities.

8.7 Relation Declarations

relation-decl ::= { decl-modifier } "relation" IDENT "{" relation-body "}"
relation-body ::= "from" ":" QUALIFIED
                  "to" ":" QUALIFIED
                  "meaning" ":" STRING
                  [ "cardinality" ":" ( "one" | "many" | "zero-or-one" ) ]
                  [ "qualifiers" "{" { field-decl } "}" ]
                  [ "constraints" rule-block ]

8.8 Flow Declarations

flow-decl    ::= { decl-modifier } "flow" IDENT "for" QUALIFIED "{" flow-body "}"
flow-body    ::= "states" ident-set
                 [ "transitions" "{" { transition-rule } "}" ]
                 [ "rules" rule-block ]

transition-rule ::= IDENT "->" IDENT "by" QUALIFIED NEWLINE

8.9 Policy Declarations

policy-decl  ::= { decl-modifier } "policy" IDENT "{" policy-body "}"
policy-body  ::= { policy-prop }
policy-prop  ::= "applies" "to" ident-set
               | "rules" rule-block
               | "enforcement" ":" ( "hard" | "soft" )
               | annotation-block

8.10 Agent Declarations

agent-decl   ::= { decl-modifier } "agent" IDENT "{" agent-body "}"
agent-body   ::= { agent-prop }
agent-prop   ::= "purpose" ":" STRING
               | "model"         ":" IDENT NEWLINE
               | "inputs"        "{" { field-decl } "}"
               | "outputs"       "{" { output-stmt } "}"
               | "permissions"   rule-block
               | "prohibitions"  rule-block
               | "requirements"  rule-block
               | "readScope"     read-scope-block
               | annotation-block

output-stmt       ::= "produces" ":" QUALIFIED "in" IDENT NEWLINE
read-scope-block  ::= "readScope" "{" { read-scope-entry } "}"
read-scope-entry  ::= QUALIFIED [ "fields" "[" { IDENT } "]" ] NEWLINE

An agent MUST declare exactly one purpose, permissions, and prohibitions property. The optional properties and an inline annotation block may appear in any order; duplicate singleton properties are errors.

The readScope block declares which entity kinds and fields the agent may read when constructing its prompt context. The runtime MUST enforce readScope at prompt assembly time — data outside the declared read scope MUST NOT be included in the prompt (RFC-0015 §11). If fields is omitted for a kind entry, all fields of that kind are readable. An agent with a permissions block but no readScope block MUST produce warning M08932.

Example:

agent RecommendationAgent {
  purpose: "Recommends a benefit plan based on household composition and budget."
  model:   ClaudeRecommender

  inputs { household: Household }
  outputs { produces: PlanRecommendation in recommendations }

  permissions {
    rule "may write PlanRecommendation"
  }
  prohibitions {
    rule "must not write Plan"
  }

  readScope {
    org.benefits.plans.Plan
    org.hr.employees.Person    fields [name, dateOfBirth, coverageTier]
    org.benefits.Household
  }
}

8.11 View Declarations

The view-decl production is defined in §8.15. View declarations use an optional header-level for binding (matching the flow-decl pattern) when binding to a single entity type; the data property in the body binds to a query. Both show/explain/actions and layout body patterns are valid.

A layout block within a view MAY include layout hints (columns, sectionOrder) that are advisory to the runtime theme layer (RFC-0003 §4.5). The grammar for these hints is in §8.15 (view-layout-hint). The compiler MUST NOT reject a view for including layout hints.

8.12 Test Declarations

test-decl    ::= "test" STRING "{" test-body "}"
test-body    ::= "given"  "{" { given-stmt }  "}"
                 "when"   "{" { when-stmt }   "}"
                 "expect" "{" { expect-stmt } "}"

given-stmt   ::= IDENT ":" QUALIFIED [ "in" IDENT ] NEWLINE
when-stmt    ::= IDENT "attempts" QUALIFIED NEWLINE
               | IDENT "attempts" "transition" IDENT "->" IDENT NEWLINE
expect-stmt  ::= ( "denied" | "allowed" ) NEWLINE
               | "reason" ":" STRING NEWLINE

8.13 Action, Mutation, Actuator, Procedure, Event, Task, Compute, Extend, Client, and Workflow Declarations

Action

action-decl   ::= { decl-modifier } "action" IDENT "{" { action-prop } "}"
action-prop   ::= "meaning"    ":" STRING NEWLINE
                | "input"      "{" { field-decl } "}"
                | "execute"    "{" { execute-binding } "}"
                | "mutations"  "{" { mutation-ref } "}"
                | "after"      "{" { emits-stmt } "}"
                | annotation-block

execute-binding ::= IDENT "=" IDENT "." IDENT "using" "{" { field-assign NEWLINE } "}"
mutation-ref  ::= IDENT "using" "{" { field-assign NEWLINE } "}"
emits-stmt    ::= "emits" IDENT [ "using" "{" { field-assign NEWLINE } "}" ] NEWLINE

An action MUST NOT declare preconditions, effects, actor, or returns directly (error M07100). The mutations {} block MUST list only declared mutation names (error M07101). The after {} block MUST contain only emits statements (error M07102). Every event named in emits MUST be declared in scope (error M07108).

Mutation

mutation-decl  ::= { decl-modifier } "mutation" IDENT "{" { mutation-prop } "}"
mutation-prop  ::= "meaning" ":" STRING NEWLINE
                 | "input"   "{" { field-decl } "}"
                 | "returns" ":" type-expr NEWLINE
                 | "effects" "{" { effect-stmt } "}"

effect-stmt    ::= "creates"     QUALIFIED [ "in" IDENT ] NEWLINE
                 | "creates"     QUALIFIED "for" "each" IDENT NEWLINE
                 | "mutates"     QUALIFIED [ "." QUALIFIED ] NEWLINE
                 | "replaces"    QUALIFIED NEWLINE
                 | "deletes"     QUALIFIED [ "(" IDENT ")" ] [ "if" expr ] NEWLINE
                 | "deletes"     "all" QUALIFIED "where" field-assign NEWLINE
                 | "transitions" QUALIFIED [ "(" IDENT ")" ] "->" IDENT [ "if" expr ] NEWLINE
                 | "creates"     QUALIFIED "linking" QUALIFIED "to" QUALIFIED NEWLINE
                 | "deletes"     QUALIFIED "between" QUALIFIED "and" QUALIFIED NEWLINE
                 | "if"          expr "{" { effect-stmt } "}"

Actuator

actuator-decl  ::= { decl-modifier } "actuator" IDENT "{" { actuator-prop } "}"
actuator-prop  ::= "meaning"    ":" STRING NEWLINE
                 | "on"         ":" IDENT NEWLINE
                 | "sends"      ":" ( "email" | "sms" ) NEWLINE
                 | "calls"      ":" QUALIFIED NEWLINE
                 | "notifies"   ":" "push" NEWLINE
                 | "posts"      ":" "webhook" NEWLINE
                 | "template"   ":" STRING NEWLINE
                 | "to"         "=" expr NEWLINE
                 | "channel"    ":" STRING NEWLINE
                 | "message"    "=" expr NEWLINE
                 | "url"        ":" STRING NEWLINE
                 | "retry"      "{" retry-prop { retry-prop } "}"
                 | "onFailure"  "{" { failure-stmt } "}"

retry-prop     ::= "attempts"   ":" NUMBER NEWLINE
                 | "backoff"    ":" ( "linear" | "exponential" | "fixed" ) NEWLINE
                 | "on"         ":" ident-set NEWLINE

failure-stmt   ::= emits-stmt | "log" expr NEWLINE

Procedure

procedure-decl ::= { decl-modifier } "procedure" IDENT "{" { procedure-prop } "}"
procedure-prop ::= "meaning"       ":" STRING NEWLINE
                 | "input"         "{" { field-decl } "}"
                 | "preconditions" "{" { precond-stmt NEWLINE } "}"
                 | "runs"          ":" IDENT "using" "{" { field-assign NEWLINE } "}"
                 | "returns"       ":" type-expr NEWLINE

precond-stmt   ::= "session" "has" QUALIFIED [ "on" QUALIFIED [ "(" IDENT ")" ] [ "." QUALIFIED ] ] NEWLINE
                 | expr NEWLINE

A procedure MUST NOT declare effects {} or after {} (error M07103). A procedure MUST declare runs (error M07104). The returns type MUST be compatible with the action’s last mutation return type (error M07105).

Event

event-decl     ::= { decl-modifier } "event" IDENT "{" { event-prop } "}"
event-prop     ::= "meaning"      ":" STRING NEWLINE
                 | "fields"       "{" { field-decl } "}"
                 | "emittedBy"    ":" ident-set NEWLINE
                 | "subscribedBy" ":" ident-set NEWLINE

Task

task-decl      ::= { decl-modifier } "task" IDENT "{" { task-prop } "}"
task-prop      ::= "meaning"     ":" STRING NEWLINE
                 | "triggeredBy" ":" IDENT NEWLINE
                 | "input"       "{" { field-decl } "}"
                 | "effects"     "{" { effect-stmt } "}"
                 | "onError"     "{" { effect-stmt } "}"
                 | "retry"       "{" retry-prop { retry-prop } "}"
                 | "after"       "{" { emits-stmt } "}"

A task MUST declare triggeredBy (error M09000). A task MUST NOT declare preconditions (error M09004). The after {} block MUST contain only emits statements (error M09005).

Compute

compute-decl   ::= { decl-modifier } "compute" IDENT "{" { compute-prop } "}"
compute-prop   ::= "meaning" ":" STRING NEWLINE
                 | "input"   "{" { field-decl } "}"
                 | "returns" ":" type-expr NEWLINE
                 | "expr"    "=" expr NEWLINE
                 | "script"  IDENT "{" { UNICODE_CHAR - "}" } "}"

script lang MUST be typescript, python, or sql (error M06033). A compute MUST NOT have side effects (error M06034).

Extend

extend-decl    ::= "extend" IDENT "includes" ident-set

extend MUST appear in a file that imports the entity being extended. extend MUST be in a Schema class file (error M08704). The contributed facet MUST NOT redeclare existing entity fields (error M04801). Circular extend chains are error M04800.

Client

client-decl    ::= { decl-modifier } "client" IDENT "{" { client-prop } "}"
client-prop    ::= "meaning"    ":" STRING NEWLINE
                 | "baseUrl"    ":" STRING NEWLINE
                 | "auth"       ":" IDENT NEWLINE
                 | "operations" "{" { client-op-decl } "}"

client-op-decl ::= IDENT "{" { op-prop } "}"
op-prop        ::= "meaning" ":" STRING NEWLINE
                 | "method"  ":" ( "GET" | "POST" | "PUT" | "PATCH" | "DELETE" ) NEWLINE
                 | "path"    ":" STRING NEWLINE
                 | "input"   "{" { field-decl } "}"
                 | "returns" ":" ( type-expr | "void" | "{" { field-decl } "}" ) NEWLINE
                 | "errors"  "{" { error-class-entry } "}"

error-class-entry ::= ( NUMBER | NUMBER "xx" | "timeout" ) ":" ( "terminal" | "transient" | "ignore" ) NEWLINE

Workflow

workflow-decl  ::= { decl-modifier } "workflow" IDENT "{" { workflow-prop } "}"
workflow-prop  ::= "meaning"       ":" STRING NEWLINE
                 | "state"         ":" IDENT NEWLINE
                 | "input"         "{" { field-decl } "}"
                 | "steps"         "{" { workflow-step } "}"
                 | "compensations" "{" { compensation-decl } "}"

workflow-step  ::= "step" IDENT "{" { step-prop } "}"
step-prop      ::= "meaning"  ":" STRING NEWLINE
                 | "calls"    ":" QUALIFIED "using" "{" { field-assign NEWLINE } "}"
                 | "requires" ":" ident-set NEWLINE
                 | "retry"    "{" retry-prop { retry-prop } "}"
                 | "on"       "success" "{" { step-handler-stmt } "}"
                 | "on"       "failure" [ "(" "terminal" ")" ] "{" { step-handler-stmt } "}"

step-handler-stmt ::= "mutation"    IDENT "using" "{" { field-assign NEWLINE } "}" NEWLINE
                    | "transitions" "->" IDENT NEWLINE
                    | emits-stmt
                    | "compensate" ident-set NEWLINE

compensation-decl ::= "compensate" IDENT "{" { step-prop } "}"

A workflow MUST declare state referencing a declared flow (error M08200). Every transitions -> MUST name a declared flow state (error M08201). A compensate reference MUST have a corresponding compensate declaration (error M08202).

Saga

(* see §6.30 for semantics *)
saga-decl  ::= { decl-modifier } "saga" IDENT "{" { saga-prop } "}"
saga-prop  ::= "meaning"       ":" STRING NEWLINE
             | "state"         ":" IDENT NEWLINE
             | "input"         "{" { field-decl } "}"
             | "steps"         "{" { saga-step } "}"
             | "compensations" "{" { saga-step } "}"
             | IDENT           ":" expr NEWLINE

saga-step      ::= "step" IDENT "{" { saga-step-prop } "}"
                 | "compensate" IDENT "{" { saga-step-prop } "}"

saga-step-prop ::= "meaning"  ":" STRING NEWLINE
                 | "calls"    ":" QUALIFIED "using" "{" { field-assign NEWLINE } "}"
                 | "requires" ":" ident-set NEWLINE
                 | "retry"    "{" retry-prop { retry-prop } "}"
                 | "on"       "success" "{" { step-handler-stmt } "}"
                 | "on"       "failure" [ "(" "terminal" ")" ] "{" { step-handler-stmt } "}"

A saga MUST declare state referencing a declared flow (error M08200). Every transitions -> MUST name a declared flow state (error M08201). A compensate reference MUST have a corresponding compensate declaration (error M08202). A saga step MUST NOT contain a human_gate directive (error M07116).

Structural constraints distinguishing workflow from saga:

  • A workflow step MUST have either a model: binding (naming an AI agent model) or a human_gate directive. A step with neither MUST produce error M07115 (workflow step missing model: binding or human_gate directive).
  • A saga step MUST NOT contain a human_gate directive. Presence of human_gate inside any saga step MUST produce error M07116 (saga step contains human_gate — use workflow for human-in-the-loop orchestration).

These constraints make the structural distinction normative: workflow is the declaration kind for agent orchestration with human checkpoints; saga is the declaration kind for external API orchestration without human-in-the-loop gates.

All effect-stmt, emits-stmt, retry-prop, and failure-stmt productions defined above are shared across multiple declaration kinds where referenced.

8.14 Claim Declarations

claim-decl    ::= { decl-modifier } "claim" IDENT "{" { claim-prop } "}"
claim-prop    ::= "wraps"            ":" type-expr NEWLINE
                | "meaning"          ":" STRING NEWLINE
                | "requiredEvidence" ident-set NEWLINE
                | "allowedStatus"    ident-set NEWLINE
                | "policies"         "{" { claim-policy-stmt } "}"
                | annotation-block

claim-policy-stmt ::= IDENT ":" NUMBER NEWLINE

All claim-prop entries are optional and may appear in any order. wraps and meaning are required; their absence produces M08705.

8.15 Remaining Declaration Kinds

The annotation system (annotation facet, annotation aspect, @ decorators, annotations { } block) is defined in RFC-0011, which extends this grammar.

Import

import-decl  ::= "import" STRING

Invariant

invariant-decl ::= { decl-modifier } "invariant" IDENT "(" param-list ")" "{" expr "}"

Aspect

aspect-decl    ::= { decl-modifier } "aspect" IDENT "on" aspect-target "{" { aspect-stmt } "}"
aspect-target  ::= "any" "write" "(" QUALIFIED ")"
                 | "field" "(" qualified-list ")"
                 | QUALIFIED

aspect-stmt    ::= "emit" IDENT "{" { field-assign } "}" NEWLINE
                 | "require" expr NEWLINE
                 | "log" expr NEWLINE
                 | "contribution" ":" "{" { contribution-clause } "}"

contribution-clause ::= "properties" ":" "{" { field-decl } "}"

Compose and Apply

compose-decl   ::= { decl-modifier } "compose" IDENT "{" { compose-stmt } "}"
compose-stmt   ::= "include" QUALIFIED NEWLINE
                 | "resolve" "conflicts" "by" "precedence" ":" precedence-list NEWLINE
precedence-list ::= QUALIFIED { ">" QUALIFIED }

apply-stmt     ::= "apply" QUALIFIED "to" QUALIFIED

Query

query-decl     ::= { decl-modifier } "query" IDENT
                   ( "(" [ param-list ] ")" "->" type-expr
                   | "{" { query-prop } "}" )

query-prop     ::= "meaning" ":" STRING NEWLINE
                 | "input"   "{" { field-decl } "}"
                 | "returns" ":" type-expr NEWLINE
                 | annotation-block

The one-line form (query name(params) -> Type) is syntactic sugar for a block with input and returns and no meaning. The block form is canonical in the compiled IR.

View

view-decl      ::= { decl-modifier } "view" IDENT [ "for" QUALIFIED ] "{" { view-prop } "}"
view-prop      ::= "data"    ":" QUALIFIED NEWLINE
                 | "show"    "[" { QUALIFIED [ "," ] } "]" NEWLINE
                 | "explain" "{" { explain-stmt } "}"
                 | "actions" "{" { view-action-stmt } "}"
                 | "layout"  "{" { layout-section } "}"
                 | "route"   "{" { route-prop } "}"
                 | annotation-block

route-prop     ::= "path"     ":" STRING NEWLINE
                 | "when"     ":" expr NEWLINE
                 | "fallback" ":" STRING NEWLINE

explain-stmt     ::= IDENT "as" STRING NEWLINE
view-action-stmt ::= IDENT "can" "mark" IDENT NEWLINE

layout-section     ::= "section" STRING "{" { layout-item } "}"
                      | "extensionPoints" "[" { IDENT } "]" NEWLINE
                      | "sublayout"       QUALIFIED NEWLINE
                      | "region"          IDENT "{" { layout-item | "sublayout" QUALIFIED NEWLINE } "}"
                      | view-layout-hint

layout-item        ::= "field"  IDENT [ "{" "claimWidget" ":" QUALIFIED "}" ] "label" STRING NEWLINE
                      | "button" STRING "triggers" QUALIFIED NEWLINE
                      | "button" STRING "navigates" "to" QUALIFIED "(" field-assign-list ")" NEWLINE

(* Layout hints — advisory; runtime theme layer MAY ignore *)
view-layout-hint   ::= "columns"      ":" NUMBER NEWLINE
                      | "sectionOrder" ":" "[" IDENT { "," IDENT } "]" NEWLINE

The for binding is an optional header-level clause naming the primary entity type for this view (e.g. view PlanDetail for Plan { ... }). The data body property binds to a query result. Both are optional; they may refer to the same or different qualified names. All view-prop entries are unordered.

App

app-decl       ::= { decl-modifier } "app" IDENT "{" { app-prop } "}"
app-prop       ::= "version"  ":" STRING NEWLINE
                 | "audience" ":" ident-set NEWLINE
                 | app-includes

app-includes   ::= "includes"
                   ( "models" | "policies" | "flows" | "views" | "agents" )
                   ident-set NEWLINE

8.16 Model Declarations

model-decl   ::= { decl-modifier } "model" IDENT "{" model-body "}"
model-body   ::= { model-prop }
model-prop   ::= "meaning"   ":" STRING
               | "provider"  ":" STRING
               | "name"      ":" STRING
               | "digest"    ":" STRING
               | "version"   ":" STRING
               | "parameters" "{" { model-param } "}"
               | "roles" ident-set
               | annotation-block

model-param  ::= IDENT ":" ( NUMBER | STRING ) NEWLINE

A model MUST declare exactly one meaning, provider, and name, and exactly one of digest or version. The properties may appear in any order; duplicate singleton properties are errors.

model declarations follow the same import/export rules as any other declaration. A module that declares models intended for reuse across projects SHOULD place them in a dedicated file (e.g., governance/models.gnm) and export them as public.

8.17 Enum Declarations

Top-level named enumerations (RFC-0006 §4.6a):

enum-decl    ::= { decl-modifier } "enum" IDENT "{" enum-body "}"
enum-body    ::= "meaning" ":" STRING
                 "values" ident-set

Example:

enum BenefitType {
  meaning: "The category of benefit a plan provides."
  values [medical_plan, dental_plan, vision_plan, hsa, fsa, hra]
}

Inline anonymous enums are declared directly in a field type position using inline-enum (§8.3):

entity Bundles {
  status: enum { pending, ready, selected, expired }
}

Inline enums are scoped to the enclosing declaration. Values are not referenceable by name from outside that declaration. If the same value set is needed in multiple places, promote to a top-level enum.

Enum value names MUST be lower_snake_case. The compiler emits M08740 if casing is incorrect.

8.18 Configuration Declarations

RFC-0046 defines the configuration and override contracts. Both forms belong to the Schema declaration class. A config declaration is authored in module source (including schema.gnm); config-set is permitted only in a pure config.<env>.gnm override file. Such a file MUST contain only config-set declarations: imports, other declarations, and executable expressions are M46020. These restrictions are checked after parsing.

config-decl ::= "config" IDENT "{" { config-prop } "}"
config-prop ::= "meaning" ":" STRING NEWLINE
              | "type" ":" type-expr NEWLINE
              | "default" ":" config-literal NEWLINE
              | "required" ":" ( "true" | "false" ) NEWLINE
              | "sensitive" ":" ( "true" | "false" ) NEWLINE
              | "description" ":" STRING NEWLINE
              | "exported" ":" ( "true" | "false" ) NEWLINE
              | "flag" ":" ( "true" | "false" ) NEWLINE
              | "perTenant" ":" ( "true" | "false" ) NEWLINE

config-set-decl ::= "config-set" QUALIFIED "=" config-literal NEWLINE
config-literal ::= STRING | NUMBER | "-" NUMBER | "true" | "false"
                 | config-list | config-map
config-list ::= "[" [ config-literal { "," config-literal } ] "]"
config-map ::= "{" [ STRING ":" config-literal
                   { "," STRING ":" config-literal } ] "}"

A config declaration MUST have exactly one meaning and one type slot; each optional slot MAY appear at most once. The compiler validates a default or override value against the declared type. flag: true requires Boolean, and perTenant: true requires flag: true (RFC-0046 §6). The literal grammar is deliberately value-only: it has no null, calls, operators, or source references. Structured values use JSON-style lists and maps without null.

8.19 Module Manifest

The module declaration is the single permitted top-level declaration in module.gnm (RFC-0001). It declares the module’s FQN, version, type, dependencies, and references to all .gnm source files in the module.

module-decl   ::= "module" FQN "{" module-body "}"
module-body   ::= "version" ":" STRING NEWLINE
                  "type"    ":" module-type NEWLINE
                  [ module-imports-block ]
                  [ module-objects-block ]
                  [ module-ops-block ]
                  [ module-agents-block ]

module-type   ::= "backend-only" | "ui-only" | "hybrid"

module-imports-block ::= "imports" "{" { module-import-entry } "}"
module-import-entry  ::= FQN ":" STRING NEWLINE

module-objects-block ::= "objects" "[" NEWLINE { STRING NEWLINE } "]"
module-agents-block  ::= "agents"  "[" NEWLINE { STRING NEWLINE } "]"

module-ops-block     ::= "operations" "[" NEWLINE { module-op-entry NEWLINE } "]"
module-op-entry      ::= STRING
                       | "{" "path" ":" STRING
                             [ "," "rollbackCheckpoint" ":" BOOL ]
                             [ "," "rollbackDependsOn" ":" string-seq ]
                         "}"

Constraints:

  • module-decl MUST appear only in a file named module.gnm. Its presence in any other file MUST produce error M08723.
  • module.gnm MUST contain exactly one module-decl and no other top-level declarations. A file containing more than one module-decl produces error M01060 (defined in RFC-0001 §9); a file containing non-module top-level declarations alongside module-decl produces error M08724.
  • The FQN in module-decl MUST use only NAME segments (lowercase, RFC 1123 label syntax). It MUST NOT use IDENT (mixed-case) segments.

Example:

module org.benefits.plans {
  version: "1.2.3"
  type: hybrid

  imports {
    gnomon.core:        "^1.0.0"
    org.hr.employees: "^2.0.0"
  }

  objects [
    "entities/plan.gnm"
    "entities/enrollment.gnm"
  ]

  operations [
    "operations/queries.gnm"
    { path: "operations/submit.gnm", rollbackCheckpoint: true }
  ]

  agents [
    "agents/recommendation.gnm"
  ]
}

8.20 Project Manifest

project-decl  ::= "project" STRING "{" project-body "}"
project-body  ::= "version" ":" STRING
                  [ "imports" ":" string-seq ]
                  [ "modules" ":" string-seq ]
                  [ compiler-block ]

compiler-block ::= "compiler" "{" compiler-prop { compiler-prop } "}"
compiler-prop  ::= "ruleCompiler"    ":" IDENT   NEWLINE
                 | "promptTemplate"  ":" STRING  NEWLINE

8.21 Syntactic Sugar and the Desugar Pass

Overview

Sugar forms are syntactic shorthands that expand deterministically to a canonical block form before any semantic analysis. The compiler MUST implement sugar expansion as a single, isolated desugar pass with the following properties:

  1. Purely syntactic: the desugar pass operates on the raw parse tree. It MUST NOT perform symbol resolution, type checking, or semantic validation.
  2. Bijective expansion: every sugar form maps to exactly one canonical block form. Expansion is deterministic and lossless.
  3. Idempotent: applying the desugar pass twice produces the same result as applying it once.
  4. Auditable: the compiler SHOULD expose a --print-desugared flag that emits the post-desugar AST before any further compilation, to aid debugging and conformance testing.

The canonical IR (RFC-0010) MUST NOT contain sugar forms. The conformance grammar (§8) tests canonical forms; sugar forms are tested only as desugar-unit tests.

Current Sugar Inventory

Sugar formCanonical expansionProduction
query name(params) -> Typequery name { input { params } returns: Type }§8.15
Bare field-decl in entity bodyfields { field-decl } block§9.6

RFC-0011 adds a third sugar form: @FacetName decorator desugaring to annotation facet inclusion.

Expansion Rules

Query shorthand:

(* Sugar *)
query-shorthand ::= { decl-modifier } "query" IDENT "(" [ param-list ] ")" "->" type-expr

The shorthand expands to the block alternative of query-decl in §8.15: parameters become input fields and the result type becomes returns. The §8.15 production remains the single grammar definition of query-decl; this expansion describes the compiler’s canonical representation.

Bare field in entity body:

(* Sugar: field-decl appearing directly in entity-prop position *)
(* Expands to: the field-decl is moved inside a "fields { }" block *)
(* If a "fields { }" block already exists, the bare field is appended to it *)

The desugar pass MUST merge bare fields and explicit fields { } blocks into a single canonical fields { } block. The ordering of merged fields follows source order.

Closed Sugar Set

The sugar inventory is closed: new sugar forms MUST be introduced only through a revision of this RFC. Module authors MUST NOT define their own syntactic expansions. This is a deliberate constraint — user-defined sugar creates the same readability problems as operator overloading (the reader must know the module’s expansion rules to understand the code). Gnomon’s domain-readability goal requires that any .gnm file be understandable without consulting module-local syntax definitions.

Future sugar candidates (to be evaluated in subsequent RFC revisions):

CandidateSugarCanonical expansion
Inline flow statesflow: [Draft, Active] inside entity bodySeparate named flow declaration
Inline relationEmployee -> Plan via elects at top levelFull relation elects { from: Employee; to: Plan }

These are not yet in the grammar. They MUST NOT be implemented until accepted into the spec.

8.22 Shared Productions

(* Modifiers — may appear in any order before the declaration keyword *)
decl-modifier        ::= visibility-modifier | epistemic-modifier
visibility-modifier  ::= "public" | "internal"
epistemic-modifier   ::= "draft" | "deprecated" | "experimental" | "sealed" | "abstract"

(* Rule blocks — replace nat-lang-block throughout; four statement kinds *)
rule-block     ::= "{" { rule-stmt } "}"
rule-stmt      ::= compiled-rule | expr-rule | runtime-prompt | doc-note

(* compile-time: NL text lowered to constraint-expr by rule compiler at compile time *)
compiled-rule  ::= "rule" STRING [ "with" IDENT ] NEWLINE
                   (* STRING is the natural-language text; optional IDENT names a model override *)
                   (* compiler replaces this with a constraint-expr in the IR *)
                   (* cached as structured comment; re-compiled only on text or model change *)

(* structured: deterministic boolean expression; no LLM involved *)
expr-rule      ::= "expr" "{" expr "}" NEWLINE

(* runtime: prompt evaluated by a bound model at execution time; not compiled to constraint *)
runtime-prompt ::= "prompt" STRING [ "with" IDENT ] NEWLINE

(* documentation: prose annotation; never evaluated *)
doc-note       ::= "note" STRING NEWLINE

(* Legacy form retained for compatibility during migration; emits warning M08790 *)
nat-lang-stmt  ::= ( UNICODE_CHAR - ( NEWLINE | "{" | "}" ) )+ NEWLINE
nat-lang-block ::= "{" { nat-lang-stmt } "}"
(* List literal — the canonical form for any ordered sequence of values in Gnomon syntax.         *)
(* `[]` is used uniformly throughout: ident-set for name lists, string-seq for string lists,     *)
(* qualified-list for qualified name lists. All occurrences in grammar productions that express  *)
(* a "list of X" MUST use one of these forms rather than an ad-hoc brace or paren equivalent.   *)
ident-set      ::= "[" ident-list "]"
string-seq     ::= "[" { STRING [ "," ] } "]"
qualified-set  ::= "[" qualified-list "]"

(* Field declarations — used in entity, agent, relation, action, scope, and contribution blocks *)
field-decl     ::= IDENT ":" type-expr NEWLINE

(* Parameters and lists *)
param-list     ::= param-decl { "," param-decl }
param-decl     ::= IDENT ":" type-expr
ident-list     ::= IDENT { "," IDENT }
qualified-list ::= QUALIFIED { "," QUALIFIED }

(* Assignment forms *)
field-assign      ::= IDENT ":" expr
field-assign-list ::= field-assign { "," field-assign }

(* Expressions — used in invariant bodies, preconditions, and aspect stmts *)
(* Right-recursive / iterative form to maintain PEG compatibility (RFC-0008 §8.0) *)
expr        ::= unary-expr { binary-op unary-expr }
unary-expr  ::= "!" unary-expr
              | postfix-expr
postfix-expr ::= primary-expr { "." IDENT [ "(" [ arg-list ] ")" ] }
primary-expr ::= QUALIFIED
               | NUMBER
               | STRING
               | "true"
               | "false"
               | "null"
               | "sum" "(" expr ")"
               | "count" "(" expr ")"
               | "exists" "(" expr "," IDENT "->" expr ")"
               | "all" "(" expr "," IDENT "->" expr ")"
               | "age" "(" expr ")"
               | "today" "(" ")"
               | "now" "(" ")"
               | "irsLimits" "(" expr "," expr ")"
               | "context" "." IDENT { "." IDENT }
               | "(" expr ")"
binary-op   ::= "==" | "!=" | "<" | "<=" | ">" | ">="
               | "+" | "-" | "*" | "/"
               | "&&" | "||"
               | "->"

arg-list ::= expr { "," expr }

9. Unified Declaration Model

All declarations share a single block-based syntax. There is no separate “entity syntax” or “scope syntax”. The distinction is eliminated as of this revision.

9.0 File Layout Convention

When a module concept has declarations spanning multiple declaration classes, all files for that concept live together in a named subfolder under the module directory. The subfolder name is the concept name (kebab-case per NAME, §8.1). Each file within the subfolder is named after its declaration kind, as specified in §7.

Single-class concept (schema only):

modules/
  planning/
    proposal/
      schema.gnm       ← entity, type, flow, variant, or facet declarations

Multi-class concept:

modules/
  planning/
    proposal/
      schema.gnm       ← entity/type/flow/variant/facet declarations
      actions.gnm      ← action declarations
      queries.gnm      ← query declarations
      mutations.gnm    ← mutation declarations
      events.gnm       ← event declarations
      procedures.gnm   ← procedure declarations
  auth/
    user/
      schema.gnm
      actions.gnm
      queries.gnm
    agreement/
      schema.gnm
      actions.gnm
      queries.gnm

The compiler discovers all .gnm files in each concept folder. All files in a folder MUST belong to the same gnomon module (error M07901 if violated). Kind files that have no declarations for a given concept MUST be omitted rather than left empty.

Files MUST NOT be named after generic roles (common.gnm, utils.gnm, defs.gnm, misc.gnm) — error M08744. Each file MUST be named after its declaration kind as listed in §7.

9.1 FacetType and Aspect Are Distinct Mechanisms

  • A facet declaration (FacetType, RFC-0006 §4.2) is an additive composition unit. It is pulled into an entity by the entity via includes [Auditable]. The entity controls inclusion.
  • An aspect declaration (RFC-0004) is a cross-cutting contribution. It pushes structure into target kinds via selectors. The aspect controls targeting.

These have inverse control flow. The compiler MUST NOT silently coerce a facet declaration into an aspect during normalization. Automated coercion is not valid.

9.2 Declaration Conflict Rule

A module MUST NOT define the same canonical path in two source files. The compiler MUST detect declaration conflicts across files and produce error M08731.

9.3 Extending a Declaration

When adding invariants or aspects to a declaration defined in another file, import its canonical path and add the additional declarations in the same file (see §6.19 for an example).

10. Naming and Casing Conventions (Normative)

All naming rules in this section are normative. Violations MUST produce compiler diagnostics as specified in §13.

File names, folder names, and module namespaces follow RFC 1123 §2.1 and the Kubernetes naming conventions (kubernetes.io/docs/concepts/overview/working-with-objects/names). The terminal definitions NAME and FQN in §8.1 are the normative grammar forms.

10.1 File Names

  • File names (without the .gnm extension) MUST conform to NAME: lowercase, starting with a letter, containing only [a-z0-9-], max 63 characters.
  • File names MUST NOT use generic names: defs.gnm, misc.gnm, common.gnm, utils.gnm are forbidden (M08744).
  • File names MUST NOT use numeric suffixes (model2.gnm) (M08744).
  • The project manifest MUST be named project.gnm exactly (M08722).

10.2 Folder Names

  • Folder names MUST conform to NAME: lowercase kebab-case, max 63 characters.
  • Folder names SHOULD be plural nouns representing the domain: entities/, policies/, agents/, governance/.
  • The top-level module domain folder MUST be a NAME noun: benefits/, enrollment/, claims-processing/.

10.3 Identifier Casing

The following rules are enforced by the compiler. Violations produce diagnostic M08740 (error) or M08741/M08742 (warning/error as noted).

Declaration kindRequired casingExampleDiagnostic
EntityType namePascalCaseEmployee, PlanRecommendationM08740
FacetType namePascalCaseAuditable, AIDraftableM08740
RelationType namecamelCase verb or verb phraseelects, belongsTo, hasMemberM08740
FlowType namePascalCasePlanRecommendationLifecycleM08740
ActionType namecamelCase verb phrasesubmitEnrollment, draftRecommendationM08740
EvidenceType (claim) namecamelCasediagnosisCode, recommendedPlanM08740
PolicyType namePascalCaseAIGuardrails, PrivacyPolicyM08740
AgentType namePascalCase + MUST end in AgentRecommendationAgentM08742
Model namePascalCaseGemma3Local, GPT4oM08740
ViewType namePascalCasePlanRecommendationSummaryM08740
State name (in flow)PascalCaseDraft, Reviewed, ApprovedM08740
Field namecamelCaseemployeeId, fullName, hireDateM08740
Module namespaceFQN: dot-separated NAME segments, max 253 charsbenefits.enrollmentM08743

The following conventions are RECOMMENDED (warning on violation, not error):

  • FlowType names SHOULD end in Lifecycle: EnrollmentLifecycle, RecommendationLifecycle (M08741).
  • PolicyType names SHOULD end in Policy or Guardrails or Rules: PrivacyPolicy, AIGuardrails (informational, no diagnostic).
  • ActionType names SHOULD begin with a verb in camelCase: submit, draft, approve, reject, create.
  • RelationType names SHOULD be verbs or verb phrases in camelCase, not nouns: prefer elects over enrollment.

10.5 Meaning Field Content

  • All meaning fields MUST be plain-language prose readable by a non-technical domain author.
  • meaning fields MUST NOT contain code, type names, or implementation references.
  • meaning fields SHOULD end with a period.
  • meaning fields MUST NOT be empty strings. Violations produce error M08705.

11. Visibility and Epistemic State

11.1 Visibility

Every top-level declaration is either public (the default) or internal.

  • public (default): the declaration is exported in the compiled bundle and MAY be imported by other modules.
  • internal: the declaration is NOT exported in the compiled bundle and MUST NOT be referenced from outside the declaring module.

The visibility-modifier is optional. When omitted, public is assumed. Explicit public is permitted but redundant.

public entity Employee { ... }    // explicit public — same as default
internal facet InternalHelper { ... }  // module-private
entity Plan { ... }               // implicitly public

Visibility rules:

  1. A public declaration MUST NOT reference an internal declaration from a different module. Violations produce error M08750.
  2. An internal declaration MAY reference any other declaration in the same module.
  3. project declarations in project.gnm MUST NOT have a visibility modifier. Violations produce error M08751.
  4. test declarations are implicitly internal and MUST NOT carry a visibility modifier. Violations produce error M08751.
  5. The compiler MUST NOT export internal declarations in the compiled bundle (RFC-0002). Presence of an internal declaration in the exported identity envelope MUST produce error M08752.

11.2 Epistemic Modifiers

Epistemic modifiers express the authoring and lifecycle state of a declaration. They are compile-time signals to the compiler, the LSP, and the annotation system. They are distinct from visibility: a declaration may be public draft (exported but unstable) or internal deprecated (private and being phased out).

ModifierMeaningCompiler behavior
draftIncomplete or AI-proposed; not yet reviewed by a human authorWarning M08780 if referenced by a non-draft declaration
deprecatedStable but scheduled for removal; consumers should migrateWarning M08781 at every use site
experimentalStable but subject to breaking change without noticeWarning M08782 at every use site from outside the declaring module
sealedPublicly visible but MUST NOT be extended, composed, or includesd outside the declaring moduleError M08783 on external extension
abstractIncomplete by design; MUST be composed into a concrete declaration before useError M08784 if referenced directly (not as part of a composition)

Epistemic modifiers are placed before the declaration keyword, after the visibility modifier if present:

public draft entity PlanRecommendation {
  meaning: "A benefits plan recommendation generated by the AI advisor."
  // drafted by RecommendationAgent; pending human review
}

deprecated entity LegacyEnrollment {
  meaning: "Superseded by Enrollment. Use Enrollment instead."
}

public experimental facet AIEnhanced {
  meaning: "Marks a declaration as eligible for AI-driven field inference."
}

Epistemic modifier rules:

  1. A declaration MAY carry at most one epistemic modifier (M08785 on multiple).
  2. draft declarations MUST NOT appear in a compiled bundle with ciState: ready. Violations produce error M08786. This enforces that AI-generated or incomplete declarations are reviewed before release.
  3. deprecated and experimental are advisory; they do not prevent compilation or export.
  4. sealed is enforced only across module boundaries. Within a module, sealed declarations MAY be composed freely.
  5. abstract declarations may only be used in compose or includes positions. Direct field-type references or action actor references produce M08784.
  6. The draft epistemic modifier is the normative AI authoring marker (resolving RFC-0008 Q3). AI agents producing declarations MUST attach draft to any declaration that has not been reviewed by a human author (RFC-0009 §6).

11.3 Rule Statement Semantics

Rule blocks (rule-block) replace nat-lang-block throughout this RFC. The four statement forms have distinct compilation semantics:

rule "..." — Compile-time natural language constraint

facet SpendingAccount {
  rules {
    rule "employee and employer contributions combined must not exceed the annual IRS limit"
    rule "employee and employer contributions combined must not exceed the annual IRS limit" with MedicalDomainModel
  }
}
  • The compiler lowers the STRING to a constraint expression using the configured rule compiler model (§7 compiler.ruleCompiler) or the per-statement model override.
  • The compiled expression is stored in the IR. The source STRING is preserved in the bundle for tooling and human review.
  • A compilation cache associates (rule_text_hash, model_digest, template_version) with the compiled expression. The LLM is invoked only on a cache miss.
  • If no rule compiler model is configured and no per-statement override is given, the rule MUST produce error M08791 (uncompiled rule).
  • If the LLM cannot compile the rule (UNRESOLVABLE output), the compiler emits error M08792 with the UNRESOLVABLE reason. The build fails.
  • If the LLM identifies the rule as an AUTHORIZATION_RULE or LIFECYCLE_RULE, the compiler emits warning M08793 suggesting the rule be moved to a policy or flow declaration respectively.
  • rule statements in permissions/prohibitions/requirements blocks of agent declarations are compiled to agent capability assertions, not entity constraints.

expr { ... } — Structured constraint expression

invariant HSALimit(p: Person, year: PlanYear) {
  expr { p.contributions.hsa + p.household.employerHSAContribution
           <= irsLimits(year, p.household.coverageType).hsaMax }
}
  • A boolean expression in the Gnomon constraint expression language (§8.22).
  • No LLM involved. Deterministic at all times.
  • Authors who know the expression language SHOULD prefer expr { } over rule "..." for performance and reproducibility.
  • The LSP SHOULD offer a “compile to expr” refactoring that converts an accepted rule "..." to its compiled expr { } form, permanently removing the LLM dependency for that constraint.

prompt "..." — Runtime prompt

agent AdvisorAgent {
  purpose: "Provide personalized guidance on benefit selections."
  model: GPT4o

  permissions {
    prompt "explain the tradeoff between the selected HSA contribution and the household's projected medical expenses"
    prompt "summarize why the balanced bundle was recommended for this household" with SummaryModel
  }
}
  • NOT compiled to a constraint expression. Stored verbatim in the IR as a prompt template.
  • Evaluated by the bound model (agent.model or per-statement with ModelName) at runtime.
  • The model MUST have runtime-agent in its roles.
  • Runtime prompts are NOT constraint-evaluable. They MUST NOT appear in invariant, facet.rules, or policy.rules blocks — only in agent permission/requirement/prohibition blocks. Violations produce error M08794.

note "..." — Documentation only

facet HDHPLinked {
  rules {
    rule "household must have an active HDHP-qualified medical plan"
    note "HSA catch-up contributions (age >= 55) are validated separately via the HSAContributionLimit invariant"
  }
}
  • Never evaluated. Stored in the bundle as documentation metadata alongside the declaration.
  • Authors use note to explain why a rule exists, reference related invariants, or describe edge cases that are handled elsewhere.

Sugar: bare natural-language lines (legacy)

Bare natural-language lines (the old nat-lang-block form) produce warning M08790 and are treated as rule "..." during migration. They MUST be migrated to one of the four typed forms. The legacy form will be removed in a future RFC revision.

Rule compilation cache format

The compiled cache entry for a rule "..." statement is stored as a structured comment immediately following the statement in the canonical source (maintained by gnomon fmt):

rule "employee and employer contributions combined must not exceed the annual IRS limit"
//compiled: p.contributions.hsa + p.household.employerHSAContribution <= irsLimits(planYear, p.household.coverageType).hsaMax
//compiled-by: gemma3:4b@sha256:a1b2c3d4 template:gnomon-rules-v1 rule-hash:e3f4a5b6

gnomon fmt MUST preserve //compiled: and //compiled-by: comments. The compiler MUST treat a cached expression as authoritative if the rule text hash, model digest, and template version all match. A mismatch invalidates the cache and triggers LLM re-compilation.

12. Syntax Design Principles

The Gnomon DSL syntax is positioned between protobuf, HCL, and controlled English:

  • Keywords carry semantic meaning (entity, facet, relation, flow, policy, agent, view, test)
  • Declaration bodies are open and unordered; gnomon fmt enforces canonical property ordering
  • Plain-language meaning, purpose, and explain fields are first-class citizens, not comments
  • YAML is NOT an authoring format; it may appear in compiled output artifacts (RFC-0002) only — all source files use .gnm DSL syntax

12.1 Comment and Documentation Model

Three comment forms are defined:

FormParser treatmentPurpose
// textDiscardedInline implementation notes
/* text */DiscardedBlock notes, commented-out code
/// textPreserved as doc metadataNarrative documentation attached to the following declaration

Doc comment content MUST be CommonMark prose. No @tag syntax (JSDoc-style) is defined or permitted. The rationale: every piece of structured metadata that @tags would carry — purpose, parameters, examples, since, see-also — is already expressible as first-class declaration properties (meaning, input, examples, annotation facets). Using @tags in doc comments would create a second authoring surface for the same information with no clear authority. Doc comments are exclusively for extended narrative: the why, the caveats, and the context that doesn’t belong in structured properties.

meaning field vs /// doc comment: meaning is machine-readable, compiler-enforced, and part of the semantic model. It MUST be a single sentence suitable for display in UI and tooling. A /// doc comment is human-readable extended prose, preserved in the bundle but not enforced by invariants. Authors SHOULD write meaning first; doc comments augment it.

Diagnostics

The diagnostic catalog for this RFC is authored in the structured Lean module and rendered in reference catalog § Diagnostics. Inline mentions in the prose above (e.g., “rejected with MNNxxx”) cross-link to the catalog at render time.

14. Security and Authorization

  1. Authorization logic MUST reside in files whose top-level keyword is policy; it MUST NOT appear in entity or view declarations.
  2. Agent capability declarations MUST be reviewed and explicitly approved before deployment (RFC-0009).
  3. UI projections MUST NOT expose fields that the active policy prohibits for the rendering actor.

15. Compatibility and Migration

  1. Changing the syntax of an existing declaration kind is a breaking change and MUST increment the language version.
  2. Adding a top-level declaration keyword is non-breaking for a parser that explicitly supports skipping that form and whose compiler can safely omit its semantics. An unknown form MUST NOT be silently skipped when omission would discard required metadata or a declaration.
  3. RFC-0011 annotation syntax is an additive grammar extension, but an older parser MUST reject it with M11803 before compilation or install rather than skip it. The error identifies the required compiler version or feature (RFC-0011 §10).