gnomonlearn
Docs/Lifecycle/RFC-0010

RFC-0010 · Canonical IR and Runtime Architecture

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: Compiler, Runtime, AI Platform

1. Scope

Defines two related but separable concerns:

  1. Canonical Semantic IR — the normalized intermediate representation produced by extracting semantic facts from existing codebases (TypeScript, OpenAPI, etc.), used for model training and codebase-to-Gnomon migration.

  2. Runtime Architecture — the event-sourced, multi-worker architecture for executing Gnomon applications, including the kernel, surface, model worker, and capability broker boundaries.

These are treated in a single RFC because they share a common conceptual core: all meaningful change is a typed event reduced by a kernel, and code or AI models are advisory participants that propose events rather than committing state directly.

2. Goals

  1. Define a stable canonical IR format for semantic facts extracted from existing codebases
  2. Specify a training data generation pipeline from public API artifacts
  3. Define the runtime architecture that enforces the principle “all meaningful change is a typed event applied by the kernel”
  4. Establish clean boundaries between surface, runtime, kernel, and model workers
  5. Ensure the architecture is compatible with WASM execution in the browser and server-side deployment

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

Canonical IR:

  1. The canonical IR MUST store normalized semantic facts, not raw AST nodes.
  2. Every extracted symbol MUST reference its source span for traceability.
  3. Canonical IR MUST be deterministic: the same source produces the same IR across runs.

Runtime Architecture: 4. Components MUST NOT mutate state directly; all mutations are commands routed to the kernel. 5. Models MUST NOT commit domain facts; they MAY only emit proposals. 6. The kernel MUST be the sole source of committed events. 7. Effects (external I/O) MUST NOT commit state directly; they MUST be initiated from committed events. 8. Every command MUST pass kernel validation before producing a committed event.

4. Canonical Semantic IR

4.1 Purpose

The canonical IR is a compact, normalized representation of the semantic content of an existing codebase or API specification. It enables:

  • Migration of existing applications to Gnomon’s semantic model
  • Unsupervised training data generation for LLMs that reason about Gnomon concepts
  • Static analysis and model comprehension tooling

The IR is not the Gnomon authoring format. It is a compiler-internal and tooling-facing artifact.

4.2 Pipeline Stages

For a TypeScript repository:

Stage 1: Parse with TypeScript compiler API
Stage 2: Resolve symbols and types with TypeChecker
Stage 3: Build import/export/module graph
Stage 4: Build declaration graph (classes, functions, interfaces, types)
Stage 5: Build call graph
Stage 6: Infer effects: DB, HTTP, filesystem, auth, queues
Stage 7: Detect framework conventions (Next.js routes, React components,
         tRPC routers, Prisma schema, Zod validators)
Stage 8: Collapse implementation patterns into higher-level semantic declarations
Stage 9: Attach tests, docs, and traces as evidence
Stage 10: Emit canonical IR (rkyv binary for Rust/WASM consumers; serde JSON for TypeScript tooling)

4.3 Extracted Semantic Graph

At each source file, the extractor produces:

File
  imports
  exports
  declarations
  symbols
  types
  call sites
  property accesses
  decorators
  JSX components
  side effects

These are resolved via TypeChecker into a typed graph:

Module ─exports→ Symbol
Symbol ─declaredBy→ ASTNode
Function ─calls→ Function
Class ─implements→ Interface
Route ─uses→ Handler
Handler ─reads/writes→ DBEntity
Component ─renders→ Component
Schema ─validates→ Type

4.4 Normalized Symbol Record

Raw TypeScript is not stored. Each symbol is normalized to a semantic fact record:

symbol: getUser
kind: function
module: users/service
signature:
  params:
    - name: id
      type: UserId
  returns: Promise<User>
effects:
  - kind: db.read
    entity: User
    operation: findUnique
calls:
  - db.user.findUnique
source_span:
  file: src/users/service.ts
  line: 42

4.5 Pattern Compression

Repeated patterns are collapsed into higher-level declarations:

# Expanded (per-symbol)
symbol: getUser
kind: function
effects:
  - kind: db.read
    entity: User

# Compressed (pattern-recognized)
service: UserService
entity: User
operations:
  - getById
  - create
  - update
backing_store: prisma.user

The compression pass recognizes: CRUD services, authentication patterns, event emitters, workflow handlers, and schema/validation patterns.

4.6 Canonical IR Schema (Normative)

Serialization strategy

The canonical IR uses two serialization formats derived from the same Rust struct definitions:

FormatLibraryConsumersUse
Zero-copy binaryrkyvRust compiler, WASM kernelCompiled bundle persistence; mmap at startup with no decode step
JSONserde_jsonLSP, Gnomon Studio, TypeScript tooling, human debuggingDerived automatically from the same struct definitions via serde

