Browse documentation
Docs/Language

Compiler Tools and Syntax Values

Grid programs can inspect, construct, and transform expressions as data. The native compiler supplies parsing, source analysis, checked rename, and compilation diagnostics. Generated source…

Compiler tools and syntax values

Grid programs can inspect, construct, and transform expressions as data. The native compiler supplies parsing, source analysis, checked rename, and compilation diagnostics. Generated source passes through the ordinary compiler and compiled formula runtime.

Inspection occurrence rows may include renameSpan, a nonempty UTF-8 byte range for an identifier inside the occurrence's span. The editor passes its start to the compiler's checked rename operation; the location itself grants no rename or semantic authority. Existing rename restrictions still apply, including runtime overrides and incomplete binding/scope information. This metadata does not add function rename support. Detached artifacts have neither source nor rename locations. AST.WALK and AST.SELECT regenerate structural rows and join only validated span metadata. The inspection report's original occurrence rows supply the editor's identifier locations.

Authored USE inspection emits one record per directive with either LF or CRLF line endings, while canonical modules retain their scoped import fields.

Generated View glue identities use sorted binding-map keys across compiler feature sets, while retaining authored action argument order.

Owning compiler artifacts on the V3 branch

AST.PARSE(source) and AST.EXPRESSION(source) return grid.compiler.inspection.v1: the actual artifact, a separate source, sourceRevision, and compiler-generated occurrences. Explicit "authored" and "canonical" are aliases of this same inspection. Both editor inspection commands use it. There is no projected-tree default in these public operations. ok establishes successful structural inspection, not semantic validity. Malformed source refuses inspection; AST.CHECK returns compilation diagnostics and AST.ANALYZE returns revision-bound semantic findings even for invalid source.

Pass the whole inspection to AST.SOURCE, AST.WALK or AST.SELECT to retain source metadata. Walk/selection recompute structure from the owners, validate source locations, and join only those descriptive locations onto their result. The report's supplied kinds, fields and children are never structural authority. Use the detached artifact for source-free transport; its traversals have no spans. Semantic facts come from AST.ANALYZE and AST.MEANING, not syntax attributes. The checked-in inspection and analyzer examples demonstrate these separate contracts.

Use AST.PARSE(source, "artifact") for a module or AST.EXPRESSION(source, "artifact") for one expression. These return the compiler's actual owner records in grid.compiler.artifact.v1, with compiler contract grid.compiler.source.v3. Inspection uses the shared recognizer; it does not resolve imports, invoke handlers or establish semantic validity. AST.CHECK(artifact) submits a complete module to native checking and reports its compiled identity and diagnostics without executing the result.

Draft = "DEFINE LineTotal(quantity, price) = quantity * price\nTotal = LineTotal(2, 50)\n"
Inspected = AST.PARSE(Draft, "artifact")
Checked = AST.CHECK(Inspected)
Expression = AST.EXPRESSION("Quantity * UnitPrice", "artifact")

Unresolved USE directives and unused contextual definitions remain inspection data. When imported delimiters are needed, inspection requires immutable grammar metadata and otherwise returns GRID_SYNTAX_CONTEXT_REQUIRED. That metadata grants no import access: native checking uses the receiving host's actual module body and typed package providers. A denied import stops before reading its body. The import inspection example shows unresolved directives as data. Cold-loaded JSON, generated owners and structural rewrites undergo those same checks; an earlier successful check cannot authorize a changed artifact.

Native hir/mir/lir contribution labels and signatures also grant no authority. Pure native expression payloads require native checking; general contribution selectors require actual host custody in the same handler invocation. An unavailable provider or required capability refuses. Inspection and CHECK never install or execute the submitted model.

AST.ROOT, AST.WALK, AST.SELECT, AST.AT, AST.CHILDREN and AST.REWRITE also accept these artifacts. Paths use the actual owner's generated child order. Walk/selection rows expose path, the artifact-local node handle, the generated kind and variant, actual codec fields as attributes, and childCount. span is null: detached data cannot supply source provenance. Selectors match generated kinds or variant names, such as "Binary". Saved owning JSON can be loaded with AST.FROM_JSON(text). This checks the complete owner graph, including unused owners, and rejects duplicate decoded keys, invalid child roles and producer-supplied authority fields. The returned value is portable data; checking a module still requires AST.CHECK and the host's normal import authority. AST.ROOT returns its owner record; AST.AT and AST.CHILDREN return complete artifacts containing each selected subtree's closure.

AST.RENDER(artifact) emits supported expression owners directly, including arithmetic, comparisons, ordinary calls, arrays, objects, arrow lambdas, conditionals and WITH bindings. Plain modules, scalar assignments and functions also render directly, preserving input/output/default/state modifiers and RETURNS CompilerContribution<stage, category> annotations. A module note bound to one item renders as that item's leading or trailing ## comment. Template expansions whose notes bind several items or none keep their native presentation. Note text with unrepresentable comment whitespace refuses rather than changing meaning. Owning Path assignments also render their graph, endpoints, Edge objective and hop limit. Rendering a Path does not evaluate a graph or grant selector authority. Other declarations still need an available contextual renderer. Authored numeric tokens retain their spelling. In complete module emission, synthesized real numbers use the shortest round-tripping real spelling, such as 6.0. Standalone expression fragments retain scientific spelling, such as 6e0. Neither form acquires exact-integer intent. Strings and quoted object keys use Grid escapes. Infix operators keep their canonical operator spelling, such as MOD for %% or MODULO. Rendered text parses back to the same owners, apart from added grouping and the canonical lowercase spelling of type identifiers. Owners that would parse back differently, text nested deeper than the parser accepts, ambiguous reference spellings and unsupported contextual productions refuse rendering. SQL previews compile to the same query but add explicit grouping. AST.CAPABILITIES(artifact, path).render.supported checks that exact subtree. Rendering never supplies native admission, import authority or a source revision. Registered Grid handlers can call the same renderer under their existing cumulative invocation budget.

Expression = AST.EXPRESSION("(Quantity + 1) * UnitPrice", "artifact")
GeneratedSource = AST.RENDER(Expression)
CanRender = AST.CAPABILITIES(Expression, []).render.supported
Original = AST.PARSE("input Quantity = 7\nTotal = Quantity * 2\n", "artifact")
Products = AST.SELECT(Original, { kinds: ["Binary"] })
Replacement = AST.EXPRESSION("3", "artifact")
Edited = AST.REWRITE(Original, [{ path: [1, 0, 1], replacement: Replacement }])
Checked = AST.CHECK(Edited)

Rewrite paths identify disjoint occurrences. Replacing one use of a shared node leaves its other uses unchanged. Every input owner is checked, including unused ones; invalid paths, overlapping edits and incompatible child categories refuse the entire rewrite. Output is structural data requiring normal native admission, not a checked source-edit transaction or a claim of equivalent behavior.

The convenience constructors AST.LITERAL, AST.REFERENCE, AST.BINARY, AST.CALL, AST.ASSIGN, AST.FUNCTION and AST.MODULE now produce those same owning artifacts. AST.HOLE and AST.SPLICE construct ordinary marker-call owners. Literal construction preserves nested Grid array rows and finite numeric bits, including negative zero. Function and assignment factories create plain declarations; use generated AST.NODE fields for additional declaration clauses. All children require complete owning artifacts and pass structural/category checks before being joined. These factories do not evaluate generated code or confer native admission. Registered handlers use the same factories and share the invocation's cumulative work and storage allowance.

This development cutover changes the constructors' returned data schema. AST.QUOTE(expression) captures the same owners before semantic lowering; unknown names and unevaluated calls remain syntax data. Source-backed quotation returns a grid.compiler.inspection.v1 report containing artifact and separate source/occurrence metadata. Source-free quotation returns the artifact itself. Traversal, rendering, substitution and constructors accept either form, and AST.SOURCE reads inspection metadata without granting source or execution authority. Serialized inspection metadata remains descriptive data.

Raw owning JSON ingress retains the 2 MiB text and depth bounds and rejects decoded duplicate keys before materialization. Its framing scan is bounded by the actual raw input extent and key-storage requests. Fixed record/type/field headers do not spend authored-owner slots in that scan. The generated decoder then enforces the unchanged logical owner, entry and scalar-payload limits; passing raw preflight grants no native admission or execution authority.

Syntax construction and native admission count child edges, with a leaf at zero. The unchanged depth-128 boundary therefore preserves the original number under 128 unary wrappers, including all 129 owners; a 130th owner refuses. General graph validation and rewrite/prepared-edit operations retain their separate depth-128 node bound, with a leaf at one. Literal construction also retains its original value-nesting bound. These boundaries use the original fixtures and numeric limits; decoding bounded records still supplies no native admission or execution authority.

AST.EXPAND joins actual owners using declared grammatical slots, including expression and declaration/list splices. Native scope events preserve binder hygiene and explicit capture/export intent. Its report retains the template, bindings, owning syntax artifact and per-node structural origins. Generated source is an optional preview: an unrenderable owner retains its syntax and origins with generatedSourceRefusal; it does not acquire invented source spans. Source locations are validated at ingress. Generate reconstructs the expansion from its inputs and admits the owning module through the receiving host. Claimed preview text and supplied origin rows grant no execution authority. The template contract describes category and intent fields.

Native hosts can retain the complete compiler-produced MIR using grid_gir_passes::compile_source_to_mir or compile_source_module_artifact_to_mir. CompiledMir owns the actual native module, pools, metadata, optimizer diagnostics and captured compile options. Its module() and report() accessors borrow that result; into_lir() consumes it and resumes the existing emitter without parsing, resolving imports, invoking handlers or lowering again. Existing native provenance remains attached. The emitter still checks current host limits. Ordinary module qualification uses this same production route. This API has no external constructor, mutable-module access or deserializer, and grants no execution rights. Declared hir/mir/lir handlers also admit the closed native expression profile below and the checked native module receiving interfaces. General resource and physical-cost acceptance remains tracked separately in the V3 ledger.

Native hosts can also stop before MIR optimization with compile_source_to_hir or compile_source_module_artifact_to_hir. CompiledHir owns the actual HIR roots, expression and callable pools, prepared workbook, and the admitted inputs needed to finish relational regions and Process provenance. Read-only accessors expose those native owners. Consuming into_mir() or into_lir() resumes the same compiler continuation after the original source, artifact and resolver have been dropped; imports and handlers are not repeated. Dimensions, late dialect contracts and emission checks still run during continuation, so retaining HIR does not promise that later compilation will succeed. This API does not admit external HIR or certify serialized type, effect or authority claims.

Internal checked native continuations retain their original invocation budget through emission. Encoder buffers and ordering scratch consume its cumulative requested-storage allowance before allocation; the final output bound is checked before assembly. Late native execution-shape derivation uses that same work allowance and interruption control through Workbook dependency traversal, Predicate closure and nested portable TREE decoding. Deep dependency traversal reserves additional stack storage before growth. A refusal publishes no compiled model and remains terminal for that invocation. Dependency collections, metadata allocation and some bulk operations still need resource accounting; this does not establish complete native-stage coverage. Public expression ingress and native module receiving operations use the same continuation and resource ledger. Supported module/dialect interfaces are described under native module contributions; unavailable receiving authority and unrepresentable interfaces refuse explicitly.

AST.FREE_NAMES(artifact) and AST.SUBSTITUTE(artifact, replacements) also operate directly on supported owners. They understand arrow lambdas, ordinary LET/LAMBDA calls, sequential WITH bindings and their outer-scope fallback, and plain named modules/functions. Module names bind forward and recursive uses. Cell references use canonical RnCn names in free-name results and substitution keys. Free-name results include unbound callable names; native analysis determines whether those names are builtins, imports, model bindings or unresolved names. Binding analysis follows the native consumer's scope events, including DO bindings, WHERE/USING bodies and values, and constant names shadowed by lexical parameters. Qualified/contextual forms that need unavailable native context report unsupported scope analysis. Native-generated material spends the same selected operation; compact placeholder syntax cannot request unbounded parameter expansion. Named trailing callback parameters and their DO/UNTIL bodies follow those same native events. SQL scalar/predicate traversal preserves CTE and recursive CTE scopes. Descriptive rendering supports these forms, ordinary comprehension filters, and the admitted SQL query corpus; unrepresentable source spellings still refuse.

Substitution matches case-insensitive free names and renames binders when needed to avoid capturing an inserted reference. A callable replacement must be a plain reference. Every replacement is checked, even when unused; unused valid entries do not rename declarations or alter the original graph. Shared owners are reused within one lexical environment; occurrences under different binders are handled separately. Output remains syntax data requiring normal native admission.

Template = AST.EXPRESSION("(item) => external + item", "artifact")
Changed = AST.SUBSTITUTE(Template, {external: AST.EXPRESSION("item", "artifact")})
FreeNames = AST.FREE_NAMES(Changed)

AST.NODE(kind, attributes, children) constructs an actual owner. kind is its generated SourceNode variant, attributes contains its generated codec fields, and each {syntax: N} indexes the supplied child artifacts. Repeated handles preserve sharing. All children are validated, including unused owners; missing handles and incompatible grammatical categories refuse construction. The former projected node names such as "lambda" are retired from this API. Use the actual variant and fields, such as "ArrowLambda".

Left = AST.EXPRESSION("Quantity", "artifact")
Right = AST.NODE("Atom", {"0": {type: "Atom", variant: "Number", fields: {value: 3, origin: [], lexical: []}}}, [])
Product = AST.NODE("Binary", {op: {type: "BinaryOp", variant: "Mul", fields: {}}, left: {syntax: 0}, right: {syntax: 1}}, [Left, Right])

The source-free generator builds a complete module this way. Its Generated value can be submitted directly to the native host; Checked reports compilation without executing that generated model.

