diff --git a/docs/modeling/grounding-worked-examples.md b/docs/modeling/grounding-worked-examples.md new file mode 100644 index 00000000000..7236a3e70f5 --- /dev/null +++ b/docs/modeling/grounding-worked-examples.md @@ -0,0 +1,1076 @@ +# v4 Grounding — Worked Examples + +> Companion to the **D2 reversal + fact-bundle reseed plan** (`src/v4/DECISIONS.md`). +> PLAN-ONLY: these demonstrate the modeling *shape*; no substrate is edited. + +## The model + +An `extdeps` target model is a **demonstration** that each of the target's +types **grounds** — decomposes, via the concept DAG, into a subset of the +universal substrate primitives (`Bool`, `Nat`, the connectives, `Node`). A +type is a **carrier** (the data) and a **meaning** (a `Node` decode of what +the data denotes). + +A coercion between two types can fail, so it is a function into the +ratified `Outcome` carrier: + +``` +coerce : A -> Outcome +// Outcome = Produced { value: T } | Rejected { diagnostic: Diagnostic } +// — std/diagnostic.dag:369, already used by int_div / int_mod. +``` + +`Produced` carries the coerced value; `Rejected` carries a `Diagnostic` — +a **named, located** failure (it has a `Locus`), never a silent drop. + +**How a coercion is derived — read this.** A coercion is *derived* by +comparing two groundings, not hand-authored. The deriver is a **mechanical +zip-fold** (a catamorphism): it walks both groundings in parallel — `List` +against `List` recurses, `Conj` against `Conj` compares field-wise, leaves +compare directly. It is not an *engine* — per `DECISIONS.md` U1 it makes +no decisions and runs no search. + +**Coincidence is mechanical structural equality.** Two groundings +*coincide* when their canonical `Node` forms are equal — the equality +`node.dag`'s B1-CANON *contract* defines: `content_hash = merkle_fold ∘ +canonical`. Comparing groundings *is* comparing content-hashes of +canonical `Node`s; decidable, not free-form semantic equivalence. (B1-CANON +is the operator-ratified *specification* of that fold; `node.dag` does not +yet carry a realized `canonical` / `content_hash` function body — see +**Design status** below.) + +**The shared vocabulary keeps the fold mechanical.** Facts are *sourced* +independently — each type grounded from *its own* spec — but must be +*expressed* in one shared vocabulary: the `std/` primitives, authority +`std/algebra.dag`. Were `RustI32` and `Int32` grounded in different +vocabulary (`bit_count` vs `width`), their `Node` trees would differ +*structurally* though they mean the same — and the mechanical compare +would wrongly say "not equal." Shared vocabulary is load-bearing: it is +what makes the fold both mechanical *and* complete. + +**Design status — specified, not yet realized.** The hard half is +*designed and ratified*, not *built*: `node.dag`'s B1-CANON ratifies the +canonical-form + content-hash **contract** (`content_hash = merkle_fold ∘ +canonical`), and `DECISIONS.md` T-9/C1 specifies the comparison as +*decidable by construction* (structural recursion over the closed declared +candidate set). But neither the canonical fold nor the coercion zip-fold +is a realized `.dag` function body yet — `node.dag` carries the contract, +not an implementation. What stays true is that this is *mechanical +design*, not a research problem: the parallel walk is determined by the +contract, not invented. The genuine hard work is the **modeling +discipline**: forcing every spec fact into the shared vocabulary so the +fold can see identity — Phase 1's job. One compile-time residue stays +deferred: refinement subsumption (`p ⟹ q`) is not a pure tree-walk and +fail-closes (substrate T-25). + +This is *not* the reversed D2 alias. D2 *asserted* `type RustI32 = Int32`. +Here every type is grounded from its own spec and expressed in the shared +std vocabulary; any identity is a *claim discharged by the fold*, never an +assertion. + +## What the "IR" is — it is `Node` + +The examples below write "↔ IR `Int32`", "IR record", etc. There is no +separate "IR" artifact. **The IR is `Node`** — `std/node.dag`'s single +recursive type: the 6 connectives `Atom | Conj | Disj | Arrow | +Cardinality | Instantiation`. `core` produces `InferredTree` = `Node` + +the frozen flat `InferredFacts` coordinate (IR-1) — still not a separate +type. Per `compiler/00_compile.dag` the pipeline is the **OMNI pivot**: + +``` +ingest : (Source, LanguageModel) -> Outcome +core : Node -> Outcome +emit : (InferredTree, TargetModel) -> Outcome +``` + +Two corrections this forces on the examples' wording: + +1. **Source is not "translated to" an IR.** There is one representation. + `ingest` *builds* a `Node` that represents the source; `emit` *reads* + a `Node` to produce target text. Source is parsed *into* the `Node` — + which **is** the program. There is no python-IR / rust-IR pair. +2. **std types are vocabulary, not "IR types."** `Int32`, `List` are + `std/` vocabulary that *grounds into* `Node` connectives; the `Node` + *represents* a construct using that vocabulary. "↔ IR `List`" + means: the `Node` represents the sequence with std `List` vocabulary; + the *target model* — not the IR — decides how `List` realizes in Rust. + +**Node-tree vs program-DAG.** The `Node` *type* is a finite tree (A1: +recursion lives solely in the children list). Program-level sharing and +cycles — def-use, loops — are by-reference via `Symbol` `Atom`s, never by +inlining. So the realized program IR is a **`Symbol`-linked DAG of +`Node`**, distinct from the finite `Node` tree. + +**One mechanic, N+M ways.** The compiler is not a pile of special-case +stages. It has ONE mechanic: a **causal transform** = projection (read +facts off `Node`) + coercion (the `Outcome`-typed map). `infer`, `lower`, +the lenses, `emit` are all instances of it; tokenize/parse/emit are +"special" only in that text I/O is a common case packaged as a module — +the machinery is identical, and the tokenize/parse legs are the +`Transform` L1 behavior (one of `node.dag`'s 5: `Value | Transform | +Branch | Loop | Bind`). So the worked examples below are not a +coercion-verdict catalog — they are evidence of **one grounding mechanic +applied N+M ways**: you author N ingest models + M emit models (authoring +cost N+M), and every ingest composes with every emit through the one +`Node` pivot (capability N×M). N+M authored → N×M capabilities, because +the mechanic is pivot-shaped. The N×M *compiler-emit* capability claim is +scoped to **Shape A** targets — see the next section; Shape-B artifacts +are emitted by `.dag` user programs, not by the compiler. + +### Shape A vs Shape B — what this catalog does and does not claim + +This catalog demonstrates **grounding** — that each target's types +decompose into the shared `Node` / `std` vocabulary — and the **coercion +shape** between groundings. Grounding is **universal and shape-agnostic**: +a Rust type, a JSON Schema object, an OpenAPI operation, a SPICE voltage, +an English noun phrase all ground the same way, and the fact-bundle +discipline is identical for all of them. + +It does **not** claim every target is a compiler render-target. +`THESIS.md` locks a distinction the worked examples must not blur +(THESIS.md §"Omni-emission" — the Shape A vs Shape B bullets; ROADMAP +Track 16): + +- **Shape A — compiler language targets**: programming languages and HDLs + — `rust`, `python`, `go`, `cpp`, `typescript`, `verilog` (and the + low-level / IR targets `llvm_ir`, `ptx`, `machine_code`, likewise + modeled in `extdeps/languages/`). The compiler emits these **directly** + via `emit(TargetModel)` against a language spec. The N+M / N×M + *compiler-emit* capability claim above is about these. +- **Shape B — user-program artifacts**: `openapi`, `json_schema`, `yaml`, + `json`, `csv`, `toml`, `spice` netlists, English docs. These are **NOT** + compiler render-targets — they are emitted by `.dag` **user programs** + walking typed values (`concat` / `fold` / `match`). Adding a Shape-B + target is writing one reusable `.dag` emitter program, not a compiler + change. + +So a Shape-B entry in this catalog is a **grounding / data-model +example** — it shows how that format's types ground and how a coercion +against them is shaped. It is **never** an instruction to implement the +format as a compiler `emit(TargetModel)` render path. The grounding +discipline is shared across both shapes; the *emission mechanism* is not. + +## Spectrum + +These examples are chosen to span the full range deliberately — +`machine_code` (pure bits) → `rust` (typed, generic) → `verilog` +(4-valued logic) → `spice` (continuous) → `lean` (dependent types) → +`english` (natural language). One model handling all of them is the +evidence that it is universal. + +--- + +## Live-state tags (P0) + +Every stage below is tagged for its honest live-state on `origin/main`: + +- **`[DAG-REALIZED]`** — the `.dag` has a real function body for this + path (not a stub) — but the v4 compiler is not yet bootstrapped into + an executing pipeline; nothing *runs* it today. +- **`[MODELED]`** — the modeling shape only; no `.dag` body yet. + +There is deliberately **no `[BUILT]`/runs-today tag**: v4's compiler is +itself `.dag`, Wave-1, not bootstrapped into an executing binary. The +strongest claim any stage can honestly make here is `[DAG-REALIZED]` — +and the doc never claims more. + +## The end-to-end shape — one grounded chain, one modeled spine + +### A. The most-grounded chain — the `.dag` self-hosting frontend `[DAG-REALIZED]` + +The v4 frontend is **Wave-1** and `.dag`-realized, not executing: +`01_tokenize.dag` has a real function body for the **E0 void-lexical** +path and `02_parse.dag` for the **G0 void-grammar** path. So the +most-grounded end-to-end chain — real `.dag` function bodies, though +nothing executes them as a pipeline yet — is the empty/void one: + +``` +"" (empty .dag source) + → tokenize("", file, LexRules=E0) : (String,Symbol,LexRules) -> Outcome + → Produced(empty TokenStream) [DAG-REALIZED] + → parse(emptyTokenStream, Grammar=G0) : (TokenStream,Grammar) -> Outcome + → Produced(degenerate ParseTree) // ParseTree = Node [DAG-REALIZED] +``` + +The fail-closed direction is `.dag`-realized too — non-empty source +against E0: + +``` +"x" → tokenize → Rejected { Diagnostic { reason, at: Locus = WholeFile } } [DAG-REALIZED] +``` + +That `Rejected` is a constructed `Diagnostic` with a `Locus` — "named, +never silent" is *shown* in the realized `.dag` body, not asserted in +prose. Richer `.dag` tokenization (real keywords, programs) is +declarative grammar-data **not yet realized** — `[MODELED]` from here +up. Both realized functions already return `Outcome`. + +**The round-trip — one `Node`, two directions.** The same void chain run +forward and back: + +``` +"" → tokenize → parse → ParseTree [DAG-REALIZED] — ingest builds the Node + → emit → "" [MODELED] — emit reads the Node back +``` + +`tokenize` / `parse` are causal transforms — the `Transform` L1 behavior +— each projecting facts off its input and coercing to its output; they +are not special-case stages. `emit` is the *same mechanic* run the other +direction (`05_emit.dag` is a `T-10` scaffold, so the emit leg is +`[MODELED]` — the mechanic-identity claim is structural, not a runtime +claim). This *shows* "emit is a section of ingest": one `Node`, ingest +constructs it, emit projects it back — not two hand-built stages. + +### B. The modeled spine — `python int → IR → rust i32` `[MODELED]` + +There is **no** Python or Rust parser (`extdeps/languages/python.dag` +models Python's type *surface*, not a parser). The whole chain is +`[MODELED]`. **`Node` is the explicit hub** — "IR" and the `IR_*` names +below are *not* a distinct IR type plane; per the "What the IR is" section +above, `IR_Int` etc. are the shared `std/` vocabulary carried *as* `Node`. +The chain has two coercions with *different totality*: + +**Ingest — `python int → IR Int` (total).** + +``` +ingest_int : PythonInt -> Outcome [MODELED] +``` + +`IR_Int` is `GroupCompletion` — unbounded. Every Python `int` +(arbitrary-precision) grounds to an `IR_Int`; ingest is **total** — always +`Produced`. No overflow exists at the IR: the IR integer has no width. + +**Emit — `IR Int → rust i32` (partial — overflow lives here).** + +``` +emit_i32 : IR_Int -> Outcome [MODELED] +// Spec: models rust core::convert::TryFrom for i32 — the fallible +// conversion. NOT `as` (wraps/truncates), NOT `From` (widening-only). + +emit_i32(ir) = + if −2³¹ ≤ value(ir) ≤ 2³¹−1 → Produced( rust i32 ) + else → Rejected { Diagnostic { + reason: integer_out_of_range, at: Locus } } +``` + +`RustI32` grounds as `Compose>` — the abstract +`Int` carrier refined by an independent machine-width axis (per +`std/integer.dag`; **not** a parallel bit-carrier — `integer.dag` forbids +that). The `−2³¹..2³¹−1` bound is the `MachineWidth` refinement +predicate, not catamorphism output. + +So Python `10**100` ingests fine (`Produced` an `IR_Int`) and **fails +closed at emit** (`Rejected`, a real `Diagnostic`). Overflow is an +**emit-boundary** fact — localized, typed, named. + +### A worked operation + +Operations live on the IR, where integers are unbounded — so +`int_add : (IR_Int, IR_Int) -> IR_Int` is **total** (no overflow in the +IR; cf. `std/integer.dag` `int_add`). Overflow appears only when the +*result* is emitted: `emit_i32(int_add(a, b))` is the partial step. "`a + b` +too big" is therefore **not** a property of `+` — it is a property of +*emitting `+`'s result to a fixed-width target*. + +### Emit is a section of ingest, not a bijection + +`ingest` and `emit` are the **two directions of one grounding map**, not +inverses. `ingest` is lossy on text (comments, whitespace, sugar collapse +to the same `Node`); `emit` picks one canonical text. `emit ∘ ingest` ≈ +identity *on meaning*, never on text. At the carrier level above, ingest +is additionally *total* and emit *partial* — the asymmetry that localizes +overflow at the emit boundary. + +--- + +## Per-target carrier groundings + +## 1. Rust — `[T; N]` (const generics, compound coercion) + +**Model** — grounded from the Rust Reference array type: + +``` +// CARRIER — an array value is exactly N elements of T in order. N is part +// of the type as a const Nat parameter, not a library allocation fact. +type RustArray = Conj { + elements: List, + length_proof: Witness< |elements| = N > +} + +// MEANING — identity on the element sequence. +``` + +`RustArray` grounds to `List` plus a +length witness, and `RustI32` grounds as `Compose>` (§B — the substrate's fixed-width discipline, +`std/integer.dag`; not a `{32×Bool}` bit-carrier). + +**Step-by-step coercion shape — `RustArray -> Outcome, length_proof: Witness<|elements| = 3> }>`:** +1. groundings: `List>>` plus + `Witness(length = 3)` on the Rust side. The IR target is the + **length-witnessed** form — `List` carried *with* its + `Witness(length = 3)` (in `Node` terms, the `Cardinality` connective) — + **not** a plain unbounded `List`. The length is a source fact, so it + must appear in the target carrier. +2. the coercion fold compares outer `List` vs `List`, + then recurses into the element grounding. +3. element `grounding(RustI32)` vs `grounding(Int32)` → coincide. +4. coincident element groundings return `Produced { value }` where the + value is the IR length-witnessed list — `elements: List` **and** + `length_proof: Witness<|elements| = 3>`. The length-3 fact **flows + forward into the output carrier** (P2 facts-flow-forward); it is not + dropped to a plain `List`, and no accepted-loss is needed because + nothing is lost. No array coercion is authored; the compound result, + length witness included, follows from the structural comparison. + +**Cross-language shape — `PythonList[int] -> Outcome>`:** +outer `List` matches, but each element must pass `IR_Int -> Outcome` +as in §B, and the source length must discharge `Witness(length = 3)`. +In-range values of the right length produce the Rust array; any element +outside the `MachineWidth` predicate or any non-3 length returns +`Rejected { diagnostic: Diagnostic }`. + +--- + +## 2. machine_code — a 64-bit general-purpose register (the pure-bits endpoint) + +**Model:** + +``` +// CARRIER — a register value is exactly 64 classical bits. The width is a +// structural fact (a length witness), not a comment — same shape as the +// Rust array above; a bare `List` would admit any length. +type Reg64 = Conj { + bits: List, + length_proof: Witness< |bits| = 64 > +} + +// MEANING — none intrinsic. A raw register is an uninterpreted bit +// pattern; meaning is supplied by the instruction that consumes it +// (the same 64 bits are an integer to ADD, an address to LOAD, a +// float to ADDSD). Reg64 grounds carrier-only; meaning is deferred +// to the consumer. +``` + +This is the spectrum's trivial endpoint — `machine_code` *is* bits, so +the grounding is direct, no decode. + +**Coercion shape — `Reg64 -> Outcome, length_proof: Witness<|bits| = 64> }>`:** +the coercion is **identity-quality** — `Reg64` *is already* the +length-witnessed bit-list, so the target carrier is the same shape, not a +bare `List`. Projecting to a bare `List` would silently drop +the width-64 witness — the facts-flow-forward violation §1 (the Rust +array) warns against; the width-64 fact must flow forward into the target +carrier (or be an *explicit* accepted-loss, which a "pure-bits endpoint" +identity coercion has no reason to be). Returns `Produced { value }` +carrying **both** `bits` and `length_proof`. Instruction-specific reads +are separate coercions: the consumer supplies the meaning (`Int64`, +address, binary64, ...), and an unsupported or missing meaning returns +`Rejected { diagnostic: Diagnostic }` rather than inventing one. + +--- + +## 3. Verilog — `reg [31:0]` (a target primitive *richer* than ours) + +Verilog's logic value is **4-valued**: `{0, 1, x (unknown), z (high-Z)}` +— not our 2-valued `Bool`. + +**Model:** + +``` +// CARRIER — exactly 32 four-state bits. Width is a structural length +// witness, not a comment — same shape as the Rust array. +type VBit = Zero | One | Unknown | HighZ // closed 4-sum (a coproduct) +type VReg32 = Conj { + bits: List, + length_proof: Witness< |bits| = 32 > +} + +// MEANING — the 32 four-state bits. A plain `reg [31:0]` is UNSIGNED in +// Verilog; signedness is NOT a fact of this carrier — it requires the +// explicit `signed` modifier (`reg signed [31:0]`). Read as a number the +// {0,1} bits are a 32-bit two's-complement BIT PATTERN; the +// signed-vs-unsigned interpretation is supplied by the declaration, not +// by the vector. Undefined if any bit is x/z. +``` + +`VBit` grounds — as a closed sum over the substrate's coproduct +connective. It does **not** ground as `Bool`: Verilog's primitive is +richer. `Bool` is exactly the `{Zero, One}` sub-part of `VBit`. + +**Step-by-step coercion shape — `VReg32 -> Outcome`:** +1. IR `Int32` grounds to `Compose>` (the + fixed-width integer discipline from §B); `VReg32` grounds to + `Conj { bits: List, length_proof: Witness<|bits| = 32> }`. +2. the coercion fold compares element-wise: + `Bool` vs `VBit` — `Bool ⊊ VBit`. +3. `IR Int32 -> Outcome` is total over this relation: every + `Bool` embeds as `Zero` or `One`, so the result is `Produced`. +4. `VReg32 -> Outcome` is partial on **two** axes. (i) Any + `Unknown`/`HighZ` bit returns `Rejected { diagnostic: Diagnostic }` — + x/z is not an integer state. (ii) For all-`{Zero, One}` bits the 32-bit + pattern is well-defined, **but a plain `reg [31:0]` is unsigned** — it + carries no signedness fact, and IR `Int32` is *signed* + (`Compose`). Producing signed `Int32` from a plain `reg [31:0]` + would fabricate the signedness fact — the same hazard as the LLVM + `add i32` case (§10). The honest coercion: a plain `reg [31:0]` lands + an **unsigned** 32-bit carrier; signed `IR Int32` is `Produced` only + when the source is `reg signed [31:0]` — the signedness-bearing + declaration — otherwise `Rejected`. + +This is "speaks a *subset*" made precise: Verilog and the IR share the +`{0,1}` subset; the `x/z` states are Verilog-only and honestly +fail-closed; and signedness, absent from a plain vector, is required as +an explicit declaration fact rather than fabricated. The model handles a +target whose primitive is richer than ours without distortion — and +without inventing facts the carrier never modeled. + +--- + +## 4. SPICE — a node voltage (approximate carrier vs exact-voltage gap) + +**Model:** + +``` +// CARRIER — current std authority: dsl/std/float.dag pins Real to +// ApproximateField>, not an exact continuum. +type SpiceApproxVoltage = Conj { + magnitude: ApproximateField>, + unit: Volt +} + +// MEANING — approximate voltage fact with explicit approximation policy. +// GAP — SpiceExactVoltage requires a grounded exact-real/quantity carrier. +``` + +`Real` is not treated here as an exact continuous carrier: the live +authority (`dsl/std/float.dag`) defines `Real = +ApproximateField>`. `Volt` is a `Dimension`. +IEEE-754 `f64` grounds separately as a fixed-width approximate carrier with +rounding and special-value facts. An ideal SPICE voltage that requires an +exact mathematical continuum is therefore a named fail-closed gap: +`SpiceExactVoltageMissingExactRealCarrier`, not a silent reuse of `Real`. + +**Step-by-step — coercing a `Rust f64` toward `SpiceApproxVoltage` (the unit must be supplied, not fabricated):** +1. `SpiceApproxVoltage` grounds to `ApproximateField>` + **plus a `Volt` unit fact**; `f64` grounds to IEEE-754 binary64 — a + **unitless** approximate magnitude (`dsl/std/float.dag` / + `src/v4/std/float.dag`). +2. the coercion fold compares the groundings: the approximate-field + *magnitude* carriers are related (different width/policy facts) — but + `SpiceApproxVoltage` carries a `Volt` coordinate the `f64` grounding + **does not have**. +3. Because the `Volt` fact is absent from the source, a bare + `f64 -> SpiceApproxVoltage` **cannot be `Produced`** — conjuring the + unit coordinate would fabricate a fact, the exact violation this doc + models against (the emit-side dual of a hollow alias). The unit must be + **supplied**: the honest coercion is + `(f64, unit: Volt) -> Outcome`, the `Volt` an + explicit boundary input (the SPICE context asserts "this number is + volts"). The f64-only coercion lands only the magnitude — + `f64 -> Outcome>` — returning `Produced` (quality + `Lossy`) when the approximation policy is explicitly accepted and + recorded; the consumer that has the `Volt` fact constructs the full + `SpiceApproxVoltage`. +4. `NaN` / `±∞` return `Rejected { diagnostic: Diagnostic }` because they + are IEEE-754 special values, not voltage magnitudes. A requested + `Rust f64 -> Outcome` returns + `Rejected { diagnostic: Diagnostic { reason: + SpiceExactVoltageMissingExactRealCarrier, ... } }` until an exact carrier + is modeled. + +The endpoint here is no longer mislabeled as exact, and the unit is +**supplied, never fabricated**. The approximate path is a +**declared-lossy** derived map over the *magnitude*; the `Volt` +coordinate enters only as an explicit boundary fact; the exact-voltage +path is a named fail-closed gap. + +--- + +## 5. Lean — `Fin n` (dependent types) + +A Lean type can depend on a *value*. `Fin n` is the type of natural numbers +strictly less than `n`, so the bound `n` is part of the type itself. + +**Model:** + +``` +// CARRIER + WITNESS — the dependent index n is an explicit Nat; the type-level +// constraint "value < n" grounds as a Witness (see src/v3/std/dimensions.dag), +// the substrate's proof-carrier. +type LeanFin = Conj { + value: Nat, + bound_proof: Witness< value < n > // n : Nat, lifted into the type +} +``` + +A dependent type = carrier + a `Witness` pinning the dependent value. + +**Step-by-step coercion shape — `IR Nat -> Outcome>`:** +1. grounds to `Nat` + `Witness(value < 3)`. +2. an IR `Nat` value `0`, `1`, or `2` discharges the witness and returns + `Produced { value: LeanFin<3> }`. +3. an IR `Nat` value `>= 3` cannot discharge the witness and returns + `Rejected { diagnostic: Diagnostic }`; you cannot claim `Fin 3` + without the bound proof. + +Dependent types ground via the `Witness` substrate — the type's proof +obligation becomes a `Witness` the coercion must discharge. + +--- + +## 6. English — noun phrases (the fail-closed endpoint, and composite grounding) + +English has no type system. What we model is the **groundable fragment** — +and that fragment is not only leaf values: English can *express* the +**connectives** (though not via a simple word-mapping — see below), so it +can ground *composite structure*. + +### Leaves — number words → `Nat` + +``` +// CARRIER — a sequence of words from English's CLOSED number grammar: +// units, teens, tens, scale words (hundred/thousand/…), sign +// ("negative"). Closed + enumerable → it grounds. +type NumberWord = One | Two | … | Hundred | Thousand | Negative | … +type EnglishInteger = List + +// MEANING — the decode to an integer: a Node of Nat arithmetic. +// "forty-two" → tens(4)*10 + units(2) = 42 +// "negative forty-two" → −(that) = −42 +``` + +An English integer literal **grounds** — closed carrier + deterministic +decode. `EnglishInteger -> Outcome` returns `Produced` when the +grammar deterministically decodes the phrase: "negative forty-two" maps +to the IR `Int` value `−42`. A qualifier such as "about" or "-ish" has +no deterministic decode and returns `Rejected { diagnostic: Diagnostic }`. + +### Connectives — English can ground composite structure, but the word is *not* the connective + +English can express the substrate connectives — but **the surface word +does not determine which connective it is.** The decode reads the +construction's *meaning*; the word is a weak, often-misleading hint. The +modeling here is genuinely non-trivial. + +**`Conj` vs `Disj` — "and" does not pick.** +- "an order has a customer **and** a total" — both-present coordinates + → `Conj{ customer, total }`. +- "we accept cash **and** card" — a *menu of alternatives*, one is + chosen → `Disj{ Cash, Card }`. The same word "and", a different + connective. + +**`Disj` is exclusive — and English does not mark that with a bare word.** +A substrate `Disj` (a sum) is a value that is *exactly one* variant. +- "**either** soup **or** salad" — the *either…or* construction marks + the exclusivity → exclusive `Disj`. +- a bare "milk **or** sugar?" is often *inclusive* (both allowed) — and + inclusive-or is **not a `Disj` at all** (it is closer to a `Conj` of + optionals / a non-empty subset). + +So a faithful decode must establish (a) conjunction-of-coordinates vs +choice-among-alternatives, and (b) if a choice, exclusive vs inclusive — +and the surface word reliably tells you *none* of it. The same +under-determination holds for "of" (`Instantiation` vs the possessive +"a friend **of** mine"), plurals (`Cardinality` vs idiom), and "for +each". A construction whose connective cannot be determined returns +`Rejected { diagnostic: Diagnostic }`. + +### The `Outcome` boundary — words under-determine structure + +This is why English's groundable subset is an *island* and the +fail-closed boundary is large — **not** because the connective words are +missing, but because the words **under-determine** the structure. +"this and that" may be a `Conj` or a `Disj`; "or" may be exclusive or +inclusive; the word alone cannot say. Leaf phrases reject the same way: +`EnglishPhrase -> Outcome` returns `Rejected { diagnostic: +Diagnostic }` for "forty-two-ish", "about forty-two", or "ship it when +the build feels solid". + +When the construction *is* unambiguous — a disciplined, controlled +English written to a fixed structural convention — English grounds +composite structure honestly, recursively, as a `Node` decode. Free prose +under-determines and rejects. Model what determinately grounds; reject the +rest. (This is the +`english_ingest_fail_closed.dag` boundary-honesty probe v4 already +plans.) English is not a degenerate case; it is a full language whose +words under-determine structure, hence a large, honest `Rejected` +boundary. + +--- + +## 7. Go — `chan T` (typed communication endpoint) + +Go channels are typed FIFO communication endpoints. Their value model is not +"a list"; the channel value is a capability to send and/or receive values of +`T`, with ordering and blocking behavior supplied by the Go spec. + +**Model:** + +``` +// CARRIER — the channel TYPE `chan T`. Per the Go spec, a channel type +// is EXACTLY element type + direction — two channel types are identical +// iff same element type and same direction. Nothing else is a type fact. +type GoChan = Conj { + element: TypeGrounding, + direction: SendOnly | ReceiveOnly | Bidirectional +} +// SCOPE — this carrier models the channel TYPE, not a channel VALUE. +// `capacity` is NOT a type fact: it is a value-construction argument to +// `make(chan T, n)` — two `chan int` types are identical regardless of +// the capacity their values were made with. Capacity, and the runtime +// value-state — open/closed, live buffer occupancy, queued contents, +// nil-ness — all belong to the channel VALUE / `make` / eval layer, +// explicitly outside this type carrier. + +// MEANING — the channel type's communication contract: ordered FIFO +// transfer of T values, with `direction` the static type fact. Blocking +// behavior is a RUNTIME fact — it depends on the make-time capacity and +// the live buffer occupancy / open/closed-ness, none of which the static +// type determines — so it is not claimed by this carrier. +``` + +**Step-by-step coercion shape — `GoChan -> Outcome>`:** +1. `chan int32` grounds to endpoint facts plus `grounding(int32)`. +2. the coercion fold compares endpoint vs endpoint, + then recurses into the element grounding. +3. `int32` vs `Int32` coincide when both decode as 32-bit two's-complement. +4. matching element grounding plus the `direction` type fact return + `Produced`. A missing `direction` returns `Rejected { diagnostic: + Diagnostic }` rather than defaulting to bidirectional. `capacity` is + *not* a type fact, so its absence is **not** a rejection criterion for + the channel type — rejecting a `chan T` type for "missing capacity" + would itself be an unfaithful model (a plain `chan T` type genuinely + has no capacity). + +The channel type fact is `direction` (with the element type) — a grounded +target fact, not an annotation. Capacity (a `make`-time value-construction +argument) and the runtime scheduling state — live buffer occupancy, +open/closed-ness — are a separate channel-value / eval-layer concern, not +part of this type grounding. + +--- + +## 8. C++ — `int` (implementation-defined primitive width) + +C++ `int` is a language primitive. Per **C++20** (ISO/IEC 14882:2020, +§[basic.fundamental]) — the edition that **fixed** signed integer +representation — its **signed value representation is two's complement**; +only its **width** is implementation-defined (16+ bits; LP64 / ILP32 +commonly pick 32). That fixity carries forward unchanged to the current +edition, C++23 (ISO/IEC 14882:2024). The model reads width from the +target/ABI binding (T-29) and treats representation as a fixed *spec* +fact, not an implementation-defined axis. (Pre-C++20, signed +representation was itself implementation-defined — modeling that would +require pinning an older edition; this example is anchored to C++20, the +edition where the fact became fixed.) + +**Model:** + +``` +// Anchor: ISO/IEC 14882:2020 (C++20) §[basic.fundamental] +// CARRIER — a C++ `int` fact-bundle: the signed-integer base plus the +// width and representation facts. `Compose` is BINARY in std/ +// (`Compose`, integer.dag) — a multi-fact bundle is +// a `Conj` of facts, not a variadic `Compose`. PLAN-ONLY note: the +// `Representation` axis is Phase-2 std/ substrate (T-3-extended — +// signedness/representation do not exist in std/ yet); it is shown here +// as the intended fact, marked future-substrate, not a live carrier. +type CppInt = Conj { + base: Int, // signed-integer carrier (live std/) + width: Nat, // implementation-defined + width_proof: Witness< width >= 16 >, // C++ guarantees int is >= 16 bits + representation: Representation // = TwosComplement, C++20-fixed; + // Representation axis is Phase-2 + // substrate (T-3-extended), not live +} + +// MEANING — integer value within the range fixed by width under +// two's-complement. +``` + +**Step-by-step coercion shape — `CppInt -> Outcome`:** +1. `CppInt` grounds to `Int` plus a **fixed** two's-complement + representation fact plus **one** implementation-defined fact — `width` + (the genuine per-ABI variable; range is derived from width). +2. the coercion fold compares the abstract integer value to + IR `Int`; the width fact stays attached as a target fact. +3. `CppInt -> Outcome` returns `Produced` because every inhabited + C++ `int` denotes an integer value. +4. `IR Int -> Outcome` is partial: it returns `Produced` only when + the value is inside the implementation-defined range; otherwise + `Rejected { diagnostic: Diagnostic }`. + +This contrasts Rust `i32`: Rust fixes the width in the type name; C++ `int` +requires the target/ABI model to carry the implementation-defined **width** +fact. If the binding cannot provide it, the coercion fails closed instead +of assuming LP64/ILP32. + +--- + +## 9. TypeScript — `number | string` (structural union with disjoint primitive arms) + +TypeScript unions are structural acceptance sets. Generic `A | B` is not +automatically an exclusive substrate `Disj` because structural members can +overlap. This example uses disjoint primitive arms (`number | string`) so the +accepted value has a unique arm after the target's own type classification. + +**Model:** + +``` +// CARRIER — membership in one of two disjoint primitive acceptance sets. +type TsNumberOrString = StructuralUnion { + members: Set { TsNumber, TsString }, + disjointness: Witness> +} + +// MEANING — the accepted member's own meaning. Generic unions require +// overlap/narrowing facts before they can be treated as a Disj. +``` + +**Step-by-step coercion shape — `TsNumberOrString -> Outcome`:** +1. TypeScript `number` grounds to IEEE-754 binary64; ECMAScript `string` + grounds to a sequence of UTF-16 code units, including possible ill-formed + surrogate subsequences. +2. IR alternatives ground independently: `Float64`, `String`. +3. the coercion fold first uses the disjoint primitive + membership witness to choose the arm, then compares that arm's grounding. +4. `number` to `Float64` returns `Produced`. `string` to IR `String` + returns `Produced` only if the IR string model is UTF-16-code-unit-shaped + or a validated decode from UTF-16 code units to scalar values succeeds; + otherwise it returns `Rejected { diagnostic: Diagnostic }` or a + `Produced` value with an explicit accepted-loss fact. + +The generic union case stays a structural membership/acceptance fact until +overlap or discriminant evidence proves an exclusive `Disj`. + +--- + +## 10. LLVM IR — SSA value (typed single-assignment register) + +An LLVM SSA value is a typed result of one definition. Its identity is a graph +edge, not a mutable storage slot. + +**Model:** + +``` +// CARRIER — one definition edge with a declared LLVM type. +type LlvmSsaValue = Conj { + definition: NodeRef, + llvm_type: LlvmType, + value: T +} + +// MEANING — the value produced by the defining instruction, decoded through +// llvm_type. Single-assignment is a graph invariant over definition. +``` + +**Step-by-step coercion shape — `LlvmSsaValue -> Outcome`:** +1. LLVM `i32` grounds to **32 bits** — a width fact only. LLVM integer + types are **sign-agnostic**; `i32` itself carries no signedness. +2. the consuming operation supplies arithmetic meaning — but not always + signedness. `add i32` is **signedness-neutral**: two's-complement + `add` is the *identical* operation for signed and unsigned operands, + so `add` grounds a 32-bit two's-complement integer, **not** a signed + one. LLVM carries signedness only in the operations where it differs — + `sdiv`/`udiv`, `srem`/`urem`, `sext`/`zext`, etc. +3. IR `Int32` is **signed** (`Compose>` — `Int` + is the signed carrier). So the coercion fold needs a signedness fact + the source must actually carry. +4. a **signedness-bearing** source supplies that fact → return `Produced`. + The genuine signedness-bearing sources are: a **signed instruction** + (`sdiv`/`srem`/`sext`/`ashr`, …) or **signedness metadata** (a + `signext`/`zeroext` parameter attribute, or `!range` metadata) — NOT a + bare typed parameter, which is itself sign-agnostic. `add i32` alone, + or raw `i32` with no signedness-bearing source, returns + `Rejected { diagnostic: Diagnostic }` — reading *signed* `Int32` out of + a sign-neutral operation is fact fabrication. (A sign-agnostic 32-bit + two's-complement integer is itself a faithful target; only the + **signed** `IR Int32` needs the extra fact.) + +SSA identity grounds as the DAG definition edge. Mutability is not modeled +because LLVM SSA values are not mutable cells. + +--- + +## 11. PTX — SIMT predicate register (lane-indexed truth) + +PTX predicate registers are boolean-like values evaluated per lane in a SIMT +execution context. The lane coordinate is part of the fact. + +**Model:** + +``` +// CARRIER — one per-lane record per lane: the lane's truth value and +// whether the lane is within the current execution mask. A SINGLE list +// of per-lane records — value and active flag co-index by construction, +// so a mismatched-length mask is structurally unrepresentable (P2). Two +// independent List (lanes / active_mask) would admit a length +// mismatch — an illegal state — and is rejected for that reason. +type PtxLane = Conj { value: Bool, active: Bool } +type PtxPredicate = List + +// MEANING — a lane-indexed condition; inactive lanes do not assert false, +// they are outside the current execution mask. +``` + +**Step-by-step coercion shape — `PtxPredicate -> Outcome>`:** +1. predicate grounds to `List` — each element a `{ value, active }` + record; value and mask co-index by construction. +2. IR `List` grounds only to lane truth values. +3. the coercion fold finds related but non-identical groundings: the + per-lane `active` flag exists in PTX but not in the plain list. +4. PTX to plain list returns `Produced` only if an explicit accepted-loss + policy drops the `active` flags, or if the IR target also carries them. + Plain list to PTX requires the `active` flags supplied per lane; + otherwise it returns `Rejected { diagnostic: Diagnostic }`. + +The model prevents treating inactive lanes as false values. That distinction is +a structural coordinate, not a convention. + +--- + +## 12. `.dag` — `Arrow` declaration (the language modeling itself) + +In v4, a function-like declaration is an `Arrow`: parameter facts, result fact, +and a body/realization authority. + +**Model:** + +``` +// CARRIER — a typed mapping plus its authoritative realization. +type DagArrow = Conj { + params: List, + result: TypeNode, + body: Body | ExternalRealization +} + +// MEANING — a total transform from parameter groundings to result grounding, +// checked by the body or named external realization. +``` + +**Step-by-step coercion shape — `DagArrow Int32> -> Outcome`:** +1. params and result ground as type nodes in the shared substrate. +2. the coercion fold matches `Arrow` against function type + structure. +3. parameter/result types recurse; `Int32` coincides with itself. +4. the signature comparison returns `Produced`; body coercion is not a type + alias. It returns `Produced` only when the body or external realization is + the declared authority, otherwise `Rejected { diagnostic: Diagnostic }`. + +This is self-grounding without circularity: the carrier is substrate data, and +the meaning is checked through the same structural rules as user code. + +--- + +## 13. JSON — object (unordered named fields) + +A JSON object is an unordered mapping from strings to JSON values. Member order +is serialization syntax, not object meaning. + +**Model:** + +``` +// CARRIER — finite map from string keys to recursively grounded JSON values. +// Each recursive-container arm carries its payload, so `JsonValue` is the +// single authority for a JSON value's content (no label-only variant whose +// payload lives in a separate type). +type JsonValue = Null | Bool | Number | String + | Array> + | Object +type JsonObject = Map + +// MEANING — the map. Duplicate source keys are a parse-boundary diagnostic, +// not two object fields. +``` + +**Step-by-step coercion shape — `JsonObject -> Outcome`:** +1. JSON object grounds to `Map`. +2. IR record grounds to a closed `Conj` with required fields. +3. the coercion fold compares map entries to field + coordinates by key. +4. every required key plus recursively produced values return `Produced`. + Missing keys, duplicate keys, or non-natural `age` return + `Rejected { diagnostic: Diagnostic }`. + +Object member order never participates in the coercion. If a consumer needs +source order, that is a separate syntax/provenance fact. + +--- + +## 14. YAML — mapping with anchors (graph-shaped syntax, tree-shaped data) + +YAML can express aliases and anchors, so its syntax may be graph-shaped even +when the decoded data model is a mapping/sequence/scalar tree. + +**Model:** + +``` +// CARRIER — resolved YAML node plus optional source anchor identity. +type YamlNode = + Scalar +| Sequence> +| Mapping> +| Alias + +// MEANING — after alias resolution, a YAML value tree; anchor identity remains +// provenance unless the target asks for graph identity. +``` + +**Step-by-step coercion shape — `YamlMapping -> Outcome`:** +1. resolve aliases through the declared anchor map; unresolved aliases return + `Rejected { diagnostic: Diagnostic }`. +2. mapping grounds to a finite map of key/value node groundings. +3. IR record grounds to named coordinates. +4. scalar-string keys matching field names plus recursively produced values + return `Produced`; non-scalar keys or unresolved aliases return + `Rejected { diagnostic: Diagnostic }`. + +The model does not pretend YAML is JSON. Anchors are grounded syntax facts with +a declared resolution step. + +--- + +## 15. CSV — row (positional fields under a schema) + +A CSV row alone is only a list of fields. Names and types come from an external +schema or header row, not from the row bytes themselves. + +**Model:** + +``` +// CARRIER — ordered fields plus the schema that assigns names and decoders. +type CsvRow = Conj { + fields: List, + schema: S +} + +// MEANING — a record only after schema/header facts decode positions. +``` + +**Step-by-step coercion shape — `CsvRow -> Outcome`:** +1. row grounds to `List`; schema grounds to field names and decoders. +2. the coercion fold aligns positions to record coordinates + through the schema. +3. `id` string decodes through `Nat` grammar; `name` remains string. +4. matching arity plus successful decoders return `Produced`; extra, missing, + or undecodable fields return `Rejected { diagnostic: Diagnostic }`. + +Without the schema, a CSV row cannot coerce to a named record. It remains an +ordered string list; an attempted record coercion returns `Rejected`. + +--- + +## 16. TOML — table (typed configuration map) + +A TOML table is a named map whose values come from TOML's closed value set: +strings, integers, floats, booleans, dates/times, arrays, and tables. + +**Model:** + +``` +// CARRIER — finite map from dotted keys to closed TOML values. Each +// recursive-container arm carries its payload, so `TomlValue` is the +// single authority for a TOML value's content. +type TomlValue = String | Integer | Float | Bool | DateTime + | Array> + | Table +type TomlTable = Map + +// MEANING — a hierarchical record assembled from key paths. +``` + +**Step-by-step coercion shape — `TomlTable -> Outcome`:** +1. table grounds to a map of key paths to closed value variants. +2. IR config grounds to record coordinates with expected types. +3. the coercion fold aligns dotted key paths to nested + record fields. +4. existing required paths plus recursively produced TOML variants return + `Produced`; duplicate paths, conflicting table/value paths, and missing + required values return `Rejected { diagnostic: Diagnostic }`. + +TOML's value variants are a closed sum. Modeling them as strings would erase the +target's typed facts. + +--- + +## 17. JSON Schema — object schema (constraints over JSON values) + +JSON Schema does not ground as a JSON object value. It grounds as a predicate +over JSON values, encoded in JSON syntax. + +**Model:** + +``` +// CARRIER — JSON syntax for a closed set of validation keywords. +type JsonSchemaObject = Conj { + type_keyword: Optional, + properties: Map, + required: Conj { + names: List, + unique_proof: Witness< all_distinct(names) > // JSON Schema: the `required` + // array elements MUST be unique + } +} + +// MEANING — a predicate: JsonValue -> Bool, plus witnesses for accepted values. +``` + +**Step-by-step coercion shape — `JsonSchemaObject -> Outcome`:** +1. schema grounds to constraints: allowed JSON kind, property schemas, required + property names. +2. IR record type grounds to required coordinates and their value groundings. +3. the coercion fold compares required properties to record + fields and recurses into property schemas. +4. the closed fragment whose constraints exactly determine the record shape + returns `Produced`; open `additionalProperties` or unconstrained fields + return `Rejected { diagnostic: Diagnostic }` for record-type coercion and + remain predicate facts. + +The schema is not the data. Its meaning is validation, so coercion produces type +facts only when the predicate is structurally precise enough. + +--- + +## 18. OpenAPI — operation object (HTTP contract) + +An OpenAPI operation describes a request/response contract over HTTP. The +operation is not an endpoint implementation; it is a typed boundary declaration. + +**Model:** + +``` +// CARRIER — method/path plus parameter, request-body, response, and status facts. +// `content` (OpenAPI Request Body / Response Object) is a MEDIA-TYPE MAP — +// one schema per media type, with multiple alternatives (e.g. application/json +// AND application/xml) — never a single schema. +type ContentMap = Map +type OpenApiOperation = Conj { + method: HttpMethod, + path: PathTemplate, + parameters: Conj { + items: List, + unique_proof: Witness< all_distinct_by(items, name_and_location) > + // OpenAPI: parameters MUST be unique by (name, `in`) location + }, + request: Optional, + responses: Map // status → content map; the keys + // at both levels unique by Map +} + +// MEANING — a partial function from grounded HTTP requests to grounded HTTP +// responses, indexed by status code and then by media type. +``` + +**Step-by-step coercion shape — `OpenApiOperation -> Outcome`:** +1. method/path ground to HTTP target facts; parameters ground through location + facts (`path`, `query`, `header`, `cookie`). +2. request and response schemas ground through their JSON Schema meanings. +3. the coercion fold compares the request side to the IR + arrow input record and the response map to the IR result sum. +4. every parameter/body/response schema grounding to the corresponding IR type + returns `Produced`; missing status cases or ungrounded schemas return + `Rejected { diagnostic: Diagnostic }`. + +This keeps OpenAPI as a boundary contract. The implementation body remains a +separate authority, connected only after the contract groundings line up. diff --git a/src/v4/DECISIONS.md b/src/v4/DECISIONS.md index 461dae519c1..7b4e09fa80f 100644 --- a/src/v4/DECISIONS.md +++ b/src/v4/DECISIONS.md @@ -55,10 +55,11 @@ through — and moves to Part 1. | **C5-3** | **F = the spec-provable meaning core; spec silence ⇒ out of F** (operator-ratified 2026-05-16; conservative/fail-safe). If the language spec does not *unambiguously* place a feature on the meaning side, it is NOT in F — Declared-normalized (emit canonicalizes; recorded per-feature) or Fail-closed (ingest needs semantics it lacks ⇒ Diagnostic, never a guess). The **spec decides; the modeler has no discretion**. Consequence: a language's lossless core may be strictly smaller than its spec (e.g. C++ most-vexing-parse → out, Fail-closed), declared per-feature **up front** in the C5-fidelity disposition table, never discovered at round-trip-test time. Sharpens the pre-existing C5 / C5-fidelity rows | `lens/testgen.dag` C5-1/C5-3 block + `extdeps/languages/*` C5-fidelity dispositions | | **AGENT-1** | The **non-text agent surface** (operator-ratified 2026-05-15 — *include & design early; explicitly NOT the north star*; "a very important/exclusive feature" but a NATURAL CONSEQUENCE, not a new subsystem). A non-text client (LLM/agent) interacts with the program **as data, never files**: READ = `apply_lens` at `SectionRef` + `affected_set(dag,diff)` (the affected lens replaces file-reading exploration); WRITE = the **D1** `apply_diff:(Node,Diff)->Result` (the ratified D1 operation — NOT a total `->Node`; an agent-supplied Diff is external/possibly-stale input ⇒ FAIL-CLOSED typed Diagnostic, all-or-nothing, INVARIANTS P3 — AGENT-1 uses D1's op, does not restate a total one) entering the B2-OMNI pipeline at **`core`** (a SIBLING of `ingest`, NOT an ingest — the change is already Node: no source text, no LanguageModel, no parse), content-addressed (B1), not a text patch; BACK = the `affected_set` lens read in whatever shape T-21/`lens/affected_set.dag` DECLARES — AGENT-1 is a CLIENT, defers to that single authority (P2) and coins NO return noun (`Witness` was an ungrounded AGENT-1 noun, P1/P2 — removed) + a faithful re-emit (C5-1 node-level hash-checked + C5-2 emit-locality + C4 committed==emit); GATE = `apply_lens(_,Enforce)` fail-closed (agent earns no special trust). It is a **CLIENT** of application.dag + affected_set + B2-OMNI + C5/C4 — NO new authority/noun/query subsystem (QRY-1 + feedback_closed_system_design). Owned by T-23 so it is a contract, not an accident; realized only when T-23 composes T-21 + B2-OMNI + C5/C4 (scaffold today — nothing runs yet) | `lens/application.dag` header (AGENT-SURFACE block) + `compiler/00_compile.dag` B2-OMNI back-ref + `TASKS.md` T-23 note | | **I** | **Fail-closed success/failure beside `Diagnostic` (M6 / P2).** v4's **single** substrate coproduct for "produced value vs fail-closed reject carrying gunbc's `Diagnostic`" is **`Outcome`** with variants `Produced { value: ok }` and `Rejected { diagnostic: Diagnostic }` in `std/diagnostic.dag` (operator-ratified 2026-05-16). `TASKS.md` / `STRUCTURE.md` **`Result<…, Diagnostic>` prose** names the **same semantic surface** — it **denotes `Outcome<…>`**, not a second parallel `.dag` `Result` type. v4 **does not** declare a generic `Result` in `std/` alongside `Outcome`; introducing one would duplicate M6's authority unless this ledger is amended. Variant/field names are **binding** for downstream mirrors. A future *different* error payload (non-`Diagnostic`) is a new substrate decision (STOP), not an unratified shadow carrier. | `std/diagnostic.dag` (`Outcome`) + this row; `TASKS.md` / `STRUCTURE.md` (prose only) | -| **D2** | **Primitive-inhabitance FORM — the `extdeps` resolver shape** (operator-ratified 2026-05-16; resolves the loyal-koi-702 STOP-2/STOP-3 escalated via the T-4 mgr). A language/format `extdeps` file is a **resolver** for the abstract `std/` carriers — the `infra(abstract)→gcloud/aws(concrete)` pattern (operator-cited prior art: gunb.ai `tools/extdeps/cloud_extdeps`, where the abstract `InfraScopeType` is declared ONCE and each provider supplies a translation, never a re-declaration). **D2a — three thin per-primitive declarations, NO re-declared algebra inhabitance:** (1) **alias-identity** to the `std/` carrier (`type RustI32 = Int32`) — the machine-readable-inhabitance form (`List = FreeMonoid` precedent); the algebra inhabitance flows through the alias, so "see through the labels" is literal `Node` identity; (2) a **grounding map** (surface spelling — `i32`); (3) **operation-semantics carriers** (`OverflowDisposition`, NaN/Inf handling) — genuine per-language facts, siblings to the alias. A per-language `data _: OrderedRing<Prim,…>` inhabitance is the parallel `OrderedRing` substrate **INVARIANTS P1:42 forbids** (`numeric_aliases_align_to_refinements`) — superseded; #3174's `RustScalar` Disj registry + `IrToRust<>` carrier dissolve into this shape. **D2b — fn-value form:** the integer chain is fully CONSTRUCTIVE (Peano `Nat` → `GroupCompletion` → `AbelianGroup` → `Compose`) — its operation `Arrow` bodies are sub-DAGs of L1 behaviors (THESIS:203, the user-function case), so D2b's primitive question never fires for `integer.dag`. A genuinely-irreducible spec primitive (IEEE-754 float arithmetic) flows through the SAME single external-primitive path THESIS:203 already defines — `Transform → FunctionRef → Arrow`, where the `Arrow`'s `body` is *a realization declaration in `extdeps/`* (THESIS:203's primitive case). D2b coins **NO new carrier**: no `Symbol`+`Anchor` data node referenced directly by the inhabitance — that would be the second external-primitive path P2 forbids. The `ApproximateField` inhabitance holds `FunctionRef`s to the op `Arrow`s; for an IEEE-754 primitive the `Arrow`'s `body` realization (anchored to the spec §) is the per-target `extdeps/languages/*` resolver (the D2.2 resolver), not a std-homed carrier. The `Arrow` HAS a body (the `extdeps/` realization), so it is not a bodiless `fn` and PARSE-1 is untriggered; NOT a kernel/A1 extension (no new connective/behavior). **D2.2 — coercion** = the U1 homomorphism realized by the generic B2-OMNI emit fold reading the resolver data; NOT a hand table (the `IrToRust<>` per-target string table INVARIANTS P1 forbids), NOT a per-language emit lens (B2-OMNI/B4: one generic emit, target-specificity is declarative T-11 data). **D2.3** — compound/generic coercion composes for FREE via the `Node` catamorphism (A1's single recursive type; `List` = `Instantiation` recursed); no per-instantiation rows, not blocked on the Functor hierarchy (a cost/algebra-lens concern). **D2.4** — the round-trip guarantee is structural-on-F per **C5-1**; TestClaims document it, never establish it. **D2.5** — overflow/UB/arbitrary-precision are DISTINCT `std/` carriers selected by the alias target + the per-language `OverflowDisposition` carrier, never a re-declared semantics. **Scope — D2 covers per-primitive inhabitance form ONLY:** it does NOT decide LanguageModel-grammar facts (C++ most-vexing-parse, TypeScript structural typing, etc.) — those are owned by C5-3 / B2-OMNI / B4 per their own cascade; a grammar-slice worker must not import D2 reasoning into them. | `std/integer.dag` + `std/float.dag` headers (D2 blocks) + `TASKS.md` T-4 brief amendment + `extdeps/languages/*` headers (workers encode the resolver shape); cross-ref INVARIANTS P1 / A1 / B2-OMNI / U1 / C5-1 / IR-1 | +| **D2** | **[SUPERSEDED by D2-REV — see the D2-REV row below + the "D2 REVERSAL" section]** **Primitive-inhabitance FORM — the `extdeps` resolver shape** (operator-ratified 2026-05-16; resolves the loyal-koi-702 STOP-2/STOP-3 escalated via the T-4 mgr). A language/format `extdeps` file is a **resolver** for the abstract `std/` carriers — the `infra(abstract)→gcloud/aws(concrete)` pattern (operator-cited prior art: gunb.ai `tools/extdeps/cloud_extdeps`, where the abstract `InfraScopeType` is declared ONCE and each provider supplies a translation, never a re-declaration). **D2a — three thin per-primitive declarations, NO re-declared algebra inhabitance:** (1) **alias-identity** to the `std/` carrier (`type RustI32 = Int32`) — the machine-readable-inhabitance form (`List = FreeMonoid` precedent); the algebra inhabitance flows through the alias, so "see through the labels" is literal `Node` identity; (2) a **grounding map** (surface spelling — `i32`); (3) **operation-semantics carriers** (`OverflowDisposition`, NaN/Inf handling) — genuine per-language facts, siblings to the alias. A per-language `data _: OrderedRing<Prim,…>` inhabitance is the parallel `OrderedRing` substrate **INVARIANTS P1:42 forbids** (`numeric_aliases_align_to_refinements`) — superseded; #3174's `RustScalar` Disj registry + `IrToRust<>` carrier dissolve into this shape. **D2b — fn-value form:** the integer chain is fully CONSTRUCTIVE (Peano `Nat` → `GroupCompletion` → `AbelianGroup` → `Compose`) — its operation `Arrow` bodies are sub-DAGs of L1 behaviors (THESIS:203, the user-function case), so D2b's primitive question never fires for `integer.dag`. A genuinely-irreducible spec primitive (IEEE-754 float arithmetic) flows through the SAME single external-primitive path THESIS:203 already defines — `Transform → FunctionRef → Arrow`, where the `Arrow`'s `body` is *a realization declaration in `extdeps/`* (THESIS:203's primitive case). D2b coins **NO new carrier**: no `Symbol`+`Anchor` data node referenced directly by the inhabitance — that would be the second external-primitive path P2 forbids. The `ApproximateField` inhabitance holds `FunctionRef`s to the op `Arrow`s; for an IEEE-754 primitive the `Arrow`'s `body` realization (anchored to the spec §) is the per-target `extdeps/languages/*` resolver (the D2.2 resolver), not a std-homed carrier. The `Arrow` HAS a body (the `extdeps/` realization), so it is not a bodiless `fn` and PARSE-1 is untriggered; NOT a kernel/A1 extension (no new connective/behavior). **D2.2 — coercion** = the U1 homomorphism realized by the generic B2-OMNI emit fold reading the resolver data; NOT a hand table (the `IrToRust<>` per-target string table INVARIANTS P1 forbids), NOT a per-language emit lens (B2-OMNI/B4: one generic emit, target-specificity is declarative T-11 data). **D2.3** — compound/generic coercion composes for FREE via the `Node` catamorphism (A1's single recursive type; `List` = `Instantiation` recursed); no per-instantiation rows, not blocked on the Functor hierarchy (a cost/algebra-lens concern). **D2.4** — the round-trip guarantee is structural-on-F per **C5-1**; TestClaims document it, never establish it. **D2.5** — overflow/UB/arbitrary-precision are DISTINCT `std/` carriers selected by the alias target + the per-language `OverflowDisposition` carrier, never a re-declared semantics. **Scope — D2 covers per-primitive inhabitance form ONLY:** it does NOT decide LanguageModel-grammar facts (C++ most-vexing-parse, TypeScript structural typing, etc.) — those are owned by C5-3 / B2-OMNI / B4 per their own cascade; a grammar-slice worker must not import D2 reasoning into them. | `std/integer.dag` + `std/float.dag` headers (D2 blocks) + `TASKS.md` T-4 brief amendment + `extdeps/languages/*` headers (workers encode the resolver shape); cross-ref INVARIANTS P1 / A1 / B2-OMNI / U1 / C5-1 / IR-1 | | **D3** | **ApproximateField machine-readable witness — encoding deferred (INVARIANTS P1/P3)** (operator spine 2026-05-16 for float algebra **shape** via **D2b** + Tier-2 **D2** intrinsic `Symbol` nan identities; **amended** after codex REQUEST_CHANGES on **PR #3191**). `std/float.dag` **does not** publish `data float_approximate_field: ApproximateField` while v2-bridge constructive `fn` bodies at this site would fabricate IEEE finite `+`/`*` or binary64 `one` (left-operand hooks or wrong-bias `Succ` on the Peano exponent carrier = known-wrong machine-readable authority — INVARIANTS P1 modeling faithfulness + P3 fail-closed honesty). Re-introduce the data row when **T-4 `extdeps/languages/*`** supplies grounded THESIS:203 **Arrow** bodies **and/or** v4 admits bodiless primitive signatures (**PARSE-1**). **Does ship:** `Float` carrier + Tier-2 `Outcome` ordered compare + intrinsic `data : Symbol = ` for nan rejection (cross-ref **D2**, **I**, **PARSE-1**). | `std/float.dag` (carrier + Tier-2 compare + `Symbol` data; **no** `data float_approximate_field` until grounded) + this row | -| **D4** | **GroundingMap-home — the shared `extdeps/languages/resolver.dag` registry** (operator-ratified 2026-05-16; co-drafted; completes **D2**). The D2 resolver's *shared* types live in ONE new file `extdeps/languages/resolver.dag` — NOT re-declared per language (parallel-declaration P2 forbids; `feedback_import_not_redeclare_carriers`) and NOT homed in `rust.dag` (which would make one language file a substrate authority for the other four, and balloon as future shared resolver types land). `type GroundingMap { spelling: String }` is its first resident. **Admission rule (STRICT):** `resolver.dag` hosts ONLY *structurally-language-INVARIANT* resolver types — a type whose structure provably cannot vary across the modeled language specs (a convergence carrier). Spec-varying types stay per-language (`OverflowDisposition` etc. — D2.5 / L-2). Test before admitting: can you prove the structure invariant across the specs? Future shared resolver types (e.g. the C5-fidelity `Modeled \| Declared-normalized \| Fail-closed` disposition classifier) land here without a fresh placement decision. Closed-tree extension: `STRUCTURE.md` `.dag` count +1. Per-language files each add a one-line `import … resolver { GroundingMap }` + their per-primitive `data __grounding` instances (the grounding-row fan-out — canonical `rust.dag` first, then the 4 others). | new `extdeps/languages/resolver.dag` + `STRUCTURE.md` count/enumeration + `extdeps/languages/*` import lines + grounding instances; this row; cross-ref **D2** | +| **D4** | **[SUPERSEDED by D2-REV — see the D2-REV row below + the "D2 REVERSAL" section]** **GroundingMap-home — the shared `extdeps/languages/resolver.dag` registry** (operator-ratified 2026-05-16; co-drafted; completes **D2**). The D2 resolver's *shared* types live in ONE new file `extdeps/languages/resolver.dag` — NOT re-declared per language (parallel-declaration P2 forbids; `feedback_import_not_redeclare_carriers`) and NOT homed in `rust.dag` (which would make one language file a substrate authority for the other four, and balloon as future shared resolver types land). `type GroundingMap { spelling: String }` is its first resident. **Admission rule (STRICT):** `resolver.dag` hosts ONLY *structurally-language-INVARIANT* resolver types — a type whose structure provably cannot vary across the modeled language specs (a convergence carrier). Spec-varying types stay per-language (`OverflowDisposition` etc. — D2.5 / L-2). Test before admitting: can you prove the structure invariant across the specs? Future shared resolver types (e.g. the C5-fidelity `Modeled \| Declared-normalized \| Fail-closed` disposition classifier) land here without a fresh placement decision. Closed-tree extension: `STRUCTURE.md` `.dag` count +1. Per-language files each add a one-line `import … resolver { GroundingMap }` + their per-primitive `data __grounding` instances (the grounding-row fan-out — canonical `rust.dag` first, then the 4 others). | new `extdeps/languages/resolver.dag` + `STRUCTURE.md` count/enumeration + `extdeps/languages/*` import lines + grounding instances; this row; cross-ref **D2** | | **D5** | **Operator-driven frozen-header / frozen-contract reconcile is sanctioned in-PR** (operator-ratified 2026-05-16). "Preserve-verbatim" on a frozen scaffold header forbids *unsanctioned worker contract-drift* — it does NOT forbid *sanctioned reconciliation*. When an operator-tier action (a BLOCKING finding, an operator ruling) legitimately moves a worker's body past its frozen header or I/O contract, the header/contract is **reconciled to match in the SAME PR**, flagged with a `HEADER RECONCILE` block citing the driving operator action. **Discriminator:** an operator-tier action drove the body change ⇒ reconcile the header/contract in-PR, flagged; NO operator action drove it ⇒ the body must conform to the frozen header (preserve-verbatim holds, the worker cannot move the contract). Covers BOTH header-doc drift (stale `Owns`/`Consumes` bullets after a sanctioned refactor) AND frozen-contract changes (operator BLOCKS an I/O contract as P2/§2-insufficient). Already operating: `integer.dag` #3190 (`Consumes` reconciled), #3209 finding 2 (`WaitProcessResult`). Does NOT permit free worker header edits — operator-driven only. | this row + the `HEADER RECONCILE` block convention in affected file headers (`integer.dag` #3190 precedent form); refines the frozen-scaffold-header / preserve-verbatim discipline | +| **D2-REV** | **D2 / D4 REVERSED — fact-bundle modeling supersedes alias-identity** (operator-ratified 2026-05-17, **out-of-band** — the verbatim operator-quote provenance is in the "D2 REVERSAL" section below). An `extdeps` primitive is modeled as a fact-bundle grounded from its own spec, never a bare `std/` alias; deduplicate to a `std/` carrier only on *proven* coincidence; the structural fact-density / hollow-alias gate is `T-30`, a hard prerequisite of T-4. This is a one-line index pointer — the full record (root cause, phased plan, impact map, "coincide" definition) is the **"D2 REVERSAL + FACT-BUNDLE RESEED"** section below, which is the authority. Supersedes the **D2** and **D4** rows above. | the **"D2 REVERSAL + FACT-BUNDLE RESEED"** section of this file (authority); `#3224` executes Phase 1; `docs/modeling/grounding-worked-examples.md` companion | --- @@ -281,6 +282,157 @@ or defer to the task. --- +## D2 REVERSAL + FACT-BUNDLE RESEED — RATIFIED (2026-05-17) + +> Operator-declared and **RATIFIED 2026-05-17**. This section +> **supersedes D2** (and its downstream D4). The operator declared D2 +> wrong, ratified the fact-bundle principle, and dispatched the Phase-1 +> execution (PR #3224) — so the decision is ratified, not awaiting a +> merge vote. This PR (#3223) is the ledger encoding of that ratified +> decision; #3224 executes Phase 1 against it. + +### What reversed + +D2 ratified the **alias-identity inhabitance form**: a language `extdeps` +file declares each primitive as `type X = StdX` (e.g. +`type RustI32 = Int32`), the algebra "flowing through the alias." D4 +homed the shared D2-resolver type (`GroundingMap`) in +`extdeps/languages/resolver.dag`. + +The operator declared D2 **wrong** (verbatim: *"D2 is wrong — i was +misunderstanding the purpose of this alias"*). A bare alias is not +modeling: it asserts an *unproven* identity between our carrier and an +external language's, while reading **zero facts** from that language's +spec. `type RustI32 = Int32` models nothing about Rust. + +### Root cause — an enforcement gap, not a missing principle + +`MODELING.md` **M1** ("types decompose into facts") and **M3** ("extdeps +model specs") already mandate fact-modeling. The principle was not +missing. Two failures let the alias through: + +1. **`INVARIANTS.md` P1:42** (`numeric_aliases_align_to_refinements`) + forbids a *parallel `OrderedRing` substrate* — do not + re-declare the algebra per language. D2 read this as "therefore + bare-alias the whole carrier," conflating *algebra duplication* + (correctly forbidden) with *carrier fact-modeling* (wrongly dropped). +2. **A hollow alias is invisible to every structural gate.** + `type RustX = StdX` is structurally minimal — nothing for a reviewer + or checker to flag. The api-review rubric (`INVARIANTS.md` + + `docs/modeling-discipline.md`) checks duplicate authority and coproduct + dissolution; it has no **fact-density** check. Aliasing passes review + *because* it is hollow. + +### The replacement — fact-bundle modeling + +Operator-stated principle (2026-05-17), governing the reseed: + +- **Model the facts. Always.** Deduplicate two models into one **only** + when their identity is **proven** — identity is an evidenced claim, + never an assumed default. +- **Invent or reuse — a bare alias is neither.** To model an external + primitive you either *invent* a fact for it (read from that system's + spec) or *reuse* a `std/` fact (with cited evidence of identity). +- **External defaults to separate; internal defaults to reuse.** + `extdeps/` models systems we do not control and do not fully know → + default to separate, honest, accumulated modeling; reuse `std/` only + on evidenced identity. Internal code (compiler layers, our own + substrate) → we control both sides, identity is usually *known* → + default to reuse `std/`, still naming the evidence. Keeping + `RustSignedness` separate until Rust's spec is checked is honest + modeling, not a duplicate-authority violation. + +### The phased plan + +- **Phase 0 — stop the bleeding. DONE 2026-05-17.** `#3219` + (`resolver.dag`, the D2-resolver encoding-half) closed; `#3208` + (lean/machine_code, D2-resolver-shaped) held. Forward-fix, not revert. +- **Phase 1 — the doc keystone (rubric + enforcement).** Amend + `INVARIANTS.md` P1:42 so "aligns to refinements" means *the language + carrier is a fact-bundle coinciding with the std carrier*, not a bare + alias. Promote `MODELING.md` M1 to a named first-class rule. Add a new + Practice to `docs/modeling-discipline.md` — "model facts, not aliases" + — with a worked good example (fact-bundle) and bad example (bare + alias); since the api-review rubric reads that doc, a documented + bad-example arms every review against the hollow alias. That is the + *first* enforcement tier — but it is reviewer-applied, i.e. + convention-level until a structural/API gate exists. Phase 1 ships that + documented bad-example: the convention-tier enforcement that the + `docs/modeling-discipline.md` api-review practice checks. The stronger + *structural* tier — a generated **fact-density / hollow-alias gate** — + is **its own foundation task, `T-30`** (a sibling of P1-KEYSTONE, NOT + folded into `docs/modeling-discipline.md`), and it is a **hard + prerequisite of T-4**: the per-language fact-bundle rework does not + begin until the structural gate exists. + This resolves a real gap by a dependency edge, not a phase argument. D2 + slipped through *two* failures (see root cause above): an **inverted** + `P1:42` — misread as *licensing* the alias — and the **absence** of any + bad-example for review to fail against. Phase 1 corrects both — it + re-points `P1:42` and adds the bad-example, net-new versus the pre-D2 + state. But a documented bad-example is *convention* enforcement, and + convention is exactly what let D2 through; reworking every per-language + file under convention-tier-only enforcement would re-expose that + surface. So the structural gate is **not** a loose follow-up and **not** + sequenced by phase number — it is `T-30`, with a hard edge `T-30 → T-4`, + landing *before* the per-language reseed by construction. The documented + bad-example is the **interim floor only**: it holds the line until + `T-30` lands; it is explicitly *not* the enforcement the per-language + rework runs under. + Reverse the D2/D4 rows. Rewrite the + `TASKS.md` T-4 authoring contract. +- **Phase 2 — rework the entire T-## program** around fact-bundle + modeling, first-class, plus the `std/` substrate axes the model needs + that do not exist yet: signedness, representation, and an + **exact-real carrier plus a physical-quantity carrier** — surfaced by + the SPICE worked example, where a node voltage is an exact real value + carrying a physical quantity (volts) that the approximate `f64` carrier + cannot ground without declared loss. (Rational is at most a narrower + inhabitant of the exact-real carrier, not the carrier itself.) The + structural fact-density / hollow-alias gate is **not** a Phase-2 item — + it is `T-30`, a hard prerequisite of T-4 (see Phase 1). +- **Phase 3 — execution.** Per-task / per-language / per-compiler-layer + modeling rework, Rust exemplar first, under the Phase-1 rubric. + +### Impact-map disposition (the close/revert/rework list) + +`extdeps/languages` files and the merged D2 commits were classified +(grep-verified). The unwind is **forward-fix / supersession**, never +`git revert` of the merged commits (#3195 D2, #3216 D4/D5) — that would +clobber surviving language vocabulary and the `std/` numeric core. + +- **Orthogonal — untouched:** the `std/` numeric core + (`Int`/`UInt`/`Compose`/algebra witnesses/`Float`), `llvm_ir`/`ptx` + carriers, the format models, `react`, `coordination`, + `process`/`file_system`. +- **D2-encoding — rework (vocabulary preserved):** the 5 merged language + files (`rust`/`python`/`go`/`cpp`/`typescript`); `verilog`/`llvm_ir`/ + `ptx` prose-only; `INVARIANTS.md` P1:42 (the doc root); `DECISIONS.md` + D2/D4; `TASKS.md` T-4 contract; the `std/integer.dag` / + `std/float.dag` D2 header prose (NOT the core). +- **Active PRs:** `#3219` closed; `#3208` held. + +### Worked examples + +`docs/modeling/grounding-worked-examples.md` (this PR) demonstrates the +fact-bundle/grounding model on one complex type per target — spanning +`machine_code` (pure bits) → `rust` → `verilog` (4-valued logic) → +`spice` (continuous) → `lean` (dependent types) → `english` (natural +language, mostly fail-closed). Each: the model (carrier + meaning) and +step-by-step coercion. Plan-only; the remaining mainstream +language/format targets fan out against the same template. + +### Status + +**RATIFIED 2026-05-17** (operator, out-of-band — the operator declared D2 +wrong [the verbatim operator quote is in *What reversed* above, this same +section], ratified the fact-bundle principle, and dispatched the Phase-1 +execution). Phase 1 is executing now as **PR #3224** (TASKS.md + +DECISIONS.md re-sequencing). This PR (#3223) encodes the ratified +decision into the ledger; #3224 is stacked on it. TASKS.md consuming the +D2-reversal as ratified is therefore correct, not premature. + +--- + ## Part 5 — Ratification flow For each PROPOSED item: ratify (👍 / "confirm") or redirect ("instead,