The Rust struct definitions are normative. Both formats are derived from them via #[derive] macros. No separate schema document (TypeScript interfaces, proto file) is maintained as a source of truth. The structs live in the gnomon-ir crate.

// All IR structs carry both derive sets.
// rkyv provides zero-copy binary; serde provides JSON.
#[derive(
    rkyv::Archive, rkyv::Serialize, rkyv::Deserialize,
    serde::Serialize, serde::Deserialize,
    Debug, Clone, PartialEq,
)]
// Field names use snake_case in Rust; serde renames to camelCase for JSON consumers.
#[serde(rename_all = "camelCase")]

Zero-copy binary (rkyv): The compiler serializes the IR to a byte buffer using rkyv. The WASM kernel receives this buffer via gnomon_kernel_init and accesses fields directly from the buffer without a deserialization step — no allocation, no copy. The buffer is memory-mapped from the compiled bundle file on disk. This is the hot path.

JSON (serde): The compiler optionally emits a JSON representation of the same data for consumption by TypeScript tooling (LSP, Gnomon Studio, migration tooling). TypeScript tooling MUST consume the serde JSON form; it MUST NOT attempt to parse rkyv binary directly. The JSON representation is generated by the same compilation pass that produces the binary form — no separate extraction step.

Versioning: The schemaVersion field MUST be incremented on any breaking change to the struct set. Breaking changes include removing or renaming fields and changing field types. Adding optional fields is non-breaking. Older rkyv archives with lower schemaVersion MUST remain loadable by newer tooling via a registered compatibility shim. Diagnostic M10060 fires when a shim is applied.

Struct definitions

use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
use serde::{Deserialize, Serialize};

/// Top-level IR document produced per extracted module.
#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CanonicalIr {
    pub schema_version: u32,        // increment on breaking change
    pub source_module: String,      // module namespace
    pub extracted_at: String,       // ISO-8601 timestamp
    pub symbols: Vec<SymbolRecord>,
    pub relations: Vec<RelationRecord>,
    pub effects: Vec<EffectRecord>,
    pub domain_concepts: Vec<DomainConceptRecord>,
    pub statement_blocks: Vec<StatementBlockRecord>,
}

/// A single extracted symbol (function, class, field, type, etc.).
#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SymbolRecord {
    pub id: String,                         // stable hash of (module + name + kind)
    pub name: String,
    pub kind: SymbolKind,
    pub module: String,
    pub signature: Option<SignatureRecord>,
    pub source_span: SourceSpan,
    pub suggested_kind: Option<GnomonDeclKind>, // RFC-0006 §4.B mapping suggestion
    pub migration_confidence: MigrationConfidence,
    pub calls: Vec<String>,                 // symbol ids
    pub called_by: Vec<String>,             // symbol ids
    pub decorators: Vec<String>,
}

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum SymbolKind {
    Function, Class, Interface, TypeAlias,
    Enum, Const, Route, Component, Schema,
}

/// Declaration kinds from RFC-0006 §4.B.
/// Named by keyword, not by XxxType suffix.
#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum GnomonDeclKind {
    Entity, Facet, Relation, Action, Mutation,
    Actuator, Event, Procedure, Query, Task,
    Integration, Client, Saga, Workflow,
    Flow, Invariant, Policy, Agent, Claim,
    Compute, Extend, Variant, Type,
}

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum MigrationConfidence { High, Medium, Low }

/// A typed relationship between two symbols.
#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RelationRecord {
    pub id: String,
    pub from_symbol: String,
    pub to_symbol: String,
    pub kind: RelationKind,
    pub cardinality: Option<Cardinality>,
    pub source_span: SourceSpan,
}

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum RelationKind {
    Calls, Implements, Extends, Uses, Reads, Writes,
    Renders, Validates, Imports, Exports,
}

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum Cardinality { One, Many, ZeroOrOne }

/// An inferred side effect of a symbol.
#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct EffectRecord {
    pub symbol: String,
    pub kind: EffectKind,
    pub target: Option<String>,
    pub operation: Option<String>,
    pub source_span: SourceSpan,
}

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum EffectKind {
    DbRead, DbWrite, DbDelete,
    HttpRequest, HttpResponse,
    QueueEnqueue, QueueDequeue,
    FilesystemRead, FilesystemWrite,
    AuthCheck, AuthGrant,
}

/// A pattern-compressed higher-level domain concept.
#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DomainConceptRecord {
    pub id: String,
    pub kind: DomainConceptKind,
    pub name: String,
    pub symbols: Vec<String>,
    pub suggested_gnomon_kind: GnomonDeclKind,
    pub migration_confidence: MigrationConfidence,
}

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum DomainConceptKind {
    Service, Entity, Saga, AuthGuard, EventEmitter,
}