Registered Grid handlers can call the same AST.NODE, AST.ROOT, AST.WALK, AST.CHILDREN, AST.AT, AST.SELECT, AST.REWRITE, AST.CAPABILITIES, and AST.RENDER, AST.FREE_NAMES, and AST.SUBSTITUTE owner operations. The handler's native invocation budget covers input conversion, traversal, child copies, rewriting, and returned data across nested calls. Local exhaustion, cancellation and deadline refusal remain effective for later calls in that invocation. The pricing example composes checked child artifacts through this API before native expression admission; constructors themselves grant no binding or execution authority. Ordinary invalid-data results remain Grid error values, so a conditional can select another result. Resource exhaustion still aborts the whole invocation.

A handler module may also declare a Process. The handler's selected native callable must remain pure and cannot execute that Process, capture ambient model inputs, or obtain effects from its module. A caller using the imported Process still needs the normal complete Process admission and import closure. A transported module can pass a local Process name to a static PROCESS parameter without retained source locations. Computed, indexed and serialized targets still fail native admission. Qualified imported member targets retain a source-provenance dependency that remains part of the migration.

Complete FORMAT, VALIDATE, and PRESENT clauses preserve their native presentation metadata after owner transport. Attached ## documentation also travels as text and ordered module-item candidates; native admission applies the shared note-binding rule to actual assignable targets. Module-item splicing remaps the ordered candidate groups to inserted item occurrences; an empty splice retains the note as unattached. Rendering preserves attached notes on the targets selected by that same rule and retains decorative notes separately. Source offsets and producer-supplied diagnostics cannot authorize either operation. Missing or ambiguous source-only clause checkpoints still refuse detached admission.

Complete call/value OF expressions, such as ABS() OF -7 and ROUND(_, 2) OF 1.234, admit from portable owners and remain structurally rewritable. Admission repeats the native ordinary-call and pipe checks in their original order, including placeholder and operand restrictions. This support requires a complete shared call head and value; ambiguous following source regions, incomplete pipe prefixes and unrelated head alternatives still refuse. Serialized offsets or diagnostics cannot supply that missing context.

A complete following FORMAT policy also supplies the module context needed to admit an adjacent assignment after transport. For example, input Precision = "0.00" followed by FORMAT number Precision retains the live policy input. Admission checks the actual next module owner and its tag, preserves duplicate clause errors, and visits the tentative operand in native order. Missing or mismatched policies cannot turn an incomplete clause into an accepted one.

View inspection can borrow immutable grammar from supplied module artifacts:

Library = AST.PARSE("ELEMENT Panel(value: read number)\n  Metric value\nEND\n", "artifact")
Draft = "USE \"ui.grid\" AS ui\ninput Value = 7\nSURFACE Desk\n  ui.Panel(Value)\nEND\n"
Inspected = AST.PARSE(Draft, { imports: { "ui.grid": Library } })

Context keys are the authored USE paths. Missing View grammar returns GRID_SYNTAX_CONTEXT_REQUIRED. Supplied grammar cannot authorize an import: checking or executing that module still requires the host's actual resolver. The portable artifact owns its operands and carries no original source identity. Unsupported source ambiguity checkpoints retain an explicit native refusal.

The V3 branch also connects ordinary imported Grid handlers to this same native compiler. A declaration with RETURNS CompilerContribution<syntax, expression> registers a syntax-producing handler when the authorized host admits its defining module. Ordinary functions remain ordinary functions. The handler receives literal segments and named live interpolation slots, then returns actual expression owner records.

The handler's defining module may USE other .gs libraries; their helpers join the handler's callable closure and are admitted with it. Native admission accepts only closed, pure callables whose signatures carry no generic collection constraint. Reading the request through INDEX([request], 1) keeps its generic type, so a later positional INDEX over one of its fields constrains that type and refuses with CALLABLE_SELECTED_CONTEXT. Look the request up with a position parameter instead, as in INDEX([value], position), which keeps it ordinary dynamic data. A refused handler stops its import with that diagnostic.

RETURNS CompilerContribution<source, expression> instead returns a string containing one complete Grid expression. The compiler parses that expression with the authoritative recognizer under the same cumulative invocation budget. Generated text references the compiler-issued slot names; live hole values are never substituted into text. Both stages use the same native linker, preserving defining-module helpers and binding hygiene before normal compilation. Changing a live input does not run either handler again. A result with the wrong stage shape, an incomplete expression, extra declarations or unauthorized free names refuses compilation.

The complete pricing example includes an imported Grid handler and an independent Python owner generator. Its runtime coverage composes source and detached pricing input with imported Process kernels and recursive contextual Views. Initial Total is 90; changing Quantity from 2 to 3 gives 135. A structural discount edit gives 80, then 120. Native import, category, malformed-owner and cancellation refusals leave prior models intact.

AST.PARSE(source, "canonical") and Inspect compiler AST now return grid.compiler.inspection.v1: the actual artifact, a separate source and sourceRevision, and generated occurrences with paths, owner fields, child counts and source spans. Inspection does not execute handlers or establish semantic validity. Expression inspection uses the same envelope; select "artifact" for detached expression data. Use AST.CHECK(report.artifact) for a complete inspected module; old projected canonical trees are no longer accepted by the public checker.

The native audit_syntax_model tool now uses the same owner artifact in every mode. Its --canonical and --artifact options are aliases. Portable decoding is separate from --require-admission, which also checks source and detached owners using only explicitly supplied --module dependencies. The audit's old projection and reconstruction branches are removed.

Source transactions derive edits from the native parsed program and its binding inventory; source-free transactions use owning artifacts. Their versioned transaction envelopes do not select a V2 compiler. Whole-module definition reflection, quotation, constructors and template expansion use actual owners. Native stage interfaces, contribution origins and both transaction contracts are described below. Frozen stored-format codecs remain isolated for compatibility. Comparative Performance and current candidate acceptance remain tracked separately.

Native runtime preparation

Both native Host editions keep decoded expressions in packed arenas and consume Typed MIR contracts from the exact admitted module. Eligible number, Boolean, calendar, datetime and text calculations share compatible stages and private producers within bounded groups, and reuse intermediate buffers. Published values retain independent ownership. Structural edits prepare a replacement before publication and invalidate preparation associated with the old module.

Existing compiled model files, scalar operation order, coercion, errors and lazy branches retain their contracts. Unsupported operations use the existing general compiled evaluation. This preparation supplies no service or execution authority and requires no new source annotation.

Constant IF expressions can discard unused, self-contained numeric and Boolean work when a checked proof preserves evaluation behavior. Comparisons between literal numbers and logic over literal Booleans can expose more constant conditions, including IF((1 < 2) AND NOT(FALSE), A1, 0). Eager input reads, calls, coercion warnings and error behavior still apply. The constant-IF example shows a closed branch that can be removed alongside input reads and a conversion warning that remain observable.

In the Code workspace

Draft checks and compiler-tool findings carry the revision they describe. After you edit the source, old findings cannot place markers or apply repairs to the new text. Findings without a source location remain visible. A proposed repair still needs explicit review and staging.

External editors and local imports

Start the file-authoring language server with gridctl lsp --stdio. The client supplies its workspace folder; relative module imports stay inside that folder. Package code, analyzers and expansion remain disabled in an untrusted workspace. Ordinary completion, navigation and diagnostics do not need model access.

For local installed dependencies, set these existing host configuration values before starting the server:

  • GRID_DOMAIN_PACK_CATALOG_PATH: the installed Domain Pack catalog JSON. The server verifies the complete packages, manifest and artifact digests, runtime requirements and exact dependencies before resolving domain: modules.
  • GRID_API_SERVICE_PACKAGE_DIRS: files or directories containing validated grid-api-service.json or *.grid-api.json packages, separated using the operating system's path-list separator. api: imports select exact versions; conflicting local definitions are refused.

For example, with the real-estate pack installed in that catalog:

USE "domain:real-estate@2.1.0/modules/underwriting.gs" AS underwriting

annual_income = 120000
operating_expenses = 45000
net_operating_income = underwriting.noi(annual_income, operating_expenses)

These are local metadata reads. They do not download dependencies, call an API or authorize package execution. Go to Definition opens a verified Domain Pack module in its own file; imported source positions are never edits to the current document. The server captures configuration at startup and rereads selected metadata for each fresh analysis. Restart it after changing configuration. Analysis allows at most 256 resolution requests and 8 MiB of module text; each installed metadata reader also has an 8 MiB aggregate budget and a bounded catalog or directory inventory.

Compiler tools panel

Open Compiler tools in the Code toolbar. The panel makes no compiler requests until you choose an action.

  • Inspect syntax opens a source-linked tree. Select a node to reveal its source, attributes, and byte range. A named node can prepare a checked rename.
  • Inspect compiler AST opens the canonical owning compiler fields through the same native authoring worker. Original source remains separate for navigation. Inspection does not establish semantic validity or complete reconstruction.
  • Select any inspected node and choose Check supported operations to see rendering, name analysis/substitution, structural selection/rewriting, owning reconstruction and module admission support. Refusals include their reason. Answers identify the draft revision, representation and node path; inspect again after an edit. Availability does not establish semantic validity.
  • Select an expression and choose Explain expression for its binding, contextual type, known effects, direct source dependencies, and available units, bounds, and proofs. Each fact distinguishes established, partial, and unknown information. Go to definition follows a resolved source binding.
  • In Edit expression, prepare a replacement or extract a named function. Select a function declaration for Change function signature: rename or reorder its parameters, remove unused ones, or supply arguments for new ones. Preview each source change alongside the resulting compiler diagnostics. Staging rechecks the transaction against the original draft and applies all its edits together; a changed draft or invalid proposal cannot be staged.
  • Check source reports diagnostics and named dimension, bound, and proof facts without executing the model.
  • Choose an example to open a separate scratchpad. Run outputs evaluates only the named outputs in a fresh authoring model. Generate preview evaluates the generator output, admits a generated owning module or checks generated source, and optionally evaluates its named outputs in another fresh model. Owning output compiles directly without rendering source.
  • Inspect expansion reads an AST.EXPAND output and opens a viewer linking generated nodes and compiler findings to their template and inserted inputs. It checks declaration source without running the generated model. An expression requiring surrounding declarations is clearly labeled as such.
  • Review the proposed replacement and Stage replacement for review. This pauses automatic synchronization; save explicitly to apply it. A changed model draft invalidates the preview.

Editor completion, hover, and signature help include AST.QUOTE and dotted AST.* names. The guide and all examples are bundled for offline reading.

Authoring requests accept up to 64 KiB of source and 32 selected output names. A fresh native worker handles each request, with a 15-second wall deadline, a 2 MiB report limit, and at most two workers per host. Unix workers also have a CPU limit; Linux adds an address-space limit. The worker initializes no live model, connector, or import resolver. This is a deterministic language admission boundary, not an operating-system sandbox. Closing the panel cancels its response; an already-started server worker remains bounded by its deadline.

Quotation and reflection

formula = AST.QUOTE(quantity * unit_price)
original = AST.SOURCE(formula)
dependencies = AST.FREE_NAMES(formula)

price(quantity) = quantity * 7
definition = AST.DEFINITION(price)
definition_source = AST.SOURCE(definition)

Quotation captures the original expression owners without evaluating references or calls. AST.DEFINITION reads a local function, named assignment, or cell definition, including a definition written later in the source. The owning compiler returns that declaration’s actual owners: a Function or Assignment root, with its original body and declaration fields. Native source-boundary decisions keep a following assignment outside the reflected declaration. All materialized reflection requests in a compilation share one capture budget; a refused batch publishes no partial values. Quoting price returns only a reference. Imported definitions and computed targets are refused. Existing BODY, ARGS, and FUNCTION keep their existing record formats and callable metadata.

Reflected definitions depend on source. A formula edit in a model containing AST.DEFINITION requires ordinary whole-source compilation; partial formula splicing refuses rather than retaining an obsolete definition. Changing an input value does not change its authored definition.

Public data contract

AST.CHECK also accepts grid.compiler.artifact.v1 in every build. Its envelope has exactly schema, stage: "syntax", compilerContract: "grid.compiler.source.v3", and payload. The V3 contract labels are final: grid.compiler.source.v3 for syntax artifacts, grid.compiler.native-expression.v3 for native stage results, and grid.compiler.wasm.v4 / grid.view.local.wasm.v3 for the browser packages. The earlier labels grid.compiler.source.v3-dev1 and grid.compiler.wasm.v3 were never in a published release and are refused like any other unknown contract. The payload contains root: {syntax: N} and nodes, the generated codec records of the compiler's actual source owners. Admission checks the entire graph and uses the native compiler; no generated Grid source is emitted or reparsed. Typed integer fields accept exactly integral, in-range Grid numbers. Floating fields also accept finite Grid numbers and preserve their IEEE value, including negative zero; exact JSON integers that would lose precision are refused. Canonical floating output uses explicit bit records. Arbitrary JSON data stays unchanged. Unknown contracts, fields, invalid IDs and producer authority claims are refused. Raw JSON ingress also rejects duplicate decoded keys.

A genuinely imported function may declare RETURNS CompilerContribution<hir, expression>, mir or lir. Its result must be the closed record below. The existing Module byte codec supplies module; this profile does not introduce a second IR schema.

{
  "schema": "grid.compiler.native-expression.v1",
  "compilerContract": "grid.compiler.native-expression.v3",
  "stage": "hir",
  "category": "expression",
  "module": "<canonical lowercase hexadecimal Module bytes>",
  "export": 0
}

All six fields are required; additional fields and different contracts refuse. export is an integral in-range artifact-local callable ID, including Grid's floating-point representation of a whole number. The body must have a supported closed, pure callable interface with no captures or host requirements. Actual model dependencies, cell references and lexical shadowing supply the live hole types. Native checking derives body types and contracts, recomputes fingerprints and analysis hints, relocates IDs, joins at the declared boundary and performs mandatory final validation before the existing compiled-model executor can run it. Strictness must match the destination; ingress cannot weaken its semantics.

