From 7412333b030b5cfe867644afca7ade3c9251e277 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot Date: Sun, 22 Nov 2026 17:54:26 -0500 Subject: [PATCH 1/5] feat!: replace the constitution with org-wide CODING_STANDARDS.md and REVIEW.md CONSTITUTION.md, ENFORCEMENT.md, the YAML corpus validator and CONCEPTS.md are removed. CODING_STANDARDS.md leads with 'Impossible states first' and carries every law that still earns its place under SF-* IDs, with a former-ID table. REVIEW.md holds the shared finding bar, severities and evidence rules. --- .github/workflows/ci.yml | 8 +- .husky/pre-commit | 2 +- AGENTS.md | 133 +-- CODING_STANDARDS.md | 199 ++++ CONCEPTS.md | 21 - CONSTITUTION.md | 119 --- CONTRIBUTING.md | 56 +- ENFORCEMENT.md | 296 ------ README.md | 38 +- REVIEW.md | 77 ++ deno.json | 14 +- deno.lock | 515 +-------- ...expected-value-from-the-code-under-test.md | 32 +- .../the-vacuous-pass-gate-input-sets.md | 249 ++--- ...freeze-observations-about-a-moving-base.md | 48 +- scripts/validate-constitution.test.ts | 956 ----------------- scripts/validate-constitution.ts | 987 ------------------ 17 files changed, 546 insertions(+), 3204 deletions(-) create mode 100644 CODING_STANDARDS.md delete mode 100644 CONCEPTS.md delete mode 100644 CONSTITUTION.md delete mode 100644 ENFORCEMENT.md create mode 100644 REVIEW.md delete mode 100755 scripts/validate-constitution.test.ts delete mode 100755 scripts/validate-constitution.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bc8590f..648c62d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,7 @@ name: CI # One job on every pull request, with no path filter, so the required `check` is emitted for every change, docs-only -# ones included. It runs the same two validators as the pre-commit hook. +# ones included. It runs the same check as the pre-commit hook. on: push: branches: [main] @@ -27,7 +27,5 @@ jobs: - uses: denoland/setup-deno@22d081ff2d3a40755e97629de92e3bcbfa7cf2ed # v2 with: deno-version: v2.x - - name: Validate the constitution - run: deno task test - - name: Validator tests - run: deno task test:validator + - name: Check markdown formatting + run: deno task check diff --git a/.husky/pre-commit b/.husky/pre-commit index fdf054a..d17d95a 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1 +1 @@ -deno task test && deno task test:validator +deno task check diff --git a/AGENTS.md b/AGENTS.md index c0de45c..2c69177 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,126 +1,11 @@ -# AGENTS.md — Constitution Repository +# constitution -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. +The organization's shared `CODING_STANDARDS.md` and `REVIEW.md`. Consumer +repositories vendor this repository at `repos/constitution/`. There is no code +here. -@CONSTITUTION.md - -## Startup Workflow - -Before making changes: - -1. **Read this file** completely. -2. **Confirm the active task** with the user or the agent's task list. -3. **Review recent commits** with `git log --oneline -5`. -4. **Ensure current branch is not `main`** — feature branches only. If on main, create one. - -## Working Rules - -- **One task at a time.** Finish before starting the next. -- **Conventional commits required.** The commit-msg hook enforces `type(scope): description`. Run `git commit` through the hook — do not bypass with `--no-verify`. -- **Verification required.** Run the verification commands before claiming done. -- **Stay in scope.** Don't modify files unrelated to the task. Scope reduction requires explicit user approval. -- **Leave clean state.** The next session must run verification immediately. - -## Amending the Constitution - -### Corpus - -- **`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 - -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 - -ID format: `CONST-`. Pick the next free number in the family (never renumber to close gaps). - -| Letter | Family | Purpose | -|---|---|---| -| `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 | -| `B` | Boundary | Core/shell boundaries, effects, adapters | -| `T` | Testing | Testing strategy, mutation, properties | -| `N` | Naming & structure | Module organization and naming | -| `W` | Work discipline | Task scope, bypass declarations, reviews | -| `S` | Subtraction | Code deletion and structural simplification | - -### Changing a Rule - -- 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 | -|---|---|---| -| **Locked** | `AGENTS.md`, `.husky/_/`, verification scripts | Read and propose changes; do not edit to make verification pass. | -| **Editable** | `deno.json`, `deno.lock`, `commitlint.config.cjs`, `.gitignore`, `.husky/` (hooks only, not `_/`) | Edit freely within the active task. | -| **Human-controlled** | `CONSTITUTION.md`, `README.md`, merging to `main`, pushing, destructive ops | Propose changes; ask the user before acting. | - -## Definition of Done - -A task is done only when ALL of the following are true: - -- [ ] Target changes are applied. -- [ ] Verification commands ran and passed. -- [ ] Commit uses conventional format (`type(scope): description`). -- [ ] Evidence recorded via the runtime memory system and task list. -- [ ] No dirty files left in the working tree. - -## Verification Commands - -```bash -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 lineage check against the revision before it: - -```bash -deno task test --against -``` - -### Anti-Bypass Rules - -- Run the **full command**, not parts in isolation. -- Evidence must be from the **current run**, not a prior session. -- **Any failure blocks done.** Do not bypass with `--no-verify`. -- Do not suppress, skip, or disable checks to make verification pass. - -### Hallucination Prevention - -- **Read before edit:** before editing a file, read it in the current session. Do not edit from memory. -- **Verify before claim:** before saying "done," the verification command must have run and its output recorded. -- **Search before write:** before writing code that calls a library API, read the actual API surface. Do not generate from training memory. - -## Multi-Agent Ownership - -When multiple agents work in the same repo: - -- Each agent owns a disjoint file/module set. -- An agent must claim a file before editing it. -- Agents may not recursively delegate to each other. -- The one-shot verification must pass before any agent claims done. - -## End of Session - -Before ending a session: - -1. Record current state, blockers, and next steps via the runtime memory system and task list. -2. Commit with a conventional-format message once work is in a safe state. -3. Leave the repo clean — `git status` should show nothing unexpected. - -## Escalation - -- **Constitution conflict**: `CONSTITUTION.md` is already in context — reread it there, not from disk. -- **Unclear requirements**: Ask the user. -- **Verification failure**: Record via memory, flag for review, do not bypass. -- **Scope ambiguity**: Re-read this file and the Definition of Done. +- Read `CODING_STANDARDS.md`, `REVIEW.md` and `CONTRIBUTING.md` before you + change a rule. +- This repository is public. Nothing private goes in it (`SF-SEC-1`). +- Verify with `deno task check` before you push. Never pass `--no-verify`. +- Work on a branch; `main` changes only through a pull request. diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md new file mode 100644 index 0000000..878b107 --- /dev/null +++ b/CODING_STANDARDS.md @@ -0,0 +1,199 @@ +# Coding Standards + +Review criteria for every repository in the systemfsoftware organization. A +repository vendors this repository with `git subtree` at `repos/constitution/`, +and its own `CODING_STANDARDS.md` files add the rules only that repository +needs. A local rule may narrow a rule here, never loosen it. Cite a rule by its +ID, as `(SF-IMP-1)`. + +Read every rule by its purpose: where its words and its harm part ways, the harm +decides. + +## Impossible states first + +Before you write or propose any test, make the wrong state impossible to build. +A state the compiler refuses needs no test, and no later change can bring it +back unnoticed. + +- **SF-IMP-1** Close your types so an illegal value cannot be constructed: a + union of the valid combinations, a branded type for each role, a separate + service tag for each resource that must not be shared. Outside data becomes a + domain type only through a decode that returns a typed result, never through a + cast or a suppression comment. + - Why: a value the type could have refused reaches runtime, and every check + downstream trusts it. + - 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. +- **SF-IMP-2** Model mutually exclusive states as a tagged union, one variant + per state carrying only its own fields. Keep a plain nullable only for a value + that is 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. +- **SF-IMP-3** Give every distinct failure its own tagged variant. + - Why: callers cannot branch on the real failure, and distinct errors collapse + into one case. +- **SF-IMP-4** The compiler is the evidence for such a fix. Wire the wrong state + once on purpose, paste the compiler error into the PR body, and revert the + wiring. Never commit that wiring as a test. + - Why: the type error holds on every future build; a test proves one case once + and costs a run every time. +- **SF-IMP-5** Never write or propose an integration, end-to-end or microVM test + for an invariant a type can hold: make the type hold it (`SF-IMP-1`). Runtime + tests are for what the compiler cannot prove (a decode of outside data, a + peer's answer, timing, what a real database or runtime does), at the lightest + tier that reaches that boundary, and a proposal for one names the behaviour it + covers. + - Why: those tests run for minutes on hosts every session shares, and they + prove less than a compile error. + +## Tests + +- **SF-TST-1** Test the published surface with real inputs and outputs: what a + consumer imports or calls, never the package's internals. + - Why: a test that stops short of what ships stays green while the shipped + artifact is broken. +- **SF-TST-2** Take every expected value from an oracle the code under test did + not produce: a literal from the requirement, 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. +- **SF-TST-3** Make every test able to fail when the behaviour it names breaks, + and see it fail once. + - Why: a suite that notices nothing certifies nothing, and a toothless test + hides among the ones that work. +- **SF-TST-4** Judge outcomes, not steps. Assert what the system produced, never + which functions ran, which lines a file holds, or which keys, entries or + values the repository's own configuration lists. + - Why: a test of steps or configuration breaks on every refactor and passes + while the outcome is wrong. +- **SF-TST-5** A test whose assertion breaks these rules (it checks steps, + configuration or file layout, copies its expected value from the code, cannot + fail, or covers removed behaviour) is deleted, never rewritten, retitled or + replaced. Deleting a worthless test is welcome and is not lost coverage. A + test that keeps these rules and goes red found a defect: fix the code under + test, never the test. + - Why: a reshaped bad test keeps its cost and its false confidence; a weakened + good test hides the defect it found. +- **SF-TST-6** A unit test is deterministic and isolated: no child process, real + clock, network, host port, host file system or state shared with another test. + I/O belongs to an adapter's tests, run where the repository's testing rules + say. + - Why: a test that spawns processes or sleeps stalls the machine it runs on + and fails by timing, not by defect. +- **SF-TST-7** A property test that times out is a design failure. Fix the + schema it draws from, or delete the test if it is a scenario dressed as a + property. Never raise its timeout, cut its runs or narrow its generator. + - Why: a tuned budget hides a schema that admits values the domain does not. + +## Shape the code + +- **SF-SHP-1** Keep effects at the edges, as values: a pure step returns the + next read or write as data, and a thin shell performs it. + - Why: an effect inside a decision cannot be tested without the world it + touches. +- **SF-SHP-2** The shell imports the core, and every implementation is wired 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. +- **SF-SHP-3** Name every file and folder for its job; a name answers "of + what?". + - Why: a bucket named for a layer says nothing a reader can check, and one + change scatters across the tree. +- **SF-SHP-4** 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. +- **SF-SHP-5** Fix the root cause; when the design is wrong, restructure it. Add + no alias, fallback or compatibility shim nobody asked for. + - Why: a patched symptom comes back, and every shim is a second path to keep + correct. +- **SF-SHP-6** Justify every choice by these rules and the repository's own, + never by the file next to it or an earlier plan's wording. + - Why: an unexamined default hardens into a rule, and each copy seeds the + next. +- **SF-SHP-7** Treat every line as a liability: delete, unify or make the bad + state unconstructable before you add. A removal reaches every definition, call + site and export in the same change. + - Why: the codebase only grows, and two conventions standing is the next + change imitating the wrong one. +- **SF-SHP-8** Prefer what the runtime, the lockfile and the organization's own + packages already provide. Add no patch, fork or override of a dependency; + change the design that needed it or fix it upstream. A PR that adds a + third-party dependency states its registry maintainers, publish provenance, + weekly downloads and three real dependents, each read from the primary source. + - Why: a patched dependency silently diverges on every upgrade, and an + unvetted one is a supply-chain hole. + +## Secrets and public repositories + +- **SF-SEC-1** Commit no secret, token or credential. A public repository + receives nothing from a private one: no private repository, package or product + name, local path, host, person, email, private run ID or link, issue-tracker + ID, or internal agent or process name, in files, fixtures, commit messages, PR + text or comments. + - Why: a leaked secret must be rotated everywhere it reached, and a private + name in public history cannot be taken back. + +## Checks and gates + +These apply to anything that grades work: lint rules, CI jobs, hooks, +thresholds, rubrics. + +- **SF-GATE-1** Bind each obligation through the strongest mechanism that can + carry it: the type system first, then a command that fails, then a refusal + before the call runs, and prose last. + - Why: prose orients and enforces nothing; a type error cannot be argued with. +- **SF-GATE-2** Add a check only for a mistake it names, and key it on the + failure itself (recomputed source, the compiler's verdict, the real outcome), + never on names, line positions, formatting or a field the author supplied. + When something fails, fix the failure; do not add a check beside it. + - Why: brittle checks pile up, block correct work and still miss the mistake. +- **SF-GATE-3** A check asserts its input set: an empty corpus, an empty file + list or a missing input is a failure. + - Why: a check that cannot fail is a certificate, not enforcement. +- **SF-GATE-4** Decide which checks, tests and requirements apply to code 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. +- **SF-GATE-5** A grader changes only in a change whose task is that grader, + observed failing before and passing after. Never edit, loosen or add to a + grader (a threshold, budget, glob, baseline, timeout, lint config, workflow or + rubric) so that in-flight work passes. + - Why: whoever edits the grader reports the score they chose. +- **SF-GATE-6** Enroll a rule over a clean tree, at error: fix every live + violation first. No baseline, allowlist or warn level. + - Why: a baseline is suppression with a date on it, and a warning is noise + nobody reads. + +## Finish + +- **SF-FIN-1** Show evidence before you call work done: a command that passed, + the compiler error, or the state of the real system. + - Why: work called done on no evidence ships broken. + +## Former IDs + +The laws in the retired `CONSTITUTION.md` map here. Dated plans keep the old +IDs; read them through this table. + +| Former | Now | +| :--------------------------------------------------------- | :------------------------------------- | +| CONST-D1, CONST-B5 | SF-IMP-1 | +| CONST-D4 | SF-IMP-2 | +| CONST-D2 | SF-IMP-3 | +| CONST-B1, CONST-B2, CONST-B3, CONST-B6, CONST-P1, CONST-P2 | SF-SHP-1 | +| CONST-B4 | SF-SHP-2 | +| CONST-N1, CONST-N2 | SF-SHP-3 | +| CONST-N3 | SF-SHP-4 | +| CONST-S1 | SF-SHP-5 | +| CONST-S2 | SF-SHP-6 | +| CONST-S4, CONST-S3 | SF-SHP-7 | +| CONST-T8, CONST-T9, CONST-T14, CONST-T15 | SF-TST-1 | +| CONST-T10 | SF-TST-2 | +| CONST-T3, CONST-T13 | SF-TST-3 | +| CONST-T12, CONST-P3 | SF-GATE-4 | +| CONST-E7, CONST-E9 | SF-FIN-1, SF-GATE-5 | +| CONST-W1 | moved to each agent's own instructions | +| CONST-G3, CONST-G4, CONST-G5 | `REVIEW.md` | +| CONST-D3, CONST-W2, CONST-W3, and any other | retired | diff --git a/CONCEPTS.md b/CONCEPTS.md deleted file mode 100644 index a8e3a96..0000000 --- a/CONCEPTS.md +++ /dev/null @@ -1,21 +0,0 @@ -# Concepts - -Shared domain vocabulary for this project — entities, named processes, and status concepts with project-specific meaning. Seeded with core domain vocabulary, then accretes as ce-compound and ce-compound-refresh process learnings; direct edits are fine. Glossary only, not a spec or catch-all. - -## Constitution corpus - -### Constitution corpus -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 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. 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 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 deleted file mode 100644 index 265f9a1..0000000 --- a/CONSTITUTION.md +++ /dev/null @@ -1,119 +0,0 @@ -# Constitution - -Read every law by its purpose: where its words and its harm part ways, the harm decides. - -## Model the domain - -```yaml -- 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 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. -``` - -## 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. -``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a1757c2..9f33b20 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,47 +1,29 @@ # 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 -``` +Install [Deno](https://deno.land) 2, then run `deno task prepare` once to enable +the commit 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 +deno task check ``` -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. +It checks the formatting of every markdown file. CI runs the same task as the +required `check`. + +## Changing a rule + +- A rule is one bullet: a bold ID, one or two sentences addressed to the reader, + and a `Why:` line naming the harm it prevents. Add a wrong and a right example + only where the law is hard to apply without one. +- An ID is `SF--`. Take the next free number in the family. Never + renumber a rule or reuse a removed ID; add a removed ID to the former-ID table + with where its obligation went. +- A rule belongs here only if it holds for every repository in the organization. + A rule for one repository goes in that repository's `CODING_STANDARDS.md`; a + rule about how an agent works goes in that agent's own instructions. +- Delete or merge before you add. A new rule names the failure it prevents. +- Commits follow Conventional Commits; the commit hook runs commitlint. diff --git a/ENFORCEMENT.md b/ENFORCEMENT.md deleted file mode 100644 index 6a06a32..0000000 --- a/ENFORCEMENT.md +++ /dev/null @@ -1,296 +0,0 @@ -# Enforcement - -Rules for whoever builds or changes an instrument that grades the maker — lint gates, stream rules, CI checks, thresholds, rubrics, advisors. Never `@`-import this file into a maker's context. - -## Mechanism - -- Bind each obligation through the strongest mechanism that can carry it, strongest first: - 1. the type system — the illegal state does not construct; - 2. a command that fails — lint, threshold, boundary audit; - 3. a pre-execution refusal — the write or tool call does not happen; - 4. resident prose — the floor; it orients, it does not enforce. -- A post-hoc reminder is prose, not a refusal. If the violating call already executed, the mechanism is rung 4. - -## Gate design - -- Forbid an outcome; never command a ritual. *Do not ship an export whose dist file is missing*, not *declare a category and write a reason*. -- Key every verdict on a recomputation — source bytes, compiler verdict, rehash — never on a field the graded work's author supplied. When a gate reads a field, recompute that field in the same run. -- Resolve every uncertainty against the permissive outcome: unparseable output degrades to revise, never to pass; an absent grant means required; an unreadable input is surfaced, never skipped; a dead run never reports itself running. -- Assert the input set, not only its contents: an empty corpus, an empty mutated set, or a missing input goes red. A gate that cannot fail is a certificate, not enforcement. - -## Changing an instrument - -- 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-E7), you build the instrument and land it through your own channel; only then does the maker's work proceed. - -## Enrollment - -- Enroll over a clean tree only: migrate every live violation first, then enroll at error. A baseline or allowlist of existing violations is suppression with a date on it. -- A rule registered only in its own test harness is not enrolled. Prove carriage by driving the published artifact the way a consumer resolves it. -- `warn` is forbidden: error with a clean tree, or off with the reason named. -- Delete the retired shape from every owner at enrollment. Two conventions standing is the next agent imitating the wrong one. - -## Gate economy - -- 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 434167a..acc5d5d 100644 --- a/README.md +++ b/README.md @@ -2,27 +2,45 @@ [![License: Apache 2.0](https://img.shields.io/badge/license-Apache_2.0-blue?style=flat-square)](LICENSE) -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. +The shared coding standards and review policy for System F Software. Every +repository in the organization vendors this one and is reviewed against the same +rules. ## What is here -| 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`). | +| File | Read it when | +| :----------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- | +| [CODING_STANDARDS.md](CODING_STANDARDS.md) | You plan, write, review or propose a test for code in any organization repository. It leads with "Impossible states first". | +| [REVIEW.md](REVIEW.md) | You review a change or answer review findings: the finding bar, severities and evidence. | +| [`docs/solutions/`](docs/solutions) | You want the past problem behind a rule. | -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. +The files follow the `CODING_STANDARDS.md` and `REVIEW.md` model of the +[Compound Engineering plugin](https://github.com/EveryInc/compound-engineering-plugin): +`ce-code-review` and Claude Code Review read them as criteria and review policy. ## Use it in a repository -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. +1. Vendor this repository with `git subtree` at `repos/constitution/`. +2. In the repository's root `REVIEW.md`, include both files, each on its own + line: -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. + ```markdown + @repos/constitution/CODING_STANDARDS.md @repos/constitution/REVIEW.md + ``` + +3. Keep the repository's own rules in its own `CODING_STANDARDS.md` and + `REVIEW.md`. A repository with no rules of its own may symlink its root + `CODING_STANDARDS.md` to `repos/constitution/CODING_STANDARDS.md`. +4. Route agents to the files from the repository's `AGENTS.md` under the trigger + "you plan, write, review or propose a test". Do not `@`-import them into an + always-loaded file. + +Update the vendored copy with +`git subtree pull --prefix repos/constitution https://github.com/systemfsoftware/constitution main --squash`. ## Contributing -Setup, the validation task and the amendment rules are in [CONTRIBUTING.md](CONTRIBUTING.md). +See [CONTRIBUTING.md](CONTRIBUTING.md). ## License diff --git a/REVIEW.md b/REVIEW.md new file mode 100644 index 0000000..b2b83ed --- /dev/null +++ b/REVIEW.md @@ -0,0 +1,77 @@ +# Review instructions + +How review behaves in every repository of the systemfsoftware organization. A +repository's root `REVIEW.md` includes this file and `CODING_STANDARDS.md` from +its vendored copy (`@repos/constitution/REVIEW.md`, +`@repos/constitution/CODING_STANDARDS.md`), and adds its own severities, checks +and exclusions below them. Where the two disagree, the repository's file wins +for that repository, except that it cannot lower a P0 defined here. + +## What counts as a finding + +File a finding only when all of these hold: + +- It reproduces on the PR's current head, on a line the diff adds, edits, moves + or copies. That the violation existed before the change, or came over with + moved code, never lowers it. An issue only on untouched lines goes in + Coverage, not in the findings. +- It cites a rule from `CODING_STANDARDS.md` here, a repository + `CODING_STANDARDS.md`, or a compound pack the repository enrolls, and that + rule's stated scope covers the file. An author's personal or global + instruction file is never criteria. A runtime defect needs no rule. +- It shows the rule's harm is present here, not only that its words match. Where + a rule's letter and its purpose disagree, the purpose decides. +- The PR body does not record it as a deliberate tradeoff that names the rule. + If it does, contest the tradeoff instead of the line. +- It asks for a change to the lines the diff touches. A finding that only asks + for more coverage is not a finding. +- A finding that asks for a test names the behaviour no type can hold + (`SF-IMP-5`). A finding that asks for an integration, end-to-end or microVM + test of an invariant a type could hold is not a finding; ask for the type + instead. + +**Accretion.** On the second finding against the same block (a parser, a +classifier, an allowlist, a guard, a prose rule), file one finding against how +the block is represented instead: the condition restated, the boundary changed, +or a decision for the owner. Each case patched into such a block buys one more +round. + +## Severity + +- **P0**: an illegal state a type could have refused (`SF-IMP-1` to `SF-IMP-3`) + in new or changed code; a grader edited or loosened so the change passes + (`SF-GATE-5`); a secret, or anything private in a public repository + (`SF-SEC-1`); data loss. While one stands, the change is not ready, whatever + else it fixes. +- **P1**: a runtime defect in behaviour a person or a deploy reaches; a + violation of any other rule in `CODING_STANDARDS.md` here or in the + repository; a test that breaks a test rule. A test that cannot fail is a + broken grader, so it blocks the merge, and its only remedy is deletion + (`SF-TST-5`). +- **P2 at most**: plans, `docs/solutions/`, PR bodies and other docs; test + structure no rule covers. These never block a merge. +- **P3**: style and naming. + +A breach is legal only when the change itself declares it, naming the rule and +the case. A promise of a follow-up is not a declaration. + +## Limits + +- Report at most five P3 findings per review. +- On a re-review, report P0 and P1 findings, plus any finding on lines changed + since the last reviewed head. Don't re-raise findings already recorded as + follow-ups. + +## Do not report + +- Anything CI already enforces: type errors, lint, formatting, commit messages. +- Anything under `repos/**`: vendored, updated only by `git subtree pull`. +- Generated output and lockfiles, except to check a dependency change the PR + states. + +## Evidence + +- A claim about behaviour cites `file:line` in the source. An inference from a + name is not evidence. +- A claim about a CLI flag, a library or a vendor's behaviour cites live output, + the installed source or a reproduction, not documentation alone. diff --git a/deno.json b/deno.json index 45337a0..45b1a09 100644 --- a/deno.json +++ b/deno.json @@ -1,13 +1,19 @@ { - "version": "0.1.0", + "version": "1.0.0", "nodeModulesDir": "auto", "tasks": { - "test": "deno run --allow-read=CONSTITUTION.md,ENFORCEMENT.md --allow-run=git scripts/validate-constitution.ts", - "test:validator": "./scripts/validate-constitution.test.ts", + "check": "deno fmt --check", "prepare": "git config core.hooksPath .husky" }, "imports": { - "@std/yaml": "jsr:@std/yaml@^1.2.0", "@commitlint/config-conventional": "npm:@commitlint/config-conventional@^21.2.0" + }, + "fmt": { + "include": [ + "**/*.md" + ], + "exclude": [ + "docs/plans/" + ] } } diff --git a/deno.lock b/deno.lock index bad6466..73d7e5e 100644 --- a/deno.lock +++ b/deno.lock @@ -1,545 +1,52 @@ { "version": "5", "specifiers": { - "jsr:@std/yaml@^1.2.0": "1.2.0", - "npm:@commitlint/cli@21": "21.2.2_@types+node@26.4.0_typescript@7.0.2", - "npm:@commitlint/config-conventional@^21.2.0": "21.2.2" - }, - "jsr": { - "@std/yaml@1.2.0": { - "integrity": "20beb41e4983ba3437dbefac62b14061ab058e8a187596f19d28ff9035f6e6cf" - } + "npm:@commitlint/config-conventional@^21.2.0": "21.2.3" }, "npm": { - "@babel/code-frame@7.29.7": { - "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", - "dependencies": [ - "@babel/helper-validator-identifier", - "js-tokens", - "picocolors" - ] - }, - "@babel/helper-validator-identifier@7.29.7": { - "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==" - }, - "@commitlint/cli@21.2.2_@types+node@26.4.0_typescript@7.0.2": { - "integrity": "sha512-a+6hQxIxnpdvSvS2apvttPNbEliYsVC3PqFYDiiB2kjbwIsQsj1urvQ4Tkf70pKYozPalKAuRQmm/GHwndduqA==", - "dependencies": [ - "@commitlint/config-conventional", - "@commitlint/format", - "@commitlint/lint", - "@commitlint/load", - "@commitlint/read", - "@commitlint/types", - "tinyexec", - "yargs" - ], - "bin": true - }, - "@commitlint/config-conventional@21.2.2": { - "integrity": "sha512-NxA37SZviusFUEYOQZ5hNnZ1h7O/KiemPkxjOlpzKJNnWxThiwc6/SaZhaPa8fyLvfRBAywhQhJJk8XESHWlpQ==", + "@commitlint/config-conventional@21.2.3": { + "integrity": "sha512-EP2n5DN2GwRWNVrLX0Jx3mpQlW5PfFi9HnD9OJ8hN/H0xFqpCFyHeGDhg+0P8/21iMMcdkcQgbNqmVklebqYsQ==", "dependencies": [ "@commitlint/types", "conventional-changelog-conventionalcommits" ] }, - "@commitlint/config-validator@21.2.0": { - "integrity": "sha512-t7AzNHAKeIdo/3NRGwzpufKHsKkPHmFs/56N2Fnsh0/r0rGtnQzTxk6vnFgjaGr4hdSQKNB50/KAhR9Yk4LJKA==", - "dependencies": [ - "@commitlint/types", - "ajv" - ] - }, - "@commitlint/ensure@21.2.0": { - "integrity": "sha512-76IF9vDNS13lAzEEik9eKwzt8f9hYhWiwVXZ2AnyLCz5/f511FsEQ3pw1X3/zSQpdRLQU7i5qDMVKyXi1GWjSg==", - "dependencies": [ - "@commitlint/types", - "es-toolkit" - ] - }, - "@commitlint/execute-rule@21.0.1": { - "integrity": "sha512-RifH+FmImozKBE6mozhF4K3r2RRKP7SMi/Q/zLCmExtp5e05lhHOUYqGBlFBAGNHaZxU/WYw1XuugYK9jQzqnA==" - }, - "@commitlint/format@21.2.2": { - "integrity": "sha512-v6fvxZSc/AvVMROlr3H34+1766bZSYApRUSCAMjWamStPjKMvZ8GdvVA5YW/VQNgbFTmcMz6OYmSTJEvIjPrfA==", - "dependencies": [ - "@commitlint/types", - "picocolors" - ] - }, - "@commitlint/is-ignored@21.2.2": { - "integrity": "sha512-9UoKNgfFE3LU7FrzierCvk3CdDfMDeVGC86qZiT/n0TIjfq/dmZ9MHuXd45OTNRa26ZanmJRxEtmiXk/lEJihg==", - "dependencies": [ - "@commitlint/types", - "semver" - ] - }, - "@commitlint/lint@21.2.2": { - "integrity": "sha512-Fy8JxEBzdmsYWFude/61GxXu5O+wEymwiRK2z9GL9R8mCsXphCoGxAFc5iHn5mjlfcSrhiiONE+ksf4KOjnaPg==", - "dependencies": [ - "@commitlint/is-ignored", - "@commitlint/parse", - "@commitlint/rules", - "@commitlint/types" - ] - }, - "@commitlint/load@21.2.2_@types+node@26.4.0_typescript@7.0.2": { - "integrity": "sha512-0Tt6wDPX167cjKC5D4zhm0+20wJJG+TN/TKovMOspfSe78rOnKX+MNzlVNiu6HyQPZChPJ8QBH31MVt6Bb8fCg==", - "dependencies": [ - "@commitlint/config-validator", - "@commitlint/execute-rule", - "@commitlint/resolve-extends", - "@commitlint/types", - "cosmiconfig", - "cosmiconfig-typescript-loader", - "es-toolkit", - "is-plain-obj", - "picocolors" - ] - }, - "@commitlint/message@21.2.0": { - "integrity": "sha512-YxGoiXD/HXNXLJPrQwE5poXa+XH0CBEm+mdvbHQP0g6MV/dmJyUFCzPNzZbxL93GvZ70TmtTK0Z0/IBpAqHv8g==" - }, - "@commitlint/parse@21.2.2": { - "integrity": "sha512-MEkobPfvRp+z06Wro8HMG1BDGHzZmj82A1LH1nWeG3ipHpg/x4m6v3wEDvMBIKjRFUnfR3nBeFs3MVCr7UdAmg==", - "dependencies": [ - "@commitlint/types", - "conventional-changelog-angular", - "conventional-commits-parser" - ] - }, - "@commitlint/read@21.2.1": { - "integrity": "sha512-hUW7EJQnNTL0vPOmVMNK4CrnrNBN0nN+JJHReFkdHO5y4iyHeEmTBwuC15OCqUTjxWo7idnH1LftfpWVIaPWIA==", - "dependencies": [ - "@commitlint/top-level", - "@commitlint/types", - "@conventional-changelog/git-client", - "tinyexec" - ] - }, - "@commitlint/resolve-extends@21.2.2": { - "integrity": "sha512-RPkJ/IFi7sMUUVbZLqwWFtWw/zRDcfFsmrPSiTMrt5wb7AdxOr86EGQFvmGzef5QKV5IPBWWCujqVTw1RWX44A==", - "dependencies": [ - "@commitlint/config-validator", - "@commitlint/types", - "es-toolkit", - "global-directory", - "resolve-from@5.0.0" - ] - }, - "@commitlint/rules@21.2.2": { - "integrity": "sha512-eplQzyYkBjYB1HyyRj8hkcK11Y9DU9nuBz7uOKEd6NpE9NGDytLFCAnlRE+OoiK/5sHEJsaz2RGhuWBvYzIbNA==", - "dependencies": [ - "@commitlint/ensure", - "@commitlint/message", - "@commitlint/to-lines", - "@commitlint/types" - ] - }, - "@commitlint/to-lines@21.0.1": { - "integrity": "sha512-bd1BFII7p1EQZre9Kaj+kKaMFP3cFCdt21K7DItVux9XP5WjLgJ0/Uy1pJJh9aPwVJ6SKg62PxqlZaHI8hQAXw==" - }, - "@commitlint/top-level@21.2.0": { - "integrity": "sha512-Y5gmQ+KxzqCrBFJfLvFEPvvwD3LDiNZoTT2yeFBm96M8qhmqSzQc5DvX3rheAaAMjyIvMXOCLS/mWfdpONsjyQ==", - "dependencies": [ - "escalade" - ] - }, - "@commitlint/types@21.2.0": { - "integrity": "sha512-7zVFCDB2reMvJH5dmbKnOQPjZEvjdJTH8jc0U/PIPU1r3/+vf5pD1HlfitV2MWsWXrvu7u39iY1lyLUPOaN0Gw==", + "@commitlint/types@21.2.3": { + "integrity": "sha512-sGEA473TlCvhCGNoTBY9OXZVWdscIXdGt0dm8EpB+2MRfmt8LNh/X56P/T3nCtEB+eH5qGEa3odphSAoUxSfSQ==", "dependencies": [ "conventional-commits-parser", "picocolors" ] }, - "@conventional-changelog/git-client@3.1.2": { - "integrity": "sha512-jZqwnJwf7nboIlAcw/mkOjVa6DexCcUOgT2oOQgkoi3z9vR8tGFkcMy2BFcYwjhL9sYcDDXkRQDayiDieCoW7A==", - "dependencies": [ - "@simple-libs/child-process-utils", - "@simple-libs/stream-utils", - "semver" - ] - }, "@conventional-changelog/template@1.4.0": { "integrity": "sha512-aalGyl7dbB5PArRebDIX43ZvBlXrYm9uWzGJ26t+4SzJVPsOuvfILGGbw5X4yX7i50YEmJ8zvbiWnqH/AAnZqg==" }, - "@simple-libs/child-process-utils@2.0.0": { - "integrity": "sha512-dvNoRKLijXnD0XoJAz94pbNuB5GQgDr55UhpSPhffDkTT0Cmcqh9jSCOtwfT2d4H6MI9E7c4SgtMuJXZ6F3c6A==", - "dependencies": [ - "@simple-libs/stream-utils" - ] - }, "@simple-libs/stream-utils@2.0.0": { "integrity": "sha512-fCTuZK4QBa+39Oz9l4OGfJfz+GpwCp3AqO7Zch3to99xHPgstVsRFpeQ8LNd2o1Gv8raL2mCFwiaHh7bFSp5DQ==" }, - "@types/node@26.4.0": { - "integrity": "sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==", - "dependencies": [ - "undici-types" - ] - }, - "@typescript/typescript-aix-ppc64@7.0.2": { - "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", - "os": ["aix"], - "cpu": ["ppc64"] - }, - "@typescript/typescript-darwin-arm64@7.0.2": { - "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", - "os": ["darwin"], - "cpu": ["arm64"] - }, - "@typescript/typescript-darwin-x64@7.0.2": { - "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", - "os": ["darwin"], - "cpu": ["x64"] - }, - "@typescript/typescript-freebsd-arm64@7.0.2": { - "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", - "os": ["freebsd"], - "cpu": ["arm64"] - }, - "@typescript/typescript-freebsd-x64@7.0.2": { - "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", - "os": ["freebsd"], - "cpu": ["x64"] - }, - "@typescript/typescript-linux-arm64@7.0.2": { - "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", - "os": ["linux"], - "cpu": ["arm64"] - }, - "@typescript/typescript-linux-arm@7.0.2": { - "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", - "os": ["linux"], - "cpu": ["arm"] - }, - "@typescript/typescript-linux-loong64@7.0.2": { - "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", - "os": ["linux"], - "cpu": ["loong64"] - }, - "@typescript/typescript-linux-mips64el@7.0.2": { - "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", - "os": ["linux"], - "cpu": ["mips64el"] - }, - "@typescript/typescript-linux-ppc64@7.0.2": { - "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", - "os": ["linux"], - "cpu": ["ppc64"] - }, - "@typescript/typescript-linux-riscv64@7.0.2": { - "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", - "os": ["linux"], - "cpu": ["riscv64"] - }, - "@typescript/typescript-linux-s390x@7.0.2": { - "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", - "os": ["linux"], - "cpu": ["s390x"] - }, - "@typescript/typescript-linux-x64@7.0.2": { - "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", - "os": ["linux"], - "cpu": ["x64"] - }, - "@typescript/typescript-netbsd-arm64@7.0.2": { - "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", - "os": ["netbsd"], - "cpu": ["arm64"] - }, - "@typescript/typescript-netbsd-x64@7.0.2": { - "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", - "os": ["netbsd"], - "cpu": ["x64"] - }, - "@typescript/typescript-openbsd-arm64@7.0.2": { - "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", - "os": ["openbsd"], - "cpu": ["arm64"] - }, - "@typescript/typescript-openbsd-x64@7.0.2": { - "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", - "os": ["openbsd"], - "cpu": ["x64"] - }, - "@typescript/typescript-sunos-x64@7.0.2": { - "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", - "os": ["sunos"], - "cpu": ["x64"] - }, - "@typescript/typescript-win32-arm64@7.0.2": { - "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", - "os": ["win32"], - "cpu": ["arm64"] + "argue-cli@3.2.0": { + "integrity": "sha512-VipTB0gXgGIFO2Rg9yEVN5wLt2AurJcZqDbgmYSwPwsykhLrQhs240/bfceev4w68lI8JshoOJIk9uW7tFzROw==" }, - "@typescript/typescript-win32-x64@7.0.2": { - "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", - "os": ["win32"], - "cpu": ["x64"] - }, - "ajv@8.20.0": { - "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", - "dependencies": [ - "fast-deep-equal", - "fast-uri", - "json-schema-traverse", - "require-from-string" - ] - }, - "ansi-regex@6.3.0": { - "integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==" - }, - "ansi-styles@6.2.3": { - "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==" - }, - "argparse@2.0.1": { - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" - }, - "argue-cli@3.1.0": { - "integrity": "sha512-DhBpBfXL4SS2uC0N922MMajKR3CdrTG0u2or1PNYgXMsrSzViJrbtvT0nCLlLGUI0plam/ZZCs7aAauHtW9thw==" - }, - "callsites@3.1.0": { - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==" - }, - "cliui@9.0.1": { - "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==", - "dependencies": [ - "string-width@7.2.0", - "strip-ansi", - "wrap-ansi" - ] - }, - "conventional-changelog-angular@9.4.0": { - "integrity": "sha512-HdxRxuS8bBXVIuo4V82gvSwAXT0vYQUizrjs/izmPg5JdDstr8v8I5hduGL3iQbG+o310dUDxC4+LetuS5hu9w==", - "dependencies": [ - "@conventional-changelog/template" - ] - }, - "conventional-changelog-conventionalcommits@10.4.0": { - "integrity": "sha512-Rriac6ZrAlVm6cy9Bz4NSp+WMHpwNXoPIYex+HjCgduAVUSbnew29DQjQw0C4g9u3HtSYzGiGY+pdBXAZo+4aA==", + "conventional-changelog-conventionalcommits@10.4.1": { + "integrity": "sha512-jS1LRFSbRoAr6JbhhRy1JYfNNUj5LM3+v49hRE03CgccsiYqgdVj/RTmrw4J1rylrqijHwdOlJWiJa61JHOgHg==", "dependencies": [ "@conventional-changelog/template" ] }, - "conventional-commits-parser@7.1.2": { - "integrity": "sha512-O+x4N2yH+ijvqWlIyTHsXTAP+algNWgGbjY2duCe8w2vUMvUB95cLRslCPfTMQyLAKlet3bhZTdu6ozn4M+QJQ==", + "conventional-commits-parser@7.1.3": { + "integrity": "sha512-Q9oWm1o9uy/oEsZQIraoFMZ4RuPD+79KgwWj6mJVP356tazolCB0piRLZ5Kz9te9p027uSEcUW+Gu44Eh+X79g==", "dependencies": [ "@simple-libs/stream-utils", "argue-cli" ], "bin": true }, - "cosmiconfig-typescript-loader@6.3.0_@types+node@26.4.0_cosmiconfig@9.0.2__typescript@7.0.2_typescript@7.0.2": { - "integrity": "sha512-Akr82WH1Wfqatyiqpj8HDkO2o2KmJRu1FhKfSNJP3K4IdXwHfEyL7MOb62i1AGQVLtIQM+iCE9CGOtrfhR+mmA==", - "dependencies": [ - "@types/node", - "cosmiconfig", - "jiti", - "typescript" - ] - }, - "cosmiconfig@9.0.2_typescript@7.0.2": { - "integrity": "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg==", - "dependencies": [ - "env-paths", - "import-fresh", - "js-yaml", - "parse-json", - "typescript" - ], - "optionalPeers": [ - "typescript" - ] - }, - "emoji-regex@10.6.0": { - "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==" - }, - "env-paths@2.2.1": { - "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==" - }, - "error-ex@1.3.4": { - "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", - "dependencies": [ - "is-arrayish" - ] - }, - "es-toolkit@1.52.0": { - "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==" - }, - "escalade@3.2.0": { - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==" - }, - "fast-deep-equal@3.1.3": { - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" - }, - "fast-uri@3.1.6": { - "integrity": "sha512-7Ical1vFEMr0onbVzEDIreM22I4khW+fzyQPwvAFWBp1iwdshSZRsL4jjRvPG9JP1uiqMHRto+YU6R2/CzDz5Q==" - }, - "get-caller-file@2.0.5": { - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" - }, - "get-east-asian-width@1.6.0": { - "integrity": "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==" - }, - "global-directory@5.0.0": { - "integrity": "sha512-1pgFdhK3J2LeM+dVf2Pd424yHx2ou338lC0ErNP2hPx4j8eW1Sp0XqSjNxtk6Tc4Kr5wlWtSvz8cn2yb7/SG/w==", - "dependencies": [ - "ini" - ] - }, - "import-fresh@3.3.1": { - "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", - "dependencies": [ - "parent-module", - "resolve-from@4.0.0" - ] - }, - "ini@6.0.0": { - "integrity": "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==" - }, - "is-arrayish@0.2.1": { - "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==" - }, - "is-plain-obj@4.1.0": { - "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==" - }, - "jiti@2.6.1": { - "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", - "bin": true - }, - "js-tokens@4.0.0": { - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" - }, - "js-yaml@4.3.2": { - "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", - "dependencies": [ - "argparse" - ], - "bin": true - }, - "json-parse-even-better-errors@2.3.1": { - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" - }, - "json-schema-traverse@1.0.0": { - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" - }, - "lines-and-columns@1.2.4": { - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==" - }, - "parent-module@1.0.1": { - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dependencies": [ - "callsites" - ] - }, - "parse-json@5.2.0": { - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dependencies": [ - "@babel/code-frame", - "error-ex", - "json-parse-even-better-errors", - "lines-and-columns" - ] - }, "picocolors@1.1.1": { "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" - }, - "require-from-string@2.0.2": { - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==" - }, - "resolve-from@4.0.0": { - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==" - }, - "resolve-from@5.0.0": { - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==" - }, - "semver@7.8.5": { - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "bin": true - }, - "string-width@7.2.0": { - "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", - "dependencies": [ - "emoji-regex", - "get-east-asian-width", - "strip-ansi" - ] - }, - "string-width@8.2.2": { - "integrity": "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==", - "dependencies": [ - "get-east-asian-width", - "strip-ansi" - ] - }, - "strip-ansi@7.2.0": { - "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", - "dependencies": [ - "ansi-regex" - ] - }, - "tinyexec@1.3.0": { - "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==" - }, - "typescript@7.0.2": { - "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", - "optionalDependencies": [ - "@typescript/typescript-aix-ppc64", - "@typescript/typescript-darwin-arm64", - "@typescript/typescript-darwin-x64", - "@typescript/typescript-freebsd-arm64", - "@typescript/typescript-freebsd-x64", - "@typescript/typescript-linux-arm", - "@typescript/typescript-linux-arm64", - "@typescript/typescript-linux-loong64", - "@typescript/typescript-linux-mips64el", - "@typescript/typescript-linux-ppc64", - "@typescript/typescript-linux-riscv64", - "@typescript/typescript-linux-s390x", - "@typescript/typescript-linux-x64", - "@typescript/typescript-netbsd-arm64", - "@typescript/typescript-netbsd-x64", - "@typescript/typescript-openbsd-arm64", - "@typescript/typescript-openbsd-x64", - "@typescript/typescript-sunos-x64", - "@typescript/typescript-win32-arm64", - "@typescript/typescript-win32-x64" - ], - "bin": true - }, - "undici-types@8.3.0": { - "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==" - }, - "wrap-ansi@9.0.2": { - "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", - "dependencies": [ - "ansi-styles", - "string-width@7.2.0", - "strip-ansi" - ] - }, - "y18n@5.0.8": { - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==" - }, - "yargs-parser@22.0.0": { - "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==" - }, - "yargs@18.1.0": { - "integrity": "sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg==", - "dependencies": [ - "cliui", - "escalade", - "get-caller-file", - "string-width@8.2.2", - "y18n", - "yargs-parser" - ] } }, "workspace": { "dependencies": [ - "jsr:@std/yaml@^1.2.0", "npm:@commitlint/config-conventional@^21.2.0" ] } diff --git a/docs/solutions/architecture-patterns/a-test-never-takes-its-expected-value-from-the-code-under-test.md b/docs/solutions/architecture-patterns/a-test-never-takes-its-expected-value-from-the-code-under-test.md index a293b83..7a6d46b 100644 --- a/docs/solutions/architecture-patterns/a-test-never-takes-its-expected-value-from-the-code-under-test.md +++ b/docs/solutions/architecture-patterns/a-test-never-takes-its-expected-value-from-the-code-under-test.md @@ -15,27 +15,31 @@ tags: [constitution, characterization, snapshot, differential, testing, oracle] ## The defect -A test whose expected value came from the code under test is a tautology: it asserts that the -code equals itself, so it passes whether or not the code is right. It shows up under three names: +A test whose expected value came from the code under test is a tautology: it +asserts that the code equals itself, so it passes whether or not the code is +right. It shows up under three names: - a snapshot or golden file recorded from the code's current output - an approval test that replays a legacy script's output as the specification -- a differential that compares the code against another build or version of itself +- a differential that compares the code against another build or version of + itself -## Where the corpus says it +## Where the standards say it -CONST-T10's law: "Take every expected value from an oracle the code under test did not produce". -Its corpus criteria name the line: an expected value computed or recorded by running the code -under test, or any build or version of it, fails. Recording an expected value is computing it by -running the code earlier, so all three names above fall under that line. +SF-TST-2: "Take every expected value from an oracle the code under test did not +produce". The rule rejects an expected value computed or recorded by running the +code under test, or any build or version of it. Recording an expected value is +computing it by running the code earlier, so all three names above fall under +that line. -CONST-T8's corpus entry covers the two legitimate neighbours: comparing old and new during a -migration until they agree, then deleting the old; and persisted gold that is externally authored -and independently gated. A comparison against a genuinely independent implementation is an oracle -under CONST-T10, not a tautology. +SF-TST-1 covers the two legitimate neighbours: comparing old and new during a +migration until they agree, then deleting the old; and persisted gold that is +externally authored and independently gated. A comparison against a genuinely +independent implementation is an oracle under SF-TST-2, not a tautology. ## Enforcement Review only. On 2026-09-23 no snapshot-API lint existed in this repo, in -`systemfsoftware/are-the-types-wrong`, or in `systemfsoftware/systemfsoftware`. A mechanical check -belongs to whoever owns the lint instruments, not to the author of the rule (CONST-E7). +`systemfsoftware/are-the-types-wrong`, or in `systemfsoftware/systemfsoftware`. +A mechanical check belongs to whoever owns the lint instruments, not to the +author of the rule (SF-GATE-5). diff --git a/docs/solutions/architecture-patterns/the-vacuous-pass-gate-input-sets.md b/docs/solutions/architecture-patterns/the-vacuous-pass-gate-input-sets.md index 4c99266..45222ef 100644 --- a/docs/solutions/architecture-patterns/the-vacuous-pass-gate-input-sets.md +++ b/docs/solutions/architecture-patterns/the-vacuous-pass-gate-input-sets.md @@ -13,123 +13,137 @@ applies_when: - A merge-blocking check reports a count it computed itself - Restructuring a corpus the repo's own pre-commit gate certifies - Authoring cross-revision fixtures after narrowing the gate's input set -tags: [gate-design, vacuous-pass, verification, fail-closed, known-bad-fixture, corpus-surgery, atomic-commit] +tags: [ + gate-design, + vacuous-pass, + verification, + fail-closed, + known-bad-fixture, + corpus-surgery, + atomic-commit, +] --- # A gate can go green because it stopped looking ## Context -The constitution's format gate validated one markdown file whose path was a module-level -constant. The law was then split across two files. The gate's logic was untouched and -entirely correct — it parsed, it compared declared rule ids against parsed rule ids, it -found no discrepancy, it exited 0. It was reporting on a third of the rules. - -Nothing in the output distinguished that from a healthy corpus. The same run over the -whole corpus and the run over a third of it print the same shape, differing only in a -number nobody had a baseline for. - -Two further shapes of the same defect surfaced during review of the fix, both after the -input set had been widened to a tuple of paths: - -- A path present in the tuple but **absent from disk** was caught by a hard failure. A - path present, parsing cleanly, and declaring **zero rules** was not — emptying the - resident half to a preamble plus two `placeholder: true` blocks printed a valid line - with a smaller count and exited 0. -- The cross-revision arm tolerated a path that did not exist at the older revision, - because a newly created file legitimately has nothing to compare. That tolerance also - swallowed a path **renamed** in the same commit that re-scoped a rule: the older - revision had no such path, so the rule's retitle went uncompared and the run reported - no reassignment. -- A fourth shape surfaced when the surgery ran in the other direction — merging the two - files back into one while the gate's input tuple narrowed to a single path. There was - no legal intermediate commit. Landing the gate first left the live citation from the - resident file to an articles-resident rule dangling; landing the corpus first deleted a - path the gate still named, hitting the missing-input hard failure. The pre-commit hook - runs the gate at commit time, so both orderings are unlandable, not merely ugly. The - merge, the input-set change, the permission scopes, and the deletion had to arrive as - one atomic commit for the hook to grade a coherent end state. +The constitution's format gate validated one markdown file whose path was a +module-level constant. The law was then split across two files. The gate's logic +was untouched and entirely correct — it parsed, it compared declared rule ids +against parsed rule ids, it found no discrepancy, it exited 0. It was reporting +on a third of the rules. + +Nothing in the output distinguished that from a healthy corpus. The same run +over the whole corpus and the run over a third of it print the same shape, +differing only in a number nobody had a baseline for. + +Two further shapes of the same defect surfaced during review of the fix, both +after the input set had been widened to a tuple of paths: + +- A path present in the tuple but **absent from disk** was caught by a hard + failure. A path present, parsing cleanly, and declaring **zero rules** was not + — emptying the resident half to a preamble plus two `placeholder: true` blocks + printed a valid line with a smaller count and exited 0. +- The cross-revision arm tolerated a path that did not exist at the older + revision, because a newly created file legitimately has nothing to compare. + That tolerance also swallowed a path **renamed** in the same commit that + re-scoped a rule: the older revision had no such path, so the rule's retitle + went uncompared and the run reported no reassignment. +- A fourth shape surfaced when the surgery ran in the other direction — merging + the two files back into one while the gate's input tuple narrowed to a single + path. There was no legal intermediate commit. Landing the gate first left the + live citation from the resident file to an articles-resident rule dangling; + landing the corpus first deleted a path the gate still named, hitting the + missing-input hard failure. The pre-commit hook runs the gate at commit time, + so both orderings are unlandable, not merely ugly. The merge, the input-set + change, the permission scopes, and the deletion had to arrive as one atomic + commit for the hook to grade a coherent end state. ## Guidance **Assert the corpus, not only the contents.** A check over a subset is -indistinguishable from a check over the whole unless the gate says which inputs it -measured. Three rules follow. - -1. **A missing input is a hard failure, never a smaller pass.** Absence of an expected - input is a defect in the gate's own configuration, and it must exit non-zero rather - than validate what remains. - -2. **Presence is not contribution.** An input that resolves, parses, and yields nothing - scores exactly like one that yields its half. Require every declared input to - contribute at least one unit of the thing being validated. This is a recomputation - from the bytes — *did this file produce a rule?* — not a number the author supplies. - This rule is the prescription, not a description of the gate that prompted it: that - gate enforced the rule only through its whole-corpus emptiness check, and a single - path parsing to nothing while another contributed would still have passed. A gate - with several named inputs needs the per-path check written in, or shape 2 stays open. - -3. **What cannot be failed must be reported.** Some gaps are legal and failing them - would fire on correct work: a deliberate deletion, a genuinely new input with no - history. Name them on the success line — which inputs were not compared, which - identifiers vacated — so the reader sees the reduced coverage instead of inferring - full coverage from a clean exit. - -**Enumerate the orderings before choosing atomicity.** When the change edits both the -corpus and the gate that certifies it, write out every commit ordering and prove each -non-atomic one fails before accepting that one commit is forced. Then pin the atomic -commit's contents so the hook grades the end state, not a transition: the corpus merge, -the input-set constant, the shebang and task permission scopes, and the file deletion -land together. One site left at the old shape is the failure path. - -**Anchor cross-revision fixtures where the input set was complete.** A `--against` -comparison reads only the paths the gate names — at the compared revision, not just at -HEAD. A vacancy fixture anchored on a revision where part of the corpus lived outside -the current input set measures less than it claims and exits 0 saying nothing: the same -vacuous pass, wearing a diff arm. Anchor on the revision where the current input set -held the entire historical corpus, so the fixture's clean exit actually proves the -declared vacancy. - -**Never key a gate on a value its own author supplies.** The tempting fix for shape 1 is -a pinned expected count. That is a field the author writes, so the gate never runs on the -case it exists to catch. Prefer a key the gate recomputes: a digest over current bytes, a -compiler verdict, a re-derivation from the tree. - -**Prove the widening with a known-bad fixture.** A gate that has only ever been run -against a healthy input has demonstrated that it can print a success line. Run it against -an input that must fail, and read the failure text. Each defect above was found by a -fixture, not by reasoning about the code. +indistinguishable from a check over the whole unless the gate says which inputs +it measured. Three rules follow. + +1. **A missing input is a hard failure, never a smaller pass.** Absence of an + expected input is a defect in the gate's own configuration, and it must exit + non-zero rather than validate what remains. + +2. **Presence is not contribution.** An input that resolves, parses, and yields + nothing scores exactly like one that yields its half. Require every declared + input to contribute at least one unit of the thing being validated. This is a + recomputation from the bytes — _did this file produce a rule?_ — not a number + the author supplies. This rule is the prescription, not a description of the + gate that prompted it: that gate enforced the rule only through its + whole-corpus emptiness check, and a single path parsing to nothing while + another contributed would still have passed. A gate with several named inputs + needs the per-path check written in, or shape 2 stays open. + +3. **What cannot be failed must be reported.** Some gaps are legal and failing + them would fire on correct work: a deliberate deletion, a genuinely new input + with no history. Name them on the success line — which inputs were not + compared, which identifiers vacated — so the reader sees the reduced coverage + instead of inferring full coverage from a clean exit. + +**Enumerate the orderings before choosing atomicity.** When the change edits +both the corpus and the gate that certifies it, write out every commit ordering +and prove each non-atomic one fails before accepting that one commit is forced. +Then pin the atomic commit's contents so the hook grades the end state, not a +transition: the corpus merge, the input-set constant, the shebang and task +permission scopes, and the file deletion land together. One site left at the old +shape is the failure path. + +**Anchor cross-revision fixtures where the input set was complete.** A +`--against` comparison reads only the paths the gate names — at the compared +revision, not just at HEAD. A vacancy fixture anchored on a revision where part +of the corpus lived outside the current input set measures less than it claims +and exits 0 saying nothing: the same vacuous pass, wearing a diff arm. Anchor on +the revision where the current input set held the entire historical corpus, so +the fixture's clean exit actually proves the declared vacancy. + +**Never key a gate on a value its own author supplies.** The tempting fix for +shape 1 is a pinned expected count. That is a field the author writes, so the +gate never runs on the case it exists to catch. Prefer a key the gate +recomputes: a digest over current bytes, a compiler verdict, a re-derivation +from the tree. + +**Prove the widening with a known-bad fixture.** A gate that has only ever been +run against a healthy input has demonstrated that it can print a success line. +Run it against an input that must fail, and read the failure text. Each defect +above was found by a fixture, not by reasoning about the code. ## Why This Matters -The failure is silent by construction and lands in the one place nobody reads twice: -output that already says everything is fine. Downstream, the green result is then cited as -evidence the invariant holds — so the gate does not merely fail to catch the defect, it -actively certifies its absence. +The failure is silent by construction and lands in the one place nobody reads +twice: output that already says everything is fine. Downstream, the green result +is then cited as evidence the invariant holds — so the gate does not merely fail +to catch the defect, it actively certifies its absence. -The documentation compounds the harm. Prose asserting a guarantee the gate does not -implement ("a rule dropped in a move fails the gate") trains a maintainer to skip the -manual review the gate is not doing. Two independent reviewers caught that sentence here; -it had been written in the same change that widened the gate, by the author most convinced -the gate was now sound. +The documentation compounds the harm. Prose asserting a guarantee the gate does +not implement ("a rule dropped in a move fails the gate") trains a maintainer to +skip the manual review the gate is not doing. Two independent reviewers caught +that sentence here; it had been written in the same change that widened the +gate, by the author most convinced the gate was now sound. ## When to Apply -- Widening any check from one artifact to several — the moment the input set becomes a - collection, it becomes a thing that can silently shrink. -- Any gate that prints a count it computed itself, with no baseline the reader can check. -- Any check whose failure path is reachable only by a state the repository never normally - reaches; that path has almost certainly never run. -- Reviewing a claim about what a gate enforces. Run the fixture; do not read the code and - agree with it. -- Restructuring a corpus that a merge-blocking hook certifies — merging files, moving - rules, narrowing the input set. Prove the orderings first; atomicity is a conclusion, - not a style. +- Widening any check from one artifact to several — the moment the input set + becomes a collection, it becomes a thing that can silently shrink. +- Any gate that prints a count it computed itself, with no baseline the reader + can check. +- Any check whose failure path is reachable only by a state the repository never + normally reaches; that path has almost certainly never run. +- Reviewing a claim about what a gate enforces. Run the fixture; do not read the + code and agree with it. +- Restructuring a corpus that a merge-blocking hook certifies — merging files, + moving rules, narrowing the input set. Prove the orderings first; atomicity is + a conclusion, not a style. ## Examples -The corpus validator names its input set as a collection (`PATHS`), and an absent input is -fatal rather than a smaller pass: +The corpus validator names its input set as a collection (`PATHS`), and an +absent input is fatal rather than a smaller pass: ```ts const PATHS = ["CONSTITUTION.md"] as const; @@ -150,24 +164,23 @@ valid: 36 rules across 6 yaml blocks in 1 files, 9 families; no id reassigned si 1 id(s) vacated since origin/main: CONST-T4 ``` -And the fixture-anchoring pair from the reverse surgery — same gate, same narrowing, -different anchor: - -| Anchor revision | Corpus shape at that revision | Result | -|---|---|---| -| a split-era revision | vacated ids lived in the file outside the gate's current input set | exit 0, zero vacancies named — silently measures nothing | -| the pre-split revision | the one named file held every historical rule | exit 0, all nine vacancies named | - -The fixture battery that found all of it — each must fail, and the failure text is the -artifact worth keeping: - -| Fixture | Required result | -|---|---| -| one corpus path absent from disk | fail, naming the path | -| one corpus path present but declaring nothing | fail, naming the path | -| an identifier duplicated across two paths | fail on the duplicate | -| a rule deleted while a citation to it survives | fail on the dangling citation | -| a malformed fence in the second path | fail, naming that path and a path-local block index | -| a rule deleted with nothing citing it | pass, and name the vacated identifier | -| a path renamed alongside a rule retitle | pass, and name the uncompared path | - +And the fixture-anchoring pair from the reverse surgery — same gate, same +narrowing, different anchor: + +| Anchor revision | Corpus shape at that revision | Result | +| ---------------------- | ------------------------------------------------------------------ | -------------------------------------------------------- | +| a split-era revision | vacated ids lived in the file outside the gate's current input set | exit 0, zero vacancies named — silently measures nothing | +| the pre-split revision | the one named file held every historical rule | exit 0, all nine vacancies named | + +The fixture battery that found all of it — each must fail, and the failure text +is the artifact worth keeping: + +| Fixture | Required result | +| ---------------------------------------------- | --------------------------------------------------- | +| one corpus path absent from disk | fail, naming the path | +| one corpus path present but declaring nothing | fail, naming the path | +| an identifier duplicated across two paths | fail on the duplicate | +| a rule deleted while a citation to it survives | fail on the dangling citation | +| a malformed fence in the second path | fail, naming that path and a path-local block index | +| a rule deleted with nothing citing it | pass, and name the vacated identifier | +| a path renamed alongside a rule retitle | pass, and name the uncompared path | diff --git a/docs/solutions/workflow-issues/plans-freeze-observations-about-a-moving-base.md b/docs/solutions/workflow-issues/plans-freeze-observations-about-a-moving-base.md index 4ebe0db..be887e0 100644 --- a/docs/solutions/workflow-issues/plans-freeze-observations-about-a-moving-base.md +++ b/docs/solutions/workflow-issues/plans-freeze-observations-about-a-moving-base.md @@ -11,24 +11,56 @@ applies_when: - Commits land on the branch between plan freeze and the first implementation unit - A fixture expectation in a plan contradicts what the gate prints at execution time root_cause: stale planning baseline -tags: [plan-freeze, base-drift, fixtures, measured-expectations, review-findings] +tags: [ + plan-freeze, + base-drift, + fixtures, + measured-expectations, + review-findings, +] --- # Plans freeze observations about a moving base ## Context -During the Article III verification amendment, the plan was researched and frozen against base `dd5722a`. Six commits landed on the branch before the implementation units started. By execution time, plan rows that named the pre-split tree ("exactly six vacated ids at this revision", "the uncompared-file clause fires at revision X") described a tree that no longer existed: the corpus split and corpus-commit had moved the vacated-id set to nine and moved the uncompared-file boundary to an earlier revision. The multi-agent review wave flagged the unsatisfiable rows; execution had already recorded the honest outputs by running the gate and keeping what it printed. +During the Article III verification amendment, the plan was researched and +frozen against base `dd5722a`. Six commits landed on the branch before the +implementation units started. By execution time, plan rows that named the +pre-split tree ("exactly six vacated ids at this revision", "the uncompared-file +clause fires at revision X") described a tree that no longer existed: the corpus +split and corpus-commit had moved the vacated-id set to nine and moved the +uncompared-file boundary to an earlier revision. The multi-agent review wave +flagged the unsatisfiable rows; execution had already recorded the honest +outputs by running the gate and keeping what it printed. -The defect is not that the plan was wrong when written — it was measured against the base it named. The defect is that nothing re-derived the expectations when the base moved, and the plan's freeze rule (byte-identical after start) made correcting the rows in place the wrong move. +The defect is not that the plan was wrong when written — it was measured against +the base it named. The defect is that nothing re-derived the expectations when +the base moved, and the plan's freeze rule (byte-identical after start) made +correcting the rows in place the wrong move. ## Guidance -- At the first implementation unit, re-run every plan verification command against the current head. Record divergent outputs in the run record as measured facts; do not edit frozen plan rows to match. -- Derive fixture expectations at execution time from the gate's actual output. A number carried from research time is a hypothesis about the terminal; the run's own execution is the terminal. -- When a plan row and a measured output disagree, trust the measurement, note the divergence in the run record, and let the review (not the plan edit) carry the correction. Two unsatisfiable rows in this session were caught exactly this way — by a reviewer executing the named revision and comparing against the plan's text. -- Reviewers verify plan claims by execution against named revisions, not by re-reading the plan. That stance is what surfaced the drift; keep it in every review brief. +- At the first implementation unit, re-run every plan verification command + against the current head. Record divergent outputs in the run record as + measured facts; do not edit frozen plan rows to match. +- Derive fixture expectations at execution time from the gate's actual output. A + number carried from research time is a hypothesis about the terminal; the + run's own execution is the terminal. +- When a plan row and a measured output disagree, trust the measurement, note + the divergence in the run record, and let the review (not the plan edit) carry + the correction. Two unsatisfiable rows in this session were caught exactly + this way — by a reviewer executing the named revision and comparing against + the plan's text. +- Reviewers verify plan claims by execution against named revisions, not by + re-reading the plan. That stance is what surfaced the drift; keep it in every + review brief. ## Applicability -This applies to any planned change whose plan encodes observations about tree state (counts, absence boundaries, report shapes) rather than only intent. A plan that names only invariants and lets execution derive numbers has no rows to go stale. Where the plan must carry concrete expectations (fixtures for a gate), scope each expectation to the revision it was measured at, so a moved base invalidates the row loudly instead of silently. +This applies to any planned change whose plan encodes observations about tree +state (counts, absence boundaries, report shapes) rather than only intent. A +plan that names only invariants and lets execution derive numbers has no rows to +go stale. Where the plan must carry concrete expectations (fixtures for a gate), +scope each expectation to the revision it was measured at, so a moved base +invalidates the row loudly instead of silently. diff --git a/scripts/validate-constitution.test.ts b/scripts/validate-constitution.test.ts deleted file mode 100755 index d8fecc6..0000000 --- a/scripts/validate-constitution.test.ts +++ /dev/null @@ -1,956 +0,0 @@ -#!/usr/bin/env -S deno run --allow-write=/tmp --allow-run=deno,git,sh --allow-env -const TREE_ROOT = new URL("../", import.meta.url).pathname; -const CONFIG = new URL("../deno.json", import.meta.url).pathname; -const VALIDATOR_ARG = Deno.env.get("VALIDATOR_PATH") ?? "scripts/validate-constitution.ts"; -const VALIDATOR = VALIDATOR_ARG.startsWith("/") - ? VALIDATOR_ARG - : new URL(VALIDATOR_ARG, `file://${TREE_ROOT}`).pathname; -const HOOK_ARG = Deno.env.get("HOOK_PATH") ?? ".husky/pre-commit"; -const HOOK = HOOK_ARG.startsWith("/") - ? HOOK_ARG - : new URL(HOOK_ARG, `file://${TREE_ROOT}`).pathname; - -// Deno refuses to hand a subprocess any LD_*/DYLD_* variable, and giving a spawn -// an explicit `env` needs unscoped `--allow-run`. Stripping those names from this -// process's environment once is the one route that leaves `--allow-run` scoped; -// every spawn below, and the validator it launches, then inherits a clean env. -for (const name of Object.keys(Deno.env.toObject())) { - if (name.startsWith("LD_") || name.startsWith("DYLD_")) Deno.env.delete(name); -} - -const CONSTITUTION = `# Constitution - -The law text lives here. - -## Governance - -\`\`\`yaml -- id: CONST-G1 - law: A law must be legible. - why: Because illegible law cannot be applied. - example: - wrong: "Write terse law." - right: "Write plain law." -\`\`\` - -## Testing - -\`\`\`yaml -- id: CONST-T1 - law: A gate must fail a command. - why: A gate that cannot fail is a certificate. - example: - wrong: "Report success always." - right: "Exit non-zero on defect." -\`\`\` -`; - -const INCIDENTS = `["consumer abc1234:path/f.ts:12 thing", "this repo 0123abc:scripts/x.ts:3 thing"]`; - -const ENFORCEMENT = `# Enforcement - -Doctrine prose. Gates fail commands, not clauses. - -## Corpus - -\`\`\`yaml -version: 1 -laws: - - law: CONST-G1 - handle: LEGIBLE-LAW - absorbs: [CONST-B1, CONST-B2] - checks: - - question: "Is the law legible?" - criteria: "A reader can act on it." - mechanism: [review] - severity: P0 - waiver: "None." - incidents: ${INCIDENTS} - - law: CONST-T1 - handle: GATE-FAILS-COMMAND - absorbs: [] - checks: - - question: "Does the gate fail?" - criteria: "Exit is non-zero on defect." - mechanism: [command] - severity: P0 - waiver: "None." - incidents: ${INCIDENTS} -judging: - - id: CONST-G3 - handle: P0-VERDICT - rule: "Render a verdict of fixed or wrong." -retired: - - id: CONST-E7 - reason: "Folded into CONST-G1." -\`\`\` -`; - -type Result = { code: number; out: string }; - -function decode(bytes: Uint8Array): string { - return new TextDecoder().decode(bytes); -} - -async function runValidator(cwd: string, args: string[] = []): Promise { - const cmd = new Deno.Command("deno", { - args: [ - "run", - "--quiet", - "--allow-read=CONSTITUTION.md,ENFORCEMENT.md", - "--allow-run=git", - `--config=${CONFIG}`, - VALIDATOR, - ...args, - ], - cwd, - // Keep this child's env: it needs PATH to resolve the validator's own git - // spawn. LD_*/DYLD_* were already stripped from this process above. - stdout: "piped", - stderr: "piped", - }); - const o = await cmd.output(); - return { code: o.code, out: decode(o.stdout) + decode(o.stderr) }; -} - -async function runGit(cwd: string, args: string[]): Promise { - const cmd = new Deno.Command("git", { - args: ["-c", "user.email=test@example.com", "-c", "user.name=test", "-c", "commit.gpgsign=false", ...args], - cwd, - clearEnv: true, - stdout: "piped", - stderr: "piped", - }); - const o = await cmd.output(); - if (!o.success) { - throw new Error(`git ${args.join(" ")} failed: ${decode(o.stderr)}`); - } -} - -async function runHook(cwd: string): Promise { - const cmd = new Deno.Command("sh", { - args: [HOOK], - cwd, - stdout: "piped", - stderr: "piped", - }); - const o = await cmd.output(); - return { code: o.code, out: decode(o.stdout) + decode(o.stderr) }; -} - -/** - * A temp repo's `deno.json`. `test` drives the real validator on the corpus so - * the hook has the corpus gate to run; `test:validator` is a stub that always - * passes, so the pre-fix hook (whose exit status is its last line) can mask a - * failing `test` — which is the defect under test. The stub is reachable, so - * the valid-corpus control asserts a real 0. - */ -function hookDenoJson(): string { - return `${JSON.stringify({ - tasks: { - "test": - `deno run --quiet --allow-read=CONSTITUTION.md,ENFORCEMENT.md --allow-run=git --config=${CONFIG} ${VALIDATOR}`, - "test:validator": `deno eval "Deno.exit(0)"`, - }, - }, null, 2)}\n`; -} - -async function commitAll(dir: string, message: string): Promise { - await runGit(dir, ["add", "-A"]); - await runGit(dir, ["commit", "-qm", message]); -} - -async function withCorpus( - files: { constitution?: string; enforcement: string }, - fn: (dir: string) => Promise, -): Promise { - const dir = await Deno.makeTempDir({ dir: "/tmp", prefix: "constitution-test-" }); - try { - await Deno.writeTextFile(`${dir}/CONSTITUTION.md`, files.constitution ?? CONSTITUTION); - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, files.enforcement); - await fn(dir); - } finally { - await Deno.remove(dir, { recursive: true }); - } -} - -function assert(cond: boolean, message: string): void { - if (!cond) throw new Error(message); -} - -function assertFailsWith(result: Result, needle: string): void { - assert(result.code === 1, `expected exit 1, got ${result.code}; output: ${result.out}`); - assert( - result.out.includes(needle), - `expected output to include ${JSON.stringify(needle)}; got: ${result.out}`, - ); -} - -function assertUnmeasurable(result: Result, needle = "UNMEASURABLE"): void { - assert(result.code === 3, `expected exit 3, got ${result.code}; output: ${result.out}`); - assert( - result.out.includes(needle), - `expected output to include ${JSON.stringify(needle)}; got: ${result.out}`, - ); -} - -type Case = { name: string; fn: () => Promise }; -const cases: Case[] = []; -function test(name: string, fn: () => Promise): void { - cases.push({ name, fn }); -} - -test("#green: a valid placeholder corpus exits 0, and --against its own rev exits 0", async () => { - await withCorpus({ enforcement: ENFORCEMENT }, async (dir) => { - const r = await runValidator(dir); - assert(r.code === 0, `expected exit 0, got ${r.code}; output: ${r.out}`); - assert(r.out.includes("valid: 2 laws, 1 judging rules"), `success line missing: ${r.out}`); - - await runGit(dir, ["init", "-q"]); - await runGit(dir, ["add", "-A"]); - await runGit(dir, ["commit", "-qm", "rev"]); - await runGit(dir, ["tag", "rev"]); - const against = await runValidator(dir, ["--against", "rev"]); - assert(against.code === 0, `expected exit 0, got ${against.code}; output: ${against.out}`); - }); -}); - -test("#1: a fabricated absorbed or retired id is rejected", async () => { - const citedAbsorbed = ENFORCEMENT - .replace( - "Doctrine prose. Gates fail commands, not clauses.", - "Doctrine prose. CONST-Q9 governs the gate.", - ) - .replace("absorbs: [CONST-B1, CONST-B2]", "absorbs: [CONST-B5, CONST-Q9]"); - await withCorpus({ enforcement: citedAbsorbed }, async (dir) => { - assertFailsWith( - await runValidator(dir), - "absorbed id 'CONST-Q9' has family 'Q' which is not registered", - ); - }); - - const liveFamilyAbsorbed = ENFORCEMENT.replace( - "absorbs: [CONST-B1, CONST-B2]", - "absorbs: [CONST-B5, CONST-B7]", - ); - await withCorpus({ enforcement: liveFamilyAbsorbed }, async (dir) => { - assertFailsWith(await runValidator(dir), "absorbed id 'CONST-B7' is not a known old id"); - }); - - const fabricatedRetired = ENFORCEMENT.replace( - "- id: CONST-E7\n reason: \"Folded into CONST-G1.\"", - "- id: CONST-Q9\n reason: \"Folded into CONST-G1.\"", - ); - await withCorpus({ enforcement: fabricatedRetired }, async (dir) => { - assertFailsWith(await runValidator(dir), "retired id 'CONST-Q9' is not a known old id"); - }); -}); - -test("#3: --against fails when an id absorbed at rev has no home now", async () => { - await withCorpus({ enforcement: ENFORCEMENT }, async (dir) => { - const rev = ENFORCEMENT.replace("absorbs: [CONST-B1, CONST-B2]", "absorbs: [CONST-B1, CONST-B5]"); - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, rev); - await runGit(dir, ["init", "-q"]); - await runGit(dir, ["add", "-A"]); - await runGit(dir, ["commit", "-qm", "rev"]); - await runGit(dir, ["tag", "rev"]); - await Deno.writeTextFile( - `${dir}/ENFORCEMENT.md`, - ENFORCEMENT.replace("absorbs: [CONST-B1, CONST-B2]", "absorbs: [CONST-B1]"), - ); - assertFailsWith(await runValidator(dir, ["--against", "rev"]), "unaccounted id CONST-B5"); - }); -}); - -test("#12: an absorbed id must match the id shape and carry a registered family", async () => { - const enf = ENFORCEMENT.replace("absorbs: [CONST-B1, CONST-B2]", "absorbs: [CONST-Z5, CONST-9]"); - await withCorpus({ enforcement: enf }, async (dir) => { - const r = await runValidator(dir); - assertFailsWith(r, "absorbed id 'CONST-Z5' has family 'Z' which is not registered"); - assert( - r.out.includes("absorbed id 'CONST-9' does not match"), - `expected shape FAIL line; got: ${r.out}`, - ); - }); -}); - -test("#13: an empty checks list is rejected", async () => { - const enf = ENFORCEMENT.replace( - " checks:\n - question: \"Is the law legible?\"\n criteria: \"A reader can act on it.\"\n", - " checks: []\n", - ); - assert(enf.includes("checks: []"), "fixture edit failed"); - await withCorpus({ enforcement: enf }, async (dir) => { - assertFailsWith(await runValidator(dir), "'checks' must be a non-empty list"); - }); -}); - -test("#item1: a judging id must match the id shape and carry a registered family", async () => { - const badFamily = ENFORCEMENT.replace("- id: CONST-G3", "- id: CONST-Q9"); - assert(badFamily !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ enforcement: badFamily }, async (dir) => { - assertFailsWith( - await runValidator(dir), - "judging id 'CONST-Q9' has family 'Q' which is not registered", - ); - }); - - const badShape = ENFORCEMENT.replace("- id: CONST-G3", "- id: CONST-G"); - assert(badShape !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ enforcement: badShape }, async (dir) => { - assertFailsWith( - await runValidator(dir), - "judging id 'CONST-G' does not match ^CONST-[A-Z]\\d+$", - ); - }); -}); - -test("#item2: a repeated judging id is rejected", async () => { - const repeated = ENFORCEMENT.replace( - ' - id: CONST-G3\n handle: P0-VERDICT\n rule: "Render a verdict of fixed or wrong."', - ' - id: CONST-G3\n handle: P0-VERDICT\n rule: "Render a verdict of fixed or wrong."\n' + - ' - id: CONST-G3\n handle: SECOND-VERDICT\n rule: "Render the verdict again."', - ); - assert(repeated !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ enforcement: repeated }, async (dir) => { - assertFailsWith(await runValidator(dir), "CONST-G3: duplicate id"); - }); -}); - -const LAWLESS = `# Constitution - -The law text lives here, and for now it declares no laws at all. -`; - -const RETIRED_ONLY_CORPUS = `# Enforcement - -Doctrine prose. Gates fail commands, not clauses. - -## Corpus - -\`\`\`yaml -version: 1 -retired: - - id: CONST-E7 - reason: "Superseded by the current governance rule." -\`\`\` -`; - -const JUDGING_ONLY_CORPUS = `# Enforcement - -Doctrine prose. Gates fail commands, not clauses. - -## Corpus - -\`\`\`yaml -version: 1 -judging: - - id: CONST-G3 - handle: P0-VERDICT - rule: "Render a verdict of fixed or wrong." -\`\`\` -`; - -test("#item3a: a corpus contributing only a retired id is unmeasurable", async () => { - await withCorpus( - { constitution: LAWLESS, enforcement: RETIRED_ONLY_CORPUS }, - async (dir) => { - assertUnmeasurable(await runValidator(dir), "CONSTITUTION.md: declares no laws"); - }, - ); -}); - -test("#item3b: a corpus contributing only a judging rule is unmeasurable", async () => { - await withCorpus( - { constitution: LAWLESS, enforcement: JUDGING_ONLY_CORPUS }, - async (dir) => { - assertUnmeasurable(await runValidator(dir), "CONSTITUTION.md: declares no laws"); - }, - ); -}); - -test("#item4: --against reports a law whose handle moved", async () => { - await withCorpus({ enforcement: ENFORCEMENT }, async (dir) => { - await runGit(dir, ["init", "-q"]); - await runGit(dir, ["add", "-A"]); - await runGit(dir, ["commit", "-qm", "rev"]); - await runGit(dir, ["tag", "rev"]); - await Deno.writeTextFile( - `${dir}/ENFORCEMENT.md`, - ENFORCEMENT.replace("handle: LEGIBLE-LAW", "handle: PLAIN-LAW"), - ); - assertFailsWith( - await runValidator(dir, ["--against", "rev"]), - "reassigned id CONST-G1: handle 'LEGIBLE-LAW' at rev, 'PLAIN-LAW' now", - ); - }); -}); - -test("#item5: --against reports an id retired at rev that is live now", async () => { - const liveConstitution = `${CONSTITUTION} -## Enforcement - -\`\`\`yaml -- id: CONST-E7 - law: A gate must fail a command. - why: Because a gate that cannot fail is a certificate. - example: - wrong: "Report success always." - right: "Exit non-zero on defect." -\`\`\` -`; - const liveEnforcement = ENFORCEMENT - .replace( - "judging:\n", - ` - law: CONST-E7 - handle: E7-GATE-FAILS - absorbs: [] - checks: - - question: "Does the gate fail?" - criteria: "Exit is non-zero on defect." - mechanism: [command] - severity: P0 - waiver: "None." - incidents: ${INCIDENTS} -judging: -`, - ) - .replace('retired:\n - id: CONST-E7\n reason: "Folded into CONST-G1."\n', ""); - assert(liveEnforcement.includes("law: CONST-E7"), "fixture edit failed"); - assert(!liveEnforcement.includes("retired:"), "fixture edit failed"); - - await withCorpus( - { constitution: liveConstitution, enforcement: liveEnforcement }, - async (dir) => { - await Deno.writeTextFile(`${dir}/CONSTITUTION.md`, CONSTITUTION); - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENFORCEMENT); - await runGit(dir, ["init", "-q"]); - await runGit(dir, ["add", "-A"]); - await runGit(dir, ["commit", "-qm", "rev"]); - await runGit(dir, ["tag", "rev"]); - await Deno.writeTextFile(`${dir}/CONSTITUTION.md`, liveConstitution); - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, liveEnforcement); - assertFailsWith( - await runValidator(dir, ["--against", "rev"]), - "resurrected id CONST-E7", - ); - }, - ); -}); - -test("#item6: a missing ## Corpus block is unmeasurable", async () => { - const noCorpus = ENFORCEMENT.replace(/## Corpus[\s\S]*$/, "Doctrine only."); - assert(noCorpus !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ enforcement: noCorpus }, async (dir) => { - assertUnmeasurable(await runValidator(dir), "no ## Corpus block"); - }); -}); - -test("#item7: a law text padded past the word budget is rejected", async () => { - const padded = `${CONSTITUTION}\n${"padding ".repeat(2000)}`; - await withCorpus({ enforcement: ENFORCEMENT, constitution: padded }, async (dir) => { - assertFailsWith(await runValidator(dir), "exceeds the 1800-word budget"); - }); -}); - -test("#item8: a law entry with a single incident is rejected", async () => { - const oneIncident = ENFORCEMENT.replace( - INCIDENTS, - `["consumer abc1234:path/f.ts:12 thing"]`, - ); - assert(oneIncident !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ enforcement: oneIncident }, async (dir) => { - assertFailsWith(await runValidator(dir), "fewer than two incidents"); - }); -}); - -const G2_LAW = ` -\`\`\`yaml -- id: CONST-G2 - law: A freshly minted governance law. - why: The lineage can retire what it just created. - example: - wrong: "Keep it forever." - right: "Retire it, with a reason." -\`\`\` -`; -const CONSTITUTION_WITH_G2 = `${CONSTITUTION}${G2_LAW}`; -const ENF_RETIRED_G2 = ENFORCEMENT.replace( - ' - id: CONST-E7\n reason: "Folded into CONST-G1."\n', - ' - id: CONST-E7\n reason: "Folded into CONST-G1."\n - id: CONST-G2\n reason: "Retired the same day."\n', -); -const ENF_ABSORBS_G2 = ENFORCEMENT.replace( - "absorbs: [CONST-B1, CONST-B2]", - "absorbs: [CONST-B1, CONST-B2, CONST-G2]", -); -const ENF_G2_ENTRY = ENFORCEMENT.replace( - "judging:\n", - ` - law: CONST-G2 - handle: FRESH-GOVERNANCE - absorbs: [] - checks: - - question: "Is the freshly minted law covered?" - criteria: "It is." - mechanism: [review] - severity: P0 - waiver: "None." - incidents: ${INCIDENTS} -judging: -`, -); - -function assertOk(result: Result, label: string): void { - assert( - result.code === 0, - `${label}: expected exit 0, got ${result.code}; output: ${result.out}`, - ); -} - -test("#fix1a: an id live at the comparison revision may be retired, with and without --against", async () => { - assert(CONSTITUTION_WITH_G2.includes("CONST-G2"), "fixture edit failed"); - assert(ENF_RETIRED_G2 !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ constitution: CONSTITUTION_WITH_G2, enforcement: ENFORCEMENT }, async (dir) => { - await runGit(dir, ["init", "-q"]); - await runGit(dir, ["add", "-A"]); - await runGit(dir, ["commit", "-qm", "rev"]); - await runGit(dir, ["tag", "rev"]); - - await Deno.writeTextFile(`${dir}/CONSTITUTION.md`, CONSTITUTION); - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENF_RETIRED_G2); - - const noFlag = await runValidator(dir); - assert(noFlag.code === 0, `no-flag expected exit 0, got ${noFlag.code}; output: ${noFlag.out}`); - const against = await runValidator(dir, ["--against", "rev"]); - assert(against.code === 0, `--against expected exit 0, got ${against.code}; output: ${against.out}`); - }); -}); - -test("#fix1b: an id live at the comparison revision may be absorbed, with and without --against", async () => { - assert(ENF_ABSORBS_G2 !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ constitution: CONSTITUTION_WITH_G2, enforcement: ENFORCEMENT }, async (dir) => { - await runGit(dir, ["init", "-q"]); - await runGit(dir, ["add", "-A"]); - await runGit(dir, ["commit", "-qm", "rev"]); - await runGit(dir, ["tag", "rev"]); - - await Deno.writeTextFile(`${dir}/CONSTITUTION.md`, CONSTITUTION); - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENF_ABSORBS_G2); - - const noFlag = await runValidator(dir); - assert(noFlag.code === 0, `no-flag expected exit 0, got ${noFlag.code}; output: ${noFlag.out}`); - const against = await runValidator(dir, ["--against", "rev"]); - assert(against.code === 0, `--against expected exit 0, got ${against.code}; output: ${against.out}`); - }); -}); - -test("#fix1c: a fabricated id is rejected with and without --against", async () => { - await withCorpus({ constitution: CONSTITUTION, enforcement: ENFORCEMENT }, async (dir) => { - await runGit(dir, ["init", "-q"]); - await runGit(dir, ["add", "-A"]); - await runGit(dir, ["commit", "-qm", "rev"]); - await runGit(dir, ["tag", "rev"]); - - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENF_RETIRED_G2); - - assertFailsWith( - await runValidator(dir), - "retired id 'CONST-G2' is not a known old id", - ); - assertFailsWith( - await runValidator(dir, ["--against", "rev"]), - "retired id 'CONST-G2' is not a known old id", - ); - }); -}); - -test("#fix1d: an id minted and then retired across two commits stays accepted", async () => { - await withCorpus({ constitution: CONSTITUTION_WITH_G2, enforcement: ENF_G2_ENTRY }, async (dir) => { - await runGit(dir, ["init", "-q"]); - - // Commit 1: G2 is minted and live. - assertOk(await runValidator(dir), "mint"); - await commitAll(dir, "mint CONST-G2"); - - // Commit 2: G2 is removed from the law text and retired. - await Deno.writeTextFile(`${dir}/CONSTITUTION.md`, CONSTITUTION); - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENF_RETIRED_G2); - assertOk(await runValidator(dir), "retire, HEAD still holds G2 live"); - await commitAll(dir, "retire CONST-G2"); - - // Commit 3: an unrelated edit. HEAD now holds G2 retired, not live. - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, `${ENF_RETIRED_G2}\nUnrelated prose.\n`); - await commitAll(dir, "unrelated edit"); - - assertOk(await runValidator(dir), "no flag, G2 retired at HEAD"); - assertOk(await runValidator(dir, ["--against", "HEAD"]), "--against HEAD, G2 retired at HEAD"); - }); -}); - -test("#fix1e: an id minted and then absorbed across two commits stays accepted", async () => { - await withCorpus({ constitution: CONSTITUTION_WITH_G2, enforcement: ENF_G2_ENTRY }, async (dir) => { - await runGit(dir, ["init", "-q"]); - - // Commit 1: G2 is minted and live. - assertOk(await runValidator(dir), "mint"); - await commitAll(dir, "mint CONST-G2"); - - // Commit 2: G2 is removed from the law text and absorbed into CONST-G1. - await Deno.writeTextFile(`${dir}/CONSTITUTION.md`, CONSTITUTION); - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENF_ABSORBS_G2); - assertOk(await runValidator(dir), "absorb, HEAD still holds G2 live"); - await commitAll(dir, "absorb CONST-G2"); - - // Commit 3: an unrelated edit. HEAD now holds G2 absorbed, not live. - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, `${ENF_ABSORBS_G2}\nUnrelated prose.\n`); - await commitAll(dir, "unrelated edit"); - - assertOk(await runValidator(dir), "no flag, G2 absorbed at HEAD"); - assertOk(await runValidator(dir, ["--against", "HEAD"]), "--against HEAD, G2 absorbed at HEAD"); - }); -}); - -test("#fix6a: a made-up retired id committed without validation stays refused", async () => { - const retired = ENFORCEMENT.replace( - ' - id: CONST-E7\n reason: "Folded into CONST-G1."\n', - ' - id: CONST-D9\n reason: "Never live anywhere."\n', - ); - assert(retired !== ENFORCEMENT, "fixture edit failed"); - const expected = "retired id 'CONST-D9' is not a known old id"; - await withCorpus({ enforcement: ENFORCEMENT }, async (dir) => { - await runGit(dir, ["init", "-q"]); - await commitAll(dir, "a valid corpus"); - - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, retired); - await commitAll(dir, "retire a made-up id, bypassing the hook"); - assertFailsWith(await runValidator(dir), expected); - - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, `${retired}\nUnrelated prose.\n`); - await commitAll(dir, "an unrelated edit"); - assertFailsWith(await runValidator(dir), expected); - }); -}); - -test("#fix6b: a made-up absorbed id committed without validation stays refused", async () => { - const absorbed = ENFORCEMENT.replace( - "absorbs: [CONST-B1, CONST-B2]", - "absorbs: [CONST-B1, CONST-D9]", - ); - assert(absorbed !== ENFORCEMENT, "fixture edit failed"); - const expected = "absorbed id 'CONST-D9' is not a known old id"; - await withCorpus({ enforcement: ENFORCEMENT }, async (dir) => { - await runGit(dir, ["init", "-q"]); - await commitAll(dir, "a valid corpus"); - - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, absorbed); - await commitAll(dir, "absorb a made-up id, bypassing the hook"); - assertFailsWith(await runValidator(dir), expected); - - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, `${absorbed}\nUnrelated prose.\n`); - await commitAll(dir, "an unrelated edit"); - assertFailsWith(await runValidator(dir), expected); - }); -}); - -test("#hook: the pre-commit hook fails when deno task test fails", async () => { - const dir = await Deno.makeTempDir({ dir: "/tmp", prefix: "constitution-hook-" }); - try { - const dangling = ENFORCEMENT.replace( - "Doctrine prose. Gates fail commands, not clauses.", - "Doctrine prose. CONST-Q42 governs the gate.", - ); - assert(dangling !== ENFORCEMENT, "fixture edit failed"); - await Deno.writeTextFile(`${dir}/CONSTITUTION.md`, CONSTITUTION); - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, dangling); - await Deno.writeTextFile(`${dir}/deno.json`, hookDenoJson()); - await runGit(dir, ["init", "-q"]); - await commitAll(dir, "dangling corpus"); - - // The dangling citation fails `deno task test`; the hook must not mask it. - const red = await runHook(dir); - assert( - red.code !== 0, - `expected the hook to exit non-zero on a dangling corpus, got ${red.code}; output: ${red.out}`, - ); - - // Control: a valid corpus, with test:validator reachable, must exit 0. - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENFORCEMENT); - const control = await runHook(dir); - assert( - control.code === 0, - `expected the hook to exit 0 on a valid corpus, got ${control.code}; output: ${control.out}`, - ); - } finally { - await Deno.remove(dir, { recursive: true }); - } -}); - -test("#fix2: --against resolves a corpus vendored in a subdirectory", async () => { - const root = await Deno.makeTempDir({ dir: "/tmp", prefix: "constitution-nested-" }); - try { - const nested = `${root}/vendor/constitution`; - await Deno.mkdir(nested, { recursive: true }); - await Deno.writeTextFile(`${nested}/CONSTITUTION.md`, CONSTITUTION); - await Deno.writeTextFile(`${nested}/ENFORCEMENT.md`, ENFORCEMENT); - await runGit(root, ["init", "-q"]); - await runGit(root, ["add", "-A"]); - await runGit(root, ["commit", "-qm", "rev"]); - await runGit(root, ["tag", "rev"]); - - const r = await runValidator(nested, ["--against", "rev"]); - assert(r.code === 0, `expected exit 0, got ${r.code}; output: ${r.out}`); - } finally { - await Deno.remove(root, { recursive: true }); - } -}); - -test("#fix5: a quoted id in an unmeasured fence escapes the raw-vs-parsed coverage count", async () => { - // The fence info string carries a space, so `extractBlocks` never sees the - // block and its law is silently unmeasured. Pre-fix the raw count missed the - // quoted id too, so the coverage check stayed silent and the defect passed. - const misFenced = `${CONSTITUTION} -\`\`\` yaml -- id: "CONST-G1" - law: A shadowed copy the fence never measures. - why: The fence info string carries a space. - example: - wrong: "Trust a slightly different fence." - right: "Use exactly three backticks and yaml." -\`\`\` -`; - await withCorpus({ constitution: misFenced, enforcement: ENFORCEMENT }, async (dir) => { - assertFailsWith( - await runValidator(dir), - "law id(s) declared in the raw text but only", - ); - }); -}); - -test("#4a: a duplicate handle is rejected", async () => { - const dup = ENFORCEMENT.replace("handle: GATE-FAILS-COMMAND", "handle: LEGIBLE-LAW"); - assert(dup !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ enforcement: dup }, async (dir) => { - assertFailsWith(await runValidator(dir), "handle 'LEGIBLE-LAW' is not unique"); - }); -}); - -test("#4b: a law with no enforcement entry is rejected", async () => { - await withCorpus({ constitution: CONSTITUTION_WITH_G2, enforcement: ENFORCEMENT }, async (dir) => { - assertFailsWith(await runValidator(dir), "law CONST-G2: no enforcement entry"); - }); -}); - -test("#4c: a law with two enforcement entries is rejected", async () => { - const extra = ` - law: CONST-G1 - handle: SECOND-G1-HANDLE - absorbs: [] - checks: - - question: "Is the law legible twice?" - criteria: "It is not." - mechanism: [review] - severity: P0 - waiver: "None." - incidents: ${INCIDENTS} -`; - const two = ENFORCEMENT.replace("judging:\n", `${extra}judging:\n`); - assert(two !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ enforcement: two }, async (dir) => { - assertFailsWith(await runValidator(dir), "law CONST-G1: 2 enforcement entries"); - }); -}); - -test("#4d: a dangling citation to an invented id is rejected", async () => { - const cited = ENFORCEMENT.replace( - "Doctrine prose. Gates fail commands, not clauses.", - "Doctrine prose. CONST-G9 governs the gate.", - ); - assert(cited !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ enforcement: cited }, async (dir) => { - assertFailsWith(await runValidator(dir), "dangling citation: 'CONST-G9'"); - }); -}); - -const PROSE_DEFINITION_FORMS = [ - `- id: "CONST-Q42"`, - `- law: 'CONST-Q42'`, - `- id: CONST-Q42`, - `- CONST-Q42`, - `absorbs: [CONST-Q42]`, -]; - -test("#fix7a: a definition-shaped line in enforcement prose is a citation", async () => { - for (const form of PROSE_DEFINITION_FORMS) { - const prose = ENFORCEMENT.replace("## Corpus", `Not a definition:\n${form}\n\n## Corpus`); - assert(prose !== ENFORCEMENT, `fixture edit failed for ${JSON.stringify(form)}`); - await withCorpus({ enforcement: prose }, async (dir) => { - assertFailsWith(await runValidator(dir), "dangling citation: 'CONST-Q42'"); - }); - } -}); - -test("#fix7b: a definition-shaped line in constitution prose is a citation", async () => { - for (const form of [`- id: "CONST-Q42"`, `- law: 'CONST-Q42'`, `- CONST-Q42`]) { - const constitution = CONSTITUTION.replace( - "The law text lives here.", - `The law text lives here.\n\n${form}`, - ); - assert(constitution !== CONSTITUTION, `fixture edit failed for ${JSON.stringify(form)}`); - await withCorpus({ constitution, enforcement: ENFORCEMENT }, async (dir) => { - assertFailsWith(await runValidator(dir), "dangling citation: 'CONST-Q42'"); - }); - } -}); - -test("#fix7c: a definition-shaped line in prose that names a live law resolves", async () => { - const prose = ENFORCEMENT.replace( - "## Corpus", - `Not a definition, but it resolves: -- id: "CONST-G1" - -## Corpus`, - ); - assert(prose !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ enforcement: prose }, async (dir) => { - const r = await runValidator(dir); - assert(r.code === 0, `expected exit 0, got ${r.code}; output: ${r.out}`); - }); -}); - -const ENF_GHOST_ENTRY = ENFORCEMENT.replace( - "judging:\n", - ` - law: CONST-D9 - handle: GHOST-D9 - absorbs: [] - checks: - - question: "Is the ghost entry covered?" - criteria: "No live law declares it." - mechanism: [review] - severity: P0 - waiver: "None." - incidents: ${INCIDENTS} -judging: -`, -); -assert(ENF_GHOST_ENTRY !== ENFORCEMENT, "fixture edit failed"); - -const ENF_RETIRED_D9 = ENFORCEMENT.replace( - ' - id: CONST-E7\n reason: "Folded into CONST-G1."\n', - ' - id: CONST-E7\n reason: "Folded into CONST-G1."\n' + - ' - id: CONST-D9\n reason: "Retired once the ghost entry was gone."\n', -); -assert(ENF_RETIRED_D9 !== ENFORCEMENT, "fixture edit failed"); - -const ENF_ABSORBS_D9 = ENFORCEMENT.replace( - "absorbs: [CONST-B1, CONST-B2]", - "absorbs: [CONST-B1, CONST-B2, CONST-D9]", -); -assert(ENF_ABSORBS_D9 !== ENFORCEMENT, "fixture edit failed"); - -test("#c19a: a ghost corpus entry cannot launder a retired id", async () => { - await withCorpus({ enforcement: ENFORCEMENT }, async (dir) => { - assertOk(await runValidator(dir), "a valid corpus"); - await runGit(dir, ["init", "-q"]); - await commitAll(dir, "a valid corpus"); - - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENF_GHOST_ENTRY); - assertFailsWith(await runValidator(dir), "CONST-D9: names no live law"); - await commitAll(dir, "add a ghost entry, bypassing the hook"); - - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENF_RETIRED_D9); - await commitAll(dir, "remove the ghost entry and retire CONST-D9"); - - const expected = "retired id 'CONST-D9' is not a known old id"; - assertFailsWith(await runValidator(dir), expected); - assertFailsWith(await runValidator(dir, ["--against", "HEAD"]), expected); - }); -}); - -test("#c19b: a ghost corpus entry cannot launder an absorbed id", async () => { - await withCorpus({ enforcement: ENFORCEMENT }, async (dir) => { - assertOk(await runValidator(dir), "a valid corpus"); - await runGit(dir, ["init", "-q"]); - await commitAll(dir, "a valid corpus"); - - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENF_GHOST_ENTRY); - assertFailsWith(await runValidator(dir), "CONST-D9: names no live law"); - await commitAll(dir, "add a ghost entry, bypassing the hook"); - - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENF_ABSORBS_D9); - await commitAll(dir, "remove the ghost entry and absorb CONST-D9"); - - const expected = "absorbed id 'CONST-D9' is not a known old id"; - assertFailsWith(await runValidator(dir), expected); - assertFailsWith(await runValidator(dir, ["--against", "HEAD"]), expected); - }); -}); - -test("#c19c: a block scalar inside the corpus block is a citation", async () => { - const scalar = ENFORCEMENT.replace( - ' - question: "Is the law legible?"\n criteria: "A reader can act on it."\n', - ' - question: "Is the law legible?"\n' + - " criteria: |\n" + - " A reader can act on it.\n" + - " - CONST-Q42\n", - ); - assert(scalar !== ENFORCEMENT, "fixture edit failed"); - await withCorpus({ enforcement: scalar }, async (dir) => { - assertFailsWith(await runValidator(dir), "dangling citation: 'CONST-Q42'"); - }); -}); - -test("#c19d: a block scalar inside a law block is a citation", async () => { - const scalar = CONSTITUTION.replace( - " why: Because illegible law cannot be applied.\n", - " why: |\n Because illegible law cannot be applied, and a citation:\n - CONST-Q42\n", - ); - assert(scalar !== CONSTITUTION, "fixture edit failed"); - await withCorpus({ constitution: scalar, enforcement: ENFORCEMENT }, async (dir) => { - assertFailsWith(await runValidator(dir), "dangling citation: 'CONST-Q42'"); - }); -}); - -const ENF_JUDGING_G7 = ENFORCEMENT.replace( - ' - id: CONST-G3\n handle: P0-VERDICT\n rule: "Render a verdict of fixed or wrong."\n', - ' - id: CONST-G3\n handle: P0-VERDICT\n rule: "Render a verdict of fixed or wrong."\n' + - ' - id: CONST-G7\n handle: LINEAGE-VERDICT\n rule: "Render a lineage verdict."\n', -); -assert(ENF_JUDGING_G7 !== ENFORCEMENT, "fixture edit failed"); - -const ENF_RETIRED_G7 = ENFORCEMENT.replace( - ' - id: CONST-E7\n reason: "Folded into CONST-G1."\n', - ' - id: CONST-E7\n reason: "Folded into CONST-G1."\n' + - ' - id: CONST-G7\n reason: "Retired once the judging row was gone."\n', -); -assert(ENF_RETIRED_G7 !== ENFORCEMENT, "fixture edit failed"); - -test("#c19e: a judging id minted then retired across commits stays accepted", async () => { - await withCorpus({ enforcement: ENF_JUDGING_G7 }, async (dir) => { - await runGit(dir, ["init", "-q"]); - assertOk(await runValidator(dir), "mint CONST-G7, not on OLD_IDS"); - await commitAll(dir, "mint CONST-G7 as a judging id"); - - await Deno.writeTextFile(`${dir}/ENFORCEMENT.md`, ENF_RETIRED_G7); - await commitAll(dir, "remove the judging row and retire CONST-G7"); - - assertOk(await runValidator(dir), "no flag, CONST-G7 retired at HEAD"); - assertOk( - await runValidator(dir, ["--against", "HEAD"]), - "--against HEAD, CONST-G7 retired at HEAD", - ); - }); -}); - -let failed = 0; -for (const c of cases) { - try { - await c.fn(); - console.log(`ok - ${c.name}`); - } catch (e) { - failed++; - console.error(`not ok - ${c.name}\n ${(e as Error).message}`); - } -} -if (failed > 0) { - console.error(`\n${failed} failed, ${cases.length - failed} passed`); - Deno.exit(1); -} -console.log(`\nall ${cases.length} passed`); diff --git a/scripts/validate-constitution.ts b/scripts/validate-constitution.ts deleted file mode 100755 index ce0c146..0000000 --- a/scripts/validate-constitution.ts +++ /dev/null @@ -1,987 +0,0 @@ -#!/usr/bin/env -S deno run --allow-read=CONSTITUTION.md,ENFORCEMENT.md --allow-run=git -/** - * Validate the constitution corpus against the two-file corpus contract. - * - * The enforcement doctrine applied reflexively (ENFORCEMENT.md): the gate must - * fail a command, not a cited clause. This script validates the corpus the law - * lives in — CONSTITUTION.md (the law text) and ENFORCEMENT.md (doctrine plus the - * `## Corpus` block that binds every live law to a handle, checks, incidents and - * a mechanism). It certifies the shape the law is written in; it never grades - * what the law says. - * - * Coverage is checked before schema. An id the parser never reaches cannot be - * validated, and an unterminated fence silently removes every id after it from - * the block — so counting ids in the raw text and comparing against ids parsed - * out of blocks is the only way this gate reports on what it did NOT see. Without - * that comparison a green run means "no id I happened to parse was malformed", - * which is not the claim the gate is making. - * - * A corpus path that is merely absent is not the only shape of a vacuous pass: a - * file present and parsing but declaring nothing scores identically to a healthy - * one. A missing or unparseable file, or a missing `## Corpus` block, is - * unmeasurable and exits 3 — never 0. Otherwise a named defect list exits 1, and - * a clean corpus exits 0. - * - * Ids are not born in one document. A citation to an id must resolve to a live - * law, a judging rule, or an absorbed id; a retired id is deliberately not a - * valid citation, because a rule that moved keeps its number cold. `--against - * ` recomputes the lineage from git: every id at the revision must be live, - * absorbed, or retired now, and where the revision named handles, a live id whose - * handle moved is a reassignment (every citation to the number now points at a - * different obligation) — the one identifier defect no single revision can see. - */ -import { parse } from "@std/yaml"; - -const CONSTITUTION = "CONSTITUTION.md"; -const ENFORCEMENT = "ENFORCEMENT.md"; -const PATHS = [CONSTITUTION, ENFORCEMENT] as const; - -const LAW_ID_RE = /^CONST-[A-Z]\d+$/; -const HANDLE_RE = /^[A-Z][A-Z0-9]*(-[A-Z0-9]+)*$/; -const CITE_RE = /\bCONST-[A-Z]\d+\b/g; -const RAW_LAW_ID_RE = /^\s*-\s*id:\s*["']?CONST-[A-Z]\d+["']?\s*$/; -const RAW_CORPUS_ID_RE = /^\s*-\s*(?:law|id):\s*["']?CONST-[A-Z]\d+["']?\s*$/; - -const MAX_WORDS = 1800; -const LADDER = ["type", "command", "refusal", "review"]; -const SEVERITY = "P0"; - -const FAMILIES: Record = { - "G": "Governance", - "E": "Enforcement", - "P": "Purity", - "D": "Domain modelling", - "B": "Boundary", - "T": "Testing", - "N": "Naming & structure", - "W": "Work discipline", - "S": "Subtraction", -}; - -const LAW_KEYS = ["id", "law", "why", "example"]; -const EXAMPLE_KEYS = ["wrong", "right"]; -const CHECK_KEYS = ["question", "criteria"]; -const ENTRY_KEYS = [ - "law", - "handle", - "absorbs", - "checks", - "mechanism", - "severity", - "waiver", - "incidents", -]; -const JUDGING_KEYS = ["id", "handle", "rule"]; -const RETIRED_KEYS = ["id", "reason"]; - -const KNOWN_FAMILIES = Object.keys(FAMILIES).sort().join(", "); -const KNOWN_LADDER = LADDER.join(", "); - -const OLD_IDS: Record = { - "CONST-B1": true, - "CONST-B2": true, - "CONST-B3": true, - "CONST-B4": true, - "CONST-B5": true, - "CONST-B6": true, - "CONST-D1": true, - "CONST-D2": true, - "CONST-D3": true, - "CONST-D4": true, - "CONST-E7": true, - "CONST-E9": true, - "CONST-G3": true, - "CONST-G4": true, - "CONST-G5": true, - "CONST-N1": true, - "CONST-N2": true, - "CONST-N3": true, - "CONST-P1": true, - "CONST-P2": true, - "CONST-P3": true, - "CONST-S1": true, - "CONST-S2": true, - "CONST-S3": true, - "CONST-S4": true, - "CONST-T3": true, - "CONST-T8": true, - "CONST-T9": true, - "CONST-T10": true, - "CONST-T12": true, - "CONST-T13": true, - "CONST-T14": true, - "CONST-T15": true, - "CONST-W1": true, - "CONST-W2": true, - "CONST-W3": true, -}; - -type LineRange = { first: number; count: number }; -type YamlBlock = { - path: string; - index: number; - body: string; - closed: boolean; - bodyRange: LineRange; -}; -type Map_ = Record; - -function fail(errors: string[]): never { - for (const e of errors) console.log(`FAIL ${e}`); - Deno.exit(1); -} - -function unmeasurable(message: string): never { - console.error(`UNMEASURABLE: ${message}`); - Deno.exit(3); -} - -function asMap(v: unknown): Map_ | null { - return v !== null && typeof v === "object" && !Array.isArray(v) - ? v as Map_ - : null; -} - -function describe(v: unknown): string { - if (v === null) return "null"; - if (Array.isArray(v)) return "a sequence"; - if (typeof v === "object") return "a mapping"; - return `a ${typeof v}`; -} - -function extractBlocks(path: string, text: string): YamlBlock[] { - const lines = text.split("\n"); - const blocks: YamlBlock[] = []; - let i = 0; - let index = 0; - while (i < lines.length) { - if (/^```yaml\s*$/.test(lines[i])) { - const start = i; - i++; - const bodyLines: string[] = []; - let closed = false; - while (i < lines.length) { - if (/^```\s*$/.test(lines[i])) { - closed = true; - break; - } - bodyLines.push(lines[i]); - i++; - } - blocks.push({ - path, - index: index++, - body: bodyLines.join("\n"), - closed, - bodyRange: { first: start + 1, count: bodyLines.length }, - }); - if (closed) i++; - } else { - i++; - } - } - return blocks; -} - -function countRaw(text: string, re: RegExp): number { - let n = 0; - for (const line of text.split("\n")) if (re.test(line)) n++; - return n; -} - -function words(text: string): number { - return text.split(/\s+/).filter(Boolean).length; -} - -function familyOf(id: string): string { - return id["CONST-".length]; -} - -const DEF_LINE_RES: RegExp[] = [ - /^\s*-\s*id:\s*["']?CONST-[A-Z]\d+/, - /^\s*-\s*law:\s*["']?CONST-[A-Z]\d+/, - /^\s*-\s*["']?CONST-[A-Z]\d+["']?\s*$/, - /^\s*absorbs:\s*\[/, -]; - -function isDefinitionLine(line: string): boolean { - return DEF_LINE_RES.some((r) => r.test(line)); -} - -type ParsedBlock = { first: number; count: number; declared: Set }; - -const parsedBlocks = new Map(); - -function isDeclaredDefinition(path: string, lineNumber: number, line: string): boolean { - if (!isDefinitionLine(line)) return false; - const block = parsedBlocks.get(path)?.find( - (b) => lineNumber >= b.first && lineNumber < b.first + b.count, - ); - if (block === undefined) return false; - return [...line.matchAll(CITE_RE)].every((m) => block.declared.has(m[0])); -} - -function markParsedLines(path: string, range: LineRange, declared: Set): void { - let blocks = parsedBlocks.get(path); - if (blocks === undefined) { - blocks = []; - parsedBlocks.set(path, blocks); - } - blocks.push({ first: range.first, count: range.count, declared }); -} - -const againstIndex = Deno.args.indexOf("--against"); -const againstEquals = Deno.args.find((a) => a.startsWith("--against=")); -const against = againstIndex >= 0 - ? Deno.args[againstIndex + 1] - : againstEquals?.slice("--against=".length); -const againstRequested = againstIndex >= 0 || againstEquals !== undefined; -if (againstRequested && (against === undefined || against.length === 0)) { - fail(["--against requires a revision (form: --against or --against=)"]); -} -const strayAgainst = Deno.args.find((a) => - a.startsWith("--against") && a !== "--against" && !a.startsWith("--against=") -); -if (strayAgainst !== undefined) { - fail([`unknown flag '${strayAgainst}' — did you mean --against ?`]); -} - -const texts: Record = {}; -for (const p of PATHS) { - try { - texts[p] = await Deno.readTextFile(p); - } catch { - unmeasurable(`${p}: missing or unreadable`); - } -} -const constText = texts[CONSTITUTION]; -const enfText = texts[ENFORCEMENT]; - -const errors: string[] = []; - -/** The required-key and unknown-key check, shared by its six call sites. */ -function checkKeys(label: string, map: Map_, keys: readonly string[], infix = ""): void { - for (const k of keys) { - if (!(k in map)) errors.push(`${label}: ${infix}missing key '${k}'`); - } - const unknown = Object.keys(map).filter((k) => !keys.includes(k)); - if (unknown.length > 0) { - errors.push(`${label}: ${infix}unknown key(s) [${unknown.sort().join(", ")}]`); - } -} - -const lawBlocks = extractBlocks(CONSTITUTION, constText); -const laws: Map_[] = []; -for (const b of lawBlocks) { - if (!b.closed) { - errors.push( - `${b.path}: unterminated \`\`\`yaml fence in block ${b.index} — every id after it is unmeasured`, - ); - } - let doc: unknown; - try { - doc = parse(b.body); - } catch (e) { - errors.push(`${b.path} block ${b.index}: YAML parse error: ${(e as Error).message}`); - continue; - } - if (!Array.isArray(doc)) { - errors.push( - `${b.path} block ${b.index}: expected a top-level sequence of laws, got ${describe(doc)}`, - ); - continue; - } - const declared = new Set(); - for (const item of doc) { - laws.push(item as Map_); - const id = asMap(item)?.id; - if (typeof id === "string") declared.add(id); - } - markParsedLines(b.path, b.bodyRange, declared); -} - -const constWords = words(constText); -if (constWords > MAX_WORDS) { - errors.push( - `${CONSTITUTION}: ${constWords} words exceeds the ${MAX_WORDS}-word budget`, - ); -} - -const liveLawIds = new Set(); -const lawEntryCount = new Map(); - -for (let i = 0; i < laws.length; i++) { - const item = laws[i]; - const map = asMap(item); - if (map === null) { - errors.push(`law #${i + 1}: not a mapping`); - continue; - } - const rawId = map.id; - const id = typeof rawId === "string" ? rawId : ``; - - checkKeys(id, map, LAW_KEYS); - - for (const k of ["id", "law", "why"] as const) { - if (k in map && typeof map[k] !== "string") { - errors.push(`${id}: '${k}' must be a string`); - } - } - - if ("example" in map) { - const ex = asMap(map.example); - if (ex === null) { - errors.push(`${id}: 'example' must be a mapping with 'wrong' and 'right'`); - } else { - checkKeys(id, ex, EXAMPLE_KEYS, "example "); - for (const k of EXAMPLE_KEYS) { - if (k in ex && typeof ex[k] !== "string") { - errors.push(`${id}: example.'${k}' must be a string`); - } - } - } - } - - if (typeof rawId === "string") { - if (!LAW_ID_RE.test(rawId)) { - errors.push(`${rawId}: id does not match ${LAW_ID_RE.source}`); - } else if (!Object.hasOwn(FAMILIES, familyOf(rawId))) { - errors.push( - `${rawId}: family '${familyOf(rawId)}' is not registered — known families are [${KNOWN_FAMILIES}]`, - ); - } - if (liveLawIds.has(rawId)) errors.push(`${rawId}: duplicate id`); - liveLawIds.add(rawId); - } -} - -const rawLawIds = countRaw(constText, RAW_LAW_ID_RE); -if (rawLawIds > laws.length) { - errors.push( - `${CONSTITUTION}: ${rawLawIds} law id(s) declared in the raw text but only ${laws.length} parsed into yaml blocks — unterminated fence or a dropped block`, - ); -} - -const structuralErrorCount = errors.length; - -function findCorpusHeading(text: string): number { - const lines = text.split("\n"); - let idx = -1; - for (let i = 0; i < lines.length; i++) { - if (/^## Corpus\s*$/.test(lines[i])) idx = i; - } - return idx; -} - -type CorpusRead = { - /** Everything after the `## Corpus` heading, or null when the heading is absent. */ - text: string | null; - /** Whether the first fenced block parsed into a mapping. */ - hasMap: boolean; - blockRange: LineRange | null; - entries: Map_[]; - judging: Map_[]; - retired: Map_[]; - /** Structural complaints; the live pass reports them, the at-rev pass tolerates them. */ - problems: string[]; -}; - -/** One reader for both passes: the live corpus, and the corpus at `--against `. */ -function readCorpus(text: string): CorpusRead { - const headingLine = findCorpusHeading(text); - const found = headingLine < 0 ? null : text.split("\n").slice(headingLine + 1).join("\n"); - const read: CorpusRead = { - text: found, - hasMap: false, - blockRange: null, - entries: [], - judging: [], - retired: [], - problems: [], - }; - if (found === null) return read; - const blocks = extractBlocks(ENFORCEMENT, found); - if (blocks.length === 0) { - read.problems.push(`${ENFORCEMENT}: ## Corpus is not followed by a fenced yaml block`); - return read; - } - if (blocks.length > 1) { - read.problems.push( - `${ENFORCEMENT}: ## Corpus must hold exactly one fenced yaml block, found ${blocks.length}`, - ); - } - const first = blocks[0]; - if (!first.closed) { - read.problems.push(`${ENFORCEMENT}: unterminated \`\`\`yaml fence in the ## Corpus block`); - } - let doc: unknown; - try { - doc = parse(first.body); - } catch (e) { - read.problems.push(`${ENFORCEMENT}: ## Corpus YAML parse error: ${(e as Error).message}`); - doc = undefined; - } - const map = asMap(doc); - if (doc !== undefined && map === null) { - read.problems.push(`${ENFORCEMENT}: ## Corpus must be a mapping, got ${describe(doc)}`); - } - if (map === null) return read; - read.hasMap = true; - read.blockRange = { - first: headingLine + 1 + first.bodyRange.first, - count: first.bodyRange.count, - }; - const rawLaws = map.laws; - const rawJudging = map.judging; - const rawRetired = map.retired; - if (rawLaws !== undefined && !Array.isArray(rawLaws)) { - read.problems.push(`${ENFORCEMENT}: corpus 'laws' must be a sequence`); - } - if (rawJudging !== undefined && !Array.isArray(rawJudging)) { - read.problems.push(`${ENFORCEMENT}: corpus 'judging' must be a sequence`); - } - if (rawRetired !== undefined && !Array.isArray(rawRetired)) { - read.problems.push(`${ENFORCEMENT}: corpus 'retired' must be a sequence`); - } - if (Array.isArray(rawLaws)) for (const e of rawLaws) read.entries.push(e as Map_); - if (Array.isArray(rawJudging)) for (const e of rawJudging) read.judging.push(e as Map_); - if (Array.isArray(rawRetired)) for (const e of rawRetired) read.retired.push(e as Map_); - return read; -} - -function declaredCorpusIds(read: CorpusRead): Set { - const declared = new Set(); - for (const e of read.entries) { - const em = asMap(e); - if (em === null) continue; - if (typeof em.law === "string") declared.add(em.law); - if (Array.isArray(em.absorbs)) { - for (const a of em.absorbs) if (typeof a === "string") declared.add(a); - } - } - for (const e of [...read.judging, ...read.retired]) { - const em = asMap(e); - if (em !== null && typeof em.id === "string") declared.add(em.id); - } - return declared; -} - -const live = readCorpus(enfText); -if (live.blockRange !== null) { - markParsedLines(ENFORCEMENT, live.blockRange, declaredCorpusIds(live)); -} -const corpusText = live.text; -const corpusMissing = corpusText === null; -const rawCorpusIds = corpusText === null ? 0 : countRaw(corpusText, RAW_CORPUS_ID_RE); -errors.push(...live.problems); - -type Corpus = { - entries: Map_[]; - judging: Map_[]; - retired: Map_[]; - absorbedIds: string[]; - retiredIds: string[]; -}; -const corpus: Corpus = { - entries: live.entries, - judging: live.judging, - retired: live.retired, - absorbedIds: [], - retiredIds: [], -}; - -async function lineageIds(): Promise> { - const ids = new Set(); - const commits = new Set(); - for (const rev of against === undefined ? ["HEAD"] : ["HEAD", against]) { - for (const commit of await commitsTouchingCorpus(rev)) commits.add(commit); - } - if (commits.size > 0) { - const refs: string[] = []; - for (const commit of commits) for (const p of PATHS) refs.push(`${commit}:./${p}`); - const blobs = await gitCatFileBatch(refs); - for (const commit of commits) { - const lawText = blobs.get(`${commit}:./${CONSTITUTION}`); - const declaredHere = new Set( - lawText !== undefined && lawText !== null - ? idsFromConstitutionAtRev(lawText) - : [], - ); - for (const id of declaredHere) ids.add(id); - const doctrine = blobs.get(`${commit}:./${ENFORCEMENT}`); - if (doctrine !== undefined && doctrine !== null) { - const at = readCorpus(doctrine); - if (at.hasMap) { - for (const e of at.entries) { - const em = asMap(e); - if (em !== null && typeof em.law === "string" && declaredHere.has(em.law)) { - ids.add(em.law); - } - } - for (const e of at.judging) { - const em = asMap(e); - if (em !== null && typeof em.id === "string") ids.add(em.id); - } - } - } - } - } - return ids; -} - -async function commitsTouchingCorpus(rev: string): Promise { - try { - const out = await new Deno.Command("git", { - args: ["log", "--format=%H", rev, "--", `./${CONSTITUTION}`, `./${ENFORCEMENT}`], - cwd: Deno.cwd(), - clearEnv: true, - stdout: "piped", - stderr: "piped", - }).output(); - if (!out.success) return []; - return new TextDecoder().decode(out.stdout).split("\n").map((l) => l.trim()).filter(Boolean); - } catch { - return []; - } -} - -async function gitCatFileBatch(objects: string[]): Promise> { - const blobs = new Map(); - if (objects.length === 0) return blobs; - try { - const child = new Deno.Command("git", { - args: ["cat-file", "--batch"], - cwd: Deno.cwd(), - clearEnv: true, - stdin: "piped", - stdout: "piped", - stderr: "piped", - }).spawn(); - const writer = child.stdin.getWriter(); - const writing = (async () => { - await writer.write(new TextEncoder().encode(objects.map((o) => `${o}\n`).join(""))); - await writer.close(); - })().catch(() => {}); - const out = await child.output(); - await writing; - const bytes = out.stdout; - const decoder = new TextDecoder(); - let at = 0; - for (const object of objects) { - const newline = bytes.indexOf(0x0a, at); - if (newline < 0) break; - const header = decoder.decode(bytes.subarray(at, newline)); - at = newline + 1; - if (header.endsWith(" missing")) { - blobs.set(object, null); - continue; - } - const parts = header.split(" "); - const size = Number(parts[parts.length - 1]); - if (parts.length !== 3 || !Number.isInteger(size) || size < 0 || at + size > bytes.length) { - break; - } - blobs.set(object, parts[1] === "blob" ? decoder.decode(bytes.subarray(at, at + size)) : null); - at += size + 1; - } - } catch { - return blobs; - } - return blobs; -} - -let constAtRev: string | null = null; -let enfAtRev: string | null = null; -if (against !== undefined) { - try { - [constAtRev, enfAtRev] = await Promise.all([ - gitShow(against, CONSTITUTION), - gitShow(against, ENFORCEMENT), - ]); - } catch (e) { - errors.push(`--against ${against}: git is not runnable (${(e as Error).message})`); - } -} - -const knownOldIds = new Set(Object.keys(OLD_IDS)); -for (const id of await lineageIds()) knownOldIds.add(id); - -const handleOwner = new Map(); -const handleById = new Map(); -function registerHandle(id: string, rawHandle: unknown): void { - if (typeof rawHandle !== "string") { - errors.push(`${id}: 'handle' must be a string`); - return; - } - if (!HANDLE_RE.test(rawHandle)) { - errors.push(`${id}: handle '${rawHandle}' is not UPPER-KEBAB`); - } - if (handleOwner.has(rawHandle)) { - errors.push(`handle '${rawHandle}' is not unique (used by ${handleOwner.get(rawHandle)} and ${id})`); - } else { - handleOwner.set(rawHandle, id); - } - handleById.set(id, rawHandle); -} - -for (let i = 0; i < corpus.entries.length; i++) { - const map = asMap(corpus.entries[i]); - if (map === null) { - errors.push(`corpus entry #${i + 1}: not a mapping`); - continue; - } - const rawLaw = map.law; - const label = typeof rawLaw === "string" ? rawLaw : ``; - - checkKeys(label, map, ENTRY_KEYS); - - if (typeof rawLaw !== "string") { - errors.push(`${label}: 'law' must be a string`); - } else if (!liveLawIds.has(rawLaw)) { - errors.push(`${label}: names no live law`); - } else { - lawEntryCount.set(rawLaw, (lawEntryCount.get(rawLaw) ?? 0) + 1); - } - - registerHandle(label, map.handle); - - if ("absorbs" in map) { - const a = map.absorbs; - if (!Array.isArray(a) || a.some((x) => typeof x !== "string")) { - errors.push(`${label}: 'absorbs' must be a list of ids`); - } else { - for (const x of a as string[]) { - if (!LAW_ID_RE.test(x)) { - errors.push(`${label}: absorbed id '${x}' does not match ${LAW_ID_RE.source}`); - } else if (!Object.hasOwn(FAMILIES, familyOf(x))) { - errors.push( - `${label}: absorbed id '${x}' has family '${familyOf(x)}' which is not registered — known families are [${KNOWN_FAMILIES}]`, - ); - } else if (!knownOldIds.has(x)) { - errors.push(`${label}: absorbed id '${x}' is not a known old id`); - } else { - corpus.absorbedIds.push(x); - } - } - } - } - - if ("checks" in map) { - const c = map.checks; - if (!Array.isArray(c) || c.length === 0) { - errors.push(`${label}: 'checks' must be a non-empty list`); - } else { - for (const ch of c) { - const cm = asMap(ch); - if (cm === null) { - errors.push(`${label}: each check must be a mapping`); - continue; - } - checkKeys(label, cm, CHECK_KEYS, "check "); - for (const k of ["question", "criteria"]) { - if (k in cm && typeof cm[k] !== "string") { - errors.push(`${label}: check.'${k}' must be a string`); - } - } - } - } - } - - if ("mechanism" in map) { - const m = map.mechanism; - if (!Array.isArray(m) || m.length === 0) { - errors.push(`${label}: 'mechanism' must be a non-empty list`); - } else { - const bad = m.filter((x) => typeof x !== "string" || !LADDER.includes(x as string)); - if (bad.length > 0) { - errors.push( - `${label}: mechanism [${bad.map(String).join(", ")}] outside the ladder [${KNOWN_LADDER}]`, - ); - } - } - } - - if ("severity" in map && map.severity !== SEVERITY) { - errors.push(`${label}: severity '${String(map.severity)}' must be ${SEVERITY}`); - } - - if ("waiver" in map && typeof map.waiver !== "string") { - errors.push(`${label}: 'waiver' must be a string`); - } - - if ("incidents" in map) { - const inc = map.incidents; - if (!Array.isArray(inc) || inc.some((x) => typeof x !== "string")) { - errors.push(`${label}: 'incidents' must be a list of strings`); - } else if (inc.length < 2) { - errors.push(`${label}: fewer than two incidents (found ${inc.length})`); - } - } -} - -const judgingIds = new Set(); -for (let i = 0; i < corpus.judging.length; i++) { - const map = asMap(corpus.judging[i]); - if (map === null) { - errors.push(`judging entry #${i + 1}: not a mapping`); - continue; - } - const rawId = map.id; - const label = typeof rawId === "string" ? rawId : ``; - checkKeys(label, map, JUDGING_KEYS); - for (const k of ["id", "rule"]) { - if (k in map && typeof map[k] !== "string") { - errors.push(`${label}: '${k}' must be a string`); - } - } - if (typeof rawId === "string") { - if (!LAW_ID_RE.test(rawId)) { - errors.push(`${label}: judging id '${rawId}' does not match ${LAW_ID_RE.source}`); - } else if (!Object.hasOwn(FAMILIES, familyOf(rawId))) { - errors.push( - `${label}: judging id '${rawId}' has family '${familyOf(rawId)}' which is not registered — known families are [${KNOWN_FAMILIES}]`, - ); - } - if (judgingIds.has(rawId)) errors.push(`${rawId}: duplicate id`); - judgingIds.add(rawId); - } - registerHandle(label, map.handle); -} - -for (let i = 0; i < corpus.retired.length; i++) { - const map = asMap(corpus.retired[i]); - if (map === null) { - errors.push(`retired entry #${i + 1}: not a mapping`); - continue; - } - const rawId = map.id; - const label = typeof rawId === "string" ? rawId : ``; - checkKeys(label, map, RETIRED_KEYS); - if (typeof rawId !== "string") errors.push(`${label}: 'id' must be a string`); - if (typeof map.reason !== "string" || map.reason.trim().length === 0) { - errors.push(`${label}: 'reason' must be a non-empty string`); - } - if (typeof rawId === "string") { - if (!knownOldIds.has(rawId)) { - errors.push(`${label}: retired id '${rawId}' is not a known old id`); - } else { - corpus.retiredIds.push(rawId); - } - } -} - -const idCounts = new Map(); -const bump = (id: string) => idCounts.set(id, (idCounts.get(id) ?? 0) + 1); -for (const id of liveLawIds) bump(id); -for (const id of judgingIds) bump(id); -for (const id of corpus.absorbedIds) bump(id); -for (const id of corpus.retiredIds) bump(id); -for (const [id, n] of idCounts) { - if (n > 1) { - errors.push(`${id}: id appears more than once across live laws, judging ids, absorbs lists, and retired`); - } -} - -for (const id of liveLawIds) { - const n = lawEntryCount.get(id) ?? 0; - if (n === 0) errors.push(`law ${id}: no enforcement entry`); - if (n > 1) errors.push(`law ${id}: ${n} enforcement entries`); -} - -if (corpusText !== null) { - const parsedCorpusIds = corpus.entries.length + corpus.judging.length + corpus.retired.length; - if (rawCorpusIds > parsedCorpusIds) { - errors.push( - `${ENFORCEMENT}: ${rawCorpusIds} corpus id(s) declared in the raw block but only ${parsedCorpusIds} parsed — unterminated fence or a dropped entry`, - ); - } -} - -const validTargets = new Set([ - ...liveLawIds, - ...judgingIds, - ...corpus.absorbedIds, -]); -const dangling: Record = {}; -for (const p of PATHS) { - const lines = texts[p].split("\n"); - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - if (isDeclaredDefinition(p, i, line)) continue; - for (const m of line.matchAll(CITE_RE)) { - const id = m[0]; - if (validTargets.has(id)) continue; - (dangling[p] ??= []).push(id); - } - } -} -for (const p of PATHS) { - const ids = [...new Set(dangling[p] ?? [])].sort(); - for (const id of ids) { - errors.push(`dangling citation: '${id}' is cited in ${p} but is neither a live law, a judging rule, nor an absorbed id`); - } -} - -const totalRawIds = rawLawIds + rawCorpusIds; - -let againstAccountingOnly = false; -let vacated: string[] = []; -const uncompared: string[] = []; - -function idsFromConstitutionAtRev(text: string): string[] { - const ids: string[] = []; - for (const b of extractBlocks(`${CONSTITUTION}@rev`, text)) { - let doc: unknown; - try { - doc = parse(b.body); - } catch { - continue; - } - const seq = Array.isArray(doc) - ? doc - : (asMap(doc)?.rules as unknown[] | undefined); - if (!Array.isArray(seq)) continue; - for (const it of seq) { - const id = asMap(it)?.id; - if (typeof id === "string") ids.push(id); - } - } - return ids; -} - -async function gitShow(rev: string, path: string): Promise { - const cmd = new Deno.Command("git", { - // `:./` resolves `` from this process's directory, so a - // corpus vendored in a subdirectory of its repo compares correctly. - args: ["show", `${rev}:./${path}`], - cwd: Deno.cwd(), - // Spawning with an explicit env needs unscoped `--allow-run`; clearing the - // child env is the one route that keeps the run permission scoped, and it - // drops any LD_*/DYLD_* variable Deno refuses to pass along. - clearEnv: true, - stdout: "piped", - stderr: "piped", - }); - const out = await cmd.output(); - if (!out.success) return null; - return new TextDecoder().decode(out.stdout); -} - -if (against !== undefined) { - if (constAtRev === null) uncompared.push(CONSTITUTION); - if (enfAtRev === null) uncompared.push(ENFORCEMENT); - - const oldIds = new Set(constAtRev !== null ? idsFromConstitutionAtRev(constAtRev) : []); - - const handlesAtRev = new Map(); - const absorbedAtRev = new Set(); - const retiredAtRev = new Set(); - let hasCorpusAtRev = false; - - if (enfAtRev !== null) { - const atRev = readCorpus(enfAtRev); - if (atRev.hasMap) { - hasCorpusAtRev = true; - for (const e of atRev.entries) { - const em = asMap(e); - if (em === null) continue; - if (typeof em.law === "string") { - oldIds.add(em.law); - if (typeof em.handle === "string") handlesAtRev.set(em.law, em.handle); - } - if (Array.isArray(em.absorbs)) { - for (const a of em.absorbs) if (typeof a === "string") absorbedAtRev.add(a); - } - } - for (const e of atRev.judging) { - const em = asMap(e); - if (em === null) continue; - if (typeof em.id === "string") { - oldIds.add(em.id); - if (typeof em.handle === "string") handlesAtRev.set(em.id, em.handle); - } - } - for (const e of atRev.retired) { - const em = asMap(e); - if (em !== null && typeof em.id === "string") retiredAtRev.add(em.id); - } - } - } - - for (const id of absorbedAtRev) oldIds.add(id); - for (const id of retiredAtRev) oldIds.add(id); - const sortedOldIds = [...oldIds].sort(); - - if (oldIds.size === 0) { - errors.push( - `--against ${against}: no ids found at that revision — wrong rev, or every file renamed`, - ); - } else { - const liveNow = new Set([...liveLawIds, ...judgingIds]); - const absorbedNow = new Set(corpus.absorbedIds); - const retiredNow = new Set(corpus.retiredIds); - - for (const id of sortedOldIds) { - if (liveNow.has(id) || absorbedNow.has(id) || retiredNow.has(id)) continue; - errors.push(`unaccounted id ${id}`); - } - - if (hasCorpusAtRev) { - for (const id of sortedOldIds) { - if (!liveNow.has(id)) continue; - const oldHandle = handlesAtRev.get(id); - const nowHandle = handleById.get(id); - if (oldHandle !== undefined && nowHandle !== undefined && oldHandle !== nowHandle) { - errors.push( - `reassigned id ${id}: handle '${oldHandle}' at ${against}, '${nowHandle}' now`, - ); - } - } - for (const id of [...new Set([...absorbedAtRev, ...retiredAtRev])].sort()) { - if (liveNow.has(id)) { - errors.push(`resurrected id ${id}: absorbed or retired at ${against} but live now`); - } - } - } else { - againstAccountingOnly = true; - } - - vacated = sortedOldIds.filter((id) => - !liveNow.has(id) && (absorbedNow.has(id) || retiredNow.has(id)) - ); - } -} - -if (corpusMissing) { - if (structuralErrorCount > 0) fail(errors.slice(0, structuralErrorCount)); - unmeasurable(`${ENFORCEMENT}: no ## Corpus block — the corpus is unmeasurable`); -} -if (errors.length > 0) fail(errors); -if (laws.length === 0) { - unmeasurable(`${CONSTITUTION}: declares no laws — the law text is unmeasurable`); -} -if (corpusText !== null && corpus.entries.length === 0) { - unmeasurable(`${ENFORCEMENT}: ## Corpus contributes no law entries — the corpus is unmeasurable`); -} -if (totalRawIds === 0) { - unmeasurable("no identifiers matched in either file — the corpus is empty, or the id syntax moved"); -} - -const totalBlocks = lawBlocks.length + extractBlocks(ENFORCEMENT, enfText).length; -let line = - `valid: ${laws.length} laws, ${corpus.judging.length} judging rules, ${corpus.absorbedIds.length} absorbed, ` + - `${corpus.retired.length} retired across ${totalBlocks} yaml blocks in ${PATHS.length} files, ` + - `${Object.keys(FAMILIES).length} families`; -if (against !== undefined && againstAccountingOnly) { - line += `; lineage by accounting only, no handles at ${against}`; -} -if (against !== undefined && uncompared.length > 0) { - line += `; not compared: ${uncompared.sort().join(", ")}`; -} -console.log(line); -if (against !== undefined && uncompared.length > 0) { - console.log(`comparison against ${against} is not complete`); -} -if (against !== undefined && vacated.length > 0) { - console.log(`vacated since ${against}: ${vacated.join(", ")}`); -} From cc64b80ca653d6dbc18ed65a4151f41370fe38bc Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:46:03 -0500 Subject: [PATCH 2/5] feat!: cut and sharpen the org contract after red-team; GRADERS.md and WORKING.md split out CODING_STANDARDS.md drops the Former IDs table (now in the PR body), SF-SHP-3, -4 and -6, and restating Why lines; folds SF-IMP-2 into SF-IMP-1, SF-TST-3 into SF-TST-5 and SF-SHP-2 into SF-SHP-1; scopes SF-IMP-1 and -3; rewrites SF-GATE-5 (CI evidence, operational timeouts, owner's quoted order) and SF-SHP-8 (search org packages and skills first); adds SF-SHP-9 and a Maintaining section. SF-GATE-1, -3, -4 and -6 move to an on-demand GRADERS.md. WORKING.md holds how agents work (SF-WRK-1..5, SF-FIN-1) for consumers to import always-on. REVIEW.md: moved code is judged by what its new place creates, P1 blocks, P0 waived only by the owner's quoted order, one round per head with a verdict line, findings stay on the PR, no finding asks for a check. --- CODING_STANDARDS.md | 163 ++++++++++++++++---------------------------- GRADERS.md | 20 ++++++ README.md | 15 +++- REVIEW.md | 84 ++++++++++++----------- WORKING.md | 18 +++++ 5 files changed, 154 insertions(+), 146 deletions(-) create mode 100644 GRADERS.md create mode 100644 WORKING.md diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md index 878b107..851b556 100644 --- a/CODING_STANDARDS.md +++ b/CODING_STANDARDS.md @@ -3,8 +3,8 @@ Review criteria for every repository in the systemfsoftware organization. A repository vendors this repository with `git subtree` at `repos/constitution/`, and its own `CODING_STANDARDS.md` files add the rules only that repository -needs. A local rule may narrow a rule here, never loosen it. Cite a rule by its -ID, as `(SF-IMP-1)`. +needs. A repository's own rule wins for that repository, except that it cannot +loosen anything `REVIEW.md` rates P0. Cite a rule by its ID, as `(SF-IMP-1)`. Read every rule by its purpose: where its words and its harm part ways, the harm decides. @@ -15,25 +15,23 @@ Before you write or propose any test, make the wrong state impossible to build. A state the compiler refuses needs no test, and no later change can bring it back unnoticed. -- **SF-IMP-1** Close your types so an illegal value cannot be constructed: a - union of the valid combinations, a branded type for each role, a separate - service tag for each resource that must not be shared. Outside data becomes a - domain type only through a decode that returns a typed result, never through a - cast or a suppression comment. +- **SF-IMP-1** In typed code, close your types so an illegal value cannot be + constructed: a union of the valid combinations, a branded type for each role, + a separate service tag for each resource that must not be shared. Model + mutually exclusive states as a tagged union, one variant per state carrying + only its own fields; keep a plain nullable only for a value that is absent the + same way in every state. Outside data becomes a domain type only through a + decode that returns a typed result, never through a cast or a suppression + comment. Where a program in an untyped language reads outside data, it + validates that data at the boundary with a schema that fails. - Why: a value the type could have refused reaches runtime, and every check downstream trusts it. - 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. -- **SF-IMP-2** Model mutually exclusive states as a tagged union, one variant - per state carrying only its own fields. Keep a plain nullable only for a value - that is 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. -- **SF-IMP-3** Give every distinct failure its own tagged variant. - - Why: callers cannot branch on the real failure, and distinct errors collapse - into one case. +- **SF-IMP-3** In typed code, give every failure a caller handles differently + its own tagged variant, so callers can branch on the real failure. - **SF-IMP-4** The compiler is the evidence for such a fix. Wire the wrong state once on purpose, paste the compiler error into the PR body, and revert the wiring. Never commit that wiring as a test. @@ -41,10 +39,10 @@ back unnoticed. and costs a run every time. - **SF-IMP-5** Never write or propose an integration, end-to-end or microVM test for an invariant a type can hold: make the type hold it (`SF-IMP-1`). Runtime - tests are for what the compiler cannot prove (a decode of outside data, a - peer's answer, timing, what a real database or runtime does), at the lightest - tier that reaches that boundary, and a proposal for one names the behaviour it - covers. + tests are for what the compiler cannot prove: a decode of outside data, a + peer's answer, timing, what a real database or runtime does. Write them at the + lightest tier that reaches that boundary, and a proposal for one names the + behaviour it covers. - Why: those tests run for minutes on hosts every session shares, and they prove less than a compile error. @@ -59,19 +57,17 @@ back unnoticed. between two views, or a second implementation. - Why: a test that compares the code with itself cannot fail when the code is wrong. -- **SF-TST-3** Make every test able to fail when the behaviour it names breaks, - and see it fail once. - - Why: a suite that notices nothing certifies nothing, and a toothless test - hides among the ones that work. - **SF-TST-4** Judge outcomes, not steps. Assert what the system produced, never which functions ran, which lines a file holds, or which keys, entries or values the repository's own configuration lists. - Why: a test of steps or configuration breaks on every refactor and passes while the outcome is wrong. -- **SF-TST-5** A test whose assertion breaks these rules (it checks steps, - configuration or file layout, copies its expected value from the code, cannot - fail, or covers removed behaviour) is deleted, never rewritten, retitled or - replaced. Deleting a worthless test is welcome and is not lost coverage. A +- **SF-TST-5** Every test must be able to fail when the behaviour it names + breaks. A test whose assertion is defective (it checks steps, configuration or + file layout, copies its expected value from the code, cannot fail, or covers + removed behaviour) is deleted, never rewritten, retitled or replaced. A test + whose only fault is how it reaches the code (an internal import, a real clock) + is fixed. Deleting a worthless test is welcome and is not lost coverage. A test that keeps these rules and goes red found a defect: fix the code under test, never the test. - Why: a reshaped bad test keeps its cost and its false confidence; a weakened @@ -90,40 +86,31 @@ back unnoticed. ## Shape the code - **SF-SHP-1** Keep effects at the edges, as values: a pure step returns the - next read or write as data, and a thin shell performs it. - - Why: an effect inside a decision cannot be tested without the world it - touches. -- **SF-SHP-2** The shell imports the core, and every implementation is wired 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. -- **SF-SHP-3** Name every file and folder for its job; a name answers "of - what?". - - Why: a bucket named for a layer says nothing a reader can check, and one - change scatters across the tree. -- **SF-SHP-4** 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. + next read or write as data, and a thin shell performs it. The shell imports + the core, and every implementation is wired at one composition root; the core + never imports the shell, a database or a framework. + - Why: a decision chained to the world it touches cannot be tested or + replaced. - **SF-SHP-5** Fix the root cause; when the design is wrong, restructure it. Add no alias, fallback or compatibility shim nobody asked for. - Why: a patched symptom comes back, and every shim is a second path to keep correct. -- **SF-SHP-6** Justify every choice by these rules and the repository's own, - never by the file next to it or an earlier plan's wording. - - Why: an unexamined default hardens into a rule, and each copy seeds the - next. - **SF-SHP-7** Treat every line as a liability: delete, unify or make the bad state unconstructable before you add. A removal reaches every definition, call site and export in the same change. - Why: the codebase only grows, and two conventions standing is the next change imitating the wrong one. -- **SF-SHP-8** Prefer what the runtime, the lockfile and the organization's own - packages already provide. Add no patch, fork or override of a dependency; - change the design that needed it or fix it upstream. A PR that adds a - third-party dependency states its registry maintainers, publish provenance, - weekly downloads and three real dependents, each read from the primary source. - - Why: a patched dependency silently diverges on every upgrade, and an - unvetted one is a supply-chain hole. +- **SF-SHP-8** Before you write a client, a script, a test utility or a helper + another module could reuse, search the organization's packages and the + repository's skills for one. If one exists, use it or fix it there. A PR that + adds one names where it searched. Add no patch, fork or override of a + dependency; change the design that needed it or fix it upstream. + - Why: a second copy drifts from the first, and a patched dependency silently + diverges on every upgrade. +- **SF-SHP-9** Scripts are typed programs in the repository's typed language + (Deno or TypeScript where it has none), never shell beyond a wrapper that only + sets options and runs one command. + - Why: a shell script has no types and no tests, and fails silently. ## Secrets and public repositories @@ -138,62 +125,32 @@ back unnoticed. ## Checks and gates These apply to anything that grades work: lint rules, CI jobs, hooks, -thresholds, rubrics. +thresholds, rubrics. A change that builds or edits one also reads `GRADERS.md`. -- **SF-GATE-1** Bind each obligation through the strongest mechanism that can - carry it: the type system first, then a command that fails, then a refusal - before the call runs, and prose last. - - Why: prose orients and enforces nothing; a type error cannot be argued with. - **SF-GATE-2** Add a check only for a mistake it names, and key it on the failure itself (recomputed source, the compiler's verdict, the real outcome), never on names, line positions, formatting or a field the author supplied. When something fails, fix the failure; do not add a check beside it. - Why: brittle checks pile up, block correct work and still miss the mistake. -- **SF-GATE-3** A check asserts its input set: an empty corpus, an empty file - list or a missing input is a failure. - - Why: a check that cannot fail is a certificate, not enforcement. -- **SF-GATE-4** Decide which checks, tests and requirements apply to code 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. - **SF-GATE-5** A grader changes only in a change whose task is that grader, - observed failing before and passing after. Never edit, loosen or add to a - grader (a threshold, budget, glob, baseline, timeout, lint config, workflow or - rubric) so that in-flight work passes. + shown refusing a case it must refuse and passing the tree; a CI run is that + evidence where the check is too heavy to run locally. Never edit, loosen or + add to a grader (a threshold, budget, glob, baseline, lint config, workflow, + rubric, a `CODING_STANDARDS.md` or `REVIEW.md`, or a timeout a test or CI step + runs under) so that in-flight work passes. A timeout a program waits on a + network, database or peer at run time is not a grader. The one exception is + the owner's order, quoted in the PR body. - Why: whoever edits the grader reports the score they chose. -- **SF-GATE-6** Enroll a rule over a clean tree, at error: fix every live - violation first. No baseline, allowlist or warn level. - - Why: a baseline is suppression with a date on it, and a warning is noise - nobody reads. - -## Finish - -- **SF-FIN-1** Show evidence before you call work done: a command that passed, - the compiler error, or the state of the real system. - - Why: work called done on no evidence ships broken. - -## Former IDs - -The laws in the retired `CONSTITUTION.md` map here. Dated plans keep the old -IDs; read them through this table. - -| Former | Now | -| :--------------------------------------------------------- | :------------------------------------- | -| CONST-D1, CONST-B5 | SF-IMP-1 | -| CONST-D4 | SF-IMP-2 | -| CONST-D2 | SF-IMP-3 | -| CONST-B1, CONST-B2, CONST-B3, CONST-B6, CONST-P1, CONST-P2 | SF-SHP-1 | -| CONST-B4 | SF-SHP-2 | -| CONST-N1, CONST-N2 | SF-SHP-3 | -| CONST-N3 | SF-SHP-4 | -| CONST-S1 | SF-SHP-5 | -| CONST-S2 | SF-SHP-6 | -| CONST-S4, CONST-S3 | SF-SHP-7 | -| CONST-T8, CONST-T9, CONST-T14, CONST-T15 | SF-TST-1 | -| CONST-T10 | SF-TST-2 | -| CONST-T3, CONST-T13 | SF-TST-3 | -| CONST-T12, CONST-P3 | SF-GATE-4 | -| CONST-E7, CONST-E9 | SF-FIN-1, SF-GATE-5 | -| CONST-W1 | moved to each agent's own instructions | -| CONST-G3, CONST-G4, CONST-G5 | `REVIEW.md` | -| CONST-D3, CONST-W2, CONST-W3, and any other | retired | + +## Maintaining this file + +- A rule enters only when a review finding the author fixed, a fix commit or a + solution record shows the failure, no check covers it, and it holds in every + repository. State it as a condition a reviewer can see in a diff, with no + volatile numbers. Delete or merge before you add. +- IDs are permanent. A rule that is merged or retired leaves a gap; its number + is never reused. Retired so far: SF-IMP-2 into SF-IMP-1, SF-TST-3 into + SF-TST-5, SF-SHP-2 into SF-SHP-1; SF-SHP-3, SF-SHP-4 and SF-SHP-6 deleted; + SF-GATE-1, -3, -4 and -6 moved to `GRADERS.md`; SF-FIN-1 moved to + `WORKING.md`. +- How agents work, as distinct from what code looks like, goes in `WORKING.md`. diff --git a/GRADERS.md b/GRADERS.md new file mode 100644 index 0000000..358f475 --- /dev/null +++ b/GRADERS.md @@ -0,0 +1,20 @@ +# Graders + +Read this when a change builds or edits anything that grades work: a lint rule, +a CI job, a hook, a threshold, a rubric. `SF-GATE-2` and `SF-GATE-5` in +`CODING_STANDARDS.md` apply as well. + +- **SF-GATE-1** Bind each obligation through the strongest mechanism that can + carry it: the type system first, then a command that fails, then a refusal + before the call runs, and prose last. +- **SF-GATE-3** A check asserts its input set: an empty corpus, an empty file + list or a missing input is a failure. + - Why: a check that cannot fail is a certificate, not enforcement. +- **SF-GATE-4** Decide which checks, tests and requirements apply to code 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. +- **SF-GATE-6** Enroll a rule over a clean tree, at error: fix every live + violation first. No baseline, allowlist or warn level. + - Why: a baseline is suppression with a date on it, and a warning is noise + nobody reads. diff --git a/README.md b/README.md index acc5d5d..9405b67 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ rules. | :----------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- | | [CODING_STANDARDS.md](CODING_STANDARDS.md) | You plan, write, review or propose a test for code in any organization repository. It leads with "Impossible states first". | | [REVIEW.md](REVIEW.md) | You review a change or answer review findings: the finding bar, severities and evidence. | +| [GRADERS.md](GRADERS.md) | You build or change a check: a lint rule, CI job, hook, threshold or rubric. | +| [WORKING.md](WORKING.md) | Always: every repository imports it into its always-on `AGENTS.md` or `CLAUDE.md`. | | [`docs/solutions/`](docs/solutions) | You want the past problem behind a rule. | The files follow the `CODING_STANDARDS.md` and `REVIEW.md` model of the @@ -31,9 +33,16 @@ The files follow the `CODING_STANDARDS.md` and `REVIEW.md` model of the 3. Keep the repository's own rules in its own `CODING_STANDARDS.md` and `REVIEW.md`. A repository with no rules of its own may symlink its root `CODING_STANDARDS.md` to `repos/constitution/CODING_STANDARDS.md`. -4. Route agents to the files from the repository's `AGENTS.md` under the trigger - "you plan, write, review or propose a test". Do not `@`-import them into an - always-loaded file. +4. Route agents to the standards and review files from the repository's + `AGENTS.md` under the trigger "you plan, write, review or propose a test", + and to `GRADERS.md` under "you build or change a check". Do not `@`-import + those into an always-loaded file. +5. `@`-import `repos/constitution/WORKING.md` into the always-on `AGENTS.md` or + `CLAUDE.md`, on a line of its own. + +A repository with its own root `CODING_STANDARDS.md` receives the organization's +rules through the `REVIEW.md` include: review tools find standards files by +placement, so the vendored copy otherwise governs only `repos/constitution/`. Update the vendored copy with `git subtree pull --prefix repos/constitution https://github.com/systemfsoftware/constitution main --squash`. diff --git a/REVIEW.md b/REVIEW.md index b2b83ed..803375f 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -1,34 +1,32 @@ # Review instructions -How review behaves in every repository of the systemfsoftware organization. A -repository's root `REVIEW.md` includes this file and `CODING_STANDARDS.md` from -its vendored copy (`@repos/constitution/REVIEW.md`, -`@repos/constitution/CODING_STANDARDS.md`), and adds its own severities, checks -and exclusions below them. Where the two disagree, the repository's file wins -for that repository, except that it cannot lower a P0 defined here. +Review policy for every systemfsoftware repository. A repository's root +`REVIEW.md` includes this file and adds its own rules below. A repository's rule +wins for that repository, except that it cannot lower a P0 defined here. ## What counts as a finding File a finding only when all of these hold: -- It reproduces on the PR's current head, on a line the diff adds, edits, moves - or copies. That the violation existed before the change, or came over with - moved code, never lowers it. An issue only on untouched lines goes in - Coverage, not in the findings. -- It cites a rule from `CODING_STANDARDS.md` here, a repository - `CODING_STANDARDS.md`, or a compound pack the repository enrolls, and that - rule's stated scope covers the file. An author's personal or global - instruction file is never criteria. A runtime defect needs no rule. +- It reproduces on the PR's current head, and the diff introduced it. An issue + that moved or copied code already had is not introduced; list it under a + Coverage heading at the end of the review. A defect the new location creates + (a private name now in a public repository, I/O now inside the core, code now + reachable from a caller its guards did not expect) is introduced. +- It cites a rule from `CODING_STANDARDS.md` or `GRADERS.md` here, a repository + `CODING_STANDARDS.md`, or a compound pack the repository enrolls, and the file + is within the rule's scope; a rule that states no scope covers every file. An + author's personal or global instruction file is never criteria. A runtime + defect needs no rule. - It shows the rule's harm is present here, not only that its words match. Where a rule's letter and its purpose disagree, the purpose decides. -- The PR body does not record it as a deliberate tradeoff that names the rule. - If it does, contest the tradeoff instead of the line. -- It asks for a change to the lines the diff touches. A finding that only asks - for more coverage is not a finding. -- A finding that asks for a test names the behaviour no type can hold - (`SF-IMP-5`). A finding that asks for an integration, end-to-end or microVM - test of an invariant a type could hold is not a finding; ask for the type - instead. +- It asks for a change to lines the diff touches, to call sites the diff's own + removal or rename leaves stale, or to the PR's text and commit messages where + a rule governs them (`SF-SEC-1`, or a rule that requires the PR to state + something). No finding asks for more coverage, a new check, a guard or a lint. + A finding asks for a test only as the remedy for a defect in behaviour no type + can hold, and names that behaviour (`SF-IMP-5`); where a type could hold it, + the finding asks for the type. **Accretion.** On the second finding against the same block (a parser, a classifier, an allowlist, a guard, a prose rule), file one finding against how @@ -38,33 +36,39 @@ round. ## Severity -- **P0**: an illegal state a type could have refused (`SF-IMP-1` to `SF-IMP-3`) - in new or changed code; a grader edited or loosened so the change passes - (`SF-GATE-5`); a secret, or anything private in a public repository - (`SF-SEC-1`); data loss. While one stands, the change is not ready, whatever - else it fixes. -- **P1**: a runtime defect in behaviour a person or a deploy reaches; a - violation of any other rule in `CODING_STANDARDS.md` here or in the - repository; a test that breaks a test rule. A test that cannot fail is a - broken grader, so it blocks the merge, and its only remedy is deletion +- **P0** blocks the merge: an illegal state the diff makes constructable that a + type could have refused (`SF-IMP-1`); a grader edited or loosened so the + change passes (`SF-GATE-5`); a secret, or anything private in a public + repository (`SF-SEC-1`); data loss. +- **P1** blocks the merge: a runtime defect in behaviour a person or a deploy + reaches; a violation of a rule in `CODING_STANDARDS.md` or `GRADERS.md` here, + or in the repository's `CODING_STANDARDS.md` unless its `REVIEW.md` rates the + rule lower; a test with a defective assertion, whose only remedy is deletion (`SF-TST-5`). -- **P2 at most**: plans, `docs/solutions/`, PR bodies and other docs; test - structure no rule covers. These never block a merge. -- **P3**: style and naming. +- **P2** never blocks: plans, `docs/solutions/`, PR bodies and other docs; test + structure no rule covers. +- **P3** never blocks: style and naming. -A breach is legal only when the change itself declares it, naming the rule and -the case. A promise of a follow-up is not a declaration. +A change may declare a breach of a `CODING_STANDARDS.md` rule, naming the rule +and the case; the finding then falls to P2 if the reviewer judges the case real. +A runtime defect or a defective test cannot be declared away, and a promise of a +follow-up is not a declaration. The author never waives a P0; only the owner's +order, quoted in the PR body, does. ## Limits +- One review round per head. A later round files new findings only on lines + changed since the last reviewed head, and its verdict re-lists every earlier + P0 and P1 finding still unresolved. - Report at most five P3 findings per review. -- On a re-review, report P0 and P1 findings, plus any finding on lines changed - since the last reviewed head. Don't re-raise findings already recorded as - follow-ups. +- File findings on the PR, never as new issues. +- End every review with one verdict line: merge, or the P0 and P1 findings that + stop it. ## Do not report -- Anything CI already enforces: type errors, lint, formatting, commit messages. +- Anything CI enforces and ran on this head: type errors, lint, formatting, + commit-message format. - Anything under `repos/**`: vendored, updated only by `git subtree pull`. - Generated output and lockfiles, except to check a dependency change the PR states. diff --git a/WORKING.md b/WORKING.md new file mode 100644 index 0000000..760ac32 --- /dev/null +++ b/WORKING.md @@ -0,0 +1,18 @@ +# Working + +How every agent works in a systemfsoftware repository. A repository imports this +file into its always-on `AGENTS.md` or `CLAUDE.md`. A repository's own +instructions may narrow a rule here, never loosen it. + +- **SF-WRK-1** Deliver the whole task. Stop only when it is merged or in the + merge queue, or blocked by something only the owner holds; say which. +- **SF-WRK-2** Do reversible work without asking. A design or technical decision + you would ask the owner goes to Gemini; report its answer and proceed. +- **SF-WRK-3** Spawn no subagents unless the owner asked for them in this task. +- **SF-WRK-4** Run no full test suite, end-to-end or microVM run on a shared + host; CI runs them. +- **SF-WRK-5** Before a destructive or wide step, restate the instruction's verb + and object in one line and act on that, not on a nearby meaning. +- **SF-FIN-1** Call nothing done, blocked or broken without the output that + shows it: a command that passed, the compiler error, or the state of the real + system. From 82d14cdabff2ff49537f2438e068ce8df2a6ed5e Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:56:28 -0500 Subject: [PATCH 3/5] feat!: SF-IMP-4 commits a type-level assertion; only the owner's own review waives a P0; an owner-ordered grader change is its own PR --- CODING_STANDARDS.md | 26 +++++++++++++++++--------- REVIEW.md | 8 ++++++-- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md index 851b556..3e81714 100644 --- a/CODING_STANDARDS.md +++ b/CODING_STANDARDS.md @@ -22,8 +22,9 @@ back unnoticed. only its own fields; keep a plain nullable only for a value that is absent the same way in every state. Outside data becomes a domain type only through a decode that returns a typed result, never through a cast or a suppression - comment. Where a program in an untyped language reads outside data, it - validates that data at the boundary with a schema that fails. + comment, except the assertion `SF-IMP-4` names. Where a program in an untyped + language reads outside data, it validates that data at the boundary with a + schema that fails. - Why: a value the type could have refused reaches runtime, and every check downstream trusts it. - Wrong: a lock helper took a lock spec and a nullable adapter, so a spec that @@ -32,11 +33,17 @@ back unnoticed. impossible to construct. - **SF-IMP-3** In typed code, give every failure a caller handles differently its own tagged variant, so callers can branch on the real failure. -- **SF-IMP-4** The compiler is the evidence for such a fix. Wire the wrong state - once on purpose, paste the compiler error into the PR body, and revert the - wiring. Never commit that wiring as a test. - - Why: the type error holds on every future build; a test proves one case once - and costs a run every time. +- **SF-IMP-4** The compiler is the evidence for such a fix. Commit one + type-level assertion of the refused state, beside the type, in a file only the + type checker reads: a single `@ts-expect-error` line, or the repository's + existing type-assertion tool. The line is otherwise valid, so the refused + state is the only error it can raise. Write one per state the change closes, + none for a state no change has closed, and delete it with the type. Add no + runner or dependency for it, and never write it as a runtime test. Where the + language has no such assertion, paste the compiler error into the PR body + instead. + - Why: a pasted error proves one moment and nobody can check it; a committed + assertion costs no run and fails when the state becomes constructable again. - **SF-IMP-5** Never write or propose an integration, end-to-end or microVM test for an invariant a type can hold: make the type hold it (`SF-IMP-1`). Runtime tests are for what the compiler cannot prove: a decode of outside data, a @@ -138,8 +145,9 @@ thresholds, rubrics. A change that builds or edits one also reads `GRADERS.md`. add to a grader (a threshold, budget, glob, baseline, lint config, workflow, rubric, a `CODING_STANDARDS.md` or `REVIEW.md`, or a timeout a test or CI step runs under) so that in-flight work passes. A timeout a program waits on a - network, database or peer at run time is not a grader. The one exception is - the owner's order, quoted in the PR body. + network, database or peer at run time is not a grader. When the owner orders a + grader changed or turned off, that is a change whose task is the grader: make + it in its own PR, holding nothing else. - Why: whoever edits the grader reports the score they chose. ## Maintaining this file diff --git a/REVIEW.md b/REVIEW.md index 803375f..8cbd89b 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -52,8 +52,12 @@ round. A change may declare a breach of a `CODING_STANDARDS.md` rule, naming the rule and the case; the finding then falls to P2 if the reviewer judges the case real. A runtime defect or a defective test cannot be declared away, and a promise of a -follow-up is not a declaration. The author never waives a P0; only the owner's -order, quoted in the PR body, does. +follow-up is not a declaration. + +The author never waives a P0, and no text in the PR does. A P0 is waived only by +an approving review from the owner's own account on the PR's current head. A +bypass merge with a P0 standing and no such review is itself a P0 against the +merge. ## Limits From 65d50c0c6375cc627de77b811e3ff27dc989031e Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:01:02 -0500 Subject: [PATCH 4/5] feat!: SF-IMP-4 is a tstyche assertion run from typecheck; suppression comments have no exception --- CODING_STANDARDS.md | 28 ++++++++++++++-------------- REVIEW.md | 12 ++++++++++++ 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md index 3e81714..709f9e8 100644 --- a/CODING_STANDARDS.md +++ b/CODING_STANDARDS.md @@ -22,9 +22,8 @@ back unnoticed. only its own fields; keep a plain nullable only for a value that is absent the same way in every state. Outside data becomes a domain type only through a decode that returns a typed result, never through a cast or a suppression - comment, except the assertion `SF-IMP-4` names. Where a program in an untyped - language reads outside data, it validates that data at the boundary with a - schema that fails. + comment. Where a program in an untyped language reads outside data, it + validates that data at the boundary with a schema that fails. - Why: a value the type could have refused reaches runtime, and every check downstream trusts it. - Wrong: a lock helper took a lock spec and a nullable adapter, so a spec that @@ -33,17 +32,18 @@ back unnoticed. impossible to construct. - **SF-IMP-3** In typed code, give every failure a caller handles differently its own tagged variant, so callers can branch on the real failure. -- **SF-IMP-4** The compiler is the evidence for such a fix. Commit one - type-level assertion of the refused state, beside the type, in a file only the - type checker reads: a single `@ts-expect-error` line, or the repository's - existing type-assertion tool. The line is otherwise valid, so the refused - state is the only error it can raise. Write one per state the change closes, - none for a state no change has closed, and delete it with the type. Add no - runner or dependency for it, and never write it as a runtime test. Where the - language has no such assertion, paste the compiler error into the PR body - instead. - - Why: a pasted error proves one moment and nobody can check it; a committed - assertion costs no run and fails when the state becomes constructable again. +- **SF-IMP-4** The compiler is the evidence for such a fix. Commit one tstyche + assertion that the refused state is refused, in the package's `test-types/`, + run by its `typecheck` script (`tsc -b && tstyche`) and never by its tests. + Use `expect().type.not.toBeAssignableTo()` (or + `not.toBeAssignableFrom`); use `toRaiseError` only where no assignability pair + expresses the refusal (an overload, an inference failure, a missing service), + and always with the expected message. Import both types from the package's own + exports. Write one per state the change closes, and delete it with the type. + Where the language has no such tool, paste the compiler error into the PR + body. + - Why: it costs no test run, fails when the state becomes constructable again, + and passes for that reason only. - **SF-IMP-5** Never write or propose an integration, end-to-end or microVM test for an invariant a type can hold: make the type hold it (`SF-IMP-1`). Runtime tests are for what the compiler cannot prove: a decode of outside data, a diff --git a/REVIEW.md b/REVIEW.md index 8cbd89b..eb5a172 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -69,6 +69,18 @@ merge. - End every review with one verdict line: merge, or the P0 and P1 findings that stop it. +## Always check + +Each of these is a P1 against an `SF-IMP-4` assertion: + +- more than one assertion per closed state; +- `Bad` or `Good` redeclared inside the `.tst.ts` file; +- `@ts-expect-error`, `any` or `as` inside it; +- a package with `test-types/` whose `typecheck` does not run tstyche; +- a runtime test added for a state the compiler already closes. + +These files count toward no coverage figure. + ## Do not report - Anything CI enforces and ran on this head: type errors, lint, formatting, From b0275c2206c6fe3e88099d0a4c67ef598815f871 Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:16:47 -0500 Subject: [PATCH 5/5] docs: tighten the org contract for agents, rewrite README for people, and let SF-IMP-4 assertions import internal types by relative path Gemini's plain-English pass, tightened under the pre-rewrite word counts, with owner-ruled passages kept word for word. README is rewritten for human readers per the write-readme-md skill. SF-IMP-4 (option B, ruled by Fable and Gemini): the assertion lives in test-types/ and imports a published type by package name or an internal one by a relative path into src/; no export, subpath or imports map is added for it. SF-TST-1 exempts SF-IMP-4 assertions. REVIEW.md checks for an export whose only importer is a .tst.ts file. --- CODING_STANDARDS.md | 267 ++++++++++++++++++++++---------------------- GRADERS.md | 34 +++--- README.md | 86 ++++++++------ REVIEW.md | 124 ++++++++++---------- WORKING.md | 31 ++--- 5 files changed, 277 insertions(+), 265 deletions(-) diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md index 709f9e8..adeea0d 100644 --- a/CODING_STANDARDS.md +++ b/CODING_STANDARDS.md @@ -1,164 +1,161 @@ # Coding Standards -Review criteria for every repository in the systemfsoftware organization. A -repository vendors this repository with `git subtree` at `repos/constitution/`, -and its own `CODING_STANDARDS.md` files add the rules only that repository -needs. A repository's own rule wins for that repository, except that it cannot -loosen anything `REVIEW.md` rates P0. Cite a rule by its ID, as `(SF-IMP-1)`. +Review criteria for every repository in systemfsoftware. Repositories vendor +this repo via `git subtree` at `repos/constitution/`. Local +`CODING_STANDARDS.md` files add repo-specific rules that take local precedence, +except that they cannot loosen anything `REVIEW.md` rates P0. Cite rules by ID, +such as `(SF-IMP-1)`. -Read every rule by its purpose: where its words and its harm part ways, the harm -decides. +Apply each rule by its purpose. Where wording and harm disagree, harm decides. ## Impossible states first -Before you write or propose any test, make the wrong state impossible to build. -A state the compiler refuses needs no test, and no later change can bring it -back unnoticed. - -- **SF-IMP-1** In typed code, close your types so an illegal value cannot be - constructed: a union of the valid combinations, a branded type for each role, - a separate service tag for each resource that must not be shared. Model - mutually exclusive states as a tagged union, one variant per state carrying - only its own fields; keep a plain nullable only for a value that is absent the - same way in every state. Outside data becomes a domain type only through a - decode that returns a typed result, never through a cast or a suppression - comment. Where a program in an untyped language reads outside data, it - validates that data at the boundary with a schema that fails. - - Why: a value the type could have refused reaches runtime, and every check - downstream trusts it. - - 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. -- **SF-IMP-3** In typed code, give every failure a caller handles differently - its own tagged variant, so callers can branch on the real failure. +Make invalid states impossible to construct before writing or proposing a test. +A state the compiler refuses needs no test and cannot return unnoticed. + +- **SF-IMP-1** In typed code, close types so illegal values cannot be + constructed: use a union of valid combinations, a branded type per role, or a + separate service tag per unshared resource. Model mutually exclusive states as + a tagged union where each variant holds only its own fields. Use a plain + nullable type only when a value is absent the same way in every state. Parse + external data into domain types only via a decoder returning a typed result, + never a cast or suppression comment. In untyped languages, validate external + data at the boundary with a schema that fails on invalid input. + - Why: an illegal value the compiler could have rejected reaches runtime, + where downstream code trusts it. + - Wrong: a lock helper accepted a lock spec and a nullable adapter, so a spec + requiring a lock with no adapter ran its body unlocked. + - Right: a single union of valid spec-and-adapter pairs made the unlocked + state impossible to construct. +- **SF-IMP-3** In typed code, give each failure a caller handles differently its + own tagged variant so callers can branch on it. - **SF-IMP-4** The compiler is the evidence for such a fix. Commit one tstyche - assertion that the refused state is refused, in the package's `test-types/`, - run by its `typecheck` script (`tsc -b && tstyche`) and never by its tests. - Use `expect().type.not.toBeAssignableTo()` (or + assertion that the refused state is refused. Put it in the package's + `test-types/`, run by its `typecheck` script and never by its tests. Use + `expect().type.not.toBeAssignableTo()` (or `not.toBeAssignableFrom`); use `toRaiseError` only where no assignability pair expresses the refusal (an overload, an inference failure, a missing service), - and always with the expected message. Import both types from the package's own - exports. Write one per state the change closes, and delete it with the type. + and always with the expected message. Import the real types: a published type + by the package's name, an internal one by a relative path into `src/`. Never + add or widen an export, subpath or imports map so an assertion can reach a + type. Write one per state the change closes, and delete it with the type. Where the language has no such tool, paste the compiler error into the PR body. - Why: it costs no test run, fails when the state becomes constructable again, and passes for that reason only. -- **SF-IMP-5** Never write or propose an integration, end-to-end or microVM test - for an invariant a type can hold: make the type hold it (`SF-IMP-1`). Runtime - tests are for what the compiler cannot prove: a decode of outside data, a - peer's answer, timing, what a real database or runtime does. Write them at the - lightest tier that reaches that boundary, and a proposal for one names the - behaviour it covers. - - Why: those tests run for minutes on hosts every session shares, and they - prove less than a compile error. +- **SF-IMP-5** Never write or propose an integration, end-to-end, or microVM + test for an invariant a type can enforce; enforce it in types (`SF-IMP-1`). + Test at runtime only behaviour the compiler cannot prove (decoding external + data, peer responses, timing, or database and runtime behaviour). Run tests at + the lightest tier reaching that boundary and name the covered behaviour in any + test proposal. + - Why: slow tests tie up shared hosts while proving less than a compile error. ## Tests -- **SF-TST-1** Test the published surface with real inputs and outputs: what a - consumer imports or calls, never the package's internals. - - Why: a test that stops short of what ships stays green while the shipped +- **SF-TST-1** Test the published surface with real inputs and outputs, using + only what consumers import or call, never package internals. A type assertion + under `SF-IMP-4` is not a test and may import internal types. + - Why: tests bypassing the published interface can pass when the shipped artifact is broken. -- **SF-TST-2** Take every expected value from an oracle the code under test did - not produce: a literal from the requirement, 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 +- **SF-TST-2** Derive expected values from an oracle independent of the code + under test (requirement literal, independent fixture, law between two views, + or second implementation). + - Why: comparing code against its own output cannot fail when the code is wrong. -- **SF-TST-4** Judge outcomes, not steps. Assert what the system produced, never - which functions ran, which lines a file holds, or which keys, entries or - values the repository's own configuration lists. - - Why: a test of steps or configuration breaks on every refactor and passes - while the outcome is wrong. -- **SF-TST-5** Every test must be able to fail when the behaviour it names - breaks. A test whose assertion is defective (it checks steps, configuration or - file layout, copies its expected value from the code, cannot fail, or covers - removed behaviour) is deleted, never rewritten, retitled or replaced. A test - whose only fault is how it reaches the code (an internal import, a real clock) - is fixed. Deleting a worthless test is welcome and is not lost coverage. A - test that keeps these rules and goes red found a defect: fix the code under - test, never the test. - - Why: a reshaped bad test keeps its cost and its false confidence; a weakened - good test hides the defect it found. -- **SF-TST-6** A unit test is deterministic and isolated: no child process, real - clock, network, host port, host file system or state shared with another test. - I/O belongs to an adapter's tests, run where the repository's testing rules - say. - - Why: a test that spawns processes or sleeps stalls the machine it runs on - and fails by timing, not by defect. -- **SF-TST-7** A property test that times out is a design failure. Fix the - schema it draws from, or delete the test if it is a scenario dressed as a - property. Never raise its timeout, cut its runs or narrow its generator. - - Why: a tuned budget hides a schema that admits values the domain does not. +- **SF-TST-4** Assert outcomes, not internal steps: verify what the system + produced, never which functions ran, which lines a file contains, or which + keys, entries, or values repo configuration lists. + - Why: tests coupled to steps or configuration break on refactoring and still + pass when outcomes are wrong. +- **SF-TST-5** Every test must fail when its named behaviour breaks. Delete any + test with a defective assertion (checking steps, configuration, or file + layout; copying expected values from code; unable to fail; or covering removed + behaviour); never rewrite, retitle, or replace it. Fix a test whose only fault + is how it reaches the code (an internal import or real clock). Deleting a + worthless test is welcome and does not count as lost coverage. When a valid + test fails, fix the code under test, not the test. + - Why: reshaping a bad test keeps its cost and false confidence; weakening a + good test hides defects. +- **SF-TST-6** Keep unit tests deterministic and isolated: no child processes, + real clocks, network calls, host ports, host file system, or shared state + across tests. Put I/O tests in adapter suites and run them where repo testing + rules specify. + - Why: tests that spawn processes or sleep stall the host and fail on timing + rather than code defects. +- **SF-TST-7** Treat a property-test timeout as a design failure. Fix its input + schema, or delete the test if it encodes one specific scenario. Never raise + its timeout, lower its run count, or narrow its generator. + - Why: tuning the budget hides a schema generating out-of-domain values. ## Shape the code -- **SF-SHP-1** Keep effects at the edges, as values: a pure step returns the - next read or write as data, and a thin shell performs it. The shell imports - the core, and every implementation is wired at one composition root; the core - never imports the shell, a database or a framework. - - Why: a decision chained to the world it touches cannot be tested or - replaced. -- **SF-SHP-5** Fix the root cause; when the design is wrong, restructure it. Add - no alias, fallback or compatibility shim nobody asked for. - - Why: a patched symptom comes back, and every shim is a second path to keep - correct. -- **SF-SHP-7** Treat every line as a liability: delete, unify or make the bad - state unconstructable before you add. A removal reaches every definition, call - site and export in the same change. - - Why: the codebase only grows, and two conventions standing is the next - change imitating the wrong one. -- **SF-SHP-8** Before you write a client, a script, a test utility or a helper - another module could reuse, search the organization's packages and the - repository's skills for one. If one exists, use it or fix it there. A PR that - adds one names where it searched. Add no patch, fork or override of a +- **SF-SHP-1** Keep side effects at the edges: a pure core returns the next read + or write as data, and a thin shell executes it. The shell imports the core, + and one composition root wires all implementations. The core never imports the + shell, a database, or a framework. + - Why: decision logic coupled to side effects cannot be tested or replaced in + isolation. +- **SF-SHP-5** Fix the root cause of defects; restructure wrong underlying + designs. Never add unrequested aliases, fallbacks, or compatibility shims. + - Why: patching symptoms lets defects return, and each shim adds a second code + path to maintain. +- **SF-SHP-7** Every line of code is a liability. Delete dead code, unify + duplicate paths, or make invalid states unconstructable before adding code. + When removing something, delete every definition, call site, and export in the + same PR. + - Why: unused code or competing conventions lead future PRs to imitate the + wrong pattern. +- **SF-SHP-8** Before writing a client, script, test utility, or helper, search + org packages and repo skills for an existing one; use or fix it in place. Name + where you searched in any PR adding a helper. Never patch, fork, or override a dependency; change the design that needed it or fix it upstream. - - Why: a second copy drifts from the first, and a patched dependency silently - diverges on every upgrade. -- **SF-SHP-9** Scripts are typed programs in the repository's typed language - (Deno or TypeScript where it has none), never shell beyond a wrapper that only - sets options and runs one command. - - Why: a shell script has no types and no tests, and fails silently. + - Why: duplicate helpers drift out of sync, and patched dependencies silently + diverge on upgrade. +- **SF-SHP-9** Write scripts in the repo's typed language, or in Deno or + TypeScript if it has none. Use shell scripts only as thin wrappers setting + options and running one command. + - Why: shell scripts lack type checking and tests, and fail silently. ## Secrets and public repositories -- **SF-SEC-1** Commit no secret, token or credential. A public repository - receives nothing from a private one: no private repository, package or product - name, local path, host, person, email, private run ID or link, issue-tracker - ID, or internal agent or process name, in files, fixtures, commit messages, PR - text or comments. - - Why: a leaked secret must be rotated everywhere it reached, and a private - name in public history cannot be taken back. - -## Checks and gates - -These apply to anything that grades work: lint rules, CI jobs, hooks, -thresholds, rubrics. A change that builds or edits one also reads `GRADERS.md`. - -- **SF-GATE-2** Add a check only for a mistake it names, and key it on the - failure itself (recomputed source, the compiler's verdict, the real outcome), - never on names, line positions, formatting or a field the author supplied. - When something fails, fix the failure; do not add a check beside it. - - Why: brittle checks pile up, block correct work and still miss the mistake. -- **SF-GATE-5** A grader changes only in a change whose task is that grader, - shown refusing a case it must refuse and passing the tree; a CI run is that - evidence where the check is too heavy to run locally. Never edit, loosen or - add to a grader (a threshold, budget, glob, baseline, lint config, workflow, - rubric, a `CODING_STANDARDS.md` or `REVIEW.md`, or a timeout a test or CI step - runs under) so that in-flight work passes. A timeout a program waits on a - network, database or peer at run time is not a grader. When the owner orders a - grader changed or turned off, that is a change whose task is the grader: make - it in its own PR, holding nothing else. +- **SF-SEC-1** Never commit secrets, tokens, or credentials. Never put anything + from a private repo into a public repo across files, fixtures, commit + messages, PR text, or comments: private repo, package, or product names, local + paths, hosts, people, emails, private run IDs or links, issue-tracker IDs, or + internal agent or process names. + - Why: leaked secrets require rotation everywhere, and private names in public + git history cannot be erased. + +## Graders and gates + +Applies to graders (lint rules, CI jobs, hooks, thresholds, rubrics). Read +`GRADERS.md` when building or editing a grader. + +- **SF-GATE-2** Add a grader only for a named mistake. Key it on the failure + itself (recomputed source, compiler verdict, or real outcome), never on names, + line positions, formatting, or author-supplied fields. Fix underlying failures + instead of adding graders beside them. + - Why: brittle graders pile up, block valid work, and still miss the + underlying mistake. +- **SF-GATE-5** Edit a grader only in a PR whose task is that grader, proving it + refuses a failing case and passes the clean tree (use a CI run when too heavy + to run locally). Never edit, loosen, or add to a grader so in-flight work + passes. Graders include thresholds, budgets, globs, baselines, lint configs, + workflows, rubrics, `CODING_STANDARDS.md`, `REVIEW.md`, and test or CI + timeouts, but not runtime timeouts waiting on a network, database, or peer. + When the owner orders a grader changed or turned off, that is a change whose + task is the grader: make it in its own PR, holding nothing else. - Why: whoever edits the grader reports the score they chose. ## Maintaining this file -- A rule enters only when a review finding the author fixed, a fix commit or a - solution record shows the failure, no check covers it, and it holds in every - repository. State it as a condition a reviewer can see in a diff, with no - volatile numbers. Delete or merge before you add. -- IDs are permanent. A rule that is merged or retired leaves a gap; its number - is never reused. Retired so far: SF-IMP-2 into SF-IMP-1, SF-TST-3 into - SF-TST-5, SF-SHP-2 into SF-SHP-1; SF-SHP-3, SF-SHP-4 and SF-SHP-6 deleted; - SF-GATE-1, -3, -4 and -6 moved to `GRADERS.md`; SF-FIN-1 moved to - `WORKING.md`. -- How agents work, as distinct from what code looks like, goes in `WORKING.md`. +- Add a rule only when a fixed review finding, fix commit, or solution record + demonstrates the failure, no grader covers it, and it holds in every repo. + State rules as diff-visible conditions without volatile numbers. Delete or + merge existing rules before adding a new one. +- Rule IDs are permanent; gaps are never reused. Retired: SF-IMP-2 (merged into + SF-IMP-1), SF-TST-3 (merged into SF-TST-5), SF-SHP-2 (merged into SF-SHP-1). + Deleted: SF-SHP-3, SF-SHP-4, SF-SHP-6. Moved: SF-GATE-1, SF-GATE-3, SF-GATE-4, + SF-GATE-6 to `GRADERS.md`; SF-FIN-1 to `WORKING.md`. +- Put agent workflow rules, rather than code rules, in `WORKING.md`. diff --git a/GRADERS.md b/GRADERS.md index 358f475..9c386f6 100644 --- a/GRADERS.md +++ b/GRADERS.md @@ -1,20 +1,20 @@ # Graders -Read this when a change builds or edits anything that grades work: a lint rule, -a CI job, a hook, a threshold, a rubric. `SF-GATE-2` and `SF-GATE-5` in -`CODING_STANDARDS.md` apply as well. +Read this when building or editing a grader (lint rule, CI job, hook, threshold, +or rubric). `SF-GATE-2` and `SF-GATE-5` in `CODING_STANDARDS.md` also apply. -- **SF-GATE-1** Bind each obligation through the strongest mechanism that can - carry it: the type system first, then a command that fails, then a refusal - before the call runs, and prose last. -- **SF-GATE-3** A check asserts its input set: an empty corpus, an empty file - list or a missing input is a failure. - - Why: a check that cannot fail is a certificate, not enforcement. -- **SF-GATE-4** Decide which checks, tests and requirements apply to code 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. -- **SF-GATE-6** Enroll a rule over a clean tree, at error: fix every live - violation first. No baseline, allowlist or warn level. - - Why: a baseline is suppression with a date on it, and a warning is noise - nobody reads. +- **SF-GATE-1** Enforce each obligation with the strongest available mechanism: + type system first, failing command second, pre-call refusal third, prose + documentation last. +- **SF-GATE-3** Assert that the grader's input set is non-empty; treat an empty + corpus, empty file list, or missing input as a failure. + - Why: a grader that cannot fail is a certificate, not enforcement. +- **SF-GATE-4** Determine which graders, tests, and requirements apply to code + by what it is and does, never its name or file path. + - Why: relying on names or paths causes a rename or move to drop a requirement + or apply it to the wrong code. +- **SF-GATE-6** Enable a new grader rule at error severity over a clean tree by + fixing all existing violations first, without baselines, allowlists, or + warning levels. + - Why: baselines are temporary suppression, and warnings are noise nobody + reads. diff --git a/README.md b/README.md index 9405b67..00c8e23 100644 --- a/README.md +++ b/README.md @@ -2,50 +2,68 @@ [![License: Apache 2.0](https://img.shields.io/badge/license-Apache_2.0-blue?style=flat-square)](LICENSE) -The shared coding standards and review policy for System F Software. Every -repository in the organization vendors this one and is reviewed against the same -rules. +This repository holds an organization's shared coding standards and review +policy. Every repository in the organization vendors it with `git subtree` so +that engineers and review tools check changes against the same rules. + +Keeping these files in one place gives every project a common baseline for +writing code, reviewing changes, building automated checks, and guiding coding +agents. ## What is here -| File | Read it when | -| :----------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- | -| [CODING_STANDARDS.md](CODING_STANDARDS.md) | You plan, write, review or propose a test for code in any organization repository. It leads with "Impossible states first". | -| [REVIEW.md](REVIEW.md) | You review a change or answer review findings: the finding bar, severities and evidence. | -| [GRADERS.md](GRADERS.md) | You build or change a check: a lint rule, CI job, hook, threshold or rubric. | -| [WORKING.md](WORKING.md) | Always: every repository imports it into its always-on `AGENTS.md` or `CLAUDE.md`. | -| [`docs/solutions/`](docs/solutions) | You want the past problem behind a rule. | +| File | Read it when | +| :----------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [CODING_STANDARDS.md](CODING_STANDARDS.md) | You plan, write, review, or propose a test for code in any organization repository. It holds the review criteria and leads with "Impossible states first". | +| [REVIEW.md](REVIEW.md) | You review a change or respond to review findings. It defines the review policy, including the finding bar, severities, and evidence. | +| [GRADERS.md](GRADERS.md) | You build or change an automated check, such as a lint rule, CI job, hook, threshold, or rubric. | +| [WORKING.md](WORKING.md) | Always. It describes how agents work, and every repository imports it into its always-on `AGENTS.md` or `CLAUDE.md`. | +| [`docs/solutions/`](docs/solutions) | You want to read the past problem behind a rule. | -The files follow the `CODING_STANDARDS.md` and `REVIEW.md` model of the -[Compound Engineering plugin](https://github.com/EveryInc/compound-engineering-plugin): -`ce-code-review` and Claude Code Review read them as criteria and review policy. +These files follow the `CODING_STANDARDS.md` and `REVIEW.md` model from the +[Compound Engineering plugin](https://github.com/EveryInc/compound-engineering-plugin). +Both `ce-code-review` and Claude Code Review read them directly as review +criteria and review policy. -## Use it in a repository +## How to adopt it -1. Vendor this repository with `git subtree` at `repos/constitution/`. -2. In the repository's root `REVIEW.md`, include both files, each on its own - line: +1. Vendor this repository into your project at `repos/constitution/` using + `git subtree`. +2. Add both shared files to your repository's root `REVIEW.md`, each on a line + of its own: - ```markdown - @repos/constitution/CODING_STANDARDS.md @repos/constitution/REVIEW.md + ```text + @repos/constitution/CODING_STANDARDS.md + @repos/constitution/REVIEW.md ``` -3. Keep the repository's own rules in its own `CODING_STANDARDS.md` and - `REVIEW.md`. A repository with no rules of its own may symlink its root +3. Keep repository-specific rules in your own root `CODING_STANDARDS.md` and + `REVIEW.md`. If your repository has no rules of its own, symlink its root `CODING_STANDARDS.md` to `repos/constitution/CODING_STANDARDS.md`. -4. Route agents to the standards and review files from the repository's - `AGENTS.md` under the trigger "you plan, write, review or propose a test", - and to `GRADERS.md` under "you build or change a check". Do not `@`-import - those into an always-loaded file. -5. `@`-import `repos/constitution/WORKING.md` into the always-on `AGENTS.md` or - `CLAUDE.md`, on a line of its own. - -A repository with its own root `CODING_STANDARDS.md` receives the organization's -rules through the `REVIEW.md` include: review tools find standards files by -placement, so the vendored copy otherwise governs only `repos/constitution/`. - -Update the vendored copy with -`git subtree pull --prefix repos/constitution https://github.com/systemfsoftware/constitution main --squash`. +4. Route agents to the shared files from your repository's `AGENTS.md`. Point + them to `CODING_STANDARDS.md` and `REVIEW.md` under the trigger "you plan, + write, review or propose a test", and to `GRADERS.md` under "you build or + change a check". Do not `@`-import those files into an always-loaded file. +5. Import `repos/constitution/WORKING.md` into your always-on `AGENTS.md` or + `CLAUDE.md` on a line of its own: + + ```text + @repos/constitution/WORKING.md + ``` + +> [!NOTE] +> If a repository has its own root `CODING_STANDARDS.md`, it still receives the +> organization's rules through the `REVIEW.md` include. Review tools locate +> standards files by placement, so the vendored copy in `repos/constitution/` +> otherwise governs only `repos/constitution/`. + +## Update the vendored copy + +Pull the latest rules into a repository that already vendors them: + +```bash +git subtree pull --prefix repos/constitution https://github.com/systemfsoftware/constitution main --squash +``` ## Contributing diff --git a/REVIEW.md b/REVIEW.md index eb5a172..be60bb2 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -1,58 +1,52 @@ # Review instructions -Review policy for every systemfsoftware repository. A repository's root -`REVIEW.md` includes this file and adds its own rules below. A repository's rule -wins for that repository, except that it cannot lower a P0 defined here. +Review policy for every systemfsoftware repo. A repo's root `REVIEW.md` includes +this file and adds local rules below it. Local rules override rules here +locally, except they cannot lower a P0 severity. ## What counts as a finding -File a finding only when all of these hold: - -- It reproduces on the PR's current head, and the diff introduced it. An issue - that moved or copied code already had is not introduced; list it under a - Coverage heading at the end of the review. A defect the new location creates - (a private name now in a public repository, I/O now inside the core, code now - reachable from a caller its guards did not expect) is introduced. -- It cites a rule from `CODING_STANDARDS.md` or `GRADERS.md` here, a repository - `CODING_STANDARDS.md`, or a compound pack the repository enrolls, and the file - is within the rule's scope; a rule that states no scope covers every file. An - author's personal or global instruction file is never criteria. A runtime - defect needs no rule. -- It shows the rule's harm is present here, not only that its words match. Where - a rule's letter and its purpose disagree, the purpose decides. -- It asks for a change to lines the diff touches, to call sites the diff's own - removal or rename leaves stale, or to the PR's text and commit messages where - a rule governs them (`SF-SEC-1`, or a rule that requires the PR to state - something). No finding asks for more coverage, a new check, a guard or a lint. - A finding asks for a test only as the remedy for a defect in behaviour no type - can hold, and names that behaviour (`SF-IMP-5`); where a type could hold it, - the finding asks for the type. - -**Accretion.** On the second finding against the same block (a parser, a -classifier, an allowlist, a guard, a prose rule), file one finding against how -the block is represented instead: the condition restated, the boundary changed, -or a decision for the owner. Each case patched into such a block buys one more -round. +File a finding only when all hold: + +- The issue reproduces on the PR's current head and was introduced by the diff. + List pre-existing issues in moved or copied code under a Coverage heading at + the end. Defects created by the new location count as introduced (private + names moved to a public repo, or newly reachable unguarded code). +- The finding cites a rule from `CODING_STANDARDS.md` or `GRADERS.md` here, a + repo's `CODING_STANDARDS.md`, or an enrolled compound pack, and the file is in + scope (unscoped rules cover all files). Never cite personal or global + instructions. Runtime defects need no citation. +- The rule's harm is present, not merely a wording match. Where wording and + purpose disagree, purpose decides. +- The finding requests changes to diff-touched lines, stale call sites from + removal or rename, or PR text and commit messages governed by a rule + (`SF-SEC-1`, or a rule that requires the PR to state something). Never request + test coverage, a new grader, a guard, or a lint rule. Request a test only for + a defect in behaviour no type can enforce, naming it (`SF-IMP-5`); otherwise + request the type. + +**Accretion.** On a second finding against the same block (parser, classifier, +allowlist, guard, or prose rule), file one finding against its representation: +propose restating the condition, changing the boundary, or escalating to the +owner rather than patching cases. ## Severity -- **P0** blocks the merge: an illegal state the diff makes constructable that a - type could have refused (`SF-IMP-1`); a grader edited or loosened so the - change passes (`SF-GATE-5`); a secret, or anything private in a public - repository (`SF-SEC-1`); data loss. -- **P1** blocks the merge: a runtime defect in behaviour a person or a deploy - reaches; a violation of a rule in `CODING_STANDARDS.md` or `GRADERS.md` here, - or in the repository's `CODING_STANDARDS.md` unless its `REVIEW.md` rates the - rule lower; a test with a defective assertion, whose only remedy is deletion - (`SF-TST-5`). -- **P2** never blocks: plans, `docs/solutions/`, PR bodies and other docs; test - structure no rule covers. -- **P3** never blocks: style and naming. - -A change may declare a breach of a `CODING_STANDARDS.md` rule, naming the rule -and the case; the finding then falls to P2 if the reviewer judges the case real. -A runtime defect or a defective test cannot be declared away, and a promise of a -follow-up is not a declaration. +- **P0** blocks the merge: an illegal state made constructable by the diff that + a type could refuse (`SF-IMP-1`), a grader edited or loosened to pass + (`SF-GATE-5`), a secret or private detail in a public repo (`SF-SEC-1`), or + data loss. +- **P1** blocks the merge: a runtime defect reachable by a person or deploy, a + rule violation in `CODING_STANDARDS.md` or `GRADERS.md` here, a rule violation + in the repo's `CODING_STANDARDS.md` unless its `REVIEW.md` lowers severity, or + a test with a defective assertion requiring deletion (`SF-TST-5`). +- **P2** never blocks the merge: plans, `docs/solutions/`, PR bodies, other + docs, and unruled test structure. +- **P3** never blocks the merge: style and naming. + +A PR may declare an intentional breach of a `CODING_STANDARDS.md` rule by naming +the rule and case; it drops to P2 if judged real. Runtime defects and defective +tests cannot be declared away; promising a follow-up is not a declaration. The author never waives a P0, and no text in the PR does. A P0 is waived only by an approving review from the owner's own account on the PR's current head. A @@ -61,20 +55,22 @@ merge. ## Limits -- One review round per head. A later round files new findings only on lines - changed since the last reviewed head, and its verdict re-lists every earlier - P0 and P1 finding still unresolved. -- Report at most five P3 findings per review. -- File findings on the PR, never as new issues. -- End every review with one verdict line: merge, or the P0 and P1 findings that - stop it. +- Run one review round per commit head. On later heads, file new findings only + on lines changed since the last reviewed head, and re-list unresolved P0 and + P1 findings in the verdict. +- Report at most five P3 findings. +- File findings on the PR, never as separate issues. +- End every review with one verdict line: `merge`, or unresolved P0 and P1 + findings blocking merge. ## Always check Each of these is a P1 against an `SF-IMP-4` assertion: - more than one assertion per closed state; -- `Bad` or `Good` redeclared inside the `.tst.ts` file; +- `Bad` or `Good` redeclared inside the `.tst.ts` file instead of imported; +- an export, subpath or imports-map entry whose only importer is a `.tst.ts` + file; - `@ts-expect-error`, `any` or `as` inside it; - a package with `test-types/` whose `typecheck` does not run tstyche; - a runtime test added for a state the compiler already closes. @@ -83,15 +79,15 @@ These files count toward no coverage figure. ## Do not report -- Anything CI enforces and ran on this head: type errors, lint, formatting, - commit-message format. -- Anything under `repos/**`: vendored, updated only by `git subtree pull`. -- Generated output and lockfiles, except to check a dependency change the PR - states. +- Issues CI enforces and already ran on this head (type errors, lint, + formatting, commit format). +- Files under `repos/**` (vendored, updated only via `git subtree pull`). +- Generated output and lockfiles, except when verifying a PR-stated dependency + change. ## Evidence -- A claim about behaviour cites `file:line` in the source. An inference from a - name is not evidence. -- A claim about a CLI flag, a library or a vendor's behaviour cites live output, - the installed source or a reproduction, not documentation alone. +- Cite `file:line` for code behaviour claims; inferring from identifier names is + not evidence. +- Cite live command output, installed source, or a reproduction for CLI flag, + library, or vendor claims, not documentation alone. diff --git a/WORKING.md b/WORKING.md index 760ac32..446bba5 100644 --- a/WORKING.md +++ b/WORKING.md @@ -1,18 +1,19 @@ # Working -How every agent works in a systemfsoftware repository. A repository imports this -file into its always-on `AGENTS.md` or `CLAUDE.md`. A repository's own -instructions may narrow a rule here, never loosen it. +Rules for every agent in a systemfsoftware repository. Each repository imports +this file into its always-on `AGENTS.md` or `CLAUDE.md`. Local instructions may +narrow these rules, never loosen them. -- **SF-WRK-1** Deliver the whole task. Stop only when it is merged or in the - merge queue, or blocked by something only the owner holds; say which. -- **SF-WRK-2** Do reversible work without asking. A design or technical decision - you would ask the owner goes to Gemini; report its answer and proceed. -- **SF-WRK-3** Spawn no subagents unless the owner asked for them in this task. -- **SF-WRK-4** Run no full test suite, end-to-end or microVM run on a shared - host; CI runs them. -- **SF-WRK-5** Before a destructive or wide step, restate the instruction's verb - and object in one line and act on that, not on a nearby meaning. -- **SF-FIN-1** Call nothing done, blocked or broken without the output that - shows it: a command that passed, the compiler error, or the state of the real - system. +- **SF-WRK-1** Deliver the whole task. Stop only when merged, in the merge + queue, or blocked by something only the owner holds, and state which applies. +- **SF-WRK-2** Do reversible work without asking. Send any design or technical + decision you would ask the owner to Gemini, report its answer, and proceed. +- **SF-WRK-3** Never spawn subagents unless explicitly requested by the owner in + the current task. +- **SF-WRK-4** Never run full test suites, end-to-end tests, or microVM runs on + shared hosts; leave them to CI. +- **SF-WRK-5** Before any destructive or broad action, restate the instruction's + verb and object in one line and act strictly on that, not on a nearby + interpretation. +- **SF-FIN-1** Never claim a task is done, blocked, or broken without concrete + proof, such as a passing command, compiler error, or observed system state.