RFC-0018 · Gnomon Compiler Services
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, DX
1. Scope
Defines the compiler services layer — the structured query API that the CLI compiler (gnomon build), the language server (gnomon lsp), and other tooling use to access compiler analysis artifacts. This RFC covers:
- The compiler session model — how the compiler is initialized and held resident
- The parse context system — structured description of cursor state in a partially-parsed file
- The scope and symbol query API — what declarations are visible from a given position
- The property registry — machine-readable catalog of valid properties per declaration kind
- The incremental compilation model — how file changes propagate through the symbol table
- The rule compiler service — model invocation, cache protocol, and expression output
- The compiler daemon — optional out-of-process interface for debugging and tooling
This RFC does not define the grammar (RFC-0008), the IR format (RFC-0010), or the LSP protocol (RFC-0017). It defines the query layer that sits between them.
2. Goals
- The LSP and CLI compiler share identical analysis logic — no divergence between editor diagnostics and build diagnostics
- Completions and hover are derived from compiler analysis, not from hardcoded LSP rules
- The rule compiler is invokable from both CLI builds and LSP sessions using the same mechanism
- The property registry is the single source of truth for what is valid in each declaration context — grammar changes propagate to completions automatically
- Incremental reanalysis is bounded — changing one file does not reanalyze the whole project
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
- The LSP MUST NOT implement symbol resolution, scope analysis, or type checking independently. It MUST delegate all such queries to the compiler session.
- The compiler session MUST produce identical diagnostics to the CLI compiler for the same input. Any divergence is a compiler defect.
- The rule compiler service MUST be invokable from both the LSP session and the CLI build pipeline using the same cache and the same model invocation protocol.
- The property registry MUST be derived mechanically from the grammar (RFC-0008 §8). It MUST NOT be maintained as a separate hand-edited document.
- Scope queries MUST be answerable on partially-parsed files (files with syntax errors). The scope system MUST return best-effort results rather than failing on incomplete input.
4. Compiler Architecture
The Gnomon compiler is a library (gnomon-compiler crate). It is not a subprocess. Both gnomon build and gnomon lsp link against this library and interact with it through the CompilerSession interface defined in §5.
┌─────────────────────────────────────────────────┐
│ gnomon-compiler │
│ │
│ Parser ──► Symbol Table ──► Type Checker │
│ │ │ │
│ Scope Engine Property Registry │
│ │ │
│ Query API ◄─────────────────────────┤
│ │ │
│ Rule Compiler Service │
│ (model invocation + cache) │
└─────────────────────────────────────────────────┘
▲ ▲
│ │
gnomon lsp gnomon build
(RFC-0017) (RFC-0018)
The CompilerSession is a long-lived object that holds the full project symbol table in memory. It supports incremental updates: when a file changes, only the affected portions of the symbol table are invalidated and recomputed.
5. CompilerSession Interface
The CompilerSession is the primary entry point for all compiler queries. Its interface is specified here in a language-neutral pseudocode; the Rust implementation follows this contract.
interface CompilerSession {
// --- Lifecycle ---
// Initialize a session from a project root. Locates project.gnm,
// loads all .gnm files, builds symbol table, loads compiler config.
static fn open(project_root: Path) -> Result<CompilerSession, InitError>
// Initialize a session for a single file (no project.gnm).
// Cross-file resolution is unavailable. Completions are degraded.
static fn open_single_file(file: Path, content: String) -> CompilerSession
// --- Incremental update ---
// Apply an incremental content change to a file.
// Invalidates the affected portions of the symbol table.
// Does NOT block; reanalysis is lazy (performed on next query).
fn update_file(file: Path, content: String)
// Force synchronous reanalysis of all dirty files.
// Called before a CLI build; the LSP prefers lazy reanalysis.
fn flush() -> Vec<Diagnostic>
// --- Diagnostics ---
fn diagnostics(file: Path) -> Vec<Diagnostic>
fn all_diagnostics() -> Vec<Diagnostic>
// --- Symbol queries ---
fn symbol_table() -> SymbolTable
fn resolve(file: Path, pos: Position) -> Option<DeclRef>
fn references(canonical_path: CanonicalPath) -> Vec<Location>
fn hover_info(file: Path, pos: Position) -> Option<HoverInfo>
// --- Scope and completion ---
fn parse_context(file: Path, pos: Position) -> ParseContext
fn scope_at(file: Path, pos: Position) -> ScopeInfo
fn completions_at(file: Path, pos: Position) -> Vec<CompletionCandidate>
// --- Type queries ---
fn type_of(file: Path, pos: Position) -> Option<TypeInfo>
fn valid_properties_for(decl_kind: DeclKind) -> Vec<PropertySpec>
// --- Rule compiler ---
fn compile_rule(rule_text: String, context: RuleContext) -> RuleCompileResult
fn rule_cache_status(rule_text: String) -> CacheStatus
}
6. Parse Context
The ParseContext describes the structural state of the cursor in a (possibly incomplete) file. It is the primary input for generating accurate completions. The parser MUST produce a best-effort ParseContext even for files with syntax errors.
enum ParseContext {
// Cursor is at the top level of a file (between declarations).
TopLevel,
// Cursor is after a declaration keyword, before the name.
// e.g.: "entity |"
AfterDeclKeyword { kind: DeclKind },
// Cursor is inside a declaration body, at a property key position.
// e.g.: "entity Foo { |"
AtPropertyKey { decl_kind: DeclKind },
// Cursor is at the value position of a known property.
// e.g.: "entity Foo { meaning: |"
AtPropertyValue {
decl_kind: DeclKind,
property: PropertyKey,
expected: TypeConstraint, // what type this property accepts
},
// Cursor is inside an ident-set or string-seq value.
// e.g.: "includes [Auditable, |"
InsideIdentSet {
decl_kind: DeclKind,
property: PropertyKey,
filter: IdentSetFilter, // which kinds of names are valid here
},
// Cursor is inside a rule block, at the start of a new statement.
// e.g.: "rules { every change must record actor\n |"
AtRuleStatement {
block_type: RuleBlockType,
enclosing: DeclKind,
},
// Cursor is inside an expr { } block.
// e.g.: "expr { person.contributions.|"
InsideExprBlock {
expr_context: ExprContext, // left-hand partial parse of expression
},
// Cursor is after "with " in a rule or prompt statement.
// Only model names with the appropriate role are valid.
AfterWithKeyword { for_role: ModelRole },
// Cursor is after "model: " in an agent or binding body.
AtModelRef { required_role: Option<ModelRole> },
// Cursor is in an import path string.
// e.g.: "import \"|"
InImportPath,
// Cursor is inside an annotation block.
// e.g.: "annotations { |"
InAnnotationBlock { annotation_facet: Option<CanonicalPath> },
// Cursor is inside the body of a test declaration.
// block: which sub-block (Given, When, Then) the cursor is in.
InTestBlock { block: TestBlock },
// Cursor is inside an action body (preconditions, effects, mustSatisfy).
InActionBody { decl: CanonicalPath },
// Cursor is inside an invariant body expression.
InInvariantBody { decl: CanonicalPath },
// Cursor is inside a claim declaration body.
InClaimBody { decl: CanonicalPath },
// Cursor is inside a compose declaration body.
InComposeBody { decl: CanonicalPath },
// Cursor is inside an aspect declaration body (statement list).
InAspectBody { decl: CanonicalPath },
// Cursor is inside a query declaration body.
InQueryBody { decl: CanonicalPath },
// Cursor is inside an annotation facet declaration body.
InAnnotationFacetBody { decl: CanonicalPath },
// Cursor is inside an annotation aspect declaration body.
InAnnotationAspectBody { decl: CanonicalPath },
// Cursor is inside a migration declaration body (RFC-0016).
InMigrationBody { decl: CanonicalPath },
// Cursor is inside a binding declaration body (RFC-0015).
InBindingBody { decl: CanonicalPath },
InExecuteBlock, // cursor inside execute {} block of an action or saga
InClientBody, // cursor inside client declaration body
InSagaBody, // cursor inside saga declaration body
InProcedureBody, // cursor inside procedure declaration body
// Cursor position could not be resolved (parse error, unknown context).
Unknown,
}
enum TestBlock { Given, When, Then }
6.1 IdentSetFilter
When the cursor is inside an ident-set value, the filter specifies which declaration kinds are valid completions:
enum IdentSetFilter {
FacetsOnly, // after "includes ["
FacetsNotAlreadyIncluded, // after "includes [" with existing entries
FlowsForKind { entity: TypeExpr }, // after "flow " — only flows whose "for" matches
InvariantsOnly, // after "mustSatisfy ["
ActorsOnly, // after "actor ["
EntitiesAndFacetsAndActions, // after "applies to ["
ModelsWithRole { role: ModelRole }, // after "with " or "model: "
StateNamesForFlow { flow: CanonicalPath }, // after "->" in transition rules
Any,
}
6.2 ExprContext
Inside an expr { } block, the partial parse of the expression tells the completion engine what is valid next:
struct ExprContext {
// The leftmost receiver in the current expression path.
// e.g. for "person.contributions." this is the TypeInfo of "contributions"
current_receiver: Option<TypeInfo>,
// Whether the cursor is after a "." — field access position
after_dot: bool,
// Whether the cursor is inside a function call argument list
in_arg_list: Option<FunctionName>,
// The expected type at this expression position (from parent context)
expected_type: Option<TypeConstraint>,
}
ExprContext also governs query predicate expressions (RFC-0007 §7); the InQueryBody ParseContext uses ExprContext with read-only access to all fields of the entity being queried.
7. Scope and Symbol Queries
7.1 ScopeInfo
struct ScopeInfo {
// The parse context at this position
parse_context: ParseContext,
// The innermost declaration the cursor is inside, if any
enclosing_declaration: Option<DeclRef>,
// All declarations visible from this position,
// pre-filtered by what makes semantic sense for the parse context.
// e.g. in an "includes [" context, only facets are returned.
visible_symbols: Vec<SymbolRef>,
// For type-reference positions: additional filtering by compatibility.
// e.g. after "flow " — only flows whose "for" type matches the enclosing entity.
type_filtered_symbols: Vec<SymbolRef>,
}
7.2 SymbolRef
struct SymbolRef {
canonical_path: CanonicalPath, // e.g. "benefits.entities.Employee"
decl_kind: DeclKind,
meaning: Option<String>, // truncated to 120 chars for display
file: Path,
line: u32,
visibility: Visibility, // Public | Internal
epistemic: Option<Epistemic>, // Draft | Deprecated | etc.
}
7.3 Completion candidate generation
completions_at calls scope_at, then maps the ScopeInfo to CompletionCandidate items:
enum CompletionKind {
Property = "Property", // field name, relation name, or view slot
Identifier = "Identifier", // entity FQN, action FQN, or declared identifier
Keyword = "Keyword", // reserved language keyword
Snippet = "Snippet", // multi-token template (e.g. full action block)
Model = "Model", // model FQN from model registry
}
struct CompletionCandidate {
label: String,
kind: CompletionKind, // Property | Identifier | Keyword | Snippet | Model
detail: String, // e.g. "facet" or "entity" or "model (rule-compiler)"
documentation: String, // full meaning field
insert_text: String, // may use $1 snippet placeholders
filter_text: String, // for fuzzy matching
sort_key: String, // controls ordering; required props sort before optional
deprecated: bool,
}
Special completion behaviors
After includes [:
- Return all facets visible from this file
- Filter out facets already listed in the current
includesset - Sort: facets from the same module first, then alphabetical
After flow in an entity body:
- Return only flows where the flow’s
fortype is compatible with the enclosing entity’s type or any of itsisancestors - If no flows exist, offer a snippet to create one:
flow ${1:Name} for ${2:Entity} { ... }
After model: in an agent body:
- Return only model declarations with
runtime-agentinroles - Show provider and name in
detailfield
After mustSatisfy [:
- Return only
invariantdeclarations whose parameter types are compatible with the enclosing action’sinputtypes - Incompatible invariants are shown with a ⚠ suffix and
deprecated: true
At property key position inside a declaration body:
- Return valid property names for the
decl_kindfrom the property registry (§8) - Mark required properties with a
!suffix and sort them first - Filter out properties already present in the current body (for properties that may appear at most once)
ParseContext → completion-kind mapping for new declaration contexts:
| ParseContext | Completion kinds (CompletionKind variants) |
|---|---|
InExecuteBlock | Identifier (client operation names from adapter schema), Keyword (IO binding keywords: using, =) |
InClientBody | Property (client property keywords: meaning, spec, baseUrl, auth, errors, operations) |
InSagaBody | Property (saga property keywords: state, input, steps, compensations, on success, on failure) |
InProcedureBody | Property (procedure property keywords: meaning, preconditions, input, calls, returns) |
8. Property Registry
The property registry is a compile-time artifact derived mechanically from the grammar (RFC-0008 §8). It maps each DeclKind to its set of valid properties, their types, cardinality, and requirement status.
struct PropertySpec {
name: String,
decl_kind: DeclKind, // which declaration kind this property belongs to
value_type: TypeConstraint, // what type the value must conform to
cardinality: PropertyCardinality,
required: bool,
invariant: Option<String>, // diagnostic code if violated (e.g. "M08702")
doc: String, // human-readable description for hover/completion
}
enum PropertyCardinality {
ExactlyOne, // required, appears once
ZeroOrOne, // optional, appears at most once
ZeroOrMore, // optional, may appear multiple times (e.g. multiple rule-stmts)
}
enum TypeConstraint {
StringLiteral,
QualifiedRef { valid_kinds: Vec<DeclKind> },
IdentSet { filter: IdentSetFilter },
StringSeq,
TypeExpr, // any valid type-expr
RuleBlock, // a { rule-stmt* } block
ExprBlock, // an expr { ... } block
FieldDeclBlock, // a { field-decl* } block
InlineBlock { sub_properties: Vec<PropertySpec> },
EnumLiteral { values: Vec<String> },
BooleanLiteral,
NumberLiteral,
}
8.1 Property registry snapshot (partial)
The following table shows selected entries. The full registry is generated from the grammar; this snapshot is for specification illustration.
| DeclKind | Property | TypeConstraint | Cardinality | Required |
|---|---|---|---|---|
entity | meaning | StringLiteral | ExactlyOne | yes (M08702) |
entity | is | QualifiedRef([entity]) | ZeroOrOne | no |
entity | includes | IdentSet(FacetsOnly) | ZeroOrOne | no |
entity | flow | QualifiedRef([flow]) | ZeroOrOne | no |
entity | fields | FieldDeclBlock | ZeroOrOne | no |
entity | examples | StringSeq | ZeroOrOne | no |
facet | meaning | StringLiteral | ExactlyOne | yes (M08702) |
facet | rules | RuleBlock | ZeroOrOne | no |
flow | states | IdentSet(Any) | ExactlyOne | yes |
flow | transitions | InlineBlock([transition-rule*]) | ZeroOrOne | no |
flow | rules | RuleBlock | ZeroOrOne | no |
agent | purpose | StringLiteral | ExactlyOne | yes |
agent | model | QualifiedRef([model]) | ZeroOrOne | no |
agent | inputs | FieldDeclBlock | ZeroOrOne | no |
agent | outputs | InlineBlock([output-stmt*]) | ZeroOrOne | no |
agent | permissions | RuleBlock | ExactlyOne | yes |
agent | prohibitions | RuleBlock | ExactlyOne | yes |
agent | requirements | RuleBlock | ZeroOrOne | no |
model | meaning | StringLiteral | ExactlyOne | yes (M08702) |
model | provider | StringLiteral | ExactlyOne | yes |
model | name | StringLiteral | ExactlyOne | yes |
model | digest | StringLiteral | ZeroOrOne | one of digest/version |
model | version | StringLiteral | ZeroOrOne | one of digest/version |
model | parameters | InlineBlock([model-param*]) | ZeroOrOne | no |
model | roles | IdentSet(EnumLiteral([rule-compiler, runtime-agent])) | ZeroOrOne | no |
policy | applies to | IdentSet(EntitiesAndFacetsAndActions) | ZeroOrOne | no |
policy | rules | RuleBlock | ZeroOrOne | no |
policy | enforcement | EnumLiteral([hard, soft]) | ZeroOrOne | no |
8.2 Snippet generation from the property registry
When inserting a declaration skeleton (e.g., entity Foo { ... }), the compiler generates a snippet by:
- Taking all
Requiredproperties for theDeclKind - Ordering them by the canonical property order (RFC-0012 §4.2)
- Generating a snippet string with
$Nplaceholders
Example for entity:
entity ${1:Name} {
meaning: "${2:What this entity represents.}"
$0
}
The LSP MUST use snippet generation from the property registry rather than hardcoded snippet strings.
9. Incremental Compilation Model
9.1 Dependency graph
The compiler maintains a dependency graph over declarations. An edge A → B means “A depends on B” (A references B). When B changes:
- B is re-parsed and re-analyzed
- All declarations in A’s dependency set are marked dirty
- Dirty declarations are reanalyzed lazily on the next query that touches them
9.2 Granularity
The incremental model operates at declaration granularity, not file granularity. Changing a single declaration in a file invalidates only the declarations that depend on it, not all declarations in the file.
File-level reparse is triggered by:
- Any top-level keyword addition or removal (structural change)
- Changes to import declarations
Declaration-level reanalysis is triggered by:
- Changes to declaration body content
- Changes to a dependency’s exported interface
9.3 Update protocol
// Called by the LSP on every textDocument/didChange event
session.update_file(file, new_full_content)
// The session:
// 1. Incrementally re-parses only the changed spans
// 2. Detects which declarations changed (added, removed, modified)
// 3. Marks affected dependency subgraphs as dirty
// 4. Returns immediately (analysis is lazy)
// Queries then trigger lazy reanalysis of only the required declarations:
session.completions_at(file, pos) // triggers reanalysis of enclosing declaration if dirty
session.diagnostics(file) // triggers full reanalysis of all dirty decls in file
9.4 Rule compilation in incremental model
Rule compilation results are stored in the rule cache (§10.5). Rule re-compilation is triggered when:
- The
rule "..."text changes (cache key mismatch) - The
compiler.ruleCompilermodel changes inproject.gnm(model digest mismatch) - The
compiler.promptTemplateversion changes
Rule re-compilation is always asynchronous. The compiler marks the rule as CacheStatus::Pending immediately and triggers a background compilation. Callers (e.g., the LSP) receive Pending status and display a loading indicator.
10. Rule Compiler Service
10.1 Overview
The rule compiler service lowers rule "..." statements to Gnomon constraint expressions (RFC-0008 §11.3). It is a shared service used by both gnomon build and gnomon lsp.
10.2 Invocation interface
fn compile_rule(rule_text: String, context: RuleContext) -> RuleCompileResult
// A resolved reference to an Gnomon model declaration (RFC-0008 §6.20).
struct ModelRef {
// Canonical path of the model declaration (e.g. "com.example.models.Gemma3Local").
canonical_path: CanonicalPath,
// provider field from the model declaration (e.g. "ollama").
provider: String,
// name field — the provider-local model name (e.g. "gemma3:4b").
name: String,
// digest or version from the model declaration.
// One of these MUST be present; if both are present, digest takes precedence.
digest: Option<String>, // "sha256:a1b2c3..."
version: Option<String>, // "3.0"
// Roles this model is declared for (from the model's `roles` ident-set).
roles: Vec<ModelRole>,
}
enum ModelRole {
RuleCompiler, // "rule-compiler" in source
RuntimeAgent, // "runtime-agent" in source
}
struct RuleContext {
// The declaration kind and canonical path that contains this rule.
// Used to resolve field names in the constraint expression.
enclosing_decl: DeclRef,
// The model to use. If None, uses compiler.ruleCompiler from project.gnm.
model_override: Option<ModelRef>,
// Whether to allow cache hits (true in normal operation; false for --no-cache).
use_cache: bool,
}
enum RuleCompileResult {
Compiled {
expr: ConstraintExpr,
model_used: ModelRef,
template_used: String,
cache_hit: bool,
},
Unresolvable {
reason: String, // the UNRESOLVABLE message from the model
suggestion: Option<String>, // e.g. "Add field X to entity Y"
},
Misclassified {
classification: RuleClass, // AuthorizationRule | LifecycleRule | Advisory
suggestion: String, // where the rule should be moved
},
NoModelConfigured, // no rule compiler model in project + no override
ModelUnavailable {
model: ModelRef,
reason: String, // e.g. "Ollama not running at localhost:11434"
},
Timeout,
}
enum RuleClass {
AuthorizationRule, // belongs in a policy declaration
LifecycleRule, // belongs in a flow declaration
Advisory, // advisory language; no constraint produced
}
10.3 Model invocation protocol
The rule compiler invokes the configured model as follows:
Ollama (provider: "ollama"):
POST http://localhost:11434/api/generate
{
"model": "<model.name>",
"system": "<prompt template content>",
"prompt": "<rule text>",
"stream": false,
"options": { "temperature": 0, "top_p": 1 }
}
Temperature is always 0 regardless of model parameters.temperature. This is non-negotiable for rule compilation determinism.
OpenAI-compatible (provider: "openai"):
POST https://api.openai.com/v1/chat/completions
Authorization: Bearer $OPENAI_API_KEY
{
"model": "<model.name>",
"messages": [
{ "role": "system", "content": "<prompt template content>" },
{ "role": "user", "content": "<rule text>" }
],
"temperature": 0,
"max_tokens": 256
}
Custom provider (provider: "<other>"):
The compiler looks for a binary named gnomon-rule-compiler-<provider> on $PATH. If found, it is invoked as:
echo '{"ruleText": "...", "templateContent": "...", "modelName": "..."}' | gnomon-rule-compiler-<provider>
The binary MUST write a JSON response to stdout:
{ "result": "compiled | unresolvable | misclassified | error",
"expr": "...",
"reason": "..." }
10.4 Prompt template loading
Prompt templates are loaded in priority order:
<project_root>/governance/lsp-templates/<templateName>.prompt.md(project-local)<gnomon_data_dir>/templates/<templateName>.prompt.md(toolchain-bundled)
The default template is gnomon-rules-v1. The current canonical content is defined in docs/spikes/GEMMA_RULE_COMPILER_PROMPT.md (see spec source) (in this RFC suite, non-normative until stabilized).
10.5 Rule cache protocol
The rule cache is stored in <project_root>/.gnomon-cache/rules/. Each cache entry is a JSON file named <cache_key>.json where cache_key = SHA256(length(rule_text) + ":" + rule_text + "\0" + model_digest + "\0" + template_version). The length prefix and null-byte separators prevent hash collisions between inputs whose concatenations would otherwise be identical.
{
"cacheKey": "sha256:e3f4a5b6...",
"ruleText": "employee and employer contributions must not exceed the IRS limit",
"modelDigest": "sha256:a1b2c3d4...",
"templateVersion":"gnomon-rules-v1",
"result": "compiled",
"compiledExpr": "p.contributions.hsa + p.household.employerHSAContribution <= irsLimits(planYear, coverageType).hsaMax",
"compiledAt": "2026-04-29T12:00:00Z",
"userEdited": false
}
Cache entries with userEdited: true are NEVER evicted — the user’s manual edit takes permanent precedence over LLM output. Cache entries with userEdited: false are evicted when the model digest or template version changes.
The committed form of a compiled rule in .gnm source is the //compiled: structured comment:
rule "employee and employer contributions must not exceed the 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 immediately following a rule "..." statement. The compiler MUST treat a committed //compiled: comment as authoritative if the rule-hash, model digest, and template version match. A mismatch triggers re-compilation.
10.6 Cache status query
enum CacheStatus {
Pending, // compilation in progress (async)
Hit { expr: String, user_edited: bool },// compiled expression available
Stale { expr: String }, // cached but model digest changed
Miss, // never compiled
Unresolvable { reason: String }, // model could not produce valid expression
Misclassified { as_type: RuleKind }, // rule belongs in different declaration context
ModelUnavailable { reason: String }, // configured model not reachable
}
11. HoverInfo and TypeInfo
11.1 HoverInfo
struct HoverInfo {
decl_kind: DeclKind,
canonical_path: CanonicalPath,
meaning: Option<String>,
visibility: Visibility,
epistemic: Option<Epistemic>,
defined_in: Location,
// For model declarations
model_info: Option<ModelHoverInfo>,
// For rule "..." statements
rule_info: Option<RuleHoverInfo>,
// For field references inside expr { } blocks
type_info: Option<TypeInfo>,
}
struct ModelHoverInfo {
provider: String,
name: String,
pin: String, // digest or version value
roles: Vec<ModelRole>,
reachable: bool, // whether the LSP can currently reach the provider
}
struct RuleHoverInfo {
rule_text: String,
cache_status: CacheStatus,
compiled_expr: Option<String>, // the constraint expression if cached
compiled_by: Option<String>, // "model@digest template:version"
user_edited: bool,
}
11.2 TypeInfo
struct TypeInfo {
type_expr: TypeExpr,
resolved_declaration: Option<DeclRef>, // if this is a named type
is_list: bool,
is_optional: bool,
is_claim_wrapped: bool,
claim_evidence_required: Vec<String>, // if is_claim_wrapped
accessible_fields: Vec<FieldSpec>, // fields accessible via dot notation
}
struct FieldSpec {
name: String,
type_info: TypeInfo,
required: bool,
meaning: Option<String>,
}
accessible_fields drives expression completion: after person. the compiler returns the accessible fields of Person, which drives completions_at in InsideExprBlock { after_dot: true } context.
12. Compiler Daemon (Debug Interface)
For debugging and third-party tooling, the compiler exposes an optional JSON-RPC 2.0 interface when invoked as:
gnomon lsp --debug-rpc=PORT
This is an additional interface layered over the in-process CompilerSession. It is not required for normal LSP operation and MUST NOT be used by the LSP transport layer. Its purpose is to allow external tools (test harnesses, MCP servers, alternative editors) to query the compiler.
12.1 Methods
gnomon/session/open { projectRoot: string } -> { sessionId: string }
gnomon/session/update { sessionId, file, content } -> {}
gnomon/completions { sessionId, file, line, col } -> { items: CompletionCandidate[] }
gnomon/hover { sessionId, file, line, col } -> HoverInfo | null
gnomon/diagnostics { sessionId, file } -> Diagnostic[]
gnomon/symbolTable { sessionId } -> SymbolRef[]
gnomon/resolve { sessionId, file, line, col } -> DeclRef | null
gnomon/compileRule { sessionId, ruleText, enclosingDecl } -> RuleCompileResult
gnomon/cacheStatus { sessionId, ruleText } -> CacheStatus
gnomon/propertyRegistry { sessionId, declKind } -> PropertySpec[]
The debug RPC interface MUST NOT be exposed on a public network interface. It MUST bind to 127.0.0.1 only.
13. Diagnostic Contract
All diagnostics produced by the compiler session conform to:
struct Diagnostic {
file: Path,
span: Span, // { start: Position, end: Position }
code: DiagCode, // M08xxx, F12xxx, L00xx
severity: Severity, // Error | Warning | Info | Hint
message: String,
related: Vec<RelatedDiagnostic>,
fix: Option<CodeFix>,
}
struct CodeFix {
title: String,
edits: Vec<TextEdit>,
}
The fix field carries a machine-applicable fix for diagnostics where the correction is unambiguous. The LSP MUST expose these as textDocument/codeAction quick-fixes. The CLI compiler MAY apply them with gnomon build --fix.
14. Security
- The compiler session MUST NOT execute any
.gnmsource code. It is a static analysis tool only. - The rule compiler service MUST NOT be invoked with a model that is not declared in the project’s symbol table and visible to the compiler session.
- The
.gnomon-cache/directory MUST have filesystem permissions restricted to the current user. The compiler MUST NOT write cache files that are world-readable. - Rule text from
.gnmsource is transmitted to the configured model provider. The compiler MUST log a warning on first invocation per session if the model provider is non-local (notprovider: "ollama"with a localhost endpoint). - The compiler daemon (§12) MUST bind only to
127.0.0.1. Any attempt to bind to0.0.0.0MUST be rejected.