The initial expression profile bounds native bytes to 1 MiB, the expression pool to 16,384 records and metadata depth to 64. It rejects regions, handles, cells, streams, descriptors, custom dialects and unrelated module metadata before codec derivations. Nested duplicate JSON keys, unsupported opcodes and malformed section/count layouts refuse. Decoder scratch, native checking, joining and emission share the original cumulative operation allowance. A late cancellation publishes no compiled model, including after the resolver and handler have been dropped. This closed expression profile remains distinct from the checked general native module/dialect/effect receiving interfaces described below.

Owning Check and Meaning retain bounded contributionOrigins from that exact sealed input. Entries identify the real declaration, input units, material identity, source-arena expression and actual joining stage. Native entries retain actual immutable owner custody: admittedArenaExpressions lists current semantic arena sites for that owner, including imported destinations. Source-arena IDs remain qualified by source; a process-local pointer never appears in the report. nativeInterface and nativeContract describe that actual admitted owner. Source spans appear only when authentic source metadata exists. A native entry has no generated source definition; its body history is explicitly unavailable before its joining stage. The inventory describes compilation contributions and does not attribute an imported arena's IDs or a parent's proofs to a selected child. A failed compilation reports semantic admission as notEstablished. These observations cannot be decoded into provenance or execution authority.

Native generators decode with SourceModuleArtifact::from_json or from_text, then call compile_source_module_artifact_to_lir with the host resolver and symbolic context. That entry performs native admission before the sole lowering to a compiled model. The projected-tree compile_canonical_syntax_to_lir functions and CompilerRequest::CanonicalCheck are removed; ArtifactCheck checks actual module owners. The projected AdmissionSupport and ReconstructionSupport requests are removed; legacy projected capability discovery reports no compiler reconstruction or admission support and does not call the compiler service. Actual owning artifact capability discovery remains available. Hosts receiving ordinary Grid values use grid_runtime_core::compiler_value_json, the same bounded record/vector conversion as AST.CHECK, before decoding. Imports and symbolic identity come from the host. A successful AST.CHECK reports an artifactRevision, compilationRevision, and representation: "owning"; it does not execute the result or claim equivalent behavior. Complete FORMAT, PRESENT, and VALIDATE clauses retain their operands and lexical boundary in the owning artifact. Detached admission validates that boundary and runs the native duplicate, operand, range-eligibility, and message checks in order. Missing boundaries, malformed candidates, and unresolved source overlaps refuse admission; source locations or producer assertions cannot supply the missing structure. Source export and complete detached-source migration remain unfinished. The registered Grid expression-handler declaration is described above. Generated fields follow the actual owning native declarations. Inline records carry type, variant and fields; syntax-child handles refer into the enclosing artifact arena. Use traversal paths for occurrence selection and AST.AT to obtain a complete detached closure. Copying one node with its original handles into a different artifact does not produce a valid subtree. AST.NODE takes child artifacts and remaps their handles after checking the generated owner.

The inspection examples cover imports, unit productions, normalized type tags, declaration modifiers, presentation clauses, logical policies, graph queries, rules, TREE grammar records and contextual Views. They read owner fields directly. Numeric codec fields can contain exact IEEE-754 bit records; grammar fragments can contain UTF-8 byte vectors. These are compiler data, not display strings. Function type/effect/capture facts are obtained from separate semantic services and do not become part of the syntax owner schema.

AST.DEFINITION from whole-source owning compilation returns the same grid.compiler.inspection.v1 envelope as inspection and quotation. Detached constructed modules return a grid.compiler.artifact.v1 value without source metadata. Native binding resolution selects the declaration; artifact handles and locations cannot claim a binding.

Native module admission charges expanded logical path aliases to the same cumulative construction allowance before copying them. A small artifact that would produce excessive derived path storage is refused with GRID_SYNTAX_STORAGE. This includes chained aliases and repeated use in logical rules and queries; ordinary source compilation retains its existing semantics.

Portable View owners enforce the source grammar's BODY slot spelling and arity, foreign type-clause boundaries, and SURFACE declaration name spelling even for unused declarations. Type-clause scanning charges the selected construction allowance before allocating workspace. A tentative validation clause before VALIDATE RECORD is resolved against the actual next module declaration; producer metadata cannot authorize discarding it.

Fresh compiler consumers use V3 owners. The retained saved-definition/PART codecs and historical projection preserve versioned stored bytes and identities; their closed input families cannot authorize general module execution. AST.CHECK accepts owning modules, and new generators construct owning artifacts. Retained compatibility boundaries are recorded separately.

Construction and transformation

Checked source transactions

source = "price(quantity) = quantity * 7\nanswer = price(6)"
parsed = AST.PARSE(source)
proposal = AST.EDIT(source, {
  revision: parsed.sourceRevision,
  operation: {
    kind: "changeSignature",
    function: "price",
    parameters: [{ name: "items", from: "quantity" }]
  }
})
updated_source = AST.APPLY(source, proposal)

AST.EDIT(source, request) prepares a grid.syntax.transaction.v1 report. Replacement text and new signature argument text use the same actual owning expression grammar as AST.EXPRESSION. Recognition does not evaluate quoted code or resolve free names; validation of the complete edited program establishes their native context. Application reconstructs and recompiles the proposal before returning source. request contains revision and one operation:

Kind Fields Behavior
replaceExpression span, replacement Replace one exact retained expression with parsed expression text, parenthesized to preserve its surrounding precedence.
extractFunction span, name Move the selected expression into a function before its owning declaration, passing free value and lexical callable bindings explicitly.
renameBinding offset, newName Rename one identified source binding and its mapped uses; refuse incomplete inventories, capture or host declaration mismatch.
renameFunction function, newName Rename one local native callable and every identified direct caller, including unused bodies; refuse unresolved, alias, partial or reflection uses.
changeSignature function, parameters Edit one local function and every resolved direct caller, including nested calls.

Each signature parameter has name and exactly one of from (an old parameter) or argument (a new expression inserted at every caller). Existing arguments follow their old parameter identities when reordered. Parameter reads respect sequential LET and LAMBDA shadowing; capture and removal of a used parameter are refused. New argument text is interpreted in each caller's lexical scope. Untouched source stays byte-identical. Comments inside an extracted body move with that body; retained argument comments move with their argument. Deliberately removed expressions or parameters can remove comments within their edited ranges.

The report carries its request, original and updated source revisions, updatedSource, sorted non-overlapping edits, an explanation, focused preview entries, ok, resulting diagnostics, and validation. Invalid compiled proposals remain reviewable with ok: false. AST.APPLY reconstructs the proposal, verifies its edits, source identities, explanation and focused preview, and compiles it again. Both preparation and application reject a base with native compilation errors. The proposal binds baseCompilationRevision and updatedCompilationRevision to the actual resolved dependencies and compiler configuration. Changing an import can invalidate a proposal even when the root source bytes match.

It returns updated source text; it does not mutate a model. External success flags and diagnostic fields never authorize an application. Native hosts can use apply_source_edit_atomically_with_context while holding their document write guard: the exclusive source borrow spans revision comparison and candidate compilation, followed by one complete String replacement. Every refusal leaves the original source intact.

Native hosts can pass a SourceEditControl to prepare_source_edit_observed_with_context, apply_source_edit_observed_with_context, or apply_source_edit_atomically_observed_with_context. One finite, sticky allowance covers the base and candidate compilations together. A caller may select smaller work/byte allowances at ingress; it cannot replenish an active lease. The byte counter covers inspected/copied source text, not allocator capacity or RSS. Cancellation is checked before admission, after admission, before each actual optimizer pass, before emission and before the final source replacement. A synchronous parser, pass or host callback completes its current phase. AST/CANCELLED and operation-budget refusals leave source unchanged and remain terminal for that control. Ordinary compiler execution creates no edit control and uses its existing optimizer path; these checkpoints are selected by the checked-tool output target.

AST.RENAME retains its grid.syntax.edit.v1 display envelope and now includes a compiler-checked transaction. Pass that nested proposal to AST.APPLY for revision and dependency revalidation.

Compilation checks validity; it does not prove equivalent behavior. Extraction, argument reordering/removal, and newly supplied arguments can change evaluation order, effects, or reflection results. Every transaction explicitly reports that equivalence is not established.

Current refactorings require retained lexical scope. Imported definitions, partial/reflection/adapter uses of a changed function, and qualified, positional, or grammar expressions in an extracted or signature-edited body are refused. Expression replacement can still target an exact retained expression of those forms. The source must parse before preparation. Limits include 128 parameters, 4,096 edits/callers, 1 MiB source or replacement text, existing expression node/depth limits, and a 2 MiB report. These are explicit supported-operation limits, not claims that the entire language is refactorable.

Source-free category transformations

Owning AST.EDIT requests can select generated-owner occurrences using edits: {kind: "transformOccurrences", rules: [{selector, replacement}]}. Each rule selects the original input once using kinds, attributes, within and maxDepth. Supply a complete owning artifact as the replacement. Duplicate or ancestor/descendant matches refuse together. Every replacement is checked even when it has no match; generated destination roles and whole-module native compilation decide whether the transaction is valid.

AST.APPLY reconstructs the complete transaction, checks source-free input and dependency revisions and returns the candidate artifact. Native hosts can apply it atomically while holding their document lock. Cancellation and budget refusal preserve the original input. Compilation checks validity; it does not establish behavioral equivalence. See the owning transformation example for ordinary Grid construction, checking and application.

Constructing syntax

expression = AST.BINARY("*", AST.REFERENCE("quantity"), AST.LITERAL(7))
definition = AST.FUNCTION("price", ["quantity"], expression)
answer = AST.ASSIGN("total", AST.CALL("price", [AST.LITERAL(6)]))
generated_source = AST.RENDER(AST.MODULE([definition, answer]))
check = AST.CHECK(generated_source)

All convenience constructors and AST.NODE construct actual V3 owners as specified above. Their results compose directly with quotation and expansion. AST.SUBSTITUTE(tree, replacements) simultaneously replaces free names. It renames lambda and sequential LET binders, function parameters, and generated declaration names when necessary to prevent capture. Plain AST.ASSIGN, AST.FUNCTION, and AST.MODULE constructions share this support. Module names bind throughout the module, including forward and recursive references. Inserted expressions are never substituted again; unused or shadowed replacement keys do not rename declarations.

Declaration hygiene supports unqualified named bindings. Names containing digits must include an underscore to stay outside the compiler's spreadsheet-address syntax. Duplicate module names, qualified names, annotations, incomplete source projections, and other declaration families require compiler binding analysis. AST.CAPABILITIES reports these limits before transformation. Each replacement must be an expression, and combined input and expanded-name sizes are bounded.

Review generated declaration names before joining the result to other source: preventing capture can rename a module binding. Generated trees have no authored source spans. Use AST.RENAME or checked transactions for existing source declarations, preserving their annotations, comments, and formatting. Explicit templates extend this hygiene with named holes, list splicing, and traced origins.

Quoted templates and expansion origins

formula = AST.QUOTE(SUM(AST.SPLICE("prices")) * quantity + AST.HOLE("fee"))
expansion = AST.EXPAND(formula, {
  prices: [AST.QUOTE(3 + 4), AST.LITERAL(0)],
  fee: AST.QUOTE(5)
})
generated_source = expansion.generatedSource

AST.HOLE("name") denotes one expression, and AST.SPLICE("name") denotes a list of expressions in a call's arguments or an array row. They are captured unevaluated inside AST.QUOTE; calling them directly constructs the same marker syntax for use with AST.CALL, AST.FUNCTION, and other constructors. Bindings map case-sensitive labels of 1–128 UTF-8 bytes to one syntax value or a list of syntax values, respectively. Empty lists remove that list occurrence. Array row boundaries are retained. Missing, unused, mismatched, and misplaced bindings are refused. Fixed-arity operator operands, record keys and parameter names are not expression-splice positions. A declared slot can replace a module item or splice its item list using actual owning declarations, as shown in the category template.

grid.compiler.template.v1 declares slots separately from the owning artifact: {schema: "grid.compiler.template.v1", artifact, slots: [{path: [0], binding: "items", splice: true}]}. Paths select child occurrences in the original owner, not indexes in generated text. A single slot accepts one actual owner of the same root category. List slots require a true list destination: module items, positional call arguments (including lists containing named arguments), or array elements (including rows containing spreads). Named arguments and spread operands remain single owners and cannot themselves be list slots. Whole-module replacement is also supported. Overlapping paths, fractional indexes, incorrect categories and non-list splices are refused. Every inserted graph is decoded and structurally validated; a slot never fabricates a placeholder declaration or reparses text for admission. Module splicing preserves documentation attachment groups. Native callback parameters, DO/WHERE/USING bindings, comprehension generators and CTE names preserve capture avoidance. Contexts that require unavailable native module/import authority still refuse; slots do not grant that authority.

Expansion is simultaneous. It does not recursively expand marker calls supplied inside an input. Temporary hole names cannot collide with names in either the template or its inputs. The shared scope engine renames supported template binders to keep inserted free names free, including constructed module declarations, forward references, recursive calls, parameters, and sequential local bindings. The source-only and incomplete-scope restrictions above remain applicable.

The grid.syntax.expansion.v1 report contains template, bindings, detached syntax (an owning artifact), generatedSource, and origins. Each origin identifies a generated node path and UTF-8 generatedSpan, its template path and optional authored span, and, for inserted nodes, its binding label, optional zero-based list item, and input path/span. Repeated inputs have distinct generated occurrences. Original source stays in the retained template or binding, separate from generated syntax; generated nodes never claim authored source spans. Constructors detach child locations, so composed templates can expose a structural origin without authored text. Inputs made with quotation retain their exact input text and locations.

