sisi 0.1.0: a shared rulebook and verification tool for AI coding agents
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.9) (push) Canceled after 0s

Contracts with a ladder of checks, an end-of-turn gate, retrospectives and
shared lessons, time-to-delivery measurement, a library of 140 verification
techniques and 20 recipes, personal data kept outside the clone, and
releases with rollback. Standard library only.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-22 22:29:02 -07:00
commit 2fc1fe9c2d
223 files changed
+22163

No files matched your search

@@ -0,0 +1,53 @@
---
id: api-breaking-schema
title: Breaking-change checks for protobuf, OpenAPI and GraphQL schemas
answers: Did my schema change break existing clients of this API?
rung: 4
section: regression
languages: any
kinds: general, migration
cost: low
detect: buf --version
ran_here: no
verified: docs
---
## Use when
- You edited a `.proto` file, an OpenAPI document or a GraphQL schema that other code or other teams consume.
- You must show a change is additive, not breaking.
## Do not use when
- The schema is internal and changes with all its users in one commit; a compile is enough.
- You need runtime behaviour: see `contract-testing-pact` in `real-world/`.
## Set up
- Protobuf: install `buf` (https://buf.build/docs/installation) and keep a `buf.yaml` at the module root.
- OpenAPI: install `oasdiff` (Go binary or Docker image).
- GraphQL: `npm i -D @graphql-inspector/cli graphql`.
Each tool compares the working tree to a known-good base: a git ref or a saved copy of the old schema.
## Minimal example
```sh
buf breaking --against '.git#branch=main' # protobuf, against the main branch
oasdiff breaking --fail-on ERR base/openapi.yaml openapi.yaml # OpenAPI; first arg is the old spec
graphql-inspector diff base/schema.graphql schema.graphql # GraphQL; reports breaking, dangerous, safe
```
Get the base BEFORE editing: `git show main:api/openapi.yaml > /tmp/base-openapi.yaml`. Use `--fail-on WARN` with oasdiff to also fail on risky changes. `buf` has rule sets (`FILE`, `PACKAGE`, `WIRE_JSON`, `WIRE`) set under `breaking:` in `buf.yaml`; pick the one that matches how clients are built.
## Run
Any of the commands above.
Passing looks like: no output and exit 0 from `buf breaking`; oasdiff exits 0 with no `error` lines; graphql-inspector says no breaking changes. Failure: buf prints `file:line:col:message` for each break and exits 100; oasdiff with `--fail-on ERR` exits 1 and lists each change with an id; graphql-inspector exits 1 on breaking changes.
## As a contract check
```json
{"id": "api-schema-compat", "claim": "The OpenAPI spec has no breaking changes against main", "kind": "general", "rung": 4,
"cmd": "git show main:api/openapi.yaml > /tmp/base.yaml && oasdiff breaking --fail-on ERR /tmp/base.yaml api/openapi.yaml", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
```
## What a pass does not prove
- Only the schema, not the server. A server can stop matching its own spec; test that separately (`contract-testing-pact`, schema-validating end-to-end tests).
- Semantics are invisible: renaming meaning without renaming a field passes.
- Not run here (the tools are not installed). `buf breaking --against` and `oasdiff breaking --fail-on ERR` are from their READMEs; the graphql-inspector command and buf's exit code 100 are from memory and should be checked with `--help`.
- Comparing to the wrong base (your own branch) always passes. Check the base is the released one.
- Check the check: remove a field in a scratch copy and confirm it reports a break.
+55
View File
@@ -0,0 +1,55 @@
---
id: api-semver-rust
title: Public API compatibility for Rust crates with cargo-semver-checks
answers: Did my change break the public API of this crate for anyone who depends on it?
rung: 4
section: regression
languages: rust
kinds: general
cost: low
detect: cargo semver-checks --version
ran_here: no
verified: docs
---
## Use when
- You changed a library crate's public items (types, functions, traits, enum variants, features).
- You are about to bump or publish a version and must say whether the bump is right.
## Do not use when
- The crate is a binary with no public library API.
- No earlier version exists to compare against (the first release).
## Set up
```sh
cargo install cargo-semver-checks --locked
```
It compares the current source's rustdoc JSON against a baseline: the latest release on the registry, or one you name.
## Minimal example
Baseline options (from the tool's README): a registry version, or a git revision of your own history.
```sh
cargo semver-checks # against the latest published version
cargo semver-checks --baseline-version 0.4.2 # against a named registry version
cargo semver-checks --baseline-rev v0.4.2 # against a git tag or commit
cargo semver-checks --package mylib # one package in a workspace
```
Before editing, run it once to know the starting state. A removed `pub fn` or a new required trait method fails with the lint name (for example `function_missing`) and the item's path.
## Run
`cargo semver-checks`
Passing looks like: a line such as `Summary no semver update required` (or the version bump you already made is enough) and exit 0. Failure lists each broken item and the required bump, exit 1.
## As a contract check
```json
{"id": "semver", "claim": "The public API of mylib is compatible with the last release for this version bump", "kind": "general", "rung": 4,
"cmd": "cargo semver-checks --package mylib", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
```
## What a pass does not prove
- It checks the API's shape (names, signatures, variants), not behaviour. A function can keep its signature and change what it returns.
- It runs a list of known break patterns; some breaks (trait coherence, unusual generics) are not detected. The README says the lint list is incomplete.
- A baseline equal to your own unpublished changes proves nothing. Make sure the baseline is the released version.
- Not run here (tool not installed); commands and the `--baseline-*` flags are from its README.
- Check the check: remove a `pub` function in a scratch copy and see it fail.
@@ -0,0 +1,57 @@
---
id: api-surface-typescript
title: Public API report diffs for TypeScript with API Extractor
answers: Did the exported types and functions of this TypeScript package change, and was that intended?
rung: 4
section: regression
languages: typescript
kinds: general
cost: medium
detect: npx --no-install api-extractor --help
ran_here: yes
verified: ran
---
## Use when
- You maintain a TypeScript library or package whose exported types others import.
- You want any change to the public surface to show up as a reviewable diff in a committed file.
## Do not use when
- The code is an application, not a library; nobody imports it.
- You only want type checking; `tsc --noEmit` is enough (see `zero-warnings`).
## Set up
```sh
npm i -D @microsoft/api-extractor typescript
mkdir -p config etc # init writes to config/ only if it exists; --local needs etc/ to exist
npx api-extractor init # creates config/api-extractor.json (else ./api-extractor.json)
npm run build # api-extractor reads the emitted .d.ts files
```
`tsconfig.json` needs `"declaration": true`. Set `mainEntryPointFilePath` (template default `<projectFolder>/lib/index.d.ts`) to your built `.d.ts`; it should match `typings` in `package.json`. `apiReport.enabled` is `true` in the template. The report is written to `etc/<unscopedPackageName>.api.md` and must be committed. Every export needs a release tag (`/** @public */`), or the `ae-missing-release-tag` warning fails the non-local run.
## Minimal example
```sh
npm run build
npx api-extractor run --local # writes or updates etc/pkg.api.md; use only when you intend to change the API
git diff etc/pkg.api.md # review: every line here is a public change
npx api-extractor run --print-api-report-diff # CI mode: fails if the report differs from the committed one, and prints the diff
```
Take the report BEFORE editing: run `api-extractor run --local`, commit, then edit. After editing, run it without `--local`; a nonzero exit means the surface changed. Then decide: revert the change, or update the report in the same commit and say why.
## Run
`npm run build && npx api-extractor run`
Passing looks like: `API Extractor completed successfully`, exit 0. Failure: the warning `You have changed the API signature for this project. Please copy the file "temp/pkg.api.md" to "etc/pkg.api.md", or perform a local build`, then `API Extractor completed with warnings` and exit 1. A missing report file fails the same way (`The API report file is missing`). In non-local mode any warning, not only the report diff, makes the run fail.
## As a contract check
```json
{"id": "ts-api-report", "claim": "The exported API matches the committed API report", "kind": "general", "rung": 4,
"cmd": "npm run build && npx api-extractor run", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"}
```
## What a pass does not prove
- Only the exported names and types, not behaviour.
- Running with `--local` rewrites the report and passes anything. In an agent's contract, use the non-local command.
- Ran here with @microsoft/api-extractor 7.60.1 and TypeScript 6.0.3: `--local` wrote the report, a plain run passed on an unchanged API, and a plain run after adding an export exited 1 with the diff. TypeScript 6 also needs `rootDir` in `tsconfig.json`.
- Types that are exported but marked `@internal` are filtered out of some reports by configuration.
- Check the check: add an `export` and confirm the run fails until the report is updated.
+63
View File
@@ -0,0 +1,63 @@
---
id: architecture-lint
title: Forbidding operations or imports outside a designated module
answers: Does anything outside the one module allowed to do X still do X?
rung: 4
section: regression
languages: rust, python, typescript, java
kinds: general, money
cost: medium
detect: cargo clippy --version
ran_here: yes
verified: ran
---
## Use when
- A rule says "only module M may write files / do money arithmetic / import the database", and you want it enforced, not remembered.
- You are moving code and must show that no new call crosses a boundary.
## Do not use when
- The rule is about behaviour at run time (use tests).
- The forbidden thing is common and legitimate in many places; the allow-list would be longer than the rule.
## Set up
- Rust: `clippy.toml` with `disallowed-methods` and `disallowed-types`, each entry with a `reason`. The allowed module opts out with `#[allow(clippy::disallowed_methods)]`.
- Python: `pip install import-linter`, a `.importlinter` file with a `forbidden` contract.
- TypeScript: `dependency-cruiser`, `forbidden` rules in `.dependency-cruiser.js` (not run here).
- Java: ArchUnit rules in a JUnit test (not run here).
## Minimal example
Rust, `clippy.toml`:
```toml
disallowed-methods = [
{ path = "std::fs::write", reason = "writes go through store::save only" },
]
```
Python, `.importlinter`:
```ini
[importlinter]
root_package = pkg
[importlinter:contract:1]
name = domain must not import db
type = forbidden
source_modules = pkg.domain
forbidden_modules = pkg.db
```
Compare-two-lint-runs trick: a lint cannot always be limited to one type (`clippy::arithmetic_side_effects` flags every type). Run clippy twice with different configs, once flagging all types and once with your type in `arithmetic-side-effects-allowed`. What appears in the first run only is exactly the places that touch your type. Give each run its own `--target-dir` so neither reuses the other's cached result.
## Run
`cargo clippy --all-targets -- -D clippy::disallowed_methods` or `lint-imports`
Passing looks like: no output, exit 0. Failure: clippy names the method and the reason and exits 101 under `-D`; import-linter prints `pkg.domain.m -> pkg.db (l.1)` and exits nonzero. Both ran here.
## As a contract check
```json
{"id": "arch-boundary", "claim": "No file writes outside the store module", "kind": "general", "rung": 4,
"cmd": "cargo clippy --all-targets -- -D clippy::disallowed_methods", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
```
## What a pass does not prove
- Only the named paths. `std::fs::File::create` or a shell call passes if you did not list it. List every route to the effect.
- An `#[allow]` anywhere silences it. Count the waivers (`grep -rn "allow(clippy::disallowed" src | wc -l`) and review the number's changes with `ratchet-floor`.
- Macros and code in dependencies are not seen.
- Check the check: add a forbidden call in a scratch file and confirm the failure (done here for clippy and import-linter).
@@ -0,0 +1,56 @@
---
id: baseline-before-change
title: Record what works before you touch it, then compare
answers: Did my change leave everything that already worked exactly as it was?
rung: 4
section: regression
languages: any
kinds: general, ui, migration
cost: low
detect:
ran_here: yes
verified: ran
---
## Use when
- You are about to edit something that already works and the task says "improve", "fix", "refactor" or "tidy".
- Feedback on a change is ambiguous. A baseline lets you show what you changed instead of guessing what was meant.
- No automated test covers the area you are about to touch.
## Do not use when
- The thing is new, so there is nothing to preserve. Use an example test or a property test instead.
- The output is noisy (timestamps, random ids) and you have not yet fixed the noise; the comparison will fail for the wrong reason.
## Set up
1. Before the first edit, run the command that produces the observable output (a test run, a CLI call, a page render, a query).
2. Save the output as files in the repo (`tests/baseline/`) and commit or at least `git add` them. Say in the commit message that the files are the baseline.
3. Write one command that regenerates the output and diffs it against the saved files.
## Minimal example
```sh
mkdir -p tests/baseline
./mytool report --fixture tests/fixtures/small.csv > tests/baseline/report.txt # BEFORE editing
git add tests/baseline && git commit -m "baseline before change"
# ... edit code ...
./mytool report --fixture tests/fixtures/small.csv | diff -u tests/baseline/report.txt -
```
If the change is meant to alter some of the output, update only those lines, and make the diff show nothing else.
## Run
`./mytool report --fixture tests/fixtures/small.csv | diff -u tests/baseline/report.txt -`
Passing looks like: no output and exit status 0. Failure shows as a unified diff and exit status 1.
## As a contract check
```json
{"id": "baseline-report", "claim": "The report output is unchanged except for the intended lines", "kind": "general", "rung": 4,
"cmd": "./mytool report --fixture tests/fixtures/small.csv | diff -u tests/baseline/report.txt -",
"expect": {"exit": 0}, "timeout_s": 60}
```
## What a pass does not prove
- It proves only that the output is the same as before, not that the baseline was right. If the baseline was captured from broken code, the check protects the bug.
- It covers only the inputs you captured. Choose inputs that exercise the parts you will touch.
- A baseline captured after the first edit is worthless. Check `git log` order: the baseline commit must come first.
- To check the check can fail: change one character in the code and see the diff appear.
- This is rung 4 at best. It detects change, it does not judge quality.
@@ -0,0 +1,56 @@
---
id: characterization-tests
title: Characterization tests that pin existing behaviour before a refactor
answers: Does the code still do what it did before I restructured it?
rung: 3
section: regression
languages: any
kinds: general, parsing
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- You are refactoring, replacing or optimising code that has few or no tests.
- You do not know exactly what the code does and the spec is missing; you need the behaviour that exists today, bugs included.
## Do not use when
- A real specification exists. Test against the specification, not against current behaviour.
- The behaviour is non-deterministic and you cannot control the source of randomness or time.
## Set up
Pick the entry points the rest of the code calls. List inputs: typical, edge (empty, one, maximum), and the last bug reports. If you have real logs or fixtures, replay them. If the code takes more than a few inputs, generate many and record the outputs (rung 4 style) or compare old and new implementations directly (see `differential` entries in `many-inputs/`).
## Minimal example
Write the test to fail first with a wrong guess, then paste the real output as the expected value. Commit this BEFORE refactoring.
```python
# tests/test_characterize_slug.py (python3 -m unittest)
import unittest
from textutil import slug
class Pinned(unittest.TestCase):
def test_current_behaviour(self):
cases = {"Hello World": "hello-world", "": "", " a b ": "a-b", "Ünï": "n"}
for given, got in cases.items():
with self.subTest(given=given):
self.assertEqual(slug(given), got)
```
The `"Ünï": "n"` row looks like a bug. Keep it, add a comment `# BUG? pinned as is`, and tell the human. Do not fix behaviour during the refactor; fix it in a separate commit with the test changed on purpose.
## Run
`python3 -m unittest tests.test_characterize_slug`
Passing looks like: `OK`, exit 0, on the old code (before) and on the new code (after). If it fails on the old code, the test describes behaviour wrong; fix the test, not the code.
## As a contract check
```json
{"id": "characterization", "claim": "Existing behaviour pinned by characterization tests is unchanged", "kind": "general", "rung": 3,
"cmd": "python3 -m unittest tests.test_characterize_slug", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
```
## What a pass does not prove
- Only the inputs you wrote. A refactor can change behaviour on every input you did not think of.
- It pins bugs as well as features. Review the table for surprises.
- Run `mutation testing` (`test-quality/`) on the pinned function to see whether the cases are strong enough.
- Check the check: introduce a deliberate change in the new code and confirm one case fails.
@@ -0,0 +1,54 @@
---
id: db-migration-safety
title: Database migration safety (round trip on a copy, squawk, data preservation)
answers: Will this migration run cleanly on real data without losing or corrupting any of it?
rung: 4
section: regression
languages: any
kinds: migration
cost: medium
detect: sqlite3 --version
ran_here: yes
verified: ran
---
## Use when
- You wrote or changed a schema migration (add, drop, rename, retype a column; change constraints).
- You were asked to change a data format that already holds user data.
## Do not use when
- The database is empty and disposable and no migration will ever run on real data.
## Set up
Work on a copy: never run an untested migration on the only copy of the data. Take a copy of a realistic database (a snapshot, an anonymised dump, or a fixture with awkward rows: nulls, long text, duplicates). For PostgreSQL also lint the SQL with `squawk` (`npm install -g squawk-cli` or `pip install squawk-cli`).
## Minimal example
The shape, shown with SQLite: record, migrate up, check the data, migrate down, check equality.
```sh
sqlite3 prod.db .dump | sort > before.sql
cp prod.db work.db
sqlite3 work.db "alter table u add column name text;" # the migration up
sqlite3 work.db "select count(*) from u;" # row count still 2
sqlite3 work.db "alter table u drop column name;" # the migration down
sqlite3 work.db .dump | sort > after.sql
diff before.sql after.sql && echo round-trip-identical
```
Add data-preservation checks that matter to the domain: row counts per table, sums of money columns, a checksum over each preserved column (`select sum(amount) ...`) before and after. For Postgres run `squawk migrations/*.sql` before applying; it flags locks that block writes and unsafe changes such as adding a `NOT NULL` column without a default.
## Run
The commands above, or your migration tool's own up and down commands against the copy.
Passing looks like: `round-trip-identical`, row counts and sums equal, squawk prints no warnings and exits 0. Failure: a diff, differing counts, or squawk exits 1 with rule names.
## As a contract check
```json
{"id": "migration-round-trip", "claim": "Migrating a copy up then down returns identical data", "kind": "migration", "rung": 4,
"cmd": "sh tests/migration-round-trip.sh", "expect": {"exit": 0, "stdout_contains": "round-trip-identical"}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Only the data in your copy. A migration that works on 2 rows may time out or lock on 200 million.
- A reversible migration is not a safe one: a `down` that restores structure may not restore values dropped by `up`.
- SQLite dumps compare text; ordering matters, hence `sort`. Dumps of other databases need `pg_dump --data-only --inserts` or per-table checksums.
- The squawk part was not run (not installed); the install commands are from its README.
- Check the check: make `down` a no-op and confirm the diff appears.
@@ -0,0 +1,55 @@
---
id: golden-files-hand-verified
title: Golden outputs recomputed by hand or by an independent method
answers: Is this expected output actually correct, or just whatever my code produced?
rung: 4
section: regression
languages: any
kinds: general, money, parsing
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- You need a fixed expected output for a calculation, report or parser, and a wrong golden file would lock in a bug.
- The numbers matter (money, dates, units). Independent recomputation is what makes the golden trustworthy.
## Do not use when
- You only need to detect change, not correctness. Use `snapshot-insta` or `baseline-before-change`.
- No independent method exists. Say so in the record instead of pretending.
## Set up
Keep each golden next to a provenance file, or a header comment, that records how it was verified. Verification methods, strongest first: a different program (a spreadsheet, `bc`, a second implementation, a published worked example), a hand calculation written out, a regulator's or vendor's published example. "The code printed it and it looked fine" is not a method.
## Minimal example
`tests/golden/invoice-total.expected` is the golden; `tests/golden/invoice-total.PROVENANCE` holds:
```
output: tests/golden/invoice-total.expected
method: independent
how: recomputed with Python's decimal module (or bc, a spreadsheet), not the project's code
command: python3 -c 'from decimal import Decimal as D; print((D("19.99")*3+D("5.00")*D("1.5")+D("0.10")).quantize(D("0.01")))'
result: 67.57
checked_by: agent, 2026-11-22
```
Check both in one command:
```sh
expected=$(python3 -c 'from decimal import Decimal as D; print((D("19.99")*3+D("5.00")*D("1.5")+D("0.10")).quantize(D("0.01")))')
[ "$expected" = "$(cat tests/golden/invoice-total.expected)" ] && ./mytool total tests/fixtures/invoice.json | diff - tests/golden/invoice-total.expected
```
## Run
The line above, as one test script. Passing looks like: no output, exit 0. Failure: a diff, or a nonzero exit when the independent value and the golden disagree (the check fails before it ever runs your code, which is the point).
## As a contract check
```json
{"id": "golden-independent", "claim": "Golden totals match an independently computed value and the tool matches the golden", "kind": "money", "rung": 4,
"cmd": "sh tests/check-golden.sh", "expect": {"exit": 0}, "timeout_s": 60}
```
## What a pass does not prove
- It shows the golden equals the independent method on these inputs, not that the inputs are representative. Include awkward values (rounding at half cents, zero, negative, very large).
- The independent method can share your misunderstanding. Using the same formula in a second language is not independent; a spreadsheet or a published worked example is better.
- The recorded `method:` is a claim. If it says `independent` but the command only calls your own code, the check is a snapshot at best. A reviewer should read the PROVENANCE file.
- Check the check: edit one digit in the golden and confirm the script fails. Here the unrounded Python result was `67.570`, which also failed a string comparison until it was quantized: compare in the golden's own format.
+56
View File
@@ -0,0 +1,56 @@
---
id: perf-regression
title: Performance regression checks with an explicit budget (criterion, hyperfine, iai-callgrind)
answers: Did my change make this code or command measurably slower than before?
rung: 4
section: regression
languages: rust, any
kinds: general
cost: medium
detect: hyperfine --version
ran_here: no
verified: docs
---
## Use when
- You changed a hot path or are asked to "optimise", and need evidence of faster or not slower.
- A command's run time has a limit users depend on.
## Do not use when
- Timing noise exceeds the effect you care about and you cannot reduce it (shared CI runners). Count instructions instead (iai-callgrind) or measure memory or allocations.
- The claim is about correctness; speed says nothing about that.
## Set up
- Rust micro-benchmarks: `cargo add --dev criterion`, add `[[bench]] name = "b" harness = false`, put the benchmark in `benches/b.rs`.
- Whole commands: `hyperfine` (https://github.com/sharkdp/hyperfine).
- Low-noise Rust: `iai-callgrind` counts instructions with valgrind (Linux, needs valgrind installed).
## Minimal example
Baseline BEFORE editing, compare after, on the same machine, with nothing else running.
```sh
cargo bench --bench b -- --save-baseline main # before the change
cargo bench --bench b -- --baseline main # after: prints "change: [...]" and a verdict
hyperfine --warmup 3 --runs 20 --export-json after.json './mytool big.csv'
```
A budget is an explicit number. Criterion and hyperfine do not fail on a regression, so read the numbers: with `jq` take `.results[0].mean` (seconds) from the hyperfine JSON and fail if it exceeds the budget.
```sh
jq -e '.results[0].mean < 0.50' after.json # exit 1 when the mean is not under 0.5 s
```
Handle noise: warm-up runs, at least 10 runs, compare the median or min rather than the mean, repeat a failing run once, and record the machine. For a Rust gate that does not depend on timing, iai-callgrind can fail on an instruction-count increase (its regression option, see its README; not run here).
## Run
The commands above.
Passing looks like: criterion ends `No change in performance detected.` (here: `change: [-1.2% -0.3% +0.5%] (p = 0.53 > 0.05)`), and `jq -e` exits 0. A real slowdown prints `Performance has regressed.`; criterion still exits 0, so a contract must parse it or use the `jq` budget.
## As a contract check
```json
{"id": "perf-budget", "claim": "mytool processes big.csv in under 0.5 s mean", "kind": "general", "rung": 4,
"cmd": "hyperfine --warmup 3 --runs 20 --export-json /tmp/h.json './mytool big.csv' && jq -e '.results[0].mean < 0.50' /tmp/h.json", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Timing depends on the machine; a budget set on a laptop may fail on CI. Record where it was set.
- A benchmark measures the inputs you chose, not production load. Optimised-away work (`black_box` missing) gives fake speed.
- Criterion `--save-baseline`/`--baseline` ran here (exit 0 and `No change` confirmed). hyperfine and iai-callgrind were not installed: `--warmup` and `--runs` are in the hyperfine README; `--export-json` is from memory, check `hyperfine --help`.
- Check the check: add a sleep and confirm the budget fails.
+56
View File
@@ -0,0 +1,56 @@
---
id: ratchet-floor
title: A ratchet, a count that may only move one way, checked against the base commit
answers: Is this number (warnings, coverage, done items) no worse than it was before my change?
rung: 4
section: regression
languages: any
kinds: general
cost: low
detect: git --version
ran_here: yes
verified: ran
---
## Use when
- A count must never get worse: lint warnings may only fall, test coverage or "done" items in a plan may only rise.
- A test inside the tree cannot see the history. Only a comparison with the base commit shows a number was quietly lowered.
## Do not use when
- The number is allowed to move both ways with the work (lines of code, file counts).
- There is no base commit: a brand-new repository has nothing to compare with.
## Set up
Keep the number in one machine-readable line in a committed file, for example `**Floor: 12 done**` in `docs/parity.md`, or a `.ratchet/warnings.txt` containing `37`. Write a script that reads it at the base ref and in the working tree.
## Minimal example
`scripts/floor.sh <base-ref>` (a version of this pattern runs in a reference project):
```sh
#!/bin/bash
set -euo pipefail
base_ref="${1:?usage: floor.sh <base-ref>}"
floor_of() { sed -n 's/^\*\*Floor: \([0-9][0-9]*\) done\*\*.*/\1/p' | head -n 1; }
base=$(git show "${base_ref}:docs/parity.md" | floor_of)
now=$(floor_of < docs/parity.md)
[ -n "$base" ] || { echo "no floor at ${base_ref}; nothing to compare"; exit 0; }
[ -n "$now" ] || { echo "working tree has no floor line" >&2; exit 1; }
echo "floor: base ${base}, now ${now}"
[ "$now" -ge "$base" ] || { echo "the floor never decreases" >&2; exit 1; }
```
For a count that may only fall (warnings), flip the last test to `-le`. Run it with `origin/main` or the merge base as `<base-ref>`, not with `HEAD`, because `HEAD` already contains your edit once committed.
## Run
`scripts/floor.sh origin/main`
Passing looks like: a `floor: base N, now M` line with M at least N, exit 0. Failure prints `the floor never decreases` and exits 1. A missing floor line in the working tree is a failure, not a pass.
## As a contract check
```json
{"id": "ratchet-floor", "claim": "The done-item floor is not lower than on the base branch", "kind": "general", "rung": 4,
"cmd": "scripts/floor.sh origin/main", "expect": {"exit": 0}, "timeout_s": 30}
```
## What a pass does not prove
- That the counted items are real. If an agent marks items done without doing the work, the floor rises and the check passes. Pair it with a check on each item.
- Deleting the line fails here, but deleting the whole file and the script passes the ratchet vacuously; protect the script by also running it from a trusted base ref where possible.
- Check the check: lower the number by one in a scratch copy and confirm exit 1 (run here with a throwaway git repo: `ratchet fails: 4 < 5`).
@@ -0,0 +1,50 @@
---
id: read-only-guarantee
title: Proving a viewer or query path changes nothing
answers: Does this read-only path leave every byte, size and modification time of the data untouched?
rung: 3
section: regression
languages: any
kinds: general, state-machine
cost: low
detect: sha256sum --version
ran_here: yes
verified: ran
---
## Use when
- A viewer, report, query, export or "dry run" must not change stored data, and a user would be harmed if it did.
- You change a read path and want evidence no write sneaked in (a log line, a cache file, a lock, a SQLite `-wal`).
## Do not use when
- The path is allowed to write caches or logs elsewhere. Scope the check to the data directory only.
## Set up
Make a fixture data directory with realistic content, files of several sizes, nested folders. Write a function that snapshots every file's relative path, size, modification time and content hash, so that a changed, added or removed file shows.
## Minimal example
```sh
snap() { (cd "$1" && find . -type f -printf '%p %s %T@ ' -exec sha256sum {} \; | sort); }
snap data > /tmp/before
./mytool view --data data # the path under test; exercise every page or query
snap data > /tmp/after
cmp /tmp/before /tmp/after && echo unchanged
```
The strongest form also makes the whole tree read-only on disk (`chmod -R a-w data`) and runs the viewer again: it must still work, which proves it never needed to write. In the reference project's test (`crates/ledger-gui/tests/read_only.rs`) the walk records bytes, size and mtime for every file, repeats with read-only and with writable books, and fails if any file appears or goes (for example SQLite's `-wal` and `-shm`).
## Run
The script above.
Passing looks like: `unchanged` and exit 0. Failure: `cmp` prints the first differing line and exits 1; the diff names the file (`diff /tmp/before /tmp/after`).
## As a contract check
```json
{"id": "read-only", "claim": "The viewer changes no byte, size or mtime in the data directory", "kind": "general", "rung": 3,
"cmd": "sh tests/read-only-check.sh", "expect": {"exit": 0, "stdout_contains": "unchanged"}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Only the paths and queries you exercised. A rarely used page may still write.
- Equal mtime resolution: some file systems store coarse times. The content hash covers that for contents.
- It cannot see writes elsewhere (a database server, the network). Add a check on those separately.
- Check the check: append a byte during the run (`echo x >> data/a`) and confirm the check fails (done here: `ro-detects`).
+51
View File
@@ -0,0 +1,51 @@
---
id: size-budget
title: Binary and bundle size budgets
answers: Did my change make the binary, package or JavaScript bundle bigger than it is allowed to be?
rung: 4
section: regression
languages: any
kinds: general, ui
cost: low
detect:
ran_here: yes
verified: ran
---
## Use when
- You add a dependency, enable a feature or change build settings, and size matters (download size, page weight, embedded targets).
- You were told "keep it small" and need a number that says so.
## Do not use when
- Size is irrelevant to the user. A budget nobody cares about gets bumped without thought.
- You are comparing builds with different compilers or flags; compare like with like.
## Set up
Decide the budget as a number with a reason, and write it in a file under version control, not in the check command. Measure the build output the user receives (the stripped release binary, the gzipped bundle).
Tools: `size-limit` (npm) for bundles, `cargo bloat` for Rust binary attribution, or plain `stat` and `wc`.
## Minimal example
```sh
cargo build --release --locked
size=$(stat -c %s target/release/mytool) # GNU stat; on macOS use: stat -f %z
budget=$(cat tests/size-budget.txt) # e.g. 8000000
[ "$size" -le "$budget" ] || { echo "size $size > budget $budget"; exit 1; }
```
For JavaScript: `gzip -c dist/app.js | wc -c`, or `npx size-limit` with limits in `package.json` under `"size-limit"`. Record the size BEFORE the change (`echo $size > /tmp/before`) so a failure can name the growth in bytes, and so you can see how close you already were.
## Run
The script above.
Passing looks like: no output and exit 0. Failure prints `size N > budget M` and exits 1.
## As a contract check
```json
{"id": "size-budget", "claim": "The release binary is within its size budget", "kind": "general", "rung": 4,
"cmd": "cargo build --release --locked && test $(stat -c %s target/release/mytool) -le $(cat tests/size-budget.txt)", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
```
## What a pass does not prove
- Only the artifact size. It says nothing about start-up time, memory or what was added.
- Raising the number in `tests/size-budget.txt` makes any failure pass. A reviewer should see that file's diff with a reason.
- Different build settings (debug versus release, stripped or not) change size a lot; run the same profile as the budget was set with.
- Check the check: set the budget one byte below the real size and confirm exit 1 (the shell test was run here with exactly this).
+52
View File
@@ -0,0 +1,52 @@
---
id: snapshot-insta
title: Snapshot testing with insta (Rust), Jest/Vitest and syrupy (Python)
answers: Is the output of this function, report or message exactly what it was before?
rung: 4
section: regression
languages: rust, javascript, typescript, python
kinds: general, parsing
cost: low
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- Output is large or structured (a report, error text, a parsed tree) and hand-writing expected values is impractical.
- You are refactoring and the output must stay the same.
## Do not use when
- The output contains time, random ids or paths; redact them first or use an example assertion.
- You would approve snapshots without reading them. Then the test records, it does not check.
## Set up
- Rust: `cargo add --dev insta`, and optionally `cargo install cargo-insta` for `cargo insta review`.
- Jest or Vitest: built in, `expect(x).toMatchSnapshot()` or `toMatchInlineSnapshot()`.
- Python: `pip install syrupy`; tests take the `snapshot` fixture.
## Minimal example
```rust
#[test]
fn greeting() { insta::assert_snapshot!(greet("Ada")); }
```
Python (syrupy): `def test_x(snapshot): assert {"a": 1} == snapshot`. Jest: `expect(render()).toMatchSnapshot()`.
Create the baselines BEFORE refactoring: Rust `INSTA_UPDATE=always cargo test`, syrupy `pytest --snapshot-update`, Jest `jest -u`. Commit the `.snap`, `.ambr` or `__snapshots__` files, then edit code.
## Run
- `INSTA_UPDATE=no cargo test` (use `no` in CI so nothing is written), or `cargo insta test`.
- `pytest`; `jest --ci` (does not write new snapshots).
Passing looks like: `test result: ok` / `1 passed`. Failure: insta prints `-old snapshot` / `+new results` and exits 101; syrupy reports `assert [+ received] == [- snapshot]`. By default insta writes a `.snap.new` file next to the old one; delete or review it, never commit it unseen.
## As a contract check
```json
{"id": "snapshots", "claim": "All snapshot tests match the committed snapshots", "kind": "general", "rung": 4,
"cmd": "INSTA_UPDATE=no cargo test", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- That the snapshot was right when recorded. Read each new snapshot like a diff.
- Updating snapshots turns every failure into a pass. The evidence is `git diff` on the snapshot files showing only intended changes.
- Obsolete snapshots can pile up: `cargo insta test --unreferenced=reject` (flag listed in cargo-insta source, not run here) and `jest --ci` flag obsolete ones.
- Check the check: change the function and see the failure (done here with insta 1.49 and syrupy).
@@ -0,0 +1,62 @@
---
id: ui-structure-snapshot
title: Accessibility-tree and DOM-structure snapshots
answers: Is the page's structure (headings, buttons, labels, order) the same as before, regardless of pixels?
rung: 4
section: regression
languages: javascript, typescript, python
kinds: ui
cost: low
detect: npx playwright --version
ran_here: yes
verified: ran
---
## Use when
- You want a UI check that does not break on fonts, antialiasing or colour shifts.
- You are refactoring markup or components and the screen must keep the same elements and labels.
- You want a companion to `visual-regression-web`: structure first, pixels second.
## Do not use when
- The claim is about appearance (spacing, colour, alignment). Structure snapshots cannot see it.
- You have not decided what the structure should be; you would just record whatever exists.
## Set up
```sh
npm i -D @playwright/test && npx playwright install chromium
```
Python has the same API: `expect(locator).to_match_aria_snapshot("...")` in `pytest-playwright`.
## Minimal example
```ts
import { test, expect } from '@playwright/test';
test('main structure', async ({ page }) => {
await page.goto('/');
await expect(page.locator('main')).toMatchAriaSnapshot(`
- heading "Shop" [level=1]
- paragraph
- button "Buy"
- navigation "Main":
- link "Home"
`);
});
```
Take the snapshot BEFORE editing. Scope the locator to the region you are touching, and keep a second snapshot of the rest of the page, so only the intended region may change. Use `npx playwright test --update-snapshots` to write the expectations into the test file or `.aria.yml` files when you mean to change them (flag `--update-source-method` picks patch or overwrite).
## Run
`npx playwright test`
Passing looks like: `N passed`, exit 0. Failure shows a diff such as `- button "Buy"` against `+ button "Buy now"` and exit 1.
## As a contract check
```json
{"id": "ui-structure", "claim": "The accessibility tree of the main regions is unchanged", "kind": "ui", "rung": 4,
"cmd": "npx playwright test tests/aria.spec.ts", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Nothing about appearance. A button can keep its label and become invisible.
- Matching is partial by default: extra elements not listed may exist. Write the whole subtree you care about, or check the Playwright aria-snapshot docs for the `/children` setting (not run here).
- Accessible names come from text, so copy changes fail it; that is often the signal you want.
- Check the check: edit a label and see the diff appear (done here with Playwright 1.57).
- Other tools (Testing Library `getByRole`, Cypress snapshots) give the same kind of check; the claim is the same, the rung is 4.
@@ -0,0 +1,61 @@
---
id: visual-regression-native-gui
title: Snapshot testing for native GUIs (egui_kittest and the general pattern)
answers: Did my change alter what a desktop GUI draws somewhere I did not mean to?
rung: 4
section: regression
languages: rust, any
kinds: ui
cost: medium
detect: cargo --version
ran_here: no
verified: docs
---
## Use when
- A native GUI (egui, or any toolkit you can drive headless) already looks right and you are about to change layout or styling.
- You need a baseline that works in CI where there is no screen.
## Do not use when
- A web UI: use `visual-regression-web`.
- You cannot render headless and have no way to compare the drawn output.
## Set up
In `Cargo.toml` (a reference project uses this version):
```toml
[dev-dependencies]
egui_kittest = { version = "0.36", features = ["wgpu", "snapshot", "eframe"] }
```
Other toolkits: render offscreen, or dump the draw list or widget tree, to a file and diff it (Qt: `QWidget::grab()`; GTK: widget tree dump; Flutter: `matchesGoldenFile`).
## Minimal example
```rust
use egui_kittest::Harness;
#[test]
fn sidebar_is_unchanged() {
let mut h = Harness::new_ui(|ui| { ui.heading("Books"); let _ = ui.button("Open"); });
h.fit_contents();
h.snapshot("sidebar"); // tests/snapshots/sidebar.png
}
```
Do it in this order: write the test and run it on the unchanged code to create the baseline (`UPDATE_SNAPSHOTS=true cargo test`; `force` also rewrites images within the error margin), commit `tests/snapshots/`, then edit. Scope an intended change by taking one snapshot per region or widget, so only that region's baseline is refreshed.
A pattern that held up in the reference project: pixels differ between renderers (CI software renderer versus a GPU), so compare a hash of the painted shapes everywhere and pixels only on the machine that made them. The baseline stores the hash on line one and the shape text below, so a mismatch says which shape moved. Blessing is an explicit env var (`SIDENAV_BLESS=1`) that is never set to silence a failure.
## Run
`cargo test -p <gui-crate> --test <snapshot-test>`
Passing looks like: `test result: ok`. Failure shows a diff image under `tests/snapshots/` (`*.diff.png`) or the differing shapes, exit 101.
## As a contract check
```json
{"id": "gui-snapshots", "claim": "GUI snapshots match their baselines", "kind": "ui", "rung": 4,
"cmd": "cargo test -p mygui --test snapshots", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 900}
```
## What a pass does not prove
- Only the states you built in the harness. Hover, focus, small windows and high-DPI need separate snapshots.
- Not run here (egui_kittest needs a GPU or software renderer); the commands come from the crate docs and the reference project's tests.
- Raising `max_failed_pixels` above about 10 can hide a moved border; the crate docs warn about it.
- Setting the update variable and re-running makes any failure pass. Check `git diff --stat tests/snapshots` shows only the intended files.
- The shapes hash proves painting is the same, not that it looks good.
@@ -0,0 +1,63 @@
---
id: visual-regression-web
title: Screenshot comparison for web UI with Playwright
answers: Did my change alter how the page looks anywhere I did not mean to change?
rung: 4
section: regression
languages: javascript, typescript, python
kinds: ui
cost: medium
detect: npx playwright --version
ran_here: yes
verified: ran
---
## Use when
- A page already looks right and you are about to edit its CSS, markup or components.
- You were asked to change one region (a button, a header) and must show nothing else moved.
- The user has approved a design and wants it pinned.
## Do not use when
- The page is still being designed; screenshots will fail on every edit. Use a structure snapshot (`ui-structure-snapshot`) first.
- The content is live data you cannot fix or mask.
## Set up
```sh
npm i -D @playwright/test && npx playwright install chromium # once
```
In `playwright.config.ts` fix the viewport, disable animations and allow no drift: `expect: { toHaveScreenshot: { maxDiffPixels: 0, animations: 'disabled' } }`, `use: { viewport: { width: 800, height: 600 } }`. Run on one OS only (the CI image); font rendering differs between OSes.
## Minimal example
`tests/home.spec.ts`
```ts
import { test, expect } from '@playwright/test';
test('home looks the same', async ({ page }) => {
await page.goto('/');
// Dynamic regions are masked: a changing clock must not fail the test.
await expect(page).toHaveScreenshot('home.png', { mask: [page.locator('#clock')] });
});
// Per-region scope: every region except the intended one gets its own baseline.
test('header is untouched', async ({ page }) => {
await page.goto('/');
await expect(page.locator('#hdr')).toHaveScreenshot('header.png');
});
```
Order of work: (1) BEFORE the first edit run `npx playwright test --update-snapshots` and commit the PNGs. (2) Edit. (3) Run `npx playwright test`. (4) The intended region may differ. Re-baseline only that region's test (`npx playwright test -g "buy button" --update-snapshots`) and keep the whole-page test failing only on that region by masking it: `mask: [page.locator('#buy')]`. Every other test must pass untouched. Read the diff images in `test-results/` before re-baselining.
## Run
`npx playwright test`
Passing looks like: `N passed`, exit 0. Failure prints `N pixels (ratio ...) are different` and writes `-actual.png` and `-diff.png` into `test-results/`. Missing baselines are written on first run and the run still reports them; treat that as not yet checked.
## As a contract check
```json
{"id": "ui-visual-regression", "claim": "No unintended visual change on the pages covered by baselines", "kind": "ui", "rung": 4,
"cmd": "npx playwright test", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Only that pixels match the baseline. If you re-baseline to make a failure go away you have proved nothing; re-baseline only the region you meant to change.
- A mask hides a region completely: do not mask the thing you changed in the other tests.
- It does not show the design is good or that feedback was understood. That needs rung 5 or 6.
- Only the viewports, pages and states you captured are covered (hover, error and empty states need their own tests).
- Check the check: change a colour and see it fail. In a run here, changing the masked clock text still passed while a changed button label failed.
+53
View File
@@ -0,0 +1,53 @@
---
id: zero-warnings
title: Lints, compiler and docs warnings as errors
answers: Does the code build, lint and document with no warnings at all?
rung: 4
section: regression
languages: any
kinds: general
cost: low
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- Finishing any change in a project that keeps zero warnings, or you want it to.
- A warning is often a real fault: an unused variable that should have been used, a broken doc link, a deprecated call.
## Do not use when
- The project has hundreds of existing warnings. Use `ratchet-floor` on the count first.
- Do not put `-D warnings` into a committed build config for a library others compile with newer toolchains; a new compiler lint then breaks their build. Use it in CI only.
## Set up
Pick the tools for the language:
- Rust: `cargo clippy`, `cargo build`, `cargo doc`.
- Python: `ruff check`, `python -W error -m pytest` (warnings become failures).
- TypeScript: `tsc --noEmit --noUnusedLocals`, `eslint --max-warnings 0`.
## Minimal example
```sh
RUSTFLAGS="-D warnings" cargo build --all-targets
cargo clippy --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps
cargo test --doc
```
Before changing anything, run these on the base commit and note which already fail, so you are not blamed for old problems and do not hide your own. Never silence a warning with `#[allow]` or `# noqa` without a one-line reason; if you add one, say so in the report.
## Run
The commands above, one after the other.
Passing looks like: every command exits 0 with no `warning:` lines. Failure: `error: unused variable: x` and `error: could not compile` (compiler), `error: unresolved link to broken` and `error: could not document` (docs), exit 101 under clippy `-D warnings`. All three ran here.
## As a contract check
```json
{"id": "zero-warnings", "claim": "No compiler, clippy or rustdoc warnings", "kind": "general", "rung": 4,
"cmd": "cargo clippy --all-targets -- -D warnings && RUSTDOCFLAGS='-D warnings' cargo doc --no-deps", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
```
## What a pass does not prove
- Absence of lint warnings says nothing about correctness. Clean code can be wrong.
- Only the code you compiled: feature flags, other targets and other operating systems are separate builds (`--all-features`, `cross-platform-matrix`).
- A suppression added to get green is a failure in disguise; compare `git diff` for new `allow` attributes.
- Check the check: introduce an unused variable and confirm the build fails.