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

+54
View File
@@ -0,0 +1,54 @@
---
id: accessibility-axe
title: Automated accessibility checks with axe-core
answers: Does this page have any detectable accessibility violations (contrast, labels, roles)?
rung: 3
section: real-world
languages: javascript, typescript, python
kinds: ui
cost: low
detect: npx playwright --version
ran_here: no
verified: docs
---
## Use when
- You build or change pages and the user said accessibility matters, or you add forms, buttons, images or colours.
- You want a cheap guard against missing labels, low contrast, wrong ARIA roles and bad heading order.
## Do not use when
- You want to claim "accessible". Automated rules catch only a portion of problems; say "no detectable violations".
## Set up
```sh
npm i -D @playwright/test @axe-core/playwright && npx playwright install chromium
```
## Minimal example
```ts
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
test('home has no detectable a11y violations', async ({ page }) => {
await page.goto('/');
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations).toEqual([]); // prints each violation with the offending element
});
```
Run it on every state that changes the DOM: after opening the menu, the dialog, the error state. Use `.withTags(['wcag2a', 'wcag2aa'])` to pick a standard. Do not disable rules to get green; if a rule must be excluded, `.disableRules([...])` it with a comment saying why and mention it in the report. Take the violation list before your change and show it has not grown.
## Run
`npx playwright test`
Passing looks like: `N passed`. Failure prints the `violations` array: rule id (`color-contrast`), impact, and the HTML node, exit 1.
## As a contract check
```json
{"id": "a11y-axe", "claim": "No axe violations on the covered pages", "kind": "ui", "rung": 3,
"cmd": "npx playwright test tests/a11y.spec.ts", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Roughly a third to a half of accessibility problems can be found by machine; keyboard flow, screen reader wording and sense of the page need a human or a real assistive tool.
- Only pages and states visited. Pixel-level contrast on images is not checked.
- Not run here; the `AxeBuilder({ page }).analyze()` call is from the package README.
- Check the check: add an `<img>` without `alt` and confirm `image-alt` appears.
@@ -0,0 +1,58 @@
---
id: agent-surface-evals
title: Scripted agent transcripts played against the real tool server
answers: Can an agent finish the job by following only what the tool itself tells it to do next?
rung: 3
section: real-world
languages: any
kinds: general, state-machine
cost: high
detect:
ran_here: no
verified: docs
---
## Use when
- You build or change a tool that AI agents call: an MCP server, a CLI an agent drives, an API with guidance in its responses.
- The tool's responses carry guidance ("next steps", error hints) and you want it proved to be enough, with no model involved.
## Do not use when
- The tool is only used by humans. Use `cli-transcript-tests`.
- You want to measure a particular model's skill; this check uses no model and proves only that a path exists.
## Set up
Write transcripts as data files (JSON), one per journey. A transcript is `{ "description", "settings", "setup": [...], "steps": [...] }`. `setup` calls are made directly (the chart and the books an agent finds on arrival; they are not the agent's moves) and may save values with `"save": {"x": "/pointer"}`. Write a small runner that starts the real server (a temporary data directory, a real socket or stdio), plays the steps, and fails when a step's tool is not in the previous result's next steps. The reference project does exactly this in `crates/app-cli/tests/agent_evals.rs`, with six transcripts in `crates/app-cli/tests/agent_evals/*.json`; the test asserts the exact list of transcript names, so a deleted transcript fails.
## Minimal example
Trimmed from the reference project's `onboarding_to_first_post.json`:
```json
{ "description": "A new book: onboarding to the first account, following only next_steps.",
"steps": [
{ "call": "books.start", "args": { "agent": { "model": "scripted", "reasoning_effort": "none", "harness": "agent_evals" } } },
{ "expect": { "/state": "needs_onboarding" } },
{ "expect_next_steps_contains": "books.set_setting" },
{ "follow": "books.set_setting", "with": { "changes": [{ "key": "company.name", "value": "Eval Co" }], "decided_by": "Avery Quill" } },
{ "expect_next_steps_contains": "books.add_account" },
{ "follow": "books.add_account", "with": { "code": "1000", "name": "Cash", "account_type": "asset" } } ] }
```
The step forms in the reference runner: `call` (first step only, and only `books.start`), `follow` (the previous result's `next_steps` must name that tool; its `args` are used with `with` laid over them, so `with` supplies only what an agent decides: an amount, a date), `follow_prompt` (the previous result must name that prompt), `expect_next_steps_contains` and `expect` (JSON-pointer equality on the previous result). The runner panics on any other step. The tool names above belong to that project's server; use your own server's.
Add the cases agents get wrong: a refused call must say what to do instead, and the transcript then follows that advice.
## Run
Your test command; the reference project's is `cargo test -p app-cli --test agent_evals`. The test function plays every file, and asserts that each transcript called at least one tool after the start.
Passing looks like: `test result: ok` for `agent_evals_follow_only_next_steps`. Failure names the step, for example `"onboarding step 3: books.add_account is not in the previous result's next_steps: [...]"`, or `was refused` when the call itself errored.
## As a contract check
```json
{"id": "agent-evals", "claim": "An agent can complete each journey by following the tool's own next steps", "kind": "general", "rung": 3,
"cmd": "cargo test -p app-cli --test agent_evals", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "timeout_s": 900, "tier": "deep"}
```
## What a pass does not prove
- That a model will actually choose those steps; it proves they exist and are enough.
- Only the journeys scripted. Add one for each reported agent failure.
- Not run here. `verified: docs` means checked against the reference project's runner source and transcripts (this entry describes that pattern; the runner is specific to its server).
- The reference runner has no explicit "end state" step: a transcript ends where its last `expect` lines say, so give every transcript a final `expect` on the result that proves the journey finished.
- A transcript with no `expect` lines proves only that calls did not error. Assert on content.
- Check the check: edit the server's next steps to name a wrong tool and see a transcript fail.
@@ -0,0 +1,56 @@
---
id: annotation-behaviour-check
title: Verifying that declared properties (read-only, idempotent) hold in behaviour
answers: Does every tool marked read-only or idempotent really behave that way?
rung: 3
section: real-world
languages: any
kinds: general, state-machine
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- A tool, API method or command declares a property an agent will rely on: MCP `readOnlyHint`, `idempotentHint`, `destructiveHint`, an HTTP `GET` that must be safe, a "dry run" flag.
- You add or change such a tool. A false `readOnlyHint` makes an agent call a destructive tool freely.
## Do not use when
- Nothing relies on the declaration.
## Set up
Build a fixture with data in every table or file the tools can touch. Write a snapshot function for the whole data area (paths, sizes, hashes; see `read-only-guarantee`). Get the tool list and its annotations from the running server (`tools/list` in MCP), and iterate over it so new tools are covered by default.
## Minimal example
```python
# pseudo-code for a test loop; a reference project does this for every tool in tools/list
for tool in server.list_tools():
for args in sample_arguments(tool): # valid calls plus refused ones
before = snapshot(data_dir)
result = server.call(tool.name, args)
after = snapshot(data_dir)
if tool.annotations.get("readOnlyHint"):
assert before == after, f"{tool.name} {args} changed data" # success or refusal
if tool.annotations.get("idempotentHint") and not result.is_error:
server.call(tool.name, args)
assert snapshot(data_dir) == after, f"{tool.name} is not idempotent"
```
Check both outcomes: a refused call must also leave data unchanged. Exclude only files that legitimately change (SQLite `-wal` and `-shm` files change on read; compare database contents by a digest instead). A second assertion belongs here: a tool that does change data must not be marked read-only, so also assert that at least one tool carries `readOnlyHint: false` and that each such tool's sample call changes something; otherwise the loop may be testing nothing.
## Run
Your test command, for example `cargo test --test spec_mcp`.
Passing looks like: all tools pass and the log says how many read-only calls ran and that each changed nothing. Failure names the tool, the arguments and the changed file.
## As a contract check
```json
{"id": "annotations-true", "claim": "Every tool marked read-only leaves data unchanged, success or refusal", "kind": "general", "rung": 3,
"cmd": "cargo test --test spec_mcp readonly", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900}
```
## What a pass does not prove
- Only the argument samples used. A tool that writes on a rare path (a cache miss, a quota reset) passes unless the samples reach it.
- A declared property outside the data you snapshot (network calls, email) is not checked. Say which areas are covered.
- The check ran here only in miniature (the snapshot comparison from `read-only-guarantee`); the loop above is the pattern from the reference project, not a tool you can install.
- Check the check: make one read-only tool touch a file and confirm the loop catches it.
+50
View File
@@ -0,0 +1,50 @@
---
id: clean-clone-build
title: Build and test from a fresh clone in a clean container
answers: Does this work from a fresh checkout, or only on my working tree?
rung: 3
section: real-world
languages: any
kinds: general
cost: medium
detect: docker --version
ran_here: yes
verified: ran
---
## Use when
- You are about to say "done" on something that builds, packages or deploys.
- You added a file, a generated asset, an environment variable or a tool that your tree may have and the repository does not.
- A path that only exists on your machine (an ignored file, a global tool) could be hiding a break.
## Do not use when
- The change is a comment or documentation only.
- A full build takes hours; then use CI as the clean room and wait for it.
## Set up
Commit (or stage) everything first: a clone sees only committed files. You need `git` and, for a clean machine, Docker or Podman and an image of the target OS.
## Minimal example
```sh
git clone --no-local . /tmp/fresh # only committed files come along
docker run --rm -v /tmp/fresh:/work:ro -w /work debian:trixie-slim \
sh -c 'apt-get update -qq && apt-get install -y -qq make >/dev/null && make test'
```
Without Docker the fresh clone alone catches most problems: `cd /tmp/fresh && make test`. Run the project's real build and test command, with no cache mounts, and on the clean machine install tools only as the README says. If the README's steps are not enough, the README is a bug.
Here a repository with an ignored `generated.txt` passed `make test` in its own directory and failed (`Error 1`) in the fresh clone.
## Run
The commands above. Passing looks like: the same exit 0 and test summary you got on your tree. Failure: missing file, missing tool or failing test in the clean place only, which means the claim "works" was about your tree.
## As a contract check
```json
{"id": "clean-clone", "claim": "A fresh clone builds and passes tests", "kind": "general", "rung": 3,
"cmd": "rm -rf /tmp/fresh && git clone --no-local . /tmp/fresh && cd /tmp/fresh && make test", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800}
```
## What a pass does not prove
- Only the commit you cloned. Uncommitted edits are not tested; commit first.
- A clone on the same machine still inherits your global tools and `~/.cargo`; use a container for the OS and toolchain claim.
- A pinned base image can go stale. Note the image tag.
- Network-fetched dependencies can change between runs; use lockfiles (`--locked`, `npm ci`) so the clean build is repeatable.
- Check the check: delete an ignored-but-needed file and confirm the clone fails.
@@ -0,0 +1,56 @@
---
id: cli-transcript-tests
title: Recorded CLI sessions with trycmd, cram or scrut
answers: Does the command-line tool still print exactly what its documented examples show?
rung: 4
section: real-world
languages: any
kinds: general, parsing
cost: low
detect: scrut --version
ran_here: no
verified: docs
---
## Use when
- You build or change a command-line tool and want its documented usage checked like tests.
- Output, exit codes and error messages are part of the product.
## Do not use when
- The output includes times or absolute paths and you cannot normalise them; use patterns or a different assertion.
- The tool is a library; use ordinary unit tests.
## Set up
- Rust: `cargo add --dev trycmd`, and `tests/cli.rs` containing `#[test] fn cli() { trycmd::TestCases::new().case("tests/cmd/*.toml").case("README.md"); }`.
- Any language: `scrut` (Markdown or `.t` files, `scrut test file.md`) or Python `cram` (`pip install cram`, `cram tests/*.t`).
## Minimal example
A cram or scrut file (`tests/basic.t`): commands indented with `$ `, expected output below, and `(re)` for a regex line.
```
$ mytool --version
mytool 1.2.3
$ mytool add 2 3
5
$ mytool add x 3
error: 'x' is not a number
[2]
```
`[2]` is the expected exit status. Record the file by running the tool BEFORE changing it and reading the output yourself. Write error cases too: what the user sees when it fails is part of the contract. trycmd writes new expectations when run with `TRYCMD=overwrite`; use that only to accept an intended change.
## Run
`scrut test tests/basic.t` or `cram tests/basic.t` or `cargo test --test cli`
Passing looks like: a summary of passed tests and exit 0. Failure prints a diff of expected against actual output and exits 1.
## As a contract check
```json
{"id": "cli-transcripts", "claim": "CLI behaviour matches the recorded transcripts", "kind": "general", "rung": 4,
"cmd": "cargo test --test cli", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Only the invocations recorded. A flag nobody wrote a case for is not covered.
- Transcripts record what the program printed, not what it should have printed. Review expected output as you would a spec.
- Overwrite modes pass anything; look at the `git diff` of the transcript files.
- Not run here (none of these tools is installed). The trycmd and scrut forms are from their READMEs; the `cram` syntax and the `[2]` exit-status line are from memory; test them on a trivial file first.
- Check the check: change an output string in the tool and confirm a diff.
@@ -0,0 +1,80 @@
---
id: contract-testing-pact
title: Consumer-driven contract tests between services (Pact)
answers: Does the service I changed still satisfy what each of its consumers expects?
rung: 3
section: real-world
languages: javascript, typescript, python, java, go, rust
kinds: general
cost: high
detect:
ran_here: no
verified: docs
---
## Use when
- Two services talk over HTTP or messages, owned by different people, and integration tests are slow or flaky.
- You change a provider's response, or a consumer's request, and need to know who breaks.
## Do not use when
- One codebase owns both sides and a type checker covers the interface. A shared schema check (`api-breaking-schema`) is cheaper.
- You only need one end-to-end flow; use `e2e-playwright` or `smoke-after-deploy`.
## Set up
JavaScript/TypeScript (pact-js, current release 17.x; needs Node 16 or newer): `npm install --save-dev @pact-foundation/pact`. Other languages: `pip install pact-python` (4.x), and the Pact libraries for Java, Go and Rust (see docs.pact.io). The Python, Go and Rust APIs differ from the JavaScript one below; use the library's own README. Decide where contracts are stored: a Pact Broker, or a committed `pacts/` directory.
## Minimal example
Consumer side: describe one interaction in a test, run it against Pact's mock server, which writes a contract file to `pacts/` when the test passes. Provider side: replay every consumer's contract against the real provider. From the pact-js README (the `PactV3` and `MatchersV3` classes are the current consumer API):
```ts
import { PactV3, MatchersV3 } from '@pact-foundation/pact';
import path from 'path';
const provider = new PactV3({
dir: path.resolve(process.cwd(), 'pacts'),
consumer: 'MyConsumer',
provider: 'MyProvider',
});
it('returns user 1', () => {
provider
.given('user 1 exists')
.uponReceiving('a request for user 1')
.withRequest({ method: 'GET', path: '/users/1' })
.willRespondWith({
status: 200,
headers: { 'Content-Type': 'application/json' },
body: { id: MatchersV3.integer(1), name: MatchersV3.like('Ada') },
});
return provider.executeTest(async (mockserver) => {
const res = await fetch(`${mockserver.url}/users/1`); // replace with your real client
expect((await res.json()).name).toBe('Ada');
});
});
```
Provider verification (also from the README; `Verifier` is the provider interface):
```ts
import { Verifier } from '@pact-foundation/pact';
await new Verifier({
providerBaseUrl: 'http://localhost:8081', // your provider, already running
pactUrls: [path.resolve(process.cwd(), 'pacts/MyConsumer-MyProvider.json')],
stateHandlers: { 'user 1 exists': async () => { /* insert user 1 */ } },
}).verifyProvider();
```
Use `like()`-style matchers instead of exact values so only the structure is pinned. Run verification on the provider before merging a provider change.
## Run
Consumer: your normal test command (it writes the contract). Provider: the test file above, run by your test runner (`npm run test:pact:provider`, a script you define). Passing looks like: every interaction verified and the test passes (exit 0). Failure: `verifyProvider()` rejects, so the test fails with the interaction and mismatched field in the output. A state name missing from `stateHandlers` is a provider setup gap to fix, not a pass. With a Broker, `publishVerificationResult` should be on only in CI.
## As a contract check
```json
{"id": "pact-provider", "claim": "The provider satisfies all consumer contracts", "kind": "general", "rung": 3,
"cmd": "npm run test:pact:provider", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"}
```
## What a pass does not prove
- Only interactions consumers wrote down. A consumer using a field it never put in a contract is not protected.
- Matching structure is not matching meaning.
- Not run here (no Pact libraries installed); the snippets follow the pact-js README and docs (docs/consumer.md, docs/provider.md). The API changes between major versions, so confirm names against the installed version.
- Pending pacts (`enablePending: true`) make a new contract not fail the provider build; do not enable them in a gating check.
- Provider states that set up fake data can hide real-data issues.
- Check the check: remove a field from the provider response in a scratch copy and see the verification fail.
@@ -0,0 +1,60 @@
---
id: cross-platform-matrix
title: Running build and tests on the other operating systems in CI
answers: Does this also work on Windows and macOS, not just on the Linux machine I tested on?
rung: 3
section: real-world
languages: any
kinds: general
cost: medium
detect: gh --version
ran_here: no
verified: docs
---
## Use when
- The software ships for more than one OS, or touches paths, file permissions, line endings, case sensitivity, processes, sockets or the clock.
- You changed anything that reads or writes files, spawns processes or draws a UI.
## Do not use when
- The product is Linux-server-only and says so. Then a matrix is cost without benefit.
- You cannot reach CI. Say so; a Linux pass does not support a claim about other systems.
## Set up
Use the CI provider's hosted runners. For GitHub Actions the labels are `ubuntu-latest` (or a pinned `ubuntu-24.04`), `windows-latest` and `macos-latest`. Pin versions where results must not drift.
## Minimal example
`.github/workflows/matrix.yml`
```yaml
name: matrix
on: [push, pull_request]
jobs:
test:
strategy:
fail-fast: false # one OS failing must not hide the others
matrix:
os: [ubuntu-24.04, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- run: cargo test --locked
shell: bash
```
Write the platform code with the differences in mind and test them: `#[cfg(unix)]` for permission bits (a read-only folder cannot be made on Windows; use the read-only attribute), path separators, `\r\n`. A test that cannot run on one OS must be skipped explicitly with a reason, never silently.
After pushing, read the result: `gh run list --branch "$(git branch --show-current)"` and `gh run view <id> --log-failed`.
## Run
Push and wait for the workflow. Passing looks like: every matrix job green (`gh run view` shows `✓` for each OS). Failure: a red job named after the OS; read its log, do not rerun until green.
## As a contract check
```json
{"id": "ci-matrix", "claim": "Tests pass on Linux, Windows and macOS in CI for this commit", "kind": "general", "rung": 3,
"cmd": "gh run list --commit $(git rev-parse HEAD) --workflow matrix.yml --json conclusion --jq '.[0].conclusion' | grep -x success", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
```
## What a pass does not prove
- Only the OS versions of the hosted runners, with their tools. Real desktops differ (graphics, locale, antivirus).
- Skipped tests are invisible in a green run. Count them in the log.
- GUI pixel comparisons differ across OS renderers; compare structure or shapes there (`visual-regression-native-gui`).
- Not run here: no CI access in this session; the workflow syntax is standard GitHub Actions, the `gh` commands were not executed.
- Check the check: confirm the workflow file actually lists the OSes, and that `gh run list` returns a run for this commit rather than nothing.
@@ -0,0 +1,61 @@
---
id: doc-tests-and-links
title: Doctests, compiled examples and link checking
answers: Do the examples in the docs and comments still run, and do the links still resolve?
rung: 3
section: real-world
languages: rust, python, any
kinds: general
cost: low
detect: cargo --version
ran_here: yes
verified: ran
---
## Use when
- You wrote or changed documentation, a README, or a doc comment that contains code or links.
- You change a public function: the examples that show it must still compile and give the stated result.
## Do not use when
- The examples need unavailable services. Mark them (`no_run` in Rust) so they at least compile, and say so.
## Set up
- Rust: `cargo test --doc` compiles and runs each fenced example in doc comments and in the crate's README when included with `#![doc = include_str!("../README.md")]`.
- Python: `python3 -m doctest -v file.py` or `pytest --doctest-modules`.
- Links: `lychee` (https://github.com/lycheeverse/lychee) checks Markdown and HTML links; `lychee --offline` checks local file links only.
## Minimal example
```rust
/// Adds two numbers.
///
/// ```
/// assert_eq!(mycrate::add(2, 2), 4);
/// ```
pub fn add(a: i32, b: i32) -> i32 { a + b }
```
```python
def f(x):
"""
>>> f(2)
4
"""
return x * 2
```
Make the example the real documentation of behaviour: assert results, not just calls. Check docs build without broken intra-doc links: `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps` (see `zero-warnings`).
## Run
`cargo test --doc`, `python3 -m doctest file.py`, `lychee --offline README.md docs/`
Passing looks like: `test result: ok` (Rust), no output and exit 0 (Python doctest), `0 errors` (lychee). Failure: Rust marks `test src/lib.rs - add (line 3) ... FAILED`; Python prints `***Test Failed*** 1 failure` and exits 1. Both ran here; lychee was not usable here, so its output is from its README.
## As a contract check
```json
{"id": "doctests", "claim": "All documentation examples compile and pass", "kind": "general", "rung": 3,
"cmd": "cargo test --doc", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Examples with no assertion pass when they only run. `0 passed` also appears when there are no doctests at all; require a count above zero.
- An external link that answers 200 can still point to the wrong page. Network link checks are flaky; run them separately from the main gate.
- Prose can still be wrong. Only code and links are tested.
- Check the check: change an expected value and see the failure (done here with Rust and Python).
+56
View File
@@ -0,0 +1,56 @@
---
id: e2e-playwright
title: End-to-end browser tests against the running app (Playwright)
answers: Can a user actually do this task in the real running app in a real browser?
rung: 3
section: real-world
languages: javascript, typescript, python
kinds: ui, general
cost: medium
detect: npx playwright --version
ran_here: yes
verified: ran
---
## Use when
- A claim is about a user flow: sign in, add to cart, save a form, see the result.
- Unit tests pass but you have not seen the pieces work together through the real UI.
## Do not use when
- The claim is about a calculation or a rule; a unit or property test is faster and more precise.
- The flow depends on third-party services you cannot fake; stub them at the network layer (`page.route`) and say you did.
## Set up
```sh
npm i -D @playwright/test && npx playwright install chromium
```
Let Playwright start the app so the test never runs against a stale server: in `playwright.config.ts` set `webServer: { command: 'npm run start', url: 'http://localhost:3000', reuseExistingServer: false }` and `use: { baseURL: 'http://localhost:3000' }`. Use a fresh test database or fixture each run.
## Minimal example
```ts
import { test, expect } from '@playwright/test';
test('a visitor can add a note', async ({ page }) => {
await page.goto('/');
await page.getByRole('textbox', { name: 'Note' }).fill('buy milk');
await page.getByRole('button', { name: 'Add' }).click();
await expect(page.getByRole('listitem')).toHaveText('buy milk'); // asserts the result, not just that the click worked
});
```
Locate by role and accessible name, not CSS classes, so the test survives restyling. Assert on what the user sees after the action. For a bug fix, write the test so it fails on the old code first.
## Run
`npx playwright test`
Passing looks like: `N passed`, exit 0. Failure shows the failing step, a trace (`--trace on` then `npx playwright show-trace`), and exit 1. A web server that fails to start makes the run fail, not pass. (Run here against a static page served by `python3 -m http.server`.)
## As a contract check
```json
{"id": "e2e", "claim": "The add-note flow works in a real browser", "kind": "ui", "rung": 3,
"cmd": "npx playwright test", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Only the paths you scripted, in one browser. Add projects for Firefox and WebKit when it matters.
- Flaky tests tempt retries. A test that passes only on retry is failing sometimes; fix the wait (assert on a visible state) instead of adding `retries`.
- `expect(...).toBeVisible()` alone proves little; assert the content or effect.
- Check the check: break the feature (remove the handler) and confirm the test fails.
+63
View File
@@ -0,0 +1,63 @@
---
id: lighthouse-budget
title: Lighthouse CI budgets and score assertions
answers: Is this page still within its performance, accessibility and best-practice budgets?
rung: 4
section: real-world
languages: javascript, any
kinds: ui
cost: medium
detect: npx lhci --version
ran_here: no
verified: docs
---
## Use when
- Page weight, load time or Lighthouse scores matter and you changed scripts, images, fonts or markup.
- You want a number with a limit, checked on every change.
## Do not use when
- The page needs a login you cannot script around; Lighthouse measures a single loaded page.
- You want a verdict on user experience. Scores are a proxy.
## Set up
```sh
npm i -D @lhci/cli
```
Create `lighthouserc.json`. Run it in an environment you can repeat (a CI container); local laptops give different timings.
## Minimal example
`lighthouserc.json`
```json
{
"ci": {
"collect": { "url": ["http://localhost:3000/"], "numberOfRuns": 3, "startServerCommand": "npm run start" },
"assert": {
"assertions": {
"categories:performance": ["error", { "minScore": 0.9 }],
"categories:accessibility": ["error", { "minScore": 1 }],
"total-byte-weight": ["error", { "maxNumericValue": 500000 }]
}
}
}
}
```
Several runs and the median handle noise. Prefer hard resource budgets (bytes, request counts), which do not wobble, over timing metrics. Record the current scores BEFORE you edit so you know the margin. `lhci assert --preset=lighthouse:recommended` is available as a starting set and individual assertions can be switched off (`--assertions.uses-webp-images=off`).
## Run
`npx lhci autorun` (collect, assert, upload), or `npx lhci collect && npx lhci assert`.
Passing looks like: all assertions pass and exit 0. Failure prints each failed assertion with expected and actual values and exits nonzero.
## As a contract check
```json
{"id": "lighthouse", "claim": "The home page meets its Lighthouse budgets", "kind": "ui", "rung": 4,
"cmd": "npx lhci autorun", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600}
```
## What a pass does not prove
- Lab results on one URL and one machine, not real users' devices and networks.
- Timing scores vary between runs; a pass on three runs is not a guarantee.
- Lowering a threshold to pass is a change to review, as in `ratchet-floor`.
- Not run here (`lhci` is not installed). `lhci assert`, `--preset` and `--assertions` appear in the Lighthouse CI configuration docs; the JSON shape follows those docs.
- Check the check: set `minScore` to 1 on performance and confirm it can fail.
+61
View File
@@ -0,0 +1,61 @@
---
id: load-test-k6
title: Load tests with pass/fail thresholds (k6)
answers: Does the service stay fast and correct under the load it must handle?
rung: 3
section: real-world
languages: any
kinds: general
cost: medium
detect: k6 version
ran_here: no
verified: docs
---
## Use when
- You changed a query, cache, index, lock or request path and need to show it holds under concurrency.
- A latency or error-rate promise exists (a service level objective).
## Do not use when
- The service has no stated target; invent none. Ask for one, or compare before and after instead.
- You would point it at a production system or one you do not own. Test a copy.
## Set up
Install k6 (https://grafana.com/docs/k6/latest/set-up/install-k6/). Run the system under test locally or in a staging copy with realistic data volume.
## Minimal example
`load.js`
```js
import http from 'k6/http';
import { check } from 'k6';
export const options = {
vus: 20, duration: '30s',
thresholds: {
http_req_failed: ['rate<0.01'], // under 1 % errors
http_req_duration: ['p(95)<300'], // 95 % of requests under 300 ms
},
};
export default function () {
const res = http.get('http://localhost:3000/api/items');
check(res, { 'status is 200': (r) => r.status === 200, 'has items': (r) => r.json().length > 0 });
}
```
Thresholds are what make this a check: if any is crossed, k6 exits nonzero. Checks (`check`) alone only count and do not fail the run, so also put `checks: ['rate>0.99']` in `thresholds`. Run once against the unchanged system first and record the numbers.
## Run
`k6 run load.js`
Passing looks like: every threshold line marked with a tick (`✓`) and exit 0. Failure marks the threshold `✗` and exits with code 99.
## As a contract check
```json
{"id": "load", "claim": "p95 latency under 300 ms and under 1% errors at 20 users", "kind": "general", "rung": 3,
"cmd": "k6 run load.js", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300}
```
## What a pass does not prove
- Only the traffic mix you scripted. Real users behave differently.
- The load generator and the system share a machine in a local test; results are optimistic. Record where it ran.
- Not run here (`k6` is not installed). Thresholds and their behaviour come from the k6 documentation; the exit code 99 is from memory.
- Passing latency does not show the responses were right; keep the `check` calls and a threshold on them.
- Check the check: set `p(95)<1` and confirm the run fails.
@@ -0,0 +1,60 @@
---
id: multi-user-isolation
title: Proving one account cannot read another's data
answers: Can user B see, change or guess user A's data through any door the product offers?
rung: 3
section: real-world
languages: any
kinds: general
cost: medium
detect:
ran_here: no
verified: docs
---
## Use when
- The product has accounts, tenants, workspaces or roles, and a leak between them would be serious.
- You added an endpoint, a query, an export, a search index, a cache or a background job that touches stored data.
## Do not use when
- A single-user tool with no sharing. Use `read-only-guarantee` if the concern is accidental writes.
## Set up
Two layers, as a Rust project did them in a CI workflow (`two-user.yml`) and an integration test (`two_user.rs`):
1. Operating-system layer. A system account `appsvc` runs the server and owns the data root; the root is created mode `0700` (`sudo install -d -o appsvc -g appsvc -m 0700 /srv/appdata`). The test runs as a different account (the CI runner) and must be refused.
2. Network layer. The server listens only on loopback (`--http 127.0.0.1:PORT`) with `--isolation enforced`; each book has its own bearer token, minted by the server (`token create --book acme --name ci`, stored in a 0600 file under the root). The test reaches the data only through that door, with the token.
For a product with accounts rather than OS users, the same idea: create accounts A and B with distinctive data (`ALPHA-SECRET-1`) and make every request as B using only B's credentials.
## Minimal example
What the reference test asserts as the agent account, in Rust: `std::fs::read_dir(tenant_root)` and `File::open(tenant_root/books/<book>/journal.jsonl)` must both fail with `ErrorKind::PermissionDenied` (the test checks the error kind, so a missing path does not pass as "refused"); then `books.start` over HTTP with the token must report `isolation` equal to `service_user (enforced)`, and a read, a write, an upload and an export must still work through that door (the account is shut out of the files, not out of the product). Separate tests check that `--http` rejects non-loopback addresses and that books moved to the server keep their head hash.
A generic web-API version of the cross-account cases (not from the reference project):
```sh
# As user B, ask for A's record by every route: direct id, list, search, export, attachment URL.
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $TOKEN_B" "$BASE/api/records/$A_RECORD_ID" # expect 403 or 404
curl -s -H "Authorization: Bearer $TOKEN_B" "$BASE/api/records?q=ALPHA-SECRET" | grep -c ALPHA-SECRET || true # expect 0
```
Also test: no credentials at all (401), a tampered or expired token, writing to A's record as B (must change nothing; check A's record afterwards), and listing endpoints returning only B's rows. Write every case with a distinctive value and assert its absence from every response body, not only the status code.
## Run
The reference job builds the server, creates the accounts and directories, starts two servers, then runs, as the agent account, with the deployment given in `TWO_USER_TEST=1`, `APP_TENANT_ROOT`, `APP_SERVER_URL`, `APP_BOOK`, `APP_TOKEN` and related variables:
cargo test -p app-cli --test two_user -- --nocapture --test-threads=1
Passing looks like: both tests ran and passed. Without `TWO_USER_TEST` each test prints `SKIPPED ...` and returns, which cargo counts as a pass, so a laptop run proves nothing: require that the output contains no `SKIPPED`. Failure: a panic such as "this account can read the tenant root". For a web API, your own script: every forbidden access returns 403, 404 or 401, the secret strings appear in no response, and A's data is byte-identical afterwards.
## As a contract check
```json
{"id": "isolation", "claim": "Account B cannot read or modify account A's data through the API", "kind": "general", "rung": 3,
"cmd": "sh tests/isolation.sh", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"}
```
For the reference-style OS check, make the script fail on a `SKIPPED` line in the cargo output.
## What a pass does not prove
- Only the doors you tried. Enumerate every endpoint from the route list or the tool list, and test each as B.
- Insecure direct object references hide in ids that are guessable; also try other users' ids from a list you did not get from the API.
- Not run here. `verified: docs` means this entry was checked against the reference project's workflow file and test source, which it describes accurately; the generic curl cases are not taken from it, and the project's two-user test does not try one account's token against another account's book.
- A shared cache or search index can leak even when the database is separate. Include them.
- Check the check: temporarily remove the authorisation check and confirm the test fails.
@@ -0,0 +1,54 @@
---
id: packaging-install-upgrade
title: Install and upgrade real packages in containers across distributions
answers: Can a user install this package, open their data, upgrade, and still have their data intact?
rung: 3
section: real-world
languages: any
kinds: general, migration
cost: high
detect: docker --version
ran_here: no
verified: docs
---
## Use when
- You ship `.deb`, `.rpm`, Arch packages, installers or a self-update path.
- Version N+1 changes a file format or a data directory, and users have data from version N.
## Do not use when
- You ship only a container image or a library; test the image directly or use `clean-clone-build`.
## Set up
Build the old and the new package. For each target distribution, start a clean container (Debian, Fedora, Arch images are enough) with the package directory mounted read-only. Create an ordinary user in the container: installs run as root, data belongs to a user.
## Minimal example
The pattern, as used in a reference project (`deploy/packaging/test-linux-packages.sh`), per distribution:
```sh
docker run --rm -v "$PWD/target/packages:/packages:ro" debian:trixie-slim bash -c '
set -euo pipefail
useradd -m tester
apt-get install -y /packages/mytool_0.1.0_amd64.deb
su tester -c "mytool setup && mytool create demo"
before=$(su tester -c "mytool list")
apt-get install -y /packages/mytool_0.1.1_amd64.deb # the upgrade
after=$(su tester -c "mytool list")
[ "$before" = "$after" ]'
```
Check things that break in practice: the data's head or checksum is unchanged, a long-running process restarts onto the new binary (`readlink /proc/$pid/exe` must not say `(deleted)`), the self-updater refuses when a package manager owns the install, and uninstall leaves user data alone. Repeat with `fedora:latest` (`dnf install`) and `archlinux:latest` (`pacman -U`).
## Run
Your script, once per distribution. Passing looks like: exit 0 in every container and the same data summary before and after. Failure: a nonzero exit with the failed assertion; keep the container logs.
## As a contract check
```json
{"id": "pkg-upgrade", "claim": "Install, open data, upgrade: data is unchanged on Debian, Fedora and Arch", "kind": "general", "rung": 3,
"cmd": "sh deploy/test-packages.sh", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 3600}
```
## What a pass does not prove
- Only the distributions and versions tested. Other package managers and init systems differ.
- Real user data is richer than your demo data; use an anonymised copy from an old version when you can.
- Docker's default seccomp and missing systemd can change behaviour; services that need them need `--privileged` or a VM, which weakens isolation.
- Not run here (no packages to build). The shape comes from the reference project's script; Docker and the base images are installed on this machine.
- Check the check: corrupt the data in the new package's migration and see the comparison fail.
@@ -0,0 +1,53 @@
---
id: runtime-self-check
title: Give the product its own verify or doctor command and run it as a check
answers: Does the product's own data pass its own integrity checks (hash chain, control totals, invariants)?
rung: 3
section: real-world
languages: any
kinds: money, state-machine, general
cost: medium
detect:
ran_here: yes
verified: ran
---
## Use when
- The product holds data whose consistency can be checked from the data alone: a journal with a hash chain, ledgers whose debits equal credits, counters that must add up to a stored total, foreign keys that must resolve.
- You want the same check to run in tests, after a migration, after a restore, in CI and in production.
## Do not use when
- There is no invariant to check. A `verify` command that always prints OK is worse than none.
## Set up
Add a command, for example `mytool verify [--data DIR]`, that reads the data and checks invariants without writing anything (see `read-only-guarantee`). Make it exit 0 when all hold and nonzero with a specific message for each broken one. Typical checks: each record's hash includes the previous hash; sum of debits equals sum of credits; row counts match a stored control total; no orphan references; every file referenced exists.
## Minimal example
A hash-chained log, with `verify` as a few lines of shell:
```sh
# each line: <prev-hash> <payload>; the next line's prev-hash must be sha256 of the whole previous line
prev=GENESIS
while IFS= read -r line; do
[ "${line%% *}" = "$prev" ] || { echo "chain broken at: $line"; exit 1; }
prev=$(printf '%s' "$line" | sha256sum | cut -d' ' -f1)
done < journal.log
echo "chain ok"
```
Run it on good data, then edit one payload byte in a copy and confirm it fails (done here: a tampered line printed `chain broken at:` and exited 1). Then use it as a check wherever data changes: after a migration (`db-migration-safety`), after an upgrade (`packaging-install-upgrade`), after a restore. The owner's reference project exposes this as a `verify` tool and runs it in migration and hostile-input tests, asserting the books still verify afterwards.
## Run
`mytool verify --data data/` or the script above.
Passing looks like: `chain ok` (or the product's own summary) and exit 0. Failure: a message naming the first broken record, exit 1.
## As a contract check
```json
{"id": "self-verify", "claim": "The data directory passes the product's own integrity check", "kind": "general", "rung": 3,
"cmd": "mytool verify --data tests/fixtures/books", "expect": {"exit": 0, "stdout_contains": "ok"}, "tier": "deep", "timeout_s": 120}
```
## What a pass does not prove
- Only the invariants coded into `verify`. If a bug writes data that satisfies the checker, the checker passes. Keep the invariants independent from the write path.
- A hash chain shows tampering or corruption after the fact; it does not show the entries were correct.
- A verify that runs on an empty fixture proves nothing; use data with every kind of record.
- Check the check: corrupt one record in a copy and confirm failure.
@@ -0,0 +1,50 @@
---
id: smoke-after-deploy
title: Post-deploy smoke checks and health endpoints
answers: Is the thing I just deployed actually up and serving correct responses?
rung: 3
section: real-world
languages: any
kinds: general
cost: low
detect: curl --version
ran_here: yes
verified: ran
---
## Use when
- You deployed, released or restarted a service and are about to say it is live.
- You want a small set of fast checks that run after every deploy and after rollback.
## Do not use when
- You need deep correctness; smoke checks only show it is alive and wired.
- You cannot reach the deployed URL; then say what you could not check.
## Set up
Have a health endpoint (for example `/healthz`) that checks real dependencies (database reachable, migrations applied), not just that the process is up. Know the version string the deploy should now report, so you can tell the new build from the old one.
## Minimal example
```sh
BASE=https://app.example.com
expected=$(git rev-parse --short HEAD)
curl -fsS --max-time 10 --retry 5 --retry-delay 3 --retry-connrefused "$BASE/healthz" | tee /tmp/health.json
curl -fsS "$BASE/version" | grep -q "$expected" # the new build is the one answering
curl -fsS -o /dev/null -w '%{http_code}\n' "$BASE/" | grep -qx 200
curl -fsS "$BASE/api/items?limit=1" | python3 -c 'import json,sys; json.load(sys.stdin)' # one real read that parses
```
`-f` makes curl fail on HTTP errors (4xx, 5xx), which is what turns the check into an exit code. `--retry` gives a starting service time. Add one write-and-read round trip against a test account if the service has state. Keep the smoke set under a minute.
## Run
The commands above, as a script with `set -e`. Passing looks like: exit 0, the health JSON shows each dependency `ok`, and the version matches. Failure: curl exits 22 (HTTP error), 28 (timeout) or 7 (connection refused); `grep` exits 1 when the version is old.
## As a contract check
```json
{"id": "smoke", "claim": "The deployed service is healthy and serving the new build", "kind": "general", "rung": 3,
"cmd": "sh scripts/smoke.sh https://app.example.com", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120}
```
## What a pass does not prove
- Only the endpoints probed. A healthy `/healthz` can sit in front of a broken checkout page.
- A load balancer may send you to one healthy instance while another is bad; probe more than once.
- A cached or CDN-served response can mask a failed deploy. The version check is what shows the new build is live.
- Check the check: point it at a wrong path (`/nope`) and confirm `curl -f` exits 22 (run here against a local server: 22 for the missing path, 7 for a refused connection; the full script was not run against a real deployment).
@@ -0,0 +1,60 @@
---
id: tool-description-lint
title: Linting tool descriptions and help text for misleading instructions
answers: Do this tool's descriptions and help text tell an agent anything false, missing or contradictory?
rung: 3
section: real-world
languages: any
kinds: general
cost: low
detect: python3 --version
ran_here: yes
verified: ran
---
## Use when
- You write or change tool descriptions for an MCP server, `--help` text, error messages or prompts that an agent reads and acts on.
- You rename or remove a tool and need every mention of it found.
## Do not use when
- You want to judge whether the text is persuasive or clear to a model. A lint finds mechanical errors only; use a rubric review or `agent-surface-evals`.
## Set up
Dump the tool list as JSON (for MCP, the result of `tools/list`; for a CLI, the output of each `--help`). Write the rules as a small script and keep it in the repo. Useful rules: every tool named in a description exists; a tool marked read-only does not say it creates, saves or deletes; every required parameter has a description; no description is empty or over a stated length; examples in descriptions parse against the input schema.
## Minimal example
`tests/lint_tools.py` (ran here against a two-tool list)
```python
import json, re, sys
tools = json.load(open(sys.argv[1]))["tools"]
names = {t["name"] for t in tools}
bad = []
for t in tools:
d = t.get("description", "")
for ref in re.findall(r"\b[a-z_]+\.[a-z_]+\b", d):
if ref not in names and ref.split(".")[0] in {n.split(".")[0] for n in names}:
bad.append(f"{t['name']}: description names unknown tool {ref}")
if t.get("annotations", {}).get("readOnlyHint") and re.search(r"\b(creates?|deletes?|saves?|writes?|updates?)\b", d, re.I):
bad.append(f"{t['name']}: readOnlyHint tool description talks about writing")
for p in t["inputSchema"].get("required", []):
if not t["inputSchema"]["properties"].get(p, {}).get("description"):
bad.append(f"{t['name']}: required parameter {p} has no description")
print("\n".join(bad) or "tool text ok"); sys.exit(1 if bad else 0)
```
## Run
`python3 tests/lint_tools.py tools.json`
Passing looks like: `tool text ok` and exit 0. Failure lists each problem, one per line, and exits 1, for example `books.show: description names unknown tool books.post_entry`.
## As a contract check
```json
{"id": "tool-text-lint", "claim": "Tool descriptions name only existing tools and match their annotations", "kind": "general", "rung": 3,
"cmd": "python3 tests/lint_tools.py tests/tools.json", "expect": {"exit": 0, "stdout_contains": "tool text ok"}, "timeout_s": 60}
```
## What a pass does not prove
- Only the rules you wrote. A description can be mechanically clean and still send an agent the wrong way.
- The regex for write words has false positives and misses synonyms; treat each hit as a question to a human.
- A stale `tools.json` passes against an old tool list. Regenerate it from the running server in the same check.
- Check the check: add a reference to a tool that does not exist and confirm failure (done here).