AST.EXPAND neither compiles nor runs generated code. In Code, choose the Quoted template example and Inspect expansion. Select a node or follow a compiler finding to compare its template, input, and generated text. Renamed bindings are shown explicitly. Declaration source is checked by the ordinary compiler; standalone expressions report that context is required. Successful checking does not establish runtime success or equivalent behavior. Inspection reconstructs the expansion from retained inputs instead of trusting supplied generated text, syntax, or origin claims. Generate preview also accepts an expansion report and applies the existing deterministic admission directly to its reconstructed owning module before optional execution. The authoring report also supplies compiler-generated occurrence rows for template, input and generated owners; the viewer does not reconstruct a legacy syntax tree or interpret owner handles.

Existing syntax depth/node budgets apply. Combined inputs are bounded to twice the syntax budget; output syntax and rendered source retain their 1 MiB limit. Origin allocation is bounded during construction, and the complete serialized expansion report, including retained inputs, is limited to 2 MiB. The editor worker's 64 KiB source and 15-second limits still apply. No automatic expansion is added to ordinary model compilation. The native inspect_expansion_node_observed(report, path, observer) API and worker {operation: "expansionNode", source, output, path} request reconstruct retained inputs and return the selected generated owner, template occurrence, input occurrence and generated text. Supplied generated text, syntax and origins are ignored. The node report uses grid.compiler.expansion-node.v1 and explicitly has semanticAdmission: false. Native hygiene across every category, origins preserved through every constructor, and expansion histories remain further work.

Public owning transformations keep one operation allowance across decoding, graph and role validation, retained copies, native import inspection and output. Logical values/entries, scalar bytes, repeated inspection work and requested workspace retain their separate limits; another phase cannot renew spent credit. Generated vector, text, optional and boxed buffers are charged before allocation. Borrowed validation and serialization of already retained owners spend inspection work and actual output storage rather than charging authored payload again. The complete serialized output still passes the original codec payload and depth bounds. Input, work and storage credit remain cumulative; cancellation and prior refusal remain attached to the original invocation. Raw JSON preflight meters decoded keys, duplicate checks and shape-derived array and map materialization before building a value. Report traversal and copying retain a charged depth-sized frontier. Complete report assembly checks exact escaped JSON bytes and composed nesting, including every retained input and origin. Native binding inventories and refactoring reports use the same complete report bound. Native refactoring indexes charge each deterministic lookup step; their declaration and scope identities still come from the native consumer. Private serialization extents never grant grammar or native admission.

Observed native entry points poll cancellation during proportional tool work, at host demands and immediately before publication. Refusal is sticky across later calls using the same caller observer. Source/owning inputs remain immutable and no partial rewrite or expansion is published. Host callbacks are synchronous and cooperative; a callback already running completes before the next checkpoint. Ordinary model compilation does not select this tooling ledger.

Selected native tools and compiler factories prepay lexical/encoding work in windows of at most 64 primitive steps. Native tool caller observers also prepay requested storage in windows of at most 1,024 bytes. Actual local payload, workspace and work ceilings remain exact; unused reservations stay spent. Host demands and final publication force a cancellation checkpoint. Raw owning readers retain their exact preflight callbacks rather than selecting these native-host windows.

Fresh encoder-produced scalar copies can reuse their private framing and exact serialized extent. A refactoring report composes that resource summary with its fully checked envelope and proof, preserving the complete 2 MiB and nesting bounds. Supplied reports still receive complete inspection. These private summaries contain no source, binding or execution authority; unchanged native validation and the general encoder remain available for every other shape.

Rendering preserves stored authored numeric spelling. Synthesized real numbers in expression fragments retain their historical scientific notation. Complete module emission uses canonical real spelling with a decimal point or exponent. The grammar root selects this formatting policy once; neither form grants an exact-integer origin or authored lexical custody.

Bulk selection and structural rewrites

formula = AST.QUOTE(unit_price * quantity + delivery_fee)
references = AST.SELECT(formula, { kinds: ["Atom"] })
support = AST.CAPABILITIES(formula, [])

# Paths refer to occurrences in the original formula.
revised = AST.REWRITE(formula, [
  { path: [0, 0], replacement: AST.LITERAL(7) },
  { path: [1], replacement: AST.LITERAL(5) }
])
revised_source = AST.RENDER(revised)

AST.SELECT(syntax, selector) returns flat rows in source-tree preorder, with the same path, kind, attributes, span, and childCount fields as AST.WALK. Owning rows also identify their generated variant and local node handle; kinds matches the generated kind or variant (for example Atom or Binary), and attributes matches generated codec fields. A selector can specify kinds, exact attributes, a within path, and maxDepth relative to that subtree. Omitted filters match everything; maxDepth: 0 selects only the subtree root. Returned paths remain absolute in the original tree. Unknown selector fields are errors. A report exceeding the 1 MiB logical output budget is refused; narrow the selector to inspect a large tree in bounded sections.

AST.AT and AST.WALK admit external syntax once per call before extracting or visiting nodes. For owning artifacts and quotation reports, AST.AT returns a detached minimal owner closure. Source text and authored spans remain in the separate inspection report. For many lookups over one tree, prefer AST.SELECT: it admits and traverses the tree once, returning paths and compact node summaries without repeating the whole-tree validation for each path.

AST.REWRITE(syntax, edits) applies a batch of {path, replacement} records simultaneously. Input order does not matter; replacements are not revisited. Duplicate and ancestor/descendant paths are refused, as are nonexistent paths, invalid parent shapes, and combined or resulting budget excess. The original tree stays unchanged. The result has no retained source or authored spans. This is structural rewriting: it can change bindings and behavior. Use AST.SUBSTITUTE for capture-avoiding free-name substitution and compiler-checked source edits for preserving surrounding comments and formatting.

AST.CAPABILITIES(syntax, path) reports render, freeNames, and substitute support for that subtree. Each has supported and, on refusal, a reason and the absolute path of the first unsupported node. select and rewrite report structural operation support; sourceSpan is the retained authored range, if any. Support describes node forms, not unlimited resources or the validity of a future replacement: normal argument, scope, and output limits still apply. Capability discovery uses the renderer and scope policies without attempting to render or substitute every subtree.

For actual artifacts, compilerReconstruct confirms the selected closure has passed generated codec, graph and grammatical-role validation. compilerAdmit is available only at the complete module root. It describes the native operation; it does not run semantic checks, grant imports, certify types/effects or prove behavior equivalence. Rendering support is checked over the selected subtree; binding support likewise depends on the selected owners. Source locations appear only in the revision-bound inspection report; portable artifact traversal supplies no spans.

These bulk operations validate external owners once per request. Traversal does not validate the whole graph again for each selected node. A successful structural query supplies no semantic or execution authority.

AST.RENDER emits supported expression forms, ordinary parsed named assignments, and constructed assignments, functions, and modules. It refuses source-only declarations or qualified references whose modifiers or spelling it cannot safely reproduce. AST.SOURCE returns retained text; it does not render an edited tree. This distinction preserves scheduling, types, comments, and source forms outside the emitter's supported subset. Rendering is not compilation or semantic-equivalence proof. String emission uses Grid’s own escape rules, preserving Unicode and control characters when reparsed. Object keys use Grid’s separate raw-key convention. Keys containing quotes or backslashes are explicitly refused by rendering and capability discovery because the emitter cannot reproduce them safely.

Compiler services

Function Result
AST.EXPRESSION(text) Actual expression owners with separate source, revision and occurrence metadata
AST.PARSE(text) Actual module owners with separate source, revision and occurrence metadata; malformed source refuses
AST.ANALYZE(text) Source symbols, completeness flags, function types, effects, contracts, and captures
AST.CHECK(text_or_owning_module) Ordinary compilation diagnostics and facts; owning modules report their exact artifact revision
AST.MEANING(text, selection) Revision-bound expression binding, contextual type, effects, direct dependencies, and available compiled facts
AST.MEANING(module[, selectionOrBatch]) Native root inventory or bounded compilation-bound Meaning queries over owning source data
AST.RENAME(text, byte_offset, new_name) Original source, updated source, and checked edits

Rename preserves untouched text and refuses ambiguous or unsupported scope, collisions, and capture. Reports expose completeness rather than claiming every source construct is covered. Compilation checks do not execute the model. The check report's sorted namedFacts rows associate inferred dimensions, bounds, and validation proofs with source names. A missing fact is null; inference has not established it. Raw namedWires identifiers are local to that compilation and must not be stored as stable source identities.

Expression meaning and source revisions

source = "price = 7\ntotal = price * 6"
parsed = AST.PARSE(source)
expressions = AST.SELECT(parsed, { kinds: ["Binary"] })
selected = INDEX(expressions, 1)
meaning = AST.MEANING(source, {
  revision: parsed.sourceRevision,
  span: selected.span
})

Parse, analysis, and check reports include sourceRevision, a sha256: identity of the exact UTF-8 source bytes, including comments and whitespace. The source-text overload of AST.MEANING requires that revision plus the exact nonempty byte range of one retained expression. A changed source returns AST/STALE; invalid UTF-8 boundaries, fractional offsets, ambiguous ranges, and declaration selections are refused. Revisions identify content, not compiler versions or permission to mutate a model. Tree paths and compiler arena IDs are not revision identities.

Source meaning now borrows the exact program admitted by the production compiler before lowering. Binding/type/dependency inspection and compiled diagnostics and assignment facts no longer come from separate admissions. The native compiler_tools::expression_meaning_with_context entry accepts the host's existing resolver and symbolic context; a fresh query observes changed imports. Stale or invalid byte selections are refused before resolution. Semantic inspection analyzes the admitted program without constructing View editing catalogs. AST.CHECK and compiled AST.MEANING reports now also include compilationRevision, an opaque 64-character hexadecimal identity. It binds the versioned compiler contract and selected configuration, the root material, actual resolver observations (including contextual paths and package records), admitted symbolic authority and expansion receipts, the emitted compiled model and diagnostics. Check and meaning selections over the same successful compilation share this identity. Changes to unused or transitive imported source and native owning imports are observed during the original admission, without a second resolver pass. A failed native import records its refusal; an inspection allowance failure returns AST/REVISION_LIMIT instead of an incomplete revision.

sourceRevision remains the exact source-byte selection identity. artifactRevision identifies admitted root material; selected native construction can bind captured import and package material into that identity. It is not a complete dependency revision. compilationRevision is compiler inspection data: it is not a stored replay snapshot, a build SHA, portable cache authorization, or an execution grant. Native hosts can use check_source_with_context, check_artifact_with_context, and expression_meaning_with_context with their existing authorized resolver and symbolic context.

Owning artifact Check selects the same native Grid handler host as source Check and source/owning compilation. It executes declared handlers during compilation under their shared operation allowance, observes each authorized import once, and binds the admitted results into the compilation revision. A supplied handler host keeps precedence, including its refusals; invalid handler results are refused by the same native admission. Check does not install or execute the resulting model. Inspection and structural artifact decoding do not invoke these handlers.

A compiler-tag handler can return its existing {code, message} refusal, or {code, message, segment, span: {start, end}} to identify a UTF-8 byte range inside one decoded literal segment. Segment numbering is zero-based; holes separate segments. Native recognition maps a valid range back to the exact submitted payload, including escaped characters, Unicode and block literals. Malformed or mid-character ranges are refused. Only authentic recognition retains this source map; transported/detached owner data cannot invent it and uses the outer template location. Imported payloads retain their source path.

The built-in AST.CHECK(artifact) entry uses the same shipped module resolver as AST.CHECK(source), including the existing shipped path aliases. Explicit native context entries use exactly their supplied resolver; passing no resolver does not acquire the default. Neither entry resolves arbitrary external modules.

Ordinary source compilation accepts authorized owning dependencies returned by ModuleResolver::resolve_compiler_input. The first actual owning response selects one bounded construction context for the source root and its mixed source/owning closure. It retains genuine source bytes, owning identities, native import paths, prepared View locks and extension manifests without another host read. Changed material and exhausted construction allowances refuse before further host access. Imports in either order, transitive imports and repeated aliases share native admission and the existing compiled-model executor. Explicit source-only replay capture still refuses owning material; an inspection report cannot manufacture import authority. Native construction also accepts API service descriptors from the authorized ModuleResolver::resolve_api_service callback. It records bounded fingerprints of the actual descriptors and binds them into construction identity. Changed or revoked repeated inputs, oversized records and exhausted inventories refuse before subsequent host calls. Explicit source capture and replay continue to refuse API packages; descriptor custody grants no connection or execution rights.

API calls retain an exact native site binding through function and value imports, compound placeholders and pipes. Imported functions keep their defining service even when a caller reuses the same alias for another service. Direct calls and retained function bodies emit the same API request metadata through the existing compiled-model executor. Callable effect inference and traversal cardinality follow these native bindings, preserving formula restrictions and the existing effect traversal. API arguments compose with native callables and extension argument/result cells. The former root-wide API lookup by alias is removed.

Callable expressions also compose with extension extraction. The compiler retains native callable identities in synthetic argument and seed cells and lowers the actual rewritten result consumer. Callable bodies are neither emitted as source nor copied into a compatibility evaluator. Existing effectful and seeded package contracts remain in force.

Revision observation is selected only for compiler tools. One query bounds its resolver calls at 1,024, hashed input/output bytes at 64 MiB, serialization writes at 1,048,576 and JSON nesting at the existing syntax depth. Owning observations share a separate native inspection allowance across the query. These are logical inspection bounds, not complete compiler peak-memory or elapsed-time guarantees. Native hosts can now call compiler_tools::compile_source_snapshot_with_context to retain one SourceCompilationSnapshot. It owns the actual admitted native program, source bytes, compilation revision and compiled check facts. check() borrows its report; meaning(selection) queries that retained program after the original source buffer and resolver have been dropped. Imports, handlers and lowering are not repeated. A later resolver change affects a new snapshot, while old queries retain their original facts and identity. Selections still require the exact source revision and valid UTF-8 byte boundaries.