/// IR node for an gnomon statement block (rule, expr, prompt, note).
#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct StatementBlockRecord {
    pub id: String,
    pub kind: StatementKind,
    pub owner_declaration: String,
    pub source_span: SourceSpan,
    pub body: StatementBody,
}

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StatementKind { Rule, Expr, Prompt, Note }

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StatementBody {
    Rule  { condition: Option<String>, effect: Option<String>, references: Vec<String> },
    Expr  { expression: String, result_type: Option<String>, references: Vec<String> },
    Prompt { template: String, variables: Vec<PromptVariable>, model_ref: Option<String> },
    Note  { text: String },
}

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PromptVariable {
    pub name: String,
    pub r#type: String,
    pub required: bool,
}

/// Source location.
#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SourceSpan {
    pub file: String,
    pub start_line: u32,
    pub start_col: u32,
    pub end_line: u32,
    pub end_col: u32,
}

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SignatureRecord {
    pub params: Vec<ParamRecord>,
    pub returns: Option<String>,
    pub throws: Vec<String>,
}

#[derive(Archive, RkyvSerialize, RkyvDeserialize, Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ParamRecord {
    pub name: String,
    pub r#type: String,
    pub optional: bool,
}

4.7 Training Data Generation

The canonical IR enables self-supervised training pair generation. Given multiple imperfect views of the same system (natural language docs, OpenAPI spec, SDK code, observed behavior), the training pipeline:

  1. Aligns redundant views of the same concept across artifacts
  2. Infers the latent semantic model (the canonical IR)
  3. Generates training pairs from view↔model alignment

Example training pairs from a single API endpoint:

NL → Semantics:

INPUT: "Create a repository for the authenticated user"
OUTPUT: command CreateRepository { ... }

API Spec → Semantics:

INPUT: POST /user/repos { name, private }
OUTPUT: entity Repository { ... }
        invariant UniqueRepoNamePerOwner { ... }
        command CreateRepository { ... }

Semantics → API (round-trip):

INPUT: command CreateRepository { ... }
OUTPUT: POST /user/repos

Missing constraint detection:

INPUT: entity Repository { name, owner }
OUTPUT: invariant UniqueRepoNamePerOwner

Scaling across diverse public APIs (payments, healthcare, infrastructure, identity) teaches the model domain-general patterns:

  • POST + resource creation → command
  • authenticated user → actor constraint
  • name uniqueness → invariant
  • ownership field → relationship
  • boolean flags → enum/domain modeling opportunity

4.8 Scoring and Round-Trip Consistency

Candidate IR extractions SHOULD be scored by round-trip consistency: can the original view (API spec, docs, code) be approximately reconstructed from the IR? Higher round-trip fidelity indicates a more semantically complete extraction. This allows unsupervised quality filtering without manual labeling.

4.9 IR-to-Gnomon Type Kind Mappings (Normative)

The canonical IR produced by extraction is not the Gnomon authoring format. To migrate an existing codebase or API to Gnomon, IR concepts MUST be mapped to RFC-0006 type kinds. This section defines the normative mapping.

The extraction pipeline SHOULD emit a suggested_kind annotation on each extracted symbol. The migration tooling MUST validate these suggestions against the mappings below and produce a diagnostic when a symbol is ambiguously or incorrectly classified.

IR extracted conceptRFC-0006 kindNotes
Persistent domain object (class, model, entity)EntityTypeEach extracted entity field becomes a typed field declaration
Mutable resource field that may be AI-producedClaim (EvidenceType wrapper)Upgrade from bare field when AI authorship is detected in extraction
Named relationship between two entitiesRelationTypeMany-to-one or many-to-many associations, with cardinality preserved
State machine or status enumFlowTypeExtracted state transitions become flow declarations
Service method / controller handler / mutationActionTypeActor is inferred from auth guard or route middleware
Validation rule / invariant / unique constraintInvariant (PolicyType or inline on EntityType)DB-level constraints map to invariant declarations
Authorization rule / permission checkPolicyTypeRole checks, ownership guards, and scope constraints
API endpoint (REST, GraphQL, tRPC)ActionTypeMethod + path + auth → command with actor constraint
Background job / queue handlerActionType with actor: SystemAsync effects declared in effects block
Read-only query / search endpointQuery (subset of ActionType with no side effects)No state change; maps to derivation or view projection
Embedded document / JSONB blobEntityType with document projection OR bare payload: jsonbChoose EntityType when the document has a stable schema; bare jsonb when schema is unknown
Vector/embedding columnGnomon projection (embedding: projection vector(field))Declare as a projection on the parent EntityType
Derived/computed column or materialized viewDerivation (RFC-0007 §8)Source and method declared in derivation block
AI model output (classification, extraction)Claim (EvidenceType) + ActionType that produces itAgent declaration needed for the producing model
Enum / discriminated unionEnumerated type within an EntityType fieldPreserve discriminant values as labeled state entries
Audit log tableAspect target (Auditable semantic facet)Do not migrate as a standalone entity; fold into Auditable facet
User/session identityPrincipal reference (RFC-0000 §9)Map to actor constraints on ActionType declarations, not an independent EntityType unless the app models users as domain objects

