diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 60b3349f..ca577b24 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,12 +1,13 @@ name: CI # One full gate per tree. A pull request runs it on its head; a merge-queue draft runs it on the merged tree. A push -# to main runs it once for the commit that landed. A newer push to a pull request cancels its older run. +# to main runs it once for the commit that landed. A newer push to a pull request cancels its older run. Commit +# linting of the squashed message lives in `squash-message.yml`, so a title or body edit never re-runs this gate. on: push: branches: [main] pull_request: - types: [opened, synchronize, reopened, edited] + types: [opened, synchronize, reopened] workflow_dispatch: permissions: @@ -41,12 +42,6 @@ jobs: with: mode: save key: ${{ steps.pnpm-store.outputs.key }} - # The squash merge takes the pull request title and body as the commit message, so that is what is linted. - - if: github.event_name == 'pull_request' - env: - TITLE: ${{ github.event.pull_request.title }} - BODY: ${{ github.event.pull_request.body }} - run: printf '%s\n\n%s\n' "$TITLE" "$BODY" | pnpm exec commitlint - run: pnpm format:check - run: pnpm lint - run: pnpm typecheck diff --git a/.github/workflows/squash-message.yml b/.github/workflows/squash-message.yml new file mode 100644 index 00000000..e2dc96ad --- /dev/null +++ b/.github/workflows/squash-message.yml @@ -0,0 +1,41 @@ +name: Squash message + +# The squash commit takes the pull request's title and body, so those are linted here rather than in `ci.yml`: a +# title or body edit starts this job alone, never another run of the full gate on an unchanged tree. A queue draft is +# titled "merge queue: ..." and is not the message that lands, so it skips the lint; the pull request it embeds was +# linted, and the queue conditions require this check on that pull request. A fork that names its branch +# `mergify/merge-queue/...` gets the skip but then fails that queue condition, so the spoof cannot slip a message. +on: + pull_request: + types: [opened, synchronize, reopened, edited] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + squash-message: + name: squash message + if: ${{ !startsWith(github.head_ref, 'mergify/merge-queue/') }} + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + - run: pnpm install --frozen-lockfile --filter . + - name: Lint the squash message + env: + PR_TITLE: ${{ github.event.pull_request.title }} + PR_BODY: ${{ github.event.pull_request.body }} + run: | + title=${PR_TITLE//$'\r'/} + body=${PR_BODY//$'\r'/} + printf '%s\n\n%s' "$title" "$body" | pnpm exec commitlint --verbose diff --git a/.mergify.yml b/.mergify.yml new file mode 100644 index 00000000..f0970c44 --- /dev/null +++ b/.mergify.yml @@ -0,0 +1,28 @@ +# Mergify: the policy lives in systemfsoftware/.github (.mergify.yml). This file only names this repository's checks. +extends: .github + +queue_rules: + - name: subtree + merge_method: merge + queue_conditions: + # Org convention (systemfsoftware/.github README, "Subtree PRs"): one commit + # carries both trailers, and the PR history is not linear. + - 'commits[*].commit_message ~= (?ms)\A(?=.*^git-subtree-dir: \S+$)(?=.*^git-subtree-split: [0-9a-f]{40}$)' + - -linear-history + - check-success = checks / check + # The squash message is the pull request's title and body; `squash-message.yml` lints it on the pull request. + - check-success = squash message + merge_conditions: + - check-success = checks / check + + - name: default + queue_conditions: + # Subtree PRs merge via the subtree queue above; a subtree + # claim without trailers matches no queue and cannot merge at all. + - "-commits[*].commit_message ~= (?m)^git-subtree-dir: \\S+$" + - "-title ~= (?i)\\b(add|pull|update|sync|vendor|refresh|import)\\b[^.]*\\bsubtrees?\\b|\\bsubtrees?\\b[^.]*(\\badd\\b|\\bpull\\b|\\bupdate\\b|\\bsync\\b|\\bvendor\\b|\\brefresh\\b|\\bimport\\b)" + - check-success = checks / check + # The squash message is the pull request's title and body; `squash-message.yml` lints it on the pull request. + - check-success = squash message + merge_conditions: + - check-success = checks / check diff --git a/AGENTS.md b/AGENTS.md index b3a357cc..598e99a2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,252 +1,56 @@ -# Learning more about the Effect +# agent -This repository uses the Effect Typescript library. +Effect-native agents with durable Threads, published as four packages: `@yielded/agent`, +`@yielded/agent-storage-sql`, `@yielded/agent-storage-sqlite` and `@yielded/agent-platform-node`. +This repository is public: nothing private goes in files, commit messages, pull requests or comments. -Before writing any Effect code, first read `node_modules/effect/AGENTS.md` -**completely**, and follow the links in the file when required. +## Commands -If you need to learn more about particular Effect apis and concepts that the -guide doesn't cover, search through the source code in `node_modules/effect/src`. +Work inside `nix develop` when the repository has a flake; until then Node 24 and pnpm 12.9.0 are enough. -In `packages/*`, import Effect modules through namespace subpaths, for example -`import * as Effect from "effect/Effect"`. The shared TypeScript configuration -enforces this with `preferNamespaceImport`. - -# Effect Atom client boundary - -This repository consumes APIs through Effect Atom clients (`@effect/atom-react`). -Keep business logic in Effect: compose multi-step client workflows as atoms, -declare cross-query invalidation as reactivity keys on mutations, and keep -promise-mode dispatches at the React boundary logic-free — no `.then` chains -in components or routes. - -## Project command policy - -The toolchain is pnpm, tsdown, vitest, oxlint (the `@systemfsoftware` preset), dprint, commitlint and -`effect-tsgo`. `package.json` owns what each script runs. - -Use these repository commands: - -- Install dependencies: `pnpm install --ignore-scripts && pnpm run prepare`. -- Format check: `pnpm format:check`; format fixes: `pnpm format`. -- Lint: `pnpm lint`. -- Typecheck: `pnpm typecheck`. -- Build: `pnpm build`. -- Tests: `pnpm test`, or one package with `pnpm --filter test`. -- Repository export, record-format and purity checks: `pnpm check:exports`, `pnpm check:record-format` - and `pnpm check:package-purity`. - -# Instructions for implementation agents - -This repository is designed to be implemented by a large, parallel AI-assisted project. Every -agent must preserve a common domain language, dependency direction, and durability contract. - -## Required reading - -Before editing code: - -1. Read `README.md`. -2. Read `GLOSSARY.md` when changing domain concepts or public terminology. -3. Before changing runtime, storage, or platform packages, read the READMEs and API comments of the - packages in scope. The runtime model guide returns with the documentation rebuild. -4. Read the relevant guide, API comments, and neighboring tests for the modules in scope. -5. Read `node_modules/effect/AGENTS.md` before writing Effect code (the canonical Effect - guidance; `.agents/skills` carries the focused task skills). -6. Read `.agents/skills/effect/references/cli/index.md` before creating or changing repository scripts. -7. Inspect neighboring package tests before introducing a new pattern. - -Use the repository's exact `.agents/skills` paths for required workflows; do not rely on a client choosing these over skills installed elsewhere. Read `.agents/skills/effect/SKILL.md` for Effect work and `.agents/skills/cloudflare/SKILL.md` for Cloudflare work, then follow the relevant references. The installed Effect package's `AGENTS.md` remains authoritative for its APIs. - -Keep user-facing behavior in existing guides, implementation contracts beside the code, and -verification evidence in the task or PR artifacts. Explain change rationale in the pull request. -Do not commit separate specifications, planning documents, decision registers, ADRs, roadmaps, -or investigation logs to the product repository. - -## Documentation - -Documentation helps humans evaluate and understand the current library, then use it. -Keep it terse and edit whole pages for a clear reading path. Agents can read source -and API comments; product documentation is not their implementation context. -A feature or fix usually needs a small change to existing guidance, not another section. - -- Guides explain the mental model, ownership, and essential usage. Use one focused - example and link to runnable examples for complete setup. -- References describe public options, defaults, and caller-visible limitations in - a scannable form. Keep essential security and recovery caveats beside their API. -- Source, schemas, and API comments own implementation contracts. Keep SQL query - plans, predicate inventories, internal state-machine walkthroughs, and exhaustive - failure explanations out of guides and reference pages. Move an enduring contract - into its owning API comment when it is missing there. -- PRs and release notes own release history, package-version availability, - `main`/unreleased warnings, old-version fallbacks, migration stories, investigation - findings, and verification results. Keep these out of product documentation, - including banners, callouts, compatibility sections, and annotated examples. -- Review every changed page as a whole before handoff. Remove repetition and material - that does not help a reader evaluate the library, use an API, or avoid a concrete - pitfall. Preserve the actual constraint briefly; put its implementation rationale - in source or the PR. Documentation is not a work log or feature inventory. -- Use small diagrams when they clarify ownership or usage. Draw architecture flows - with `FlowMap` and request sequences with `Trace` from - `@yielded/starlight-theme/components`, in `.mdx`. Give each `FlowMap` a `title` and - `description`; the shared theme owns layout, ownership colors, and theming. -- Use `bun add` for consumer installation examples. Package manifests and the root - catalog own package versions and peer compatibility. Never repeat Effect's current - version in documentation or installation commands; use plain `effect`. Retain - protocol identifiers and contributor toolchain requirements where needed for usage. - -## Non-negotiable architecture rules - -1. Public asynchronous operations return `Effect` or `Stream`, not naked `Promise` values. -2. Expected failures remain typed in `E`; dependency requirements remain visible in `R`. -3. Effect `Schema` is the canonical source for persisted, transported, tool, and structured model - values. -4. Every acquired resource belongs to `Scope`. The engine must not create daemon fibers. -5. Use the pinned Effect v4 AI primitives directly. Do not introduce framework-owned copies of - Effect AI `Tool`, `Toolkit`, `LanguageModel`, `Prompt`, `Response`, or `Model`. -6. Provider SDK values never become canonical thread records. Effect AI values may be used - by the interpreter, but durable records remain explicit, versioned Schemas. -7. The canonical log is append-only and owns conversation content, operation evidence and terminal - outcomes. An unfinished Run's versioned checkpoint is authoritative operational state, committed - atomically with its new history under the single owner's mutation gate and revision check. Delete - it at canonical settlement; unresolved operations and handoffs retain their own rows. Projections and lookup indexes - remain disposable. `verify` checks retained history and active checkpoints, including original - context consistency through `historyDigest`; it does not attest discarded intermediate - checkpoint revisions or provide tamper evidence. Storage validates schema, version, identity, - sequence and atomic commit boundaries without a hash chain or per-record integrity digests. -8. No code may claim exactly-once external side-effect execution. -9. An unresolved ordinary tool call is never automatically replayed after ownership loss. - One process owns a Thread at a time on every backend. Local owner generations reject late - results; distributed claims, ownership leases and multi-worker PostgreSQL are out of scope. -10. Tool/model/subagent concurrency is bounded and deterministic at commit time. Tool batches use - Effect structured concurrency and Semaphore permits rather than a separate Promise scheduler. -11. Security decisions are fail-closed. Model output is untrusted input. -12. Node platform assumptions must not enter core domain modules. - -## Package dependency direction - -```text -effect <- ai-decision (thread model selection) -@yielded/agent <- storage-sql <- storage-sqlite / storage-postgres / storage-cloudflare -@yielded/agent <- storage-memory -@yielded/agent + selected adapters <- platform packages -@yielded/agent <- testing -@yielded/agent <- pr-review +```bash +pnpm install --ignore-scripts && pnpm run prepare +pnpm typecheck +pnpm lint +pnpm format:check +pnpm build +pnpm --filter test ``` -Within `packages/effect-agent/src`, dependencies point inward: -`core <- engine <- capabilities <- durable` and `core <- sandbox <- capabilities`. -Public module paths address these implementations directly; source directories are not separate -packages. Keep core and sandbox contracts platform-neutral. The export check enforces these -internal boundaries as well as package imports. - -An inward package must not import an outward package. If a feature appears to require that, define -or deepen an inward port and implement an outward adapter. - -Framework code lives only in `packages/*`; do not create an `apps/` workspace. Create a new framework package only for a -genuinely new framework concern agreed with the repository owner. Provider integrations remain upstream Effect AI Layers, not framework provider -packages. - -## Toolchain rules - -- pnpm `12.9.0` is the package manager. Use `catalog:` (declared in `pnpm-workspace.yaml`) for shared - dependencies and `workspace:*` for repository packages. -- The catalog is the single source for the exact Effect v4 version. Do not pin Effect - independently in a package. -- After changing an Effect-family version, run `pnpm install` and `pnpm typecheck`. -- Shared contributor skills under `.agents/skills` are authored in [danieljvdm/skills](https://github.com/danieljvdm/skills) and distributed by Dev Kit. Copies track their source in a `.dev-kit-origin.json` receipt. Check for upstream updates with `bunx @danieljvdm/dev-kit@latest skills status`, and fast-forward an unmodified skill with `bunx @danieljvdm/dev-kit@latest skills update `; a skill with local edits is left for an agent merge instead of being overwritten. Add a new skill from the approved catalog with `bunx @danieljvdm/dev-kit@latest skills add `. -- Contributor agent skills are repository tooling. They are not runtime Skill definitions and - must not be imported by `@yielded/agent*`. -- Before handoff, run `pnpm lint`, `pnpm typecheck` and `pnpm test`. -- For live model calls, use provider keys already in the environment. -- For lockfile-only PR fixes, push after `pnpm install --frozen-lockfile` passes; finish full validation afterward. - -Keep shared skills identical to their pinned source. Improve shared guidance in the source repository, then refresh the copies through Dev Kit. Put repository-specific commands, gates, and constraints in this file or linked guidance. `.agents/skills/test-audit` remains local. Keep contributor skills committed so fresh checkouts are self-contained. - -## Change discipline - -- This library is a v0 beta. Prefer simpler machinery and measured performance gains over - compatibility with superseded APIs or storage formats. -- Add or update Effect Schema definitions before implementing new wire or persisted values. -- Keep ordinary changes lean and scoped to the requested outcome. Load `.agents/skills/simplify/SKILL.md` when the user explicitly asks for simplification; do not automatically run a broad simplify pass. Public APIs and persisted formats may change to simplify the architecture or meet the task's requirements. Do not preserve obsolete paths or add compatibility layers unless the user explicitly requires compatibility. The architecture and durability rules above still apply. -- Update existing guides or API comments when a change affects their documented behavior. -- Explain rejected alternatives in the pull request when a future agent could reasonably - re-propose them. -- Do not silently widen errors to `unknown`, `Error`, or `any`. -- Do not use type assertions to cross a schema boundary. -- Change canonical history through export → re-encode → import, never through in-place payload - rewrites. Export only idle Threads and keep the source quiescent until the archive is complete. - Current Run state and operation state carry explicit versions. Storage-layout steps remain - adapter-owned, ordered, and atomic. - Refuse formats and layouts newer than the running code before mutation. -- Write changesets as one or two imperative sentences naming the consumer-visible change. Add only - a short usage example or an explicit BEHAVIOR CHANGE note when consumers must act; keep IDs, - root-cause, review and test stories, and implementation mechanics in the pull request. - -## Testing policy - -Default to no new tests or test infrastructure. Verify requested behavior with -existing checks and direct workflow evidence. Prefer E2E for complex features; -this does not require writing an E2E suite or a larger substitute for a rejected -unit test. Save a verifiable, repeatable artifact without building reporting -machinery. - -Never write unit tests after implementation. If isolation is necessary, first -write the scoped failure inventory, then the necessary failing tests, then the -code. New or expanded committed automation requires a current regression or an -explicit human test request, plus a concrete gap existing proof cannot cover. -Being a library does not waive this bar or require tests for every transition. - -For a new regression, cite its pre-existing public issue or offending commit beside the test. For an explicit human test request, record the requested seam before implementation. A current PR, invented incident, or private identifier is not regression provenance, and a citation alone does not establish test value. - -Load the [testing skill](.agents/skills/testing/SKILL.md) before planning proof or adding, retaining, or removing tests. It owns selection, failure-first isolation and evidence reuse. Keep useful public-contract, recovery and authority checks at their strongest boundary; remove redundant matrices and implementation mirrors. The final `pnpm lint`, `pnpm typecheck` and `pnpm test` gate still applies. - -Exercise E2E workflows through their real entrypoint to an independently checked outcome, preserving the storage, authorization, orchestration and provider boundaries needed by the proof. Use one representative scenario; add failure or recovery paths only for a requirement or concrete risk in scope. Prefer existing acceptance commands and direct interaction over new harnesses. - -Every E2E run, including a failed or interrupted run, must leave inspectable evidence and concise replay instructions: exact steps, tested revision or reconstructable patch, environment and prerequisites, fixture or seed identifiers, setup and cleanup, expected and observed outcomes, and pass/fail/blocked status. Retain enough inputs to rerun the scenario; reuse existing receipts and captures without new reporting machinery. Keep credentials, cookies, private payloads and capability URLs out of artifacts. Store sanitized evidence in the task's artifact directory or an approved artifact store outside the product repository, and link it in the final handoff. Ephemeral console output or a green summary alone is insufficient. - -For audits of existing tests, use [test-audit](.agents/skills/test-audit/SKILL.md) -for read-only discovery, candidate evidence, and retention checks before cleanup. - -For performance-sensitive changes, read `.agents/skills/measure-performance/SKILL.md` and use the existing harness that answers the concrete question. For deployed durable runtime comparisons, follow [the durable benchmark](examples/durable-bench/README.md): preview with `--cost-only`, start with the default `screen` preset and deterministic provider, reuse saved fixtures, and avoid new benchmark infrastructure or machine-wide CPU locks. Keep the default run and rolling 24-hour write budgets unless the user explicitly authorizes a higher spending limit; a `--budget-reason` is a record, not authorization. Use quick/full or long histories only for a question the screen cannot answer. For first-request startup or CPU attribution, follow [the cold-start reproduction](examples/cold-start/README.md); collect CPU profiles separately from latency measurements. Documentation-only changes do not require benchmark runs. +`package.json` owns what each script runs, so read it before you assume. `pnpm check:exports`, +`pnpm check:record-format`, `pnpm check:package-purity` and `pnpm check:pack` guard the published +surface. A pull request merges only through the Mergify queue, whose result on the merged tree is the +gate. Never pass `--no-verify`. -Use [pull-requests](.agents/skills/pull-requests/SKILL.md) for concise -PR descriptions. Add diagrams only for meaningful architecture changes and code -examples only when they clarify the change. +Use an Effect API only if it exists in the installed `node_modules/effect`, which the pnpm catalog pins. -This is a public library. Keep PR descriptions self-contained and follow any -required PR template. Omit private tracker links and issue IDs, including Linear -references; link to public code or guides when useful. Keep company/customer -names, account identifiers, and private workspace links out of PR text and linked -evidence unless the user explicitly requests them. +## Routing -When a bot review blocks a PR, verify its findings against the current code before -changing anything. Authorized agents can clear a fully fixed, refuted, or explicitly -accepted review by commenting `@effect-agent dismiss ` with evidence -on subsequent lines. This dismisses the whole review and refreshes its check without -inference. See the [agent/CLI instructions](action/README.md#dismissing-a-review). -Resolving an inline conversation alone does not clear a blocking review. +Load a doc when its trigger fires, not before. -## Parallel work +| Load | When | +| ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | +| `repos/constitution/CODING_STANDARDS.md`, `repos/constitution/REVIEW.md` and this repository's `CODING_STANDARDS.md` and `REVIEW.md` | you plan, write, review or propose a test | +| `repos/constitution/GRADERS.md` | you build or change a check (a lint rule, CI job, hook or threshold) | +| `node_modules/effect/AGENTS.md`, then `.agents/skills/effect/SKILL.md` | you write Effect code | +| `GLOSSARY.md` | you change a domain concept or public terminology | +| the READMEs and API comments of the packages in scope | you change runtime, storage or platform code | +| the installed source under `node_modules/` | you use a library API you have not seen used in this tree | +| `.agents/skills/simplify/SKILL.md` | the owner explicitly asks for simplification | -Parallel agents must own disjoint packages or documents. Shared domain schemas, error unions, -journal records, and public exports require one designated integrator. -Before integrating parallel work, review the combined diff and run -`pnpm lint`, `pnpm typecheck` and `pnpm test`. Add focused verification only for a concrete remaining question; -do not automatically repeat successful adapter, schema or crash suites. +## Boundaries -## Completion standard +| Surface | Your limit | +| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | +| Graders: the oxlint, dprint and commitlint configs, `oxlint.baseline.json`, `.github/workflows/`, `.mergify.yml` | Never change one to make your work pass; change the implementation. | +| Law: `CODING_STANDARDS.md`, `REVIEW.md`, this file | Change only when the task is to change the law. | +| Vendored: `repos/**` | Read only; update with `git subtree pull`. | +| Human-controlled: merging, deploys, credentials, repository settings | Never do these yourself. | +| Everything else | Edit as the task needs. | -Finish when the requested observable outcomes have sufficient evidence, relevant -public contracts and operational limitations are documented, and `pnpm lint`, `pnpm typecheck` and `pnpm test` -passes. Choose failure, interruption, resource, recovery and security checks for -concrete risks in the change; this is not a mandatory scenario matrix. Preserve -blocked required proof explicitly. A new source file, state transition or public -API does not imply a new test file. +Doppler is the only credential store. Never print a secret. -## Worktree startup +## End of session -Create worktrees from cached refs; fetch explicitly when a newer base is needed. -Run `pnpm install` when dependencies or `node_modules/effect/AGENTS.md` are needed. -Installation uses Bun's shared store and keeps project-specific packages local. -Start only the development services needed for the task, explicitly. Worktree -creation itself should not install dependencies or start servers. +Work on a branch. Never use `git stash`: set work aside by committing it on your own branch. One branch +carries one PR. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..d2ce7efc --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +@AGENTS.md +@subtrees.toml +@repos/constitution/WORKING.md diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md new file mode 100644 index 00000000..eee701c6 --- /dev/null +++ b/CODING_STANDARDS.md @@ -0,0 +1,83 @@ +# Coding Standards + +Review criteria for every change in this repository. They add to the organization's +`repos/constitution/CODING_STANDARDS.md` (included by `REVIEW.md`) and take local precedence, +except that they cannot loosen anything `REVIEW.md` rates P0. This file holds rules that no CI check +fully enforces; each names what enforces it, or says that review does. + +## Non-negotiable architecture rules + +1. Public asynchronous operations return `Effect` or `Stream`, not naked `Promise` values. + Enforced by review. +2. Expected failures remain typed in `E`; dependency requirements remain visible in `R`. `pnpm typecheck` + (`effect-tsgo` `anyUnknownInErrorContext`) rejects `any` and `unknown` in either channel; review + enforces the rest. +3. Effect `Schema` is the canonical source for persisted, transported, tool, and structured model + values. Enforced by review; `pnpm check:record-format` pins the persisted record format. +4. Every acquired resource belongs to `Scope`. The engine must not create daemon fibers. Enforced by review. +5. Use the pinned Effect v4 AI primitives directly. Do not introduce framework-owned copies of + Effect AI `Tool`, `Toolkit`, `LanguageModel`, `Prompt`, `Response`, or `Model`. Enforced by review. +6. Provider SDK values never become canonical thread records. Effect AI values may be used + by the interpreter, but durable records remain explicit, versioned Schemas. Enforced by review. +7. The canonical log is append-only and owns conversation content, operation evidence and terminal + outcomes. An unfinished Run's versioned checkpoint is authoritative operational state, committed + atomically with its new history under the single owner's mutation gate and revision check. Delete + it at canonical settlement; unresolved operations and handoffs retain their own rows. Projections and lookup indexes + remain disposable. `verify` checks retained history and active checkpoints, including original + context consistency through `historyDigest`; it does not attest discarded intermediate + checkpoint revisions or provide tamper evidence. Storage validates schema, version, identity, + sequence and atomic commit boundaries without a hash chain or per-record integrity digests. + Enforced by `packages/storage-sqlite/test/sqlite-ledger.test.ts` and the shared store conformance + suites it runs; review enforces the rest. +8. No code may claim exactly-once external side-effect execution. Enforced by review. +9. An unresolved ordinary tool call is never automatically replayed after ownership loss. + One process owns a Thread at a time on every backend. Local owner generations reject late + results; distributed claims, ownership leases and multi-worker PostgreSQL are out of scope. + Enforced by `packages/platform-node/test/crash/crash.test.ts` and the ledger tests above; review + enforces the rest. +10. Tool/model/subagent concurrency is bounded and deterministic at commit time. Tool batches use + Effect structured concurrency and Semaphore permits rather than a separate Promise scheduler. + Enforced by `packages/effect-agent/test/engine/tool-broker.test.ts` and + `packages/effect-agent/test/capabilities/subagent-reservation.test.ts`; review enforces the rest. +11. Security decisions are fail-closed. Model output is untrusted input. Enforced by review. +12. Node platform assumptions must not enter core domain modules. `pnpm check:exports` restricts core + modules to relative framework imports and `effect`; `pnpm check:package-purity` bundles each + published entrypoint for the neutral platform. + +## Package dependency direction + +```text +@yielded/agent <- storage-sql <- storage-sqlite +@yielded/agent + selected adapters <- platform-node +``` + +An inward package must not import an outward package. If a feature appears to require that, define +or deepen an inward port and implement an outward adapter. `pnpm check:exports` requires every +cross-package import to be a public export and a declared dependency; review enforces the direction +itself. The direction of the internal layers under `packages/effect-agent/src` is enforced by +`pnpm check:exports` and is not restated here. + +Framework code lives only in `packages/*`; do not create an `apps/` workspace. Create a new framework +package only for a genuinely new framework concern agreed with the repository owner. Provider +integrations remain upstream Effect AI Layers, not framework provider packages. Enforced by review. + +## Change discipline + +- This library is a v0 beta. Prefer simpler machinery and measured performance gains over + compatibility with superseded APIs or storage formats. Do not preserve obsolete paths or add + compatibility layers unless the owner requires compatibility. Enforced by review. +- Add or update Effect Schema definitions before implementing new wire or persisted values. Enforced by review. +- Do not silently widen errors to `unknown`, `Error`, or `any`. `pnpm typecheck` rejects the error and + requirements channels; review enforces the rest. +- Do not use type assertions to cross a schema boundary. Enforced by review. +- Change canonical history through export, re-encode and import, never through in-place payload + rewrites. Export only idle Threads and keep the source quiescent until the archive is complete. + Current Run state and operation state carry explicit versions. Storage-layout steps remain + adapter-owned, ordered, and atomic. Refuse formats and layouts newer than the running code before + mutation. Enforced by review; `pnpm check:record-format` fails a changed record format without a + version bump. +- Write changesets as one or two imperative sentences naming the consumer-visible change. Add only + a short usage example or an explicit BEHAVIOR CHANGE note when consumers must act; keep IDs, + root-cause, review and test stories, and implementation mechanics in the pull request. Enforced by review. +- Explain rejected alternatives in the pull request when a future agent could reasonably + re-propose them. Enforced by review. diff --git a/REVIEW.md b/REVIEW.md new file mode 100644 index 00000000..053c308d --- /dev/null +++ b/REVIEW.md @@ -0,0 +1,7 @@ +# Review instructions + +How review behaves in this repository. The rules a finding cites are in `CODING_STANDARDS.md`, in +`repos/constitution/CODING_STANDARDS.md` and `repos/constitution/REVIEW.md` (included below). + +@repos/constitution/CODING_STANDARDS.md +@repos/constitution/REVIEW.md diff --git a/dprint.json b/dprint.json index b8ec6f4b..a615d06d 100644 --- a/dprint.json +++ b/dprint.json @@ -15,6 +15,7 @@ "**/dist", "pnpm-lock.yaml", "coverage/**", + "repos/**", "**/CHANGELOG.md", ".agents/**", ".claude/**", diff --git a/oxlint.config.ts b/oxlint.config.ts index d25a3738..5b16ecd0 100644 --- a/oxlint.config.ts +++ b/oxlint.config.ts @@ -25,7 +25,7 @@ function spellings(key: string): ReadonlyArray { export default defineConfig({ extends: [recommended], - ignorePatterns: ['.agents/**', '.claude/**', '**/dist/**'], + ignorePatterns: ['.agents/**', '.claude/**', 'repos/**', '**/dist/**'], overrides: Object.entries(baseline).map(([key, files]) => ({ files: [...files], rules: Object.fromEntries(spellings(key).map((name) => [name, 'off' as const])), diff --git a/repos/constitution/.github/workflows/ci.yml b/repos/constitution/.github/workflows/ci.yml new file mode 100644 index 00000000..648c62da --- /dev/null +++ b/repos/constitution/.github/workflows/ci.yml @@ -0,0 +1,31 @@ +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 check as the pre-commit hook. +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + check: + name: check + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: denoland/setup-deno@22d081ff2d3a40755e97629de92e3bcbfa7cf2ed # v2 + with: + deno-version: v2.x + - name: Check markdown formatting + run: deno task check diff --git a/repos/constitution/.gitignore b/repos/constitution/.gitignore new file mode 100644 index 00000000..c2658d7d --- /dev/null +++ b/repos/constitution/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/repos/constitution/.husky/commit-msg b/repos/constitution/.husky/commit-msg new file mode 100755 index 00000000..74f6a8cd --- /dev/null +++ b/repos/constitution/.husky/commit-msg @@ -0,0 +1 @@ +deno run --allow-read --allow-env --allow-run --allow-sys npm:@commitlint/cli@21 --edit $1 diff --git a/repos/constitution/.husky/pre-commit b/repos/constitution/.husky/pre-commit new file mode 100755 index 00000000..d17d95a6 --- /dev/null +++ b/repos/constitution/.husky/pre-commit @@ -0,0 +1 @@ +deno task check diff --git a/repos/constitution/AGENTS.md b/repos/constitution/AGENTS.md new file mode 100644 index 00000000..2c69177e --- /dev/null +++ b/repos/constitution/AGENTS.md @@ -0,0 +1,11 @@ +# constitution + +The organization's shared `CODING_STANDARDS.md` and `REVIEW.md`. Consumer +repositories vendor this repository at `repos/constitution/`. There is no code +here. + +- 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/repos/constitution/CLAUDE.md b/repos/constitution/CLAUDE.md new file mode 100644 index 00000000..43c994c2 --- /dev/null +++ b/repos/constitution/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/repos/constitution/CODING_STANDARDS.md b/repos/constitution/CODING_STANDARDS.md new file mode 100644 index 00000000..adeea0da --- /dev/null +++ b/repos/constitution/CODING_STANDARDS.md @@ -0,0 +1,161 @@ +# Coding Standards + +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)`. + +Apply each rule by its purpose. Where wording and harm disagree, harm decides. + +## Impossible states first + +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. 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 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 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, 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** 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** 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 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: 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** 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 + +- 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/repos/constitution/CONTRIBUTING.md b/repos/constitution/CONTRIBUTING.md new file mode 100644 index 00000000..9f33b200 --- /dev/null +++ b/repos/constitution/CONTRIBUTING.md @@ -0,0 +1,29 @@ +# Contributing + +## Setup + +Install [Deno](https://deno.land) 2, then run `deno task prepare` once to enable +the commit hooks. + +## Verify + +```bash +deno task check +``` + +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/repos/constitution/GRADERS.md b/repos/constitution/GRADERS.md new file mode 100644 index 00000000..9c386f60 --- /dev/null +++ b/repos/constitution/GRADERS.md @@ -0,0 +1,20 @@ +# Graders + +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** 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/repos/constitution/LICENSE b/repos/constitution/LICENSE new file mode 100644 index 00000000..b09cd785 --- /dev/null +++ b/repos/constitution/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/repos/constitution/README.md b/repos/constitution/README.md new file mode 100644 index 00000000..00c8e233 --- /dev/null +++ b/repos/constitution/README.md @@ -0,0 +1,74 @@ +# constitution + +[![License: Apache 2.0](https://img.shields.io/badge/license-Apache_2.0-blue?style=flat-square)](LICENSE) + +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 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. | + +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. + +## How to adopt it + +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: + + ```text + @repos/constitution/CODING_STANDARDS.md + @repos/constitution/REVIEW.md + ``` + +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 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 + +See [CONTRIBUTING.md](CONTRIBUTING.md). + +## License + +Apache 2.0. See [LICENSE](LICENSE). diff --git a/repos/constitution/REVIEW.md b/repos/constitution/REVIEW.md new file mode 100644 index 00000000..be60bb21 --- /dev/null +++ b/repos/constitution/REVIEW.md @@ -0,0 +1,93 @@ +# Review instructions + +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 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 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 +bypass merge with a P0 standing and no such review is itself a P0 against the +merge. + +## Limits + +- 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 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. + +These files count toward no coverage figure. + +## Do not report + +- 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 + +- 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/repos/constitution/WORKING.md b/repos/constitution/WORKING.md new file mode 100644 index 00000000..446bba5a --- /dev/null +++ b/repos/constitution/WORKING.md @@ -0,0 +1,19 @@ +# Working + +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 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. diff --git a/repos/constitution/commitlint.config.cjs b/repos/constitution/commitlint.config.cjs new file mode 100644 index 00000000..84dcb122 --- /dev/null +++ b/repos/constitution/commitlint.config.cjs @@ -0,0 +1,3 @@ +module.exports = { + extends: ['@commitlint/config-conventional'], +}; diff --git a/repos/constitution/deno.json b/repos/constitution/deno.json new file mode 100644 index 00000000..45b1a099 --- /dev/null +++ b/repos/constitution/deno.json @@ -0,0 +1,19 @@ +{ + "version": "1.0.0", + "nodeModulesDir": "auto", + "tasks": { + "check": "deno fmt --check", + "prepare": "git config core.hooksPath .husky" + }, + "imports": { + "@commitlint/config-conventional": "npm:@commitlint/config-conventional@^21.2.0" + }, + "fmt": { + "include": [ + "**/*.md" + ], + "exclude": [ + "docs/plans/" + ] + } +} diff --git a/repos/constitution/deno.lock b/repos/constitution/deno.lock new file mode 100644 index 00000000..73d7e5e0 --- /dev/null +++ b/repos/constitution/deno.lock @@ -0,0 +1,53 @@ +{ + "version": "5", + "specifiers": { + "npm:@commitlint/config-conventional@^21.2.0": "21.2.3" + }, + "npm": { + "@commitlint/config-conventional@21.2.3": { + "integrity": "sha512-EP2n5DN2GwRWNVrLX0Jx3mpQlW5PfFi9HnD9OJ8hN/H0xFqpCFyHeGDhg+0P8/21iMMcdkcQgbNqmVklebqYsQ==", + "dependencies": [ + "@commitlint/types", + "conventional-changelog-conventionalcommits" + ] + }, + "@commitlint/types@21.2.3": { + "integrity": "sha512-sGEA473TlCvhCGNoTBY9OXZVWdscIXdGt0dm8EpB+2MRfmt8LNh/X56P/T3nCtEB+eH5qGEa3odphSAoUxSfSQ==", + "dependencies": [ + "conventional-commits-parser", + "picocolors" + ] + }, + "@conventional-changelog/template@1.4.0": { + "integrity": "sha512-aalGyl7dbB5PArRebDIX43ZvBlXrYm9uWzGJ26t+4SzJVPsOuvfILGGbw5X4yX7i50YEmJ8zvbiWnqH/AAnZqg==" + }, + "@simple-libs/stream-utils@2.0.0": { + "integrity": "sha512-fCTuZK4QBa+39Oz9l4OGfJfz+GpwCp3AqO7Zch3to99xHPgstVsRFpeQ8LNd2o1Gv8raL2mCFwiaHh7bFSp5DQ==" + }, + "argue-cli@3.2.0": { + "integrity": "sha512-VipTB0gXgGIFO2Rg9yEVN5wLt2AurJcZqDbgmYSwPwsykhLrQhs240/bfceev4w68lI8JshoOJIk9uW7tFzROw==" + }, + "conventional-changelog-conventionalcommits@10.4.1": { + "integrity": "sha512-jS1LRFSbRoAr6JbhhRy1JYfNNUj5LM3+v49hRE03CgccsiYqgdVj/RTmrw4J1rylrqijHwdOlJWiJa61JHOgHg==", + "dependencies": [ + "@conventional-changelog/template" + ] + }, + "conventional-commits-parser@7.1.3": { + "integrity": "sha512-Q9oWm1o9uy/oEsZQIraoFMZ4RuPD+79KgwWj6mJVP356tazolCB0piRLZ5Kz9te9p027uSEcUW+Gu44Eh+X79g==", + "dependencies": [ + "@simple-libs/stream-utils", + "argue-cli" + ], + "bin": true + }, + "picocolors@1.1.1": { + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" + } + }, + "workspace": { + "dependencies": [ + "npm:@commitlint/config-conventional@^21.2.0" + ] + } +} diff --git a/repos/constitution/docs/plans/2026-08-29-2245-refactor-article-iii-verification-plan.md b/repos/constitution/docs/plans/2026-08-29-2245-refactor-article-iii-verification-plan.md new file mode 100644 index 00000000..c6acc204 --- /dev/null +++ b/repos/constitution/docs/plans/2026-08-29-2245-refactor-article-iii-verification-plan.md @@ -0,0 +1,432 @@ +--- +title: Article III Verification Doctrine Rehaul - Plan +type: refactor +date: 2026-08-29 +supersedes: docs/plans/2026-08-29-2210-refactor-article-iii-verification-plan.md +artifact_contract: ce-unified-plan/v1 +artifact_readiness: implementation-ready +product_contract_source: ce-plan-bootstrap +execution: code +--- + +# Article III Verification Doctrine Rehaul - Plan + +## Goal Capsule + +- **Objective:** The constitution's verification law binds only what measured evidence supports — oracle independence, observer-fit test placement, change-relevant mutation over a named non-empty set, published-contract pinning before deletion, and recomputed gate keys — and no longer prescribes the Testing Trophy, mandatory mocked composition, blanket property coverage of the core, or characterization as a standing duty. The corpus gate is Deno. A reader outside this repo can confirm it: `pnpm test` passes with 33 rules across both corpus files, and `pnpm test --against ` run after the corpus commit names exactly CONST-T1, CONST-T2, and CONST-T5 as vacated with no id reassigned. +- **Means:** The corpus gate is rewritten as a Deno script that implements the behavior the repo's own documentation specifies (vacated-id and uncompared-file reporting); Article III is replaced (vacate T1/T2/T5, reword T3, keep T4, mint T8–T14 plus CONST-E5); CONST-S4 is repointed to CONST-T9; AGENTS.md and README.md prose is reconciled (KTD1–KTD5; normative rule text in Appendix A). +- **Authority:** The H1–H12 verdict dossier and the org-mechanism specification (both delivered in the invoking conversation) govern doctrine conflicts. The corpus's own id-surgery table in AGENTS.md governs id handling. Ecosystem tooling law: Deno only for code (software-wiki harness law). The current corpus at `origin/main` (28 rules: 7 resident Article V + 21 retrieved) is the base being amended, not evidence of correctness (CONST-S2). +- **Execution profile:** One feature branch; four conventional commits in order — plan checkpoint, validator, corpus, prose — pushed together in one PR; no consumer-repo changes. +- **Stop conditions:** A gate failure not explained by the amendment's own edits stops the run. An edit whose find-pattern misses (grep still finds the old text after the edit) stops the run for repair. Implementation-time evidence contradicting a settled decision stops the run. +- **Tail ownership:** Branch shipping, PR, and CI watch belong to the calling pipeline. The org tree's watchdog and mutation-config updates belong to that repo after its next vendor pull. + +--- + +## Product Contract + +### Summary + +Replace the Python corpus gate with a Deno script implementing the full documented behavior — schema, coverage, families, gates, dangling citations, cross-revision reassignment, and vacated-id/uncompared-file reporting. Rewrite Article III of `CONSTITUTION-ARTICLES.md` so the verification doctrine matches the evidence: observer-fit placement instead of trophy widths, a narrow grant for property tests instead of a blanket mandate, mutation gated on a named change-relevant set whose run also grades the test files, published-contract pinning instead of characterization, an independent-oracle requirement with a refusal complement, and one enforcement rule (CONST-E5) binding every gate's key to a recomputation. Repoint CONST-S4's rebuild pin from the vacated CONST-T5 to the new CONST-T9, and reconcile AGENTS.md and README.md so no prose teaches the vacated doctrine or a false rule count. + +### Problem Frame + +The org's enforcing tree already implements observer-fit placement, toothless-property detection, mutation of named sets, a contract lane driven from outside the process, and import-keyed test classification. The constitution still describes a Testing Trophy with mocked composition as the widest band and mandatory characterization before every rebuild. Agents obey `check:` lines, so the stale doctrine is not inert prose — it actively instructs behavior the enforcing tree refuted. The dossier (H1–H12, 73 primary sources) adjudicates the doctrine: same-session test generation is tautology-prone without an independent oracle (H1), the two-surface count is underdetermined (H2), decision-only mutation over-claims observer-fit (H5), a decision-layer fault-majority is false as a census (H6), and gates bind through accountability while advisory surfacing is inert (H12). The constitution must state principles at that altitude and leave mechanism binding to consumer trees, because consumer repos in several languages vendor this file. + +The amendment prunes refuted doctrine and replaces it with a larger instruction surface: Article III grows from 5 to 9 rules and the corpus from 28 to 33. That growth is deliberate — each minted rule names an observer, oracle, or gate discipline the old five could not express, and the refuted doctrine is gone from every line the nine now occupy. The no-retirement id rule means each mint is permanent; that cost is accepted per rule, not in aggregate. + +### Key Decisions + +- **Vacate CONST-T1 and CONST-T5 rather than reword them.** The trophy and the characterization duty are refuted doctrine, not rewordable ones; their numbers stay vacant forever per the corpus's own id-surgery rule. (session-settled: user-directed — chosen over keeping trophy and characterization as reworded doctrine: the org tree's measured mechanisms and the dossier refuted both.) Governs R2, R3, R20. +- **The dossier adjudicates doctrine conflicts.** Where the org tree's current mechanisms and the evidence disagree, the evidence wins: mutation scope is change-relevant, not decision-only (H5); the organizing principle is oracle independence, not a surface count (H2). (session-settled: user-directed — chosen over encoding the org repo's mechanisms verbatim: H5 refuted decision-only scoping as observer-fit and H2 refuted the exhaustive two-surface claim.) Governs R5, R8. +- **CONST-E5 ships in this amendment.** The unforgeable-gate rule is in scope now, not deferred. (session-settled: user-directed — chosen over deferring gate-verification doctrine to a later amendment: user directed inclusion when the deferral was presented as default.) Governs R14. +- **Principles only — no tool names, no consumer names, no filename suffixes in rule YAML.** Mutation is an instrument class; how a tree scopes its mutant set is that tree's config. (session-settled: user-directed — chosen over naming the enforcing stack as exemplar: consumer repos in other languages vendor this file, and a named first consumer turns a house rule into law.) Governs R19. + +### Requirements + +**Corpus gate (Deno)** + +- R1. `scripts/validate-constitution.py` is deleted; a Deno script at `scripts/validate-constitution.ts` implements the same gate — the two-file corpus contract, fenced-YAML coverage accounting, the rule schema (required, optional, and gate fields), the family registry, duplicate-id detection, dangling-citation resolution across both files, and the `--against` cross-revision reassignment check — plus the vacated-id and uncompared-file reporting on the success line that AGENTS.md and `docs/solutions/architecture-patterns/the-vacuous-pass-gate-input-sets.md` already specify. Exit codes: 0 clean, 1 with named defects, 3 unmeasurable. `pnpm test` invokes the script directly; the shebang carries the permission flags (read limited to the two corpus files, run limited to `git`); the `@std/yaml` dependency is declared in `deno.json` imports. + +**Article III surgery** + +- R2. CONST-T1 is removed from `CONSTITUTION-ARTICLES.md`; the number is never reused; no corpus text prescribes trophy layers, widths, or mocked composition as doctrine. +- R3. CONST-T5 is removed; "characterization" appears nowhere in the corpus as a standing duty. +- R4. CONST-T2 is removed; its blanket property mandate does not survive in any reworded rule (see KTD1 for why the replacement takes a fresh id and a fresh title). +- R5. CONST-T3 keeps its id and title "Mutation Is the Measure" with a reworded body: the gate covers a named, non-empty, change-relevant mutated set; the `dont` list covers suppression, after-the-fact narrowing, gate-lowering, an empty set, and raw cross-project percentage comparison. +- R6. CONST-T4's text stands byte-identical. +- R7. CONST-T14 "Properties Where the Surface Cannot Reach" is minted: a property is earned when a universal over generated input, or a refusal no generated law can express, cannot be reached from the published surface; a `dont` forbids properties that restate a decision already pinned from above. +- R8. CONST-T8 "The Observer Must See the Fault Class" is minted: each behavior is enrolled in the observer that can see its failure class; `dont` entries forbid orchestrator suites, mixed mutant populations, and substitutes whose expected value derives from the single implementation they replace. +- R9. CONST-T13 "Mutation Also Grades the Tests" is minted: a run whose mutants all died fails when an authored property file defends nothing the rest of the suite does not; opting out happens in the mutation config, never by deleting the named file. +- R10. CONST-T9 "Pin the Published Contract Before You Delete a Path" is minted: observables are pinned with an expected side independent of the implementation under change; a persisted gold survives a rewrite only when externally authored, independently gated, and cheap to re-bless. +- R11. CONST-T10 "The Oracle Is Not the System Under Test" is minted: every assertion draws on an oracle the SUT did not produce, and a hand-written refusal survives beside generated accept-laws at any specifiable refusal boundary. +- R12. CONST-T11 "Snapshots and Differentials Are Published-Surface Oracles" is minted: snapshot and differential fixtures are produced only through the package's published export map. +- R13. CONST-T12 "Altitude Is What the Test Calls" is minted: a test's observer is decided by what it imports and invokes, never by filename, folder, or suffix; the check is lint. +- R14. CONST-E5 "A Gate's Key Is Recomputed, Never Reported" is minted at the end of Article III's rules block (retrieved placement — see KTD3): gates key on recomputation from source bytes, a compiler verdict, or a rehash; a gate whose verdict the gated agent can produce or observe is unverified until an independent channel confirms it. + +**Resident law** + +- R15. CONST-S4's structural-rebuild bullet cites CONST-T9 instead of CONST-T5, and its `check` clause requires a CONST-T9 pin on every published path a rebuild deletes. No other S4 text changes. + +**Prose reconciliation** + +- R16. AGENTS.md's file-choice paragraph cites CONST-T14 as its review-gated artifact-announced testing example instead of CONST-T2; the "28 of 34 rules" count sentence is recomputed against the amended corpus (33 rules) and restated with measured numbers; its vacated-id reporting claim is now backed by the gate's real behavior. +- R17. README.md's Article III row describes the new doctrine without naming the Testing Trophy, and the "Rules: 34" badge is recomputed to 33. + +**Refusals** + +- R19. No rule YAML names a tool, a consumer repository, a language stack, or a filename suffix. +- R20. No Testing Trophy diagram, width metaphor, or layer table survives anywhere in the corpus. + +### Success Criteria + +- `pnpm test` exits 0 and its success line reports the post-amendment corpus (33 rules across both files). +- After the corpus commit, `pnpm test --against ` exits 0, prints no reassignment, and names exactly CONST-T1, CONST-T2, and CONST-T5 as vacated. +- Against a pre-#9 revision, the same gate names exactly CONST-E1, CONST-E2, CONST-E3, CONST-E4, CONST-G1, and CONST-G2 as vacated. +- A probe that adds a citation to a vacated id makes the gate fail naming the dangling citation; the probe is reverted after the demonstration. +- A grep sweep over the corpus, AGENTS.md, README.md, and `scripts/` finds no reference to CONST-T1, CONST-T2, CONST-T5, "Testing Trophy", or characterization-as-duty. + +### Scope Boundaries + +In scope: `CONSTITUTION-ARTICLES.md`, `CONSTITUTION.md`, `scripts/validate-constitution.py` (deleted), `scripts/validate-constitution.ts` (new), `deno.json` (new), `package.json` (test script), `AGENTS.md`, `README.md`, and this plan. + +### Deferred to Follow-Up Work + +- The org tree's `WATCHDOG.md` police-checks "T1 = trophy, T5 = pin with characterization" (measured in the invoking conversation); it enforces vacated obligations after this amendment and must be updated in that repo after its next vendor pull. Other consumer repos are unmeasured; vacancy failure at their pulls is loud by design. A tracker ticket for this follow-up is filed by the shipping pipeline. +- Restructuring AGENTS.md's measured-count prose so future amendments drift less is a separate docs decision. + +Outside this amendment's identity: validator schema, family registry, or gate registration changes (none needed — E and T are registered, `review`/`lint`/`mutation` are registered gates); renumbering to close id gaps (forbidden by the corpus's own rule); restoring the Application section or the Preamble that commits #9/#10 removed. + +--- + +## Planning Contract + +### Key Technical Decisions + +- KTD1. **CONST-T2 is vacated; its replacement is minted as CONST-T14 with a distinct title.** The narrowed grant forbids what the old `do` required — blanket property coverage of the core violates the new `dont` — so the obligation narrowed, and the corpus's id-surgery table assigns a narrowed obligation a new id. The `--against` reassignment check compares titles, and only for ids present at both revisions, so it is structurally blind to a body-narrowing under a kept id; id discipline for body-level obligation change is therefore review-only, which is exactly why the narrowed grant takes a fresh id and a fresh title ("Properties Where the Surface Cannot Reach") — no reader can mistake the new rule for a light edit of the old. AGENTS.md's prose citation of CONST-T2 re-points to CONST-T14 (R16), which is likewise review-gated and artifact-announced. +- KTD2. **CONST-T3 keeps its id and title.** The reword adds only loophole-closers (empty set, after-the-fact narrowing, raw-percentage comparison) and renames the gated set from "the core" to a named change-relevant set; nothing the old text required is now forbidden, so an agent compliant with the old text still complies. Same obligation, sharper instrument hygiene. +- KTD3. **CONST-E5 is retrieved law at the end of Article III, not resident law.** Commit ebd9b10 (#9) removed the resident Application section — CONST-G1/E1–E4/G2 — with the rationale that gate accumulation had produced cargo-culted checks; recreating a resident enforcement block for one rule reopens exactly that. The resident file is now conduct-only by direction of #9, and CONST-E5 is not conduct. It belongs where the work announces it: an agent authoring or judging a gate holds a verification artifact, which is Article III's retrieval trigger. Family follows about-ness, not placement — the corpus's own precedent is CONST-P3 (purity) living in Article II. E5 is the next free E number because E1–E4, though deleted in #9, are permanently vacant. Grounding: this repo's vacuous-pass learning ("never key a gate on a value its own author supplies") and dossier H12 (enforced gates bind, advisory surfacing is inert; an instrument correlated with the work can manufacture a false verdict). The rule stops at accountability — a recomputed key plus an independent confirmation channel — because binding by a machine gate an agent merely observes is unmeasured (dossier open question Q6). +- KTD4. **Numbering follows the settled mint set; the bundle is one doctrine revision.** CONST-T8 through CONST-T13 per the specification; CONST-T14 for the property grant; CONST-E5 in the E family. T6 and T7 remain vacant alongside T1, T2, and T5; gaps are free and a citation into a gap fails loudly. The eight mints ship as one amendment deliberately: the rules are mutually dependent — T9's pinning assumes T10's oracle independence, T11's snapshots and T12's altitude both key on T8's observer placement, and CONST-E5 disciplines the gates the T-family names — so splitting them would mint rules that cite rules that do not exist yet. +- KTD5. **Four commits, pushed together as one PR: plan checkpoint, validator, corpus, prose.** The Deno gate lands before the corpus commit so the amendment it judges is verified by a gate that already reports vacancies; the corpus commit carries both constitution files; prose lands last. The intermediate states exist only on the local branch for minutes — CI and consumer repos see only the PR head. The corpus/prose divergence window never publishes, and each layer stays auditable on its own. +- KTD6. **The gate is Deno, not Python.** Ecosystem tooling law is Deno-only for code, and the user directed it for this run. The rewrite is a port, not a redesign: every check the Python gate made is preserved, and the one addition is the vacated-id/uncompared-file reporting the repo's documentation already specifies (AGENTS.md's gate paragraph; the vacuous-pass learning's success-line shape). The `@std/yaml` parser is declared in `deno.json` and imported by bare name; the shebang carries the least-privilege flags so callers invoke the script directly. + +### Id surgery map + +| Action | Id | Title | +|---|---|---| +| Vacate | CONST-T1 | The Testing Trophy | +| Vacate | CONST-T2 | Properties Over Examples (blanket mandate) | +| Vacate | CONST-T5 | Pin Behavior Before You Rebuild | +| Keep id, reword body | CONST-T3 | Mutation Is the Measure | +| Keep, byte-identical | CONST-T4 | Behavior Lives Where the Mutator Sees It | +| Mint | CONST-T8 | The Observer Must See the Fault Class | +| Mint | CONST-T9 | Pin the Published Contract Before You Delete a Path | +| Mint | CONST-T10 | The Oracle Is Not the System Under Test | +| Mint | CONST-T11 | Snapshots and Differentials Are Published-Surface Oracles | +| Mint | CONST-T12 | Altitude Is What the Test Calls | +| Mint | CONST-T13 | Mutation Also Grades the Tests | +| Mint | CONST-T14 | Properties Where the Surface Cannot Reach | +| Mint | CONST-E5 | A Gate's Key Is Recomputed, Never Reported | + +Base: 28 rules (CONSTITUTION.md 7 + CONSTITUTION-ARTICLES.md 21). Post-amendment: 28 − 3 + 8 = 33. + +### Assumptions + +- The org tree's enforcing mechanisms are taken as specified in the invoking conversation; they were measured in that repo and are not re-verified from here. +- The dossier's adjudications are taken as the doctrine authority as delivered; primary-source re-derivation is out of scope for this amendment. +- CONST-T2's vacancy (KTD1) is resolved by the corpus's own id-surgery table after the question was declined in dialogue; the user redirected nothing when authorizing autonomous shipping. +- The two inference-grade `harm` fields (the empty-set guard's catching behavior, machine-gate binding on an observing agent) are stated as rationale, not measured findings, and the rules that carry them are framed as guards and accountability requirements. +- The locked-surface guidance for verification scripts is overridden for the gate file itself by direct user direction (Python out, Deno in); the override is declared in the validator commit body. + +### Risks & Dependencies + +- Consumer repos citing CONST-T1, CONST-T2, or CONST-T5 fail loudly at their next vendor pull. That is the intended vacancy behavior — a citation into a gap resolves to nothing, which the gate surfaces by name. One consumer is known to cite them (the org tree's `WATCHDOG.md`, per the invoking conversation); its repair is the deferred follow-up, not a shim here. +- AGENTS.md's measured-count prose will drift again on the next amendment. Accepted; the amendment checklist already requires recomputation on delete/split/merge/re-scope commits. +- The first `pnpm test` run after the Deno rewrite fetches `@std/yaml` from JSR (as the old command fetched PyPI); subsequent runs are cached. + +### System-Wide Impact + +Every consumer repo's agents receive the amended doctrine at their next vendor pull; the constitution repo's own harness (AGENTS.md guidance, README's doctrine table and badge) changes with it. The gate moves from Python to Deno — consumer repos that invoke the vendored validator directly inherit a Deno dependency; those using `pnpm test` inherit it transparently. + +--- + +## Implementation Units + +### U5. Deno corpus gate + +**Goal:** The corpus gate is a Deno script implementing the full documented behavior, including vacated-id and uncompared-file reporting; the Python file is gone. + +**Requirements:** R1 + +**Dependencies:** none (executes first) + +**Files:** `scripts/validate-constitution.ts` (new), `scripts/validate-constitution.py` (deleted), `deno.json` (new), `package.json` (test script) + +**Approach:** + +1. Read the Python gate in full and port every check: two-file coverage, fenced-block extraction and per-block parse errors, declared-vs-parsed id accounting, schema fields, gate values, family registry, duplicate ids, `do`/`dont` string-or-string-list shape, `example` map-of-strings shape, cross-file dangling citations, `--against` title-keyed reassignment. +2. Add the success-line reporting: ids vacated since the revision, and corpus paths absent at it — neither fails the run; both are named. +3. Declare `@std/yaml` in `deno.json` imports; point `package.json`'s `test` script at the script path; carry permissions in the shebang (`--allow-read` limited to the two corpus files, `--allow-run=git`); mark the file executable. + +**Patterns to follow:** the reporting shape in the vacuous-pass learning ("what cannot be failed must be reported"); the Python gate's error-message voice. + +**Test scenarios:** + +- Red-first: before the rewrite, `pnpm test --against ebd9b10~1` (captured) prints only `no id reassigned` — six vacated ids unreported. +- After the rewrite, against `ebd9b10~1`: names exactly CONST-E1, CONST-E2, CONST-E3, CONST-E4, CONST-G1, CONST-G2 as vacated; exit 0. +- Against the pre-split revision `28c79e6~1`: names `CONSTITUTION-ARTICLES.md` as not compared; exit 0. +- Against the current HEAD: names nothing vacated; exit 0. +- Without `--against`: output shape unchanged from the Python gate's, exit 0. +- Dangling-citation fixture: a temporary citation to a vacated id fails the run naming it. + +**Verification:** the six scenarios pass; `deno lint` on the new script is clean. + +### U1. Article III surgery + +**Goal:** Article III states observer-fit, oracle-independence, mutation, pinning, and gate-key doctrine; the trophy and the characterization duty are gone. + +**Requirements:** R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, R13, R14, R19, R20 + +**Dependencies:** none on U5 (independent content; ordering matters only for U4's evidence) + +**Files:** `CONSTITUTION-ARTICLES.md` + +**Approach:** + +1. Read the current Article III block before editing. +2. Replace the rules block with the Appendix A block verbatim: CONST-T8, CONST-T14, CONST-T3, CONST-T13, CONST-T4, CONST-T9, CONST-T10, CONST-T11, CONST-T12, then CONST-E5 as the terminal rule. CONST-T4's entry stays byte-identical to the current text. +3. Article III's heading and the surrounding article structure do not change. + +**Patterns to follow:** the existing rule YAML schema (`id`, `title`, `gate`, `do`, `dont`, `harm`, `check`); gate values limited to the registered set. + +**Test scenarios:** (all run at the corpus-commit boundary, after U2's S4 repoint — the dangling T5 citation in CONSTITUTION.md keeps the gate red until then) + +- Validator schema: `pnpm test` exits 0; the success line reports 33 rules. +- Dangling-citation probe: temporarily add a citation to CONST-T5 in a corpus file; the gate fails naming the dangling citation; revert the probe and confirm green. +- Stale-doctrine sweep: a grep over the corpus for `CONST-T1`, `CONST-T2`, `CONST-T5`, `Testing Trophy`, and `characterization` returns nothing. + +**Verification:** the three scenarios pass at the corpus-commit boundary. + +### U2. S4 repoint + +**Goal:** CONST-S4 pins structural rebuilds with CONST-T9 instead of the vacated CONST-T5. + +**Requirements:** R15 + +**Dependencies:** U1 (the citation target must exist) + +**Files:** `CONSTITUTION.md` + +**Approach:** + +1. Read the current CONST-S4 block before editing and confirm both find-patterns are present verbatim. +2. In the structural-rebuild bullet, replace "behaviour pinned with characterization tests first, CONST-T5" with "published contract pinned first (CONST-T9)". +3. In the `check` clause, replace "a structural rebuild ships its characterization tests" with "a structural rebuild ships a CONST-T9 pin on every published path it deletes". +4. If either find-pattern misses, stop for amendment repair — do not approximate the edit. + +**Patterns to follow:** the resident Article V rule shape; no other S4 field changes. + +**Test scenarios:** + +- A grep of `CONSTITUTION.md` for CONST-T5 returns nothing; a grep for CONST-T9 returns the S4 citation. +- `pnpm test` exits 0 at the corpus-commit boundary (with U1). + +**Verification:** both scenarios pass. + +### U3. Harness prose reconciliation + +**Goal:** The harness and front-page prose teach the amended doctrine, cite only live rules, and carry measured numbers. + +**Requirements:** R16, R17 + +**Dependencies:** U1, U2, U5 (prose must match final rule text, ids, and gate behavior) + +**Files:** `AGENTS.md`, `README.md` + +**Approach:** + +1. In AGENTS.md's file-choice paragraph, replace the CONST-T2 example citation with CONST-T14. +2. In AGENTS.md's gate-explanation paragraph, recompute the inbound-citation count and the corpus total (33) against the amended files and restate the sentence with the measured numbers; its vacated-reporting claim now names real behavior. +3. In README.md's doctrine table, rewrite the Article III row to describe observer-fit placement, properties by narrow grant, and mutation as the measure; recompute the "Rules" badge from 34 to 33. + +**Patterns to follow:** AGENTS.md's existing measured-claim style; README.md's table-row and badge shapes. + +**Test scenarios:** + +- Repo-wide grep sweep (excluding `.git`, lock files, and this plan) for CONST-T1, CONST-T2, CONST-T5, "Testing Trophy", and characterization-as-duty returns nothing. +- The recomputed AGENTS.md and README numbers match fresh counts run at implementation time, not numbers carried from this plan. + +**Verification:** both scenarios pass. + +### U4. Verification battery and commits + +**Goal:** Evidence is recorded and the work lands as four conventional commits. + +**Requirements:** all + +**Dependencies:** U5, U1, U2, U3 + +**Files:** none new + +**Approach:** + +1. Run the full Verification Contract in order. +2. Commit the plan checkpoint (`docs(plans):`) first; then the Deno gate (`feat(scripts)!:`) with the locked-surface override declared in the body; then the corpus change (U1 + U2, `refactor(constitution)!:`); then the prose (U3, `docs:`). +3. Run commitlint over all four commits. + +**Test scenarios:** + +- All four commits pass `pnpm exec commitlint --from HEAD~4`. +- The working tree is clean after the commits. + +**Verification:** the Verification Contract's exit criteria all hold. + +--- + +## Verification Contract + +| Check | Command / method | Exit criterion | +|---|---|---| +| Corpus gate | `pnpm test` | Exit 0; success line reports 33 rules across both corpus files | +| Vacancy gate | `pnpm test --against ` | Exit 0; no reassignment; names exactly CONST-T1, CONST-T2, CONST-T5 vacated | +| Backfill fixture | `pnpm test --against ebd9b10~1` | Exit 0; names exactly the six #9-removed ids vacated | +| Uncompared fixture | `pnpm test --against 28c79e6~1` | Exit 0; names `CONSTITUTION-ARTICLES.md` not compared | +| Dangling-citation probe | temporary citation to a vacated id, then `pnpm test` | Fails naming the citation; probe reverted; gate green again | +| Stale-doctrine sweep | grep corpus, AGENTS.md, README.md, `scripts/` for vacated ids and retired doctrine names | Zero matches | +| Commit format | `pnpm exec commitlint --from HEAD~4` | Exit 0 for all four commits | +| Clean state | `git status --porcelain` | Empty after commits | + +--- + +## Definition of Done + +- All requirements R1–R20 hold in the tree. +- The Verification Contract passes in full, in the current session. +- The four commits (plan, validator, corpus, prose) are separate, conventional, and pushed together in one PR. +- No consumer-repo file is touched; the org-tree watchdog follow-up remains deferred with its tracker ticket filed. +- Working tree is clean. + +--- + +## Appendix A — Article III replacement block + +Normative payload for U1. YAML block content, replacing the current Article III `rules:` sequence: + +```yaml +rules: + - id: CONST-T8 + title: The Observer Must See the Fault Class + gate: review + do: enroll each behavior in the observer that can see its failure class — a pure decision is read by properties and by mutation of that decision; a published operation is read by tests that call only exported names; a shell that only translates is read by those exported-name tests, not by a suite of its own + dont: + - give the orchestrator its own test suite — extract the decision or live with the exported-name test + - enroll adapters, codecs, or wiring in the same mutant set as decisions + - treat a substitute whose expected value derives from the single implementation it replaces as an observer + harm: the wrong instrument reports coverage and measures nothing; mocked composition certifies wiring; a fat middle grows where decisions and I/O stay tangled + check: review — every new test names the surface it binds (decision or published export) and does not import a non-exported symbol to assert it + - id: CONST-T14 + title: Properties Where the Surface Cannot Reach + gate: review + do: prove a pure decision with a property when a universal over generated input, or a refusal no generated law can express, cannot be reached from the published surface; the type is the generator + dont: + - cover the core with hand-picked example unit tests + - write a property for a decision already fully pinned from above just because the decision is important + harm: a green suite that tests only the cases you imagined; or a property farm that restates the public contract and dies with it + check: review — each authored property names the universal the public surface cannot reach + - id: CONST-T3 + title: Mutation Is the Measure + gate: mutation + do: gate a named, change-relevant mutated set at a perfect kill score; the set names the behavior it covers, and its scope is a cost decision, never a fault-majority claim; kill a survivor with a sharper property or by deleting the dead branch it exploits + dont: + - reach the number by a suppression comment + - reach the number by narrowing the mutated set after the fact + - reach the number by lowering the gate + - let an empty mutated set pass + - treat a raw mutation percentage as comparable across changes or codebases + harm: a score certifying tests that notice nothing; an empty or author-shrunk set passing vacuously + check: mutation gate (break = 100) on the declared mutated set; lint banning suppression, scope-narrowing, and an empty set + - id: CONST-T13 + title: Mutation Also Grades the Tests + gate: mutation + do: fail a run whose mutants all died if an authored property file defends nothing the rest of the suite does not; opt out in the mutation config, never by deleting the file the gate named + dont: + - treat a perfect mutant score as proof every test pulled its weight + - accuse a file that covered an unattributed kill + harm: toothless properties accumulate; deleting them to silence the gate removes the only named contract + check: mutation — the test-set verdict is part of the same run as the score + - id: CONST-T4 + title: Behavior Lives Where the Mutator Sees It + gate: lint + do: put any code that can be wrong (transform, check, branch) in a file the mutator covers + dont: place behavior in a declaration file (types, schemas, constant data), excluded from mutation + harm: a bug hidden behind a perfect score, in a file nothing mutates + check: lint — declaration files contain no behavior + - id: CONST-T9 + title: Pin the Published Contract Before You Delete a Path + gate: review + do: before removing or replacing a published operation, pin its observables (value, error variant, serialized document, process result) with examples or properties whose expected side is not the implementation under change; if the old operation still runs, compare old and new on the same published inputs until they agree, then delete old + dont: + - pin private functions + - derive expected values by running the implementation under change + - treat a mutation or property score as proof a deleted published capability still exists — those are blind to absence + - leave a persisted gold after the old path is gone unless the gold is externally authored, independently gated, and cheap to re-bless + harm: a rebuild silently drops a capability; same-session gold blesses the bug; a clean score after a delete is a silent regression + check: review — pins call only published names; each expected value names an independent source (spec clause, prior published major, second implementation, or a hand-written oracle next to the constructor) + - id: CONST-T10 + title: The Oracle Is Not the System Under Test + gate: review + do: every assertion has an oracle the SUT did not produce — a spec literal, a fixture not generated by importing the module, a law relating two views of the same value, or a second implementation; generated round-trip laws on a type cover what the type accepts and nothing it should reject, so a hand-written refusal survives beside them at any specifiable refusal boundary + dont: + - compute expected by calling the SUT + - assert collaborator call graphs + - treat generated accept-laws as full coverage of a refinement + harm: a green suite that cannot fail when the behavior is wrong; widening a refinement leaves generated laws green + check: review — plus sabotage: after green, break one core law and one published field; at least one test must go red + - id: CONST-T11 + title: Snapshots and Differentials Are Published-Surface Oracles + gate: lint + do: snapshot only canonicalized published output; compare two implementations only of the same published operation (or a prior published major against current) + dont: + - snapshot or compare private helpers, mappers, or unexported modules + - snapshot a value small enough to be a property or a named example + harm: tests that fail on refactors callers cannot see and pass on contract breaks they can + check: lint — snapshot and differential fixtures are produced only through the package's published export map + - id: CONST-T12 + title: Altitude Is What the Test Calls + gate: lint + do: decide a test's observer from what it imports and invokes — published names or a decision under mutation — never from a filename, folder, or suffix + dont: key which doctrine applies to a test on a label the author can rename + harm: a rename silently un-enrolls the file from its observer; the absence reads as coverage + check: lint — no rule that selects tests by filename suffix + - id: CONST-E5 + title: A Gate's Key Is Recomputed, Never Reported + gate: review + do: + - key every gate on a recomputation from source bytes, a compiler verdict, or a rehash — never on a field the gated work's author supplied; when a gate reads a field, recompute that field in the same run + - treat a gate whose verdict the gated agent can produce or observe as unverified until an independent channel confirms it — an instrument the agent does not control, or review by someone who is not the gated agent + dont: + - accept a self-reported field, a presence flag, a metadata suffix, or a comment as evidence a property holds + - treat a mechanical gate's green as self-certifying + harm: a check keyed on author-supplied values passes everything and catches nothing, and the green then masks the broken invariant the gate exists to catch; an instrument correlated with the work under test can manufacture a verdict no single observer catches + check: review — each gate names the recomputation it runs and the independent channel that confirms its verdict +``` + +--- + +## Appendix B — CONST-S4 edits + +Normative payload for U2, verified verbatim against the current corpus. Two edits, complete and final: + +- Structural-rebuild bullet: "behaviour pinned with characterization tests first, CONST-T5" becomes "published contract pinned first (CONST-T9)". +- Check clause: "a structural rebuild ships its characterization tests" becomes "a structural rebuild ships a CONST-T9 pin on every published path it deletes". + +--- + +## Sources & Research + +- H1–H12 verdict dossier (delivered in the invoking conversation): doctrine authority. Load-bearing verdicts: H1 (same-session contamination), H2 (oracle independence over surface count), H5 (change-relevant mutation; decision-only refuted; empty-set guard load-bearing), H7 (refusal complement), H8 (seam authority), H11 (external-gated gold), H12 (gates bind; accountability reading). Independently spot-confirmed against primary literature (arXiv:2607.05139, arXiv:2410.21136, EMSE'22 commit-relevant mutants). +- Org-mechanism specification (delivered in the invoking conversation): the enforcing tree's mechanisms, the mint set CONST-T8 through CONST-T13, and the measured consumer citation (org tree WATCHDOG.md). +- Python gate `scripts/validate-constitution.py`, read in full: the port source — schema fields, family registry, cross-file citation resolution, title-keyed `--against` reassignment over ids present at both revisions. +- AGENTS.md: id-surgery table (obligation identity), family registry, file-choice rule, the gate-explanation paragraph whose counts R16 recomputes and whose vacated-reporting claim the Deno gate makes true. +- `docs/solutions/architecture-patterns/the-vacuous-pass-gate-input-sets.md`: grounding for CONST-E5 and the `--against` reporting shape — a gate keyed on author-supplied values certifies nothing; what cannot be failed must be reported. +- Tooling: Deno-only ecosystem law (software-wiki harness convention); `@std/yaml` (`jsr:@std/yaml`, single-document `parse`, safe for untrusted input — docs.deno.com/runtime/reference/std/yaml). +- Corpus base: `origin/main` at dd5722a (28 rules; commits ebd9b10/#9 and dd5722a/#10 removed the Application section and the Preamble). diff --git a/repos/constitution/docs/plans/2026-08-30-0100-feat-omp-constitution-ttsr-plugin-plan.md b/repos/constitution/docs/plans/2026-08-30-0100-feat-omp-constitution-ttsr-plugin-plan.md new file mode 100644 index 00000000..287e44d9 --- /dev/null +++ b/repos/constitution/docs/plans/2026-08-30-0100-feat-omp-constitution-ttsr-plugin-plan.md @@ -0,0 +1,49 @@ +--- +title: "feat(plugin): create OMP constitution TTSR rules plugin" +date: 2026-08-30 +category: feature +artifact_contract: ce-unified-plan/v1 +artifact_readiness: implementation-ready +execution: code +product_contract_source: ce-plan +--- + +# Goal Capsule + +Add a standard OMP plugin package (`@systemfsoftware/omp-plugin-constitution` under `packages/omp-plugin/` or `plugins/constitution/`) that defines Time-Traveling Stream Rules (TTSR) in markdown (`rules/*.md`). The rules trigger on edits/writes to source code and tests, enforcing strict adherence to the Supreme Engineering Constitution (`CONSTITUTION.md` and `CONSTITUTION-ARTICLES.md` Articles I–V). Any violation in review or source generation is flagged immediately with automatic P0 severity and actionable remediation. + +# Product Contract + +## 1. Scope and Objective +- Package an OMP plugin adhering to Claude/OMP plugin discovery specifications (`.omp-plugin/plugin.json`, `rules/`, `package.json`, `README.md`). +- Define targeted TTSR stream rules (`rules/*.md`) covering: + 1. `constitution-pure-core.md`: Enforces Article I (purity, tagged error variants, branded types, cyclomatic complexity 1, no primitive obsession, no boolean/status string errors, no null states). + 2. `constitution-boundary.md`: Enforces Article II (functional core / imperative shell, effects as lazy values, I/O sandwich order, inward dependencies, decode never unchecked cast `as any`/`as unknown`). + 3. `constitution-verification.md`: Enforces Article III (public export API testing, mutation testing on decisions, narrow property grants, independent oracles, no mocked intermediate single-implementation glue code, no tautological/characterization tests). + 4. `constitution-conduct-and-review.md`: Enforces Article V & Governance (automatic P0 on constitutional breaches with zero appeals unless declared under CONST-W3, root cause over expedient patch, subtract before add, scope discipline). +- Each rule carries frontmatter with `condition`, `scope` (`tool:edit(...)`, `tool:write(...)`, `tool:ast_edit(...)`), and `interruptMode: tool-only` or `always`. +- Update project manifest (`package.json`) and root test validation to ensure all rules are valid YAML frontmatter and tested against `omp ttsr test` (or regex validator). + +## 2. Requirements & Invariants +- **R1 (Plugin Discovery)**: Plugin manifest `.omp-plugin/plugin.json` and `.claude-plugin/plugin.json` properly identify the plugin name, version, and author metadata. +- **R2 (TTSR Rule Format)**: Every rule file in `rules/` has valid YAML frontmatter with `description`, `condition`, `scope`, and markdown instructions quoting the exact rule IDs (`CONST-P1`, `CONST-D1`, `CONST-B1`, `CONST-T8`, `CONST-G3`, etc.). +- **R3 (Zero Hallucination / Grounded)**: Rule text cites exact IDs and principles from the repository's `CONSTITUTION.md` and `CONSTITUTION-ARTICLES.md`. +- **R4 (Verification)**: `pnpm test` (and any new plugin test scripts) must execute cleanly, validating all YAML blocks across the repository. + +# Implementation Units + +- [ ] **U1: Scaffold OMP Plugin Manifest & Directory Structure** + - **Goal**: Create the plugin layout under `plugins/constitution/` or root plugin metadata with `.omp-plugin/plugin.json`, `.claude-plugin/plugin.json`, and `package.json`. + - **Files**: `plugins/constitution/.omp-plugin/plugin.json`, `plugins/constitution/.claude-plugin/plugin.json`, `plugins/constitution/package.json`, `plugins/constitution/README.md`. + +- [ ] **U2: Implement Article I & II TTSR Rules (Core & Boundary)** + - **Goal**: Author `rules/constitution-pure-core.md` and `rules/constitution-boundary.md` with precise regex and ast conditions for unchecked casts (`as any`, `as unknown`), eager async promises on domain signatures, mutable control flow in pure core, and missing error tagging. + - **Files**: `plugins/constitution/rules/constitution-pure-core.md`, `plugins/constitution/rules/constitution-boundary.md`. + +- [ ] **U3: Implement Article III & V TTSR Rules (Verification & Review P0)** + - **Goal**: Author `rules/constitution-verification.md` and `rules/constitution-conduct-review.md` covering mocked single implementations, tautological assertions, private helper unit tests, and the mandatory P0 automatic review rejection. + - **Files**: `plugins/constitution/rules/constitution-verification.md`, `plugins/constitution/rules/constitution-conduct-review.md`. + +- [ ] **U4: Wire Validation, Test Battery, and Documentation** + - **Goal**: Update root `scripts/validate-constitution.ts` (or add plugin test scripts) to validate the plugin rules, update `README.md` and `AGENTS.md` to document the OMP plugin installation and usage. + - **Files**: `scripts/validate-constitution.ts`, `README.md`, `AGENTS.md`, `package.json`. diff --git a/repos/constitution/docs/plans/2026-09-01-0533-retire-the-ttsr-plugin-entirely-plan.md b/repos/constitution/docs/plans/2026-09-01-0533-retire-the-ttsr-plugin-entirely-plan.md new file mode 100644 index 00000000..525e4dc9 --- /dev/null +++ b/repos/constitution/docs/plans/2026-09-01-0533-retire-the-ttsr-plugin-entirely-plan.md @@ -0,0 +1,99 @@ +# Plan — Retire the TTSR plugin entirely (supersedes 2026-09-01-0454) + +```yaml +plan: + id: unified-ce-unified-plan/v1 + status: implementation-ready + created: 2026-09-01-05:33 + supersedes: docs/plans/2026-09-01-0454-refactor-restore-single-constitution-plan.md + delivery: one branch (restore-single-document), one PR (#21), own commits +``` + +## Problem + +The 0454 plan kept the plugin alive in reduced form: three rule files as +"residency statements" and `constitution-conduct-review.md` as the one active +interrupt. The user rejected that on first principles: **the constitution is +always on, so every plugin rule is useless.** The plugin's entire function was +to carry law into the agent's context on a trigger; residency (`@CONSTITUTION.md`) +already delivers all of it, always. The conduct-review interrupt is the clearest +case — its body restates `CONST-G3`, `CONST-W3`, `CONST-S1`, `CONST-S4`, +`CONST-S2`, every one of them resident in `CONSTITUTION.md` the moment the +trigger fires. The interrupt injects text the agent already has. + +This is CONST-S4 turned on the restore itself: the statement files were a +helper added where removal does the job. + +## Requirements + +- **R1 — The plugin is gone.** `plugins/` (constitution README, all four rule + files, `.omp-plugin/`, `.claude-plugin/`) is deleted. No manifest, no + statement file, no tombstone README survives (DEL1: remove means remove). +- **R2 — The repo teaches one delivery path.** `README.md` quick start drops + the marketplace/install step; `@CONSTITUTION.md` is the only wiring. + `AGENTS.md` drops "agent harness" from the tooling description. +- **R3 — The ttsr learning is marked historical.** Its subject corpus (the + constitution plugin's condition regexes) no longer exists; the two + transferable traps (PCRE flag translation, backreference tautology matching) + stay for any future TTSR plugin. +- **R4 — Clean cutover.** No live surface references the plugin or any rule + file name: `git grep -nI -e 'plugins/constitution' -e 'constitution-conduct-review' + -e 'constitution-pure-core' -e 'constitution-boundary' + -e 'constitution-verification' -- . ':!docs/plans'` prints zero lines. + (Plan documents are the named exception; this one included.) + +## Implementation units + +- **U1 — Plan supersession** (this document): write, delete 0454, + commit `docs(plans)`. +- **U2 — Plugin removal**: `git rm -r plugins/`; README step 2 removed; + AGENTS.md tooling line corrected. One commit. +- **U3 — Learning annotation**: ttsr doc Context paragraph noting the plugin's + removal and why, lesson kept as transferable. Rides U2's commit — same + cutover, one reviewable unit. +- **U4 — Verification battery**: `deno task test` (gate reads only + `CONSTITUTION.md`; unaffected, must stay green); `deno lint`; the R4 sweep; + `omp plugin doctor` diffed against the pre-deletion baseline (local plugin + state lives under `/root/.omp/plugins` — repo deletion must not change the + doctor verdict shape; stale local links are machine state, out of repo scope). + +## Verification Contract + +| # | Check | Command | Expected | +|---|---|---|---| +| 1 | corpus gate | `deno task test` | `valid: 40 rules across 6 yaml blocks in 1 files, 9 families`, exit 0 | +| 2 | lint | `deno lint` | clean | +| 3 | DEL1 sweep | git grep per R4 | zero lines, read stdout | +| 4 | loader state | `omp plugin doctor` | same summary shape as baseline (5 ok / 1 warn / 1 pre-existing error); no new error introduced by the repo deletion | +| 5 | clean tree | `git status --porcelain` | empty | + +## Key technical decisions + +```yaml +- id: KTD1 + decision: Delete the plugin entirely rather than keep a zero-rule shell. + why: A plugin directory with no rules and a README that says "this plugin + does nothing, residency delivers the law" is a standing tombstone — DEL1's + named anti-pattern. The git history carries the artifact. +- id: KTD2 + decision: The ttsr learning is annotated, not deleted. + why: Solutions docs are durable learnings; the flag-translation trap is + generic TTSR knowledge independent of this plugin's life. Its Context now + names the plugin as removed so no reader treats the corpus as live. +- id: KTD3 + decision: conduct-review's law needs no replacement interrupt. + why: Every rule it restates is resident (CONST-G3, W3, S1, S4, S2). A regex + trigger that injects already-present text is not enforcement, it is noise — + and its 200-char proximity window misfired on benign severity mentions + (flagged in review). +``` + +## Non-goals + +- Consumer-repo follow-ups (subtree pulls, local `omp plugin uninstall`): + machine/consumer state, tracked as follow-ups after merge. +- Gate hardening (issues #19, #20) — already filed, unchanged. + +## Work relationships + +None — terminal correction to the restore PR. diff --git a/repos/constitution/docs/plans/2026-09-07-1721-the-maker-never-holds-the-instrument-plan.md b/repos/constitution/docs/plans/2026-09-07-1721-the-maker-never-holds-the-instrument-plan.md new file mode 100644 index 00000000..beaf29d1 --- /dev/null +++ b/repos/constitution/docs/plans/2026-09-07-1721-the-maker-never-holds-the-instrument-plan.md @@ -0,0 +1,131 @@ +# Plan — The maker never holds the instrument (corrects the 26a527c enforcement reasoning) + +```yaml +plan: + id: unified-ce-unified-plan/v1 + status: implementation-ready + created: 2026-09-07-1721 + delivery: one branch (doctrine/maker-never-holds-the-instrument), one PR, own commits +``` + +## Problem + +Commit `26a527c` ("restore the single resident document") merged the corpus +correctly but reasoned about enforcement incorrectly, three ways: + +1. **It minted enforcement law in the maker's voice.** CONST-E6 ("make any + principle that can fail a command fail that command") instructs the agent + doing the work to construct the machinery that judges that work. The + settled doctrine (wiki canon `reviewer-agent-separation`, ten sources) is + the opposite: the maker cannot be the sole checker; the check must be + structurally separated. The reward-tampering literature measures the + exploit class (arXiv:2406.10162, arXiv:2609.00069). +2. **It deleted the refusal channel on a conflation.** The TTSR plugin was + retired because "an interrupt can only inject text the agent already + has." An interrupt that re-injects resident text is redundant; an + interrupt that *refuses* the violating write re-fires at the decision + point — after compaction, at turn 40 — which residency cannot do + (wiki `compelled-retrieval-gate-limits`, `pin-or-gate` measurements). +3. **It flipped the corpus gate inside the same commit as the corpus it + gates** ("no legal intermediate commit exists") — the expedience plea the + evaluator-boundary doctrine exists to refuse. + +The residency merge itself stands: the maker's law is resident, single, and +always-on. What changes is who enforcement doctrine is for and who may +touch the instruments. + +## Doctrine + +The constitution is the maker's law — obligations written to the agent doing +the work. Instrument doctrine (how gates are designed, keyed, enrolled, and +changed) is not maker law: it moves to `ENFORCEMENT.md`, read by the channel +that owns the instruments and never loaded into the maker's context. The +maker's side of the boundary is one rule, action-keyed so no role inference +is needed: whatever your change must pass is read-only to you; you cannot +enumerate your graders, so the ban attaches to the judgment surface class, +not to whether you believe it grades this task. + +## Requirements + +- **R1 — Retire CONST-E6** (Prefer the Gate) and **CONST-E8** (The Evaluator + Is Not the Agent's to Edit): both permit the maker to author or edit the + instrument (E6 by instruction, E8 by its own-commit exception). Ids vacate + forever; citations to them must resolve nowhere in the corpus. +- **R2 — Mint CONST-E9** (Never Edit What Grades Your Work) in the + Application section, action-keyed: the ban attaches to the surface class + (lint configs, thresholds, baselines, CI checks, rubrics, validators), and + a needed gate is a proposal to the owner and a wait, never a build by the + graded. +- **R3 — Repoint CONST-G5**: the gate stays the final word; disagreements + escalate to the channel that owns the instrument, never resolved by the + maker editing the gate. +- **R4 — Vacate CONST-E5** from the maker corpus; its recomputation doctrine + continues in `ENFORCEMENT.md` for the instrument owner. +- **R5 — Write `ENFORCEMENT.md`**: the ladder (type > command > refusal at + the decision point > resident prose as the floor), gate-design law, + instrument-change discipline (land alone, red before green, other hands), + enrollment law (clean tree, no baselines, warn is dominated, carriage + proven at the published surface), and the historical correction to the + 2026-09-01 rationale. +- **R6 — Reconcile prose**: `CONCEPTS.md` residency entry, `AGENTS.md` corpus + section and E-family row, `README.md` counts and quick start, + `scripts/validate-constitution.ts` docstring, and annotations on the two + solutions docs that cite the retired ids or the superseded rationale. +- **R7 — No new tests.** The admission gate ran (skill://choose-test-layer + step 0): this amendment proposes none; verification is the repo's + pre-existing corpus gate, which has real non-test consumers (CI and the + pre-commit hook). + +## Verification Contract + +| # | Check | Command | Expected | +|---|---|---|---| +| 1 | corpus gate | `deno task test` | `valid: 38 rules across 6 yaml blocks in 1 files, 9 families`, exit 0 | +| 2 | reassignment | `deno task test --against 26a527c` | E5/E6/E8 reported vacated, E9 minted, no reassignment errors | +| 3 | citation sweep | `grep -nE 'CONST-E[568]' CONSTITUTION.md` | zero lines | +| 4 | lint | `deno lint` | clean | +| 5 | clean tree | `git status --porcelain` | empty after commits | + +## Key technical decisions + +```yaml +- id: KTD1 + decision: Split by audience, not by presence. + why: The pre-26a527c resident/retrieved split failed on presence; that + failure is dead and stays dead. The instrument doctrine's reader is the + instrument owner at build time — a moment where retrieval is correct. + (session-settled: user-directed — "the constitution should be for the + maker only".) +- id: KTD2 + decision: E9 is action-keyed ("never edit what grades your work"), not + role-keyed. + why: The document is always-on for every reader — makers, reviewers, + advisors — and the reader cannot be relied on to know its role or to + enumerate its graders. The act is recognizable in the moment; the role + is not. (session-settled: user-directed.) +- id: KTD3 + decision: The validator's docstring is repointed, its behavior unchanged. + why: The corpus gate is the instrument that grades this amendment; E9 + forbids editing it in service of this work. The docstring's retired-id + citation is prose repair, not behavior change. +- id: KTD4 + decision: No gate change accompanies the corpus change. + why: 26a527c's same-commit gate flip is the violation being corrected; + this amendment ships with the gate's behavior untouched. +``` + +## Research record + +- Wiki (taste, canon band): `reviewer-agent-separation` (the maker cannot be + the sole checker; the check must be structurally separated), + `form-checking-gate-is-a-ritual` (the governed party writing the checked + field has no independent witness), `compelled-retrieval-gate-limits` + (presence is not conformance), `restraint-gates-must-be-emission-gated` + (a reminder is not a refusal). +- Web (substance): arXiv:2406.10162 (reward tampering), arXiv:2609.00069 + (harness tampering in self-improving agents), arXiv:2609.02246 + (deterministic guardrails for self-improving agents). +- Destructive review: three assumptions surfaced (separation doctrine's + warrant band; residency's narrowed survival; the non-resident doctrine + file's audience-moment distinction); lens: band vs weakest atom plus claim + vs bytes; all three survive, the second narrowed. diff --git a/repos/constitution/docs/plans/2026-10-09-0320-refactor-constitution-rewrite-plan.md b/repos/constitution/docs/plans/2026-10-09-0320-refactor-constitution-rewrite-plan.md new file mode 100644 index 00000000..0a23652c --- /dev/null +++ b/repos/constitution/docs/plans/2026-10-09-0320-refactor-constitution-rewrite-plan.md @@ -0,0 +1,1175 @@ +--- +title: Constitution Rewrite - Inner-Loop Laws, Outer-Loop Enforcement - Plan +type: refactor +date: 2026-10-09 +topic: constitution-rewrite +artifact_contract: ce-unified-plan/v1 +product_contract_source: ce-brainstorm +execution: code +--- + +# Constitution Rewrite - Inner-Loop Laws, Outer-Loop Enforcement - Plan + +## Goal Capsule + +- **Objective:** A coding agent that vendors the constitution carries only what it can act on while it works: 17 laws, at most 1,800 words, each one a sentence, its harm, and a wrong/right pair from a real public incident. Whoever grades its work finds every check, mechanism, severity, waiver and judging rule in `ENFORCEMENT.md`, keyed to those laws. Every id a reader has ever cited resolves to its new home, by machine in the corpus and by table in this plan. +- **Means:** Rewrite `CONSTITUTION.md` to Appendix A (KTD7). Give `ENFORCEMENT.md` a per-law corpus with lineage (KTD1-KTD4). Have a separate instrument owner extend the validator (KTD5). Migrate the live surfaces in this repo (KTD9). +- **Authority:** Conductor brief c05, rulings c06, steer c07 (the overfit gate) and rulings c08 and c09 (strict failure incidents, the termination rule) settle every product question. `CONSTITUTION.md` governs what a law means; `ENFORCEMENT.md` governs how an instrument is changed; `AGENTS.md` governs commit, verification and surface-class discipline. `AGENTS.md`, `CONSTITUTION.md` and `README.md` are human-controlled: the conductor takes their full text to the owner, and nothing merges without that approval. +- **Execution profile:** One branch, `refactor/constitution-rewrite`, cut from `origin/main` and published as a single-layer `gh stack`, opened as one PR with three commits in order: the plan, the validator, then the corpus and its surfaces (KTD5, KTD10). +- **Stop conditions:** + - Stop if `wc -w CONSTITUTION.md` exceeds 1,800. + - Stop if any law's example cannot be traced to its Appendix E source. + - Stop if any law has fewer than two independent incidents in Appendix E (R21). + - Stop before committing any `CONSTITUTION.md` text if gate 1, 2 or 3 (R21-R23) has not run on that exact law text, or if the conductor has not ruled on every gate 3 flag. + - Stop if the new validator passes on the `origin/main` tree. + - Stop if any scratch violation in the Verification Contract exits 0. + - Stop if `--against origin/main` reports an unaccounted id. + - Stop if the validator owner's run had the law text in its context. + - If commit signing fails, report the exact error and leave the git config alone. + - Never use `--no-verify`, never force-push, never run mutation or Stryker locally. +- **Who finishes:** The maker (`ce-work`) does U2-U5. The instrument owner, a fresh-context subagent, does U1. The parent agent integrates and verifies (U5) and opens the PR. The conductor takes the text to the owner and merges. + +--- + +## Product Contract + +Product Contract preservation: changed R1, R5, R6, R7, R8, R9, R10, R12, R13, R15, R17, R18 and R20; added R19-R25. Each change applies a c06 ruling, the c07 overfit gate, or the c08 and c09 rulings; no requirement was dropped. + +### Summary + +Rewrite `CONSTITUTION.md` as 17 inner-loop laws in four sections (Model the domain, Shape the code, Prove it, Finish) under a one-line preamble. Each law has exactly four fields: `id`, `law`, `why`, and `example: {wrong, right}`. `ENFORCEMENT.md` keeps its doctrine and gains a versioned corpus: + +- a law-keyed entry per law: a stable obligation handle, an `absorbs:` list, check questions with criteria, mechanism rungs, severity and waiver; +- three judging rules, G3, G4 and G5, which keep their ids. + +A fresh-context instrument owner extends the validator to the new shape and to lineage-by-handle. The human-readable id mapping stays in this plan (Appendix B). + +### Problem Frame + +The maker reads `CONSTITUTION.md` in its context window on every turn (`AGENTS.md:5` `@`-imports it). At 693a6d7 the file is 4,054 words (`wc -w`). All 36 rules carry `gate:` and `check:`, and only 8 carry an `example:` (D4, P2, B2, B3, B6, B5, P3, S4). The maker cannot run a `check:`. Each one is an instruction to lint, review or mutation, read by an agent that executes none of them. That text is also where the contradictions live: CR-1 (T12's check against N2's check) set one check against another, not one law against another, and it took PR #27 to patch. + +Ids churn. T4 and T11 were vacated (#26, #25). The consumer cites 11 ids that no longer exist on `main` (Appendix B2), and 31 of those citing lines are `CONST-E4` alone. + +`ENFORCEMENT.md` already declares itself the outer-loop home ("Never `@`-import this file into a maker's context", `ENFORCEMENT.md:3`), so the split has somewhere to go. + +### Key Decisions + +- **Two audiences, nothing duplicated.** `CONSTITUTION.md` is the inner loop. Constraints, sampling, audit and verdict live in `ENFORCEMENT.md`. (session-settled: user-directed, brief c05 - chosen over keeping `gate`/`check` inline, which is context noise to an agent that cannot run it and is where CR-1 lived.) +- **Four fields per law: `id`, `law`, `why`, `example: {wrong, right}`.** No `gate`, `check`, severity, waiver or tool name. (session-settled: user-directed, c05 and c06 OQ7 - chosen over flat `wrong`/`right` keys, because "exactly four keys" is then literally checkable.) +- **The merge map is the brief's, with c06's folds.** Merged into one law each: + - B1+B2+B3+B6+P1+P2, D1+B5, N1+N2, T8+T15+T9+T14, T3+T13, E7+E9 (c08 removes W3 and W2 from E7 and S2); + - D3, W2 and W3 are retired: under c08's strict gate 1 none has two failure incidents behind its clause. P3, retired under c08, is absorbed by T12 under c09: T12's new wording ("never from its name or location") carries P3's "never by folder", and its second incident is P3's purity rule keyed on a filename; + - under c09, T14 is retired as a law by ruling, and P1, B5 and T9 are cut by the termination rule (gate 3 still flagged them). Each one's guidance becomes a technique in its host's ENFORCEMENT entry, and its id is absorbed there (Appendix E). + + Kept: B4, D2, D4, N3, T10, T12, S1, S3, S4, W1. G3, G4 and G5 become ENFORCEMENT judging rules. (session-settled: user-directed, c05 and c06 OQ4.) +- **17 laws.** The binding limit is the word budget, not the count; c09's termination rule prefers fewer, well-evidenced laws. (session-settled: user-directed, c06 OQ5 and c09.) +- **A law whose obligation survives keeps its id, even when merged.** It takes the lowest surviving id. (session-settled: user-directed, c05 - chosen over today's rule that a changed obligation vacates the number, `CONCEPTS.md:11`, which would vacate every merged id.) +- **Lineage is machine-checked in ENFORCEMENT; the prose table lives in this plan.** Each law-keyed entry carries a stable obligation `handle` and an `absorbs:` list, and `--against` checks lineage through them. (session-settled: user-directed, c06 OQ2.) +- **Two kinds of ENFORCEMENT entry.** A law-keyed entry must name a live law. Judging rules G3, G4 and G5 keep their ids and are exempt from that check. (session-settled: user-directed, c06 OQ3.) +- **T12 keeps its id; its handle is TEST-OBLIGATION.** (session-settled: user-directed, c06 OQ6.) +- **The validator change is written by a fresh-context subagent that never saw the law drafts.** It lands as its own commit in this PR, shown failing on the old corpus and passing on the new, with both owners named in the PR body. CONST-E9 holds; there is no declared breach. (session-settled: user-directed, c06 OQ1.) +- **Every example comes from public history: this repo or public systemfsoftware repos.** A law with no public incident does not stand alone. (session-settled: user-directed, c06 OQ8.) +- **A law stands only on two independent failure incidents.** A failure is code or a PR that broke the law, a revert, a failing command, or a review that rejected the violation; plan or review prose counts only where it names a concrete code location at a SHA. Independent means a different PR or commit. No single document or PR supplies incidents for more than two laws. A fixed incident is anchored at the fix's parent, with the fix hunk. (session-settled: user-directed, c07, c08 and c09.) c09 is the last redraft round: a law still flagged by gate 3 under (a), (c) or (d), or left with fewer than two qualifying failures, is cut from `CONSTITUTION.md`; its guidance becomes an ENFORCEMENT technique and its id is absorbed. Appendix E records each law's pair and each cut. +- **The rewrite claims structure, not better agents.** Nothing here measures behaviour. A held-out evaluation (old against new constitution on unseen tasks) does not exist yet; it belongs to the replay evaluator, which can ablate one law at a time using each entry's `incidents:` (R25). (session-settled: user-directed, c07.) +- **Live surfaces migrate; dated `docs/plans` keep old ids as records.** (session-settled: user-directed, c06 OQ9.) +- **`AGENTS.md` "Writing a Rule" and "Changing a Rule" change in this PR.** The family registry keeps G, now for the judging rules. (session-settled: user-directed, c06 OQ10.) +- **The consumer migration is a later PR in the consumer repo.** This PR only produces the mapping. (session-settled: user-directed, c05.) + +### Requirements + +**The resident law** + +- R1. `CONSTITUTION.md` is the Appendix A text: 17 laws in four sections ordered by when the agent needs them (Model the domain, Shape the code, Prove it, Finish). +- R2. Every law has exactly `id`, `law` (one sentence addressed to "you"), `why` (the harm), and `example` with exactly `wrong` and `right`, all strings. +- R3. A one-line preamble says to read every law by its purpose. +- R4. No `gate`, `check`, severity, waiver or tool name appears in the file. +- R5. The whole file is at most 1,800 words by `wc -w`, and the PR body reports the number. Appendix A measures 1,273. +- R6. No private repository is named anywhere in the change. Every example comes from this repo's or a public systemfsoftware repo's history, with its source cited in Appendix E. +- R20. A law carries only clauses with two failure incidents behind them (R21). Under c08 that removes D3's branding duty from CONST-D1, P3's "never by folder", T8's forwarding-helper clause, W2's challenge duty from CONST-S2 and W3's declaration duty from CONST-E7. Under c09, CONST-D1 drops "free of casts" (casts were B5's), CONST-T8 drops "test a pure decision directly" and its mock clause (one qualifying failure), and CONST-B1 is only "effects at the edges, as values". T12's c09 sentence carries P3's "never by folder" again, now with two failures. + +**The overfit gate (c07)** - gates 1-3 run, and are recorded, on the exact law text before any `CONSTITUTION.md` text is committed. Any later change to a `law` or `why` sentence re-runs them. + +- R21. Gate 1 (c08, strict): every law, and every clause of it, has at least two independent FAILURE incidents: code or a PR that broke it, a revert, or a review that rejected the violation. A later doc, plan or amendment that applies the law is not an incident; it may only point to one. Two incidents of one law come from different PRs or commits, not two symptoms of one change. Each ref is a commit SHA plus `path:line` at that commit, where `git show :` prints the violating code or the review text. Appendix E lists them. A law left with fewer than two is merged into a neighbour or cut; a clause left with fewer than two is removed. +- R22. Gate 2: no `law` or `why` sentence names a package, file, path, tool, CLI, suffix, framework or date. The example may. The two greps in the Verification Contract (Gate 2 rows) run over the extracted sentences and their output is recorded. +- R23. Gate 3: a fresh-context reviewer from a different model family sees only the law sentences, their `why` lines and the Appendix E refs. Per law, evidence first, it judges (a) wording broader than its incidents, (b) redundancy, (c) truth and use on an unrelated Effect-TS codebase, (d) tool or mechanism dressed as law. Every flag goes to the conductor unresolved; the conductor's ruling precedes the corpus commit. The model that actually ran is recorded. +- R24. The PR body makes no claim that the rewrite improves agent behaviour. It may claim no internal contradictions (the validator), no inner-loop noise (no `gate`/`check` fields), the word budget, and full id lineage. It states that a behavioural held-out evaluation does not exist yet and is the replay evaluator's job. +- R25. Each law-keyed ENFORCEMENT entry carries `incidents:`, the Appendix E refs that justify the law, so a replay evaluator can remove one law, re-score, and cut laws that move nothing. + +**The outer loop** + +- R7. `ENFORCEMENT.md` keeps its current doctrine text and gains a versioned corpus. Each law has exactly one law-keyed entry carrying: + - its handle and `absorbs:` list (Appendix C); + - check questions with explicit criteria; + - its mechanism rungs (type, command, refusal, review); + - its severity and waiver rule; + - its `incidents:` (R25). + + The corpus also carries one `retired:` list: each id whose obligation was removed, with its reason (D3, W2, W3 under c08). +- R8. G3 (P0-VERDICT), G4 (PURPOSE-READING) and G5 (SUPREMACY) are judging rules in the corpus. They keep their ids and carry their current obligations. Where G3 says "declared under CONST-W3" today, it says "declared in the change itself, naming the law and the case": the waiver stays a reviewer-side rule, while the maker-side declaration duty is retired with W3 (R20). +- R9. Every clause of an absorbed or kept rule's `do`, `dont`, `check` and `scope` that is not in the new law text lands in that law's entry criteria: + - P1's one path by exhaustive match, and P2's complexity-1 measure, go to B1 as a technique (c09); + - B5's decode, never cast goes to D1 as a technique (c09); + - T9's pin-before-delete, T14's property scope and generators, and the mock guidance go to T8 as techniques (c09); + - T15's investment order goes to T8; + - T3's mutation gate and T13's test-set verdict go to T3; + - N2's allowed-suffix convention goes to N1; + - B6's ordering-by-types goes to B1 as a technique, applied where one description carries the interaction; + - S4's merge-base delta and T12's behavioural-requirement scope come from PR #27 (KTD11). + + Clauses of D3, W2 and W3 are not carried: those ids are retired (R20, Appendix B). P3's clauses go to T12's entry (c09). + +**Ids and mapping** + +- R10. Every current id and every id the consumer cites maps to a law, a judging rule, an ENFORCEMENT doctrine section, or "retired: obligation removed" with a reason (Appendix B). +- R11. The mapping lists every consumer citation outside `repos/` at consumer `origin/main` 3ab8edca, with its new target (Appendices B and D). + +**The validator** + +- R12. `deno task test` fails when any of these holds: + - a law lacks exactly the four fields, or `example` lacks exactly `wrong` and `right`; + - `CONSTITUTION.md` exceeds 1,800 words; + - a law has zero or more than one law-keyed entry; + - a law-keyed entry names no live law; + - handles are not unique across the corpus; + - an id appears more than once across live laws, `absorbs:` lists and the `retired:` list, or a `retired:` item lacks a reason; + - a citation in either file resolves to neither a law, a judging rule, nor an absorbed id (a retired id is not a valid citation); + - a law-keyed entry carries fewer than two `incidents:` (c08, OQ11). + + It keeps the coverage-before-schema check and the unmeasurable exit (3). +- R13. `deno task test --against ` accounts for every id present at `` as live, absorbed, judging or retired. Where `` carries handles, it fails on an id whose handle changed and on an absorbed or retired id that returns as live. Where `` has no handles (`origin/main` today), its success line says the comparison was accounting-only. +- R14. The extended validator passes on the PR head. It fails on each scratch violation V1-V12 (Verification Contract) and on the `origin/main` tree. Every run is executed locally by the parent and recorded. +- R15. U1's owner writes the validator change without the law text in its context and lands it as its own commit. The PR body names both owners. + +**Repo surfaces** + +- R16. `README.md` matches the new shape: the badge count, the "all 36 rules" sentence, the Articles table (it becomes the four sections), and the Machine Validation excerpt and description. +- R17. Live in-repo text follows the mapping and the new schema: + - `ENFORCEMENT.md:25` (CONST-E9 becomes CONST-E7); + - `docs/solutions/architecture-patterns/a-test-never-takes-its-expected-value-from-the-code-under-test.md:27-29,40` (T10's quoted `dont` line, and E9); + - `CONCEPTS.md:8,11,21` (Constitution corpus, Rule, Corpus gate); + - `AGENTS.md:28,34` and its "Changing a Rule", "Minting an ID" G row, and `deno task test` comment lines. +- R18. The PR body's first line states that `AGENTS.md`, `CONSTITUTION.md` and `README.md` are human-controlled and need the owner's approval of the final text before merge. The body notes that PR #27's commits bypassed the hooks (no `core.hooksPath` in that worktree). Its claims obey R24. +- R19. Dated `docs/plans` files are not edited. + +### Acceptance Examples + +- AE1. An agent that `@`-imports `CONSTITUTION.md` reads 17 laws and no `gate`, `check` or severity text (R1-R4). +- AE2. A reviewer grading a change against CONST-T12 finds its criteria in the CONST-T12 entry of `ENFORCEMENT.md`, under handle TEST-OBLIGATION (R7). +- AE3. A consumer plan citing CONST-E4 resolves through Appendix B2 to CONST-E7, and a consumer file citing CONST-P2 resolves to CONST-B1 through Appendix B1 and through CONST-B1's `absorbs:`; a file citing CONST-D3 finds it retired, with the reason, in Appendix B1 and in the corpus's retired list (R10, R13). +- AE4. A later amendment that renames CONST-T12's handle fails `deno task test --against ` (R13). +- AE5. Deleting CONST-B4's ENFORCEMENT entry fails `deno task test` (R12). + +### Scope Boundaries + +- No consumer edits; the consumer migration is a later PR there. +- The PR #27 branch (`fix/t12-n2-suffix-conflict`) is untouched. #27 closes unmerged once this PR opens; its useful content lives on here, in the CONST-T12 and CONST-S4 ENFORCEMENT criteria (KTD11). +- No new families; G stays registered for the judging rules. +- None of these count as done: renaming fields while the checks stay inline; dropping a law with no mapping; invented examples; a plan in place of the rewrite; a gate wired but turned off. + +### Outstanding Questions + +None. c06 resolved OQ1-OQ10, and c08 resolved OQ11: the validator checks that every law-keyed entry has at least two `incidents:` (R12), written by U1's owner in its own commit; the owner's sign-off on the governed files covers the new check. + +### Sources + +- `CONSTITUTION.md` at 693a6d7: 36 rules; 36 `gate:` and 36 `check:` fields; 8 `example:` fields; 4,054 words. +- `ENFORCEMENT.md:3,7-12,17,19,23-25`; `AGENTS.md:5,28,34`; `CONCEPTS.md:8,11,21`; `README.md:5,39,43-54,58-82`. +- `scripts/validate-constitution.ts:1,39-44,60-67,247-253`; `deno.json:5`; `.husky/pre-commit:1` (`deno task test` on the working tree). +- `docs/plans/2026-09-07-1721-the-maker-never-holds-the-instrument-plan.md:29-31,111-114` (the 26a527c same-commit gate flip, and its repair). +- Consumer `systemfsoftware/systemfsoftware` (public) at `origin/main` 3ab8edca: `git grep -nE 'CONST-[A-Z][0-9]+' origin/main -- . ':!repos/'` finds 208 citing lines across 45 ids; summed per id (Appendix B), 274, because a line that cites two ids counts once for each. The public repos `stryker-js-effect`, `are-the-types-wrong-effect` and `effect-endgame-starter-kit` were searched for N3 incidents and hold none outside vendored copies. + +--- + +## Planning Contract + +### Key Technical Decisions + +- **KTD1. The ENFORCEMENT corpus is one fenced YAML block under a new final `## Corpus` heading.** The block is a map: + ```yaml + version: 1 + laws: + - law: CONST-T12 + handle: TEST-OBLIGATION + absorbs: [] + checks: + - question: ... + criteria: ... + mechanism: [command] + severity: P0 + waiver: ... + incidents: + - consumer docs/solutions/...:27 (2d4c724f #519) + - this repo f843304 + judging: + - id: CONST-G3 + handle: P0-VERDICT + rule: ... + ``` + - `mechanism` values come from the ENFORCEMENT ladder: `type`, `command`, `refusal`, `review`. Old `lint` and `mutation` gates become `command`, and old `type-checker` becomes `type`. Appendix C gives each law's rungs. + - The doctrine sections above the corpus stay byte-identical except line 25. + + `incidents:` lists the Appendix E refs as plain strings, source first. Governs R7, R8, R25. +- **KTD2. Severity is P0 for every law, and the waiver is a declaration in the change.** G3 grades every undeclared violation P0, so each entry states `severity: P0`. Each `waiver` names CONST-E7's declaration: the breach and the case, stated in the change itself. A per-law severity scale would contradict G3. Governs R7, R8. +- **KTD3. Handles are UPPER-KEBAB, unique across laws and judging rules, and frozen once landed (Appendix C).** A handle names the obligation, not the wording, so a reworded law keeps its handle. A changed obligation needs a new id. Governs R7, R13. +- **KTD4. Lineage semantics for `--against `.** + 1. Collect the ids at ``: rule or law blocks in `CONSTITUTION.md`, plus law-keyed and judging entries in `ENFORCEMENT.md` when present. + 2. Each one must be live (a law or a judging rule) or appear in exactly one `absorbs:` list. Otherwise: `FAIL unaccounted id`. + 3. When `` has a corpus, a live id whose handle differs fails as `reassigned`, and an id absorbed at `` that is live now fails as `resurrected`. + 4. When `` has no corpus, the success line appends `; lineage by accounting only, no handles at `. This follows the vacuous-pass doctrine (`ENFORCEMENT.md:19`): a reduced comparison is named, not hidden. + 5. Ids vacated without absorption are still listed as vacated. + + Governs R13. +- **KTD5. Validator ownership and commit order.** + - U1's owner is a fresh-context subagent. It works in an isolated scratch copy of the `origin/main` tree and receives only the validator contract (U1 Approach), never Appendix A. It returns a patch plus its own scratch-fixture evidence. + - Before commit 1, wire the hooks in the executing worktree: run `deno task prepare` (it sets `core.hooksPath .husky`, where `.husky/pre-commit` and `.husky/commit-msg` live) and confirm `git hook run pre-commit` runs `deno task test`. The shared repo config points at `.husky/_`, which does not exist in a worktree, so without this step no hook runs; PR #27's commits bypassed hooks that way. + - Commit 1 is this plan, made before any corpus edit so the hook runs the old validator on the old corpus. + - The maker then writes U2-U4 in the working tree, and the parent applies U1's patch. + - Commit 2 carries only the U1 files. Its own tree (new validator, old corpus) is red by design; the PR body states this and shows it. The pre-commit hook runs `deno task test` on the working tree (`.husky/pre-commit:1`), which already holds the new corpus, so the hook passes without `--no-verify`. + - Commit 3 carries the corpus and surfaces. + - The red run and the green run are executed by the parent in `git worktree` checkouts of the validator commit and the final commit (the Red before and Schema rows; AGENTS.md rule VER1, the verifier is never the maker). + + Governs R14, R15. +- **KTD6. The word budget is whitespace-separated tokens over the whole `CONSTITUTION.md`, the same count as `wc -w`.** Headings, fences and keys count. Governs R5, R12. +- **KTD7. Law blocks are top-level YAML sequences, one fenced block per section, with no `rules:` wrapper.** Appendix A is the normative text, copied byte for byte. The owner's approval may change wording; any change must keep R2-R5. Governs R1-R5. +- **KTD8. A clause trace proves nothing was silently dropped.** The PR body carries a table with one row per `do`/`dont`/`check`/`scope` clause of the 36 rules at 693a6d7, naming where the clause now lives: a law sentence, an entry's criteria, or a judging rule. Clauses that only restate another clause say so. Governs R9. +- **KTD9. Live-surface edits are the R16 and R17 list and nothing else.** `docs/solutions/architecture-patterns/the-vacuous-pass-gate-input-sets.md` quotes dated validator output (`:149-150`) and stays as a record. Governs R16, R17, R19. +- **KTD10. Commit types.** The plan commit is `docs(plans): ...`. The validator commit is `feat(gate)!: ...`, because the corpus shape it accepts breaks. The corpus commit is `refactor(constitution)!: ...`, following 26a527c's restructure precedent, with a `BREAKING CHANGE:` footer naming the removed fields and the merged ids. +- **KTD11. PR #27's two improvements carry into the corpus.** CONST-T12's entry is scoped to behavioural requirements: no rule, runner, project split or tool chooses the requirement, harness or suite that governs a test from its folder or from any part of its name beyond the generic test-file ending the runner uses to discover tests; a lint that governs only a file's name or placement states no testing requirement and is allowed (CONST-N1's naming criteria). CONST-S4's entry has review compute the net line delta from the diff against the merge base of the change and its target branch at the time of review, recomputed whenever the target moves, never from a figure the author supplied. Source: `fix/t12-n2-suffix-conflict` at c3bd625; KTD8's clause trace lists both clauses. Governs R9. + +### Sequencing + +Gates 1-3 (R21-R23) run on the Appendix A law text before U2 starts, and again on the owner's final wording if it changes a `law` or `why` sentence. U1 runs in parallel with U2-U4; U5 depends on all four. + +```mermaid +flowchart LR + P[commit 1: plan] --> U2 & U3 & U4 + U1[U1 validator, isolated] --> U5 + U2[U2 CONSTITUTION.md] --> U5 + U3[U3 ENFORCEMENT corpus] --> U5 + U4[U4 live surfaces] --> U5[U5 integrate: commits 2 and 3, verify, PR] +``` + +### Risks + +- The red intermediate commit (commit 2) breaks `git bisect` on that one commit. That is accepted and declared (c06). +- The owner's wording changes could push the file past 1,800 words. The validator catches this at commit time. +- Two incidents per law guards against fitting one event; it does not show the laws change behaviour. That needs the held-out evaluation R24 names, which does not exist yet. +- Some incidents support two laws (Appendix E lists the shared PRs and fixes); no document or PR backs more than two (c09). Gate 3's redundancy question is where that overlap gets judged. + +--- + +## Implementation Units + +### U1. Extend the corpus validator (instrument owner) + +- **Goal:** `scripts/validate-constitution.ts` enforces R12 and R13 on the two-file corpus. +- **Requirements:** R12, R13, R14, R15. +- **Files:** `scripts/validate-constitution.ts` (including the shebang `--allow-read`), `deno.json` (the `test` task's `--allow-read` adds `ENFORCEMENT.md`). +- **Approach:** Dispatch a fresh-context subagent (`single-unit-coder`) into a scratch copy of the `origin/main` tree. Its whole input is this contract: KTD1's corpus shape with placeholder entries, KTD3, KTD4, KTD6, KTD7's block shape, R12, R13, and the doctrine in `ENFORCEMENT.md`. It is told not to read `docs/plans/` or any rewritten corpus. It builds its own synthetic fixtures in a dot-prefixed scratch directory and deletes them before returning. It returns the patch and its fixture run log. The subagent's id is recorded for the PR body. +- **Test scenarios:** V1-V12 (Verification Contract), run first by the owner on synthetic fixtures, then by the parent on scratch copies of the real corpus. No test file is committed: the repo has no suite, and the validator itself is the gate. +- **Verification:** the parent runs V1-V12 and the red run (KTD5). + +### U2. Rewrite `CONSTITUTION.md` + +- **Goal:** the file is Appendix A. +- **Requirements:** R1-R6, R20. +- **Files:** `CONSTITUTION.md`. +- **Approach:** replace the whole file with the Appendix A block content. +- **Verification:** `wc -w CONSTITUTION.md` is at most 1,800, and `diff` against Appendix A shows nothing. + +### U3. Add the ENFORCEMENT corpus + +- **Goal:** each law and judging rule has its entry per KTD1-KTD3. +- **Requirements:** R7, R8, R9. +- **Files:** `ENFORCEMENT.md`. +- **Approach:** + - Append `## Corpus`. + - Write each law-keyed entry from Appendix C (handle, absorbs, rungs), with `incidents:` from Appendix E. Derive its checks and criteria from the `gate`, `check`, `do`, `dont` and `scope` text of every id it keeps or absorbs at 693a6d7, with no new obligation. + - Write CONST-T12's and CONST-S4's criteria per KTD11. + - Write G3, G4 and G5 from their current text, with G3's CONST-W3 reference rewritten per R8. + - Change line 25's CONST-E9 to CONST-E7. + - Build the KTD8 clause trace for the PR body while writing. +- **Verification:** `git diff origin/main -- ENFORCEMENT.md` shows changes only at line 25 and in the new final section, and the clause trace has no unmapped row. + +### U4. Migrate the live surfaces + +- **Goal:** no live text in this repo describes the old schema or cites an absorbed id. +- **Requirements:** R16, R17, R19. +- **Files:** `AGENTS.md`, `CONCEPTS.md`, `README.md`, `docs/solutions/architecture-patterns/a-test-never-takes-its-expected-value-from-the-code-under-test.md`. +- **Approach:** + - `AGENTS.md:28`: the corpus bullet names the four sections. + - `AGENTS.md:34` "Writing a Rule": the four law fields, plus the ENFORCEMENT entry fields. + - `AGENTS.md` "Changing a Rule": the c05 id policy, and handles frozen per KTD3. + - `AGENTS.md` "Minting an ID": the G row's purpose becomes the ENFORCEMENT judging rules. + - `AGENTS.md`: the `deno task test` comment names two files. + - `CONCEPTS.md` Rule (`:11`) and Corpus gate (`:21`): restated to the two-file corpus and the new id policy. The Constitution corpus entry (`:8`) is unchanged unless its wording names one file. + - `README.md`: the R16 list. + - The solutions doc: its T10 quote becomes T10's `law` sentence, and E9 becomes E7. +- **Verification:** the DEL1 command in the Verification Contract. + +### U5. Integrate, verify and open the PR + +- **Goal:** three signed commits on `refactor/constitution-rewrite` and one open PR. +- **Requirements:** R14, R15, R18. +- **Approach:** + - Follow KTD5's commit order and run every Verification Contract row. + - Adopt the branch with `gh stack init` and check the `gh stack view` trunk. + - Push with a plain `git push -u`. + - Run `gh stack submit --auto --open`. + - Write a PR body with: the R18 first line; both owners; the red/green evidence; the `wc -w` number; V1-V12 results; the KTD8 clause trace; and a link to Appendix B. + +--- + +## Verification Contract + +Every row is run by the parent on the PR head unless it says otherwise. A scratch row runs on a temporary copy of the PR-head tree with one edit and is never committed. Inside table cells, `\|` is the markdown escape for a pipe: type a plain `|` when running a command. + +| Row | Command | Expected | +|---|---|---| +| Schema | `deno task test` | exit 0; the success line counts 17 laws and 3 judging rules | +| Lineage | `deno task test --against origin/main` | exit 0; the success line names the accounting-only comparison | +| Words | `wc -w CONSTITUTION.md` | at most 1800 | +| Red before | new validator in a worktree of commit 2 (old corpus) | exit 1 with FAIL lines naming the old fields | +| V1 | add a `gate:` key to one law | exit 1, unknown field | +| V2 | delete one law's `why` | exit 1, missing field | +| V3 | delete one `example.right` | exit 1, example shape | +| V4 | append 120 words to one `law` | exit 1, word budget | +| V5 | delete CONST-B4's law-keyed entry | exit 1, law without entry | +| V6 | point one entry at `CONST-B9` | exit 1, entry names no live law | +| V7 | give two entries the same handle | exit 1, duplicate handle | +| V8 | add `CONST-B4` to an `absorbs:` list | exit 1, absorbed id is live | +| V9 | remove `CONST-N2` from every `absorbs:` list, then `--against origin/main` | exit 1, unaccounted id | +| V10 | scratch repo: commit the PR-head corpus, change CONST-T12's handle, commit, `--against HEAD~1` | exit 1, reassigned | +| V11 | cite `CONST-E9` in `ENFORCEMENT.md` doctrine text, with it absorbed | exit 0 (an absorbed id resolves); cite `CONST-Q1`: exit 1, dangling | +| V12 | remove a closing fence | exit 1, coverage | +| DEL1 | `git grep -nE 'CONST-(D3\|P1\|P2\|P3\|B2\|B3\|B5\|B6\|N2\|T9\|T14\|T15\|T13\|E9\|W2\|W3)\b' -- . ':!docs/plans'` | matches only `absorbs:` and `retired:` lines in `ENFORCEMENT.md` | +| Gate 1 | Appendix E: `git show :` prints each ref's cited line, each fix commit exists, each law has two refs from different PRs or commits, and no PR or document backs more than two laws | 17 of 17 | +| Gate 2 code tokens | extract every `law` and `why` line to a scratch file, then ``grep -nP '`\|\*\.\|\.(ts\|js\|md\|json\|ya?ml)\b\|/\|\b\d{4}-\d{2}-\d{2}\b\|\b\d{4}\b\|\b[a-z]+[A-Z]\w*\|\w+\(\)\|@\w\|#\d'`` | exit 1, no output | +| Gate 2 tool names | `grep -nPi` over the same file for the tool, runner and framework list in Appendix E | output recorded; any hit is reported, with the reading of the word | +| Gate 3 | blind reviewer per R23 on the law text being committed | every flag listed for the conductor, model recorded | +| Private names | for each name from `gh repo list systemfsoftware --visibility private`, search `git diff origin/main...HEAD` for `systemfsoftware/` and `github.com/systemfsoftware/` | no match. A bare name is not searched: one private repo's name equals a file this diff edits, so a bare-name hit proves nothing | +| Commits | `git config core.hooksPath` and `git hook run pre-commit` before commit 1; `git log --format='%h %G? %s' origin/main..HEAD` | `.husky`; the hook runs `deno task test`; `G` on every commit; conventional subjects | +| Stack | the OP13b `gh stack view --json \| jq -e` check | exit 0 | + +--- + +## Definition of Done + +- U1-U5 are done, and every Verification Contract row has passed in the run that ships them. +- The three commits are signed and in KTD5's order. The PR is open, not a draft, and its body carries every U5 element. +- No scratch fixture, `git worktree` or abandoned edit remains, and `git status` is clean. + +--- + +## Appendix A - Normative law text + +Measured with `wc -w` on the block content: 1,273 words. Each example's source is the first incident for that law in Appendix E. + +````markdown +# Constitution + +Read every law by its purpose: where its words and its harm part ways, the harm decides. + +## Model the domain + +```yaml +- id: CONST-S3 + law: Define the outside contract first, and model only what a known requirement needs. + why: Structure built for a consumer nobody has never pays off, and it constrains what follows. + example: + wrong: The CliRequest schema was exported though nothing decoded it; every use was a type position, and its obligation scan timed out at 15 seconds. + right: Export a schema only when a consumer decodes with it; derive the types from unexported bases. +- id: CONST-D1 + law: Close your types so an illegal value cannot be constructed. + why: A value the type could have refused reaches runtime, and every check downstream trusts it. + example: + wrong: A lock helper took a lock spec and a nullable adapter, so a spec that required the lock, paired with no adapter, ran its body unlocked. + right: One union of the valid spec-and-adapter pairs made the unlocked case impossible to construct. +- id: CONST-D2 + law: Give every distinct failure its own tagged variant. + why: Callers cannot branch on the real failure, and distinct errors collapse into one case. + example: + wrong: Generator exhaustion and a real counterexample both became one "refuted" error built from a placeholder, so a property that never ran read as refuted. + right: Exhaustion is its own tagged error, and a refutation cannot be built without a real counterexample. +- id: CONST-D4 + law: Model mutually exclusive states as a tagged union, one variant per state carrying only its own fields; keep a plain nullable for a value absent the same way in every state. + why: A state machine hides in a record, and the compiler cannot reject an invalid mix of fields. + example: + wrong: "CheckerDecision { results, needsRetest }: the state is read off a field." + right: CheckFinished | RetestRequired, the second variant produced by the decider's retest branch. +``` + +## Shape the code + +```yaml +- id: CONST-B1 + law: Keep effects at the edges, as values. + why: An effect inside a decision cannot be tested without the world it touches, and a defect hides at the seam. + example: + wrong: The config resolver read a file, decided, resolved the next specifier and recursed inside one async function. + right: A pure step returns the next read as data, and a thin shell performs it. +- id: CONST-B4 + law: Let the shell import the core, and wire every implementation at one composition root; the core never imports the shell, a database, or a framework. + why: A decision chained to infrastructure cannot be tested or replaced. + example: + wrong: A CLI adapter imported the Node standard-IO layer and provided it to itself, below the composition root. + right: The adapter declares that it needs standard IO, and the composition root provides it. +- id: CONST-N1 + law: Organise code by what it does, and name every file and folder for its job; a name must answer "of what?". + why: One change scatters across the tree, and a bucket named for a layer says nothing a reader can check. + example: + wrong: Packages were nested into role tiers (core, testing, lint) that grouped packages sharing nothing a reader could check. + right: The tiers were reverted; folders name product families. +- id: CONST-N3 + law: Give each module one responsibility, and split it when its tests need elaborate setup. + why: Nobody can reason about the whole module, and its tests grow brittle. + example: + wrong: One module held a config type, its text parser, a process-wide cache with a test-only reset, and the file read, so its tests needed a fake file system. + right: It split into a schema, a translator and an executor that does the read, and each is tested on its own. +- id: CONST-S1 + law: Fix the root cause; when the design is wrong, restructure it. + why: A patched symptom comes back. + example: + wrong: Every transaction rollback was mapped to a version conflict, so any bug in the transaction looked like a race and retries walked an order into a rollback the customer never earned. + right: The duplicate check moved inside the serializable transaction, and only a real serialization failure retries. +- id: CONST-S2 + law: Justify every choice by these laws, never by the file next to it or a prior plan's wording. + why: An unexamined default hardens into a rule, and each copy seeds the next. + example: + wrong: A planning session wrote an adapter's package name into law, and every later import and plan inherited the misnaming. + right: Authority traces to the architecture; the package was renamed for what it does and the old name deleted in the same change. +- id: CONST-S4 + law: Treat every line as a liability; delete, unify, or make the bad state unconstructable before you add. + why: The codebase only grows, and rot survives every patch. + example: + wrong: A thirteen-role taxonomy grew to 100 rules; one role shipped 5 rules against 0 files. + right: Thirty rules were deleted at no cost; the compiler already refused each violation. +``` + +## Prove it + +```yaml +- id: CONST-T8 + law: Test the published surface with real inputs and outputs. + why: A test that stops short of what ships stays green while the shipped artifact is broken. + example: + wrong: Tests imported the package's source, so it published with no built output and no consumer could import it. + right: The package ships its build, and the pack check reads what each tarball contains. +- id: CONST-T10 + law: Take every expected value from an oracle the code under test did not produce - a spec literal, an independent fixture, a law between two views, or a second implementation. + why: A test that compares the code with itself cannot fail when the code is wrong. + example: + wrong: A snapshot of 500 observed depths moved whenever the generator, the schema, or the seed moved. + right: The snapshot kind was deleted rather than re-recorded. +- id: CONST-T3 + law: Make every test able to fail when the behaviour it names breaks. + why: A suite that notices nothing certifies nothing, and a toothless test hides among the ones that work. + example: + wrong: Round-trip laws drew their inputs from the schema's own generator, so every widened pattern survived. + right: Rejection properties whose inputs come from the domain contract killed the survivors. +- id: CONST-T12 + law: Decide what applies to code (which checks, tests and requirements) from what it is and does, never from its name or location. + why: A rename or a move silently drops a requirement, or applies one where it does not belong, while everything stays green. + example: + wrong: Mutation targets were chosen by a path label; when fixtures moved, five were enrolled, one built to fail. + right: A target is selected by what it is, a workspace package the lockfile declares. +``` + +## Finish + +```yaml +- id: CONST-W1 + law: Deliver the whole accepted task; shrink it only with the requester's agreement. + why: Half-finished work, and effort spent second-guessing intent. + example: + wrong: The offered shortcut was to drop packages that could not comply from the enrolled set. + right: Every deciding package was enrolled; the one exception was named in the change for the author to rule on. +- id: CONST-E7 + law: Show evidence (a command that passed or a test that ran) before you call work done, and never edit, add, or weaken anything that grades your work. + why: Work called done on no evidence ships broken, and whoever edits the grader reports the score they chose. + example: + wrong: One commit changed the law and flipped the gate that grades it. + right: The next amendment shipped with the gate's behaviour untouched. +``` +```` + +--- + +## Appendix B - Id mapping + +Consumer citations count the lines that cite the id in the consumer at `origin/main` 3ab8edca, outside `repos/`. "plans" is `docs/plans`, "solutions" is `docs/solutions`, and "other" is any other path (Appendix D). + +### B1 - Every id on this repo's `main` (36) + +| Old id | Title on `main` | New target | Consumer citations | Note | +|---|---|---|---|---| +| CONST-G4 | By Purpose, Not Quotation | CONST-G4 (judging rule, PURPOSE-READING) | 2 (2 plans) | Keeps its id in ENFORCEMENT; the maker-facing half is the preamble line. | +| CONST-E9 | Never Edit What Grades Your Work | CONST-E7 | 13 (2 other, 10 plans, 1 solutions) | Merged. | +| CONST-E7 | Evidence Before Done | CONST-E7 | 1 (1 plans) | Lowest surviving id of E7+E9. | +| CONST-G5 | Supreme | CONST-G5 (judging rule, SUPREMACY) | 2 (2 plans) | Keeps its id in ENFORCEMENT. | +| CONST-P1 | Purity | CONST-B1 | 11 (1 other, 9 plans, 1 solutions) | Absorbed (c09 termination rule): gate 3 flagged its pure-function clause as unsupported by its incidents and redundant with B1. One path by exhaustive match is a technique in B1's ENFORCEMENT entry. | +| CONST-D1 | Types Before Logic | CONST-D1 | 1 (1 plans) | Kept as "close your types"; D3 is retired. | +| CONST-D2 | Each Error Its Own Variant | CONST-D2 | 10 (1 other, 7 plans, 2 solutions) | Kept. | +| CONST-D3 | No Primitive Obsession | retired: obligation removed | 10 (9 other, 1 plans) | No failure where a bare primitive stood in for a domain value was found (c08 gate 1). | +| CONST-D4 | Null Is Not a State | CONST-D4 | 10 (4 other, 4 plans, 2 solutions) | Kept. | +| CONST-P2 | The Pure Core Has One Path | CONST-B1 | 9 (7 plans, 2 solutions) | Absorbed with P1; the complexity-1 measure moves to B1's ENFORCEMENT entry. | +| CONST-B1 | Functional Core, Imperative Shell | CONST-B1 | 8 (1 other, 6 plans, 1 solutions) | Survives as "effects at the edges, as values"; absorbs B2, B3, B6, P1 and P2. | +| CONST-B2 | Effects Are Values | CONST-B1 | 3 (3 plans) | Merged. | +| CONST-B3 | The I/O Sandwich | CONST-B1 | 15 (1 other, 13 plans, 1 solutions) | Merged; the fixed five-phase sequence is dropped (c08: withdrawn where a case writes before it classifies). | +| CONST-B6 | The Sandwich Order Is Carried by Types | CONST-B1 | 3 (3 plans) | Merged; ordering-by-types is a technique in B1's ENFORCEMENT entry, applied where one description carries the interaction; a generator body does not preserve order in its type (c08). | +| CONST-B4 | Dependencies Point Inward | CONST-B4 | 9 (9 plans) | Kept. | +| CONST-B5 | Decode, Never Cast | CONST-D1 | 7 (7 plans) | Absorbed (c09 termination rule): gate 3 flagged its typed-result clause as broader than its incidents. Decode, never cast is a technique in D1's ENFORCEMENT entry. | +| CONST-P3 | Purity Is Per Function, Not Per Folder | CONST-T12 | 10 (7 plans, 3 solutions) | Absorbed (c09): T12 now decides what applies from what code is, never its name or location; P3's filename-keyed purity rule is T12's second incident. Judging purity by return type is a technique in T12's entry. | +| CONST-T15 | The Testing Trophy | CONST-T8 | 1 (1 plans) | Absorbed; investment order moves to T8's ENFORCEMENT entry. | +| CONST-T8 | Test Public Functions Directly | CONST-T8 | 2 (2 plans) | Survives as "test the published surface"; absorbs T15, T9 and T14. | +| CONST-T14 | Properties Where the Surface Cannot Reach | CONST-T8 | 2 (2 plans) | Absorbed (c09 ruling): a testing technique, not a law. Property scope and generators are a technique in T8's ENFORCEMENT entry. | +| CONST-T3 | Mutation Is the Measure | CONST-T3 | 10 (2 other, 7 plans, 1 solutions) | Lowest of T3+T13; the mutation gate moves to T3's ENFORCEMENT entry. | +| CONST-T13 | Mutation Also Grades the Tests | CONST-T3 | 0 | Merged; the test-set verdict moves to T3's ENFORCEMENT entry. | +| CONST-T9 | Pin the Published Contract Before You Delete a Path | CONST-T8 | 1 (1 plans) | Absorbed (c09 termination rule): gate 3 flagged its trigger as broader than its incidents and redundant with T8. Pin before delete is a technique in T8's ENFORCEMENT entry. | +| CONST-T10 | The Oracle Is Not the System Under Test | CONST-T10 | 5 (1 other, 4 plans) | Kept. | +| CONST-T12 | What a Test Does Comes from What It Calls | CONST-T12 | 1 (1 plans) | Kept (OQ6); restated as TEST-OBLIGATION. | +| CONST-N1 | Organized by What It Does | CONST-N1 | 5 (5 plans) | Lowest of N1+N2. | +| CONST-N2 | Names Scream the Domain | CONST-N1 | 12 (12 plans) | Merged; the allowed-suffix convention moves to N1's ENFORCEMENT entry and tooling. | +| CONST-N3 | Fits in the Head | CONST-N3 | 2 (2 plans) | Kept. | +| CONST-G3 | Constitutional Violations Are Automatic P0 Failures | CONST-G3 (judging rule, P0-VERDICT) | 0 | Keeps its id in ENFORCEMENT; its W3 reference becomes a declaration in the change itself (R8). | +| CONST-S1 | Depth Over Expedience | CONST-S1 | 2 (2 plans) | Kept. | +| CONST-W1 | Scope Discipline | CONST-W1 | 1 (1 plans) | Kept. | +| CONST-S2 | First Principles Over Precedent | CONST-S2 | 1 (1 plans) | Kept. | +| CONST-S3 | API-First Discovery | CONST-S3 | 7 (7 plans) | Kept. | +| CONST-W2 | Challenge Before You Commit | retired: obligation removed | 2 (2 plans) | No failure where a large or irreversible choice went unchallenged was found (c08 gate 1). | +| CONST-W3 | No Silent Bypass | retired: obligation removed | 6 (1 other, 5 plans) | One failure only (consumer gh-285 review, #288). G3's reviewer-side waiver for a declared breach stays (R8). | +| CONST-S4 | Subtract Before You Add | CONST-S4 | 22 (22 plans) | Kept. | + +### B2 - Ids the consumer cites that are not on `main` + +| Old id | Last title | Last on `main` | New target | Consumer citations | Note | +|---|---|---|---|---|---| +| CONST-E1 | Prefer the Gate | 4b790f3 (2026-08-20) | ENFORCEMENT Mechanism (the ladder) | 5 (5 plans) | | +| CONST-E2 | Evidence Before Done | 4b790f3 (2026-08-20) | CONST-E7 | 1 (1 plans) | Same obligation as today's E7. | +| CONST-E3 | A Gate Earns Its Place | 4b790f3 (2026-08-20) | ENFORCEMENT Gate economy | 5 (5 plans) | | +| CONST-E4 | The Evaluator Is Not the Agent's to Edit | 4b790f3 (2026-08-20) | CONST-E7 | 31 (31 plans) | Same obligation as today's E9. | +| CONST-E8 | The Evaluator Is Not the Agent's to Edit | 26a527c (2026-09-01) | CONST-E7 | 2 (2 plans) | Same obligation as today's E9. | +| CONST-G1 | By Purpose, Not Quotation | 4b790f3 (2026-08-20) | CONST-G4 (judging rule) | 1 (1 plans) | Same text as today's G4. | +| CONST-G2 | Supreme | 4b790f3 (2026-08-20) | CONST-G5 (judging rule) | 1 (1 plans) | Same text as today's G5. | +| CONST-T1 | The Testing Trophy | dd5722a (2026-08-27) | CONST-T8 | 1 (1 plans) | Today's T15 obligation. | +| CONST-T2 | Properties Over Examples | dd5722a (2026-08-27) | CONST-T8 | 1 (1 plans) | Today's T14 obligation. | +| CONST-T4 | Behavior Lives Where the Mutator Sees It | 37c076f (2026-09-23) | retired: obligation removed | 18 (18 plans) | Vacated in #26; its purpose is carried by T3 and T8. | +| CONST-T5 | Pin Behavior Before You Rebuild | dd5722a (2026-08-27) | CONST-T8 | 2 (2 plans) | Today's T9 obligation. | +| CONST-T11 | Snapshots and Differentials Are Development-Time Evidence, Never Committed Artifacts | 63e9813 (2026-09-12) | CONST-T10 | 0 | Vacated in #25; its no-self-oracle rule is stated in T10. Not cited by the consumer. | + +## Appendix C - Lineage payload for the ENFORCEMENT corpus + +All 36 ids at 693a6d7 are accounted for: 17 are live laws, 13 are absorbed, 3 are judging rules, and 3 are retired (D3, W2, W3). + +| Law | Handle | Absorbs | Mechanism rungs (from the old `gate:` values) | +|---|---|---|---| +| CONST-S3 | CONTRACT-FIRST | - | review | +| CONST-D1 | CLOSED-TYPES | CONST-B5 | type; command: lint (B5 technique) | +| CONST-D2 | ERROR-VARIANTS | - | command: lint | +| CONST-D4 | STATES-AS-UNIONS | - | command: lint | +| CONST-B1 | EFFECTS-AT-EDGES | CONST-B2, CONST-B3, CONST-B6, CONST-P1, CONST-P2 | type (B6 technique, where it applies); command: lint (B2; P1 and P2 technique); review (B1, B3) | +| CONST-B4 | DEPENDENCIES-INWARD | - | command: lint | +| CONST-N1 | ORGANISED-BY-PURPOSE | CONST-N2 | command: lint (N2); review (N1) | +| CONST-N3 | FITS-IN-THE-HEAD | - | review | +| CONST-S1 | ROOT-CAUSE | - | review | +| CONST-S2 | FIRST-PRINCIPLES | - | review | +| CONST-S4 | SUBTRACT-FIRST | - | review | +| CONST-T8 | PUBLIC-SURFACE | CONST-T15, CONST-T9, CONST-T14 | review | +| CONST-T10 | INDEPENDENT-ORACLE | - | review | +| CONST-T3 | TESTS-CAN-FAIL | CONST-T13 | command: mutation | +| CONST-T12 | TEST-OBLIGATION | CONST-P3 | command: lint (T12, P3) | +| CONST-W1 | FULL-SCOPE | - | review | +| CONST-E7 | EVIDENCE-NOT-SELF-GRADING | CONST-E9 | review | +| | | | | +| CONST-G3 (judging rule) | P0-VERDICT | - | review | +| CONST-G4 (judging rule) | PURPOSE-READING | - | review | +| CONST-G5 (judging rule) | SUPREMACY | - | review | + +## Appendix D - Consumer citations outside `docs/plans` + +| Consumer file | Ids cited | Targets | +|---|---|---| +| `.omp/rules-corpus/solution-problem-type-enum.json` | CONST-B1, CONST-B3, CONST-D2, CONST-D4, CONST-E9, CONST-P1, CONST-T3 | CONST-B1, CONST-D2, CONST-D4, CONST-E7, CONST-T3 | +| `AGENTS.md` | CONST-E9 | CONST-E7 | +| `compound-packs/schema-laws/README.md` | CONST-D4 | CONST-D4 | +| `compound-packs/schema-laws/tagged-unions-over-state-by-presence.md` | CONST-D4 | CONST-D4 | +| `docs/residual-review-findings/gh-285.md` | CONST-W3 | retired | +| `docs/solutions/architecture-patterns/constructor-rule-boundary.md` | CONST-B1, CONST-B3 | CONST-B1 | +| `docs/solutions/architecture-patterns/label-routed-rules-are-unfalsifiable.md` | CONST-P3 | CONST-T12 | +| `docs/solutions/architecture-patterns/workflow-error-channel-gates.md` | CONST-D2, CONST-P1, CONST-T3 | CONST-D2, CONST-B1, CONST-T3 | +| `docs/solutions/architecture-patterns/workflow-success-channel-tagged-union.md` | CONST-D4 | CONST-D4 | +| `docs/solutions/conventions/unsanctioned-property-lane-rehomed-as-deterministic-universals.md` | CONST-E9 | CONST-E7 | +| `docs/solutions/runtime-errors/match-dispatch-buries-the-registration-call-site.md` | CONST-P2 | CONST-B1 | +| `packages/daemon/effect-daemon-cluster/AGENTS.md` | CONST-T3 | CONST-T3 | +| `packages/runner/vitest/src/internal/property/error.schema.ts` | CONST-D3 | retired | +| `packages/runner/vitest/src/internal/provided.ts` | CONST-D3 | retired | +| `packages/runner/vitest/src/replay.schema.ts` | CONST-D3 | retired | +| `packages/runner/vitest/tests/property-replay.test.ts` | CONST-T10 | CONST-T10 | + +--- + +## Appendix E - Incident evidence (gates 1-3) + +Gate 1 last ran 2026-10-09 under c09 (R21). "consumer" is the public `systemfsoftware/systemfsoftware`; "this repo" is `systemfsoftware/constitution`. Each ref is `sha:path:line`, and `git show :` printed the quoted line. A fixed incident is anchored at the fix's parent and carries the fix hunk (`git show -U0 -- `); where the fix only adds lines, the hunk shown is the addition. A ref with no fix is a review that rejected the violation, or a violation that still stands. The first incident of each law is its example's source. + +Result: 17 of 17 laws have two failure incidents from different PRs or commits; every cited line printed and every fix commit exists. No PR, fix commit or document backs more than two laws. Shared between two laws: #375 and `f08fddc94` (S3; P1 before its cut), #166 (D1; P1 before its cut), #342 and `3838c7309` (B4, S2), `7b4e08e24` (S1, T12), `166e6bb65` (S4, T12), #229 (S4, T10), #21 (W1, E7). A replay evaluator ablating one law should know those laws share evidence. + +#### CONST-S3 + +- consumer violating-code: `41c844fdb:packages/testing/mutation/stryker-js/cli/src/cli-request.schema.ts:26` (2026-08-26, #254, fix `7bd4fa7ec`). A CliRequest schema was exported with no consumer decoding it; every use was a type position, and its obligation scan drove the CLI suite to a 15-second timeout. + - printed: `export const CliRequest = S.Union([RunRequestSchema, LlmsRequestSchema])` + - fix hunk: + ```diff + @@ -1,33 +0,0 @@ + (…) + -const RunRequestSchema = S.TaggedStruct('run', { options: S.Any, survivors: S.Boolean }) + -const LlmsRequestSchema = S.TaggedStruct('llms', { document: S.Any }) + - + -export const CliRequest = S.Union([RunRequestSchema, LlmsRequestSchema]) + -export type RunRequest = Omit & { + - readonly options: PartialStrykerOptions + -} + (…) + ``` +- consumer violating-code: `7f11497e8:packages/stryker-js/stryker-js-cli/src/Cli.ts:1000` (2026-09-10, #375, fix `f08fddc94`). The root command kept declaring FileSystem|Path after the manifest emitter that needed them was deleted, so the import survived only to appear in one type parameter. + - printed: `FileSystem.FileSystem | Path.Path` + - fix hunk: + ```diff + @@ -1000 +566 @@ function makeStrykerCommand(requestRef: Ref.Ref>) { + - FileSystem.FileSystem | Path.Path + + never + ``` + +#### CONST-D1 + +- consumer violating-code: `151b9f4de:packages/effect-daemon-spec/src/internal/with-lock-by-mode.executor.ts:24` (2026-08-15, #166, fix `2d367db70`). withLockByMode took a spec and a nullable adapter, so a spec that required the lock, paired with no adapter, ran its body unlocked. + - printed: `if (lock === null || isModeNone(lockSpec)) {` + - fix hunk: + ```diff + @@ -24 +43 @@ export const withLockByMode = ( + - if (lock === null || isModeNone(lockSpec)) { + + if (binding.kind === 'unlocked') { + ``` +- consumer violating-code: `de5414e3a:packages/discern/src/decision.blueprint.ts:461` (2026-09-24, #519, fix `2d4c724ff`). classify accepted any `Label extends string` options, so once a string-typed criteria got through, every downstream label check accepted any string. + - printed: `options: ClassifyOptions