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
- Non-technical domain authors can read and write declarations without engineering assistance
- All declaration bodies use a single open block-property syntax; authoring depth is additive, not modal
- File purpose is inferrable from the top-level declaration keyword, not the file extension
- Syntax is structured enough to be parsed deterministically, readable enough to be reviewed without tooling
- UI and app declarations are projections over the semantic model, not independent layers
- 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
- Every source file MUST use the
.gnmextension. Files with any other extension MUST produce error M08700. - 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-locatetype,variant,flow, andinvariantdeclarations 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 namedmigrations.gnmortransforms.gnmwithin a concept folder. - Every entity declaration MUST include a
meaningproperty. - Every facet declaration MUST include a
meaningproperty. - Every agent declaration MUST enumerate explicit
permissionsandprohibitions. - UI view declarations MUST NOT contain business rules; authorization and invariants belong in policy declarations.
- The project manifest (
project.gnm) MUST NOT contain declaration content other than theproject { }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 keyword | Declaration class | RFC-0006 primitive / derivation |
|---|---|---|
type | Schema | Vocabulary / primitive type aliases (no RFC-0006 primitive) |
entity | Schema | Entity (§4.1) |
facet | Schema | Facet (§4.2) |
variant | Schema | Discriminated union value type (Proposal 1) |
flow | Schema | Lifecycle state machine (§4.6) |
invariant | Schema | Named parametric constraint; derives from Policy (§4.7) |
mutation | Schema | Named pure transactional state change (§6.21) |
compute | Schema | Named pure derived value (§6.27) |
extend | Schema | Cross-module facet contribution (§6.28) |
config | Schema | Typed runtime configuration declaration (RFC-0046 §4) |
config-set | Schema | Pure override-file value binding (RFC-0046 §3.2) |
relation | Relations | Named association between entities (§4.3) |
action | Operations | Composes mutations and emits events (§6.10) |
query | Operations | Named read accessor over gnomon query API (RFC-0007 §7) |
task | Operations | Named background computation triggered by event (§6.23) |
integration | Operations | Named external push protocol (Proposal 7) |
procedure | Operations | API binding: auth + action delegation (§6.25) |
actuator | Operations | Event-driven side-effect handler (§6.22) |
event | Operations | Named domain event with typed fields (§6.24) |
client | Operations | Typed outbound API contract (§6.29) |
saga | Operations | Multi-step fallible external API saga (§6.30) |
workflow | Operations | Multi-agent orchestration with human-in-the-loop gates (RFC-0022) |
api | Operations | Protocol-agnostic public service surface (RFC-0033) |
serve | Operations | Wire-protocol binding for an api declaration (RFC-0034) |
claim | Schema | EvidenceType — declares a named Claim<T> type (§4.5) |
transform | Migrations | Pure data migration function; maps entity instances between versions (RFC-0016 §3) |
migration | Migrations | Schema + data evolution step with forward and rollback paths (RFC-0016 §2) |
policy | Governance | Policy (§4.7) |
agent | Governance | Participation contract (RFC-0009; not a semantic primitive) |
compose | Governance | Policy composition mechanism (RFC-0004) |
aspect | Governance | Cross-cutting contribution mechanism (RFC-0004) |
view | Surface | Projection layer (RFC-0007 §5.3); compiles via RFC-0003 §5a |
app | Surface | Bundle declaration; compiles to RFC-0002 bundle |
test | Tests | Executable policy/safety assertions (no RFC-0006 primitive) |
model | Governance | AI 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 declarationsgovernance/— cross-cutting policy and agent declarationsexamples/— concrete instance examplestests/— 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:
keywordselects the declaration kind (e.g.,entity,action,compute)Nameis 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 representsdeprecated: Boolean— (optional; property slot) signals that this declaration should not be used in new code; equivalent to thedeprecatedepistemic modifier at the slot levelowner: 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:
| Kind | Structural constraint |
|---|---|
invariant | Requires a parameter list in the header and a bare expression body — not a property block |
aspect | Body is a statement list (emit, mutate, assert), not key-value properties |
test | Requires ordered mandatory blocks: given, when, then |
flow | states block MUST appear before transitions for the compiler to resolve state references |
facet | meaning 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:
| Modifier | Valid contexts | Meaning |
|---|---|---|
required | fields {}, 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. |
deprecated | fields {} | Field is scheduled for removal. Compiler emits M08781 at every write site. |
sensitive | fields {} | Field contains PII or sensitive data. Excluded from default query projections; requires @SensitiveData annotation (RFC-0011). |
indexed | fields {} | Hint to the storage layer that this field is frequently used in filters; may create a secondary index. |
unique | fields {} | 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—requiredanddefault(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
actionMUST NOT declarepreconditions,effects, orreturnsdirectly (error M07100) - The
mutations {}block MUST list only declaredmutationnames (error M07101) - The
after {}block MUST contain onlyemitsstatements (error M07102) - Every event named in an
emitsstatement MUST be declared in scope (error M07108) - Every
executebinding MUST reference a declaredclientand a declared operation on that client (error M07109) - An
executebinding 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:
applywith@forms is annotation-only: it cannot add fields, change types, or alter the target declaration’s behavior.- Multiple
@forms may appear on a singleapplystatement; they are applied in declaration order. - The annotation-arg-block provides required annotation facet field values for this application site.
applyat the member level (apply Namespace#Entity.field @Annotation) attaches the annotation to the named field, not the enclosing entity.applyis valid in any Governance-class file. Compilers MUST NOT permitapplyin Schema or Operations files.
Invariants:
- The target FQN MUST resolve to a declared entity, field, query, or operation (error M06070 if not).
- Each
@annotation MUST reference a declaredannotation facet, not a semanticfacet(error M08770). applyMUST NOT duplicate an annotation already declared inline on the target (error M06071 — useannotations { }override at the source instead).applyMUST NOT appear in the same module that declares the target (error M06072 — use inlineannotations { }instead).
Diagnostic codes:
M06070—applytarget FQN does not resolve to a declared declarationM06071—applyannotation duplicates an annotation already declared inline on the targetM06072—applyin same module as target; use inlineannotations { }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:
| Role | Description |
|---|---|
rule-compiler | May be used by the compiler to lower rule "..." statements to constraint expressions |
runtime-agent | May 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; requirestemplateandtosends: sms— SMS delivery; requirestocalls: <client>.<operation>— outbound API call (see §6.29clientdeclaration)notifies: push— push notification; requirestoposts: webhook— outbound webhook; requiresurl
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:
mutation | task | |
|---|---|---|
| Execution | Synchronous, in-transaction | Asynchronous, post-event |
| Triggered by | Composed into action | Domain event (triggeredBy) |
| Actor | None | System |
| Can emit events | No | Yes (after {}) |
| Declaration class | Schema | Operations |
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)
mutation | action | actuator | task | procedure | query | |
|---|---|---|---|---|---|---|
| Has actor | No | No | No | System | Yes | Yes |
| Has preconditions | No | No | No | No | Yes | Yes |
| Owns state changes | Yes | No (delegates) | No | Yes (async) | No | No |
| Calls external APIs | No | Yes (execute {}) | Yes | No | No | No |
| Emits events | No | Yes (after) | No | Yes (after) | No | No |
| Triggered by | Action composition | Procedure (runs) | Event (on) | Event (triggeredBy) | Actor | Actor |
Has returns | Optional | Implicit (last mutation) | No | No | Yes | Yes |
| Declaration class | Schema | Operations | Operations | Operations | Operations | Operations |
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:
query | compute | |
|---|---|---|
| Has actor | Yes | No |
| Has preconditions | Yes (access control) | No |
| Declaration class | Operations | Schema |
| Has side effects | No | No |
| Co-located with entity | No (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:
| Module | Function | Schema source | RFC |
|---|---|---|---|
gnomon.io.openapi | openapi(path) | OpenAPI 3.x YAML or JSON file | RFC-0028 |
gnomon.io.protobuf | protobuf(path) | Protocol Buffer .proto file | RFC-0030 |
gnomon.io.graphql-introspect | graphqlIntrospect(url) | GraphQL introspection endpoint | RFC-0031 |
gnomon.io.graphql-introspect | graphqlSchema(path) | GraphQL SDL file | RFC-0031 |
gnomon.io.trpc | trpc(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 immediatelytransient— may resolve on retry; apply declared retry policyignore— treat as success (idempotent operations where the desired state already exists)
Compiler rules:
- A hand-authored
clientMUST declare at least one operation (error M08100) - Every hand-authored operation MUST declare
method,path,input, andreturns(error M08100) - Every
errorsentry MUST use a recognized class:terminal,transient,ignore(error M08101) - A
clientreferenced in anexecute {}binding MUST be declared in scope (error M08102) - The operation named in an
execute {}binding MUST be declared on the referencedclientor present in its spec (error M08103) - The
using {}bindings in anexecute {}call MUST match the operation’s declared or spec-derived input fields (error M08104) - A spec-backed
clientwith an unreachable or unparseablespecsource MUST produce a compile-time error (error M08105) - A spec-backed
clientMUST NOT also declareoperations {}(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 declaredflowtracking saga progress. Everytransitions ->statement MUST reference states in this flow. Required (error M08200).steps— named units of work executed in dependency order. A step calls aclientoperation (calls:) or triggers internal async work.requires— step dependencies. Steps with norequiresrun immediately. Steps withrequires: [A, B]run only after both A and B succeed.on success { }/on failure(terminal) { }— per-step handlers.on successMUST contain amutationcall to record the result in the persistence graph and atransitionsstatement 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 incompensatebut with no correspondingcompensatedeclaration 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:
forMUST name a declaredentityin scope (error M16010)toMUST name a valid semver string (error M16011)apply {}MUST NOT reference fields not declared on the entity at thefromversion (error M16012)- Return types MUST be compatible with the entity’s
to-version field types (error M16013)
Diagnostic codes:
M16010—forreferences undeclared entityM16011—tois not a valid semantic version stringM16012—apply {}references field absent from the entity at thefromversionM16013— expression return type incompatible with target field typeM16020—transformbody has side effects (external call, event emission, or persistence read)M16021— expression intransformis 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:
- A named
input {}and inlineinput := {}MUST NOT both appear on the same declaration (error M06080). - A named
returns: TypeNameand inlinereturns := {}MUST NOT both appear (error M06081). - 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 namedinput {}and inlineinput := {}declared on the same operationM06081— both namedreturns: TypeNameand inlinereturns := {}declared on the same operationM06083— explicitreturns: Unitis forbidden; omitreturnsto 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 name | Role |
|---|---|
module.gnm | Module manifest — FQN, version, type, imports (RFC-0001). REQUIRED. |
project.gnm | Project 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 name | Declaration class | Kinds permitted |
|---|---|---|
schema.gnm | Schema | entity, type, variant, flow, invariant, facet, mutation, compute, claim, extend |
actions.gnm | Operations | action |
queries.gnm | Operations | query |
mutations.gnm | Operations | mutation |
events.gnm | Operations | event |
procedures.gnm | Operations | procedure |
tasks.gnm | Operations | task |
integrations.gnm | Operations | integration |
clients.gnm | Operations | client |
saga.gnm | Operations | saga |
agents.gnm | Governance | agent |
policies.gnm | Governance | policy, compose |
views.gnm | Surface | app, view |
tests.gnm | Tests | test |
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:
| Form | Meaning |
|---|---|
rule ::= ... | Production definition |
"x" | Literal terminal |
UPPER | Terminal token class (§8.1) |
a b | Concatenation |
a | b | Ordered 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
workflowstep MUST have either amodel:binding (naming an AI agent model) or ahuman_gatedirective. A step with neither MUST produce error M07115 (workflowstep missingmodel:binding orhuman_gatedirective). - A
sagastep MUST NOT contain ahuman_gatedirective. Presence ofhuman_gateinside anysagastep MUST produce error M07116 (sagastep containshuman_gate— useworkflowfor 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-declMUST appear only in a file namedmodule.gnm. Its presence in any other file MUST produce error M08723.module.gnmMUST contain exactly onemodule-decland no other top-level declarations. A file containing more than onemodule-declproduces error M01060 (defined in RFC-0001 §9); a file containing non-moduletop-level declarations alongsidemodule-declproduces error M08724.- The FQN in
module-declMUST use onlyNAMEsegments (lowercase, RFC 1123 label syntax). It MUST NOT useIDENT(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:
- Purely syntactic: the desugar pass operates on the raw parse tree. It MUST NOT perform symbol resolution, type checking, or semantic validation.
- Bijective expansion: every sugar form maps to exactly one canonical block form. Expansion is deterministic and lossless.
- Idempotent: applying the desugar pass twice produces the same result as applying it once.
- Auditable: the compiler SHOULD expose a
--print-desugaredflag 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 form | Canonical expansion | Production |
|---|---|---|
query name(params) -> Type | query name { input { params } returns: Type } | §8.15 |
Bare field-decl in entity body | fields { 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):
| Candidate | Sugar | Canonical expansion |
|---|---|---|
| Inline flow states | flow: [Draft, Active] inside entity body | Separate named flow declaration |
| Inline relation | Employee -> Plan via elects at top level | Full 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
facetdeclaration (FacetType, RFC-0006 §4.2) is an additive composition unit. It is pulled into an entity by the entity viaincludes [Auditable]. The entity controls inclusion. - An
aspectdeclaration (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
.gnmextension) MUST conform toNAME: 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.gnmare forbidden (M08744). - File names MUST NOT use numeric suffixes (
model2.gnm) (M08744). - The project manifest MUST be named
project.gnmexactly (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
NAMEnoun: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 kind | Required casing | Example | Diagnostic |
|---|---|---|---|
| EntityType name | PascalCase | Employee, PlanRecommendation | M08740 |
| FacetType name | PascalCase | Auditable, AIDraftable | M08740 |
| RelationType name | camelCase verb or verb phrase | elects, belongsTo, hasMember | M08740 |
| FlowType name | PascalCase | PlanRecommendationLifecycle | M08740 |
| ActionType name | camelCase verb phrase | submitEnrollment, draftRecommendation | M08740 |
| EvidenceType (claim) name | camelCase | diagnosisCode, recommendedPlan | M08740 |
| PolicyType name | PascalCase | AIGuardrails, PrivacyPolicy | M08740 |
| AgentType name | PascalCase + MUST end in Agent | RecommendationAgent | M08742 |
| Model name | PascalCase | Gemma3Local, GPT4o | M08740 |
| ViewType name | PascalCase | PlanRecommendationSummary | M08740 |
| State name (in flow) | PascalCase | Draft, Reviewed, Approved | M08740 |
| Field name | camelCase | employeeId, fullName, hireDate | M08740 |
| Module namespace | FQN: dot-separated NAME segments, max 253 chars | benefits.enrollment | M08743 |
10.4 Naming Conventions (Recommended)
The following conventions are RECOMMENDED (warning on violation, not error):
- FlowType names SHOULD end in
Lifecycle:EnrollmentLifecycle,RecommendationLifecycle(M08741). - PolicyType names SHOULD end in
PolicyorGuardrailsorRules: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
electsoverenrollment.
10.5 Meaning Field Content
- All
meaningfields MUST be plain-language prose readable by a non-technical domain author. meaningfields MUST NOT contain code, type names, or implementation references.meaningfields SHOULD end with a period.meaningfields 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:
- A
publicdeclaration MUST NOT reference aninternaldeclaration from a different module. Violations produce error M08750. - An
internaldeclaration MAY reference any other declaration in the same module. projectdeclarations inproject.gnmMUST NOT have a visibility modifier. Violations produce error M08751.testdeclarations are implicitlyinternaland MUST NOT carry a visibility modifier. Violations produce error M08751.- The compiler MUST NOT export
internaldeclarations in the compiled bundle (RFC-0002). Presence of aninternaldeclaration 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).
| Modifier | Meaning | Compiler behavior |
|---|---|---|
draft | Incomplete or AI-proposed; not yet reviewed by a human author | Warning M08780 if referenced by a non-draft declaration |
deprecated | Stable but scheduled for removal; consumers should migrate | Warning M08781 at every use site |
experimental | Stable but subject to breaking change without notice | Warning M08782 at every use site from outside the declaring module |
sealed | Publicly visible but MUST NOT be extended, composed, or includesd outside the declaring module | Error M08783 on external extension |
abstract | Incomplete by design; MUST be composed into a concrete declaration before use | Error 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:
- A declaration MAY carry at most one epistemic modifier (M08785 on multiple).
draftdeclarations MUST NOT appear in a compiled bundle withciState: ready. Violations produce error M08786. This enforces that AI-generated or incomplete declarations are reviewed before release.deprecatedandexperimentalare advisory; they do not prevent compilation or export.sealedis enforced only across module boundaries. Within a module,sealeddeclarations MAY be composed freely.abstractdeclarations may only be used incomposeorincludespositions. Direct field-type references oractionactor references produce M08784.- The
draftepistemic modifier is the normative AI authoring marker (resolving RFC-0008 Q3). AI agents producing declarations MUST attachdraftto 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
policyorflowdeclaration respectively. rulestatements inpermissions/prohibitions/requirementsblocks ofagentdeclarations 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 { }overrule "..."for performance and reproducibility. - The LSP SHOULD offer a “compile to expr” refactoring that converts an accepted
rule "..."to its compiledexpr { }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.modelor per-statementwith ModelName) at runtime. - The model MUST have
runtime-agentin itsroles. - Runtime prompts are NOT constraint-evaluable. They MUST NOT appear in
invariant,facet.rules, orpolicy.rulesblocks — only inagentpermission/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
noteto 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 fmtenforces canonical property ordering - Plain-language
meaning,purpose, andexplainfields 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
.gnmDSL syntax
12.1 Comment and Documentation Model
Three comment forms are defined:
| Form | Parser treatment | Purpose |
|---|---|---|
// text | Discarded | Inline implementation notes |
/* text */ | Discarded | Block notes, commented-out code |
/// text | Preserved as doc metadata | Narrative 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
- Authorization logic MUST reside in files whose top-level keyword is
policy; it MUST NOT appear inentityorviewdeclarations. - Agent capability declarations MUST be reviewed and explicitly approved before deployment (RFC-0009).
- UI projections MUST NOT expose fields that the active policy prohibits for the rendering actor.
15. Compatibility and Migration
- Changing the syntax of an existing declaration kind is a breaking change and MUST increment the language version.
- 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.
- 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).