Migration confidence levels:

Each IR symbol SHOULD be annotated with a migration confidence level:

  • high: the mapping is unambiguous (e.g., a Prisma model → EntityType, a unique constraint → invariant)
  • medium: the mapping is probable but requires human review (e.g., a service method that may be a query or a mutation)
  • low: the mapping is speculative and MUST be confirmed by a human author before inclusion in an authoring module

The migration tooling MUST NOT emit low-confidence mappings as normative authoring declarations without an explicit author confirmation step. Low-confidence symbols MUST be emitted as commented-out draft declarations with a M10050 diagnostic.

5. Storage-to-Kernel Integration Contract

This section closes the gap between the RFC-0007 storage model and the RFC-0010 runtime kernel. It defines the compile pipeline that transforms a storage manifest into kernel artifacts, and the runtime write path that connects kernel event commitment to storage persistence.

5.1 Compile Pipeline: Storage Manifest → Kernel Artifacts

The compiler produces two independent outputs from the same module source:

  1. Storage manifest (RFC-0002 §7) — the DDL specification consumed by the install pipeline
  2. Kernel artifact (gnomon.kernel.rs / compiled WASM) — the runtime component that owns state reduction and validation

These are produced in a single compile pass from the same semantic model but serve different consumers. The kernel artifact is NOT derived from the storage manifest; both are derived in parallel from the module’s compiled object graph.

Module source
    │
    ▼
Compiler (semantic model resolution)
    │
    ├──► Storage manifest (RFC-0002 §7)
    │    └── DDL for base tables, projection tables, views, indexes
    │    └── Claim field storage strategies (RFC-0007 §6.0)
    │
    └──► Kernel artifact (gnomon.kernel.rs / WASM)
         └── Reducer functions per ActionType (RFC-0006 §4.4)
         └── Invariant check functions per declared invariant
         └── Claim enforcement functions per Claim declaration
         └── State machine transition tables per FlowType (RFC-0006 §4.6)
         └── Aspect weave points per RFC-0004 declarations
         └── Authorization tables per PolicyType (RFC-0006 §4.7)

The kernel artifact MUST be versioned with the same fingerprint as the compiled bundle. A bundle fingerprint mismatch between installed kernel and installed schema MUST be detected and rejected at runtime startup (M10040).

5.2 Kernel Generation Rules

For each compiled module object graph, the kernel generator MUST produce:

Per mutation declaration (RFC-0008 §6.21):

  • A reducer function with signature fn reduce(state, command) -> Result<Vec<Event>, KernelError>
  • Effect assertions derived from the mutation’s effects {} block
  • Invariant enforcement calls for each entity referenced in the effects block

Note: preconditions and actor constraints live in procedure declarations (RFC-0008 §6.25), not in mutations. The kernel enforces mutation-level effects; the runtime layer enforces procedure-level authorization before routing to the kernel.

Per FlowType:

  • A transition guard table: (from_state, actor_role) -> Option<to_state>
  • Transition guards MUST enforce actor constraints declared in .gnm flow declarations (RFC-0008 §6.5)

Per Claim declaration:

  • An evidence validator function that checks required_evidence presence, allowed_status membership, and min_confidence_to_use thresholds
  • Storage strategy routing: inline JSONB write, projection column write, or evidence side-table insert — determined by the strategy selected in the storage manifest (RFC-0007 §6.0)

Per PolicyType:

  • Authorization predicate functions referenced by the transition guard table and reducer preconditions

5.3 Runtime Write Path: Command → Event → Storage

The write path from a user command to durable storage must cross both the kernel layer and the storage layer. This is the normative sequence:

1. Surface emits Command
2. gnomon-runtime routes Command to kernel
3. Kernel:
   a. Resolves actor identity and trust level (RFC-0000 §9.1)
   b. Evaluates ActionType preconditions
   c. Evaluates PolicyType authorization predicates
   d. For each Claim field in the command payload:
      - Runs evidence validator (required_evidence, allowed_status)
      - Checks confidence thresholds
   e. Evaluates invariants (must_satisfy)
   f. If all checks pass: emits Event (committed fact)
   g. If any check fails: returns KernelError with diagnostic code
4. Event is appended to event log
5. gnomon-runtime:
   a. Routes event to persistence adapter
   b. Persistence adapter writes to gnomon base table (RFC-0007 §6.1)
   c. Persistence adapter writes to projection tables (RFC-0007 §6.3)
   d. Persistence adapter writes claim evidence per storage strategy (RFC-0007 §6.0)
   e. Persistence adapter updates edge table for any relations in the event (RFC-0007 §6.2)