Successful and refused Process selection retain the actual program. Failed compilation retains diagnostics and withholds successful-looking inference. Exact assignment proofs remain attached only to their owning expression. Ordinary compilation selects no retention. The snapshot is immutable native inspection data with private fields; it has no deserializer, executable handle or mutable program access. This does not introduce external hir/mir/lir ingress.

Grid can inspect the same source-free program with AST.MEANING(module), where module is a detached owning module from AST.MODULE or AST.PARSE(text, "artifact"). The result contains ok, diagnostics, compilationRevision and roots. Choose a root by its description and pass { revision: compilationRevision, root: rootIndex, children: [] } as the second argument to inspect it. Child indices are zero-based native operands. Passing an array of selections returns { compilationRevision, meanings } in request order. See the complete owning Meaning example.

Each call performs current host admission, including authorized imports and handlers. A batch shares that one admission across all its queries. The root inventory and a later query are separate calls; a changed dependency between them refuses the old revision. There is no serialized snapshot, executable handle, source reconstruction or retained resolver. The on-demand compiler worker accepts the equivalent artifactMeaning request with artifact and an optional selection object or array. Code's existing source selection UI keeps its source-based request.

Selections require a compiler-produced 64-character lowercase hex revision, whole-number root/child indices below 65,536 and at most 128 child steps. Malformed selections are refused before host resolution. Batches contain 1–32 selections, share a maximum of 65,536 admitted-program-node/query pairs, and produce at most 2 MiB total JSON. The conservative node charge includes the whole admitted arena and callable definitions for each query, even for a leaf. A failed compilation exposes diagnostics and withholds successful facts. These bounds describe tooling work, not product-wide physical-cost acceptance.

Native hosts can also call compiler_tools::compile_owning_snapshot_with_context with a SourceModuleArtifact JSON value and their existing resolver/context. The resulting OwningCompilationSnapshot retains the actual native program without source text. check() returns the same result and compilation revision as check_artifact_with_context. roots() lists admitted statement values, function bodies and View expressions. Query a root with NativeMeaningSelection containing that compilation revision, the root index, and a children path in operand order. An empty path selects the root; [0] selects its first operand. These paths identify occurrences in this snapshot's semantic program. They are not source-artifact node IDs, source locations or executable handles.

The owning snapshot indexes native model roots and capture uses once. Queries use resolved callable targets, capture slots, parameter identities and sequential LET/LAMBDA scopes. Generated handler calls use their admitted callable target for type inference; textual names cannot replace that binding. Imported definitions retain their own callable scope. A changed artifact, resolved import or compiler configuration produces a different revision and rejects an old selection. Queries retain no resolver and cannot re-run imports, handlers or lowering. Assignment bounds and proofs are reported only for the exact selected assignment root. No parent proof is copied onto a child occurrence.

Native reports use grid.compiler.meaning.v1; the existing source API keeps grid.syntax.meaning.v1. Native selections have no source span. Native expressions whose address binding, View scope, TAG or Process type obligations are not retained explicitly report partial or unknown facts. Generic CHOICE queries use admitted schemas and the same immutable source binding rule as compilation; reactive defaults do not establish nominal types. Contextual inference still runs at query time. Selected snapshots expose compiler_passes(); owning root inventories and Meaning responses carry compilerPasses. This bounded report retains the actual optimizer order, outcomes, effective declared invalidations, source-position policy and producing dimensional/bounds/validation facts. Bounds inference records the reads, exact IEEE-754 interval endpoint bits, validation contracts/verdicts and cycle cuts used during that same pass invocation. Its MIR attributes describe the bounds-pass representation, not rewritten final MIR. The graphs are descriptive evidence, not replayable proof or execution authority. Dimensional inference retains actual call/parent identities, MIR nodes, cell reads, memo reuse, raw/resolved types and unification outcomes from the same invocation. Pooled numeric literals can create separate polymorphic variables. Currency axes and rational exponents remain exact; temperature helper internals and unifier union-find transitions are explicitly unrecorded. The ordinary dimensional pass uses a zero-sized disabled recorder; selected retention is bounded to 65,536 events, depth 128 and 2 MiB, with no partial successful report on exhaustion. An unvalidated reactive input remains unbounded despite a constant default. Ordinary Check retains its existing shape and selects no observer; ordinary bounds inference has a zero-sized disabled recorder. Selected retention is bounded to 256 passes, 65,536 interval nodes/edges, the existing depth limit and a 2 MiB report; exhaustion returns no partial successful report. Compilation rejection labels observed facts notEstablished for semantic admission. Meaning queries reuse the immutable final compiler capture, with revision-bound source-owner and semantic occurrence identities. Only actual, uninvalidated producing proofs are reported as established; dynamic facts and unproduced proofs remain explicitly partial or withheld. Inspecting those facts does not grant native contribution or receiving-host authority. Physical-cost acceptance is recorded separately from the semantic contract.

Meaning reports have schema: "grid.syntax.meaning.v1", sourceRevision, compilationRevision, span, selected source, ordinary compilation diagnostics, and ok. Their binding, type, effects, dependencies, units, bounds, and proofs fields carry status and value. Status is known, partial, unknown, or notApplicable; unknown facts include a reason.

Binding queries use resolved callable targets and the source index, including function parameters and sequential lexical scopes. Contextual type queries use the existing inferencer and finalized function schemes. They retain unresolved variables and any as partial information. Enclosing higher-order constraints, TAG/Process obligations, and some lowered scopes are not reconstructed. There is no inference from the current runtime value. View expressions parsed by compiler lowering are selectable through the same revision-bound query; their nested expressions use the compiler's retained expression handles. Unclassified View source fragments do not become selectable expressions through this route. Surface-scoped View locals resolve through the compiler's admitted local records, including their declaration span and stable browser binding identity. Their type report reuses the compiler's View initializer inference and remains partial because browser actions can later change a local. Instance-scoped element and row bindings can vary across uses of the same source span and remain unresolved when no unique source binding can be established.

Effects include classified expression effects and named-callee effects. An empty partial list does not establish purity. Dependencies include resolved direct source references. When an explicit cell or rectangular range has no source definition, the compiler still reports its canonical target and source uses with referencesComplete: false; the dependency status remains partial. Relative and implicit references remain partial. This is not a transitive runtime dependency graph. Unit, bound, and validation-proof facts currently attach only to an exact, unique named-assignment value for which the ordinary compiler retained that fact. A fact about a whole formula is never attributed to one of its child expressions. Failed compilation withholds semantic type/effect/proof facts.

The Code inspector requests these facts only when Explain expression is selected. It preserves the syntax tree, labels old-draft reports, and disables navigation until current source is inspected again. All work remains in the bounded authoring worker; explaining an expression does not execute it.

These services require a host that installs the compiler-tools service. Grid's native Grid service installs its existing compiler at startup. Bare embedded compiled formula runtimes can use syntax data operations and must explicitly install that service to parse or check source; otherwise those calls return AST/UNAVAILABLE. Requests contain source, never model handles, import resolvers, files, network credentials, or mutation grants. Source imports that require a resolver fail through ordinary compiler diagnostics.

Grid-authored analyzers

An analyzer is an ordinary one-argument Grid function receiving model source as text. It returns {sourceRevision, diagnostics}. Each diagnostic has code, severity (error, warning, or info), message, a UTF-8 byte span, and optional fixes. A fix contains title and an operation accepted by AST.EDIT.

AST.DIAGNOSTICS(source, report) validates and normalizes this data against the exact source revision. Its schema is grid.analyzer.diagnostics.v1. It does not claim compiler validity, establish proofs, execute the inspected model, or apply suggested changes. Unknown fields, stale revisions, invalid UTF-8 ranges, and unsupported fix requests are refused. Diagnostics may use an empty range; expression-edit ranges must be nonempty.

The effects analyzer inspects actual function owners and joins their source locations with the compiler's separate classified function effects. Its suggested blank placeholder changes behavior and must be reviewed. An empty effect list or a clean analyzer report does not establish purity or completeness of compiler analysis.

In Code, open Compiler tools → Analyze the model with Grid, load the example or enter an analyzer, and choose Run analyzer. The analyzer program is kept separately from the model draft. Findings appear in the normal Problems list with their analyzer origin. A finding without a valid source location remains in Problems, including its suggested fixes; only a valid location supplies an editor marker or source jump. The native service prepares each suggestion against that exact payload and compilation context, attaching a compiler-checked transaction or an individual refusal. Analyzer-supplied transaction fields are discarded and checked afresh. Review fix opens that transaction's focused preview; older reports request preparation on review. Staging rechecks that transaction and the unchanged draft; saving remains explicit. Changing the model hides old findings. Refreshing its dependency environment or replacing its native document ownership also revokes old findings and checked previews, even if the source text is unchanged. Canceled or old-context responses cannot supply locations or stage edits for the current source. Source and analyzer drafts remain available. Findings do not control Save.

Runs are explicit and source-only. Each source and analyzer is limited to 64 KiB at the worker boundary; the existing deterministic staging admission, two-worker cap, and 15-second deadline apply. The driver supplies fresh bindings for source-as-data and the result, projects ordinary Grid records through the existing compiler data converter, and independently validates the report before attaching checked suggestions and the analyzer's entry name and source revision. There is no filesystem, import resolver, network credential, or live-model mutation grant.

Reports allow at most 256 diagnostics, 8 fixes per diagnostic and 256 fixes in total, within the 2 MiB report budget. Codes use 1–64 ASCII letters, digits, underscores, hyphens or dots; messages have at most 4,096 bytes and fix titles 256 bytes. Preparing a transaction checks a complete candidate without applying it; its ok: false result remains reviewable. One refused suggestion does not erase its finding or other fixes. Cancellation or allowance exhaustion refuses the whole operation without refreshing its budget. Suggested changes remain inert until explicit staging. This version runs one selected analyzer against one source revision; it does not provide analyzer dependency scheduling or cross-module fact caching.

Working examples

The repository's examples/compiler-tools/ directory includes executable Grid models and reusable analyzers:

  • Effects analyzer supplies source-linked findings and a reviewable edit suggestion.
  • Model auditor lists function signatures, separates pure and effectful functions, and inspects formula references without executing the inspected model.
  • Checked refactoring renames a binding while preserving comments and demonstrates lexical substitution that avoids capture.
  • Invoice language parses buy 6 at 7 using an authored grammar, finds its quantity and price by name with a PATTERN and TREE.MATCH, and constructs source that computes invoice_total = 42.
  • Generate prices constructs a function and call yielding total = 42.
  • Model family generates three calculations yielding 42, 54, and 66.
  • Quoted template fills a formula's expression hole and argument splice, traces its inputs, and generates a calculation yielding 47.
  • Constant IF preserves eager reads and conversion warnings while allowing closed unused numeric and Boolean work to be removed.

The invoice example uses the grammar's existing native TREE authority. It explicitly translates terminal data into Grid syntax. An AST record cannot forge a native TREE value, grammar authority, rewrite certificate, or proof that a Grid program preserves meaning. General Grid AST-to-TREE conversion and automatic compiler rewrite hooks are not part of this interface.

Explicit staged generation

The maintained native example provides a concrete two-stage authoring tool:

cargo run --manifest-path rust/Cargo.toml -p grid-runtime-core \
  --example compiler_tools -- generate \
  examples/compiler-tools/model-family.grid generated_source total_7 total_9 total_11

It executes the generator through compiled formula, reads its generated_source result, checks the emitted source with the same compiler, and executes the explicitly requested symbols in a fresh compiled formula model. The JSON report includes source text, both source hashes, compilation size, and the results. Omit the trailing symbol names to compile without executing the generated model.

A generator may instead return grid.compiler.artifact.v1 module data built with AST.NODE. The same isolated worker decodes and admits those owners, applies its existing deterministic subset restrictions and compiles directly to a compiled model. Its report contains generatedArtifact, generatedArtifactSha256, lirBytes, executed and values; it does not invent generatedSource. A generated input, Process, effect or import receives the same worker refusal as source input. Ordinary host admission remains the route for models requiring those capabilities.

The example admits a documented subset of deterministic named calculations, local functions, collection helpers, and AST operations. It rejects external effects, addressed/model state, unsupported calls, and more than 4,096 expression nodes or 64 KiB of source at either stage; generated artifacts have the same 64 KiB limit measured over their encoded JSON, including escapes. Its allowlist is selected by the compiler-tools worker; a rejection does not mean the construct is unavailable in ordinary Grid models.

For grammars and trees, the worker admits PARSE, PARSE_RESULT_TREE, TREE.AT, TREE.TERMINAL, TREE.CONSTRUCTOR and TREE.MATCH. PATTERN is the only admitted tree declaration, with MATCH and WITHOUT clauses; MODULO and Predicate-backed WHEN clauses, and the THEORY, ALGEBRA, TRANSFORM, TRANSLATE, SOLVER and THEOREM declarations, are refused. TREE.MATCH takes its result and work limits as whole-number literals of at most 1,000 results and 1,000,000 work units, so admission bounds the match before it runs.

An explicit authoring command or panel action starts a worker process. The parent refuses output after 15 seconds or a worker failure. GRID_COMPILER_TOOLS_TIMEOUT_MS can lower that bound to between 1 and 15,000 milliseconds. Unix workers also install a 10-second CPU limit; Linux additionally installs a 4 GiB address-space limit. macOS does not support that address-space limit. Other platforms have the parent wall-time bound. These limits do not constitute an operating-system security sandbox. No output is accepted until both stages succeed, and generated code gains no import resolver, external effects, live-model state, or mutation authority. This is a runnable authoring example, not automatic macro expansion during ordinary compilation. Application hosts can compose the same compiler and compiled formula APIs at their own explicitly authorized staging boundary.

Remaining migration

The default, authored and canonical public inspection routes and structured checking use actual source owners. The editor and checked-in examples share that contract. Quotation, constructors and template expansion also use actual owners. The Grid/editor projected inspection routes are retired. Whole-module definition reflection uses native declaration identities and actual owners. The live editor requires grid.compiler.inspection.v1 owner occurrences and refuses old syntax.root reports. It reads function fields, binding identities and rename locations from those owners. General V2 tree renderers and broad legacy projectors/constructors require explicit historical or private test selection.

