From 41a33cfa395f87da542fc608269e2b38c0bc9caa Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:43:40 +0200 Subject: [PATCH 1/2] feat(efficacy): every arm is built by a script, inline by the emitter The generator loses its model path: inline is resolve_chain.py --emit --inline-skills, skills the emitter as before, and hybrid and short are no longer built. Every emitted root now carries the brief whole. The self-test rebuilds every committed arm at its recorded ref and fails on any byte of difference. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/architecture/05-building-block-view.md | 2 +- .../architecture/09-architecture-decisions.md | 1 + docs/coverage.md | 7 +- .../025-every-arm-is-built-by-a-script.md | 82 + docs/journeys/prepare/generate-the-arms.md | 37 +- docs/requirements.md | 5 +- tests/efficacy/arms/inline/CLAUDE.md | 2223 +++++++++++++---- tests/efficacy/arms/inline/generation.json | 147 +- tests/efficacy/arms/skills/CLAUDE.md | 18 +- tests/efficacy/arms/skills/generation.json | 12 +- tests/efficacy/generate_arm.py | 586 ++--- tests/efficacy/harness.py | 16 +- tests/efficacy/report.py | 13 +- 13 files changed, 2100 insertions(+), 1049 deletions(-) create mode 100644 docs/decisions/025-every-arm-is-built-by-a-script.md diff --git a/docs/architecture/05-building-block-view.md b/docs/architecture/05-building-block-view.md index dd3b9e6..6e1c63f 100644 --- a/docs/architecture/05-building-block-view.md +++ b/docs/architecture/05-building-block-view.md @@ -15,7 +15,7 @@ dependency with its keyword. | Block | Responsibility | Reads | Writes | | ----- | -------------- | ----- | ------ | -| `generate_arm.py` | Makes one arm's file once: fixed text, one non-interactive generation from `agents.md`, under a line budget where the arm has one, or the emitter. Scans prompt and output for leaks, and refuses a file over its budget | `brief.txt`, the templates source | `arms//CLAUDE.md`, `generation.json` | +| `generate_arm.py` | Builds one arm's file by script, with no model call: fixed text, the templates' emitter, its skills apart or inlined, or a map of the chain's topics. Scans the output for leaks and named tools; its self-test rebuilds every committed arm and fails on any difference | `brief.txt`, the templates source | `arms//CLAUDE.md`, `generation.json` | | `harness.py` | Prepares each workspace, runs the agent in isolation, catches reach, freezes the result, keeps the run record current | The specs, the arm files, the change prompt | The run root | | `reuse.py` | Copies an earlier round's trials and readings into a new root, with their tool lock | An earlier root | The run root, the scoring area | | `progress.py` | Watches a run: one bar per arm, its voided tries, its cost and the trial running; then its scoring: one bar per arm, the security readings and the trial being scored; then its judging: one bar per arm of judgings out of those owed, the failures still owed and the blind label in hand. Redrawn every 30 s. Read-only | The run records, the scoring area | The console | diff --git a/docs/architecture/09-architecture-decisions.md b/docs/architecture/09-architecture-decisions.md index 7462f04..7f121fb 100644 --- a/docs/architecture/09-architecture-decisions.md +++ b/docs/architecture/09-architecture-decisions.md @@ -62,6 +62,7 @@ report shows first. | [ADR-015](../decisions/015-contrasts-and-verdicts.md) | A contrast gets a verdict only when both its arms run in the same round | Accepted | | [ADR-023](../decisions/023-the-iso-radar.md) | From round 6 the radar reads ISO/IEC 25010:2023: eight axes, each the share of its targets met against `none`, a marker only past the axis's margin, the cost shown above | Accepted | | [ADR-024](../decisions/024-verdicts-read-the-iso-radar.md) | From round 6 an arm's verdict and round 6's screen read the ISO radar's axes; a pilot round read by them is a post-hoc draft | Accepted | +| [ADR-025](../decisions/025-every-arm-is-built-by-a-script.md) | From round 6 every arm is built by a script with no model call, `inline` by the emitter's `--inline-skills`; `hybrid`, `short` and `hand` run no more | Accepted | ## 9.5 Running and keeping a round diff --git a/docs/coverage.md b/docs/coverage.md index 48b3b14..2d0b3d0 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -185,13 +185,14 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | | FR-13-01 | Self-test | `harness.py` "the record is written as every trial starts and ends"
`harness.py` "every trial records the CLI's version, read as it starts" | -| FR-13-02 | Self-test | `generate_arm.py` "every generated arm's file has its generation record beside it" | +| FR-13-02 | Self-test | `generate_arm.py` "every built arm's file has its generation record beside it" | | FR-13-03 | Self-test | `archive.py` "readings, judgings, map and lock come; bundles do not"
`archive.py` "the original tarball's hash is recorded"
`archive.py` "the revisions are recorded"
`archive.py` "a reading changed in the archive fails the verify" | | FR-13-04 | Self-test | `archive.py` "a reading changed after the stamp is a problem"
`archive.py` "the report refuses docs/audits/ without a current stamp"
`report.py` "a report into a templates source's docs/audits needs the stamp" | | FR-13-05 | Self-test | `archive.py` "the restored root reads as the original does"
`archive.py` "a restored record points at the restored tarball and void"
`archive.py` "a restored transcript keeps its time" | | FR-13-06 | Self-test | `generate_arm.py` "the two map arms name the same moments in the chain's order"
`generate_arm.py` "the reading map names every template of the chain once, under docs/solid-ai-templates/"
`generate_arm.py` "each template skill is its template verbatim, named by the manifest"
`generate_arm.py` "a chain file the manifest does not describe is refused" | -| FR-13-07 | Self-test | `generate_arm.py` "every fixed-text root opens with the brief, verbatim"
`generate_arm.py` "the brief and the facts name the stack and no tooling" | -| FR-13-08 | Self-test | `generate_arm.py` "a generated file naming a tool is refused, and the prompt forbids one" | +| FR-13-07 | Self-test | `generate_arm.py` "every built root opens with the brief, verbatim, the emitted ones too"
`generate_arm.py` "every committed arm's root opens with the brief, verbatim"
`generate_arm.py` "the brief and the facts name the stack and no tooling" | +| FR-13-08 | Self-test | `generate_arm.py` "a built file naming a tool is refused" | +| FR-13-09 | Self-test | `generate_arm.py` "every committed arm is what the script builds at its recorded ref, byte for byte, the same twice" | ## 14 One run at a time diff --git a/docs/decisions/025-every-arm-is-built-by-a-script.md b/docs/decisions/025-every-arm-is-built-by-a-script.md new file mode 100644 index 0000000..bd304ee --- /dev/null +++ b/docs/decisions/025-every-arm-is-built-by-a-script.md @@ -0,0 +1,82 @@ +--- +id: "025" +status: Accepted +date: 2026-11-15 +category: arms +supersedes: [] +superseded_by: [] +--- + +# ADR-025: From round 6, every arm is built by a script + +## Context + +Through round 5e, three arms were written: `inline`, `hybrid` and `short` +were one model generation each, and `hand` was a person's file. A +generation run again gives a different file, so the arm under one name +changes: round 5e's `hybrid` was 511 lines, and the one regenerated for +round 6 was 221. A result then speaks for one draw of the method, not for +the method, and two rounds of one arm do not compare. + +The templates' own emitter, `resolve_chain.py --emit`, already builds a +root file and task skills from a chain by placing each section by its load, +copying the rule text unchanged; `--inline-skills` puts the skills in the +root. It builds no hybrid file: the templates hold that emitted files name +no template file (their FR-06-07), and that no rule is left to a reference +alone, since nothing loads a referenced file (their ADR-058). Round 5e bore +that out: `hybrid` read 0.1 of the 13 templates it pointed to, so it ran on +the rules it inlined, a slightly shorter `inline`. + +## Decision + +From round 6 every arm a round runs is built by `generate_arm.py` with no +model call, and the same ref gives the same bytes; `inline` is what the +emitter builds with `--inline-skills`, and `hybrid`, `short` and `hand` run +no more. + +## Rationale + +- An arm that is the same file on every build is a method, not a sample of + one; a round's result then speaks for it, and two rounds compare. +- The emitter is the templates' own build, so the arm is upstream's output, + as the benchmark measures upstream only. +- `hybrid` has no build upstream that keeps the templates' rules, and its + references went unread, so a scripted stand-in would measure the + benchmark's choices rather than the templates'. + +## Design + +| # | Rule | In practice | +| - | ---- | ----------- | +| 1 | No model writes an arm | `generate_arm.py` has no model path; every kind is fixed text, the emitter or a map | +| 2 | `inline` is the emitter's single file | `resolve_chain.py --emit --inline-skills`: every adopted rule in the root, a section a check enforces cut to its command and pass condition, as the emitter cuts it for every model | +| 3 | `skills` is the emitter's root and skills | `resolve_chain.py --emit`, as before | +| 4 | Every root states the brief | The emitter's description slot takes the brief whole, so an emitted root opens as every other arm's does | +| 5 | A committed arm is what the script builds | The self-test rebuilds every committed arm at its recorded ref and fails on any byte of difference, and builds one twice | +| 6 | The pilot's written arms stay as they are | `hand`, `short` and `hybrid` keep their files for the pilot rounds' reports; no script rebuilds them, and no round from 6 runs them | + +## Alternatives considered + +| # | Alternative | Outcome | +| - | ----------- | ------- | +| A | Every arm built by a script, `hybrid` dropped | Chosen | +| B | Several generations per written arm, trials spread across them | Why not: the arm stays a sample, and the spread between files has to be paid for in trials | +| C | A hybrid built by the benchmark: the emitter's root, the skills table cut, the chain listed | Why not: how the benchmark trims and joins shapes the arm, and the templates' rules forbid the result | +| D | Hybrid and inline modes added to the templates' emitter first | Why not: a hybrid that names template files breaks the templates' FR-06-07 and ADR-058; `--inline-skills` is already the inline build | + +## Consequences + +| Consequence | Effect | +| ----------- | ------ | +| `inline` changes | The emitter's file is 1,778 lines at `9abed019`, against the 552 a model wrote for round 5e: a new arm, with no round-5e reading | +| `skills` changes | Its root now carries the brief's paragraphs on personal data and on boundaries, which it lacked; a new arm too | +| Round 6's arms | `none`, `reference`, `inline`, `skills`, `lazyref`, `lazyskills`, and those #169 adds | +| The report still reads arm files from the checkout | The pilot arms' files stay so a pilot report can count their lines, until #171 | + +## History + +Every change to this decision, oldest first. `#N` is in this repository. + +| Date | Change | Why | Issue | +| ---- | ------ | --- | ----- | +| 2026-11-15 | Every arm is built by a script; `inline` from the emitter's `--inline-skills`; `hybrid`, `short` and `hand` run no more | A written arm changes with every writing; the owner kept only arms a script builds | #167 | diff --git a/docs/journeys/prepare/generate-the-arms.md b/docs/journeys/prepare/generate-the-arms.md index 10e844f..08d039d 100644 --- a/docs/journeys/prepare/generate-the-arms.md +++ b/docs/journeys/prepare/generate-the-arms.md @@ -1,44 +1,47 @@ # Generate the arms -The operator prepares round 5, whose context files must each be made once, -before block A, from one chain of the templates. +The operator prepares a round, whose context files are each built by +script, before block A, from one chain of the templates. Target: -- Each arm's file made once, with clean leak scans and its - `generation.json` committed beside it +- Each arm's file built, with a clean leak scan and its `generation.json` + committed beside it ([ch. 5.5.3](../../architecture/05-building-block-view.md)) Assumptions: -- A templates clone at the round's registered ref, named with `--templates` -- Round 5's four context-file arms: `reference` as fixed text, `inline` and - `hybrid` as one generation each, `skills` from the emitter +- A templates clone holding the round's registered ref, named with + `--templates` +- The arms, all built with no model call + ([ADR-025](../../decisions/025-every-arm-is-built-by-a-script.md)): + `reference`, `lazyref` and `lazyskills` as fixed text, `inline` and + `skills` from the templates' emitter - All times are estimates ## Steps | # | Who | Step | Time | Notes | | - | --- | ---- | ---- | ----- | -| 1 | Operator | Runs the generator's self test | 1 min | Proves the leak scan, the reference text and the fact filling can fail | -| 2 | Operator | Dry-runs each model arm: builds and scans the prompt without a model | 1 min each | The cheap check after any change to the brief or the chain | -| 3 | Generator | Makes each arm, at a root outside this repository | 5 to 10 min each | Nobody answers questions, and nobody trims a result | -| 4 | Operator | Reads each `generation.json`: ref, chain, commit, how the file was made, its size, both scans | 5 min | The report reads it from there | +| 1 | Operator | Runs the generator's self test | 2 min | Proves the scans and the fact filling can fail, and rebuilds every committed arm | +| 2 | Operator | Dry-runs each arm at the round's ref | 1 min each | Builds and scans the files, writes nothing under `arms/` | +| 3 | Generator | Builds each arm, at a root outside this repository | 1 min each | The same ref gives the same bytes | +| 4 | Operator | Reads each `generation.json`: ref, chain, commit, how the file was built, its size, both scans | 5 min | The report reads it from there | | 5 | Operator | Commits the files and their records | 5 min | An existing file is never overwritten without `--replace` | -| | | Total | about 40 min | | +| | | Total | about 20 min | | ## Commands ```bash py tests/efficacy/generate_arm.py --self-test -py tests/efficacy/generate_arm.py --arm inline --root --dry-run -py tests/efficacy/generate_arm.py --arm inline --root +py tests/efficacy/generate_arm.py --arm inline --ref --root --dry-run +py tests/efficacy/generate_arm.py --arm inline --ref --root --replace ``` ## Findings | # | Finding | Status | | - | ------- | ------ | -| 1 | Retrying a refused generation until one passes would select the tersest sample. The instruction instead asks the model to measure every line before answering | Settled in [ADR-002](../../decisions/002-the-arms.md), 2026-09-26 | -| 2 | The prompt scan is broad and the output scan narrow: a spec-only token in the prompt means the wiring is wrong, and only data nobody could derive counts as an output leak | Settled in [ch. 5.5.4](../../architecture/05-building-block-view.md) | -| 3 | Round 5's `reference` and `skills` arms are made by other means: fixed text, and `resolve_chain.py --emit` | Open in [round 5's registration, 13.4](../../rounds/round-5.md) | +| 1 | A written arm changes with every writing: round 5e's `hybrid` was 511 lines, the one regenerated for round 6 was 221 | Settled in [ADR-025](../../decisions/025-every-arm-is-built-by-a-script.md), 2026-11-15 | +| 2 | The emitted `skills` root lacked the brief's paragraphs on personal data and on boundaries, and no check read an emitted root | Settled in [ADR-025](../../decisions/025-every-arm-is-built-by-a-script.md), rule 4 | +| 3 | The emitter builds no hybrid file, and the templates' rules forbid one that names template files | Settled in [ADR-025](../../decisions/025-every-arm-is-built-by-a-script.md); `hybrid` runs no more | diff --git a/docs/requirements.md b/docs/requirements.md index c512cc7..c0b10df 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -198,8 +198,9 @@ | FR-13-04 | The benchmark shall refuse to write a report under `docs/audits/` once a reading changed since the archive was verified. | Archive, Report | | FR-13-05 | The benchmark shall restore an archive so it reads as the original root does, its records pointing at the restored files. | Archive | | FR-13-06 | The benchmark shall build a map arm's root from the brief, the chain and the templates' manifest alone, the same moments in the same order for both map arms, and each `lazyskills` skill holding one template verbatim. | Arm generator | -| FR-13-07 | The benchmark shall give every arm's root the same project facts: the brief, which names the stack the spec fixes and no tooling. | Arm generator | -| FR-13-08 | The benchmark shall tell a model arm's generation to name no tool, and refuse a generated file that names one. | Arm generator | +| FR-13-07 | The benchmark shall give every arm's root the same project facts: the brief, verbatim under the title, the emitted roots too, which names the stack the spec fixes and no tooling. | Arm generator | +| FR-13-08 | The benchmark shall refuse a built arm file that names a tool. | Arm generator | +| FR-13-09 | The benchmark shall build every arm a round runs by script, with no model call, and fail its self-test where a committed arm differs from what the script builds at the arm's recorded ref. | Arm generator | ### 14 One run at a time diff --git a/tests/efficacy/arms/inline/CLAUDE.md b/tests/efficacy/arms/inline/CLAUDE.md index d6c4cb8..de8a689 100644 --- a/tests/efficacy/arms/inline/CLAUDE.md +++ b/tests/efficacy/arms/inline/CLAUDE.md @@ -1,449 +1,640 @@ # tariff -Pricing and invoicing web application — Imbra Ltd -Owner: Imbra Ltd. Runs locally only; no repository URL, live URL or deployment target applies. -- Model: inline - -## 1. Project - -### 1.1 Overview - -`tariff` assembles invoices from a product catalog, several kinds of discount -rule, tax jurisdictions and customers. Stack: Python 3.12, Flask 3, Jinja, -HTMX, SQLite. It runs locally, with no deployment target. - -Two actors use it: an administrator working in a browser, and a separate -program that imports the pricing engine directly as a library, without the -web application present. The store is a local SQLite file. Nothing in this -application reaches the network: no outbound HTTP call, no inbound API -beyond the local web UI, no CORS surface, no SSRF surface. Do not add one -without revisiting this file. - -One administrator signs in to use the web application; nobody else has an -account. Customers are people: the system stores each one's name, email and -postal address, and names them on the invoices billed to them. Imbra Ltd is -in the EU, so GDPR applies — see section 6. - -### 1.2 Project structure - -See `README.md` for the directory map; do not duplicate it here. - -Placement rule: keep the pricing engine in its own package, with no import -of Flask, Jinja, HTMX or any other web-layer module. It must import and run -correctly with the web application absent. The web application package may -import the pricing engine; the reverse must never happen. - -### 1.3 Commands - -The project has not yet chosen a package manager, test runner, type -checker, linter or formatter. Until it does, each command below names what -it must do, not how: - -- **Install**: resolve and install the project's pinned dependencies from - its lockfile. -- **Migrate**: apply pending SQLite schema migrations through a committed - script before the application starts. -- **Run**: start the Flask application locally, reading the port from an - environment variable, with a sensible default for local development. -- **Test**: run the automated test suite (unit and integration) covering - both the pricing engine library and the web application. -- **Type-check / Lint / Format**: run the project's static type checker, - linter and formatter, each in its strict and quiet mode, reporting zero - issues. - -## 2. Architecture boundaries - -- Keep the pricing engine a standalone Python library with no dependency on - Flask, Jinja, HTMX or any web-layer code (MUST); it must import and run - with the web application absent. -- Treat the web application as one caller of the pricing engine, never a - second place that computes a price, discount or tax figure — call the - library; never re-implement its logic in a route handler or a template. -- Keep the module graph acyclic: the web application depends on the - pricing engine; the pricing engine never imports the web application - (MUST). - **Check**: no module under the pricing-engine package imports anything - from the web-application package; the check must report zero violations. -- Treat the pricing engine's public functions and classes as the contract - the other program — its second caller — depends on. Apply the - deprecation rule (section 3.2) before changing or removing any of them. -- Give the pricing engine package its own version, independent of the web - application's; bump it deliberately, following semantic versioning, - whenever its public API changes. -- Never let the pricing engine write to standard output or standard error, - and never let it configure logging beyond its own logger (MUST). Make - its logger injectable, falling back to its own module logger, so each - caller captures its output on its own terms. - **Check**: run the library alone in a fresh process and confirm it emits - nothing on stdout or stderr; a test runner's own log handler can hide a - default that would otherwise leak into both callers. - -## 3. Code conventions - -### 3.1 Git - -- Commit under one full name and one consistent email; never change - identity mid-project. -- Work on a branch; never commit directly to `main`. -- Never commit build output, dependency directories or secrets. Commit a - generated file only when the project tracks it on purpose. +`tariff` — Imbra Ltd — a pricing and invoicing web application: +a product catalog, discount rules of several kinds, tax jurisdictions, +customers, and invoices assembled from them — Python 3.12 / Flask 3 / +Jinja / HTMX / SQLite — runs locally, no deployment target + +Personal data: customers are people, stored with their name, email and +postal address and named on the invoices billed to them. The business is +in the EU, so the GDPR applies: a customer may ask for their data to be +erased or for a copy of it. One administrator signs in to use the +application; nobody else has an account. + +Boundaries and actors: two actors, the administrator working in a browser +and another program; the pricing engine is a library the program imports +without the web application present, and the web application is one +caller of it. The store is a local file. Nothing reaches the network. +The program's interfaces are the library's own API and the invoice +exports. + +- Model: root and skills +- Owner: Imbra Ltd +- Repository: this repository + +## Commands + +Python 3.12, Flask 3, Jinja, HTMX and SQLite; the brief names no tooling. It runs locally; there is no deployment target. + +## Answers + +- Who approves a change: not stated in the brief +- How work is tracked: not stated in the brief +- What a release is: not stated in the brief; the application runs locally + +## Rules + +Built by `resolve_chain.py --emit`; change the templates, not the rules below. + +The adopted rules that apply on every task. + +### Base — Quality Attributes + +How code is designed, kept clean, swept and checked. + +#### Principles + +- Keep one authoritative representation of each piece of knowledge (DRY); + the third copy is a bug +- Extract shared logic only where substantial logic repeats; a few similar + lines inline are not duplication +- Choose the simplest solution a stated requirement justifies (KISS) +- Build what is needed now, never for a hypothetical requirement (YAGNI) +- Record beside every deferral the concrete condition that reopens it +- Delete a path once evidence shows it unreachable or obsolete: no caller, + or a retired input +- Treat a real-data probe that never reaches a path as a lead, not proof; + a sample misses rare cases + +#### Architecture + +- Compute derived counts and statistics from the data; never hardcode them +- Remove unused modules, assets and data files promptly + +#### Naming + +- Name a function with a verb, a class or module with a noun, and a boolean + with `is`, `has` or `can` +- Rename a name that needs a comment to explain it +- Use the same name for the same concept in every module +- Name a public enum member, CLI flag or result discriminator for the + capability it offers, never the library behind it: `Transport.HEADED`, + not `Transport.PLAYWRIGHT` (MUST). A private symbol MAY name its library + +#### Complexity + +- Keep cognitive complexity at or under 15 per function +- Nest at most three levels; use guard clauses and early returns +- Replace a boolean flag that selects behaviour with an enum or two named + functions +- Name every magic number and magic string as a constant +- Size a tuned threshold, such as a latency alert, from its measured + distribution (p95, p99, maximum legitimate); name the data source in + the constant's docstring +- Take a limit a specification fixes, such as a protocol's maximum + message size, from that specification and name it, never from an + observed percentile + +#### Dependencies + +- Keep the module graph acyclic; break a cycle with a third module or an + interface, never with a divergent local copy +- Keep coupling shallow: a change inside one module MUST NOT require + changes in unrelated modules +- Talk only to direct dependencies, and keep together what changes together + (SHOULD) +- Reach a heavy, native or platform-limited dependency through one module + that owns its import and names the install command when it is missing + +#### Errors + +- Validate input at boundaries and fail at once on invalid state +- Read a value from its source-of-truth field, and raise when the field is + missing; never fall back to a value derived from a slug, name or hash +- Bound every wait on another thread, process or connection, report why it + gave up, and check the worker's liveness as well as the deadline +- Never break a public catch contract: a raise callers catch by a built-in + type keeps that type +- Add an error type only where a caller could act differently +- Never let a caller-side input filter stand in for a precondition: widen + the filter, or assert the precondition inside the function + +#### Module structure + +- Keep a CLI a thin layer over a library that holds its logic +- Keep constants beside the functions that use them + +#### Library output + +- Never write to the host's standard output or error from a library, and + never configure logging beyond the library's own logger (MUST) +- Make the library's logger injectable, falling back to its module logger +- Check the silence in a fresh process; a test runner's handler hides the + default + +#### Encoding and line endings + +- Encode every committed text file in UTF-8, with LF line endings (MUST) +- Keep identifiers ASCII (MUST); comments, docstrings, strings and + documentation carry no charset restriction + +```bash +pre-commit run check-ascii-identifiers --all-files --verbose +``` + +Pass condition: the inspected count is above zero and +`non-ASCII identifiers` is zero. The hook reads Python; `not applicable` +means the project tracks none. + +- Set a program's output encoding explicitly, and pin its line ending where + another program reads the output +- Commit a `.gitattributes` with `* text=auto`, adding `eol=lf` for hard + LF +- Mark a text path exempt from LF with `-text` in `.gitattributes` +- Check line endings on every tracked file, whatever its name, exempting a + `-text` file; count a file Git files `i/-text` as binary only when it + holds a NUL byte +- Let a linter format on save, and keep manual style rules to a minimum + (SHOULD) + +```bash +seen=0 exempt=0 binary=0 bad=() +while IFS= read -r -d '' rec; do + info=${rec%%$'\t'*} path=${rec#*$'\t'} seen=$((seen + 1)) + case " ${info#*attr/} " in *" -text "*) exempt=$((exempt + 1)); continue ;; esac + case $info in "i/ "* | i/lf* | i/none*) continue ;; esac + nuls=$(git cat-file blob ":0:$path" | tr -dc '\000' | wc -c) + [[ $info == i/-text* && $nuls -gt 0 ]] && binary=$((binary + 1)) && continue + bad+=("$path") +done < <(git ls-files -z --eol) +printf 'files inspected: %d\nexempt by -text: %d\n' "$seen" "$exempt" +printf 'binary by content: %d\nfiles not filed i/lf: %d\n' "$binary" "${#bad[@]}" +for f in "${bad[@]}"; do echo " $f"; done +[ "$seen" -gt 0 ] && [ "${#bad[@]}" -eq 0 ] +``` + +Pass condition: exit zero, given only when the inspected count is above +zero and the not-`i/lf` count is zero. An empty `i/none` file passes; a +stray carriage return, filed `i/-text` with no NUL byte, still fails. + +#### Comments + +- Prefer code that needs no comment; comment only intent the code cannot + express +- Re-verify a comment explaining why something is safe whenever the code + is next read +- Never cite a ticket, PR or ADR number in a code comment, docstring or + commented configuration; state the substance (MUST NOT) +- Name a source (author, year, method) where non-obvious or scientific + logic needs one (MAY) + +#### Debug code + +- Commit no debug output (`print()`, `console.log()`) and no hardcoded + breakpoint +- Delete commented-out code +- Gate debug tooling behind a flag or environment variable, off by default + +##### Probe scripts + +- Write a probe, a throwaway script that measures data or behaviour, + rather than guess +- Delete a probe before the commit that uses its findings (MUST) +- Keep findings in source comments, decision records or docs, never in + the probe + +#### Rejected mechanisms + +- Grep the codebase for a construct a comment records as not working, + before moving on: `grep -rn '' ` +- Read every hit as a suspected instance of the same defect, not a style + question + +#### Destructive operations + +- Delete, truncate, overwrite or kill only what the operation can prove it + created: process ancestry, a key scheme, a filename prefix, a marker file + or an ownership tag; never a path, a configuration value or a file + extension +- Find nothing where the proof is unavailable: no error, no prompt, no + guess +- Validate the input as well: reject an empty configuration value, and + match the key scheme +- Apply this to every reaper: a cache clean, an output-directory clear, a + log rotation, a temp-file sweep + +``` +match on ".html" wrong directory -> README.html deleted +match on "[0-9a-f]{16}.html" wrong directory -> nothing matched +``` + +#### Check trust + +- Confirm a validation, scraping, migration or codemod tool is correct + before acting on its output in bulk +- Treat a physically implausible output as a tool defect: fix it, re-run, + then apply +- Cross-check an independent source before overwriting stored data with a + source that looks wrong +- Never weaken the rule behind a check to make it green or quiet + +#### Static checks + +- Adopt the language's static type checker at its strictest setting where + the language has one, and keep it clean (MUST) +- Annotate every public function's parameters and return type where the + language allows it (MUST) +- Adopt a linter and a formatter, and keep both clean (MUST) +- Run the type checker, the linter and the formatter before every commit + and in CI + +```bash + + + +``` + +Pass condition: all three print nothing. Each command is the project's own, +in its quiet mode. + +#### Enforcement + +- Enforce these conventions through the gates: editor, pre-commit, CI +- Merge to `main` only with passing tests + +#### Completion + +Adding pagination, for example, ends with bounded results, their tests and +an updated contract. It does not end with a rewrite of the service layer. + +- Finish a task when the requested behaviour works through the entry point + its user or caller reaches, and the checks that prove it pass +- Report a check that could not run as not run, never as a pass +- Add an abstraction, infrastructure or a process step only when a stated + requirement, a demonstrated defect or a material risk justifies it +- Report a problem found outside the task, or file it as its own task, + rather than fixing it in the same change (SHOULD) + +### Base — Git Conventions + +How changes are committed, reviewed, verified and merged. + +#### Commits + +- Commit under your full name and one consistent email; never change + identity mid-project +- Work on a branch; never commit directly to `main` +- Never commit build output, dependency directories or secrets +- Commit a generated file only when the project tracks it on purpose, under + the regeneration rules below +- Treat every repository as public: no secret, credential or sensitive + value in source or history - Keep a `.gitignore` (MUST) covering dependencies, build output, secrets, - editor state, OS files and coverage output. -- Commit lockfiles (MUST). -- Inspect the working tree and the index before starting a task. Never - discard, reset, stash or overwrite a change the task did not make. - Stage only the changes the task made — a whole file only when it held - no prior change, otherwise only the task's hunks. Read the staged diff - before committing. Stop and ask when a task change and a prior change - share a hunk. Report a pre-existing change that blocks the task rather - than removing it. -- Keep a pull request to one concern (SHOULD). Test locally before - committing. Review the diff against the base before merging, in the - order security, correctness, clarity, conventions. Merge only after the - review passes and CI is green. -- Read the CI run for the push before describing a change as good. Treat - a pull request with no registered check as not passed. Never merge - while a check is failing, cancelled or not yet registered. Re-run a - verification a pull request claims once the base has moved since it was - written. Read a new or changed workflow's first run in its real - environment before trusting it. -- Never force-push, including with `--force-with-lease` (MUST NOT). Bring - a branch up to date by merging the base into it, never by rebasing and - force-pushing. - -**Off-limits paths** (MUST NOT change without explicit approval; propose -first, with a rollback strategy and the tests that would catch a -regression): - -- Authentication and session code (the administrator's sign-in). -- SQLite migrations. -- `.env*` and secrets. -- CI/CD workflow files, if and when the project adds any. -- Payment code: not applicable — this application does not process - payments. - -A diff confined to prose is ordinary work; a comment a tool reads (a -linter disable, a coverage pragma) counts as executable content and is -off-limits the same as a command or a permission. Name an off-limits path -at the top of a change's summary whenever the diff touches one, proposal -or not. -**Check**: the change summary names every off-limits path the diff -touches; the check must report zero undeclared touches. - -### 3.2 Python - -- Keep one authoritative representation of each piece of pricing, discount - or tax knowledge (DRY). Build only what a stated requirement justifies - (YAGNI); record beside every deferral the concrete condition that - reopens it. Delete a path once evidence shows it unreachable. -- Compute derived counts and statistics from the data; never hardcode - them. Remove unused modules, assets and data files promptly. -- Name a function with a verb, a class or module with a noun, a boolean - with `is`, `has` or `can`. Rename a name that needs a comment to explain - it. Use the same name for the same concept in every module. -- Keep cognitive complexity at or under 15 per function; nest at most - three levels; use guard clauses and early returns. Replace a boolean - flag that selects behaviour with an enum or two named functions. -- Name every magic number and string as a constant — a discount - percentage, a tax rate, a threshold. Size a tuned threshold from its - measured distribution, naming the data source beside the constant; - take a limit a specification fixes (e.g. a tax jurisdiction's own - rounding rule) from that specification instead. -- Keep coupling shallow: a change inside one module must not require - changes in unrelated modules. Talk only to direct dependencies. Reach a - heavy or platform-limited dependency through one module that owns its - import. -- Validate input at boundaries and fail at once on invalid state. Read a - value from its source-of-truth field, and raise when it is missing; - never fall back to a value derived from a slug, name or hash. Add an - error type only where a caller could act differently. Never let a - caller-side filter stand in for a precondition. -- Deprecate a public symbol, naming its replacement, before a later change - removes it. Deprecate every part of one call site together; never alias - the outer name alone. -- Keep constants beside the functions that use them. -- Encode every committed text file in UTF-8 with LF line endings (MUST); - keep identifiers ASCII (MUST). Set a program's output encoding - explicitly wherever another program reads its output — in particular, - the invoice export path. Commit a `.gitattributes` with `* text=auto`, - adding `eol=lf` for hard LF. - **Check**: every tracked text file is UTF-8 with LF endings and ASCII - identifiers; the check must report zero exceptions. -- Prefer code that needs no comment. Never cite a ticket, PR or ADR number - in a comment or docstring — state the substance. Name a source (author, - year, method) where a tax or discount rule's logic is non-obvious. -- Commit no debug output (`print()`) and no hardcoded breakpoint. Delete - commented-out code. Gate debug tooling behind a flag, off by default. -- Write a probe script to measure data or behaviour rather than guess; - delete it before the commit that uses its findings; keep the findings - themselves in durable comments or decision records. -- Grep for a construct a comment records as not working before reusing - it; read every hit as a suspected instance of the same defect. -- Run a new constraint — a tightened bound, a narrowed exemption — against - the existing corpus before it merges. -- When deleting, truncating or purging data (notably a GDPR erasure, see - section 6), act only on what the operation can prove is its target: an - exact customer ID, not a name match or a path guess. Find nothing, and - raise, where that proof is unavailable. -- Confirm a migration, import or bulk-edit script is correct before - acting on its output in bulk; cross-check an independent source before - overwriting stored data that looks wrong. -- Adopt the project's static type checker at its strictest setting and - keep it clean (MUST); annotate every public function's parameters and - return type (MUST). Adopt a linter and a formatter and keep both clean - (MUST). Run all three before every commit and in CI; each must print - nothing. -- Finish a task when the requested behaviour works through the entry - point its caller reaches, and the checks that prove it pass. Report a - check that could not run as not run, never as a pass. Report a problem - found outside the task as its own task rather than folding it in. - -### 3.3 Web layer (Flask / Jinja / HTMX) - -- Read the port from an environment variable; never hardcode it. Keep - initialisation short. -- Run one-off tasks (migrations, data fixes) with the application's own - code, config and dependencies; commit admin scripts to the repository - rather than running ad-hoc shell commands; prefer idempotent scripts; - never run one against the live database without a tested rollback plan. -- Keep handlers thin: decode the request, call the pricing engine or a - service function, render the response. Never put business logic in a - handler. Validate all incoming request data before processing it. -- Parse a typed query parameter explicitly, distinguishing absent - (default), present-and-valid (use it) and present-but-invalid (raise a - 400) — never let a parsing helper silently turn a bad value into the - default. -- Read header names case-insensitively. Avoid the `X-` prefix on a custom - header; use an application-specific prefix instead. -- Never let a GET or HTMX `hx-get` request change state. Make every PUT - and DELETE (including an `hx-delete`) idempotent. -- Represent dates and times as ISO 8601, currency codes as ISO 4217, and - country or tax-jurisdiction codes as ISO 3166-1 alpha-2, wherever the - application stores, computes or displays them. -- Use a consistent error shape across every route and HTMX fragment. Never - expose a stack trace or an internal path to the browser; return a - generic message and log the detail server-side. Use proper 4xx/5xx - status codes, never 200, for an error. Set an explicit `Content-Type` - on every response. -- Enforce authentication on every route (MUST); this application declares - no public endpoint. Apply the auth check before any business logic - runs. Never expose a write path without the authenticated - administrator's session. -- Not applicable, since nothing here reaches the network: HTTPS/TLS - enforcement, HSTS and other reverse-proxy security headers, CORS, - multi-instance process lifecycle (graceful shutdown, SIGKILL recovery). - -### 3.4 Data model (SQLite) - -- Pick one naming convention for tables, columns, keys and indexes, and - record it here once chosen — open for the project to decide. -- Give every table a primary key; prefer a surrogate key. Store each fact - in one place; duplicate only when measured read performance requires - it, with the rationale documented. Never pack several values into one - field (e.g. a composite discount-rule string) — use a related record. -- Enforce every reference (customer → invoice, invoice → product, invoice - → tax jurisdiction) with SQLite's own foreign-key constraint, or an - explicit check that every reference resolves. Decide what deleting the - target of each reference does — see section 6 for the customer case. - Document the maximum depth and cycle-prevention strategy for any - self-referencing relationship, such as a stacked or nested discount - rule, if one exists. -- Make every schema change through a versioned migration (MUST); never - edit the schema by hand. Prefer additive changes, compatible with old - writers. Give a destructive change (drop or rename a column) a plan: - add the new column, migrate the data, drop the old one, with both up - and down steps (MUST). Say so, and get approval, where a down step - cannot restore the data. Test a migration against realistic data before - applying it. -- Use the most specific SQLite type for each field: a date/time type, not - a string, for dates. Store timestamps in UTC; convert to local time only - at the presentation layer. Store every monetary value — a price, a - discount, a tax amount, an invoice total — as an integer in minor units - or an exact decimal type; never as a float (MUST). Document a maximum - length for every text field: customer name, email, postal address, - product description. -- Open one connection per request or worker thread; never a long-lived - global handle. Wrap a multi-step write (e.g. assembling an invoice from - its line items) in a transaction; commit only once every write - succeeds; keep the transaction short. -- Bound every interactive query with a limit or pagination (e.g. a - customer or invoice listing); a filter alone is not a bound. Select only - the columns a code path uses. Fetch related rows for a set in one query - or batch, never one query per row in a loop. -- Use a hard delete or an anonymizing update for a customer erasure (see - section 6), never a soft delete that still returns the row to ordinary - queries. Keep an append-only audit log table instead of a soft-delete - flag. -- Reset state between test runs — truncate tables or roll back a - transaction wrapping each test. Never substitute a different database - engine in tests; SQLite's own behaviour is part of what is tested. - Never run a schema migration against a production database inside a - test suite. - -## 4. Quality — testing - -Classify a test by the boundary it crosses: unit (none), integration -(process/component — e.g. a real temporary SQLite file), system (the -whole application against its requirements), regression (reusing -existing tests against a fixed defect), exploratory (unscripted). - -- Double only what a unit test would cross a boundary to reach: file I/O, - the system clock (discount and tax-jurisdiction rules can be - date-effective), randomness. Keep deterministic in-process - collaborators real. -- Add a regression test for every fixed defect. -- Cover every happy path the pricing, discount, tax and invoicing rules - define, plus negative inputs and edge cases (SHOULD), plus each - dependency's faults (an unavailable database file, a malformed row). -- Meet the project's coverage threshold for new code before merging; - never let coverage regress between releases. Run every unit test from - CI with no human step. Name a test so its name alone states the unit, - the input and the expected outcome (SHOULD). -- Keep pricing, discount and tax logic in pure functions; push SQLite - access to thin adapters at the edges (SHOULD). Inject dependencies - rather than construct them in the code under test. Split a function - that needs more than two mocks to test. -- Test behaviour, not implementation details. Set or clear every - environment variable a test depends on, in that test. Treat a test that - passes or fails by run order as an isolation bug. Wait on a condition - with a deadline, never a fixed sleep. Never enumerate, signal or - terminate a process the test did not start. Never mutate host state - outside the working directory. Investigate a failing test's own logic - before skipping or suppressing it. -- Allocate a per-test temporary database file or path from a fixture or a - module-level counter, never from state a test class inherits. -- Assert after every test that no thread, subprocess or server the suite - started survives it; join with a timeout, never a sleep. -- Exercise every call site of a changed shared pricing, discount or tax - path, not only the reported case; keep the list of consumers beside the - shared path. - -## 5. Security - -- Validate all external input (invoice, customer and discount-rule forms) - at the boundary, with a schema validator, using an allowlist. Reject - invalid input with a clear error; never silently coerce or strip - fields. -- Encode dynamic data for its rendering context at the point of output. - Rely on Jinja's auto-escaping; never insert user-supplied data through - a raw-HTML path (`|safe`, `Markup`) that bypasses it. -- Use parameterized SQLite queries for all database access; never - concatenate user input into a query string. -- Hash the administrator's password with bcrypt, scrypt or Argon2 — never - MD5, SHA-1 or plain SHA-256. Require a minimum length and reject - known-breached passwords; impose no composition rules. Use - constant-time comparison for secrets and tokens. Lock the account or - throttle after repeated failed sign-in attempts. -- Generate the session ID with a cryptographic random generator; - regenerate it after login. Set `HttpOnly`, `Secure` and - `SameSite=Strict` on the session cookie. Expire the session after an - idle period. Invalidate it on logout; do not rely on cookie expiry - alone. -- Give every state-changing request (every HTMX `POST`/`PUT`/`PATCH`/ - `DELETE`) a CSRF defence (MUST), since the administrator's session is - authenticated by an ambient cookie. Use the framework's built-in CSRF - middleware; prefer the synchroniser token pattern. Validate the token - on every state-changing request, never on GET. Never change state on a - GET request. -- Never hardcode a secret, API key or credential in source. Keep local - secret files out of version control. Rotate a secret immediately if it - is ever committed. -- Never expose a stack trace, an internal path or a database error to the - administrator's browser; log the full detail server-side. Answer a - failed sign-in the same way regardless of whether the account exists: - "invalid credentials", never "user not found". -- Never log a secret, token or password, and never log a customer's name, - email or postal address (see section 6) — log an opaque ID instead. - Sanitize any user-supplied data that reaches a log. Log authentication - and authorization failures at WARN, with an opaque user ID, never a - submitted username. Keep the client IP only in an access-restricted - security log, purged at the end of its retention period. -- Never deserialize untrusted data with a format that can instantiate - arbitrary types; use a data-only format (JSON) for any HTMX partial - that carries structured data. Pin dependency versions and verify - lockfile checksums; never trust an upstream registry blindly. -- Never read, print or `cat` a file that may hold secrets (`.env`, - `credentials.json`, `*.pem`, `*.key`). Never echo or log an environment - variable's value; check its presence by name only. Warn before - committing a file that commonly holds secrets. Flag any secret exposed - in a session immediately, name it, and recommend rotation. -- Not applicable, since nothing here reaches the network: HTTPS/HSTS/TLS - enforcement, reverse-proxy security headers, CORS, SSRF defences. Not - applicable, since the application has no upload feature: file-upload - validation. - -## 6. Privacy and data governance (GDPR) - -- Classify a customer's name, email and postal address as Confidential - personal data. Classify an invoice (which carries that PII alongside - pricing and tax figures) as Confidential. Classify the product catalog, - discount rules and tax-jurisdiction tables as Internal. -- Match access to classification: only the signed-in administrator may - read or write Confidential data; there is no lower-privileged role to - restrict it from. -- Encrypt PII at rest (MUST). There is no network transit to secure here. -- Minimize PII collection: store only the name, email and postal address - the invoicing relationship needs. -- Never put a customer's name, email or postal address in an application - log, error message or stack trace (MUST NOT); use an opaque customer ID - there instead. -- Provide an erasure path (GDPR Art. 17) that anonymizes or removes a - customer's name, email and postal address from the live customer record - on request. -- Preserve the name and address already billed on a previously issued - invoice exactly as issued (GDPR Art. 17(3)(b) permits retaining what a - legal — here, tax and bookkeeping — obligation requires): erase or - anonymize the customer record, never retroactively edit an issued - invoice's billing details. Never delete an issued invoice as a side - effect of an erasure request; clear or anonymize the customer reference - on it instead of deleting the row. -- Provide an access/export path (GDPR Art. 15) that produces a complete, - human-readable copy of a customer's stored personal data and the - invoices billed to them, on request. -- Record every erasure and export request in an append-only audit trail: - who requested it, when, and what action was taken — never the PII - values themselves, so that erasing the PII leaves no copy in the trail. - Log every other change to Confidential data (a customer record, an - invoice, a price-setting discount rule) the same way: who changed what, - when, and the previous value, with PII excluded. Keep this trail in its - own store, separate from application logs, access-restricted to the - administrator. -- Define a retention period for customer and invoice data that satisfies - the bookkeeping and tax-retention law of the applicable EU member - state, and purge data automatically once it lapses; the exact period is - open for the project to decide, pending confirmation of the applicable - jurisdiction. Apply the same retention and purge discipline to the - audit trail. -- Use synthetic customer data in tests and local development fixtures; - never real customer PII. -- Designate the administrator as the owner of every data domain - (customers, invoices, products, discount rules, tax jurisdictions) - until the project names otherwise. - -## 7. Review process - -Review in this order, most critical first, weighing each finding -separately: **security**, **correctness**, **clarity**, **conventions**. -Label each finding a demonstrated defect, a policy deviation, or a -suggestion; block a merge only on the first two. - -**MUST checklist** + editor state, OS files and coverage output +- Commit lockfiles (MUST) + +#### Existing changes + +- Inspect the working tree and the index before starting a task +- Never discard, reset, stash or overwrite a change the task did not make + (MUST NOT) +- Never clear the tree to obtain a clean test baseline; ask the owner +- Stage only the changes the task made: a whole file only when it held no + prior change, otherwise only the task's hunks; never stage everything +- Read the staged diff before committing; it holds only the task's changes +- Stop and ask when a task change and a prior change share a hunk +- Report a pre-existing change that blocks the task rather than removing it + +#### Pull requests + +- Keep a pull request to one concern (SHOULD) +- Test locally before committing +- Review the diff against the base before merging, in the order security, + correctness, clarity, conventions +- Merge only after the review passes and CI is green + +#### CI evidence + +- Read the CI run for the push before describing a change as good; a local + run is evidence about one platform +- Treat a pull request with no registered check as not passed: wait until + one registers, then watch every check to completion +- Never merge while a check is failing, cancelled or not yet registered +- Re-run a verification a pull request body claims once the base has moved + since it was written; above all a proof of absence +- Read a new or changed workflow's first run in its real environment, and + require a verdict from it before trusting the workflow + +#### Updating a branch + +- Never force-push, including with `--force-with-lease` (MUST NOT) +- Bring a branch up to date by merging the base into it; never rebase and + force-push + +#### Off-limits paths + +- Declare an Off-limits section in the project's context file, listing the + paths that MUST NOT change without explicit approval (MUST) +- Offer this default set for the project to cut down: auth and session + code, payment code, migrations, `.env*` and secrets, and CI/CD + workflows +- Propose a change inside an off-limits path before making it, with a + rollback strategy and the tests that would catch a regression (MUST) +- Treat an approval as covering the proposed plan, never the whole path +- Apply the restriction to executable content: steps, commands, flags, + permissions, triggers, pins +- Treat a diff confined to prose as ordinary work +- Treat a comment a tool reads as executable, such as a linter disable or + a coverage pragma +- Classify by the diff: it is prose only when removing every comment line + leaves nothing +- Name an off-limits path at the top of the change's summary whenever the + diff touches one, proposal or not (MUST) + +```bash +pre-commit run report-off-limits-paths --hook-stage manual --all-files --verbose +``` + +- Require the paths-declared and files-changed counts above zero +- Pass each path as a `--path` argument, kept beside the declared list; + `--base` defaults to `origin/main` +- State every off-limits line in the summary as an escalation; it is not + a failure +- Run it after committing: at or behind the base with a clean tree it + prints `not applicable`, and a base that does not resolve fails it + +### Base — Documentation + +Which documents a project keeps, and how they stay true. + +#### Rule language + +- Read a plain imperative ("Use X", "Never Y") as MUST or MUST NOT +- Add an RFC 2119 key word where strength matters: SHOULD or MAY for a + weaker rule, MUST to stress an absolute one + +| Word | Meaning | +| --- | --- | +| MUST | Absolute requirement; a deviation needs an approver's sign-off | +| MUST NOT | Absolute prohibition; a deviation needs an approver's sign-off | +| SHOULD | Recommended; a deviation needs a justification | +| SHOULD NOT | Not recommended; may be ignored with a justification | +| MAY | Optional; the developer decides | + +#### Single source of truth + +- Keep the project structure in `README.md` only, and reference it + elsewhere +- Keep the agent files' project-structure section a pointer to the README + plus placement rules, never a second directory tree +- Never reference a file, component or service that does not exist + +#### Upkeep + +- Update every document a change touches, in the same commit: + - `CLAUDE.md` when architecture, stack, design rules or conventions change + - `README.md` when structure, stack or setup steps change + - `AGENTS.md` whenever `CLAUDE.md` changes, so the two agree +- Write in present tense; past or future tense signals a stale document +- Write as little as needed; a document that drifts is worse than none +- Remove redundant, inconsistent or outdated text promptly (SHOULD), in + its own change when it is unrelated to the one that finds it + +#### Disagreements + +- Establish which is wrong before changing a document or the system it + contradicts +- Check whether the rule is inherited: a document generated from a template + can drift while the system still matches the template +- Never act on the document alone when the observed state is defensible + (MUST NOT) +- Read the document, observe the system, find the rule that governs both, + then fix whichever one that rule does not support + +#### Line width + +- Wrap Markdown at the width the project declares, never at one written + into a rule + +#### Writing style + +- Use bold and italic sparingly: never bold inline code or a whole + sentence, and use at most one short bold label per list item +- Code-format only identifiers: file names, paths, environment variables +- Summarise a method, constant or flag in prose and link to its source; + never transcribe its definition +- Put a command the reader runs in a fenced block, exactly as typed +- Point at a self-documenting source, such as `--help`, a generated schema + or generated API docs, rather than restating it; document only what it + cannot state itself +- State a count about the tree only inside a block a generator writes and + gates, or in a dated record; elsewhere name the thing without counting it + +#### Cold readers + +- State the symptom before the mechanism +- Expand a term taken from the code at its first use, or avoid it +- Show a real example rather than describe one +- Keep to one idea per sentence +- Separate how bad it is now from how bad it becomes +- Apply these to every ticket, pull request and defect record an agent + writes; the record outlives the session + +### Base — Testing + +What to test, how to keep tests honest, and how to prove a change. + +#### Test types + +Classify a test by the boundary it crosses, not by who runs it or which +tool drives it. + +| Type | Boundary crossed | Focus | +| --- | --- | --- | +| Unit | None | One function or class in isolation | +| Integration | Process or component | Interaction with a real dependency | +| System | System | The product against its requirements | +| Regression | Any, reusing existing tests | Unintended change | +| Exploratory | Any, unscripted | Unexpected behaviour | + +- Double only what a unit test would cross a boundary to reach: I/O, time, + randomness, another process +- Keep deterministic in-process collaborators real +- Use the real dependency for the boundary an integration test covers; you + MAY double the unrelated ones +- Add a regression test for every fixed defect (SHOULD) + +#### Coverage + +- Cover every happy path the functional requirements define +- Cover negative inputs and edge cases as well (SHOULD) +- Cover each dependency's faults at every tier: unavailable, malformed + response, timeout, degraded operation (SHOULD) +- Meet the project's coverage threshold for new code before merging +- Never let coverage regress between releases +- Run every unit test from CI, with no human step +- Name a test so the name alone states the unit, the input and the expected + outcome (SHOULD) +- Run a unit that reads a structured external artifact against real + production data once before calling its suite complete, and add a + regression test for each gap it shows + +#### Testability + +- Keep business logic in pure functions, and push I/O to thin adapters at + the edges (SHOULD) +- Inject dependencies rather than construct them in the code under test + (SHOULD) +- Split a function that needs more than two mocks to test (SHOULD) +- Treat code that is hard to test as a design problem + +#### Isolation + +- Test behaviour, not implementation details +- Set or clear every environment variable a test depends on, in that test; + never rely on the ambient process state +- Treat a test that passes or fails by run order as an isolation bug +- Wait on a condition with a deadline, never a fixed sleep +- Never enumerate, signal or terminate a process the test did not start + (MUST NOT) +- Never mutate host state outside the working directory: the process + table, system services, the registry, the user's applications (MUST NOT) +- Stub every seam through which the code under test reaches a host + resource the test does not own, even when its subject is already faked +- Keep the dependency an integration test covers real, isolated to that + test, such as a throwaway container or a temporary database +- Investigate a failing test before anything else; never skip or suppress + one without a documented reason +- Check the test's own logic first when it behaves unexpectedly + +#### External definitions + +- Assert at least one case against a fixed vector the specification + publishes, wherever a format is defined outside the codebase (MUST) +- Never take a round trip through your own encoder and decoder as proof + that either is correct +- Assert what an object does, not the type the runtime reports for it +- Assert that a misuse fails, and which error only where the interface + declares one +- Never assert an exception class the runtime raises on its own + +#### Guard use + +- Assert that the code under test takes a guard, not only that the guard + works, where the guard exists for other code to take (MUST) +- Prefer a behavioural assertion, such as "a stopped component does no + work" +- Otherwise wrap the real guard in a recorder that logs entry and exit, and + assert the order of the work against it +- Pair every "does nothing" assertion with its "does something" control +- Sweep the module for sibling guards when one proves inert + +```bash +MODULE= +FIELD= +echo "references to $FIELD in $MODULE: $(grep -c "$FIELD" "$MODULE" || true)" +grep -n "$FIELD" "$MODULE" || true +``` + +Pass condition: the count is at least two and the listed lines include a +consumer. A count of one is the assignment alone: the guard is built and +never consulted. + +#### Provenance + +- Assert the source of a value, not the value, where a fix changes where it + comes from +- For such a fix, inject a source that yields a different value, and assert + the code overrides it +- Treat a new test that passes against the unfixed code as aimed at the + wrong property, not as proof the fix was unnecessary +- Substitute at the name the module under test reads, not on the module + that defines the type + +#### Thresholds + +- State, beside every threshold assertion, the property it gates, the + conditions it was calibrated under and what to do when an improvement + moves it +- Name the property in the failure message, not only the observed value + +#### Empty results + +##### Reach + +- Assert that a test expecting no violations reached its inputs: compare + the files it discovered against what its roots should cover (MUST) +- Fail on that comparison; never print a count for a reader to notice +- Report every occurrence, not the first per line or per file +- Fail an "every item holds" assertion when the set shrinks unexpectedly +- Give the coverage assertion its own test and its own message (SHOULD) +- Assert that each item declares its own value where a permissive default + exists; prefer a default that is not a legal value + +##### Floors + +- Assert a known floor, not mere non-emptiness +- Size the floor from a measurement, and state the derivation beside the + constant +- Use the measured count for an append-only corpus, and a stated margin + below it for one that churns + +#### Call sites + +- Exercise every call site of a changed shared path, not only the reported + case (MUST) +- Run the ground-truth comparison on every entity that uses the path +- Re-run every consumer that derives a committed artifact from the changed + surface, and keep that list beside the surface + +#### Real data + +- Drive a diagnostic view through the production entry point behind a + flag, never a separate command with its own setup +- Run the real pipeline on the input a fix targets, and diff its output + against the expected values +- Never take passing unit tests, suites and staleness checks as proof that + the fix fired + +#### Rendered output + +- Verify a visual change on its rendered output, read headless off the + pixels or the resolved DOM, never off the source (MUST) +- Capture the render before the change as well as after it (SHOULD) +- Confirm the build is fresh before re-editing a change that still looks + wrong + +#### Drift guards + +- Give every fact stored in two places a test that fails when the copies + diverge, such as: + - a documented limit and its constant + - live routes and the API contract + - the runtime version and the package metadata + - an export list and the module's bindings +- Introspect the live artifact rather than hardcode the expected value + (SHOULD) +- Assert one direction: the derived copy matches the source of truth + +### Base — Peer Review + +How a change is reviewed, and how a finding is proven before it is reported. + +#### Principle + +- Peer-review all code before merging (MUST) +- Hold the reviewer accountable for what merges, and the developer for what + they write +- Put reviews ahead of your own development; a blocked review blocks the + team + +#### MUST checklist - [ ] No credential, token or sensitive value appears in a committed file -- [ ] Every failure path is handled; no silent catch, no swallowed - exception +- [ ] Every failure path is handled; no silent catch, no swallowed exception - [ ] Every new dependency carries a licence the project's policy allows - [ ] Significant logic and architectural decisions are documented - [ ] Existing documentation matches the code after the change - [ ] Every changed section was re-read whole, not only the changed line -- [ ] Every claim changed text makes about itself (a count, "all") was - checked by counting with a tool -- [ ] Input from outside the process is validated as untrusted before it - is destructured, indexed or used as a key -- [ ] A refactor preserves behaviour on every path — each case, direction - and mode, including null handling, sort order and boundary values +- [ ] Every claim changed text makes about itself, such as a count or "all", + was checked by counting with a tool +- [ ] Input from outside the process, such as a URL parameter, is + validated as untrusted before it is destructured, indexed or used as + a key +- [ ] A refactor preserves behaviour on every path: each case, direction and + mode, including null handling, sort order and boundary values -**SHOULD checklist** +#### SHOULD checklist - [ ] Each non-trivial function has a unit test per relevant variant - [ ] Coverage does not fall @@ -452,30 +643,1136 @@ suggestion; block a merge only on the first two. - [ ] No new abstraction without two call sites, and no new dependency without a documented reason -- Produce a plan before implementing a feature or a non-trivial change: - the files touched, the signatures or outline, the edge cases, the - assumptions. Never write implementation code before the plan is - approved. Skip the plan for one-line fixes, typos and fully-specified - requests. -- Label a finding unverified until it is demonstrated. Reproduce a defect - by running the path before reporting it; read a passing test that - contradicts the reproduction before blaming the code. -- Explain a deviation from a SHOULD rule in the pull request. Land a - deviation from a MUST or MUST NOT rule only with a designated - approver's sign-off and its reason recorded in the pull request. Never - waive a MUST rule without that sign-off. - -## 8. Session protocol - -- At the start of a session, inspect the working tree and index, and read - this file before making any change. -- While working, follow sections 2 through 7 for every change. -- Before ending a session, read the MUST and SHOULD checklists in section - 7 and execute each item in sequence, in full — do not summarize or skip - any of them. - -## 9. Governance - -- **Who approves a change?** Open for the project to decide. -- **How is work tracked?** Open for the project to decide. -- **What is a release?** Open for the project to decide. +#### CI signals + +- Read the log of a red check before calling the pull request green or red +- Separate an infrastructure failure (the check could not run) from a diff + failure (it ran and found something), and say which in the merge decision +- File a separate task for an infrastructure failure, and note it in the + merge decision +- Never retry until green without saying so (MUST NOT) +- Never bypass a failing check by skipping hooks or by an admin merge + unless the maintainer explicitly accepts the risk (MUST NOT) + +#### Structure audit + +- Run a structure audit, which checks project completeness rather than + changed files, after a new project setup, a framework or stack migration, + a new major layer, and before a release milestone +- Verify every MUST in the base templates (the standard documents, a + `.gitignore`) and in the project's layer and stack templates +- Verify each sub-clause of a MUST separately; a rule requiring examples and + their output is two checks + +#### Planning + +- Produce a plan before implementing a feature or a non-trivial change: the + files, the signatures or outline, the edge cases, and the assumptions +- Never write implementation code until the plan is approved (MUST NOT) +- Skip the plan for one-line fixes, typos, changes the requester has + specified in full, and work whose approach the requester already approved +- Stay inside the approved plan; when a constraint invalidates it, stop and + re-surface the options + +#### Verifying a finding + +- Label a finding unverified until it is demonstrated (MUST) + +##### From an agent + +- Check an agent's finding against the file, commit or document that + settles it before acting on it or repeating it +- Distinguish a verified negative from a failed lookup, and say which +- Count a finding several agents agree on as one finding +- Correct a finding you passed on that proves wrong, and name what the + check showed +- Reconcile a finding with a verified record it contradicts before + changing anything: confirm both read the same artifact, prefer the more + specific evidence, and record the outcome +- Record a reversal of a documented decision, with its reason, in the + artifact that documented it +- Give a verifying agent the existing record and ask it to reconcile, not + re-derive +- Never delete a record because a check "could not confirm" it (MUST NOT) + +#### Deviations + +- Explain a deviation from a SHOULD rule in the pull request +- Land a deviation from a MUST or MUST NOT rule only with a designated + approver's sign-off and its reason recorded in the pull request (MUST) +- Never waive a MUST or MUST NOT rule yourself; stop and ask the approver + +### Backend — HTTP Conventions + +#### Port binding + +- Read the port from an environment variable such as `PORT`; never + hardcode it (MUST) +- Use a well-known default in development, and the port the platform + assigns in production + +#### Process lifecycle + +- Start fast — keep initialisation short (MUST) +- Shut down gracefully on a stop signal (`SIGTERM`) in order: stop + accepting new requests, let in-flight ones finish until the drain + deadline, cancel what remains, wait up to a bounded cancellation period, + release resources, then exit (MUST) +- Release resources when the cancellation period ends, even when some + cancelled work is still running +- Force-exit when the whole shutdown, from draining to releasing + resources, passes its hard deadline (MUST) +- Set the drain deadline plus the cancellation period below the hard + deadline, leaving time to release resources +- Fit the hard deadline inside the grace period the platform allows + before it kills the process +- Recover cleanly when a process is killed without warning (`SIGKILL`, + power loss) (MUST) +- Keep no state in process memory that a restart cannot rebuild; put it in + an external store, so any instance can be replaced + +#### Admin processes + +- Run one-off tasks (migrations, data fixes, REPL sessions) with the + application's code, config and dependencies (MUST) +- Commit admin scripts to the repository; never run them as ad-hoc shell + commands (MUST) +- Prefer idempotent scripts — safe to re-run +- Never run an admin task against production without a tested rollback plan + +#### Handler design + +- Keep handlers thin: decode request → call service → encode response +- Never put business logic in a handler; delegate it to a service layer +- Validate all incoming request data before processing +- Set a timeout on every outbound call (HTTP clients, database queries) + +#### Query parameters + +- Parse a typed query parameter explicitly so you can distinguish three + states: absent (use the default), present-and-valid (use it), and + present-but-invalid (raise 400) +- Never rely on a parsing helper that returns the default on a malformed + value; it silently turns a client error into a successful default-valued + 200 + +#### Request headers + +- Read every header name case-insensitively, as RFC 9110 defines them + (MUST) +- Avoid the `X-` prefix on custom headers (SHOULD NOT); RFC 6648 + deprecated this convention +- Use a vendor or application-specific prefix on a custom header instead + (SHOULD) + +#### HTTP methods + +- Never let a GET or HEAD request change resource state; RFC 9110 defines + both as safe +- Make every PUT and DELETE idempotent, as RFC 9110 defines them + +#### Resource representation + +- Make a text payload's field types conform to the relevant ISO standard + (MUST): + - Date and time values: ISO 8601 + - Language codes: ISO 639 + - Country codes: ISO 3166-1 alpha-2 + - Currency codes: ISO 4217 +- Serialise any JSON integer outside ±(2^53 − 1), -9007199254740991 to + 9007199254740991, as a string (MUST); JavaScript cannot represent one + beyond that range precisely, in either direction +- Reject non-finite values in an endpoint that serialises computed floats + to JSON (MUST); `NaN`/`Infinity` are not valid RFC 8259 JSON +- Configure the JSON encoder to reject them, so it fails loud at the + serialisation boundary (a 500) instead of emitting a bare `NaN` token + that strict parsers reject +- Represent an undefined computed float in JSON as `null`, normalised + before serialisation +- Document such a JSON field as nullable in the contract +- Return only the fields the caller needs (MUST); never pad a payload + with fields that are not consumed + +#### Error responses + +- Use consistent error response shape across all endpoints +- Never return stack traces, internal paths, or implementation details to the + client +- Use 4xx for client errors, 5xx for server errors — never use 200 for errors +- Carry a gRPC or GraphQL error the way its protocol defines instead: a + gRPC status code over HTTP 200, a GraphQL `errors` array under + GraphQL-over-HTTP's status rules +- Set an explicit `Content-Type` on every JSON response + +#### Authentication and authorisation + +- Serve all API traffic over HTTPS outside local development (MUST); + plain HTTP is not acceptable in staging or production +- Give access tokens a short, finite lifetime (MUST) +- Enforce both authentication and authorisation on every external API + endpoint (MUST), except a public endpoint the project declares +- Make a public endpoint only a declared read, or a declared write that + must run before the caller has an identity, such as a sign-up, sign-in, + account recovery or a contact form +- Declare each public endpoint in the route definition and the API + contract, in the change that makes it public; a public catalogue stays + public, the account records beside it stay protected +- Require authentication at minimum on internal API endpoints (SHOULD) +- Never make any other write endpoint accessible without a valid + authenticated identity (MUST NOT) +- Apply authentication and authorisation before any business logic runs +- Rate-limit each public endpoint per client — never expose an unbounded + write operation +- Return no account data from a public write +- Rate-limit a sign-in or recovery endpoint per account and per client +- Answer a sign-up or recovery request the same way, in content and + timing, whether or not the account exists +- Make each recovery token single-use, short-lived and bound to one account + +### Backend — API Design + +#### Statelessness +- Keep APIs stateless (MUST): store no client context on the server + between requests +- Carry everything a request needs in the request itself (MUST) +- Keep session state in the client or a dedicated session store, never in + the API service + +### Base — Application Security + +Apply these cross-cutting security rules to application code in every +project, regardless of language or framework. + +The sections below cover the OWASP Top 10 categories: injection, broken +access control, cryptographic failures, insecure design, security +misconfiguration, vulnerable components, identification and authentication +failures, software and data integrity failures, logging and monitoring +failures, and server-side request forgery. + +#### Input validation + +- Validate all external input at the system boundary — the first point + where untrusted data enters the application +- Validate complex input with a schema validation library; never + hand-write it +- Use an allowlist, not a blocklist — define what is valid, reject + everything else +- Reject invalid input with a clear error; do not silently coerce or strip + fields +- Do not repeat the boundary's schema validation in inner layers; a + function still asserts the preconditions it relies on + +#### Output encoding (XSS) + +- Encode dynamic data for its rendering context at the point of output: + HTML, URL, JavaScript, SQL, shell +- Encode on output, not on input — store the raw value, encode when + rendering +- Use the encoding the framework or template engine provides +- Never insert user-supplied data through a raw-HTML path that bypasses + auto-escaping +- Apply the encoding that matches each context; HTML encoding does not + prevent URL injection + +#### Injection prevention + +- Use parameterized queries for all database access; never concatenate user + input into SQL strings +- Escape shell arguments when invoking external commands, or use API + alternatives that do not invoke a shell +- Never pass user input to dynamic code execution, such as an `eval` + +#### Authentication + +- Hash passwords with a modern algorithm: bcrypt, scrypt, or Argon2 — never + MD5, SHA-1, or plain SHA-256 +- Require a minimum password length and reject known-breached passwords; + never impose composition rules (NIST SP 800-63B) +- Use constant-time comparison for secrets and tokens; timing attacks leak + information through response time +- Lock accounts or throttle after repeated failed attempts + +#### Session management + +- Generate session IDs with a cryptographic random generator +- Regenerate the session ID after login; this prevents session fixation +- Set cookie flags: `HttpOnly`, `Secure`, `SameSite=Lax` (or `Strict` for + sensitive applications) +- Expire sessions after an idle period: 30 minutes for sensitive + applications, configurable otherwise +- Invalidate sessions on logout; do not rely on cookie expiry alone + +#### Cross-site request forgery (CSRF) + +- Give every state-changing request a CSRF defence (MUST) when the session + is authenticated by an ambient credential +- Treat as ambient any credential the browser attaches on its own: a + cookie, HTTP Basic, or a client certificate +- Use the framework's built-in CSRF middleware; never hand-roll token + generation or comparison +- Treat `SameSite=Lax` on the session cookie as defence in depth, not the + defence; it does not cover top-level `POST` navigation on older browsers, + and a subdomain takeover defeats it +- Prefer the synchroniser token pattern +- Use the signed double-submit cookie where the server holds no session + state, with the token bound to the session identifier +- Validate the token on every `POST`, `PUT`, `PATCH` and `DELETE`, never on + `GET` +- Never change state on a `GET` request (MUST NOT) +- Treat an API authenticated only by a bearer token the client attaches + explicitly as needing no CSRF token; the browser never adds that header + on its own +- Require a CSRF token on a bearer-token API that also accepts cookie + authentication + +#### Secrets in code + +- Never hardcode secrets, API keys, tokens, or credentials in source files +- Keep local secret files out of version control +- Rotate a secret immediately if it is accidentally committed; removing it + from git history is not sufficient, since the secret is compromised + +#### Transport security + +- Use HTTPS everywhere, with no exceptions for production traffic +- Enable HSTS on all production sites (MUST), with `includeSubDomains` and + a minimum `max-age` of one year +- Require TLS 1.2 as the minimum version; disable TLS 1.0 and 1.1 +- Use strong cipher suites; disable known-weak ciphers + +#### Security headers + +- Set security headers on every HTTP response at the reverse proxy or + middleware level, not per route +- Set these required headers: + - `Content-Security-Policy` — start strict, relax only what a page needs + - `X-Content-Type-Options: nosniff` + - `X-Frame-Options: DENY` (or CSP `frame-ancestors`) + - `Strict-Transport-Security` (see Transport security) + - `Referrer-Policy: strict-origin-when-cross-origin` + - `Permissions-Policy` — disable unused browser APIs +- Map each static asset type to its `Content-Type` in code when enabling + `nosniff`; the browser then never corrects a wrong one +- Never let MIME resolution depend on the host when `nosniff` is enabled + (MUST NOT) +- When enabling `nosniff`, verify script and style execution in a real + browser, not just status codes +- Never use `unsafe-inline` or `unsafe-eval` in CSP without a written + justification +- Do not expose server version or technology stack in headers; remove + `X-Powered-By`, `Server` version strings + +#### Error handling + +- Never expose stack traces, internal paths, or database errors to end + users; return generic error messages externally +- Log full error details server-side for debugging +- Use consistent error response formats; do not leak internal structure + through varying error shapes +- Return each error through the protocol's own error signal, never as a + success +- Do not reveal whether a resource exists via error messages: login errors + should say "invalid credentials", not "user not found" vs "wrong password" + +#### Logging + +- Never log secrets, tokens or passwords +- Never log personally identifiable information (PII), except the client + IP in the security log below +- Sanitize log output; user-supplied data in logs can enable log injection + attacks +- Log security-relevant events: authentication attempts, access denials, + privilege changes, configuration changes +- Include enough context for investigation: timestamp, an opaque user ID, + action, result; never a name, email or submitted username +- Record the client IP only in the security log, access-restricted and + purged at the end of its retention period +- Retain security logs for a defined period; compliance may require 90 + days to 7 years + +#### Deserialization and data integrity + +- Never deserialize untrusted data with a format that can instantiate + arbitrary types; use a data-only format such as JSON +- Validate the structure and types of deserialized data before use; treat + it as untrusted input +- Verify integrity of downloaded artifacts, updates, and dependencies; use + checksums or digital signatures +- Pin dependency versions and verify checksums in lockfiles; do not trust + upstream registries blindly +- Use pinned, verified steps and images in CI/CD pipelines (MUST) +- Never pull `latest` tags in production CI/CD pipelines + +#### Agent secrets handling + +- Never read, print, or cat files that may contain secrets (MUST NOT): + `.env`, `credentials.json`, `*-key*`, `*.pem`, `*.key`, + `serviceaccount.json`, `secrets.yaml` +- Never echo, log, or display environment variable values (MUST NOT) +- Check a variable's presence by its exact name without printing its value, + and treat a set but empty variable as absent +- Never include secret values in commit messages, PR descriptions, or + conversation output (MUST NOT) +- Warn the user (MUST) before committing files that commonly contain + secrets (`.env`, `credentials.json`, private keys) +- Verify a secret's presence by a match count or an existence check, + never by printing it +- Flag a secret exposed in a session to the user immediately: name the + exposed secret, recommend immediate rotation, and note that session + history may be cached or logged + +### Backend — Authentication and Authorization + +Rules for identity verification (authn) and access control (authz). +Applies to any backend service that has protected resources. +Extends the security rules "Authentication" (`security-authn`) and +"Session management" (`security-sessions`), with backend-specific depth. + +#### General principles + +- Keep authentication (who are you?) and authorization (what can you do?) + in separate layers; they are separate concerns +- Never implement your own cryptographic primitives — use well-audited libraries +- Fail closed: deny access by default; grant explicitly +- Centralise auth logic; never scatter permission checks across route handlers + +#### Authentication + +- Prefer delegating authentication to an identity provider (IdP) over + rolling your own +- Expire an access token within 15 minutes when the service issues tokens + itself +- Issue refresh tokens only to user sessions, such as a browser or mobile + client; rotate each on use and expire it within 7 days +- Never issue a refresh token to a service +- Authenticate a service by credentials of its own, such as OAuth 2.0 + client credentials, mutual TLS or a scoped API key (below) +- Validate every signed token's signature, expiry, issuer and audience +- Reject a token that lacks any required claim +- Store refresh tokens server-side, in a database or a dedicated session + store, so they can be revoked; stateless refresh tokens cannot be + invalidated before expiry + +#### Token transport + +- Send access tokens in the `Authorization: Bearer ` header (MUST) +- Do NOT accept tokens in query parameters — they appear in server logs and + browser history +- Store a browser client's refresh tokens in `httpOnly`, `Secure`, + `SameSite=Strict` cookies (MUST) +- Never store refresh tokens in `localStorage` or JavaScript-accessible memory + +#### Authorization + +- Use role-based access control (RBAC) as the baseline (SHOULD): + assign permissions to roles, assign roles to users +- Add attribute-based access control (ABAC) as a layer on top of RBAC for + fine-grained needs +- Replace RBAC with ABAC only with a reason in a decision record +- Enforce authorization at the service layer, not only at the route layer; + a route that passes auth may call a service that operates on another + user's data +- Never trust client-supplied IDs for ownership checks — always verify that + the authenticated user owns or has access to the requested resource + +#### Observability + +- Log authentication failures at WARN to the security log, with IP and + user agent +- Name the account by its opaque user ID when it exists; never log the + submitted username or password +- Log authorization failures at WARN with user ID, resource, and action +- Alert on a spike in auth failures; it may indicate a credential stuffing + attack + +#### Testing + +- Cover permission logic with unit tests for all role combinations, + including edge cases (no role, multiple roles, deprecated role) +- Assert in an integration test that a protected endpoint rejects an + unauthenticated request with an unauthenticated status, such as HTTP 401 +- Assert in an integration test that it rejects an authenticated request + lacking permission with a permission-denied status, such as HTTP 403 +- Test token expiry: assert that an expired token is rejected +- Test token revocation where refresh tokens exist: assert that a revoked + refresh token cannot obtain a new access token + +### Backend — Database Conventions + +#### Schema changes + +- Make every schema change through a migration committed to source + control — never edit the database manually +- Never regenerate or modify a migration that is already merged +- Write one migration per logical change — do not batch unrelated schema + changes +- Provide a `down` migration for every `up`; where reversal would lose + data, say so in the migration and get approval before applying it + +#### Queries + +- Parameterise every query that takes a value; never build a query by + string interpolation +- Bound every query an interactive request runs with a limit or + pagination; a filter alone is no bound, since a filter on a flag can + still match millions of rows +- Stream or batch a deliberate export or batch scan, never load it whole +- Select only the columns or fields the code uses — never every column by + default +- Fetch related data for a set of rows in one query or batch, never one + query per row in a loop (N+1) + +#### Transactions + +- Wrap multi-step writes in a transaction — commit only after all writes + succeed +- Never leave a transaction open across a request boundary +- Keep transactions short — do not call external services inside a transaction +- Use an isolation level stronger than the engine's default only when + genuinely required + +#### Connections + +- Use a connection pool — never open a new connection per request +- Inject the database session/connection as a dependency — no global DB + handles +- Set the pool size explicitly from the instance count and the + database's connection cap, so all instances together stay under it +- Monitor pool exhaustion — alert when pool wait time exceeds threshold + +#### Soft deletes + +- Use soft deletes (`deleted_at` timestamp) only when audit history is + required; otherwise use hard deletes +- If using soft deletes, filter deleted rows out of every query by + default — never return deleted rows to callers +- Keep an append-only audit log table instead of soft deletes (MAY) + +#### Testing + +- Reset state between test runs — truncate tables or wrap each test in a + transaction rolled back after completion +- Do not substitute a different database engine in tests, such as an + in-memory one — behaviour differences cause false passes +- Never run schema migrations against a production database inside a test + suite + +### Frontend — UX Principles + +#### UX principles + +- Make every view usable on a small screen, not only on a desktop one +- Show only what the user needs at each step +- Never use a dark pattern: misleading UI, a forced action, a hidden cost +- Use the same interaction pattern for the same task throughout +- Treat a slow interface as a UX defect +- Make every component behave as it looks: what looks like a button acts + like one + +#### Accessibility — WCAG 2.1 AA + +- Meet WCAG 2.1 AA +- Keep text contrast at 4.5:1 or more, 3:1 for large text +- Make every interactive element reachable and operable by keyboard +- Never put a click handler on a non-focusable element (MUST NOT); it adds + no tab stop or keyboard activation +- Use a native interactive element for such a control instead: a button, a + link or another native control +- Style focus with `:focus-visible`, not `:focus`, which also outlines + mouse clicks +- Keep a visible focus indicator on every focusable element, links and nav + links included (MUST); links often lack one even where buttons have it +- Never convey meaning by colour alone +- Give images descriptive `alt` text, and decorative ones `alt=""` +- Use semantic HTML: landmark elements and a correct heading hierarchy +- Give an icon-only or ambiguous control, such as a social link, a + descriptive `aria-label`; never add one where visible text already names + the control +- Make an accessible name contain the control's visible text, ideally at + its start (WCAG 2.5.3, Label in Name) +- Close menus on Escape and restore focus + +#### Accessibility testing + +Automated tools catch about 30–40% of WCAG issues, so AA takes manual +testing too. + +##### Automated (run in CI) + +- Scan rendered pages or components with an automated accessibility + checker in CI; merge on zero violations + +##### Manual (run before shipping new interactive components) + +- Tab through the whole feature without a mouse: every action reachable, + focus order logical, no focus trap but an intentional modal +- Test it with one screen reader, such as NVDA, VoiceOver or TalkBack, and + check every content and state change is announced +- Zoom to 200%: nothing clipped or overlapping, and no horizontal scroll + at a 1280px viewport +- Check Windows High Contrast or the forced-colors media query: no + information lost when colours are overridden + +##### Criteria for done + +A feature is not complete until: + +- [ ] The automated accessibility check reports zero violations +- [ ] Keyboard navigation verified manually +- [ ] Screen reader walkthrough completed for new interactive elements + +#### Design system + +- Use the project's design system where one exists; never build an ad-hoc + component that duplicates one of its patterns +- Take design tokens (colours, spacing, typography, radii, breakpoints) + from the design system (MUST); never hardcode a visual value + +#### Browser support + +- Support the last two versions of Chrome, Firefox, Safari and Edge by + default +- Degrade gracefully where a browser lacks a feature + +### Base — Data Modeling + +Rules for schema design, naming, normalization, and relationships, in any +store: a relational database, a document store or a static data file. + +#### Naming conventions + +- Use one naming convention per store for every table or collection, + field, key and index; record it in the project's context file + +#### Normalization + +- Give every table or collection a primary key — prefer surrogate keys for + internal use, natural keys for external-facing APIs +- Store each fact in one place by default — duplicate it only when + measured read performance requires it +- Never pack several values into one string field, such as + comma-separated values — use a list or a related record +- Document the rationale when intentionally denormalizing + +#### Relationships + +- Never rely on application code alone to keep references valid +- Enforce valid references with the store's own constraint where it has + one, else with a check that every reference resolves +- Decide for every reference what deleting its target does: + - delete the referencing records for strong ownership + - clear the reference for a weak one + - refuse the delete when an orphan indicates a bug +- Keep a record apart, referenced by key, unless it has no life outside + its parent +- Document a self-referencing relationship's (e.g. `parent_id`) maximum + depth and cycle prevention strategy (MUST) + +#### Schema evolution + +- Run every schema change through a versioned migration (MUST); never + change a production schema by hand +- Prefer additive changes, such as a new field, table or collection +- Keep an additive change compatible with old writers: add a field + optional or with a default, never required without one where records + exist +- Give every destructive change (drop or rename a field) a migration plan: + add new → migrate data → drop old (MUST) +- Include both up and down steps in every migration (MUST) +- Say so where a down step cannot restore the data, and get approval + before applying that migration +- Test migrations against a production-like dataset before deploying + +#### Data types + +- Use the most specific type the store offers — a date type, not a + string, for dates +- Store timestamps in UTC — convert to local time at the + presentation layer +- Store monetary values as integers in minor units or as a decimal type — + never floating point +- Use `UUID` or `ULID` for distributed ID generation — auto-increment + is acceptable for single-database systems +- Document a maximum length for every text field (MUST); unbounded text + invites abuse and complicates indexing + +### Base — Data Governance + +Rules for data classification, retention, privacy, and ownership. +Applies to any project that stores or processes user data, business +data, or regulated information. + +#### Data classification + +- Classify every data field into one of four tiers: + - **Public** — safe to expose (product names, documentation) + - **Internal** — business-sensitive, not for external use + (internal metrics, cost data) + - **Confidential** — restricted access (customer PII, financial + records, API keys) + - **Restricted** — highest sensitivity (passwords, payment card + data, health records) +- Document the classification in the schema or data dictionary (MUST) +- Match access controls to the classification tier (MUST) +- Grant confidential and restricted data only to the roles or identities + that need it + +#### PII handling + +- Identify all personally identifiable information (PII) fields + in the schema — name, email, phone, address, IP, device IDs +- Encrypt PII at rest and in transit (MUST) +- Minimize PII collection — do not store what you do not need +- Provide a mechanism to delete PII — hard delete or anonymize, never + just soft-delete it +- Never put PII in application logs, error messages, or stack traces + (MUST NOT); the audit trail is a separate store, not a log +- Keep the client IP, the one PII field a security log may hold, in that + log alone, access-restricted and purged when its retention ends +- Mask or redact PII in non-production environments + +#### Retention + +- Define a retention policy for each data category — document + how long data is kept and when it is purged +- Meet every regulation that applies to the data in each retention + period (MUST) +- Implement automated purging — do not rely on manual cleanup +- Apply retention policies to audit logs and backups too +- Never retain backups indefinitely +- Document the purge mechanism: soft delete → hard delete after + N days, or direct hard delete + +#### Data ownership + +- Designate an owner for every data domain (users, orders, inventory) + (MUST) — a team or individual accountable for quality, access, and + lifecycle +- Have the data owner approve schema changes and access grants +- Document data ownership in the schema or data dictionary + +#### Audit trail + +- Log every change to confidential and restricted data (MUST): + who changed what, when, and the previous value +- Never record a credential's or secret's value in the audit trail, old or + new (MUST NOT); record that it changed, who changed it and when +- Record a PII field's change the same way, without its values, so + deleting the PII leaves no copy in the append-only trail +- Keep the audit trail in its own store, never in application logs, + with access restricted to the tier of the data it records +- Make audit logs append-only (MUST); never let application code edit + or delete them +- Include the actor (user ID or service identity), timestamp, + action (create, update, delete), and affected record + +## Procedures + +This agent loads no skills, so each task's procedures are here. + +### start-issue + +Starting work on an issue, a ticket or a bug report + +#### Picking up an issue + +- Re-read the target for existing coverage before writing anything; an + issue describes the tree on its filing date +- Verify everything the issue cites as existing, and run what it proposes + against the tree before adopting it +- Check the open pull requests and the decisions accepted since the filing + date for work that already closes or moves it +- Restate the scope before starting when it has moved since filing +- Read what a cited sibling change shipped, not what it proposed +- Resolve each cited version identifier against its source; a superseded + one still resolves +- Treat a closed classification in the acceptance criteria as a claim: + sort every member yourself before acting on any + + ``` + criteria: "each check runs on Linux or macOS" + sorted: 9 Linux, 2 macOS, 1 neither -- it runs only on Windows + ``` + +- Name each member that fits no branch, and the branch it fails + +### write-tests + +Writing or changing tests, fixtures or assertions + +#### Fault injection + +- Reproduce a fault that depends on the OS, filesystem, locale or + interpreter with a double at the real call's seam; never wait for the + platform to supply it (MUST) +- Clear a transient fault as it fires; give a permanent fault its own + double (MUST) +- Name the platform the evidence came from wherever a test clears a + suspected component +- Distrust a suspect cleared on one platform; retest it on the platforms + the evidence did not cover (SHOULD) + +#### Unique resources + +- Allocate a per-test port, directory, database or queue from a + module-level counter or a fixture, never from a counter on a class other + tests inherit (MUST) + +#### Worker leaks + +- Assert after every test that no thread, subprocess or server the suite + started survives it (MUST) +- Run the assertion per test, not once at session end +- Name the leak in the message, and the fix: join with a timeout, never + sleep +- Leave the assertion on permanently + +### add-check + +Adding or tightening a check, such as a linter rule, a CI step, a hook or a threshold + +#### Import bans + +- Declare a directional import ban where one part of the tree must not + import another (MAY), and check every ban declared + +```bash +pre-commit run find-import-bans --all-files --verbose +``` + +Pass condition: the bans-declared and modules-inspected counts are above +zero and `import-ban violations` is zero. Each ban is a +`--forbid IMPORTER:IMPORTED` argument; `not applicable` means none is +declared. + +#### New constraints + +- Run a new constraint (a rule, a check, a tightened bound, a narrowed + exemption) against the existing corpus before it merges (MUST) + +#### Enforcing the width + +- Declare the width as the line-length setting in the Markdown linter's + configuration (MUST); the linter reads no other file, so a width set only + for editors goes unenforced +- Keep any second copy of the width, such as `.editorconfig` for editors, + equal to the linter's +- Declare in the same place which of fenced blocks, table rows and headings + are exempt +- Exempt a line only where it cannot wrap: an unbreakable token, a bare + URL, a Markdown link, or a single-line directive a parser reads whole +- Enforce the width with the Markdown linter's line-length rule in CI + (MUST); a project that declares no width has no rule +- Pass that CI run the configuration and the files to lint explicitly + (MUST) + +### add-dependency + +Adding, upgrading or removing a dependency + +#### Optional dependencies + +- Where a dependency is optional, run one CI leg without it installed, + importing the package (MUST) + +### regenerate + +Editing a generated file's source, writing a generator, or merging the base branch into a branch that carries generated files + +#### Generated output + +- Make a generator emit output that passes the linters natively; a needed + `lint --fix` is a generator bug (MUST) + +#### Regenerating after a merge + +- Regenerate derived artifacts and re-run the staleness comparison after + every such merge, and stage what they produce + +#### Regenerated artifacts + +- Regenerate a derived artifact in the change that edits its source, and + stage both together (MUST) +- Name the regeneration trigger beside the sources it derives from (MUST) +- Run the staleness comparison after the edit, and again after any merge + that brings another branch's sources in (MUST) + +```bash + || exit 1 +git ls-files --error-unmatch -- > /dev/null || exit 1 +git diff --exit-code --stat -- +``` + +- Read the staged copy as the baseline: the comparison runs before the + commit, and in a clean checkout, such as CI's, the index is the commit +- Require a zero status; a failed regenerator, an artifact that is not + staged and any diff each fail it +- Treat any diff as a staged artifact that does not match its sources +- Treat a regenerator that fails this on a current artifact as defective: + it is not idempotent +- Summarise the visible impact before and after in the pull request body: + a verdict matrix, a delta table, a screenshot diff +- Open a tracked follow-up naming the stale files, by name or glob, where + regeneration is too expensive to bundle (MUST) +- Drop a regenerated file whose diff is line endings only: + +```bash +git diff --ignore-cr-at-eol +``` + +- Read an empty diff as noise, and drop the file with + `git checkout -- ` +- Never drop a file on `--ignore-all-space`; it hides `"a b"` becoming + `"ab"` +- Read any other whitespace-only diff before dropping it +- Open every regenerated binary artifact in a viewer or an image-read tool, + and confirm it tracks its source +- Regenerate a known-current control artifact first; a non-zero diff there + means the environment disagrees with the committed files +- Reconcile a non-zero control diff before committing anything regenerated +- Pair a spot-check of three to five representative artifacts with one + population metric when a change regenerates many + +#### Generated files + +- Start every generated file with a banner naming the tool that wrote it + and the command that refreshes it (SHOULD) +- Give every generator a `--check` flag that re-renders in memory and exits + non-zero on a diff or a missing file, and require it in pre-commit and CI + (SHOULD) +- Re-render to judge staleness; never rely on inspection, above all for a + visual or binary output such as a diagram export +- Exclude generated paths from formatters (SHOULD) +- Re-run the generator when its inputs change; never edit its output +- Preserve human-entered content when refreshing a generated file, or fail + naming what would be discarded (MUST) + +### change-api + +Adding or changing an endpoint, a field, an error response or the API contract + +#### API-first +- Design API-first (MUST): agree and document the public contract before + implementation begins (MUST), so client teams work in parallel and the + API is testable without a frontend +- Record any deviation from API-first in a decision record with its + justification (MUST) + +#### Protocol selection + +| Protocol | Use when | +|-----------|-----------------------------------------------------------------------------------------------------| +| REST | Default. External APIs, browser/mobile clients, third-party integrations, ops/admin endpoints | +| gRPC | Internal service-to-service, performance-critical paths, streaming, polyglot teams sharing a schema | +| GraphQL | Frontend-facing APIs where clients need flexible querying and over-fetching is a real problem | +| WebSocket | Real-time push, bidirectional streams where HTTP polling is not viable | +| Messaging | Async, fire-and-forget, event-driven | + +- Start with REST; deviate only with a reason in a decision record +- Combine REST for external and ops endpoints with gRPC for internal hot + paths (MAY) +- Justify any other pair of API styles in one service in a decision + record; two surfaces double the maintenance +- Never use gRPC as the primary interface for browser clients + +#### API contract +- Give every API the machine-readable contract of its kind, even when it + runs over HTTP (MUST): + - an OpenAPI specification for REST + - protobuf for gRPC + - a GraphQL schema + - a message schema for messaging +- Keep the contract current (MUST); a stale contract is worse than none +- Cover every resource, operation, parameter, response schema, error + response and authentication requirement in the contract +- Keep a changelog of API changes across versions +- Assert that the enums, operations and error codes in code match the + contract, so drift fails a test, not a consumer +- Contract-test a running instance against cases generated from the + contract +- Give the contract a revision of its own, apart from the package version + and from the API version +- Bump the contract revision for every contract change, additive ones + included; never bump it for a release that leaves the contract unchanged + +#### Versioning +- Keep every API version backward compatible (MUST) +- Version the API in the URI path prefix: `/v1/`, `/v2/` +- Start at `v1`; introduce `v2` only when a breaking change is unavoidable +- Use a custom request header (`Api-Version: 2`) where a path prefix does + not fit +- Never version through the media type (MUST NOT) + +#### Backward compatibility +- Release a new API version for every breaking change: a removed or + renamed response field, a changed field type, a switched auth scheme +- Treat as breaking, too, a changed verb or path, wire protocol or + Content-Type, and business logic that changes observable results +- Never bump the API version for an additive change (MUST NOT): a new + optional field, endpoint, verb or query parameter keeps `/v1/` and moves + only the contract revision + +#### Pagination +- Paginate every collection endpoint (MUST); never return an unbounded list +- Use `limit` and `offset` (or cursor-based) pagination +- Include navigation links or cursors (`next`, `prev`) in the response + +### deprecate + +Deprecating, renaming or removing a public name, an endpoint or a template + +#### Deprecation and renames + +- Deprecate a public symbol, naming its replacement, before a later change + removes it +- Deprecate every part of one call site together, such as a method and its + keyword arguments, or break the whole call; never alias the outer name + alone +- Retire a concept by sweeping every surface that still instructs its use, + tickets and plans included, until a search returns only historical + records + +#### Deprecation strategy +When a breaking change is introduced: + +1. Deploy the new version alongside the old one +2. Add the `Deprecation` header to all responses from the old version with + the Unix timestamp of when deprecation started: + `Deprecation: @` +3. Optionally add the `Sunset` header with the planned removal date: + `Sunset: ` +4. Notify all consumers and agree on a migration timeline +5. Remove the old version only after the sunset date has passed; without + a `Sunset` header, only after the timeline agreed in step 4 ends + +### migrate-data + +Writing or running a schema migration, a data fix or a backfill + +#### Indexing + +- Index every foreign key column — not every engine does so automatically +- Add composite indexes for common multi-column filter + sort combinations +- Avoid over-indexing write-heavy tables — each index adds write overhead +- Drop unused indexes — check the engine's index usage statistics + regularly + +### write-docs + +Writing or restructuring documentation, a decision record or a diagram + +#### Standard documents + +- Carry these three in every project (MUST); their layout is the project's own + +| File | Purpose | +| --- | --- | +| `README.md` | What the project is and how to use it | +| `AGENTS.md` | Agent context and project rules, for any agent | +| `CLAUDE.md` | Agent context and project rules, for Claude Code | + +#### Diagrams and assets + +- Commit every editable source beside its rendered output; never commit a + binary-only diagram +- Give a committed artefact one authority: commit its editable source or + its generator, never both +- Never use proprietary formats such as Word, Illustrator or Affinity + Designer +- Split a diagram that serves two purposes into two + +#### Docs as code + +- Keep technical documentation in the repository, in Markdown, under the + same review as code + +### verify-finding + +Reporting a defect, a measurement or a claim, or acting on another agent's finding + +#### From reading + +- [ ] Reproduce the defect before reporting it: run the path +- [ ] Read a passing test that contradicts the reproduction before blaming + the code; it may pin a decision + +#### From a measurement + +- [ ] The tool measures the rule's unit: bytes are not characters +- [ ] The tool measured the claimed scope, not a diff, sample or partition; + a whole-codebase claim comes from a whole-codebase run (MUST) +- [ ] The mode that produced each kept number is recorded beside it +- [ ] One flagged item was checked by hand +- [ ] Each count carrying a finding was produced twice, by different means +- [ ] A zero was checked by finding one positive by hand +- [ ] The tool fails loudly on unsupported input rather than exiting clean + (SHOULD) + +#### From an extraction + +- [ ] An element reported absent was checked against the raw artifact +- [ ] Extracted size was compared with the raw artifact, and known elements + survived the round trip +- [ ] The claim is scoped to what was inspected: "not verifiable from the + extract", never "missing" + +#### From a probe + +- [ ] The probe ran under the conditions the finding is about, such as its + user, credential and environment +- [ ] A claim the probe cannot make under those conditions is scoped to the + ones it tested + +### review + +Reviewing a pull request or a diff, or judging whether it is ready to merge + +#### Priority order + +Review in this order, most critical first. The quality rules, and any +language quality rules the project carries, are the standard for items 2 +to 4. + +1. **Security**: anything exploitable, any credential or licence problem +2. **Correctness**: wrong results, unhandled failures, race conditions +3. **Clarity**: obscure names, deep nesting, high cognitive complexity, + boolean flag parameters +4. **Conventions**: deviations from the project's agreed patterns + +The order above is by area; weigh each finding separately. + +- Label each finding a demonstrated defect, a deviation from a policy the + project adopted, or a suggestion +- Block a merge only on a defect or a policy deviation; leave a + suggestion to the author + +### generate-context + +Generating or regenerating the project's agent context files + +#### Adopting shared rules + +- Treat template rules as candidates; the project chooses what it adopts +- Adopt a rule when it addresses a named local defect, a requirement or a + credible material risk; a preventive security control needs no incident +- Never let a template update create compliance work, tickets or decision + records by itself (MUST NOT); a newer tag alone is no reason to move the + pin +- Record a declined candidate in at most one line, if at all (MAY), in the + existing pull request or discussion +- Keep adopted rules in force until the project changes them, and keep the + operative selection in the project's context file +- Inline this adoption boundary in a reference or hybrid context file + (MUST), so a new upstream MUST cannot widen the adopted set +- Assess security fixes in tools the project runs promptly; review new + conventions when a project need warrants it + +#### Output file by agent + +| Agent | Context file | +| --- | --- | +| Claude Code | `CLAUDE.md` | +| Cursor | `.cursor/rules/project.mdc` | +| GitHub Copilot | `.github/copilot-instructions.md` | +| OpenAI Codex CLI | `AGENTS.md` | +| Generic or other | `AGENTS.md` | diff --git a/tests/efficacy/arms/inline/generation.json b/tests/efficacy/arms/inline/generation.json index 4c36073..f7604d6 100644 --- a/tests/efficacy/arms/inline/generation.json +++ b/tests/efficacy/arms/inline/generation.json @@ -1,7 +1,6 @@ { "arm": "inline", - "kind": "model", - "output_model": "inline", + "kind": "emit", "ref": "9abed019", "source": { "remote": "https://github.com/solid-ai-dev/solid-ai-templates.git", @@ -16,7 +15,7 @@ "base-security", "base-data-governance" ], - "started_at": "2026-11-13T20:55:33", + "started_at": "2026-11-15T11:26:55", "commit": "9abed01916b941d9ed2f8daa8ff8c3b28f0718fd", "resolved_files": [ "templates/core/quality.md", @@ -33,141 +32,17 @@ "templates/data/data-modeling.md", "templates/data/data-governance.md" ], - "prompt_chars": 84056, - "prompt_leak": null, - "prompt_file": "C:\\efficacy\\gen6b-inline\\arm-inline-prompt.txt", - "auth_probe": "ready", - "command": [ - "C:\\Users\\bgeorgiev\\.local\\bin\\claude.EXE", - "-p", - "--output-format", - "json", - "--model", - "claude-sonnet-5", - "--effort", - "high", - "--permission-mode", - "bypassPermissions", - "--setting-sources", - "", - "--settings", - "C:\\efficacy\\gen6b-inline\\home\\settings.json", - "--strict-mcp-config", - "--disallowed-tools", - "WebSearch", - "WebFetch" + "declined": [ + "templates/security/security.md#Server-Side Request Forgery (SSRF)", + "templates/security/security.md#File uploads", + "templates/security/security.md#CORS", + "templates/backend/auth.md#API keys (service-to-service)" ], - "model": "claude-sonnet-5", - "effort": "high", - "elapsed_s": 430.0, - "exit_status": 0, - "result": { - "duration_api_ms": 427908, - "stop_reason": "end_turn", - "session_id": "4b6adbf2-f3cc-4144-8121-990b729f4e89", - "total_cost_usd": 0.5432242, - "usage": { - "input_tokens": 2, - "cache_creation_input_tokens": 38590, - "cache_read_input_tokens": 25101, - "output_tokens": 38384, - "output_tokens_details": { - "thinking_tokens": 29500 - }, - "server_tool_use": { - "web_search_requests": 0, - "web_fetch_requests": 0 - }, - "service_tier": "standard", - "cache_creation": { - "ephemeral_1h_input_tokens": 38590, - "ephemeral_5m_input_tokens": 0 - }, - "inference_geo": "global", - "iterations": [ - { - "input_tokens": 2, - "output_tokens": 38384, - "cache_read_input_tokens": 25101, - "cache_creation_input_tokens": 38590, - "cache_creation": { - "ephemeral_5m_input_tokens": 0, - "ephemeral_1h_input_tokens": 38590 - }, - "type": "message" - } - ], - "speed": "standard", - "fallback_credit": null - }, - "modelUsage": { - "claude-sonnet-5": { - "inputTokens": 2, - "outputTokens": 38384, - "cacheReadInputTokens": 25101, - "cacheCreationInputTokens": 38590, - "webSearchRequests": 0, - "costUSD": 0.5432242, - "contextWindow": 1000000, - "maxOutputTokens": 64000, - "thinkingTokens": 29500, - "cacheCreationEphemeral5mInputTokens": 0, - "cacheCreationEphemeral1hInputTokens": 38590, - "canonicalModel": "claude-sonnet-5", - "provider": "firstParty", - "costBasis": "list" - } - }, - "permission_denials": [], - "terminal_reason": "completed", - "fast_mode_state": "off", - "fast_mode_disabled_reason": "sdk_opt_in_required", - "subagent_stats": { - "spawned": 0, - "requested": { - "background": 0, - "foreground": 0, - "unset": 0 - }, - "started_in_background": 0, - "max_depth": 0, - "spawned_by_subagents": 0, - "completed": 0, - "failed": 0, - "killed": { - "parent": 0, - "user": 0, - "system": 0 - }, - "refused": { - "depth_limit": 0, - "concurrency_limit": 0, - "budget": 0 - }, - "by_type": {} - }, - "safety_stops": 0, - "is_error": false, - "num_turns": 1, - "subtype": "success", - "api_error_status": null, - "result": "# tariff\n\nPricing and invoicing web application \u2014 Imbra Ltd\nOwner: Imbra Ltd. Runs locally only; no repository URL, live URL or deployment target applies.\n- Model: inline\n\n## 1. Project\n\n### 1.1 Overview\n\n`tariff` assembles invoices from a product catalog, several kinds of discount\nrule, tax jurisdictions and customers. Stack: Python 3.12, Flask 3, Jinja,\nHTMX, SQLite. It runs locally, with no deployment target.\n\nTwo actors use it: an administrator working in a browser, and a separate\nprogram that imports the pricing engine directly as a library, without the\nweb application present. The store is a local SQLite file. Nothing in this\napplication reaches the network: no outbound HTTP call, no inbound API\nbeyond the local web UI, no CORS surface, no SSRF surface. Do not add one\nwithout revisiting this file.\n\nOne administrator signs in to use the web application; nobody else has an\naccount. Customers are people: the system stores each one's name, email and\npostal address, and names them on the invoices billed to them. Imbra Ltd is\nin the EU, so GDPR applies \u2014 see section 6.\n\n### 1.2 Project structure\n\nSee `README.md` for the directory map; do not duplicate it here.\n\nPlacement rule: keep the pricing engine in its own package, with no import\nof Flask, Jinja, HTMX or any other web-layer module. It must import and run\ncorrectly with the web application absent. The web application package may\nimport the pricing engine; the reverse must never happen.\n\n### 1.3 Commands\n\nThe project has not yet chosen a package manager, test runner, type\nchecker, linter or formatter. Until it does, each command below names what\nit must do, not how:\n\n- **Install**: resolve and install the project's pinned dependencies from\n its lockfile.\n- **Migrate**: apply pending SQLite schema migrations through a committed\n script before the application starts.\n- **Run**: start the Flask application locally, reading the port from an\n environment variable, with a sensible default for local development.\n- **Test**: run the automated test suite (unit and integration) covering\n both the pricing engine library and the web application.\n- **Type-check / Lint / Format**: run the project's static type checker,\n linter and formatter, each in its strict and quiet mode, reporting zero\n issues.\n\n## 2. Architecture boundaries\n\n- Keep the pricing engine a standalone Python library with no dependency on\n Flask, Jinja, HTMX or any web-layer code (MUST); it must import and run\n with the web application absent.\n- Treat the web application as one caller of the pricing engine, never a\n second place that computes a price, discount or tax figure \u2014 call the\n library; never re-implement its logic in a route handler or a template.\n- Keep the module graph acyclic: the web application depends on the\n pricing engine; the pricing engine never imports the web application\n (MUST).\n **Check**: no module under the pricing-engine package imports anything\n from the web-application package; the check must report zero violations.\n- Treat the pricing engine's public functions and classes as the contract\n the other program \u2014 its second caller \u2014 depends on. Apply the\n deprecation rule (section 3.2) before changing or removing any of them.\n- Give the pricing engine package its own version, independent of the web\n application's; bump it deliberately, following semantic versioning,\n whenever its public API changes.\n- Never let the pricing engine write to standard output or standard error,\n and never let it configure logging beyond its own logger (MUST). Make\n its logger injectable, falling back to its own module logger, so each\n caller captures its output on its own terms.\n **Check**: run the library alone in a fresh process and confirm it emits\n nothing on stdout or stderr; a test runner's own log handler can hide a\n default that would otherwise leak into both callers.\n\n## 3. Code conventions\n\n### 3.1 Git\n\n- Commit under one full name and one consistent email; never change\n identity mid-project.\n- Work on a branch; never commit directly to `main`.\n- Never commit build output, dependency directories or secrets. Commit a\n generated file only when the project tracks it on purpose.\n- Keep a `.gitignore` (MUST) covering dependencies, build output, secrets,\n editor state, OS files and coverage output.\n- Commit lockfiles (MUST).\n- Inspect the working tree and the index before starting a task. Never\n discard, reset, stash or overwrite a change the task did not make.\n Stage only the changes the task made \u2014 a whole file only when it held\n no prior change, otherwise only the task's hunks. Read the staged diff\n before committing. Stop and ask when a task change and a prior change\n share a hunk. Report a pre-existing change that blocks the task rather\n than removing it.\n- Keep a pull request to one concern (SHOULD). Test locally before\n committing. Review the diff against the base before merging, in the\n order security, correctness, clarity, conventions. Merge only after the\n review passes and CI is green.\n- Read the CI run for the push before describing a change as good. Treat\n a pull request with no registered check as not passed. Never merge\n while a check is failing, cancelled or not yet registered. Re-run a\n verification a pull request claims once the base has moved since it was\n written. Read a new or changed workflow's first run in its real\n environment before trusting it.\n- Never force-push, including with `--force-with-lease` (MUST NOT). Bring\n a branch up to date by merging the base into it, never by rebasing and\n force-pushing.\n\n**Off-limits paths** (MUST NOT change without explicit approval; propose\nfirst, with a rollback strategy and the tests that would catch a\nregression):\n\n- Authentication and session code (the administrator's sign-in).\n- SQLite migrations.\n- `.env*` and secrets.\n- CI/CD workflow files, if and when the project adds any.\n- Payment code: not applicable \u2014 this application does not process\n payments.\n\nA diff confined to prose is ordinary work; a comment a tool reads (a\nlinter disable, a coverage pragma) counts as executable content and is\noff-limits the same as a command or a permission. Name an off-limits path\nat the top of a change's summary whenever the diff touches one, proposal\nor not.\n**Check**: the change summary names every off-limits path the diff\ntouches; the check must report zero undeclared touches.\n\n### 3.2 Python\n\n- Keep one authoritative representation of each piece of pricing, discount\n or tax knowledge (DRY). Build only what a stated requirement justifies\n (YAGNI); record beside every deferral the concrete condition that\n reopens it. Delete a path once evidence shows it unreachable.\n- Compute derived counts and statistics from the data; never hardcode\n them. Remove unused modules, assets and data files promptly.\n- Name a function with a verb, a class or module with a noun, a boolean\n with `is`, `has` or `can`. Rename a name that needs a comment to explain\n it. Use the same name for the same concept in every module.\n- Keep cognitive complexity at or under 15 per function; nest at most\n three levels; use guard clauses and early returns. Replace a boolean\n flag that selects behaviour with an enum or two named functions.\n- Name every magic number and string as a constant \u2014 a discount\n percentage, a tax rate, a threshold. Size a tuned threshold from its\n measured distribution, naming the data source beside the constant;\n take a limit a specification fixes (e.g. a tax jurisdiction's own\n rounding rule) from that specification instead.\n- Keep coupling shallow: a change inside one module must not require\n changes in unrelated modules. Talk only to direct dependencies. Reach a\n heavy or platform-limited dependency through one module that owns its\n import.\n- Validate input at boundaries and fail at once on invalid state. Read a\n value from its source-of-truth field, and raise when it is missing;\n never fall back to a value derived from a slug, name or hash. Add an\n error type only where a caller could act differently. Never let a\n caller-side filter stand in for a precondition.\n- Deprecate a public symbol, naming its replacement, before a later change\n removes it. Deprecate every part of one call site together; never alias\n the outer name alone.\n- Keep constants beside the functions that use them.\n- Encode every committed text file in UTF-8 with LF line endings (MUST);\n keep identifiers ASCII (MUST). Set a program's output encoding\n explicitly wherever another program reads its output \u2014 in particular,\n the invoice export path. Commit a `.gitattributes` with `* text=auto`,\n adding `eol=lf` for hard LF.\n **Check**: every tracked text file is UTF-8 with LF endings and ASCII\n identifiers; the check must report zero exceptions.\n- Prefer code that needs no comment. Never cite a ticket, PR or ADR number\n in a comment or docstring \u2014 state the substance. Name a source (author,\n year, method) where a tax or discount rule's logic is non-obvious.\n- Commit no debug output (`print()`) and no hardcoded breakpoint. Delete\n commented-out code. Gate debug tooling behind a flag, off by default.\n- Write a probe script to measure data or behaviour rather than guess;\n delete it before the commit that uses its findings; keep the findings\n themselves in durable comments or decision records.\n- Grep for a construct a comment records as not working before reusing\n it; read every hit as a suspected instance of the same defect.\n- Run a new constraint \u2014 a tightened bound, a narrowed exemption \u2014 against\n the existing corpus before it merges.\n- When deleting, truncating or purging data (notably a GDPR erasure, see\n section 6), act only on what the operation can prove is its target: an\n exact customer ID, not a name match or a path guess. Find nothing, and\n raise, where that proof is unavailable.\n- Confirm a migration, import or bulk-edit script is correct before\n acting on its output in bulk; cross-check an independent source before\n overwriting stored data that looks wrong.\n- Adopt the project's static type checker at its strictest setting and\n keep it clean (MUST); annotate every public function's parameters and\n return type (MUST). Adopt a linter and a formatter and keep both clean\n (MUST). Run all three before every commit and in CI; each must print\n nothing.\n- Finish a task when the requested behaviour works through the entry\n point its caller reaches, and the checks that prove it pass. Report a\n check that could not run as not run, never as a pass. Report a problem\n found outside the task as its own task rather than folding it in.\n\n### 3.3 Web layer (Flask / Jinja / HTMX)\n\n- Read the port from an environment variable; never hardcode it. Keep\n initialisation short.\n- Run one-off tasks (migrations, data fixes) with the application's own\n code, config and dependencies; commit admin scripts to the repository\n rather than running ad-hoc shell commands; prefer idempotent scripts;\n never run one against the live database without a tested rollback plan.\n- Keep handlers thin: decode the request, call the pricing engine or a\n service function, render the response. Never put business logic in a\n handler. Validate all incoming request data before processing it.\n- Parse a typed query parameter explicitly, distinguishing absent\n (default), present-and-valid (use it) and present-but-invalid (raise a\n 400) \u2014 never let a parsing helper silently turn a bad value into the\n default.\n- Read header names case-insensitively. Avoid the `X-` prefix on a custom\n header; use an application-specific prefix instead.\n- Never let a GET or HTMX `hx-get` request change state. Make every PUT\n and DELETE (including an `hx-delete`) idempotent.\n- Represent dates and times as ISO 8601, currency codes as ISO 4217, and\n country or tax-jurisdiction codes as ISO 3166-1 alpha-2, wherever the\n application stores, computes or displays them.\n- Use a consistent error shape across every route and HTMX fragment. Never\n expose a stack trace or an internal path to the browser; return a\n generic message and log the detail server-side. Use proper 4xx/5xx\n status codes, never 200, for an error. Set an explicit `Content-Type`\n on every response.\n- Enforce authentication on every route (MUST); this application declares\n no public endpoint. Apply the auth check before any business logic\n runs. Never expose a write path without the authenticated\n administrator's session.\n- Not applicable, since nothing here reaches the network: HTTPS/TLS\n enforcement, HSTS and other reverse-proxy security headers, CORS,\n multi-instance process lifecycle (graceful shutdown, SIGKILL recovery).\n\n### 3.4 Data model (SQLite)\n\n- Pick one naming convention for tables, columns, keys and indexes, and\n record it here once chosen \u2014 open for the project to decide.\n- Give every table a primary key; prefer a surrogate key. Store each fact\n in one place; duplicate only when measured read performance requires\n it, with the rationale documented. Never pack several values into one\n field (e.g. a composite discount-rule string) \u2014 use a related record.\n- Enforce every reference (customer \u2192 invoice, invoice \u2192 product, invoice\n \u2192 tax jurisdiction) with SQLite's own foreign-key constraint, or an\n explicit check that every reference resolves. Decide what deleting the\n target of each reference does \u2014 see section 6 for the customer case.\n Document the maximum depth and cycle-prevention strategy for any\n self-referencing relationship, such as a stacked or nested discount\n rule, if one exists.\n- Make every schema change through a versioned migration (MUST); never\n edit the schema by hand. Prefer additive changes, compatible with old\n writers. Give a destructive change (drop or rename a column) a plan:\n add the new column, migrate the data, drop the old one, with both up\n and down steps (MUST). Say so, and get approval, where a down step\n cannot restore the data. Test a migration against realistic data before\n applying it.\n- Use the most specific SQLite type for each field: a date/time type, not\n a string, for dates. Store timestamps in UTC; convert to local time only\n at the presentation layer. Store every monetary value \u2014 a price, a\n discount, a tax amount, an invoice total \u2014 as an integer in minor units\n or an exact decimal type; never as a float (MUST). Document a maximum\n length for every text field: customer name, email, postal address,\n product description.\n- Open one connection per request or worker thread; never a long-lived\n global handle. Wrap a multi-step write (e.g. assembling an invoice from\n its line items) in a transaction; commit only once every write\n succeeds; keep the transaction short.\n- Bound every interactive query with a limit or pagination (e.g. a\n customer or invoice listing); a filter alone is not a bound. Select only\n the columns a code path uses. Fetch related rows for a set in one query\n or batch, never one query per row in a loop.\n- Use a hard delete or an anonymizing update for a customer erasure (see\n section 6), never a soft delete that still returns the row to ordinary\n queries. Keep an append-only audit log table instead of a soft-delete\n flag.\n- Reset state between test runs \u2014 truncate tables or roll back a\n transaction wrapping each test. Never substitute a different database\n engine in tests; SQLite's own behaviour is part of what is tested.\n Never run a schema migration against a production database inside a\n test suite.\n\n## 4. Quality \u2014 testing\n\nClassify a test by the boundary it crosses: unit (none), integration\n(process/component \u2014 e.g. a real temporary SQLite file), system (the\nwhole application against its requirements), regression (reusing\nexisting tests against a fixed defect), exploratory (unscripted).\n\n- Double only what a unit test would cross a boundary to reach: file I/O,\n the system clock (discount and tax-jurisdiction rules can be\n date-effective), randomness. Keep deterministic in-process\n collaborators real.\n- Add a regression test for every fixed defect.\n- Cover every happy path the pricing, discount, tax and invoicing rules\n define, plus negative inputs and edge cases (SHOULD), plus each\n dependency's faults (an unavailable database file, a malformed row).\n- Meet the project's coverage threshold for new code before merging;\n never let coverage regress between releases. Run every unit test from\n CI with no human step. Name a test so its name alone states the unit,\n the input and the expected outcome (SHOULD).\n- Keep pricing, discount and tax logic in pure functions; push SQLite\n access to thin adapters at the edges (SHOULD). Inject dependencies\n rather than construct them in the code under test. Split a function\n that needs more than two mocks to test.\n- Test behaviour, not implementation details. Set or clear every\n environment variable a test depends on, in that test. Treat a test that\n passes or fails by run order as an isolation bug. Wait on a condition\n with a deadline, never a fixed sleep. Never enumerate, signal or\n terminate a process the test did not start. Never mutate host state\n outside the working directory. Investigate a failing test's own logic\n before skipping or suppressing it.\n- Allocate a per-test temporary database file or path from a fixture or a\n module-level counter, never from state a test class inherits.\n- Assert after every test that no thread, subprocess or server the suite\n started survives it; join with a timeout, never a sleep.\n- Exercise every call site of a changed shared pricing, discount or tax\n path, not only the reported case; keep the list of consumers beside the\n shared path.\n\n## 5. Security\n\n- Validate all external input (invoice, customer and discount-rule forms)\n at the boundary, with a schema validator, using an allowlist. Reject\n invalid input with a clear error; never silently coerce or strip\n fields.\n- Encode dynamic data for its rendering context at the point of output.\n Rely on Jinja's auto-escaping; never insert user-supplied data through\n a raw-HTML path (`|safe`, `Markup`) that bypasses it.\n- Use parameterized SQLite queries for all database access; never\n concatenate user input into a query string.\n- Hash the administrator's password with bcrypt, scrypt or Argon2 \u2014 never\n MD5, SHA-1 or plain SHA-256. Require a minimum length and reject\n known-breached passwords; impose no composition rules. Use\n constant-time comparison for secrets and tokens. Lock the account or\n throttle after repeated failed sign-in attempts.\n- Generate the session ID with a cryptographic random generator;\n regenerate it after login. Set `HttpOnly`, `Secure` and\n `SameSite=Strict` on the session cookie. Expire the session after an\n idle period. Invalidate it on logout; do not rely on cookie expiry\n alone.\n- Give every state-changing request (every HTMX `POST`/`PUT`/`PATCH`/\n `DELETE`) a CSRF defence (MUST), since the administrator's session is\n authenticated by an ambient cookie. Use the framework's built-in CSRF\n middleware; prefer the synchroniser token pattern. Validate the token\n on every state-changing request, never on GET. Never change state on a\n GET request.\n- Never hardcode a secret, API key or credential in source. Keep local\n secret files out of version control. Rotate a secret immediately if it\n is ever committed.\n- Never expose a stack trace, an internal path or a database error to the\n administrator's browser; log the full detail server-side. Answer a\n failed sign-in the same way regardless of whether the account exists:\n \"invalid credentials\", never \"user not found\".\n- Never log a secret, token or password, and never log a customer's name,\n email or postal address (see section 6) \u2014 log an opaque ID instead.\n Sanitize any user-supplied data that reaches a log. Log authentication\n and authorization failures at WARN, with an opaque user ID, never a\n submitted username. Keep the client IP only in an access-restricted\n security log, purged at the end of its retention period.\n- Never deserialize untrusted data with a format that can instantiate\n arbitrary types; use a data-only format (JSON) for any HTMX partial\n that carries structured data. Pin dependency versions and verify\n lockfile checksums; never trust an upstream registry blindly.\n- Never read, print or `cat` a file that may hold secrets (`.env`,\n `credentials.json`, `*.pem`, `*.key`). Never echo or log an environment\n variable's value; check its presence by name only. Warn before\n committing a file that commonly holds secrets. Flag any secret exposed\n in a session immediately, name it, and recommend rotation.\n- Not applicable, since nothing here reaches the network: HTTPS/HSTS/TLS\n enforcement, reverse-proxy security headers, CORS, SSRF defences. Not\n applicable, since the application has no upload feature: file-upload\n validation.\n\n## 6. Privacy and data governance (GDPR)\n\n- Classify a customer's name, email and postal address as Confidential\n personal data. Classify an invoice (which carries that PII alongside\n pricing and tax figures) as Confidential. Classify the product catalog,\n discount rules and tax-jurisdiction tables as Internal.\n- Match access to classification: only the signed-in administrator may\n read or write Confidential data; there is no lower-privileged role to\n restrict it from.\n- Encrypt PII at rest (MUST). There is no network transit to secure here.\n- Minimize PII collection: store only the name, email and postal address\n the invoicing relationship needs.\n- Never put a customer's name, email or postal address in an application\n log, error message or stack trace (MUST NOT); use an opaque customer ID\n there instead.\n- Provide an erasure path (GDPR Art. 17) that anonymizes or removes a\n customer's name, email and postal address from the live customer record\n on request.\n- Preserve the name and address already billed on a previously issued\n invoice exactly as issued (GDPR Art. 17(3)(b) permits retaining what a\n legal \u2014 here, tax and bookkeeping \u2014 obligation requires): erase or\n anonymize the customer record, never retroactively edit an issued\n invoice's billing details. Never delete an issued invoice as a side\n effect of an erasure request; clear or anonymize the customer reference\n on it instead of deleting the row.\n- Provide an access/export path (GDPR Art. 15) that produces a complete,\n human-readable copy of a customer's stored personal data and the\n invoices billed to them, on request.\n- Record every erasure and export request in an append-only audit trail:\n who requested it, when, and what action was taken \u2014 never the PII\n values themselves, so that erasing the PII leaves no copy in the trail.\n Log every other change to Confidential data (a customer record, an\n invoice, a price-setting discount rule) the same way: who changed what,\n when, and the previous value, with PII excluded. Keep this trail in its\n own store, separate from application logs, access-restricted to the\n administrator.\n- Define a retention period for customer and invoice data that satisfies\n the bookkeeping and tax-retention law of the applicable EU member\n state, and purge data automatically once it lapses; the exact period is\n open for the project to decide, pending confirmation of the applicable\n jurisdiction. Apply the same retention and purge discipline to the\n audit trail.\n- Use synthetic customer data in tests and local development fixtures;\n never real customer PII.\n- Designate the administrator as the owner of every data domain\n (customers, invoices, products, discount rules, tax jurisdictions)\n until the project names otherwise.\n\n## 7. Review process\n\nReview in this order, most critical first, weighing each finding\nseparately: **security**, **correctness**, **clarity**, **conventions**.\nLabel each finding a demonstrated defect, a policy deviation, or a\nsuggestion; block a merge only on the first two.\n\n**MUST checklist**\n\n- [ ] No credential, token or sensitive value appears in a committed file\n- [ ] Every failure path is handled; no silent catch, no swallowed\n exception\n- [ ] Every new dependency carries a licence the project's policy allows\n- [ ] Significant logic and architectural decisions are documented\n- [ ] Existing documentation matches the code after the change\n- [ ] Every changed section was re-read whole, not only the changed line\n- [ ] Every claim changed text makes about itself (a count, \"all\") was\n checked by counting with a tool\n- [ ] Input from outside the process is validated as untrusted before it\n is destructured, indexed or used as a key\n- [ ] A refactor preserves behaviour on every path \u2014 each case, direction\n and mode, including null handling, sort order and boundary values\n\n**SHOULD checklist**\n\n- [ ] Each non-trivial function has a unit test per relevant variant\n- [ ] Coverage does not fall\n- [ ] Lint errors and warnings do not rise\n- [ ] Each third-party dependency is necessary, understood and maintained\n- [ ] No new abstraction without two call sites, and no new dependency\n without a documented reason\n\n- Produce a plan before implementing a feature or a non-trivial change:\n the files touched, the signatures or outline, the edge cases, the\n assumptions. Never write implementation code before the plan is\n approved. Skip the plan for one-line fixes, typos and fully-specified\n requests.\n- Label a finding unverified until it is demonstrated. Reproduce a defect\n by running the path before reporting it; read a passing test that\n contradicts the reproduction before blaming the code.\n- Explain a deviation from a SHOULD rule in the pull request. Land a\n deviation from a MUST or MUST NOT rule only with a designated\n approver's sign-off and its reason recorded in the pull request. Never\n waive a MUST rule without that sign-off.\n\n## 8. Session protocol\n\n- At the start of a session, inspect the working tree and index, and read\n this file before making any change.\n- While working, follow sections 2 through 7 for every change.\n- Before ending a session, read the MUST and SHOULD checklists in section\n 7 and execute each item in sequence, in full \u2014 do not summarize or skip\n any of them.\n\n## 9. Governance\n\n- **Who approves a change?** Open for the project to decide.\n- **How is work tracked?** Open for the project to decide.\n- **What is a release?** Open for the project to decide.", - "ttft_ms": 345832, - "type": "result", - "duration_ms": 428384, - "uuid": "6cbb0a75-a65c-4632-b129-7400d9ad854c", - "ttft_stream_ms": 2771, - "time_to_request_ms": 482, - "first_content_frame_ms": 2772, - "queued_turn_count": 0, - "result_index": 0, - "credential_expires_at": "2026-12-11T13:29:52.387Z" - }, - "budget": null, + "inline_skills": true, "output_leak": null, "named_tooling": [], "outcome": "generated", - "output": "C:\\Work\\products\\solid-ai\\solid-ai-benchmark-regen\\tests\\efficacy\\arms\\inline\\CLAUDE.md", - "output_lines": 481, - "output_words": 4236 + "output": "C:\\Work\\products\\solid-ai\\solid-ai-benchmark\\tests\\efficacy\\arms\\inline\\CLAUDE.md", + "output_lines": 1778, + "output_words": 11990 } \ No newline at end of file diff --git a/tests/efficacy/arms/skills/CLAUDE.md b/tests/efficacy/arms/skills/CLAUDE.md index a1fc42c..c757b7f 100644 --- a/tests/efficacy/arms/skills/CLAUDE.md +++ b/tests/efficacy/arms/skills/CLAUDE.md @@ -1,6 +1,22 @@ # tariff -A pricing and invoicing web application: a product catalog, discount rules, tax jurisdictions, customers and invoices. +`tariff` — Imbra Ltd — a pricing and invoicing web application: +a product catalog, discount rules of several kinds, tax jurisdictions, +customers, and invoices assembled from them — Python 3.12 / Flask 3 / +Jinja / HTMX / SQLite — runs locally, no deployment target + +Personal data: customers are people, stored with their name, email and +postal address and named on the invoices billed to them. The business is +in the EU, so the GDPR applies: a customer may ask for their data to be +erased or for a copy of it. One administrator signs in to use the +application; nobody else has an account. + +Boundaries and actors: two actors, the administrator working in a browser +and another program; the pricing engine is a library the program imports +without the web application present, and the web application is one +caller of it. The store is a local file. Nothing reaches the network. +The program's interfaces are the library's own API and the invoice +exports. - Model: root and skills - Owner: Imbra Ltd diff --git a/tests/efficacy/arms/skills/generation.json b/tests/efficacy/arms/skills/generation.json index 43c653f..4d46e4a 100644 --- a/tests/efficacy/arms/skills/generation.json +++ b/tests/efficacy/arms/skills/generation.json @@ -1,7 +1,6 @@ { "arm": "skills", "kind": "emit", - "output_model": null, "ref": "9abed019", "source": { "remote": "https://github.com/solid-ai-dev/solid-ai-templates.git", @@ -16,7 +15,7 @@ "base-security", "base-data-governance" ], - "started_at": "2026-11-13T14:45:06", + "started_at": "2026-11-15T11:26:57", "commit": "9abed01916b941d9ed2f8daa8ff8c3b28f0718fd", "resolved_files": [ "templates/core/quality.md", @@ -39,8 +38,9 @@ "templates/security/security.md#CORS", "templates/backend/auth.md#API keys (service-to-service)" ], - "budget": null, + "inline_skills": false, "output_leak": null, + "named_tooling": [], "skills": { "add-check": 256, "add-dependency": 38, @@ -56,7 +56,7 @@ "write-tests": 186 }, "outcome": "generated", - "output": "C:\\Work\\products\\solid-ai\\solid-ai-benchmark-regen\\tests\\efficacy\\arms\\skills\\CLAUDE.md", - "output_lines": 1370, - "output_words": 9448 + "output": "C:\\Work\\products\\solid-ai\\solid-ai-benchmark\\tests\\efficacy\\arms\\skills\\CLAUDE.md", + "output_lines": 1386, + "output_words": 9596 } \ No newline at end of file diff --git a/tests/efficacy/generate_arm.py b/tests/efficacy/generate_arm.py index b8b8d27..55747bf 100644 --- a/tests/efficacy/generate_arm.py +++ b/tests/efficacy/generate_arm.py @@ -1,27 +1,24 @@ -"""Generate one round-5 arm's context file, once, with nobody answering. +"""Build one arm's context file from one chain of the templates, by script. -Every round-5 arm is made from one chain of the templates at one commit, so -the arms differ only in how they deliver it. This module makes them: +Every arm is made from one chain of the templates at one commit, so the arms +differ only in how they deliver it, and no model writes any of them: - `reference` is fixed text naming each template of the chain -- `inline` and `hybrid` are one non-interactive generation each, following - `templates/core/agents.md` with no interview -- `short` is the same generation in the inline model, held to 40 lines of - 88 characters -- `skills` is what `resolve_chain.py --emit` builds, the facts filled from - the brief +- `inline` is what `resolve_chain.py --emit --inline-skills` builds: one root + file holding every adopted rule, the facts filled from the brief +- `skills` is what `resolve_chain.py --emit` builds: the root file and one + skill per kind of task, the facts filled from the brief - `lazyref` and `lazyskills` are fixed text too: a map from the topics the manifest gives each template of the chain to that template, read as a file or loaded as a skill the first time the work touches one of them, and for `lazyskills` one skill per template, holding it verbatim It writes `arms//CLAUDE.md` (and, for an arm with skills, the skills -beside it), and refuses to keep a result the specification leaked into, or -one over its arm's budget. +beside it), and refuses to keep a result the specification leaked into. -Run it once per arm. Re-running it produces a different file and therefore -a different arm, so it refuses to overwrite an existing one without -`--replace`, and the record it writes is what the report cites. +The same ref gives the same bytes, so the self-test rebuilds every committed +arm and fails on any difference. It still refuses to overwrite an existing +file without `--replace`, since a new ref is a new arm. """ import argparse @@ -35,14 +32,11 @@ import sys import tempfile import textwrap -import time from harness import (ROUND5_DECLINED, ROUND5_REF, # noqa: E402 ROUND5_ROOTS, TEMPLATES_ENV, VENDORED, TrialError, source_record, - templates_root, agent_environment, agent_executable, - assert_authenticated, assert_outside_repository, - prepare_home, read_input) + templates_root, assert_outside_repository, read_input) HERE = os.path.dirname(os.path.abspath(__file__)) @@ -51,18 +45,14 @@ BRIEF = os.path.join(HERE, "brief.txt") # The arms this module makes, each with the directory under `arms/` its file -# and record live in, and how it is made: fixed text, a model generation in -# one of `agents.md`'s models, the emitter, or a map of the chain's topics -# read as files or loaded as skills, and a model arm's budget as (lines, -# width) where it has one. `hand` is a person's file, kept verbatim with no -# record, so it is not made here. +# and record live in, and how it is made: fixed text, the templates' emitter +# with its skills apart or inlined, or a map of the chain's topics read as +# files or loaded as skills. An arm a model or a person writes would change +# with every writing, so none is made here. GENERATED = { "reference": {"dir": "reference", "kind": "fixed"}, - "inline": {"dir": "inline", "kind": "model", "model": "inline"}, - "hybrid": {"dir": "hybrid", "kind": "model", "model": "hybrid"}, - "skills": {"dir": "skills", "kind": "emit"}, - "short": {"dir": "short", "kind": "model", "model": "inline", - "budget": (40, 88)}, + "inline": {"dir": "inline", "kind": "emit", "inline_skills": True}, + "skills": {"dir": "skills", "kind": "emit", "inline_skills": False}, "lazyref": {"dir": "lazyref", "kind": "map", "load": "read"}, "lazyskills": {"dir": "lazyskills", "kind": "map", "load": "skill"}, } @@ -86,29 +76,10 @@ def record_path(arm): "generation.json") -# Two lists, because the prompt and the output are different questions. -# -# The PROMPT scan is a wiring check: a generation is never handed -# `SPEC.md`, so any of these appearing in the prompt means the plumbing is -# wrong. It can afford to be broad, since a false positive costs a look -# rather than a generation. -PROMPT_TOKENS = [ - "half-even", "ROUND_HALF_EVEN", "n-for-m", - "WID-1", "GAD-2", "BOK-3", "SRV-4", "SEE-5", - "r-tier-wid", "r-bulk-see", "r-pct-bok", "r-pct-all", - "c-welcome", "c-tenoff", "WELCOME", "TENOFF", - "PricedInvoice", "TariffError", - "/invoices/preview", "/invoices/new", "export.csv", "export.json", - "228.35", "227.07", "195.24", "0.135", - "TARIFF_ADMIN_PASSWORD", "/sign-in", "/sign-out", - "Ada Example", "ada@example.com", -] - -# The OUTPUT scan asks something narrower, and the prompt scan is what -# earns it: once the prompt is clean, the model demonstrably never read the -# specification, so anything specification-shaped in the output was -# *inferred*. Only arbitrary data can survive that argument — a seed sku, a -# rule id, a figure from the worked example. Nothing derives those. +# The output scan. No arm is handed `SPEC.md`, so only arbitrary data the +# specification alone supplies counts as a leak: a seed sku, a rule id, a +# figure from the worked example. A name the templates' own rules imply, +# such as an error base called after the package, is no leak. NON_INVENTABLE = [ "WID-1", "GAD-2", "BOK-3", "SRV-4", "SEE-5", "r-tier-wid", "r-bulk-see", "r-pct-bok", "r-pct-all", @@ -117,70 +88,6 @@ def record_path(arm): "Ada Example", "ada@example.com", ] -# Two tokens taught this the hard way. -# -# `HX-Request` came off the prompt list: the templates document the header -# themselves, as any HTMX guidance would, so the scan fired on a clean -# prompt. `/customers/` came off it the same way, from the templates' REST -# rule, whose example nests `/customers/{id}/orders`. Every other token was then checked the same way against the chain -# at the release and appears nowhere in it. -# -# `TariffError` came off the *output* list on the first real generation. The -# prompt had already scanned clean, so the model could not have read it — -# it named the error base after the package, which is exactly what the -# templates' one-hierarchy rule asks of a package called `tariff`. The -# specification chose the same name for the same reason. `PricedInvoice`, -# the routes, the coupon codes and `half-even` are all derivable the same -# way and stay out of the output list for the same reason. - -INSTRUCTION = """\ -You generate one project's `CLAUDE.md` from the solid-ai-templates, with no -person to answer questions. - -Follow `templates/core/agents.md`, given in full below, for what the file -holds and how it is written. The project brief below is the whole of what -the project has said about itself. Adopt every rule of the chain below that -applies to the project the brief describes, and leave out every rule that -does not. Where the brief does not settle something, choose what the rules -already imply and move on; do not ask. - -The brief names no tools, and the project has chosen none. Where a rule asks -for a type checker, a linter, a formatter, a test runner or a package -manager, or a template shows a command as a placeholder, say what the check -must do and name no tool and no command: that choice is the project's. - -Output the finished `CLAUDE.md` and nothing else: no preamble, no -explanation, no code fence around the whole document. - -%s -## Project brief - -%s - -## templates/core/agents.md - -%s - -## The rules this project's chain resolves - -%s -""" - -# What each output model's clause tells the generation. The hybrid clause -# names where the templates sit in the workspace, because the harness -# vendors them there rather than adding a submodule, and a file telling its -# reader to add one would be wrong from its first line. -MODELS = { - "inline": "Use the inline model of `agents.md`.", - "hybrid": ("Use the hybrid model of `agents.md`. The templates are " - "present in the project at `%s/%s/`, the repository's `%s/` " - "directory at the same revision as the rules below, as a " - "vendored copy rather than a submodule: point there, list the " - "template files to read by their paths under it, and do not " - "tell anyone to add a submodule." - % (VENDORED["into"], VENDORED["path"], VENDORED["path"])), -} - # The `reference` arm's whole file: the brief, then the chain named, no rule # copied in. Every arm's root states the same project facts, so the arms # differ in how they hand over the rules and in nothing the project says of @@ -199,12 +106,11 @@ def record_path(arm): # The facts the emitted root file leaves as slots, each filled from the # brief and nothing else. A slot the brief does not settle says so rather -# than inventing an answer. +# than inventing an answer. The description slot, under the title, takes +# the brief whole, so an emitted root opens as every other arm's does. +BRIEF_SLOT = "{{one-sentence description}}" FACTS = { "{{project-name}}": "tariff", - "{{one-sentence description}}": - "A pricing and invoicing web application: a product catalog, " - "discount rules, tax jurisdictions, customers and invoices.", "{{owner}}": "Imbra Ltd", "{{repository}}": "this repository", "{{the commands to build, test and run the project}}": @@ -217,37 +123,11 @@ def record_path(arm): SLOT = re.compile(r"\{\{[^}]+\}\}") -# The budget clause. The width keeps a line from carrying a paragraph. The -# closing check adds no content; it asks the model to hold a bound it is -# already given, since a file over it is refused whole. -BUDGET = """\ -The finished `CLAUDE.md` MUST be at most {lines} lines, blank lines counted, -and no line may be longer than {width} characters. Keep the rules that matter -most for this project and leave the rest out; a rule that does not fit is left -out, not squeezed onto another rule's line. - -Before you answer, measure every line against {width} characters and shorten -or split each one over it, then count the lines again. A file over either -bound is refused whole, never trimmed.""" - - -def arm_clause(arm): - """The model and budget paragraphs for one model arm's instruction.""" - entry = GENERATED[arm] - lines = ["## The output model", "", MODELS[entry["model"]]] - if entry.get("budget"): - count, width = entry["budget"] - lines.extend(["", "## The budget", "", - BUDGET.format(lines=count, width=width)]) - return "\n".join(lines) + "\n" - - # The tools a Python project most often chooses. Neither the brief nor the -# templates name one, so a generated file that does invented it, and an arm -# told a tool gets checks the other arms were never told to run. The list is -# a guard against the common case, not a proof: a rarer tool is caught by -# reading the generated file, which is committed and reviewed. It can afford -# to be broad, since a false positive costs one more generation. +# templates name one, so a built file that does carries a tool the chain +# took in, and an arm told a tool gets checks the other arms were never told +# to run. The list is a guard against the common case, not a proof: a rarer +# tool is caught by reading the built file, which is committed and reviewed. TOOLING = re.compile(r"\b(mypy|pyright|ruff|flake8|pylint|black|isort|" r"pytest|tox|nox|bandit|uv|pip|pipenv|poetry|hatch)\b", re.IGNORECASE) @@ -260,23 +140,6 @@ def named_tooling(texts): for match in TOOLING.findall(text)}) -def over_budget(document, budget): - """Every way a file exceeds its (lines, width) budget, as sentences; - empty where it fits or has no budget.""" - if not budget: - return [] - lines, width = budget - text = document.rstrip("\n").split("\n") - findings = [] - if len(text) > lines: - findings.append("%d lines, over the budget of %d" % (len(text), lines)) - widest = max((len(line) for line in text), default=0) - if widest > width: - findings.append("a line of %d characters, over the width of %d" - % (widest, width)) - return findings - - def read_brief(path=BRIEF): """The pinned brief, read from its only copy. @@ -336,18 +199,6 @@ def resolve_union(tree, roots): return union -def read_chain(tree, files): - """Concatenate the resolved templates, each under its own path.""" - parts = [] - for name in files: - path = os.path.join(tree, name) - if not os.path.exists(path): - raise TrialError("resolved file %s is not in the tree" % name) - with io.open(path, encoding="utf-8") as handle: - parts.append("\n%s" % (name, handle.read())) - return "\n\n".join(parts) - - def scan(text, label, tokens): """Every listed token this text carries, or None if it carries none.""" hits = {token: text.count(token) for token in tokens if token in text} @@ -356,15 +207,6 @@ def scan(text, label, tokens): return {"where": label, "hits": hits} -def build_prompt(tree, arm, files): - """The model arm's prompt: its model, the brief, agents.md, the chain.""" - with io.open(os.path.join(tree, "templates", "core", "agents.md"), - encoding="utf-8") as handle: - agents = handle.read() - return INSTRUCTION % (arm_clause(arm), read_brief(), agents, - read_chain(tree, files)) - - def reference_text(files, brief): """The `reference` arm's file for a chain and a brief, the same for the same two.""" @@ -492,8 +334,10 @@ def template_skills(tree, rows): return skills -def fill_facts(text): - """The emitted root file with every fact slot filled from the brief.""" +def fill_facts(text, brief): + """The emitted root file with every fact slot filled from the brief, the + description slot with the brief itself.""" + text = text.replace(BRIEF_SLOT, brief.strip()) for slot, value in FACTS.items(): text = text.replace(slot, value) left = SLOT.findall(text) @@ -503,9 +347,10 @@ def fill_facts(text): return text -def emit_arm(tree, roots): - """The `skills` arm, built by the templates' emitter: the root file with - its facts filled, and {kind: SKILL.md text}.""" +def emit_arm(tree, roots, brief, inline_skills): + """An arm the templates' emitter builds: the root file with its facts + filled, and {kind: SKILL.md text}, empty where the skills are inlined + into the root.""" out = tempfile.mkdtemp(prefix="efficacy-emit-") declined = os.path.join(out, "declined.txt") with io.open(declined, "w", encoding="utf-8", newline="\n") as handle: @@ -513,14 +358,15 @@ def emit_arm(tree, roots): try: proc = subprocess.run( [sys.executable, "tools/resolve_chain.py", "--emit", - os.path.join(out, "emitted"), "--declined", declined] + roots, + os.path.join(out, "emitted"), "--declined", declined] + + (["--inline-skills"] if inline_skills else []) + roots, cwd=tree, capture_output=True, text=True, encoding="utf-8") if proc.returncode != 0: raise TrialError("the emitter failed: %s" % (proc.stdout + proc.stderr).strip()) with io.open(os.path.join(out, "emitted", "AGENTS.md"), encoding="utf-8") as h: - root = fill_facts(h.read()) + root = fill_facts(h.read(), brief) skills = {} base = os.path.join(out, "emitted", ".agents", "skills") for kind in sorted(os.listdir(base)) if os.path.isdir(base) else []: @@ -532,44 +378,67 @@ def emit_arm(tree, roots): shutil.rmtree(out, ignore_errors=True) -def agent_command(home, model, effort, budget): - """The generator invocation: isolated, offline, non-interactive.""" - argv = [ - agent_executable(), "-p", - "--output-format", "json", - "--model", model, - "--effort", effort, - "--permission-mode", "bypassPermissions", - "--setting-sources", "", - "--settings", os.path.join(home, "settings.json"), - "--strict-mcp-config", - "--disallowed-tools", "WebSearch", "WebFetch", - ] - if budget is not None: - argv.extend(["--max-budget-usd", str(budget)]) - return argv - - -def extract_document(payload, raw): - """The generated file, from the CLI's JSON envelope or its raw output.""" - if isinstance(payload, dict): - for key in ("result", "text", "content"): - value = payload.get(key) - if isinstance(value, str) and value.strip(): - return value.strip() - return raw.strip() +def build_arm(arm, ref, brief): + """One arm's files at a templates ref: (document, {kind: SKILL.md text}, + what the record says of how they were built). The same arm, ref and + brief always give the same files.""" + entry = GENERATED[arm] + tree = worktree_at(ref) + try: + files = resolve_union(tree, ROUND5_ROOTS) + details = {"commit": subprocess.run( + ["git", "-C", tree, "rev-parse", "HEAD"], capture_output=True, + text=True, encoding="utf-8").stdout.strip(), + "resolved_files": files} + skills = {} + if entry["kind"] == "fixed": + document = reference_text(files, brief) + elif entry["kind"] == "emit": + document, skills = emit_arm(tree, ROUND5_ROOTS, brief, + entry["inline_skills"]) + details["declined"] = ROUND5_DECLINED + details["inline_skills"] = entry["inline_skills"] + else: + rows = moments(tree, files) + document = map_text(rows, entry["load"], brief) + if entry["load"] == "skill": + skills = template_skills(tree, rows) + details["load"] = entry["load"] + details["moments"] = [{"skill": kind, "moment": description, + "file": name} + for kind, description, name in rows] + finally: + remove_worktree(tree) + return document.rstrip() + "\n", skills, details + + +def committed_arm(arm): + """An arm's committed files: (document, {kind: SKILL.md text}), or None + where the arm has no committed file.""" + path = output_path(arm) + if not os.path.isfile(path): + return None + with io.open(path, encoding="utf-8", newline="") as handle: + document = handle.read() + skills = {} + base = skills_path(arm) + for kind in sorted(os.listdir(base)) if os.path.isdir(base) else []: + with io.open(os.path.join(base, kind, "SKILL.md"), encoding="utf-8", + newline="") as handle: + skills[kind] = handle.read() + return document, skills def parse_args(argv): parser = argparse.ArgumentParser( - description="Generate one round-5 arm's context file.") + description="Build one arm's context file from the templates.") parser.add_argument("--arm", choices=sorted(GENERATED), - help="the arm to generate; required for everything " + help="the arm to build; required for everything " "but --self-test") parser.add_argument("--root", - help="scratch directory for the isolated home and the " - "record; MUST be outside this repository. " - "Required for everything but --self-test") + help="scratch directory for the record; MUST be " + "outside this repository. Required for " + "everything but --self-test") parser.add_argument("--ref", default=ROUND5_REF, help="the templates commit to resolve the chain at " "(default %s, the registered one)" % ROUND5_REF) @@ -577,39 +446,37 @@ def parse_args(argv): help="a git clone of the templates repository, " "upstream or a fork; overrides %s" % TEMPLATES_ENV) - parser.add_argument("--model", default="claude-sonnet-5") - parser.add_argument("--effort", default="high") - parser.add_argument("--budget", type=float, default=None) - parser.add_argument("--timeout", type=int, default=3600) parser.add_argument("--replace", action="store_true", help="overwrite the arm's existing file; the arm " "changes when you do") parser.add_argument("--dry-run", action="store_true", - help="build and scan the prompt, call no model") + help="build and scan the files, write nothing under " + "arms/") parser.add_argument("--self-test", action="store_true", help="prove the scans, the fixed text and the facts " - "can fail, then exit") + "can fail, rebuild every committed arm, then " + "exit") return parser.parse_args(argv) def self_test(): """A scan that cannot fail is not a control, and neither is a fill or a - budget. + build said to be the same twice. Plants a specification-only token and requires the scan to report it, and a clean text to scan clean. Requires the reference text to name every file under the vendored path and to be the same twice. Requires a fact slot the brief does not fill to be refused, and every known slot - filled. Requires a file one line over the budget, and one a character - too wide, refused, and a file at both bounds kept. + filled. Rebuilds every committed arm at its recorded ref and requires + the same bytes, and requires every root to open with the brief. """ clean = "A pricing and invoicing web application with discount rules." - if scan(clean, "clean", PROMPT_TOKENS) is not None: + if scan(clean, "clean", NON_INVENTABLE) is not None: print("FAIL: the scan fired on text carrying no specification token") return 1 - planted = clean + " Rounding is half-even to two places." - found = scan(planted, "planted", PROMPT_TOKENS) - if found is None or "half-even" not in found["hits"]: + planted = clean + " The seed product WID-1 costs 228.35." + found = scan(planted, "planted", NON_INVENTABLE) + if found is None or "WID-1" not in found["hits"]: print("FAIL: the scan missed a planted specification token") return 1 print("the leak scan reports a planted token and passes clean text") @@ -617,7 +484,8 @@ def self_test(): # The brief and the emitter's facts name the stack the spec fixes and no # tooling: a tool the project chose would reach only the arms that copy # it, and the arms would then differ in what they were told. - told = [read_brief()] + list(FACTS.values()) + brief = read_brief() + told = [brief] + list(FACTS.values()) named = named_tooling(told) if named or "Python 3.12" not in told[0]: print("FAIL: the brief or the facts name tooling, or drop the " @@ -625,8 +493,8 @@ def self_test(): return 1 print("the brief and the facts name the stack and no tooling") - # A model arm may still fill a template's command placeholder with a - # tool of its own choosing; such a file is refused. + # A chain that took in a tool's name would hand it to the arms that + # copy the chain's text; such a file is refused. if (named_tooling(["Run `mypy --strict .` and `uv run pytest`."]) != ["mypy", "pytest", "uv"] or named_tooling(["Use Ruff for linting and Pyright for types."]) @@ -634,13 +502,11 @@ def self_test(): or named_tooling(["Run black --check . and isort --check ."]) != ["black", "isort"] or named_tooling(["Type-check at the strictest setting; " - "lint and format clean."]) - or "name no tool and no command" not in INSTRUCTION): - print("FAIL: a generated file naming a tool is not caught, a clean " - "one is, or the prompt does not forbid naming tools") + "lint and format clean."])): + print("FAIL: a built file naming a tool is not caught, or a clean " + "one is") return 1 - print("a generated file naming a tool is refused, and the prompt forbids " - "one") + print("a built file naming a tool is refused") files = ["templates/core/quality.md", "templates/backend/api.md"] planted_brief = "`tariff` - a planted brief - Python 3.12 / Flask 3\n" @@ -680,15 +546,18 @@ def self_test(): reading = map_text(rows, "read", planted_brief) loading = map_text(rows, "skill", planted_brief) - # Every root the generator builds from fixed text states the same - # project facts as the model arms are given: the brief, verbatim, - # under the title and before any rule. + # Every root the generator builds states the same project facts: + # the brief, verbatim, under the title and before any rule. The + # emitter's own head is filled the same way. opening = "# tariff\n\n%s\n" % planted_brief.strip() + emitted = fill_facts("# {{project-name}}\n\n%s\n\n- Owner: {{owner}}\n" + % BRIEF_SLOT, planted_brief) if not all(root.startswith(opening) - for root in (text, reading, loading)): - print("FAIL: a fixed-text root does not open with the brief") + for root in (text, reading, loading, emitted)): + print("FAIL: a built root does not open with the brief") return 1 - print("every fixed-text root opens with the brief, verbatim") + print("every built root opens with the brief, verbatim, the " + "emitted ones too") first = [line.split(" | ")[0] for line in reading.splitlines() if line.startswith("| ") and not line.startswith("| ---")] second = [line.split(" | ")[0] for line in loading.splitlines() @@ -730,57 +599,58 @@ def self_test(): finally: shutil.rmtree(tree, ignore_errors=True) - known = " ".join(FACTS) - if SLOT.search(fill_facts(known)): + known = " ".join([BRIEF_SLOT] + list(FACTS)) + if SLOT.search(fill_facts(known, planted_brief)): print("FAIL: a known fact slot was left unfilled") return 1 try: - fill_facts(known + " {{unknown}}") + fill_facts(known + " {{unknown}}", planted_brief) print("FAIL: a slot the brief does not fill was kept") return 1 except TrialError: pass print("every known fact slot is filled, and an unknown one is refused") - budget = GENERATED["short"]["budget"] - lines, width = budget - at_bounds = "\n".join(["x" * width] * lines) + "\n" - if over_budget(at_bounds, budget): - print("FAIL: a file at both bounds was refused") - return 1 - long = "\n".join(["x"] * (lines + 1)) + "\n" - wide = "\n".join(["x" * (width + 1)] + ["x"] * (lines - 1)) + "\n" - if not over_budget(long, budget) or not over_budget(wide, budget): - print("FAIL: a file over the budget was kept") - return 1 - if over_budget(long, None): - print("FAIL: an arm with no budget refused a file") - return 1 - print("the budget keeps a file at %d lines of %d characters and refuses " - "one over either" % (lines, width)) - if "MUST be at most %d lines" % lines not in arm_clause("short") \ - or "measure every line against %d" % width \ - not in arm_clause("short") \ - or "budget" in arm_clause("inline").lower(): - print("FAIL: the budget clause is not in short's instruction alone") - return 1 - print("the budget is stated in short's instruction and no other") - - # A generated file without its record cannot say which source, model and - # ref made it, so the report could not cite how its arm was built. + # A file without its record cannot say which source and ref made it, so + # the report could not cite how its arm was built. + records = {} for arm in GENERATED: - path = record_path(arm) - if not os.path.isfile(output_path(arm)): + if committed_arm(arm) is None: continue try: - with io.open(path, encoding="utf-8") as handle: - record = json.load(handle) + with io.open(record_path(arm), encoding="utf-8") as handle: + records[arm] = json.load(handle) except (OSError, ValueError): - record = {} - if record.get("arm") != arm or record.get("outcome") != "generated": + records[arm] = {} + if records[arm].get("arm") != arm \ + or records[arm].get("outcome") != "generated": print("FAIL: %s has no generation record beside it" % arm) return 1 - print("every generated arm's file has its generation record beside it") + print("every built arm's file has its generation record beside it") + + # The committed files are what the script builds now at their recorded + # ref, byte for byte: a hand edit, or a build that varies, fails here. + # The first arm is built twice, so a build that varies from one run to + # the next fails even where nothing is committed yet. + for index, arm in enumerate(sorted(records)): + ref = records[arm].get("ref") + built = build_arm(arm, ref, brief) + if index == 0 and build_arm(arm, ref, brief) != built: + print("FAIL: %s built twice at %s gave different files" + % (arm, ref)) + return 1 + document, skills = committed_arm(arm) + if (document, skills) != built[:2]: + print("FAIL: %s's committed files are not what the script builds " + "at %s" % (arm, ref)) + return 1 + if not document.startswith("# tariff\n\n%s\n" % brief.strip()): + print("FAIL: %s's committed root does not open with the brief" + % arm) + return 1 + print("every committed arm is what the script builds at its recorded " + "ref, byte for byte, the same twice") + print("every committed arm's root opens with the brief, verbatim") return 0 @@ -804,78 +674,37 @@ def main(argv): arm, entry = options.arm, GENERATED[options.arm] output = output_path(arm) if os.path.exists(output) and not options.replace: - print("refused: %s already exists. An arm is generated once; " - "regenerating changes the arm. Pass --replace if that is what " - "you mean." % output) + print("refused: %s already exists. An arm is built once per ref; " + "a new ref is a new arm. Pass --replace if that is what you " + "mean." % output) return 1 os.makedirs(options.root, exist_ok=True) started_at = datetime.datetime.now() - record = {"arm": arm, "kind": entry["kind"], - "output_model": entry.get("model"), "ref": options.ref, + record = {"arm": arm, "kind": entry["kind"], "ref": options.ref, "source": source_record(options.ref), "roots": ROUND5_ROOTS, "started_at": started_at.isoformat(timespec="seconds")} - tree = worktree_at(options.ref) - try: - files = resolve_union(tree, ROUND5_ROOTS) - record["commit"] = subprocess.run( - ["git", "-C", tree, "rev-parse", "HEAD"], capture_output=True, - text=True, encoding="utf-8").stdout.strip() - record["resolved_files"] = files - skills = {} - if entry["kind"] == "fixed": - document = reference_text(files, read_brief()) - elif entry["kind"] == "emit": - document, skills = emit_arm(tree, ROUND5_ROOTS) - record["declined"] = ROUND5_DECLINED - elif entry["kind"] == "map": - rows = moments(tree, files) - document = map_text(rows, entry["load"], read_brief()) - if entry["load"] == "skill": - skills = template_skills(tree, rows) - record["load"] = entry["load"] - record["moments"] = [{"skill": kind, "moment": description, - "file": name} - for kind, description, name in rows] - else: - prompt = build_prompt(tree, arm, files) - finally: - remove_worktree(tree) + document, skills, details = build_arm(arm, options.ref, read_brief()) + record.update(details) print("chain at %s (%s): %d unique files" - % (options.ref, record["commit"][:8], len(files))) - - if entry["kind"] == "model": - document = generate(options, record, prompt, started_at) - if document is None: - write_record(options.root, record, started_at) - return 0 if record.get("outcome") == "dry-run" else 1 - - # A file over its budget is refused whole rather than trimmed, since - # trimming would put a person's judgement into the arm. - record["budget"] = entry.get("budget") - over = over_budget(document, entry.get("budget")) - if over: - record["outcome"] = "refused: over budget" - record["over_budget"] = over - print("refused: the generated file is over its budget: %s" - % "; ".join(over)) - return write_record(options.root, record, started_at) or 1 + % (options.ref, record["commit"][:8], + len(record["resolved_files"]))) texts = [document] + list(skills.values()) - leak = scan("\n".join(texts), "generated files", NON_INVENTABLE) + leak = scan("\n".join(texts), "built files", NON_INVENTABLE) record["output_leak"] = leak if leak is not None: record["outcome"] = "refused: specification leaked" - print("refused: the generated files carry data only the " - "specification supplies: %r" % leak["hits"]) + print("refused: the built files carry data only the specification " + "supplies: %r" % leak["hits"]) return write_record(options.root, record, started_at) or 1 tools = named_tooling(texts) record["named_tooling"] = tools if tools: record["outcome"] = "refused: names tooling" - print("refused: the generated files name tools the brief does not: " - "%s" % ", ".join(tools)) + print("refused: the built files name tools the brief does not: %s" + % ", ".join(tools)) return write_record(options.root, record, started_at) or 1 # A dry run of any arm stops here: it writes nothing under `arms/`, @@ -889,14 +718,14 @@ def main(argv): os.makedirs(os.path.dirname(output), exist_ok=True) with io.open(output, "w", encoding="utf-8", newline="\n") as handle: - handle.write(document.rstrip() + "\n") + handle.write(document) + shutil.rmtree(skills_path(arm), ignore_errors=True) + for kind, text in skills.items(): + path = os.path.join(skills_path(arm), kind, "SKILL.md") + os.makedirs(os.path.dirname(path), exist_ok=True) + with io.open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(text) if skills: - shutil.rmtree(skills_path(arm), ignore_errors=True) - for kind, text in skills.items(): - path = os.path.join(skills_path(arm), kind, "SKILL.md") - os.makedirs(os.path.dirname(path), exist_ok=True) - with io.open(path, "w", encoding="utf-8", newline="\n") as handle: - handle.write(text) record["skills"] = {kind: len(text.split()) for kind, text in skills.items()} record["outcome"] = "generated" @@ -911,63 +740,6 @@ def main(argv): return write_record(options.root, record, started_at) -def generate(options, record, prompt, started_at): - """Run the model generation; the document, or None with the record - saying why not.""" - record["prompt_chars"] = len(prompt) - leak = scan(prompt, "prompt", PROMPT_TOKENS) - record["prompt_leak"] = leak - if leak is not None: - record["outcome"] = "refused: prompt leak" - print("refused: the prompt carries specification-only tokens, so the " - "wiring is wrong: %r" % leak["hits"]) - return None - prompt_path = os.path.join(options.root, "arm-%s-prompt.txt" % options.arm) - with io.open(prompt_path, "w", encoding="utf-8", newline="\n") as handle: - handle.write(prompt) - record["prompt_file"] = prompt_path - if options.dry_run: - record["outcome"] = "dry-run" - print("dry run: prompt written to %s, no model called" % prompt_path) - return None - - home = prepare_home(options.root) - try: - record["auth_probe"] = assert_authenticated( - home, agent_environment, agent_executable()) - except TrialError as error: - record["outcome"] = "refused: not authenticated" - print("refused: %s" % error) - return None - argv_ = agent_command(home, options.model, options.effort, options.budget) - record.update({"command": argv_, "model": options.model, - "effort": options.effort}) - started = time.monotonic() - try: - proc = subprocess.run(argv_, input=prompt, cwd=options.root, - env=agent_environment(home), - capture_output=True, text=True, - encoding="utf-8", timeout=options.timeout) - except subprocess.TimeoutExpired: - record["outcome"] = "timeout" - print("the generator did not finish within %ds" % options.timeout) - return None - record["elapsed_s"] = round(time.monotonic() - started, 1) - record["exit_status"] = proc.returncode - try: - payload = json.loads(proc.stdout) - except ValueError: - payload = None - record["result"] = payload if isinstance(payload, dict) else None - document = extract_document(payload, proc.stdout) - if proc.returncode != 0 or not document: - record["outcome"] = "failed" - record["stderr"] = proc.stderr[-4000:] - print("the generator failed (status %s)" % proc.returncode) - return None - return document - - def keep_record(record, path): """Write the record of the generation behind the committed file.""" with io.open(path, "w", encoding="utf-8") as handle: diff --git a/tests/efficacy/harness.py b/tests/efficacy/harness.py index 58003ec..5949730 100644 --- a/tests/efficacy/harness.py +++ b/tests/efficacy/harness.py @@ -137,11 +137,11 @@ SKILLS_INTO = ".claude/skills" # The arms, each a word, and the context file each starts with, relative to -# `arms/`. Arm `none` carries no file: it is the bare agent. `hand` is a -# person's file, kept verbatim. `inline`, `reference` and `skills` are round -# 5's; `hybrid` was regenerated for it, and an arm's vendored ref comes from -# its generation record. `short` was made again from round 5's chain, under a -# 40-line budget. +# `arms/`. Arm `none` carries no file: it is the bare agent. An arm's +# vendored ref comes from its generation record. `generate_arm.py` builds +# every arm a round may run; `hand`, `short` and `hybrid` are the pilot +# rounds' arms, a person's file and two a model wrote, kept as they are for +# the pilot rounds' reports, and no script rebuilds them. ARMS = { "none": {"label": "no context file", "context": None}, "short": {"label": "the templates' file, inline, 40 lines", @@ -152,7 +152,7 @@ "context": "hand/CLAUDE.md"}, "reference": {"label": "the templates, named only", "context": "reference/CLAUDE.md", "vendor": VENDORED}, - "inline": {"label": "the templates' file, inline from agents.md", + "inline": {"label": "the emitted root file, every rule inline", "context": "inline/CLAUDE.md"}, "skills": {"label": "the emitted root file and task skills", "context": "skills/CLAUDE.md", "skills": "skills/skills"}, @@ -3569,12 +3569,12 @@ def round5_checks(): and spec_problem(["lazyref"], "thin", ROUND5_SPEC[1]) is not None and spec_problem(["lazyskills"], *ROUND5_SPEC) is None), ] - record = os.path.join(ARMS_DIR, "hybrid", "generation.json") + record = os.path.join(ARMS_DIR, "lazyref", "generation.json") with io.open(record, encoding="utf-8") as handle: recorded = json.load(handle).get("ref") checks.append(("a vendoring arm vendors at its recorded ref", recorded is not None - and arm_vendor("hybrid")["ref"] == recorded)) + and arm_vendor("lazyref")["ref"] == recorded)) scratch = os.path.join(tempfile.gettempdir(), "efficacy-skills-self-test") remove_tree(scratch) diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index 045337e..410d038 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -7526,9 +7526,12 @@ def row_start(arm, verdict): # `reference` reused, the judge's design score constant per arm so each # contrast's verdict is known. Every declared contrast is printed, one # column per file arm, and the reused arms and the contrasts crossing - # rounds are named. - design = {"none": 3, "inline": 3, "hybrid": 3, "reference": 4, - "skills": 4} + # rounds are named. Of the two fresh files, the longer reads better, so + # the reading holds whichever of them the arm files make the longer. + longer, shorter = sorted(("inline", "skills"), key=context_lines, + reverse=True) + design = {"none": 3, shorter: 3, "hybrid": 3, "reference": 4, + longer: 4} trials = {trial_name(arm, index): { "scores": ({"reused_from": {"name": "planted"}} if arm in ("hybrid", "reference") else {}), @@ -7563,8 +7566,8 @@ def row_start(arm, verdict): "Together: the long file added quality, the short one did not" in finding and all(row_start(arm, verdict) in finding for arm, verdict in - (("hybrid", "Not measured"), ("inline", "No"), - ("reference", "Not measured"), ("skills", "Yes"))), + (("hybrid", "Not measured"), (shorter, "No"), + ("reference", "Not measured"), (longer, "Yes"))), finding), ("a trial's repeats are meaned, and one judging means itself", judge_score({"judgings": [ From ec27aed2da3ac428abadb3104663f94663270de0 Mon Sep 17 00:00:00 2001 From: Branimir Georgiev <66906831+braboj@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:54:27 +0200 Subject: [PATCH 2/2] fix(efficacy): the pilot's written arms keep their records for the report Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DpT5xQh3AgRFs2tJwMT4g3 --- docs/coverage.md | 2 +- tests/efficacy/generate_arm.py | 9 +++++++-- tests/efficacy/report.py | 17 ++++++++++++++--- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/docs/coverage.md b/docs/coverage.md index 2d0b3d0..a06cbaa 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -185,7 +185,7 @@ when: | ID | Kind | Checked by | | -- | ---- | ---------- | | FR-13-01 | Self-test | `harness.py` "the record is written as every trial starts and ends"
`harness.py` "every trial records the CLI's version, read as it starts" | -| FR-13-02 | Self-test | `generate_arm.py` "every built arm's file has its generation record beside it" | +| FR-13-02 | Self-test | `generate_arm.py` "every built arm's file has its generation record beside it"
`report.py` "a pilot arm no script builds keeps its record for the report, and its vendored templates" | | FR-13-03 | Self-test | `archive.py` "readings, judgings, map and lock come; bundles do not"
`archive.py` "the original tarball's hash is recorded"
`archive.py` "the revisions are recorded"
`archive.py` "a reading changed in the archive fails the verify" | | FR-13-04 | Self-test | `archive.py` "a reading changed after the stamp is a problem"
`archive.py` "the report refuses docs/audits/ without a current stamp"
`report.py` "a report into a templates source's docs/audits needs the stamp" | | FR-13-05 | Self-test | `archive.py` "the restored root reads as the original does"
`archive.py` "a restored record points at the restored tarball and void"
`archive.py` "a restored transcript keeps its time" | diff --git a/tests/efficacy/generate_arm.py b/tests/efficacy/generate_arm.py index 55747bf..ba00218 100644 --- a/tests/efficacy/generate_arm.py +++ b/tests/efficacy/generate_arm.py @@ -57,6 +57,12 @@ "lazyskills": {"dir": "lazyskills", "kind": "map", "load": "skill"}, } +# Every arm with a generation record under `arms/`, by its directory: the +# arms built here, and the pilot's written arms, whose records stay so a +# pilot round's report still cites how each was made and what it vendored. +RECORDED = dict({arm: entry["dir"] for arm, entry in GENERATED.items()}, + hybrid="hybrid", short="short") + def output_path(arm): """Where an arm's generated file is committed.""" @@ -72,8 +78,7 @@ def record_path(arm): """The record of the generation behind an arm's file, committed beside it. The report cites it, and a scratch directory would not outlive the run.""" - return os.path.join(HERE, "arms", GENERATED[arm]["dir"], - "generation.json") + return os.path.join(HERE, "arms", RECORDED[arm], "generation.json") # The output scan. No arm is handed `SPEC.md`, so only arbitrary data the diff --git a/tests/efficacy/report.py b/tests/efficacy/report.py index 410d038..534214e 100644 --- a/tests/efficacy/report.py +++ b/tests/efficacy/report.py @@ -37,7 +37,7 @@ import archive # noqa: E402 import lib # noqa: E402 -from generate_arm import GENERATED, record_path # noqa: E402 +from generate_arm import RECORDED, record_path # noqa: E402 from harness import (ARMS, ARMS_DIR, PROMPT, ROUND5_ARMS, # noqa: E402 ROUND5_K, ROUND5_SPEC, ROUND5D_ARMS, ROUND5E_ARMS, SCORABLE, TEMPLATES_ENV, VENDORED, VOIDING, TrialError, @@ -1380,7 +1380,7 @@ def generation_records(): """Each generated arm's record, committed beside the file it produced, by arm; an arm whose record is absent is left out.""" records = {} - for arm in GENERATED: + for arm in RECORDED: path = record_path(arm) if os.path.exists(path): with io.open(path, encoding="utf-8") as handle: @@ -2047,7 +2047,7 @@ def provenance_lines(trials, names, arms, k, seed, generation): lines.append("| Bootstrap | %d resamples, %d%%, seed %s |" % (RESAMPLES, int(100 * CONFIDENCE), seed)) for arm in arms: - if arm not in GENERATED: + if arm not in RECORDED: continue record = generation.get(arm) if record: @@ -7522,6 +7522,17 @@ def row_start(arm, verdict): < text.find("Together:"), prose_of(text, "## Arms against `none`")), ]) + # The pilot's written arms are built no more, but their records stay, + # so a pilot report still cites how each was made and what it vendored. + pilot = generation_records() + checks.append(("a pilot arm no script builds keeps its record for the " + "report, and its vendored templates", + {"hybrid", "short"} <= set(pilot) + and mapped_templates("hybrid") + == pilot["hybrid"].get("resolved_files") + and len(mapped_templates("hybrid")) > 0, + sorted(pilot))) + # A run reusing an earlier round's trials: five arms, `hybrid` and # `reference` reused, the judge's design score constant per arm so each # contrast's verdict is known. Every declared contrast is printed, one