6. gnomon-runtime routes event to surface as Patch

Key invariants of this path:

  • Steps 3a–3g are the kernel’s exclusive domain. The persistence adapter MUST NOT perform validation.
  • Steps 5a–5e are the persistence adapter’s exclusive domain. The kernel MUST NOT write to storage directly.
  • The event log (step 4) MUST be appended before any storage write. If storage writes fail, the event log entry allows replay.
  • Claim evidence writes (step 5d) MUST use the storage strategy declared in the installed storage manifest, not the strategy from any other version.

5.4 Storage-Kernel Version Coupling

The kernel artifact and the storage schema are tightly coupled: a kernel generated from one bundle version expects the storage schema from the same version. Version mismatches cause silent data corruption or runtime errors.

Rules:

  1. At startup the runtime MUST compare the installed kernel bundle fingerprint against the installed storage manifest fingerprint. A mismatch MUST halt startup with error M10040.
  2. The install pipeline (RFC-0005) MUST apply schema operations (Class 2) and kernel deployment atomically within the same install plan execution. Partial applies that leave schema and kernel at different versions MUST be detectable and recoverable.
  3. Kernel rollback (redeploying a prior kernel artifact) MUST be accompanied by a corresponding storage migration if the rollback crosses a breaking schema change boundary.

5.5 Event Log and Storage Relationship

The event log and the gnomon base/projection tables serve different purposes and MUST NOT be treated as interchangeable:

Event logGnomon tables
ContentOrdered sequence of committed eventsCurrent state of all gnomon instances
ConsumersKernel replay, audit, syncQuery API, AI context, derivations
MutabilityAppend-only (events are immutable)Written by persistence adapter from events
Source of truth forWhat happened and whenWhat the current state is

DDL migrations (schema operations) are NOT expressed as events. They are out-of-band operations applied by the install pipeline before the kernel starts.

6. Runtime Architecture

6.1 Core Principle

All meaningful change is a typed event applied by the kernel.

Everything else is projection. This principle gives the runtime a single source of truth for state transitions and makes the system auditable, testable, and reproducible.

6.2 Architecture Layers

┌─────────────────────────────────┐
│         gnomon-surface            │  main thread
│  custom elements, patch render, │
│  DOM adapters, accessibility    │
└──────────────┬──────────────────┘
               │ events / patches
┌──────────────▼──────────────────┐
│         gnomon-runtime            │  dedicated worker
│  event queue, capability broker,│
│  persistence adapter, sync,     │
│  model broker                   │
└──────────────┬──────────────────┘
               │ commands / events
┌──────────────▼──────────────────┐
│      gnomon-kernel (WASM)         │  compiled Rust
│  schema, reducers, aspects,     │
│  validators, invariants,        │
│  command → event compiler       │
└──────────────┬──────────────────┘
               │ proposals (advisory only)
┌──────────────▼──────────────────┐
│        gnomon-models              │  model worker
│  feature extraction,            │
│  tiny local experts,            │
│  proposal scoring               │
└─────────────────────────────────┘

6.3 Message Taxonomy

TypeMeaningMay commit state?
CommandRequest to change stateNo
EventCommitted fact produced by the kernelYes (kernel only)
PatchVisual update derived from an eventNo
EffectExternal I/O initiated from a committed eventNo
ProposalModel suggestion requiring kernel acceptanceNo

6.4 Example Flow

User clicks submit
  → Command.SubmitEnrollment
  → gnomon-runtime routes to gnomon-kernel
  → Kernel validates against declared invariants and policies
  → Event.EnrollmentSubmitted (committed)
  → Event log append
  → Patch UI
  → Effect: notify server, trigger sync

An AI model observing the state may emit:

Proposal.SuggestPlanUpdate (confidence: 0.82)
  → gnomon-runtime routes to surface for human review
  → Human confirms → Command.UpdatePlan
  → Kernel validates and commits

6.5 Hard Rules

  • Components MUST NOT mutate state.
  • Models MUST NOT mutate state.
  • Workers MUST NOT invent domain truth.
  • Effects MUST NOT commit state directly.
  • Only the kernel emits committed events.

6.6 Kernel Responsibilities

The gnomon-kernel (compiled Rust/WASM) owns:

  • Schema validation (against declared entity types)
  • Invariant checking (declared invariants from RFC-0006)
  • Aspect enforcement (RFC-0004)
  • Command-to-event compilation
  • Reducer execution (state transitions per declared FlowType)
  • Authorization checks (RFC-0005 and RFC-0009)

The kernel is generated from the compiled Gnomon bundle (RFC-0002). It is not hand-authored.

