From 77879c1823ef458b0de11e8d5e372bc5f6acf41b Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:18:07 -0500 Subject: [PATCH 1/4] Squashed 'repos/constitution/' changes from 63e9813b874..a14be1581b4 a14be1581b4 docs: rewrite the README as a front page for people deciding to use it (#34) b07a664f79e fix(enforcement): judge refusal properties without generated laws (#31) d4bac76f296 revert: remove the law audit report from the constitution (#33) b7dbd9bb8a7 docs(audits): first law audit of the sixteen laws (#32) f97212e007b fix(validator): refuse invented lineage ids and prose definition lines (#30) 0c81dcbbbce fix(validator): accept later-minted lineage ids, vendored corpora, and gate the hook on both tasks (#29) d189d3d3002 refactor(constitution)!: rewrite into 16 laws with an ENFORCEMENT corpus (#28) 693a6d7e905 fix(constitution)!: vacate CONST-T4 with no replacement (#26) 37c076fcbf9 fix(constitution)!: vacate CONST-T11 and state no-self-oracle rule in CONST-T10 (#25) git-subtree-dir: repos/constitution git-subtree-split: a14be1581b48c9ea18e3c71f5fce5819f5a29ca8 --- .husky/pre-commit | 2 +- AGENTS.md | 21 +- CONCEPTS.md | 6 +- CONSTITUTION.md | 498 ++----- CONTRIBUTING.md | 47 + ENFORCEMENT.md | 260 +++- README.md | 102 +- deno.json | 3 +- ...0320-refactor-constitution-rewrite-plan.md | 1175 +++++++++++++++++ ...expected-value-from-the-code-under-test.md | 41 + ...opment-time-evidence-is-never-committed.md | 82 -- .../the-vacuous-pass-gate-input-sets.md | 56 +- ...x-rules-flag-translation-backreferences.md | 40 - scripts/validate-constitution.test.ts | 956 ++++++++++++++ scripts/validate-constitution.ts | 1035 ++++++++++++--- 15 files changed, 3501 insertions(+), 823 deletions(-) create mode 100644 CONTRIBUTING.md create mode 100644 docs/plans/2026-10-09-0320-refactor-constitution-rewrite-plan.md create mode 100644 docs/solutions/architecture-patterns/a-test-never-takes-its-expected-value-from-the-code-under-test.md delete mode 100644 docs/solutions/architecture-patterns/development-time-evidence-is-never-committed.md delete mode 100644 docs/solutions/architecture-patterns/ttsr-regex-rules-flag-translation-backreferences.md create mode 100755 scripts/validate-constitution.test.ts diff --git a/.husky/pre-commit b/.husky/pre-commit index 9b938ee..fdf054a 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1 +1 @@ -deno task test +deno task test && deno task test:validator diff --git a/AGENTS.md b/AGENTS.md index 381cf84..c0de45c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # AGENTS.md — Constitution Repository -Single source of truth for the supreme design law of [System F Software](https://systemfsoftware.com). Consumer repos vendor via `git subtree` + symlink. This repo has no production code, no test suite, and no build step — it is two documents plus governance tooling (corpus validation, commit validation): `CONSTITUTION.md`, the maker's law, resident in every agent's context, all articles, always; and `ENFORCEMENT.md`, the instrument owner's doctrine, never loaded into the maker's context. +Single source of truth for the supreme design law of [System F Software](https://systemfsoftware.com). Consumer repos vendor via `git subtree` + symlink. This repo has no production code, no test suite, and no build step — it is two documents plus governance tooling (corpus validation, commit validation): `CONSTITUTION.md`, the maker's law, resident in every agent's context, every law, always; and `ENFORCEMENT.md`, the instrument owner's doctrine, never loaded into the maker's context. @CONSTITUTION.md @@ -25,12 +25,15 @@ Before making changes: ### Corpus -- **`CONSTITUTION.md` (Resident):** the entire maker corpus — the Application section plus Articles I–V — loaded in every session. There is no retrieved half and no on-demand trigger: law that is not in the window is not law. Residency delivers obligation, not enforcement; the machinery of judgment lives outside the maker's reach. +- **`CONSTITUTION.md` (Resident):** the entire maker corpus — a one-line preamble and the laws in four sections (Model the domain, Shape the code, Prove it, Finish) — loaded in every session. There is no retrieved half and no on-demand trigger: law that is not in the window is not law. Residency delivers obligation, not enforcement; the machinery of judgment lives outside the maker's reach. - **`ENFORCEMENT.md` (Non-resident):** the instrument owner's doctrine — gate design, instrument-change discipline, enrollment law. Read by whoever builds or changes a gate, never `@`-imported into a maker's context. Consumer repos route to it from the leaves that own enforcement surfaces (lint plugins, guard scripts, CI workflows, rules directories, advisor rosters): one line — "You are editing an enforcement instrument. Read the vendored `ENFORCEMENT.md` before this lands." A routing line added anywhere else is the defect: the maker must not meet instrument doctrine while doing graded work. +- **`docs/solutions/`:** past problems and their fixes, organized by category with YAML frontmatter (`module`, `tags`, `problem_type`); `CONCEPTS.md` at repo root holds shared domain vocabulary. ### Writing a Rule -Rules are fenced YAML blocks with: `id`, `title`, `gate`, `do`, `dont`, `harm`, `check` (and optional `example`, `scope`, `layers`). +Laws are fenced YAML sequences, one block per section of `CONSTITUTION.md`. Each item has exactly `id`, `law` (one sentence addressed to you), `why` (the harm), and `example` with exactly `wrong` and `right`. The whole file stays within 1,800 words (`wc -w`). `deno task test` fails on a missing or extra field and on the word budget. + +Each law has exactly one entry in the `## Corpus` block of `ENFORCEMENT.md`: `law`, `handle`, `absorbs`, `checks` (each a `question` with its `criteria`), `mechanism` (type, command, refusal, review), `severity`, `waiver`, and at least two `incidents` — failures from public history, each a commit, path and line. The corpus also holds the `judging` rules and the `retired` ids. `deno task test` fails on a law without exactly one entry, a duplicate handle, fewer than two incidents, or a citation that resolves to no live, judging or absorbed id; whether each incident is a real failure is review. ### Minting an ID @@ -38,7 +41,7 @@ ID format: `CONST-`. Pick the next free number in the family (never r | Letter | Family | Purpose | |---|---|---| -| `G` | Governance | Invoking constitution or resolving priority | +| `G` | Governance | Judging rules in the `ENFORCEMENT.md` corpus: verdict severity, reading by purpose, supremacy | | `E` | Enforcement | The maker's conduct under judgment (evidence, the instrument boundary); instrument design lives in `ENFORCEMENT.md` | | `P` | Purity | Decision functions and side-effect isolation | | `D` | Domain modelling | Domain types and constraints | @@ -50,8 +53,10 @@ ID format: `CONST-`. Pick the next free number in the family (never r ### Changing a Rule -- Same obligation reworded / moved: **keep ID**. -- Obligation narrowed, widened, split, or deleted: **retire old ID forever** and mint new one. +- Same obligation reworded or moved: **keep the id and its handle**. +- Obligations merged: the survivor keeps the lowest surviving id; the others go to its entry's `absorbs:`. +- Obligation removed: the id goes to `retired:` with its reason. Obligation narrowed, widened, or split: mint a new id. +- Handles are frozen once landed, and an absorbed or retired id is never reused: `deno task test --against ` fails a changed handle and an absorbed or retired id that returns as live. Whether a change is a rewording or a changed obligation is review. ## Surface Classes | Surface | Files | Rule | @@ -73,11 +78,11 @@ A task is done only when ALL of the following are true: ## Verification Commands ```bash -deno task test # one file: schema, coverage, ids, families, dangling citations +deno task test # two files: law schema, word budget, corpus entries, handles, ids, families, dangling citations deno run --allow-read --allow-env --allow-run npm:@commitlint/cli@21 --from HEAD~1 ``` -After a commit that deletes, splits, merges, or re-scopes a rule — not after every edit — also run the reassignment check against the revision before it: +After a commit that deletes, splits, merges, or re-scopes a rule — not after every edit — also run the lineage check against the revision before it: ```bash deno task test --against diff --git a/CONCEPTS.md b/CONCEPTS.md index e920c23..a8e3a96 100644 --- a/CONCEPTS.md +++ b/CONCEPTS.md @@ -8,14 +8,14 @@ Shared domain vocabulary for this project — entities, named processes, and sta The complete set of law documents the repository ships, treated as one unit. The corpus is what the gate certifies and what agents are bound by — not any single file's contents. Shrinking the measured portion of the corpus is a defect, not an optimization. ### Rule -One fenced YAML block inside the constitution carrying an id of the form `CONST-` — the family letter is one of G, E, P, D, B, T, N, W, S (governance, enforcement, purity, domain modelling, boundary, testing, naming & structure, work discipline, subtraction). A rule is the atomic unit of law: it is minted with a fresh number, amended in place, or vacated. Minting takes the next free number in the family — a minting law enforced by review, not by the gate. A vacated number is never reused for new law. +One law in `CONSTITUTION.md`, carrying an id of the form `CONST-` — the family letter is one of G, E, P, D, B, T, N, W, S (governance, enforcement, purity, domain modelling, boundary, testing, naming & structure, work discipline, subtraction) — a one-sentence `law`, its harm in `why`, and a wrong/right `example`, with exactly one entry in the `ENFORCEMENT.md` corpus holding its frozen handle, checks, mechanism, severity, waiver and failure incidents. A rule is the atomic unit of law. A law whose obligation survives keeps its id even when merged: it takes the lowest surviving id, and the others go to its entry's `absorbs:`. A removed obligation goes to `retired:` with its reason, and a changed obligation takes a new id. Minting takes the next free number in the family — a minting law enforced by review, not by the gate. An absorbed or retired number is never reused for new law. ### Vacuous pass A gate exiting green because it measured less than it claims — a missing input, an input that contributes nothing, a comparison arm that reads only part of the history. The output shape is identical to a healthy run, so the green actively certifies the absence of defects it did not look for. The doctrine this repo's gate is built on: assert the corpus, not only the contents; a gate that cannot fail is a certificate, not enforcement. ### Residency -The delivery contract for the maker's law: whatever must bind the agent's choices is always present in its context window, with no retrieval step. The counter-design — a thin resident pointer plus retrieved full text — forces presence at fetch time but never conformance at use time. Residency delivers obligation, not enforcement: the window tells the maker what is required, and whether the requirement held is decided afterward by instruments the maker cannot edit (ENFORCEMENT.md). What cannot fit residency is reference material and instrument doctrine, not law. +The delivery contract for the maker's law: whatever must bind the agent's choices is always present in its context window, with no retrieval step. The counter-design — a thin resident pointer plus retrieved full text — forces presence at fetch time but never conformance at use time. Residency delivers obligation, not enforcement: the window tells the maker what is required, and whether the requirement held is decided afterward by instruments the maker cannot edit. What cannot fit residency is reference material and instrument doctrine, not law. ### Corpus gate -The single check that certifies the constitution corpus — schema of every rule block, id and family registry, citation integrity across the corpus, and cross-revision comparison on demand. It runs as the repository's test command and again at every commit through the pre-commit hook, which makes any corpus-shape change also a gate change: the gate certifies the very input set a restructure edits. +The single check that certifies the constitution corpus — schema of every law and corpus entry, the word budget, id and family registry, handle uniqueness, citation integrity across both files, and, on demand, lineage against an earlier revision: every id there is live, absorbed, a judging rule, or retired. It runs as the repository's test command and again at every commit through the pre-commit hook, which makes any corpus-shape change also a gate change: the gate certifies the very input set a restructure edits. diff --git a/CONSTITUTION.md b/CONSTITUTION.md index efc6abe..265f9a1 100644 --- a/CONSTITUTION.md +++ b/CONSTITUTION.md @@ -1,415 +1,119 @@ # Constitution -## Application +Read every law by its purpose: where its words and its harm part ways, the harm decides. -```yaml -rules: - - id: CONST-G4 - title: By Purpose, Not Quotation - gate: review - do: invoke a principle by showing the harm is present; where letter and purpose diverge, purpose governs — ask "does this harm occur here" - dont: invoke a principle by quoting a clause or asking which clause to cite - harm: the letter applied where no harm exists defeats the purpose - check: review — an invocation names the harm, not the clause - - id: CONST-E9 - title: Never Edit What Grades Your Work - gate: review - do: - - treat every judgment surface as read-only — anything whose job is to check, measure, gate, or grade, including lint configs, rule lists, thresholds, baselines, CI checks, validator scripts, rubrics, coverage floors, and review criteria - - when a rule could fail a command and no command does, say the work is ungated and hand the gap to whoever owns the instrument — your work waits for it - dont: - - edit, add to, weaken, re-tune, or delete any judgment surface in service of your work — you cannot enumerate your graders, because some fire later (review, CI, the next enrollment wave), so the ban attaches to the surface, never to whether you believe it grades this task - - build the gate your work will be graded by, or shape one so the current work passes; the same hands in a separate commit is the same cheat with better hygiene - harm: whoever edits the instrument that grades their own work reports the score they chose; the green then certifies nothing and hides the broken invariant the gate existed to catch - check: review — the change being graded and any judgment-surface change name different owners; a needed gate is a proposal to the owner and a wait, never a build by the graded - - id: CONST-E7 - title: Evidence Before Done - gate: review - do: treat "done" as a gate passed or a test shown - dont: accept a reported score or a claimed "it works" as done - harm: compliance claimed without evidence - check: review — done names the gate that passed or the test that ran; a report of either is not either - - id: CONST-G5 - title: Supreme - gate: review - do: - - govern AGENTS.md, lint, and the ADRs on what a rule should say, where they conflict - - defer to the gate on whether a rule held — where this document and a gate disagree about a specific change, the gate is the final word; the disagreement is escalated to the channel that owns the instrument, never resolved by the maker editing the gate or overriding it in place - - place contestable choices — suffixes, patterns, module shape — in ADRs - dont: pin contestable choices in this document - harm: contestable choices frozen as supreme law; conflicts left unresolved - check: review — a conflict resolved by this document, a contestable choice resolved by an ADR -``` - ---- - -## Article I — The Pure Core +## Model the domain ```yaml -rules: - - id: CONST-P1 - title: Purity - gate: lint - do: each domain decision is a pure function — data in, a value or typed error out - dont: - - in a decision, do I/O, throw, read a clock, or use randomness - - return an effect handle from a decision — if it needs the runtime, move the boundary, not the purity - harm: logic untestable over all inputs, untrustworthy - check: lint — decisions import no I/O or effect-runtime; mutation - - id: CONST-D1 - title: Types Before Logic - gate: type-checker - do: define types before behavior; make illegal states unrepresentable so bad data fails to compile - dont: start from functions and add types after - harm: invalid data reaches runtime; tests multiply to cover what a type could forbid - check: type-checker rejects the illegal state; review - - id: CONST-D2 - title: Each Error Its Own Variant - gate: lint - do: give every distinct failure its own tagged variant - dont: distinguish failures by a boolean or string field - harm: callers can't branch on the real failure; distinct errors collapse into one case - check: lint; review — callers branch on the variant tag, never on a field value - - id: CONST-D3 - title: No Primitive Obsession - gate: lint - do: brand every domain-meaningful value (ids, amounts, codes) as its own type - dont: pass bare text or number in a domain-significant position - harm: values transposed or misused; the type says nothing about what they are - check: lint — no bare primitives in domain signatures - - id: CONST-D4 - title: Null Is Not a State — but absence is fine for optional data - gate: lint - do: - - model mutually-exclusive states as a tagged union — one variant per state, each carrying only its valid fields - - use a plain nullable for a value absent identically in every state - dont: - - encode a state by which fields are present - - wrap such a field in Option/Maybe to "fix" it — the wrapper renames the hole, not closes it - harm: a state machine hidden in a record; the compiler can't reject invalid field combinations — the question is never "null or Option" but "a value that may not exist, or a state in disguise" - check: lint — flags an optional that correlates with the discriminant, not plain optionals; review - example: - wrong: Order { status, shippedAt?, trackingId? } — state by presence; an Option wrapper is the same defect - right: Order = Pending { placedAt } | Shipped { placedAt, shippedAt, trackingId } - fine: Customer { name, middleName? } — genuinely optional; plain nullable, no wrapper - - id: CONST-P2 - title: The Pure Core Has One Path (Cyclomatic Complexity 1) - gate: lint - do: write each core decision as a single path — choice as exhaustive dispatch over a closed type (match a tagged union), iteration as map/fold; the core is an expression, not a procedure - dont: - - in the core, use if/else, switch, ?:, or &&/|| for control - - in the core, use for/while — repetition moves into map/fold - scope: binds the pure core (decision and workflow files); the ban is on the control-flow form, not branching — a core function reads as one path yet still decides and iterates; the shell sequences steps and carries no decisions, its only structure is the sandwich (CONST-B3); the gate runs on core files, not the shell - harm: every branch is an untested path where state silently diverges — the mutator reaches it, the suite does not - check: lint — cyclomatic complexity = 1 on core files (match, map, fold are calls, not control flow, so they hold at 1; if/switch/loops raise it) - example: - wrong: if (o.kind === "Shipped") ship(o) else hold(o) — two paths in a decision - right: match(o) { Shipped -> ship, Pending -> hold } — one exhaustive dispatch over a closed type - wrong_iteration: fold over the data with a for-loop in the core — iterating the core as a procedure - right_iteration: fold(xs, 0, add) — iterate as one expression (a shell loop is fine — that's the shell) +- id: CONST-D1 + law: Close your types so an illegal value cannot be constructed. + why: A value the type could have refused reaches runtime, and every check downstream trusts it. + example: + wrong: A lock helper took a lock spec and a nullable adapter, so a spec that required the lock, paired with no adapter, ran its body unlocked. + right: One union of the valid spec-and-adapter pairs made the unlocked case impossible to construct. +- id: CONST-D2 + law: Give every distinct failure its own tagged variant. + why: Callers cannot branch on the real failure, and distinct errors collapse into one case. + example: + wrong: Generator exhaustion and a real counterexample both became one "refuted" error built from a placeholder, so a property that never ran read as refuted. + right: Exhaustion is its own tagged error, and a refutation cannot be built without a real counterexample. +- id: CONST-D4 + law: Model mutually exclusive states as a tagged union, one variant per state carrying only its own fields; keep a plain nullable for a value absent the same way in every state. + why: A state machine hides in a record, and the compiler cannot reject an invalid mix of fields. + example: + wrong: "CheckerDecision { results, needsRetest }: the state is read off a field." + right: CheckFinished | RetestRequired, the second variant produced by the decider's retest branch. ``` ---- - -## Article II — The Boundary +## Shape the code ```yaml -rules: - - id: CONST-B1 - title: Functional Core, Imperative Shell - gate: review - do: split every module into a pure core (decisions) and a thin shell (I/O); pass plain serializable data across the seam - dont: let a boundary object (handler, adapter, middleware) make a decision — it only translates external ↔ domain - harm: decisions tangled with I/O can't be tested without mocks; bugs hide in the boundary - check: review — a boundary object that needs its own test suite has logic in it; move it to the core - - id: CONST-B2 - title: Effects Are Values - gate: lint - do: return effects as lazy values (descriptions), interpreted once at the edge; attach logging, metrics, tracing as decorators on the value - dont: - - put an eager async result (promise, future, task) on the public surface - - embed a cross-cutting concern in a decision - harm: an already-started result can't be held, retried, or swapped; embedded concerns can't be turned off or composed - check: lint — no eager async result on the public surface - example: - wrong: "getUser : UserId -> " - right: "getUser : UserId -> Effect — a lazy value, interpreted once at the edge" - - id: CONST-B3 - title: The I/O Sandwich - gate: review - do: shape every outside interaction as read (impure) → transform (pure) → write (impure); the shell calls the core directly - dont: insert a layer that only passes work through without a read, transform, or write - harm: side effects leak into business logic; pass-through layers add coupling for nothing - check: review — pass-through delegation is the violation; the shell doing the read/transform/write, or sitting between transport and core, is not - example: - flow: | - read → decode → decide → shape → write - impure bread (read, write) around a thick pure filling (decode, decide, shape), no I/O between the pure steps. - read pull raw inputs — store, gateway, network, clock (impure) - decode validate raw → branded domain types (fail as data) (pure) - decide one decision over typed data → Decision | Error (pure) - shape build outputs and events from the Decision (pure) - write persist · emit · respond (impure) - wrong: read → decide → read → decide — I/O interleaved; the filling turns impure - edge: a later read that depends on an earlier decision — pre-fetch it, split into two sandwiches, or keep it openly in the shell; never fake a "pure core" around it - - id: CONST-B6 - title: The Sandwich Order Is Carried by Types - gate: type-checker - do: express an outside interaction as one phase chain — each phase's return type carries the required member the next phase's parameter demands — so the order is a consequence of the types and the compiler decides it - dont: - - hand-sequence the phases and state their order beside them; an order asserted in prose is decided by nothing - - give the phases a hierarchy — where a later phase's type is assignable to an earlier phase's parameter, an inversion still compiles - harm: an order nothing decides permits every permutation while reading as a guarantee, so the interleaved read that turns the filling impure — the defect CONST-B3 names — reaches production with the rule green - check: type-checker — composing the phases in the wrong order omits the required member, so the compiler names the phase that must come first; the sentence survives into the published declaration as that member's own name, which is what carries it into a consumer's compiler - example: - wrong: "write(decide(read(raw))) — hand-sequenced; every permutation type-checks, so the order is a comment" - right: "read : Raw -> ReadDone, decode : ReadDone -> DecodeDone, decide : DecodeDone -> DecideDone — decode cannot receive what read has not produced" - - id: CONST-B4 - title: Dependencies Point Inward - gate: lint - do: let the shell import the core; wire all implementations at one composition root - dont: let the core import the shell, the database, or the framework - harm: a decision layer chained to infrastructure can't be tested or replaced - check: import-graph lint - - id: CONST-B5 - title: Decode, Never Cast - gate: lint - do: turn outside data (bytes, serialized text, a foreign type) into a domain type via a decode returning a typed result - dont: - - assert type with an unchecked cast (`as`, `as unknown as`, `as any`) - - assert type with a suppression comment - harm: a shape nothing verified; everything downstream trusts a check that never ran - check: lint — no unchecked casts or suppression comments on outside data - example: - wrong: config := value as Config - right: "config := decode(value) : Result" - - id: CONST-P3 - title: Purity Is Per Function, Not Per Folder - gate: review - do: judge pure-versus-effectful by return type alone - dont: infer it from a folder, package, or "library versus application" - harm: a database-driver mislabeled "pure," a parser "impure," because of where it lives - check: review — return type decides; the lint behind CONST-P1 - example: - pure: "decide : Command -> Result" - effectful: "load : OrderId -> Effect — owns effects" +- id: CONST-B1 + law: Keep effects at the edges, as values. + why: An effect inside a decision cannot be tested without the world it touches, and a defect hides at the seam. + example: + wrong: The config resolver read a file, decided, resolved the next specifier and recursed inside one async function. + right: A pure step returns the next read as data, and a thin shell performs it. +- id: CONST-B4 + law: Let the shell import the core, and wire every implementation at one composition root; the core never imports the shell, a database, or a framework. + why: A decision chained to infrastructure cannot be tested or replaced. + example: + wrong: A CLI adapter imported the Node standard-IO layer and provided it to itself, below the composition root. + right: The adapter declares that it needs standard IO, and the composition root provides it. +- id: CONST-N1 + law: Organise code by what it does, and name every file and folder for its job; a name must answer "of what?". + why: One change scatters across the tree, and a bucket named for a layer says nothing a reader can check. + example: + wrong: Packages were nested into role tiers (core, testing, lint) that grouped packages sharing nothing a reader could check. + right: The tiers were reverted; folders name product families. +- id: CONST-N3 + law: Give each module one responsibility, and split it when its tests need elaborate setup. + why: Nobody can reason about the whole module, and its tests grow brittle. + example: + wrong: One module held a config type, its text parser, a process-wide cache with a test-only reset, and the file read, so its tests needed a fake file system. + right: It split into a schema, a translator and an executor that does the read, and each is tested on its own. +- id: CONST-S1 + law: Fix the root cause; when the design is wrong, restructure it. + why: A patched symptom comes back. + example: + wrong: Every transaction rollback was mapped to a version conflict, so any bug in the transaction looked like a race and retries walked an order into a rollback the customer never earned. + right: The duplicate check moved inside the serializable transaction, and only a real serialization failure retries. +- id: CONST-S2 + law: Justify every choice by these laws, never by the file next to it or a prior plan's wording. + why: An unexamined default hardens into a rule, and each copy seeds the next. + example: + wrong: A planning session wrote an adapter's package name into law, and every later import and plan inherited the misnaming. + right: Authority traces to the architecture; the package was renamed for what it does and the old name deleted in the same change. +- id: CONST-S4 + law: Treat every line as a liability; delete, unify, or make the bad state unconstructable before you add. + why: The codebase only grows, and rot survives every patch. + example: + wrong: A suffix-keyed copy-paste rule fleet grew to 100 rules across 21 plugins; one plugin shipped five rules against zero files. + right: The whole fleet was deleted in one change, thirteen plugin packages and about 31,000 lines. ``` ---- - -## Article III — Verification +## Prove it ```yaml -rules: - - id: CONST-T15 - title: The Testing Trophy - gate: review - do: invest in order — static analysis first, then properties on the core where CONST-T14 grants them, then composition through the sandwich (CONST-B3), then contracts at the published edge; the order is the doctrine, a count of tests per layer is not - dont: - - gate anything on a numeric layer width or a layer-naming table — the widths were refuted instrumentation, not law - - build a Test Pyramid — a wide base of helper unit tests buries logic in I/O and leaves the untested middle - harm: investment spent where the compiler and the mutator already decide; the untested middle stays untested while the suite looks broad - check: review — each authored test names its observer and the step of the order it earns, never a width - - id: CONST-T8 - title: Test Public Functions Directly, Pure Logic with Mutation - gate: review - do: test the public API with real inputs and outputs; test internal calculation and branching logic with mutation tests (and properties only when CONST-T14 requires them); never write dedicated unit tests for code that only forwards calls between components - dont: - - write unit tests for intermediate helper functions that only pass data to other functions - - mix I/O code or adapters into the same mutation test run as pure calculation logic - - mock a dependency when only one real implementation exists - harm: unit-testing intermediate layers locks in private implementation details without catching real bugs; mocking real code gives false confidence; business rules stay tangled with I/O - check: review — every test calls either a public export or a pure decision function, never a private forwarding helper - - id: CONST-T14 - title: Properties Where the Surface Cannot Reach - gate: review - do: prove a pure decision with a property when a universal over generated input, or a refusal no generated law can express, cannot be reached from the published surface; the type is the generator - dont: - - cover the core with hand-picked example unit tests - - write a property for a decision already fully pinned from above just because the decision is important - harm: a green suite that tests only the cases you imagined; or a property farm that restates the public contract and dies with it - check: review — each authored property names the universal the public surface cannot reach - - id: CONST-T3 - title: Mutation Is the Measure - gate: mutation - do: gate a named, change-relevant mutated set at a perfect kill score; the set names the behavior it covers, and its scope is a cost decision, never a fault-majority claim; kill a survivor with a sharper property or by deleting the dead branch it exploits - dont: - - reach the number by a suppression comment - - reach the number by narrowing the mutated set after the fact - - reach the number by lowering the gate - - let an empty mutated set pass - - treat a raw mutation percentage as comparable across changes or codebases - harm: a score certifying tests that notice nothing; an empty or author-shrunk set passing vacuously - check: mutation gate (break = 100) on the declared mutated set; lint banning suppression, scope-narrowing, and an empty set - - id: CONST-T13 - title: Mutation Also Grades the Tests - gate: mutation - do: fail a run whose mutants all died if an authored property file defends nothing the rest of the suite does not; opt out in the mutation config, never by deleting the file the gate named - dont: - - treat a perfect mutant score as proof every test pulled its weight - - accuse a file that covered an unattributed kill - harm: toothless properties accumulate; deleting them to silence the gate removes the only named contract - check: mutation — the test-set verdict is part of the same run as the score - - id: CONST-T4 - title: Behavior Lives Where the Mutator Sees It - gate: lint - do: put any code that can be wrong (transform, check, branch) in a file the mutator covers - dont: place behavior in a declaration file (types, schemas, constant data), excluded from mutation - harm: a bug hidden behind a perfect score, in a file nothing mutates - check: lint — declaration files contain no behavior - - id: CONST-T9 - title: Pin the Published Contract Before You Delete a Path - gate: review - do: before removing or replacing a published operation, pin its observables (value, error variant, serialized document, process result) with examples or properties whose expected side is not the implementation under change; if the old operation still runs, compare old and new on the same published inputs until they agree, then delete old - dont: - - pin private functions - - derive expected values by running the implementation under change - - treat a mutation or property score as proof a deleted published capability still exists — those are blind to absence - - leave a persisted gold after the old path is gone unless the gold is externally authored, independently gated, and cheap to re-bless - harm: a rebuild silently drops a capability; same-session gold blesses the bug; a clean score after a delete is a silent regression - check: review — pins call only published names; each expected value names an independent source (spec clause, second implementation, or a hand-written oracle next to the constructor), never the subject's own output or a second build of it - - id: CONST-T10 - title: The Oracle Is Not the System Under Test - gate: review - do: every assertion has an oracle the SUT did not produce — a spec literal, a fixture not generated by importing the module, a law relating two views of the same value, or a second implementation; generated round-trip laws on a type cover what the type accepts and nothing it should reject, so a hand-written refusal survives beside them at any specifiable refusal boundary - dont: - - compute expected by calling the SUT - - assert collaborator call graphs - - treat generated accept-laws as full coverage of a refinement - harm: a green suite that cannot fail when the behavior is wrong; widening a refinement leaves generated laws green - check: review — plus sabotage (after green, break one core law and one published field; at least one test must go red) - - id: CONST-T11 - title: Snapshots and Differentials Are Development-Time Evidence, Never Committed Artifacts - gate: lint - do: use stored-output snapshots and same-lineage differentials only as development-time evidence in a dot-prefixed, always-gitignored scratch directory; the committed suite asserts intended behavior against an oracle the subject did not produce - dont: - - commit a stored-output snapshot, a recorded-output fixture, or a differential-comparison test - - keep scratch evidence past the commit that lands the intended-contract tests - harm: a committed capture re-records whatever the subject currently does and passes forever, certifying nothing; a committed differential passes whenever both builds of the same subject share a bug - check: lint — no snapshot API call and no same-lineage differential import in a committed test file; review — the scratch directory is gitignored and empty at commit - - id: CONST-T12 - title: What a Test Does Comes from What It Calls, Not Its Filename - gate: lint - do: classify what a test is by what it imports and calls — public exports or pure logic under mutation — never by its folder, filename, or file extension - dont: decide which testing rules apply to a file based on its name or suffix - harm: renaming a test file secretly stops its rules from running while the test suite still looks complete - check: lint — no linter or test runner rules that pick tests by filename suffix +- id: CONST-T8 + law: Test the published surface with real inputs and outputs. + why: A test that stops short of what ships stays green while the shipped artifact is broken. + example: + wrong: Tests imported the package's source, so it published with no built output and no consumer could import it. + right: The package ships its build, and the pack check reads what each tarball contains. +- id: CONST-T10 + law: Take every expected value from an oracle the code under test did not produce - a spec literal, an independent fixture, a law between two views, or a second implementation. + why: A test that compares the code with itself cannot fail when the code is wrong. + example: + wrong: A snapshot of 500 observed depths moved whenever the generator, the schema, or the seed moved. + right: The snapshot kind was deleted rather than re-recorded. +- id: CONST-T3 + law: Make every test able to fail when the behaviour it names breaks. + why: A suite that notices nothing certifies nothing, and a toothless test hides among the ones that work. + example: + wrong: Round-trip laws drew their inputs from the schema's own generator, so every widened pattern survived. + right: Rejection properties whose inputs come from the domain contract killed the survivors. +- id: CONST-T12 + law: Decide what applies to code (which checks, tests and requirements) from what it is and does, never from its name or location. + why: A rename or a move silently drops a requirement, or applies one where it does not belong, while everything stays green. + example: + wrong: Mutation targets were chosen by a path label; when fixtures moved, five were enrolled, one built to fail. + right: A target is selected by what it is, a workspace package the lockfile declares. ``` ---- - -## Article IV — Organization +## Finish ```yaml -rules: - - id: CONST-N1 - title: Organized by What It Does - gate: review - do: organize by workflow and capability; keep code that changes together, together - dont: organize by what the system has (entities, technical layers) - harm: one change scattered across the tree - check: review — one change touches one capability subtree - - id: CONST-N2 - title: Names Scream the Domain - gate: lint - do: name files and folders for the job they do — a name must answer "of what?" - dont: - - use layer names (`core`, `shell`) - - use junk drawers (`util`, `service`, `manager`) - - use a suffix no rule keys on - harm: files no one can locate; meaningless buckets - check: filename lint — allowed suffixes; banned layer and junk-drawer names - - id: CONST-N3 - title: Fits in the Head - gate: review - do: give a module one responsibility; split it when a test needs elaborate setup (the signal it has several) - dont: accumulate unrelated concerns in one module - harm: modules no one can fully reason about; brittle, sprawling tests - check: review — fixture difficulty is the decomposition signal -``` - ---- - -## Article V — Conduct - -```yaml -rules: - - id: CONST-G3 - title: Constitutional Violations Are Automatic P0 Failures - gate: review - do: treat every undeclared violation of this constitution during review as an automatic, non-negotiable P0 failure; reject the change unconditionally with zero appeals and no severity downgrades unless explicitly declared under CONST-W3 - dont: - - downgrade an undeclared constitutional breach to an advisory, P1, P2, or non-blocking finding - - treat a CONST-W3 declaration as optional prose — an explicit declaration in the change itself is the only legal waiver, and it must name the rule and the case - - accept a promise of follow-up repair or expedience plea to bypass an active rule without a CONST-W3 declaration - harm: constitutional rules decay into optional suggestions; agents negotiate away core architecture to ship faster; unblocked violations calcify into precedent - check: review — every undeclared constitutional violation is graded P0 and blocks approval unconditionally; any review that waives or downgrades an undeclared violation is rejected - - id: CONST-S1 - title: Depth Over Expedience - gate: review - do: fix the root cause; restructure when the design is wrong - dont: patch the symptom or bypass a boundary to ship faster - harm: the bug returns - check: review — the change names the root cause it fixes - - id: CONST-W1 - title: Scope Discipline - gate: review - do: execute accepted scope in full - dont: reduce scope mid-task because it grew complex, without the author's consent - harm: half-finished work; wasted effort second-guessing intent - check: review — delivered scope matches accepted scope - - id: CONST-S2 - title: First Principles Over Precedent - gate: review - do: justify a pattern by these principles — surrounding code is evidence of what exists, never of what is correct - dont: - - justify by "that is how it's done elsewhere" - - copy a neighbouring file as a template — code age grants no immunity - harm: unexamined defaults calcify into rules; one slop pattern seeds the next by imitation, and the average drifts down - check: review — a choice defended by precedent, or by the file next to it, is rejected - - id: CONST-S3 - title: API-First Discovery - gate: review - do: define the outside contract first, then derive use cases, decisions, and machinery beneath it; model only what a known requirement needs - dont: build a domain abstraction for a hypothetical future - harm: speculative structure that never pays off and constrains what comes after - check: review — every abstraction traces to a known requirement - - id: CONST-W2 - title: Challenge Before You Commit - gate: review - do: subject a large or irreversible choice to a deliberate challenge (another agent, a person, or rigorous self-examination), record it with the decision, judge it by the harm it names - dont: - - appeal to a tribunal or standing authority - - let a challenge become a clause quoted against a choice - harm: a costly, hard-to-reverse direction taken with no one trying to break it first - check: review — the challenge is recorded with the decision - - id: CONST-W3 - title: No Silent Bypass - gate: review - do: when you break a rule here — knowingly, or because it was wrong for this case — say so, in the open, in the change itself - dont: conceal a bypass - harm: two failures — the breach and the hiding of it; the next reader trusts a rule quietly broken - check: review — every rule breach is declared in the change that contains it - - id: CONST-S4 - title: Subtract Before You Add - gate: review - do: - - treat every line as a liability — removal is the default response to slop at every scale; adding is the exception you justify - - small — unify duplicates, make bad states unrepresentable, delete a branch instead of guarding it - - structural — when the root violates this document and breeds a bug class, rebuild the core (published contract pinned first (CONST-T9); decomposed into shippable milestones) rather than prune leaves off a rotten trunk - - distrust existing structure — assume rotten until it proves it conforms - dont: - - extend a copy-paste cluster with copy N+1 - - add a helper when removing or unifying one does the job - - patch around a rotten core to keep it alive - - treat code as sound because it compiles, is large, or is old - - mistake taste ("I'd write it differently") for rot - harm: the codebase only grows; rot survives every patch and regrows; each copied pattern seeds the next, and the average drifts down - check: review reads the net line delta — a refactor/improvement/chore that adds net lines states why and names what it deleted (features and their tests are exempt); a fix that leaves a named root violation standing is rejected; "rotten" names the invariant the core breaks; a structural rebuild ships a CONST-T9 pin on every published path it deletes - example: - wrong: add formatPhone() beside the three formatters already there - right: delete the three, keep one parameterised formatter - wrong_state: add a guard for the impossible state the record permits - right_state: delete the record; a tagged union makes the state unconstructable - +- id: CONST-W1 + law: Deliver the whole accepted task; shrink it only with the requester's agreement. + why: Half-finished work, and effort spent second-guessing intent. + example: + wrong: The offered shortcut was to drop packages that could not comply from the enrolled set. + right: Every deciding package was enrolled; the one exception was named in the change for the author to rule on. +- id: CONST-E7 + law: Show evidence (a command that passed or a test that ran) before you call work done, and never edit, add, or weaken anything that grades your work. + why: Work called done on no evidence ships broken, and whoever edits the grader reports the score they chose. + example: + wrong: One commit changed the law and flipped the gate that grades it. + right: The next amendment shipped with the gate's behaviour untouched. ``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a1757c2 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,47 @@ +# Contributing + +This repository holds two documents and the tooling that validates them. There is no production code, no build and no test suite beyond the corpus validator. + +## Setup + +Install [Deno](https://deno.land/), then: + +```bash +git clone https://github.com/systemfsoftware/constitution.git +cd constitution +deno task prepare # points git at the .husky hooks +``` + +## Verify + +```bash +deno task test # validates CONSTITUTION.md and ENFORCEMENT.md +deno task test:validator # tests the validator itself +``` + +`deno task test` fails on a law without exactly one corpus entry, a duplicate handle, fewer than two incidents, a dangling citation, a missing or extra field, or a file over the word budget. + +After a commit that deletes, splits, merges or re-scopes a rule, check the lineage against the revision before it: + +```bash +deno task test --against +``` + +The pre-commit hook runs both test tasks. Commit messages use conventional format, `type(scope): subject`, and the commit-msg hook enforces it through commitlint. Do not bypass the hooks with `--no-verify`. + +## Amending a law + +`CONSTITUTION.md` is human-controlled: propose the change and wait for the owner. Then keep the corpus in step: + +- **Same obligation, reworded or moved:** keep the id and its handle. +- **Obligations merged:** the survivor keeps the lowest surviving id, and the others move to its entry's `absorbs:`. +- **Obligation removed:** the id moves to `retired:` with its reason. +- **Obligation narrowed, widened or split:** mint a new id. + +Ids are `CONST-`, with the family letter for the section. Pick the next free number and never renumber. Handles and retired or absorbed ids are never reused. Each law needs one `ENFORCEMENT.md` entry with at least two incidents, each a real commit, path and line from this history. + +Each law is one sentence addressed to the maker, with its `why` and a `wrong` and `right` example. `CONSTITUTION.md` must stay within its word budget. + +## Changing the validator or the gates + +Gates are judgment surfaces. A change to `scripts/validate-constitution.ts` or to the rules in `ENFORCEMENT.md` is its own commit, and it must not be shipped in the same change as the law it grades. diff --git a/ENFORCEMENT.md b/ENFORCEMENT.md index b1d7911..6a06a32 100644 --- a/ENFORCEMENT.md +++ b/ENFORCEMENT.md @@ -22,7 +22,7 @@ Rules for whoever builds or changes an instrument that grades the maker — lint - An instrument change lands alone, in its own commit, observed failing before and passing after, for the reason it states — by hands that do not hold the work the instrument judges. - Never loosen a threshold, budget, glob, or baseline to make in-flight work pass. The same hands in a second commit is the same cheat. -- When the maker escalates an ungated principle (CONST-E9), you build the instrument and land it through your own channel; only then does the maker's work proceed. +- When the maker escalates an ungated principle (CONST-E7), you build the instrument and land it through your own channel; only then does the maker's work proceed. ## Enrollment @@ -36,3 +36,261 @@ Rules for whoever builds or changes an instrument that grades the maker — lint - Every gate names the mistake it prevents. A gate that cannot name one does not land. - Judge gate work by net line delta; subtraction must leave an artifact. - The enforcement surface is read-only to the agents it governs. + +## Corpus + +One entry per law in `CONSTITUTION.md`: its frozen handle, the ids it absorbs, the questions a reviewer asks with their criteria, the mechanism rungs that bind it, its severity and waiver, and the failure incidents that justify it. Judging rules bind the reviewer, not the maker. Retired ids name an obligation that was removed, and are never cited. + +```yaml +version: 1 +laws: + - law: CONST-D1 + handle: CLOSED-TYPES + absorbs: [CONST-B5] + checks: + - question: "Were the types defined before the behaviour, so that an illegal state does not compile?" + criteria: "The type checker rejects the illegal state. Starting from functions and adding types after, or a guard for a state the type permits, fails." + - question: "Technique: does outside data become a domain type only through a decode?" + criteria: "Bytes, serialized text or a foreign type become a domain type through a decode returning a typed result. An unchecked cast (as, as unknown as, as any) or a suppression comment asserting a shape on outside data fails; command: lint." + mechanism: [type, command] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 151b9f4de:packages/effect-daemon-spec/src/internal/with-lock-by-mode.executor.ts:24 (2026-08-15, #166, fix 2d367db70). withLockByMode took a spec and a nullable adapter, so a spec that required the lock, paired with no adapter, ran its body unlocked." + - "systemfsoftware/systemfsoftware de5414e3a:packages/discern/src/decision.blueprint.ts:461 (2026-09-24, #519, fix 2d4c724ff). classify accepted any `Label extends string` options, so once a string-typed criteria got through, every downstream label check accepted any string." + - law: CONST-D2 + handle: ERROR-VARIANTS + absorbs: [] + checks: + - question: "Does every distinct failure have its own tagged variant?" + criteria: "Failures are not distinguished by a boolean or string field. Callers branch on the variant tag, never on a field value; command: lint, with review for the branching." + mechanism: [command] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 2e8809b55:packages/runner/vitest/src/internal/property/engine.ts:593 (2026-10-06, #650, fix 1f8d87077). An exhausted generator and a real falsification both became one PropertyRefuted built from a fabricated sentinel, so 'never evaluated' read as 'refuted'." + - "systemfsoftware/systemfsoftware 0c45ffa8c:scripts/tools/publish-and-setup-npm-trust.ts:181 (2026-09-22, #463, fix d8131fa1a). An unreadable registry and a registry with zero trust configs both returned the same empty array, so the bootstrap registered a duplicate publisher the registry rejected with 409." + - law: CONST-D4 + handle: STATES-AS-UNIONS + absorbs: [] + checks: + - question: "Are mutually exclusive states a tagged union, one variant per state carrying only its valid fields?" + criteria: "A state encoded by which fields are present fails, and wrapping such a field in Option or Maybe renames the hole rather than closing it. The lint flags an optional that correlates with the discriminant, not plain optionals." + - question: "Is a plain nullable used only for a value absent identically in every state?" + criteria: "Customer { name, middleName? } is fine. Order { status, shippedAt?, trackingId? } is a state machine hidden in a record." + mechanism: [command] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 49b3f7275:packages/testing/mutation/stryker-js/typescript-checker/src/Checker.workflow.ts:64 (2026-09-04, #346, fix 90baa86ab). CheckMutantsDecision encoded 'finished' vs 'retest required' by whether needsRetest was empty, and the shell branched on that field." + - "systemfsoftware/systemfsoftware eafd889c5:packages/discern/src/Budget.schema.ts:4 (2026-09-25, #547, fix 4a755267a). An absent optional `decisions`/`calls` meant 'no limit', and CaseTrace's optional `reason` was keyed on its status." + - law: CONST-B1 + handle: EFFECTS-AT-EDGES + absorbs: [CONST-B2, CONST-B3, CONST-B6, CONST-P1, CONST-P2] + checks: + - question: "Is every module split into a pure core of decisions and a thin shell of I/O, with plain serializable data across the seam?" + criteria: "A boundary object (handler, adapter, middleware) only translates between outside and domain. One that needs its own test suite has logic in it, and the logic moves to the core; review." + - question: "Are effects returned as lazy values, interpreted once at the edge?" + criteria: "No eager async result (promise, future, started task) on the public surface; command: lint. Logging, metrics and tracing are decorators on the value, never embedded in a decision." + - question: "Do reads and writes stay out of the pure steps of a decision?" + criteria: "No I/O sits between two pure steps. A later read that depends on an earlier decision is pre-fetched, split into a second interaction, or kept openly in the shell, never hidden inside a pure core. A layer that only passes work through, with no read, transform or write, fails. No fixed phase sequence is required: a case may write before it classifies; review." + - question: "Technique: where one description carries the interaction, do the types carry the phase order?" + criteria: "Each phase's return type carries the member the next phase's parameter demands, so a wrong order fails to compile; a hand-sequenced order stated in prose decides nothing. A generator body does not preserve order in its type, so the technique does not apply there; type." + - question: "Technique: is each decision a pure function, data in and a value or typed error out?" + criteria: "A decision does no I/O, throws nothing, reads no clock and uses no randomness, and returns no effect handle; if it needs the runtime, move the boundary. Command: lint, decisions import no I/O or effect runtime. Purity is judged by return type (CONST-T12's entry)." + - question: "Technique: does each core decision read as one path?" + criteria: "Choice is exhaustive dispatch over a closed type, iteration is map or fold; if/else, switch, ternaries, &&/|| for control, and loops do not appear in decision files. Command: lint, cyclomatic complexity 1 on core files. The shell sequences steps and carries no decisions." + mechanism: [type, command, review] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 911506389:packages/stryker-js/mutation-run/src/config/resolve-extends.ts:156 (2026-08-17, #195, fix 811f859da). resolveExtendsChain read a file, decided, resolved a specifier and recursed inside one async function, so the effects sat in the middle of the decision." + - "systemfsoftware/systemfsoftware bda12ddc5:packages/stryker-js/core/src/stryker.ts:47 (2026-08-08, fix 2df51b21e). Core's runMutationTest probed the terminal and wrote phase lines to fd 1 from the middle of the run instead of receiving its sink from the edge." + - law: CONST-B4 + handle: DEPENDENCIES-INWARD + absorbs: [] + checks: + - question: "Do dependencies point inward, with every implementation wired at one composition root?" + criteria: "The shell imports the core; the core imports no shell, database or framework. Command: import-graph lint." + mechanism: [command] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 87ce6a050:packages/stryker-js/cli/src/run-event-stream.adapter.ts:1 (2026-08-16, #173, fix 22fd736ce). The run-event-stream adapter imported NodeStdio and provided it inside itself, below the composition root." + - "systemfsoftware/systemfsoftware 3d5587876:packages/testing/mutation/stryker-js/platform-node/src/Plugins.ts:14 (2026-09-01, #342, fix 3838c7309). The mutation engine's own modules imported and composed the Node platform layers inline instead of declaring ports bound at the CLI root." + - law: CONST-N1 + handle: ORGANISED-BY-PURPOSE + absorbs: [CONST-N2] + checks: + - question: "Is code organised by workflow and capability, so that code that changes together lives together?" + criteria: "One change touches one capability subtree. Organising by what the system has (entities, technical layers) fails; review." + - question: "Does every file and folder name answer \"of what?\"" + criteria: "Layer names (core, shell), junk drawers (util, service, manager) and a suffix no rule keys on fail. Command: filename lint with allowed suffixes and banned names. A lint that governs only a file's name or placement states no testing requirement and is allowed (CONST-T12)." + mechanism: [command, review] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware e686ab9b1:pnpm-workspace.yaml:100 (2026-09-05, #357, fix 02c393fcf). Packages were nested into role tiers (core, testing, lint) whose folder names say a layer, not a job." + - "systemfsoftware/systemfsoftware 01696895c:packages/testing/type-testing/arethetypeswrong/core/package.json:2 (2026-08-23, #241, fix 3d6aa9f9e). The package was named `arethetypeswrong-core`, a layer token, not a capability." + - law: CONST-N3 + handle: FITS-IN-THE-HEAD + absorbs: [] + checks: + - question: "Does each module have one responsibility?" + criteria: "Fixture difficulty is the decomposition signal: a test that needs elaborate setup means the module holds several responsibilities and is split." + mechanism: [review] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 91cefa52c:omp/packages/omp-utils/src/toml-loader.kernel.ts:12 (2026-07-24, fix a7dd87325). One module fused the config declaration, TOML translation, a process-wide cache with a test-only reset, and the file read, so its tests needed a fake file system." + - "systemfsoftware/systemfsoftware 90baa86ab:packages/lint/oxlint/plugins/meta/core/src/index.ts:86 (2026-09-04, #351, fix ef89c23e7). One plugin package registered 20 rules across five unrelated domains in one module and one mutation cell of about 2,075 mutants that no budget could finish." + - law: CONST-S1 + handle: ROOT-CAUSE + absorbs: [] + checks: + - question: "Does the change name the root cause it fixes?" + criteria: "A patched symptom, or a boundary bypassed to ship faster, fails. When the design is wrong, the change restructures it." + mechanism: [review] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 7a0e98e73:examples/inventory-fulfillment/src/store/ReservationLogDrizzle.ts:88 (2026-09-24, #448, fix b20a70d1d). Every transaction rollback was relabelled a version conflict, so a duplicate-key collision looked like a stock race and retries walked the order into a rollback." + - "systemfsoftware/systemfsoftware fe16c51ae:.github/workflows/mutation.yml:69 (2026-08-17, fix 7b4e08e24). A fixture that broke the mutation matrix was patched out with a path label instead of selecting by what a target is; when the fixtures moved, five were enrolled, one built to fail." + - law: CONST-S2 + handle: FIRST-PRINCIPLES + absorbs: [] + checks: + - question: "Is every pattern justified by the laws rather than by precedent?" + criteria: "A choice defended by \"that is how it is done elsewhere\", by the file next to it, or by a prior plan's wording is rejected. Surrounding code is evidence of what exists, never of what is correct; code age grants no immunity." + mechanism: [review] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 3d5587876:packages/testing/mutation/stryker-js/platform-node/package.json:2 (2026-09-01, #342, fix 3838c7309). The package carrying the whole mutation engine was named after the runtime, a name a prior plan had written down and later work inherited." + - "systemfsoftware/systemfsoftware 3488c2eb2:packages/core/effect/daemon-spec/AGENTS.md:49 (2026-09-03, #348, fix b89b52d46). A leaf carried a gate command copied by paraphrase from another file rather than re-derived, and the copy named the wrong task." + - law: CONST-S4 + handle: SUBTRACT-FIRST + absorbs: [] + checks: + - question: "Was removal tried before addition?" + criteria: "Duplicates are unified, bad states made unrepresentable, a branch deleted instead of guarded. Extending a copy-paste cluster, adding a helper where removing or unifying one does the job, or patching around a rotten core fails. Taste is not rot: \"rotten\" names the invariant the core breaks." + - question: "What is the net line delta, and does a refactor, improvement or chore that adds lines justify them?" + criteria: "Review computes the delta from the diff against the merge base of the change and its target branch at the time of review, recomputed whenever the target moves, never from a figure the author supplied. A refactor, improvement or chore that adds net lines states why and names what it deleted; features and their tests are exempt. A fix that leaves a named root violation standing is rejected. A structural rebuild ships a pin on every published path it deletes (CONST-T8)." + - question: "Technique: does every abstraction the change adds trace to a known requirement?" + criteria: "Name the requirement or consumer behind each new type, export, module or layer. One built for a hypothetical future consumer fails, and so does an export no consumer uses." + - question: "Technique: was the outside contract defined first, with use cases, decisions and machinery derived beneath it?" + criteria: "The published contract exists before the machinery that serves it; machinery with no contract above it fails." + mechanism: [review] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 824aa02e8:packages/oxlint-plugins/effect-store/src/rules/cell.ts:6 (2026-08-16, fix 166e6bb65). A suffix-keyed copy-paste rule fleet grew to 100 rules across 21 plugins; effect-store shipped five rules against zero files." + - "systemfsoftware/systemfsoftware b2ecd0e58:docs/residual-review-findings/attw-dsl-snapshots.md:8 (2026-08-22, #229). Review rejected committed per-recipe snapshot artifacts and a dead parity gate; the merge deleted 119 committed fixture and snapshot files." + - law: CONST-T8 + handle: PUBLIC-SURFACE + absorbs: [CONST-T15, CONST-T9, CONST-T14] + checks: + - question: "Does every test call a public export, with real inputs and outputs, or a pure decision under mutation?" + criteria: "Dedicated unit tests for code that only forwards calls fail. I/O code and adapters do not share a mutation run with pure calculation logic. A dependency with only one real implementation is not mocked." + - question: "Is test investment in order?" + criteria: "Static analysis first, then properties on the core where the property technique grants them, then composition through the shell, then contracts at the published edge. Each authored test names its observer and its step; no gate on a numeric layer width or a layer-naming table, and no pyramid of helper unit tests." + - question: "Technique: before a published operation is removed or replaced, are its observables pinned?" + criteria: "Value, error variant, serialized document and process result are pinned with examples or properties whose expected side is not the implementation under change. While the old operation runs, old and new are compared on the same published inputs until they agree, then old is deleted. Pins call only published names. A mutation or property score is blind to absence and proves nothing about a deleted capability. A persisted gold outlives the old path only when it is externally authored, independently gated and cheap to re-bless." + - question: "Technique: is a property written only where the published surface cannot reach?" + criteria: "A property proves a pure decision when a universal over generated input, or a schema's refusal, cannot be reached from the published surface; the type is the generator. Hand-picked example unit tests on the core, and a property for a decision already pinned from above, fail. Each authored property names the universal the surface cannot reach." + mechanism: [review] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware d8f0d6e75:packages/differential-spec/package.json:14 (2026-09-23, #498, fix 3dde409e9). Tests imported the package's source through a resolve condition, so the published tarball shipped with no dist/ and consumers could not import it." + - "systemfsoftware/systemfsoftware b83e6425c:packages/arethetypeswrong/cli/src/attw.executor.ts:159 (2026-08-10, fix 7ee1dd2b7). Tests stopped at the handler, so the real binary silently dropped every entrypoints flag and reported no entrypoints with exit 0." + - law: CONST-T10 + handle: INDEPENDENT-ORACLE + absorbs: [] + checks: + - question: "Does every assertion have an oracle the code under test did not produce?" + criteria: "A spec literal, a fixture not generated by importing the module, a law relating two views of one value, or a second implementation. An expected value computed or recorded by running the code under test, or any build or version of it, fails; collaborator call graphs are not asserted." + - question: "Is a hand-written refusal property written only where no consumer of the refined value can observe the refusal?" + criteria: "A refusal a decider, workflow, or published entry can observe is proven there. A refusal property draws its candidates from outside the refinement and judges decode against an oracle the schema did not produce; a property drawing from the refined schema's own generator accepts every widened refinement. Its can-fail evidence is an observed red, named by run or mutant id: a generated-input property run that failed, a mutant the property kills in the latest main CI mutation report, a throwaway deliberate-red CI change, or a new test run red on the real pre-fix commit; otherwise the change states red not shown. Red not shown discloses missing evidence and is never a waiver or a declaration under this entry's waiver: CONST-T3 and this law still apply in full, each through its own mechanism. A change stating it names, for each route, why it could not be produced, citing a run id, report, or commit SHA the reviewer can open that shows the route attempted or unavailable. Only a property the reviewer judges, from the property itself, can fail on a plausible bug justifies red not shown. A property with neither evidence nor red not shown, red not shown when a red was observed, a missing or contradicted reason or citation for any route, or a property the reviewer does not judge can fail on a plausible bug, is a breach of this law, P0." + mechanism: [review] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 12b663a48:packages/effect-schema-law/__tests__/bounded-union.snapshot.test.ts:141 (2026-08-05, fix 1c9e79034). A snapshot recorded 500 nesting depths sampled from the code's own generator under a fixed seed." + - "systemfsoftware/systemfsoftware 68d123e53:packages/testing/type-testing/arethetypeswrong/core/tests/snapshots.integration.test.ts:54 (2026-08-22, #229). Each per-recipe snapshot stored the analysis output of the code under test; review at b2ecd0e5:docs/residual-review-findings/attw-dsl-snapshots.md:8 rejected the snapshots as self-satisfying." + - law: CONST-T3 + handle: TESTS-CAN-FAIL + absorbs: [CONST-T13] + checks: + - question: "Is a named, change-relevant mutated set gated at a perfect kill score?" + criteria: "The set names the behaviour it covers, and its scope is a cost decision. Suppression comments, narrowing the set after the fact, lowering the gate, and an empty set fail; a raw mutation percentage is never compared across changes or codebases. A survivor is killed with a sharper property or by deleting the dead branch it exploits. Command: mutation gate, break 100." + - question: "Does every authored property file defend something the rest of the suite does not?" + criteria: "A run whose mutants all died fails when an authored property file defends nothing else. The opt-out is in the mutation config, never by deleting the named file, and a file that covered an unattributed kill is not accused. The verdict is part of the same run as the score." + mechanism: [command] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware cca5f66e8:packages/hex-schema/src/hex-string.schema.ts:12 (2026-07-31, fix b5cf2e1d2). The round-trip laws drew inputs from a generator mirroring the pattern under test, so every widening of the pattern survived." + - "systemfsoftware/systemfsoftware 0b48aea4e:packages/effect-daemon-spec/stryker.config.json:28 (2026-08-05, fix beb24866d). effect-daemon-spec's tests killed no mutant attributed to any test, under a break of 0, so the run scored 33.33 and exited 0; review at a914e31e:docs/residual-review-findings/test-contribution-gate.md:146 recorded it." + - law: CONST-T12 + handle: TEST-OBLIGATION + absorbs: [CONST-P3] + checks: + - question: "Is what applies to code decided from what the code imports and calls, never from its folder, name or extension?" + criteria: "No rule, runner, project split or tool chooses the requirement, harness or suite that governs a test from its folder or from any part of its name beyond the generic test-file ending the runner uses to discover tests; that ending decides only that the file runs. Each requirement resolves from the test's imports and calls. A lint that governs only a file's name or placement, against an allowed list or against the file's imports, states no testing requirement and is allowed. Command: lint." + - question: "Technique: is purity judged by return type alone?" + criteria: "Pure or effectful is read from the return type, never inferred from a folder, a package, or \"library versus application\"." + mechanism: [command] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware fe16c51ae:.github/workflows/mutation.yml:69 (2026-08-17, fix 7b4e08e24). Mutation targets were chosen by a path label; when fixtures moved, the label stopped matching and five fixture configs were enrolled, one built to fail." + - "systemfsoftware/systemfsoftware 824aa02e8:packages/oxlint-plugins/effect-kernel/src/rules/kernel-no-effect-runtime.ts:8 (2026-08-16, fix 166e6bb65). A purity rule applied only to files named *.kernel.ts, so a byte-identical file with another name escaped it." + - law: CONST-W1 + handle: FULL-SCOPE + absorbs: [] + checks: + - question: "Does the delivered scope match the accepted scope?" + criteria: "Scope is reduced mid-task only with the author's consent; a reduction because the work grew complex fails." + mechanism: [review] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/systemfsoftware 6851d0d4d:docs/plans/2026-09-26-2001-refactor-workflow-only-mutation-plan.md:20 (2026-09-26, #559). Offered to shrink the accepted enrollment by unenrolling ten packages (named at :37-38 of the same file: effect-atom, four effect-daemon media, five oxlint-plugin rule packages); the requester refused." + - "systemfsoftware/constitution 26a527c07:docs/plans/2026-09-01-0533-retire-the-ttsr-plugin-entirely-plan.md:16 (2026-09-01, #21). The restore kept the plugin alive in reduced form (three rule files and constitution-conduct-review.md); the requester rejected the reduced delivery and required the full removal." + - law: CONST-E7 + handle: EVIDENCE-NOT-SELF-GRADING + absorbs: [CONST-E9] + checks: + - question: "Does \"done\" name the gate that passed or the test that ran?" + criteria: "A reported score, a claimed \"it works\", or a report of a gate or test is not the gate or test itself." + - question: "Do the graded change and any judgment-surface change name different owners?" + criteria: "Lint configs, rule lists, thresholds, baselines, CI checks, validator scripts, rubrics, coverage floors and review criteria are read-only to the work they grade, whether or not the maker believes they grade this task. Building the gate the work will be graded by, or shaping one so the current work passes, fails, including in a separate commit by the same hands. A needed gate is a proposal to its owner, and the work waits for it." + mechanism: [review] + severity: P0 + waiver: "A breach is legal only when the change itself declares it, naming this law and the case; an undeclared breach is P0 (CONST-G3)." + incidents: + - "systemfsoftware/constitution 26a527c07:scripts/validate-constitution.ts:38 (2026-09-01, #21). The commit that merged the corpus also flipped the gate that grades it; d311127:docs/plans/2026-09-07-1721-the-maker-never-holds-the-instrument-plan.md:29 recorded it as the violation." + - "systemfsoftware/systemfsoftware a914e31e7:docs/residual-review-findings/test-contribution-gate.md:31 (2026-08-04). The gate replacement moved the grading script from top-level scripts/ into packages/stryker-plugins/src/test-contribution/, a neutrally named folder of an editable package; review flagged it as lock relocation." + - "systemfsoftware/systemfsoftware ee74d0b96:docs/residual-review-findings/fix-referenced-project-typecheck.md:45 (2026-08-04). Root guards were relied on to protect main, but five of six never ran in CI because .github/workflows/reusable-checks.yml invoked none of them." + - "systemfsoftware/systemfsoftware aa1bb6286:packages/core/effect/schema/law/AGENTS.md:15 (2026-08-24, #246, fix 9372ca05a). The package doctrine cited a test command's exit 0 as evidence while the package held zero tests; the empty suite passed." +judging: + - id: CONST-G3 + handle: P0-VERDICT + rule: "Every undeclared violation of the constitution found in review is an automatic P0: the change is rejected with no appeal and no downgrade to advisory, P1, P2 or non-blocking. The only legal waiver is a declaration in the change itself, naming the law and the case; a promise of follow-up repair or an expedience plea is not one. A review that waives or downgrades an undeclared violation is rejected." + - id: CONST-G4 + handle: PURPOSE-READING + rule: "Invoke a law by showing its harm is present, never by quoting a clause or asking which clause to cite. Where letter and purpose diverge, purpose governs: ask whether the harm occurs here." + - id: CONST-G5 + handle: SUPREMACY + rule: "The constitution governs AGENTS.md, lint and ADRs on what a rule should say, where they conflict. On whether a rule held for a specific change, the gate is the final word; a disagreement goes to the channel that owns the instrument, never resolved by the maker editing or overriding the gate. Contestable choices (suffixes, patterns, module shape) live in ADRs, not in the constitution." +retired: + - id: CONST-D3 + reason: "Obligation removed: no failure was found where a bare primitive stood in for a domain value, and a law stands only on two failure incidents." + - id: CONST-W2 + reason: "Obligation removed: no failure was found where a large or irreversible choice went unchallenged, and a law stands only on two failure incidents." + - id: CONST-S3 + reason: "Obligation removed: cut at gate 3, where a blind review found both failure incidents back only \"model only what a known requirement needs\", never \"define the outside contract first\". Its guidance stays as technique checks under SUBTRACT-FIRST (CONST-S4)." + - id: CONST-W3 + reason: "Obligation removed: one failure incident only, and a law stands on two. The reviewer-side waiver for a declared breach stays in P0-VERDICT (CONST-G3)." +``` diff --git a/README.md b/README.md index b24e080..434167a 100644 --- a/README.md +++ b/README.md @@ -1,99 +1,29 @@ -# Constitution +# constitution -[![License: Apache-2.0](https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square)](LICENSE) -[![System F Software](https://img.shields.io/badge/systemfsoftware.com-constitution-black?style=flat-square)](https://systemfsoftware.com/constitution) -[![Rules: 38](https://img.shields.io/badge/rules-38%20in%20corpus-blue?style=flat-square)](CONSTITUTION.md) +[![License: Apache 2.0](https://img.shields.io/badge/license-Apache_2.0-blue?style=flat-square)](LICENSE) -Shared engineering laws for repositories at [System F Software](https://systemfsoftware.com). +The shared engineering laws for System F Software: how to model a domain, shape its code, prove it works and finish a change. Repositories across the organization vendor this one and read the same laws. -It defines baseline architecture and code quality standards: a pure functional core behind a thin imperative shell, domain types before logic, mutation testing for decision paths, and subtracting code before adding more. Stack-neutral and enforced across all projects. +## What is here -```mermaid -flowchart LR - S["systemfsoftware/constitution
Upstream Repository"] -->|git subtree| A[Consumer Repo A] - S -->|git subtree| B[Consumer Repo B] - S -->|git subtree| C[Consumer Repo C] - A -.symlink.-> S - B -.symlink.-> S - C -.symlink.-> S -``` +| File | Read it when | +| :-- | :-- | +| [CONSTITUTION.md](CONSTITUTION.md) | You write or review code under these laws. It holds 16 laws in four sections (model the domain, shape the code, prove it, finish), each with its harm and a wrong and right example. | +| [ENFORCEMENT.md](ENFORCEMENT.md) | You build or change a check that grades work, such as a lint rule, a CI job or a rubric. It holds the gate design, each law's mechanism and its incidents. | +| [`docs/solutions/`](docs/solutions) | You want the past problem behind a rule. Each note has YAML frontmatter (`module`, `tags`, `problem_type`). | ---- +Each law states an obligation and the harm it prevents. Read every law by its purpose: where the words and the harm disagree, the harm decides. -## Quick Start +## Use it in a repository -Vendor the repository using `git subtree` and symlink `CONSTITUTION.md` to the project root: +Vendor this repository into the consumer with `git subtree` under `repos/constitution`, and symlink `CONSTITUTION.md` to the vendored copy, as [systemfsoftware](https://github.com/systemfsoftware/systemfsoftware) does. -```bash -# 1. Fetch the remote into a local ref -git fetch https://github.com/systemfsoftware/constitution.git main:refs/remotes/vendor/constitution +Consumers that build or change a gate route that work to `ENFORCEMENT.md`. Makers read `CONSTITUTION.md` only, so the grading rules stay out of the work they grade. -# 2. Add as a squashed subtree -git subtree add --prefix=vendor/constitution refs/remotes/vendor/constitution --squash \ - -m "chore: vendor shared constitution" +## Contributing -# 3. Symlink the constitution to the repo root -ln -s vendor/constitution/CONSTITUTION.md CONSTITUTION.md -``` - -Include `@CONSTITUTION.md` in your agent harness (`AGENTS.md` or `CLAUDE.md`) so all 38 rules remain always-on in the context window. Never include `ENFORCEMENT.md` there — it is doctrine for whoever builds the gates, not for the agent the gates grade. Instead, wire it at the surfaces that own instruments: in every `AGENTS.md` leaf governing a lint plugin, guard script, CI workflow, rules directory, or advisor roster, add one routing line — "You are editing an enforcement instrument. Read the vendored `ENFORCEMENT.md` before this lands." - ---- - -## The Articles - -The 38 rules are structured across six sections in [`CONSTITUTION.md`](CONSTITUTION.md): - -| Section | Key Invariants | -| :--- | :--- | -| **Application** | Invoke rules by harm rather than clause; build failures decide; never edit what grades your work; evidence before done. | -| **Article I: Pure Core** | Pure decisions, explicit types, tagged error variants, no `null` states. | -| **Article II: Boundaries** | Functional core / imperative shell, values for effects, decode inputs rather than casting. | -| **Article III: Verification** | Testing Trophy investment order, properties by narrow grant, mutation as the measure, independent oracles. | -| **Article IV: Organization** | Organize by domain responsibility, clear naming, keep modules small. | -| **Article V: Conduct** | Zero-appeal P0 review enforcement, fix root causes, challenge decisions before committing, subtract before adding. | - ---- - -## Machine Validation - -Rules are defined as structured YAML blocks in `CONSTITUTION.md`: - -```yaml -- id: CONST-S4 - title: Subtract Before You Add - gate: review - do: treat every line as a liability — removal is the default response to slop - dont: extend a copy-paste cluster; patch around a rotten core - harm: the codebase only grows; rot survives every patch and regrows - check: review reads the net line delta; fixes that leave root violations are rejected -``` - -Run the validator to check rule IDs, schema compliance, and citation integrity across the corpus: - -```bash -deno task test -``` - -To verify that rule identifiers have not been reassigned against a previous git revision: - -```bash -deno task test --against -``` - ---- - -## Pulling Updates - -Pull upstream changes into the subtree without touching existing symlinks: - -```bash -git subtree pull --prefix=vendor/constitution https://github.com/systemfsoftware/constitution.git main --squash \ - -m "chore: update shared constitution" -``` - ---- +Setup, the validation task and the amendment rules are in [CONTRIBUTING.md](CONTRIBUTING.md). ## License -[Apache-2.0](LICENSE) © 2026 Ryan Lee. +Apache 2.0. See [LICENSE](LICENSE). diff --git a/deno.json b/deno.json index efabd36..45337a0 100644 --- a/deno.json +++ b/deno.json @@ -2,7 +2,8 @@ "version": "0.1.0", "nodeModulesDir": "auto", "tasks": { - "test": "deno run --allow-read=CONSTITUTION.md --allow-run=git scripts/validate-constitution.ts", + "test": "deno run --allow-read=CONSTITUTION.md,ENFORCEMENT.md --allow-run=git scripts/validate-constitution.ts", + "test:validator": "./scripts/validate-constitution.test.ts", "prepare": "git config core.hooksPath .husky" }, "imports": { diff --git a/docs/plans/2026-10-09-0320-refactor-constitution-rewrite-plan.md b/docs/plans/2026-10-09-0320-refactor-constitution-rewrite-plan.md new file mode 100644 index 0000000..0a23652 --- /dev/null +++ b/docs/plans/2026-10-09-0320-refactor-constitution-rewrite-plan.md @@ -0,0 +1,1175 @@ +--- +title: Constitution Rewrite - Inner-Loop Laws, Outer-Loop Enforcement - Plan +type: refactor +date: 2026-10-09 +topic: constitution-rewrite +artifact_contract: ce-unified-plan/v1 +product_contract_source: ce-brainstorm +execution: code +--- + +# Constitution Rewrite - Inner-Loop Laws, Outer-Loop Enforcement - Plan + +## Goal Capsule + +- **Objective:** A coding agent that vendors the constitution carries only what it can act on while it works: 17 laws, at most 1,800 words, each one a sentence, its harm, and a wrong/right pair from a real public incident. Whoever grades its work finds every check, mechanism, severity, waiver and judging rule in `ENFORCEMENT.md`, keyed to those laws. Every id a reader has ever cited resolves to its new home, by machine in the corpus and by table in this plan. +- **Means:** Rewrite `CONSTITUTION.md` to Appendix A (KTD7). Give `ENFORCEMENT.md` a per-law corpus with lineage (KTD1-KTD4). Have a separate instrument owner extend the validator (KTD5). Migrate the live surfaces in this repo (KTD9). +- **Authority:** Conductor brief c05, rulings c06, steer c07 (the overfit gate) and rulings c08 and c09 (strict failure incidents, the termination rule) settle every product question. `CONSTITUTION.md` governs what a law means; `ENFORCEMENT.md` governs how an instrument is changed; `AGENTS.md` governs commit, verification and surface-class discipline. `AGENTS.md`, `CONSTITUTION.md` and `README.md` are human-controlled: the conductor takes their full text to the owner, and nothing merges without that approval. +- **Execution profile:** One branch, `refactor/constitution-rewrite`, cut from `origin/main` and published as a single-layer `gh stack`, opened as one PR with three commits in order: the plan, the validator, then the corpus and its surfaces (KTD5, KTD10). +- **Stop conditions:** + - Stop if `wc -w CONSTITUTION.md` exceeds 1,800. + - Stop if any law's example cannot be traced to its Appendix E source. + - Stop if any law has fewer than two independent incidents in Appendix E (R21). + - Stop before committing any `CONSTITUTION.md` text if gate 1, 2 or 3 (R21-R23) has not run on that exact law text, or if the conductor has not ruled on every gate 3 flag. + - Stop if the new validator passes on the `origin/main` tree. + - Stop if any scratch violation in the Verification Contract exits 0. + - Stop if `--against origin/main` reports an unaccounted id. + - Stop if the validator owner's run had the law text in its context. + - If commit signing fails, report the exact error and leave the git config alone. + - Never use `--no-verify`, never force-push, never run mutation or Stryker locally. +- **Who finishes:** The maker (`ce-work`) does U2-U5. The instrument owner, a fresh-context subagent, does U1. The parent agent integrates and verifies (U5) and opens the PR. The conductor takes the text to the owner and merges. + +--- + +## Product Contract + +Product Contract preservation: changed R1, R5, R6, R7, R8, R9, R10, R12, R13, R15, R17, R18 and R20; added R19-R25. Each change applies a c06 ruling, the c07 overfit gate, or the c08 and c09 rulings; no requirement was dropped. + +### Summary + +Rewrite `CONSTITUTION.md` as 17 inner-loop laws in four sections (Model the domain, Shape the code, Prove it, Finish) under a one-line preamble. Each law has exactly four fields: `id`, `law`, `why`, and `example: {wrong, right}`. `ENFORCEMENT.md` keeps its doctrine and gains a versioned corpus: + +- a law-keyed entry per law: a stable obligation handle, an `absorbs:` list, check questions with criteria, mechanism rungs, severity and waiver; +- three judging rules, G3, G4 and G5, which keep their ids. + +A fresh-context instrument owner extends the validator to the new shape and to lineage-by-handle. The human-readable id mapping stays in this plan (Appendix B). + +### Problem Frame + +The maker reads `CONSTITUTION.md` in its context window on every turn (`AGENTS.md:5` `@`-imports it). At 693a6d7 the file is 4,054 words (`wc -w`). All 36 rules carry `gate:` and `check:`, and only 8 carry an `example:` (D4, P2, B2, B3, B6, B5, P3, S4). The maker cannot run a `check:`. Each one is an instruction to lint, review or mutation, read by an agent that executes none of them. That text is also where the contradictions live: CR-1 (T12's check against N2's check) set one check against another, not one law against another, and it took PR #27 to patch. + +Ids churn. T4 and T11 were vacated (#26, #25). The consumer cites 11 ids that no longer exist on `main` (Appendix B2), and 31 of those citing lines are `CONST-E4` alone. + +`ENFORCEMENT.md` already declares itself the outer-loop home ("Never `@`-import this file into a maker's context", `ENFORCEMENT.md:3`), so the split has somewhere to go. + +### Key Decisions + +- **Two audiences, nothing duplicated.** `CONSTITUTION.md` is the inner loop. Constraints, sampling, audit and verdict live in `ENFORCEMENT.md`. (session-settled: user-directed, brief c05 - chosen over keeping `gate`/`check` inline, which is context noise to an agent that cannot run it and is where CR-1 lived.) +- **Four fields per law: `id`, `law`, `why`, `example: {wrong, right}`.** No `gate`, `check`, severity, waiver or tool name. (session-settled: user-directed, c05 and c06 OQ7 - chosen over flat `wrong`/`right` keys, because "exactly four keys" is then literally checkable.) +- **The merge map is the brief's, with c06's folds.** Merged into one law each: + - B1+B2+B3+B6+P1+P2, D1+B5, N1+N2, T8+T15+T9+T14, T3+T13, E7+E9 (c08 removes W3 and W2 from E7 and S2); + - D3, W2 and W3 are retired: under c08's strict gate 1 none has two failure incidents behind its clause. P3, retired under c08, is absorbed by T12 under c09: T12's new wording ("never from its name or location") carries P3's "never by folder", and its second incident is P3's purity rule keyed on a filename; + - under c09, T14 is retired as a law by ruling, and P1, B5 and T9 are cut by the termination rule (gate 3 still flagged them). Each one's guidance becomes a technique in its host's ENFORCEMENT entry, and its id is absorbed there (Appendix E). + + Kept: B4, D2, D4, N3, T10, T12, S1, S3, S4, W1. G3, G4 and G5 become ENFORCEMENT judging rules. (session-settled: user-directed, c05 and c06 OQ4.) +- **17 laws.** The binding limit is the word budget, not the count; c09's termination rule prefers fewer, well-evidenced laws. (session-settled: user-directed, c06 OQ5 and c09.) +- **A law whose obligation survives keeps its id, even when merged.** It takes the lowest surviving id. (session-settled: user-directed, c05 - chosen over today's rule that a changed obligation vacates the number, `CONCEPTS.md:11`, which would vacate every merged id.) +- **Lineage is machine-checked in ENFORCEMENT; the prose table lives in this plan.** Each law-keyed entry carries a stable obligation `handle` and an `absorbs:` list, and `--against` checks lineage through them. (session-settled: user-directed, c06 OQ2.) +- **Two kinds of ENFORCEMENT entry.** A law-keyed entry must name a live law. Judging rules G3, G4 and G5 keep their ids and are exempt from that check. (session-settled: user-directed, c06 OQ3.) +- **T12 keeps its id; its handle is TEST-OBLIGATION.** (session-settled: user-directed, c06 OQ6.) +- **The validator change is written by a fresh-context subagent that never saw the law drafts.** It lands as its own commit in this PR, shown failing on the old corpus and passing on the new, with both owners named in the PR body. CONST-E9 holds; there is no declared breach. (session-settled: user-directed, c06 OQ1.) +- **Every example comes from public history: this repo or public systemfsoftware repos.** A law with no public incident does not stand alone. (session-settled: user-directed, c06 OQ8.) +- **A law stands only on two independent failure incidents.** A failure is code or a PR that broke the law, a revert, a failing command, or a review that rejected the violation; plan or review prose counts only where it names a concrete code location at a SHA. Independent means a different PR or commit. No single document or PR supplies incidents for more than two laws. A fixed incident is anchored at the fix's parent, with the fix hunk. (session-settled: user-directed, c07, c08 and c09.) c09 is the last redraft round: a law still flagged by gate 3 under (a), (c) or (d), or left with fewer than two qualifying failures, is cut from `CONSTITUTION.md`; its guidance becomes an ENFORCEMENT technique and its id is absorbed. Appendix E records each law's pair and each cut. +- **The rewrite claims structure, not better agents.** Nothing here measures behaviour. A held-out evaluation (old against new constitution on unseen tasks) does not exist yet; it belongs to the replay evaluator, which can ablate one law at a time using each entry's `incidents:` (R25). (session-settled: user-directed, c07.) +- **Live surfaces migrate; dated `docs/plans` keep old ids as records.** (session-settled: user-directed, c06 OQ9.) +- **`AGENTS.md` "Writing a Rule" and "Changing a Rule" change in this PR.** The family registry keeps G, now for the judging rules. (session-settled: user-directed, c06 OQ10.) +- **The consumer migration is a later PR in the consumer repo.** This PR only produces the mapping. (session-settled: user-directed, c05.) + +### Requirements + +**The resident law** + +- R1. `CONSTITUTION.md` is the Appendix A text: 17 laws in four sections ordered by when the agent needs them (Model the domain, Shape the code, Prove it, Finish). +- R2. Every law has exactly `id`, `law` (one sentence addressed to "you"), `why` (the harm), and `example` with exactly `wrong` and `right`, all strings. +- R3. A one-line preamble says to read every law by its purpose. +- R4. No `gate`, `check`, severity, waiver or tool name appears in the file. +- R5. The whole file is at most 1,800 words by `wc -w`, and the PR body reports the number. Appendix A measures 1,273. +- R6. No private repository is named anywhere in the change. Every example comes from this repo's or a public systemfsoftware repo's history, with its source cited in Appendix E. +- R20. A law carries only clauses with two failure incidents behind them (R21). Under c08 that removes D3's branding duty from CONST-D1, P3's "never by folder", T8's forwarding-helper clause, W2's challenge duty from CONST-S2 and W3's declaration duty from CONST-E7. Under c09, CONST-D1 drops "free of casts" (casts were B5's), CONST-T8 drops "test a pure decision directly" and its mock clause (one qualifying failure), and CONST-B1 is only "effects at the edges, as values". T12's c09 sentence carries P3's "never by folder" again, now with two failures. + +**The overfit gate (c07)** - gates 1-3 run, and are recorded, on the exact law text before any `CONSTITUTION.md` text is committed. Any later change to a `law` or `why` sentence re-runs them. + +- R21. Gate 1 (c08, strict): every law, and every clause of it, has at least two independent FAILURE incidents: code or a PR that broke it, a revert, or a review that rejected the violation. A later doc, plan or amendment that applies the law is not an incident; it may only point to one. Two incidents of one law come from different PRs or commits, not two symptoms of one change. Each ref is a commit SHA plus `path:line` at that commit, where `git show :` prints the violating code or the review text. Appendix E lists them. A law left with fewer than two is merged into a neighbour or cut; a clause left with fewer than two is removed. +- R22. Gate 2: no `law` or `why` sentence names a package, file, path, tool, CLI, suffix, framework or date. The example may. The two greps in the Verification Contract (Gate 2 rows) run over the extracted sentences and their output is recorded. +- R23. Gate 3: a fresh-context reviewer from a different model family sees only the law sentences, their `why` lines and the Appendix E refs. Per law, evidence first, it judges (a) wording broader than its incidents, (b) redundancy, (c) truth and use on an unrelated Effect-TS codebase, (d) tool or mechanism dressed as law. Every flag goes to the conductor unresolved; the conductor's ruling precedes the corpus commit. The model that actually ran is recorded. +- R24. The PR body makes no claim that the rewrite improves agent behaviour. It may claim no internal contradictions (the validator), no inner-loop noise (no `gate`/`check` fields), the word budget, and full id lineage. It states that a behavioural held-out evaluation does not exist yet and is the replay evaluator's job. +- R25. Each law-keyed ENFORCEMENT entry carries `incidents:`, the Appendix E refs that justify the law, so a replay evaluator can remove one law, re-score, and cut laws that move nothing. + +**The outer loop** + +- R7. `ENFORCEMENT.md` keeps its current doctrine text and gains a versioned corpus. Each law has exactly one law-keyed entry carrying: + - its handle and `absorbs:` list (Appendix C); + - check questions with explicit criteria; + - its mechanism rungs (type, command, refusal, review); + - its severity and waiver rule; + - its `incidents:` (R25). + + The corpus also carries one `retired:` list: each id whose obligation was removed, with its reason (D3, W2, W3 under c08). +- R8. G3 (P0-VERDICT), G4 (PURPOSE-READING) and G5 (SUPREMACY) are judging rules in the corpus. They keep their ids and carry their current obligations. Where G3 says "declared under CONST-W3" today, it says "declared in the change itself, naming the law and the case": the waiver stays a reviewer-side rule, while the maker-side declaration duty is retired with W3 (R20). +- R9. Every clause of an absorbed or kept rule's `do`, `dont`, `check` and `scope` that is not in the new law text lands in that law's entry criteria: + - P1's one path by exhaustive match, and P2's complexity-1 measure, go to B1 as a technique (c09); + - B5's decode, never cast goes to D1 as a technique (c09); + - T9's pin-before-delete, T14's property scope and generators, and the mock guidance go to T8 as techniques (c09); + - T15's investment order goes to T8; + - T3's mutation gate and T13's test-set verdict go to T3; + - N2's allowed-suffix convention goes to N1; + - B6's ordering-by-types goes to B1 as a technique, applied where one description carries the interaction; + - S4's merge-base delta and T12's behavioural-requirement scope come from PR #27 (KTD11). + + Clauses of D3, W2 and W3 are not carried: those ids are retired (R20, Appendix B). P3's clauses go to T12's entry (c09). + +**Ids and mapping** + +- R10. Every current id and every id the consumer cites maps to a law, a judging rule, an ENFORCEMENT doctrine section, or "retired: obligation removed" with a reason (Appendix B). +- R11. The mapping lists every consumer citation outside `repos/` at consumer `origin/main` 3ab8edca, with its new target (Appendices B and D). + +**The validator** + +- R12. `deno task test` fails when any of these holds: + - a law lacks exactly the four fields, or `example` lacks exactly `wrong` and `right`; + - `CONSTITUTION.md` exceeds 1,800 words; + - a law has zero or more than one law-keyed entry; + - a law-keyed entry names no live law; + - handles are not unique across the corpus; + - an id appears more than once across live laws, `absorbs:` lists and the `retired:` list, or a `retired:` item lacks a reason; + - a citation in either file resolves to neither a law, a judging rule, nor an absorbed id (a retired id is not a valid citation); + - a law-keyed entry carries fewer than two `incidents:` (c08, OQ11). + + It keeps the coverage-before-schema check and the unmeasurable exit (3). +- R13. `deno task test --against ` accounts for every id present at `` as live, absorbed, judging or retired. Where `` carries handles, it fails on an id whose handle changed and on an absorbed or retired id that returns as live. Where `` has no handles (`origin/main` today), its success line says the comparison was accounting-only. +- R14. The extended validator passes on the PR head. It fails on each scratch violation V1-V12 (Verification Contract) and on the `origin/main` tree. Every run is executed locally by the parent and recorded. +- R15. U1's owner writes the validator change without the law text in its context and lands it as its own commit. The PR body names both owners. + +**Repo surfaces** + +- R16. `README.md` matches the new shape: the badge count, the "all 36 rules" sentence, the Articles table (it becomes the four sections), and the Machine Validation excerpt and description. +- R17. Live in-repo text follows the mapping and the new schema: + - `ENFORCEMENT.md:25` (CONST-E9 becomes CONST-E7); + - `docs/solutions/architecture-patterns/a-test-never-takes-its-expected-value-from-the-code-under-test.md:27-29,40` (T10's quoted `dont` line, and E9); + - `CONCEPTS.md:8,11,21` (Constitution corpus, Rule, Corpus gate); + - `AGENTS.md:28,34` and its "Changing a Rule", "Minting an ID" G row, and `deno task test` comment lines. +- R18. The PR body's first line states that `AGENTS.md`, `CONSTITUTION.md` and `README.md` are human-controlled and need the owner's approval of the final text before merge. The body notes that PR #27's commits bypassed the hooks (no `core.hooksPath` in that worktree). Its claims obey R24. +- R19. Dated `docs/plans` files are not edited. + +### Acceptance Examples + +- AE1. An agent that `@`-imports `CONSTITUTION.md` reads 17 laws and no `gate`, `check` or severity text (R1-R4). +- AE2. A reviewer grading a change against CONST-T12 finds its criteria in the CONST-T12 entry of `ENFORCEMENT.md`, under handle TEST-OBLIGATION (R7). +- AE3. A consumer plan citing CONST-E4 resolves through Appendix B2 to CONST-E7, and a consumer file citing CONST-P2 resolves to CONST-B1 through Appendix B1 and through CONST-B1's `absorbs:`; a file citing CONST-D3 finds it retired, with the reason, in Appendix B1 and in the corpus's retired list (R10, R13). +- AE4. A later amendment that renames CONST-T12's handle fails `deno task test --against ` (R13). +- AE5. Deleting CONST-B4's ENFORCEMENT entry fails `deno task test` (R12). + +### Scope Boundaries + +- No consumer edits; the consumer migration is a later PR there. +- The PR #27 branch (`fix/t12-n2-suffix-conflict`) is untouched. #27 closes unmerged once this PR opens; its useful content lives on here, in the CONST-T12 and CONST-S4 ENFORCEMENT criteria (KTD11). +- No new families; G stays registered for the judging rules. +- None of these count as done: renaming fields while the checks stay inline; dropping a law with no mapping; invented examples; a plan in place of the rewrite; a gate wired but turned off. + +### Outstanding Questions + +None. c06 resolved OQ1-OQ10, and c08 resolved OQ11: the validator checks that every law-keyed entry has at least two `incidents:` (R12), written by U1's owner in its own commit; the owner's sign-off on the governed files covers the new check. + +### Sources + +- `CONSTITUTION.md` at 693a6d7: 36 rules; 36 `gate:` and 36 `check:` fields; 8 `example:` fields; 4,054 words. +- `ENFORCEMENT.md:3,7-12,17,19,23-25`; `AGENTS.md:5,28,34`; `CONCEPTS.md:8,11,21`; `README.md:5,39,43-54,58-82`. +- `scripts/validate-constitution.ts:1,39-44,60-67,247-253`; `deno.json:5`; `.husky/pre-commit:1` (`deno task test` on the working tree). +- `docs/plans/2026-09-07-1721-the-maker-never-holds-the-instrument-plan.md:29-31,111-114` (the 26a527c same-commit gate flip, and its repair). +- Consumer `systemfsoftware/systemfsoftware` (public) at `origin/main` 3ab8edca: `git grep -nE 'CONST-[A-Z][0-9]+' origin/main -- . ':!repos/'` finds 208 citing lines across 45 ids; summed per id (Appendix B), 274, because a line that cites two ids counts once for each. The public repos `stryker-js-effect`, `are-the-types-wrong-effect` and `effect-endgame-starter-kit` were searched for N3 incidents and hold none outside vendored copies. + +--- + +## Planning Contract + +### Key Technical Decisions + +- **KTD1. The ENFORCEMENT corpus is one fenced YAML block under a new final `## Corpus` heading.** The block is a map: + ```yaml + version: 1 + laws: + - law: CONST-T12 + handle: TEST-OBLIGATION + absorbs: [] + checks: + - question: ... + criteria: ... + mechanism: [command] + severity: P0 + waiver: ... + incidents: + - consumer docs/solutions/...:27 (2d4c724f #519) + - this repo f843304 + judging: + - id: CONST-G3 + handle: P0-VERDICT + rule: ... + ``` + - `mechanism` values come from the ENFORCEMENT ladder: `type`, `command`, `refusal`, `review`. Old `lint` and `mutation` gates become `command`, and old `type-checker` becomes `type`. Appendix C gives each law's rungs. + - The doctrine sections above the corpus stay byte-identical except line 25. + + `incidents:` lists the Appendix E refs as plain strings, source first. Governs R7, R8, R25. +- **KTD2. Severity is P0 for every law, and the waiver is a declaration in the change.** G3 grades every undeclared violation P0, so each entry states `severity: P0`. Each `waiver` names CONST-E7's declaration: the breach and the case, stated in the change itself. A per-law severity scale would contradict G3. Governs R7, R8. +- **KTD3. Handles are UPPER-KEBAB, unique across laws and judging rules, and frozen once landed (Appendix C).** A handle names the obligation, not the wording, so a reworded law keeps its handle. A changed obligation needs a new id. Governs R7, R13. +- **KTD4. Lineage semantics for `--against `.** + 1. Collect the ids at ``: rule or law blocks in `CONSTITUTION.md`, plus law-keyed and judging entries in `ENFORCEMENT.md` when present. + 2. Each one must be live (a law or a judging rule) or appear in exactly one `absorbs:` list. Otherwise: `FAIL unaccounted id`. + 3. When `` has a corpus, a live id whose handle differs fails as `reassigned`, and an id absorbed at `` that is live now fails as `resurrected`. + 4. When `` has no corpus, the success line appends `; lineage by accounting only, no handles at `. This follows the vacuous-pass doctrine (`ENFORCEMENT.md:19`): a reduced comparison is named, not hidden. + 5. Ids vacated without absorption are still listed as vacated. + + Governs R13. +- **KTD5. Validator ownership and commit order.** + - U1's owner is a fresh-context subagent. It works in an isolated scratch copy of the `origin/main` tree and receives only the validator contract (U1 Approach), never Appendix A. It returns a patch plus its own scratch-fixture evidence. + - Before commit 1, wire the hooks in the executing worktree: run `deno task prepare` (it sets `core.hooksPath .husky`, where `.husky/pre-commit` and `.husky/commit-msg` live) and confirm `git hook run pre-commit` runs `deno task test`. The shared repo config points at `.husky/_`, which does not exist in a worktree, so without this step no hook runs; PR #27's commits bypassed hooks that way. + - Commit 1 is this plan, made before any corpus edit so the hook runs the old validator on the old corpus. + - The maker then writes U2-U4 in the working tree, and the parent applies U1's patch. + - Commit 2 carries only the U1 files. Its own tree (new validator, old corpus) is red by design; the PR body states this and shows it. The pre-commit hook runs `deno task test` on the working tree (`.husky/pre-commit:1`), which already holds the new corpus, so the hook passes without `--no-verify`. + - Commit 3 carries the corpus and surfaces. + - The red run and the green run are executed by the parent in `git worktree` checkouts of the validator commit and the final commit (the Red before and Schema rows; AGENTS.md rule VER1, the verifier is never the maker). + + Governs R14, R15. +- **KTD6. The word budget is whitespace-separated tokens over the whole `CONSTITUTION.md`, the same count as `wc -w`.** Headings, fences and keys count. Governs R5, R12. +- **KTD7. Law blocks are top-level YAML sequences, one fenced block per section, with no `rules:` wrapper.** Appendix A is the normative text, copied byte for byte. The owner's approval may change wording; any change must keep R2-R5. Governs R1-R5. +- **KTD8. A clause trace proves nothing was silently dropped.** The PR body carries a table with one row per `do`/`dont`/`check`/`scope` clause of the 36 rules at 693a6d7, naming where the clause now lives: a law sentence, an entry's criteria, or a judging rule. Clauses that only restate another clause say so. Governs R9. +- **KTD9. Live-surface edits are the R16 and R17 list and nothing else.** `docs/solutions/architecture-patterns/the-vacuous-pass-gate-input-sets.md` quotes dated validator output (`:149-150`) and stays as a record. Governs R16, R17, R19. +- **KTD10. Commit types.** The plan commit is `docs(plans): ...`. The validator commit is `feat(gate)!: ...`, because the corpus shape it accepts breaks. The corpus commit is `refactor(constitution)!: ...`, following 26a527c's restructure precedent, with a `BREAKING CHANGE:` footer naming the removed fields and the merged ids. +- **KTD11. PR #27's two improvements carry into the corpus.** CONST-T12's entry is scoped to behavioural requirements: no rule, runner, project split or tool chooses the requirement, harness or suite that governs a test from its folder or from any part of its name beyond the generic test-file ending the runner uses to discover tests; a lint that governs only a file's name or placement states no testing requirement and is allowed (CONST-N1's naming criteria). CONST-S4's entry has review compute the net line delta from the diff against the merge base of the change and its target branch at the time of review, recomputed whenever the target moves, never from a figure the author supplied. Source: `fix/t12-n2-suffix-conflict` at c3bd625; KTD8's clause trace lists both clauses. Governs R9. + +### Sequencing + +Gates 1-3 (R21-R23) run on the Appendix A law text before U2 starts, and again on the owner's final wording if it changes a `law` or `why` sentence. U1 runs in parallel with U2-U4; U5 depends on all four. + +```mermaid +flowchart LR + P[commit 1: plan] --> U2 & U3 & U4 + U1[U1 validator, isolated] --> U5 + U2[U2 CONSTITUTION.md] --> U5 + U3[U3 ENFORCEMENT corpus] --> U5 + U4[U4 live surfaces] --> U5[U5 integrate: commits 2 and 3, verify, PR] +``` + +### Risks + +- The red intermediate commit (commit 2) breaks `git bisect` on that one commit. That is accepted and declared (c06). +- The owner's wording changes could push the file past 1,800 words. The validator catches this at commit time. +- Two incidents per law guards against fitting one event; it does not show the laws change behaviour. That needs the held-out evaluation R24 names, which does not exist yet. +- Some incidents support two laws (Appendix E lists the shared PRs and fixes); no document or PR backs more than two (c09). Gate 3's redundancy question is where that overlap gets judged. + +--- + +## Implementation Units + +### U1. Extend the corpus validator (instrument owner) + +- **Goal:** `scripts/validate-constitution.ts` enforces R12 and R13 on the two-file corpus. +- **Requirements:** R12, R13, R14, R15. +- **Files:** `scripts/validate-constitution.ts` (including the shebang `--allow-read`), `deno.json` (the `test` task's `--allow-read` adds `ENFORCEMENT.md`). +- **Approach:** Dispatch a fresh-context subagent (`single-unit-coder`) into a scratch copy of the `origin/main` tree. Its whole input is this contract: KTD1's corpus shape with placeholder entries, KTD3, KTD4, KTD6, KTD7's block shape, R12, R13, and the doctrine in `ENFORCEMENT.md`. It is told not to read `docs/plans/` or any rewritten corpus. It builds its own synthetic fixtures in a dot-prefixed scratch directory and deletes them before returning. It returns the patch and its fixture run log. The subagent's id is recorded for the PR body. +- **Test scenarios:** V1-V12 (Verification Contract), run first by the owner on synthetic fixtures, then by the parent on scratch copies of the real corpus. No test file is committed: the repo has no suite, and the validator itself is the gate. +- **Verification:** the parent runs V1-V12 and the red run (KTD5). + +### U2. Rewrite `CONSTITUTION.md` + +- **Goal:** the file is Appendix A. +- **Requirements:** R1-R6, R20. +- **Files:** `CONSTITUTION.md`. +- **Approach:** replace the whole file with the Appendix A block content. +- **Verification:** `wc -w CONSTITUTION.md` is at most 1,800, and `diff` against Appendix A shows nothing. + +### U3. Add the ENFORCEMENT corpus + +- **Goal:** each law and judging rule has its entry per KTD1-KTD3. +- **Requirements:** R7, R8, R9. +- **Files:** `ENFORCEMENT.md`. +- **Approach:** + - Append `## Corpus`. + - Write each law-keyed entry from Appendix C (handle, absorbs, rungs), with `incidents:` from Appendix E. Derive its checks and criteria from the `gate`, `check`, `do`, `dont` and `scope` text of every id it keeps or absorbs at 693a6d7, with no new obligation. + - Write CONST-T12's and CONST-S4's criteria per KTD11. + - Write G3, G4 and G5 from their current text, with G3's CONST-W3 reference rewritten per R8. + - Change line 25's CONST-E9 to CONST-E7. + - Build the KTD8 clause trace for the PR body while writing. +- **Verification:** `git diff origin/main -- ENFORCEMENT.md` shows changes only at line 25 and in the new final section, and the clause trace has no unmapped row. + +### U4. Migrate the live surfaces + +- **Goal:** no live text in this repo describes the old schema or cites an absorbed id. +- **Requirements:** R16, R17, R19. +- **Files:** `AGENTS.md`, `CONCEPTS.md`, `README.md`, `docs/solutions/architecture-patterns/a-test-never-takes-its-expected-value-from-the-code-under-test.md`. +- **Approach:** + - `AGENTS.md:28`: the corpus bullet names the four sections. + - `AGENTS.md:34` "Writing a Rule": the four law fields, plus the ENFORCEMENT entry fields. + - `AGENTS.md` "Changing a Rule": the c05 id policy, and handles frozen per KTD3. + - `AGENTS.md` "Minting an ID": the G row's purpose becomes the ENFORCEMENT judging rules. + - `AGENTS.md`: the `deno task test` comment names two files. + - `CONCEPTS.md` Rule (`:11`) and Corpus gate (`:21`): restated to the two-file corpus and the new id policy. The Constitution corpus entry (`:8`) is unchanged unless its wording names one file. + - `README.md`: the R16 list. + - The solutions doc: its T10 quote becomes T10's `law` sentence, and E9 becomes E7. +- **Verification:** the DEL1 command in the Verification Contract. + +### U5. Integrate, verify and open the PR + +- **Goal:** three signed commits on `refactor/constitution-rewrite` and one open PR. +- **Requirements:** R14, R15, R18. +- **Approach:** + - Follow KTD5's commit order and run every Verification Contract row. + - Adopt the branch with `gh stack init` and check the `gh stack view` trunk. + - Push with a plain `git push -u`. + - Run `gh stack submit --auto --open`. + - Write a PR body with: the R18 first line; both owners; the red/green evidence; the `wc -w` number; V1-V12 results; the KTD8 clause trace; and a link to Appendix B. + +--- + +## Verification Contract + +Every row is run by the parent on the PR head unless it says otherwise. A scratch row runs on a temporary copy of the PR-head tree with one edit and is never committed. Inside table cells, `\|` is the markdown escape for a pipe: type a plain `|` when running a command. + +| Row | Command | Expected | +|---|---|---| +| Schema | `deno task test` | exit 0; the success line counts 17 laws and 3 judging rules | +| Lineage | `deno task test --against origin/main` | exit 0; the success line names the accounting-only comparison | +| Words | `wc -w CONSTITUTION.md` | at most 1800 | +| Red before | new validator in a worktree of commit 2 (old corpus) | exit 1 with FAIL lines naming the old fields | +| V1 | add a `gate:` key to one law | exit 1, unknown field | +| V2 | delete one law's `why` | exit 1, missing field | +| V3 | delete one `example.right` | exit 1, example shape | +| V4 | append 120 words to one `law` | exit 1, word budget | +| V5 | delete CONST-B4's law-keyed entry | exit 1, law without entry | +| V6 | point one entry at `CONST-B9` | exit 1, entry names no live law | +| V7 | give two entries the same handle | exit 1, duplicate handle | +| V8 | add `CONST-B4` to an `absorbs:` list | exit 1, absorbed id is live | +| V9 | remove `CONST-N2` from every `absorbs:` list, then `--against origin/main` | exit 1, unaccounted id | +| V10 | scratch repo: commit the PR-head corpus, change CONST-T12's handle, commit, `--against HEAD~1` | exit 1, reassigned | +| V11 | cite `CONST-E9` in `ENFORCEMENT.md` doctrine text, with it absorbed | exit 0 (an absorbed id resolves); cite `CONST-Q1`: exit 1, dangling | +| V12 | remove a closing fence | exit 1, coverage | +| DEL1 | `git grep -nE 'CONST-(D3\|P1\|P2\|P3\|B2\|B3\|B5\|B6\|N2\|T9\|T14\|T15\|T13\|E9\|W2\|W3)\b' -- . ':!docs/plans'` | matches only `absorbs:` and `retired:` lines in `ENFORCEMENT.md` | +| Gate 1 | Appendix E: `git show :` prints each ref's cited line, each fix commit exists, each law has two refs from different PRs or commits, and no PR or document backs more than two laws | 17 of 17 | +| Gate 2 code tokens | extract every `law` and `why` line to a scratch file, then ``grep -nP '`\|\*\.\|\.(ts\|js\|md\|json\|ya?ml)\b\|/\|\b\d{4}-\d{2}-\d{2}\b\|\b\d{4}\b\|\b[a-z]+[A-Z]\w*\|\w+\(\)\|@\w\|#\d'`` | exit 1, no output | +| Gate 2 tool names | `grep -nPi` over the same file for the tool, runner and framework list in Appendix E | output recorded; any hit is reported, with the reading of the word | +| Gate 3 | blind reviewer per R23 on the law text being committed | every flag listed for the conductor, model recorded | +| Private names | for each name from `gh repo list systemfsoftware --visibility private`, search `git diff origin/main...HEAD` for `systemfsoftware/` and `github.com/systemfsoftware/` | no match. A bare name is not searched: one private repo's name equals a file this diff edits, so a bare-name hit proves nothing | +| Commits | `git config core.hooksPath` and `git hook run pre-commit` before commit 1; `git log --format='%h %G? %s' origin/main..HEAD` | `.husky`; the hook runs `deno task test`; `G` on every commit; conventional subjects | +| Stack | the OP13b `gh stack view --json \| jq -e` check | exit 0 | + +--- + +## Definition of Done + +- U1-U5 are done, and every Verification Contract row has passed in the run that ships them. +- The three commits are signed and in KTD5's order. The PR is open, not a draft, and its body carries every U5 element. +- No scratch fixture, `git worktree` or abandoned edit remains, and `git status` is clean. + +--- + +## Appendix A - Normative law text + +Measured with `wc -w` on the block content: 1,273 words. Each example's source is the first incident for that law in Appendix E. + +````markdown +# Constitution + +Read every law by its purpose: where its words and its harm part ways, the harm decides. + +## Model the domain + +```yaml +- id: CONST-S3 + law: Define the outside contract first, and model only what a known requirement needs. + why: Structure built for a consumer nobody has never pays off, and it constrains what follows. + example: + wrong: The CliRequest schema was exported though nothing decoded it; every use was a type position, and its obligation scan timed out at 15 seconds. + right: Export a schema only when a consumer decodes with it; derive the types from unexported bases. +- id: CONST-D1 + law: Close your types so an illegal value cannot be constructed. + why: A value the type could have refused reaches runtime, and every check downstream trusts it. + example: + wrong: A lock helper took a lock spec and a nullable adapter, so a spec that required the lock, paired with no adapter, ran its body unlocked. + right: One union of the valid spec-and-adapter pairs made the unlocked case impossible to construct. +- id: CONST-D2 + law: Give every distinct failure its own tagged variant. + why: Callers cannot branch on the real failure, and distinct errors collapse into one case. + example: + wrong: Generator exhaustion and a real counterexample both became one "refuted" error built from a placeholder, so a property that never ran read as refuted. + right: Exhaustion is its own tagged error, and a refutation cannot be built without a real counterexample. +- id: CONST-D4 + law: Model mutually exclusive states as a tagged union, one variant per state carrying only its own fields; keep a plain nullable for a value absent the same way in every state. + why: A state machine hides in a record, and the compiler cannot reject an invalid mix of fields. + example: + wrong: "CheckerDecision { results, needsRetest }: the state is read off a field." + right: CheckFinished | RetestRequired, the second variant produced by the decider's retest branch. +``` + +## Shape the code + +```yaml +- id: CONST-B1 + law: Keep effects at the edges, as values. + why: An effect inside a decision cannot be tested without the world it touches, and a defect hides at the seam. + example: + wrong: The config resolver read a file, decided, resolved the next specifier and recursed inside one async function. + right: A pure step returns the next read as data, and a thin shell performs it. +- id: CONST-B4 + law: Let the shell import the core, and wire every implementation at one composition root; the core never imports the shell, a database, or a framework. + why: A decision chained to infrastructure cannot be tested or replaced. + example: + wrong: A CLI adapter imported the Node standard-IO layer and provided it to itself, below the composition root. + right: The adapter declares that it needs standard IO, and the composition root provides it. +- id: CONST-N1 + law: Organise code by what it does, and name every file and folder for its job; a name must answer "of what?". + why: One change scatters across the tree, and a bucket named for a layer says nothing a reader can check. + example: + wrong: Packages were nested into role tiers (core, testing, lint) that grouped packages sharing nothing a reader could check. + right: The tiers were reverted; folders name product families. +- id: CONST-N3 + law: Give each module one responsibility, and split it when its tests need elaborate setup. + why: Nobody can reason about the whole module, and its tests grow brittle. + example: + wrong: One module held a config type, its text parser, a process-wide cache with a test-only reset, and the file read, so its tests needed a fake file system. + right: It split into a schema, a translator and an executor that does the read, and each is tested on its own. +- id: CONST-S1 + law: Fix the root cause; when the design is wrong, restructure it. + why: A patched symptom comes back. + example: + wrong: Every transaction rollback was mapped to a version conflict, so any bug in the transaction looked like a race and retries walked an order into a rollback the customer never earned. + right: The duplicate check moved inside the serializable transaction, and only a real serialization failure retries. +- id: CONST-S2 + law: Justify every choice by these laws, never by the file next to it or a prior plan's wording. + why: An unexamined default hardens into a rule, and each copy seeds the next. + example: + wrong: A planning session wrote an adapter's package name into law, and every later import and plan inherited the misnaming. + right: Authority traces to the architecture; the package was renamed for what it does and the old name deleted in the same change. +- id: CONST-S4 + law: Treat every line as a liability; delete, unify, or make the bad state unconstructable before you add. + why: The codebase only grows, and rot survives every patch. + example: + wrong: A thirteen-role taxonomy grew to 100 rules; one role shipped 5 rules against 0 files. + right: Thirty rules were deleted at no cost; the compiler already refused each violation. +``` + +## Prove it + +```yaml +- id: CONST-T8 + law: Test the published surface with real inputs and outputs. + why: A test that stops short of what ships stays green while the shipped artifact is broken. + example: + wrong: Tests imported the package's source, so it published with no built output and no consumer could import it. + right: The package ships its build, and the pack check reads what each tarball contains. +- id: CONST-T10 + law: Take every expected value from an oracle the code under test did not produce - a spec literal, an independent fixture, a law between two views, or a second implementation. + why: A test that compares the code with itself cannot fail when the code is wrong. + example: + wrong: A snapshot of 500 observed depths moved whenever the generator, the schema, or the seed moved. + right: The snapshot kind was deleted rather than re-recorded. +- id: CONST-T3 + law: Make every test able to fail when the behaviour it names breaks. + why: A suite that notices nothing certifies nothing, and a toothless test hides among the ones that work. + example: + wrong: Round-trip laws drew their inputs from the schema's own generator, so every widened pattern survived. + right: Rejection properties whose inputs come from the domain contract killed the survivors. +- id: CONST-T12 + law: Decide what applies to code (which checks, tests and requirements) from what it is and does, never from its name or location. + why: A rename or a move silently drops a requirement, or applies one where it does not belong, while everything stays green. + example: + wrong: Mutation targets were chosen by a path label; when fixtures moved, five were enrolled, one built to fail. + right: A target is selected by what it is, a workspace package the lockfile declares. +``` + +## Finish + +```yaml +- id: CONST-W1 + law: Deliver the whole accepted task; shrink it only with the requester's agreement. + why: Half-finished work, and effort spent second-guessing intent. + example: + wrong: The offered shortcut was to drop packages that could not comply from the enrolled set. + right: Every deciding package was enrolled; the one exception was named in the change for the author to rule on. +- id: CONST-E7 + law: Show evidence (a command that passed or a test that ran) before you call work done, and never edit, add, or weaken anything that grades your work. + why: Work called done on no evidence ships broken, and whoever edits the grader reports the score they chose. + example: + wrong: One commit changed the law and flipped the gate that grades it. + right: The next amendment shipped with the gate's behaviour untouched. +``` +```` + +--- + +## Appendix B - Id mapping + +Consumer citations count the lines that cite the id in the consumer at `origin/main` 3ab8edca, outside `repos/`. "plans" is `docs/plans`, "solutions" is `docs/solutions`, and "other" is any other path (Appendix D). + +### B1 - Every id on this repo's `main` (36) + +| Old id | Title on `main` | New target | Consumer citations | Note | +|---|---|---|---|---| +| CONST-G4 | By Purpose, Not Quotation | CONST-G4 (judging rule, PURPOSE-READING) | 2 (2 plans) | Keeps its id in ENFORCEMENT; the maker-facing half is the preamble line. | +| CONST-E9 | Never Edit What Grades Your Work | CONST-E7 | 13 (2 other, 10 plans, 1 solutions) | Merged. | +| CONST-E7 | Evidence Before Done | CONST-E7 | 1 (1 plans) | Lowest surviving id of E7+E9. | +| CONST-G5 | Supreme | CONST-G5 (judging rule, SUPREMACY) | 2 (2 plans) | Keeps its id in ENFORCEMENT. | +| CONST-P1 | Purity | CONST-B1 | 11 (1 other, 9 plans, 1 solutions) | Absorbed (c09 termination rule): gate 3 flagged its pure-function clause as unsupported by its incidents and redundant with B1. One path by exhaustive match is a technique in B1's ENFORCEMENT entry. | +| CONST-D1 | Types Before Logic | CONST-D1 | 1 (1 plans) | Kept as "close your types"; D3 is retired. | +| CONST-D2 | Each Error Its Own Variant | CONST-D2 | 10 (1 other, 7 plans, 2 solutions) | Kept. | +| CONST-D3 | No Primitive Obsession | retired: obligation removed | 10 (9 other, 1 plans) | No failure where a bare primitive stood in for a domain value was found (c08 gate 1). | +| CONST-D4 | Null Is Not a State | CONST-D4 | 10 (4 other, 4 plans, 2 solutions) | Kept. | +| CONST-P2 | The Pure Core Has One Path | CONST-B1 | 9 (7 plans, 2 solutions) | Absorbed with P1; the complexity-1 measure moves to B1's ENFORCEMENT entry. | +| CONST-B1 | Functional Core, Imperative Shell | CONST-B1 | 8 (1 other, 6 plans, 1 solutions) | Survives as "effects at the edges, as values"; absorbs B2, B3, B6, P1 and P2. | +| CONST-B2 | Effects Are Values | CONST-B1 | 3 (3 plans) | Merged. | +| CONST-B3 | The I/O Sandwich | CONST-B1 | 15 (1 other, 13 plans, 1 solutions) | Merged; the fixed five-phase sequence is dropped (c08: withdrawn where a case writes before it classifies). | +| CONST-B6 | The Sandwich Order Is Carried by Types | CONST-B1 | 3 (3 plans) | Merged; ordering-by-types is a technique in B1's ENFORCEMENT entry, applied where one description carries the interaction; a generator body does not preserve order in its type (c08). | +| CONST-B4 | Dependencies Point Inward | CONST-B4 | 9 (9 plans) | Kept. | +| CONST-B5 | Decode, Never Cast | CONST-D1 | 7 (7 plans) | Absorbed (c09 termination rule): gate 3 flagged its typed-result clause as broader than its incidents. Decode, never cast is a technique in D1's ENFORCEMENT entry. | +| CONST-P3 | Purity Is Per Function, Not Per Folder | CONST-T12 | 10 (7 plans, 3 solutions) | Absorbed (c09): T12 now decides what applies from what code is, never its name or location; P3's filename-keyed purity rule is T12's second incident. Judging purity by return type is a technique in T12's entry. | +| CONST-T15 | The Testing Trophy | CONST-T8 | 1 (1 plans) | Absorbed; investment order moves to T8's ENFORCEMENT entry. | +| CONST-T8 | Test Public Functions Directly | CONST-T8 | 2 (2 plans) | Survives as "test the published surface"; absorbs T15, T9 and T14. | +| CONST-T14 | Properties Where the Surface Cannot Reach | CONST-T8 | 2 (2 plans) | Absorbed (c09 ruling): a testing technique, not a law. Property scope and generators are a technique in T8's ENFORCEMENT entry. | +| CONST-T3 | Mutation Is the Measure | CONST-T3 | 10 (2 other, 7 plans, 1 solutions) | Lowest of T3+T13; the mutation gate moves to T3's ENFORCEMENT entry. | +| CONST-T13 | Mutation Also Grades the Tests | CONST-T3 | 0 | Merged; the test-set verdict moves to T3's ENFORCEMENT entry. | +| CONST-T9 | Pin the Published Contract Before You Delete a Path | CONST-T8 | 1 (1 plans) | Absorbed (c09 termination rule): gate 3 flagged its trigger as broader than its incidents and redundant with T8. Pin before delete is a technique in T8's ENFORCEMENT entry. | +| CONST-T10 | The Oracle Is Not the System Under Test | CONST-T10 | 5 (1 other, 4 plans) | Kept. | +| CONST-T12 | What a Test Does Comes from What It Calls | CONST-T12 | 1 (1 plans) | Kept (OQ6); restated as TEST-OBLIGATION. | +| CONST-N1 | Organized by What It Does | CONST-N1 | 5 (5 plans) | Lowest of N1+N2. | +| CONST-N2 | Names Scream the Domain | CONST-N1 | 12 (12 plans) | Merged; the allowed-suffix convention moves to N1's ENFORCEMENT entry and tooling. | +| CONST-N3 | Fits in the Head | CONST-N3 | 2 (2 plans) | Kept. | +| CONST-G3 | Constitutional Violations Are Automatic P0 Failures | CONST-G3 (judging rule, P0-VERDICT) | 0 | Keeps its id in ENFORCEMENT; its W3 reference becomes a declaration in the change itself (R8). | +| CONST-S1 | Depth Over Expedience | CONST-S1 | 2 (2 plans) | Kept. | +| CONST-W1 | Scope Discipline | CONST-W1 | 1 (1 plans) | Kept. | +| CONST-S2 | First Principles Over Precedent | CONST-S2 | 1 (1 plans) | Kept. | +| CONST-S3 | API-First Discovery | CONST-S3 | 7 (7 plans) | Kept. | +| CONST-W2 | Challenge Before You Commit | retired: obligation removed | 2 (2 plans) | No failure where a large or irreversible choice went unchallenged was found (c08 gate 1). | +| CONST-W3 | No Silent Bypass | retired: obligation removed | 6 (1 other, 5 plans) | One failure only (consumer gh-285 review, #288). G3's reviewer-side waiver for a declared breach stays (R8). | +| CONST-S4 | Subtract Before You Add | CONST-S4 | 22 (22 plans) | Kept. | + +### B2 - Ids the consumer cites that are not on `main` + +| Old id | Last title | Last on `main` | New target | Consumer citations | Note | +|---|---|---|---|---|---| +| CONST-E1 | Prefer the Gate | 4b790f3 (2026-08-20) | ENFORCEMENT Mechanism (the ladder) | 5 (5 plans) | | +| CONST-E2 | Evidence Before Done | 4b790f3 (2026-08-20) | CONST-E7 | 1 (1 plans) | Same obligation as today's E7. | +| CONST-E3 | A Gate Earns Its Place | 4b790f3 (2026-08-20) | ENFORCEMENT Gate economy | 5 (5 plans) | | +| CONST-E4 | The Evaluator Is Not the Agent's to Edit | 4b790f3 (2026-08-20) | CONST-E7 | 31 (31 plans) | Same obligation as today's E9. | +| CONST-E8 | The Evaluator Is Not the Agent's to Edit | 26a527c (2026-09-01) | CONST-E7 | 2 (2 plans) | Same obligation as today's E9. | +| CONST-G1 | By Purpose, Not Quotation | 4b790f3 (2026-08-20) | CONST-G4 (judging rule) | 1 (1 plans) | Same text as today's G4. | +| CONST-G2 | Supreme | 4b790f3 (2026-08-20) | CONST-G5 (judging rule) | 1 (1 plans) | Same text as today's G5. | +| CONST-T1 | The Testing Trophy | dd5722a (2026-08-27) | CONST-T8 | 1 (1 plans) | Today's T15 obligation. | +| CONST-T2 | Properties Over Examples | dd5722a (2026-08-27) | CONST-T8 | 1 (1 plans) | Today's T14 obligation. | +| CONST-T4 | Behavior Lives Where the Mutator Sees It | 37c076f (2026-09-23) | retired: obligation removed | 18 (18 plans) | Vacated in #26; its purpose is carried by T3 and T8. | +| CONST-T5 | Pin Behavior Before You Rebuild | dd5722a (2026-08-27) | CONST-T8 | 2 (2 plans) | Today's T9 obligation. | +| CONST-T11 | Snapshots and Differentials Are Development-Time Evidence, Never Committed Artifacts | 63e9813 (2026-09-12) | CONST-T10 | 0 | Vacated in #25; its no-self-oracle rule is stated in T10. Not cited by the consumer. | + +## Appendix C - Lineage payload for the ENFORCEMENT corpus + +All 36 ids at 693a6d7 are accounted for: 17 are live laws, 13 are absorbed, 3 are judging rules, and 3 are retired (D3, W2, W3). + +| Law | Handle | Absorbs | Mechanism rungs (from the old `gate:` values) | +|---|---|---|---| +| CONST-S3 | CONTRACT-FIRST | - | review | +| CONST-D1 | CLOSED-TYPES | CONST-B5 | type; command: lint (B5 technique) | +| CONST-D2 | ERROR-VARIANTS | - | command: lint | +| CONST-D4 | STATES-AS-UNIONS | - | command: lint | +| CONST-B1 | EFFECTS-AT-EDGES | CONST-B2, CONST-B3, CONST-B6, CONST-P1, CONST-P2 | type (B6 technique, where it applies); command: lint (B2; P1 and P2 technique); review (B1, B3) | +| CONST-B4 | DEPENDENCIES-INWARD | - | command: lint | +| CONST-N1 | ORGANISED-BY-PURPOSE | CONST-N2 | command: lint (N2); review (N1) | +| CONST-N3 | FITS-IN-THE-HEAD | - | review | +| CONST-S1 | ROOT-CAUSE | - | review | +| CONST-S2 | FIRST-PRINCIPLES | - | review | +| CONST-S4 | SUBTRACT-FIRST | - | review | +| CONST-T8 | PUBLIC-SURFACE | CONST-T15, CONST-T9, CONST-T14 | review | +| CONST-T10 | INDEPENDENT-ORACLE | - | review | +| CONST-T3 | TESTS-CAN-FAIL | CONST-T13 | command: mutation | +| CONST-T12 | TEST-OBLIGATION | CONST-P3 | command: lint (T12, P3) | +| CONST-W1 | FULL-SCOPE | - | review | +| CONST-E7 | EVIDENCE-NOT-SELF-GRADING | CONST-E9 | review | +| | | | | +| CONST-G3 (judging rule) | P0-VERDICT | - | review | +| CONST-G4 (judging rule) | PURPOSE-READING | - | review | +| CONST-G5 (judging rule) | SUPREMACY | - | review | + +## Appendix D - Consumer citations outside `docs/plans` + +| Consumer file | Ids cited | Targets | +|---|---|---| +| `.omp/rules-corpus/solution-problem-type-enum.json` | CONST-B1, CONST-B3, CONST-D2, CONST-D4, CONST-E9, CONST-P1, CONST-T3 | CONST-B1, CONST-D2, CONST-D4, CONST-E7, CONST-T3 | +| `AGENTS.md` | CONST-E9 | CONST-E7 | +| `compound-packs/schema-laws/README.md` | CONST-D4 | CONST-D4 | +| `compound-packs/schema-laws/tagged-unions-over-state-by-presence.md` | CONST-D4 | CONST-D4 | +| `docs/residual-review-findings/gh-285.md` | CONST-W3 | retired | +| `docs/solutions/architecture-patterns/constructor-rule-boundary.md` | CONST-B1, CONST-B3 | CONST-B1 | +| `docs/solutions/architecture-patterns/label-routed-rules-are-unfalsifiable.md` | CONST-P3 | CONST-T12 | +| `docs/solutions/architecture-patterns/workflow-error-channel-gates.md` | CONST-D2, CONST-P1, CONST-T3 | CONST-D2, CONST-B1, CONST-T3 | +| `docs/solutions/architecture-patterns/workflow-success-channel-tagged-union.md` | CONST-D4 | CONST-D4 | +| `docs/solutions/conventions/unsanctioned-property-lane-rehomed-as-deterministic-universals.md` | CONST-E9 | CONST-E7 | +| `docs/solutions/runtime-errors/match-dispatch-buries-the-registration-call-site.md` | CONST-P2 | CONST-B1 | +| `packages/daemon/effect-daemon-cluster/AGENTS.md` | CONST-T3 | CONST-T3 | +| `packages/runner/vitest/src/internal/property/error.schema.ts` | CONST-D3 | retired | +| `packages/runner/vitest/src/internal/provided.ts` | CONST-D3 | retired | +| `packages/runner/vitest/src/replay.schema.ts` | CONST-D3 | retired | +| `packages/runner/vitest/tests/property-replay.test.ts` | CONST-T10 | CONST-T10 | + +--- + +## Appendix E - Incident evidence (gates 1-3) + +Gate 1 last ran 2026-10-09 under c09 (R21). "consumer" is the public `systemfsoftware/systemfsoftware`; "this repo" is `systemfsoftware/constitution`. Each ref is `sha:path:line`, and `git show :` printed the quoted line. A fixed incident is anchored at the fix's parent and carries the fix hunk (`git show -U0 -- `); where the fix only adds lines, the hunk shown is the addition. A ref with no fix is a review that rejected the violation, or a violation that still stands. The first incident of each law is its example's source. + +Result: 17 of 17 laws have two failure incidents from different PRs or commits; every cited line printed and every fix commit exists. No PR, fix commit or document backs more than two laws. Shared between two laws: #375 and `f08fddc94` (S3; P1 before its cut), #166 (D1; P1 before its cut), #342 and `3838c7309` (B4, S2), `7b4e08e24` (S1, T12), `166e6bb65` (S4, T12), #229 (S4, T10), #21 (W1, E7). A replay evaluator ablating one law should know those laws share evidence. + +#### CONST-S3 + +- consumer violating-code: `41c844fdb:packages/testing/mutation/stryker-js/cli/src/cli-request.schema.ts:26` (2026-08-26, #254, fix `7bd4fa7ec`). A CliRequest schema was exported with no consumer decoding it; every use was a type position, and its obligation scan drove the CLI suite to a 15-second timeout. + - printed: `export const CliRequest = S.Union([RunRequestSchema, LlmsRequestSchema])` + - fix hunk: + ```diff + @@ -1,33 +0,0 @@ + (…) + -const RunRequestSchema = S.TaggedStruct('run', { options: S.Any, survivors: S.Boolean }) + -const LlmsRequestSchema = S.TaggedStruct('llms', { document: S.Any }) + - + -export const CliRequest = S.Union([RunRequestSchema, LlmsRequestSchema]) + -export type RunRequest = Omit & { + - readonly options: PartialStrykerOptions + -} + (…) + ``` +- consumer violating-code: `7f11497e8:packages/stryker-js/stryker-js-cli/src/Cli.ts:1000` (2026-09-10, #375, fix `f08fddc94`). The root command kept declaring FileSystem|Path after the manifest emitter that needed them was deleted, so the import survived only to appear in one type parameter. + - printed: `FileSystem.FileSystem | Path.Path` + - fix hunk: + ```diff + @@ -1000 +566 @@ function makeStrykerCommand(requestRef: Ref.Ref>) { + - FileSystem.FileSystem | Path.Path + + never + ``` + +#### CONST-D1 + +- consumer violating-code: `151b9f4de:packages/effect-daemon-spec/src/internal/with-lock-by-mode.executor.ts:24` (2026-08-15, #166, fix `2d367db70`). withLockByMode took a spec and a nullable adapter, so a spec that required the lock, paired with no adapter, ran its body unlocked. + - printed: `if (lock === null || isModeNone(lockSpec)) {` + - fix hunk: + ```diff + @@ -24 +43 @@ export const withLockByMode = ( + - if (lock === null || isModeNone(lockSpec)) { + + if (binding.kind === 'unlocked') { + ``` +- consumer violating-code: `de5414e3a:packages/discern/src/decision.blueprint.ts:461` (2026-09-24, #519, fix `2d4c724ff`). classify accepted any `Label extends string` options, so once a string-typed criteria got through, every downstream label check accepted any string. + - printed: `options: ClassifyOptions