Fresh Definition/PART composition consumes V3 owners directly. Its versioned publication writer still produces the fixed stored format and identity; that projection is never decoded back into fresh compiler input. Archived graph readers remain at explicit retained ingress. New Ledger source bundles retain V3 owning inspection; historical sidecar verification selects the old capture format for byte agreement through the same native compiler. The retained codecs, their selections and every external production compatibility edge are recorded separately.

An original-case review traces all 58 distinct failures in the original reader/reconstruction cohorts to owning successors or explicitly selected historical controls. All 58 now have verified repairs. The original 129-node unary fixture also passes owning construction and native expression insertion under its original 128-child-edge syntax contract; the separate general graph API retains its 128-node contract. The 130-node syntax control still refuses. Historical View reports preserve the original malformed or unresolved outline boundaries as descriptive data, never execution authority. Original fixtures, numeric limits and retained failure receipts are unchanged. The complete compiler work also includes later-stage contributions and current end-to-end correctness and Performance acceptance.

The private native editor now carries actual child/column selections into outline positions, contract values, slot blocks and action requirements. Builtin inferred and embedded controls, availability groups and region layouts borrow those same actual owners. Inferred embedded/composite continuation grammar survives owning transport and reaches the existing native reducer. A property edit uses the same operation for original and candidate validation. It retains the genuine source context for native actions. Local declaration/use observations now connect default fields, validation clauses, direct bindings and caller arguments. Dotted Local fields retain their original member endpoints; escaped records, unsupported contexts and compiler errors keep explicit review links. Sensitive or ambiguous defaults do not acquire field controls. Model-member references use their original base token, while native LET/LAMBDA/MATCH declarations stay separate from reads. Repeated controls reuse one declaration inventory and preserve the existing 512 KiB aggregate reference allowance. This is internal migration work. The private editor and imported View libraries now use complete native module recognition/admission, retaining actual model declaration and expression relations. Their separate statement/scanner and View-only rebuild paths are removed. Direct named/cell input controls now use these native publications for record defaults and validation. Original trivia also preserves comments after expression-valued record defaults. Actual accepted clauses and lexer trivia preserve comment boundaries; copied or foreign declaration records cannot select edit sites. Model aliases and sheet-qualified inputs now share the native address-alias traversal; duplicate or foreign intermediate declarations cannot acquire edit ownership. Native row admissions now connect containing declarations to columns and actions, and component instantiations expose their consumed Local declarations. Imported locals retain their owning-source boundary. Stored/computed column references use actual native interpretation; identical component interfaces can share a catalog ID without sharing declaration identity. Validation edits now check the accepted clause’s actual native references, with lexical scope observations that preserve the compiled expression. Native root field rules and private record-contract applications retain schema-removal protection; imported rules link the caller’s application. Native model field renames now follow admitted aliases and member results to original key tokens. One transaction allowance covers both analyses and verifies all field uses and defaults. Dynamic keys, record escapes, reflection and unported write/shared contexts retain explicit refusals. Native analysis no longer lets the legacy refactor collector overwrite its metadata. The public editor uses native source/binding inventories and checked transactions. Source-linked and detached owning transactions retain their respective revision and host-context checks.

Stored native definition publications use the complete V3 recognizer for new capture. A bounded structural conversion preserves their existing wire identity and pure-definition restrictions. The separate R1 input recognizer and its parser storage mode are removed; the frozen decoder remains for stored data. This conversion does not emit or reparse Grid source. General compiler tooling uses SourceModuleArtifact instead of the retained-definition format. Legacy general module reconstruction (CanonicalModule, import_canonical_module, import_validated_canonical_module, and reconstruct_canonical_module) is removed. parse_canonical_module remains a historical inspection projection without an execution entry. Historical Ledger verification calls the versioned syntax::historical_projection::{capture_v1, capture_v1_with_resolver} adapter; its old general capture report entry points are removed.

The standalone native CompilerDeclaration::from_syntax_with_source method and ReconstructedDeclaration handle are also removed. Generators use SourceModuleArtifact to own and admit View operands, function bodies and other contextual declarations directly. CompilerDeclaration::from_syntax remains only in private frozen-format tests. Production retained records use bounded codec functions; a span-owned semantic operand requires the V3 owning artifact rather than reconstructed source. The stored definition codec and historical Ledger projection retain their existing formats. The old expression reader no longer emits and reparses contextual records or defers calls through generated source. For example, a projected numeric-sequence record is refused by that reader; its V3 owning artifact admits the sequence directly through the native compiler. The emitter trait, generated callbacks, View and Process source generators, grammar-body materializers, and temporary source buffers are removed. Diagnostic formatting and historical descriptive projection remain separate from native admission. Fresh V2 consumer retirement is complete; the versioned stored-format and historical boundaries remain explicitly isolated in the retirement inventory.

Selected native composition and input-state migration compare borrowed compiler statements directly. Equality preserves declaration policies and types, exact numeric origins, references, operators, and ordered aggregate structure; source locations and arena ordinals do not determine the contract. Comparisons are bounded and never construct projected syntax or new execution authority. Existing host preflight, lineage, permissions, aliases, predicates and persisted-state checks remain required. Stored publication digests and their frozen codec are unchanged.

Owning module admission can use the host's existing extension resolver and literal compiler. Inspection and JSON decoding do not invoke providers. Construction retains exact manifest fingerprints together with the canonical importing context and binds them into the native input identity. Repeated requests must retain the same manifest; changed or revoked manifests and exhausted bounds refuse before literal expansion. This native construction material cannot be replayed as a Process source snapshot. Explicit source capture keeps its capability refusal. The consuming native compilation entry expands literals just as ordinary source compilation does. Imported templates retain their defining delimiter context; cold compiled-model loading and live input updates use the expanded native expressions without invoking the provider again. API services use the same bounded native construction described above. Broader legacy retirement remains unfinished.

The old syntax::native_inputs development entry is removed. Stored-definition clients use native_definitions::retained::{capture, admit, decode}; this codec accepts only definitions and PART data, with no resolver or USE decoding. V3 module artifacts retain actual import owners and obtain import authority from the host when admitted. A PART artifact still requires authenticated native composition.

Selected native definition inputs also retain their actual PART declarations. Detached admission preserves those membership contracts and still performs native duplicate checks. A retained declaration alone grants no composition or execution authority.

Inferred View placements retain their rendered and Table child productions until native presentation selects the appropriate grammar. Artifact decoding does not infer that selection from a source span or a producer-supplied type. The selected native consumer validates columns, filters, keys and empty sentences; invalid or mismatched owners refuse. AS labels remain owning operands through native presentation, including embedded Map titles and button actions. Ordinary Views retain their established source capacity; extra alternative-recognition work uses a separate bounded allowance without changing language limits.

Direct named placements preserve their established document IDs after owning transport. Transparent grouping does not change the name; repeated placements use the existing sibling suffix. Compound expressions retain structural identity. These keys come from actual syntax owners, not source locations or supplied IDs.

Private native drawing structural edits now preserve comments and child geometry under one operation. Ungroup distributes only literal transforms; computed transforms and behavior remain with their Group. The native compiler and existing public outline also recognize drawing from phrases through their element contract while retaining named-picker behavior. Private native numeric gestures now use one original analysis and one combined candidate analysis across every selected property. Genuine literal syntax and all actual native occurrences must agree; folded bindings and computed geometry remain expression-owned. Original comments and CRLF survive repeated edits. Inline/argument gestures, complete native transaction routing and public native editor activation remain unfinished.

Private native text and expression edits now retain genuine source operands through candidate verification. Page titles retarget CHECKs through original command owners, including references before the page; page paths and drawer titles preserve their admitted metadata. Bare subject rebinding follows the native name/value grammar without turning grouped or computed expressions into symbols. All analysis, lookup and source construction use the original operation. Native page-name changes now update genuine GO/NEXT and CHECK owners while preserving titles, routes, parameters and atomic undo. Actual native navigation verification covers imported expansions and rejects changed destinations. No source replay or document-string decoding recovers those references. Native outline and page duplicate/delete/reorder transactions now preserve source roles, shared declarations and atomic undo under that same operation. Structural edits, moves and wraps reuse an expanded inline region's retained native analysis. Nested array members retain their original header observations. Native insertion catalogs and checked insertions now use the selected View's actual contracts and argument owners. Recorded CHECK authoring validates native keys, instance targets and nested row contexts under the same operation. Tree settings and ancestor row references retain their meaning without source metadata. Native scalar option transactions now use actual standard, inferred, imported and embedded contracts. Component arguments/defaults and shared options preserve caller content, guards and neighboring source under one original/candidate operation. Native event, slot, caller-content and appearance transactions now use those same owners and retain inline expansion, payload bytes, lexical scope and Table column roles. Imported declaration coverage, action-value diagnostics and named-slot completion use the original native records. Exhausted operation allowances withhold completion output. Root theme edits now verify the native theme inventory and share bounded planning with the existing editor; drawing option requests use the native grouping transaction. Native validation, record-default and Table-column requests now authenticate original and candidate source owners under one operation. Action requirements and availability groups use the same native projection's editing permissions, including imported controls, named events and declaration-scope previews. Inline expansion reuses its retained analysis and preserves one undo edit. Comments, multiline payloads, refusal branches and neighboring source remain part of candidate verification. Explicit admitted Tables retain their existing editing exception; fabricated controls cannot authorize a protected picker. Local record references now distinguish actual row owners, private writes and literal tag directives. Unused bare values defer namespace ambiguity until the declaration is reached. Record-schema add/remove requests and renames now authenticate the original and candidate members. Module FIELD targets retain their original quoted/dot key tokens in the selected observer, resolve actual model aliases, and rename both validation targets and operand references. A component's own private record can be renamed when its actual subject is consumed by an inferred Form; other whole-record consumers retain refusal links. Native private and model records now share the original member/postfix facts, including quoted keys, lambda shadowing, reached row/slot scopes and native function bodies. CHECK fixtures and comparisons retain actual native declaration identities and exact command links; resets, unrelated records and sibling subrecords stay independent. Twenty-eight of the 29 unchanged record-rename contracts pass through the native entry. The remaining large-expression contract reaches the existing syntax node cap before its expected source-linked refactor refusal; that cap is unchanged. Native layout requests now share the checked arrangement policy and authenticate actual native region/matrix owners before and after editing. Original atom spans and recognized trivia preserve symbol labels, nested block comments, hash notes, Unicode and CRLF. Renaming, resizing, adding and removing regions preserve content owners and return one undoable replacement. All 23 original layout contracts pass through native analysis and gesture entries. Added cases cover all 256 regions, block-comment resizing, forged metadata, foreign operations, and exact/one-short cumulative limits; the existing 4,096-cell maximum also passes. Native region headers retain their visibility controls.

Mixed native edits now borrow one completed original analysis across property, text, structure, insertion, move, wrap and numeric gesture operations. Each operation validates its candidate under the same cumulative allowance; one forward pass builds the combined patch and the compiler validates that result. All seven original mixed-edit contracts and all 39 original move/wrap contracts pass through native entries. Tests cover exact and exhausted cumulative limits, foreign source/operation substitution, atomic overlap refusal and scope review. The completed source-error flag is retained before UI diagnostic truncation, so clearing or truncating transported diagnostics cannot authorize an edit. Numeric gestures now update supplied component arguments under the same native literal-ownership checks as properties. A missing optional argument uses its native property plan to materialize preceding defaults, borrowing the original analysis once. Inline property insertion preserves valid inline spelling, comments and line endings. Two absent arguments whose whole-call patches would overlap retain the existing atomic refusal.

Move and wrap plans authenticate structural spans, destinations, operation admission and the complete node hierarchy against native publication. Their selection, tree changes, source assembly and result checks spend the original operation allowance. Forged original or candidate metadata is refused before publication; exact and one-short limits cover all three logical budget axes. The structural check projects metadata from retained native syntax without recognizing source again. This adds selected editor work; its complete physical budget remains to be established. Ordinary compiler observers remain disabled, and the current paired ordinary measurement stays within the retained budgets. Native symbol reference lists now publish after View reads are collected, so case-insensitive model uses and lexically shadowed locals remain distinct. Qualified names, A1/R1C1 cells, range endpoints and spill references borrow original token sites retained by their actual grammar production. Qualifiers and spill markers stay outside those token sites; Default, workbook and remote qualifiers never become local symbol identities. Range interiors still have no independent editable token, and existing incomplete-reference/rename refusals remain in effect. These observations are statically disabled for ordinary parsing.

Native named and cell definition navigation now uses the actual native publication and its original assignment head. No assignment-definition parser probe runs in selected analysis. Quoted names, qualifiers, typed/decorated heads and duplicate declarations retain their original navigation sites. The cell-target grammar may consume trivia while checking for a range; the native index trims that endpoint through the original lexer observations, including comments. Publication and lookup spend the existing operation allowance. This does not change rename authority or public entry selection.

Native assignment references now borrow the exact leaves consumed by each value expression. Function registration retains the native definition key, original name token and body leaves; call navigation joins genuine native call occurrences to the resolved callable table. Selected analysis no longer runs assignment/function reference, function-header or call-head parser probes. Sheet anchors, direct aliases, lexical shadows, qualifiers and imported source boundaries remain distinct. Bound names still supply completion sites, and a metered native expression traversal preserves LET/LAMBDA completion contexts and binder diagnostics. No source substring is parsed by that traversal. Declaration lookup charges are independent of hash iteration order. Exact and one-short allowances, repeated exact runs and original navigation/completion comparisons cover these changes. Ordinary syntax-owner storage is unchanged; additional function observations are selected only by editor admission.