6.7 Artifact Set

ArtifactContent
gnomon.schemaEntity types, value types, event types
gnomon.facetsVisual, chat, and agent projections
gnomon.aspectsValidation, audit, auth, lifecycle aspects
gnomon.effectsBrowser/server capability declarations
gnomon.modelsAdvisory model seams and derivation rules
gnomon.kernel.rsGenerated Rust reducers (+ optional hand-authored extensions)

6.8 UI Surface Technology

The surface layer uses standards-based Web Components backed by the Rust/WASM kernel. This avoids framework dependency while preserving the typed event boundary.

Web Components (Lit or plain custom elements)  ← UI primitives
Rust/WASM kernel                              ← app state, reducers, validation
Typed events                                  ← boundary contract
Patches/signals                               ← rendering updates

The surface component dispatches typed events; the runtime routes them to the kernel; the kernel returns patches. Components never own state.

6.9 Kernel WASM Callable Interface (Normative)

The gnomon-kernel is compiled to WASM and called by gnomon-runtime through a stable ABI. The following extern "C" function signatures are normative. Any kernel WASM module that does not export all REQUIRED functions MUST be rejected at startup with M10045.

/// Initialize the kernel with the compiled bundle bytes.
/// Must be called once before any other kernel function.
/// Returns 0 on success; non-zero error code on failure.
///
/// `bundle_ptr` points to a rkyv-encoded `CompiledBundle` (§4.6).
/// The kernel retains a reference to this buffer for the lifetime of
/// the kernel instance; the caller MUST NOT free or move the buffer
/// after a successful init. The buffer SHOULD be memory-mapped from
/// the compiled bundle file (RFC-0002) — the kernel reads fields
/// directly from the mmap with no deserialization step.
#[no_mangle]
pub extern "C" fn gnomon_kernel_init(
    bundle_ptr: *const u8,
    bundle_len: usize,
) -> i32;

/// Submit a command for kernel validation and reduction.
/// `command_ptr` points to a JSON-encoded Command message (RFC-0010 §6.3).
/// On success: writes a JSON-encoded Vec<Event> to `out_ptr`; returns byte length written.
/// On failure: writes a JSON-encoded KernelError to `out_ptr`; returns negative error code.
#[no_mangle]
pub extern "C" fn gnomon_kernel_submit(
    command_ptr: *const u8,
    command_len: usize,
    out_ptr: *mut u8,
    out_capacity: usize,
) -> i32;

/// Validate a command without committing any events (dry-run).
/// Same encoding as gnomon_kernel_submit.
/// Returns 0 if valid; negative error code if not.
#[no_mangle]
pub extern "C" fn gnomon_kernel_validate(
    command_ptr: *const u8,
    command_len: usize,
    out_ptr: *mut u8,
    out_capacity: usize,
) -> i32;

/// Query the current state of an gnomon entity instance by id.
/// `query_ptr` points to a JSON-encoded GnomonQuery.
/// On success: writes JSON-encoded GnomonQueryResult to `out_ptr`.
#[no_mangle]
pub extern "C" fn gnomon_kernel_query(
    query_ptr: *const u8,
    query_len: usize,
    out_ptr: *mut u8,
    out_capacity: usize,
) -> i32;

/// Return the bundle fingerprint this kernel was compiled from.
/// Writes a null-terminated ASCII string (sha256:<hex>) to `out_ptr`.
#[no_mangle]
pub extern "C" fn gnomon_kernel_fingerprint(
    out_ptr: *mut u8,
    out_capacity: usize,
) -> i32;

/// Release memory allocated by the kernel for an `out_ptr` buffer.
/// Must be called after every successful gnomon_kernel_* output read.
#[no_mangle]
pub extern "C" fn gnomon_kernel_free(
    ptr: *mut u8,
    len: usize,
);

/// Return the schema version of this kernel ABI.
/// Returns a u32 version integer (current: 1).
#[no_mangle]
pub extern "C" fn gnomon_kernel_abi_version() -> u32;

Encoding contract:

BufferEncodingNotes
bundle_ptr (init)rkyv binaryZero-copy; kernel retains pointer for lifetime
command_ptrserde JSON (UTF-8)Runtime messages remain JSON in ABI v1
out_ptr (events, errors, queries)serde JSON (UTF-8)Runtime messages remain JSON in ABI v1

The init bundle uses rkyv binary because it is large, read-only, and read many times across a kernel lifetime — mmap + zero-copy reads dominate. Runtime command and event messages are smaller and more dynamic; JSON is sufficient for ABI v1. A future ABI version MAY negotiate a binary encoding for the runtime message path if profiling shows it to be a bottleneck.

Memory ownership: The kernel owns all output buffers. The caller MUST call gnomon_kernel_free with the original pointer and the byte length returned by the producing function. The caller MUST NOT access the buffer after calling gnomon_kernel_free.

REQUIRED exports: gnomon_kernel_init, gnomon_kernel_submit, gnomon_kernel_validate, gnomon_kernel_fingerprint, gnomon_kernel_free, gnomon_kernel_abi_version.

OPTIONAL exports: gnomon_kernel_query (required for modules with declared query blocks; MUST be absent for modules that declare no queries).

ABI stability: The function signatures MUST NOT change within a schema_version. New optional exports may be added. Removing or changing a REQUIRED export is a breaking change and MUST increment schema_version in §4.6.

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.

8. Security and Authorization

8.1 Kernel enforcement rules

  1. The kernel MUST enforce all authorization policies declared in RFC-0005 and RFC-0009 before emitting committed events.
  2. The kernel MUST be compiled from the install-plan bundle; runtime-modified kernels MUST NOT be trusted.
  3. Effects MUST be declared in gnomon.effects; ad hoc network or filesystem access from workers MUST be blocked.
  4. Model proposals MUST be routed through the surface for human confirmation before becoming commands, for any action classified as high-authority by the installed policy.

8.2 Object-Capability Security Model

The gnomon runtime takes its security model from object-capability theory (ocap). The core principle is: a component may only perform an action if it holds an unforgeable capability reference to the resource it wants to act on. There is no ambient authority — you cannot name a resource you were not explicitly given a reference to.

This is a stronger model than the current RFC-0009 permissions block, which grants agents authority over named action strings (ambient authority — any caller that knows the name can attempt the call; the kernel checks post-facto). The ocap model moves the check earlier: the capability is a prerequisite for forming the call at all.

Capability tokens in Rust

In the kernel’s Rust implementation, capabilities are zero-sized types (ZSTs) with private constructors. Only the kernel can mint a capability; no external code can construct one by naming it:

// Only constructible inside the kernel module — the private `new()` is not pub.
pub struct Cap<const ACTION: u64>(());

impl<const ACTION: u64> Cap<ACTION> {
    pub(crate) fn new() -> Self { Self(()) }
}

// A kernel function that requires a capability to mutate a Proposal:
pub fn transition_proposal(
    id: ProposalId,
    to: ProposalState,
    cap: Cap<ACTION_TRANSITION_PROPOSAL>,  // caller must hold this
) -> Result<Event, KernelError> {
    // ...
}

The const parameter ACTION is a stable hash of the action name, derived at compile time. The kernel mints capabilities after evaluating the procedure’s preconditions and policy declarations. A component that did not receive a capability from the kernel cannot invoke the protected function — the type system enforces this statically, with no runtime string comparison.

Mapping to gnomon declarations

gnomon declarationocap concept
procedure preconditionsCapability minting gate — evaluates context, mints Cap<A> if conditions pass
policyAdditional predicate evaluated during minting
mutationProtected function — requires Cap<A> in signature
agent permissions blockDeclares which Cap<A> types the agent’s runtime context may receive
agent prohibitions blockStatically eliminates capabilities from the agent’s reachable set

Capability attenuation

A capability may be attenuated — narrowed to a subset of its original authority before being passed to a sub-component. For example, a Cap<ACTION_MANAGE_HOUSEHOLD> may be attenuated to Cap<ACTION_VIEW_HOUSEHOLD> for a read-only agent. Attenuation is one-directional: you can only reduce authority, never amplify it.

impl Cap<ACTION_MANAGE_HOUSEHOLD> {
    // Produce a view-only capability from a manage capability.
    pub fn attenuate_to_view(self) -> Cap<ACTION_VIEW_HOUSEHOLD> {
        Cap::new()
    }
}

The kernel generates attenuation functions for all capability pairs where one action’s authority is a declared subset of another, based on the policy and permissions declarations in the module.

Relationship to RFC-0009

RFC-0009’s permissions and prohibitions blocks remain the authoring surface. The ocap model is the implementation of those declarations in the kernel:

  • permissions [action:foo] → the kernel’s minting logic grants Cap<ACTION_FOO> after evaluating preconditions
  • prohibitions [action:foo] → the kernel’s type-level configuration removes Cap<ACTION_FOO> from the reachable set for that agent context

This means RFC-0009 requires no syntactic change. The ocap model is an implementation detail of the Rust kernel that makes the authorization guarantees formally stronger — moving from “runtime string check” to “compile-time type exclusion.”

9. Knowledge Index

The Knowledge Index is a set of lazily-computed, cached query structures built over the assembled semantic graph. Each index answers one class of cross-declaration question that would otherwise require repeated full-graph traversal. Indexes are a compiler-internal abstraction; they are not part of the compiled bundle (RFC-0002) and are never exposed to the runtime.