Selected source coverage now uses original lexer trivia and admitted metadata owners. View insertion uses the actual model terminator; strings and comments containing END MODEL do not create insertion sites. A native inline terminator also supplies a valid insertion boundary without a whole-source token scan.

Process completions use exact native expression-consumption records and original identifier tokens. Native MATCH tests retain their authored guard relationship; generated REQUEST duration scalars produce no source sites. Sequential locals, independent groups, private scopes, iteration/carry values, selected methods, imports and match payloads preserve their existing completion namespaces. A shared native result with distinct source occurrences is refused conservatively. No legacy expression read walker supplies selected Process completions.

Final name lists, spelling hints, quick fixes, diagnostics and edit withholding now spend the same operation allowance before their work and output allocations. Spelling comparison uses bounded stack storage. An exhausted final publication returns a diagnostic without exposing partial completion or edit output. Native reference publication supplies its own conservative rename metadata; selected analysis no longer builds empty legacy reference maps. Existing source and output limits remain unchanged. Shared-index construction now charges declaration and diagnostic copies, symbol and completion-context output, source-coverage inventories and sorting, and View action-write metadata to that same allowance. Process identity comparisons include imported and generated origin payloads. MATCH guard records retain their actual enclosing source owner, so a foreign module cannot supply local completion sites. These are logical work and payload bounds; complete physical allocation and peak-memory acceptance remains open.

A numeric gesture now plans all selected arguments of one native component invocation together. Missing arguments are written in contract order, using only declared defaults for unselected gaps. Unselected arguments retain their original source, including formulas and comments. Selected computed expressions still require an explicit property edit. A final native check verifies every argument and neighboring source. Multiple invocations and inline-body preparation compose under the original operation allowance. Ordinary argument gestures need one original analysis and one combined candidate analysis; public activation remains pending.

All eight original inferred-presentation contracts pass through native entry points with unchanged fixtures and assertions, including imported/private policies, namespace aliases, native controls, tables and maps. That coverage is complete. Record write/component/import reference contexts, the complete selected physical and work audit, public activation and old public reader retirement remain unfinished.

Public native editor cutover — October 12 development checkpoint

The three public source analyzers and all 24 View edit entry points now select native owning analysis. Move and wrap, text/property/structure, insertion, batch, transaction and option operations authenticate the same source owners and native publications through complete candidate validation. One operation covers original and candidate analysis, imports, inline preparation, planning, refusals and final publication; no stage replenishes its allowance.

The original 1 MiB source, 65,536 node/entry and depth-128 ceilings remain. Repeated inspection and requested scratch storage use separate finite allowances selected at ingress, with sticky refusal. They do not count repeated traversal or fixed record framing as new authored payload. Legacy exact local-budget controls retain their original value/entry/byte accounting. These are logical work and requested-storage bounds; they do not establish allocator capacity, RSS, ordinary-path tax or paired Performance acceptance.

Native declaration and reference identities, Process completion facts and View field/record contexts supply the public reports. A supplied native program is read directly and never replaced by parsing its descriptive source text; that read-only report cannot grant rename authority. Function rename remains unavailable. An owner-depth refusal may retain bounded lexical diagnostics from an entirely plain recognized assignment module, while withholding symbols, completion sites and edits; uncertain contextual scopes retain only refusal.

Obsolete successful projected editor readers and broad reconstruction helpers are excluded from ordinary production. Required stored PART/pure-definition codecs and explicitly selected historical Ledger-v1 source/sidecar codecs remain. The six remaining historical View completion/projection helpers are selected only for those archive controls or tests. Earlier pending-activation paragraphs above describe their historical checkpoints. Current public editor compatibility, compiler unit and model checks pass; full compiler and physical acceptance remain separate work.

Payload refusal offsets returned by Grid handlers accept bounded integral numeric values. Fractional, reversed and non-UTF-8 ranges refuse; source locations require the authentic submitted payload recognition record. Detached owning syntax has no submitted source location authority.

Structural expansion does not depend on a printable preview. Categories without an available renderer return generatedSource: null and a generatedSourceRefusal; every generated occurrence still retains its template and input origin. Such origins omit generatedSpan, and selected-node inspection returns the exact owning subtree without inventing text or locations. The worker reconstructs these fields from the retained template and bindings. Native Generate admits the actual graph through the same compiler. This does not establish import or contextual authority for a template that needs it.

Process templates observe the native declarations and reads for parameters, participants, rooms, sequential/independent body bindings and EACH/REPEAT scopes. SHARE/UNSHARE audiences, ASK roles and RUN targets/mappings stay joined to those bindings. Caller-supplied free names remain free. A generated parameter or role rename also updates the named argument or RUN role label of its local target, including a forward call; external target interfaces remain authoritative. Function-body retention copies do not create another semantic binding visit. Bare function checkpoints keep their native header joined to the generated function. Native owner admission works even when that checkpoint has no source preview. Explicit identified captures/export intent and wider contextual module/import categories remain in development.

Explicit template intent uses the closed grid.compiler.template.v2 contract: schema, artifact, slots, captures and exports. Existing v1 templates retain their three-field contract and capture-avoidance behavior. A capture is {binding, name, target: {path, name, ordinal}}; an export is {path, name, ordinal}. Paths follow structural child indices in the template artifact. The ordinal selects the native declaration event for that owner and name, starting at zero. Paths and names supply selection, never authority.

Every v2 private template binder receives a fresh spelling before caller owners are inserted. Only an actual declaration selected by capture or export intent keeps its published name. Local named argument and Process role labels follow their generated target interface. Captures must select a free reference in a supplied, reached input and identify the native binding visible at every insertion of that input. Other free input names cannot be captured by preserved declarations. Exports must identify retained local module declarations. Forged, out-of-scope, replaced or ambiguous shared targets refuse atomically; v2 does not grant import or execution authority. Per-node expansion inspection unwraps both template versions and reconstructs output from the retained native inputs. Host-authorized import contexts remain a separate compiler admission concern.

Ordinary V3 compilation does not package the historical source-capture parser, whole-program projection factories or View/unit source sidecars. The frozen Ledger v1 adapter selects historical-ledger-v1 at build selection. Its stored format support and private controls retain their existing capture bodies. Narrow stored-definition codecs remain for archived identity and replay; new compiler tools use actual owning native admission. Action-policy clause positions come from native recognition through a static selection, independent of the historical capture adapter.

Retained source Meaning queries keep the actual native program and its same-admission observations together, including View-local reads and initializers. Imports are resolved once through the same compiler admission and its Process, handler and theorem policies. Repeated queries use that immutable result. Genuine nominal schemas and successful Process lowering contribute available type facts; failed compilation withholds successful-looking facts. Bound native observation refusals remain AST/LIMIT rather than becoming an empty-selection error.

Known compiled assignment units, bounds and validation facts can include a revision-bound origin into compilerPasses: the actual producing pass name, invocation ordinal, representation and record path. Cell-root inference, reference observation and validation are distinct records. These joins are selected once for an inspection snapshot; ordinary compilation and checked edit transactions do not retain this index. The records are descriptive inspection data. A child expression does not inherit an assignment proof, and transported metadata cannot establish a producing pass or semantic authority.

Template expansion and binding inspection use the selected compiler host for imports. One expansion retains the resolved inputs through native analysis and rewriting. A contextless request that needs an import refuses rather than inventing an export. Namespaced imports freshen the local alias and its native calls together. Definition-library EXPOSING can rename a local binding with AS; the foreign callable key, source body and export identity remain intact. Private exposures freshen independently, while explicit capture/export intent selects each actual local declaration. Reserved names, missing exports, ambiguous aliases and changed owning dependencies retain native refusals. API and package import policies remain their separately checked contracts.

Callable capture follows the native callable namespace. An equal-spelled value cannot authorize capture of a builtin call. User callables named SUM, LET or LAMBDA follow actual native call selection and ordinary user argument scope. Expansion-node inspection reconstructs the retained template and inputs with that host context; supplied generated text and origins never authorize a node.

Ordinary compilation also excludes the old span-based View execution adapters. Retained native View owners and their shared reducers supply View semantics and editor transactions. An old outline reaching the ordinary finalizer refuses GRID_SYNTAX_CONTEXT_REQUIRED; historical Ledger-v1 build selection and private tests retain the archived adapter bodies. Native recognition helpers remain part of the current grammar. Broader legacy retirement remains in progress.

The ordinary frozen PART/pure-definition reader also excludes the historical whole-module input ledger, root ordering, scope/span schedule and general input origin state. Those belong to tests or historical Ledger-v1 selection. The fixed stored stream retains its bounded field decoding, wire identity and native admission. Native imported-unit location publication remains active without constructing an old combined source pool.

View template hygiene uses the native contextual grammar, including unused ELEMENT bodies, Local declarations, row and MATCH binders, named actions, PAGE references, typed parameters, slots and refusal handlers. Repeated placements and overload families share their actual declaration identity. Imported elements keep foreign ownership; native AS and EXPOSING aliases are renamed with their caller uses. Scope inspection does not invent a placement or run a second View evaluator.

Renaming an implicit PAGE identity preserves its native default display title and public route by materializing those two defaults. Generated literals retain an origin at the exact authored page header, with hygienicPageTitle or hygienicPagePath generation facts. Existing body origins retain their original child paths after those fields are inserted. Expansion inspection reconstructs all occurrences from the retained template and host inputs. Full nominal/type hygiene, qualified model targets and general stage generation facts remain in progress.

Template owner copying reuses an operation-owned scratch index while clearing its touched entries between lexical owners. A shared codec node can therefore retain distinct bindings in distinct scopes. Repeated name inventory entries reuse bounded scratch storage; only distinct retained text consumes scalar storage. Allocation bookkeeping and origin path storage consume workspace, while the actual returned origin records and text remain measured under the unchanged output and scalar limits.

Native CHOICE families have their own template namespace. Constructor calls, explicit type applications, generic parameters, recursive fields and MATCH constructor patterns retain the family selected by native admission. A value with the same spelling cannot select a type. Exporting a family retains its public schema identity. Nested readable type references use the native type classifier rather than substitutions in rendered source.

When a hygienic PAGE has a dynamic title, its owning record can retain the native header-derived fallback title in an optional fallback_title scalar. Ordinary recognition leaves it absent. Literal titles retain their exact text. Expansion inspection reconstructs the Page parent's header origin for this generated value; submitted location metadata supplies no semantic authority. Malformed fallback text refuses under the native scalar contract.

Qualified bare View destinations follow the actual Surface-first native lookup. Private pages with the same spelling in different surfaces retain distinct identities. GO and NEXT references follow their owning Page declaration across surface scopes. Explicit sheet, workbook and machine destinations retain their native model meaning; equal page spelling does not turn them into View targets.

Native source and owning compilation snapshots expose compiler_pass_node with a NativePassNodeSelection (revision, pass, slot, boundary). boundary is before or after. The compiler reconstructs only the selected pool slot from its immutable native pass journal, without another parser, resolver or compiler invocation. A foreign revision refuses AST/STALE; an invalid ordinal, slot or boundary refuses selection. Selection objects reject unknown producer fields. The response retains exact opcodes, type tags, costs, packed operand references and attribute bytes. It is descriptive data, never execution or proof authority.

facts.rewrites uses grid.native.pass-changes.delta.v1. Each actual optimizer graph starts with a beforeImage; successive passes use previousPassAfter. Node columns are opcode, type tag, cost, packed operands as hexadecimal strings, and attributes as hexadecimal bytes. Event columns are kind, slot, changed-column bits and after-values. Bits 1/2/4/8/16 select those columns in order. Kinds 0/1/2 mean slot added/removed/changed. Slot identity does not establish semantic lineage. Every graph invocation resets the image, including repeated optimizer runs.

Derivation records retain their actual reads, premises, conclusions, operation codes and attributes. nodeFrom links a verified record to this pass's before state. nativeNodeFields.fields_by_reference declares which redundant fields use that link (dimensional operands, type tags and costs). Exact comparison precedes sharing; unmatched records keep every original field. The native snapshot query resolves shared fields. No source-node identity is inferred from a pool slot, and absent nullable interval fields carry no invented fact.

Record-contract template hygiene follows native declaration and import identities. Private contract names, INCLUDE references and VALIDATE RECORD/ROWS uses freshen together; exact record keys retain their spelling. Named model and View-local validation targets follow their native value scope independently of the contract namespace. Foreign contract member names stay intact while the actual local namespace or exposure alias may freshen. Explicit exports select the contract's own declaration. Native parsing consumes tentative VALIDATE keyword probes, but lexical template inspection does not treat RECORD, ROWS or FIELD as free values. Each expanded occurrence remains inspectable from its retained template input.

Template type hygiene preserves native representation, semantic-label, physical-unit, currency and admitted custom-unit precedence independently of equal-spelled local CHOICE families. Actual nominal constructors and explicit adt applications still follow their own declarations; generic formals retain their scope. Classification uses the existing native type lattice and admitted unit catalog, and is selected only for matching family candidates.

Private custom-unit declarations, dependent base atoms, type annotations and native numeric suffixes now freshen together. Units retain a separate namespace from values and CHOICE families. Explicit unit exports preserve their declaration; builtin collisions and malformed declarations retain native registry refusals. Native suffix admission preserves duration and other scalar precedence. Compound type edits use the authoritative unit grammar and exact atom ranges, with per-node expansion inspection retained.

Native predicate schemas, payload attachments, marker queries, structured members, logical facts/rules and inverse laws now join their own template namespace. Actual native admission selects each reference; dotted identifiers and postfix access preserve exact payload keys. Logical traversal retains actual child positions instead of repeatedly scanning a whole proposition.