9.1 Design Principles

  • Lazy construction: An index is computed only when first requested. Unused indexes impose no build cost.
  • Content-addressed caching: Each index is keyed by a hash of its input declarations. If the relevant declarations have not changed since the last build, the index is restored from the on-disk cache without recomputation. The cache lives in the Bazel action cache (RFC-0032) or the gnomon compiler’s local .gnomon-cache/ directory.
  • Declared dependencies: Each index declares which declaration kinds it reads. The compiler uses these declarations to invalidate only the indexes affected by a changed file, not all indexes. This enables incremental builds that pay O(changed declarations) rather than O(all declarations).
  • Parallel construction: Indexes with no inter-index dependencies are constructed concurrently. The compiler builds the dependency graph of indexes at startup and schedules them in topological order with a work-stealing thread pool.
  • Bidirectional maps: Relation-type indexes store both directions (e.g., entity→actions and action→entity) in the same structure to avoid separate reverse-traversal passes.

9.2 Data Structure Choices

  • Direct lookup (HashMap<ShapeId, T>): O(1) access for direct FQN → shape lookups. The primary shape map uses this.
  • Prefix lookup (trie over FQN): For namespace-scoped queries (“all shapes in org.benefits.*”), a prefix trie over FQN strings gives O(k) lookup where k is the query prefix length.
  • Bidirectional multimap (HashMap<A, Vec<B>> + HashMap<B, Vec<A>>): For relation indexes; built once, queried in either direction in O(1) + O(results).
  • Sorted set (BTreeSet): For ordered traversals (e.g., migration DAG topological sort, version-ordered operation lists).

9.3 Named Indexes

The following indexes are normative. Compiler passes and codegen steps MUST obtain derived facts from these indexes rather than traversing the shape graph ad hoc.

IndexReadsAnswers
EntityToActionsIndexentity, action, mutationFor a given entity: which actions target it? Which mutations modify it?
EntityToFacetsIndexentity, facet, extendFor a given entity: which facets are included (direct and via extend)?
AgentCapabilityIndexagent, procedure, policyFor a given agent: which procedures is it permitted to call? Which are prohibited?
ProtocolBindingIndexclient, serve, operation, serve-operationFor a given operation: what is its fully-resolved wire binding (method, path, auth, parameter locations)?
MigrationDAGIndexmigration, transformThe topological migration graph for a module; detects cycles; orders apply steps
EventSubscriberIndexevent, actuator, taskFor a given event: which actuators and tasks subscribe?
AnnotationIndexall declarations, annotation facet, annotation aspectFor a given declaration: what is its resolved annotation map (after precedence merge)?
OperationContractIndexoperation, query, procedure, mutationFor a given callable: its resolved input, output, and error taxonomy (after inline struct synthesis and returns defaulting)
ApiExposureIndexapi, serveFor a given api: which operations are exposed? Which serve bindings cover it? Are all operations covered?
KnowledgeIndexRegistry—The set of all registered indexes and their dependency declarations; used by the compiler scheduler

9.4 Index Interface (Normative)

Each index implements the following interface (expressed in Rust; other host language implementations MUST preserve the semantics):

pub trait KnowledgeIndex: Send + Sync {
    /// Stable identifier for this index — used as the cache key prefix.
    fn id(&self) -> &'static str;

    /// The declaration kinds this index reads. The compiler invalidates this
    /// index whenever a declaration of a listed kind changes.
    fn reads(&self) -> &[ShapeKind];

    /// Compute the index from the assembled model. Called once per build
    /// on a cache miss. MUST be a pure function of the model.
    fn compute(model: &AssembledModel) -> Self where Self: Sized;
}

The AssembledModel is the fully-resolved semantic graph produced after the desugar, symbol-resolution, and merge passes. An index MUST NOT modify the model.

9.5 Cache Invalidation

The compiler maintains a per-index content hash computed over the FQNs and content hashes of all declarations listed in reads(). On rebuild:

  1. Compute the current content hash for each index’s input set.
  2. Compare against the stored hash in .gnomon-cache/.
  3. If unchanged: restore the serialized index from cache. O(1).
  4. If changed: recompute the index. Store the new index and hash.

Content hashes are computed over the canonical binary IR (RFC-0010 §4.6), not source text, ensuring that whitespace-only edits do not invalidate indexes.

10. Compatibility and Migration

  1. Canonical IR format changes MUST be versioned; older IR MUST remain parseable by newer tooling.
  2. Kernel artifacts are generated; schema changes produce new kernel versions and MUST go through the install plan diff (RFC-0005).
  3. Surface components are decoupled from kernel version by the typed event contract; surface updates do not require kernel recompile unless event schemas change.
  4. Knowledge Index implementations are compiler-internal. Adding a new index or changing an existing index’s data structure is a compiler-version change, not a module-version change, and does not require a migration.