Template expansion covers expression, pattern, statement, declaration and module owners and their native list destinations. Version 2 freshens introduced private names; explicit captures select a native enclosing declaration by owner path, name and ordinal, and explicit exports select actual publication declarations. Ledger asset and contract type markers, values and intrinsics remain separate; logical variables, predicates and path aliases follow the native visibility at each occurrence. Private Ledger spellings respect existing identifier limits. Qualified foreign members and data keys retain their identity while local aliases join their generated declarations. Standalone Surface, Element, Function, Process, assignment and USE roots use the same contextual/header producers as module items. Expansion-node inspection reconstructs the retained template and inserted input owners under the actual host context; an unavailable printable preview omits generated spans. Generated spans identify the generated document. This completes template structural generation lineage; subsequent semantic stage/pass/proof lineage is a separate compiler obligation.

Binding-derived source-free refactors

The native binding refactor contract adds source-free rename, extraction, signature changes and caller updates to the existing AST.EDIT/AST.APPLY transactions. Query the explicit grid.syntax.owningBindings.v1 envelope through AST.REWRITE; select the returned revision-bound binding IDs in an owning edit's edits operation object. Complete native scope/caller derivation and candidate compilation precede publication. Application reconstructs the complete transaction and preserves the original on stale inputs, forged facts, unproved affected uses, cancellation or budget refusal.

Module-item compiler handlers

A handler returned under CompilerContribution<source, declarations> emits a complete Grid declaration unit. CompilerContribution<syntax, declarations> returns the same owning module artifact used by AST.PARSE. Use a standalone tag:

USE "generator.gs" AS generator

<generator.emit template>twice</generator.emit>

Total = generated(3)

The defining generator.gs can contain:

DEFINE emit(request) RETURNS CompilerContribution<source, declarations> = "DEFINE generated(x) = x * 2"

The native compiler admits each generated declaration in the receiving module. The module category additionally accepts executable bindings and model items; generated USE directives resolve through the same actual host. Neither a matching data record nor a stage/category annotation alone supplies handler, import or execution authority. A module result cannot enter a scalar position.

All invocations, generated Source parsing, Syntax decoding, owner copying and nested expansion share the original operation budget. Source inspection retains the standalone tag without invoking its handler. Expansion depth refuses at the existing maximum; failed attempts do not reset the operation allowance.

Module holes are captured as actual owning subgraphs and connected through the native hygienic substitution pass. Their runtime values stay live without invoking the handler again. Contributed View owners join the actual completed compiler forest as distinct generated modules and use the existing native View placement pass. Binding tools inspect raw tag holes without invoking handlers; nested contextual compilation invokes each admitted tag once. Source/Syntax callable fragments export exactly one actual named function, including its parameter/body owner and native signature checking. region fragments export exactly one actual Process definition with its native inputs and body. Both admit explicit USE imports and reject extra exported definitions or a different category; neither can become a scalar. General hir/mir/lir modules use their complete native receiving operation; they do not enter through the pure expression fragment profile.

The complete owning refactor example constructs its input directly, queries fresh inventories, applies all four operations and checks the resulting module.

A module handler may return a closed refusal record with code, message, segment and a span containing byte start and end. The compiler validates the range against that submitted payload segment and maps it through native authored source metadata. Detached transport records cannot manufacture source coordinates. Malformed ranges refuse before a diagnostic acquires a payload location. Generated module root observations refer to the actual final owning forest; they carry no admission authority.

Selected native module handlers can call one of these stage factories to retain an actual compiler stage continuation:

AST.HIR(graph, category, inputs, exports)
AST.MIR(graph, category, inputs, exports)
AST.LIR(graph, category, inputs, exports)

These operations are available only inside the native compiler handler host. The returned selector belongs to that same handler and invocation; it cannot reconstruct an owner from serialized bytes or acquire another handler's custody. HIR resumes its actual compiler passes, MIR retains its native module and pending compiler continuation, and a completed lir stage requires intrinsic native admission. A retained MIR owner with a late native lir contribution may still have provisional callable fingerprints and selected callable admission facts. Retention grants no execution rights or substitute resource authority. The consuming into_lir or native receiving boundary joins the genuine late body, derives canonical fingerprints and resident callable admission, and performs final validation of actual resource producers, handle lineage and producer-before-consumer order as well. Retained MIR inspection is not executable compiled-model admission. Typed receiving links preserve the actual live input interface and expose checked Value, Callable and closed Process exports. A native region requires actual region content or a Process owner; Workbook and other registered dialect regions need no Process export. A native module can retain its complete Process image, plans and kernels. Root plans and private/public-room child calls receive genuine typed targets with their formal roles, finite bounds, reachable resources and effects. COLLECT keeps the existing shared-effect and operation admission rules.

A closed inferred Process export demands its actual layout before kernel lowering; the producer needs no sample plan. Forwarded Process names retain private source-compiler publication custody through HIR/MIR and the source-produced compiled model. A serialized name or interface cannot reconstruct that custody. An inferred polymorphic Process retains its actual compiler-owned template. The receiving compiler specializes it from genuine closed caller types and, for bounded collection traversal, actual argument extents. It uses the existing layout solver and kernels; distinct closed instances and forwarded private children retain their real identities. A runnable Process still requires a finite checked instance with its actual schemas, roles and resources. Unresolved or unbounded inputs and unavailable receiving capabilities refuse; a serialized signature cannot reconstruct template custody.

Native View documents retain their actual source-compiler slot witness and checked binding manifests. Relocated owner slots and live model aliases survive the final receiving symbol-table publication. Name collisions, writable ports without their exact lvalue, ungranted trusted code/libraries and unsupported resource/dialect relocation refuse explicitly. Inputs and outputs require their actual checked storage/resource interface. A matching metadata record or decoded compiled model cannot mint source-compiler View or provider custody.

Compact Value exports follow their actual descriptor inputs, including live seeds, prefix/window reads, sparse lookup keys and criteria/sum rectangles. Sparse progressions retain their gaps; coordinate rectangles and relative roots retain their original geometry and output anchors. All eight native capture forms use the existing call ABI. Unrepresentable/wrapping progressions and external-model ranges without a receiving binding refuse.

Selected Graph/Predicate and Frame contributions retain actual source slots, resource handles and completed producing contracts. Frame declarations can own logical binding cells without Workbook storage. Their private source associations survive receiving relocation; expression records remain inspectable after Workbook execution roots move to their actual dialect producers. COLLECT requires an actual resident Frame and the exact host queue contract. Runtime resource, provider and credential authority remains necessary at operation ingress.

Frame resource parameters

A source-backed native module may declare an unbound Frame input. The input connects to an actual receiving Frame owner rather than a string selector or ordinal. This handler uses the existing MIR continuation:

DEFINE emit(request) RETURNS CompilerContribution<mir, module> = AST.MIR(AST.PARSE("INPUT Port is frame = BLANK\nTotal = SELECT edge_id, weight FROM Port\n", "artifact"), "module", ["Port"], ["Total"])

A caller supplies its genuine source-owned Frame through the normal hole:

USE "frame-compiler.grid" AS compiler
graph roads = GRAPH([["id", "from", "to", "weight"], ["e1", "a", "b", 5]] AS edges, "id" AS edge_id, "from" AS from, "to" AS to, ["weight"] AS edge_properties, TRUE AS directed)
frame Incoming = roads.EDGES()
<compiler.emit template start="{{" end="}}">{{Incoming}}</compiler.emit>
Rows = COLLECT(Total)

The owning hir/mir/lir factories retain the actual source parameter declaration, real Frame producer, and interpolation connection. Receiving links bind the existing ReadProducedHandle edge, validate actual dependency lineage and place producers before consumers once. Live source updates do not invoke the handler again. Every Frame parameter must appear in the explicit input list. A selector string, wrong resource kind, foreign owner, cyclic dependency or invented type/interface refuses before executable compiled-model publication.

The public compile_source_to_mir and CompiledHir::into_mir APIs retain the same genuine parameter material while their real source continuation runs. CompiledMir::into_general_contribution admits that owned material under its supplied operation; it does not reopen source or reconstruct HIR. Direct into_lir refuses an unbound parameter. Ordinary compiled-model emission retains no parameter holder. Public construction has no invented native invocation budget; its deferred construction cost is charged to the actual later admission.

Generic Graph, Path and Partition input tags do not construct an ordinary handle-producing declaration or reader and cannot supply a receiving resource owner. They refuse explicitly. Actual source-owned Graph, Path and Partition declarations, canonical projections and complete native-module composition remain available, including resident Frame results. Other resource kinds require their actual typed receiver and host capability. In particular, an external Frame reader retains its maintained provider, caller identity and data-store authorization; compiling a request or matching metadata never grants I/O or credentials.

Native module Meaning inventory

AST.MEANING(artifact) appends typed native targets after the existing authored semantic roots. Existing root indices and authored name lookup remain stable. New roots use kind and nativeName where a native name exists: nativeModule, nativeRegion, nativeEffects, nativeCallable, nativeProcess, nativeContribution, nativeProcessInterface, nativeResourceInterface, nativeHandle and nativeDescriptor. Select their returned root with the returned compilation revision using the existing selection or batch protocol.

Native reports expose the actual final emitter-input metadata, region operations and capability requirements, callable contracts/captures, closed Process edges, checked resource interfaces and handle producer/consumer lineage. General contribution receivingLinks retain actual input expression references and cell/callable/Process relocations. They do not infer identity from names or equal values. A nativeRegion child path first selects an expression root, then its actual operand indices; the returned packed reference identifies that occurrence within the immutable snapshot. Other native targets have typed roots rather than expression-child paths.

Units, bounds and proofs identify their actual uninvalidated producing records in compilerPasses. A module/region fact is never copied onto a child expression. Unspecified type tags, opaque/dynamic effects and metadata without a producing derivation remain partial or withheld. Native contracts and required capabilities are descriptive data; they do not grant execution or assert runtime purity.

The native source snapshot also exposes native_roots() and native_meaning(). All queries reuse the same retained compilation and reject stale revisions. Capture is selected only at Meaning ingress and shares the existing observation allowance; ordinary compilation/execution and editor transactions do not retain this extra native snapshot.

Complete module contributions across stages

The five-stage pricing example uses equivalent source, syntax, hir, mir and lir module handlers. Generated modules contain live inputs, an imported Process plan and a View; the receiving caller admits its API query against its actual provider. The hir/mir/lir factories receive actual owning modules, declared input ports and export names inside the registered compiler invocation. A returned selector cannot authorize a new host or invocation. Cold model loading and live changes use the existing compiled-model runtime without running a handler again.

API operations in native module contributions

Native hir, mir and source-produced lir contributions can retain API requests inside their own modules. The compiler captures the actual parser-sealed operation binding in private stage custody. Before publishing a contribution into another input, it resolves the exact service through that input's host and compares the installed operation binding, including package digest, semantic and parameter interface. A missing provider or changed package refuses the contribution.

The receiver checks literal request metadata and object parameter keys against that binding and the actual shipped kernel's effect and resource contract. Exported values keep their producing job-queue effects and live dependencies. Nested native contributions carry authentic custody through their existing compiler owners; source-node tags and portable metadata cannot supply it.

The native API handler and caller pass Amount as a live input to an API query inside the generated module. Replace the handler's HIR stage with mir or lir to use the corresponding actual compiler continuation. The embedding resolver must provide api:example/numbers@1.0.0 and the handler.

Native hosts admitting cold request-bearing compiled models explicitly use source_compile::admit_lir_general_contribution_with_api_context with their actual ModuleResolver and original CompilerInvocationBudget. This selected entry binds every request to the current installed provider, validates its exact metadata and parameter interface, and retains private receiving custody. The contextless admit_lir_general_contribution entry refuses such requests. Cancellation and existing limits remain effective throughout admission.

Compiler admission authorizes the request representation. Executing an API operation still uses the host's installed package, connection, identity, credential and policy checks. A serialized request does not grant those rights or prepare an adapter, and inspection never invokes these operations. There is one compiled-model evaluator; API binding work occurs at selected admission and publication, with no additional per-cell or per-resolve authority branch.

Browser parser and View-local WASM

The portable browser packages use the same native recognizer, owning codecs and Workbook compiled-model evaluator as the native compiler. grid-compiler-wasm supports module/expression parsing, inspection and owner validation. Imported owning modules can supply grammar metadata through parseWithImports; these claims never authorize host import resolution or execution.

Load parsing, inspection and validation from the syntax-only image, grid_compiler_wasm_syntax.wasm. The full image adds only the language service. Pass createCompilerInspection a fetch response so the image compiles while it downloads, rather than a byte copy of it. Each response's ok and diagnostic are available at once; value, the complete artifact or report, is decoded the first time it is read. Code that only checks a source for errors never builds that object.

grid-view-wasm admits a pure local compiled-model graph once. Its specification separates explicit host inputs, local state and outputs by actual cell identity. Updates supply an expected revision; stale updates and undeclared input roles refuse without committing state. Local scalar, array/record and declared pure callable computation stays native. Host resources, effects and unsupported operations refuse at admission; host actions retain their existing authorized transport. Dispose the local session when its View is unmounted.

The admitted pure-call catalog includes trigonometry, lookup, text joining and array operations such as SEQUENCE, SORT, UNIQUE, TAKE, DROP, HSTACK and XLOOKUP. These use the same native compiled-model semantics. An action reads the current local value when it constructs its authorized Host request; background Host updates preserve private drafts, keyboard focus and text selection. Capacity refusals leave the last committed revision intact so a later valid update can recover. Floating-point transcendental results can differ in their last bit across native and browser platforms.

The package includes generated browser bindings and separate parser/runtime images. Loading is explicit; ordinary Views retain their current presentation and host behavior. Maintained native/WASM controls compare owning payloads and diagnostic locations, imported View grammar, declared callables and all 128 dependent computations. The first-party controls additionally exercise the real View renderer, private Form drafts/focus and shared-parser source editor. Run these controls with matching preserved parser/runtime bytes and native fixtures; native execution alone does not establish browser or portable parity. Whole-candidate and cumulative physical acceptance remain separate. The executable browser loader example is examples/compiler-tools/browser-wasm.mjs.