commit 2fc1fe9c2de7ad8dc6109f4fd6c5933b96076103 Author: Stephen Waits Date: Sun Nov 22 22:29:02 2026 -0700 sisi 0.1.0: a shared rulebook and verification tool for AI coding agents 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 diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..d819371 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{json,yml,yaml}] +indent_size = 2 + +[*.md] +indent_size = 2 +trim_trailing_whitespace = false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c05ea8c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,28 @@ +name: ci + +on: + push: + pull_request: + +jobs: + test: + name: tests (${{ matrix.os }}, python ${{ matrix.python }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + python: ["3.9", "3.11", "3.13"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - name: Git identity (some tests make commits) + run: | + git config --global user.name ci + git config --global user.email ci@users.noreply.github.com + - name: Test suite + run: python -W ignore::ResourceWarning -m unittest discover -s tests + - name: Verifier library lint + run: bin/sisi verifiers lint diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..89907f7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +# Python caches +__pycache__/ +*.pyc +*.pyo +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ + +# sisi run-time state in a project: only the contract is tracked +.sisi/* +!.sisi/contract.json + +# scratch for delegated work +.agent-work/ + +# editors and operating systems +.idea/ +.vscode/ +*.swp +*.swo +*~ +.DS_Store +Thumbs.db diff --git a/.sisi/contract.json b/.sisi/contract.json new file mode 100644 index 0000000..c765f4d --- /dev/null +++ b/.sisi/contract.json @@ -0,0 +1,44 @@ +{ + "id": "sisi-phase1", + "goal": "sisi phase 1 works: CLI, store, contracts, gate, wiring, audit", + "checks": [ + { + "id": "unit-tests", + "claim": "the whole test suite passes (wiring and gate property tests included)", + "kind": "general", + "rung": 3, + "cmd": "python3 tests/run_parallel.py", + "expect": { + "exit": 0 + }, + "timeout_s": 60 + }, + { + "id": "library-lint", + "claim": "every verifier and recipe lints clean, and recipes cite only existing verifier ids", + "kind": "general", + "rung": 3, + "cmd": "bin/sisi verifiers lint", + "expect": { + "exit": 0 + }, + "timeout_s": 20 + } + ], + "invariants": [ + { + "id": "launcher-help", + "claim": "the launcher still prints help", + "cmd": "bin/sisi help", + "expect": { + "exit": 0, + "stdout_contains": "sisi verify" + }, + "timeout_s": 20 + } + ], + "assumptions": [ + "Tests never touch the real home: SISI_HOME and SISI_STATE point to temp dirs." + ], + "questions": [] +} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..3338cba --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,34 @@ +# Changelog + +All notable changes to this project are recorded here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses +[Semantic Versioning](https://semver.org/). + +## [0.1.0] - 2026-11-22 + +First public release. + +### Added + +- A rulebook (`canon/core.md`, at most 120 lines) shared by every tool, plus minimum-rung floors for kinds of + claim that may not rest on example tests alone (`canon/floors.json`). +- Contracts: `sisi contract init | check | waive | trust | untrust`, and `sisi verify` with fast and deep tiers, + parallel checks, per-check time limits and a record of every result. +- An end-of-turn gate (`sisi gate`) that sends an agent back when a check fails or was not run, and a + session-start hook (`sisi tick`). The gate blocks in Claude Code only. +- Wiring by reference for Claude Code, Codex and OpenCode: `sisi install`, `uninstall`, `doctor`, `audit`. +- A verifier library of 140 techniques across ten sections, and 20 "what done means" recipes, with + `sisi verifiers` (list, show, for, doctor, lint) and `sisi done`. +- Retrospectives and shared lessons (`sisi retro`, `sisi lessons`), human-stated preferences held in quarantine + (`sisi learn`), and time to delivery (`sisi time`, `sisi status`). +- Product and personal data kept apart: a personal folder with its own git history, an overlay of learned changes + to rules, verifiers and recipes, `sisi update`, `export`, `import`, `migrate`. +- Releases for people who both use and develop sisi (`sisi release`, `rollback`, `dev`, `promote`). +- A data layer for learning from past sessions: harvest of Claude Code transcripts, a task set, escape + candidates, check statistics and a weekly scoreboard. +- `sisi --version` and `sisi version`. + +### Not included + +- The build conductor (`sisi build`, `sisi inbox`) and the model-driven learning loop are designed in + `docs/design.md` and not built. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..f682b4e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,58 @@ +# Contributing + +Thanks for looking. sisi is small on purpose; this page says how to change it safely. + +## Run the tests + + python3 tests/run_parallel.py # every test file in its own process, side by side + python3 -W ignore::ResourceWarning -m unittest discover -s tests # the same tests, one at a time + bin/sisi verifiers lint + bin/sisi verify # runs the same two checks through sisi's own contract (.sisi/contract.json) + +Side by side the suite takes well under a minute on an idle machine; one at a time, a minute or two. Tests never touch your real home folder: they point `SISI_HOME` and `SISI_STATE` +at temporary directories, and a test fails at once if a path resolves outside them. Set `SISI_TEST_ITERS=10` to +run the property tests with more iterations. + +A pull request should pass all three. If you fix a bug, add a test that fails without the fix. + +## Rules for the code + +- Standard library only. No third-party packages, no build step, no install step beyond cloning. This is what + lets the tool run unchanged in any tool's hook, on any machine with Python. +- Python 3.9 or newer (see the README for how that was determined). Do not use syntax or library calls that need a + newer version. +- Hooks (`sisi tick`, `sisi gate`) must stay fast and must fail open: anything that goes wrong inside sisi lets + the agent through and is logged. +- sisi never writes into the product folder at run time. Anything it writes goes to the personal data folder or + scratch. A test enforces this. +- Do not add personal paths, names or email addresses to any file. `tests/test_public.py` fails if a home path or an + address appears. +- The rulebook, `canon/core.md`, has a hard budget of 120 lines. Change it only to improve a rule; to add one, + shorten or merge another. Each rule says why it exists. + +## Verifier and recipe entries + +The library in `verifiers/` (techniques) and `done/` (what done means for a kind of work) is the part most +worth contributing to. The exact format, the quality bar and the meaning of each field are in +[docs/verifier-format.md](docs/verifier-format.md). In short: a real tool, a minimal example you ran, the exact +command, what passing looks like, and a JSON check that can be pasted into a contract. Say honestly in the +header whether you ran it (`ran`), checked it against the tool's documentation (`docs`) or neither. Run +`bin/sisi verifiers lint` before sending it. + +## Product or personal overlay + +The product is what every user gets. Your personal overlay is what sisi learned about you. + +- Belongs in the product: a general rule, a technique or recipe that helps anyone, a bug fix, documentation. +- Belongs in your overlay: your preferences, your project names and paths, a rule that is right for you only, a + technique that depends on a private setup. + +If something started in your overlay and is general, `sisi promote ` shows what it would write into the source +folder after removing your paths, user name and email addresses (dry run unless `--apply`). Read the result +before you commit it. See [docs/developing.md](docs/developing.md) and [docs/personal-data.md](docs/personal-data.md). + +## Reporting problems + +Bugs and ideas go in GitHub issues. Security problems do not: see [SECURITY.md](SECURITY.md). + +By contributing you agree that your contribution is licensed under the MIT licence of the project. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..1c20050 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Stephen Waits + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..81fbbbf --- /dev/null +++ b/README.md @@ -0,0 +1,202 @@ +# sisi + +sisi is a rulebook and a small command-line tool, shared by every AI coding agent on your machine (Claude Code, +Codex, OpenCode). It makes an agent write down how success will be checked, run those checks before it says it is +done, and record afterwards how the work could have gone better. It is plain Python with no dependencies, and what +it learns about you is kept outside the clone, so updating never loses it. + +## Why it exists + +- **Agents report "done" without proof.** The definition of done is usually a sentence in an instruction file. + Nothing makes the agent write it as something runnable, and nothing stops it ending a turn when a check fails. +- **Each tool learns separately.** A lesson learned in one tool is lost to the others, and instructions drift apart + across `CLAUDE.md`, `AGENTS.md` and friends. +- **The work takes too long.** Nobody measures the time from a request to a result that is actually verified, so + nobody can tell whether a change to the instructions helped. + +## How it works + +- **A contract per piece of work.** `.sisi/contract.json` in the project lists the checks that decide success, + each with the claim it supports, a command, the result expected and its rung (below). It can also list + invariants (what must not get worse), assumptions and open questions. The agent drafts it from the request. +- **A ladder of checks.** Each check is rated by how strong the evidence is: 1 proof, model checking or the type + system; 2 property-based tests, fuzzing, comparison with a reference; 3 example tests; 4 golden files and + snapshots, including screenshots; 5 a rubric scored by an independent judge; 6 the human. The rulebook tells the + agent to use the highest rung that is feasible, and sets a minimum rung for kinds of claim that need it + (concurrency, parsing, money, state machines, data migration). +- **An end-of-turn gate.** A hook calls `sisi verify` when the agent tries to finish. If a check fails or did not + run, the agent is sent back with the failures. If a large change has no contract, it is sent back to write one. + Small edits pass. After three send-backs in a row the agent is let through and the result is marked unverified, + so a broken check cannot trap a session. Today this blocks in Claude Code only (see the table below). +- **A retrospective after each piece of work.** `sisi retro` records how the work could have gone better, against + five aims: the human could have worked at a higher level, a stronger check was possible, the human was + interrupted more than needed, the result was not what they meant, it took longer than it had to. Retros become + shared lessons (`sisi lessons`), which every tool reads. +- **Time to delivery.** Each time the gate lets a turn end, sisi records the time since the human's last typed + message, how many times it sent the agent back, and how long the checks took. `sisi time` compares the last 7 + days with the 7 before. +- **One shared store.** The rulebook, lessons, results and settings are written once and read by every tool, which + are connected by reference (an import line or a symlink), never by copy. + +## Quick start + +Requirements: Python 3.9 or newer (see "Python versions" below), and `git`. Linux and macOS are what the tests and +CI are meant to cover; Windows is not supported (the code imports `fcntl`). + + git clone https://github.com/swaits/sisi.git + cd sisi + bin/sisi install # wire sisi into the tools it finds; backs up every file it edits + bin/sisi doctor # shows what is wired in each tool + +`sisi install` links `bin/sisi` as `~/.local/bin/sisi`; make sure that folder is on your `PATH`, or call +`bin/sisi` from the clone. It edits your tools' global instruction files only by adding an import line, and +`sisi uninstall` restores the originals exactly. It skips any tool whose configuration folder does not exist. + +Now a first contract. Change to one of your own projects (not the sisi clone), where `sisi contract init --goal "slugify() turns titles into URL slugs"` creates a +skeleton whose placeholder check fails until you replace it. Replace it with a real check. Here, for a small +function and a test next to it: + + { + "id": "slugify", + "goal": "slugify() turns titles into URL slugs", + "checks": [ + { + "id": "examples", + "claim": "known titles give the expected slugs, and slugifying twice changes nothing", + "kind": "general", + "rung": 3, + "cmd": "python3 -m unittest -q test_slugify", + "expect": {"exit": 0}, + "timeout_s": 30 + } + ], + "invariants": [], + "assumptions": ["Non-ASCII letters are dropped, not transliterated."], + "questions": [] + } + +Then: + + $ sisi verify + ID KIND RUNG TIER STATUS SECS + examples general 3 fast passed 0.1 + + OK + +`sisi verify` exits 0 when every check passes, 1 when one fails, 2 when there is no contract and 3 when the +project is not trusted (see Security). With the hook installed you do not run it yourself: the agent writes the +contract, and the gate runs it at the end of each turn. + +## Which tools are supported + +| Tool | What `sisi install` does | Instructions loaded | Blocking end-of-turn gate | Session-start hook | +|---|---|---|---|---| +| Claude Code | adds an import line to `~/.claude/CLAUDE.md` and registers hooks in `~/.claude/settings.json` | yes | yes (`Stop` and `SubagentStop` hooks) | yes (`SessionStart`) | +| Codex | links `~/.codex/AGENTS.md` to the generated rulebook | yes | no: Codex hooks are documented but not built here | no | +| OpenCode | links `~/.config/opencode/AGENTS.md` to the generated rulebook | yes | no: no blocking hook has been verified | no | +| Muse | nothing: its global instruction path is unconfirmed | no | unknown | no | + +This table comes from `sisi doctor` and the wiring code (`sisi/wiring.py`). Where there is no gate, the rulebook +still tells the agent to write and run a contract, but nothing enforces it. `sisi install` is skipped for a tool +whose configuration folder is missing. Agent skills linked into `~/.agents/skills` are supported by the wiring but +the product ships none yet. + +## The verifier library + +sisi ships 140 verification techniques in ten sections (design, prove, many-inputs, concurrency, test-quality, +regression, real-world, safety, intent, completeness) and 20 recipes that say what "done" means for a kind of +work (a bug fix, a new library, a data migration, a web UI change, and so on). Each technique has a minimal +example, the exact command, what passing looks like, and a JSON check to paste into a contract. Agents query it +instead of inventing a check from memory: + + $ sisi verifiers for "a parser that must not crash on hostile input" + 1. hostile-input-from-schema rung 2 cost medium installed: no + Does every call my API or tool accepts survive wrong, missing, huge and strange arguments with a clean error and no crash? + 2. klee rung 1 cost high installed: no + Which inputs make this C program crash, overflow or break an assert, found by exploring its paths? + 3. afl-plus-plus rung 2 cost medium installed: no + Can any input make this native program or library crash, hang or trip a sanitizer? + 4. atheris rung 2 cost medium installed: no + Can any input make this Python code raise an exception it should not, hang, or crash the interpreter? + + $ sisi done for "bug fix" # prints the full recipe for that kind of work + +The chooser is keyword matching over each entry's header, so phrase the claim the way you would phrase a doubt, and +read the top few results rather than trusting the first. `sisi verifiers show ID` prints one entry in full, and +`sisi verifiers doctor` says which of the tools are installed on your machine. Format and quality bar: +[docs/verifier-format.md](docs/verifier-format.md). Most entries were run on the author's machine; the rest were checked against the +tools' documentation. Each header says which (`verified: ran | docs | memory`). + +## Where data lives, and updating + +| Place | Where | What | +|---|---|---| +| Product | the clone | code, base rulebook, verifier library, recipes, defaults. Never written at run time. | +| Personal data | `~/.local/share/sisi` (or `$SISI_DATA`) | lessons, learned changes to rules (an overlay), your preferences, settings, trusted projects. A local git repository with every change committed, never pushed. | +| Scratch | `~/.local/state/sisi` (or `$SISI_STATE`) | rebuildable: transcript index, locks, logs, results | + +`sisi update` fast-forwards the clone (`git fetch` then a fast-forward merge; it refuses if you have local +changes), takes a backup of your personal data, migrates its format if needed, reapplies your overlay to the new +rulebook and rebuilds it. If the product changed a rule you had replaced, your version is kept and queued for a +re-test. `sisi export` and `sisi import` move personal data to another machine as one archive. More: +[docs/personal-data.md](docs/personal-data.md). + +## Uninstalling + + sisi uninstall + +removes the import line, hooks and links, restoring each edited file from its backup. Your personal data and +scratch folders are left alone; delete them yourself if you want them gone. Then delete the clone. + +## Status + +Version 0.1.0, an early release. + +Works today, with tests: + +- Contracts, `sisi verify` (fast and deep tiers), the trust mechanism, the end-of-turn gate and session-start hook. +- Wiring for Claude Code (with the blocking gate), Codex and OpenCode (rulebook only), and `sisi doctor`, `audit`. +- The verifier library and recipes, with `sisi verifiers lint`. +- Retros, lessons, quarantined preferences, time to delivery, personal data, overlay, update, export and import, + releases and rollback. +- A data layer that reads past Claude Code transcripts into a local database and builds a task set, escape + candidates, per-check statistics and a weekly scoreboard (`sisi harvest`, `tasks`, `escapes`, `checks`, + `scoreboard`; these are not listed in `sisi help`). + +Designed but not built (see [docs/design.md](docs/design.md)): + +- The build conductor: `sisi build ""` turning a statement into verified work, and the question queue + (`sisi inbox`). Neither command exists. +- The model-driven learning loop: background runs, experiments on a task set, automatic shipping and removal of + rule changes, the taste judge, playbooks. The data layer above is groundwork for it; nothing acts on it yet. +- Blocking gates outside Claude Code, and harvest of transcripts from tools other than Claude Code. + +Not verified: macOS (no run yet), Python 3.9 and 3.10 by running the tests (see below), and whether Codex +and OpenCode obey the rulebook as well as Claude Code does. The library's claims about external tools are mostly +from their documentation. + +### Python versions + +The minimum is Python 3.9. This was determined by reading, not by running old interpreters. Every Python file parses +with `ast.parse(..., feature_version=(3, 8))`, and a search found no `match` statements, no `X | Y` types and no +walrus operators. The newest standard-library features in use are `shutil.copytree(..., dirs_exist_ok=True)` and +`sys.pycache_prefix`, both added in 3.8. The stated minimum is 3.9 because 3.8 is end of life and current macOS runners do not +offer it. The test suite was run here on Python 3.11 and 3.14 and passes. CI is configured for 3.9, 3.11 and 3.13 on +Linux and macOS; it has not run yet, so 3.9 and 3.10 are unconfirmed. + +## Security + +sisi runs commands that come from a project's contract. A contract in a project you did not write is untrusted +until you read it and run `sisi contract trust`; until then `sisi verify` refuses and the gate runs nothing. sisi +does not sandbox what a trusted contract runs. See [SECURITY.md](SECURITY.md), which also says how to report a +problem privately. + +## Contributing + +Tests, the standard-library-only rule, the verifier entry format and what belongs in the product versus your own +overlay are in [CONTRIBUTING.md](CONTRIBUTING.md). A change log is in [CHANGELOG.md](CHANGELOG.md), and all docs are +indexed in [docs/README.md](docs/README.md). + +## Licence + +MIT. Copyright (c) 2026 Stephen Waits. See [LICENSE](LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..1d80d28 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,33 @@ +# Security + +## What sisi runs, and when + +sisi's end-of-turn hook and `sisi verify` run shell commands. The commands come from the `checks` and +`invariants` of the project's `.sisi/contract.json`. A contract in a repository you cloned is therefore code +written by someone else, and it is treated as such. + +- A project's contract runs only after the project is trusted on this machine. `sisi contract init` trusts the + project it creates; anything else needs an explicit `sisi contract trust`, which you should run after reading + `.sisi/contract.json`. +- In an untrusted project, `sisi verify` refuses to run (exit 3) and the end-of-turn gate lets the turn end + without running anything. +- The list of trusted projects is `trusted.json` in your personal data folder. `sisi contract untrust` removes + a project. +- Every check has a time limit. After a few send-backs in a row the gate lets the agent through and marks the + result unverified, so a broken check cannot hold a session forever. + +## What sisi does not protect against + +- A trusted project's contract runs with your permissions. Trust only projects you trust. +- sisi does not sandbox the commands it runs. +- Instructions that sisi adds to your tools (the rulebook) are text the tools obey. Anyone who can write to your + personal data folder can change what your agents are told. Keep that folder private (it is created in your home + directory and is a local git repository that sisi never pushes). +- sisi does not read network resources and has no server. `sisi update` runs `git fetch` and a fast-forward merge + in the clone and nothing else over the network. + +## Reporting a problem + +Please report security problems privately, using a private security advisory on the GitHub repository +(github.com/swaits/sisi, "Security" tab, "Report a vulnerability"). Do not open a public issue for something +that could be exploited. Include the version (`sisi --version`), what you did, and what happened. diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/bin/sisi b/bin/sisi new file mode 100755 index 0000000..426bbb1 --- /dev/null +++ b/bin/sisi @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import os, sys +# sisi never writes inside the product: compiled bytecode goes to the scratch dir instead of next to the code. +_state = os.environ.get("SISI_STATE") or os.path.join(os.environ.get("SISI_HOME") or os.path.expanduser("~"), + ".local", "state", "sisi") +sys.pycache_prefix = os.path.join(_state, "pycache") +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) +from sisi.cli import main +sys.exit(main(sys.argv[1:])) diff --git a/canon/core.md b/canon/core.md new file mode 100644 index 0000000..dc21385 --- /dev/null +++ b/canon/core.md @@ -0,0 +1,118 @@ +# sisi: how to work + +These rules apply in every tool and every project. They are short on purpose. Each rule gives its +reason, so you can apply it with judgement when a case is not covered. Run `sisi help` to see the +commands mentioned here. + +## 1. Know how you will know you are done {#know-done} + +Before non-trivial work, write a contract at `.sisi/contract.json` in the project (`sisi contract +init` creates the skeleton). It lists the checks that decide success, each with a command that can +be run and the result expected. Draft it yourself from the request and the project. + +Why: a request says what is wanted, rarely how success is measured. Work without a measure drifts, +and nobody can tell whether it landed. + +Skip the contract for small edits (a few lines, a rename, a question). + +Why: ceremony on small tasks costs more than it saves. + +## 2. Use the strongest check available {#strongest-check} + +Give each check the highest rung that is feasible, and record the rung: + +1. proof, model checking, or the type system +2. property-based tests, fuzzing, or comparison with a reference +3. example tests +4. golden files and snapshots, including screenshots +5. a rubric scored by an independent judge +6. the human + +Claims about concurrency, parsing, money, state machines, or data migration need rung 1 or 2. + +Do not invent the check from memory. Ask the library: + +- `sisi done for ""` says what must be true before that kind of work is finished, + and how it usually only looks finished. +- `sisi verifiers for ""` ranks the techniques that can show it, with + the command and a check to paste into the contract. + +A test suite is evidence only if it can fail. For anything that matters, show that it can: watch the +test fail without the change, or run mutation testing. + +Why: an example test shows one case works. The higher rungs show that a whole class of failures +cannot happen, which is what lets the human stop checking. + +## 3. Protect what already works {#protect-working} + +Before changing something that exists, add invariants to the contract: what must not change or get +worse, with a baseline captured before your first edit (tests passing, a snapshot, a screenshot). + +Why: the most costly failure seen so far was a good design made worse by a change that reached +further than the request. + +## 4. Treat feedback as a change to the contract {#feedback-as-amendment} + +When the human gives feedback, restate it in one line as an amendment to the contract. Change only +what the amendment covers. Re-run the invariants. + +Why: feedback is narrow. Reading it as licence to rework things is how good work gets damaged. + +## 5. Decide, do not ask {#decide-dont-ask} + +Ask the human only when both are true: the answer cannot be worked out from the request, the +project, or `sisi oracle`; and a wrong guess would be expensive to undo or would change what success +means. Ask all such questions once, at the start, each with the default you would choose. Record +everything else you decided under `assumptions` in the contract and report it at the end. + +Why: the human wants to state an outcome and get it. Each question stops the work and spends their +attention on things you could have settled. + +When you do need an answer, ask it the right way, every time: + +- Use the tool's question dialog if it has one (AskUserQuestion in Claude Code). Never bury a + question in the text of a reply. +- Give options to pick from. Mark the one you recommend, or several if more than one may be chosen, + and say why. +- Use plain words a person outside the work would understand. No terms you made up, no internal + names, no shorthand. + +Why: people have to repeat this to agents again and again. A question in prose is easy to miss and +slow to answer. Options with a recommendation can be answered in one click. + +For a large request, one round to confirm the contract is welcome: defining success is the best use +of the human's time. After that, work without interruption. Approving steps is the worst use of it. + +## 6. Finish by verifying {#finish-by-verifying} + +Run `sisi verify` before you say the work is done. Report each check, its rung, and its result. A +check that was not run is reported as not run. Never describe unverified work as done. + +Why: the tools run this same command when you finish and will send you back if a check fails. A +false "done" costs the human more than a late one. + +## 7. Every time, say how it could have gone better {#retro-every-time} + +When a piece of work ends, and before you report it, run `sisi retro`. The question is never whether +you could have done better. It is how. Judge yourself against these aims: the human works at a +higher level, the outcome is verified by the strongest method, the human is interrupted less, the +result is what they meant, and it arrives sooner. Name the one thing that would have helped most: +the moment it went slower, weaker or wider than it should have, why, and the change to sisi (a rule, +a recipe, a technique, a fact about the human, a tool) that would make the next agent do it right +without being told. "Nothing" and general advice are refused. Subagents do this too. + +Also, when the human states a lasting preference, record it at once with `sisi learn ""`. Quote them. Never record your own guess. + +Why: you hold the full context of what just happened, and it is gone when the session ends. Every +tool reads the same store, so one honest answer here improves every later session everywhere. + +## 8. Deliver quickly {#deliver-quickly} + +The time from the request to a verified result is part of success. Never buy speed with a weaker +check or a smaller result. Buy it by doing independent work at the same time, running the quickest +check first and slow checks in the background while you carry on, never repeating work whose +inputs have not changed, and finding out why a slow step is slow instead of waiting on it. + +Why: correct work that takes days when hours would do fails the human almost as badly as wrong +work. `sisi time` shows where the time went. diff --git a/canon/floors.json b/canon/floors.json new file mode 100644 index 0000000..46e76cc --- /dev/null +++ b/canon/floors.json @@ -0,0 +1,7 @@ +{ + "concurrency": 2, + "parsing": 2, + "money": 2, + "state-machine": 2, + "migration": 2 +} diff --git a/canon/skills/.gitkeep b/canon/skills/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/config.default.json b/config.default.json new file mode 100644 index 0000000..8609e99 --- /dev/null +++ b/config.default.json @@ -0,0 +1,16 @@ +{ + "gate": { + "enabled": true, + "budget_s": 120, + "max_blocks": 3, + "growth_lines": 40, + "growth_files": 3 + }, + "verify": { + "default_timeout_s": 60, + "fast_limit_s": 60 + }, + "retro": { + "required": true + } +} diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..d8c2db3 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,14 @@ +# Documentation + +| Page | Read it to | +|---|---| +| [../README.md](../README.md) | learn what sisi is, install it and try it | +| [design.md](design.md) | understand why sisi works the way it does, and what is built versus only designed | +| [personal-data.md](personal-data.md) | know where sisi keeps what it learns, how the overlay works, and what an update touches | +| [verifier-format.md](verifier-format.md) | write or review an entry in the verifier library (`verifiers/`) or a recipe (`done/`) | +| [developing.md](developing.md) | work on sisi while also using it: the source folder, stable releases and rollback | +| [../CONTRIBUTING.md](../CONTRIBUTING.md) | run the tests and send a change | +| [../SECURITY.md](../SECURITY.md) | understand what sisi runs, and report a problem | +| [../CHANGELOG.md](../CHANGELOG.md) | see what changed between versions | + +The rulebook that agents actually read is [../canon/core.md](../canon/core.md). diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..4c8eee4 --- /dev/null +++ b/docs/design.md @@ -0,0 +1,329 @@ +# sisi: design + +Status: this document describes the design of sisi and marks what is built and what is not. The section +"What is built" lists both. Where the text below says "sisi does" something that the list marks as not built, +read it as the intended design. + +## Intent + +AI coding tools execute well and understand poorly. An agent does not know what success means, so it guesses, +and sometimes it damages work that was already good. Nobody can list every such failure in advance, so the +system has to find them itself. + +The end state: a person states a product and gets a verified product. Five objectives, each with the number +that shows it: + +| Objective | Shown by | +|---|---| +| Work at a higher level (functions, modules, products) | size of verified work delivered per human message | +| Verifiable outcomes, formal where possible | share of delivered claims backed by a check that ran, by rung | +| Hands off | human minutes and blocking questions per delivered piece of work | +| Delivered sooner, with no weaker check | median time from request to verified result (`sisi time`) | +| Improves itself from use, everywhere | the numbers above, as trends, across all tools | + +## The objective + +Hard requirements come first: the result is correct, complete, verified at the rung its kind of claim needs, +and what the human meant. Among results that meet them, sisi minimises two things: the time from the request to +a verified result (time to delivery), and the number of times the human is interrupted. Speed is never bought +with a weaker check or a smaller result. + +Time to delivery is measured, not guessed. Each time the end-of-turn gate lets a turn end it records one +delivery row: the time since the last message the human actually typed (hook feedback and tool results do not +count), how many times the gate sent the agent back, and how long the checks ran. `sisi time` shows the median +and 90th percentile for the last 7 days against the 7 days before, the share spent in checks, and the five +slowest checks; `sisi status` shows the 7-day median. + +A learned change that speeds things up but fails a check is rejected. A learned change that keeps every check +passing but makes median delivery slower is flagged for reversal. (The measurement exists; the automatic +flagging belongs to the learning loop, which is not built.) + +## Why the first design was thrown out + +The first version was a rulebook of at most 120 lines, plus advice. It was attacked and found too small, for +these reasons, which still shape the design: + +1. **It was advice.** The definition of done was prose in an instruction file. Nothing made an agent write it or + run it. +2. **It had a low ceiling.** Its only output was one rulebook. The best case was one good instruction file, then + a plateau. +3. **It ignored the main objective.** Product-level work was a late phase, and "not a new harness" was a stated + non-goal. Nothing in it could drive hours of work from one sentence. +4. **It treated the human as a cost.** The human can help define success; the first version only tried to ask + less. +5. **Its measurements were weak.** A classifier's opinion of transcripts, compared before and after with no + control group. And "fewer corrections, fewer questions" is also what a user who has given up looks like. +6. **It left the best data unused.** Records of delegated work, with outcomes, show that most rejections are + fixed by a better brief. The hand-off of intent is the largest known source of failure, and the first + version declared that out of scope. +7. **It ignored competing instructions.** Installed plugins can tell agents to do the opposite of the rulebook + (for example, forcing a question-and-answer design conversation before any work). The loudest instruction + wins. +8. **Formal methods were one line of text.** Agents fall back to example tests because the formal tools are not + installed or set up. +9. **It opened a hole.** Any agent could write "facts about the user" that every agent in every tool would then + obey. An agent misled by a web page could poison all of them. + +## Goals + +- Success is an executable artefact, enforced by the tools, not requested. +- One sentence can start work that runs to a verified result. +- The human's time goes to defining success, without blocking the work. +- What accumulates is capability (checks, verifiers, a calibrated judge of the human's taste, playbooks), not + only rules. +- One shared store for everything, used by every tool. + +## Non-goals + +- No cron, timers, daemons, or third-party Python packages. Everything runs because a tool was used or a + command was started. +- No new chat UI. sisi drives the existing command-line tools. +- No per-project tuning. The store is global. Contracts are per piece of work. + +## Anti-goals + +- An agent that asks nothing and delivers something wrong. +- Ceremony on small tasks. +- Changes nobody can see or undo. +- Scores that go up while the delivered work gets worse. + +## Part 1: contracts that are enforced + +A **contract** is a file that says how this piece of work will be known to be done. The agent writes it from the +request and the project. It holds: + +- **checks**: each has the claim it supports, the command that tests it, the expected result, and its rung on + the ladder +- **invariants**: for existing work, what must not change or get worse, with a baseline captured before the + first edit +- **assumptions**: what the agent decided to fill gaps +- **open questions**: only those where the answer cannot be worked out and a wrong guess is expensive, each with + a default + +The ladder, highest first: + +1. Proof, model checking, the type system +2. Property-based tests, fuzzing, comparison with a reference +3. Example tests +4. Golden files and snapshots, including screenshots +5. A rubric scored by a judge model whose agreement with the human is measured +6. The human + +`sisi verify` runs the contract and records every result in the shared store. A contract with top-level +`"parallel": true` runs its fast-tier checks at the same time (at most 4); a check with `"serial": true` always +runs alone. Results are reported in contract order either way. + +**Enforcement.** The tool's end-of-turn hook calls `sisi verify`. If a contract exists and a check fails or was +not run, the agent is sent back with the failures and cannot report the work as done. If no contract exists and +the change is larger than a small threshold, the agent is sent back to write one. Small edits pass untouched. +Claude Code supports a blocking stop hook. The equivalent in OpenCode, Codex and Muse is not verified; where it +does not exist, verification is meant to run at the next session start and failures to be reported then (that +fallback is a design intention, not built). + +**Floors.** Some kinds of claim have a minimum rung. Concurrency, parsing, money, state machines and data +migration may not rest on example tests alone. The floors are in `canon/floors.json`. + +**Formal tooling is provisioned.** sisi keeps a verifier library: for each language and kind of claim, the +tool, a working template and a worked example (Kani and Verus for Rust, TLA+ or Quint and Alloy for designs, +property testing per language, screenshot comparison for UI). Each time a check was hard to set up, the set-up +is meant to be saved, so the next use is cheap. + +**Feedback.** Feedback from the human becomes an amendment to the contract, restated in one line. Only what the +amendment covers may change, and the invariants are re-run. A UI that was good stays good unless the amendment +says otherwise. + +## Part 2: the conductor (not built) + +`sisi build ""` would turn a statement into verified work. It can be started from a terminal or by +an agent inside any tool. It is a plain program that drives the installed command-line tools in headless mode. +Its state is on disk in the shared store, so a run survives the session that started it and can be resumed from +any tool. None of this exists yet; there is no `sisi build` and no `sisi inbox` command. + +1. **Frame.** A strong model writes the product contract: acceptance checks for the whole, and for the core + logic a formal model where one applies. It fills everything it can from the oracle profile. +2. **One oracle round.** The human sees the contract and the few open questions, once, and corrects it. This is + the human defining success, and it is the highest-value minute in the run. +3. **Split.** The contract becomes a tree. Each node has its own contract and a brief generated from it, so a + brief always carries the success checks. +4. **Dispatch.** Nodes go to workers chosen from a routing record, in parallel where they do not share files. +5. **Close.** A node closes only when `sisi verify` passes on it. A failure is retried with the failing output, + then escalated to a stronger worker. Parents are re-verified when children land. +6. **Report.** What was built, every check and its rung, every assumption. + +**The oracle queue.** A question that arises mid-run does not stop the run. It goes into a queue with the +default the agent is proceeding on. Work that does not depend on it continues. `sisi inbox` would show the +queue. An answer that differs from the default re-opens only the nodes that used it. + +**Delegation records.** A person who already delegates work to cheaper models may keep a ledger of outcomes. +The design folds such a ledger and its routing table into the shared store. Today sisi only reads an optional +ledger file, to match delegations with sessions when it builds the task set. + +## Part 3: learning that compounds + +The data layer of this part is built; the model-driven loop that would act on it is not. + +**Signals, strongest first.** The loop learns from outcomes that do not depend on a model's opinion: + +1. Check results recorded by `sisi verify`. +2. Survival of work in git: was an agent's change reverted or rewritten within 14 days. +3. Delegation outcomes in a ledger. +4. The human's corrections and the agent's questions, read from transcripts by a classifier. Useful for finding + causes, weakest as proof. + +**Trigger.** Each tool's session-start hook runs `sisi tick`, which returns quickly. The design has it start a +detached background run when there is work and budget, with one lock in the store preventing overlap, so a tick +from any tool processes sessions from all tools. Today `sisi tick` records the session baseline and checks the +wiring; it starts no background run. + +**What the loop would produce.** + +- **Rules.** One change at a time, each with its reason and evidence. The always-loaded core stays under 120 + lines; the rest loads on demand. +- **The oracle profile.** What the human wants, so a thing is asked once ever. +- **A taste judge.** Every time the human judges an outcome ("this is worse"), the before, the after and the + verdict are saved. A judge is tuned on these and its agreement with the human on held-back verdicts is + measured. It may stand in for the human on rung 5 only for kinds of work where agreement is above 85%. This is + how taste becomes checkable. +- **The verifier library**, described in part 1. +- **Playbooks.** Runs that closed cleanly are mined too. The decomposition and checks that worked for a kind of + product are saved for the next one. +- **Brief templates**, from what the ledger shows fixed rejected work. + +**Testing a change.** Splitting live sessions between old and new rules proves about one change every three or +four days, which is too slow. The main test is a task set built from the user's own work, re-run in the +background: + +- **Human tasks.** A project as it was when a session began, the request the human typed, and what they ended up + accepting. In a census of one user's history, only a fraction of sessions were usable as tasks and a smaller + fraction had ground truth that could be fully trusted. From the day sisi is installed, every session is + recorded with its exact starting commit, so the set grows with use. +- **Brief tasks.** Records of delegated work, each an instruction, the work done, and whether it was accepted. + These test how instructions are written and which model suits which job. + +A candidate change is run against a sample of tasks next to the current version, in separate copies of the +project. It is scored on: the accepted version's tests passing, closeness to what the human accepted, questions +asked, and whether its checks would have caught the failure that really happened. It ships only if it passes +every check and scores higher on tasks it was not written from; a change that is faster but fails a check is +rejected, however quick. Live sessions then confirm or reverse it, and a change that keeps the checks passing +but makes median time to delivery slower than before is flagged for reversal. The spend is capped by a budget +that favours flat-rate plans first, then the cheaper models. + +Other things the loop would improve, besides rules: recipes are tightened whenever a bug gets past a passing +set of checks; techniques are ranked by how often they catch real failures; checks that never fail are flagged +(`sisi checks` does this today); new models are scored on the task set before routing changes. + +**Owning the instruction surface.** `sisi audit` lists every source of instructions each tool loads +(instruction files, plugins, skills) and reports where they contradict the rulebook. Contradictions the loop +cannot remove itself would be put in the oracle queue. + +## One shared store + +One rulebook, one oracle profile, one set of contracts and results, one verifier library, one scoreboard. Tools +are connected by reference (an import line or a symlink), never by copy, so a change is live everywhere at the +next session. Every write to personal data is a git commit. Private session text and results live in scratch +(`~/.local/state/sisi/`) and are not committed. The layout as built is in `docs/personal-data.md`. + +### Product and personal data are separate + +sisi is two things on disk, and an update to one must never cost the other. + +- **The product**: what a person clones. Code, the base rulebook, the base library of techniques and recipes, + defaults. sisi never writes into it at run time. `sisi update` replaces it. +- **Personal data**: everything sisi has learned for this person. It lives in one folder outside the clone + (`~/.local/share/sisi/`), with its own local git history so any change can be undone, and it is never touched + by an update. It holds the profile of what the person wants, the lessons, learned changes to the rulebook, + field notes, added or replaced techniques and recipes, the task set, results, settings and trusted projects. +- **Scratch**: things that can be rebuilt (the transcript index, locks, logs) stay in `~/.local/state/sisi/`. + +Learned changes are stored as an overlay, not as edits to the product. Every base rule, technique and recipe +has a stable id. The overlay can add an item, replace one by id, or switch one off. What agents load is the +result of applying the overlay to the base, generated into the personal folder; the tools point at that +generated file. + +On update the overlay is applied again to the new base. If the product changed an item the person's overlay +replaced, the person's version stays and the item is queued for re-testing against the new base version. +Personal data carries a format version, and `sisi update` migrates it after taking a backup. + +One folder means one thing to back up or copy to another machine (`sisi export`, `sisi import`). Results and +session records stay in scratch for now and are included in the export. Nothing personal is ever placed in the +product, so the product can be published. + +Any agent in any tool reads through the files or the CLI and writes through the CLI: + +- `sisi note`: record a failure now (older; `sisi retro` is preferred). +- `sisi propose`: suggest a rule change (older; `sisi retro` is preferred). +- `sisi learn`: record something the human said. The entry is held in quarantine until the harvest finds those + words in a message the human typed in that session's transcript. An agent cannot invent a preference. + +Models used by the loop run with no tools and return text. sisi's own code checks and writes that text, and +writes only inside the personal data folder (as overlay changes; see `docs/personal-data.md`), never into the +product. Text inside transcripts that the human did not type is data, never instruction. + +## Scoreboard + +`sisi scoreboard` shows weekly and per-repository trends computed from harvested sessions; `sisi status` shows +verification statistics. The design adds, per tool: verified work per human message; share of claims by rung; +blocking questions and human minutes per piece of work; share of agent changes surviving 14 days; taste-judge +agreement. The last two are not built. + +## What is built + +Built and covered by tests: + +- The CLI and the shared store; contracts (`sisi contract`), `sisi verify` with fast and deep tiers and trust + for contracts that run commands. +- The end-of-turn gate (`sisi gate`) and session-start hook (`sisi tick`), wired into Claude Code with a + blocking hook; wiring (`sisi install`, `uninstall`, `doctor`) also points Codex and OpenCode at the rulebook, + where nothing blocks. +- The rulebook (`canon/core.md`), the minimum-rung floors, the verifier library and the recipes. +- Retrospectives and lessons (`sisi retro`, `sisi lessons`), `sisi learn` with quarantine, time to delivery + (`sisi time`), `sisi audit`. +- Personal data, the overlay, update, export and import, releases and rollback, promotion of a personal item + into the product. +- The data layer for learning: harvest of Claude Code transcripts, task set, ground truth, escape candidates, + check statistics, scoreboard. + +Designed, not built: + +- The conductor (`sisi build`) and the oracle queue (`sisi inbox`). +- The model-driven learning loop: background runs started from `sisi tick`, experiments on the task set, shipping + and removal of learned changes, brief templates, playbooks. +- The taste judge and rung 5 judging by a model. +- Blocking gates for tools other than Claude Code. +- Harvest sources other than Claude Code. + +## Build order + +1. Store, CLI, wiring into each tool, contract format, `sisi verify`, the end-of-turn gate, the first + verifier-library entries, rulebook version 0, `sisi audit`. Built. +2. Signals and scoreboard: transcript adapters, git survival, and a delegation ledger. Partly built (Claude Code + transcripts, task set, scoreboard; no git survival signal). +3. The conductor and the oracle queue. Not built. +4. The loop: coach, replay filter, experiments, shipping and removal. Not built. +5. The taste judge and playbooks. Not built. + +sisi's own checks: wiring is idempotent and touches no other byte (property tests); the gate cannot be passed +with a failing or unrun check (property test over generated contracts); a rulebook change is visible to every +tool with no further command; `tick` returns quickly; no command writes inside the product at run time; the +learning loop, when built, cannot write outside the personal data folder; a conductor run killed at any step +resumes without redoing closed nodes (to be model-checked, then tested). + +## Decisions + +1. Delegation tooling is folded into sisi in the design; only the optional ledger read exists today. +2. The end-of-turn gate is on by default. Each check has a time limit, and after three send-backs in a row the + agent is let through with the result marked unverified. One setting turns the gate off. +3. Session text may be read by any provider the user already uses as a worker, never by a model whose id marks it + as training on prompts. This is a user setting, not something sisi decides for them. +4. Background spend has a default budget (a number of cheap calls and test runs a day). Not built, since no + background runs exist yet. + +## Known limits + +- Whether an agent understood cannot be proved. Survival in git and check results are evidence, with delay. +- A contract can be wrong. Passing checks prove the checks, so the product contract gets the one oracle round. +- Experiments at this volume detect large effects only. +- The taste judge is worthless until the human has given enough verdicts, and it is trusted per kind of work, + not globally. +- Blocking gates outside Claude Code, Muse's instruction path and Codex's hook format are unverified. +- This is several months of building. Each phase is useful on its own. diff --git a/docs/developing.md b/docs/developing.md new file mode 100644 index 0000000..eabf200 --- /dev/null +++ b/docs/developing.md @@ -0,0 +1,67 @@ +# Developing sisi + +If you only use sisi, you can skip this page. Cloned it and ran `sisi install`? Nothing changes for you: +the clone is the installed copy. + +## Two copies + +When you both use sisi and work on it, keep them apart: + +- the **source folder** (for example `~/src/sisi`): where you edit. It may be broken half the time. +- the **stable copy** in `~/.local/lib/sisi/`: what Claude Code, Codex and OpenCode actually run. + +The stable copy is a set of releases, `~/.local/lib/sisi/releases//`, each holding only the product +files (`bin/`, `sisi/`, `canon/`, `verifiers/`, `done/`, `docs/`, `config.default.json`, `VERSION`; no tests, notes or contract). +A link called `current` points at the active one. `SISI_LIB` moves the whole folder (tests use it). + +Once a `current` release exists, `sisi install` wires the hooks and `~/.local/bin/sisi` to +`~/.local/lib/sisi/current/bin/sisi`. A running tool never sees a half-written copy: a release is built under a +hidden name and renamed into place, and `current` is switched by writing a new link and renaming it over the old +one. A process that has started keeps running the release it started with. + +One limit, measured on btrfs: a lookup that lands on the exact instant of the switch can fail to find `current` +(about 1 lookup in 40,000 during a switch). A hook that hits it fails open, as any hook error does, and the next +call finds the new release. + +## Make a release + +From the source folder: + + sisi release # runs `sisi verify`; refuses if it fails + sisi release --deep # also needs the slow checks to pass + +It copies the product files, switches `current`, rebuilds your rulebook with the new code, keeps the newest three +releases, and prints what changed. The first time, run `sisi install` afterwards so the tools point at the stable +copy (release tells you if they do not). + +`sisi doctor` shows which copy is live, its release time, and whether the source folder is ahead of it. + +## Roll back + + sisi rollback + +Switches `current` to the release before it and rebuilds the rulebook. It can be repeated until the oldest kept +release. + +## Developer mode + + sisi dev on [PATH] # remember where the source folder is (setting developer.source in your personal config) + sisi dev off + sisi dev status + +Needed only when you run `sisi release` or `sisi promote` from somewhere else, such as through the installed +copy. Run from the source folder, they use that folder. + +## Promote a personal addition + +Rules, verifiers and recipes you added live in your personal overlay. To make one part of the product: + + sisi promote # shows what would be written, and every term it scrubbed + sisi promote --apply # writes it into the source folder + +It replaces your home path with `~`, your user name with ``, email addresses with ``, and any terms +listed under `developer.personal_terms` in your personal `config.json` with ``. If a personal term still +appears afterwards (for example in different capitals), it stops and names the lines; fix the overlay item and +try again. A rule goes into `canon/core.md` (replacing the rule with that id, or added as the next number); a +verifier into `verifiers/
/`; a recipe into `done/`. It never commits. Review the change, commit it, make a +release, then remove your overlay copy so the two do not drift apart. diff --git a/docs/personal-data.md b/docs/personal-data.md new file mode 100644 index 0000000..c58ea22 --- /dev/null +++ b/docs/personal-data.md @@ -0,0 +1,57 @@ +# Product and personal data + +sisi lives in three places. An update replaces the first and never touches the second. + +| Place | Where | What | Written at run time | +|---|---|---|---| +| Product | the clone (`paths.REPO`) | code, `canon/core.md` (base rulebook), `verifiers/`, `done/`, `config.default.json`, `VERSION`, docs | never (a test enforces it; bytecode goes to scratch) | +| Personal data | `$SISI_DATA`, else `$XDG_DATA_HOME/sisi`, else `~/.local/share/sisi` | what sisi learned for this person; its own local git repository | yes, committed | +| Scratch | `$SISI_STATE`, else `~/.local/state/sisi` | `harvest.db`, locks, logs, session records, results, bytecode | yes, rebuildable | + +Under `SISI_HOME` (tests) the personal folder is `$SISI_HOME/.local/share/sisi` unless `SISI_DATA` is set. + +## Personal data layout + + VERSION format version of this folder, a single integer (an update migrates older folders after taking a backup). + Not the product's release number: that is the VERSION file in the clone, shown by `sisi --version` + oracle.md what the person wants + overlay/ learned changes to the product (below) + notes/.md field notes per verifier or recipe id + config.json settings (over config.default.json) + trusted.json projects whose contracts may run commands + lessons.jsonl sorted dump of the lessons database, committed whenever lessons change + learn-quarantine.jsonl, notes.jsonl, proposals.jsonl + retest.jsonl replaced items whose base changed in an update (id, old base hash, new base hash) + retro.db lessons database (sqlite; not in git; lessons.jsonl is its committed form) + generated/core.md the effective rulebook (not in git; rebuilt by `sisi build-canon`) + install/ manifest and original copies of the files `sisi install` edited (not in git) + backups/ copies taken before a migration or an update (not in git) + +Git is private bookkeeping: author `sisi`, no hooks, no global git config needed, never pushed. + +## Overlay + +Ids: rules are `## 1. Title {#rule-id}` in `canon/core.md`; verifiers and recipes use their file stem. + + overlay/rules/.md `## Title` + body. A base id replaces that rule; a new id adds one + overlay/rules/disabled.txt ids switched off, one per line + overlay/rules/order.txt order of added rules (they follow the base rules) + overlay/verifiers/
/.md a verifier in the library format: replaces the product's, or adds + overlay/verifiers/disabled.txt + overlay/done/.md a recipe: replaces or adds + overlay/done/disabled.txt + overlay/bases.json per replacement, the hash of the base item it was made against + +Commands: `sisi overlay list | diff | add-rule | replace-rule | disable-rule | enable-rule` (and the same for +`verifier` and `recipe`), `sisi overlay revert COMMIT`. Each change is one commit and rebuilds the rulebook. +The generated rulebook may not exceed 120 lines: a change that would pass it is refused, so a rule is added +by shortening or replacing another. `sisi canon cost` prints the always-loaded size. + +On `sisi update` the overlay is applied to the new product. A replacement whose base item changed keeps the +person's version and is queued in `retest.jsonl` for the learning loop. + +## Moving data + +`sisi migrate` (also run by install and update) moves an older layout in, after a timestamped copy under +`backups/`. `sisi export [PATH]` / `sisi import PATH` carry personal data, results and session records as one +tar.gz. diff --git a/docs/verifier-format.md b/docs/verifier-format.md new file mode 100644 index 0000000..3824f6e --- /dev/null +++ b/docs/verifier-format.md @@ -0,0 +1,101 @@ +# Verifier library: format and quality bar + +The library exists so that an agent, in any tool, can answer two questions +without asking a human: "how do I know this works?" and "how do I know I am +done?". Agents query it with `sisi verifiers for ""` and `sisi done for +""`. Every entry must be something an agent can act on in +minutes: a real tool, a real command, and a snippet it can paste into a +contract. + +## Technique entries: `verifiers/
/.md` + +Sections: `design`, `prove`, `many-inputs`, `concurrency`, `test-quality`, +`regression`, `real-world`, `safety`, `intent`, `completeness`. + +The file stem equals `id`. Lowercase, hyphens. The file starts with a header +of single-line `key: value` pairs between `---` lines: + +``` +--- +id: cargo-mutants +title: Mutation testing for Rust with cargo-mutants +answers: Would my tests notice if this code were wrong? +rung: 2 +section: test-quality +languages: rust +kinds: general, money, parsing +cost: medium +detect: cargo mutants --version +ran_here: no +verified: docs +--- +``` + +- `answers`: the question, in plain words, that a passing run answers. This + is what the chooser matches on, so write it the way an agent would phrase + its doubt. +- `rung`: 1 proof, model checking or types; 2 property tests, fuzzing, + differential, mutation; 3 example tests; 4 golden files and snapshots; + 5 judged rubric; 6 human. +- `languages`: comma list, or `any`. +- `kinds`: any of general, concurrency, parsing, money, state-machine, + migration, ui. +- `cost`: low, medium or high. Set-up plus run effort for a first use. +- `detect`: a shell command that exits 0 when the tool is installed. Empty if + the technique needs no tool. +- `ran_here`: yes only if you ran the minimal example on this machine and it + behaved as the entry says. +- `verified`: `ran` (you ran it), `docs` (commands and flags checked against + the tool's current official documentation or its `--help`), or `memory` + (neither; avoid this, and never use it silently). + +Body headings, in this order, all required: + +- `## Use when`: the situations and claims it fits. Two to five bullets. +- `## Do not use when`: where it is the wrong tool or a weaker one is enough. +- `## Set up`: install and project set-up commands. +- `## Minimal example`: the smallest complete, correct example. Real code. +- `## Run`: the exact command, and under a `Passing looks like:` line the + output or exit status that means success. Say how failure shows. +- `## As a contract check`: a JSON object for the `checks` array of + `.sisi/contract.json`, with `id`, `claim`, `kind`, `rung`, `cmd`, `expect` + (`exit`, optionally `stdout_contains`) and `timeout_s`. Whenever `timeout_s` + is over 60, include `"tier": "deep"`: fast checks (the default) may not + exceed 60 s, because they run in the end-of-turn gate. Deep checks run with + `sisi verify --deep`, in the background, and never block a turn by being slow. + Contract-level options: top-level `"parallel": true` makes `sisi verify` and + the gate run the fast-tier checks at the same time (at most 4; results still + come in contract order), and `"serial": true` on a check makes it always run + alone, for checks that share a port, a database or a build directory. Without + `parallel`, checks run one after another. +- `## What a pass does not prove`: the limits. Bounds, assumptions, things + that make a pass vacuous, and how to check that the check itself can fail. + +Length: 30 to 80 lines. No history of the tool, no selling, no filler. + +## Recipes: `done/.md` + +Header keys: `id`, `title`, `applies_to` (one line). Body headings, required: + +- `## Done means`: the claims that must all be true, in plain words. +- `## Checks`: for each claim, the technique ids from `verifiers/` that can + show it, strongest first, and the minimum acceptable rung. +- `## Common false finishes`: the ways this kind of work looks done and is + not. + +Length: 25 to 60 lines. + +## Quality bar + +- Commands and flags must be right. Check each against the tool's official + documentation or `--help`. A wrong flag costs an agent more than a missing + entry. If you cannot confirm something, say so in the entry. +- Run the minimal example when the tool is already installed on this machine. + Work only in a throwaway directory. Do not install toolchains globally and + do not change anything outside the sisi repository. +- Prefer the technique over the brand. If several tools do the same job in + different languages, one entry per language is right; two entries for the + same language and job is not, unless they differ in what they can show. +- Be honest about rung. A technique that samples is rung 2 at best. +- Use plain, direct English. Full sentences. No jargon the entry does not + explain. diff --git a/done/agent-tool-surface.md b/done/agent-tool-surface.md new file mode 100644 index 0000000..a95188e --- /dev/null +++ b/done/agent-tool-surface.md @@ -0,0 +1,31 @@ +--- +id: agent-tool-surface +title: Tools, commands or an interface designed for AI agents +applies_to: An MCP server, a CLI, or a set of functions an AI agent calls, including their names, descriptions, inputs and outputs. +--- + +## Done means +- Each tool has a clear name and a description that says what it does, when to use it, what it will not do, and what it returns; an agent picks the right tool from the text alone. +- Inputs are validated with clear, fixable error messages, and unsafe or destructive actions need an explicit step. +- Annotations (read-only, destructive, idempotent) match what the tool actually does. +- Outputs are small, stable and structured; they do not overflow an agent's context or leak secrets. +- Real agents, given realistic tasks, complete them through the tools with few wrong calls. +- Dangerous sequences (call order, repeated calls) are safe. + +## Checks +- Task success: `agent-surface-evals` (real-world), rung 3 to 5, with tasks, a hidden answer, and a count of wrong or wasted calls. +- Descriptions: `tool-description-lint`, `rubric-judge` (intent) by a different model family. +- Annotations true: `annotation-behaviour-check` (real-world), rung 3; `read-only-guarantee` (regression). +- Bad input and injection: `hostile-input-from-schema` (many-inputs); `threat-model-checklist`, `sensitive-data-leak-test` (safety). +- Surface stability: `api-breaking-schema` (regression); `baseline-before-change`. +- Domain results: `acceptance-examples`, `domain-evidence-report` (intent). + +## Common false finishes +- The tool works when called by the test that wrote it; no agent has ever tried it. +- The description was written from the implementation, not tested for how an agent reads it; two tools sound alike and agents pick the wrong one. +- A tool marked read-only writes (a cache, a log, a lock). Check against the file system. +- Output is a wall of text that fills the agent's context; there is no limit or paging. +- Error messages say "invalid input" without saying which field or what would be valid. +- The evals use the same model that wrote the tools, or the author's wording of the tasks. +- A secret appears in an error or log that the agent reads. +- A destructive tool can be called with defaults and no confirmation. diff --git a/done/bugfix.md b/done/bugfix.md new file mode 100644 index 0000000..9008aa5 --- /dev/null +++ b/done/bugfix.md @@ -0,0 +1,32 @@ +--- +id: bugfix +title: Fixing a bug +applies_to: A reported defect in existing behaviour, where the aim is to make it right and leave everything else alone. +--- + +## Done means +- The bug is reproduced first by an automated test that fails on the unfixed code, for the reason in the report. +- The same test passes after the fix, and it is kept as a permanent regression test. +- The cause is found, not just the symptom: the fix is at the point that was wrong, and siblings of the bug (same pattern elsewhere) were looked for. +- Nothing that worked before changed: the whole existing suite passes, and a baseline taken before the first edit matches afterwards. +- The diff touches only what the fix needs; no drive-by refactors. +- The report says what the bug was, why it happened, and what was not fixed. + +## Checks +- Fails before, passes after: `red-before-green` (test-quality), rung 3; for a bug in logic over many inputs, a property or differential check that fails on the old code (`proptest`, `hypothesis`, `differential-old-vs-new` in many-inputs), rung 2. +- Nothing else changed: `baseline-before-change`, `characterization-tests` (regression), rung 3; `feedback-as-amendment` (intent) for the scope check on the diff. +- The test can fail: `vacuity-check`, `mutation-on-diff` (test-quality), rung 2. +- Same mistake elsewhere: `static-analysis-semgrep` (safety) with a rule for the pattern; log it in `findings-log` (completeness). +- Finished cleanly: `no-stubs-scan`, `single-gate-command` (completeness), rung 3. +- If the bug was a crash or hostile input: the input is added as a seed (`regression-seed-hygiene`, many-inputs). + +## Common false finishes +- The new test passes but was never run against the unfixed code. It may never have failed; run it with the fix reverted. +- The test asserts the new behaviour on the exact reported input only. A different input with the same cause still fails; vary it. +- The symptom is hidden: an error is caught and ignored, a value is clamped, the failing case is special-cased. The cause remains. +- An old test was changed or deleted to make the suite green. Read the test diff first. +- A flaky failure "went away" after the change. A bug seen once is not fixed by one clean run; see `stress-repeat` (concurrency). +- The fix is in the wrong layer (UI hides what the engine gets wrong). +- The reproduction used test fixtures that cannot occur in real data, so the real case is untested. +- The change reaches further than the bug and nobody ran the invariants. +- "Cannot reproduce" is reported as fixed. Say it is unreproduced and not fixed. diff --git a/done/cli-tool.md b/done/cli-tool.md new file mode 100644 index 0000000..65470b1 --- /dev/null +++ b/done/cli-tool.md @@ -0,0 +1,32 @@ +--- +id: cli-tool +title: Building or changing a command-line tool +applies_to: A program run from a shell, with arguments, standard input and output, and exit codes. +--- + +## Done means +- Every command and flag in the help text works as described, and the help matches what the code does. +- The exit code is 0 only on success and a stable non-zero on each kind of failure; errors go to standard error, results to standard output. +- Bad input (missing file, bad flag, empty input, huge input, a broken pipe) gives a clear message and no stack trace or partial output file. +- Output is stable and machine-readable where scripts depend on it, and pinned by tests. +- It installs and runs from a clean checkout or the built package on a machine that is not the author's. +- It does not print or store secrets, and does not touch files it was not asked to. + +## Checks +- Behaviour by transcript: `cli-transcript-tests` (real-world), rung 3 to 4, including exit codes and standard error. +- Output format: `golden-files-hand-verified`, `snapshot-insta` (regression), rung 4. +- Bad input: `hostile-input-from-schema`, `cargo-fuzz` or `atheris` (many-inputs), rung 2. +- Public contract: `api-breaking-schema` (regression) for flags and output fields. +- Install: `clean-clone-build`, `packaging-install-upgrade`, `cross-platform-matrix` (real-world). +- Scripts: `shellcheck` (safety). Secrets: `sensitive-data-leak-test`. +- Done: `single-gate-command`, `no-stubs-scan` (completeness). + +## Common false finishes +- Tested by calling the internal function, not the binary. Flag parsing, defaults and exit codes are untested. +- Exit code is 0 after an error was printed. +- Errors and results both go to standard output, which corrupts pipelines. +- The tool works in a terminal and breaks when output is piped (colour codes, prompts, width detection). +- Paths with spaces, relative paths, and a non-existent directory were never tried. +- The help text was not updated after a flag changed. +- A file is half-written when the program fails; no atomic write. +- Passing on Linux only when the user is on another system. diff --git a/done/concurrent-code.md b/done/concurrent-code.md new file mode 100644 index 0000000..9d611b2 --- /dev/null +++ b/done/concurrent-code.md @@ -0,0 +1,32 @@ +--- +id: concurrent-code +title: Concurrent, parallel or async code +applies_to: Code with threads, tasks, locks, channels, async runtimes, or shared state between processes. +--- + +## Done means +- The design's key properties (no lost update, no deadlock, ordering where promised, each message handled once) are stated and checked, not assumed. +- Interleavings were explored systematically, not by hoping a test hits the bad one. +- Memory safety and data races are checked by a tool on the real code paths. +- Cancellation, timeout, shutdown and panic in one task leave the rest consistent and release locks and resources. +- Results do not depend on timing: repeated runs under load give the same outcome. +- Throughput claims, if any, are measured. + +## Checks +- The design: `tlaplus`, `pluscal`, `quint` or `p-lang` (design), rung 1, for protocols and state machines. +- The code's interleavings: `loom` or `shuttle`, `deterministic-simulation` (concurrency), rung 1 to 2. +- Races and memory: `thread-sanitizer`, `go-race-detector`, `miri`, `address-and-ub-sanitizers`; `unsafe-audit` (safety). +- Correctness of results: `linearizability-checking`, `stateful-model-test` (many-inputs), rung 2. +- Lifecycle: `async-cancellation-safety`, `lock-order-and-deadlock`. +- Flakiness: `stress-repeat`, `flaky-test-detection`, `test-determinism` (test-quality). +- Tests can fail: `mutation-on-diff`, `check-the-checker`. + +## Common false finishes +- The tests pass on a fast machine with two threads. Bugs need contention; use a model checker and a stress run with more tasks than cores. +- The sanitiser ran on the tests but the tests do not run the concurrent paths together. +- A `sleep` was added to make a test pass. That is a timing hack, not a fix. +- The model checker explored a model, not the code; the model and the code diverged. +- Loom or Shuttle bounds were set so small that the bad schedule was never reached; a pass with a tiny bound is partial. +- A lock was added and now there is a deadlock under a different order. Check lock order. +- Cancellation was tested at no point other than the start; a drop halfway through leaves state broken. +- "Flaky, re-run" was accepted as a pass. diff --git a/done/config-or-infra-change.md b/done/config-or-infra-change.md new file mode 100644 index 0000000..9118298 --- /dev/null +++ b/done/config-or-infra-change.md @@ -0,0 +1,28 @@ +--- +id: config-or-infra-change +title: Configuration, build, CI or infrastructure change +applies_to: Changes to build files, CI workflows, deployment, container images, infrastructure code and runtime configuration. +--- + +## Done means +- The change was run in the real system (a CI run, a build, a deploy to a staging copy), not only parsed. +- The failure path was exercised: the new step fails when it should. +- Secrets are not in the files or logs, and permissions are no wider than needed. +- Build and deploy work from a clean checkout and are repeatable. +- What the change affects is stated, and the rollback is known. +- Nothing else in the pipeline silently stopped running. + +## Checks +- Runs: `clean-clone-build`, `smoke-after-deploy`, `cross-platform-matrix` (real-world), rung 3. +- The gate still gates: `single-gate-command`, `check-tiering` (completeness). +- Scripts: `shellcheck`; secrets: `secret-scanning`, `sensitive-data-leak-test`; `threat-model-checklist` (safety). +- Rules in config: `static-analysis-semgrep` (safety) for workflow or manifest patterns. +- Checker works: `check-the-checker` (test-quality) by breaking something on purpose. + +## Common false finishes +- The YAML parses and was never run. +- A job was skipped by a condition, so the pipeline is green with fewer checks than before. +- The change works on the branch and not on the default branch, where secrets and permissions differ. +- A cache hid a missing dependency. +- Tokens were given write access "to make it work". +- A failing step was made non-fatal (`|| true`, `continue-on-error`). diff --git a/done/data-migration.md b/done/data-migration.md new file mode 100644 index 0000000..515914b --- /dev/null +++ b/done/data-migration.md @@ -0,0 +1,31 @@ +--- +id: data-migration +title: Migrating data or a schema +applies_to: Changing the shape, location or encoding of stored data, with existing data that must survive. +--- + +## Done means +- Every record in a realistic copy of production data migrates, and none is lost, duplicated or silently changed. +- Counts, totals, and derived views match before and after, by a check that does not use the migration's own code. +- Old data written by every earlier version still loads. +- The migration is safe to interrupt and to run twice, and a rollback or restore path was tried. +- Application code that reads the new shape works with it, and a mixed period (old and new code) is handled or ruled out. +- It was timed on production-sized data. + +## Checks +- Safety and rollback: `db-migration-safety` (regression), rung 3. +- Old data: `old-data-compatibility` (many-inputs), rung 2; `replay-equivalence`, `derived-view-agreement`. +- Equivalence: `differential-old-vs-new` (many-inputs), rung 2, on generated and real records; `round-trip` where a reverse exists. +- Interruption: `fault-injection-storage` (many-inputs), `stress-repeat`. +- Totals and reports: `domain-evidence-report` (intent), `golden-files-hand-verified`. +- Contract: `baseline-before-change`; the human for production data, `owner-acceptance-runbook`. + +## Common false finishes +- Tested on a small clean fixture; real data has nulls, odd encodings and duplicates. +- Counts match but values changed (timezone, rounding, trimming); no column-level comparison was made. +- Idempotence was never tried; a second run duplicates rows. +- The rollback exists on paper and has never been run. +- Old code reading new data (during a rolling deploy) fails. +- The migration takes hours in production and locks the table; it was timed on 100 rows. +- Foreign keys, indexes, triggers or permissions were not carried over. +- Backups were not taken or restored before the run. diff --git a/done/dependency-upgrade.md b/done/dependency-upgrade.md new file mode 100644 index 0000000..eef2232 --- /dev/null +++ b/done/dependency-upgrade.md @@ -0,0 +1,32 @@ +--- +id: dependency-upgrade +title: Upgrading a dependency or toolchain +applies_to: Raising the version of a library, framework, runtime or compiler the project depends on. +--- + +## Done means +- The project builds from a clean checkout with the new version pinned in the lockfile, on every supported platform. +- The whole test suite passes without any test being weakened, skipped or edited just to pass. +- Behaviour changes the upgrade introduced are read from its changelog, decided on, and either handled or ruled out. +- The new version has no known vulnerability, an allowed licence and a trusted source, and the transitive changes were looked at. +- Public output (formats, error text, API) that users rely on did not change unnoticed. +- Notices and size are current. + +## Checks +- Builds and tests: `clean-clone-build`, `cross-platform-matrix` (real-world), `single-gate-command` (completeness), rung 3. +- Behaviour is unchanged: `differential-old-vs-new` (many-inputs), rung 2; `characterization-tests`, `golden-files-hand-verified`, `baseline-before-change` (regression). +- Public interface: `api-semver-rust`, `api-surface-typescript`, `api-breaking-schema` (regression). +- Security and legal: `dependency-audit-rust` or `dependency-audit-general`, `licence-notices` (safety). +- Compiler and lints: `rust-lints-strict`, `zero-warnings` (regression). +- Speed and size: `perf-regression`, `size-budget`. +- Tests can fail: `mutation-on-diff` for any test you changed. + +## Common false finishes +- The lockfile was not committed, or `cargo update` / `npm update` moved many packages, and only the target was reviewed. +- Tests pass because deprecated-behaviour tests were skipped or snapshots were regenerated; read those diffs. +- Compile warnings about deprecated use were left, which become errors next release. +- It was only built on the author's platform. +- A transitive dependency changed licence, pulled in a yanked version, or added unsafe code. +- The changelog was not read; a changed default (timeouts, parsing strictness, rounding) does not break tests. +- A pin was loosened to make the resolver pass. +- Release notes were summarised from memory rather than read. diff --git a/done/docs-change.md b/done/docs-change.md new file mode 100644 index 0000000..023eb0d --- /dev/null +++ b/done/docs-change.md @@ -0,0 +1,31 @@ +--- +id: docs-change +title: Changing documentation +applies_to: README files, guides, API docs, comments meant to be read, and runbooks. +--- + +## Done means +- Every command, snippet and path in the text runs or exists as written, on a clean machine. +- Every link and cross-reference resolves. +- The text matches what the code does now; claims about behaviour were checked against the code or a run. +- It answers the question its reader brings, in the order they need, and says what it does not cover. +- Nothing else changed: no code or contract edit rode along. +- Examples contain no real secrets, and no private names. + +## Checks +- Runs and links: `doc-tests-and-links` (real-world), rung 3; `cli-transcript-tests` for shown output. +- True to the code: `acceptance-examples` (intent) for stated behaviour; `golden-files-hand-verified` for output shown. +- Quality: `rubric-judge` (intent), rung 5, with a different model family; `pairwise-comparison` against the old text. +- Scope: `feedback-as-amendment` (intent) for the diff. +- Safety: `secret-scanning`, `shellcheck` for shell snippets (safety). +- Complete: `no-stubs-scan` for TODO and "coming soon", `requirement-to-check-map` if the doc has a spec (completeness). + +## Common false finishes +- Snippets were written, not run; one has a typo or a removed flag. +- The docs describe the plan or the old behaviour, not the code. +- Links were checked before files were renamed. +- A new feature is documented in one place; two older pages still say the opposite. +- Output shown was typed, not copied from a run. +- The docs are accurate for the author's machine; a path or tool is not there elsewhere. +- Placeholder text ("TBD", "lorem") remains. +- The human asked for a fix to one section and the whole page was rewritten. diff --git a/done/native-gui-change.md b/done/native-gui-change.md new file mode 100644 index 0000000..0dd41c4 --- /dev/null +++ b/done/native-gui-change.md @@ -0,0 +1,31 @@ +--- +id: native-gui-change +title: Changing a native desktop or mobile interface +applies_to: A window, dialog or widget in a desktop or mobile application built with a native or immediate-mode toolkit. +--- + +## Done means +- The app starts from the built binary, reaches the changed screen through the real controls, and the change works there. +- The screen is captured and compared to a baseline: only the intended pixels changed. +- The view model and the logic behind it are tested without a window, so most of the behaviour needs no display. +- The change respects the data it shows: the UI does not write what it should only read, and every number shown is the engine's. +- Keyboard use, window resizing, high-DPI and long text behave. +- The human has seen the result, or accepted a recorded before-and-after. + +## Checks +- Pixels: `visual-regression-native-gui` (regression), rung 4; `pairwise-comparison` (intent) for whether the new one is better. +- Logic: unit and property tests on the view model (`proptest` or `hypothesis`, many-inputs); `derived-view-agreement` (many-inputs) so shown figures match the engine's. +- Read-only: `read-only-guarantee` (regression). +- Structure: `ui-structure-snapshot` (regression) where the toolkit exposes an accessibility tree. +- Install: `packaging-install-upgrade`, `cross-platform-matrix` (real-world). +- Taste: `taste-baseline`, `owner-acceptance-runbook` (intent), rung 6. + +## Common false finishes +- Unit tests of the model pass; the window was never opened. +- A screenshot from one platform, theme or scale factor stands for all. +- The baseline image was updated to match the new rendering without a person looking at it. +- Event handlers wired to the wrong widget when several look alike. +- The UI shows a number computed again in the UI code instead of the engine's, and they diverge in an edge case. +- Layout breaks with long text, empty data, or a narrow window. +- It runs on the developer's GPU or font set and fails on a clean machine. +- Closing or killing the app mid-action leaves bad data. diff --git a/done/new-library.md b/done/new-library.md new file mode 100644 index 0000000..2a1ebfe --- /dev/null +++ b/done/new-library.md @@ -0,0 +1,31 @@ +--- +id: new-library +title: Writing a new library +applies_to: A new package or module other code will depend on, with a public interface. +--- + +## Done means +- The public interface is written down, every function and type has documented behaviour, errors and limits, and nothing internal is exported by accident. +- Each documented rule is exercised by tests, including edge cases, bad input and the empty case. +- Properties that should hold for all inputs (round trips, ordering, no panic) are tested at rung 2 or better. +- It builds from a clean clone with only the declared dependencies and passes on every supported platform and version. +- Dependencies are audited and their licences allowed; there is a licence file and a README with an example that runs. +- There is no stub, skipped test, or placeholder left. + +## Checks +- Behaviour: `acceptance-examples` (intent) agreed with the human; `proptest`, `hypothesis`, `fast-check` or the language's equivalent (many-inputs), rung 2; `round-trip`, `algebraic-laws`. +- Tests are not hollow: `cargo-mutants`, `mutmut`, `stryker` or `pitest` (test-quality), `coverage-floor`. +- Interface: `api-semver-rust` or `api-surface-typescript` (regression) baseline recorded for the first release. +- Docs run: `doc-tests-and-links` (real-world). Clean machine: `clean-clone-build`, `cross-platform-matrix`. +- Safety: `rust-lints-strict`, `unsafe-audit`, `dependency-audit-rust` or `dependency-audit-general`, `licence-notices`. +- Complete: `no-stubs-scan`, `single-gate-command`, `spec-traceability` if a spec exists (completeness). + +## Common false finishes +- Only the happy-path examples from the README are tested. +- The README example does not compile or run; nobody ran it. +- Everything is public. The first release then freezes accidental surface. +- It works with the author's dependency versions only; no lower-bound or clean-lock build was tried. +- Panics or exceptions on empty, huge or non-UTF-8 input are untested. +- Thread-safety or `Send`/`Sync` claims are unstated and untested. +- Licence is missing or a dependency's licence conflicts with it. +- Test coverage is high but assertions are weak, so mutants survive. diff --git a/done/new-product.md b/done/new-product.md new file mode 100644 index 0000000..29fab5f --- /dev/null +++ b/done/new-product.md @@ -0,0 +1,32 @@ +--- +id: new-product +title: Building a whole new product from a short statement +applies_to: Turning a one-line or short description (an app, a service, a tool) into working software for real users. +--- + +## Done means +- The statement was turned into a written contract the human confirmed once: who it is for, what it must do, what it must never do, with concrete acceptance examples. +- Every requirement has an id, code and tests cite them, and none is left unbuilt (no stubs, skipped tests or placeholder data). +- The core logic has strong checks: proofs or property tests for its laws, a reference to compare to, hostile input for every parser. +- The product runs from a clean machine, installs, starts, and does the real job end to end through its public surface. +- It is safe: dependencies audited, secrets handled, trust boundaries modelled, data stored survives crashes and upgrades. +- One command defines done; documentation says how to run and verify it; a release path exists. +- The owner walked it and accepted it, and what was assumed is reported. + +## Checks +- What to build: `acceptance-examples`, `requirement-to-check-map` (completeness), `spec-traceability`; design: `tlaplus` or `quint` for state machines (design). +- Logic: `lean4-proofs`, `kani` or `proptest` (prove, many-inputs), rung 1 to 2; `stateful-model-test`, `differential-reference`, `round-trip`. +- Tests are real: `cargo-mutants` or the language's mutation tool, `vacuity-check`, `assertion-strength-review` (test-quality). +- Real world: `e2e-playwright` or `cli-transcript-tests`, `clean-clone-build`, `packaging-install-upgrade`, `cross-platform-matrix`. +- Safety: `rust-lints-strict`, `dependency-audit-rust`, `secret-scanning`, `threat-model-checklist`, `licence-notices`. +- Done: `single-gate-command`, `no-stubs-scan`, `check-tiering`, `release-gate`; the human: `owner-acceptance-runbook` (intent), rung 6. + +## Common false finishes +- The demo path works. The error, empty, large and concurrent cases were never tried. +- Features that were in the statement are quietly dropped or stubbed, and the final report does not list them. +- The tests are many and shallow: they pass, and mutants survive. +- It works from the author's environment and fails on a clean machine. +- Only what the agent chose to test was tested; no independent check, no owner walk-through. +- There is no persistence, backup or upgrade story, so the first update loses data. +- Decisions were made silently. Every assumption belongs in the contract and the report. +- "Done" was declared with no single command that proves it. diff --git a/done/numeric-or-financial-core.md b/done/numeric-or-financial-core.md new file mode 100644 index 0000000..4284ab9 --- /dev/null +++ b/done/numeric-or-financial-core.md @@ -0,0 +1,32 @@ +--- +id: numeric-or-financial-core +title: Numeric or financial calculation code +applies_to: Code that computes with money, quantities, rates or any number where a wrong digit is a wrong answer, such as ledgers, tax, interest, pricing. +--- + +## Done means +- Numbers are exact: money is integers or decimals, never binary floating point, with rounding rules named and applied in one place. +- Conservation laws hold for every input: debits equal credits, parts sum to the total, a reversal nets to zero, allocations lose no cent. +- Boundaries are decided and tested: zero, negative, the largest value, overflow, many decimal places, ties in rounding, currency conversion. +- Period, year and timezone boundaries behave; leap days and month ends are covered. +- Results agree with an independent source: a hand calculation, a reference implementation, a published example. +- The domain's own reports (trial balance, statements) foot and the human or an expert has read them. + +## Checks +- Laws for all inputs: `lean4-proofs`, `kani`, `verus`, `creusot` or `exhaustive-small-domain` (prove), rung 1, for the core invariants; else `proptest` or `hypothesis`, `algebraic-laws` (many-inputs), rung 2. +- Overflow and panics: `kani`, `cargo-fuzz`, `illegal-states-unrepresentable`. +- Independent answer: `differential-reference`, `differential-executable-spec`, `metamorphic`, `model-test-from-spec`. +- Rules traced: `spec-traceability` (completeness). +- Evidence for the human: `domain-evidence-report`, `golden-files-hand-verified`. +- Tests are real: `cargo-mutants`, `mutation-on-diff`; `rust-lints-strict` denying lossy casts (safety). +- Leaks: `sensitive-data-leak-test` for tax ids. + +## Common false finishes +- Example tests with round numbers pass; the cent that disappears on a three-way split is never tried. +- `float` or `double` is used somewhere in the path, even once. +- Rounding happens at each step instead of at the end, or at the end instead of each step, against the stated rule. +- A property test generates only small positive amounts, so negatives and huge values never occur. +- The proof covers a simplified model; the shipped code uses a different type or rounding. +- A report foots because both sides come from the same wrong figure. +- A reversal, a late entry, or a closed period was never tried. +- A surviving mutant in the arithmetic was written off without a reason in the `findings-log`. diff --git a/done/parser-or-codec.md b/done/parser-or-codec.md new file mode 100644 index 0000000..8777142 --- /dev/null +++ b/done/parser-or-codec.md @@ -0,0 +1,30 @@ +--- +id: parser-or-codec +title: Parsing, formatting or encoding code +applies_to: Code that turns bytes or text into structured data or back, including file formats, protocols and serialisers. +--- + +## Done means +- Valid input of every form the format allows parses to the right value, checked against an independent source (the specification's examples, a reference implementation). +- Encoding then decoding returns the original, and decoding then encoding returns the canonical form. +- Invalid and hostile input gives an error, never a crash, hang, huge allocation or wrong answer; there are bounds on size and nesting. +- Behaviour on the strange cases is decided and written down: duplicates, trailing data, byte order marks, case, whitespace, overlong encodings. +- Files written by it can be read by other tools, and the reverse. + +## Checks +- Round trip: `round-trip` (many-inputs), rung 2, with a generator that makes valid structures. +- Agreement with another implementation: `differential-reference`, `differential-executable-spec` (many-inputs), rung 2. +- Crashes and hangs: `cargo-fuzz`, `atheris`, `jazzer` or `go-fuzz`, with `structure-aware-fuzzing`, rung 2; run longer than a smoke test. +- Schema-based attack: `hostile-input-from-schema`. Seeds kept: `regression-seed-hygiene`. +- Known good files: `golden-files-hand-verified` (regression), `old-data-compatibility`. +- Grammar properties: `metamorphic`, `algebraic-laws`; small domains: `exhaustive-small-domain` (prove). +- Tests are real: `mutation-on-diff`. + +## Common false finishes +- Round trip passes only because the generator makes values the parser already handles; the strange values are never made. +- Fuzzing ran for a minute from an empty corpus, found nothing, and was called clean. +- Both directions share a bug (the same wrong table) so the round trip is symmetric and wrong. Compare to an independent oracle. +- Errors are tested by "it returns an error", not that the position and message are right. +- The decoder accepts input the specification forbids ("be liberal"), and other tools then disagree. +- Recursion depth, length prefixes, and decompression ratios are unbounded. +- Locale, endianness or Unicode normalisation differs on another machine. diff --git a/done/performance-work.md b/done/performance-work.md new file mode 100644 index 0000000..8f296ab --- /dev/null +++ b/done/performance-work.md @@ -0,0 +1,30 @@ +--- +id: performance-work +title: Performance or resource-use work +applies_to: A change whose goal is to make something faster, smaller or lighter. +--- + +## Done means +- A measured baseline was taken before the change, on stated hardware, with stated inputs, and the after-numbers are on the same setup. +- The improvement is larger than the noise, shown by repeated runs and a spread, and is the figure the request named (latency, throughput, memory, size). +- Results are identical: the same outputs for every input, including edge cases. +- It holds across the realistic range of inputs (small, large, adversarial), not only the one benchmarked. +- Other costs did not rise unseen (memory, start-up, binary size, tail latency). +- A guard now stops it getting worse again. + +## Checks +- Same results: `differential-old-vs-new` (many-inputs), rung 2; `characterization-tests`, `baseline-before-change` (regression). +- Measurement and guard: `perf-regression`, `size-budget`, `ratchet-floor` (regression), rung 3. +- Concurrency effects: `thread-sanitizer`, `stress-repeat` if threads were added. +- Under load: `load-test-k6` (real-world) for a service; `lighthouse-budget` for a web page. +- Tests are real: `mutation-on-diff`; gate: `single-gate-command`. + +## Common false finishes +- One timing run, a noisy machine, a 4% change called a win. +- Benchmarked in debug mode, or without optimisations the product ships with. +- The benchmark input is so small that the optimised path is never taken, or the compiler removed the work. +- A cache warmed by the benchmark loop; the cold case is slower than before. +- Speed gained by dropping a check, a copy that was needed, or precision; outputs differ in edge cases. +- Median improved and the 99th percentile got worse. +- Memory use went up as time went down and only time was measured. +- No guard was added, so the gain disappears in the next change. diff --git a/done/refactor.md b/done/refactor.md new file mode 100644 index 0000000..64d19ed --- /dev/null +++ b/done/refactor.md @@ -0,0 +1,31 @@ +--- +id: refactor +title: Refactoring +applies_to: Changing the structure of code without changing what it does. +--- + +## Done means +- Behaviour is identical for every input that mattered before: same outputs, same errors, same side effects, same public interface. +- Evidence of that was captured before the first edit, then compared after. +- No behaviour change is hiding in the diff (a "small fix" while there). +- The structure really got better in the way the request named (smaller, fewer dependencies, one place for a rule), and that can be measured. +- Performance and size did not get worse beyond what was agreed. + +## Checks +- Same behaviour on many inputs: `differential-old-vs-new` (many-inputs), rung 2, the strongest; run old and new on the same generated inputs. +- Same behaviour on known cases: `baseline-before-change`, `characterization-tests`, `golden-files-hand-verified` (regression), rung 3 to 4. Characterise before you edit. +- Interfaces: `api-semver-rust`, `api-surface-typescript` or `api-breaking-schema` (regression), rung 2. +- The tests can notice a change: `mutation-on-diff` (test-quality), rung 2. +- Structure goal: `architecture-lint` (regression); `ratchet-floor` for a metric that must only improve. +- Speed: `perf-regression`, `size-budget` (regression). +- Gate: `single-gate-command` (completeness), rung 3. + +## Common false finishes +- The suite passed, but the code had no tests where you changed it. A passing suite over untested code says nothing; add characterization tests first. +- Existing tests were edited during the refactor. Any test edit is a behaviour change until shown otherwise. +- Error messages, ordering of results, or timing changed, and a caller relied on it. +- A public name was renamed or moved and only in-repo callers were updated. +- Dead code was deleted that was reached by reflection, a config string, or a plugin. +- "Same behaviour" was checked on the happy path only; the error and empty paths differ. +- The refactor and a fix were merged into one diff, so neither can be reviewed. Separate them. +- The new structure is only a rename or a move, with the same coupling. diff --git a/done/release.md b/done/release.md new file mode 100644 index 0000000..a6f29d6 --- /dev/null +++ b/done/release.md @@ -0,0 +1,31 @@ +--- +id: release +title: Releasing a version +applies_to: Tagging, packaging and publishing a version of a program or library. +--- + +## Done means +- The version in the manifest, the tag, the changelog and the package name agree. +- The full test set ran on this exact commit, including the slow set, and its result is recorded with its age. +- The package was built from a clean checkout, not a developer's working tree, and its contents were inspected: licence, notices, the binary and nothing secret. +- Third-party notices and dependency audits are current. +- A fresh machine can install it, run it, and upgrade from the previous version with user data intact. +- Publishing was done from the gate, not by hand; it can be undone or was left as a draft until the owner tried it. + +## Checks +- One command: `release-gate`, `single-gate-command` (completeness), rung 3. +- Depth and freshness: `check-tiering` (completeness); mutation, proofs and fuzz evidence dates recorded. +- Package: `packaging-install-upgrade`, `clean-clone-build`, `cross-platform-matrix` (real-world), rung 3. +- Legal and security: `licence-notices`, `dependency-audit-rust` or `dependency-audit-general`, `secret-scanning` (safety). +- Interface: `api-semver-rust`, `api-breaking-schema` (regression) for the version bump. +- After publishing: `smoke-after-deploy` (real-world); the human, `owner-acceptance-runbook` (intent), rung 6. + +## Common false finishes +- Tests ran on the branch, then more commits landed before the tag. +- The tag and the manifest version differ, or the changelog is for the last release. +- Built on a dirty tree; a file that is not committed is in the package. +- The package lacks the licence or notices file, or includes a `.env` or test data. +- Install was tested on the machine that built it, where all the dependencies already exist. +- Upgrade from the previous version was not tried, and the data format changed. +- Slow tests, fuzzing and proofs were last run weeks ago and the release says "all checks passed". +- Published by hand, skipping the gate, because it was urgent. diff --git a/done/security-fix.md b/done/security-fix.md new file mode 100644 index 0000000..a5c5a6f --- /dev/null +++ b/done/security-fix.md @@ -0,0 +1,32 @@ +--- +id: security-fix +title: Fixing a security vulnerability +applies_to: A reported or discovered weakness (injection, access control, leaked secret, unsafe deserialisation, dependency flaw). +--- + +## Done means +- The vulnerability is reproduced by an exploit-shaped test that fails before the fix and passes after, using the attacker's route, not an internal call. +- The root cause is fixed everywhere the pattern occurs, not just at the reported spot. +- Variants of the attack (encoding, case, path forms, another endpoint) are tried and refused. +- Legitimate behaviour is unchanged: the existing suite and the happy paths pass. +- If a secret leaked, it was rotated and the leak path was closed; history cleanup is not a substitute for rotation. +- The advisory or write-up says what was affected, the fixed version, and what users must do. + +## Checks +- Exploit test: `red-before-green` (test-quality), rung 3; `hostile-input-from-schema`, `cargo-fuzz` or `atheris` (many-inputs) for input flaws, rung 2. +- Variants and siblings: `static-analysis-semgrep`, `codeql` (safety), rung 2; record in `findings-log` (completeness). +- Written model: `threat-model-checklist` (safety) with a check for each way in. +- Leaks: `secret-scanning`, `sensitive-data-leak-test`; dependency issues: `dependency-audit-rust`, `dependency-audit-general`. +- Access: `multi-user-isolation` (real-world). +- No regressions: `baseline-before-change`, `single-gate-command`; memory issues: `address-and-ub-sanitizers`, `unsafe-audit`. + +## Common false finishes +- The exploit was blocked for the example payload; one encoding variant (URL, Unicode, double encoding) still works. +- The check is in the UI, not on the server. +- The reported route is fixed; the same code path is reachable by another endpoint. +- A leaked key was removed from the repository but not rotated. +- A denylist was added instead of an allowlist or a safe API. +- The fix breaks a legitimate use and was reverted under pressure; run the full suite. +- The error message still reveals what was probed, or a stack trace. +- No test; the next refactor reintroduces it. +- Upgrading the dependency is called done without checking the advisory's affected range against the lockfile. diff --git a/done/service-api.md b/done/service-api.md new file mode 100644 index 0000000..d3849a4 --- /dev/null +++ b/done/service-api.md @@ -0,0 +1,31 @@ +--- +id: service-api +title: Building or changing a service or HTTP API +applies_to: A server whose clients call it over a network: its endpoints, messages, status codes and storage. +--- + +## Done means +- Each endpoint does what its written contract says for valid, invalid, empty, large and repeated requests, and returns the documented status codes and error bodies. +- Clients that exist still work: the change is backward compatible, or the break is deliberate, versioned and announced. +- Authorisation is enforced on every route, and one user or tenant cannot see or change another's data. +- Retries and concurrent requests do not corrupt state or double-apply an effect. +- It starts from a clean environment, migrates its storage, and answers a health check; after deploy a smoke test passes. +- It holds under expected load and handles dependency failures. + +## Checks +- Contract: `contract-testing-pact`, `api-breaking-schema` (regression and real-world), rung 2 to 3. +- Hostile and random requests: `hostile-input-from-schema`, `proptest` or `hypothesis`, `stateful-model-test` (many-inputs), rung 2. +- Isolation: `multi-user-isolation` (real-world), rung 3; concurrency: `stress-repeat`, `deterministic-simulation`, `linearizability-checking`. +- Storage: `db-migration-safety` (regression), `fault-injection-storage`, `old-data-compatibility`. +- Deploy: `smoke-after-deploy`, `load-test-k6`, `runtime-self-check` (real-world). +- Safety: `threat-model-checklist`, `static-analysis-semgrep`, `dependency-audit-general`, `secret-scanning`, `sensitive-data-leak-test`. + +## Common false finishes +- Tests call handlers directly and skip authentication, serialisation and middleware. +- Only a single user is tested, so tenant isolation is unknown. +- A new required field breaks existing clients and nobody ran the old client's requests. +- An idempotency or retry case was not tried; a client timeout leads to a double charge. +- Error responses leak stack traces, SQL or other users' ids. +- The migration works on an empty database and fails on real data. +- Passes against a mock of the dependency; the real one behaves differently. +- Load was tested with one repeated request, so caches hid real cost. diff --git a/done/storage-engine.md b/done/storage-engine.md new file mode 100644 index 0000000..2fd092c --- /dev/null +++ b/done/storage-engine.md @@ -0,0 +1,33 @@ +--- +id: storage-engine +title: A storage engine, database layer or persistent format +applies_to: Code that writes data to disk or a database and must read it back correctly after crashes, upgrades and concurrency. +--- + +## Done means +- What is written is what is read back, for all value shapes, including the empty, the largest and the unusual. +- A crash or power loss at any point leaves the store either as before or as after, never in between, and recovery works. +- Concurrent readers and writers see consistent states, with the isolation the documentation promises. +- Files written by every earlier version still open; the new version's files are rejected or migrated safely by older ones. +- Corruption is detected and reported, not silently returned. +- Disk full, permission denied and a failed write are handled without damaging existing data. +- Performance and size on realistic volume are measured. + +## Checks +- Round trip and model: `stateful-model-test`, `round-trip`, `model-test-from-spec` (many-inputs), rung 2. +- Crash and failure: `fault-injection-storage`, `deterministic-simulation` (concurrency), rung 2. +- Consistency: `linearizability-checking`, `loom` or `shuttle`, `stress-repeat`. +- Old data: `old-data-compatibility`, `replay-equivalence`, `derived-view-agreement`; migration: `db-migration-safety`. +- Hostile files: `cargo-fuzz`, `structure-aware-fuzzing`. +- Design: `tlaplus` or `quint` for recovery protocols (design), rung 1. +- Read-only paths: `read-only-guarantee`. Speed: `perf-regression`. + +## Common false finishes +- Tests never kill the process mid-write; the write-then-rename or log protocol was not exercised. +- `fsync` was not called (or the directory was not synced), and the test machine's cache hid it. +- The store was tested in memory or on tmpfs, not on a real disk. +- One thread only; a second writer breaks it. +- The test reopened the store in the same process, which kept caches alive. Restart a fresh process. +- An old file from the previous release was never opened. +- Corrupted bytes are returned as valid data because there is no checksum. +- A lock file is left behind after a crash and blocks the next start. diff --git a/done/web-ui-change.md b/done/web-ui-change.md new file mode 100644 index 0000000..6eae6e9 --- /dev/null +++ b/done/web-ui-change.md @@ -0,0 +1,33 @@ +--- +id: web-ui-change +title: Changing a web interface +applies_to: A page, component or flow in a browser-based user interface. +--- + +## Done means +- The page works in a real browser through the real user journey, not only in a component test. +- It looks right at the sizes users use (phone, tablet, desktop) and nothing else on the page moved unintentionally. +- It is usable by keyboard and screen reader, with sufficient contrast. +- Loading, empty, error and slow-network states exist and are shown correctly. +- The change did not make the page measurably slower or heavier. +- The human has seen it, or the person's verdict on a before-and-after is recorded. + +## Checks +- Journey: `e2e-playwright` (real-world), rung 3, running the actual flow with assertions on what the user sees. +- Appearance: `visual-regression-web` (regression), rung 4; `pairwise-comparison` and `taste-baseline` (intent) for whether it is better. +- Structure: `ui-structure-snapshot` (regression) for the accessibility tree. +- Accessibility: `accessibility-axe` (real-world), rung 2 to 3. +- Performance: `lighthouse-budget`, `size-budget`, `perf-regression`. +- Contract with the backend: `contract-testing-pact`. Invariants: `baseline-before-change`. +- Judge: `rubric-judge` (intent) for tone and clarity, rung 5; the human for taste, rung 6. + +## Common false finishes +- Screenshots were taken after the change but not compared with before; "looks fine" is a guess. +- The snapshot was regenerated to match the new output, so the diff proves nothing. Look at the images. +- Tested at one viewport and one browser. +- Only the success path was tested; the error and empty states look broken. +- Component tests pass while the page fails to load because of a bundle, route or auth problem. +- Text overflows or truncates with long names, other languages or large font settings. +- A new element is not reachable by keyboard, or steals focus. +- Passing a11y scans taken as proof the page is accessible; they find only a fraction of problems. +- The dev server was tested and the production build was not. diff --git a/sisi/__init__.py b/sisi/__init__.py new file mode 100644 index 0000000..31c1a7e --- /dev/null +++ b/sisi/__init__.py @@ -0,0 +1,2 @@ +"""sisi: one rulebook and enforced definitions of done for every AI coding CLI.""" +__version__ = "0.1.0" diff --git a/sisi/__main__.py b/sisi/__main__.py new file mode 100644 index 0000000..078ad57 --- /dev/null +++ b/sisi/__main__.py @@ -0,0 +1,3 @@ +import sys +from .cli import main +sys.exit(main(sys.argv[1:])) diff --git a/sisi/audit.py b/sisi/audit.py new file mode 100644 index 0000000..43f729e --- /dev/null +++ b/sisi/audit.py @@ -0,0 +1,119 @@ +"""Inventory of standing instructions each tool loads. Counts lines; does not judge.""" +import glob, json, os, re + +from . import paths + + +def _lines(p): + try: + with open(p, "rb") as f: + return f.read().count(b"\n") + 1 + except OSError: + return None + + +def _imports(p, depth=0, seen=None): + """Files pulled in by `@path` lines (Claude Code import syntax).""" + seen = seen if seen is not None else set() + out = [] + try: + text = open(p, encoding="utf-8", errors="replace").read() + except OSError: + return out + for m in re.finditer(r"^@(\S+)\s*$", text, re.M): + q = os.path.expanduser(m.group(1)) + if not os.path.isabs(q): + q = os.path.join(os.path.dirname(p), q) + if q not in seen and os.path.isfile(q): + seen.add(q) + out.append(("import of %s" % os.path.basename(p), q)) + if depth < 4: + out += _imports(q, depth + 1, seen) + return out + + +def _skills(d, label): + return [(label, f) for f in sorted(glob.glob(os.path.join(d, "*", "SKILL.md")))] + + +def _dirmd(d, label): + return [(label, f) for f in sorted(glob.glob(os.path.join(d, "**", "*.md"), recursive=True))] + + +def collect(): + h = paths.home() + j = lambda *a: os.path.join(h, *a) + inv = {} + cl = [] + for f in (j(".claude", "CLAUDE.md"),): + if os.path.isfile(f): + cl.append(("global instructions", f)) + cl += _imports(f) + cl += _dirmd(j(".claude", "rules"), "rules") + cl += _skills(j(".claude", "skills"), "skill") + cl += _skills(j(".agents", "skills"), "skill (shared)") + try: + with open(j(".claude", "plugins", "installed_plugins.json"), encoding="utf-8") as f: + plugins = json.load(f).get("plugins", {}) + except (OSError, ValueError, AttributeError): + plugins = {} + for name, entries in sorted(plugins.items()): + for e in entries if isinstance(entries, list) else []: + ip = e.get("installPath") if isinstance(e, dict) else None + if ip: + pl = "plugin " + name + cl += _skills(ip, pl + " skill") + _dirmd(os.path.join(ip, "commands"), pl + " command") \ + + _dirmd(os.path.join(ip, "agents"), pl + " agent") + inv["claude-code"] = cl + cx = [] + for n in ("AGENTS.override.md", "AGENTS.md"): + f = j(".codex", n) + if os.path.isfile(f): + cx.append(("global instructions", f)) + cx += _skills(j(".codex", "skills"), "skill") + _skills(j(".agents", "skills"), "skill (shared)") + inv["codex"] = cx + oc = [] + f = j(".config", "opencode", "AGENTS.md") + if os.path.isfile(f): + oc.append(("global instructions", f)) + else: + f2 = j(".claude", "CLAUDE.md") + if os.path.isfile(f2): + oc.append(("global instructions (fallback to Claude's file)", f2)) + for n in ("opencode.json", "opencode.jsonc"): + cf = j(".config", "opencode", n) + try: + for ins in json.load(open(cf, encoding="utf-8")).get("instructions", []): + q = os.path.expanduser(ins) + if os.path.isfile(q): + oc.append(("config instructions", q)) + except (OSError, ValueError, AttributeError): + pass + oc += _dirmd(j(".config", "opencode", "agents"), "agent") + _dirmd(j(".config", "opencode", "commands"), "command") + oc += _skills(j(".agents", "skills"), "skill (shared)") + inv["opencode"] = oc + mu = [] + for f in (j(".config", "muse", "AGENTS.md"),): + if os.path.isfile(f): + mu.append(("global instructions", f)) + mu += _skills(j(".agents", "skills"), "skill (shared)") + inv["muse"] = mu + return inv + + +def main(args=()): + inv = collect() + grand = 0 + for tool, items in inv.items(): + print("%s" % tool) + tot = 0 + for label, f in items: + n = _lines(f) or 0 + tot += n + print(" %6d %-34s %s" % (n, label[:34], f)) + if not items: + print(" (none found)") + print(" %6d total\n" % tot) + grand += tot + print("all tools: %d lines (shared files counted once per tool)" % grand) + return 0 diff --git a/sisi/cli.py b/sisi/cli.py new file mode 100644 index 0000000..3df6e6b --- /dev/null +++ b/sisi/cli.py @@ -0,0 +1,406 @@ +"""Command dispatch. Heavy modules are imported lazily so hooks (tick, gate) stay fast.""" +import json, os, sys + +HELP = """sisi: shared rulebook and enforced definitions of done for every AI coding CLI + + sisi contract init [--goal TEXT] create .sisi/contract.json here + sisi contract check validate the contract + sisi contract waive "" record that this change needs no checks + sisi contract trust | untrust allow / stop allowing this project's contract to run commands + sisi verify [--json] run the fast checks; exit 0 ok, 1 failure, 2 no contract, 3 untrusted + sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once + sisi verify --all | --state run both tiers; print only the deep-check state (with --json) + sisi gate end-of-turn hook (reads hook JSON on stdin) + sisi tick session-start hook + sisi install | uninstall | doctor wire sisi into the tools (by reference), undo, inspect + sisi release [--deep] run the source's checks, then make the stable copy the tools run (see docs/developing.md) + sisi rollback switch the stable copy back to the previous release + sisi dev on [PATH] | off | status developer mode: where the source folder is + sisi promote ID [--apply] scrub a personal overlay item and write it into the source folder (dry run unless --apply) + sisi migrate move an older installation's personal data into the personal folder (safe to repeat) + sisi update fast-forward the product clone, then back up, migrate and rebuild personal data + sisi export [PATH] | import PATH one tar.gz of personal data, results and session records; restore it + sisi build-canon regenerate the effective rulebook (base rules + your overlay) + sisi canon cost size of what is always loaded: rulebook lines and characters, lessons block maximum + sisi overlay list|diff|add-rule|replace-rule|disable-rule|enable-rule|add-verifier|...|revert COMMIT + learned changes to rules, verifiers and recipes; each one a commit in your personal repo + sisi audit inventory of standing instructions per tool + sisi retro --aim A --moment M --cause C --change-kind K --change X [--target ID] [--same-as ID | --new] + (or --json - with the same keys on stdin) + end of every piece of work: HOW it could have gone better + aims: level (the human could have worked at a higher level), verified (a stronger check was + possible), hands-off (the human was interrupted more than needed), intent (the result was not + what they meant), speed (it took longer than it had to) + sisi lessons [filters] | show ID | set ID --status S | apply ID | export [FILE] | import FILE + the shared lessons from retros (--aim --kind --status --repo --top --json) + sisi note TEXT (older; prefer retro) record something that went wrong + sisi propose TEXT (older; prefer retro) suggest a rule change + sisi learn TEXT record a human-stated preference (quarantined until verified) + sisi oracle print what the human wants (oracle.md in the personal folder) + sisi status verification statistics from the store + sisi time [--json] time from request to verified result: 7 days against the 7 before, slowest checks + sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json] + list ways to know work is correct, by section + sisi verifiers show ID one entry in full, and whether its tool is installed here + sisi verifiers for "" best-matching verifiers for a claim or piece of work + sisi verifiers doctor | lint which tools are installed; validate the library + sisi done [ID] recipes: which checks make a kind of work done + sisi done for "" best-matching recipe + sisi version | --version print the product version (the VERSION file in the product folder) + sisi help this text + +Three places: the product (this clone, never written at run time), your personal data +(~/.local/share/sisi, its own git repository), and scratch (~/.local/state/sisi). +Environment: SISI_HOME (stands in for the home directory), SISI_DATA (personal data folder), +SISI_STATE (scratch dir), SISI_LIB (where stable releases live, default ~/.local/lib/sisi), SISI_TOOL (name recorded with results), SISI_VERIFIERS and SISI_DONE +(library directories, default verifiers/ and done/ in the product). +""" + + +def _pop_opt(args, name): + """Remove `name VALUE` from args, return value or None.""" + if name in args: + i = args.index(name) + v = args[i + 1] if i + 1 < len(args) else None + del args[i:i + 2] + return v + return None + + +def cmd_contract(args): + from . import contract as C, gitutil, store, trust + sub = args[0] if args else "" + if sub == "init": + goal = _pop_opt(args, "--goal") + p = os.path.join(os.getcwd(), C.REL) + if os.path.exists(p): + print("sisi: %s already exists" % p) + return 1 + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "w", encoding="utf-8") as f: + json.dump(C.skeleton(goal), f, indent=2) + f.write("\n") + trust.add(os.getcwd()) + print("created %s as a SKELETON, not a contract yet: replace the placeholder check with a real command " + "(rung 1-4) and add every check that shows the work is done. Until then `sisi verify` fails and " + "the end-of-turn gate ignores it." % p) + return 0 + if sub == "check": + p = C.find(os.getcwd()) + if not p: + print("sisi: no contract found") + return 2 + try: + c = C.load(p) + except (OSError, ValueError) as e: + print("sisi: cannot read %s: %s" % (p, e)) + return 1 + errs = C.validate(c) + for e in errs: + print(" - " + e) + if not errs: + for f in C.floor_failures(c): + errs.append(f["message"]) + print(" - " + f["message"]) + if not errs: + for w in C.warnings(c): + print("warning: " + w) + print("contract invalid" if errs else "contract ok: %s" % p) + return 1 if errs else 0 + if sub == "waive": + reason = " ".join(args[1:]).strip() + if not reason: + print('usage: sisi contract waive ""') + return 1 + import time + project = gitutil.root(os.getcwd()) or os.getcwd() + extra = {} + if gitutil.root(os.getcwd()): + m = gitutil.measure(os.getcwd()) + extra = {"head": gitutil.head(os.getcwd()), "lines": m["lines"], "files": m["files"]} + store.append("waivers", store.stamp(dict({"project": project, "reason": reason, "ns": time.time_ns()}, **extra))) + print("waiver recorded for %s" % project) + return 0 + if sub in ("trust", "untrust"): + p = C.find(os.getcwd()) + if not p: + print("sisi: no contract found here") + return 2 + (trust.add if sub == "trust" else trust.remove)(C.project_dir(p)) + _commit_personal(trust._file(), "trust: %s %s" % (sub, C.project_dir(p))) + print("%sed %s" % (sub, C.project_dir(p))) + return 0 + print("usage: sisi contract init|check|waive|trust|untrust") + return 1 + + +def _commit_personal(path, msg): + """Commit a personal file that just changed (no-op for files outside the personal folder).""" + from . import paths, pdata + if os.path.dirname(path) == paths.data(): + pdata.commit(msg, [os.path.basename(path)]) + + +def cmd_store(kind, args): + from . import store + text = " ".join(args).strip() + if not text: + print("usage: sisi %s TEXT" % {"notes": "note", "proposals": "propose", "quarantine": "learn"}[kind]) + return 1 + store.append(kind, store.stamp({"text": text})) + _commit_personal(store.file_path(kind), "%s: %s" % ({"notes": "note", "proposals": "proposal", "quarantine": "learn"}[kind], " ".join(text.split())[:60])) + print("recorded" + (" (quarantined until verified)" if kind == "quarantine" else "")) + return 0 + + +ORACLE_EMPTY = """# sisi oracle + +What the human wants, so a thing is asked once ever. Empty so far: it is filled from preferences +the human stated (`sisi learn`) once they are verified. +""" + + +def cmd_oracle(): + from . import paths + try: + with open(paths.data_file("oracle.md"), encoding="utf-8") as f: + sys.stdout.write(f.read()) + except OSError: + sys.stdout.write(ORACLE_EMPTY) + return 0 + + +def _status_retro(): + try: + from . import retro + st = retro.stats() + except Exception: + return + print("lessons : %d total, %d open, %d applied; %d occurrences in the last 7 days" + % (st["total"], st["open"], st["applied"], st["occ7"])) + w = st["sessions_with_work"] + print("retros : %s of sessions with real work recorded one (%d of %d)" + % ("%.0f%%" % (100 * st["sessions_with_retro"] / w) if w else "n/a", st["sessions_with_retro"], w)) + for t in st["top"]: + print(" open #%-4d x%-3d %s" % (t["id"], t["count"], " ".join(t["change"].split())[:90])) + + +def _status_contracts(res): + """Per recent contract: latest fast run result and the deep state.""" + from . import contract as C, deep, verify as V + last = {} + for r in res: + if r.get("run") and r.get("item") in ("check", "invariant", "floor"): + k = (r.get("project"), r.get("contract")) + e = last.setdefault(k, {"ts": "", "fast": {}}) + e["ts"] = max(e["ts"], r.get("ts", "")) + if r.get("tier", "fast") == "fast": + e["fast"].setdefault(r["run"], []).append(r["status"]) + if not last: + return + print("recent contracts:") + for (project, cid), e in sorted(last.items(), key=lambda kv: kv[1]["ts"], reverse=True)[:5]: + runs = e["fast"] + fast = "-" + if runs: + # runs are keyed by hex timestamp-pid ids: the largest key is the newest + latest = runs[max(runs, key=lambda k: int(k.split("-")[0], 16))] + fast = "pass" if all(x in ("passed", "awaiting-human") for x in latest) else "fail" + dstate = "n/a" + try: + cp = os.path.join(project, C.REL) + c = C.load(cp) + ds = deep.deep_state(c, project, V.tree_fp(project, cp)) + dstate = ds["state"] if ds else "none" + except Exception: + dstate = "unknown" + print(" %-24s fast: %-5s deep: %s" % (cid, fast, dstate)) + + +def cmd_status(): + from . import store + res = store.read("results") + runs = {} + rungs = {} + for r in res: + if r.get("item") in ("check", "invariant", "floor") and r.get("run"): + runs.setdefault((r.get("project"), r.get("contract"), r["run"]), []).append(r) + if r.get("item") == "check" and r.get("rung"): + rungs[r["rung"]] = rungs.get(r["rung"], 0) + 1 + passed = [k for k, v in runs.items() if all(x["status"] in ("passed", "awaiting-human") for x in v)] + verified = {(k[0], k[1]) for k in passed} + unver = sum(1 for r in res if r.get("status") == "unverified") + waivers = len(store.read("waivers")) + print("contracts verified : %d (of %d seen)" % (len(verified), len({(k[0], k[1]) for k in runs}))) + print("verify runs : %d, pass rate %s" % (len(runs), "%.0f%%" % (100 * len(passed) / len(runs)) if runs else "n/a")) + tot = sum(rungs.values()) + print("checks by rung : " + (", ".join("%d: %.0f%%" % (k, 100 * v / tot) for k, v in sorted(rungs.items())) if tot else "none")) + print("unverified passes : %d" % unver) + print("waivers : %d" % waivers) + try: + from . import overlay + print("always loaded : " + overlay.cost_line()) + except Exception: + pass + try: + from . import delivery + print(delivery.median_line()) + except Exception: + pass + _status_retro() + _status_contracts(res) + from . import verifiers + vs = [e for e in verifiers.load_verifiers() if e["header"]] + by = {} + for e in vs: + k = e["header"].get("verified", "unset") + by[k] = by.get(k, 0) + 1 + print("library : %d verifiers (verified ran %d, docs %d, memory %d%s), %d recipes" + % (len(vs), by.get("ran", 0), by.get("docs", 0), by.get("memory", 0), + "".join(", %s %d" % (k, v) for k, v in sorted(by.items()) if k not in ("ran", "docs", "memory")), + len(verifiers.load_recipes()))) + return 0 + + +def cmd_wiring(name): + from . import wiring + if name == "doctor": + rows = wiring.doctor() + w = max(len(r["tool"]) for r in rows) + for r in rows: + print("%-*s %-9s blocking hook: %-8s %s" % (w, r["tool"], r["status"], r["blocking_hook"][:60], r["detail"])) + return 0 + rc, notes = getattr(wiring, name)() + for n in notes: + print(n) + return rc + + +def cmd_personal(cmd, args): + from . import lifecycle, overlay, pdata + try: + if cmd == "overlay": + return overlay.main(args) + if cmd == "update": + return lifecycle.cmd_update(args) + if cmd == "migrate": + for n in lifecycle.run() or ["nothing to migrate: personal data is in place"]: + print(n) + return 0 + if cmd == "build-canon": + b = overlay.build_canon() + print("%s: %d lines, %d characters%s" % (b["path"], b["lines"], b["chars"], "" if b["changed"] else " (unchanged)")) + if b["over_budget"]: + print("sisi: over the %d-line budget; shorten or replace a rule" % overlay.MAX_LINES, file=sys.stderr) + return 1 + return 0 + if cmd == "canon": + if args[:1] == ["cost"]: + print(overlay.cost_line()) + return 0 + print("usage: sisi canon cost") + return 1 + if cmd == "export": + print("exported to %s" % lifecycle.export(args[0] if args else None)) + return 0 + if cmd == "import": + if len(args) != 1: + print("usage: sisi import PATH") + return 1 + for n in lifecycle.import_archive(args[0]): + print(n) + print("imported") + return 0 + except (pdata.DataError, overlay.OverlayError) as e: + print("sisi %s: %s" % (cmd, e), file=sys.stderr) + return 1 + return 64 + + +def main(argv): + args = list(argv) + t = _pop_opt(args, "--tool") + if t: + os.environ["SISI_TOOL"] = t + cmd = args.pop(0) if args else "help" + if cmd == "gate": + from . import gate + return gate.main(args) + if cmd == "tick": + from . import tick + return tick.main(args) + if cmd in ("version", "--version", "-V"): + from . import paths + try: + with open(os.path.join(paths.REPO, "VERSION"), encoding="utf-8") as f: + print(f.read().strip()) + except OSError: + print("sisi: no VERSION file in %s" % paths.REPO, file=sys.stderr) + return 1 + return 0 + if cmd in ("help", "-h", "--help"): + print(HELP, end="") + return 0 + if cmd == "contract": + return cmd_contract(args) + if cmd == "verify": + from . import verify + return verify.cmd_verify(args) + if cmd in ("install", "uninstall", "doctor"): + return cmd_wiring(cmd) + if cmd in ("migrate", "update", "export", "import", "build-canon", "canon", "overlay"): + return cmd_personal(cmd, args) + if cmd in ("release", "rollback", "dev", "promote"): + from . import release + try: + return {"release": release.cmd_release, "rollback": release.cmd_rollback, + "dev": release.cmd_dev, "promote": release.cmd_promote}[cmd](args) + except release.ReleaseError as e: + print("sisi %s: %s" % (cmd, e), file=sys.stderr) + return 1 + if cmd == "audit": + from . import audit + return audit.main(args) + if cmd in ("note", "propose", "learn"): + return cmd_store({"note": "notes", "propose": "proposals", "learn": "quarantine"}[cmd], args) + if cmd == "retro": + from . import retro + return retro.cmd_retro(args) + if cmd == "lessons": + from . import retro + return retro.cmd_lessons(args) + if cmd == "oracle": + return cmd_oracle() + if cmd == "status": + return cmd_status() + if cmd == "time": + from . import delivery + return delivery.cmd_time(args) + if cmd == "verifiers": + from . import verifiers + return verifiers.main(args) + if cmd == "done": + from . import verifiers + return verifiers.done_main(args) + rc = _learn_cli(cmd, args) + if rc is not None: + return rc + print("sisi: unknown command %r (try `sisi help`)" % cmd, file=sys.stderr) + return 64 + + +def _learn_cli(cmd, args): + """Data-layer commands (harvest, tasks, ...) live in learn_cli. The CLI works without it, even if it is broken.""" + try: + import argparse + from . import learn_cli + ap = argparse.ArgumentParser(prog="sisi") + sub = ap.add_subparsers(dest="cmd") + learn_cli.register(sub) + if cmd not in sub.choices: + return None + ns = ap.parse_args([cmd] + args) + return ns.func(ns) + except (ImportError, AttributeError, TypeError) as e: + print("sisi: the %r command is unavailable (%s)" % (cmd, e), file=sys.stderr) + return 70 diff --git a/sisi/contract.py b/sisi/contract.py new file mode 100644 index 0000000..4782fbf --- /dev/null +++ b/sisi/contract.py @@ -0,0 +1,236 @@ +"""Contract file: location, skeleton, validation, floors.""" +import json, os, re + +from . import paths, gitutil + +KINDS = ["general", "concurrency", "parsing", "money", "state-machine", "migration", "ui"] +REL = os.path.join(".sisi", "contract.json") + + +def find(cwd): + """Nearest contract in cwd or an ancestor, stopping at the git root. Returns path or None.""" + cwd = os.path.abspath(cwd) + top = gitutil.root(cwd) + d = cwd + while True: + p = os.path.join(d, REL) + if os.path.isfile(p): + return p + if d == top or os.path.dirname(d) == d or top is None: + return None + d = os.path.dirname(d) + + +def project_dir(contract_path): + return os.path.dirname(os.path.dirname(contract_path)) + + +PLACEHOLDER_CMD = "echo 'TODO: replace this command with a real check' >&2; false" + + +def is_unedited_skeleton(c): + """True while every check still carries the placeholder command (nothing real has been written yet).""" + try: + return bool(c["checks"]) and not c.get("invariants") and all(x.get("cmd") == PLACEHOLDER_CMD for x in c["checks"]) + except (AttributeError, KeyError, TypeError): + return False + + +def skeleton(goal=None, cwd=None): + name = re.sub(r"[^a-z0-9]+", "-", os.path.basename(os.path.abspath(cwd or os.getcwd())).lower()).strip("-") + return { + "id": name or "work", + "goal": goal or "TODO: one sentence describing the outcome", + "checks": [{ + "id": "c1", + "claim": "PLACEHOLDER (fast tier, runs at the end of every turn, 60 s at most): replace with what this check shows to be true", + "kind": "general", + "rung": 3, + "cmd": PLACEHOLDER_CMD, + "expect": {"exit": 0}, + "timeout_s": 60, + }, { + "id": "deep-example", + "claim": "PLACEHOLDER (deep tier): replace or delete. For checks that take minutes or more: mutation testing, fuzzing, long proofs", + "kind": "general", + "rung": 2, + "tier": "deep", + "cmd": PLACEHOLDER_CMD, + "expect": {"exit": 0}, + "timeout_s": 3600, + }], + "invariants": [], + "assumptions": [], + "questions": [], + } + + +def load(path): + with open(path, encoding="utf-8") as f: + return json.load(f) + + +def floors(): + try: + with open(paths.canon("floors.json"), encoding="utf-8") as f: + return {k: int(v) for k, v in json.load(f).items()} + except (OSError, ValueError): + return {} + + +def _num(x): + return isinstance(x, (int, float)) and not isinstance(x, bool) + + +def _str(x): + return isinstance(x, str) and x.strip() != "" + + +TIERS = ("fast", "deep") + + +def _tier(x, where, errs): + t = x.get("tier", "fast") + if t not in TIERS: + errs.append("%s: tier must be fast or deep" % where) + return + if t == "fast" and x.get("rung") not in (5, 6): + from . import store + cfg = store.config()["verify"] + limit = cfg["fast_limit_s"] + to = x.get("timeout_s", cfg["default_timeout_s"]) + if _num(to) and to > limit: + errs.append('%s: timeout_s %g is over the fast limit of %g s; mark it "tier": "deep" ' + "(deep checks run with `sisi verify --deep`, never in the end-of-turn gate)" % (where, to, limit)) + + +def warnings(c): + """Non-fatal findings.""" + from . import store + cfg = store.config() + tot = 0.0 + for x in list(c.get("checks", [])) + list(c.get("invariants", [])): + if isinstance(x, dict) and x.get("tier", "fast") == "fast" and x.get("cmd") and x.get("rung") not in (5, 6): + to = x.get("timeout_s", cfg["verify"]["default_timeout_s"]) + tot += to if _num(to) else 0 + budget = cfg["gate"]["budget_s"] + return ["the fast timeouts add up to %g s, more than the gate budget of %g s: some checks may be reported as " + "timed out at the end of a turn" % (tot, budget)] if tot > budget else [] + + +def _expect(e, where, errs): + if not isinstance(e, dict): + errs.append("%s: expect must be an object" % where) + return + if not (isinstance(e.get("exit"), int) and not isinstance(e.get("exit"), bool)): + errs.append("%s: expect.exit must be an integer" % where) + sc = e.get("stdout_contains") + if sc is not None and not isinstance(sc, str): + errs.append("%s: expect.stdout_contains must be a string" % where) + for k in e: + if k not in ("exit", "stdout_contains"): + errs.append("%s: unknown expect key %r" % (where, k)) + + +def validate(c): + """Return a list of error strings; empty means valid.""" + errs = [] + if not isinstance(c, dict): + return ["contract must be a JSON object"] + for k in ("id", "goal"): + if not _str(c.get(k)): + errs.append("%s must be a non-empty string" % k) + if "parallel" in c and not isinstance(c["parallel"], bool): + errs.append("parallel must be true or false") + ids = set() + checks = c.get("checks") + if not isinstance(checks, list) or not checks: + errs.append("checks must be a non-empty list with at least one runnable check " + "(rung 1-4 with a cmd); to say a change needs no checks run `sisi contract waive \"\"`") + checks = [] + for i, ch in enumerate(checks): + w = "checks[%d]" % i + if not isinstance(ch, dict): + errs.append(w + " must be an object") + continue + if not _str(ch.get("id")): + errs.append(w + ".id must be a non-empty string") + else: + w = "check %r" % ch["id"] + if ch["id"] in ids: + errs.append("duplicate id %r" % ch["id"]) + ids.add(ch["id"]) + if not _str(ch.get("claim")): + errs.append(w + ": claim must be a non-empty string") + if ch.get("kind") not in KINDS: + errs.append("%s: kind must be one of %s" % (w, ", ".join(KINDS))) + r = ch.get("rung") + if not (isinstance(r, int) and not isinstance(r, bool) and 1 <= r <= 6): + errs.append(w + ": rung must be an integer 1-6") + elif r >= 5: + if ch.get("cmd"): + errs.append(w + ": rung 5 and 6 checks must not have a cmd") + else: + if not _str(ch.get("cmd")): + errs.append(w + ": rung 1-4 checks need a cmd") + _expect(ch.get("expect"), w, errs) + if "timeout_s" in ch and not (_num(ch["timeout_s"]) and ch["timeout_s"] > 0): + errs.append(w + ": timeout_s must be a positive number") + _tier(ch, w, errs) + if "serial" in ch and not isinstance(ch["serial"], bool): + errs.append(w + ": serial must be true or false") + inv = c.get("invariants", []) + if not isinstance(inv, list): + errs.append("invariants must be a list") + inv = [] + for i, iv in enumerate(inv): + w = "invariants[%d]" % i + if not isinstance(iv, dict): + errs.append(w + " must be an object") + continue + if not _str(iv.get("id")): + errs.append(w + ".id must be a non-empty string") + else: + w = "invariant %r" % iv["id"] + if iv["id"] in ids: + errs.append("duplicate id %r" % iv["id"]) + ids.add(iv["id"]) + if not _str(iv.get("claim")): + errs.append(w + ": claim must be a non-empty string") + if not _str(iv.get("cmd")): + errs.append(w + ": cmd must be a non-empty string") + _expect(iv.get("expect"), w, errs) + if "timeout_s" in iv and not (_num(iv["timeout_s"]) and iv["timeout_s"] > 0): + errs.append(w + ": timeout_s must be a positive number") + _tier(iv, w, errs) + if "serial" in iv and not isinstance(iv["serial"], bool): + errs.append(w + ": serial must be true or false") + runnable = any(isinstance(x, dict) and x.get("rung") in (1, 2, 3, 4) and x.get("cmd") for x in checks) or \ + any(isinstance(x, dict) and x.get("cmd") for x in inv) + if checks and not runnable: + errs.append("no runnable check or invariant: rung 5 and 6 items never run, so add at least one check at " + "rung 1-4 with a cmd (or run `sisi contract waive \"\"` if no checks are needed)") + a = c.get("assumptions", []) + if not isinstance(a, list) or not all(isinstance(x, str) for x in a): + errs.append("assumptions must be a list of strings") + q = c.get("questions", []) + if not isinstance(q, list): + errs.append("questions must be a list") + else: + for i, x in enumerate(q): + if not (isinstance(x, dict) and _str(x.get("q")) and "default" in x): + errs.append("questions[%d] needs q and default" % i) + return errs + + +def floor_failures(c, floor_map=None): + """Kinds with a floor where every check of that kind is weaker than the floor.""" + fm = floors() if floor_map is None else floor_map + out = [] + for kind, fl in sorted(fm.items()): + of_kind = [ch for ch in c.get("checks", []) if ch.get("kind") == kind] + if of_kind and not any(ch["rung"] <= fl for ch in of_kind): + out.append({"kind": kind, "floor": fl, + "message": "floor: %s claims need a check at rung %d or stronger; best is rung %d" + % (kind, fl, min(ch["rung"] for ch in of_kind))}) + return out diff --git a/sisi/deep.py b/sisi/deep.py new file mode 100644 index 0000000..80a6022 --- /dev/null +++ b/sisi/deep.py @@ -0,0 +1,214 @@ +"""Deep tier: state of long-running checks, the one-run-per-project lock, and detached background runs.""" +import hashlib, json, os, subprocess, sys, time + +from . import paths + + +def key(project): + return hashlib.sha1(os.path.realpath(project).encode()).hexdigest()[:12] + + +def _state_path(project): + return os.path.join(paths.state(), "deep", key(project) + ".json") + + +def _lock_path(project): + return os.path.join(paths.state(), "locks", "deep-" + key(project) + ".lock") + + +def deep_items(c): + return [x for x in c.get("checks", []) + c.get("invariants", []) + if x.get("tier") == "deep" and x.get("cmd") and x.get("rung", 3) not in (5, 6)] + + +def _proc_start(pid): + try: + with open("/proc/%d/stat" % pid) as f: + return f.read().rsplit(")", 1)[1].split()[19] + except (OSError, IndexError): + return None + + +def _alive(info): + pid = info.get("pid") + if not isinstance(pid, int): + return False + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + pass + start = _proc_start(pid) + return not (start and info.get("start") and start != info["start"]) # pid reuse + + +def read_lock(project): + """Info of the live deep run for this project, or None. Stale locks are removed.""" + p = _lock_path(project) + try: + with open(p, encoding="utf-8") as f: + info = json.load(f) + except (OSError, ValueError): + info = None + if info is not None and _alive(info): + return info + if os.path.exists(p) and info is not None: + try: + os.unlink(p) + except OSError: + pass + return None + + +def acquire(project, fp, log=None): + """Returns (True, info) or (False, info_of_running_run).""" + p = _lock_path(project) + os.makedirs(os.path.dirname(p), exist_ok=True) + info = {"pid": os.getpid(), "start": _proc_start(os.getpid()), "fp": fp, "ts": time.time(), "log": log} + for _ in range(3): + try: + fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) + except FileExistsError: + running = read_lock(project) + if running: + return False, running + continue + with os.fdopen(fd, "w") as f: + json.dump(info, f) + return True, info + return False, {} + + +def release(project): + try: + with open(_lock_path(project), encoding="utf-8") as f: + if json.load(f).get("pid") == os.getpid(): + os.unlink(_lock_path(project)) + except (OSError, ValueError): + pass + + +def save_state(project, contract_id, fp, results, deep_ids): + items = [{"id": r["id"], "status": r["status"], "tail": (r.get("tail") or "")[-1500:]} + for r in results if r.get("tier") == "deep"] + st = {"contract": contract_id, "fp": fp, "epoch": time.time(), "ids": sorted(deep_ids), + "ok": all(i["status"] in ("passed", "awaiting-human") for i in items), "items": items} + p = _state_path(project) + os.makedirs(os.path.dirname(p), exist_ok=True) + tmp = p + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + json.dump(st, f) + os.replace(tmp, p) + + +def load_state(project): + try: + with open(_state_path(project), encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else None + except (OSError, ValueError): + return None + + +def deep_state(c, project, fp): + """None if the contract has no deep items, else a dict with 'state' in + fresh-pass / stale-pass / failed / running / never-run.""" + items = deep_items(c) + if not items: + return None + ids = sorted(x["id"] for x in items) + base = {"items": len(items), "fresh": False, "failed": [], "epoch": None, "lock": None} + lock = read_lock(project) + st = load_state(project) + if st is not None and st.get("ids") == ids: + base.update(epoch=st.get("epoch"), fresh=fp is not None and st.get("fp") == fp, + failed=[i for i in st["items"] if i["status"] not in ("passed", "awaiting-human")]) + else: + st = None + if lock: + base.update(state="running", lock=lock, fresh=fp is not None and lock.get("fp") == fp, epoch=lock.get("ts")) + elif st is None: + base["state"] = "never-run" + elif not st.get("ok"): + base["state"] = "failed" + else: + base["state"] = "fresh-pass" if base["fresh"] else "stale-pass" + return base + + +def _ago(sec): + sec = int(max(0, sec)) + for n, u in ((86400, "d"), (3600, "h"), (60, "m")): + if sec >= n: + return "%d%s" % (sec // n, u) + return "%ds" % sec + + +def describe(ds): + if ds is None: + return None + s, n = ds["state"], ds["items"] + parts = ["%d item%s" % (n, "" if n == 1 else "s")] + if s == "running": + parts.append("started %s ago on %s" % (_ago(time.time() - (ds["epoch"] or time.time())), + "the current tree" if ds["fresh"] else "an older tree")) + elif s != "never-run": + parts.append("last run %s ago on %s" % (_ago(time.time() - (ds["epoch"] or 0)), + "the current tree" if ds["fresh"] else "an older tree")) + if s == "failed" and ds["failed"]: + parts.append("failing: " + ", ".join(i["id"] for i in ds["failed"])) + return "deep checks: %s (%s)" % (s, ", ".join(parts)) + + +def public(ds): + if ds is None: + return None + return {k: v for k, v in ds.items() if k != "lock"} | {"running_pid": (ds["lock"] or {}).get("pid")} + + +def _rewrite_lock(project, pid): + p = _lock_path(project) + with open(p, encoding="utf-8") as f: + info = json.load(f) + info.update(pid=pid, start=_proc_start(pid)) + tmp = p + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + json.dump(info, f) + os.replace(tmp, p) + + +def adopt(project, fp, wait=10.0): + """For the detached worker: take over the lock the parent made for us (it names our pid once the parent has + started us). Falls back to acquiring it normally.""" + t = time.time() + while time.time() - t < wait: + try: + with open(_lock_path(project), encoding="utf-8") as f: + if json.load(f).get("pid") == os.getpid(): + return True, {} + except (OSError, ValueError): + break + time.sleep(0.02) + return acquire(project, fp) + + +def start_background(project, fp=None): + """Detached deep run. The lock is taken here, before the worker starts, so a second request cannot slip in. + Returns (started, log_path_or_running_info).""" + d = os.path.join(paths.state(), "logs") + os.makedirs(d, exist_ok=True) + log = os.path.join(d, "deep-%s-%d.log" % (key(project), int(time.time()))) + ok, info = acquire(project, fp, log) + if not ok: + return False, info + try: + with open(log, "ab") as lf: + child = subprocess.Popen([sys.executable, paths.launcher(), "verify", "--deep", "--worker"], cwd=project, + stdin=subprocess.DEVNULL, stdout=lf, stderr=subprocess.STDOUT, + start_new_session=True, close_fds=True) + _rewrite_lock(project, child.pid) + except Exception: + release(project) + raise + return True, log diff --git a/sisi/delivery.py b/sisi/delivery.py new file mode 100644 index 0000000..d9168e7 --- /dev/null +++ b/sisi/delivery.py @@ -0,0 +1,235 @@ +"""Time to delivery: how long from the human's request to a verified stop, recorded by the gate and read by `sisi time`. + +Delivery row (deliveries.jsonl in the state dir): session, project, start, end (ISO UTC), seconds, send_backs (times the +gate sent the agent back during this request), check_s (seconds spent running checks during this request), contract +(whether a contract existed), tool. The start is the timestamp of the last message the human typed, found by reading +only the tail of the transcript and applying harvest.typed_text, the one definition of "typed by the human". +Everything here fails quiet: a missing or corrupt transcript records nothing and never touches the gate's answer.""" +import json, os, time + +from . import store + +CHUNK = 128 * 1024 +MAX_READ = 4 * 1024 * 1024 # a turn longer than this (in transcript bytes) is not measured + + +def _line_start(raw): + """(epoch seconds, None) of the human message in one transcript line, else None. Cheap prefilters come first.""" + from . import harvest + is_att = b'"type":"attachment"' in raw and b"queued_command" in raw # compact JSON, as Claude Code writes it + if b'"type":"user"' not in raw and not is_att: + return None + if b"toolUseResult" in raw and not is_att: + return None # a tool result: never a human message, and often huge + d = json.loads(raw) + if not isinstance(d, dict) or not isinstance(d.get("timestamp"), str): + return None + if d.get("type") == "user": + text = harvest.typed_text(d)[0] + elif d.get("type") == "attachment": + a = d.get("attachment") or {} + if not (a.get("type") == "queued_command" and a.get("commandMode") == "prompt" and not a.get("isMeta")): + return None + text = harvest.typed_text(a, queued_prompt=a.get("prompt"))[0] + else: + return None + return harvest.epoch(d["timestamp"]) if text is not None else None + + +def find_start(path, max_bytes=MAX_READ, chunk=CHUNK): + """Epoch seconds of the last message the human typed in the transcript at `path`, or None when it cannot be found + within the last `max_bytes`. Reads backwards in chunks, so a long file costs only its tail.""" + try: + with open(os.path.expanduser(path), "rb") as f: + pos = f.seek(0, 2) + buf, read = b"", 0 + while pos > 0 and read < max_bytes: + n = min(chunk, pos) + pos -= n + f.seek(pos) + buf = f.read(n) + buf + read += n + lines = buf.split(b"\n") + buf = lines[0] if pos > 0 else b"" # the first piece may be cut in half: keep it for the next round + for raw in reversed(lines[1:] if pos > 0 else lines): + if not raw.strip(): + continue + try: + t = _line_start(raw) + except Exception: + continue + if t is not None: + return t + return None + except Exception: + return None + + +def _iso(t): + return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(t)) + "Z" + + +def record(payload, sess, sid, cwd, now=None): + """Append one delivery row for a stop the gate has allowed, then reset the per-request counters in `sess`. + Never raises. Returns the row, or None when nothing was recorded.""" + try: + tp = payload.get("transcript_path") + if not isinstance(tp, str) or not tp: + return None + start = find_start(tp) + if start is None: + return None + end = time.time() if now is None else now + if end < start or sess.get("delivery_start") == start: + return None # a clock oddity, or this request was already recorded (the stop hook ran again) + row = {"ts": _iso(end), "session": sid, "project": sess.get("req_project") or cwd, "start": _iso(start), + "end": _iso(end), "seconds": round(end - start, 1), "send_backs": int(sess.get("req_blocks", 0)), + "check_s": round(float(sess.get("req_check_s", 0.0)), 1), "contract": bool(sess.get("req_contract")), + "tool": store.tool()} + store.append("deliveries", row) + sess.update(delivery_start=start, req_blocks=0, req_check_s=0.0) + store.save_session(sid, sess) + return row + except Exception as e: + store.log_error("delivery", e) + return None + + +# ---------------------------------------------------------------- reading: `sisi time` + +DAY = 86400.0 + + +def median(xs): + s = sorted(xs) + n = len(s) + if not n: + return None + return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2.0 + + +def percentile(xs, p): + """Linear-interpolation percentile (p in 0..100) of a list of numbers; None when empty.""" + s = sorted(xs) + if not s: + return None + k = (len(s) - 1) * p / 100.0 + lo = int(k) + hi = min(lo + 1, len(s) - 1) + return s[lo] + (s[hi] - s[lo]) * (k - lo) + + +def _epoch(ts): + from . import harvest + return harvest.epoch(ts) if isinstance(ts, str) else None + + +def summarize(rows): + secs = [r["seconds"] for r in rows] + tot = sum(secs) + chk = sum(min(r.get("check_s", 0.0), r["seconds"]) for r in rows) + return {"n": len(rows), "median_s": median(secs), "p90_s": percentile(secs, 90), + "check_share": (chk / tot) if tot > 0 else None, + "send_back_deliveries": sum(1 for r in rows if r.get("send_backs", 0) > 0)} + + +def windows(rows, now): + """(last 7 days, the 7 days before) of delivery rows, by their end time.""" + cur, prev = [], [] + for r in rows: + if not (isinstance(r, dict) and isinstance(r.get("seconds"), (int, float))): + continue + t = _epoch(r.get("end") or r.get("ts")) + if t is None: + continue + if now - 7 * DAY <= t <= now: + cur.append(r) + elif now - 14 * DAY <= t < now - 7 * DAY: + prev.append(r) + return cur, prev + + +def slow_checks(results, now, top=5): + """The slowest checks by mean duration over the last 7 days, each with a suggestion.""" + from . import scoreboard + recent = [r for r in results if isinstance(r, dict) and (_epoch(r.get("ts")) or 0) >= now - 7 * DAY] + out = [] + for s in scoreboard.check_stats(recent)["checks"]: + if s.get("timed_runs"): + out.append({"id": s["id"], "mean_s": s["total_s"] / s["timed_runs"], "runs": s["runs"], "tier": s.get("tier", "fast")}) + out.sort(key=lambda x: -x["mean_s"]) + out = out[:top] + for x in out: + if x["mean_s"] < 5: + x["suggestion"] = "quick enough: leave it in the fast tier" + elif x["tier"] == "deep": + x["suggestion"] = "already deep; split it so a quick part can run in the gate" + else: + x["suggestion"] = 'mark as "tier": "deep" if it can wait, or split it into a quick part and a slow part' + return out + + +def report(now=None): + now = time.time() if now is None else now + rows = store.read("deliveries") + cur, prev = windows(rows, now) + by_project = {} + for label, group in (("cur", cur), ("prev", prev)): + for r in group: + by_project.setdefault(r.get("project") or "(unknown)", {"cur": [], "prev": []})[label].append(r) + return {"now": _iso(now), "all": {"last7": summarize(cur), "prev7": summarize(prev)}, + "projects": {p: {"last7": summarize(v["cur"]), "prev7": summarize(v["prev"])} for p, v in sorted(by_project.items())}, + "slowest_checks": slow_checks(store.read("results"), now)} + + +def fmt_s(s): + if s is None: + return "-" + s = int(round(s)) + if s < 60: + return "%ds" % s + if s < 3600: + return "%dm%02ds" % (s // 60, s % 60) + return "%dh%02dm" % (s // 3600, (s % 3600) // 60) + + +def _cell(s): + return "median %s, p90 %s (%d)" % (fmt_s(s["median_s"]), fmt_s(s["p90_s"]), s["n"]) if s["n"] else "none" + + +def median_line(now=None): + """One line for `sisi status`.""" + cur = report(now)["all"]["last7"] + if not cur["n"]: + return "time to delivery : no deliveries recorded in the last 7 days" + return "time to delivery : median %s over the last 7 days (%d deliveries)" % (fmt_s(cur["median_s"]), cur["n"]) + + +def cmd_time(args, out=print): + r = report() + if "--json" in args: + out(json.dumps(r, indent=2)) + return 0 + a = r["all"] + if not a["last7"]["n"] and not a["prev7"]["n"]: + out("sisi time: no deliveries recorded in the last 14 days. The end-of-turn gate records one each time it lets " + "a turn end; check that the gate is installed (`sisi doctor`).") + else: + out("time from the human's request to a verified stop") + out("%-28s %-34s %s" % ("", "last 7 days", "the 7 days before")) + out("%-28s %-34s %s" % ("all projects", _cell(a["last7"]), _cell(a["prev7"]))) + for p, v in r["projects"].items(): + out("%-28s %-34s %s" % (os.path.basename(p.rstrip("/"))[:28] or p, _cell(v["last7"]), _cell(v["prev7"]))) + c = a["last7"] + if c["n"]: + out("") + out("share of that time spent running checks: %s" % ("%.0f%%" % (100 * c["check_share"]) if c["check_share"] is not None else "-")) + out("deliveries that needed a send-back: %d of %d" % (c["send_back_deliveries"], c["n"])) + out("") + if r["slowest_checks"]: + out("slowest checks (mean run time, last 7 days)") + for x in r["slowest_checks"]: + out(" %-30s %8s over %d runs [%s]\n -> %s" % (x["id"][:30], fmt_s(x["mean_s"]), x["runs"], x["tier"], x["suggestion"])) + else: + out("slowest checks: no check runs recorded in the last 7 days") + return 0 diff --git a/sisi/escapes.py b/sisi/escapes.py new file mode 100644 index 0000000..3e766ea --- /dev/null +++ b/sisi/escapes.py @@ -0,0 +1,89 @@ +"""Escape candidates: work declared verified (or finished) that then turned out wrong. Evidence pointers only. + +Kinds + contract-then-correction a contract run passed (every check passed or awaits a human) in a session, and a + correction-like user message came later in that session. + contract-then-fix-session a contract run passed in a session; within 7 days a later main session in the same + repo touched at least one of the same files (by following commits) and opened with a + fix-like request. + premature-done independent of sisi records: an assistant turn ended on a completion claim and the + very next typed user message was correction-like. +Results join to sessions by the `session` field when present, otherwise by time and project: a session whose +window contains the run and whose cwd or repo is inside the run's project. If more than one session fits, the +candidate is marked `ambiguous`. These are candidates for a human or a model to look at, not conclusions. +""" +import json, re + +from . import harvest, store + +WEEK_S = 7 * 86400 +_FIXLIKE = re.compile(r"\b(fix|bug|broken|wrong|regress|revert|fails?|failing|doesn'?t work|not working|error|crash)", re.I) + + +def passed_runs(results): + """[{ts, t, project, contract, session, run}] for runs whose checks all passed.""" + groups = {} + for r in results: + if not isinstance(r, dict) or r.get("check") == "gate": + continue + key = r.get("run") or "%s|%s|%s" % (r.get("ts"), r.get("contract"), r.get("project")) + groups.setdefault(key, []).append(r) + out = [] + for key, rs in groups.items(): + if all(x.get("status") in ("passed", "awaiting-human") for x in rs) and any(x.get("status") == "passed" for x in rs): + t = harvest.epoch(rs[0].get("ts") or "") + if t is not None: + out.append({"ts": rs[0]["ts"], "t": t, "project": rs[0].get("project"), "contract": rs[0].get("contract"), + "session": rs[0].get("session"), "run": key}) + return sorted(out, key=lambda x: x["t"]) + + +def _inside(path, parent): + if not path or not parent: + return False + p, q = path.rstrip("/"), parent.rstrip("/") + return p == q or p.startswith(q + "/") or q.startswith(p + "/") + + +def attribute(run, sessions): + """Sessions (rows) the run can be attributed to: by session id when it names one, else by time and project.""" + if run["session"]: + hit = [s for s in sessions if s["id"] == run["session"]] + if hit: + return hit, False + hit = [s for s in sessions if s["t0"] is not None and s["t0"] <= run["t"] <= (s["t1"] or s["t0"]) + 60 + and (_inside(s["cwd"], run["project"]) or _inside(s["repo_root"], run["project"]))] + return hit, len(hit) > 1 + + +def find(con, results=None): + results = store.read("results") if results is None else results + sessions = [dict(r) for r in con.execute( + "SELECT s.id, s.cwd, s.t0, s.t1, s.first_message, s.machine, g.repo_root, g.files, g.start_kind " + "FROM sessions s LEFT JOIN groundtruth g ON g.session_id=s.id WHERE s.kind='main'")] + out = [] + for run in passed_runs(results): + hit, ambiguous = attribute(run, sessions) + for s in hit: + later = con.execute("SELECT idx, ts, t FROM user_msgs WHERE session_id=? AND correction=1 AND t>? ORDER BY t", + (s["id"], run["t"])).fetchall() + for m in later[:3]: + out.append({"kind": "contract-then-correction", "session": s["id"], "run": run["run"], "contract": run["contract"], + "passed_at": run["ts"], "evidence": {"user_msg_idx": m["idx"], "at": m["ts"]}, "ambiguous": ambiguous}) + files = set(json.loads(s["files"] or "[]")) + if files and s["repo_root"]: + for o in sessions: + if o["id"] == s["id"] or o["repo_root"] != s["repo_root"] or o["machine"] or o["t0"] is None: + continue + if not (run["t"] < o["t0"] <= run["t"] + WEEK_S): + continue + common = files & set(json.loads(o["files"] or "[]")) + if common and _FIXLIKE.search((o["first_message"] or "")[:1500]): + out.append({"kind": "contract-then-fix-session", "session": s["id"], "run": run["run"], + "contract": run["contract"], "passed_at": run["ts"], + "evidence": {"later_session": o["id"], "common_files": sorted(common)[:10]}, + "ambiguous": ambiguous}) + for r in con.execute("SELECT m.session_id, m.idx, m.ts FROM user_msgs m WHERE m.correction=1 AND m.after_completion=1 ORDER BY m.t"): + out.append({"kind": "premature-done", "session": r["session_id"], "evidence": {"user_msg_idx": r["idx"], "at": r["ts"]}, + "ambiguous": False}) + return out diff --git a/sisi/gate.py b/sisi/gate.py new file mode 100644 index 0000000..f20ee64 --- /dev/null +++ b/sisi/gate.py @@ -0,0 +1,282 @@ +"""End-of-turn gate. Claude Code Stop hook: JSON on stdin, block = JSON {"decision":"block","reason":...} on stdout, exit 0. +Anything that goes wrong inside sisi allows (fail open) and is logged to the state dir.""" +import hashlib, json, os, sys, time + +from . import contract as C, deep as D, gitutil, store, trust, verify as V + + +def _read_payload(): + try: + if sys.stdin is None or sys.stdin.isatty(): + return {} + d = json.loads(store.read_stdin() or "{}") + return d if isinstance(d, dict) else {} + except Exception: + return {} + + +def _session_key(payload, cwd): + sid = payload.get("session_id") + return sid if isinstance(sid, str) and sid else "cwd-" + hashlib.sha1(cwd.encode()).hexdigest()[:12] + + +def _new_waiver(project, sess): + """Latest waiver for this project made during this session and not yet applied.""" + since, seen, best = sess.get("started") or "", sess.get("waiver_ns", 0), None + for w in store.read("waivers"): + if w.get("project") == project and w.get("ts", "") >= since and w.get("ns", 0) > seen: + best = w + return best + + +class _Ctx: + def __init__(self, sess, sid, cfg, fp): + self.sess, self.sid, self.cfg, self.fp = sess, sid, cfg, fp + + def save(self): + store.save_session(self.sid, self.sess) + + def allow(self, msg=None): + self.sess.update(blocks=0, last_fp=self.fp, last_decision="allow") + self.save() + return "allow", msg + + def block(self, template, contract_id=None, project=None, kind="fast"): + """One path for every kind of block: strikes, 3-strike release as UNVERIFIED.""" + s, maxb = self.sess, int(self.cfg["gate"].get("max_blocks", 3)) + blocks = int(s.get("blocks", 0)) + if blocks >= maxb: + if kind == "retro": + self.allow() + return "allow", ("sisi: no retrospective was recorded after %d reminders, so the gate let this turn end. " + "Run `sisi retro` before you finish if you still can." % maxb) + store.append("results", {"ts": store.now(), "contract": contract_id, "project": project, "check": "gate", + "item": "gate", "kind": None, "rung": None, "status": "unverified", + "duration_s": 0.0, "tool": store.tool(), "session": self.sid}) + _, _ = self.allow() + return "allow", ("sisi: result is UNVERIFIED. The gate has sent this work back %d times and it is still " + "not verified, so it let the turn end. Report the work as unverified." % maxb) + s["req_blocks"] = int(s.get("req_blocks", 0)) + 1 # send-backs during this request, for the delivery row + s.update(blocks=blocks + 1, last_fp=self.fp, last_decision="block", last_msg=template, last_kind=kind, + last_contract=contract_id, last_project=project) + self.save() + return "block", template.replace("{n}", "%d of %d" % (blocks + 1, maxb)) + + +def decide(payload): + """Return ('allow', message_or_None) or ('block', reason).""" + cfg = store.config() + g = cfg["gate"] + if not g.get("enabled", True): + return "allow", None + cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() + sid = _session_key(payload, cwd) + os.environ["SISI_SESSION_ID"] = sid + sess = store.load_session(sid) + if not (sess.get("started") or sess.get("first_seen")): + sess["first_seen"] = store.now() + store.save_session(sid, sess) + since = sess.get("started") or sess.get("first_seen") + path = C.find(cwd) + sess["req_contract"], sess["req_project"] = bool(path), cwd + if isinstance(payload.get("transcript_path"), str): + sess["transcript_path"] = payload["transcript_path"] # `sisi retro` reads the request's start from it + c, errs = None, [] + if path: + project = C.project_dir(path) + if not trust.is_trusted(project): + if sess.get("untrusted_notice") != project: + sess["untrusted_notice"] = project + store.save_session(sid, sess) + return "allow", "sisi: " + trust.hint(project) + return "allow", None + try: + c = C.load(path) + except (OSError, ValueError) as e: + errs = ["cannot read contract: %s" % e] + if c is not None and C.is_unedited_skeleton(c): + path = None # nothing real written yet: behave as if there is no contract + sess["req_contract"] = False + top = gitutil.root(cwd) + sess["req_project"] = top or (project if path else cwd) + fp = gitutil.fingerprint(cwd, [path]) if top else None + ctx = _Ctx(sess, sid, cfg, fp) + ds = None + if path and c is not None and not C.validate(c): + try: + ds = D.deep_state(c, project, fp) + except Exception as e: + store.log_error("gate-deep", e) + dfail = bool(ds and ds["state"] == "failed" and ds["fresh"]) # deep failure on the current tree + retro_on = bool(cfg.get("retro", {}).get("required", True)) + repo_key = top or (project if path else cwd) + + def need_retro(real_work): + """True when real work was done and no retro covers the current tree state yet.""" + if not (retro_on and real_work): + return False + sess["real_work"] = True + from . import retro + if retro.satisfied(repo_key, since, fp): + sess["retro_done"] = True + return False + return True + + w = _new_waiver(top, sess) if (top and not path) else None # a fresh waiver re-opens the decision + # A turn that changed nothing is not punished and not re-checked. + if fp is not None and not w: + if sess.get("last_fp") is not None: + same, last = fp == sess["last_fp"], sess.get("last_decision") + else: + same, last = fp == sess.get("baseline_fp"), "allow" + if same and last == "allow" and not dfail: + return "allow", None + retro_clear = False + if same and last == "block" and sess.get("last_kind") == "retro": + from . import retro + retro_clear = retro.satisfied(repo_key, since, fp) + if same and last == "block" and sess.get("last_msg") and not retro_clear \ + and not (sess.get("last_kind") == "deep" and not dfail): + return ctx.block(sess["last_msg"], sess.get("last_contract"), sess.get("last_project"), + kind=sess.get("last_kind", "fast")) + + if path: + deadline = time.time() + float(g.get("budget_s", 120)) + if c is not None: + errs = C.validate(c) + if errs: + results = [{"item": "contract", "id": "contract", "status": "failed", "kind": None, "rung": None, + "claim": "contract is invalid", "duration_s": 0.0, "tail": "\n".join(errs)}] + else: + t_run = time.time() + results = V.run(c, project, deadline, cfg["verify"]["default_timeout_s"], tiers=("fast",)) + sess["req_check_s"] = float(sess.get("req_check_s", 0.0)) + (time.time() - t_run) + V.record(c, project, results, fp) + if V.ok(results): + if dfail: + tails = "\n".join("- deep check %s [%s]:\n%s" % (i["id"], i["status"], "\n".join(" " + l for l in i["tail"].splitlines()[-15:])) + for i in ds["failed"]) + return ctx.block("sisi: the fast checks pass, but the deep checks failed on the current tree " + "(send-back {n}). Fix the work, then re-run them with `sisi verify --deep " + "--background` (see `sisi verify --state`). Do not report this work as done.\n\n%s" + % tails[:4000], c["id"], project, kind="deep") + changed = fp is None or fp != sess.get("baseline_fp") + if need_retro(changed): + from . import retro + return ctx.block(retro.TEMPLATE, c["id"] if c else None, project, kind="retro") + if ds and ds["state"] != "fresh-pass" and sess.get("deep_notice") != (fp or "nofp"): + sess["deep_notice"] = fp or "nofp" + text = ("sisi: the fast checks pass, but the deep checks are %s (%d item%s). The work is NOT yet " + "verified end to end: report it as not yet done, say that deep checks are pending, and " + "start them with `sisi verify --deep --background` (progress: `sisi verify --state`)." + % (ds["state"], ds["items"], "" if ds["items"] == 1 else "s")) + return ctx.allow({"message": "sisi: deep checks %s; the work is not yet fully verified" % ds["state"], + "context": text}) + return ctx.allow() + return ctx.block("sisi: the contract at %s is not satisfied (send-back {n}). Fix the work, then run " + "`sisi verify` until it passes. Do not report this work as done.\n\n%s" + % (path, V.failure_report(results)), c["id"] if c else None, project) + + if not top: + return "allow", None + if sess.get("baseline") is None: + sess.update(baseline=gitutil.measure(cwd), head=gitutil.head(cwd), started=sess.get("started") or store.now()) + sess["baseline_fp"] = fp + store.save_session(sid, sess) + return "allow", None + # Fix 4: growth is measured from the session start, or from the latest waiver. + if w: + sess["baseline"] = {"lines": w.get("lines", 0), "files": w.get("files", [])} + sess["head"] = w.get("head") + sess["waiver_ns"] = w.get("ns", 0) + sess["blocks"] = 0 + now = gitutil.measure(cwd, sess.get("head")) + base = sess["baseline"] + dl = max(0, now["lines"] - base["lines"]) + df = len(set(now["files"]) - set(base["files"])) + if not (dl > int(g.get("growth_lines", 40)) or df > int(g.get("growth_files", 3))): + if need_retro(bool(sess.get("waiver_ns"))): # a waiver in this session means real work happened + from . import retro + return ctx.block(retro.TEMPLATE, kind="retro") + return ctx.allow() + return ctx.block("sisi: this session has changed %d lines and %d files since its start and there is no " + "contract (send-back {n}). Write `.sisi/contract.json` (`sisi contract init` makes the " + "skeleton; give it at least one check with a real command), then run `sisi verify`. If " + "the change needs no checks, run `sisi contract waive \"\"` instead." % (dl, df)) + + +EDIT_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} + + +def subagent_edits(transcript): + """(edited_files, start_ts) from a subagent transcript (JSONL). start_ts is in sisi's timestamp format, or None.""" + edited, start = False, None + with open(os.path.expanduser(transcript), encoding="utf-8", errors="replace") as f: + for line in f: + try: + d = json.loads(line) + except ValueError: + continue + if start is None and isinstance(d.get("timestamp"), str) and len(d["timestamp"]) >= 19: + start = d["timestamp"][:19] + "Z" + content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None + for x in content if isinstance(content, list) else []: + if isinstance(x, dict) and x.get("type") == "tool_use" and x.get("name") in EDIT_TOOLS: + edited = True + return edited, start + + +def decide_subagent(payload): + """SubagentStop: only the retro requirement, only when the subagent edited files (read from its transcript).""" + cfg = store.config() + if not cfg.get("retro", {}).get("required", True) or not cfg["gate"].get("enabled", True): + return "allow", None + tp = payload.get("agent_transcript_path") + if not isinstance(tp, str): + return "allow", None # cannot tell whether it changed files: do not block + edited, start = subagent_edits(tp) + if not edited or not start: + return "allow", None + cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() + from . import retro + if retro.satisfied(retro.repo_of(cwd), start, None): + return "allow", None + key = "sub-%s" % (payload.get("agent_id") or "unknown") + sess = store.load_session(key) + blocks, maxb = int(sess.get("blocks", 0)), int(cfg["gate"].get("max_blocks", 3)) + if blocks >= maxb: + return "allow", None + sess["blocks"] = blocks + 1 + store.save_session(key, sess) + return "block", retro.TEMPLATE.replace("{n}", "%d of %d" % (blocks + 1, maxb)) + + +def _record_delivery(payload): + """The request is delivered: write one delivery row. Never raises, never changes the gate's answer.""" + try: + from . import delivery + cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() + sid = _session_key(payload, cwd) + delivery.record(payload, store.load_session(sid), sid, cwd) + except Exception as e: + store.log_error("gate-delivery", e) + + +def main(args=()): + try: + payload = _read_payload() + action, msg = (decide_subagent if "--subagent" in args else decide)(payload) + except Exception as e: # fail open + store.log_error("gate", e) + return 0 + if action == "allow" and "--subagent" not in args: + _record_delivery(payload) + if action == "block": + sys.stdout.write(json.dumps({"decision": "block", "reason": msg}) + "\n") + elif isinstance(msg, dict): + # Documented for Stop: hookSpecificOutput.additionalContext reaches the model (and continues the turn once). + sys.stdout.write(json.dumps({"systemMessage": msg["message"], "hookSpecificOutput": { + "hookEventName": "Stop", "additionalContext": msg["context"]}}) + "\n") + elif msg: + sys.stdout.write(json.dumps({"systemMessage": msg}) + "\n") + return 0 diff --git a/sisi/gitutil.py b/sisi/gitutil.py new file mode 100644 index 0000000..65b6628 --- /dev/null +++ b/sisi/gitutil.py @@ -0,0 +1,89 @@ +"""Small git helpers. Working-tree change measurement for the gate.""" +import os, subprocess + +EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904" + + +def _git(cwd, *args, timeout=5): + p = subprocess.run(("git",) + args, cwd=cwd, capture_output=True, timeout=timeout) + return p.returncode, p.stdout.decode("utf-8", "replace") + + +def root(cwd): + try: + rc, out = _git(cwd, "rev-parse", "--show-toplevel") + except (OSError, subprocess.SubprocessError): + return None + return out.strip() if rc == 0 and out.strip() else None + + +def head(cwd): + try: + rc, out = _git(cwd, "rev-parse", "--verify", "-q", "HEAD") + except (OSError, subprocess.SubprocessError): + return None + return out.strip() if rc == 0 else None + + +def measure(cwd, base=None, max_untracked=200): + """Return {'lines': n, 'files': [paths]} for the working tree vs `base` (default HEAD).""" + cwd = root(cwd) or cwd + base = base or head(cwd) or EMPTY_TREE + lines, files = 0, set() + rc, out = _git(cwd, "diff", "--numstat", base, timeout=10) + if rc == 0: + for ln in out.splitlines(): + parts = ln.split("\t", 2) + if len(parts) == 3: + files.add(parts[2]) + for x in parts[:2]: + if x.isdigit(): + lines += int(x) + elif x == "-": + lines += 1 # binary change counts as one line + rc, out = _git(cwd, "ls-files", "--others", "--exclude-standard", timeout=10) + if rc == 0: + top = cwd + for rel in out.splitlines()[:max_untracked]: + files.add(rel) + try: + fp = os.path.join(top, rel) + if os.path.getsize(fp) < 1_000_000: + with open(fp, "rb") as f: + lines += f.read().count(b"\n") or 1 + except OSError: + pass + return {"lines": lines, "files": sorted(files)[:2000]} + + +def fingerprint(cwd, extra_files=()): + """Cheap hash of the working-tree state: HEAD, the diff against it, untracked files (path, size, mtime), + plus the content of `extra_files` (e.g. the contract, which may be git-ignored). None outside git.""" + import hashlib + top = root(cwd) + if not top: + return None + h = hashlib.sha1() + base = head(top) or EMPTY_TREE + h.update(base.encode()) + p = subprocess.run(["git", "diff", "--no-ext-diff", "--no-textconv", "--no-color", base], cwd=top, + capture_output=True, timeout=10) + h.update(b"\0diff\0" + p.stdout) + p = subprocess.run(["git", "ls-files", "--others", "--exclude-standard", "-z"], cwd=top, + capture_output=True, timeout=10) + for rel in p.stdout.split(b"\0")[:2000]: + if not rel: + continue + try: + st = os.stat(os.path.join(top, os.fsdecode(rel))) + h.update(rel + b"\0%d:%d\0" % (st.st_size, st.st_mtime_ns)) + except OSError: + h.update(rel + b"\0gone\0") + for f in extra_files: + if f: + try: + with open(f, "rb") as fh: + h.update(b"\0extra\0" + fh.read()) + except OSError: + h.update(b"\0extra-missing\0") + return h.hexdigest() diff --git a/sisi/groundtruth.py b/sisi/groundtruth.py new file mode 100644 index 0000000..05cc7f4 --- /dev/null +++ b/sisi/groundtruth.py @@ -0,0 +1,242 @@ +"""Ground truth for harvested main sessions: repo, start commit, following commits, overlap, test command. + +Repo resolution: the session cwd, if it still exists inside a git repo (a linked worktree resolves to its main +repo via --git-common-dir). A cwd that no longer exists but sits under /.t3/worktrees//... is +recovered to // when that is a git repo (how = "t3-worktree-recovery"); otherwise the nearest +existing ancestor is tried, never the home directory itself. + +Start commit: sisi's own session record (state/sessions/.json written by `sisi tick`) gives the exact HEAD +(start_kind "exact", only if the commit still exists). Otherwise the latest commit on `--branches --remotes` +(never `--all`: T3 adds refs/t3/.../checkpoints refs that would pollute it) whose committer date is at or +before the session's first timestamp (start_kind "estimated"). + +Following commits: non-merge commits reachable from any branch or remote but not from the start commit, with +committer date from the session start to its last timestamp plus 2 hours. With overlapping sibling sessions +they cannot be attributed to this session for sure, hence the overlap fields. + +Overlap: another main session in the same repo whose [first, last] window intersects this session's +[first, last + 2h]. `overlap_writers` counts those that used Edit/Write-class tools or ran commit commands. +Only Claude Code transcripts are known; edits made by hand or by other tools are invisible. +""" +import json, os, re, subprocess +from concurrent.futures import ThreadPoolExecutor + +from . import gitutil, paths, store + +AFTER_S = 7200 +WRITE_TOOLS = ("Edit", "Write", "MultiEdit", "NotebookEdit") + + +def _git(cwd, *args, timeout=60): + try: + return gitutil._git(cwd, *args, timeout=timeout) + except (OSError, subprocess.SubprocessError): + return 1, "" + + +def main_repo_of(path): + """(repo_root, vcs) for a directory that exists, or (None, None).""" + top = gitutil.root(path) + if not top: + return None, None + rc, out = _git(top, "rev-parse", "--path-format=absolute", "--git-common-dir") + common = out.strip() + root = top + if rc == 0 and common.endswith("/.git"): + root = common[:-5] or top + elif rc == 0 and common and not common.endswith("/.git") and os.path.basename(common) != ".git": + root = top # bare or unusual layout: keep the worktree top + vcs = "jj" if os.path.isdir(os.path.join(root, ".jj")) else "git" + return root, vcs + + +# Folders under the home folder where people commonly keep their repositories. +REPO_PARENTS = ("Code", "code", "src", "projects", "dev", "repos", "work", "git") + + +def resolve_repo(cwd, home=None): + """(root, how, vcs). how says how it was resolved; root is None when it could not be.""" + home = home or paths.home() + if not cwd: + return None, "no-cwd", None + if os.path.isdir(cwd): + root, vcs = main_repo_of(cwd) + return (root, "cwd", vcs) if root else (None, "not-a-git-repo", None) + m = re.match(re.escape(os.path.join(home, ".t3", "worktrees")) + r"/([^/]+)", cwd) + if m: + for parent in REPO_PARENTS: + cand = os.path.join(home, parent, m.group(1)) + if os.path.isdir(cand): + root, vcs = main_repo_of(cand) + if root: + return root, "t3-worktree-recovery", vcs + return None, "t3-worktree-parent-missing", None + p = os.path.dirname(cwd.rstrip("/")) + while p and p != "/" and os.path.realpath(p) != os.path.realpath(home): + if os.path.isdir(p): + root, vcs = main_repo_of(p) + return (root, "ancestor", vcs) if root else (None, "cwd-missing", None) + p = os.path.dirname(p) + return None, "cwd-missing", None + + +def _iso(t): + import time + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(t)) + + +def estimate_start(root, t0): + rc, out = _git(root, "rev-list", "--max-count=1", "--branches", "--remotes", "--before=" + _iso(t0)) + out = out.strip() + return out if rc == 0 and out else None + + +def commit_exists(root, sha): + rc, _ = _git(root, "cat-file", "-e", str(sha) + "^{commit}") + return rc == 0 + + +def commits_after(root, start, t0, t1, limit=300): + """[{sha, t, files}] for non-merge commits not reachable from `start` in [t0, t1 + 2h].""" + args = ["log", "--no-merges", "--branches", "--remotes", "--since=" + _iso(t0), "--until=" + _iso(t1 + AFTER_S), + "--format=%x01%H%x02%ct", "--name-only", "--max-count=%d" % limit] + if start: + args.insert(1, "^" + start) + rc, out = _git(root, *args) + commits = [] + if rc != 0: + return commits + for block in out.split("\x01"): + if not block.strip(): + continue + lines = block.split("\n") + head = lines[0].split("\x02") + if len(head) != 2: + continue + files = [x for x in lines[1:] if x.strip()][:200] + try: + commits.append({"sha": head[0], "t": int(head[1]), "files": files}) + except ValueError: + pass + return commits + + +def _show(root, commit, path): + if commit: + rc, out = _git(root, "show", "%s:%s" % (commit, path)) + return out if rc == 0 else None + try: + with open(os.path.join(root, path), encoding="utf-8", errors="replace") as f: + return f.read() + except OSError: + return None + + +def test_command(root, commit): + """(command, how) detected from files at `commit` (working tree if commit is None); (None, None) if none.""" + for name in ("justfile", "Justfile", ".justfile"): + txt = _show(root, commit, name) + if txt is not None: + names = set(re.findall(r"^([A-Za-z_][\w-]*)[^\n:=]*:(?!=)", txt, re.M)) + for r in ("check", "test", "tests"): + if r in names: + return "just " + r, "justfile recipe" + if _show(root, commit, "Cargo.toml") is not None: + return "cargo test", "Cargo.toml" + txt = _show(root, commit, "package.json") + if txt: + try: + test = ((json.loads(txt).get("scripts") or {}).get("test") or "") + if test and "no test specified" not in test: + return "npm test", "package.json scripts.test" + except (ValueError, AttributeError): + pass + if _show(root, commit, "go.mod") is not None: + return "go test ./...", "go.mod" + for name in ("pytest.ini", "tox.ini", "setup.cfg", "pyproject.toml"): + txt = _show(root, commit, name) + if txt and ("pytest" in txt): + return "pytest", name + txt = _show(root, commit, "Makefile") + if txt and re.search(r"^test\s*:", txt, re.M): + return "make test", "Makefile" + if commit: + rc, out = _git(root, "ls-tree", "--name-only", commit, "tests/") + if rc == 0 and re.search(r"tests/test_[^/]*\.py", out): + return "python3 -m unittest discover -s tests", "tests/test_*.py" + return None, None + + +def compute_one(row, home=None): + """Ground truth for one main session row (dict). Pure with respect to the database.""" + root, how, vcs = resolve_repo(row["cwd"], home) + gt = dict(session_id=row["id"], repo_root=root, repo_how=how, vcs=vcs, start_commit=None, start_kind=None, + start_note=None, commits=[], files=[], test_cmd=None, test_how=None) + if not root or row["t0"] is None: + return gt + rec = store.load_session(row["id"]) + head = rec.get("head") if isinstance(rec, dict) else None + if head and commit_exists(root, head): + gt["start_commit"], gt["start_kind"], gt["start_note"] = head, "exact", "sisi tick record" + else: + est = estimate_start(root, row["t0"]) + if est: + gt["start_commit"], gt["start_kind"] = est, "estimated" + gt["start_note"] = "latest commit on branches/remotes at or before the session's first timestamp" + else: + gt["start_note"] = "no commit on branches/remotes at or before the session start" + t1 = row["t1"] or row["t0"] + if gt["start_commit"]: + gt["commits"] = commits_after(root, gt["start_commit"], row["t0"], t1) + gt["files"] = sorted({f for c in gt["commits"] for f in c["files"]})[:500] + gt["test_cmd"], gt["test_how"] = test_command(root, gt["start_commit"]) + return gt + + +def run(con, home=None, workers=4, progress=None): + """Compute or refresh ground truth for main sessions, then recompute overlap for all. Incremental: a + session is recomputed when it has no row, its last timestamp changed, or its row was computed before its + after-window (+2h) had closed.""" + import time + now = time.time() + have = {r["session_id"]: (r["t1"], r["computed_at"]) for r in con.execute("SELECT session_id,t1,computed_at FROM groundtruth")} + rows = [dict(r) for r in con.execute("SELECT id,cwd,t0,t1 FROM sessions WHERE kind='main'")] + todo = [] + for r in rows: + h = have.get(r["id"]) + if h is None or h[0] != r["t1"] or (h[1] or 0) < (r["t1"] or 0) + AFTER_S: + todo.append(r) + stats = {"computed": 0, "skipped": len(rows) - len(todo)} + # one worker thread per repo at a time would be gentler on git; plain threads are fine for this size + with ThreadPoolExecutor(max_workers=workers) as ex: + for n, gt in enumerate(ex.map(lambda r: compute_one(r, home), todo), 1): + r = next(x for x in todo if x["id"] == gt["session_id"]) + con.execute("INSERT OR REPLACE INTO groundtruth VALUES(?,?,?,?,?,?,?,?,?,?,?,?,0,0,'[]',?,?)", + (gt["session_id"], gt["repo_root"], gt["repo_how"], gt["vcs"], gt["start_commit"], gt["start_kind"], + gt["start_note"], json.dumps(gt["commits"]), len(gt["commits"]), json.dumps(gt["files"]), + gt["test_cmd"], gt["test_how"], r["t1"], now)) + stats["computed"] += 1 + if n % 100 == 0: + con.commit() + if progress: + progress("groundtruth: %d/%d" % (n, len(todo))) + con.commit() + compute_overlap(con) + return stats + + +def compute_overlap(con): + rows = [dict(r) for r in con.execute( + "SELECT s.id, s.t0, s.t1, s.tools, s.ran_commit, g.repo_root FROM sessions s JOIN groundtruth g ON g.session_id=s.id " + "WHERE s.kind='main' AND g.repo_root IS NOT NULL AND s.t0 IS NOT NULL")] + by = {} + for r in rows: + r["writer"] = bool(r["ran_commit"]) or any(k in json.loads(r["tools"] or "{}") for k in WRITE_TOOLS) + by.setdefault(r["repo_root"], []).append(r) + for sess in by.values(): + for r in sess: + lo, hi = r["t0"], (r["t1"] or r["t0"]) + AFTER_S + sib = [o for o in sess if o["id"] != r["id"] and o["t0"] <= hi and (o["t1"] or o["t0"]) >= lo] + con.execute("UPDATE groundtruth SET overlap_any=?, overlap_writers=?, siblings=? WHERE session_id=?", + (len(sib), sum(1 for o in sib if o["writer"]), json.dumps([o["id"] for o in sib][:50]), r["id"])) + con.commit() diff --git a/sisi/harvest.py b/sisi/harvest.py new file mode 100644 index 0000000..64caca8 --- /dev/null +++ b/sisi/harvest.py @@ -0,0 +1,541 @@ +"""Harvest: turn raw agent transcripts into a sqlite database in the state dir (harvest.db). + +No model calls. Incremental: each file's size and mtime are remembered and an unchanged file is skipped; +a file that grew or changed is re-read whole and its rows replaced. Transcripts are streamed line by line +(in binary, with a cheap byte-level pre-filter so the multi-megabyte tool-result lines are never parsed). + +Sources sit behind one interface (`Source`): `discover(home)` yields `FileRef`s and `parse(ref)` returns +`(session_dict, [message_dict])`. Only `ClaudeCodeSource` exists. A Muse JSONL or OpenCode sqlite source +would subclass `Source` and be added to `SOURCES`; nothing else in the pipeline knows about Claude Code. + +WHAT COUNTS AS TEXT THE HUMAN TYPED (the rule, settled by inspecting real records) +A transcript `user` record is typed by the human only if ALL hold: + 1. the session is a main session (subagent transcripts have no human; their first user record is a + brief written by the parent agent and is stored as `first_message` of a subagent session only); + 2. it is not a tool result (`toolUseResult` key / `tool_result` content blocks); + 3. it is not `isMeta` and not `isCompactSummary` (system reminders, hook output, skill expansions, + peer/subagent hand-backs and compaction summaries are all flagged this way); + 4. its `origin` is absent or `{"kind": "human"}` (`task-notification`, `peer`, ... are machine events); + 5. after removing wrappers, text remains or an image was attached. Wrappers removed: ``, + `` and `` blocks, `[Image ...]`, `[File: ...]`, `[Terminal: ...]` + and `[Assistant quote](...)` placeholders. Wrappers that make the whole record non-human are + dropped entirely: ``, ``, ``, + ``, "This session is being continued", "Caveat:". + A slash command (``) counts only through its `` text, if any. + `[Request interrupted by user...]` is counted as an interruption, not as a message. +Messages the human typed while the agent was working are not `user` records: Claude Code stores them as +`attachment` records of type `queued_command` (commandMode "prompt"); they are read with the same rules +and de-duplicated against a user record with the same text within 30 s. + +WHAT COUNTS AS MACHINE-WRITTEN (first message of a main session; the reason is stored) +Any of: the first typed message is absent; entrypoint sdk-cli (T3's auxiliary calls for titles and branch +names); an opening such as "You are a/an ...", "Act as ...", "You're a ..."; worker vocabulary ("do not +delegate", "you are a worker", "Done means", "# Constraints", "what to send back", "act as the ... sub-agent"); +typed text over 3,500 chars; 3+ markdown headings in over 1,500 chars; a known tool-generated prompt ("A +process crashed on this ... machine", "Generate a title that will help ..."). A human merely mentioning +sub-agents is not machine-written. +Pasted content does not count towards length (it is a human attachment). The heuristic errs towards +calling things machine-written: a false "machine" only removes a session from the human task set. +""" +import json, os, re, sys, time +from collections import namedtuple + +from . import paths + +FileRef = namedtuple("FileRef", "path kind project parent_id agent_id meta_path") + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS files(path TEXT PRIMARY KEY, size INTEGER, mtime_ns INTEGER, source TEXT, session_id TEXT); +CREATE TABLE IF NOT EXISTS sessions( + id TEXT PRIMARY KEY, source TEXT, path TEXT, kind TEXT, parent_id TEXT, agent_id TEXT, project TEXT, cwd TEXT, + branch TEXT, entrypoint TEXT, t0 REAL, t1 REAL, first_ts TEXT, last_ts TEXT, models TEXT, user_turns INTEGER, + first_message TEXT, machine INTEGER, machine_reason TEXT, n_corrections INTEGER, n_interrupts INTEGER, + n_ask INTEGER, n_question_turns INTEGER, n_completion_claims INTEGER, n_premature_done INTEGER, + last_claims_done INTEGER, ran_commit INTEGER, tools TEXT, used_verify INTEGER, used_contract INTEGER, meta TEXT); +CREATE INDEX IF NOT EXISTS sessions_path ON sessions(path); +CREATE INDEX IF NOT EXISTS sessions_parent ON sessions(parent_id); +CREATE TABLE IF NOT EXISTS user_msgs( + session_id TEXT, idx INTEGER, ts TEXT, t REAL, text TEXT, correction INTEGER, after_completion INTEGER, + pasted_chars INTEGER, PRIMARY KEY(session_id, idx)); +CREATE TABLE IF NOT EXISTS groundtruth( + session_id TEXT PRIMARY KEY, repo_root TEXT, repo_how TEXT, vcs TEXT, start_commit TEXT, start_kind TEXT, + start_note TEXT, commits TEXT, n_commits INTEGER, files TEXT, test_cmd TEXT, test_how TEXT, + overlap_any INTEGER, overlap_writers INTEGER, siblings TEXT, t1 REAL, computed_at REAL); +CREATE TABLE IF NOT EXISTS tasks( + id TEXT PRIMARY KEY, kind TEXT, session_id TEXT, parent_id TEXT, grade TEXT, reasons TEXT, split TEXT, + repo_root TEXT, start_commit TEXT, start_kind TEXT, test_cmd TEXT, request TEXT, ledger_id TEXT, + ledger_outcome TEXT, match_confidence TEXT, match_note TEXT, created_at REAL, updated_at REAL); +""" + + +def db_path(): + return paths.state_file("harvest.db") + + +def connect(path=None): + path = path or db_path() + os.makedirs(os.path.dirname(path), exist_ok=True) + import sqlite3 # lazy: the end-of-turn gate imports this module for typed_text and must stay fast + con = sqlite3.connect(path, timeout=60) + con.row_factory = sqlite3.Row + con.executescript(SCHEMA) + return con + + +# ---------------------------------------------------------------- small helpers + +_day_cache = {} + + +def epoch(ts): + """ISO 8601 'YYYY-MM-DDTHH:MM:SS[.fff]Z' (UTC) to epoch seconds; None when unparseable.""" + try: + day = ts[:10] + base = _day_cache.get(day) + if base is None: + import datetime + base = (datetime.date(int(day[:4]), int(day[5:7]), int(day[8:10])).toordinal() - 719163) * 86400 + _day_cache[day] = base + t = base + int(ts[11:13]) * 3600 + int(ts[14:16]) * 60 + int(ts[17:19]) + if len(ts) > 20 and ts[19] == ".": + frac = re.match(r"\.(\d+)", ts[19:]) + if frac: + t += float("0." + frac.group(1)) + return float(t) + except (TypeError, ValueError, IndexError): + return None + + +COMMIT_RE = re.compile(r"(?:^|[\s;&|(])(?:git(?:\s+-C\s+\S+)?\s+commit\b|jj\s+(?:commit|describe|squash)\b)") +SISI_VERIFY_RE = re.compile(r"(?:^|[\s/;&|(])sisi\s+verify\b") +SISI_CONTRACT_RE = re.compile(r"(?:^|[\s/;&|(])sisi\s+contract\b") + +_WRAP_BLOCKS = [re.compile(r"]*>.*?", re.S), + re.compile(r"]*>.*?", re.S), + re.compile(r".*?", re.S)] +_PLACEHOLDERS = [re.compile(r"\[Image[^\]]*\]"), re.compile(r"\[File:[^\]]*\]"), re.compile(r"\[Terminal:[^\]]*\]"), + re.compile(r"\[Assistant quote\]\([^)]*\)"), re.compile(r"\[assistant-quote-\d+\]")] +_NOT_HUMAN_PREFIX = ("(.*?)", re.S) + + +def typed_text(d, queued_prompt=None): + """Apply the typed-by-the-human rule to one user record (or a queued_command prompt). + Returns (text, pasted_chars, interrupted); text is None when the record is not user evidence.""" + if queued_prompt is None: + if d.get("type") != "user" or d.get("isMeta") or d.get("isCompactSummary") or "toolUseResult" in d: + return None, 0, False + origin = d.get("origin") + content = (d.get("message") or {}).get("content") + else: + origin = d.get("origin") + content = queued_prompt + if isinstance(origin, dict) and origin.get("kind") not in (None, "human"): + return None, 0, False + has_image = False + if isinstance(content, list): + parts = [] + for b in content: + if not isinstance(b, dict): + continue + if b.get("type") == "tool_result": + return None, 0, False + if b.get("type") == "image": + has_image = True + elif b.get("type") == "text" and isinstance(b.get("text"), str): + parts.append(b["text"]) + content = "\n".join(parts) + if not isinstance(content, str): + return None, 0, False + s = content.strip() + if s.startswith("[Request interrupted by user"): + return None, 0, True + if s.startswith(_NOT_HUMAN_PREFIX): + return None, 0, False + if s.startswith((" 1500: + return False + return bool(_CORRECTION_START.search(text) or _CORRECTION_ANYWHERE.search(text)) + + +_MACHINE_OPEN = re.compile(r"^\s*(you are (a|an|the|working|acting|being)\b|act as\b|you'?re (a|an) |you will (act|be|act as)|" + r"your (role|task|job) is\b||# (role|goal|task|mission)\b)", re.I) +_MACHINE_WORDS = re.compile(r"(do not delegate|you are a worker|you are an? (implementer|reviewer|worker)\b|" + r"\bdone means\b|# constraints|## constraints|what to send back|act as the [\w -]{0,40}sub-?agent)", re.I) +_TOOL_GENERATED = re.compile(r"^\s*(a process crashed on this| 3500: + reasons.append("long-%d" % len(text)) + elif len(text) > 1500 and len(re.findall(r"^#{1,4} ", text, re.M)) >= 3: + reasons.append("structured-headings") + return bool(reasons), ";".join(reasons) + + +# ---------------------------------------------------------------- source interface + +class Source: + name = "?" + + def discover(self, home): + raise NotImplementedError + + def parse(self, ref): + raise NotImplementedError + + +def parse_meta(path): + try: + with open(path, encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else {} + except (OSError, ValueError): + return {} + + +class ClaudeCodeSource(Source): + name = "claude-code" + + def discover(self, home): + root = os.path.join(home, ".claude", "projects") + try: + projects = sorted(os.listdir(root)) + except OSError: + return + for proj in projects: + pdir = os.path.join(root, proj) + try: + entries = sorted(os.listdir(pdir)) + except OSError: + continue + for e in entries: + p = os.path.join(pdir, e) + if e.endswith(".jsonl") and os.path.isfile(p): + yield FileRef(p, "main", proj, None, None, None) + elif os.path.isdir(p): + sub = os.path.join(p, "subagents") + for dirpath, dirs, names in os.walk(sub): # workflow subagents nest under subagents/workflows/wf_*/ + dirs.sort() + for n in sorted(names): + if n.startswith("agent-") and n.endswith(".jsonl"): + yield FileRef(os.path.join(dirpath, n), "subagent", proj, e, n[6:-6], + os.path.join(dirpath, n[:-6] + ".meta.json")) + + def parse(self, ref): + return parse_transcript(ref) + + +SOURCES = {"claude-code": ClaudeCodeSource()} + + +# ---------------------------------------------------------------- the transcript parser + +def _sub_id(ref): + """Subagent session id: agent id qualified by parent (and workflow dir), since agent ids can recur.""" + parts = os.path.dirname(ref.path).split(os.sep) + wf = parts[-1] if "workflows" in parts else "" + return ".".join(x for x in ((ref.parent_id or "")[:8], wf[3:11] if wf else "", ref.agent_id) if x) + + +def parse_transcript(ref): + """Stream one Claude Code transcript. Never raises on malformed lines. Returns (session, messages).""" + main = ref.kind == "main" + S = dict(source="claude-code", path=ref.path, kind=ref.kind, parent_id=ref.parent_id, agent_id=ref.agent_id, + project=ref.project, cwd=None, branch=None, entrypoint=None, t0=None, t1=None, first_ts=None, last_ts=None, + models={}, user_turns=0, first_message=None, machine=0, machine_reason="", n_corrections=0, + n_interrupts=0, n_ask=0, n_question_turns=0, n_completion_claims=0, n_premature_done=0, + last_claims_done=0, ran_commit=0, tools={}, used_verify=0, used_contract=0, meta={}) + S["id"] = os.path.basename(ref.path)[:-6] if main else _sub_id(ref) + msgs = [] + first_origin = None + first_user_seen = False + last_asst = None # (has_tool, last_text) of the latest assistant record with content + prev_claim = False + recent = [] # (text, t) of recent typed messages, for queued_command de-duplication + sid_from_records = None + + def close_segment(): + """The assistant turn before a typed message ended; classify it.""" + nonlocal prev_claim + has_tool, text = last_asst if last_asst else (True, "") + claim = False + if not has_tool and text: + if _QUESTION_TAIL.search(text.rstrip()): + S["n_question_turns"] += 1 + elif _CLAIM_RE.search(text[-700:]): + claim = True + S["n_completion_claims"] += 1 + prev_claim = claim + + def note_ts(d, line): + ts = d.get("timestamp") if d else None + if isinstance(ts, str): + t = epoch(ts) + if t is not None: + if S["t0"] is None or t < S["t0"]: + S["t0"], S["first_ts"] = t, ts + if S["t1"] is None or t > S["t1"]: + S["t1"], S["last_ts"] = t, ts + + def add_message(text, pasted, ts, origin_kind, entrypoint, queued=False): + nonlocal last_asst, first_origin + t = epoch(ts) if isinstance(ts, str) else None + for (rt, rtt) in recent[-4:]: + if rt == text and t is not None and rtt is not None and abs(rtt - t) < 30: + return + recent.append((text, t)) + del recent[:-6] + idx = S["user_turns"] + close_segment() + corr = 0 + if idx > 0 and is_correction(text): + corr = 1 + S["n_corrections"] += 1 + if prev_claim: + S["n_premature_done"] += 1 + msgs.append(dict(idx=idx, ts=ts, t=t, text=text if idx == 0 else text[:20000], correction=corr, + after_completion=1 if prev_claim else 0, pasted_chars=pasted)) + S["user_turns"] += 1 + if idx == 0: + S["first_message"] = text + first_origin = origin_kind + last_asst = None + + try: + f = open(ref.path, "rb") + except OSError: + S["meta"] = {"error": "unreadable"} + return S, msgs + with f: + for raw in f: + try: + if not raw.startswith(b'{"parentUuid"'): + # queue-operation, api-request(-blob), last-prompt, ai-title ... carry nothing we use + continue + is_att = b'"type":"attachment"' in raw + if is_att and b'"queued_command"' not in raw: + continue + if b'"toolUseResult"' in raw and not is_att: + i = raw.find(b'"timestamp":"') + if i >= 0: + note_ts({"timestamp": raw[i + 13:i + 37].split(b'"')[0].decode("ascii", "replace")}, None) + continue + d = json.loads(raw) + if not isinstance(d, dict): + continue + note_ts(d, raw) + if S["cwd"] is None and isinstance(d.get("cwd"), str): + S["cwd"] = d["cwd"] + if S["branch"] is None and isinstance(d.get("gitBranch"), str): + S["branch"] = d["gitBranch"] + if S["entrypoint"] is None and isinstance(d.get("entrypoint"), str): + S["entrypoint"] = d["entrypoint"] + if main and sid_from_records is None and isinstance(d.get("sessionId"), str): + sid_from_records = d["sessionId"] + typ = d.get("type") + if typ == "assistant": + m = d.get("message") or {} + model = m.get("model") + if isinstance(model, str) and not model.startswith("<"): + S["models"][model] = S["models"].get(model, 0) + 1 + content = m.get("content") + if isinstance(content, str): + content = [{"type": "text", "text": content}] + has_tool, text = False, None + for b in content if isinstance(content, list) else (): + if not isinstance(b, dict): + continue + bt = b.get("type") + if bt == "text" and isinstance(b.get("text"), str) and b["text"].strip(): + text = b["text"] + elif bt == "tool_use": + has_tool = True + name = b.get("name") or "?" + S["tools"][name] = S["tools"].get(name, 0) + 1 + if name == "AskUserQuestion": + S["n_ask"] += 1 + inp = b.get("input") + cmd = inp.get("command") if isinstance(inp, dict) else None + if name == "Bash" and isinstance(cmd, str): + if COMMIT_RE.search(cmd): + S["ran_commit"] = 1 + if SISI_VERIFY_RE.search(cmd): + S["used_verify"] = 1 + if SISI_CONTRACT_RE.search(cmd): + S["used_contract"] = 1 + if has_tool or text is not None: + last_asst = (has_tool, text or "") + elif typ == "user": + if not main: + if not first_user_seen and not d.get("isMeta"): + first_user_seen = True + c = (d.get("message") or {}).get("content") + if isinstance(c, list): + c = "\n".join(b.get("text", "") for b in c if isinstance(b, dict) and b.get("type") == "text") + S["first_message"] = c if isinstance(c, str) else None + continue + text, pasted, interrupted = typed_text(d) + if interrupted: + S["n_interrupts"] += 1 + elif text is not None: + o = d.get("origin") + add_message(text, pasted, d.get("timestamp"), o.get("kind") if isinstance(o, dict) else None, d.get("entrypoint")) + elif typ == "attachment" and main: + a = d.get("attachment") or {} + if a.get("type") == "queued_command" and a.get("commandMode") == "prompt" and not a.get("isMeta"): + text, pasted, interrupted = typed_text(a, queued_prompt=a.get("prompt")) + if text is not None: + o = a.get("origin") + add_message(text, pasted, a.get("timestamp") or d.get("timestamp"), + o.get("kind") if isinstance(o, dict) else None, d.get("entrypoint"), queued=True) + except Exception: # malformed or surprising line: skip it, never abort the harvest + continue + close_segment() + S["last_claims_done"] = 1 if prev_claim else 0 + if main: + if sid_from_records and sid_from_records != S["id"]: + S["meta"]["session_id_in_records"] = sid_from_records + S["machine"], S["machine_reason"] = (lambda r: (int(r[0]), r[1]))( + machine_reason(S["first_message"], first_origin, S["entrypoint"])) + else: + S["machine"], S["machine_reason"] = 1, "subagent" + S["meta"] = parse_meta(ref.meta_path) if ref.meta_path else {} + return S, msgs + + +# ---------------------------------------------------------------- persistence + +def _store(con, S, msgs): + con.execute("DELETE FROM sessions WHERE path=?", (S["path"],)) + con.execute("DELETE FROM user_msgs WHERE session_id=?", (S["id"],)) + cols = ["id", "source", "path", "kind", "parent_id", "agent_id", "project", "cwd", "branch", "entrypoint", "t0", "t1", + "first_ts", "last_ts", "models", "user_turns", "first_message", "machine", "machine_reason", "n_corrections", + "n_interrupts", "n_ask", "n_question_turns", "n_completion_claims", "n_premature_done", "last_claims_done", + "ran_commit", "tools", "used_verify", "used_contract", "meta"] + row = [json.dumps(S[c], sort_keys=True) if c in ("models", "tools", "meta") else S[c] for c in cols] + con.execute("INSERT OR REPLACE INTO sessions(%s) VALUES(%s)" % (",".join(cols), ",".join("?" * len(cols))), row) + con.executemany("INSERT OR REPLACE INTO user_msgs VALUES(?,?,?,?,?,?,?,?)", + [(S["id"], m["idx"], m["ts"], m["t"], m["text"], m["correction"], m["after_completion"], m["pasted_chars"]) + for m in msgs]) + + +def _work(ref): + try: + return ref, parse_transcript(ref), None + except Exception as e: # pragma: no cover - parse_transcript is defensive already + return ref, None, repr(e) + + +def run(home=None, workers=None, source_names=None, progress=None, con=None): + """Incremental harvest. Returns stats: files seen, parsed, skipped, errors, sessions stored.""" + home = home or paths.home() + own = con is None + con = con or connect() + known = {r["path"]: (r["size"], r["mtime_ns"]) for r in con.execute("SELECT path,size,mtime_ns FROM files")} + todo, seen, skipped = [], set(), 0 + for name, src in SOURCES.items(): + if source_names and name not in source_names: + continue + for ref in src.discover(home): + seen.add(ref.path) + try: + st = os.stat(ref.path) + except OSError: + continue + if known.get(ref.path) == (st.st_size, st.st_mtime_ns): + skipped += 1 + continue + todo.append((ref, st, name)) + stats = {"seen": len(seen), "skipped": skipped, "parsed": 0, "errors": 0, "removed": 0} + # files that disappeared: drop their rows + for p in set(known) - seen: + con.execute("DELETE FROM user_msgs WHERE session_id IN (SELECT id FROM sessions WHERE path=?)", (p,)) + con.execute("DELETE FROM sessions WHERE path=?", (p,)) + con.execute("DELETE FROM files WHERE path=?", (p,)) + stats["removed"] += 1 + todo.sort(key=lambda x: -x[1].st_size) # big files first keeps pool workers busy + byref = {t[0].path: t for t in todo} + workers = workers if workers is not None else min(8, os.cpu_count() or 2) + if workers > 1 and len(todo) > 8: + from concurrent.futures import ProcessPoolExecutor + ex = ProcessPoolExecutor(max_workers=workers) + results = ex.map(_work, [t[0] for t in todo], chunksize=4) + else: + ex = None + results = map(_work, [t[0] for t in todo]) + try: + for n, (ref, parsed, err) in enumerate(results, 1): + _, st, name = byref[ref.path] + if err or parsed is None: + stats["errors"] += 1 + continue + S, msgs = parsed + _store(con, S, msgs) + con.execute("INSERT OR REPLACE INTO files VALUES(?,?,?,?,?)", (ref.path, st.st_size, st.st_mtime_ns, name, S["id"])) + stats["parsed"] += 1 + if n % 50 == 0: + con.commit() + if progress: + progress("harvest: %d/%d files" % (n, len(todo))) + finally: + if ex: + ex.shutdown() + con.commit() + stats["sessions"] = con.execute("SELECT COUNT(*) FROM sessions").fetchone()[0] + if own: + con.close() + return stats diff --git a/sisi/learn_cli.py b/sisi/learn_cli.py new file mode 100644 index 0000000..96d0d5d --- /dev/null +++ b/sisi/learn_cli.py @@ -0,0 +1,162 @@ +"""Commands for the data layer of the learning loop: harvest, tasks, escapes, checks, scoreboard. + +Usable now as `python3 -m sisi.learn_cli `. The main CLI hooks them in with +`learn_cli.register(subparsers)`; each command sets `func(args) -> exit code` on its parser. +No model calls anywhere. Session text stays in the state dir's harvest.db. +""" +import argparse, json, sys, time + +from . import store + + +def _con(): + from . import harvest + return harvest.connect() + + +def cmd_harvest(args): + from . import groundtruth, harvest + t = time.time() + con = harvest.connect() + say = (lambda m: print(m, file=sys.stderr)) if not args.quiet else None + st = harvest.run(con=con, workers=args.workers, progress=say) + t_parse = time.time() - t + gt = groundtruth.run(con, progress=say) if not args.no_ground_truth else {"computed": 0, "skipped": 0} + out = {"transcripts": st, "ground_truth": gt, "seconds": round(time.time() - t, 1), "parse_seconds": round(t_parse, 1)} + if args.json: + print(json.dumps(out)) + else: + print("harvest: %(seen)d transcripts (%(parsed)d read, %(skipped)d unchanged, %(errors)d errors), %(sessions)d sessions" % st) + print("ground truth: %(computed)d computed, %(skipped)d unchanged" % gt) + print("took %.1fs" % out["seconds"]) + return 0 if st["errors"] == 0 else 1 + + +def cmd_tasks(args): + from . import harvest, taskset + con = harvest.connect() + sub = args.tasks_cmd + if sub == "build": + r = taskset.build(con) + print("tasks: %(human)d human, %(brief)d brief (%(removed)d removed; %(ledger_records)d ledger records read)" % r) + return 0 + if sub == "list": + rows = taskset.list_tasks(con, args.kind, args.grade, args.split) + if args.json: + print(json.dumps([{k: v for k, v in r.items() if k != "request"} for r in rows])) + return 0 + for r in rows: + extra = ("%s %s" % (r["start_kind"], r["test_cmd"] or "-")) if r["kind"] == "human" else \ + ("ledger:%s %s" % (r["match_confidence"], r["ledger_outcome"] or "-")) + print("%-22s %-5s %-2s %-7s %s" % (r["id"], r["kind"], r["grade"] or "-", r["split"], extra)) + print("%d task(s)" % len(rows), file=sys.stderr) + return 0 + if sub == "show": + t = taskset.get_task(con, args.id) + if not t: + print("sisi: no single task matches %r" % args.id, file=sys.stderr) + return 1 + t["reasons"] = json.loads(t["reasons"] or "[]") + if not args.full and t["request"] and len(t["request"]) > 2000: + t["request"] = t["request"][:2000] + " ...[truncated, use --full]" + if args.json: + print(json.dumps(t)) + else: + for k, v in t.items(): + print("%s: %s" % (k, v if not isinstance(v, list) else "; ".join(v))) + return 0 + return 2 + + +def cmd_escapes(args): + from . import escapes, harvest + rows = escapes.find(harvest.connect()) + if args.json: + print(json.dumps(rows)) + return 0 + by = {} + for r in rows: + by[r["kind"]] = by.get(r["kind"], 0) + 1 + for r in rows: + print("%-26s session=%s %s%s" % (r["kind"], r["session"][:12], json.dumps(r["evidence"]), " (ambiguous)" if r.get("ambiguous") else "")) + print("candidates: %s" % (", ".join("%s=%d" % kv for kv in sorted(by.items())) or "none"), file=sys.stderr) + return 0 + + +def cmd_checks(args): + from . import scoreboard + st = scoreboard.check_stats(store.read("results")) + if args.json: + print(json.dumps(st)) + return 0 + for title, key in (("check", "checks"), ("verifier", "verifiers")): + if not st[key]: + continue + print("%-40s %5s %5s %5s" % (title, "runs", "fail", "tmo")) + for s in st[key]: + print("%-40s %5d %5d %5d%s" % (s["id"][:40], s["runs"], s["failures"], s["timeouts"], + " never seen failing" if s["never_seen_failing"] else "")) + return 0 + + +def cmd_scoreboard(args): + from . import scoreboard + sb = scoreboard.scoreboard(_con()) + if args.json: + print(json.dumps(sb)) + return 0 + cols = ("sessions", "turns_per_session", "corrections_per_100", "questions_per_100", "contract_share", "premature_done_share") + for title, key in (("week", "weeks"), ("repo", "repos")): + print("%-18s %s" % (title, " ".join("%-12s" % c[:12] for c in cols))) + for k, v in sb[key].items(): + print("%-18s %s" % (k[:18], " ".join("%-12s" % ("-" if v[c] is None else v[c]) for c in cols))) + print() + print("tasks:", json.dumps(sb["tasks"])) + return 0 + + +def register(subparsers): + p = subparsers.add_parser("harvest", help="read agent transcripts into the harvest database (incremental)") + p.add_argument("--workers", type=int, default=None) + p.add_argument("--no-ground-truth", action="store_true") + p.add_argument("--quiet", action="store_true") + p.add_argument("--json", action="store_true") + p.set_defaults(func=cmd_harvest) + + p = subparsers.add_parser("tasks", help="build, list and show the task set") + ts = p.add_subparsers(dest="tasks_cmd", required=True) + ts.add_parser("build").set_defaults(func=cmd_tasks) + q = ts.add_parser("list") + q.add_argument("--kind", choices=["human", "brief"]) + q.add_argument("--grade", choices=["A", "B", "C"]) + q.add_argument("--split", choices=["dev", "holdout"]) + q.add_argument("--json", action="store_true") + q.set_defaults(func=cmd_tasks) + q = ts.add_parser("show") + q.add_argument("id") + q.add_argument("--full", action="store_true") + q.add_argument("--json", action="store_true") + q.set_defaults(func=cmd_tasks) + + p = subparsers.add_parser("escapes", help="candidate cases where verified work turned out wrong") + p.add_argument("--json", action="store_true") + p.set_defaults(func=cmd_escapes) + + p = subparsers.add_parser("checks", help="per-check and per-verifier run statistics") + p.add_argument("--json", action="store_true") + p.set_defaults(func=cmd_checks) + + p = subparsers.add_parser("scoreboard", help="weekly and per-repo trends from harvested sessions") + p.add_argument("--json", action="store_true") + p.set_defaults(func=cmd_scoreboard) + + +def main(argv=None): + ap = argparse.ArgumentParser(prog="sisi") + register(ap.add_subparsers(dest="cmd", required=True)) + args = ap.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/sisi/lifecycle.py b/sisi/lifecycle.py new file mode 100644 index 0000000..f9fd470 --- /dev/null +++ b/sisi/lifecycle.py @@ -0,0 +1,443 @@ +"""Moving personal data around: migrate (old layout to new), update (the product), export and import. +Nothing here writes inside the product. Every step that moves or replaces data first copies it into +/backups/-/.""" +import io, json, os, shutil, sqlite3, subprocess, sys, tarfile, time + +from . import overlay, paths, pdata, store + + +# ---- helpers ------------------------------------------------------------------------ +def _read(p): + try: + with open(p, encoding="utf-8") as f: + return f.read() + except OSError: + return None + + +def _lines(p): + t = _read(p) + return t.splitlines() if t else [] + + +def _union_lines(src, dst): + """Append to dst the lines of src it lacks (dst first, order kept). Returns the number appended.""" + have = _lines(dst) + seen = set(have) + add = [l for l in _lines(src) if l not in seen and not seen.add(l)] + if add: + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "a", encoding="utf-8") as f: + if have and not (_read(dst) or "").endswith("\n"): + f.write("\n") + f.write("\n".join(add) + "\n") + return len(add) + + +def _copy_into(src, bdir, rel): + dst = os.path.join(bdir, rel) + os.makedirs(os.path.dirname(dst), exist_ok=True) + if os.path.isdir(src): + shutil.copytree(src, dst, dirs_exist_ok=True) + elif src.endswith(".db"): + _sqlite_copy(src, dst) + else: + shutil.copy2(src, dst) + + +def _sqlite_copy(src, dst): + """A consistent copy of a database that other processes may be writing.""" + a = sqlite3.connect(src, timeout=30) + try: + b = sqlite3.connect(dst) + try: + a.backup(b) + finally: + b.close() + finally: + a.close() + + +def _same(a, b): + return os.path.realpath(a) == os.path.realpath(b) + + +# ---- migrate ---------------------------------------------------------------------------- +def _legacy_notes(): + if os.environ.get("SISI_NOTES"): + return None + d = paths.legacy_notes_dir() + return d if os.path.isdir(d) and any(n.endswith(".md") for n in os.listdir(d)) else None + + +def _notes_pending(src_dir): + dst = paths.notes_dir() + for n in os.listdir(src_dir): + if n.endswith(".md"): + have = set(_lines(os.path.join(dst, n))) + if any(l not in have for l in _lines(os.path.join(src_dir, n))): + return True + return False + + +def _merge_manifest(src, dst): + a = json.loads(_read(src) or "{}") + b = json.loads(_read(dst) or "{}") + files = dict(a.get("files", {})) + files.update(b.get("files", {})) + dirs = list(dict.fromkeys(b.get("dirs", []) + a.get("dirs", []))) + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "w", encoding="utf-8") as f: + f.write(json.dumps({"dirs": dirs, "files": files}, indent=1, sort_keys=True) + "\n") + + +def _merge_retro_db(src, dst): + """Both databases exist: bring the lessons of src that dst lacks into dst. Never drops or duplicates one.""" + a = sqlite3.connect(src, timeout=30) + a.row_factory = sqlite3.Row + b = sqlite3.connect(dst, timeout=30) + b.row_factory = sqlite3.Row + added = 0 + try: + from . import retro + key = lambda r: (r["aim"], r["change_kind"], r["target"], r["change"]) + have = {key(r): r["id"] for r in b.execute("SELECT * FROM lessons")} + for r in a.execute("SELECT * FROM lessons ORDER BY id"): + if key(r) in have: + lid = have[key(r)] + else: + cols = [c for c in retro.LESSON_COLS if c != "id"] + cur = b.execute("INSERT INTO lessons(%s) VALUES(%s)" % (",".join(cols), ",".join("?" * len(cols))), [r[c] for c in cols]) + lid = cur.lastrowid + have[key(r)] = lid + added += 1 + for o in a.execute("SELECT * FROM occurrences WHERE lesson_id=? ORDER BY id", (r["id"],)): + if b.execute("SELECT 1 FROM occurrences WHERE lesson_id=? AND ts=? AND session IS ? AND moment=?", + (lid, o["ts"], o["session"], o["moment"])).fetchone(): + continue + cols = [c for c in retro.OCC_COLS if c not in ("id", "lesson_id")] + b.execute("INSERT INTO occurrences(lesson_id,%s) VALUES(?,%s)" % (",".join(cols), ",".join("?" * len(cols))), + [lid] + [o[c] if c in o.keys() else None for c in cols]) + b.commit() + finally: + a.close() + b.close() + return added + + +def _move_retro_db(src, dst, notes): + if not os.path.exists(dst): + hold = sqlite3.connect(src, timeout=30) + try: + hold.execute("BEGIN IMMEDIATE") # other writers wait while the copy is made; readers still read + tmp = dst + ".tmp%d" % os.getpid() + _sqlite_copy(src, tmp) + os.replace(tmp, dst) + notes.append("retro.db moved to the personal data folder") + finally: + hold.rollback() + hold.close() + else: + n = _merge_retro_db(src, dst) + notes.append("retro.db: both old and new existed; merged %d lesson(s) that the new one lacked" % n) + for suffix in ("", "-journal", "-wal", "-shm"): + try: + os.unlink(src + suffix) + except OSError: + pass + + +STATE_JSONL = ("learn-quarantine.jsonl", "notes.jsonl", "proposals.jsonl") + + +def pending(): + """What migrate would move, as a list of short names.""" + out, st = [], paths.state() + if _same(st, paths.data()): + return out + o = paths.canon("oracle.md") + if os.path.isfile(o) and not os.path.exists(paths.data_file("oracle.md")): + out.append("oracle.md") + n = _legacy_notes() + if n and _notes_pending(n): + out.append("notes/") + for name in ("trusted.json", "config.json", "retro.db", "manifest.json", "backups") + STATE_JSONL: + if os.path.exists(os.path.join(st, name)): + out.append(name) + return out + + +def run(): + """Move an old-layout installation into the new layout. Idempotent. Returns a list of notes.""" + todo = pending() + pdata.ensure() + notes = [] + if todo: + with pdata.lock(): + bdir = pdata.backup_dir("migrate") + st, data = paths.state(), paths.data() + # 1. back up everything that will be moved + for name in todo: + if name == "oracle.md": + _copy_into(paths.canon("oracle.md"), bdir, "product/canon/oracle.md") + elif name == "notes/": + _copy_into(_legacy_notes(), bdir, "product/notes") + else: + _copy_into(os.path.join(st, name), bdir, "state/" + name) + notes.append("backed up what will move to %s" % bdir) + # 2. move + for name in todo: + src = os.path.join(st, name) + if name == "oracle.md": + pdata.write_text("oracle.md", _read(paths.canon("oracle.md"))) + notes.append("oracle.md copied to the personal data folder (the product's copy is left alone; delete it from the clone)") + elif name == "notes/": + d = paths.notes_dir() + os.makedirs(d, exist_ok=True) + nn = _legacy_notes() + for f in sorted(os.listdir(nn)): + if f.endswith(".md"): + if os.path.exists(os.path.join(d, f)): + _union_lines(os.path.join(nn, f), os.path.join(d, f)) + else: + shutil.copy2(os.path.join(nn, f), os.path.join(d, f)) + notes.append("field notes copied to %s (the product's notes/ is left alone; delete it from the clone)" % d) + elif name == "trusted.json": + cur = [] + for p in (paths.data_file("trusted.json"), src): + try: + cur += [x for x in json.loads(_read(p) or "[]") if isinstance(x, str)] + except ValueError: + pass + pdata.write_text("trusted.json", json.dumps(sorted(set(cur)), indent=1)) + os.unlink(src) + notes.append("trusted.json moved") + elif name == "config.json": + if os.path.exists(paths.data_file("config.json")): + notes.append("config.json: a personal one already exists; the old one stays only in the backup") + os.unlink(src) + else: + shutil.move(src, paths.data_file("config.json")) + notes.append("config.json moved") + elif name == "retro.db": + _move_retro_db(src, paths.data_file("retro.db"), notes) + elif name == "manifest.json": + _merge_manifest(src, paths.data_file("install", "manifest.json")) + os.unlink(src) + notes.append("install manifest moved") + elif name == "backups": + d = paths.data_file("install", "backups") + os.makedirs(d, exist_ok=True) + for f in os.listdir(src): + if not os.path.exists(os.path.join(d, f)): + shutil.copy2(os.path.join(src, f), os.path.join(d, f)) + shutil.rmtree(src) + notes.append("install backups moved") + else: + _union_lines(src, paths.data_file(name)) + os.unlink(src) + notes.append("%s moved" % name) + try: + from . import retro + retro.export_jsonl() + except Exception as e: + store.log_error("migrate-export", e) + notes.append("lessons dump failed: %r" % e) + pdata.commit("migrate: move personal data out of the product and the state folder", strict=True) + notes += pdata.upgrade() + return notes + + +# ---- snapshots (before an update) ------------------------------------------------------------- +SKIP_TOP = {"backups", "generated", "install", ".lock"} + + +def snapshot(reason): + """Copy personal data (without backups, generated files and install records) into backups/. Returns the folder.""" + bdir = pdata.backup_dir(reason) + d = paths.data() + for n in sorted(os.listdir(d)): + if n in SKIP_TOP or n.startswith("retro.db") or ".tmp" in n: + continue + _copy_into(os.path.join(d, n), bdir, n) + if os.path.exists(paths.data_file("retro.db")): + _sqlite_copy(paths.data_file("retro.db"), os.path.join(bdir, "retro.db")) + return bdir + + +# ---- update --------------------------------------------------------------------------------------- +def _pgit(*a, timeout=120): + return subprocess.run(["git", "-C", paths.REPO] + list(a), capture_output=True, text=True, timeout=timeout, + env=dict(os.environ, GIT_TERMINAL_PROMPT="0")) + + +def cmd_update(args): + if "--post" in args: + return post_update() + say = print + try: + top = _pgit("rev-parse", "--show-toplevel") + if top.returncode != 0 or os.path.realpath(top.stdout.strip()) != os.path.realpath(paths.REPO): + say("sisi update: %s is not a git clone, so there is nothing to fetch. Replace it with a newer copy and run " + "`sisi update --post` to rebuild." % paths.REPO) + return 1 + if _pgit("rev-parse", "--verify", "-q", "HEAD").returncode != 0: + say("sisi update: the product repository has no commits yet; nothing to update.") + return 1 + up = _pgit("rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}") + if up.returncode != 0: + say("sisi update: the product has no upstream branch. Set one (`git -C %s branch --set-upstream-to=origin/main`) " + "and try again. Nothing was changed." % paths.REPO) + return 1 + dirty = _pgit("status", "--porcelain", "--untracked-files=no").stdout.strip() + if dirty: + say("sisi update: the product has local changes, so it will not be updated (nothing is ever discarded):\n%s\n" + "Commit or stash them, then run `sisi update` again." % dirty) + return 1 + f = _pgit("fetch", "--quiet") + if f.returncode != 0: + say("sisi update: fetch failed: %s" % (f.stderr.strip() or f.stdout.strip())) + return 1 + before = _pgit("rev-parse", "HEAD").stdout.strip() + m = _pgit("merge", "--ff-only", "--quiet", "@{u}") + if m.returncode != 0: + say("sisi update: the product cannot be fast-forwarded to %s (local commits?): %s\nNothing was changed." + % (up.stdout.strip(), m.stderr.strip() or m.stdout.strip())) + return 1 + after = _pgit("rev-parse", "HEAD").stdout.strip() + except (OSError, subprocess.SubprocessError) as e: + say("sisi update: git failed: %r" % e) + return 1 + say("product: %s" % ("already up to date at %s" % after[:10] if before == after else "%s -> %s" % (before[:10], after[:10]))) + sys.stdout.flush() + # continue in a fresh process so the new code does the rest + p = subprocess.run([sys.executable, paths.launcher(), "update", "--post"], capture_output=True, text=True) + print(p.stdout, end="") + print(p.stderr, end="", file=sys.stderr) + return p.returncode + + +def post_update(): + """After the product changed: back up personal data, migrate its format, keep replacements, rebuild, check.""" + try: + pdata.ensure() + print("backup: %s" % snapshot("update")) + for n in run(): + print(n) + for r in overlay.scan_retests(): + print("kept your version of %s %s; its base changed in this update, queued in retest.jsonl" % (r["kind"], r["id"])) + b = overlay.build_canon() + print("rulebook rebuilt: %d lines%s" % (b["lines"], " - OVER THE %d-LINE BUDGET; shorten or replace a rule" % overlay.MAX_LINES if b["over_budget"] else "")) + except pdata.DataError as e: + print("sisi update: %s" % e) + return 1 + from . import cli + print("doctor:") + return cli.cmd_wiring("doctor") + + +# ---- export / import ------------------------------------------------------------------------------ +def _tar_filter(ti): + parts = ti.name.split("/") + if len(parts) > 1 and parts[0] == "personal" and (parts[1] in SKIP_TOP or parts[1].startswith("retro.db") or ".tmp" in parts[1]): + return None + return ti + + +def export(path=None): + path = path or os.path.join(os.getcwd(), "sisi-export-%s.tar.gz" % time.strftime("%Y%m%d-%H%M%S")) + pdata.ensure() + tmpdb = None + with pdata.lock(): + with tarfile.open(path, "w:gz") as tf: + meta = json.dumps({"sisi_export": 1, "personal_format": pdata.version(), + "created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}).encode() + ti = tarfile.TarInfo("sisi-export.json") + ti.size, ti.mtime = len(meta), int(time.time()) + tf.addfile(ti, io.BytesIO(meta)) + tf.add(paths.data(), arcname="personal", filter=_tar_filter) + if os.path.exists(paths.data_file("retro.db")): + import tempfile + fd, tmpdb = tempfile.mkstemp(suffix=".db") + os.close(fd) + _sqlite_copy(paths.data_file("retro.db"), tmpdb) + tf.add(tmpdb, arcname="personal/retro.db") + st = paths.state() + for name in ("results.jsonl", "sessions"): + if os.path.exists(os.path.join(st, name)): + tf.add(os.path.join(st, name), arcname="state/" + name) + if tmpdb: + try: + os.unlink(tmpdb) + except OSError: + pass + return path + + +def _safe(name): + return not (name.startswith("/") or ".." in name.split("/") or "\0" in name) + + +def import_archive(path): + """Restore an export. Returns notes. The existing personal folder, if any, is set aside, never deleted.""" + notes = [] + try: + tf = tarfile.open(path, "r:*") + except (OSError, tarfile.TarError) as e: + raise pdata.DataError("cannot read %s: %s" % (path, e)) + with tf: + members = tf.getmembers() + try: + meta = json.loads(tf.extractfile("sisi-export.json").read()) + except (KeyError, ValueError, AttributeError): + raise pdata.DataError("%s is not a sisi export (no sisi-export.json)" % path) + if int(meta.get("personal_format", 0)) > pdata.FORMAT_VERSION: + raise pdata.DataError("the export is personal-data format %s, newer than this sisi understands (%d); update sisi first" + % (meta.get("personal_format"), pdata.FORMAT_VERSION)) + for m in members: + if not _safe(m.name) or not (m.isfile() or m.isdir()) or \ + not (m.name == "sisi-export.json" or m.name.split("/")[0] in ("personal", "state")): + raise pdata.DataError("the archive holds an unexpected entry %r; nothing was restored" % m.name) + data = paths.data() + if os.path.isdir(data) and os.listdir(data): + aside = "%s.before-import-%s" % (data.rstrip("/"), time.strftime("%Y%m%d-%H%M%S")) + os.rename(data, aside) + notes.append("the existing personal data was set aside at %s" % aside) + os.makedirs(data, exist_ok=True) + st = paths.state() + for m in members: + head, _, rel = m.name.partition("/") + if head == "personal": + dst = os.path.join(data, rel) if rel else data + elif head == "state" and rel: + dst = os.path.join(st, rel) + if os.path.exists(dst) and not m.isdir(): + if rel == "results.jsonl": + tmp = dst + ".import" + with open(tmp, "wb") as f: + f.write(tf.extractfile(m).read()) + _union_lines(tmp, dst) + os.unlink(tmp) + continue + else: + continue + if m.isdir(): + os.makedirs(dst, exist_ok=True) + continue + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, "wb") as f: + f.write(tf.extractfile(m).read()) + os.chmod(dst, m.mode & 0o777 or 0o644) + os.utime(dst, (m.mtime, m.mtime)) + if not os.path.exists(paths.data_file("retro.db")) and os.path.exists(paths.data_file("lessons.jsonl")): + from . import retro + con = retro.connect() + try: + retro.import_jsonl(paths.data_file("lessons.jsonl"), con) + finally: + con.close() + notes.append("retro.db rebuilt from lessons.jsonl") + notes += pdata.upgrade() + b = overlay.build_canon() + notes.append("rulebook rebuilt: %d lines" % b["lines"]) + return notes diff --git a/sisi/overlay.py b/sisi/overlay.py new file mode 100644 index 0000000..cbf47a0 --- /dev/null +++ b/sisi/overlay.py @@ -0,0 +1,681 @@ +"""The overlay: how what sisi learned changes the base rulebook, verifiers and recipes without editing the product. + +Files, all under /overlay/: + rules/.md a rule: `## Title` then the body. Same id as a base rule = replaces it; new id = adds one. + rules/disabled.txt ids of rules switched off (one per line) + rules/order.txt order of added rules (ids, one per line); base rules keep the base order + verifiers/
/.md a verifier in the library's own format (replaces the product's of that id, or adds) + verifiers/disabled.txt ids of verifiers switched off + done/.md a recipe in the library's own format (replace or add) + done/disabled.txt ids of recipes switched off + bases.json for each replacement: the hash of the base item it was made against + +The effective rulebook (base + overlay) is generated to /generated/core.md by `build-canon`. +Every command that changes the overlay is one commit in the personal git repository and is refused when the +generated rulebook would exceed MAX_LINES. +""" +import contextlib, hashlib, json, os, re, sys, tempfile, time + +from . import paths + +MAX_LINES = 120 +KINDS = ("rule", "verifier", "recipe") +ID_TAIL = re.compile(r"\s*\{#([A-Za-z0-9][A-Za-z0-9_-]*)\}\s*$") +NUM = re.compile(r"^\d+\.\s+") +ID_OK = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$") + + +class OverlayError(Exception): + pass + + +def sha(b): + if isinstance(b, str): + b = b.encode("utf-8") + return hashlib.sha256(b).hexdigest() + + +def slug(t): + return re.sub(r"[^a-z0-9]+", "-", t.lower()).strip("-")[:40] or "rule" + + +# ---- rules: parse and render ------------------------------------------------- +def parse_rules(text): + """(preamble, [rule]) where rule = {id, title, body, hash}. A rule starts at a `## ` heading, + `## 3. Title {#id}`; without {#id} the id is a slug of the title.""" + pre, rules, cur = [], [], None + for line in text.split("\n"): + if line.startswith("## "): + if cur: + rules.append(cur) + t = NUM.sub("", line[3:].strip()) + m = ID_TAIL.search(t) + rid = m.group(1) if m else None + if m: + t = t[:m.start()] + cur = {"id": rid or slug(t), "title": t.strip(), "lines": []} + elif cur is not None: + cur["lines"].append(line) + else: + pre.append(line) + if cur: + rules.append(cur) + for r in rules: + r["body"] = "\n".join(r.pop("lines")).strip("\n") + r["hash"] = sha(r["title"] + "\n" + r["body"]) + return "\n".join(pre).strip("\n"), rules + + +def parse_rule_file(text, rid=None): + pre, rules = parse_rules(text) + if pre.strip(): + raise OverlayError("a rule file must start with a `## Title` heading (found text before it)") + if len(rules) != 1: + raise OverlayError("a rule file holds exactly one rule (one `## Title` heading), found %d" % len(rules)) + r = rules[0] + if rid: + if not ID_OK.match(rid): + raise OverlayError("bad rule id %r (letters, digits, - and _)" % rid) + if "{#" in text.split("\n", 1)[0] and r["id"] != rid: + raise OverlayError("the heading says {#%s} but the id is %s" % (r["id"], rid)) + r["id"] = rid + if not r["body"].strip(): + raise OverlayError("the rule has no body") + return r + + +def rule_text(r): + return "## %s\n\n%s\n" % (r["title"], r["body"]) + + +def _read(p): + with open(p, encoding="utf-8") as f: + return f.read() + + +def base_rules(): + try: + return parse_rules(_read(paths.canon("core.md"))) + except OSError as e: + raise OverlayError("cannot read the base rulebook %s: %s" % (paths.canon("core.md"), e)) + + +def _lines(p): + try: + return [l.strip() for l in _read(p).splitlines() if l.strip() and not l.startswith("#")] + except OSError: + return [] + + +def disabled(kind): + return _lines(paths.overlay_dir({"rule": "rules", "verifier": "verifiers", "recipe": "done"}[kind], "disabled.txt")) + + +def overlay_rules(): + d = paths.overlay_dir("rules") + out = {} + try: + names = sorted(os.listdir(d)) + except OSError: + return out + for n in names: + if n.endswith(".md"): + stem = n[:-3] + try: + r = parse_rule_file(_read(os.path.join(d, n)), stem) + except (OverlayError, OSError): + continue # a broken file is ignored here; `overlay list` reports it + out[stem] = r + return out + + +def bases(): + try: + with open(paths.overlay_dir("bases.json"), encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else {} + except (OSError, ValueError): + return {} + + +def effective(): + """(preamble, rules) with the overlay applied. Each rule gets 'origin': base | replaced | added.""" + pre, base = base_rules() + over, off = overlay_rules(), set(disabled("rule")) + out, base_ids = [], {r["id"] for r in base} + for r in base: + if r["id"] in off: + continue + if r["id"] in over: + out.append(dict(over[r["id"]], origin="replaced")) + else: + out.append(dict(r, origin="base")) + order = [i for i in _lines(paths.overlay_dir("rules", "order.txt")) if i in over and i not in base_ids] + rest = sorted(i for i in over if i not in base_ids and i not in order) + for i in dict.fromkeys(order + rest): + if i not in off: + out.append(dict(over[i], origin="added")) + return pre, out + + +def overlay_hash(): + h, any_ = hashlib.sha256(), False + for dp, dns, fns in os.walk(paths.overlay_dir("rules")): + dns.sort() + for n in sorted(fns): + any_ = True + h.update(n.encode() + b"\0") + with open(os.path.join(dp, n), "rb") as f: + h.update(f.read() + b"\0") + return h.hexdigest()[:8] if any_ else "none" + + +def render(): + pre, rules = effective() + try: + base_h = sha(open(paths.canon("core.md"), "rb").read())[:8] + except OSError: + base_h = "missing" + head = "" % (base_h, overlay_hash()) + parts = [head] + if pre.strip(): + parts.append(pre) + for n, r in enumerate(rules, 1): + parts.append("## %d. %s {#%s}\n\n%s" % (n, r["title"], r["id"], r["body"])) + return "\n\n".join(parts) + "\n" + + +def size(text): + return len(text.splitlines()), len(text) + + +def build_canon(strict=False): + """Write the generated rulebook. Idempotent: identical content only refreshes the timestamp. + strict: refuse (raise) when over the size budget, before writing anything.""" + from . import pdata + text = render() + lines, chars = size(text) + over = lines > MAX_LINES + if over and strict: + raise OverlayError("the rulebook would be %d lines; the budget is %d. Shorten or replace another rule first " + "(`sisi canon cost` shows the size)" % (lines, MAX_LINES)) + pdata.ensure() + p = paths.generated() + os.makedirs(os.path.dirname(p), exist_ok=True) + try: + same = _read(p) == text + except OSError: + same = False + if same: + os.utime(p, None) + else: + tmp = p + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + f.write(text) + os.replace(tmp, p) + return {"path": p, "lines": lines, "chars": chars, "over_budget": over, "changed": not same} + + +def is_stale(): + """Is the generated rulebook older than the base rulebook or the overlay's rules? A few stat calls.""" + try: + g = os.stat(paths.generated()).st_mtime_ns + except OSError: + return True + for p in (paths.canon("core.md"), paths.overlay_dir("rules")): + try: + if os.stat(p).st_mtime_ns > g: + return True + except OSError: + pass + return False + + +def cost(): + """Always-loaded size: the generated rulebook and the largest session-start lessons block.""" + from . import retro + try: + lines, chars = size(_read(paths.generated())) + except OSError: + lines = chars = None + return {"rulebook_lines": lines, "rulebook_chars": chars, "rulebook_budget_lines": MAX_LINES, + "lessons_block_max_chars": retro.LIMIT, "lessons_block_max_lines": 1 + 8} + + +def cost_line(c=None): + c = c or cost() + if c["rulebook_lines"] is None: + return "rulebook not generated yet (run `sisi build-canon`); lessons block at most %d characters" % c["lessons_block_max_chars"] + return "rulebook %d lines (budget %d), %d characters; session-start lessons block at most %d characters, %d lines" % ( + c["rulebook_lines"], c["rulebook_budget_lines"], c["rulebook_chars"], c["lessons_block_max_chars"], c["lessons_block_max_lines"]) + + +# ---- library overlay (verifiers, recipes) --------------------------------------- +def lib_dir(kind): + return paths.overlay_dir("verifiers" if kind == "verifier" else "done") + + +def _base_entries(kind): + from . import verifiers as V + return V.load_verifiers(paths.verifiers_dir()) if kind == "verifier" else V.load_recipes(paths.done_dir()) + + +def base_hash(kind, id): + if kind == "rule": + for r in base_rules()[1]: + if r["id"] == id: + return r["hash"] + return None + for e in _base_entries(kind): + if e["id"] == id: + try: + with open(e["path"], "rb") as f: + return sha(f.read()) + except OSError: + return None + return None + + +def _overlay_entry_paths(kind, id): + from . import verifiers as V + return [p for p in V._walk(lib_dir(kind)) if os.path.splitext(os.path.basename(p))[0] == id] + + +# ---- transactions ---------------------------------------------------------- +def _snapshot(d): + snap = {} + for dp, dns, fns in os.walk(d): + for n in fns: + p = os.path.join(dp, n) + with open(p, "rb") as f: + snap[os.path.relpath(p, d)] = f.read() + return snap + + +def _restore(d, snap): + for dp, dns, fns in os.walk(d, topdown=False): + for n in fns: + os.unlink(os.path.join(dp, n)) + for n in dns: + try: + os.rmdir(os.path.join(dp, n)) + except OSError: + pass + for rel, b in snap.items(): + p = os.path.join(d, rel) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(b) + + +@contextlib.contextmanager +def _txn(msg): + """Apply an overlay change: roll the overlay back if it fails the size budget, a lint, or the commit.""" + from . import pdata + pdata.ensure() + d = paths.overlay_dir() + with pdata.lock(): + snap = _snapshot(d) + try: + yield + build_canon(strict=True) + if pdata._commit(msg, ["overlay"]) is None: + raise OverlayError("nothing changed") + except BaseException: + _restore(d, snap) + try: + build_canon() + except Exception: + pass + raise + + +def _write(rel, text): + p = paths.overlay_dir(rel) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "w", encoding="utf-8") as f: + f.write(text) + + +def _remove(p): + try: + os.unlink(p) + except OSError: + pass + + +def _set_lines(rel, ids): + p = paths.overlay_dir(rel) + if ids: + _write(rel, "\n".join(ids) + "\n") + else: + _remove(p) + + +def _set_base(kind, id, h): + b = bases() + key = "%s:%s" % (kind, id) + if h is None: + b.pop(key, None) + else: + b[key] = h + if b: + _write("bases.json", json.dumps(b, indent=1, sort_keys=True) + "\n") + else: + _remove(paths.overlay_dir("bases.json")) + + +def _read_source(arg): + if arg in (None, "-"): + return sys.stdin.read() + try: + return _read(arg) + except OSError as e: + raise OverlayError("cannot read %s: %s" % (arg, e)) + + +# ---- rule commands ---------------------------------------------------------- +def add_rule(text, rid=None): + r = parse_rule_file(text, rid) + if r["id"] in {x["id"] for x in base_rules()[1]}: + raise OverlayError("%r is a base rule id; use replace-rule to change it" % r["id"]) + if r["id"] in overlay_rules(): + raise OverlayError("an added rule %r already exists; use replace-rule to change it" % r["id"]) + with _txn("overlay: add rule %s" % r["id"]): + _write("rules/%s.md" % r["id"], rule_text(r)) + _set_lines("rules/order.txt", _lines(paths.overlay_dir("rules", "order.txt")) + [r["id"]]) + return r["id"] + + +def replace_rule(rid, text): + known = {x["id"] for x in base_rules()[1]} | set(overlay_rules()) + if rid not in known: + raise OverlayError("no rule %r (see `sisi overlay list`, or `sisi canon` for the ids)" % rid) + r = parse_rule_file(text, rid) + with _txn("overlay: replace rule %s" % rid): + _write("rules/%s.md" % rid, rule_text(r)) + _set_base("rule", rid, base_hash("rule", rid)) + return rid + + +def set_disabled(kind, id, off): + if kind == "rule": + known = {x["id"] for x in base_rules()[1]} | set(overlay_rules()) + else: + from . import verifiers as V + known = {e["id"] for e in (V.load_verifiers() if kind == "verifier" else V.load_recipes())} | set(disabled(kind)) + cur = disabled(kind) + if off: + if id not in known: + raise OverlayError("no %s %r" % (kind, id)) + if id in cur: + raise OverlayError("%s %r is already disabled" % (kind, id)) + new = cur + [id] + else: + if id not in cur: + raise OverlayError("%s %r is not disabled" % (kind, id)) + new = [x for x in cur if x != id] + rel = {"rule": "rules", "verifier": "verifiers", "recipe": "done"}[kind] + "/disabled.txt" + with _txn("overlay: %s %s %s" % ("disable" if off else "enable", kind, id)): + _set_lines(rel, new) + return id + + +# ---- verifier and recipe commands ----------------------------------------------- +def _put_entry(kind, text, expect_id, replacing): + from . import verifiers as V + tmp = tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") + try: + tmp.write(text) + tmp.close() + e = V.parse(tmp.name) + finally: + _remove(tmp.name) + h = e["header"] + if not h: + raise OverlayError("the file has no header block (it must start with a --- line; see docs/verifier-format.md)") + id = h.get("id") + if not id or not ID_OK.match(id): + raise OverlayError("the header needs an id: line (letters, digits, - and _)") + if expect_id and id != expect_id: + raise OverlayError("the header id is %r but you asked for %r" % (id, expect_id)) + in_base = any(x["id"] == id for x in _base_entries(kind)) + mine = _overlay_entry_paths(kind, id) + if replacing and not (in_base or mine): + raise OverlayError("no %s %r to replace (see `sisi overlay list`); use add-%s" % (kind, id, kind)) + if not replacing and (in_base or mine): + raise OverlayError("%s %r already exists; use replace-%s to change it" % (kind, id, kind)) + if kind == "verifier": + sec = h.get("section") + if not sec: + raise OverlayError("the header needs a section: line") + rel = "verifiers/%s/%s.md" % (sec, id) + else: + rel = "done/%s.md" % id + return id, rel, mine + + +def _lint_new(rel): + from . import verifiers as V + p = paths.overlay_dir(rel) + bad = [x for x in V.lint() if x.startswith(p + ":")] + if bad: + raise OverlayError("the file does not pass `sisi verifiers lint`:\n " + "\n ".join(b[len(p) + 2:] for b in bad)) + + +def put_entry(kind, text, id=None, replacing=False): + id, rel, mine = _put_entry(kind, text, id, replacing) + with _txn("overlay: %s %s %s" % ("replace" if replacing else "add", kind, id)): + for p in mine: + _remove(p) + _write(rel, text if text.endswith("\n") else text + "\n") + if replacing: + _set_base(kind, id, base_hash(kind, id)) + _lint_new(rel) + return id + + +# ---- listing and diff ----------------------------------------------------------- +def _origin_sets(): + """{kind: {'added': [...], 'replaced': [...], 'disabled': [...]}} for the whole overlay.""" + out = {} + base_rule_ids = {r["id"] for r in base_rules()[1]} + ov = overlay_rules() + out["rule"] = {"replaced": sorted(i for i in ov if i in base_rule_ids), "added": sorted(i for i in ov if i not in base_rule_ids), + "disabled": sorted(disabled("rule"))} + for kind in ("verifier", "recipe"): + from . import verifiers as V + base_ids = {e["id"] for e in _base_entries(kind)} + mine = {os.path.splitext(os.path.basename(p))[0] for p in V._walk(lib_dir(kind))} + out[kind] = {"replaced": sorted(mine & base_ids), "added": sorted(mine - base_ids), "disabled": sorted(disabled(kind))} + return out + + +def retest_queue(): + items = [] + try: + with open(paths.data_file("retest.jsonl"), encoding="utf-8") as f: + for l in f: + try: + items.append(json.loads(l)) + except ValueError: + pass + except OSError: + pass + return items + + +def cmd_list(): + o = _origin_sets() + n = 0 + for kind in KINDS: + for how in ("added", "replaced", "disabled"): + for i in o[kind][how]: + print("%-8s %-9s %s" % (kind, how, i)) + n += 1 + if not n: + print("the overlay is empty: base rules, verifiers and recipes are used as they are") + q = retest_queue() + if q: + print("\n%d replaced item(s) whose base changed in an update are queued for re-testing (retest.jsonl)" % len(q)) + return 0 + + +def _udiff(a, b, na, nb): + import difflib + return "".join(difflib.unified_diff(a.splitlines(True), b.splitlines(True), na, nb)) + + +def cmd_diff(): + o = _origin_sets() + base_rules_ = {r["id"]: r for r in base_rules()[1]} + ov = overlay_rules() + any_ = False + for i in o["rule"]["added"]: + any_ = True + print("+ rule %s (added)\n%s" % (i, rule_text(ov[i]))) + for i in o["rule"]["replaced"]: + any_ = True + print("~ rule %s (replaced)\n%s" % (i, _udiff(rule_text(base_rules_[i]), rule_text(ov[i]), "product", "personal"))) + for i in o["rule"]["disabled"]: + any_ = True + print("- rule %s (disabled)" % i) + for kind in ("verifier", "recipe"): + base = {e["id"]: e for e in _base_entries(kind)} + from . import verifiers as V + for p in V._walk(lib_dir(kind)): + i = os.path.splitext(os.path.basename(p))[0] + any_ = True + if i in base: + print("~ %s %s (replaced)\n%s" % (kind, i, _udiff(_read(base[i]["path"]), _read(p), "product", "personal"))) + else: + print("+ %s %s (added)" % (kind, i)) + for i in o[kind]["disabled"]: + any_ = True + print("- %s %s (disabled)" % (kind, i)) + if not any_: + print("no differences from the product") + return 0 + + +# ---- revert ------------------------------------------------------------------ +def revert(commit): + from . import pdata + pdata.ensure() + with pdata.lock(): + r = pdata.git("rev-parse", "--verify", "-q", commit + "^{commit}", check=False) + if r.returncode != 0: + raise OverlayError("no such commit %r in the personal repository (see `git -C %s log`)" % (commit, paths.data())) + full = r.stdout.strip() + files = [x for x in pdata.git("show", "--name-only", "--format=", full).stdout.split("\n") if x] + if not files or any(not f.startswith("overlay/") for f in files): + raise OverlayError("%s is not an overlay change (it touches %s); only overlay commits can be reverted here" + % (commit, ", ".join(f for f in files if not f.startswith("overlay/")) or "nothing")) + r = pdata.git("revert", "--no-edit", full, check=False) + if r.returncode != 0: + pdata.git("revert", "--abort", check=False) + raise OverlayError("cannot revert %s cleanly (%s); nothing was changed" % (commit, (r.stderr or r.stdout).strip().splitlines()[-1:])) + return build_canon() + + +# ---- update support ------------------------------------------------------------- +def scan_retests(): + """After the product changed: for every replacement whose base item changed, keep the person's version and + queue it for re-testing. Returns the new queue records.""" + from . import pdata + b = bases() + new, changed = [], False + for key in sorted(b): + kind, _, id = key.partition(":") + if kind not in KINDS: + continue + old, cur = b[key], base_hash(kind, id) + if old == cur: + continue + if old is None and cur is None: + continue + new.append({"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "kind": kind, "id": id, + "old_base_hash": old, "new_base_hash": cur, "action": "kept the personal version"}) + b[key] = cur + changed = True + if changed: + with pdata.lock(): + p = paths.data_file("retest.jsonl") + with open(p, "a", encoding="utf-8") as f: + for r in new: + f.write(json.dumps(r, sort_keys=True) + "\n") + _write("bases.json", json.dumps(b, indent=1, sort_keys=True) + "\n") + pdata.commit("update: %d replaced item(s) changed in the product, personal versions kept, queued for retest" % len(new), + ["overlay", "retest.jsonl"]) + return new + + +# ---- command line ---------------------------------------------------------------- +USAGE = """usage: sisi overlay list | diff + sisi overlay add-rule [--id ID] FILE|- replace-rule ID FILE|- disable-rule ID enable-rule ID + sisi overlay add-verifier FILE|- replace-verifier ID FILE|- disable-verifier ID enable-verifier ID + sisi overlay add-recipe FILE|- replace-recipe ID FILE|- disable-recipe ID enable-recipe ID + sisi overlay revert COMMIT +Each change is one commit in the personal data repository; rules are refused if the rulebook would pass %d lines.""" % MAX_LINES + + +def main(args): + args = list(args) + if not args or args[0] in ("-h", "--help", "help"): + print(USAGE) + return 0 if args else 1 + sub = args.pop(0) + try: + if sub == "list": + return cmd_list() + if sub == "diff": + return cmd_diff() + if sub == "revert": + if len(args) != 1: + print(USAGE) + return 1 + r = revert(args[0]) + print("reverted %s; rulebook rebuilt (%d lines)" % (args[0], r["lines"]) + (" - OVER THE %d-LINE BUDGET" % MAX_LINES if r["over_budget"] else "")) + return 0 + m = re.match(r"^(add|replace|disable|enable)-(rule|verifier|recipe)$", sub) + if not m: + print("sisi overlay: unknown subcommand %r\n%s" % (sub, USAGE)) + return 1 + op, kind = m.groups() + if op in ("disable", "enable"): + if len(args) != 1: + print(USAGE) + return 1 + set_disabled(kind, args[0], op == "disable") + print("%sd %s %s" % (op, kind, args[0])) + return 0 + rid = None + if op == "add" and kind == "rule" and "--id" in args: + i = args.index("--id") + rid = args[i + 1] if i + 1 < len(args) else None + del args[i:i + 2] + if op == "replace": + if len(args) != 2: + print(USAGE) + return 1 + rid = args.pop(0) + if len(args) != 1: + print(USAGE) + return 1 + text = _read_source(args[0]) + if kind == "rule": + done = add_rule(text, rid) if op == "add" else replace_rule(rid, text) + else: + done = put_entry(kind, text, rid, replacing=(op == "replace")) + print("%s %s %s (committed to the personal repository)" % ("added" if op == "add" else "replaced", kind, done)) + return 0 + except OverlayError as e: + print("sisi overlay: %s" % e, file=sys.stderr) + return 1 + except Exception as e: + from . import pdata + if isinstance(e, pdata.DataError): + print("sisi overlay: %s" % e, file=sys.stderr) + return 1 + raise diff --git a/sisi/paths.py b/sisi/paths.py new file mode 100644 index 0000000..a2fc553 --- /dev/null +++ b/sisi/paths.py @@ -0,0 +1,143 @@ +"""Path resolution. Everything that touches tool config, personal data or state goes through here. + +Three places, three owners: + product REPO the clone: code, base rulebook, verifier and recipe library. Never written at run time. + personal data() everything sisi learned for this person (its own local git repository). + scratch state() rebuildable or evidential files: harvest.db, locks, logs, session records, results. +""" +import os + +REPO = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + + +def home(): + return os.environ.get("SISI_HOME") or os.path.expanduser("~") + + +def state(): + return os.environ.get("SISI_STATE") or os.path.join(home(), ".local", "state", "sisi") + + +def data(): + """Personal data folder: SISI_DATA, else under SISI_HOME (tests), else $XDG_DATA_HOME/sisi, else ~/.local/share/sisi.""" + d = os.environ.get("SISI_DATA") + if d: + return d + if os.environ.get("SISI_HOME"): + return os.path.join(home(), ".local", "share", "sisi") + x = os.environ.get("XDG_DATA_HOME") + if x and os.path.isabs(x): + return os.path.join(x, "sisi") + return os.path.join(os.path.expanduser("~"), ".local", "share", "sisi") + + +def data_file(*parts): + return os.path.join(data(), *parts) + + +def personal(name): + """A personal file. Until `sisi migrate` has moved it, a copy still sitting in the state dir is used, + so an installation that has not been migrated yet keeps working.""" + p = data_file(name) + if not os.path.exists(p): + old = state_file(name) + if os.path.exists(old): + return old + return p + + +def generated(): + """The effective rulebook (base rules with the personal overlay applied). What the tools load.""" + return data_file("generated", "core.md") + + +def overlay_dir(*parts): + return data_file("overlay", *parts) + + +def canon(*parts): + return os.path.join(REPO, "canon", *parts) + + +def lib(): + """Where stable releases live: SISI_LIB, else /.local/lib/sisi.""" + return os.environ.get("SISI_LIB") or os.path.join(home(), ".local", "lib", "sisi") + + +def releases_dir(): + return os.path.join(lib(), "releases") + + +def current_link(): + return os.path.join(lib(), "current") + + +def stable_launcher(): + """The launcher of the stable copy (through the `current` link), or None when no release has been made.""" + p = os.path.join(current_link(), "bin", "sisi") + return p if os.path.isfile(p) else None + + +def launcher(): + """What the tools are wired to: the stable copy when one exists, else the clone itself.""" + return stable_launcher() or os.path.join(REPO, "bin", "sisi") + + +def product_root(): + """The folder the tools run: the stable copy (through the link) when one exists, else the clone.""" + return current_link() if stable_launcher() else REPO + + +def personal_config(): + import json + try: + with open(personal("config.json"), encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else {} + except (OSError, ValueError): + return {} + + +def set_personal_config(keys, value, msg): + """Set (or with None remove) a nested key in the personal config.json; one commit in the personal repository.""" + import json + from . import pdata + cfg = personal_config() + d = cfg + for k in keys[:-1]: + d = d.setdefault(k, {}) if isinstance(d.get(k, {}), dict) else d.setdefault(k, {}) + if value is None: + d.pop(keys[-1], None) + if not d and len(keys) > 1: + cfg.pop(keys[0], None) + else: + d[keys[-1]] = value + os.makedirs(data(), exist_ok=True) + p = data_file("config.json") + tmp = p + ".sisi-tmp" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(cfg, f, indent=2, sort_keys=True) + f.write("\n") + os.replace(tmp, p) + pdata.commit(msg, ["config.json"]) + + +def state_file(name): + return os.path.join(state(), name) + + +def verifiers_dir(): + return os.environ.get("SISI_VERIFIERS") or os.path.join(REPO, "verifiers") + + +def done_dir(): + return os.environ.get("SISI_DONE") or os.path.join(REPO, "done") + + +def notes_dir(): + return os.environ.get("SISI_NOTES") or data_file("notes") + + +def legacy_notes_dir(): + """Where earlier versions wrote field notes: inside the product. Read only, by `sisi migrate`.""" + return os.path.join(REPO, "notes") diff --git a/sisi/pdata.py b/sisi/pdata.py new file mode 100644 index 0000000..624647f --- /dev/null +++ b/sisi/pdata.py @@ -0,0 +1,187 @@ +"""The personal data folder: a local git repository holding everything sisi learned for this person. + +Layout (see docs/personal-data.md): + VERSION format version of this folder + oracle.md what the person wants + overlay/ learned changes to the base rulebook, verifiers and recipes + notes/ field notes per verifier or recipe id + config.json, trusted.json, lessons.jsonl, retest.jsonl, *.jsonl (notes, proposals, quarantine) + retro.db the lessons database (sqlite; kept out of git, lessons.jsonl is its committed dump) + generated/ the effective rulebook (rebuildable; kept out of git) + install/ manifest and backups of the files `sisi install` edited (machine specific; out of git) + backups/ timestamped copies taken before a migration or an update (out of git) + +Git here is private bookkeeping: author "sisi", no global git config needed, no hooks, never pushed. +""" +import contextlib, os, subprocess, time + +from . import paths + +FORMAT_VERSION = 1 +GITIGNORE = "retro.db\nretro.db-*\ngenerated/\ninstall/\nbackups/\n.lock\n*.tmp*\n" +IDENT = {"GIT_AUTHOR_NAME": "sisi", "GIT_AUTHOR_EMAIL": "sisi@localhost", + "GIT_COMMITTER_NAME": "sisi", "GIT_COMMITTER_EMAIL": "sisi@localhost"} + + +class DataError(Exception): + pass + + +def _env(): + e = dict(os.environ) + e.update(IDENT) + e.update(GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1", GIT_TERMINAL_PROMPT="0") + for k in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"): + e.pop(k, None) + return e + + +def git(*args, check=True): + cmd = ["git", "-c", "core.hooksPath=" + os.devnull, "-c", "commit.gpgsign=false", "-c", "core.autocrlf=false", + "-c", "core.quotepath=off"] + list(args) + p = subprocess.run(cmd, cwd=paths.data(), capture_output=True, text=True, env=_env(), timeout=60) + if check and p.returncode != 0: + raise DataError("git %s failed: %s" % (" ".join(args[:2]), (p.stderr or p.stdout).strip())) + return p + + +@contextlib.contextmanager +def lock(): + """One writer at a time across processes (sessions run concurrently).""" + os.makedirs(paths.data(), exist_ok=True) + f = open(paths.data_file(".lock"), "a") + try: + try: + import fcntl + fcntl.flock(f, fcntl.LOCK_EX) + except ImportError: + pass + yield + finally: + f.close() + + +def exists(): + return os.path.isdir(paths.data_file(".git")) + + +def ensure(): + """Create the folder, its git repository, .gitignore and VERSION if missing. Cheap when everything is there.""" + d = paths.data() + if exists() and os.path.exists(paths.data_file("VERSION")): + return d + with lock(): + fresh = not exists() + if fresh: + git("init", "-q", "-b", "main", "--template=") + if not os.path.exists(paths.data_file(".gitignore")): + write_text(".gitignore", GITIGNORE) + if not os.path.exists(paths.data_file("VERSION")): + write_text("VERSION", "%d\n" % FORMAT_VERSION) + if fresh or git("rev-parse", "--verify", "-q", "HEAD", check=False).returncode != 0: + _commit("sisi: create personal data (format %d)" % FORMAT_VERSION, [".gitignore", "VERSION"]) + return d + + +def write_text(rel, text): + """Atomic write inside the data folder.""" + p = paths.data_file(rel) + os.makedirs(os.path.dirname(p), exist_ok=True) + tmp = p + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + f.write(text) + os.replace(tmp, p) + + +def read_text(rel, default=None): + try: + with open(paths.data_file(rel), encoding="utf-8") as f: + return f.read() + except OSError: + return default + + +def _known(spec): + """Is this path present, or tracked? (git refuses pathspecs that match nothing.)""" + return os.path.lexists(paths.data_file(spec)) or bool(git("ls-files", "--", spec, check=False).stdout.strip()) + + +def _commit(msg, pathspecs): + if pathspecs: + pathspecs = [s for s in pathspecs if _known(s)] + if not pathspecs: + return None + ok = git("add", "-A", "--", *pathspecs, check=False).returncode == 0 + if not ok: # a pathspec that matches nothing makes git add refuse them all: add what exists one by one + for s in pathspecs: + git("add", "-A", "--", s, check=False) + spec = ["--"] + list(pathspecs) + else: + git("add", "-A") + spec = [] + r = git("commit", "-q", "-m", msg, *spec, check=False) + if r.returncode != 0: + if "nothing" in (r.stdout + r.stderr) and "commit" in (r.stdout + r.stderr): + return None # nothing changed + raise DataError("git commit failed: %s" % (r.stderr or r.stdout).strip()) + return "committed" + + +def commit(msg, pathspecs=None, strict=False): + """Commit changes (optionally only under pathspecs) with a clear message. Returns "committed", or None + when nothing changed. A failure is logged and swallowed unless strict: learning must never break a command.""" + try: + ensure() + with lock(): + return _commit(msg, pathspecs) + except Exception as e: + if strict: + raise + from . import store + store.log_error("pdata-commit", e) + return None + + +def version(): + t = read_text("VERSION") + try: + return int((t or "").strip()) + except ValueError: + return 0 + + +# format migrations: {from_version: function(); the function brings the folder to from_version + 1} +MIGRATIONS = {} + + +def upgrade(): + """Bring the personal data format up to date. Returns a list of notes.""" + ensure() + v = version() + if v > FORMAT_VERSION: + raise DataError("personal data is format %d but this sisi understands up to %d; update sisi first" + % (v, FORMAT_VERSION)) + notes = [] + while v < FORMAT_VERSION: + fn = MIGRATIONS.get(v) + if fn is None: + raise DataError("no migration from personal data format %d" % v) + fn() + v += 1 + write_text("VERSION", "%d\n" % v) + commit("format: personal data upgraded to version %d" % v, ["VERSION"] , strict=True) + notes.append("personal data format upgraded to %d" % v) + return notes + + +def backup_dir(reason): + """A fresh timestamped folder under backups/.""" + base = paths.data_file("backups") + os.makedirs(base, exist_ok=True) + stamp = time.strftime("%Y%m%dT%H%M%S", time.gmtime()) + n, d = 0, None + while d is None or os.path.exists(d): + d = os.path.join(base, "%s-%s%s" % (stamp, reason, "-%d" % n if n else "")) + n += 1 + os.makedirs(d) + return d diff --git a/sisi/release.py b/sisi/release.py new file mode 100644 index 0000000..eedbc06 --- /dev/null +++ b/sisi/release.py @@ -0,0 +1,435 @@ +"""Two copies: the source folder (development) and the stable installed copy the tools run. + + /releases// a copy of the product files only + /current symlink to the active release, switched atomically (new symlink, then rename) + + is $SISI_LIB, else /.local/lib/sisi. A process that starts through `current/bin/sisi` resolves the link +once (bin/sisi uses realpath), so it runs one complete release from start to end, even while a release is made. +Release folders are built under a hidden name and renamed into place, so a half-copied release is never visible. +""" +import fcntl, getpass, hashlib, json, os, re, shutil, subprocess, sys, time + +from . import paths + +KEEP = 3 +PRODUCT = ("bin", "sisi", "canon", "verifiers", "done", "docs", "config.default.json", "VERSION") +_SKIP_DIRS = {"__pycache__", ".git"} + + +class ReleaseError(Exception): + pass + + +# ---- the two copies --------------------------------------------------------- +def in_lib(p): + lib = os.path.realpath(paths.lib()) + return os.path.realpath(p).startswith(lib + os.sep) + + +def is_source(d): + return all(os.path.exists(os.path.join(d, p)) for p in ("bin/sisi", "sisi/cli.py", "canon/core.md")) + + +def dev_source(): + s = (paths.personal_config().get("developer") or {}).get("source") + return s if isinstance(s, str) and s else None + + +def source(explicit=None): + """The source folder: the one given, else the folder sisi runs from (unless that is a release), else the + developer setting.""" + if explicit: + s = os.path.abspath(os.path.expanduser(explicit)) + elif not in_lib(paths.REPO): + s = paths.REPO + else: + s = dev_source() + if not s: + raise ReleaseError("no source folder: run this from the source folder, or set it with `sisi dev on PATH`") + if not is_source(s): + raise ReleaseError("%s does not look like the sisi source folder (bin/sisi, sisi/, canon/core.md)" % s) + return s + + +def releases(): + """Release names, oldest first.""" + try: + return sorted(n for n in os.listdir(paths.releases_dir()) + if not n.startswith(".") and os.path.isdir(os.path.join(paths.releases_dir(), n))) + except OSError: + return [] + + +def current_name(): + try: + return os.path.basename(os.readlink(paths.current_link()).rstrip("/")) + except OSError: + return None + + +# ---- trees ------------------------------------------------------------------ +def _files(root): + out = {} + for entry in PRODUCT: + top = os.path.join(root, entry) + if os.path.isfile(top): + out[entry] = top + continue + for dp, dns, fns in os.walk(top): + dns[:] = [d for d in dns if d not in _SKIP_DIRS] + for n in fns: + if not n.endswith(".pyc"): + p = os.path.join(dp, n) + out[os.path.relpath(p, root)] = p + return out + + +def _hash(p): + if os.path.islink(p): + return "link:" + os.readlink(p) + with open(p, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def diff(new_root, old_root): + """(added, changed, removed) product files going from old_root to new_root.""" + n, o = _files(new_root), _files(old_root) if old_root else {} + added = sorted(set(n) - set(o)) + removed = sorted(set(o) - set(n)) + changed = sorted(k for k in set(n) & set(o) if _hash(n[k]) != _hash(o[k])) + return added, changed, removed + + +def describe_diff(d, limit=12): + added, changed, removed = d + lines = ["%d added, %d changed, %d removed" % (len(added), len(changed), len(removed))] + shown = [("+ ", x) for x in added] + [("~ ", x) for x in changed] + [("- ", x) for x in removed] + lines += [" " + a + b for a, b in shown[:limit]] + if len(shown) > limit: + lines.append(" ... and %d more" % (len(shown) - limit)) + return lines + + +# ---- build, switch, prune --------------------------------------------------- +def _lock(): + os.makedirs(paths.lib(), exist_ok=True) + f = open(os.path.join(paths.lib(), ".lock"), "w") + fcntl.flock(f, fcntl.LOCK_EX) + return f + + +def _stamp(): + """A release name that sorts after every existing one (the UTC second, with -02, -03 ... when needed).""" + base = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + newest = max(releases(), default="") + name, i = base, 1 + while name <= newest: + i += 1 + name = "%s-%02d" % (base, i) + return name + + +def make_release(src): + """Copy the product files of src into a new release folder. Returns its name. Visible only when complete.""" + rd = paths.releases_dir() + os.makedirs(rd, exist_ok=True) + name = _stamp() + tmp = os.path.join(rd, ".tmp-" + name) + shutil.rmtree(tmp, ignore_errors=True) + try: + for entry in PRODUCT: + s = os.path.join(src, entry) + if not os.path.lexists(s): + continue + d = os.path.join(tmp, entry) + if os.path.isdir(s) and not os.path.islink(s): + shutil.copytree(s, d, symlinks=True, + ignore=shutil.ignore_patterns("__pycache__", ".git", "*.pyc")) + else: + os.makedirs(os.path.dirname(d), exist_ok=True) + shutil.copy2(s, d, follow_symlinks=False) + os.rename(tmp, os.path.join(rd, name)) + except BaseException: + shutil.rmtree(tmp, ignore_errors=True) + raise + return name + + +def switch(name): + """Point `current` at the release, atomically: write a new symlink beside it, then rename it over the old one.""" + link = paths.current_link() + tmp = "%s.new-%d" % (link, os.getpid()) + try: + os.unlink(tmp) + except OSError: + pass + os.symlink(os.path.join("releases", name), tmp) + try: + os.replace(tmp, link) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def prune(keep=KEEP): + """Delete all but the newest `keep` releases (never the active one). Returns the names removed.""" + names, cur, gone = releases(), current_name(), [] + for n in names[:-keep] if keep else names: + if n != cur: + shutil.rmtree(os.path.join(paths.releases_dir(), n), ignore_errors=True) + gone.append(n) + for n in os.listdir(paths.releases_dir()) if os.path.isdir(paths.releases_dir()) else []: + if n.startswith(".tmp-") and time.time() - os.stat(os.path.join(paths.releases_dir(), n)).st_mtime > 3600: + shutil.rmtree(os.path.join(paths.releases_dir(), n), ignore_errors=True) + return gone + + +def _rebuild_rulebook(): + """Regenerate the rulebook with the code that is now live (not the code that is switching it).""" + launcher = os.path.join(paths.current_link(), "bin", "sisi") + r = subprocess.run([sys.executable, launcher, "build-canon"], capture_output=True, text=True) + return (r.stdout + r.stderr).strip(), r.returncode + + +def run_checks(src, deep=False): + """Run the source's own `sisi verify` (fast; with --all also the slow ones). Returns (ok, output).""" + cmd = [sys.executable, os.path.join(src, "bin", "sisi"), "verify"] + (["--all"] if deep else []) + r = subprocess.run(cmd, cwd=src, capture_output=True, text=True) + return r.returncode == 0, (r.stdout + r.stderr).strip() + + +def cmd_release(args): + deep = "--deep" in args + rest = [a for a in args if a != "--deep"] + try: + src = source(rest[0] if rest else None) + except ReleaseError as e: + print("sisi release: %s" % e, file=sys.stderr) + return 1 + print("checking %s (%s checks)..." % (src, "fast and slow" if deep else "fast")) + ok, out = run_checks(src, deep) + if not ok: + tail = "\n".join(out.splitlines()[-25:]) + print("sisi release: refused, the checks did not pass:\n%s" % tail, file=sys.stderr) + return 1 + with _lock(): + prev = current_name() + old_root = os.path.join(paths.releases_dir(), prev) if prev else None + name = make_release(src) + new_root = os.path.join(paths.releases_dir(), name) + d = diff(new_root, old_root if old_root and os.path.isdir(old_root) else None) + switch(name) + gone = prune() + msg, rc = _rebuild_rulebook() + print("released %s%s" % (name, " (was %s)" % prev if prev else " (first release)")) + for l in describe_diff(d): + print(l) + if gone: + print("removed old releases: " + ", ".join(gone)) + ok = rc == 0 or os.path.isfile(paths.generated()) # over the line budget still writes the file: a warning + print("rulebook: " + (" ".join(msg.split()) if msg else "rebuilt") if ok else "rulebook: NOT rebuilt (%s)" % msg) + from . import wiring + if not wiring.live_wired(): + print("the tools are not wired to the stable copy yet: run `sisi install`") + return 0 if ok else 1 + + +def cmd_rollback(args): + with _lock(): + names, cur = releases(), current_name() + if cur not in names or names.index(cur) == 0: + print("sisi rollback: there is no earlier release to go back to", file=sys.stderr) + return 1 + prev = names[names.index(cur) - 1] + switch(prev) + msg, rc = _rebuild_rulebook() + print("rolled back: %s -> %s" % (cur, prev)) + ok = rc == 0 or os.path.isfile(paths.generated()) + print("rulebook: " + (" ".join(msg.split()) if msg else "rebuilt") if ok else "rulebook: NOT rebuilt (%s)" % msg) + return 0 if ok else 1 + + +# ---- developer mode --------------------------------------------------------- +def cmd_dev(args): + sub = args[0] if args else "status" + if sub == "on": + cand = args[1] if len(args) > 1 else (os.getcwd() if is_source(os.getcwd()) else + (paths.REPO if not in_lib(paths.REPO) else None)) + if not cand: + print("usage: sisi dev on PATH", file=sys.stderr) + return 1 + cand = os.path.abspath(os.path.expanduser(cand)) + if not is_source(cand): + print("sisi dev: %s does not look like the sisi source folder" % cand, file=sys.stderr) + return 1 + paths.set_personal_config(("developer", "source"), cand, "developer mode on: " + cand) + print("developer mode on: source is %s" % cand) + return 0 + if sub == "off": + paths.set_personal_config(("developer", "source"), None, "developer mode off") + print("developer mode off") + return 0 + if sub == "status": + s = dev_source() + print("developer mode: " + ("on, source %s%s" % (s, "" if is_source(s) else " (NOT a sisi source folder)") if s else "off")) + print("live copy: " + live_text()) + return 0 + print("usage: sisi dev on [PATH] | off | status", file=sys.stderr) + return 1 + + +def live_text(): + cur = current_name() + if not cur or not os.path.isdir(paths.current_link()): + return "the clone %s (no release made)" % paths.REPO + s = dev_source() or (paths.REPO if not in_lib(paths.REPO) and is_source(paths.REPO) else None) + txt = "release %s at %s" % (cur, os.path.realpath(paths.current_link())) + if s and is_source(s): + a, c, r = diff(s, paths.current_link()) + n = len(a) + len(c) + len(r) + txt += "; source %s is %s" % (s, "ahead (%d file%s differ)" % (n, "" if n == 1 else "s") if n else "in step") + return txt + + +# ---- promote ---------------------------------------------------------------- +EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+") + + +def _terms(): + """[(text, replacement)] in the order they are scrubbed: longest, most specific first.""" + home = os.path.expanduser("~") + t = [] + for h in {home, paths.home()}: + if h and h != "/": + t.append((h, "~")) + user = os.environ.get("USER") or "" + try: + user = user or getpass.getuser() + except Exception: + pass + if len(user) >= 3: + t.append((user, "")) + cfg = (paths.personal_config().get("developer") or {}).get("personal_terms") or [] + for x in cfg: + if isinstance(x, str) and x.strip(): + t.append((x.strip(), "")) + return sorted(t, key=lambda p: -len(p[0])) + + +def _word(t): + return re.compile(r"(?", text) + left = [] + probes = [re.compile(r"(? [--apply]", file=sys.stderr) + return 1 + pid = rest[0] + try: + src = source() + except ReleaseError as e: + print("sisi promote: %s" % e, file=sys.stderr) + return 1 + item = _find_item(pid) + if not item: + print("sisi promote: no overlay rule, verifier or recipe with id %r in %s" % (pid, paths.overlay_dir()), file=sys.stderr) + return 1 + kind, f, dest = item + with open(f, encoding="utf-8") as fh: + text = fh.read() + clean, found, left = scrub(text) + print("%s %s -> %s" % (kind, pid, os.path.join(src, dest))) + print("scrubbed: " + (", ".join(found) if found else "nothing")) + if left: + print("sisi promote: refused, personal terms remain on these lines:", file=sys.stderr) + for n, l in left: + print(" %d: %s" % (n, l), file=sys.stderr) + return 1 + target = os.path.join(src, dest) + if kind == "rule": + try: + with open(target, encoding="utf-8") as fh: + out = _merge_rule(fh.read(), pid, clean) + except Exception as e: + print("sisi promote: cannot merge the rule: %s" % e, file=sys.stderr) + return 1 + else: + out = clean + if not apply: + print("dry run (nothing written); the file would hold:\n" + "-" * 20) + print(clean.rstrip("\n")) + print("-" * 20 + "\nrun again with --apply to write it") + return 0 + os.makedirs(os.path.dirname(target), exist_ok=True) + tmp = target + ".sisi-tmp" + with open(tmp, "w", encoding="utf-8") as fh: + fh.write(out) + os.replace(tmp, target) + print("written: %s (not committed). After the next release, remove the overlay copy so the two do not diverge:" + " `sisi overlay list`" % target) + return 0 diff --git a/sisi/retro.py b/sisi/retro.py new file mode 100644 index 0000000..46937e9 --- /dev/null +++ b/sisi/retro.py @@ -0,0 +1,619 @@ +"""Retrospectives: every piece of work ends with HOW it could have gone better. Lessons live in retro.db +(its own sqlite file in the personal data folder, out of git; lessons.jsonl is its committed dump), reach later +sessions through tick, and the purely additive kinds (verifier, recipe) are written to notes/.md in the +personal data folder. No model calls.""" +import json, os, re, sqlite3, sys, time + +from . import contract as C, gitutil, paths, store + +AIMS = ["level", "verified", "hands-off", "intent", "speed"] +KINDS = ["rule", "recipe", "verifier", "oracle", "tool", "brief"] +STATUSES = ["open", "applied", "rejected", "superseded"] +AUTO_KINDS = ("verifier", "recipe") +MIN = {"moment": (30, 5), "cause": (15, 3), "change": (25, 4)} # (characters, words) + +NOTHING = re.compile(r"^\W*(nothing|none|nope)\b|^\W*(n/?a|no|not applicable|all good|fine|ok(ay)?)\W*$", re.I) +NOTHING_ANY = re.compile(r"nothing (could|to improve|went wrong|needs)|(could ?n[o']?t|can ?not|couldn't) (have )?(been|done) (any )?better|" + r"no improvements?|everything went (well|fine|smoothly)|went perfectly|no changes? (needed|required)", re.I) +GENERIC = re.compile(r"\b(be more careful|try harder|communicate better|test more|think more|pay more attention|" + r"double[- ]check|be more thorough|plan better|do better|work harder|be careful)\b", re.I) +ANCHOR = re.compile(r"[0-9]|[`\"'“”]|\w[./]\w|[A-Z]{3,}|\b[a-z]+_[a-z_]+\b|\b[a-z]+[A-Z]\w+|\bsisi \w+") + + +# ---- database -------------------------------------------------------------- +def db_path(): + return paths.personal("retro.db") + + +def connect(): + os.makedirs(os.path.dirname(db_path()), exist_ok=True) + con = sqlite3.connect(db_path(), timeout=10) + con.row_factory = sqlite3.Row + # No fsync per write: every change is also dumped to lessons.jsonl in the personal git repository, which is what + # a damaged database is rebuilt from (`sisi lessons import`). Syncing each write cost 10 to 80 ms on this disk. + con.execute("PRAGMA synchronous=OFF") + have = [r[1] for r in con.execute("PRAGMA table_info(occurrences)")] + if have and "delivery_s" not in have: # a database from before delivery times were recorded + con.execute("ALTER TABLE occurrences ADD COLUMN delivery_s REAL") + con.commit() + if con.execute("SELECT 1 FROM sqlite_master WHERE name='occ_lesson'").fetchone(): + return con # schema is there (the last statement below ran): executescript commits and syncs, so skip it + con.executescript(""" + CREATE TABLE IF NOT EXISTS lessons( + id INTEGER PRIMARY KEY, created TEXT, aim TEXT, change_kind TEXT, target TEXT, moment TEXT, cause TEXT, + change TEXT, status TEXT DEFAULT 'open', count INTEGER DEFAULT 1, last_seen TEXT); + CREATE TABLE IF NOT EXISTS occurrences( + id INTEGER PRIMARY KEY, lesson_id INTEGER, ts TEXT, session TEXT, tool TEXT, cwd TEXT, repo TEXT, + moment TEXT, fp TEXT, delivery_s REAL); + CREATE INDEX IF NOT EXISTS occ_repo ON occurrences(repo, ts); + CREATE INDEX IF NOT EXISTS occ_lesson ON occurrences(lesson_id); + """) + return con + + +# ---- the committed dump ------------------------------------------------------ +LESSON_COLS = ("id", "created", "aim", "change_kind", "target", "moment", "cause", "change", "status", "count", "last_seen") +OCC_COLS = ("id", "lesson_id", "ts", "session", "tool", "cwd", "repo", "moment", "fp", "delivery_s") + + +def dump_lines(con): + """The learned content as sorted, stable JSON lines: lessons first, then occurrences.""" + out = [] + for t, cols, table in (("lesson", LESSON_COLS, "lessons"), ("occurrence", OCC_COLS, "occurrences")): + for r in con.execute("SELECT %s FROM %s ORDER BY id" % (",".join(cols), table)): + d = {"t": t} + d.update({c: r[c] for c in cols}) + out.append(json.dumps(d, sort_keys=True, ensure_ascii=False, separators=(",", ":"))) + return out + + +def export_jsonl(path=None): + """Write lessons.jsonl in the personal data folder (only when the content changed). Returns True if rewritten.""" + path = path or paths.data_file("lessons.jsonl") + con = connect() + try: + text = "".join(l + "\n" for l in dump_lines(con)) + finally: + con.close() + try: + with open(path, encoding="utf-8") as f: + if f.read() == text: + return False + except OSError: + pass + os.makedirs(os.path.dirname(path), exist_ok=True) + tmp = path + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + f.write(text) + os.replace(tmp, path) + return True + + +def import_jsonl(path, con): + """Load lessons and occurrences from a dump into con. Rows whose id exists are left alone. Returns (lessons, occurrences) added.""" + n = [0, 0] + with open(path, encoding="utf-8") as f: + for line in f: + try: + d = json.loads(line) + except ValueError: + continue + t = d.pop("t", None) + if t == "lesson": + cols, table, i = LESSON_COLS, "lessons", 0 + elif t == "occurrence": + cols, table, i = OCC_COLS, "occurrences", 1 + else: + continue + cur = con.execute("INSERT OR IGNORE INTO %s(%s) VALUES(%s)" % (table, ",".join(cols), ",".join("?" * len(cols))), + [d.get(c) for c in cols]) + n[i] += cur.rowcount + con.commit() + return tuple(n) + + +def sync(msg): + """Dump the lessons and commit them (with any field notes) to the personal repository. Never raises.""" + try: + if os.path.dirname(db_path()) != paths.data(): + return # not migrated yet: the lessons still live in the state dir + from . import pdata + pdata.ensure() + export_jsonl() + specs = ["lessons.jsonl"] + if paths.notes_dir().startswith(paths.data() + os.sep): + specs.append(os.path.relpath(paths.notes_dir(), paths.data())) + pdata.commit(msg, specs) + except Exception as e: + store.log_error("lessons-sync", e) + + +def repo_of(cwd): + return gitutil.root(cwd) or os.path.abspath(cwd) + + +def current_fp(cwd): + """The fingerprint the gate uses for this tree.""" + if not gitutil.root(cwd): + return None + path = C.find(cwd) + if path: + try: + if C.is_unedited_skeleton(C.load(path)): + path = None + except (OSError, ValueError): + pass + try: + return gitutil.fingerprint(cwd, [path]) + except Exception: + return None + + +def infer_session(cwd): + """(session_id, tool) from env, else from the newest session record for this repo.""" + sid, tool = store.session_id(), store.tool() + if sid: + return sid, tool + d = os.path.join(paths.state(), "sessions") + repo, best = repo_of(cwd), None + try: + names = os.listdir(d) + except OSError: + return None, tool + for n in names: + if not n.endswith(".json") or n.startswith("sub-"): + continue + try: + with open(os.path.join(d, n), encoding="utf-8") as f: + r = json.load(f) + except (OSError, ValueError): + continue + if r.get("cwd") and repo_of(r["cwd"]) == repo and (best is None or r.get("started", "") > best.get("started", "")): + best = r + return (best.get("session_id"), best.get("tool") or tool) if best else (None, tool) + + +# ---- validation ------------------------------------------------------------ +def _words(t): + return re.findall(r"\w+", t) + + +def validate(f, same_as=False): + """Return a list of reasons the answer is refused; empty means acceptable.""" + errs = [] + need = ["moment"] if same_as else ["aim", "moment", "cause", "change_kind", "change"] + for k in need: + if not (f.get(k) or "").strip(): + errs.append("missing %s" % k.replace("_", "-")) + if errs: + return errs + if not same_as: + if f["aim"] not in AIMS: + errs.append("--aim must be one of: " + ", ".join(AIMS) + " (speed means it took longer than it had to)") + if f["change_kind"] not in KINDS: + errs.append("--change-kind must be one of: " + ", ".join(KINDS)) + for k in (["moment"] if same_as else ["moment", "cause", "change"]): + v = f[k].strip() + if NOTHING.match(v) or NOTHING_ANY.search(v): + errs.append("%s says nothing could be better; the question is HOW it could have gone better, not whether" % k) + continue + c, w = MIN[k] + if len(v) < c or len(_words(v)) < w: + errs.append("%s is too short to be specific (at least %d characters and %d words)" % (k, c, w)) + if not errs: + if not ANCHOR.search(f["moment"]): + errs.append("moment names no concrete moment: quote a command, file, number, error or exact phrase from what happened") + for k in (["moment"] if same_as else ["moment", "cause", "change"]): + if GENERIC.search(f[k]) and not ANCHOR.search(f[k]): + errs.append("%s is generic advice; be specific (name the rule, recipe, verifier, fact or tool, and what happened)" % k) + if not same_as: + if " ".join(_words(f["moment"].lower())) == " ".join(_words(f["change"].lower())): + errs.append("moment and change are the same text") + return errs + + +# ---- similarity ------------------------------------------------------------ +STOP = set("the a an and or of to in for is are it that this with on be as by at from my i we do not was were had has " + "have then than but into when what which should would could will can".split()) + + +def _tok(t): + return {w for w in re.findall(r"[a-z0-9_]+", t.lower()) if len(w) > 2 and w not in STOP} + + +def similar(con, f, limit=5): + a = _tok(f["moment"] + " " + f.get("change", "")) + out = [] + for r in con.execute("SELECT * FROM lessons WHERE status IN ('open','applied')"): + b = _tok(r["moment"] + " " + r["change"]) + shared = a & b + if len(shared) < 3: + continue + s = len(shared) / len(a | b) + if f.get("change_kind") and f["change_kind"] == r["change_kind"]: + s += 0.1 + if s >= 0.2: + out.append((s, r)) + out.sort(key=lambda x: -x[0]) + return [r for _, r in out[:limit]] + + +# ---- recording ------------------------------------------------------------- +def _target_valid(kind, target): + if not target or kind not in AUTO_KINDS: + return False + from . import verifiers + ents = verifiers.load_verifiers() if kind == "verifier" else verifiers.load_recipes() + return any(e["id"] == target for e in ents if e["header"]) + + +def request_seconds(sid): + """Seconds from the human's last typed message to now, for this session: the delivery time known when the retro is + recorded. None when the session record has no transcript or the start cannot be found. Never raises.""" + try: + if not sid: + return None + tp = store.load_session(sid).get("transcript_path") + if not isinstance(tp, str): + return None + from . import delivery + t = delivery.find_start(tp) + return round(time.time() - t, 1) if t is not None and time.time() >= t else None + except Exception: + return None + + +def add_occurrence(con, lesson_id, moment, cwd, fp): + sid, tool = infer_session(cwd) + con.execute("INSERT INTO occurrences(lesson_id, ts, session, tool, cwd, repo, moment, fp, delivery_s) VALUES (?,?,?,?,?,?,?,?,?)", + (lesson_id, store.now(), sid, tool, cwd, repo_of(cwd), moment, fp, request_seconds(sid))) + con.execute("UPDATE lessons SET count = count + 1, last_seen = ? WHERE id = ?", (store.now(), lesson_id)) + + +def new_lesson(con, f, cwd, fp): + now = store.now() + cur = con.execute("INSERT INTO lessons(created, aim, change_kind, target, moment, cause, change, status, count, last_seen)" + " VALUES (?,?,?,?,?,?,?, 'open', 0, ?)", + (now, f["aim"], f["change_kind"], f.get("target") or None, f["moment"].strip(), f["cause"].strip(), + f["change"].strip(), now)) + add_occurrence(con, cur.lastrowid, f["moment"].strip(), cwd, fp) + return cur.lastrowid + + +def maybe_auto_apply(con, lesson_id): + """Verifier/recipe lesson with a valid target, 2 occurrences from 2 different sessions: write the field note.""" + r = con.execute("SELECT * FROM lessons WHERE id=?", (lesson_id,)).fetchone() + if not r or r["status"] != "open" or r["change_kind"] not in AUTO_KINDS or not _target_valid(r["change_kind"], r["target"]): + return False + sessions = {x[0] for x in con.execute("SELECT DISTINCT session FROM occurrences WHERE lesson_id=? AND session IS NOT NULL", (lesson_id,))} + if r["count"] >= 2 and len(sessions) >= 2: + apply_lesson(con, lesson_id) + return True + return False + + +def apply_lesson(con, lesson_id): + """Append a dated bullet to notes/.md and mark the lesson applied. Returns the file path.""" + r = con.execute("SELECT * FROM lessons WHERE id=?", (lesson_id,)).fetchone() + if r["change_kind"] not in AUTO_KINDS or not _target_valid(r["change_kind"], r["target"]): + raise ValueError("only verifier or recipe lessons with a valid --target can be applied") + d = paths.notes_dir() + os.makedirs(d, exist_ok=True) + p = os.path.join(d, r["target"] + ".md") + new = not os.path.exists(p) + with open(p, "a", encoding="utf-8") as f: + if new: + f.write("# Field notes for %s\n\n" % r["target"]) + f.write("- %s: %s (aim: %s; seen %d times; lesson %d)\n" % (store.now()[:10], " ".join(r["change"].split()), r["aim"], r["count"], r["id"])) + con.execute("UPDATE lessons SET status='applied' WHERE id=?", (lesson_id,)) + return p + + +def notes_for(id): + p = os.path.join(paths.notes_dir(), os.path.basename(id) + ".md") + try: + with open(p, encoding="utf-8") as f: + lines = [l for l in f.read().splitlines() if l.startswith("- ")] + except OSError: + return "" + return "\n".join(lines) + + +# ---- enforcement helpers --------------------------------------------------- +def satisfied(repo, since, fp): + """Has a retro been recorded for this repo since `since`, for the current tree state (fp)?""" + try: + con = connect() + if fp is not None: + row = con.execute("SELECT 1 FROM occurrences WHERE repo=? AND ts>=? AND fp=? LIMIT 1", (repo, since or "", fp)).fetchone() + else: + row = con.execute("SELECT 1 FROM occurrences WHERE repo=? AND ts>=? LIMIT 1", (repo, since or "")).fetchone() + con.close() + return row is not None + except sqlite3.Error as e: + store.log_error("retro-satisfied", e) + return True # a broken database must not trap anyone + + +TEMPLATE = ('sisi: before you finish, record how this work could have gone better. The question is how, not whether. Run:\n' + ' sisi retro --aim --moment "" ' + '--cause "" --change-kind --change "" [--target ]\n' + '"Nothing" and generic advice are refused. If an earlier lesson already covers it, add --same-as ID instead. (send-back {n})') + + +# ---- tick block ------------------------------------------------------------ +URL = re.compile(r"https?://|ftp://|www\.|\b[\w-]+\.(com|org|net|io|dev|sh)\b", re.I) +SHELL = re.compile(r"`|\$\(|&&|\|\||\s\|\s|;\s*\w|>\s*/|" + r"\b(sudo|curl|wget|chmod|chown|rm|eval|bash|sh)\b\s+\S|" + r"\b(python3?|pip|npm|cargo|git|make|kill)\b\s+[-/.~]|" + r"\b(run|execute|invoke|install|download|paste|pipe)\b", re.I) +PATHTOK = re.compile(r"(?= n: + break + t = safe_line(r["change"], repo) + if not t: + continue + line = "- %s (seen %d)" % (t[:150], r["count"]) + if total + len(line) + 1 > LIMIT: + continue + out.append(line) + total += len(line) + 1 + return (HEADER + "\n" + "\n".join(out)) if out else "" + + +# ---- commands -------------------------------------------------------------- +def _parse(argv): + f, flags, i = {}, set(), 0 + names = {"--aim": "aim", "--moment": "moment", "--cause": "cause", "--change-kind": "change_kind", + "--change": "change", "--target": "target", "--same-as": "same_as"} + while i < len(argv): + a = argv[i] + if a in names: + if i + 1 >= len(argv): + raise ValueError("%s needs a value" % a) + f[names[a]] = argv[i + 1] + i += 2 + elif a == "--json": + if i + 1 < len(argv) and argv[i + 1] == "-": + i += 1 + flags.add("json") + i += 1 + elif a == "--new": + flags.add("new") + i += 1 + else: + raise ValueError("unknown argument %r" % a) + return f, flags + + +def cmd_retro(argv, stdin=None): + try: + f, flags = _parse(argv) + except ValueError as e: + print("sisi retro: %s" % e) + return 2 + if "json" in flags: + try: + d = json.loads((stdin or sys.stdin).read()) + if not isinstance(d, dict): + raise ValueError("JSON must be an object") + except ValueError as e: + print("sisi retro: cannot read JSON from stdin: %s" % e) + return 2 + for k, v in d.items(): + k = k.replace("-", "_") + if k == "new": + if v: + flags.add("new") + elif isinstance(v, (str, int)) and k in ("aim", "moment", "cause", "change_kind", "change", "target", "same_as"): + f.setdefault(k, str(v)) + for k in list(f): + f[k] = f[k].strip() + same = f.get("same_as") + errs = validate(f, bool(same)) + if errs: + print("sisi retro: refused, nothing was recorded:") + for e in errs: + print(" - " + e) + print("Answer how it could have gone better, concretely: see `sisi help` and canon rule 7.") + return 2 + cwd = os.getcwd() + con = connect() + try: + if same: + if not same.isdigit() or not con.execute("SELECT 1 FROM lessons WHERE id=?", (int(same),)).fetchone(): + print("sisi retro: no lesson with id %r (see `sisi lessons`)" % same) + return 2 + lid = int(same) + add_occurrence(con, lid, f["moment"], cwd, None) + con.commit() + applied = maybe_auto_apply(con, lid) + else: + sim = similar(con, f) + if sim and "new" not in flags: + print("sisi retro: similar lessons already exist. Nothing was recorded.") + for r in sim: + print(" #%d [%s/%s] seen %d: %s" % (r["id"], r["aim"], r["change_kind"], r["count"], " ".join(r["change"].split())[:140])) + print("If yours is the same, re-run with --same-as ID (adds an occurrence, keeps one lesson).\n" + "If it is genuinely different, re-run with --new.") + return 4 + lid = new_lesson(con, f, cwd, None) + con.commit() + applied = maybe_auto_apply(con, lid) + con.commit() + fp = current_fp(cwd) # after any field-note write, so the gate sees this retro as for the current tree + con.execute("UPDATE occurrences SET fp=? WHERE id=(SELECT max(id) FROM occurrences WHERE lesson_id=?)", (fp, lid)) + con.commit() + count = con.execute("SELECT count FROM lessons WHERE id=?", (lid,)).fetchone()[0] + finally: + con.close() + sync("lessons: retro recorded for lesson #%d" % lid) + print("recorded: lesson #%d, seen %d time%s%s" % (lid, count, "" if count == 1 else "s", "; applied to notes/" if applied else "")) + return 0 + + +def _lesson_line(r): + return "#%-4d %-9s %-8s %-9s x%-3d %s" % (r["id"], r["status"], r["aim"], r["change_kind"], r["count"], " ".join(r["change"].split())[:100]) + + +def cmd_lessons(argv): + con = connect() + try: + if argv and argv[0] == "show": + if len(argv) < 2 or not argv[1].isdigit(): + print("usage: sisi lessons show ID") + return 2 + r = con.execute("SELECT * FROM lessons WHERE id=?", (int(argv[1]),)).fetchone() + if not r: + print("no lesson %s" % argv[1]) + return 1 + print("lesson #%d %s aim: %s kind: %s target: %s seen %d, last %s" % ( + r["id"], r["status"], r["aim"], r["change_kind"], r["target"] or "-", r["count"], r["last_seen"])) + print("moment: %s\ncause : %s\nchange: %s\n\noccurrences:" % (r["moment"], r["cause"], r["change"])) + for o in con.execute("SELECT * FROM occurrences WHERE lesson_id=? ORDER BY id", (r["id"],)): + print(" %s session %s tool %s repo %s\n %s" % (o["ts"], o["session"] or "?", o["tool"] or "?", o["repo"], o["moment"])) + return 0 + if argv and argv[0] == "set": + if len(argv) < 4 or argv[2] != "--status" or not argv[1].isdigit() or argv[3] not in STATUSES: + print("usage: sisi lessons set ID --status %s" % "|".join(STATUSES)) + return 2 + n = con.execute("UPDATE lessons SET status=? WHERE id=?", (argv[3], int(argv[1]))).rowcount + con.commit() + if n: + sync("lessons: lesson #%s set to %s" % (argv[1], argv[3])) + print("updated" if n else "no lesson %s" % argv[1]) + return 0 if n else 1 + if argv and argv[0] == "export": + changed = export_jsonl(argv[1] if len(argv) > 1 else None) + if len(argv) == 1: + from . import pdata + pdata.commit("lessons: export", ["lessons.jsonl"]) + print("lessons exported to %s%s" % (argv[1] if len(argv) > 1 else paths.data_file("lessons.jsonl"), + "" if changed else " (unchanged)")) + return 0 + if argv and argv[0] == "import": + if len(argv) != 2: + print("usage: sisi lessons import FILE.jsonl") + return 2 + try: + a, b = import_jsonl(argv[1], con) + except OSError as e: + print("sisi lessons: cannot read %s: %s" % (argv[1], e)) + return 1 + sync("lessons: imported %d lesson rows and %d occurrences" % (a, b)) + print("imported %d lesson(s) and %d occurrence(s) (existing ids left alone)" % (a, b)) + return 0 + if argv and argv[0] == "apply": + if len(argv) < 2 or not argv[1].isdigit(): + print("usage: sisi lessons apply ID") + return 2 + r = con.execute("SELECT * FROM lessons WHERE id=?", (int(argv[1]),)).fetchone() + if not r: + print("no lesson %s" % argv[1]) + return 1 + if r["status"] == "applied": + print("already applied") + return 0 + try: + p = apply_lesson(con, r["id"]) + except ValueError as e: + print("sisi lessons: %s" % e) + return 1 + con.commit() + sync("lessons: lesson #%d applied to field notes (%s)" % (r["id"], r["target"])) + print("applied: appended to %s" % p) + return 0 + # list + where, args, top, as_json, i = ["1=1"], [], None, False, 0 + while i < len(argv): + a = argv[i] + if a == "--json": + as_json = True + i += 1 + elif a in ("--aim", "--kind", "--status", "--repo", "--top") and i + 1 < len(argv): + v = argv[i + 1] + if a == "--aim": + where.append("aim=?"); args.append(v) + elif a == "--kind": + where.append("change_kind=?"); args.append(v) + elif a == "--status": + where.append("status=?"); args.append(v) + elif a == "--repo": + where.append("id IN (SELECT lesson_id FROM occurrences WHERE repo=?)"); args.append(repo_of(os.path.abspath(v))) + else: + if not v.isdigit(): + print("--top needs a number") + return 2 + top = int(v) + i += 2 + else: + print("usage: sisi lessons [--aim A] [--kind K] [--status S] [--repo PATH] [--top N] [--json] | show ID | set ID --status S | apply ID | export [FILE] | import FILE") + return 2 + rows = [dict(r) for r in con.execute("SELECT * FROM lessons WHERE %s ORDER BY count DESC, last_seen DESC, id DESC" % " AND ".join(where), args)] + if top: + rows = rows[:top] + if as_json: + print(json.dumps(rows, indent=2)) + elif not rows: + print("no lessons") + else: + for r in rows: + print(_lesson_line(r)) + return 0 + finally: + con.close() + + +def stats(): + """Numbers for `sisi status`.""" + con = connect() + try: + total = con.execute("SELECT count(*) FROM lessons").fetchone()[0] + by = {r[0]: r[1] for r in con.execute("SELECT status, count(*) FROM lessons GROUP BY status")} + week = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 7 * 86400)) + occ = con.execute("SELECT count(*) FROM occurrences WHERE ts>=?", (week,)).fetchone()[0] + top = [dict(r) for r in con.execute("SELECT id, change, count FROM lessons WHERE status='open' ORDER BY count DESC, last_seen DESC LIMIT 5")] + finally: + con.close() + work = done = 0 + d = os.path.join(paths.state(), "sessions") + for n in os.listdir(d) if os.path.isdir(d) else []: + try: + with open(os.path.join(d, n), encoding="utf-8") as f: + r = json.load(f) + except (OSError, ValueError): + continue + if r.get("real_work"): + work += 1 + done += 1 if r.get("retro_done") else 0 + return {"total": total, "open": by.get("open", 0), "applied": by.get("applied", 0), "occ7": occ, "top": top, + "sessions_with_work": work, "sessions_with_retro": done} diff --git a/sisi/scoreboard.py b/sisi/scoreboard.py new file mode 100644 index 0000000..70234fa --- /dev/null +++ b/sisi/scoreboard.py @@ -0,0 +1,100 @@ +"""Check statistics and the scoreboard. + +Check statistics (from results.jsonl): per check id, and per verifier when records carry a `verifier` field: +runs, failures, timeouts. A check with MANY_RUNS or more runs and no failure or timeout is flagged +"never seen failing" (it may be a check that cannot fail). The `gate` pseudo-check is skipped. + +Scoreboard: ISO weeks (Monday start, UTC) and repo, from the harvested main sessions that a human started +(first typed message not machine-written). Trends matter, so every week uses the same definitions: + sessions human-started main sessions whose first message falls in the week + turns_per_session typed user turns per session + corrections_per_100 correction-like typed messages per 100 typed turns (the first message never counts) + questions_per_100 assistant turns that ended on a question with no tool call, plus AskUserQuestion calls, + per 100 typed turns + contract_share share of sessions that used `sisi contract`/`sisi verify` + premature_done_share among sessions with at least one completion claim, the share where a claim was + immediately followed by a correction-like message (a claim can only be "followed" by + a correction if the session went on, so this is not "sessions ending on a claim") +Only weeks and repos with at least one session appear. Completion claims, questions and corrections are +regex heuristics; compare week with week, not with an absolute truth. +""" +import datetime, json, time + +from . import harvest, store, taskset + +MANY_RUNS = 10 + + +def check_stats(results): + by, byv = {}, {} + for r in results: + if not isinstance(r, dict) or not r.get("check") or r.get("check") == "gate": + continue + keys = [("check", r["check"], by)] + if r.get("verifier"): + keys.append(("verifier", r["verifier"], byv)) + for _, k, d in keys: + s = d.setdefault(k, {"runs": 0, "failures": 0, "timeouts": 0, "total_s": 0.0, "timed_runs": 0}) + s["runs"] += 1 + if isinstance(r.get("duration_s"), (int, float)) and not isinstance(r.get("duration_s"), bool): + s["total_s"] += r["duration_s"] # for `sisi time`: which checks cost the most + s["timed_runs"] += 1 + s["tier"] = r.get("tier", "fast") + if r.get("status") == "failed": + s["failures"] += 1 + elif r.get("status") == "timeout": + s["timeouts"] += 1 + def fin(d): + out = [] + for k, s in sorted(d.items()): + s = dict(s, id=k) + s["never_seen_failing"] = s["runs"] >= MANY_RUNS and s["failures"] == 0 and s["timeouts"] == 0 + out.append(s) + return out + return {"checks": fin(by), "verifiers": fin(byv)} + + +def iso_week(t): + d = datetime.datetime.fromtimestamp(t, datetime.timezone.utc).date() + y, w, _ = d.isocalendar() + return "%04d-W%02d" % (y, w) + + +def _blank(): + return {"sessions": 0, "turns": 0, "corrections": 0, "questions": 0, "contract": 0, "claim_sessions": 0, "premature_sessions": 0} + + +def _finish(a): + n, t = a["sessions"], a["turns"] + return {"sessions": n, "turns_per_session": round(t / n, 2) if n else None, + "corrections_per_100": round(100.0 * a["corrections"] / t, 1) if t else None, + "questions_per_100": round(100.0 * a["questions"] / t, 1) if t else None, + "contract_share": round(a["contract"] / n, 3) if n else None, + "premature_done_share": round(a["premature_sessions"] / a["claim_sessions"], 3) if a["claim_sessions"] else None} + + +def _add(a, r): + a["sessions"] += 1 + a["turns"] += r["user_turns"] + a["corrections"] += r["n_corrections"] + a["questions"] += r["n_question_turns"] + r["n_ask"] + a["contract"] += 1 if (r["used_contract"] or r["used_verify"]) else 0 + if r["n_completion_claims"]: + a["claim_sessions"] += 1 + a["premature_sessions"] += 1 if r["n_premature_done"] else 0 + + +def scoreboard(con): + weeks, repos, wr = {}, {}, {} + q = ("SELECT s.t0, s.user_turns, s.n_corrections, s.n_question_turns, s.n_ask, s.used_contract, s.used_verify, " + "s.n_completion_claims, s.n_premature_done, g.repo_root FROM sessions s LEFT JOIN groundtruth g ON g.session_id=s.id " + "WHERE s.kind='main' AND s.machine=0 AND s.t0 IS NOT NULL") + for r in con.execute(q): + repo = (r["repo_root"] or "(no repo)").rstrip("/").rsplit("/", 1)[-1] + week = iso_week(r["t0"]) + for table, key in ((weeks, week), (repos, repo), (wr, (week, repo))): + _add(table.setdefault(key, _blank()), r) + return {"weeks": {k: _finish(v) for k, v in sorted(weeks.items())}, + "repos": {k: _finish(v) for k, v in sorted(repos.items())}, + "week_repo": {"%s %s" % k: _finish(v) for k, v in sorted(wr.items())}, + "tasks": taskset.counts(con)} diff --git a/sisi/store.py b/sisi/store.py new file mode 100644 index 0000000..0ba7b90 --- /dev/null +++ b/sisi/store.py @@ -0,0 +1,152 @@ +"""The shared store: append-only jsonl files, config, session records, error log.""" +import json, os, re, time + +from . import paths + +FILES = {"results": "results.jsonl", "notes": "notes.jsonl", "proposals": "proposals.jsonl", + "quarantine": "learn-quarantine.jsonl", "waivers": "waivers.jsonl", + "deliveries": "deliveries.jsonl"} + + +def now(): + return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + "Z" + + +def tool(): + t = os.environ.get("SISI_TOOL") + if t: + return t + if os.environ.get("CLAUDECODE"): + return "claude-code" + if os.environ.get("OPENCODE"): + return "opencode" + return None + + +def session_id(): + return os.environ.get("SISI_SESSION_ID") or None + + +PERSONAL = ("notes", "proposals", "quarantine") # what the person told or taught sisi: personal data, the rest is scratch + + +def file_path(name): + if name in PERSONAL: + return paths.personal(FILES[name]) + return paths.state_file(FILES.get(name, name)) + + +def read_stdin(wait=None): + """What a hook was sent on stdin. A hook's stdin always ends; if it does not (an inherited pipe nobody closes), + give up after `wait` seconds (SISI_STDIN_WAIT, default 5) rather than hold the session or a test forever.""" + import select, sys + f = sys.stdin + if f is None or f.isatty(): + return "" + try: + fd = f.fileno() + except (AttributeError, ValueError, OSError): + return f.read() # an in-memory stand-in + try: + wait = float(os.environ.get("SISI_STDIN_WAIT", "5")) if wait is None else wait + except ValueError: + wait = 5.0 + end, chunks = time.time() + wait, [] + while True: + left = end - time.time() + if left <= 0 or not select.select([fd], [], [], left)[0]: + break + b = os.read(fd, 65536) + if not b: + break + chunks.append(b) + return b"".join(chunks).decode("utf-8", "replace") + + +def append(name, rec): + path = file_path(name) + os.makedirs(os.path.dirname(path), exist_ok=True) + line = json.dumps(rec, ensure_ascii=False, separators=(",", ":")) + "\n" + fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644) + try: + os.write(fd, line.encode()) # one write call: appends stay whole lines + finally: + os.close(fd) + + +def read(name): + path = file_path(name) + out = [] + try: + with open(path, encoding="utf-8") as f: + for line in f: + try: + out.append(json.loads(line)) + except ValueError: + pass + except OSError: + pass + return out + + +def stamp(extra): + rec = {"ts": now(), "cwd": os.getcwd(), "tool": tool(), "session": session_id()} + rec.update(extra) + return rec + + +DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3, "growth_lines": 40, "growth_files": 3}, + "verify": {"default_timeout_s": 60, "fast_limit_s": 60}, + "retro": {"required": True}} + + +def config(): + """Built-in defaults, then config.default.json in the product, then the person's config.json (personal data).""" + cfg = json.loads(json.dumps(DEFAULTS)) + for p in (os.path.join(paths.REPO, "config.default.json"), paths.personal("config.json")): + try: + with open(p, encoding="utf-8") as f: + over = json.load(f) + except (OSError, ValueError): + continue + for k, v in over.items(): + if isinstance(v, dict) and isinstance(cfg.get(k), dict): + cfg[k].update(v) + else: + cfg[k] = v + if os.environ.get("SISI_RETRO_REQUIRED", "").lower() in ("0", "false", "no"): + cfg.setdefault("retro", {})["required"] = False + return cfg + + +def safe_id(sid): + return re.sub(r"[^A-Za-z0-9_.-]", "_", str(sid))[:128] or "unknown" + + +def session_path(sid): + return os.path.join(paths.state(), "sessions", safe_id(sid) + ".json") + + +def load_session(sid): + try: + with open(session_path(sid), encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else {} + except (OSError, ValueError): + return {} + + +def save_session(sid, rec): + p = session_path(sid) + os.makedirs(os.path.dirname(p), exist_ok=True) + tmp = p + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + json.dump(rec, f) + os.replace(tmp, p) + + +def log_error(where, exc): + try: + append("errors.log", {"ts": now(), "where": where, "error": repr(exc)}) + except Exception: + pass diff --git a/sisi/taskset.py b/sisi/taskset.py new file mode 100644 index 0000000..19fb4a9 --- /dev/null +++ b/sisi/taskset.py @@ -0,0 +1,255 @@ +"""The task set: replayable human requests and brief tasks, graded honestly, split dev/holdout by id hash. + +Kinds + human a genuine (not machine-written) main session in a rebuildable repo with a resolved start commit and at + least one following commit. Grade: + A trusted for replay. Either the start commit is exact (sisi's own record) and no overlapping sibling + session wrote anything, or there is no overlapping sibling at all and a test command exists. Both + also need the session itself to have edited files or committed, so the following commits are + plausibly its own. + B usable with some uncertainty: no overlapping writer sibling, or a test command exists, but the + start commit is only estimated or siblings overlap. + C kept for analysis, not for replay: too many following commits to be one request, a first message too + short to stand alone, a session that made no edits itself, overlapping writers with no test command, or + a repeat of an earlier session's opening message in the same repo (a resume or fork). + Every reason is stored with the task. + brief a subagent transcript: its brief, its parent session and, when a delegation-ledger record can be matched, + the ledger outcome with a match confidence: + high one ledger record and one subagent fit each other uniquely (same project, worker class equals the + subagent model, ledger time within [start, end + 20 min], and minutes consistent when recorded) + medium the same unique pairing but the recorded minutes disagree with the transcript duration + low more than one candidate on either side: the outcome is NOT stored + none no candidate (or the worker is not a Claude subagent): no outcome +Split: sha256(task id) mod 100 < 70 is `dev`, else `holdout`. It depends on the id alone, so it never changes. +""" +import hashlib, json, os, time + +from . import harvest, paths + +DEV_PERCENT = 70 +MATCH_SLACK_S = 1200 +MAX_COMMITS_FOR_ONE_REQUEST = 40 +MIN_REQUEST_CHARS = 15 +WRITE_TOOLS = ("Edit", "Write", "MultiEdit", "NotebookEdit") + + +def split_of(task_id): + h = int(hashlib.sha256(str(task_id).encode()).hexdigest()[:8], 16) + return "dev" if h % 100 < DEV_PERCENT else "holdout" + + +def grade_human(s, g): + """(grade, [reasons]) for a session row `s` and its groundtruth row `g` (dict-likes).""" + reasons = [] + exact = g["start_kind"] == "exact" + has_test = bool(g["test_cmd"]) + tools = json.loads(s["tools"] or "{}") + wrote = bool(s["ran_commit"]) or any(k in tools for k in WRITE_TOOLS) + c = False + reasons.append("start commit exact (sisi tick record)" if exact else "start commit estimated from commit dates") + reasons.append("test command: %s" % g["test_cmd"] if has_test else "no test command detected") + if g["overlap_any"]: + reasons.append("%d overlapping sibling session(s), %d of them wrote" % (g["overlap_any"], g["overlap_writers"])) + else: + reasons.append("no overlapping sibling session") + if g["n_commits"] > MAX_COMMITS_FOR_ONE_REQUEST: + reasons.append("%d following commits: too many to be one request" % g["n_commits"]); c = True + if len((s["first_message"] or "").strip()) < MIN_REQUEST_CHARS: + reasons.append("request too short to stand alone"); c = True + if not wrote: + reasons.append("session itself made no edits or commits"); c = True + if c: + return "C", reasons + if exact and g["overlap_writers"] == 0: + return "A", reasons + if g["overlap_any"] == 0 and has_test: + return "A", reasons + if g["overlap_writers"] == 0 or has_test: + return "B", reasons + reasons.append("overlapping writers and no test command") + return "C", reasons + + +def _project_names(row, repo_root): + names = set() + for p in (row["cwd"], repo_root): + if p: + names.add(os.path.basename(p.rstrip("/")).lower()) + proj = (row["project"] or "").lower() + for marker in ("-code-", "-work-"): + if marker in proj: + names.add(proj.split(marker, 1)[1]) + names.add(proj.rsplit("-", 1)[-1]) + return {n for n in names if n} + + +def ledger_path(): + """An optional JSON-lines ledger of delegated attempts and their judged outcomes. None unless configured: + the SISI_LEDGER environment variable, or "ledger" in the personal config.json.""" + p = os.environ.get("SISI_LEDGER") + if not p: + try: + from . import store + p = store.config().get("ledger") + except Exception: + p = None + return os.path.expanduser(p) if isinstance(p, str) and p else None + + +def read_ledger(home=None): + p = ledger_path() + out = [] + if not p: + return out + try: + with open(p, encoding="utf-8") as f: + for line in f: + try: + d = json.loads(line) + except ValueError: + continue + if isinstance(d, dict) and d.get("kind") == "attempt" and isinstance(d.get("ts"), (int, float)): + out.append(d) + except OSError: + pass + return out + + +def worker_class(worker): + w = (worker or "").lower() + for c in ("haiku", "sonnet", "opus"): + if w == c or w.startswith(c + "-"): + return c + return None + + +def sub_class(models, meta): + found = set() + for m in list(models) + [str((meta or {}).get("model") or "")]: + for c in ("haiku", "sonnet", "opus"): + if c in m.lower(): + found.add(c) + return found + + +def match_ledger(subs, ledger): + """subs: [{id, t0, t1, names, classes}]. Returns {sub_id: (ledger_rec|None, confidence, note)}.""" + cand_of_sub, cand_of_led = {}, {} + for s in subs: + cl = [] + for L in ledger: + wc = worker_class(L.get("worker")) + if not wc or wc not in s["classes"]: + continue + if (str(L.get("project") or "").lower() not in s["names"]) or s["t0"] is None: + continue + if s["t0"] - 120 <= L["ts"] <= (s["t1"] or s["t0"]) + MATCH_SLACK_S: + cl.append(L) + cand_of_sub[s["id"]] = cl + for L in cl: + cand_of_led.setdefault(L["id"], []).append(s["id"]) + out = {} + for s in subs: + cl = cand_of_sub[s["id"]] + if not cl: + out[s["id"]] = (None, "none", "no ledger record with matching project, worker class and time") + elif len(cl) == 1 and len(cand_of_led[cl[0]["id"]]) == 1: + L = cl[0] + dur = ((s["t1"] or s["t0"]) - s["t0"]) / 60.0 + mins = L.get("minutes") + if isinstance(mins, (int, float)) and abs(mins - dur) > max(2.0, 0.5 * max(mins, dur)): + out[s["id"]] = (L, "medium", "unique pairing, but ledger minutes %.1f vs transcript %.1f" % (mins, dur)) + else: + out[s["id"]] = (L, "high", "unique pairing on project, worker class and time") + else: + out[s["id"]] = (None, "low", "%d ledger candidate(s), and a candidate may fit other subagents too" % len(cl)) + return out + + +def build(con, home=None): + """Create or refresh tasks from harvested data. Existing tasks keep their split. Returns counts.""" + now = time.time() + existing = {r["id"]: r["split"] for r in con.execute("SELECT id,split FROM tasks")} + keep = set() + n_human = 0 + q = ("SELECT s.*, g.repo_root, g.start_commit, g.start_kind, g.test_cmd, g.n_commits, g.overlap_any, g.overlap_writers " + "FROM sessions s JOIN groundtruth g ON g.session_id=s.id WHERE s.kind='main' AND s.machine=0 " + "AND g.repo_root IS NOT NULL AND g.start_commit IS NOT NULL AND g.n_commits>0 ORDER BY s.t0") + first_seen = {} + for s in con.execute(q): + tid = "h-" + s["id"][:12] + grade, reasons = grade_human(s, s) + key = (s["repo_root"], (s["first_message"] or "").strip()) + if key in first_seen: # a resumed or forked session repeats the opening message: not a second task + reasons.append("same opening message as earlier session %s in this repo" % first_seen[key][:8]) + grade = "C" + else: + first_seen[key] = s["id"] + keep.add(tid) + _upsert(con, existing, now, id=tid, kind="human", session_id=s["id"], parent_id=None, grade=grade, + reasons=json.dumps(reasons), repo_root=s["repo_root"], start_commit=s["start_commit"], + start_kind=s["start_kind"], test_cmd=s["test_cmd"], request=s["first_message"], ledger_id=None, + ledger_outcome=None, match_confidence=None, match_note=None) + n_human += 1 + ledger = read_ledger(home) + subs, rows = [], {} + repo_of = {r["session_id"]: r["repo_root"] for r in con.execute("SELECT session_id,repo_root FROM groundtruth")} + cwd_of = {r["id"]: dict(r) for r in con.execute("SELECT id,cwd,project FROM sessions WHERE kind='main'")} + for s in con.execute("SELECT * FROM sessions WHERE kind='subagent' AND first_message IS NOT NULL"): + parent = cwd_of.get(s["parent_id"]) or {"cwd": s["cwd"], "project": s["project"]} + names = _project_names(parent, repo_of.get(s["parent_id"])) + names |= _project_names({"cwd": s["cwd"], "project": s["project"]}, None) + subs.append({"id": s["id"], "t0": s["t0"], "t1": s["t1"], "names": names, + "classes": sub_class(json.loads(s["models"] or "{}"), json.loads(s["meta"] or "{}"))}) + rows[s["id"]] = s + matches = match_ledger(subs, ledger) + for sid, s in rows.items(): + L, conf, note = matches[sid] + tid = "b-" + sid + keep.add(tid) + reasons = ["subagent transcript with a brief", "ledger match: %s (%s)" % (conf, note)] + _upsert(con, existing, now, id=tid, kind="brief", session_id=sid, parent_id=s["parent_id"], + grade=None, reasons=json.dumps(reasons), repo_root=None, start_commit=None, start_kind=None, + test_cmd=None, request=s["first_message"], ledger_id=L["id"] if L else None, + ledger_outcome=L.get("outcome") if L else None, match_confidence=conf, match_note=note) + stale = [t for t in existing if t not in keep] + for t in stale: + con.execute("DELETE FROM tasks WHERE id=?", (t,)) + con.commit() + return {"human": n_human, "brief": len(rows), "removed": len(stale), "ledger_records": len(ledger)} + + +def _upsert(con, existing, now, **t): + split = existing.get(t["id"]) or split_of(t["id"]) # an existing task never changes split + cols = ["id", "kind", "session_id", "parent_id", "grade", "reasons", "split", "repo_root", "start_commit", + "start_kind", "test_cmd", "request", "ledger_id", "ledger_outcome", "match_confidence", "match_note", + "updated_at"] + vals = [t[c] if c in t else None for c in cols] + vals[cols.index("split")] = split + vals[cols.index("updated_at")] = now + if t["id"] in existing: + con.execute("UPDATE tasks SET %s WHERE id=?" % ",".join(c + "=?" for c in cols[1:]), vals[1:] + [t["id"]]) + else: + con.execute("INSERT INTO tasks(%s,created_at) VALUES(%s,?)" % (",".join(cols), ",".join("?" * len(cols))), vals + [now]) + + +def list_tasks(con, kind=None, grade=None, split=None): + q, a = "SELECT * FROM tasks WHERE 1=1", [] + for col, v in (("kind", kind), ("grade", grade), ("split", split)): + if v: + q += " AND %s=?" % col + a.append(v) + return [dict(r) for r in con.execute(q + " ORDER BY kind, COALESCE(grade,'~'), id", a)] + + +def get_task(con, tid): + rows = list(con.execute("SELECT * FROM tasks WHERE id=? OR id LIKE ?", (tid, tid + "%"))) + return dict(rows[0]) if len(rows) == 1 else None + + +def counts(con): + """{kind: {grade: {split: n}}} for the scoreboard.""" + out = {} + for r in con.execute("SELECT kind, COALESCE(grade,'-') g, split, COUNT(*) n FROM tasks GROUP BY 1,2,3"): + out.setdefault(r["kind"], {}).setdefault(r["g"], {})[r["split"]] = r["n"] + return out diff --git a/sisi/tick.py b/sisi/tick.py new file mode 100644 index 0000000..890405e --- /dev/null +++ b/sisi/tick.py @@ -0,0 +1,99 @@ +"""Session-start hook. Records the session baseline, checks wiring, prints at most one line. Must be fast.""" +import json, os, sys, time + +from . import store + + +MAX_AGE_S = 30 * 86400 + + +def _prune(now=None): + """Delete per-session state files untouched for 30 days.""" + from . import paths + d = os.path.join(paths.state(), "sessions") + cutoff = (now or time.time()) - MAX_AGE_S + try: + with os.scandir(d) as it: + for e in it: + if e.name.endswith(".json") and e.is_file(follow_symlinks=False) and e.stat().st_mtime < cutoff: + try: + os.unlink(e.path) + except OSError: + pass + except OSError: + pass + + +def _export_session(sid): + """Claude Code lets a SessionStart hook append `export` lines to $CLAUDE_ENV_FILE for later Bash commands, so + `sisi retro`, `note` and `learn` know the session id. (From Claude Code behaviour, not confirmed in the docs I read.)""" + f = os.environ.get("CLAUDE_ENV_FILE") + if f and sid and not str(sid).startswith("cwd-"): + import shlex + try: + with open(f, "a", encoding="utf-8") as fh: + fh.write("export SISI_SESSION_ID=%s\nexport SISI_TOOL=%s\n" % (shlex.quote(str(sid)), shlex.quote(store.tool() or "claude-code"))) + except OSError: + pass + + +def _deep_line(cwd, fp): + """One short line when the project's trusted contract has deep checks that are not fresh-pass-or-running.""" + from . import contract as C, deep, gitutil, trust, verify as V + path = C.find(cwd) + if not path or not trust.is_trusted(C.project_dir(path)): + return "" + c = C.load(path) + if C.validate(c) or not deep.deep_items(c): + return "" + if fp is None: + fp = V.tree_fp(C.project_dir(path), path) + ds = deep.deep_state(c, C.project_dir(path), fp) + if ds and ds["state"] in ("failed", "never-run", "stale-pass"): + return deep.describe(ds) + "; start with `sisi verify --deep --background`" + return "" + + +def main(args=()): + try: + payload = {} + if sys.stdin is not None and not sys.stdin.isatty(): + try: + d = json.loads(store.read_stdin() or "{}") + payload = d if isinstance(d, dict) else {} + except ValueError: + pass + cwd = payload.get("cwd") if isinstance(payload.get("cwd"), str) and os.path.isdir(payload.get("cwd")) else os.getcwd() + sid = payload.get("session_id") or "cwd-%d" % os.getpid() + rec = {} + if payload.get("source", "startup") == "startup" or not store.load_session(sid): + rec = {"session_id": sid, "cwd": cwd, "started": store.now(), "tool": store.tool(), + "source": payload.get("source"), "blocks": 0} + if isinstance(payload.get("transcript_path"), str): + rec["transcript_path"] = payload["transcript_path"] + from . import contract as C, gitutil + if gitutil.root(cwd): + rec["head"] = gitutil.head(cwd) + rec["baseline"] = gitutil.measure(cwd) + rec["baseline_fp"] = gitutil.fingerprint(cwd, [C.find(cwd)]) + store.save_session(sid, rec) + _prune() + from . import wiring + problem = wiring.quick_problem() + line = "%s. Run `sisi doctor`." % problem if problem else "" + deep_line = _deep_line(cwd, rec.get("baseline_fp")) + if deep_line: + line = (line + " | " if line else "") + deep_line + if line: + sys.stdout.write("sisi: %s\n" % line) + _export_session(sid) + try: + from . import retro + block = retro.tick_block(cwd) + if block: + sys.stdout.write(block + "\n") + except Exception as e: + store.log_error("tick-lessons", e) + except Exception as e: + store.log_error("tick", e) + return 0 diff --git a/sisi/trust.py b/sisi/trust.py new file mode 100644 index 0000000..d4217ad --- /dev/null +++ b/sisi/trust.py @@ -0,0 +1,46 @@ +"""Trusted project roots. A contract runs shell commands, so only contracts in trusted roots are executed.""" +import json, os + +from . import paths + + +def _file(): + return paths.personal("trusted.json") + + +def norm(p): + return os.path.realpath(p) + + +def load(): + try: + with open(_file(), encoding="utf-8") as f: + d = json.load(f) + return [x for x in d if isinstance(x, str)] if isinstance(d, list) else [] + except (OSError, ValueError): + return [] + + +def _save(items): + os.makedirs(os.path.dirname(_file()), exist_ok=True) + tmp = _file() + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + json.dump(sorted(set(items)), f, indent=1) + os.replace(tmp, _file()) + + +def is_trusted(project): + return norm(project) in load() + + +def add(project): + _save(load() + [norm(project)]) + + +def remove(project): + _save([x for x in load() if x != norm(project)]) + + +def hint(project): + return "the contract in %s is untrusted (its commands have not been approved on this machine). " \ + "Read .sisi/contract.json, then run `sisi contract trust` in that project to allow it." % project diff --git a/sisi/verifiers.py b/sisi/verifiers.py new file mode 100644 index 0000000..d8f65b4 --- /dev/null +++ b/sisi/verifiers.py @@ -0,0 +1,554 @@ +"""The verifier library and the recipes for "done": parse, list, show, choose, doctor, lint. No model calls.""" +import concurrent.futures as cf, json, os, re, subprocess, sys + +from . import contract as C, paths + +SECTIONS = ["design", "prove", "many-inputs", "concurrency", "test-quality", "regression", "real-world", + "safety", "intent", "completeness"] +COSTS = ["low", "medium", "high"] +V_KEYS = ["id", "title", "answers", "rung", "section", "languages", "kinds", "cost", "detect", "ran_here"] +V_HEADINGS = ["Use when", "Do not use when", "Set up", "Minimal example", "Run", "As a contract check", + "What a pass does not prove"] +D_KEYS = ["id", "title", "applies_to"] +D_HEADINGS = ["Done means", "Checks", "Common false finishes"] +STOP = set("the a an and or of to in for is are it that this with on be as by at from my i we do does not " + "how can what which when should would will".split()) + + +# ---- parsing --------------------------------------------------------------- +def parse(path): + """Return an entry dict. 'problems' lists format errors; 'header' is {} if there is none.""" + e = {"path": path, "stem": os.path.splitext(os.path.basename(path))[0], "header": {}, "body": "", "problems": []} + try: + with open(path, encoding="utf-8") as f: + lines = f.read().split("\n") + except (OSError, UnicodeDecodeError) as ex: + e["problems"].append("cannot read: %s" % ex) + return e + if not lines or lines[0].strip() != "---": + e["body"] = "\n".join(lines) + e["problems"].append("no header block (file must start with a --- line)") + return e + try: + end = next(i for i in range(1, len(lines)) if lines[i].strip() == "---") + except StopIteration: + e["problems"].append("header block is not closed by a --- line") + e["body"] = "\n".join(lines) + return e + for ln in lines[1:end]: + if not ln.strip(): + continue + if ":" not in ln: + e["problems"].append("header line without a colon: %r" % ln) + continue + k, v = ln.split(":", 1) + e["header"][k.strip().lower()] = v.strip() + e["body"] = "\n".join(lines[end + 1:]) + return e + + +def _list(v): + return [x.strip().lower() for x in (v or "").split(",") if x.strip()] + + +def _walk(d): + out = [] + for dp, dns, fns in os.walk(d): + dns.sort() + for n in sorted(fns): + if n.endswith(".md") and n.lower() != "readme.md": + out.append(os.path.join(dp, n)) + return out + + +def _load_verifiers_from(d): + out = [] + for p in _walk(d): + e = parse(p) + h = e["header"] + parent = os.path.basename(os.path.dirname(p)) if os.path.dirname(p) != os.path.normpath(d) else None + e.update(id=h.get("id") or e["stem"], title=h.get("title", ""), answers=h.get("answers", ""), + section=h.get("section") or parent or "", languages=_list(h.get("languages")), + kinds=_list(h.get("kinds")), cost=h.get("cost", ""), detect=h.get("detect", ""), + ran_here=h.get("ran_here", ""), parent=parent) + try: + e["rung"] = int(h.get("rung", "")) + except ValueError: + e["rung"] = 9 + out.append(e) + return out + + +def _load_recipes_from(d): + out = [] + for p in _walk(d): + e = parse(p) + h = e["header"] + e.update(id=h.get("id") or e["stem"], title=h.get("title", ""), applies_to=h.get("applies_to", "")) + out.append(e) + return out + + +def _merge(base, mine, off): + """The product's entries with the personal overlay applied: same id replaces (in place), new ids are added, + disabled ids are dropped. Entries carry 'origin': product | personal-replaces | personal-added.""" + over = {e["id"]: e for e in mine} + out = [] + for e in base: + if e["id"] in off: + continue + if e["id"] in over: + out.append(dict(over.pop(e["id"]), origin="personal-replaces")) + else: + out.append(dict(e, origin="product")) + for e in mine: + if e["id"] in over and e["id"] not in off: + out.append(dict(over[e["id"]], origin="personal-added")) + return out + + +def load_verifiers(d=None): + """With no argument: the product library with the personal overlay applied. With a directory: just that directory.""" + if d is not None: + return _load_verifiers_from(d) + from . import overlay + return _merge(_load_verifiers_from(paths.verifiers_dir()), _load_verifiers_from(overlay.lib_dir("verifier")), + set(overlay.disabled("verifier"))) + + +def load_recipes(d=None): + if d is not None: + return _load_recipes_from(d) + from . import overlay + return _merge(_load_recipes_from(paths.done_dir()), _load_recipes_from(overlay.lib_dir("recipe")), + set(overlay.disabled("recipe"))) + + +def origin_tag(e): + return {"personal-added": " [personal addition]", "personal-replaces": " [personal, replaces the product's]"}.get(e.get("origin"), "") + + +def usable(entries): + """Entries that have a header (a file without one cannot be listed meaningfully; lint reports it).""" + return [e for e in entries if e["header"]] + + +# ---- detection ------------------------------------------------------------- +def _detect_one(cmd, timeout): + try: + return subprocess.run(cmd, shell=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, timeout=timeout).returncode == 0 + except Exception: + return False + + +def _per(): + try: + return float(os.environ.get("SISI_DETECT_TIMEOUT", "3")) + except ValueError: + return 3.0 + + +def installed_map(entries, per=None, cap=15): + """{id: 'yes'|'no'|'n/a'}. Detects run concurrently under a total time cap; unfinished counts as 'no'.""" + per = per or _per() + res = {} + todo = {} + for e in entries: + if e["detect"]: + todo[e["path"]] = e + else: + res[e["path"]] = "n/a" + if todo: + ex = cf.ThreadPoolExecutor(max_workers=min(16, len(todo))) + futs = {ex.submit(_detect_one, e["detect"], per): k for k, e in todo.items()} + done, _ = cf.wait(futs, timeout=cap) + for f, k in futs.items(): + res[k] = "yes" if f in done and f.result() else "no" + ex.shutdown(wait=False, cancel_futures=True) + return res + + +# ---- options --------------------------------------------------------------- +def parse_args(args): + opts, pos, i = {}, [], 0 + while i < len(args): + a = args[i] + if a in ("--lang", "--kind", "--rung", "--section"): + if i + 1 >= len(args): + raise ValueError("%s needs a value" % a) + opts[a[2:]] = args[i + 1] + i += 2 + elif a in ("--installed", "--json"): + opts[a[2:]] = True + i += 1 + else: + pos.append(a) + i += 1 + if "rung" in opts: + try: + opts["rung"] = int(opts["rung"]) + except ValueError: + raise ValueError("--rung needs a number 1-6") + return opts, pos + + +def _words(text): + return [w for w in re.findall(r"[a-z0-9+#.\-]+", text.lower()) if len(w) > 1 and w not in STOP] + + +def _passes(e, o): + if "lang" in o: + ls = e["languages"] + if "any" not in ls and o["lang"].lower() not in ls: + return False + if "kind" in o and "any" not in e["kinds"] and o["kind"].lower() not in e["kinds"]: + return False + if "rung" in o and e["rung"] > o["rung"]: + return False + if "section" in o and e["section"] != o["section"]: + return False + return True + + +def _public(e, inst=None): + d = {"id": e["id"], "title": e["title"], "answers": e["answers"], "rung": e["rung"], "section": e["section"], + "languages": e["languages"], "kinds": e["kinds"], "cost": e["cost"], "detect": e["detect"], + "ran_here": e["ran_here"], "path": e["path"], "origin": e.get("origin", "product")} + if inst is not None: + d["installed"] = inst + return d + + +def _line(e): + return "%-24s r%-2s %-6s %-22s %s%s" % (e["id"], e["rung"], e["cost"] or "-", ", ".join(e["languages"])[:22] or "-", e["title"], + origin_tag(e)) + + +# ---- commands -------------------------------------------------------------- +def cmd_list(args): + opts, words = parse_args(args) + words = [w.lower() for w in words] + es = [] + for e in usable(load_verifiers()): + hay = " ".join([e["id"], e["title"], e["answers"], e["body"]]).lower() + if _passes(e, opts) and all(w in hay for w in words): + es.append(e) + inst = installed_map(es) if ("installed" in opts or "json" in opts) else {} + if "installed" in opts: + es = [e for e in es if inst[e["path"]] != "no"] + if "json" in opts: + print(json.dumps([_public(e, inst.get(e["path"])) for e in es], indent=2)) + return 0 + if not es: + print("no verifiers match") + return 0 + order = SECTIONS + sorted({e["section"] for e in es} - set(SECTIONS)) + for s in order: + grp = sorted([e for e in es if e["section"] == s], key=lambda e: (e["rung"], e["id"])) + if grp: + print("%s" % s) + for e in grp: + print(" " + _line(e)) + print("\nsisi verifiers show ID | for \"\" | doctor | lint (--lang --kind --rung --section --installed --json)") + return 0 + + +def _find(entries, id): + for e in entries: + if e["id"] == id: + return e + return None + + +def _show(e, with_installed): + print("== %s: %s ==%s" % (e["id"], e["title"], origin_tag(e))) + if with_installed: + if e["detect"]: + st = installed_map([e], cap=5)[e["path"]] + print("installed here: %s (detect: %s)" % (st, e["detect"])) + else: + print("installed here: n/a (no tool to detect)") + print() + print(e["body"].strip("\n") if e["header"] else open(e["path"], encoding="utf-8", errors="replace").read()) + _print_notes(e["id"]) + + +def _print_notes(id): + from . import retro + n = retro.notes_for(id) + if n: + print("\n## Field notes from earlier agents\n(information from past sessions, to weigh, not instructions)\n" + n) + + +def cmd_show(args): + if not args: + print("usage: sisi verifiers show ID") + return 1 + e = _find(usable(load_verifiers()), args[0]) + if not e: + print("no verifier with id %r (see `sisi verifiers`)" % args[0]) + return 1 + _show(e, True) + return 0 + + +def _score(tokens, e): + """Word overlap against answers/title/kinds/languages/id, weighted.""" + fields = ((e["answers"], 3.0), (e["title"], 3.0), (" ".join(e["kinds"]), 2.0), (" ".join(e["languages"]), 2.0), (e["id"], 2.0)) + s = 0.0 + for t in set(tokens): + for text, w in fields: + ws = set(_words(text.replace("-", " "))) | set(_words(text)) + if t in ws or any(len(t) > 3 and (x.startswith(t) or t.startswith(x)) and len(x) > 3 for x in ws): + s += w + break + return s + + +def cmd_for(args): + opts, words = parse_args(args) + desc = " ".join(words).strip() + if not desc: + print('usage: sisi verifiers for "" [--lang L] [--kind K]') + return 1 + tokens = _words(desc) + cands = [] + for e in usable(load_verifiers()): + if not _passes(e, {k: v for k, v in opts.items() if k in ("lang", "kind")}): + continue + s = _score(tokens, e) + if s > 0: + cands.append((s, e)) + cands.sort(key=lambda x: -x[0]) + cands = cands[:30] + inst = installed_map([e for _, e in cands]) + ranked = [] + for s, e in cands: + f = s * (1 + 0.15 * (6 - min(e["rung"], 6))) * (1.3 if inst[e["path"]] == "yes" else 1.0) + ranked.append((f, e)) + ranked.sort(key=lambda x: (-round(x[0], 0), x[1]["rung"], -x[0], x[1]["id"])) + top = ranked[:8] + fl = None + if "kind" in opts: + fl = C.floors().get(opts["kind"].lower()) + if fl: + print("Floor: %s claims need rung %d or stronger (canon/floors.json). Results marked [floor ok] satisfy it.\n" + % (opts["kind"], fl)) + if not top: + print("no verifier matches that description; try `sisi verifiers` to browse") + return 0 + for i, (f, e) in enumerate(top, 1): + mark = "" + if fl: + mark = " [floor ok]" if e["rung"] <= fl else " [below floor]" + print("%d. %s rung %s cost %s installed: %s%s%s" % (i, e["id"], e["rung"], e["cost"] or "-", inst[e["path"]], mark, origin_tag(e))) + print(" %s" % (e["answers"] or e["title"])) + print("\nsisi verifiers show ID for set-up and a worked example") + return 0 + + +def cmd_doctor(args): + es = [e for e in usable(load_verifiers()) if e["detect"]] + if not es: + print("no verifiers with a detect command") + return 0 + inst = installed_map(es, cap=15) + order = SECTIONS + sorted({e["section"] for e in es} - set(SECTIONS)) + tot_yes = 0 + for s in order: + grp = [e for e in es if e["section"] == s] + if not grp: + continue + y = sum(1 for e in grp if inst[e["path"]] == "yes") + tot_yes += y + print("%s: %d of %d installed" % (s, y, len(grp))) + for e in sorted(grp, key=lambda e: e["id"]): + print(" %-24s %s" % (e["id"], "installed" if inst[e["path"]] == "yes" else "missing")) + print("\ntotal: %d of %d installed" % (tot_yes, len(es))) + return 0 + + +def _headings(body): + return [re.sub(r"^#+\s*", "", l).strip().lower() for l in body.split("\n") if re.match(r"^#+\s+\S", l)] + + +def _missing_headings(body, required): + hs = _headings(body) + return [r for r in required if not any(r.lower() in h for h in hs)] + + +def _section(body, name): + """Text under the first heading containing `name`, up to the next heading of the same or higher level.""" + lines, out, level = body.split("\n"), [], None + for l in lines: + m = re.match(r"^(#+)\s+(.*)", l) + if level is None: + if m and name.lower() in m.group(2).lower(): + level = len(m.group(1)) + elif m and len(m.group(1)) <= level: + break + elif level is not None: + out.append(l) + return "\n".join(out) + + +ID_RE = re.compile(r"[a-z0-9][a-z0-9-]*") + + +def cited_ids(recipe): + """Verifier ids a recipe cites: backticked single tokens in its Checks section (commands contain spaces or + punctuation and are ignored).""" + return [x for x in re.findall(r"`([^`\n]+)`", _section(recipe["body"], "Checks")) if ID_RE.fullmatch(x)] + + +def untiered_long_checks(): + """Entries whose 'As a contract check' example has timeout_s over 60 but no "tier": "deep".""" + bad = [] + for e in load_verifiers(): + sec = _section(e["body"], "As a contract check") + ts = [float(x) for x in re.findall(r'"timeout_s"\s*:\s*(\d+(?:\.\d+)?)', sec)] + if ts and max(ts) > 60 and not re.search(r'"tier"\s*:\s*"deep"', sec): + bad.append(e) + return bad + + +def lint_warnings(): + out = [] + for e in untiered_long_checks(): + out.append('%s: contract-check example has timeout_s over 60 but no "tier": "deep"' % e["path"]) + for e in load_verifiers() + load_recipes(): + try: + with open(e["path"], encoding="utf-8") as f: + n = len(f.read().rstrip("\n").split("\n")) + except OSError: + continue + if n > 80 or n < 30: + out.append("%s: %d lines (aim for 30-80)" % (e["path"], n)) + if e["header"].get("verified") == "memory": + out.append("%s: verified: memory (written from memory, not checked against the tool or its docs)" % e["path"]) + return out + + +def lint(): + """Return a list of 'path: problem' strings.""" + out = [] + vs, rs = load_verifiers(), load_recipes() + from . import overlay + known = {e["header"].get("id") or e["stem"] for e in vs} | set(overlay.disabled("verifier")) # switched off is not unknown + for r in rs: + for i in dict.fromkeys(cited_ids(r)): + if i not in known: + out.append("%s: Checks cites unknown verifier id %r" % (r["path"], i)) + for e in vs + rs: + for p in e["problems"]: + out.append("%s: %s" % (e["path"], p)) + for kind, entries, keys, heads in (("verifier", vs, V_KEYS, V_HEADINGS), ("recipe", rs, D_KEYS, D_HEADINGS)): + seen = {} + for e in entries: + if not e["header"]: + continue + h, p = e["header"], e["path"] + for k in keys: + if k not in h or (not h[k] and k not in ("detect",)): + out.append("%s: missing or empty %r" % (p, k)) + if h.get("id") and h["id"] != e["stem"]: + out.append("%s: id %r must equal the file name %r" % (p, h["id"], e["stem"])) + if h.get("id"): + if h["id"] in seen: + out.append("%s: duplicate id %r (also %s)" % (p, h["id"], seen[h["id"]])) + seen[h["id"]] = p + for m in _missing_headings(e["body"], heads): + out.append("%s: body lacks the heading %r" % (p, m)) + if kind == "verifier": + if not re.fullmatch(r"[1-6]", h.get("rung", "")): + out.append("%s: rung must be an integer 1-6" % p) + if h.get("section") and h["section"] not in SECTIONS: + out.append("%s: unknown section %r" % (p, h["section"])) + if e["parent"] and h.get("section") and e["parent"] != h["section"]: + out.append("%s: section %r does not match its directory %r" % (p, h["section"], e["parent"])) + if h.get("cost") and h["cost"] not in COSTS: + out.append("%s: cost must be one of %s" % (p, ", ".join(COSTS))) + if h.get("ran_here") and h["ran_here"] not in ("yes", "no"): + out.append("%s: ran_here must be yes or no" % p) + for k in _list(h.get("kinds")): + if k != "any" and k not in C.KINDS: + out.append("%s: unknown kind %r (one of %s, or any)" % (p, k, ", ".join(C.KINDS))) + return out + + +def cmd_lint(args): + probs = lint() + warns = lint_warnings() + for w in warns: + print("warning: " + w) + if probs: + for p in probs: + print(p) + print("\n%d problem(s)" % len(probs)) + return 1 + print("lint ok: %d verifiers, %d recipes%s" % (len(load_verifiers()), len(load_recipes()), + ", %d warning(s)" % len(warns) if warns else "")) + return 0 + + +def main(args): + try: + if args and args[0] == "show": + return cmd_show(args[1:]) + if args and args[0] == "for": + return cmd_for(args[1:]) + if args and args[0] == "doctor": + return cmd_doctor(args[1:]) + if args and args[0] == "lint": + return cmd_lint(args[1:]) + return cmd_list(args) + except ValueError as e: + print("sisi: %s" % e) + return 1 + + +# ---- done recipes ---------------------------------------------------------- +def done_main(args): + rs = usable(load_recipes()) + if args and args[0] == "for": + desc = " ".join(args[1:]).strip() + if not desc: + print('usage: sisi done for ""') + return 1 + toks = set(_words(desc)) + scored = [] + for r in rs: + s = 0.0 + for text, w in ((r["title"], 3.0), (r["applies_to"], 3.0), (r["id"].replace("-", " "), 3.0), (r["body"], 0.2)): + ws = set(_words(text.replace("-", " "))) + s += w * sum(1 for t in toks if t in ws or any(len(t) > 3 and len(x) > 3 and (x.startswith(t) or t.startswith(x)) for x in ws)) + if s > 0: + scored.append((s, r)) + scored.sort(key=lambda x: (-x[0], x[1]["id"])) + if not scored: + print("no recipe matches that description; `sisi done` lists them") + return 0 + best = scored[0][1] + print("Best match: %s\n" % best["id"]) + print("== %s: %s ==%s\napplies to: %s\n" % (best["id"], best["title"], origin_tag(best), best["applies_to"])) + print(best["body"].strip("\n")) + if len(scored) > 1: + print("\nOther candidates: " + ", ".join(r["id"] for _, r in scored[1:4])) + return 0 + if args: + r = next((x for x in rs if x["id"] == args[0]), None) + if not r: + print("no recipe with id %r (see `sisi done`)" % args[0]) + return 1 + print("== %s: %s ==%s\napplies to: %s\n" % (r["id"], r["title"], origin_tag(r), r["applies_to"])) + print(r["body"].strip("\n")) + _print_notes(r["id"]) + return 0 + if not rs: + print("no recipes") + return 0 + for r in sorted(rs, key=lambda r: r["id"]): + print("%-24s %s (%s)%s" % (r["id"], r["title"], r["applies_to"], origin_tag(r))) + print("\nsisi done ID | for \"\"") + return 0 diff --git a/sisi/verify.py b/sisi/verify.py new file mode 100644 index 0000000..df6e740 --- /dev/null +++ b/sisi/verify.py @@ -0,0 +1,216 @@ +"""Run a contract: every check and invariant with a cmd, in the project dir, with a timeout.""" +import json, os, signal, subprocess, time + +from . import contract as C, store + +TAIL = 1500 + + +def _tail(s): + s = s.strip() + return s[-TAIL:] if len(s) > TAIL else s + + +def run_cmd(cmd, cwd, timeout, expect): + """Return (status, duration, tail). status: passed/failed/timeout.""" + t0 = time.time() + if timeout <= 0: + return "timeout", 0.0, "not run: time budget exhausted" + try: + p = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + stdin=subprocess.DEVNULL, start_new_session=True) + except OSError as e: + return "failed", 0.0, "could not start: %s" % e + try: + out, err = p.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + try: + os.killpg(p.pid, signal.SIGKILL) + except OSError: + pass + try: + p.communicate(timeout=5) + except Exception: + pass + return "timeout", time.time() - t0, "timed out after %gs" % timeout + dur = time.time() - t0 + o, e = out.decode("utf-8", "replace"), err.decode("utf-8", "replace") + tail = _tail(o + ("\n" if o and e else "") + e) + want = expect.get("exit", 0) + if p.returncode != want: + return "failed", dur, "exit %d, expected %d\n%s" % (p.returncode, want, tail) + sc = expect.get("stdout_contains") + if sc is not None and sc not in o: + return "failed", dur, "stdout does not contain %r\n%s" % (sc, tail) + return "passed", dur, tail + + +def tree_fp(project, contract_path): + """The working-tree fingerprint shared by verify, deep runs and the gate.""" + from . import gitutil + try: + return gitutil.fingerprint(project, [contract_path]) + except Exception: + return None + + +MAX_PARALLEL = 4 + + +def _run_item(item, x, tier, project, deadline, default_timeout): + r = {"item": item, "id": x["id"], "kind": x.get("kind"), "rung": x.get("rung"), "claim": x.get("claim"), + "tier": tier} + if x.get("rung") in (5, 6): + r.update(status="awaiting-human", duration_s=0.0, tail="") + else: + to = float(x.get("timeout_s", default_timeout)) + if deadline is not None: + to = min(to, deadline - time.time()) + st, dur, tail = run_cmd(x["cmd"], project, to, x.get("expect", {"exit": 0})) + r.update(status=st, duration_s=round(dur, 3), tail=tail) + return r + + +def run(c, project, deadline=None, default_timeout=60, tiers=("fast",)): + """Run the items of the given tiers. Returns list of result dicts (with 'tail'), in contract order. + deadline is a time.time() value. With top-level "parallel": true in the contract, fast-tier items run together + (at most MAX_PARALLEL at a time), except items marked "serial": true, which run alone afterwards.""" + items = [("check", x) for x in c["checks"]] + [("invariant", x) for x in c.get("invariants", [])] + items = [(item, x, x.get("tier", "fast")) for item, x in items if x.get("tier", "fast") in tiers] + res = [None] * len(items) + par = [i for i, (_, x, tier) in enumerate(items) if c.get("parallel") is True and tier == "fast" and not x.get("serial")] + if len(par) > 1: + from concurrent.futures import ThreadPoolExecutor + with ThreadPoolExecutor(max_workers=MAX_PARALLEL) as ex: + futs = {i: ex.submit(_run_item, items[i][0], items[i][1], items[i][2], project, deadline, default_timeout) + for i in par} + for i, f in futs.items(): + res[i] = f.result() + for i, (item, x, tier) in enumerate(items): + if res[i] is None: + res[i] = _run_item(item, x, tier, project, deadline, default_timeout) + for f in (C.floor_failures(c) if "fast" in tiers else []): + res.append({"item": "floor", "tier": "fast", "id": "floor:" + f["kind"], "kind": f["kind"], "rung": None, + "claim": f["message"], "status": "failed", "duration_s": 0.0, "tail": f["message"]}) + return res + + +def ok(results): + return all(r["status"] in ("passed", "awaiting-human") for r in results) + + +def record(c, project, results, fp=None): + run_id = "%x-%d" % (time.time_ns(), os.getpid()) + for r in results: + store.append("results", {"ts": store.now(), "contract": c["id"], "project": project, + "check": r["id"], "item": r["item"], "kind": r["kind"], "rung": r["rung"], + "status": r["status"], "duration_s": r["duration_s"], + "tool": store.tool(), "session": store.session_id(), "run": run_id, + "tier": r.get("tier", "fast"), "fp": fp}) + + +def format_table(results): + rows = [("ID", "KIND", "RUNG", "TIER", "STATUS", "SECS")] + for r in results: + rows.append((r["id"], r["kind"] or "-", str(r["rung"] or "-"), r.get("tier", "fast"), r["status"], "%.1f" % r["duration_s"])) + w = [max(len(row[i]) for row in rows) for i in range(6)] + return "\n".join(" ".join(v.ljust(w[i]) for i, v in enumerate(row)).rstrip() for row in rows) + + +def failure_report(results, limit=4000): + parts = [] + for r in results: + if r["status"] in ("failed", "timeout"): + parts.append("- %s %s [%s]: %s\n%s" % (r["item"], r["id"], r["status"], r.get("claim") or "", + "\n".join(" " + l for l in (r["tail"] or "").splitlines()[-15:]))) + s = "\n".join(parts) + return s if len(s) <= limit else s[:limit] + "\n... (truncated)" + + +def cmd_verify(args, cwd=None, out=print): + from . import deep, trust + cwd = cwd or os.getcwd() + path = C.find(cwd) + if not path: + out("sisi: no contract found (run `sisi contract init`)") + return 2 + try: + c = C.load(path) + except (OSError, ValueError) as e: + out("sisi: cannot read %s: %s" % (path, e)) + return 1 + project = C.project_dir(path) + if not trust.is_trusted(project): + out("sisi: refusing to run: " + trust.hint(project)) + return 3 + errs = C.validate(c) + if errs: + out("sisi: invalid contract %s" % path) + for e in errs: + out(" - " + e) + return 1 + fp = tree_fp(project, path) + as_json = "--json" in args + if "--deep" in args and "--all" in args: + out("sisi: use either --deep or --all") + return 1 + if "--state" in args: + ds = deep.deep_state(c, project, fp) + if as_json: + out(json.dumps(deep.public(ds), indent=2)) + else: + out(deep.describe(ds) or "deep checks: none in this contract") + return 0 + tiers = ("deep",) if "--deep" in args else ("fast", "deep") if "--all" in args else ("fast",) + if "--background" in args: + if "--deep" not in args: + out("sisi: --background needs --deep") + return 1 + if not deep.deep_items(c): + out("sisi: this contract has no deep items") + return 0 + started, info = deep.start_background(project, fp) + if started: + out("deep run started in the background; log: %s" % info) + out("check progress with `sisi verify --state`") + else: + out("a deep run is already running for this project (pid %s, started %s ago, against %s). " + "Not starting another." % (info.get("pid"), deep._ago(time.time() - info.get("ts", time.time())), + "the current tree" if info.get("fp") == fp else "an older tree")) + return 0 + locked = False + if "deep" in tiers and deep.deep_items(c): + locked, info = deep.adopt(project, fp) if "--worker" in args else deep.acquire(project, fp) + if not locked: + out("a deep run is already running for this project (pid %s, against %s); not starting another." + % (info.get("pid"), "the current tree" if info.get("fp") == fp else "an older tree")) + tiers = tuple(t for t in tiers if t != "deep") + if not tiers: + return 0 + cfg = store.config() + try: + results = run(c, project, default_timeout=cfg["verify"]["default_timeout_s"], tiers=tiers) + record(c, project, results, fp) + if locked: + deep.save_state(project, c["id"], fp, results, [x["id"] for x in deep.deep_items(c)]) + finally: + if locked: + deep.release(project) + good = ok(results) + ds = deep.deep_state(c, project, fp) + if as_json: + out(json.dumps({"contract": c["id"], "project": project, "ok": good, "tiers": list(tiers), "fingerprint": fp, + "deep_state": deep.public(ds), "results": results}, indent=2)) + else: + if results: + out(format_table(results)) + if not good: + out("\nFAILED:\n" + failure_report(results)) + else: + waiting = [r["id"] for r in results if r["status"] == "awaiting-human"] + out("\nOK" + (" (awaiting human: %s)" % ", ".join(waiting) if waiting else "")) + for w in C.warnings(c): + out("warning: " + w) + if ds: + out(deep.describe(ds)) + return 0 if good else 1 diff --git a/sisi/wiring.py b/sisi/wiring.py new file mode 100644 index 0000000..d5a0461 --- /dev/null +++ b/sisi/wiring.py @@ -0,0 +1,545 @@ +"""install / uninstall / doctor. Wiring by reference (import line, symlink, hook entry); never copies canon text. +The tools load the generated rulebook in the personal data folder (base rules with the overlay applied), not the +product's canon/core.md. Every modified file is backed up into /install/ first; uninstall restores it exactly.""" +import copy, hashlib, json, os, re, shlex, shutil + +from . import paths, store + +BEGIN, BEGIN_NONL, END = b"", b"", b"" +BLOCK_RE = re.compile(rb"^\n(@[^\n]*)\n\n", re.M) + + +# ---- locations ------------------------------------------------------------- +def loc(): + h = paths.home() + return { + "claude_dir": os.path.join(h, ".claude"), + "claude_md": os.path.join(h, ".claude", "CLAUDE.md"), + "settings": os.path.join(h, ".claude", "settings.json"), + "codex_dir": os.path.join(h, ".codex"), + "codex": os.path.join(h, ".codex", "AGENTS.md"), + "opencode_dir": os.path.join(h, ".config", "opencode"), + "opencode": os.path.join(h, ".config", "opencode", "AGENTS.md"), + "skills": os.path.join(h, ".agents", "skills"), + "bin": os.path.join(h, ".local", "bin", "sisi"), + } + + +def core(): + """What the tools import: the generated rulebook.""" + return paths.generated() + + +def _old_cores(): + """Places earlier installs pointed at (the product's own rulebook).""" + return (paths.canon("core.md"),) + + +def _sha(b): + return hashlib.sha256(b).hexdigest() + + +def _read(p): + try: + with open(p, "rb") as f: + return f.read() + except OSError: + return None + + +def _write(p, data): + """Atomic write. A symlink at p is written through to its real file, never replaced.""" + real = os.path.realpath(p) + tmp = real + ".sisi-tmp" + with open(tmp, "wb") as f: + f.write(data) + try: + os.chmod(tmp, os.stat(real).st_mode & 0o7777) + except OSError: + pass + os.replace(tmp, real) + + +# ---- manifest -------------------------------------------------------------- +def _idir(): + """The install records: /install/, or the state dir for an installation not migrated yet.""" + new = paths.data_file("install") + if os.path.exists(os.path.join(new, "manifest.json")) or not os.path.exists(paths.state_file("manifest.json")): + return new + return paths.state() + + +def _mpath(): + return os.path.join(_idir(), "manifest.json") + + +def _mload(): + try: + with open(_mpath(), encoding="utf-8") as f: + m = json.load(f) + except (OSError, ValueError): + m = {} + m.setdefault("files", {}) + m.setdefault("dirs", []) + return m + + +def _msave(m): + new = json.dumps(m, indent=1, sort_keys=True) + "\n" + old = _read(_mpath()) + if old is not None and old.decode() == new: + return + os.makedirs(os.path.dirname(_mpath()), exist_ok=True) + with open(_mpath(), "w", encoding="utf-8") as f: + f.write(new) + + +def _backup(m, p, data): + """Remember the original state of p before first modification.""" + if p in m["files"]: + return + name = None + if data is not None: + name = "%s-%s.orig" % (_sha(p.encode())[:8], os.path.basename(p)) + bp = os.path.join(_idir(), "backups", name) + os.makedirs(os.path.dirname(bp), exist_ok=True) + if not os.path.exists(bp): + with open(bp, "wb") as f: + f.write(data) + m["files"][p] = {"backup": name} + + +def _mkdirs(m, d): + missing = [] + while d and not os.path.isdir(d): + missing.append(d) + d = os.path.dirname(d) + for x in reversed(missing): + os.mkdir(x) + m["dirs"].append(x) + + +# ---- CLAUDE.md ------------------------------------------------------------- +def _block(nonl): + return (BEGIN_NONL if nonl else BEGIN) + b"\n@" + core().encode() + b"\n" + END + b"\n" + + +def add_import(data): + m = BLOCK_RE.search(data) + if m: + want = _block(bool(m.group(1))) + return data[:m.start()] + want + data[m.end():] + nonl = bool(data) and not data.endswith(b"\n") + return data + (b"\n" if nonl else b"") + _block(nonl) + + +def remove_import(data): + m = BLOCK_RE.search(data) + if not m: + return data + start = m.start() + if m.group(1) and data[start - 1:start] == b"\n": + start -= 1 + return data[:start] + data[m.end():] + + +def _claude_md_wired(data): + m = BLOCK_RE.search(data or b"") + return bool(m) and m.group(2) == b"@" + core().encode() + + +# ---- settings.json --------------------------------------------------------- +def hook_cmds(): + b = shlex.quote(paths.launcher()) + gate_to = int(store.config()["gate"].get("budget_s", 120)) + 30 + return {"SessionStart": (b + " tick --tool claude-code", 10), "Stop": (b + " gate --tool claude-code", gate_to), + "SubagentStop": (b + " gate --subagent --tool claude-code", 30)} + + +def _is_ours(h, sub): + if not (isinstance(h, dict) and h.get("type") == "command" and isinstance(h.get("command"), str)): + return False + try: + parts = shlex.split(h["command"]) + except ValueError: + return False + return len(parts) >= 2 and os.path.basename(parts[0]) == "sisi" and parts[1] == sub + + +def _parse_settings(text): + s = text.decode("utf-8") + if not s.strip(): + return {}, " ", True + obj = json.loads(s) + if not isinstance(obj, dict): + raise ValueError("settings.json is not a JSON object") + m = re.search(r'\n([ \t]+)"', s) + ind = m.group(1) if m else None + return obj, ind, s.endswith("\n") + + +def _dump(obj, ind, nl): + return (json.dumps(obj, indent=ind, ensure_ascii=False) + ("\n" if nl else "")).encode("utf-8") + + +def add_hooks(obj): + """Mutate obj; return True if anything changed.""" + changed = False + hooks = obj.get("hooks") + if hooks is None: + hooks = obj["hooks"] = {} + changed = True + if not isinstance(hooks, dict): + raise ValueError("settings.json 'hooks' is not an object") + for ev, (cmd, to) in hook_cmds().items(): + sub = shlex.split(cmd)[1] + groups = hooks.get(ev) + if groups is None: + groups = hooks[ev] = [] + changed = True + if not isinstance(groups, list): + raise ValueError("settings.json hooks.%s is not a list" % ev) + found = False + for g in groups: + for h in (g.get("hooks", []) if isinstance(g, dict) and isinstance(g.get("hooks"), list) else []): + if _is_ours(h, sub): + found = True + if h.get("command") != cmd: + h["command"] = cmd + changed = True + if not found: + groups.append({"hooks": [{"type": "command", "command": cmd, "timeout": to}]}) + changed = True + return changed + + +def remove_hooks(obj): + changed = False + hooks = obj.get("hooks") + if not isinstance(hooks, dict): + return False + for ev, sub in (("SessionStart", "tick"), ("Stop", "gate"), ("SubagentStop", "gate")): + groups = hooks.get(ev) + if not isinstance(groups, list): + continue + keep, ev_changed = [], False + for g in groups: + hs = g.get("hooks") if isinstance(g, dict) else None + if isinstance(hs, list) and any(_is_ours(h, sub) for h in hs): + changed = ev_changed = True + rest = [h for h in hs if not _is_ours(h, sub)] + if rest: + g = dict(g, hooks=rest) + else: + continue + keep.append(g) + if keep: + hooks[ev] = keep + elif ev_changed: + del hooks[ev] + if changed and not hooks: + del obj["hooks"] + return changed + + +def _hooks_wired(obj): + hooks = obj.get("hooks") if isinstance(obj, dict) else None + out = {} + for ev, sub, name in (("SessionStart", "tick", "tick"), ("Stop", "gate", "gate"), ("SubagentStop", "gate", "subagent")): + groups = hooks.get(ev) if isinstance(hooks, dict) else None + sub, key = sub, name + out[key] = False + for g in groups if isinstance(groups, list) else []: + for h in g.get("hooks", []) if isinstance(g, dict) and isinstance(g.get("hooks"), list) else []: + if _is_ours(h, sub) and shlex.split(h["command"])[0] == paths.launcher(): + out[key] = True + return out + + +# ---- symlinks -------------------------------------------------------------- +def _ours(p): + """A symlink sisi made: it points into the product or at the generated rulebook.""" + if not os.path.islink(p): + return False + t = os.readlink(p) + if t.startswith(paths.REPO + os.sep) or t == core() or t.startswith(paths.data() + os.sep): + return True + if t.startswith(os.path.join(paths.lib(), "")): + return True # the stable copy + from . import release # a link made when the tools ran from the source folder + src = release.dev_source() + return bool(src) and t.startswith(os.path.join(src, "")) + + +def _link(m, p, target, notes, label): + if os.path.islink(p): + cur = os.readlink(p) + if cur == target: + return + if not _ours(p): + notes.append("%s: %s is a symlink to %s; not touched" % (label, p, cur)) + return + elif os.path.lexists(p): + notes.append("%s: %s exists and is not a symlink; not touched" % (label, p)) + return + _mkdirs(m, os.path.dirname(p)) + tmp = "%s.sisi-new-%d" % (p, os.getpid()) + try: + os.unlink(tmp) + except OSError: + pass + os.symlink(target, tmp) + os.replace(tmp, p) # a running hook sees the old link or the new one, never none + notes.append("%s: linked %s" % (label, p)) + + +# ---- install / uninstall --------------------------------------------------- +def _writable(p): + """Can we create or replace the file p (following symlinks)? Returns an error string or None.""" + if os.path.islink(p) and not os.path.exists(p): + return "%s is a dangling symlink" % p + real = os.path.realpath(p) + if os.path.exists(real): + ok = os.access(real, os.W_OK) and os.access(os.path.dirname(real), os.W_OK) + else: + d = os.path.dirname(real) + while d and not os.path.isdir(d): + d = os.path.dirname(d) + ok = os.access(d, os.W_OK) + return None if ok else "%s is not writable" % p + + +def _plan_claude(L): + """Compute every change to Claude Code's files without touching anything. Returns (steps, errors).""" + steps, errs = [], [] + p = L["claude_md"] + e = _writable(p) + if e: + errs.append(e) + else: + data = _read(p) + new = add_import(data or b"") + if data is None or new != data: + steps.append((p, data, new, "claude-code: import line added to %s" % p)) + p = L["settings"] + e = _writable(p) + if e: + errs.append(e) + else: + data = _read(p) + try: + obj, ind, nl = _parse_settings(data if data is not None else b"") + if add_hooks(obj): + steps.append((p, data, _dump(obj, ind, nl if data is not None else True), + "claude-code: hooks registered in %s" % p)) + except (ValueError, UnicodeDecodeError) as ex: + errs.append("settings.json is not valid (%s); %s left untouched" % (ex, p)) + return steps, errs + + +def install(): + """Validate everything first; if anything would fail, change nothing.""" + L, notes = loc(), [] + steps, errs = [], [] + if os.path.isdir(L["claude_dir"]): + steps, errs = _plan_claude(L) + else: + notes.append("claude-code: %s not found; skipped" % L["claude_dir"]) + if errs: + return 1, ["install refused, nothing was changed:"] + [" " + e for e in errs] + # The personal folder and the generated rulebook come first: nothing may point at a file that is not there yet. + try: + from . import lifecycle, overlay + notes += lifecycle.run() + b = overlay.build_canon() + if b["over_budget"]: + notes.append("warning: the rulebook is %d lines, over the %d-line budget" % (b["lines"], overlay.MAX_LINES)) + except Exception as e: + return 1, ["install refused, the personal data could not be prepared (%r); nothing was wired" % e] + m = _mload() + try: + for p, old, new, note in steps: + _backup(m, p, old) + if old is None: + with open(p, "wb") as f: + f.write(new) + else: + _write(p, new) + notes.append(note) + for key in ("codex", "opencode"): + if os.path.isdir(L[key + "_dir"]): + _link(m, L[key], core(), notes, key) + else: + notes.append("%s: %s not found; skipped" % (key, L[key + "_dir"])) + notes.append("muse: not wired (global instruction path unconfirmed)") + sk = os.path.join(paths.product_root(), "canon", "skills") + for name in sorted(os.listdir(sk)) if os.path.isdir(sk) else []: + if os.path.isdir(os.path.join(sk, name)): + _link(m, os.path.join(L["skills"], name), os.path.join(sk, name), notes, "skills") + _link(m, L["bin"], paths.launcher(), notes, "cli") + _msave(m) + except Exception as e: # undo what was done so far + _msave(m) + uninstall() + return 1, notes + ["install failed (%r) and was rolled back" % e] + return 0, notes + + +def uninstall(): + L, notes = loc(), [] + m = _mload() + # CLAUDE.md + p = L["claude_md"] + data = _read(p) + if data is not None and BLOCK_RE.search(data): + new = remove_import(data) + if not new and m["files"].get(p, {}).get("backup") is None and p in m["files"]: + os.unlink(p) + else: + _write(p, new) + notes.append("claude-code: import line removed") + # settings.json + p = L["settings"] + data = _read(p) + ent = m["files"].get(p) + if data is not None: + try: + obj, ind, nl = _parse_settings(data) + before = copy.deepcopy(obj) + if remove_hooks(obj): + if ent is not None and ent["backup"] is None and not obj: + os.unlink(p) + else: + orig = _read(os.path.join(_idir(), "backups", ent["backup"])) if ent and ent["backup"] else None + try: + back = _parse_settings(orig)[0] if orig is not None else None + except ValueError: + back = None + if back is not None: + t = copy.deepcopy(back) + add_hooks(t) + if back is not None and t == before: + _write(p, orig) # current file is original + our entries: restore exact bytes + else: + _write(p, _dump(obj, ind, nl)) + notes.append("claude-code: hooks removed") + except (ValueError, UnicodeDecodeError) as e: + notes.append("claude-code: settings.json not touched (%s)" % e) + # symlinks + cand = [L["codex"], L["opencode"], L["bin"]] + if os.path.isdir(L["skills"]): + cand += [os.path.join(L["skills"], n) for n in sorted(os.listdir(L["skills"]))] + for p in cand: + if _ours(p): + os.unlink(p) + notes.append("removed link %s" % p) + for d in reversed(m["dirs"]): + try: + os.rmdir(d) + except OSError: + pass + try: + os.unlink(_mpath()) + except OSError: + pass + return 0, notes + + +# ---- doctor ---------------------------------------------------------------- +def doctor(): + L = loc() + rows = [] + cm, st = _read(L["claude_md"]), _read(L["settings"]) + try: + hw = _hooks_wired(_parse_settings(st)[0]) if st is not None else {"tick": False, "gate": False, "subagent": False} + except (ValueError, UnicodeDecodeError): + hw = {"tick": False, "gate": False, "subagent": False} + missing = [n for n, ok in (("import line", _claude_md_wired(cm)), ("tick hook", hw["tick"]), + ("gate hook", hw["gate"]), ("subagent hook", hw["subagent"])) if not ok] + rows.append({"tool": "claude-code", "status": "not wired" if missing else "wired", + "detail": ("missing: " + ", ".join(missing)) if missing else "import + tick + gate registered", + "blocking_hook": "yes (Stop)" if hw["gate"] else "no"}) + for key, name, hook in (("codex", "codex", "no (documented, not built)"), + ("opencode", "opencode", "no (none verified)")): + p = L[key] + if os.path.islink(p) and os.readlink(p) == core(): + st_, det = "wired", "%s -> the generated rulebook" % p + elif os.path.islink(p) and os.readlink(p) in _old_cores(): + st_, det = "not wired", "%s -> the product's canon/core.md (old wiring; run `sisi install`)" % p + elif os.path.lexists(p): + st_, det = "not wired", "%s exists and is not ours (left alone)" % p + else: + st_, det = "not wired", "no %s" % p + rows.append({"tool": name, "status": st_, "detail": det, "blocking_hook": hook}) + rows.append({"tool": "muse", "status": "not wired", + "detail": "global instruction path unconfirmed (binary mentions ~/.claude/CLAUDE.md and ~/.codex/AGENTS.md as foreign context; unverified)", + "blocking_hook": "unknown"}) + sk = paths.canon("skills") + names = [n for n in sorted(os.listdir(sk)) if os.path.isdir(os.path.join(sk, n))] if os.path.isdir(sk) else [] + bad = [n for n in names if not (_ours(os.path.join(L["skills"], n)))] + rows.append({"tool": "skills", "status": "not wired" if bad else "wired", + "detail": ("not linked: " + ", ".join(bad)) if bad else "%d skill(s) linked" % len(names), "blocking_hook": "-"}) + ok = os.path.islink(L["bin"]) and os.readlink(L["bin"]) == paths.launcher() + rows.append({"tool": "cli", "status": "wired" if ok else "not wired", "detail": L["bin"], "blocking_hook": "-"}) + from . import lifecycle, overlay, pdata + from . import release + live = release.live_text() + rows.append({"tool": "product", "status": "ok" if os.path.isfile(os.path.join(paths.product_root(), "canon", "core.md")) else "broken", + "detail": "live copy: " + live + (" (read-only at run time)" if not release.current_name() else ""), + "blocking_hook": "-"}) + todo = lifecycle.pending() + rows.append({"tool": "personal", "status": "ok" if pdata.exists() and not todo else "not ready", + "detail": "%s (format %d)%s" % (paths.data(), pdata.version(), + "; run `sisi migrate`: still to move: " + ", ".join(todo) if todo else ""), + "blocking_hook": "-"}) + gen = paths.generated() + cur = os.path.isfile(gen) and not overlay.is_stale() + rows.append({"tool": "rulebook", "status": "current" if cur else ("stale" if os.path.isfile(gen) else "missing"), + "detail": gen + ("" if cur else "; run `sisi build-canon`"), "blocking_hook": "-"}) + return rows + + +def quick_problem(): + """Cheap check for tick. Returns a short string or None.""" + L = loc() + refs = any(os.path.islink(L[k]) and os.readlink(L[k]) == core() for k in ("codex", "opencode")) + refs = refs or _claude_md_wired(_read(L["claude_md"])) # only complain about a rulebook something points at + if refs and not os.path.isfile(core()): + return "the generated rulebook is missing at %s (run `sisi build-canon`)" % core() + if refs: + from . import overlay + if overlay.is_stale(): + return "the generated rulebook is out of date (run `sisi build-canon`)" + for k in ("codex", "opencode"): + if os.path.islink(L[k]) and os.readlink(L[k]).startswith((paths.REPO, paths.data())) and not os.path.exists(L[k]): + return "%s link is dangling" % k + if os.path.isdir(L["claude_dir"]): + r = doctor_claude() + if r: + return "claude-code wiring is incomplete (%s)" % r + return None + + +def doctor_claude(): + L = loc() + cm, st = _read(L["claude_md"]), _read(L["settings"]) + try: + hw = _hooks_wired(_parse_settings(st)[0]) if st is not None else {"tick": False, "gate": False, "subagent": False} + except (ValueError, UnicodeDecodeError): + hw = {"tick": False, "gate": False, "subagent": False} + missing = [n for n, ok in (("import line", _claude_md_wired(cm)), ("tick hook", hw["tick"]), + ("gate hook", hw["gate"]), ("subagent hook", hw["subagent"])) if not ok] + return ", ".join(missing) + + +def live_wired(): + """Are the CLI link and the Claude Code hooks pointing at the launcher the tools should use now?""" + L = loc() + if not (os.path.islink(L["bin"]) and os.readlink(L["bin"]) == paths.launcher()): + return False + st = _read(L["settings"]) + try: + hw = _hooks_wired(_parse_settings(st)[0]) if st is not None else None + except (ValueError, UnicodeDecodeError): + return False + return hw is None or all(hw.values()) diff --git a/tests/run_parallel.py b/tests/run_parallel.py new file mode 100644 index 0000000..b03a4f2 --- /dev/null +++ b/tests/run_parallel.py @@ -0,0 +1,63 @@ +"""Run every test module in its own process, several at a time. + +The suite is the fast check in this project's contract, so it runs at the end +of every agent turn and must finish well inside 60 seconds even on a busy +machine. Each module already isolates itself (temporary home, state and data +folders), so modules are safe to run side by side. + +Usage: python3 tests/run_parallel.py [-j N] +Exit status is 0 only if every module passes. Output of a failing module is +printed in full; passing modules print one line. +""" +import concurrent.futures +import os +import subprocess +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) + + +def run(module): + start = time.time() + proc = subprocess.run( + [sys.executable, "-W", "ignore::ResourceWarning", "-m", "unittest", module], + cwd=HERE, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, + ) + return module, proc.returncode, proc.stdout, time.time() - start + + +def main(argv): + jobs = os.cpu_count() or 4 + if "-j" in argv: + jobs = int(argv[argv.index("-j") + 1]) + modules = sorted(f[:-3] for f in os.listdir(HERE) + if f.startswith("test_") and f.endswith(".py")) + if not modules: + print("no test modules found") + return 1 + failed = [] + total = 0 + start = time.time() + with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: + for module, code, out, secs in pool.map(run, modules): + ran = [l for l in out.splitlines() if l.startswith("Ran ")] + count = int(ran[-1].split()[1]) if ran else 0 + total += count + if code != 0 or not ran: + failed.append(module) + print("FAILED %s (%.1fs)\n%s" % (module, secs, out)) + else: + print("ok %-28s %4d tests %6.1fs" % (module, count, secs)) + print("\nRan %d tests in %d modules in %.1fs" % (total, len(modules), time.time() - start)) + if failed: + print("FAILED: " + ", ".join(failed)) + return 1 + print("OK") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/support.py b/tests/support.py new file mode 100644 index 0000000..f74ce28 --- /dev/null +++ b/tests/support.py @@ -0,0 +1,140 @@ +import json, os, subprocess, sys, tempfile, unittest + +import warnings +sys.warnoptions.append("ignore::ResourceWarning") # keeps unittest from re-enabling them +warnings.simplefilter("ignore", ResourceWarning) # tests read small files inline +REPO = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +sys.path.insert(0, REPO) +ITERS = max(1, int(os.environ.get("SISI_TEST_ITERS", "1"))) # scale property tests up with SISI_TEST_ITERS=10 +BIN = os.path.join(REPO, "bin", "sisi") + + +_CURRENT = [] # the temp root of the test now running (empty outside a SisiCase) + + +def _guarded(name): + """Every resolved root (home, state, personal data) must lie inside the running test's temp dir. A path that + resolves into the real home, state or personal data dir fails the test at once, not by luck on a busy machine.""" + from sisi import paths + orig = getattr(paths, name) + + def wrapper(*a, **kw): + r = orig(*a, **kw) + if _CURRENT and not os.path.realpath(r).startswith(_CURRENT[-1] + os.sep): + raise AssertionError("isolation leak: paths.%s() resolved to %s, outside the test's temp dir %s" % (name, r, _CURRENT[-1])) + return r + wrapper.__wrapped__ = orig + setattr(paths, name, wrapper) + + +for _n in ("home", "state", "data", "lib"): + _guarded(_n) + + +class SisiCase(unittest.TestCase): + """Every test gets a fresh SISI_HOME and SISI_STATE in temp dirs. Real config is never touched.""" + + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.tmp = os.path.realpath(self._tmp.name) + self.home = os.path.join(self.tmp, "home") + self.state = os.path.join(self.tmp, "state") + self.data = os.path.join(self.tmp, "data") + self.proj = os.path.join(self.tmp, "proj") + for d in (self.home, self.proj): + os.makedirs(d) + saved = {k: os.environ.get(k) for k in ("SISI_HOME", "SISI_STATE", "SISI_DATA", "SISI_TOOL", "SISI_SESSION_ID", "SISI_RETRO_REQUIRED", "SISI_NOTES")} + os.environ.update(SISI_HOME=self.home, SISI_STATE=self.state, SISI_DATA=self.data, + SISI_RETRO_REQUIRED="0") # retro tests turn it on + os.environ.pop("SISI_NOTES", None) + _CURRENT.append(self.tmp) + self.addCleanup(_CURRENT.pop) + for k in ("SISI_TOOL", "SISI_SESSION_ID"): + os.environ.pop(k, None) + + def restore(): + for k, v in saved.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + self.addCleanup(restore) + + def sisi_proc(self, *args, cwd=None, stdin=None, env=None): + """Run bin/sisi as a real subprocess (for timing tests and process-level behaviour).""" + e = dict(os.environ, **(env or {})) + # stdin is always closed after `stdin` (empty when none): hooks such as tick and gate read it to the end, so + # inheriting an open pipe from whoever runs the suite makes them wait forever + return subprocess.run([sys.executable, BIN] + list(args), cwd=cwd or self.proj, input=stdin or "", + capture_output=True, text=True, env=e, timeout=120) + + def sisi(self, *args, cwd=None, stdin=None, env=None): + """Run the CLI in this process (fast). Same arguments and result shape as a subprocess run.""" + import contextlib, io + from unittest import mock + from sisi import cli + out, err = io.StringIO(), io.StringIO() + old_cwd = os.getcwd() + os.chdir(cwd or self.proj) + try: + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \ + mock.patch.object(sys, "stdin", io.StringIO(stdin or "")), mock.patch.dict(os.environ, env or {}): + try: + rc = cli.main(list(args)) + except SystemExit as e: + rc = e.code if isinstance(e.code, int) else (0 if e.code is None else 1) + finally: + os.chdir(old_cwd) + return subprocess.CompletedProcess(args, rc or 0, out.getvalue(), err.getvalue()) + + def git_init(self, d=None): + d = d or self.proj + subprocess.run(["git", "init", "-q"], cwd=d, check=True) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "i"], + cwd=d, check=True) + + def write_contract(self, c, d=None, trusted=True): + d = d or self.proj + if trusted: + from sisi import trust + trust.add(d) + os.makedirs(os.path.join(d, ".sisi"), exist_ok=True) + with open(os.path.join(d, ".sisi", "contract.json"), "w") as f: + json.dump(c, f) + + def results(self): + p = os.path.join(self.state, "results.jsonl") + if not os.path.exists(p): + return [] + with open(p) as f: + return [json.loads(l) for l in f] + + +def check(id, cmd, rung=3, kind="general", exit=0, timeout_s=10, **expect): + return {"id": id, "claim": "claim " + id, "kind": kind, "rung": rung, "cmd": cmd, + "expect": dict({"exit": exit}, **expect), "timeout_s": timeout_s} + + +def human(id, rung=5, kind="general"): + return {"id": id, "claim": "claim " + id, "kind": kind, "rung": rung} + + +def contract(checks, invariants=()): + return {"id": "t", "goal": "g", "checks": list(checks), "invariants": list(invariants), + "assumptions": [], "questions": []} + + +def skip_timing_if_busy(case): + """Skip a wall-clock speed assertion when the machine is overloaded. + + A speed test measures sisi only when the machine has spare capacity. With more runnable work + than processors it measures the queue, and a failure says nothing about the code. + """ + import os + try: + load, cpus = os.getloadavg()[0], os.cpu_count() or 1 + except OSError: + return + if load > cpus: + case.skipTest("machine overloaded (load %.0f on %d processors): speed not measured" % (load, cpus)) diff --git a/tests/test_contract.py b/tests/test_contract.py new file mode 100644 index 0000000..5e87b18 --- /dev/null +++ b/tests/test_contract.py @@ -0,0 +1,67 @@ +import os, unittest +from support import * +from sisi import contract as C + + +class ContractTests(SisiCase): + def test_skeleton_is_valid_but_fails(self): + c = C.skeleton("goal") + self.assertEqual(C.validate(c), []) + self.assertEqual(self.sisi("contract", "init", "--goal", "make x").returncode, 0) + self.assertEqual(self.sisi("contract", "check").returncode, 0) + self.assertEqual(self.sisi("verify").returncode, 1) # placeholder must not pass + self.assertEqual(self.sisi("contract", "init").returncode, 1) # no clobbering + + def test_validation_errors(self): + good = contract([check("a", "true")]) + self.assertEqual(C.validate(good), []) + bad = { + "not an object": [], + "no checks": dict(good, checks=[]), + "empty goal": dict(good, goal=" "), + "bad kind": contract([check("a", "true", kind="nope")]), + "rung 0": contract([check("a", "true", rung=0)]), + "rung 7": contract([check("a", "true", rung=7)]), + "rung bool": contract([check("a", "true", rung=True)]), + "rung 3 no cmd": contract([human("a", rung=3)]), + "rung 5 with cmd": contract([dict(check("a", "true"), rung=5)]), + "no expect.exit": contract([dict(check("a", "true"), expect={})]), + "bad timeout": contract([check("a", "true", timeout_s=0)]), + "duplicate ids": contract([check("a", "true"), check("a", "true")]), + "dup across invariant": contract([check("a", "true")], [check("a", "true")]), + "invariant no cmd": contract([check("a", "true")], [{"id": "i", "claim": "c", "expect": {"exit": 0}}]), + "assumptions not strings": dict(good, assumptions=[1]), + "question w/o default": dict(good, questions=[{"q": "?"}]), + } + for name, c in bad.items(): + with self.subTest(name): + self.assertTrue(C.validate(c), name) + + def test_rung_5_6_valid_without_cmd(self): + self.assertEqual(C.validate(contract([check("a", "true"), human("h", 5), human("i", 6)])), []) + + def test_floors(self): + weak = contract([check("m", "true", rung=3, kind="money")]) + self.assertEqual(len(C.floor_failures(weak)), 1) + self.assertEqual(C.floor_failures(contract([check("m", "true", rung=2, kind="money")])), []) + # one strong check among weak ones satisfies the floor + self.assertEqual(C.floor_failures(contract([check("m", "true", rung=3, kind="money"), + check("n", "true", rung=1, kind="money")])), []) + self.assertEqual(C.floor_failures(contract([check("u", "true", rung=4, kind="ui")])), []) + for k in ("concurrency", "parsing", "money", "state-machine", "migration"): + self.assertEqual(C.floors()[k], 2) + + def test_find_stops_at_git_root(self): + self.git_init() + self.write_contract(contract([check("a", "true")])) + sub = os.path.join(self.proj, "a", "b") + os.makedirs(sub) + self.assertEqual(C.find(sub), os.path.join(self.proj, ".sisi", "contract.json")) + outer = self.tmp # a contract above the git root must not be found + self.write_contract(contract([check("a", "true")]), outer) + os.remove(os.path.join(self.proj, ".sisi", "contract.json")) + self.assertIsNone(C.find(sub)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_delivery.py b/tests/test_delivery.py new file mode 100644 index 0000000..2d3cb28 --- /dev/null +++ b/tests/test_delivery.py @@ -0,0 +1,395 @@ +import json, os, random, time, unittest +from support import * +from sisi import delivery, gate, harvest, retro, store, verify as V, contract as C + + +def ts(t): + return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(t)) + ".250Z" + + +def human_line(t, text="do the thing please"): + return {"type": "user", "timestamp": ts(t), "message": {"role": "user", "content": text}} + + +def hook_line(t): + return {"type": "user", "isMeta": True, "timestamp": ts(t), + "message": {"role": "user", "content": "Stop hook feedback:\nsisi: the contract is not satisfied"}} + + +def result_line(t, size=10): + return {"type": "user", "timestamp": ts(t), "toolUseResult": {"stdout": "x" * size}, + "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t", "content": "y" * size}]}} + + +def other_machine_lines(t): + return [{"type": "user", "timestamp": ts(t), "origin": {"kind": "task-notification"}, + "message": {"role": "user", "content": "worker finished"}}, + {"type": "user", "timestamp": ts(t), "message": {"role": "user", "content": "be good"}}, + {"type": "user", "timestamp": ts(t), "message": {"role": "user", "content": "x"}}] + + +def asst_line(t): + return {"type": "assistant", "timestamp": ts(t), "message": {"role": "assistant", "content": [{"type": "text", "text": "ok"}]}} + + +def write_transcript(path, entries): + with open(path, "w") as f: + for e in entries: + f.write((e if isinstance(e, str) else json.dumps(e, separators=(",", ":"))) + "\n") + + +def reference_start(path): + """Slow and simple: read the whole file, apply the same human-message rule to every line, keep the last.""" + best = None + with open(path) as f: + for line in f: + try: + d = json.loads(line) + except ValueError: + continue + if d.get("type") == "user" and harvest.typed_text(d)[0] is not None: + best = harvest.epoch(d["timestamp"]) + return best + + +class StartFinderTests(SisiCase): + def path(self, name="t.jsonl"): + return os.path.join(self.tmp, name) + + def test_last_human_message_wins_over_later_machine_entries(self): + t0 = 1_800_000_000 + entries = [human_line(t0 - 500, "first request"), asst_line(t0 - 400), human_line(t0, "second request, the one"), + asst_line(t0 + 5), result_line(t0 + 6), hook_line(t0 + 7)] + other_machine_lines(t0 + 8) + \ + [asst_line(t0 + 9), result_line(t0 + 10), hook_line(t0 + 11)] + write_transcript(self.path(), entries) + self.assertAlmostEqual(delivery.find_start(self.path()), t0 + 0.25, places=1) + + def test_queued_message_typed_while_working_counts(self): + t0 = 1_800_000_000 + queued = {"type": "attachment", "timestamp": ts(t0 + 30), + "attachment": {"type": "queued_command", "commandMode": "prompt", "prompt": "also do this"}} + write_transcript(self.path(), [human_line(t0), asst_line(t0 + 1), queued, result_line(t0 + 31)]) + self.assertAlmostEqual(delivery.find_start(self.path()), t0 + 30.25, places=1) + + def test_huge_tool_results_and_tiny_chunks(self): + t0 = 1_800_000_000 + entries = [human_line(t0, "the request")] + [result_line(t0 + i, size=5000) for i in range(1, 20)] + write_transcript(self.path(), entries) + self.assertAlmostEqual(delivery.find_start(self.path(), chunk=700), t0 + 0.25, places=1) + self.assertIsNone(delivery.find_start(self.path(), max_bytes=20000, chunk=700)) # too far back: not measured + + def test_none_when_nothing_found_or_unreadable(self): + write_transcript(self.path(), [asst_line(1), result_line(2), hook_line(3)]) + self.assertIsNone(delivery.find_start(self.path())) + self.assertIsNone(delivery.find_start(os.path.join(self.tmp, "missing.jsonl"))) + write_transcript(self.path("bad.jsonl"), ["{not json", "\x00\x01garbage", '{"type":"user","timestamp":5}', ""]) + self.assertIsNone(delivery.find_start(self.path("bad.jsonl"))) + write_transcript(self.path("empty.jsonl"), []) + self.assertIsNone(delivery.find_start(self.path("empty.jsonl"))) + + def test_matches_reference_on_random_transcripts(self): + rnd = random.Random(20261122) + for n in range(40 * ITERS): + t, entries = 1_800_000_000, [] + for _ in range(rnd.randint(1, 60)): + t += rnd.randint(1, 30) + k = rnd.random() + if k < 0.12: + entries.append(human_line(t, "typed %d" % rnd.randint(0, 99))) + elif k < 0.4: + entries.append(result_line(t, rnd.choice([10, 300, 4000]))) + elif k < 0.55: + entries.append(hook_line(t)) + elif k < 0.65: + entries.extend(other_machine_lines(t)) + elif k < 0.7: + entries.append("{broken") + else: + entries.append(asst_line(t)) + write_transcript(self.path(), entries) + want = reference_start(self.path()) + got = delivery.find_start(self.path(), chunk=rnd.choice([64, 257, 1000, 128 * 1024])) + self.assertEqual(got, want, "case %d" % n) + + def test_real_transcripts_if_present(self): + """Read-only: every real transcript gives a start no later than its last record, and the same answer as a full scan.""" + base = os.path.expanduser("~/.claude/projects") + found = [] + for root, _, files in os.walk(base): + if "subagents" in root: + continue + found += [os.path.join(root, f) for f in files if f.endswith(".jsonl")] + if len(found) > 40: + break + found.sort(key=lambda p: os.path.getsize(p)) + for p in (found[:1] + found[-1:]) if found else []: + if os.path.getsize(p) > 30 * 1024 * 1024: + continue + got = delivery.find_start(p) + if got is not None: + self.assertEqual(got, reference_start(p) if os.path.getsize(p) < 8 * 1024 * 1024 else got) + + +class DeliveryRowTests(SisiCase): + sid = "d-1" + + def setUp(self): + super().setUp() + self.tp = os.path.join(self.tmp, "transcript.jsonl") + self.t0 = time.time() - 90 + write_transcript(self.tp, [human_line(self.t0 - 400, "older"), asst_line(self.t0 - 300), + human_line(self.t0, "the request"), asst_line(self.t0 + 1), result_line(self.t0 + 2), + hook_line(self.t0 + 3)]) + + def hook(self, **extra): + p = dict({"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop"}, **extra) + return self.sisi_proc("gate", stdin=json.dumps(p)) + + def rows(self): + p = os.path.join(self.state, "deliveries.jsonl") + if not os.path.exists(p): + return [] + with open(p) as f: + return [json.loads(l) for l in f] + + def test_row_is_recorded_when_the_gate_allows(self): + self.write_contract(contract([check("ok", "true")])) + r = self.hook(transcript_path=self.tp) + self.assertEqual((r.returncode, r.stdout), (0, "")) + rows = self.rows() + self.assertEqual(len(rows), 1) + row = rows[0] + self.assertEqual((row["session"], row["project"], row["contract"], row["send_backs"]), (self.sid, self.proj, True, 0)) + self.assertGreaterEqual(row["seconds"], 89) + self.assertLess(row["seconds"], 140) + self.assertGreaterEqual(row["check_s"], 0.0) + self.assertEqual(row["start"], time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(self.t0)) + "Z") + self.hook(transcript_path=self.tp) # the same request again: not recorded twice + self.assertEqual(len(self.rows()), 1) + + def test_send_backs_and_check_time_are_counted_for_the_request(self): + self.write_contract(contract([check("bad", "sleep 0.3; exit 1")])) + r = self.hook(transcript_path=self.tp) + self.assertEqual(json.loads(r.stdout)["decision"], "block") + self.assertEqual(self.rows(), []) # a send-back is not a delivery + self.write_contract(contract([check("ok", "sleep 0.2")])) + r = self.hook(transcript_path=self.tp) + self.assertEqual(r.stdout, "") + row = self.rows()[0] + self.assertEqual(row["send_backs"], 1) + self.assertGreaterEqual(row["check_s"], 0.45) + + def test_no_contract_is_recorded_as_such(self): + r = self.hook(transcript_path=self.tp) + self.assertEqual(r.returncode, 0) + self.assertEqual(self.rows()[0]["contract"], False) + + def test_gate_fails_open_without_a_usable_transcript(self): + self.write_contract(contract([check("ok", "true")])) + for tp in (None, os.path.join(self.tmp, "missing.jsonl"), self.tp + ".dir"): + kw = {} if tp is None else {"transcript_path": tp} + r = self.hook(**kw) + self.assertEqual((r.returncode, r.stdout), (0, ""), kw) + os.mkdir(self.tp + ".dir") + r = self.hook(transcript_path=self.tp + ".dir") # a directory + self.assertEqual((r.returncode, r.stdout), (0, "")) + for bad in (b"\x00\xff\xfe{[", b"{" * 100000, b'{"type":"user","timestamp":"nonsense","message":{"content":"hi"}}\n'): + with open(self.tp, "wb") as f: + f.write(bad) + r = self.hook(transcript_path=self.tp) + self.assertEqual((r.returncode, r.stdout), (0, "")) + self.assertEqual(self.rows(), []) + r = self.hook(transcript_path=12345) + self.assertEqual((r.returncode, r.stdout), (0, "")) + + def test_a_failing_recorder_never_changes_the_answer(self): + from unittest import mock + self.write_contract(contract([check("ok", "true")])) + with mock.patch.object(delivery, "find_start", side_effect=RuntimeError("boom")): + a = gate.decide({"session_id": "x1", "cwd": self.proj, "transcript_path": self.tp}) + gate._record_delivery({"session_id": "x1", "cwd": self.proj, "transcript_path": self.tp}) + self.assertEqual(a, ("allow", None)) + self.assertEqual(self.rows(), []) + + def test_overhead_is_small(self): + """Recording a delivery on a large transcript costs well under the budget of 50 ms (generous bound for CI).""" + entries = [human_line(self.t0)] + [result_line(self.t0 + i, 20000) for i in range(1, 100)] + write_transcript(self.tp, entries) + delivery.find_start(self.tp) # warm imports + t = time.perf_counter() + for _ in range(5): + delivery.find_start(self.tp) + per = (time.perf_counter() - t) / 5 + self.assertLess(per, 0.25) + + def test_retro_stores_the_request_time_with_the_lesson(self): + store.save_session("r-1", {"session_id": "r-1", "transcript_path": self.tp, "cwd": self.proj}) + os.environ["SISI_SESSION_ID"] = "r-1" + con = retro.connect() + try: + lid = retro.new_lesson(con, dict(aim="speed", change_kind="tool", target=None, + moment="`make build` took 9 minutes in lib/src", cause="no cache here", + change="add a cache recipe for `make build`"), self.proj, None) + con.commit() + v = con.execute("SELECT delivery_s FROM occurrences WHERE lesson_id=?", (lid,)).fetchone()[0] + finally: + con.close() + self.assertGreaterEqual(v, 89) + self.assertLess(v, 200) + self.assertIn("it took longer than it had to", self.sisi("help").stdout) + + +def ref_percentile(xs, p): + s = sorted(xs) + if len(s) == 1: + return s[0] + pos = (len(s) - 1) * p / 100.0 + lo, frac = int(pos // 1), pos - int(pos // 1) + return s[lo] if frac == 0 else s[lo] * (1 - frac) + s[lo + 1] * frac + + +class TimeCommandTests(SisiCase): + def test_small_known_values(self): + self.assertEqual(delivery.median([5, 1, 3]), 3) + self.assertEqual(delivery.median([4, 1, 3, 2]), 2.5) + self.assertEqual(delivery.percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 90), 9.1) + self.assertEqual(delivery.percentile([7], 90), 7) + self.assertIsNone(delivery.median([])) + self.assertIsNone(delivery.percentile([], 90)) + + def test_median_and_percentile_property(self): + rnd = random.Random(7) + for _ in range(300 * ITERS): + xs = [rnd.choice([rnd.randint(0, 50), rnd.random() * 1000]) for _ in range(rnd.randint(1, 40))] + half = sorted(xs) + n = len(half) + want_med = half[n // 2] if n % 2 else (half[n // 2 - 1] + half[n // 2]) / 2 + self.assertAlmostEqual(delivery.median(xs), want_med) + for p in (0, 50, 90, 100, rnd.randint(0, 100)): + self.assertAlmostEqual(delivery.percentile(xs, p), ref_percentile(xs, p), places=6) + self.assertLessEqual(delivery.percentile(xs, 50), delivery.percentile(xs, 90) + 1e-9) + + def add_rows(self, now, spec): + """spec: list of (days_ago, seconds, project, send_backs, check_s).""" + for d, secs, proj, sb, cs in spec: + end = now - d * 86400 + store.append("deliveries", {"ts": delivery._iso(end), "session": "s", "project": proj, "start": delivery._iso(end - secs), + "end": delivery._iso(end), "seconds": secs, "send_backs": sb, "check_s": cs, "contract": True}) + + def test_report_windows_projects_shares_and_send_backs(self): + now = time.time() + self.add_rows(now, [(1, 100, "/a/alpha", 0, 10), (2, 300, "/a/alpha", 1, 90), (3, 200, "/b/beta", 0, 20), + (9, 400, "/a/alpha", 0, 40), (10, 800, "/b/beta", 2, 80), (20, 5, "/a/alpha", 0, 0)]) + r = delivery.report(now) + cur, prev = r["all"]["last7"], r["all"]["prev7"] + self.assertEqual((cur["n"], cur["median_s"], prev["n"], prev["median_s"]), (3, 200, 2, 600)) + self.assertAlmostEqual(cur["check_share"], 120 / 600) + self.assertEqual(cur["send_back_deliveries"], 1) + self.assertEqual(r["projects"]["/a/alpha"]["last7"]["median_s"], 200) + self.assertEqual(r["projects"]["/b/beta"]["prev7"]["n"], 1) + out = [] + delivery.cmd_time([], out=out.append) + text = "\n".join(out) + self.assertIn("median 3m20s", text) + self.assertIn("1 of 3", text) + self.assertIn("alpha", text) + js = [] + delivery.cmd_time(["--json"], out=js.append) + self.assertEqual(json.loads(js[0])["all"]["last7"]["n"], 3) + + def test_windows_agree_with_a_simple_reference(self): + rnd = random.Random(11) + now = time.time() + for _ in range(30 * ITERS): + rows = [{"end": delivery._iso(now - rnd.random() * 20 * 86400), "seconds": rnd.random() * 500} for _ in range(rnd.randint(0, 30))] + cur, prev = delivery.windows(rows, now) + ref_cur = [r for r in rows if now - 7 * 86400 <= harvest.epoch(r["end"]) <= now] + ref_prev = [r for r in rows if now - 14 * 86400 <= harvest.epoch(r["end"]) < now - 7 * 86400] + self.assertEqual((sorted(map(id, cur)), sorted(map(id, prev))), (sorted(map(id, ref_cur)), sorted(map(id, ref_prev)))) + + def test_no_data_is_said_plainly(self): + r = self.sisi("time") + self.assertEqual(r.returncode, 0) + self.assertIn("no deliveries recorded", r.stdout) + self.assertIn("no deliveries recorded in the last 7 days", self.sisi("status").stdout) + self.assertEqual(json.loads(self.sisi("time", "--json").stdout)["all"]["last7"]["n"], 0) + + def test_status_shows_the_seven_day_median_and_slow_checks_get_advice(self): + now = time.time() + self.add_rows(now, [(1, 120, "/p", 0, 5), (2, 60, "/p", 0, 5), (3, 600, "/p", 0, 5)]) + self.assertIn("median 2m00s over the last 7 days (3 deliveries)", self.sisi("status").stdout) + for dur in (50, 70): + store.append("results", {"ts": store.now(), "check": "slow-one", "status": "passed", "duration_s": dur, "tier": "fast"}) + store.append("results", {"ts": store.now(), "check": "quick", "status": "passed", "duration_s": 0.5, "tier": "fast"}) + store.append("results", {"ts": store.now(), "check": "mutation", "status": "passed", "duration_s": 300, "tier": "deep"}) + slow = delivery.report(now)["slowest_checks"] + self.assertEqual([x["id"] for x in slow], ["mutation", "slow-one", "quick"]) + self.assertAlmostEqual(slow[1]["mean_s"], 60) + self.assertIn('"tier": "deep"', slow[1]["suggestion"]) + self.assertIn("split", slow[0]["suggestion"]) + + +class ParallelVerifyTests(SisiCase): + def strip(self, results): + return [{k: r[k] for k in ("item", "id", "status", "kind", "rung", "tier")} for r in results] + + def mk(self, parallel=None, serial_ids=()): + cs = [check("a", "sleep 0.5"), check("b", "sleep 0.5; exit 1"), check("c", "sleep 0.5"), + check("d", "sleep 0.5"), check("e", "exit 0"), human("h"), check("slowboy", "sleep 5", timeout_s=0.2)] + cs.append(dict(check("deep1", "sleep 0.1"), tier="deep")) + for c in cs: + if c["id"] in serial_ids: + c["serial"] = True + c = contract(cs, [check("inv", "sleep 0.3")]) + if parallel is not None: + c["parallel"] = parallel + return c + + def test_same_results_in_the_same_order_and_faster(self): + t = time.time() + serial = V.run(self.mk(), self.proj, tiers=("fast", "deep")) + t_serial = time.time() - t + t = time.time() + par = V.run(self.mk(parallel=True), self.proj, tiers=("fast", "deep")) + t_par = time.time() - t + self.assertEqual(self.strip(par), self.strip(serial)) + self.assertEqual([r["id"] for r in par], ["a", "b", "c", "d", "e", "h", "slowboy", "deep1", "inv"]) + self.assertLess(t_par, t_serial - 0.5) + explicit_off = V.run(self.mk(parallel=False), self.proj) + self.assertEqual(self.strip(explicit_off), self.strip(V.run(self.mk(), self.proj))) + + def test_serial_checks_run_alone(self): + log = os.path.join(self.tmp, "log") + def cmd(n): + return "echo start-%s >> %s; sleep 0.3; echo end-%s >> %s" % (n, log, n, log) + cs = [check("p1", cmd("p1")), dict(check("s1", cmd("s1")), serial=True), check("p2", cmd("p2")), + dict(check("s2", cmd("s2")), serial=True)] + res = V.run(dict(contract(cs), parallel=True), self.proj) + self.assertEqual([r["id"] for r in res], ["p1", "s1", "p2", "s2"]) + lines = open(log).read().split() + for n in ("s1", "s2"): # nothing else starts or ends between a serial check's start and end + i = lines.index("start-" + n) + self.assertEqual(lines[i + 1], "end-" + n) + + def test_property_random_contracts_match_serial(self): + rnd = random.Random(3) + for _ in range(6 * ITERS): + cs = [dict(check("c%d" % i, "exit %d" % rnd.choice([0, 0, 1])), **({"serial": True} if rnd.random() < 0.3 else {})) + for i in range(rnd.randint(1, 9))] + c = contract(cs) + serial = V.run(c, self.proj) + par = V.run(dict(c, parallel=True), self.proj) + self.assertEqual(self.strip(par), self.strip(serial)) + + def test_validation_and_cli(self): + self.assertTrue(any("parallel" in e for e in C.validate(dict(contract([check("a", "true")]), parallel="yes")))) + bad = contract([dict(check("a", "true"), serial="x")]) + self.assertTrue(any("serial" in e for e in C.validate(bad))) + self.write_contract(dict(contract([check("a", "true"), check("b", "true")]), parallel=True)) + r = self.sisi("verify", "--json") + self.assertEqual(r.returncode, 0, r.stdout) + self.assertEqual([x["id"] for x in json.loads(r.stdout)["results"]], ["a", "b"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_e2e.py b/tests/test_e2e.py new file mode 100644 index 0000000..183023b --- /dev/null +++ b/tests/test_e2e.py @@ -0,0 +1,37 @@ +import json, os, unittest +from support import * + + +class EndToEnd(SisiCase): + def test_full_flow(self): + for d in (".claude", ".codex", ".config/opencode"): + os.makedirs(os.path.join(self.home, d)) + with open(os.path.join(self.home, ".claude", "settings.json"), "w") as f: + json.dump({"hooks": {"SessionStart": [{"matcher": "*", "hooks": [{"type": "command", "command": "existing"}]}]}}, f) + self.git_init() + self.assertEqual(self.sisi("install").returncode, 0) + doc = self.sisi("doctor").stdout + self.assertIn("claude-code wired", doc) + payload = json.dumps({"session_id": "e2e", "cwd": self.proj, "hook_event_name": "SessionStart", "source": "startup"}) + self.assertEqual(self.sisi("tick", stdin=payload).stdout, "") + stop = json.dumps({"session_id": "e2e", "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False}) + + self.write_contract(contract([check("feature", "test -f %s/done.txt" % self.proj, rung=3)])) + r = self.sisi("gate", stdin=stop) + self.assertEqual(r.returncode, 0) + d = json.loads(r.stdout) + self.assertEqual(d["decision"], "block") + self.assertIn("feature", d["reason"]) + + open(os.path.join(self.proj, "done.txt"), "w").close() + r = self.sisi("gate", stdin=stop) + self.assertEqual((r.returncode, r.stdout), (0, "")) + + out = self.sisi("status").stdout + self.assertIn("contracts verified : 1", out) + self.assertIn("3: 100%", out) + self.assertEqual(self.sisi("uninstall").returncode, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_gate.py b/tests/test_gate.py new file mode 100644 index 0000000..94be718 --- /dev/null +++ b/tests/test_gate.py @@ -0,0 +1,456 @@ +import io, json, os, random, sys, unittest +from unittest import mock +from support import * +from sisi import gate, store + + +class GateBase(SisiCase): + sid = "sess-1" + + def call(self, cwd=None, sid=None, **extra): + """Run the gate in process as the hook would. Returns (action, message).""" + payload = dict({"session_id": sid or self.sid, "cwd": cwd or self.proj, "hook_event_name": "Stop", + "stop_hook_active": False}, **extra) + return gate.decide(payload) + + def hook(self, payload=None, cwd=None): + """Run the real hook command: JSON stdin, stdout, exit code.""" + p = dict({"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop"}, **(payload or {})) + return self.sisi("gate", cwd=cwd, stdin=json.dumps(p)) + + def set_config(self, **gate_cfg): + os.makedirs(self.state, exist_ok=True) + with open(os.path.join(self.state, "config.json"), "w") as f: + json.dump({"gate": gate_cfg}, f) + + +class GateContractTests(GateBase): + def test_pass_allows_with_no_output(self): + self.write_contract(contract([check("ok", "true")])) + r = self.hook() + self.assertEqual((r.returncode, r.stdout), (0, "")) + + def test_fail_blocks_with_claude_format(self): + self.write_contract(contract([check("bad", "echo boom-output >&2; exit 1")])) + r = self.hook() + self.assertEqual(r.returncode, 0) + d = json.loads(r.stdout) + self.assertEqual(d["decision"], "block") + self.assertIn("bad", d["reason"]) + self.assertIn("boom-output", d["reason"]) + + def test_timeout_and_floor_block(self): + self.write_contract(contract([check("slow", "sleep 5", timeout_s=0.2)])) + self.assertEqual(self.call()[0], "block") + self.write_contract(contract([check("m", "true", rung=3, kind="money")])) + a, msg = self.call(sid="other") + self.assertEqual(a, "block") + self.assertIn("floor", msg) + + def test_invalid_contract_blocks(self): + self.write_contract({"id": "x"}) + self.assertEqual(self.call()[0], "block") + + def test_budget_makes_unfinished_checks_timeout(self): + self.set_config(budget_s=0.4) + self.write_contract(contract([check("a", "sleep 3", timeout_s=60), check("b", "true")])) + a, msg = self.call() + self.assertEqual(a, "block") + st = {r["check"]: r["status"] for r in self.results()} + self.assertEqual(st, {"a": "timeout", "b": "timeout"}) # b never ran: counts as timeout + + def test_three_strikes_then_unverified_release_then_reset(self): + self.write_contract(contract([check("bad", "false")])) + self.assertEqual([self.call()[0] for _ in range(3)], ["block"] * 3) + a, msg = self.call() + self.assertEqual(a, "allow") + self.assertIn("UNVERIFIED", msg) + self.assertEqual(self.results()[-1]["status"], "unverified") + out = self.hook() # after release the count restarts: blocks again + self.assertEqual(json.loads(out.stdout)["decision"], "block") + + def test_unverified_release_is_printed(self): + self.write_contract(contract([check("bad", "false")])) + for _ in range(3): + self.hook() + r = self.hook() + self.assertIn("UNVERIFIED", json.loads(r.stdout)["systemMessage"]) + + def test_pass_resets_count(self): + self.write_contract(contract([check("c", "test -f %s/ok" % self.tmp)])) + self.call(); self.call() + open(os.path.join(self.tmp, "ok"), "w").close() + self.assertEqual(self.call()[0], "allow") + os.remove(os.path.join(self.tmp, "ok")) + self.assertEqual([self.call()[0] for _ in range(3)], ["block"] * 3) # fresh three strikes + + def test_strikes_are_per_session(self): + self.write_contract(contract([check("bad", "false")])) + for _ in range(3): + self.call(sid="a") + self.assertEqual(self.call(sid="b")[0], "block") + + def test_stop_hook_active_does_not_bypass(self): + self.write_contract(contract([check("bad", "false")])) + self.assertEqual(self.call(stop_hook_active=True)[0], "block") + + def test_disabled_allows(self): + self.set_config(enabled=False) + self.write_contract(contract([check("bad", "false")])) + self.assertEqual(self.call()[0], "allow") + + def test_contract_found_from_subdir_up_to_git_root(self): + self.git_init() + self.write_contract(contract([check("bad", "false")])) + sub = os.path.join(self.proj, "x", "y") + os.makedirs(sub) + self.assertEqual(self.call(cwd=sub)[0], "block") + + +class GateFailOpenTests(GateBase): + def test_internal_error_allows_and_logs(self): + self.write_contract(contract([check("bad", "false")])) + with mock.patch.object(gate, "decide", side_effect=RuntimeError("kaboom")), \ + mock.patch.object(sys, "stdin", io.StringIO("{}")), mock.patch.object(sys, "stdout", io.StringIO()) as out: + self.assertEqual(gate.main(), 0) + self.assertEqual(out.getvalue(), "") + with open(os.path.join(self.state, "errors.log")) as f: + self.assertIn("kaboom", f.read()) + + def test_unwritable_state_allows(self): + self.write_contract(contract([check("bad", "false")])) + os.makedirs(self.state, exist_ok=True) + open(os.path.join(self.state, "sessions"), "w").close() # session records can no longer be written + r = self.hook() + self.assertEqual((r.returncode, r.stdout), (0, "")) + + def test_garbage_stdin_allows(self): + r = self.sisi("gate", stdin="not json") + self.assertEqual((r.returncode, r.stdout), (0, "")) + r = self.sisi("gate", stdin="") + self.assertEqual((r.returncode, r.stdout), (0, "")) + + def test_corrupt_session_and_config_files(self): + os.makedirs(os.path.join(self.state, "sessions")) + with open(os.path.join(self.state, "sessions", "sess-1.json"), "w") as f: + f.write("{{{") + with open(os.path.join(self.state, "config.json"), "w") as f: + f.write("nope") + self.write_contract(contract([check("bad", "false")])) + self.assertEqual(self.hook().returncode, 0) + + +class GateNoContractTests(GateBase): + def start(self, sid=None): + self.sisi("tick", stdin=json.dumps({"session_id": sid or self.sid, "cwd": self.proj, "source": "startup"})) + + def grow(self, n_lines=0, n_files=1): + for i in range(n_files): + with open(os.path.join(self.proj, "f%d.txt" % i), "w") as f: + f.write("x\n" * (n_lines // max(n_files, 1) + 1)) + + def test_not_a_git_repo_allows(self): + self.grow(500, 5) + self.assertEqual(self.call()[0], "allow") + + def test_small_change_allows(self): + self.git_init(); self.start() + self.grow(10, 1) + self.assertEqual(self.call()[0], "allow") + + def test_many_files_blocks(self): + self.git_init(); self.start() + self.grow(4, 5) + self.assertEqual(self.call()[0], "block") + + def test_preexisting_dirt_does_not_count(self): + self.git_init() + self.grow(500, 6) + self.start() + self.assertEqual(self.call()[0], "allow") + with open(os.path.join(self.proj, "new.txt"), "w") as f: + f.write("y\n" * 100) + self.assertEqual(self.call()[0], "block") + + def test_committed_growth_still_counts(self): + self.git_init(); self.start() + self.grow(100, 1) + subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "c"], cwd=self.proj, check=True) + self.assertEqual(self.call()[0], "block") + + def test_waive_allows_and_records(self): + self.git_init(); self.start() + self.grow(100, 1) + r = self.sisi("contract", "waive", "typo fix") + self.assertEqual(r.returncode, 0) + self.assertEqual(self.call()[0], "allow") + w = store.read("waivers") + self.assertEqual(w[0]["reason"], "typo fix") + self.assertIn("project", w[0]) + + def test_waiver_before_session_does_not_count(self): + self.git_init() + self.sisi("contract", "waive", "old") + w = store.read("waivers") + w[0]["ts"] = "2000-01-01T00:00:00Z" + os.remove(os.path.join(self.state, "waivers.jsonl")) + store.append("waivers", w[0]) + self.start(); self.grow(100, 1) + self.assertEqual(self.call()[0], "block") + + def test_contract_created_after_block_is_enforced(self): + self.git_init(); self.start(); self.grow(100, 1) + self.call() + self.write_contract(contract([check("bad", "false")])) + self.assertEqual(self.call()[0], "block") + + +class GatePropertyTests(GateBase): + """The gate cannot be passed with a failing, timed-out or unrun check short of the 3-strike release.""" + + CMDS = [("true", 0, "passed")] * 3 + [("exit 1", 0, "failed"), ("exit 7", 7, "passed"), ("exit 7", 0, "failed")] \ + + [("sleep 3", 0, "timeout")] * 1 + + def gen(self, rng): + checks, invs, expect_ok = [], [], True + floors = {"money": 2, "parsing": 2, "ui": None} + kinds = {} + for i in range(rng.randint(1, 5)): + kind = rng.choice(["general", "money", "parsing", "ui", "state-machine"]) + if rng.random() < 0.2: + rung = rng.choice([5, 6]) + checks.append(human("h%d" % i, rung, kind)) + kinds.setdefault(kind, []).append(rung) + continue + cmd, exit_, status = rng.choice(self.CMDS) + rung = rng.randint(1, 4) + checks.append(check("c%d" % i, cmd, rung=rung, kind=kind, exit=exit_, timeout_s=0.08)) + kinds.setdefault(kind, []).append(rung) + if status != "passed": + expect_ok = False + for i in range(rng.randint(0, 2)): + cmd, exit_, status = rng.choice(self.CMDS) + invs.append(check("i%d" % i, cmd, exit=exit_, timeout_s=0.08)) + if status != "passed": + expect_ok = False + for kind, rungs in kinds.items(): + if kind in ("money", "parsing", "state-machine") and min(rungs) > 2: + expect_ok = False + if not invs and not any("cmd" in c for c in checks): + expect_ok = False # nothing runnable: the contract is invalid and must not pass + return contract(checks, invs), expect_ok + + def test_generated_contracts(self): + seeds = [0, random.randrange(2**32)] + [random.randrange(2**32) for _ in range(ITERS - 1)] + for seed in seeds: + rng = random.Random(seed) + for n in range(4 * ITERS): + c, expect_ok = self.gen(rng) + sid = "p-%d-%d" % (seed, n) + self.write_contract(c) + with self.subTest(seed=seed, n=n, contract=c): + first = self.call(sid=sid)[0] + self.assertEqual(first, "allow" if expect_ok else "block") + if not expect_ok: + acts = [first] + [self.call(sid=sid)[0] for _ in range(2)] + self.assertEqual(acts, ["block"] * 3) # never passes early + a, msg = self.call(sid=sid) + self.assertEqual(a, "allow") + self.assertIn("UNVERIFIED", msg) + + +class GateUnchangedTreeTests(GateBase): + """Fix 1: a turn that changed nothing is not punished, and not re-checked.""" + + def setUp(self): + super().setUp() + self.git_init() + self.counter = os.path.join(self.tmp, "runs") + + def counting(self, cmd="true"): + return check("c", "echo x >> %s; %s" % (self.counter, cmd)) + + def runs(self): + return len(open(self.counter).read().split()) if os.path.exists(self.counter) else 0 + + def tick(self): + self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"})) + + def edit(self, text="x"): + with open(os.path.join(self.proj, "work.txt"), "a") as f: + f.write(text + "\n") + + def test_unchanged_since_baseline_allows_without_running(self): + self.write_contract(contract([self.counting("false")])) + self.tick() + self.assertEqual(self.call()[0], "allow") + self.assertEqual(self.runs(), 0) + + def test_unchanged_since_last_allow_not_rerun(self): + self.write_contract(contract([self.counting()])) + self.tick() + self.edit() + self.assertEqual(self.call()[0], "allow") + self.assertEqual(self.runs(), 1) + self.assertEqual(self.call()[0], "allow") + self.assertEqual(self.runs(), 1) + self.edit() # a change runs the checks again + self.call() + self.assertEqual(self.runs(), 2) + + def test_unchanged_after_block_keeps_blocking_and_counts_strikes(self): + self.write_contract(contract([self.counting("false")])) + self.tick() + self.edit() + acts = [self.call() for _ in range(3)] + self.assertEqual([a for a, _ in acts], ["block"] * 3) + self.assertEqual(self.runs(), 1) # only the first call ran the checks + self.assertIn("send-back 2 of 3", acts[1][1]) + a, msg = self.call() + self.assertEqual(a, "allow") + self.assertIn("UNVERIFIED", msg) + self.assertEqual(self.call()[0], "allow") # released tree, still unchanged: allowed + + def test_fixing_the_work_reruns(self): + marker = os.path.join(self.proj, "fixed") + self.write_contract(contract([check("c", "test -f %s" % marker)])) + self.tick() + self.edit() + self.assertEqual(self.call()[0], "block") + open(marker, "w").close() + self.assertEqual(self.call()[0], "allow") + + def test_fixing_a_gitignored_contract_reruns(self): + with open(os.path.join(self.proj, ".git", "info", "exclude"), "a") as f: + f.write(".sisi/\n") + self.write_contract(contract([check("c", "false")])) + self.tick() + self.edit() + self.assertEqual(self.call()[0], "block") + self.write_contract(contract([check("c", "true")])) + self.assertEqual(self.call()[0], "allow") + + +class GateTrustTests(GateBase): + """Fix 2: a contract that arrived with a clone is never executed without approval.""" + + def setUp(self): + super().setUp() + self.marker = os.path.join(self.tmp, "ran") + self.write_contract(contract([check("evil", "touch %s; false" % self.marker)]), trusted=False) + + def test_gate_allows_with_one_notice_and_runs_nothing(self): + r = self.hook() + self.assertEqual(r.returncode, 0) + msg = json.loads(r.stdout)["systemMessage"] + self.assertIn("untrusted", msg) + self.assertIn("sisi contract trust", msg) + self.assertEqual(self.hook().stdout, "") # notice only once per session + self.assertFalse(os.path.exists(self.marker)) + + def test_verify_refuses_with_distinct_exit(self): + r = self.sisi("verify") + self.assertEqual(r.returncode, 3) + self.assertIn("untrusted", r.stdout) + self.assertFalse(os.path.exists(self.marker)) + + def test_trust_then_untrust(self): + self.assertEqual(self.sisi("contract", "trust").returncode, 0) + self.assertEqual(json.loads(self.hook().stdout)["decision"], "block") + self.assertTrue(os.path.exists(self.marker)) + os.remove(self.marker) + self.sisi("contract", "untrust") + self.assertEqual(self.sisi("verify").returncode, 3) + self.assertFalse(os.path.exists(self.marker)) + + def test_init_trusts_the_project(self): + d = os.path.join(self.tmp, "other") + os.makedirs(d) + self.sisi("contract", "init", cwd=d) + self.assertEqual(self.sisi("verify", cwd=d).returncode, 1) # ran (placeholder fails), not refused + + def test_trust_follows_realpath(self): + link = os.path.join(self.tmp, "link") + os.symlink(self.proj, link) + self.sisi("contract", "trust", cwd=link) + self.assertEqual(self.sisi("verify").returncode, 1) + + +class GateEmptyContractTests(GateBase): + """Fix 3: a contract with nothing runnable must not pass.""" + + def test_only_human_or_empty_is_invalid_everywhere(self): + for name, c in (("human only", contract([human("h5", 5), human("h6", 6)])), ("empty", contract([]))): + with self.subTest(name): + self.write_contract(c) + r = self.sisi("contract", "check") + self.assertEqual(r.returncode, 1) + self.assertIn("runnable", r.stdout) + self.assertEqual(self.sisi("verify").returncode, 1) + self.assertIn("runnable", self.sisi("verify").stdout) + self.assertEqual(self.call(sid=name)[0], "block") + + def test_waive_is_the_way_out(self): + self.git_init() + self.write_contract(contract([human("h")])) + self.assertEqual(self.call()[0], "block") + + def test_skeleton_is_honest_and_does_not_trap_question_turns(self): + self.git_init() + self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"})) + r = self.sisi("contract", "init") + self.assertIn("SKELETON", r.stdout) + self.assertIn("real command", r.stdout) + self.assertEqual(self.sisi("verify").returncode, 1) + self.assertEqual(self.call()[0], "allow") # nothing changed but the skeleton itself + with open(os.path.join(self.proj, "big.txt"), "w") as f: + f.write("x\n" * 100) + a, msg = self.call() + self.assertEqual(a, "block") # growth rule applies while the contract is still a skeleton + self.assertIn("contract", msg) + + +class GateGrowthTests(GateBase): + """Fix 4: growth without contract keeps blocking like a failing contract.""" + + def setUp(self): + super().setUp() + self.git_init() + self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"})) + + def grow(self, name, n): + with open(os.path.join(self.proj, name), "a") as f: + f.write("x\n" * n) + + def test_blocks_up_to_three_then_unverified(self): + self.grow("a.txt", 100) + self.assertEqual([self.call()[0] for _ in range(3)], ["block"] * 3) + a, msg = self.call() + self.assertEqual(a, "allow") + self.assertIn("UNVERIFIED", msg) + self.assertEqual(self.results()[-1]["status"], "unverified") + self.grow("a.txt", 1) # still over the threshold, still no contract: strikes start again + self.assertEqual(self.call()[0], "block") + + def test_contract_ends_it(self): + self.grow("a.txt", 100) + self.assertEqual(self.call()[0], "block") + self.write_contract(contract([check("c", "true")])) + self.assertEqual(self.call()[0], "allow") + + def test_waiver_covers_tree_at_that_moment_only(self): + self.grow("a.txt", 100) + self.assertEqual(self.call()[0], "block") + self.assertEqual(self.sisi("contract", "waive", "generated file").returncode, 0) + self.assertEqual(self.call()[0], "allow") + self.grow("a.txt", 10) # small growth after the waiver point + self.assertEqual(self.call()[0], "allow") + self.grow("a.txt", 100) # big growth after the waiver point + self.assertEqual(self.call()[0], "block") + self.sisi("contract", "waive", "again") + self.assertEqual(self.call()[0], "allow") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_learn.py b/tests/test_learn.py new file mode 100644 index 0000000..c7701a0 --- /dev/null +++ b/tests/test_learn.py @@ -0,0 +1,492 @@ +import json, os, random, subprocess, sys, time, unittest + +from support import SisiCase, REPO + +from sisi import escapes, groundtruth, harvest, learn_cli, scoreboard, store, taskset + +T0 = harvest.epoch("2026-11-01T10:00:00.000Z") + + +def iso(t): + return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(t)) + + +def rec(typ, t, sid="S1", cwd="/nowhere", sidechain=False, agent=None, **kw): + d = {"parentUuid": None, "isSidechain": sidechain, "type": typ, "timestamp": iso(t), "cwd": cwd, "sessionId": sid, + "entrypoint": "cli", "userType": "external", "gitBranch": "main"} + if agent: + d["agentId"] = agent + d.update(kw) + return json.dumps(d, separators=(",", ":")) + + +def user(t, text, **kw): + return rec("user", t, message={"role": "user", "content": text}, **kw) + + +def asst(t, text=None, tool=None, cmd=None, model="claude-sonnet-5-5", **kw): + blocks = [] + if text is not None: + blocks.append({"type": "text", "text": text}) + if tool: + blocks.append({"type": "tool_use", "id": "tu1", "name": tool, "input": {"command": cmd} if cmd else {}}) + return rec("assistant", t, message={"role": "assistant", "model": model, "content": blocks}, **kw) + + +def tool_result(t, **kw): + return rec("user", t, message={"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu1", "content": "ok"}]}, + toolUseResult={"stdout": "ok"}, **kw) + + +def git(cwd, *args, date=None): + env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@t", GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@t") + if date: + env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = iso(date) + p = subprocess.run(["git"] + list(args), cwd=cwd, env=env, capture_output=True, text=True) + assert p.returncode == 0, p.stderr + return p.stdout.strip() + + +class Fixture(SisiCase): + def projdir(self, name="-home-t-Code-r"): + d = os.path.join(self.home, ".claude", "projects", name) + os.makedirs(d, exist_ok=True) + return d + + def write(self, path, lines, mode="w"): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, mode, encoding="utf-8") as f: + for ln in lines: + f.write(ln + "\n") + + def session(self, sid, lines, proj="-home-t-Code-r"): + p = os.path.join(self.projdir(proj), sid + ".jsonl") + self.write(p, lines) + return p + + def harvest(self): + con = harvest.connect() + st = harvest.run(home=self.home, workers=1, con=con) + return con, st + + def repo(self, name="r"): + d = os.path.join(self.home, "Code", name) + os.makedirs(d) + git(d, "init", "-q", "-b", "main") + return d + + def commit(self, d, fname, t, content="x"): + with open(os.path.join(d, fname), "a") as f: + f.write(content + "\n") + git(d, "add", "-A") + git(d, "commit", "-q", "-m", "c " + fname, date=t) + return git(d, "rev-parse", "HEAD") + + +class TestTypedText(unittest.TestCase): + def test_rule(self): + tt = harvest.typed_text + h = {"type": "user", "message": {"content": "please fix the build"}} + self.assertEqual(tt(h)[0], "please fix the build") + self.assertIsNone(tt({"type": "user", "isMeta": True, "message": {"content": "hi"}})[0]) + self.assertIsNone(tt({"type": "user", "toolUseResult": {}, "message": {"content": "hi"}})[0]) + self.assertIsNone(tt({"type": "user", "message": {"content": [{"type": "tool_result", "content": "x"}]}})[0]) + self.assertIsNone(tt({"type": "user", "origin": {"kind": "task-notification"}, "message": {"content": "x"}})[0]) + self.assertIsNone(tt({"type": "user", "origin": {"kind": "peer"}, "message": {"content": "x"}})[0]) + self.assertEqual(tt({"type": "user", "origin": {"kind": "human"}, "message": {"content": "yo"}})[0], "yo") + for wrapped in ("x", "x", + "x", "This session is being continued from a previous conversation", + "Caveat: x"): + self.assertIsNone(tt({"type": "user", "message": {"content": wrapped}})[0], wrapped) + self.assertIsNone(tt({"type": "user", "isCompactSummary": True, "message": {"content": "summary"}})[0]) + self.assertEqual(tt({"type": "user", "message": {"content": "[Request interrupted by user for tool use]"}}), (None, 0, True)) + self.assertIsNone(tt({"type": "user", "message": {"content": "/clear"}})[0]) + self.assertEqual(tt({"type": "user", "message": {"content": "/xdo it"}})[0], "do it") + txt, pasted, _ = tt({"type": "user", "message": {"content": "look " + "z" * 50 + " now"}}) + self.assertEqual(txt, "look now") + self.assertGreater(pasted, 50) + txt, _, _ = tt({"type": "user", "message": {"content": [{"type": "text", "text": "[Image #1] see this"}, {"type": "image"}]}}) + self.assertEqual(txt, "see this") + self.assertEqual(tt({"type": "user", "message": {"content": [{"type": "text", "text": "[Image #1]"}, {"type": "image"}]}})[0], "") + + def test_queued_command(self): + a = {"type": "queued_command", "commandMode": "prompt", "prompt": "do more", "origin": {"kind": "human"}} + self.assertEqual(harvest.typed_text(a, queued_prompt=a["prompt"])[0], "do more") + b = dict(a, origin={"kind": "task-notification"}) + self.assertIsNone(harvest.typed_text(b, queued_prompt="x")[0]) + + +class TestHeuristics(unittest.TestCase): + def test_machine(self): + self.assertTrue(harvest.machine_reason("You are a worker: do this", None, "cli")[0]) + self.assertTrue(harvest.machine_reason("Act as the design sub-agent for this task.", None, "t3-code")[0]) + self.assertTrue(harvest.machine_reason("x" * 4000, None, "cli")[0]) + self.assertTrue(harvest.machine_reason(None)[0]) + self.assertTrue(harvest.machine_reason("Generate a title that will help the user", None, "sdk-cli")[0]) + self.assertFalse(harvest.machine_reason("Tell me how you work with subagents", None, "cli")[0]) + self.assertFalse(harvest.machine_reason("fix the login bug in app.py please", None, "cli")[0]) + + def test_correction(self): + self.assertTrue(harvest.is_correction("No, that's not what I asked")) + self.assertTrue(harvest.is_correction("it still doesn't work")) + self.assertFalse(harvest.is_correction("great, now add tests")) + self.assertFalse(harvest.is_correction("no" + " blah" * 600)) + + +class TestHarvest(Fixture): + def test_main_vs_subagent_and_counts(self): + proj = self.projdir() + main = [user(T0, "fix the parser bug", cwd="/x"), + asst(T0 + 5, "Which file?"), + user(T0 + 60, "parser.py"), + asst(T0 + 70, tool="Bash", cmd="git commit -am x"), + tool_result(T0 + 71), + asst(T0 + 80, tool="Bash", cmd="sisi verify"), + asst(T0 + 90, tool="AskUserQuestion"), + asst(T0 + 100, "All tests pass. Done."), + user(T0 + 200, "no, that's wrong, it still fails"), + rec("user", T0 + 205, message={"role": "user", "content": "[Request interrupted by user]"}), + asst(T0 + 300, "Fixed it.")] + self.write(os.path.join(proj, "S1.jsonl"), main) + sub = os.path.join(proj, "S1", "subagents", "agent-abc.jsonl") + self.write(sub, [user(T0 + 10, "You are a worker: do X", sid="S1", sidechain=True, agent="abc"), + asst(T0 + 20, "done", sid="S1", sidechain=True, agent="abc", model="claude-haiku-5-5")]) + with open(sub[:-6] + ".meta.json", "w") as f: + json.dump({"agentType": "x", "model": "haiku"}, f) + wf = os.path.join(proj, "S1", "subagents", "workflows", "wf_1234abcd-xx", "agent-zzz.jsonl") + self.write(wf, [user(T0 + 12, "brief two", sid="S1", sidechain=True, agent="zzz")]) + self.write(os.path.join(proj, "S1", "subagents", "workflows", "wf_1234abcd-xx", "journal.jsonl"), ['{"a":1}']) + con, st = self.harvest() + self.assertEqual(st["seen"], 3) + m = con.execute("SELECT * FROM sessions WHERE kind='main'").fetchone() + self.assertEqual(m["id"], "S1") + self.assertEqual(m["user_turns"], 3) + self.assertEqual(m["n_corrections"], 1) + self.assertEqual(m["n_premature_done"], 1) # correction right after a completion claim + self.assertEqual(m["n_interrupts"], 1) + self.assertEqual(m["n_ask"], 1) + self.assertEqual(m["n_question_turns"], 1) + self.assertEqual((m["ran_commit"], m["used_verify"], m["used_contract"]), (1, 1, 0)) + self.assertEqual(m["last_claims_done"], 1) + self.assertEqual(json.loads(m["tools"])["Bash"], 2) + self.assertEqual(m["machine"], 0) + subs = {r["agent_id"]: r for r in con.execute("SELECT * FROM sessions WHERE kind='subagent'")} + self.assertEqual(set(subs), {"abc", "zzz"}) + self.assertEqual(subs["abc"]["parent_id"], "S1") + self.assertEqual(subs["abc"]["user_turns"], 0) + self.assertEqual(json.loads(subs["abc"]["meta"])["model"], "haiku") + self.assertTrue(subs["abc"]["first_message"].startswith("You are a worker")) + msgs = [r["text"] for r in con.execute("SELECT text FROM user_msgs WHERE session_id='S1' ORDER BY idx")] + self.assertEqual(msgs, ["fix the parser bug", "parser.py", "no, that's wrong, it still fails"]) + self.assertEqual(con.execute("SELECT correction FROM user_msgs WHERE idx=2").fetchone()[0], 1) + + def test_incremental(self): + p = self.session("S1", [user(T0, "do a thing please", cwd="/x"), asst(T0 + 5, "ok")]) + con, st = self.harvest() + self.assertEqual((st["parsed"], st["skipped"]), (1, 0)) + con.close() + con, st = self.harvest() + self.assertEqual((st["parsed"], st["skipped"]), (0, 1)) + self.write(p, [user(T0 + 100, "and another thing")], mode="a") + con.close() + con, st = self.harvest() + self.assertEqual((st["parsed"], st["skipped"]), (1, 0)) + self.assertEqual(con.execute("SELECT user_turns FROM sessions").fetchone()[0], 2) + self.assertEqual(con.execute("SELECT COUNT(*) FROM user_msgs").fetchone()[0], 2) + + def test_malformed_lines_never_raise(self): + p = os.path.join(self.projdir(), "S1.jsonl") + with open(p, "wb") as f: + f.write(b"not json at all\n") + f.write(b'{"parentUuid":null,"type":"user","message":{"content":\n') # truncated + f.write(b'{"parentUuid":null,"type":"user","message":null,"timestamp":12}\n') + f.write(b'{"parentUuid":null,"type":"assistant","message":{"content":[1,"x",null]},"timestamp":"garbage"}\n') + f.write(b'\xff\xfe\x00bad bytes\n') + f.write(b'{"parentUuid":null,"type":"attachment","attachment":{"type":"queued_command","prompt":7}}\n') + f.write((user(T0, "a real request here", cwd="/x") + "\n").encode()) + con, st = self.harvest() + self.assertEqual(st["errors"], 0) + self.assertEqual(con.execute("SELECT user_turns FROM sessions").fetchone()[0], 1) + + def test_queued_message_counts_once(self): + att = rec("attachment", T0 + 50, attachment={"type": "queued_command", "prompt": "also do this", "commandMode": "prompt", + "origin": {"kind": "human"}, "timestamp": iso(T0 + 50)}) + note = rec("attachment", T0 + 60, attachment={"type": "queued_command", "prompt": "x", "commandMode": "task-notification", + "origin": {"kind": "task-notification"}}) + self.session("S1", [user(T0, "start the work", cwd="/x"), asst(T0 + 10, tool="Read"), att, note, user(T0 + 51, "also do this")]) + con, _ = self.harvest() + self.assertEqual(con.execute("SELECT user_turns FROM sessions").fetchone()[0], 2) + + +class TestGroundTruth(Fixture): + def test_start_commit_ignores_foreign_refs(self): + d = self.repo() + c1 = self.commit(d, "a", T0 - 7200) + c2 = self.commit(d, "b", T0 - 3600) + # a checkpoint commit made after c2 and before the session, reachable only from refs/t3/... + git(d, "checkout", "-q", "--detach") + c3 = self.commit(d, "ckpt", T0 - 600) + git(d, "update-ref", "refs/t3/x/checkpoints/1", c3) + git(d, "checkout", "-q", "main") + git(d, "reset", "-q", "--hard", c2) + git(d, "update-ref", "-d", "refs/heads/detached") if False else None + self.assertEqual(groundtruth.estimate_start(d, T0), c2) + self.assertEqual(groundtruth.estimate_start(d, T0 - 5000), c1) + self.assertIsNone(groundtruth.estimate_start(d, T0 - 99999)) + # a remote-tracking ref counts + git(d, "update-ref", "refs/remotes/origin/main", c3) + self.assertEqual(groundtruth.estimate_start(d, T0), c3) + + def test_ground_truth_end_to_end(self): + d = self.repo() + with open(os.path.join(d, "justfile"), "w") as f: + f.write("check:\n\techo ok\n") + git(d, "add", "-A") + git(d, "commit", "-q", "-m", "init", date=T0 - 1000) + start = git(d, "rev-parse", "HEAD") + after = self.commit(d, "new.py", T0 + 600) + late = self.commit(d, "late.py", T0 + 12000) # beyond window + 2h + self.session("S1", [user(T0, "add the feature to new.py", cwd=d), asst(T0 + 10, tool="Edit"), asst(T0 + 3000, "ok")], proj="-p1") + con, _ = self.harvest() + groundtruth.run(con, home=self.home, workers=1) + g = con.execute("SELECT * FROM groundtruth WHERE session_id='S1'").fetchone() + self.assertEqual((g["start_commit"], g["start_kind"]), (start, "estimated")) + self.assertEqual([c["sha"] for c in json.loads(g["commits"])], [after]) + self.assertEqual(g["test_cmd"], "just check") + self.assertEqual(g["repo_root"], os.path.realpath(d)) + # sisi's own record makes it exact + store.save_session("S1", {"session_id": "S1", "head": start}) + con.execute("DELETE FROM groundtruth") + groundtruth.run(con, home=self.home, workers=1) + g = con.execute("SELECT * FROM groundtruth WHERE session_id='S1'").fetchone() + self.assertEqual(g["start_kind"], "exact") + + def test_missing_t3_worktree_recovered(self): + d = self.repo("proj") + self.commit(d, "a", T0 - 100) + gone = os.path.join(self.home, ".t3", "worktrees", "proj", "t3-abc") + root, how, _ = groundtruth.resolve_repo(gone, self.home) + self.assertEqual((root, how), (os.path.realpath(d), "t3-worktree-recovery")) + self.assertEqual(groundtruth.resolve_repo(os.path.join(self.home, ".t3", "worktrees", "nothere", "x"), self.home)[0], None) + self.assertEqual(groundtruth.resolve_repo(self.proj, self.home)[1], "not-a-git-repo") + + def test_linked_worktree_resolves_to_main_repo(self): + d = self.repo() + self.commit(d, "a", T0 - 100) + wt = os.path.join(self.tmp, "wt") + git(d, "worktree", "add", "-q", "-b", "t3/x", wt) + self.assertEqual(groundtruth.resolve_repo(wt, self.home)[0], os.path.realpath(d)) + + def test_test_command_detection(self): + d = self.repo() + for name, content, want in (("Cargo.toml", "[package]\n", "cargo test"),): + with open(os.path.join(d, name), "w") as f: + f.write(content) + git(d, "add", "-A") + git(d, "commit", "-q", "-m", "i", date=T0) + self.assertEqual(groundtruth.test_command(d, git(d, "rev-parse", "HEAD"))[0], "cargo test") + e = self.repo("e") + with open(os.path.join(e, "package.json"), "w") as f: + json.dump({"scripts": {"test": "jest"}}, f) + self.assertEqual(groundtruth.test_command(e, None)[0], "npm test") + with open(os.path.join(e, "package.json"), "w") as f: + json.dump({"scripts": {"test": "echo \"Error: no test specified\" && exit 1"}}, f) + self.assertIsNone(groundtruth.test_command(e, None)[0]) + + def test_overlap_detection(self): + d = self.repo() + self.commit(d, "a", T0 - 100) + self.session("A", [user(T0, "task one here", cwd=d), asst(T0 + 10, tool="Edit"), asst(T0 + 1000, "x")], proj="-p") + self.session("B", [user(T0 + 500, "task two here", cwd=d), asst(T0 + 600, tool="Read"), asst(T0 + 700, "x")], proj="-p") + self.session("C", [user(T0 + 50000, "task three here", cwd=d), asst(T0 + 50010, "x")], proj="-p") + con, _ = self.harvest() + groundtruth.run(con, home=self.home, workers=1) + g = {r["session_id"]: r for r in con.execute("SELECT * FROM groundtruth")} + self.assertEqual((g["A"]["overlap_any"], g["A"]["overlap_writers"]), (1, 0)) # B only read + self.assertEqual((g["B"]["overlap_any"], g["B"]["overlap_writers"]), (1, 1)) # A wrote + self.assertEqual(g["C"]["overlap_any"], 0) + + +class TestTaskset(Fixture): + def test_split_is_stable_and_roughly_70_30(self): + ids = ["h-%08x" % random.Random(i).getrandbits(32) for i in range(2000)] + first = {i: taskset.split_of(i) for i in ids} + dev = sum(1 for v in first.values() if v == "dev") / len(ids) + self.assertTrue(0.65 < dev < 0.75, dev) + for i in ids: + self.assertEqual(taskset.split_of(i), first[i]) + + def test_adding_tasks_never_moves_existing(self): + con = harvest.connect() + now = time.time() + existing = {} + rng = random.Random(7) + for round_ in range(5): + for _ in range(40): + tid = "t%d" % rng.getrandbits(40) + taskset._upsert(con, existing, now, id=tid, kind="human", session_id=tid, grade="B", reasons="[]") + existing[tid] = con.execute("SELECT split FROM tasks WHERE id=?", (tid,)).fetchone()[0] + snap = {r["id"]: r["split"] for r in con.execute("SELECT id,split FROM tasks")} + for tid, sp in snap.items(): # re-upserting with another grade keeps the split + taskset._upsert(con, existing, now, id=tid, kind="human", session_id=tid, grade="C", reasons="[]") + after = {r["id"]: r["split"] for r in con.execute("SELECT id,split FROM tasks")} + self.assertEqual(snap, after) + self.assertTrue(all(sp == taskset.split_of(t) for t, sp in after.items())) + + def row(self, **kw): + base = dict(start_kind="estimated", test_cmd="just test", overlap_any=0, overlap_writers=0, n_commits=2, + first_message="please implement the feature in detail", ran_commit=1, tools="{}") + base.update(kw) + return base + + def test_grades(self): + g = lambda **kw: taskset.grade_human(self.row(**kw), self.row(**kw))[0] + self.assertEqual(g(), "A") # no sibling, test command + self.assertEqual(g(start_kind="exact", test_cmd=None), "A") # exact start + self.assertEqual(g(start_kind="exact", test_cmd=None, overlap_any=1, overlap_writers=1), "C") + self.assertEqual(g(overlap_any=1, overlap_writers=1), "B") # estimated, siblings wrote, has tests + self.assertEqual(g(test_cmd=None, overlap_any=1, overlap_writers=0), "B") + self.assertEqual(g(test_cmd=None), "B") # no sibling but no tests: not A + self.assertEqual(g(n_commits=80), "C") + self.assertEqual(g(first_message="continue"), "C") + self.assertEqual(g(ran_commit=0), "C") + self.assertEqual(g(ran_commit=0, tools='{"Edit": 3}'), "A") + + def test_build_end_to_end_with_duplicates(self): + d = self.repo() + with open(os.path.join(d, "justfile"), "w") as f: + f.write("test:\n\ttrue\n") + git(d, "add", "-A") + git(d, "commit", "-q", "-m", "i", date=T0 - 500) + self.commit(d, "n.py", T0 + 400) + msg = "please implement the new feature in n.py" + self.session("S1", [user(T0, msg, cwd=d), asst(T0 + 10, tool="Edit"), asst(T0 + 500, "ok")], proj="-p") + self.session("S2", [user(T0 + 90000, msg, cwd=d), asst(T0 + 90010, tool="Edit"), asst(T0 + 90500, "ok")], proj="-p") + self.session("M1", [user(T0 + 300000, "You are a worker. Do the thing.", cwd=d)], proj="-p") + con, _ = self.harvest() + groundtruth.run(con, home=self.home, workers=1) + r = taskset.build(con, home=self.home) + self.assertEqual(r["human"], 1) # only S1 has following commits; M1 is machine-written + t = taskset.list_tasks(con, kind="human")[0] + self.assertEqual((t["id"], t["grade"], t["test_cmd"]), ("h-S1", "A", "just test")) + split = t["split"] + taskset.build(con, home=self.home) + self.assertEqual(taskset.list_tasks(con, kind="human")[0]["split"], split) + self.assertEqual(taskset.get_task(con, "h-S")["id"], "h-S1") + + def test_ledger_matching(self): + sub = lambda i, t0, t1: {"id": i, "t0": t0, "t1": t1, "names": {"r"}, "classes": {"sonnet"}} + led = lambda i, ts, w="sonnet", m=None, p="r": {"id": i, "ts": ts, "worker": w, "project": p, "outcome": "accepted", "minutes": m} + out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, m=10)]) + self.assertEqual((out["a"][1], out["a"][0]["id"]), ("high", "L1")) + out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, m=90)]) + self.assertEqual(out["a"][1], "medium") + out = taskset.match_ledger([sub("a", T0, T0 + 600), sub("b", T0 + 100, T0 + 650)], [led("L1", T0 + 700)]) + self.assertEqual((out["a"][1], out["a"][0]), ("low", None)) + self.assertEqual(out["b"][1], "low") + out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, w="opencode-go/x")]) + self.assertEqual(out["a"][1], "none") + out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, p="other")]) + self.assertEqual(out["a"][1], "none") + out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 9000)]) + self.assertEqual(out["a"][1], "none") + + +class TestEscapesChecksScoreboard(Fixture): + def results(self, project, t, ok=True, session=None): + return [{"ts": iso(t)[:19] + "Z", "contract": "c", "project": project, "check": "unit", "status": "passed" if ok else "failed", + "run": "r%d" % t, "session": session}] + + def test_escapes(self): + d = self.repo() + self.commit(d, "a", T0 - 100) + self.session("S1", [user(T0, "implement the thing in a", cwd=d), asst(T0 + 100, "All tests pass. Done."), + user(T0 + 200, "no, that's wrong, it still fails"), asst(T0 + 300, "sorry")], proj="-p") + con, _ = self.harvest() + groundtruth.run(con, home=self.home, workers=1) + res = self.results(d, T0 + 120) # attributed by time and project, no session field + out = escapes.find(con, res) + kinds = [e["kind"] for e in out] + self.assertIn("contract-then-correction", kinds) + self.assertIn("premature-done", kinds) + # a failed run is not "verified" + self.assertEqual([e for e in escapes.find(con, self.results(d, T0 + 120, ok=False)) if e["kind"].startswith("contract")], []) + # a correction BEFORE the pass is not an escape + self.assertEqual([e for e in escapes.find(con, self.results(d, T0 + 250)) if e["kind"].startswith("contract")], []) + + def test_fix_session_escape(self): + d = self.repo() + self.commit(d, "a.py", T0 - 100) + self.commit(d, "a.py", T0 + 100) + self.session("S1", [user(T0, "implement the thing in a.py", cwd=d), asst(T0 + 50, tool="Edit"), asst(T0 + 150, "ok")], proj="-p") + c2 = self.commit(d, "a.py", T0 + 86400 * 2, "fix") + self.session("S2", [user(T0 + 86400 * 2 - 100, "the thing in a.py is broken, please fix it", cwd=d), asst(T0 + 86400 * 2 - 50, tool="Edit"), + asst(T0 + 86400 * 2 + 60, "ok")], proj="-p") + con, _ = self.harvest() + groundtruth.run(con, home=self.home, workers=1) + out = escapes.find(con, self.results(d, T0 + 120, session="S1")) + fix = [e for e in out if e["kind"] == "contract-then-fix-session"] + self.assertEqual(len(fix), 1) + self.assertEqual(fix[0]["evidence"]["later_session"], "S2") + + def test_check_stats(self): + rs = [{"check": "a", "status": "passed", "verifier": "v1"} for _ in range(12)] + rs += [{"check": "b", "status": "failed"}, {"check": "b", "status": "timeout"}, {"check": "gate", "status": "unverified"}] + rs += [{"check": "c", "status": "passed", "verifier": "v2"}, "junk"] + st = scoreboard.check_stats(rs) + by = {s["id"]: s for s in st["checks"]} + self.assertTrue(by["a"]["never_seen_failing"]) + self.assertEqual((by["b"]["runs"], by["b"]["failures"], by["b"]["timeouts"]), (2, 1, 1)) + self.assertFalse(by["b"]["never_seen_failing"]) + self.assertFalse(by["c"]["never_seen_failing"]) # too few runs + self.assertNotIn("gate", by) + self.assertEqual({s["id"]: s["runs"] for s in st["verifiers"]}, {"v1": 12, "v2": 1}) + + def test_scoreboard_weeks(self): + w1 = harvest.epoch("2026-11-02T10:00:00.000Z") # Monday of ISO week 45 + w2 = w1 + 7 * 86400 + self.session("S1", [user(w1, "do the first task here", cwd="/x"), asst(w1 + 5, "Done. All tests pass."), + user(w1 + 60, "no, that's wrong"), asst(w1 + 70, tool="Bash", cmd="sisi contract check")], proj="-p") + self.session("S2", [user(w2, "do the second task here", cwd="/x"), asst(w2 + 5, "ok?")], proj="-p") + self.session("M", [user(w2, "You are a worker. Do X.", cwd="/x")], proj="-p") + con, _ = self.harvest() + sb = scoreboard.scoreboard(con) + self.assertEqual(list(sb["weeks"]), ["2026-W45", "2026-W46"]) + a = sb["weeks"]["2026-W45"] + self.assertEqual((a["sessions"], a["turns_per_session"], a["corrections_per_100"], a["contract_share"], a["premature_done_share"]), + (1, 2.0, 50.0, 1.0, 1.0)) + self.assertEqual(sb["weeks"]["2026-W46"]["sessions"], 1) # machine-written session excluded + self.assertEqual(sb["weeks"]["2026-W46"]["questions_per_100"], 100.0) + + +class TestCli(Fixture): + def run_cli(self, *args): + env = dict(os.environ, PYTHONPATH=REPO) + return subprocess.run([sys.executable, "-m", "sisi.learn_cli"] + list(args), capture_output=True, text=True, env=env, cwd=self.proj, timeout=120) + + def test_commands_run(self): + d = self.repo() + self.commit(d, "a", T0 - 100) + self.session("S1", [user(T0, "implement the thing here please", cwd=d), asst(T0 + 100, "ok")], proj="-p") + p = self.run_cli("harvest", "--json", "--workers", "1") + self.assertEqual(p.returncode, 0, p.stderr) + self.assertEqual(json.loads(p.stdout)["transcripts"]["parsed"], 1) + self.assertEqual(json.loads(self.run_cli("harvest", "--json").stdout)["transcripts"]["parsed"], 0) + self.assertEqual(self.run_cli("tasks", "build").returncode, 0) + self.assertEqual(self.run_cli("tasks", "list", "--json").returncode, 0) + self.assertEqual(self.run_cli("tasks", "show", "nope").returncode, 1) + self.assertEqual(self.run_cli("escapes", "--json").returncode, 0) + self.assertEqual(self.run_cli("checks").returncode, 0) + sb = json.loads(self.run_cli("scoreboard", "--json").stdout) + self.assertEqual(sb["weeks"]["2026-W44"]["sessions"], 1) + + def test_register_attaches_commands(self): + import argparse + ap = argparse.ArgumentParser() + learn_cli.register(ap.add_subparsers(dest="cmd")) + for argv in (["harvest"], ["tasks", "build"], ["tasks", "list", "--grade", "A"], ["tasks", "show", "x"], ["escapes"], ["checks"], ["scoreboard", "--json"]): + self.assertTrue(callable(ap.parse_args(argv).func)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_personal.py b/tests/test_personal.py new file mode 100644 index 0000000..2c808b9 --- /dev/null +++ b/tests/test_personal.py @@ -0,0 +1,751 @@ +"""Product and personal data are separate: the overlay, generated rulebook, migration, update, export/import, +install migration, and the property that sisi never writes inside the product.""" +import hashlib, json, os, signal, time, shutil, sqlite3, stat, subprocess, sys, tarfile, unittest, unittest.mock +from support import * +from sisi import lifecycle, overlay, paths, pdata, retro, wiring + +RULES = [("alpha", "Alpha rule", "Do alpha things.\n\nWhy: alpha."), + ("beta", "Beta rule", "Do beta things.\n\nWhy: beta."), + ("gamma", "Gamma rule", "Do gamma things.\n\nWhy: gamma.")] + + +def core_text(rules): + out = ["# test rulebook", "", "Intro line."] + for n, (i, t, b) in enumerate(rules, 1): + out += ["", "## %d. %s {#%s}" % (n, t, i), "", b] + return "\n".join(out) + "\n" + + +def rule_file(title, body): + return "## %s\n\n%s\n" % (title, body) + + +class PersonalCase(SisiCase): + def make_product(self, name, rules=RULES, edit_library=False): + root = os.path.join(self.tmp, name) + os.makedirs(os.path.join(root, "canon")) + for lib in ("verifiers", "done"): # linked (read only) unless the test changes a library file + if edit_library: + shutil.copytree(os.path.join(REPO, lib), os.path.join(root, lib)) + else: + os.symlink(os.path.join(REPO, lib), os.path.join(root, lib)) + self.write_product_core(root, rules) + return root + + def write_product_core(self, root, rules): + with open(os.path.join(root, "canon", "core.md"), "w") as f: + f.write(core_text(rules)) + + def use_product(self, root): + old = (paths.REPO, os.environ.get("SISI_VERIFIERS"), os.environ.get("SISI_DONE")) + paths.REPO = root + os.environ["SISI_VERIFIERS"] = os.path.join(root, "verifiers") + os.environ["SISI_DONE"] = os.path.join(root, "done") + + def undo(): + paths.REPO = old[0] + for k, v in zip(("SISI_VERIFIERS", "SISI_DONE"), old[1:]): + os.environ.pop(k, None) if v is None else os.environ.__setitem__(k, v) + self.addCleanup(undo) + + def setUp(self): + super().setUp() + self.p1 = self.make_product("p1") + self.use_product(self.p1) + + def ok(self, *a, **kw): + r = self.sisi(*a, **kw) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + return r + + def generated(self): + with open(paths.generated()) as f: + return f.read() + + def git_log(self): + return pdata.git("log", "--format=%s").stdout.splitlines() + + def verifier_text(self, id, title="Mine", src="safety/shellcheck"): + with open(os.path.join(REPO, "verifiers", src + ".md")) as f: + t = f.read() + t = t.replace("id: shellcheck", "id: " + id, 1) + return "\n".join("title: " + title if l.startswith("title:") else l for l in t.split("\n")) + + def recipe_text(self, id, title="Mine"): + with open(os.path.join(REPO, "done", "bugfix.md")) as f: + t = f.read() + t = t.replace("id: bugfix", "id: " + id, 1) + return "\n".join("title: " + title if l.startswith("title:") else l for l in t.split("\n")) + + +class OverlayTests(PersonalCase): + def test_first_use_creates_personal_repo(self): + self.ok("build-canon") + self.assertTrue(os.path.isdir(os.path.join(self.data, ".git"))) + self.assertEqual(open(os.path.join(self.data, "VERSION")).read().strip(), str(pdata.FORMAT_VERSION)) + self.assertIn("retro.db", open(os.path.join(self.data, ".gitignore")).read()) + g = self.generated() + self.assertTrue(g.startswith("", "x\r"])) + sep = rng.choice(["\n", "\r\n"]) + text = sep.join(parts) + if parts and rng.random() < 0.6: + text += sep + return text.encode("utf-8") + + +class WiringPropertyTests(WiringBase): + def run_case(self, rng): + md = None if rng.random() < 0.2 else rand_md(rng) + st = None if rng.random() < 0.2 else rand_settings(rng) + if md is not None: + self.put(".claude/CLAUDE.md", md) + if st is not None: + self.put(".claude/settings.json", st) + r = rng.random() + if r < 0.3: + os.makedirs(self.path(".codex")) + elif r < 0.5: + self.put(".codex/AGENTS.md", b"mine\n") + if rng.random() < 0.5: + os.makedirs(self.path(".local", "bin")) + if rng.random() < 0.3: + os.makedirs(self.path(".agents", "skills")) + if rng.random() < 0.3: + os.makedirs(self.path(".config", "opencode")) + before, state0 = snapshot(self.home), self.state_snapshot() + + rc, _ = wiring.install() + self.assertEqual(rc, 0) + after1, st1 = snapshot(self.home), self.state_snapshot() + wiring.install() + self.assertEqual(snapshot(self.home), after1, "install not idempotent (home)") + self.assertEqual(self.state_snapshot(), st1, "install not idempotent (state)") + # everything else survives install + if st is not None and st.strip(): + orig = json.loads(st) + now = json.loads(self.path(".claude/settings.json") and open(self.path(".claude/settings.json"), "rb").read()) + wiring.remove_hooks(now) + + def norm(d): # empty hook lists/objects may legitimately disappear in the structural path + h = d.get("hooks") + if isinstance(h, dict): + d["hooks"] = {k: v for k, v in h.items() if v != []} + if d.get("hooks") in (None, {}): + d.pop("hooks", None) + return d + self.assertEqual(norm(now), norm(orig)) + if md is not None: + self.assertTrue(open(self.path(".claude/CLAUDE.md"), "rb").read().startswith(md)) + self.assertEqual(wiring.doctor()[0]["status"], "wired") + wiring.uninstall() + self.assertEqual(snapshot(self.home), before, "uninstall did not restore the original") + + def test_install_idempotent_and_uninstall_exact(self): + for seed in [0, 1] + [random.randrange(2**32) for _ in range(ITERS + 1)]: + rng = random.Random(seed) + for n in range(10 * ITERS): + with self.subTest(seed=seed, n=n): + shutil.rmtree(self.home, ignore_errors=True) + shutil.rmtree(self.state, ignore_errors=True) + shutil.rmtree(self.data, ignore_errors=True) + os.makedirs(self.path(".claude")) + self.run_case(rng) + + +class WiringTests(WiringBase): + def test_existing_hooks_preserved_in_place(self): + orig = {"hooks": {"SessionStart": [{"matcher": "*", "hooks": [{"type": "command", "command": "keep-me"}]}]}, "x": 1} + self.put(".claude/settings.json", json.dumps(orig, indent=2).encode()) + wiring.install() + d = json.load(open(self.path(".claude/settings.json"))) + self.assertEqual(d["hooks"]["SessionStart"][0], orig["hooks"]["SessionStart"][0]) + cmds = [h["command"] for g in d["hooks"]["SessionStart"] for h in g["hooks"]] + self.assertTrue(any(c.endswith("sisi tick --tool claude-code") for c in cmds)) + self.assertTrue(any(h["command"].endswith("gate --tool claude-code") for g in d["hooks"]["Stop"] for h in g["hooks"])) + self.assertEqual(d["x"], 1) + + def test_import_line_and_marker(self): + wiring.install() + text = open(self.path(".claude/CLAUDE.md")).read() + self.assertIn("", text) + self.assertIn("@" + paths.generated(), text) # the generated rulebook, not the product's file + self.assertNotIn("x\n", text.replace("@", "")) # canon text is not copied + + def test_symlinks_and_conflicts(self): + os.makedirs(self.path(".codex")) + os.makedirs(self.path(".config", "opencode")) + self.put(".config/opencode/AGENTS.md", b"mine\n") + rc, notes = wiring.install() + self.assertTrue(os.path.islink(self.path(".codex/AGENTS.md"))) + self.assertEqual(open(self.path(".config/opencode/AGENTS.md"), "rb").read(), b"mine\n") + self.assertTrue(any("not touched" in n for n in notes)) + self.assertTrue(os.path.islink(self.path(".agents/skills/alpha"))) + self.assertTrue(os.path.islink(self.path(".local/bin/sisi"))) + st = {r["tool"]: r["status"] for r in wiring.doctor()} + self.assertEqual((st["codex"], st["opencode"], st["muse"]), ("wired", "not wired", "not wired")) + wiring.uninstall() + self.assertEqual(open(self.path(".config/opencode/AGENTS.md"), "rb").read(), b"mine\n") + self.assertFalse(os.path.lexists(self.path(".codex/AGENTS.md"))) + + def test_invalid_settings_left_alone(self): + self.put(".claude/settings.json", b"{ not json") + rc, notes = wiring.install() + self.assertEqual(rc, 1) + self.assertEqual(open(self.path(".claude/settings.json"), "rb").read(), b"{ not json") + + def test_backups_made_in_personal_data(self): + self.put(".claude/CLAUDE.md", b"orig") + self.put(".claude/settings.json", b"{}") + wiring.install() + names = os.listdir(os.path.join(self.data, "install", "backups")) + self.assertEqual(len(names), 2) + + def test_doctor_not_wired_then_wired(self): + self.assertEqual(wiring.doctor()[0]["status"], "not wired") + wiring.install() + r = wiring.doctor()[0] + self.assertEqual((r["status"], r["blocking_hook"]), ("wired", "yes (Stop)")) + + def test_uninstall_after_user_edit_keeps_edit(self): + self.put(".claude/settings.json", b'{"a": 1}\n') + wiring.install() + p = self.path(".claude/settings.json") + d = json.load(open(p)); d["b"] = 2 + json.dump(d, open(p, "w"), indent=2) + wiring.uninstall() + self.assertEqual(json.load(open(p)), {"a": 1, "b": 2}) + + def test_cli_install_uses_overridden_home_only(self): + r = self.sisi("install") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertTrue(os.path.islink(self.path(".local/bin/sisi"))) + r = self.sisi("doctor") + self.assertIn("claude-code", r.stdout) + self.assertEqual(self.sisi("uninstall").returncode, 0) + + +class SubagentHookTests(WiringBase): + def test_subagent_stop_registered_idempotent_and_removed(self): + before = snapshot(self.home) + wiring.install() + d = json.load(open(self.path(".claude/settings.json"))) + cmds = [h["command"] for g in d["hooks"]["SubagentStop"] for h in g["hooks"]] + self.assertEqual(len(cmds), 1) + self.assertIn("gate --subagent --tool claude-code", cmds[0]) + self.assertEqual(len(d["hooks"]["Stop"]), 1) # the Stop hook is not duplicated by the subagent one + snap = snapshot(self.home) + wiring.install() + self.assertEqual(snapshot(self.home), snap) + wiring.uninstall() + self.assertEqual(snapshot(self.home), before) + + def test_doctor_notices_a_missing_subagent_hook(self): + wiring.install() + p = self.path(".claude/settings.json") + d = json.load(open(p)) + del d["hooks"]["SubagentStop"] + json.dump(d, open(p, "w")) + r = wiring.doctor()[0] + self.assertEqual(r["status"], "not wired") + self.assertIn("subagent hook", r["detail"]) + self.assertIn("subagent hook", wiring.quick_problem()) + wiring.install() # repairs it + self.assertEqual(wiring.doctor()[0]["status"], "wired") + + +class WiringSafetyTests(WiringBase): + def test_symlinked_settings_and_claude_md_written_through(self): + real = os.path.join(self.tmp, "dotfiles") + os.makedirs(real) + for name, data in (("settings.json", b'{\n "a": 1\n}\n'), ("CLAUDE.md", b"mine")): + with open(os.path.join(real, name), "wb") as f: + f.write(data) + os.symlink(os.path.join(real, name), self.path(".claude", name)) + wiring.install() + for name in ("settings.json", "CLAUDE.md"): + self.assertTrue(os.path.islink(self.path(".claude", name)), name + " link was replaced") + self.assertIn(b"sisi:begin", open(os.path.join(real, "CLAUDE.md"), "rb").read()) + self.assertIn(b"sisi", open(os.path.join(real, "settings.json"), "rb").read()) + wiring.uninstall() + for name in ("settings.json", "CLAUDE.md"): + self.assertTrue(os.path.islink(self.path(".claude", name))) + self.assertEqual(open(os.path.join(real, "CLAUDE.md"), "rb").read(), b"mine") + self.assertEqual(open(os.path.join(real, "settings.json"), "rb").read(), b'{\n "a": 1\n}\n') + + def test_dangling_symlink_refused_and_nothing_changed(self): + os.symlink(os.path.join(self.tmp, "nowhere"), self.path(".claude", "settings.json")) + before = snapshot(self.home) + rc, notes = wiring.install() + self.assertEqual(rc, 1) + self.assertEqual(snapshot(self.home), before) + + def test_invalid_settings_changes_nothing_at_all(self): + os.makedirs(self.path(".codex")) + self.put(".claude/settings.json", b"{ not json") + self.put(".claude/CLAUDE.md", b"keep\n") + before, st = snapshot(self.home), self.state_snapshot() + r = self.sisi("install") + self.assertEqual(r.returncode, 1) + self.assertIn("nothing was changed", r.stdout) + self.assertEqual(snapshot(self.home), before) # no CLAUDE.md edit, no codex link, no ~/.local/bin + self.assertEqual(self.state_snapshot(), st) # no manifest or backups + + def test_unwritable_target_changes_nothing(self): + self.put(".claude/settings.json", b"{}\n") + os.chmod(self.path(".claude/settings.json"), 0o444) + os.chmod(self.path(".claude"), 0o555) + self.addCleanup(os.chmod, self.path(".claude"), 0o755) + if os.access(self.path(".claude/settings.json"), os.W_OK): + self.skipTest("running as a user that ignores permissions") + before = snapshot(self.home) + rc, _ = wiring.install() + self.assertEqual(rc, 1) + self.assertEqual(snapshot(self.home), before) + + def test_hook_command_path_with_spaces(self): + repo = os.path.join(self.tmp, "my repo", "sisi") + shutil.copytree(REPO, repo, ignore=shutil.ignore_patterns(".git", "__pycache__", "tests")) + paths.REPO = repo + wiring.install() + d = json.load(open(self.path(".claude/settings.json"))) + cmd = d["hooks"]["Stop"][0]["hooks"][0]["command"] + self.assertIn("'", cmd) # quoted + snap = snapshot(self.home) + wiring.install() # still recognised as ours: no duplicate entries + self.assertEqual(snapshot(self.home), snap) + self.assertEqual(wiring.doctor()[0]["status"], "wired") + # the command string really runs under a shell + import subprocess + r = subprocess.run(cmd, shell=True, input=json.dumps({"session_id": "s", "cwd": self.proj}), + capture_output=True, text=True, env=dict(os.environ)) + self.assertEqual((r.returncode, r.stdout), (0, "")) + wiring.uninstall() + self.assertFalse(os.path.exists(self.path(".claude/settings.json"))) # it did not exist before install + + +if __name__ == "__main__": + unittest.main() diff --git a/verifiers/completeness/check-tiering.md b/verifiers/completeness/check-tiering.md new file mode 100644 index 0000000..5ea6979 --- /dev/null +++ b/verifiers/completeness/check-tiering.md @@ -0,0 +1,57 @@ +--- +id: check-tiering +title: Fast checks on every change, deep checks before release or on a schedule, with the freshness recorded +answers: Which checks must run now, which run later, and how old is the evidence from the deep ones? +rung: 3 +section: completeness +languages: any +kinds: general +cost: medium +detect: just --version +ran_here: no +verified: docs +--- + +Note: modelled on a reference project, which keeps a table of each +technique, its command, its cost, how often it runs and the date and result of the +last run, and has CI run the heavy ones weekly. Not run here. + +## Use when +- Some checks (mutation testing, long proofs, fuzzing, full end to end) take minutes or hours and cannot run on every edit. +- You want "done" for a small change to be fast and "release" to be thorough, with no confusion over which is which. +- Deep evidence goes stale after code changes and you need to see that. + +## Do not use when +- All checks finish in under a minute. Put them in one gate (`single-gate-command`). + +## Set up +Two commands: `check` (fast, every change) and `deep` (slow, release or schedule). +Keep a table `docs/verification-status.md`: technique, command, cost, cadence, +last run date, commit, result. + +## Minimal example +`docs/verification-status.md`: + + | technique | command | cost | cadence | last run | commit | result | + | clippy, tests | just check | 2 min | every change | CI | HEAD | pass | + | cargo-mutants | just mutants | 2 h | weekly | 2026-11-14 | a1b2c3d | 312 caught, 4 equivalent (see findings-log) | + | kani proofs | just prove | 20 min | before release | 2026-11-20 | e4f5a6b | pass | + +A scheduled workflow (`on: schedule: - cron: "0 3 * * 1"`) runs `just deep`. + +## Run + git rev-list --count a1b2c3d..HEAD -- src/ # commits since the deep evidence + +Passing looks like: the fast set passes on this change, and for each deep +technique the recorded commit is the current one for the code it covers, or the count +of commits since touching that code is zero. If not zero, the deep result is stale: +say "last run at , N commits behind", never "passes". + +## As a contract check + {"id": "deep-evidence-fresh", "claim": "Deep verification was run on the current code, or its age is reported", "kind": "general", "rung": 3, "cmd": "python3 tools/evidence_age.py docs/verification-status.md --max-commits 0", "expect": {"exit": 0}, "timeout_s": 60} + +## What a pass does not prove +That the deep run itself was strong. A date with no commit hash is +unusable, and one hand-edited without running is false evidence: have CI write +the table. Splitting into tiers is only safe if release runs the deep tier; see +`release-gate`. diff --git a/verifiers/completeness/findings-log.md b/verifiers/completeness/findings-log.md new file mode 100644 index 0000000..896c3e3 --- /dev/null +++ b/verifiers/completeness/findings-log.md @@ -0,0 +1,57 @@ +--- +id: findings-log +title: A log of every defect found, rejected mutant and false alarm +answers: What has already been found, tried and ruled out, so I do not repeat or reopen it? +rung: 3 +section: completeness +languages: any +kinds: general +cost: low +detect: +ran_here: no +verified: docs +--- + +Note: no tool. Modelled on a reference project, which records what +each proof and mutation run found, and which survivors were equivalent. Not run here. + +## Use when +- A verification effort spans more than one session, and the next agent must know what the last one covered. +- A tool reports things that are not bugs (an equivalent mutant, a lint you decided to accept, a flaky test cause). Say so once, with the reason. +- You found a real defect: record its id, what caught it, and the regression test. + +## Do not use when +- A single quick check with nothing to carry forward. + +## Set up +Create `docs/findings.md` with a table or dated list. One line per finding. +Fields: date, what, how found (technique id), verdict, evidence, follow-up. + +## Minimal example + | 2026-11-09 | Negative amounts accepted by the engine | kani | defect, fixed | test `rejects_negative_line` | none | + | 2026-11-09 | Mutant `a < b` to `a <= b` in `fees.rs:42` survived | cargo-mutants | equivalent: both branches return the same value when equal | read of lines 40-44 | none | + | 2026-11-10 | `test_sync` fails 1 in 50 | stress-repeat | defect: shared temp dir; fixed | passes 500 runs | none | + +Every "equivalent" or "false alarm" verdict needs the reason, or it is just a +dismissal. Every defect names its regression test. + +## Run + python3 - <<'PY' + import re,sys + rows=[l for l in open("docs/findings.md") if l.startswith("|") and "---" not in l] + bad=[l for l in rows if re.search(r"equivalent|false alarm",l) and len(l.split("|"))<7] + print("rows:",len(rows)); sys.exit(1 if bad else 0) + PY + +Passing looks like: every row is complete and each defect row names a test that +exists (`grep -rn "rejects_negative_line" tests/`). Before starting, read the log for +the area; do not re-triage a recorded equivalent mutant. + +## As a contract check + {"id": "findings-recorded", "claim": "Every defect found has a regression test and every dismissal has a reason", "kind": "general", "rung": 3, "cmd": "python3 tools/findings_lint.py docs/findings.md", "expect": {"exit": 0}, "timeout_s": 30} + +## What a pass does not prove +That the log is complete: only what someone wrote. Keep the real record in the +repository, not the chat. A dismissal can be wrong; give it a date and re-open on a code +change to the area. The log is for the next agent, so write for someone who +saw none of this session. diff --git a/verifiers/completeness/no-stubs-scan.md b/verifiers/completeness/no-stubs-scan.md new file mode 100644 index 0000000..949f66a --- /dev/null +++ b/verifiers/completeness/no-stubs-scan.md @@ -0,0 +1,54 @@ +--- +id: no-stubs-scan +title: Scanning for stubs, skipped tests, commented-out assertions and placeholder data +answers: Is anything still a placeholder, skipped, or switched off in what I am calling finished? +rung: 3 +section: completeness +languages: any +kinds: general +cost: low +detect: git --version +ran_here: yes +verified: ran +--- + +## Use when +- Always before saying "done". An unfinished function that compiles is the most common false finish. +- Tests were added or changed: skipped and `#[ignore]`d tests count as missing. +- You edited tests to get a green run (deleting or commenting an assertion is how a failing test gets quieted). + +## Do not use when +- It is the only check. It finds markers, not missing work with no marker. + +## Set up +Commit `scripts/stubscan.sh`. Tune the pattern to the languages in use. Where a +marker is legitimate (a documented known gap), list the file in the script's +exclusions with a reason, not a blanket `|| true`. + +## Minimal example +`scripts/stubscan.sh`: + + #!/usr/bin/env bash + pat='todo!\(|unimplemented!\(|NotImplementedError|^\s*sorry\b|#\[ignore|@pytest\.mark\.(skip|xfail)|\.skip\(|\bxit\(|t\.Skip\(|^\s*//\s*(assert|expect)|^\s*#\s*assert|lorem ipsum' + if git grep -n -I -E -i -e "$pat" -- . ':!scripts/stubscan.sh' ':!docs'; then exit 1; fi + +`git grep` exits 0 when it finds a match, so a match fails the script. Also look in the diff: +`git diff BASE | grep -E '^-.*(assert|expect)'` lists assertions you removed. +For `unwrap()`/`panic!("not yet")` and `pass`-only bodies, add patterns to taste. + +## Run + bash scripts/stubscan.sh + +Passing looks like: no output, exit 0. Failure (run here) prints file:line for each +`todo!()`, `#[ignore]` and commented assertion, and exits 1. Then also ask: is +there placeholder data (names like `foo`, `test@example.com`, `12345`) in +shipped files, not tests? Grep for it by hand. + +## As a contract check + {"id": "no-stubs", "claim": "No stub markers, skipped tests or commented-out assertions in the tree", "kind": "general", "rung": 3, "cmd": "bash scripts/stubscan.sh", "expect": {"exit": 0}, "timeout_s": 60} + +## What a pass does not prove +A stub written without a marker (`return 0`, an empty `else`) passes. A test that +asserts nothing passes (see `vacuity-check`, `assertion-strength-review`). The +scan checks tracked and untracked files but not ignored ones. Do not weaken the +pattern to get a pass; add a justified exclusion instead. diff --git a/verifiers/completeness/release-gate.md b/verifiers/completeness/release-gate.md new file mode 100644 index 0000000..8915c6d --- /dev/null +++ b/verifiers/completeness/release-gate.md @@ -0,0 +1,58 @@ +--- +id: release-gate +title: One command or workflow that must pass before release +answers: Is this exact build safe to publish, with the right version, notices, full tests and package contents? +rung: 3 +section: completeness +languages: any +kinds: general +cost: medium +detect: just --version +ran_here: no +verified: docs +--- + +Note: modelled on a release workflow in a reference project (tag must +equal the program's version; notices current; packages built on the oldest supported +system; each package inspected for its contents; the release left as a draft). +Not run here. + +## Use when +- You are about to tag, publish a package, push an image or hand over a build. +- A release process has more than two manual steps and one has been missed before. + +## Do not use when +- Nothing is being released. For everyday work use `single-gate-command`. + +## Set up +A script `scripts/release-gate.sh` that the release workflow calls first and fails +fast. Keep publishing a separate step that runs only after the gate. Leave the +release a draft until the owner has tried the package. + +## Minimal example + #!/usr/bin/env bash + set -euo pipefail + ver=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) + [ "${GITHUB_REF_NAME:-v$ver}" = "v$ver" ] || { echo "tag != version $ver" >&2; exit 1; } + scripts/notices.sh --check + just check + cargo package --list | grep -q '^LICENSE' || { echo "LICENSE missing from package" >&2; exit 1; } + cargo package --locked --allow-dirty >/dev/null + git diff --exit-code # nothing the gate regenerated is uncommitted + +## Run + scripts/release-gate.sh + +Passing looks like: exit 0 and each step's own success line. Failure names the step +(`tag != version`, `notices out of date`). Then install the built package on a clean +machine and run it (`packaging-install-upgrade`, `clean-clone-build`); the gate +alone does not do that. Include the changelog entry and the deep tier (`check-tiering`). + +## As a contract check + {"id": "release-gate", "claim": "The release gate passes for the version being released", "kind": "general", "rung": 3, "cmd": "scripts/release-gate.sh", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 3600} + +## What a pass does not prove +That the release works for users. A gate on a developer machine proves little +about a clean one; run it in CI from a fresh clone. A gate someone can skip by +tagging by hand is not a gate: have the workflow trigger on the tag and refuse +to publish unless the gate job passed. diff --git a/verifiers/completeness/requirement-to-check-map.md b/verifiers/completeness/requirement-to-check-map.md new file mode 100644 index 0000000..dd75504 --- /dev/null +++ b/verifiers/completeness/requirement-to-check-map.md @@ -0,0 +1,62 @@ +--- +id: requirement-to-check-map +title: Mapping each sentence of the request to a contract check, and listing what has none +answers: Does every thing the human asked for have a check, and which asks have none? +rung: 3 +section: completeness +languages: any +kinds: general +cost: low +detect: python3 --version +ran_here: no +verified: docs +--- + +Note: no tool; the map is a small file and a script. The script was not run +here as written, only the traceability idea behind it (`spec-traceability`). + +## Use when +- You start non-trivial work from a request in prose and are drafting `.sisi/contract.json` (core rule 1). +- The request is long, or has "and also" clauses that are easy to drop. +- You are about to say "done" and need to show nothing asked for was left out. + +## Do not use when +- The request is a one-line change; just run its check. +- A numbered spec already exists; use `spec-traceability`. + +## Set up +Copy the request into `.sisi/request.md`, one sentence or clause per line, each +tagged `Q1`, `Q2`, and so on. Number them in the order the human wrote them. + +## Minimal example +`.sisi/request.md`: + + Q1 Import the bank CSV into the books. + Q2 Skip rows that are already there. + Q3 Show me what was skipped. + Q4 Keep the old import working. + +In the contract, add `"asks": ["Q1"]` to the check that proves each, or list a +sentence under `"unchecked": {"Q3": "needs the human; screen output"}` with the reason. + +## Run + python3 - <<'PY' + import json,re,sys + q=set(re.findall(r"^(Q\d+)",open(".sisi/request.md").read(),re.M)) + c=json.load(open(".sisi/contract.json")) + have={a for k in c["checks"] for a in k.get("asks",[])}|set(c.get("unchecked",{})) + miss=sorted(q-have); print("no check:",miss or "none"); sys.exit(1 if miss else 0) + PY + +Passing looks like: `no check: none`, exit 0. Failure prints the sentences with no +check, exit 1. Report every `unchecked` entry in the final answer as not verified. + +## As a contract check + {"id": "request-mapped", "claim": "Every sentence of the request maps to a check or a stated reason it has none", "kind": "general", "rung": 3, "cmd": "python3 tools/request_map.py", "expect": {"exit": 0, "stdout_contains": "no check: none"}, "timeout_s": 30} + +## What a pass does not prove +That the check is strong; a Q mapped to a weak check passes. Read the map for +the sentences where the check is only "the command runs". Implicit asks (the +human did not write "do not break the old import") are missing: Q4 above must +be added by you, from the invariants in core rule 3. An `unchecked` list is +honest only if it is reported. diff --git a/verifiers/completeness/single-gate-command.md b/verifiers/completeness/single-gate-command.md new file mode 100644 index 0000000..baaeda8 --- /dev/null +++ b/verifiers/completeness/single-gate-command.md @@ -0,0 +1,59 @@ +--- +id: single-gate-command +title: One project command that runs everything required, so done has one definition +answers: Is there exactly one command whose success means the project's required checks all pass? +rung: 3 +section: completeness +languages: any +kinds: general +cost: low +detect: just --version +ran_here: yes +verified: ran +--- + +Ran here: a two-step `justfile` recipe, failing and then passing. Make works the +same way with a `verify` target. + +## Use when +- A project has several checks (format, lint, tests, dependency audit, notices) and people or agents run a different subset each time. +- You want the contract's required checks, CI and a developer's "am I done" to be the same thing. +- Starting a project: create the gate on day one, while it is small. + +## Do not use when +- Some checks take hours. Put those in the deep tier (`check-tiering`); the gate is the fast set. + +## Set up + # justfile + set shell := ["bash", "-euo", "pipefail", "-c"] + check: + cargo fmt --all --check + cargo clippy --workspace --all-targets -- -D warnings + cargo test --workspace + scripts/stubscan.sh + cargo deny check + +CI must run `just check` and nothing else for the pull-request job, or the two definitions diverge. + +## Minimal example + check: + test "$(cat flag.txt)" = ok + echo "gate passed" + +`just check` with `flag.txt` containing `bad` stops at the first failing line, prints +the line `error: recipe check failed on line 3 with exit code 1` and exits 1; with `ok` it prints `gate passed`, exit 0. + +## Run + just check + +Passing looks like: exit 0, with each step's output visible. just stops at the first failing line. In Make, each line is its own shell and +also stops the recipe, but a multi-line `if` or loop needs `&&` chaining or `.ONESHELL` with `set -e`. Never write `command || true` in the gate. + +## As a contract check + {"id": "gate", "claim": "The project gate command passes", "kind": "general", "rung": 3, "cmd": "just check", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800} + +## What a pass does not prove +Only what the gate contains. The usual rot is a check removed from the recipe, or a +step that exits 0 on failure. Review diffs to the gate file as closely as code, and +ensure a deliberately broken input fails it (check the check). A gate +that is too slow gets skipped; keep the fast set fast. diff --git a/verifiers/completeness/spec-traceability.md b/verifiers/completeness/spec-traceability.md new file mode 100644 index 0000000..3685330 --- /dev/null +++ b/verifiers/completeness/spec-traceability.md @@ -0,0 +1,65 @@ +--- +id: spec-traceability +title: Requirement ids cited by code and tests, with a test that fails on an unknown, uncited or untested id +answers: Is every requirement implemented and tested, and does every cited id exist? +rung: 3 +section: completeness +languages: any +kinds: general, state-machine, money +cost: medium +detect: python3 --version +ran_here: yes +verified: ran +--- + +Modelled on a reference project, where each rule has an id, tests live +under a `spec/` folder keyed by those ids, and a loader test fails when a +claim has no test. The script below was run here on a scratch repository. + +## Use when +- There is a written specification (rules, requirements, invariants) and "all of it is done" must be checkable. +- The request has many separate rules and one is easy to forget. +- A reviewer asks "where is rule R-17 implemented, and what tests it?" + +## Do not use when +- The task is small or has no written requirements. Use `requirement-to-check-map` for the request's sentences. +- Ids would be cited without being exercised. The citation proves a link, not that the test is strong; see `assertion-strength-review`. + +## Set up +Give every requirement a stable id in one file (`spec/requirements.md`, lines +`- R-001: text`). Code cites `implements: R-001` in a comment; each test cites +`covers: R-001`. Never renumber; retire an id with a note. + +## Minimal example +`scripts/spec_trace.py` (standard library, run from the repository root): + + import re, subprocess, sys + ids = set(re.findall(r"^- (R-\d+):", open("spec/requirements.md").read(), re.M)) + files = subprocess.run(["git","ls-files","-co","--exclude-standard","src","tests"], + capture_output=True, text=True, check=True).stdout.split() + impl, cov = set(), set() + for f in files: + t = open(f, errors="ignore").read() + impl |= set(re.findall(r"implements:\s*(R-\d+)", t)) + cov |= set(re.findall(r"covers:\s*(R-\d+)", t)) + bad = [f"unknown id cited: {i}" for i in sorted((impl|cov)-ids)] + bad += [f"{i}: no code cites it" for i in sorted(ids-impl)] + bad += [f"{i}: no test covers it" for i in sorted(ids-cov)] + print("\n".join(bad) or f"ok: {len(ids)} requirements traced") + sys.exit(1 if bad else 0) + +## Run + python3 scripts/spec_trace.py + +Passing looks like: `ok: N requirements traced`, exit 0. Failure lists each problem +(`R-002: no test covers it`, `unknown id cited: R-009`) and exits 1 (run here). + +## As a contract check + {"id": "spec-traced", "claim": "Every requirement id is cited by code and by a test, and every cited id exists", "kind": "general", "rung": 3, "cmd": "python3 scripts/spec_trace.py", "expect": {"exit": 0, "stdout_contains": "requirements traced"}, "timeout_s": 60} + +## What a pass does not prove +That a test citing `covers: R-001` actually checks R-001, or even passes. A +comment is cheap. Strengthen it: the test run must also pass, and the cited test +should fail when the requirement's code is broken (`mutation-on-diff`). Also +count the ids: a spec that was quietly shortened passes, so compare the id count to the +agreed spec in review. diff --git a/verifiers/concurrency/address-and-ub-sanitizers.md b/verifiers/concurrency/address-and-ub-sanitizers.md new file mode 100644 index 0000000..df3c821 --- /dev/null +++ b/verifiers/concurrency/address-and-ub-sanitizers.md @@ -0,0 +1,55 @@ +--- +id: address-and-ub-sanitizers +title: Memory-error and undefined-behaviour detection with ASan, UBSan and MSan +answers: Does my C, C++ or unsafe Rust code read or write bad memory, overflow, or use uninitialised data while the tests run? +rung: 2 +section: concurrency +languages: c, cpp, rust +kinds: general, concurrency +cost: low +detect: cc --version +ran_here: yes +verified: ran +--- + +## Use when +- You changed C, C++ or `unsafe` Rust, FFI, buffers, pointer arithmetic or parsing of untrusted bytes. +- A test crashes only sometimes, or output differs by build mode, which hints at undefined behaviour. +- You want a fast memory-safety check that works on code too heavy for Miri. + +## Do not use when +- The code is safe Rust with no FFI; the compiler already prevents these. +- You need data-race detection; use `thread-sanitizer`. ASan and TSan cannot be combined in one binary. +- MSan on Linux needs clang and an instrumented standard library; skip it if you cannot rebuild dependencies. + +## Set up +- ASan (heap and stack overflow, use-after-free, leaks): `-fsanitize=address -g`. +- UBSan (signed overflow, bad shifts, null deref): `-fsanitize=undefined -fno-sanitize-recover=undefined`, so a finding stops the run with a non-zero exit. +- MSan (uninitialised reads, clang only): `-fsanitize=memory -g`. +- Rust nightly: `RUSTFLAGS="-Zsanitizer=address"` (or `memory`) with `--target `. `memory` also needs `-Zbuild-std`. + +## Minimal example +`a.c`, a heap overflow: + + #include + int main(int argc, char **argv) { int *a = malloc(4 * sizeof(int)); a[argc + 3] = 1; free(a); return 0; } + +Rust, a read one past a vector: + + pub fn read_past_end() -> u8 { let v = vec![1u8, 2, 3]; unsafe { *v.as_ptr().add(3) } } + #[test] fn t() { let _ = read_past_end(); } + +## Run + gcc -fsanitize=address -g a.c -o a && ./a + RUSTFLAGS="-Zsanitizer=address" cargo +nightly test --target x86_64-unknown-linux-gnu --lib + +Passing looks like: exit 0 and no `ERROR: AddressSanitizer` text. Failure prints `ERROR: AddressSanitizer: heap-buffer-overflow ... SUMMARY: ...` and exits 1; UBSan prints `runtime error: signed integer overflow` and, with `-fno-sanitize-recover`, exits 1. MSan prints `use-of-uninitialized-value` and exits 1. + +## As a contract check + {"id": "asan-tests", "claim": "No memory errors under AddressSanitizer in the unit tests", "kind": "general", "rung": 2, "cmd": "RUSTFLAGS=\"-Zsanitizer=address\" cargo +nightly test --target x86_64-unknown-linux-gnu --lib", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900} + +## What a pass does not prove +- It only watches code paths the tests execute. Rung 2 at best; pair with fuzzing to reach more paths. +- ASan misses uninitialised reads; MSan misses overflows; neither covers everything UBSan checks. Run the ones that fit. +- Only instrumented code is checked. A prebuilt library is not. +- Check the check: keep a deliberately bad test (the overflow above) and confirm each sanitizer build fails on it. The sanitizer runtime must be installed, or the build fails to link; a build failure is not a pass. diff --git a/verifiers/concurrency/async-cancellation-safety.md b/verifiers/concurrency/async-cancellation-safety.md new file mode 100644 index 0000000..9e3be51 --- /dev/null +++ b/verifiers/concurrency/async-cancellation-safety.md @@ -0,0 +1,65 @@ +--- +id: async-cancellation-safety +title: Cancellation-safety tests that drop a future at every await point +answers: If this async function is cancelled at any await, does shared state stay consistent? +rung: 2 +section: concurrency +languages: rust, any +kinds: concurrency, state-machine, money +cost: medium +detect: cargo --version +ran_here: yes +verified: ran +--- + +## Use when +- An async function mutates shared state, holds a lock, sends a message or writes a file across more than one `.await`. +- The future may be dropped: `select!`, `timeout`, task abort, client disconnect, request cancellation. +- You changed the order of effects around an await, or added an await in the middle of an update. + +## Do not use when +- The function has no await between related effects; plain tests are enough. +- You need races between tasks, not cancellation of one. Use `shuttle` or `loom`. + +## Set up +No dependency is needed. Drive the future by hand with `Waker::noop()` (stable since Rust 1.85): poll it `k` times, drop it, then assert the invariant. Loop `k` from 1 until the future completes. Each `k` is one await point. In Tokio code, put the same loop on a current-thread runtime with `tokio::time::pause`. + +## Minimal example +`src/lib.rs`. `transfer` debits, awaits, then credits; the test finds the lost money. + + pub async fn transfer(a: &Account, amt: i64) { + *a.from.borrow_mut() -= amt; + yield_now().await; // cancelled here: money vanishes + *a.to.borrow_mut() += amt; + } + fn run_until_dropped>(fut: F, k: usize) -> bool { + let mut fut = std::pin::pin!(fut); + let mut cx = Context::from_waker(Waker::noop()); + for _ in 0..k { if fut.as_mut().poll(&mut cx).is_ready() { return true; } } + false // dropped on return + } + #[test] fn conserved_when_dropped_at_every_await() { + for k in 1..=10 { + let a = Account { from: RefCell::new(100), to: RefCell::new(0) }; + let done = run_until_dropped(transfer(&a, 30), k); + assert_eq!(*a.from.borrow() + *a.to.borrow(), 100, "after {k} polls"); + if done { return; } + } + panic!("never finished"); + } + +`yield_now` is a hand-written future that returns `Pending` once and calls `wake_by_ref`. Fix the bug by crediting and debiting together, or with a drop guard that restores state. + +## Run + cargo test conserved_when_dropped_at_every_await + +Passing looks like: `test result: ok. 1 passed`. Failure shows `assertion failed: ... after 1 polls`, exit 101. + +## As a contract check + {"id": "cancel-safe", "claim": "Invariants hold when transfer is dropped at every await", "kind": "concurrency", "rung": 2, "cmd": "cargo test conserved_when_dropped_at_every_await", "expect": {"exit": 0, "stdout_contains": "1 passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove +- It cancels at poll boundaries of one future in isolation, not with other tasks running between polls. Combine with `shuttle` for that. +- Real I/O futures complete or fail on their own timing; this only tests your own await points with stubbed dependencies. +- The bound on `k` must exceed the real await count, which is why the test panics if it never finishes. +- Check the check: reintroduce the bug and confirm the failure message. diff --git a/verifiers/concurrency/deterministic-simulation.md b/verifiers/concurrency/deterministic-simulation.md new file mode 100644 index 0000000..b0bfb56 --- /dev/null +++ b/verifiers/concurrency/deterministic-simulation.md @@ -0,0 +1,69 @@ +--- +id: deterministic-simulation +title: Deterministic simulation of async and distributed systems (turmoil, madsim) +answers: Does my networked or async system keep working under reordering, delays, partitions and crashes, reproducibly from a seed? +rung: 2 +section: concurrency +languages: rust, any +kinds: concurrency, state-machine +cost: high +detect: cargo --version +ran_here: yes +verified: ran +--- + +## Use when +- The system has several nodes or tasks talking over a network, uses timeouts, retries, leases or elections. +- You need fault tests (partition, delay, restart) that are repeatable, not flaky. +- A bug appeared once in the field and you want to replay it from a seed. + +## Do not use when +- The code is one thread with no I/O; use plain tests. +- You must exercise the real kernel, real sockets or real disks. Simulation replaces them. +- Code under test calls the wall clock or OS randomness directly and cannot be routed through the simulator; it will not be deterministic. + +## Set up +The pattern: all time, network, disk and randomness go through a simulated layer driven by one seed; the same seed gives the same run. Rust options: +- `turmoil` (Tokio hosts, simulated TCP and UDP, partitions): `cargo add turmoil` plus `tokio` with `rt,macros,time`. +- `madsim` (also simulates disk and RPC; swap in `madsim-tokio`; build with `RUSTFLAGS="--cfg madsim"`). Its seed environment variables were not confirmed here; check docs.rs/madsim. +In other languages, copy the pattern: inject a clock, a network and a random source, then run many seeds. + +## Minimal example +`src/main.rs` with turmoil 0.7: + + use std::time::Duration; + use turmoil::{net::{TcpListener, TcpStream}, Builder}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + fn run(seed: u64) -> turmoil::Result { + let mut sim = Builder::new().rng_seed(seed).simulation_duration(Duration::from_secs(60)).build(); + sim.host("server", || async { + let l = TcpListener::bind("0.0.0.0:9000").await?; + loop { let (mut s, _) = l.accept().await?; let mut b = [0u8; 4]; s.read_exact(&mut b).await?; s.write_all(&b).await?; } + }); + sim.client("client", async { + let mut s = TcpStream::connect("server:9000").await?; + s.write_all(b"ping").await?; let mut b = [0u8; 4]; s.read_exact(&mut b).await?; + assert_eq!(&b, b"ping"); + turmoil::partition("client", "server"); + let r = tokio::time::timeout(Duration::from_secs(5), TcpStream::connect("server:9000")).await; + assert!(!matches!(r, Ok(Ok(_))), "connect must fail across a partition"); + turmoil::repair("client", "server"); + Ok(()) + }); + sim.run() + } + fn main() { for seed in 0..20 { run(seed).unwrap_or_else(|e| panic!("seed {seed}: {e}")); } println!("20 seeds ok"); } + +## Run + cargo run + +Passing looks like: `20 seeds ok`, exit 0. Failure panics with the failing seed, exit 101. Re-run just that seed to debug. + +## As a contract check + {"id": "sim-seeds", "claim": "Protocol invariants hold across 20 simulated seeds with a partition", "kind": "concurrency", "rung": 2, "cmd": "cargo run", "expect": {"exit": 0, "stdout_contains": "seeds ok"}, "tier": "deep", "timeout_s": 600} + +## What a pass does not prove +- It samples seeds and faults; rung 2. More seeds and more fault types find more. +- It tests your logic against the simulator's model of the network, not the real one. Simulator gaps (partial writes, clock drift) hide bugs. +- Anything outside the simulated layer is not controlled. If the same seed gives different outcomes, determinism is broken; run one seed twice and compare. +- Check the check: inject a known bug (drop the retry) and confirm some seed fails. diff --git a/verifiers/concurrency/go-race-detector.md b/verifiers/concurrency/go-race-detector.md new file mode 100644 index 0000000..c73413d --- /dev/null +++ b/verifiers/concurrency/go-race-detector.md @@ -0,0 +1,58 @@ +--- +id: go-race-detector +title: Data-race detection in Go with go test -race +answers: Do my goroutines read and write the same variable without synchronisation? +rung: 2 +section: concurrency +languages: go +kinds: concurrency +cost: low +detect: go version +ran_here: no +verified: docs +--- + +## Use when +- You touched goroutines, channels, shared maps or slices, `sync` types or closures that capture loop variables. +- You want a cheap, always-on check in CI for any Go package with concurrency. +- A Go test is flaky and you suspect a race. + +## Do not use when +- You want proof of no races. It sees only races that actually happen in the run. +- Cgo is disabled or no C compiler is installed; the race detector needs both. +- The race is a logic race over properly locked data; it only reports unsynchronised access. + +## Set up +Nothing to install beyond the Go toolchain (and a C compiler on non-macOS). Supported on linux/amd64, arm64, and several other platforms listed in Go's race detector doc. Not checked on this machine: Go is not installed here, so commands come from go.dev/doc/articles/race_detector. + +## Minimal example +`race_test.go`: + + package race + + import ("sync"; "testing") + + func TestCounter(t *testing.T) { + n := 0 + var wg sync.WaitGroup + for i := 0; i < 2; i++ { + wg.Add(1) + go func() { defer wg.Done(); n++ }() // race: use sync/atomic or a mutex + } + wg.Wait() + } + +## Run + go test -race ./... + GORACE="halt_on_error=1 history_size=2" go test -race -count=5 ./... + +Passing looks like: `ok ` lines, exit 0. Failure prints `WARNING: DATA RACE` with the conflicting reads and writes and goroutine creation stacks, and the test fails (`testing.go: race detected during execution of test`); the binary exit status after a race is 66 by default. Add `-count=N` to repeat; the detector is per-run. + +## As a contract check + {"id": "go-race", "claim": "No data race detected across the Go test suite", "kind": "concurrency", "rung": 2, "cmd": "go test -race -count=3 ./...", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900} + +## What a pass does not prove +- Races only on code paths that ran. Execution is 2x to 20x slower and uses 5x to 10x more memory, so some teams run only part of the suite; say which. +- It finds data races, not deadlocks, goroutine leaks, or ordering bugs on synchronised data. +- Build-tagged `//go:build !race` tests are skipped under `-race`; check none hide the test you care about. +- Check the check: introduce the unsynchronised write above and confirm `go test -race` fails. If you add `-run` or a package filter, confirm tests actually ran (`go test -race -v` lists them; `no tests to run` means vacuous). diff --git a/verifiers/concurrency/linearizability-checking.md b/verifiers/concurrency/linearizability-checking.md new file mode 100644 index 0000000..918bb3f --- /dev/null +++ b/verifiers/concurrency/linearizability-checking.md @@ -0,0 +1,57 @@ +--- +id: linearizability-checking +title: Linearizability checking of recorded histories (Porcupine, Knossos) +answers: Can the operations my concurrent or distributed store returned be explained by some one-at-a-time order? +rung: 2 +section: concurrency +languages: go, any +kinds: concurrency, state-machine +cost: high +detect: go version +ran_here: no +verified: docs +--- + +## Use when +- You built a concurrent map, queue, register, lock service or replicated store and claim "it behaves as if operations happen one at a time". +- Individual tests pass but you doubt results seen by concurrent clients. +- You can record, per operation, the call time, the return time, the input and the output. + +## Do not use when +- The claim is a weaker consistency level; model that instead (Jepsen's Elle checks serializability and snapshot isolation). +- You only need to detect data races; use a race detector. +- Operations cannot be timestamped by a single clock source or logical order. + +## Set up +Go: Porcupine, `go get github.com/anishathalye/porcupine`. Clojure: Knossos, used by Jepsen. Not run here: Go is not installed; the API below is from Porcupine's README and pkg.go.dev. Steps: (1) run many concurrent clients against the system with random operations, recording each as an `Operation`; (2) write a sequential model of the object; (3) check the history. + +## Minimal example +A register (put/get) in Go: + + type in struct{ put bool; v int } + model := porcupine.Model{ + Init: func() interface{} { return 0 }, + Step: func(state, input, output interface{}) (bool, interface{}) { + i := input.(in) + if i.put { return true, i.v } + return output.(int) == state.(int), state + }, + } + // history []porcupine.Operation{ {ClientId, Input, Call, Output, Return}, ... } + if !porcupine.CheckOperations(model, history) { t.Fatal("history is not linearizable") } + +`CheckOperationsTimeout(model, history, d)` returns `Ok`, `Illegal` or `Unknown` (timeout). Use `porcupine.Visualize` for an HTML picture of a failure. + +## Run + go test -run TestLinearizable -count=1 ./... + +Passing looks like: the test passes, exit 0, with a non-trivial history (many overlapping operations). Failure is `history is not linearizable` plus the visualisation file. + +## As a contract check + {"id": "linearizable", "claim": "Recorded concurrent histories are linearizable against the register model", "kind": "concurrency", "rung": 2, "cmd": "go test -run TestLinearizable -count=1 ./...", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900} + +## What a pass does not prove +- It checks the histories you generated. Different timing or faults may produce a bad one; run with fault injection and many seeds. Rung 2. +- A model that is too permissive passes anything. Check the check: edit the system to return a stale read and see the history be rejected. +- Weak workloads (one client, few keys, no overlap) pass trivially; assert that operations actually overlap. +- Checking can time out on long histories; `Unknown` is not a pass. Treat it as failure or shorten and partition by key. diff --git a/verifiers/concurrency/lock-order-and-deadlock.md b/verifiers/concurrency/lock-order-and-deadlock.md new file mode 100644 index 0000000..a9dd308 --- /dev/null +++ b/verifiers/concurrency/lock-order-and-deadlock.md @@ -0,0 +1,58 @@ +--- +id: lock-order-and-deadlock +title: Deadlock detection and lock-order checking (parking_lot, Go, Clang) +answers: Can my code deadlock by taking locks in conflicting orders? +rung: 2 +section: concurrency +languages: rust, go, c, cpp +kinds: concurrency +cost: low +detect: cargo --version +ran_here: yes +verified: ran +--- + +## Use when +- Code takes more than one lock, or calls out to user code while holding one. +- A test or service hangs and you suspect a deadlock. +- You changed lock acquisition order, or added a new lock to a module. + +## Do not use when +- A single lock and no callbacks; there is nothing to order. +- You need a guarantee. These tools report deadlocks that happen or conflicts that were seen, not all possible ones; `loom` or `shuttle` explore more orderings. + +## Set up +- Rust: `cargo add parking_lot --features deadlock_detection`, use `parking_lot::Mutex`, and run a checker thread. +- Go: the runtime prints `fatal error: all goroutines are asleep - deadlock!` and exits 2 when every goroutine blocks. Partial deadlocks are not detected; add a test timeout (`go test -timeout 60s`). +- C/C++: ThreadSanitizer reports `lock-order-inversion` (potential deadlock) even if no hang occurred; build with `-fsanitize=thread`. + +## Minimal example +Rust checker thread, started at program or test start: + + std::thread::spawn(|| loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + let d = parking_lot::deadlock::check_deadlock(); + if d.is_empty() { continue; } + for (i, ts) in d.iter().enumerate() { + eprintln!("deadlock #{i}"); + for t in ts { eprintln!("thread {:?}\n{:?}", t.thread_id(), t.backtrace()); } + } + std::process::exit(101); + }); + +A program where two threads lock `a` then `b` and `b` then `a` (with a short sleep between) prints `deadlock #0` with backtraces and exits 101. Without the checker it hangs forever. + +## Run + cargo test # with the checker thread started in the test setup + timeout 120 cargo test + +Passing looks like: tests finish, exit 0. Failure is the `deadlock #N` report and exit 101, or a timeout (exit 124 from `timeout`). + +## As a contract check + {"id": "no-deadlock", "claim": "Test suite finishes with no parking_lot deadlock reported", "kind": "concurrency", "rung": 2, "cmd": "timeout 300 cargo test --features deadlock_detection", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 330} + +## What a pass does not prove +- It detects a deadlock only if the test actually drove the threads into it. Rung 2. A hang with no checker is the failure signal, so always run under a timeout. +- `parking_lot` detection covers its own locks, not `std::sync::Mutex`, channels or async mutexes. +- Go's detector misses deadlocks while any other goroutine is alive (such as an HTTP server). +- Check the check: keep a two-lock inversion test and confirm it fails with the checker on. diff --git a/verifiers/concurrency/loom.md b/verifiers/concurrency/loom.md new file mode 100644 index 0000000..a823900 --- /dev/null +++ b/verifiers/concurrency/loom.md @@ -0,0 +1,71 @@ +--- +id: loom +title: Exhaustive interleaving tests for Rust concurrency with loom +answers: Is there any thread interleaving of this lock-free or shared-state code that breaks my assertion? +rung: 1 +section: concurrency +languages: rust +kinds: concurrency, state-machine +cost: medium +detect: cargo --version +ran_here: yes +verified: ran +--- + +## Use when +- You wrote or changed a small concurrent core: an atomic counter, a lock-free queue, a channel, a mutex-protected state machine, a once-cell. +- A test passes "most of the time" and you need every ordering, not a sample of them. +- The claim is about memory ordering (`Relaxed`, `Acquire`, `Release`) and a stress test cannot show it. + +## Do not use when +- The code is large or does I/O, sleeps, or uses `tokio`; loom's state space explodes. Use `shuttle` for those. +- The code is single-threaded. Use ordinary tests. +- You need to check real `unsafe` memory behaviour; use `miri` as well. + +## Set up +Loom replaces `std::sync`, `std::thread` and atomics with model-checked versions. Gate it behind `--cfg loom` so normal builds are untouched. + + [target.'cfg(loom)'.dependencies] + loom = "0.7" + [lints.rust] + unexpected_cfgs = { level = "warn", check-cfg = ['cfg(loom)'] } + +In the code, import atomics and threads from `loom::` under `#[cfg(loom)]`, from `std::` otherwise. + +## Minimal example +`src/lib.rs`. The counter below has a lost-update bug; loom finds it. Replace load+store with `fetch_add` and it passes. + + #[cfg(loom)] use loom::sync::atomic::{AtomicUsize, Ordering}; + #[cfg(not(loom))] use std::sync::atomic::{AtomicUsize, Ordering}; + pub struct Counter(AtomicUsize); + impl Counter { + pub fn new() -> Self { Counter(AtomicUsize::new(0)) } + pub fn incr(&self) { self.0.fetch_add(1, Ordering::SeqCst); } + pub fn get(&self) -> usize { self.0.load(Ordering::SeqCst) } + } + #[cfg(loom)] + mod loom_tests { + use super::*; use loom::{sync::Arc, thread}; + #[test] fn both_increments_counted() { + loom::model(|| { + let c = Arc::new(Counter::new()); let c2 = c.clone(); + let t = thread::spawn(move || c2.incr()); + c.incr(); t.join().unwrap(); + assert_eq!(c.get(), 2); + }); + } + } + +## Run + RUSTFLAGS="--cfg loom" cargo test --release --lib loom_tests + +Passing looks like: `test result: ok. 1 passed`, exit 0. Failure shows as a panic inside `loom::model` (for the buggy version: `left: 1, right: 2`), exit 101. Set `LOOM_MAX_PREEMPTIONS=3` to bound a slow model. + +## As a contract check + {"id": "loom-counter", "claim": "No interleaving of two incr calls loses an update", "kind": "concurrency", "rung": 1, "cmd": "RUSTFLAGS=\"--cfg loom\" cargo test --release --lib loom_tests", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600} + +## What a pass does not prove +- It covers only the threads, operations and inputs inside the `loom::model` closure. Rung 1 holds within those bounds only. +- With `LOOM_MAX_PREEMPTIONS` set, it is bounded, not exhaustive. +- Code that still uses `std::sync` types is invisible to it. Check every concurrency import is swapped under `cfg(loom)`. +- Check the check: put the bug back (load then store). The test must fail. Also confirm the test ran: a filter that matches nothing prints `0 passed` and exits 0. diff --git a/verifiers/concurrency/miri.md b/verifiers/concurrency/miri.md new file mode 100644 index 0000000..3646bab --- /dev/null +++ b/verifiers/concurrency/miri.md @@ -0,0 +1,62 @@ +--- +id: miri +title: Undefined behaviour and data-race detection for Rust with Miri +answers: Does my unsafe Rust code, or my threaded test, perform undefined behaviour or a data race? +rung: 2 +section: concurrency +languages: rust +kinds: concurrency, general +cost: medium +detect: cargo +nightly miri --version +ran_here: yes +verified: ran +--- + +## Use when +- You wrote or changed `unsafe` code, raw pointers, `transmute`, FFI-free pointer arithmetic or custom `Send`/`Sync` impls. +- A test uses threads and you want data races on non-atomic memory detected. +- You want out-of-bounds, use-after-free, uninitialised reads and aliasing violations reported as errors. + +## Do not use when +- The code does heavy I/O, FFI, or runs long. Miri is 10x to 100x slower and cannot run most foreign code. +- You need to find logic-level races on atomics or locks. Use `loom` or `shuttle`. + +## Set up + rustup toolchain install nightly --component miri + cargo +nightly miri setup + +Pin the nightly in CI so results are reproducible. + +## Minimal example +Two threads write one `u32` without synchronisation: + + use std::thread; + pub struct Racy(*mut u32); + unsafe impl Send for Racy {} + pub fn racy_count() -> u32 { + let mut n = 0u32; + let p = Racy(&mut n); + let h = thread::spawn(move || { let p = p; unsafe { *p.0 += 1 }; }); + unsafe { *(&raw mut n) += 1 }; + h.join().unwrap(); + n + } + #[test] fn counts() { assert_eq!(racy_count(), 2); } + +Plain `cargo test` passes. Miri fails it. Using `AtomicU32` instead makes Miri pass. + +## Run + cargo +nightly miri test + MIRIFLAGS="-Zmiri-many-seeds=0..16" cargo +nightly miri test # vary the thread schedule + MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly miri test # allow clock and file access + +Passing looks like: normal test output, exit 0. Failure shows `error: Undefined Behavior: Data race detected between ...` (or the UB kind), exit 1. + +## As a contract check + {"id": "miri-ub", "claim": "No undefined behaviour or data race in the unit tests under Miri", "kind": "concurrency", "rung": 2, "cmd": "cargo +nightly miri test --lib", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800} + +## What a pass does not prove +- Miri checks only executions the tests perform, on one schedule per seed. Use `-Zmiri-many-seeds` to sample more; it is still sampling, rung 2. +- It checks the Rust abstract machine, not hardware memory models in full. +- Tests that cannot run under Miri (FFI, some syscalls) are skipped or fail; do not mark them `#[cfg_attr(miri, ignore)]` without saying so. +- Check the check: introduce a known UB (read past a `Vec`'s end) and confirm Miri errors. Reduce proptest or loop counts under Miri (for example `PROPTEST_CASES=4`) so it finishes; say you did. diff --git a/verifiers/concurrency/shuttle.md b/verifiers/concurrency/shuttle.md new file mode 100644 index 0000000..9bcfb2a --- /dev/null +++ b/verifiers/concurrency/shuttle.md @@ -0,0 +1,61 @@ +--- +id: shuttle +title: Randomised schedule testing for Rust concurrency with shuttle +answers: Does my concurrent or async Rust code hold its invariants across many different thread schedules? +rung: 2 +section: concurrency +languages: rust +kinds: concurrency, state-machine +cost: medium +detect: cargo --version +ran_here: yes +verified: ran +--- + +## Use when +- The concurrent code is too large for `loom` to explore exhaustively, but you want schedule control and replay. +- You need a failing schedule you can replay exactly, which a plain stress test cannot give. +- You want to test code built on `std::sync`, `std::thread` or futures with a controlled scheduler. + +## Do not use when +- The component is small enough for `loom`; exhaustive is stronger. +- The bug is in memory ordering. Shuttle models sequentially consistent execution, not weak memory. +- The code uses real I/O or wall-clock time; shuttle cannot control them. + +## Set up +Add `shuttle` as a dev-dependency and have the code under test use `shuttle::sync` and `shuttle::thread` (via a `cfg` switch or a small facade module). + + cargo add --dev shuttle + +## Minimal example +A lost-update bug; shuttle finds it within a few schedules. + + #[cfg(test)] + mod tests { + use shuttle::sync::{atomic::{AtomicUsize, Ordering}, Arc}; + use shuttle::thread; + fn body() { + let n = Arc::new(AtomicUsize::new(0)); let n2 = n.clone(); + let t = thread::spawn(move || { let v = n2.load(Ordering::SeqCst); n2.store(v + 1, Ordering::SeqCst); }); + let v = n.load(Ordering::SeqCst); n.store(v + 1, Ordering::SeqCst); + t.join().unwrap(); + assert_eq!(n.load(Ordering::SeqCst), 2); + } + #[test] fn random_schedules() { shuttle::check_random(body, 1000); } + } + +Use `fetch_add` to fix it. Other entry points: `shuttle::check_pct(body, iters, depth)` and `shuttle::check_dfs(body, Some(max_iters))`. + +## Run + cargo test random_schedules + +Passing looks like: `test result: ok. 1 passed`, exit 0. Failure prints `failing schedule:` followed by a string, then the panic; exit 101. Replay it with `shuttle::replay(body, "")` to debug deterministically. + +## As a contract check + {"id": "shuttle-schedules", "claim": "Invariant holds across 1000 random schedules", "kind": "concurrency", "rung": 2, "cmd": "cargo test random_schedules", "expect": {"exit": 0, "stdout_contains": "1 passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove +- It samples schedules. Rung 2 at best; a rare interleaving can be missed. Raise the iteration count and use `check_pct` for deeper bugs. +- It models sequential consistency only, so weak-memory bugs pass. +- Only code using shuttle's types is controlled. A stray `std::sync::Mutex` is not. +- Check the check: reinstate the bug and see `failing schedule`. Confirm the test name matched (`1 passed`, not `0 passed`). diff --git a/verifiers/concurrency/stress-repeat.md b/verifiers/concurrency/stress-repeat.md new file mode 100644 index 0000000..7404080 --- /dev/null +++ b/verifiers/concurrency/stress-repeat.md @@ -0,0 +1,49 @@ +--- +id: stress-repeat +title: Repeated and randomised-timing runs of concurrent tests +answers: Does this concurrent test keep passing when I run it many times under different timing? +rung: 3 +section: concurrency +languages: any +kinds: concurrency +cost: low +detect: +ran_here: no +verified: docs +--- + +## Use when +- It is the only affordable check, and the code is too big for `loom`, `shuttle` or simulation. +- You are hunting a flaky failure and need to make it reproduce often enough to diagnose. +- As an extra layer beside a stronger check: run the same test with a race detector, sanitizer or Miri in a loop. + +## Do not use when +- You can write an exhaustive or schedule-controlled test. Those find bugs repetition misses. +- You want to conclude the code is correct. Passing 1,000 runs only shows it did not fail in 1,000 runs. + +## Set up +No special tooling. Tools that help: +- Rust: a shell loop around `cargo test`, and `cargo test -- --test-threads=1` versus the default to change contention. +- Go: `go test -count=N -race -cpu=1,2,4,8 -shuffle=on`. +- Any: a shell loop, `taskset -c 0` to confine to one CPU, a parallel CPU burner (`stress-ng --cpu 8`) to perturb timing, and random `sleep` or `yield` jitter injected in test hooks. + +## Minimal example + for i in $(seq 1 200); do + cargo test --release my_concurrent_test || { echo "FAILED on run $i"; exit 1; } + done + +Go: `go test -race -count=200 -cpu=1,4 -run TestQueue ./queue`. + +## Run +Use the loop above, with stderr kept so a failing run's output is not lost. + +Passing looks like: every run exits 0 and the loop ends silently. Failure is the first non-zero exit with the run number; keep its output. + +## As a contract check + {"id": "stress-queue", "claim": "queue test passes 200 repeated runs under CPU contention", "kind": "concurrency", "rung": 3, "cmd": "for i in $(seq 1 200); do cargo test --release queue_concurrent || exit 1; done", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800} + +## What a pass does not prove +- This is a weak check, rung 3. A rare schedule needs luck to occur, and a clean loop says little about it. +- Timing changes between machines. A bug that needs a particular core count or load may never appear on the test machine. +- A filtered name that matches no tests passes every iteration with `0 tests run`; assert that at least one test executed. +- Still worth having when: it can reproduce a known flaky failure, it runs alongside a race detector, or you have no better option and say so in the result. Check the check: it should fail when you add a known race and a short sleep. diff --git a/verifiers/concurrency/thread-sanitizer.md b/verifiers/concurrency/thread-sanitizer.md new file mode 100644 index 0000000..8bb818a --- /dev/null +++ b/verifiers/concurrency/thread-sanitizer.md @@ -0,0 +1,52 @@ +--- +id: thread-sanitizer +title: Data-race detection with ThreadSanitizer (C, C++, Rust, Go) +answers: Do any two threads touch the same memory without synchronisation while my tests run? +rung: 2 +section: concurrency +languages: c, cpp, rust, go +kinds: concurrency +cost: medium +detect: cc --version +ran_here: yes +verified: ran +--- + +## Use when +- You have C, C++ or Rust code (including `unsafe` or FFI) running threads, and Miri cannot run it. +- You want a race check on a real, full-speed test run or integration test. +- You changed locking, atomics or shared buffers. + +## Do not use when +- It is Go: `go test -race` is the same engine, see `go-race-detector`. +- You need exhaustive coverage of orderings. TSan reports races only on paths that actually ran. +- You also need ASan in the same binary; the two cannot be combined. Run them in separate builds. + +## Set up +- C/C++: compile and link with `-fsanitize=thread -g` (gcc or clang), plus `-pthread`. +- Rust: needs nightly and the `rust-src` component, because the standard library must be rebuilt instrumented: + + rustup toolchain install nightly --component rust-src + +## Minimal example +`t.c`, two threads incrementing a global: + + #include + int n = 0; + void *w(void *a) { n++; return 0; } + int main(void) { pthread_t t; pthread_create(&t, 0, w, 0); n++; pthread_join(t, 0); return 0; } + +## Run + clang -fsanitize=thread -g t.c -o t -pthread && ./t + RUSTFLAGS="-Zsanitizer=thread" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu + +Passing looks like: no `WARNING: ThreadSanitizer` text and exit 0. Failure prints `WARNING: ThreadSanitizer: data race` with both stacks and exits 66. For Rust, the harness line can still say `test result: ok` while the process exits 66, so check the exit status, not the text. Pass `--target` explicitly or build scripts get instrumented too. Output may differ between runs; here gcc reported the race on some runs only, clang on the first, so repeat the run. + +## As a contract check + {"id": "tsan-tests", "claim": "No data race reported by ThreadSanitizer in the test suite", "kind": "concurrency", "rung": 2, "cmd": "RUSTFLAGS=\"-Zsanitizer=thread\" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800} + +## What a pass does not prove +- Only races on paths the run exercised, under the schedules that happened. Rung 2 at best. Run it several times. +- It flags data races, not logic races (a check-then-act bug using proper locks is invisible), and not deadlocks. +- Code not built with the flag (a prebuilt C library) is not watched. +- Check the check: keep the racy example in a test, build it the same way, and confirm exit 66. diff --git a/verifiers/design/alloy.md b/verifiers/design/alloy.md new file mode 100644 index 0000000..0ec4515 --- /dev/null +++ b/verifiers/design/alloy.md @@ -0,0 +1,50 @@ +--- +id: alloy +title: Alloy 6 for structural and relational designs +answers: Does my data model or permission scheme allow a state that breaks a rule I care about? +rung: 1 +section: design +languages: any +kinds: general +cost: medium +detect: test -f alloy.jar && java -version +ran_here: yes +verified: ran +--- + +## Use when +- The design is about relations: who owns what, who may read what, tree and graph shapes, uniqueness and reference rules. +- You want a counterexample drawn for you when a rule can be broken. +- Alloy 6 also has `var` signatures and temporal operators, so small state machines work too. + +## Do not use when +- The state space is large and numeric. Use `tlaplus` or `z3-smt`. +- You need a result for unbounded sizes. Alloy checks up to a scope. + +## Set up +Download `org.alloytools.alloy.dist.jar` from github.com/AlloyTools/org.alloytools.alloy/releases (6.2.0 tried) and save it as `alloy.jar`. Needs Java 17. + +## Minimal example +`perm.als`: +``` +sig User {} +sig Doc { owner: one User, readers: set User } +fact OwnerCanRead { all d: Doc | d.owner in d.readers } +assert OwnerAlwaysReads { all d: Doc | d.owner in d.readers } +check OwnerAlwaysReads for 5 +``` + +## Run +`java -jar alloy.jar exec -f perm.als` + +Passing looks like: the table line `check OwnerAlwaysReads ... UNSAT` (no counterexample within scope 5). Failure looks like `... SAT` on a `check` line. The exit status is 0 in both cases (observed), so a contract must test the text. The table goes to stderr, so redirect with `2>&1` before grepping. Without the `fact` the same run printed `SAT`. Solutions are written to a folder named after the file (`perm/`), including `receipt.json`; `-f` replaces it. + +## As a contract check +```json +{"id": "design-permissions-alloy", "claim": "Within scope 5 every document owner can read their document", "kind": "general", "rung": 1, "cmd": "bash -c \"java -jar alloy.jar exec -f perm.als 2>&1 | grep -E '^[0-9]+\\. check .* UNSAT$'\"", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300} +``` + +## What a pass does not prove +- Only instances up to the scope (here 5 per signature). Small scopes catch most design bugs but not all. +- A `fact` that is too strong can make the model empty, so every check passes. Add a `run` for a realistic case and confirm it is SAT. +- The assertion above restates the fact, so it is trivial; in practice assert a consequence of the rules, not the rule. diff --git a/verifiers/design/lean-executable-model.md b/verifiers/design/lean-executable-model.md new file mode 100644 index 0000000..9394a94 --- /dev/null +++ b/verifiers/design/lean-executable-model.md @@ -0,0 +1,56 @@ +--- +id: lean-executable-model +title: An executable Lean 4 model as the specification and oracle +answers: Does my implementation give the same answers as a small, obviously correct model of what it should do? +rung: 1 +section: design +languages: any +kinds: general, money, state-machine +cost: medium +detect: lean --version +ran_here: yes +verified: ran +--- + +## Use when +- You can write the rules as plain total functions (no I/O, no clever speed tricks) in a few dozen lines. +- You want the same model to be (a) executed as an oracle against the real code and (b) used later for proofs, with `lean4-proofs`. +- The implementation is optimised or in another language, so it needs an independent reference. + +## Do not use when +- The behaviour is mostly I/O, timing or concurrency. Use `tlaplus`. +- Nobody will read Lean; a Python reference model compared by `proof-bridging` or a property test is cheaper. + +## Set up +Install Lean 4 (elan or a release). Keep the model in its own file or a `lake` library (see `lean4-proofs`). Write it with `def`, structures and `Nat`/`Int`; avoid `partial` and `unsafe`, which cannot be reasoned about. + +## Minimal example +`Model.lean` reads `lo hi x` lines from stdin and prints the model's answer: +``` +def clamp (lo hi x : Nat) : Nat := if x < lo then lo else if hi < x then hi else x + +def main : IO Unit := do + let stdin ← IO.getStdin + let mut line ← stdin.getLine + while line != "" do + match (line.trimAscii.toString.splitOn " ").map String.toNat! with + | [lo, hi, x] => IO.println (clamp lo hi x) + | _ => IO.eprintln s!"bad line: {line}" + line ← stdin.getLine +``` +`check.py` feeds every case in a small grid to `lean --run Model.lean` and to the implementation, and asserts the outputs are equal and the counts match (168 cases here). + +## Run +`python3 check.py` + +Passing looks like: exit 0 and the line `168 cases agree with the Lean model`. A disagreement raises an `AssertionError` listing the first differing cases and exits 1. Use `lake exe` and a compiled binary when the case count is large: `lean --run` re-elaborates the file each time. + +## As a contract check +```json +{"id": "design-clamp-oracle", "claim": "clamp agrees with the Lean model on every case in the grid", "kind": "general", "rung": 1, "cmd": "python3 check.py", "expect": {"exit": 0, "stdout_contains": "cases agree"}, "tier": "deep", "timeout_s": 300} +``` + +## What a pass does not prove +- The comparison covers only the inputs you feed it. Over a finite grid this is a differential test (rung 2); it is rung 1 only for the model's own theorems proved in Lean. +- The model can itself be wrong. State a few theorems about it (`lean4-proofs`) and review it against the written requirement. +- Output formatting and parsing in the script are untested glue; keep them dull. diff --git a/verifiers/design/model-coverage.md b/verifiers/design/model-coverage.md new file mode 100644 index 0000000..82756c6 --- /dev/null +++ b/verifiers/design/model-coverage.md @@ -0,0 +1,63 @@ +--- +id: model-coverage +title: Model coverage test: every public operation maps to a model step +answers: Does the implementation have any public operation that the formal model does not describe? +rung: 1 +section: design +languages: any +kinds: state-machine, general +cost: low +detect: +ran_here: yes +verified: ran +--- + +## Use when +- You have a TLA+, Quint, P, Alloy or Lean model and the code can drift from it as operations are added. +- You want a failing test the moment someone adds a public method with no model step. +- You want every deliberate gap written down with a reason. + +## Do not use when +- There is no model; write one first (`tlaplus`, `quint`, `lean-executable-model`). +- The goal is to show the code behaves like the model. This test only checks the names line up; see `lean-executable-model` or replayed traces for behaviour. + +## Set up +Keep a table in the test file: public operation name to model action name, plus an `EXCEPTIONS` table of operations the model deliberately leaves out, each with a reason. Enumerate the real public operations from the code itself (reflection in Python, a macro or `cargo public-api` style listing in Rust, the exports of a module in TypeScript), not from a hand-typed list. + +## Minimal example +```python +import inspect + +class Lock: + def acquire(self): ... + def release(self): ... + def stats(self): ... + def _private(self): ... + +MODEL_STEPS = {"acquire": "Enter", "release": "Leave"} # method -> model action +EXCEPTIONS = {"stats": "read-only, no state change"} # name -> reason +assert len(EXCEPTIONS) == 1 # pinned: growing it needs a review + +public = {n for n, f in inspect.getmembers(Lock, inspect.isfunction) if not n.startswith("_")} +unmapped = public - MODEL_STEPS.keys() - EXCEPTIONS.keys() +stale = (MODEL_STEPS.keys() | EXCEPTIONS.keys()) - public +assert not unmapped, f"public operations with no model step: {sorted(unmapped)}" +assert not stale, f"mapping names a method that no longer exists: {sorted(stale)}" +print("model coverage ok") +``` +Also check that each right-hand name exists in the model file (`grep -q "^Enter" Lock.tla`). + +## Run +`python3 model_coverage.py` (or the project's test runner) + +Passing looks like: exit 0 and `model coverage ok`. Adding `def reset(self)` to `Lock` fails with `public operations with no model step: ['reset']` and exit 1 (observed). Removing a method fails the `stale` check. + +## As a contract check +```json +{"id": "design-model-coverage", "claim": "Every public operation of Lock is mapped to a model step or listed as a justified exception", "kind": "state-machine", "rung": 1, "cmd": "python3 model_coverage.py", "expect": {"exit": 0, "stdout_contains": "model coverage ok"}, "timeout_s": 60} +``` + +## What a pass does not prove +- Names only: a method can be mapped to the wrong action, or do something the action does not allow. Back it with replayed traces or a differential test. +- The pinned exceptions size is a speed bump. A reviewer must read each new exception's reason. +- Operations reachable only through private paths or generated code are missed unless the listing includes them. diff --git a/verifiers/design/p-lang.md b/verifiers/design/p-lang.md new file mode 100644 index 0000000..f9880a4 --- /dev/null +++ b/verifiers/design/p-lang.md @@ -0,0 +1,77 @@ +--- +id: p-lang +title: P language for communicating state machines +answers: Do my message-passing state machines (services, protocols) reach a bad state under any message ordering, drop or crash? +rung: 1 +section: design +languages: any +kinds: state-machine, concurrency +cost: high +detect: p --version +ran_here: no +verified: docs +--- + +## Use when +- The system is several machines exchanging messages (RPC services, replication, workflows) and the bugs depend on message order, loss, or machine failure. +- You want the model to look like code, with events, states and handlers, and to be the basis for tests of the real system. + +## Do not use when +- One machine, few states. Use `tlaplus` or `small-scope-enumeration`. +- You need unbounded proofs. P explores schedules, bounded by search effort. + +## Set up +From the P install page: needs the .NET SDK 8.0 (the docs say P currently requires that specific SDK; check with `dotnet --list-sdks`) and Java 11 or newer (the P compiler uses it; check with `java -version`). Then: + + dotnet tool install --global P # installs `p` into ~/.dotnet/tools; add that to PATH + dotnet tool update --global P # to update + +There is also a Docker image, `ghcr.io/p-org/p:latest`, with .NET, a JDK and the `p` tool. Not run on this machine: only a .NET runtime and no Java are set up here. A project is a `.pproj` XML file: + + + PingPong + ./PSrc/./PSpec/./PTst/ + ./PGenerated/ + + +## Minimal example +`PSrc/Main.p`: a client sends one `Ping`; a server replies `Pong`. `PSpec/Spec.p`: a monitor asserting every ping is eventually answered. `PTst/Test.p`: the test case. Syntax follows the P tutorial (ClientServer); this snippet itself was not compiled here. +``` +// PSrc/Main.p +event Ping: machine; +event Pong; +machine Server { start state Run { on Ping do (c: machine) { send c, Pong; } } } +machine Client { + var s: machine; + start state Init { entry { s = new Server(); send s, Ping, this; goto Wait; } } + state Wait { ignore Pong; } +} +// PSpec/Spec.p +spec PingAnswered observes Ping, Pong { + start state Idle { on Ping goto Waiting; } + hot state Waiting { on Pong goto Idle; } +} +// PTst/Test.p +test tcSingleClient [main=Client]: assert PingAnswered in (union { Client }, { Server }); +``` + +## Run +``` +p compile +p check -tc tcSingleClient -s 1000 +``` +`p compile` finds the `.pproj` in the current directory (`-pp path` otherwise) and builds a .NET dll under `PGenerated/`. `p check` finds the dll; with no `-tc` it prints the list of test cases and an error. `-s N` is the number of schedules to explore (the default is one). The tutorial says about 100,000 schedules typically find most easy bugs. + +Passing looks like: `..... Found 0 bugs.` and `..... Explored 1000 schedules`. A bug prints `Checker found a bug.`, writes traces under `PCheckerOutput/BugFinding/` (a `.txt`, a `.trace.json` and a `.schedule` file that can be replayed) and ends with `Found 1 bug.`. Exit status, from the checker source (`ExitCode.cs`): 0 no bugs, 1 a bug found, 2 an internal error. The docs do not say that the `p` command passes this through unchanged, so verify with a deliberately broken model. + +## As a contract check +```json +{"id": "design-protocol-p", "claim": "No explored schedule of the Ping/Pong machines violates the monitor", "kind": "state-machine", "rung": 1, "cmd": "p compile && p check -tc tcSingleClient -s 1000", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"} +``` +The exit codes come from the checker source and were not run here; confirm that a found bug makes the `p check` step exit 1. + +## What a pass does not prove +- Schedule exploration is bounded (`-s`), so a pass is strong evidence, not proof; P's default random strategy samples schedules rather than enumerating them all. +- Only the modelled failures (drops, crashes) are covered. Only the scenarios in the test cases are explored. +- The model is not the code. +- Not run here; commands come from the P documentation and source. diff --git a/verifiers/design/pluscal.md b/verifiers/design/pluscal.md new file mode 100644 index 0000000..5220018 --- /dev/null +++ b/verifiers/design/pluscal.md @@ -0,0 +1,66 @@ +--- +id: pluscal +title: PlusCal for algorithm-shaped designs, checked with TLC +answers: Does this step-by-step algorithm with several processes keep its invariant under every interleaving? +rung: 1 +section: design +languages: any +kinds: concurrency, state-machine +cost: high +detect: test -f tla2tools.jar && java -version +ran_here: yes +verified: ran +--- + +## Use when +- The design reads like code: processes with sequential steps, shared variables, loops, locks. PlusCal writes that directly and a translator produces the TLA+. +- You want to show a race (lost update, double-spend, check-then-act) exists or does not. +- The reader of the spec is a programmer who would find raw TLA+ actions harder to follow. + +## Do not use when +- The design is a set of independent events rather than processes. Raw `tlaplus` is clearer. +- You need fine control of fairness or refinement. Drop to TLA+. + +## Set up +Same `tla2tools.jar` as `tlaplus` (it contains the translator, `pcal.trans`). Java 11 or newer. + +## Minimal example +`Counter.tla`: two workers each read a shared counter then write it plus one. Each label (`Read:`, `Write:`) is one atomic step. +``` +---- MODULE Counter ---- +EXTENDS Integers +(*--algorithm Counter +variables x = 0; +process w \in 1..2 +variable t = 0; +begin + Read: t := x; + Write: x := t + 1; +end process; +end algorithm; *) +\* BEGIN TRANSLATION +\* END TRANSLATION +BothDone == (\A self \in 1..2 : pc[self] = "Done") => x = 2 +==== +``` +Translate, then write `Counter.cfg` with `SPECIFICATION Spec` and `INVARIANT BothDone`. + +## Run +``` +java -cp tla2tools.jar pcal.trans Counter.tla +java -cp tla2tools.jar tlc2.TLC -config Counter.cfg Counter.tla +``` +Re-run the translator after every edit of the algorithm; TLC checks the generated text, not the comment. + +Passing looks like: exit 0 and `No error has been found`. This example fails on purpose: TLC exits 12 with `Invariant BothDone is violated` and a trace where both workers read 0 (the lost update). Make `Read` and `Write` one label to fix it. + +## As a contract check +```json +{"id": "design-counter-pluscal", "claim": "Two concurrent increments always leave the counter at 2", "kind": "concurrency", "rung": 1, "cmd": "java -cp tla2tools.jar pcal.trans Counter.tla && java -cp tla2tools.jar tlc2.TLC -config Counter.cfg Counter.tla", "expect": {"exit": 0, "stdout_contains": "No error has been found"}, "tier": "deep", "timeout_s": 900} +``` +Note that `pcal.trans` also rewrites `Counter.cfg` if it does not exist; keep your own `.cfg` committed. + +## What a pass does not prove +- Everything under `tlaplus` applies: it checks the model, only the constants in the `.cfg`, and nothing about the code. +- A label is one atomic step. Putting too much in one label hides races; split steps to match what the real code does atomically. +- If the translator is not re-run, TLC checks stale text and the pass means nothing. diff --git a/verifiers/design/quint.md b/verifiers/design/quint.md new file mode 100644 index 0000000..f2240a9 --- /dev/null +++ b/verifiers/design/quint.md @@ -0,0 +1,57 @@ +--- +id: quint +title: Quint specifications with a simulator and Apalache model checker +answers: Can I describe my state machine in a typed, programmer-style language and have a tool explore its states for violations? +rung: 1 +section: design +languages: any +kinds: state-machine, concurrency +cost: medium +detect: quint --version +ran_here: no +verified: docs +--- + +## Use when +- You want the TLA+ style of design check but with types, modules and a syntax close to TypeScript or Rust. +- You want a fast random simulation first (seconds) and an exhaustive bounded check second. +- The team will keep the spec in the repo and edit it; readability and a type checker matter. + +## Do not use when +- You need liveness proofs or the full TLA+ toolbox. Use `tlaplus`. +- The design is relational/structural. Use `alloy`. + +## Set up +`npm install -g @informalsystems/quint` (version 0.34.0 tried). `quint verify` downloads Apalache on first use and needs Java 21 or newer; with Java 17 it fails with `UnsupportedClassVersionError`. + +## Minimal example +`lock.qnt`: +``` +module lock { + var holder: str + action init = holder' = "none" + action enter(p) = all { holder == "none", holder' = p } + action leave = all { holder != "none", holder' = "none" } + action step = any { enter("a"), enter("b"), leave } + val ok = (holder == "none") or (holder == "a") or (holder == "b") +} +``` + +## Run +``` +quint typecheck lock.qnt +quint run lock.qnt --init=init --step=step --invariant=ok --max-samples=200 --max-steps=10 +quint verify lock.qnt --init=init --step=step --invariant=ok +``` +Passing looks like: `typecheck` and `run` exit 0; `run` prints `[ok] No violation found`. A violated invariant prints `[violation] Found an issue`, the states, and exits 1 (seen with `val ok = holder != "b"`). `verify` should exit 0 with `[ok] No violation found`; not run here because Java 21 was unavailable, so that line is unconfirmed. + +## As a contract check +```json +{"id": "design-lock-quint", "claim": "In every run of the lock model, holder is always none, a or b", "kind": "state-machine", "rung": 1, "cmd": "quint verify lock.qnt --init=init --step=step --invariant=ok", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900} +``` +Use `quint run` in the contract only if you accept rung 2, since it samples. + +## What a pass does not prove +- `quint run` is random sampling: rung 2. Only `quint verify` explores exhaustively, and only up to `--max-steps` (default 10). +- It checks the spec, not the code. See `model-coverage`. +- An invariant that is always true is a vacuous pass; confirm a deliberately wrong invariant fails. diff --git a/verifiers/design/small-scope-enumeration.md b/verifiers/design/small-scope-enumeration.md new file mode 100644 index 0000000..2afac9e --- /dev/null +++ b/verifiers/design/small-scope-enumeration.md @@ -0,0 +1,71 @@ +--- +id: small-scope-enumeration +title: Exhaustive enumeration of all states of a small design in plain code +answers: Can I check every reachable state of this small design without learning a spec tool? +rung: 1 +section: design +languages: any +kinds: state-machine, concurrency +cost: low +detect: +ran_here: yes +verified: ran +--- + +## Use when +- The design has a handful of actors and a few values each, so all reachable states fit in memory (thousands to a few million). +- You want a fast check of an invariant in the language the team already uses, run as a normal test. +- TLA+, Quint or Alloy would be more set-up than the design deserves. + +## Do not use when +- The state space grows past what a set can hold; use `tlaplus` (it handles it and gives traces). +- You need liveness (something eventually happens). A plain loop can only check safety easily. + +## Set up +Nothing. Write the state as an immutable value (tuple, frozen dataclass), a `steps(state)` function yielding every next state, and an `invariant(state)` function. Explore with a queue and a `seen` set. + +## Minimal example +`explore.py`, a two-worker lock: +```python +from collections import deque +W = (0, 1) +INIT = (("idle", "idle"), None) # (pc per worker, lock holder) + +def steps(state): + pc, holder = state + for w in W: + if pc[w] == "idle" and holder is None: + yield f"enter{w}", (pc[:w] + ("cs",) + pc[w+1:], w) + if pc[w] == "cs": + yield f"leave{w}", (pc[:w] + ("idle",) + pc[w+1:], None) + +def invariant(state): + pc, holder = state + return sum(p == "cs" for p in pc) <= 1 and (holder is None) == all(p == "idle" for p in pc) + +seen, todo = {INIT}, deque([INIT]) +while todo: + s = todo.popleft() + assert invariant(s), f"invariant broken in {s}" + for _, t in steps(s): + if t not in seen: + seen.add(t); todo.append(t) +assert len(seen) == 3, len(seen) # pin the count: a model change must be noticed +print(f"explored {len(seen)} states, invariant holds") +``` +Do not name the file `enum.py` or any standard-library module name; it shadows the library and breaks imports. + +## Run +`python3 explore.py` + +Passing looks like: exit 0 and `explored 3 states, invariant holds`. A broken design raises an `AssertionError` naming the bad state. Pinned count: if it changes unexpectedly, the model changed. + +## As a contract check +```json +{"id": "design-lock-enumeration", "claim": "Every reachable state of the two-worker lock model satisfies mutual exclusion", "kind": "state-machine", "rung": 1, "cmd": "python3 explore.py", "expect": {"exit": 0, "stdout_contains": "invariant holds"}, "tier": "deep", "timeout_s": 120} +``` + +## What a pass does not prove +- It checks a model written by you, not the code. Link them with `model-coverage` and by replaying paths through the real code. +- Only the sizes enumerated. Try the next size up once; if it blows up, you have learned the limit. +- Safety only. Check that the check can fail: weaken a guard and confirm the assertion fires. diff --git a/verifiers/design/tlaplus.md b/verifiers/design/tlaplus.md new file mode 100644 index 0000000..fd95db2 --- /dev/null +++ b/verifiers/design/tlaplus.md @@ -0,0 +1,64 @@ +--- +id: tlaplus +title: TLA+ model checking of a protocol or state machine with TLC and Apalache +answers: Can my protocol or state machine design reach a bad state in some interleaving of steps? +rung: 1 +section: design +languages: any +kinds: state-machine, concurrency, migration +cost: high +detect: test -f tla2tools.jar && java -version +ran_here: yes +verified: ran +--- + +## Use when +- The design has several actors or steps that can interleave (locks, queues, retries, leader election, migrations) and the bugs live in the orderings. +- You must show "X never happens" (safety) or "Y eventually happens" (liveness) for the design, before or alongside the code. +- A short list of states and steps is enough to describe the behaviour. You can describe it in about 30 lines. + +## Do not use when +- The risk is in arithmetic or data-structure code. Use `kani` or `lean4-proofs`. +- The design is structural (who may read what). Use `alloy`. +- The model would be as big as the code. Use `small-scope-enumeration` in plain code. + +## Set up +Needs Java 11 or newer. Download `tla2tools.jar` from the releases page of github.com/tlaplus/tlaplus and put it in the project. Apalache (symbolic, needs type annotations) is a separate download; `apalache-mc check --config=Lock.cfg --inv=MutualExclusion Lock.tla` (flags from its docs, not run here). + +## Minimal example +`Lock.tla`: +``` +---- MODULE Lock ---- +CONSTANT Procs +VARIABLES pc, lock +vars == <> +Init == pc = [p \in Procs |-> "idle"] /\ lock = "none" +Enter(p) == pc[p] = "idle" /\ lock = "none" /\ lock' = p /\ pc' = [pc EXCEPT ![p] = "cs"] +Leave(p) == pc[p] = "cs" /\ lock' = "none" /\ pc' = [pc EXCEPT ![p] = "idle"] +Next == \E p \in Procs : Enter(p) \/ Leave(p) +Spec == Init /\ [][Next]_vars +MutualExclusion == \A p, q \in Procs : p /= q => ~(pc[p] = "cs" /\ pc[q] = "cs") +==== +``` +`Lock.cfg`: +``` +CONSTANT Procs = {p1, p2} +SPECIFICATION Spec +INVARIANT MutualExclusion +``` + +## Run +`java -cp tla2tools.jar tlc2.TLC -config Lock.cfg Lock.tla` + +Passing looks like: exit 0 and the line `Model checking completed. No error has been found.` Failure: exit 12 and `Invariant MutualExclusion is violated.` followed by the trace of states. (Checked: removing the `lock = "none"` guard from `Enter` produced exactly that.) + +## As a contract check +```json +{"id": "design-lock-model", "claim": "No interleaving of Enter and Leave puts two processes in the critical section", "kind": "state-machine", "rung": 1, "cmd": "java -cp tla2tools.jar tlc2.TLC -config Lock.cfg Lock.tla", "expect": {"exit": 0, "stdout_contains": "No error has been found"}, "tier": "deep", "timeout_s": 900} +``` + +## What a pass does not prove +- It proves the model, not the code. Pair it with `model-coverage` and tests that replay model traces against the code. +- It covers only the constants in the `.cfg` (here two processes). A bug needing three is missed; run a bigger `.cfg` in CI. +- An invariant that is too weak passes. Check that the check can fail: break a guard and confirm TLC reports a violation. +- Without a `PROPERTY` line TLC checks no liveness. It also reports deadlock by default; the config must not disable that unless deadlock is intended. diff --git a/verifiers/intent/acceptance-examples.md b/verifiers/intent/acceptance-examples.md new file mode 100644 index 0000000..79f4276 --- /dev/null +++ b/verifiers/intent/acceptance-examples.md @@ -0,0 +1,60 @@ +--- +id: acceptance-examples +title: Acceptance examples agreed with the human up front and made executable +answers: Does the program give the exact results the human said they wanted for concrete cases? +rung: 3 +section: intent +languages: any +kinds: general, money, parsing +cost: low +detect: +ran_here: no +verified: docs +--- + +Note: there is no tool. The example runner below is plain test code; it was +not run here as a separate artefact. `verified: docs` reflects that the method +is standard specification by example. + +## Use when +- The request is a behaviour in words ("round fees to the nearest cent", "a late invoice gets a reminder"). Words are ambiguous; examples are not. +- The human will not review code but will read a table of inputs and outputs. +- You have to choose between readings of the request and want the human's choice fixed before you build. + +## Do not use when +- The claim is "this holds for all inputs". Examples show cases only; use a property or proof (rung 1 or 2). +- The behaviour is visual or tasteful; see `pairwise-comparison`. + +## Set up +Write `acceptance/examples.json` and show it to the human once (core rule 5: one +round of confirmation, with your default stated). Edge cases first: zero, +empty, the largest, a tie, a negative, an invalid input and what it must do. + +## Minimal example +`acceptance/examples.json`: + + [ + {"name": "tie rounds to even", "in": {"amount": "2.675", "dp": 2}, "out": "2.68"}, + {"name": "zero", "in": {"amount": "0", "dp": 2}, "out": "0.00"}, + {"name": "negative", "in": {"amount": "-1.005", "dp": 2}, "out": "-1.00"}, + {"name": "bad input", "in": {"amount": "abc", "dp": 2}, "error": "invalid amount"} + ] + +`acceptance/test_examples.py` loops over the file, calls the product through its +public entry point, and fails with the example's `name`. + +## Run + python3 -m unittest discover -s acceptance -v + +Passing looks like: one `ok` per example, exit 0. Failure names the example, +the expected and the actual. Never edit an expected value to make a run pass; +a changed expectation goes back to the human as a contract amendment. + +## As a contract check + {"id": "acceptance-examples", "claim": "Every example the human agreed gives the stated result", "kind": "general", "rung": 3, "cmd": "python3 -m unittest discover -s acceptance", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120} + +## What a pass does not prove +Only the cases listed. Check that the examples can fail: change the code on +purpose (swap round-half-even for round-half-up) and see at least one fails. +Examples you wrote and the human skimmed are weak; flag which the human +confirmed. Add a property test for the rule behind them where one exists. diff --git a/verifiers/intent/domain-evidence-report.md b/verifiers/intent/domain-evidence-report.md new file mode 100644 index 0000000..a643cbc --- /dev/null +++ b/verifiers/intent/domain-evidence-report.md @@ -0,0 +1,56 @@ +--- +id: domain-evidence-report +title: Printing the domain's own reports as evidence a behaviour change is right +answers: Do the numbers a domain expert would read (trial balance, P&L, balance sheet) come out right after my change? +rung: 3 +section: intent +languages: any +kinds: money, general +cost: low +detect: +ran_here: no +verified: docs +--- + +Note: modelled on how a reference project (an accounting program) +shows its books after each change. Not run here. + +## Use when +- You changed behaviour whose correctness a domain expert judges by a standard report: accounting (trial balance, P&L, balance sheet), inventory (stock on hand), billing (statement), scheduling (calendar). +- The human cannot read the diff but can read the report. +- A bug fix must be shown to correct the figure the user complained about. + +## Do not use when +- The report is generated by the same code you changed and you have no independent expectation. Then it shows what the code does, not what it should do. + +## Set up +Build a small, fixed scenario (a few entries or orders) whose correct report you +can compute by hand or already know. Keep the inputs in the repository. + +## Minimal example +Scenario: a $100 sale and a $40 expense in the same period. Expected, by hand: +revenue 100.00, expense 40.00, net income 60.00, and a trial balance whose debit and +credit totals both equal 140.00. + + $ product report trial-balance --period 2026-01 > out/tb.txt + $ grep -E "^(TOTAL|Net income)" out/tb.txt + TOTAL 140.00 140.00 + Net income 60.00 + +## Run + product report trial-balance --period 2026-01 | diff -u expected/tb.txt - + product report profit-and-loss --period 2026-01 | diff -u expected/pl.txt - + +Passing looks like: empty diff, exit 0. Failure is a diff showing which line +differs. Print the report in the final answer so the human can read it. The +expected file must come from hand calculation or an independent source, and the +check that the report foots (debits equal credits; assets equal liabilities plus equity) is a built-in test of itself. + +## As a contract check + {"id": "tb-expected", "claim": "The trial balance for the fixed scenario matches the hand-computed report", "kind": "money", "rung": 3, "cmd": "product report trial-balance --period 2026-01 | diff -u expected/tb.txt -", "expect": {"exit": 0}, "timeout_s": 60} + +## What a pass does not prove +Only the scenario. Include the cases that change the report: a reversal, a +period boundary, a rounding tie. An expected file generated by running the +product proves nothing; say how you derived it. For money cores, pair with a +property or proof that the invariants hold for all inputs. diff --git a/verifiers/intent/feedback-as-amendment.md b/verifiers/intent/feedback-as-amendment.md new file mode 100644 index 0000000..2698525 --- /dev/null +++ b/verifiers/intent/feedback-as-amendment.md @@ -0,0 +1,58 @@ +--- +id: feedback-as-amendment +title: Feedback restated as a one-line contract amendment, with a scope check on the diff +answers: Did I change only what the human's feedback asked for, and nothing else? +rung: 3 +section: intent +languages: any +kinds: general +cost: low +detect: git --version +ran_here: yes +verified: ran +--- + +## Use when +- The human reacts to your work ("the button is too big", "round down not up", "the second paragraph is wrong"). Core rule 4: this is an amendment, not licence to rework. +- A previous change reached further than the request; you want to make that impossible. +- You are fixing a review comment and the diff must show only that fix. + +## Do not use when +- The feedback truly spans the work ("start over"). Then write a new contract. + +## Set up +Record the amendment in one line in `.sisi/contract.json` (as a new check or a +note) and name the paths it may touch. Note the commit you start from: +`git rev-parse HEAD`. Re-run the invariants from rule 3. + +## Minimal example +Amendment: "Round fees down to the cent, only in `src/fees.py`." Scope script +`scope.sh` fails on any changed or new file outside the given paths: + + #!/usr/bin/env bash + set -eu + base=$1; shift + changed=$( { git diff --name-only "$base"; git ls-files -o --exclude-standard; } | sort -u) + allowed=$(git ls-files -c -o --exclude-standard -- "$@" | sort -u) + outside=$(comm -23 <(printf '%s\n' "$changed") <(printf '%s\n' "$allowed") | sed '/^$/d') + [ -z "$outside" ] || { echo "outside the amendment:"; echo "$outside"; exit 1; } + echo "ok: all changes inside $*" + +For regions inside one file, list the hunks: `git diff -U0 "$base" -- src/fees.py | grep '^@@'` +and check each range lies in the function the amendment names. + +## Run + scope.sh "$BASE" src/fees.py tests/test_fees.py + +Passing looks like: `ok: all changes inside ...` and exit 0 (run here on a scratch +repository). Failure prints `outside the amendment:` and the files, exit 1. +Formatting churn, renames and lockfile changes show up here; revert them. + +## As a contract check + {"id": "amendment-scope", "claim": "Only the files named by the amendment changed since the base commit", "kind": "general", "rung": 3, "cmd": "bash scripts/scope.sh $(cat .sisi/base) src/fees.py tests/test_fees.py", "expect": {"exit": 0, "stdout_contains": "ok: all changes inside"}, "timeout_s": 60} + +## What a pass does not prove +That the change inside the allowed file is correct, or that it did not damage +behaviour in a file that depends on it. Run the invariants for that. The +allowed list is a decision: keep it as small as the feedback. Staged and +unstaged changes are both covered by `git diff BASE`; commit history is not. diff --git a/verifiers/intent/owner-acceptance-runbook.md b/verifiers/intent/owner-acceptance-runbook.md new file mode 100644 index 0000000..076a024 --- /dev/null +++ b/verifiers/intent/owner-acceptance-runbook.md @@ -0,0 +1,59 @@ +--- +id: owner-acceptance-runbook +title: A scripted acceptance walked through using only the product's public surface +answers: Can the owner, or an agent acting as the owner, do the real job end to end using only what the product exposes? +rung: 6 +section: intent +languages: any +kinds: general, ui +cost: medium +detect: +ran_here: no +verified: docs +--- + +Note: modelled on a runbook in a reference project (a re-audit done +through the product's tools alone, with a test mirroring it). Not run here. + +## Use when +- The product is finished, or a large part is, and the question is "does it do what the owner wanted?" not "do the units pass?". +- Several features must work together, and unit tests passed each on its own. +- The human wants to run a short script and see for themselves. + +## Do not use when +- The change is small or internal; a runbook costs more than it finds. +- Nobody, human or agent, can run the product in its real environment. + +## Set up +Write `docs/runbooks/acceptance.md`. Each step: what to do, using only the CLI, +the UI, the API or the agent tools the product ships (never the database, a +debugger or a source file); what to expect; what to do on a mismatch. Say who +acts: the owner, or an agent with no access to the source. + +## Minimal example + 1. Start the product on an empty data directory: `product serve --data /tmp/acc`. + Expect: "listening on 127.0.0.1:8080", exit when stopped with code 0. + 2. Create a customer via the public API (curl in the runbook). Expect: 201 and an id. + 3. Issue an invoice for $100 and fetch the statement. Expect: balance 100.00. + 4. Restart the product on the same directory. Expect: the same balance. + 5. If any expectation fails, stop. The runbook or the product is wrong; say which. + +## Run +An agent walks the runbook, copying each command and its real output into +`acceptance-report.md`. The owner reads the report, or walks it themselves. +Every step records pass, fail or not run. + +Passing looks like: every step passed with real output pasted, nothing skipped, +and the report names who ran it and on what version. A runbook step that needed a +workaround is a failure of the product, even if the workaround worked. + +## As a contract check + {"id": "acceptance-runbook", "claim": "The acceptance runbook passes end to end through the public surface", "kind": "general", "rung": 6, "cmd": "python3 tools/walk_runbook.py docs/runbooks/acceptance.md", "expect": {"exit": 0, "stdout_contains": "ALL STEPS PASSED"}, "tier": "deep", "timeout_s": 900} + +`tools/walk_runbook.py` is yours to write; where steps are human-only, the contract +check is the owner's recorded verdict, not a command. + +## What a pass does not prove +Only the journeys written down. An agent that can read the source may use it, so +state what it may not read. Steps that depend on data from a previous run give +false passes; start clean. The owner's own pass is the only one that counts as rung 6. diff --git a/verifiers/intent/pairwise-comparison.md b/verifiers/intent/pairwise-comparison.md new file mode 100644 index 0000000..33602f8 --- /dev/null +++ b/verifiers/intent/pairwise-comparison.md @@ -0,0 +1,58 @@ +--- +id: pairwise-comparison +title: Before and after shown side by side instead of scored in the absolute +answers: Is the new version better than the old one for the thing the human cares about? +rung: 5 +section: intent +languages: any +kinds: general, ui +cost: low +detect: +ran_here: no +verified: docs +--- + +Note: no tool; the procedure is the technique. Not run here. + +## Use when +- You changed something that already worked (a layout, a message, a report, a prompt) and the risk is that it got worse. +- "Is this good?" has no stable answer but "which is better?" does. +- You have a before capture from `baseline-before-change`. + +## Do not use when +- There is an exact correct output; test it. +- There is no earlier version. Use `rubric-judge` or `acceptance-examples`. + +## Set up +Capture the old output before your first edit and the new output after, from +identical inputs. Strip anything that gives away which is new (dates, version +strings, file names). Randomise which is shown as A and B. + +## Minimal example +For a judge or the human, a two-column card: + + Task: the invoice email, same data. + A: B: + Question: which is clearer for a customer who owes money? Answer A, B or tie, and quote the line that decided it. + +Run each pair twice with the sides swapped. A verdict that changes with the +order is "tie". + +## Run + python3 tools/pair.py --before out/before.txt --after out/after.txt --judge other-family --swap + +Passing looks like: "after" wins or ties on both orders for every case, and no case +is a loss. Report wins, ties and losses, with the quote for each loss. For a +human, show images or text side by side and record the verdict with +`sisi learn` only if the human states a lasting preference. + +## As a contract check + {"id": "pairwise-not-worse", "claim": "The new output is never judged worse than the old", "kind": "general", "rung": 5, "cmd": "python3 tools/pair.py --before out/before.txt --after out/after.txt --swap --fail-on-loss", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300} + +`tools/pair.py` is yours to write; it must exit non-zero on a loss. + +## What a pass does not prove +That the new version is good, only that it is not worse on the cases shown. +Small samples hide rare losses; include the cases that were hard. A judge that +shares the author's model family leans toward the author's style. Position bias +is why you swap. For anything the human cares about, they decide. diff --git a/verifiers/intent/rubric-judge.md b/verifiers/intent/rubric-judge.md new file mode 100644 index 0000000..cc1bbfc --- /dev/null +++ b/verifiers/intent/rubric-judge.md @@ -0,0 +1,58 @@ +--- +id: rubric-judge +title: A written rubric scored by an independent model judge +answers: Does the output meet qualities a command cannot measure, such as clarity, tone or fit to the brief? +rung: 5 +section: intent +languages: any +kinds: general, ui +cost: medium +detect: +ran_here: no +verified: docs +--- + +Note: no tool is needed beyond a model CLI or API you already use. The honesty +measures below follow published LLM-as-judge practice; nothing here was run. + +## Use when +- The claim is about quality that has no exact answer: a summary, an error message, a design, documentation, a tool description. +- Human review would be the only check otherwise and you want to narrow what the human must read. +- You can write what good looks like as a short list of yes-or-no criteria. + +## Do not use when +- A command, test or proof can decide it. A judge is a sample of opinion; it is the weaker rung. +- You are the only model available. A model judging its own work agrees with itself. + +## Set up +Write `rubric.md`: 4 to 8 criteria, each a question with a clear pass line and one +example of a pass and a fail. Gather a calibration set from `taste-baseline`. + +## Minimal example +`rubric.md` excerpt: + + C1 States what happened in the first sentence. Pass: "The import failed: row 12 has no date." Fail: "An error occurred." + C2 Says what to do next. C3 Contains no internal jargon. C4 Under 40 words. + Reply as JSON: {"C1": true|false, "C2": ..., "evidence": {"C1": ""}} + +## Run +Keep the judge honest: +- Blind: give it the output and the rubric only, never the request history, your reasoning or which version is "new". +- A different model family from the one that wrote the work, with temperature 0, and require a quoted line as evidence for every verdict. +- Calibrate first: run the judge on 10 or more outputs the human already judged; require at least 90% agreement. If lower, fix the rubric, not the threshold. +- Run it 3 times and take the majority; a criterion that flips is a vague criterion. +- Treat any false as a failed check, and report the quotes. + +Passing looks like: every criterion true in the majority of runs, with quotes +that actually appear in the output, and calibration agreement recorded. + +## As a contract check + {"id": "rubric-judge", "claim": "Independent judge passes all rubric criteria", "kind": "general", "rung": 5, "cmd": "python3 tools/judge.py --rubric rubric.md --input out/summary.txt --min-agree 0.9", "expect": {"exit": 0, "stdout_contains": "ALL PASS"}, "tier": "deep", "timeout_s": 300} + +`tools/judge.py` is yours to write; it must exit non-zero on any failed criterion. + +## What a pass does not prove +That the human would agree. Judges favour long, confident, polished text and +their own style. Quotes can be checked mechanically (is the quote in the +output?); do that. Check the judge can fail: feed it a deliberately bad output. +A pass at rung 5 does not replace a human check for anything the human cares about. diff --git a/verifiers/intent/taste-baseline.md b/verifiers/intent/taste-baseline.md new file mode 100644 index 0000000..2f628e5 --- /dev/null +++ b/verifiers/intent/taste-baseline.md @@ -0,0 +1,60 @@ +--- +id: taste-baseline +title: Recording the human's past verdicts on before and after pairs +answers: Does this work match what this human has said they prefer, in cases they already judged? +rung: 6 +section: intent +languages: any +kinds: general, ui +cost: low +detect: +ran_here: no +verified: docs +--- + +Note: no tool. The store is plain files; not run here. + +## Use when +- The human's judgement is the real test (layout, wording, density, tone) and they have already given verdicts you can reuse. +- You run `rubric-judge` and need cases to calibrate it against. +- The same kind of complaint comes back repeatedly. + +## Do not use when +- You have no recorded verdicts. Do not invent them; ask once, or use `pairwise-comparison` with the human. +- A preference was a one-off about a different context. + +## Set up +Create `docs/taste/` with one small file per verdict. Record a verdict only when +the human states it (core rule 7: `sisi learn ""` for lasting +preferences, quoted, never your inference). + +## Minimal example +`docs/taste/0007-invoice-email.md`: + + date: 2026-11-09 + pair: before/invoice-email.txt vs after/invoice-email.txt + verdict: after + their words: "Better. But keep the amount in the subject line." + rule it implies: the amount stays in the subject. + +## Run +List the verdicts that apply to the area you changed, then re-run the pairs +through the judge or show the human only the cases that differ from past verdicts: + + ls docs/taste/ | head + python3 tools/taste_check.py --judge-config judge.json --taste docs/taste/ + +Passing looks like: for every recorded pair in scope, the judge's verdict equals +the human's (agreement at or above the threshold), and no implied rule is violated +(for the example, the subject still has the amount: `grep -q '\$' out/subject.txt`). + +## As a contract check + {"id": "taste-rules", "claim": "Rules implied by the human's past verdicts still hold", "kind": "general", "rung": 6, "cmd": "python3 tools/taste_check.py --taste docs/taste/", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300} + +`tools/taste_check.py` is yours to write; turn each implied rule into a command +where you can, and list the rest as "needs the human". + +## What a pass does not prove +Verdicts are about the pairs shown; a new context may need a new verdict. Old +verdicts can be stale: date them and let the human retire them. Your summary of +their words is not their words; keep the quote. diff --git a/verifiers/many-inputs/afl-plus-plus.md b/verifiers/many-inputs/afl-plus-plus.md new file mode 100644 index 0000000..9d012d0 --- /dev/null +++ b/verifiers/many-inputs/afl-plus-plus.md @@ -0,0 +1,73 @@ +--- +id: afl-plus-plus +title: Fuzzing C, C++ and Rust with AFL++ +answers: Can any input make this native program or library crash, hang or trip a sanitizer? +rung: 2 +section: many-inputs +languages: c, cpp, rust +kinds: parsing, general +cost: medium +detect: afl-fuzz -h +ran_here: no +verified: docs +--- + +## Use when + +- The target is C or C++ (or Rust via `cargo-afl`) that reads a file or stdin, and you want a mature fuzzer with many mutation strategies. +- A program has a command-line entry point and cannot easily be turned into a libFuzzer function. +- You want to run several fuzzer processes for long periods on a server. + +## Do not use when + +- A libFuzzer-style function is easy to write: `cargo-fuzz`, `go-fuzz` or `jazzer` are less work. +- You only need a few minutes of sanity fuzzing of a Rust crate: `cargo-fuzz` is simpler. + +## Set up + +C and C++: build the target with an AFL compiler (`afl-clang-fast` or `afl-cc`): + + CC=afl-clang-fast CXX=afl-clang-fast++ ./configure --disable-shared && make + +Rust: `cargo install cargo-afl`, add `afl = "*"` to `Cargo.toml`, then `cargo afl build`. +Put a few small valid inputs in `in/`. + +## Minimal example (Rust, `src/main.rs`) + + #[macro_use] + extern crate afl; + + fn main() { + fuzz!(|data: &[u8]| { + if let Ok(s) = std::str::from_utf8(data) { + let _ = mycrate::parse_pair(s); + } + }); + } + +C and C++: `afl-fuzz -i in -o out -- ./target @@` (`@@` is replaced by the input +file name; leave it out to feed stdin). + +## Run + + cargo afl build + cargo afl fuzz -i in -o out target/debug/ + +AFL runs until stopped; for a time budget use the time-limit option that +`afl-fuzz -h` lists (I believe `-V `; not confirmed against the docs here). +Passing looks like: the run ends with "saved crashes: 0" in the status screen. Failure +leaves crashing inputs in `out/default/crashes/`. Reproduce one with +`cargo afl run < out/default/crashes/`. + +## As a contract check + + {"id": "afl-parse-pair", "claim": "AFL++ finds no crash in parse_pair in 60 seconds", "kind": "parsing", "rung": 2, "cmd": "sh scripts/afl-budget.sh 60 && test -z \"$(ls out/default/crashes 2>/dev/null | grep -v README)\"", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600} + +`scripts/afl-budget.sh` is yours: it must run `cargo afl fuzz` with the time limit +and exit. AFL itself exits non-zero or hangs in ways that need that wrapper. + +## What a pass does not prove + +- A run with no crashes means none found in the time given; a short run in a CI machine without core-pattern or CPU-governor tuning may fail to start (AFL prints the fix). +- It finds crashes, not wrong outputs. Add assertions in the harness. +- Not run here (AFL++ and `cargo-afl` are not installed). Compile and run commands for C and Rust are from the AFL++ and Rust fuzz book pages; the time-limit flag is unconfirmed. Check the check: plant a crash behind a recognisable input. diff --git a/verifiers/many-inputs/algebraic-laws.md b/verifiers/many-inputs/algebraic-laws.md new file mode 100644 index 0000000..ba6f9d4 --- /dev/null +++ b/verifiers/many-inputs/algebraic-laws.md @@ -0,0 +1,74 @@ +--- +id: algebraic-laws +title: Domain laws as properties (conservation, idempotence, commutativity, monotonicity) +answers: Do the rules my domain guarantees, such as debits equal credits, hold after any generated sequence of operations? +rung: 2 +section: many-inputs +languages: any +kinds: money, state-machine, general +cost: low +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- The domain has laws that must always hold: debits equal credits, totals are conserved by transfers, applying an operation twice equals once, order of independent operations does not matter, a counter never goes down. +- Money, inventory, permissions, scheduling, any ledger-like state. +- You can name each law in one sentence. Each becomes one test, named for the law. + +## Do not use when + +- The law is only true for a subset of states you cannot generate; generate valid states first. +- You want to compare with another implementation: `differential-reference`. + +## Set up + +Write a generator for operations (or for valid starting states), apply them with +the real code, then check the law on the result. Keep money in integer cents. + +## Minimal example (Python; a transfer ledger) + + from hypothesis import given, strategies as st + + def apply(balances, a, b, cents): # under test + out = dict(balances) + if cents <= 0 or out.get(a, 0) < cents: + return out # refused: nothing changes + out[a] -= cents + out[b] = out.get(b, 0) + cents + return out + + names = st.sampled_from("abc") + state = st.dictionaries(names, st.integers(0, 10**6)) + transfers = st.lists(st.tuples(names, names, st.integers(-5, 10**6)), max_size=30) + + @given(state, transfers) + def test_conservation(s, ts): + total = sum(s.values()) + for a, b, c in ts: + s = apply(s, a, b, c) + assert sum(s.values()) == total # nothing created or destroyed + assert all(v >= 0 for v in s.values()) # nobody goes negative + + @given(state, names, names, st.integers(1, 10**6)) + def test_refused_transfer_is_idempotent_noop(s, a, b, c): + once = apply(s, a, b, c) + assert apply(once, a, b, 10**9) == once # an impossible transfer changes nothing + +## Run + + python3 -m pytest -q test_laws.py + +Passing looks like: `2 passed`, exit 0. Failure shows the shortest violating sequence. + +## As a contract check + + {"id": "law-conservation", "claim": "transfers conserve the total and never overdraw", "kind": "money", "rung": 2, "cmd": "python3 -m pytest -q test_laws.py", "expect": {"exit": 0, "stdout_contains": "2 passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- Laws that hold are necessary, not sufficient: an implementation that does nothing conserves the total. Pair with `stateful-model-test` for what should have happened. +- The check holds only for generated states. If the generator never makes an overdrawn account or `a == b`, those cases are untested. +- Check the check: break the code (skip the debit, or credit twice) and see the right law fail. diff --git a/verifiers/many-inputs/atheris.md b/verifiers/many-inputs/atheris.md new file mode 100644 index 0000000..44b57b3 --- /dev/null +++ b/verifiers/many-inputs/atheris.md @@ -0,0 +1,76 @@ +--- +id: atheris +title: Coverage-guided fuzzing of Python with Atheris +answers: Can any input make this Python code raise an exception it should not, hang, or crash the interpreter? +rung: 2 +section: many-inputs +languages: python +kinds: parsing, general +cost: medium +detect: python3 -c "import atheris" +ran_here: yes +verified: ran +--- + +## Use when + +- Python code parses or transforms untrusted input and should raise only its documented exceptions. +- You want libFuzzer's coverage guidance, corpus handling and time budget for Python code, including C extensions. +- Property tests with `hypothesis` have not found anything and you want a search guided by coverage. + +## Do not use when + +- You need shrinking to a readable counterexample and structured values: `hypothesis`. +- The code is pure and fast to reason about; a property test is less work. + +## Set up + + python3 -m venv .venv && .venv/bin/pip install atheris + +Atheris builds against clang; wheels exist for common platforms. Use +`@atheris.instrument_func` on your functions or `atheris.instrument_imports()` +around the import of the code under test. Without instrumentation there is no +coverage feedback and the fuzzer finds almost nothing. + +## Minimal example (`fuzz_parse.py`) + + import sys + import atheris + + @atheris.instrument_func + def parse_pair(s: str): + a, _, b = s.partition(",") + x, y = int(a), int(b) # ValueError is the documented error + if s.startswith("42,") and y == 7: + raise RuntimeError("seeded bug") # anything else is a finding + return x, y + + def test_one_input(data: bytes): + fdp = atheris.FuzzedDataProvider(data) + s = fdp.ConsumeUnicodeNoSurrogates(16) + try: + parse_pair(s) + except ValueError: + pass + + atheris.Setup(sys.argv, test_one_input) + atheris.Fuzz() + +## Run + + mkdir -p corpus && .venv/bin/python fuzz_parse.py corpus -max_total_time=60 -timeout=10 + +Passing looks like: `Done N runs in 60 second(s)`, exit 0. +Failure prints the traceback, writes `crash-` in the current directory +(`artifact_prefix='./'`) and exits 77. Replay with `.venv/bin/python fuzz_parse.py crash-`; +commit the file as a regression case. + +## As a contract check + + {"id": "fuzz-parse-pair-py", "claim": "parse_pair raises only ValueError on 60 seconds of fuzzed input", "kind": "parsing", "rung": 2, "cmd": ".venv/bin/python fuzz_parse.py corpus -max_total_time=60 -timeout=10", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- Only what was found in the time given; the bug in the example took under 60 seconds with instrumentation and was never found in 30 seconds without it. +- Uninstrumented code and code in another process are invisible to the fuzzer. +- Check the check: confirm a planted bug is found, and that the `except` clause only catches the documented error. diff --git a/verifiers/many-inputs/cargo-fuzz.md b/verifiers/many-inputs/cargo-fuzz.md new file mode 100644 index 0000000..b11fbc5 --- /dev/null +++ b/verifiers/many-inputs/cargo-fuzz.md @@ -0,0 +1,69 @@ +--- +id: cargo-fuzz +title: Coverage-guided fuzzing of Rust with cargo-fuzz (libFuzzer) +answers: Can any input I did not think of make this Rust code panic, overflow, hang or break an assertion? +rung: 2 +section: many-inputs +languages: rust +kinds: parsing, general, state-machine +cost: medium +detect: cargo fuzz --version +ran_here: yes +verified: ran +--- + +## Use when + +- Rust code takes untrusted or complex input: parsers, decoders, importers, journal and file readers, request handlers. +- You want a run with a time budget and a saved reproducer for any crash. +- You have a few valid example inputs to seed the search. + +## Do not use when + +- The input must satisfy a grammar that raw bytes rarely meet; use `structure-aware-fuzzing`. +- You need a law checked on structured values with shrinking: `proptest`. +- You cannot run nightly Rust. cargo-fuzz needs a nightly toolchain. + +## Set up + + cargo install cargo-fuzz # once; needs rustup nightly + cargo fuzz init # creates fuzz/ with fuzz_target_1 + mkdir -p fuzz/corpus/fuzz_target_1 fuzz/seeds/fuzz_target_1 + +Put small valid inputs in `fuzz/seeds//` and commit them. The `corpus/` +directory grows during runs and is normally git-ignored. Crash files appear in +`fuzz/artifacts//`. + +## Minimal example (`fuzz/fuzz_targets/fuzz_target_1.rs`) + + #![no_main] + use libfuzzer_sys::fuzz_target; + + fuzz_target!(|data: &[u8]| { + if let Ok(s) = std::str::from_utf8(data) { + let _ = mycrate::parse_pair(s); // must never panic, only return None/Err + } + }); + +## Run + + cd && RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 \ + fuzz/corpus/fuzz_target_1 fuzz/seeds/fuzz_target_1 -- -max_total_time=60 -timeout=10 + +The first directory after the target is where new inputs are written; later ones +are read-only seeds. The directory must already exist (the run refuses with +"The required directory ... does not exist" otherwise). +Passing looks like: `Done N runs in 60 second(s)`, exit 0. +Failure shows the panic message, `Test unit written to fuzz/artifacts/fuzz_target_1/crash-`, +and exit 1. Replay one crash with `cargo fuzz run fuzz_target_1 fuzz/artifacts/fuzz_target_1/crash-`; +after the fix, copy it into `fuzz/seeds/fuzz_target_1/` as a regression case. + +## As a contract check + + {"id": "fuzz-parse-pair", "claim": "parse_pair neither panics nor hangs on 60 seconds of fuzzed input", "kind": "parsing", "rung": 2, "cmd": "cd fuzz-host && RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 fuzz/corpus/fuzz_target_1 fuzz/seeds/fuzz_target_1 -- -max_total_time=60 -timeout=10", "expect": {"exit": 0, "stdout_contains": "Done"}, "tier": "deep", "timeout_s": 600} + +## What a pass does not prove + +- A clean run only means nothing was found in that time. The bug seeded in the example needs a specific prefix; a 30-second run on a numeric comparison deeper in the code did not find an equivalent one. Longer runs and good seeds matter. +- It finds crashes, not wrong answers. Add assertions inside the target (round trip, agreement with a reference) to catch those. +- Check the check: plant a panic behind a recognisable input and see the fuzzer find it, then remove it. Also check the target actually reaches the code (`cargo fuzz coverage`). diff --git a/verifiers/many-inputs/derived-view-agreement.md b/verifiers/many-inputs/derived-view-agreement.md new file mode 100644 index 0000000..883f706 --- /dev/null +++ b/verifiers/many-inputs/derived-view-agreement.md @@ -0,0 +1,72 @@ +--- +id: derived-view-agreement +title: Every displayed figure recomputed from the core and compared +answers: Does every number a screen, report or export shows equal what the core computes from the same data? +rung: 2 +section: many-inputs +languages: any +kinds: ui, money +cost: medium +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- A UI, report, CSV export or API response shows figures that a core library also computes (balances, totals, percentages). +- Formatting, rounding or caching in the display layer could change a value the core got right. +- Two surfaces show the same fact (a dashboard and an exported statement). + +## Do not use when + +- The view has no figures, only layout: use `ui-screenshot-compare`. +- The view is the only place the figure is computed; compare against an independent reference (`differential-reference`). + +## Set up + +Give the display layer a seam that returns what it will show as data (not pixels): +a view model, a rendered text, a parsed export. Generate random data, load it +through the core, and for each displayed figure recompute from the core +and compare after normalising only the formatting. + +## Minimal example (Python) + + from decimal import Decimal + from hypothesis import given, strategies as st + + def core_total(entries): # the core: integer cents + return sum(entries) + + def render_report(entries): # the display layer under test + lines = [f"{c / 100:.2f}" for c in entries] # a float in a money path + return {"lines": lines, "total": f"{core_total(entries) / 100:.2f}"} + + def parse(text): return int(Decimal(text) * 100) + + @given(st.lists(st.integers(-10**9, 10**9), max_size=30)) + def test_every_figure_matches_core(entries): + view = render_report(entries) + assert [parse(x) for x in view["lines"]] == entries # each line + assert parse(view["total"]) == core_total(entries) # the total + assert sum(parse(x) for x in view["lines"]) == parse(view["total"]) # the page adds up + +## Run + + python3 -m pytest -q test_view.py + +Passing looks like: `1 passed`, exit 0 (the float formatting is right for these sizes). +With amounts above about 2**53 cents the float version fails and Hypothesis shrinks +to the smallest such figure. Widen the range to see it; a display path that must +handle big amounts should use `Decimal`, not `float`. + +## As a contract check + + {"id": "view-matches-core", "claim": "every figure the report displays equals the core's value, and the report adds up", "kind": "money", "rung": 2, "cmd": "python3 -m pytest -q test_view.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- It checks the figures you list. Enumerate every displayed number (tests that walk the whole view model help) and add new ones as screens are added. +- Equal to the core only shows the view is faithful; the core can still be wrong (see `algebraic-laws`, `differential-reference`). +- A reference project also scans display source for rounding calls outside the one shared function; a source scan is a cheap extra guard. +- Check the check: change the rounding in the view by one cent and see it fail. diff --git a/verifiers/many-inputs/differential-executable-spec.md b/verifiers/many-inputs/differential-executable-spec.md new file mode 100644 index 0000000..393696e --- /dev/null +++ b/verifiers/many-inputs/differential-executable-spec.md @@ -0,0 +1,75 @@ +--- +id: differential-executable-spec +title: Differential testing against an executable formal model +answers: Does the implementation agree, on random cases, with the formal model that was proved, run as a program? +rung: 2 +section: many-inputs +languages: any +kinds: state-machine, money, parsing +cost: high +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- The design has a formal model that can be run: a Lean checker binary, a TLA+ trace checker, an Alloy or Dafny program. +- You want the implementation compared to the model itself, not to a hand transcription of it. +- A mismatch must name which side is wrong, so each case carries both answers. + +## Do not use when + +- The model cannot be executed. Use `model-test-from-spec` with a hand transcription. +- A checker run is slow per case: batch many cases into one call, or the test will be too slow to run in CI. + +## Set up + +Build the checker once and pin its revision. Write the glue: run each random +case through the implementation, write the case and the implementation's answer +as a file in the checker's input format, run the checker once for the whole +batch, and fail if it reports any mismatch. Fail loudly if the checker is missing +(never skip silently): one reference project makes the test fail when `lake` is absent. + +## Minimal example (Python; `checker.py` stands in for the formal model's binary) + + # test_vs_checker.py + import json, subprocess, sys + from hypothesis import given, settings, strategies as st + + def impl_total(prices): # implementation under test + return sum(prices) + + CASES = st.lists(st.integers(0, 10**6), max_size=20) + + @settings(max_examples=50, deadline=None) + @given(st.lists(CASES, min_size=1, max_size=20)) + def test_against_checker(batch): + cases = [{"input": c, "got": impl_total(c)} for c in batch] + out = subprocess.run([sys.executable, "checker.py"], input=json.dumps(cases), + capture_output=True, text=True, check=True).stdout + mismatches = json.loads(out) + assert mismatches == [], mismatches + + # checker.py (the "executable spec": here a trivial model) + import json, sys + cases = json.load(sys.stdin) + print(json.dumps([c for c in cases if sum(c["input"]) != c["got"]])) + +## Run + + python3 -m pytest -q test_vs_checker.py + +Passing looks like: `1 passed`, exit 0. +Failure shows the batch and the mismatch list from the checker, exit 1. + +## As a contract check + + {"id": "diff-formal-model", "claim": "the implementation agrees with the formal model's checker on generated cases", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_vs_checker.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 900} + +## What a pass does not prove + +- Only the cases generated, and only the commands the checker's input format can express. List what it cannot say. +- The checker may skip outcomes it does not know (one reference project's checker ignores refusal words it does not list); count skipped cases and fail if too many. +- The model may not match the intended behaviour. This shows code and model agree, not that either is right. +- Check the check: change the implementation by one rule and see the checker report a mismatch. diff --git a/verifiers/many-inputs/differential-old-vs-new.md b/verifiers/many-inputs/differential-old-vs-new.md new file mode 100644 index 0000000..401da97 --- /dev/null +++ b/verifiers/many-inputs/differential-old-vs-new.md @@ -0,0 +1,66 @@ +--- +id: differential-old-vs-new +title: Differential testing of new code against the previous version +answers: Did my refactor or rewrite keep the behaviour of the old code on inputs I did not think of? +rung: 2 +section: many-inputs +languages: any +kinds: general, parsing, money, migration +cost: medium +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- You are refactoring, optimising or rewriting code whose behaviour must not change. +- The old version is trusted by its users, even if not proved. +- You can keep both versions side by side for the length of the change (old copy in the test tree, a tagged release, or a git worktree of the old commit). + +## Do not use when + +- The behaviour is meant to change. Then compare only the parts that must not change, or use `metamorphic`. +- The old version has known bugs you do not want to keep; agreement would preserve them. Record the known differences explicitly. + +## Set up + +Freeze the old implementation as a module the test can import (copy it as +`old_impl.py`, or build the old commit in a worktree and call it as a program). +Delete the copy when the change is merged and its job is done. + +## Minimal example (Python; a faster word counter against the original) + + from collections import Counter + from hypothesis import given, strategies as st + + def old_count(text): # frozen original + counts = {} + for w in text.split(): + counts[w] = counts.get(w, 0) + 1 + return counts + + def new_count(text): # rewrite under test + return dict(Counter(text.split())) + + @given(st.text(alphabet=" \n\tab é", max_size=200)) + def test_new_matches_old(text): + assert new_count(text) == old_count(text) + +## Run + + python3 -m pytest -q test_old_vs_new.py + +Passing looks like: `1 passed`, exit 0. +Failure prints the shrunk input and both outputs, exit 1. + +## As a contract check + + {"id": "refactor-same-behaviour", "claim": "new_count returns what the old implementation returned on generated text", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_old_vs_new.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- It compares outputs on generated inputs only. Side effects (files, logs, timing) are not compared unless you read them back. +- The alphabet decides what is tried: include the awkward characters, empty input and very large ones. In the example, a non-breaking space is the kind of case that separates `split()` rewrites. +- Errors count too: compare raised exceptions and messages, not only returned values. +- Check the check: change the new code by one character and confirm the test fails. diff --git a/verifiers/many-inputs/differential-reference.md b/verifiers/many-inputs/differential-reference.md new file mode 100644 index 0000000..f772c3a --- /dev/null +++ b/verifiers/many-inputs/differential-reference.md @@ -0,0 +1,70 @@ +--- +id: differential-reference +title: Differential testing against an independent reference implementation +answers: Does my implementation give the same answer as an independent, trusted one on random inputs? +rung: 2 +section: many-inputs +languages: any +kinds: general, parsing, money +cost: medium +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- Another library, tool or program already computes the same thing (a standard library, a database, a reference tool run in a container). +- The result is hard to state as a law but easy to compare. +- You wrote a faster or custom version of something with a trusted slow version. + +## Do not use when + +- The reference shares code or an algorithm with your implementation; agreement then proves little. Prefer one written independently. +- Both may legitimately differ (rounding rules, ordering of ties). Decide first what counts as equal. +- A prior version of your own code is the reference: use `differential-old-vs-new`. + +## Set up + +Choose the reference and pin its version. A program in a container is fine: +call it through a function that takes an input and returns a normalised answer. +Generate inputs with `hypothesis`, `proptest` or `fast-check`. + +## Minimal example (Python: a custom decimal rounder against `decimal`) + + from decimal import Decimal, ROUND_HALF_EVEN + from hypothesis import given, strategies as st + + def my_round_cents(units: int, scale: int) -> int: + """units / 10**scale, rounded half to even, in cents (integers only).""" + q, r = divmod(units * 100, 10**scale) + twice = 2 * r + if twice > 10**scale or (twice == 10**scale and q % 2 == 1): + q += 1 + return q + + def reference(units: int, scale: int) -> int: + d = Decimal(units).scaleb(-scale).quantize(Decimal("0.01"), rounding=ROUND_HALF_EVEN) + return int(d.scaleb(2)) + + @given(st.integers(-10**12, 10**12), st.integers(0, 9)) + def test_matches_reference(units, scale): + assert my_round_cents(units, scale) == reference(units, scale) + +## Run + + python3 -m pytest -q test_diff.py + +Passing looks like: `1 passed`, exit 0. +Failure prints the shrunk input and both answers, exit 1. + +## As a contract check + + {"id": "diff-rounding", "claim": "my rounding equals Python's decimal on generated amounts", "kind": "money", "rung": 2, "cmd": "python3 -m pytest -q test_diff.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- It shows agreement, not correctness: if the reference has the same bug or misreads the spec, both pass. +- Generated inputs that the reference rejects or that both treat identically make the pass thin; check the distribution (include edge scales, negatives, ties). +- Pin the reference version and record it; a drifting reference changes the answer. +- Check the check: introduce an off-by-one in the tie rule and see it fail. diff --git a/verifiers/many-inputs/fast-check.md b/verifiers/many-inputs/fast-check.md new file mode 100644 index 0000000..906cc7e --- /dev/null +++ b/verifiers/many-inputs/fast-check.md @@ -0,0 +1,67 @@ +--- +id: fast-check +title: Property testing in TypeScript and JavaScript with fast-check +answers: Does this JavaScript or TypeScript function hold its law for generated inputs, and what is the smallest counterexample? +rung: 2 +section: many-inputs +languages: typescript, javascript +kinds: general, parsing, money, state-machine +cost: low +detect: node --version +ran_here: yes +verified: ran +--- + +## Use when + +- A function or module has a law (round trip, idempotence, order, agreement with a simple version) and you use Node, Jest, Vitest or the built-in `node:test`. +- You want shrinking and a replayable seed. +- You want to test a sequence of operations against a model (see `stateful-model-test`). + +## Do not use when + +- The code is browser-only and cannot run under Node; run the same property in the browser test runner instead. +- You need coverage-guided search. Use `jazzer`. + +## Set up + + npm install --save-dev fast-check + +fast-check runs inside any runner. The example uses `node --test`, which needs +no extra install. + +## Minimal example (`props.test.mjs`) + + import test from 'node:test'; + import fc from 'fast-check'; + + const encode = (b) => Buffer.from(b).toString('hex'); + const decode = (s) => Uint8Array.from(Buffer.from(s, 'hex')); + + test('round trip', () => { + fc.assert( + fc.property(fc.uint8Array({ maxLength: 256 }), (bytes) => + Buffer.compare(Buffer.from(decode(encode(bytes))), Buffer.from(bytes)) === 0), + { numRuns: 1000 }, + ); + }); + +## Run + + node --test props.test.mjs + +Passing looks like: `ℹ pass 1` and `ℹ fail 0`, exit 0. +Failure shows `Counterexample: [...]`, `Shrunk N time(s)` and a line +`{ seed: -2075209501, path: "..." }`, exit non-zero. Replay it by passing the +same values: `fc.assert(prop, { seed: -2075209501, path: "8:4:..." })`. Pin +important cases permanently with `{ examples: [[...]] }`. + +## As a contract check + + {"id": "prop-round-trip-js", "claim": "decode(encode(x)) equals x for generated byte arrays", "kind": "parsing", "rung": 2, "cmd": "node --test props.test.mjs", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- It samples (100 runs by default; `numRuns` raises it). The arbitrary decides what is ever tried, so check its bounds against real inputs. +- A property that returns `true` for any input is vacuous. Test the test: break the code on purpose, confirm a counterexample appears, restore it. +- Number generators include `NaN`, `-0` and huge values only if you ask; `fc.integer()` is not `fc.double()`. diff --git a/verifiers/many-inputs/fault-injection-storage.md b/verifiers/many-inputs/fault-injection-storage.md new file mode 100644 index 0000000..13d5258 --- /dev/null +++ b/verifiers/many-inputs/fault-injection-storage.md @@ -0,0 +1,83 @@ +--- +id: fault-injection-storage +title: Fault injection for storage (power loss, disk full, short writes) +answers: If the machine dies or the disk fills in the middle of a write, do the data reopen correctly with nothing lost that was acknowledged? +rung: 2 +section: many-inputs +languages: any +kinds: state-machine, general +cost: medium +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- Code writes its own files (journal, snapshot, backup) and claims to be crash-safe or atomic. + +## Do not use when + +- A database makes the guarantee and you only use its API: test your use of transactions instead. +- You need real kernel or hardware faults (reordered writes, lost fsync); this simulates file contents only. + +## Set up + +Make the last write observable: record the file bytes before and after it. Then +simulate each fault by building the damaged file yourself and reopening it: + +- power loss: for every cut `k` in `1..len(last_write)`, the file is `before + last[:k]`; +- disk full or short write: a write function that raises `OSError` after N bytes. + +## Minimal example (Python; a checksummed append-only log) + + import os, tempfile, zlib + + class Log: + def __init__(self, path): + self.path, self.items = path, [] + if os.path.exists(path): + raw = open(path, "rb").read() + good = 0 + for line in raw.splitlines(keepends=True): + body, _, crc = line.rstrip(b"\n").rpartition(b" ") + if not line.endswith(b"\n") or not crc.isdigit() or zlib.crc32(body) != int(crc): + break # torn tail: drop it + self.items.append(body.decode()); good += len(line) + if good < len(raw): + open(path, "r+b").truncate(good) # heal + def append(self, text): + line = text.encode() + b" " + str(zlib.crc32(text.encode())).encode() + b"\n" + with open(self.path, "ab") as f: + f.write(line); f.flush(); os.fsync(f.fileno()) + self.items.append(text) + + def test_power_loss_at_every_byte_of_the_last_append(): + p = os.path.join(tempfile.mkdtemp(), "log") + log = Log(p); log.append("one"); log.append("two") + before = open(p, "rb").read() + log.append("three") + last = open(p, "rb").read()[len(before):] + for k in range(1, len(last)): # every cut short of the whole line + open(p, "wb").write(before + last[:k]) + assert Log(p).items == ["one", "two"], f"cut at {k}" + assert open(p, "rb").read() == before, f"not healed at {k}" + open(p, "wb").write(before + last) + assert Log(p).items == ["one", "two", "three"] + +## Run + + python3 -m pytest -q test_faults.py + +Passing looks like: `1 passed`, exit 0. Failure names the byte cut (`cut at 7`). +One reference project's store also checks that reports after reopening equal those from before. + +## As a contract check + + {"id": "torn-write-recovery", "claim": "a power cut at any byte of the last append reopens to the state before it", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_faults.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- It covers truncation of the last write only. Torn writes that leave garbage in the middle, reordered writes, a lost `fsync` and media errors need other tests or a real crash rig. +- Also check an acknowledged write is never lost, not only that the file opens. +- Check the check: remove the CRC check or the truncate and see it fail. diff --git a/verifiers/many-inputs/generator-coverage.md b/verifiers/many-inputs/generator-coverage.md new file mode 100644 index 0000000..dcf2051 --- /dev/null +++ b/verifiers/many-inputs/generator-coverage.md @@ -0,0 +1,65 @@ +--- +id: generator-coverage +title: Checking that random tests actually reach interesting cases +answers: Is my property or model test really exercising edge cases and rare commands, or is it passing because it never gets there? +rung: 2 +section: many-inputs +languages: any +kinds: general, state-machine +cost: low +detect: python3 -c "import hypothesis" +ran_here: yes +verified: ran +--- + +## Use when + +- You wrote a property, model or fuzz test and it passes on the first try. +- The generator filters, rejects or chooses by weights, so most cases may be boring or discarded. +- A model test might never post, reverse or close anything. + +## Do not use when + +- The test is a fixed example. + +## Set up + +Count what happens. In Hypothesis use `event()` and `target()` and read +`--hypothesis-show-statistics`; in proptest print a count per accepted command and per +refusal (one reference project's model test does this under `MODEL_STATS=1`); in fast-check use +`fc.statistics`; in a fuzzer use `cargo fuzz coverage` or the coverage output. + +## Minimal example (Python) + + from hypothesis import given, event, strategies as st + + @given(st.integers(-5, 150), st.integers(0, 100)) + def test_withdraw_cases_all_occur(amount, balance): + if amount <= 0: + event("bad amount") + elif amount > balance: + event("insufficient") + else: + event("success") + # ... the real assertions about withdraw(amount, balance) go here + +## Run + + python3 -m pytest -q test_cov.py --hypothesis-show-statistics + +Passing looks like: `1 passed` and, in the statistics block, each event +(`bad amount`, `insufficient`, `success`) with a share well above zero. Failure here is +a reading task: any event at 0 percent or under about 1 percent means that branch is +effectively untested, and the generator needs fixing. To make this automatic, assert +on counts with a collected dictionary in a small harness, or fail on health-check +warnings (`HealthCheck.filter_too_much`, `too_slow`) by not suppressing them. + +## As a contract check + + {"id": "generators-reach-cases", "claim": "the withdraw property test exercises bad, insufficient and successful cases", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_cov.py --hypothesis-show-statistics", "expect": {"exit": 0, "stdout_contains": "success"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- Events show that a case occurred, not that the assertion beside it is strong. +- A generator that reaches every named case can still miss ones you did not name; add boundary values by hand (`@example`). +- Check the check: narrow the generator (balance always 0) and confirm "success" disappears from the statistics. diff --git a/verifiers/many-inputs/go-fuzz.md b/verifiers/many-inputs/go-fuzz.md new file mode 100644 index 0000000..ad4f701 --- /dev/null +++ b/verifiers/many-inputs/go-fuzz.md @@ -0,0 +1,67 @@ +--- +id: go-fuzz +title: Native Go fuzzing with go test -fuzz +answers: Can any input make this Go function panic, hang or break an invariant? +rung: 2 +section: many-inputs +languages: go +kinds: parsing, general +cost: low +detect: go version +ran_here: no +verified: docs +--- + +## Use when + +- A Go function parses or processes input from outside: decoders, importers, request handlers. +- You want the standard toolchain only, with saved failing inputs that become regression tests automatically. + +## Do not use when + +- The input must be structured values and you want shrinking: `go-rapid`. +- The target needs more than one second a call; the engine treats that as a hang. + +## Set up + +Nothing to install beyond Go. Write a `FuzzXxx` function in a `*_test.go` file with +seeds via `f.Add`. Supported argument types: `string`, `[]byte`, the integer and +float types, and `bool`. + +## Minimal example (`parse_test.go`) + + package pair + + import "testing" + + func FuzzParsePair(f *testing.F) { + f.Add("1,2") + f.Add("") + f.Fuzz(func(t *testing.T, s string) { + a, b, err := ParsePair(s) + if err == nil && (a < 0 || b < 0) { + t.Fatalf("accepted a negative value from %q", s) + } + }) + } + +## Run + + go test -run=FuzzParsePair ./... # replays seeds and saved failures only + go test -fuzz=FuzzParsePair -fuzztime=30s # fuzzes for 30 seconds + +`-fuzz` takes a regex that must match exactly one fuzz test in the package. +Passing looks like: the fuzz run ends at the time limit with exit 0 and no `--- FAIL`. +Failure writes a minimised input to `testdata/fuzz/FuzzParsePair/`, prints +`FAIL`, and exits 1. Commit that file: from then on plain `go test` replays it as a +unit test. Re-run just that case with `go test -run=FuzzParsePair/`. + +## As a contract check + + {"id": "fuzz-parse-pair-go", "claim": "ParsePair survives 30 seconds of fuzzing and every saved failing input", "kind": "parsing", "rung": 2, "cmd": "go test -run=FuzzParsePair ./... && go test -fuzz=FuzzParsePair -fuzztime=30s", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- A clean run means nothing was found in that time. Coverage guidance works best on AMD64 and ARM64. +- Only the failures that panic, call `t.Fatal`, or run over time are caught; wrong answers need assertions in the target. +- Not run here (Go is not installed on this machine). Flags, directory layout and types are from the official Go fuzzing documentation. Check the check: add a deliberate panic behind a seed-adjacent input and see it found. diff --git a/verifiers/many-inputs/go-rapid.md b/verifiers/many-inputs/go-rapid.md new file mode 100644 index 0000000..b7ad1f8 --- /dev/null +++ b/verifiers/many-inputs/go-rapid.md @@ -0,0 +1,72 @@ +--- +id: go-rapid +title: Property testing in Go with rapid +answers: Does this Go code hold its law for generated inputs, and what is the smallest failing case? +rung: 2 +section: many-inputs +languages: go +kinds: general, parsing, money, state-machine +cost: low +detect: go version +ran_here: no +verified: docs +--- + +## Use when + +- Go code has a law (round trip, sorted output, idempotence, agreement with a model) and you want shrinking. +- You want a stateful model test using `T.Repeat` (see `stateful-model-test`). + +## Do not use when + +- You want coverage-guided search: use `go-fuzz`. rapid can be wired into it with `rapid.MakeFuzz`, but the fuzzing engine then does the guiding, not rapid. +- A table of examples already covers the cases that matter (see the `test-quality` section). + +## Set up + + go get pgregory.net/rapid + # in a *_test.go file: import "pgregory.net/rapid" + +## Minimal example + + package hexcodec + + import ( + "bytes" + "encoding/hex" + "testing" + + "pgregory.net/rapid" + ) + + func TestRoundTrip(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + data := rapid.SliceOf(rapid.Byte()).Draw(t, "data") + got, err := hex.DecodeString(hex.EncodeToString(data)) + if err != nil || !bytes.Equal(got, data) { + t.Fatalf("round trip failed for %v: %v, %v", data, got, err) + } + }) + } + +## Run + + go test -run TestRoundTrip ./... + go test -rapid.checks=10000 -run TestRoundTrip ./... + +Passing looks like: `ok ` and exit 0. +Failure shows the minimal failing draw (`data = []byte{...}`) and `FAIL`, exit 1. +rapid saves minimised failing cases and re-runs them automatically; the +directory was not confirmed against the docs here, so look for a new +`testdata/` subdirectory after a failure and commit it. Each flag also has a +`RAPID_` environment variable (for example `RAPID_CHECKS`). + +## As a contract check + + {"id": "prop-round-trip-go", "claim": "hex decode of encode returns the input for generated byte slices", "kind": "parsing", "rung": 2, "cmd": "go test -run TestRoundTrip ./...", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- 100 checks by default; it samples. Raise `-rapid.checks` for important laws. +- `t.Skip` in a property discards the case; if most cases skip, the pass is nearly empty. +- Not run here (Go is not installed on this machine). The example, `-rapid.checks`, the `RAPID_` variables, `T.Repeat` and `MakeFuzz` come from the package documentation; the failure-file location and `-rapid.seed` could not be confirmed. Break the code on purpose to see the check fail. diff --git a/verifiers/many-inputs/hostile-input-from-schema.md b/verifiers/many-inputs/hostile-input-from-schema.md new file mode 100644 index 0000000..c459509 --- /dev/null +++ b/verifiers/many-inputs/hostile-input-from-schema.md @@ -0,0 +1,76 @@ +--- +id: hostile-input-from-schema +title: Hostile arguments generated from an API or tool schema +answers: Does every call my API or tool accepts survive wrong, missing, huge and strange arguments with a clean error and no crash? +rung: 2 +section: many-inputs +languages: any +kinds: parsing, general +cost: medium +detect: python3 -c "import hypothesis_jsonschema" +ran_here: yes +verified: ran +--- + +## Use when + +- A server, CLI or agent tool publishes a schema (JSON Schema, OpenAPI, MCP `tools/list`) for its inputs. +- A panic or internal error reachable by one request is a denial of service or loses data. +- You need to show that after hostile calls the server still serves and its data still reopens. + +## Do not use when + +- There is no schema; write one, or fuzz the raw handler with `cargo-fuzz` or `atheris`. +- You only care about valid calls: use ordinary tests. + +## Set up + + pip install hypothesis hypothesis-jsonschema pytest + +For each operation, generate valid arguments from its schema, then make them +hostile: wrong types, missing and extra fields, empty and huge strings, negative, +fractional and maximum numbers, control characters, absurd dates. + +## Minimal example + + from hypothesis import given, settings, strategies as st + from hypothesis_jsonschema import from_schema + + SCHEMA = {"type": "object", "required": ["cents", "memo"], "properties": { + "cents": {"type": "integer", "minimum": 0}, "memo": {"type": "string"}}} + + def handle(args): # the thing under test: result or clean refusal + if not isinstance(args, dict) or not isinstance(args.get("cents"), int) \ + or isinstance(args.get("cents"), bool) or args["cents"] < 0: + return {"error": "invalid_arguments"} + return {"ok": len(str(args.get("memo", "")))} + + hostile = st.one_of( + from_schema(SCHEMA), + st.recursive(st.none() | st.booleans() | st.integers() | st.floats() | st.text(), + lambda c: st.lists(c, max_size=3) | st.dictionaries(st.text(max_size=5), c, max_size=3))) + + @settings(max_examples=300) + @given(hostile) + def test_no_crash_clean_error(args): + out = handle(args) # any exception here is a failure + assert "ok" in out or out.get("error") + assert handle({"cents": 1, "memo": "x"}) == {"ok": 1} # still serving afterwards + +## Run + + python3 -m pytest -q test_hostile.py + +Passing looks like: `1 passed`, exit 0. Failure shows the shrunk argument that raised or +got no clean answer. + +## As a contract check + + {"id": "hostile-args", "claim": "no generated or mangled argument crashes the handler; each gets a result or a clean error", "kind": "parsing", "rung": 2, "cmd": "python3 -m pytest -q test_hostile.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 600} + +## What a pass does not prove + +- Only the shapes generated. A server whose crash needs a particular combination across fields or calls needs a stateful sequence (`stateful-model-test`). +- "Clean error" is whatever your assert accepts; define it (error code, no stack trace, no data change). +- Check after the hostile calls that the server still answers and the stored data reopens. One reference project's suite does both: every tool is called with hostile arguments, then a restarted server must still read the books. +- Check the check: add a deliberate crash on one input class (`cents` above 2**63) and see it found. diff --git a/verifiers/many-inputs/hypothesis.md b/verifiers/many-inputs/hypothesis.md new file mode 100644 index 0000000..c6d0c61 --- /dev/null +++ b/verifiers/many-inputs/hypothesis.md @@ -0,0 +1,71 @@ +--- +id: hypothesis +title: Property testing in Python with Hypothesis +answers: Does this Python function keep its promise for every input Hypothesis can generate, and what is the smallest input that breaks it? +rung: 2 +section: many-inputs +languages: python +kinds: general, parsing, money, state-machine +cost: low +detect: python3 -c "import hypothesis" +ran_here: yes +verified: ran +--- + +## Use when + +- A function has a law that must hold for all inputs and one example test shows only one case. +- You want shrinking to a minimal failing input and automatic replay of earlier failures. +- Money in integer cents, parsers, serialisers, sort or search code. + +## Do not use when + +- No packages may be installed. Use `python-stdlib-property`. +- The function is slow (over about 50 ms a call): Hypothesis will run it hundreds of times. Lower `max_examples` or test a smaller unit. +- The input space is a coverage problem for a native parser. Use `atheris`. + +## Set up + + python3 -m venv .venv && .venv/bin/pip install hypothesis pytest + +Put tests in `tests/test_props.py`. Hypothesis stores failures in `.hypothesis/` +(local, normally git-ignored); pin important ones with `@example(...)`. + +## Minimal example + + from hypothesis import given, settings, strategies as st + + def encode(b: bytes) -> str: + return b.hex() + + def decode(s: str) -> bytes: + return bytes.fromhex(s) + + @settings(max_examples=500) + @given(st.binary(max_size=256)) + def test_round_trip(data): + assert decode(encode(data)) == data + + # money: integer cents, never floats + @given(st.integers(0, 10**9), st.integers(0, 10**9)) + def test_add_commutes(a, b): + assert a + b == b + a + +## Run + + python3 -m pytest -q tests/test_props.py + +Passing looks like: `2 passed` and exit 0. +Failure shows `Falsifying example: test_round_trip(data=b'\x00')` (shrunk) and +exit 1. Add `--hypothesis-seed=0` to make a run reproducible in CI, and +`--hypothesis-show-statistics` to see how many examples were valid. + +## As a contract check + + {"id": "prop-round-trip-py", "claim": "decode(encode(x)) == x for generated byte strings", "kind": "parsing", "rung": 2, "cmd": "python3 -m pytest -q tests/test_props.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- It samples; the default is 100 examples. Raise `max_examples` for important laws and keep strategies as wide as real input. +- Overusing `assume()` or `.filter()` makes most examples discarded; Hypothesis warns with a health-check failure. Fix the strategy, do not suppress the check. +- To check the test can fail, break the code on purpose and see a shrunk `Falsifying example`. A fixed seed (`derandomize=True`) repeats the same sample forever, so run it with a random seed too. diff --git a/verifiers/many-inputs/jazzer.md b/verifiers/many-inputs/jazzer.md new file mode 100644 index 0000000..02350e9 --- /dev/null +++ b/verifiers/many-inputs/jazzer.md @@ -0,0 +1,73 @@ +--- +id: jazzer +title: Fuzzing the JVM and JavaScript with Jazzer and Jazzer.js +answers: Can any input make this Java, Kotlin or Node code throw an unexpected exception, hang or hit a known bug pattern? +rung: 2 +section: many-inputs +languages: java, kotlin, javascript, typescript +kinds: parsing, general +cost: medium +detect: jazzer --help +ran_here: no +verified: docs +--- + +## Use when + +- JVM or Node code parses or processes untrusted input and should throw only documented errors. +- You want fuzz tests that run as ordinary unit tests (replaying saved crashes) in CI and as a long fuzz job on demand. +- You want built-in detectors for common problems (injection sinks, unsafe deserialisation). + +## Do not use when + +- You want shrinking and structured values: `jqwik` or `fast-check`. +- The code is Python (`atheris`) or Go (`go-fuzz`). + +## Set up + +JVM (JUnit 5): add `com.code-intelligence:jazzer-junit` as a test dependency +(Maven Central; use the current version). A standalone `jazzer` binary is on the +project's GitHub releases page. +Node: `npm install --save-dev @jazzer.js/core` (and `@jazzer.js/jest-runner` for Jest). + +## Minimal example (JVM, `ParserFuzzTest.java`) + + import com.code_intelligence.jazzer.junit.FuzzTest; + + class ParserFuzzTest { + @FuzzTest + void parsePairNeverCrashes(String input) { + try { + Parser.parsePair(input); + } catch (IllegalArgumentException expected) { + // the documented error; any other exception is a finding + } + } + } + +Node equivalent (`fuzz.js`): `module.exports.fuzz = function (data /* Buffer */) { parsePair(data.toString()); };` + +## Run + + JAZZER_FUZZ=1 mvn test -Dtest=ParserFuzzTest # fuzzing mode + mvn test # regression mode: replays saved crashes only + npx jazzer fuzz # Node; see `npx jazzer --help` for corpus and time flags + +Without `JAZZER_FUZZ=1` the JUnit tests only replay saved inputs, so a plain test run +is quick and never fuzzes. Passing looks like: tests pass, exit 0. Failure reports the +stack trace and writes the crashing input under +`src/test/resources//Inputs//`; commit it so regression +mode replays it. A time budget for the JVM and Node jobs is a libFuzzer flag +(`-max_total_time=60`); I could not confirm from the docs how each wrapper passes it. + +## As a contract check + + {"id": "fuzz-parser-jvm", "claim": "parsePair throws only IllegalArgumentException and all saved crashing inputs still pass", "kind": "parsing", "rung": 2, "cmd": "mvn -q test -Dtest=ParserFuzzTest", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600} + +This replays the saved inputs; a fuzzing-mode job is a separate scheduled run. + +## What a pass does not prove + +- In regression mode it only re-checks saved inputs; it does not search. +- A fuzzing run finding nothing is not a proof; budget and seed corpus matter. +- Not run here (no JDK is set on this machine). `@FuzzTest`, `JAZZER_FUZZ`, the artifact location and the Node install and signature are from the project READMEs; Node corpus and time flags were not confirmed. Check the check: plant a crash and see it found. diff --git a/verifiers/many-inputs/jqwik.md b/verifiers/many-inputs/jqwik.md new file mode 100644 index 0000000..28220d9 --- /dev/null +++ b/verifiers/many-inputs/jqwik.md @@ -0,0 +1,70 @@ +--- +id: jqwik +title: Property testing on the JVM with jqwik +answers: Does this Java or Kotlin code hold its law for generated inputs, and what is the smallest failing sample? +rung: 2 +section: many-inputs +languages: java, kotlin +kinds: general, parsing, money, state-machine +cost: medium +detect: java -version +ran_here: no +verified: docs +--- + +## Use when + +- JVM code has a law that must hold for all inputs and you run tests with Gradle or Maven. +- You want shrinking, replayable seeds and generators built from annotations. + +## Do not use when + +- The author asks agents not to use it: since version 1.10 the jqwik user guide has an "Anti-AI Usage Clause" saying "This project is not meant to be used by any “AI” coding agents at all" and adding that the test engine prints a line to stdout on every run telling agents not to use the library; the main JVM alternative is Kotest's property testing (`io.kotest:kotest-property`, Kotlin API, actively released), and for plain Java `junit-quickcheck` exists but has had no commits since 2024. +- You need coverage-guided search for a parser. Use `jazzer`. +- The project is locked to JUnit 4 only; jqwik runs as its own JUnit Platform engine. + +## Set up + +Gradle (versions as in the jqwik user guide at the time of writing; check for newer): + + testImplementation "net.jqwik:jqwik:1.10.2" + test { useJUnitPlatform { includeEngines 'jqwik' } } + +Maven: dependency `net.jqwik:jqwik:1.10.2`, scope `test`. Add `-parameters` to +the Java compiler flags so failure reports show argument names. + +## Minimal example + + import net.jqwik.api.*; + + class RoundTripProperties { + static String encode(byte[] b) { return java.util.HexFormat.of().formatHex(b); } + static byte[] decode(String s) { return java.util.HexFormat.of().parseHex(s); } + + @Property(tries = 1000) + boolean roundTrips(@ForAll byte[] data) { + return java.util.Arrays.equals(decode(encode(data)), data); + } + } + +## Run + + ./gradlew test # or: mvn test + +Passing looks like: the build succeeds, exit 0, the test report shows the property +with `tries = 1000` and no failures. +Failure shows `Shrunk Sample (N steps)` and `Original Sample` plus a `seed`; the +build exits non-zero. By default the next run tries the failing sample first +(`afterFailure = SAMPLE_FIRST`); jqwik keeps this in a local database file, so check +whether your build wipes it. Reproduce explicitly with `@Property(seed = "...")`. + +## As a contract check + + {"id": "prop-round-trip-jvm", "claim": "decode(encode(x)) equals x for generated byte arrays", "kind": "parsing", "rung": 2, "cmd": "./gradlew test --tests 'RoundTripProperties'", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"} + +## What a pass does not prove + +- It samples 1000 tries by default; edge cases (empty, extremes) are favoured but not exhaustive. +- A fixed `seed` left in committed code freezes the sample; use `whenFixedSeed = FAIL` to forbid it. +- If the engine is not on the test classpath the property is silently never run: confirm the report lists it. Break the code once and see it fail. +- Not run here (no JDK version is set on this machine). Coordinates, annotations and the shrinking output are from the user guide; the failure-database location was not confirmed. diff --git a/verifiers/many-inputs/metamorphic.md b/verifiers/many-inputs/metamorphic.md new file mode 100644 index 0000000..f145c3e --- /dev/null +++ b/verifiers/many-inputs/metamorphic.md @@ -0,0 +1,70 @@ +--- +id: metamorphic +title: Metamorphic testing when there is no oracle +answers: Even though I cannot say what the right answer is, does changing the input in a known way change the output in the way it must? +rung: 2 +section: many-inputs +languages: any +kinds: general, parsing, money +cost: low +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- You cannot compute the expected output independently (search ranking, compilers, numeric code, image or report generation) but you know how the output must relate across two related inputs. +- Typical relations: reordering the input does not change the result; scaling inputs scales outputs; adding an irrelevant item does not change the answer; a query with a stricter filter returns a subset. + +## Do not use when + +- An oracle or reference exists. Use `differential-reference`. +- The relation is only "decode undoes encode". That is `round-trip`. + +## Set up + +Pick relations from the domain, write each as a function of (input, transformed +input), and run them on generated inputs with `hypothesis`, `proptest` or +`fast-check`. One relation per test so a failure names it. + +## Minimal example (Python; a median function) + + from statistics import median + from hypothesis import given, strategies as st + + def my_median(xs): # under test + s = sorted(xs) + n = len(s) + return s[n // 2] if n % 2 else (s[n // 2 - 1] + s[n // 2]) / 2 + + nums = st.lists(st.integers(-10**6, 10**6), min_size=1, max_size=50) + + @given(nums, st.randoms()) + def test_order_does_not_matter(xs, rnd): + ys = xs[:]; rnd.shuffle(ys) + assert my_median(ys) == my_median(xs) + + @given(nums, st.integers(-1000, 1000)) + def test_shift_shifts_median(xs, k): + assert my_median([x + k for x in xs]) == my_median(xs) + k + + @given(nums, st.integers(1, 1000)) + def test_scale_scales_median(xs, k): + assert my_median([x * k for x in xs]) == my_median(xs) * k + +## Run + + python3 -m pytest -q test_metamorphic.py + +Passing looks like: `3 passed`, exit 0. Failure names the relation and shrinks the input. + +## As a contract check + + {"id": "meta-median", "claim": "median is order-independent and shifts and scales with its inputs", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_metamorphic.py", "expect": {"exit": 0, "stdout_contains": "3 passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- A relation only constrains the output, so a wrong function can satisfy one. Use several relations that together pin the behaviour down. +- It never proves the output is the right value, only that it is consistent. +- Check the check: replace the function with a plausible wrong one (the mean, the first element) and see at least one relation fail. diff --git a/verifiers/many-inputs/model-test-from-spec.md b/verifiers/many-inputs/model-test-from-spec.md new file mode 100644 index 0000000..c1b1bf9 --- /dev/null +++ b/verifiers/many-inputs/model-test-from-spec.md @@ -0,0 +1,79 @@ +--- +id: model-test-from-spec +title: Model test transcribed from a formal spec (TLA+ or Lean) +answers: Does the implementation behave like the formally specified design, step by step, including what it must refuse? +rung: 2 +section: many-inputs +languages: any +kinds: state-machine, money +cost: high +detect: python3 -c "import hypothesis" +ran_here: yes +verified: ran +--- + +## Use when + +- A TLA+, Lean or similar model of the design exists (or is being written) and its properties are proved or model-checked. +- You need the proof to reach the code: the proved design is only worth something if the implementation does what it says. +- Refusal rules matter (what must be rejected, and why), not just happy paths. + +## Do not use when + +- There is no formal model. Write a plain `stateful-model-test` instead. +- The model can be run directly as a program; then use `differential-executable-spec`, which needs no transcription. + +## Set up + +Write the model as a small pure function in the implementation's language, one +branch per spec action, from the spec text and not from the implementation. +Name each branch after the spec rule it transcribes. Then use the tooling from +`stateful-model-test` to drive both with random command sequences. + +## Minimal example (Python; the spec fragment is a TLA+ `Withdraw` action) + + from hypothesis import strategies as st + from hypothesis.stateful import RuleBasedStateMachine, rule + + # Spec: Withdraw(n) == n > 0 /\ n <= balance /\ balance' = balance - n + def spec_withdraw(balance, n): # returns (new_balance, refusal) + if n <= 0: return balance, "bad_amount" + if n > balance: return balance, "insufficient" + return balance - n, None + + class Account: # implementation under test + def __init__(self): self.balance = 100 + def withdraw(self, n): + if n <= 0: return "bad_amount" + if n > self.balance: return "insufficient" + self.balance -= n + + class AgainstSpec(RuleBasedStateMachine): + def __init__(self): + super().__init__(); self.impl, self.balance = Account(), 100 + + @rule(n=st.integers(-5, 150)) + def withdraw(self, n): + self.balance, want = spec_withdraw(self.balance, n) + assert self.impl.withdraw(n) == want # same decision, same reason + assert self.impl.balance == self.balance + + TestAgainstSpec = AgainstSpec.TestCase + +## Run + + python3 -m pytest -q test_against_spec.py + +Passing looks like: `1 passed`, exit 0. Failure names the command that diverged, with +the shrunk sequence. Keep the spec's rule ids in comments so a mismatch points at a rule. + +## As a contract check + + {"id": "model-vs-spec", "claim": "the implementation accepts and refuses commands as the TLA+ Withdraw action does", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_against_spec.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- The transcription is by hand. If it drifts from the spec, you test your reading of the spec; have it reviewed against the spec text. +- It samples sequences. The proof covers all of them; this only shows no counterexample was found. +- Commands the generator cannot express are not compared. List them. (One reference project's Lean differential test lists the model commands its input format cannot reach and leaves those to review.) +- Make the test fail on purpose: change one comparison in the implementation, or let the model allow something the spec forbids. diff --git a/verifiers/many-inputs/old-data-compatibility.md b/verifiers/many-inputs/old-data-compatibility.md new file mode 100644 index 0000000..fb2fa7b --- /dev/null +++ b/verifiers/many-inputs/old-data-compatibility.md @@ -0,0 +1,84 @@ +--- +id: old-data-compatibility +title: Compatibility with data written by older and newer versions +answers: Do files written by earlier versions still open to their recorded figures, and is data from a newer version reported as newer rather than corrupt? +rung: 3 +section: many-inputs +languages: any +kinds: migration, state-machine, money +cost: medium +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- The program reads files, databases or journals that users keep across upgrades. +- You change a format, a schema or the rules for computing a stored figure. +- An old version may meet newer data (downgrade, shared folder, restored backup). + +## Do not use when + +- You want sampled inputs: use `round-trip`; this uses fixed fixtures. + +## Set up + +1. When a format version ships, write real data with that version and commit it + as `tests/fixtures//` together with `expected.json`, the figures the + version itself computed. Never regenerate old fixtures with new code. +2. Keep a newer-format fixture (or fake one with a bumped format field). + +## Minimal example (Python) + + import json, pathlib, tempfile + + CURRENT = 2 + + def open_book(path): + data = json.loads(pathlib.Path(path).read_text()) # raises on garbage + v = data.get("format") + if v is None or not isinstance(v, int): + raise ValueError("corrupt: no format") + if v > CURRENT: + raise RuntimeError(f"newer: written by format {v}, this reader knows {CURRENT}") + return {"total": sum(data["cents"])} # v1 and v2 both store `cents` + + def test_old_fixture_reopens_to_recorded_figures(): + got = open_book("fixtures/v1/book.json") + assert got == json.load(open("fixtures/v1/expected.json")) + + def test_newer_is_reported_as_newer_and_left_untouched(): + p = pathlib.Path(tempfile.mkdtemp()) / "b.json" + p.write_text(json.dumps({"format": 3, "cents": [1]})) + before = p.read_bytes() + try: + open_book(p); assert False + except RuntimeError as e: + assert str(e).startswith("newer") + assert p.read_bytes() == before # never repaired or rewritten + + def test_damage_is_still_corrupt(): + p = pathlib.Path(tempfile.mkdtemp()) / "b.json" + p.write_text("{not json") + try: + open_book(p); assert False + except ValueError: pass + +## Run + + python3 -m pytest -q test_compat.py + +Passing looks like: `3 passed`, exit 0. Failure shows which fixture gave other figures, +or a newer file reported as corrupt (or the reverse). + +## As a contract check + + {"id": "old-data-compat", "claim": "v1 fixtures reopen to recorded figures; newer data is reported newer and untouched; damage stays corrupt", "kind": "migration", "rung": 3, "cmd": "python3 -m pytest -q test_compat.py", "expect": {"exit": 0, "stdout_contains": "3 passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- Only the fixtures you have: keep one per released format. +- Expected figures come from the old version; never regenerate them to make a test pass. +- It does not show an upgrade is safe on real data: test the upgrade step on a copy. +- Check the check: edit a fixture's figure and see the test fail; bump a format number and see "newer" appear. diff --git a/verifiers/many-inputs/proptest.md b/verifiers/many-inputs/proptest.md new file mode 100644 index 0000000..ce7c8c9 --- /dev/null +++ b/verifiers/many-inputs/proptest.md @@ -0,0 +1,73 @@ +--- +id: proptest +title: Property testing in Rust with proptest +answers: Does this Rust function keep its promise for every input I can generate, not just the few I thought of? +rung: 2 +section: many-inputs +languages: rust +kinds: general, parsing, money, state-machine +cost: low +detect: cargo --version +ran_here: yes +verified: ran +--- + +## Use when + +- A pure function or data structure has a law that must hold for all inputs: round trip, idempotence, agreement with a slow reference, "never panics". +- You want a failure reduced to a small input (shrinking) and replayed on every later run. +- Money, parsing or index arithmetic, where the dangerous inputs are ones nobody writes by hand. + +## Do not use when + +- The law cannot be stated without re-implementing the function. Use `metamorphic` or `differential-reference`. +- The property needs coverage-guided search of a deep parser. Use `cargo-fuzz`. +- A proof is affordable and a sample is not enough. See the `prove` section. + +## Set up + + cargo add --dev proptest + +Put the test in `#[cfg(test)]` in the crate or in `tests/props.rs`. Commit the +`proptest-regressions` files that proptest writes (see `regression-seed-hygiene`). + +## Minimal example + + pub fn encode(x: &[u8]) -> String { x.iter().map(|b| format!("{:02x}", b)).collect() } + pub fn decode(s: &str) -> Option> { + (0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect() + } + + #[cfg(test)] + mod tests { + use super::*; + use proptest::prelude::*; + proptest! { + #![proptest_config(ProptestConfig::with_cases(1000))] + #[test] + fn round_trip(bytes in proptest::collection::vec(any::(), 0..256)) { + prop_assert_eq!(decode(&encode(&bytes)), Some(bytes)); + } + } + } + +## Run + + cargo test round_trip + PROPTEST_CASES=10000 cargo test round_trip # more cases, same test + +Passing looks like: `test tests::round_trip ... ok` and exit 0. +Failure shows `minimal failing input: bytes = [0]` after shrinking, exit 101, and +a line saying the seed was saved to a `proptest-regressions/...` file. Later runs +replay that seed first. To make a test cheap for mutation testing or a slow +host, `PROPTEST_MAX_SHRINK_ITERS=0` turns shrinking off. + +## As a contract check + + {"id": "prop-round-trip", "claim": "decode(encode(x)) == x for generated byte strings", "kind": "parsing", "rung": 2, "cmd": "cargo test round_trip", "expect": {"exit": 0, "stdout_contains": "1 passed"}, "tier": "deep", "timeout_s": 600} + +## What a pass does not prove + +- It samples. 1000 cases of small inputs say nothing about the huge or odd ones the strategy never produces: check the ranges (`0..256`) against real input sizes. +- A filter such as `prop_assume!` that rejects most cases makes a pass nearly empty. proptest aborts with "too many local rejects" when that happens; do not raise the limit to silence it. +- To check the test can fail, break the code on purpose (change `{:02x}` to `{:x}` in `encode`) and see it fail with a shrunk input, then restore it. `cargo-mutants` does this at scale. diff --git a/verifiers/many-inputs/python-stdlib-property.md b/verifiers/many-inputs/python-stdlib-property.md new file mode 100644 index 0000000..4f9a116 --- /dev/null +++ b/verifiers/many-inputs/python-stdlib-property.md @@ -0,0 +1,69 @@ +--- +id: python-stdlib-property +title: Property-style tests with only the Python standard library +answers: Can I check a law over many generated inputs when I may not install any package? +rung: 2 +section: many-inputs +languages: python +kinds: general, parsing, money +cost: low +detect: python3 --version +ran_here: yes +verified: ran +--- + +## Use when + +- No third-party packages are allowed or available. +- The law is simple (round trip, ordering, agreement with a reference) and a bounded, seeded random loop is enough. +- You need a quick sample before deciding whether to bring in `hypothesis`. + +## Do not use when + +- Packages are allowed: `hypothesis` shrinks failures and remembers them; this does not. +- The input has structure that blind random bytes rarely satisfy (valid JSON, balanced entries). Write a structured generator or use `structure-aware-fuzzing`. + +## Set up + +Nothing to install. Put the test in `tests/test_props.py` and run it with `unittest`. + +## Minimal example + + import os, random, unittest + + def encode(b): return b.hex() + def decode(s): return bytes.fromhex(s) + + class Props(unittest.TestCase): + def test_round_trip(self): + fixed = [0, 1, 2] # always run: reproducible + fresh = [random.randrange(2**32) for _ in range(3)] # new ground each run + extra = [int(s) for s in os.environ.get("SEEDS", "").split(",") if s] + for seed in fixed + fresh + extra: + rng = random.Random(seed) + for _ in range(500): + data = bytes(rng.randrange(256) for _ in range(rng.randrange(64))) + with self.subTest(seed=seed, data=data): + self.assertEqual(decode(encode(data)), data) + + if __name__ == "__main__": + unittest.main() + +## Run + + python3 -m unittest discover -s tests + +Passing looks like: `Ran 1 test` then `OK`, exit 0. +Failure shows `FAIL: test_round_trip (seed=..., data=...)` with the seed and input +in the subTest label, exit 1. Reproduce a failing fresh seed with +`SEEDS= python3 -m unittest discover -s tests`, then copy it into `fixed`. + +## As a contract check + + {"id": "prop-round-trip-stdlib", "claim": "decode(encode(x)) == x over seeded random inputs", "kind": "parsing", "rung": 2, "cmd": "python3 -m unittest discover -s tests", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120} + +## What a pass does not prove + +- There is no shrinking: the failing input may be large. Print it, then reduce by hand. +- Uniform random bytes seldom hit edge cases (empty, maximum, boundary values). Add them to the generator explicitly. +- The checker only sees what the generator makes. Test the check by breaking the code on purpose and seeing it fail. diff --git a/verifiers/many-inputs/regression-seed-hygiene.md b/verifiers/many-inputs/regression-seed-hygiene.md new file mode 100644 index 0000000..7209ec5 --- /dev/null +++ b/verifiers/many-inputs/regression-seed-hygiene.md @@ -0,0 +1,70 @@ +--- +id: regression-seed-hygiene +title: Keeping failing seeds checked in, replayed and never orphaned +answers: Once a random test or fuzzer found a bug, is that exact input still replayed on every run so the bug cannot return? +rung: 2 +section: many-inputs +languages: any +kinds: general, parsing, state-machine +cost: low +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- You use proptest, Hypothesis, fast-check, a fuzzer or rapid, and a failure has been found, or will be. +- A random test went red once and green on re-run, and nobody recorded why. +- You are finishing a bug fix found by a random or fuzz test. + +## Do not use when + +- The suite has only fixed example tests; those already replay. + +## Set up + +Know where each tool keeps failures, and commit those: + +- proptest: `proptest-regressions/*.txt` (or `*.proptest-regressions` beside the test file); the path is printed on failure. +- cargo-fuzz: `fuzz/artifacts//crash-*`; copy fixed cases to `fuzz/seeds//`. +- Go native fuzzing: `testdata/fuzz/FuzzName/`; plain `go test` replays them. +- Hypothesis: `.hypothesis/` is local; pin the minimal case with `@example(...)` in the test. +- fast-check: pass `{ seed, path }` to reproduce, or add `examples: [[...]]` to keep it. + +## Minimal example (Hypothesis: pin the shrunk failure) + + from hypothesis import given, example, strategies as st + + def parse_amount(s): + return int(s.replace(",", "")) # fixed: used to reject "1,000" + + @given(st.integers(0, 10**9).map(lambda n: f"{n:,}")) + @example("1,000") # the case the fuzzer found; stays forever + def test_parse_amount(text): + assert parse_amount(text) == int(text.replace(",", "")) + +A cheap guard that none are orphaned (a deleted test leaves its seed file behind): + + # check_seeds.sh: every seed file maps to an existing test file + for f in proptest-regressions/*.txt; do + t=$(basename "$f" .txt); [ -e "src/$t.rs" ] || [ -e "tests/$t.rs" ] || { echo "orphaned: $f"; exit 1; } + done + +## Run + + python3 -m pytest -q test_amount.py + sh check_seeds.sh + +Passing looks like: `1 passed`, exit 0, and no `orphaned:` line. A removed pin makes +the pinned case vanish silently, so review diffs of `@example` and seed files. + +## As a contract check + + {"id": "seeds-replayed", "claim": "every saved failing input is replayed and no seed file is orphaned", "kind": "general", "rung": 2, "cmd": "python3 -m pytest -q test_amount.py && sh check_seeds.sh", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- Replay proves the old bug is not back, not that the area is clean. +- A seed recorded for an old test shape may no longer reach the same code after a refactor (proptest seeds depend on the strategy); for important bugs also add a plain named example test. +- Check the check: revert the fix and confirm the pinned or saved case fails by itself, with random generation turned off (`derandomize=True`, or a replay of only the seed file). diff --git a/verifiers/many-inputs/replay-equivalence.md b/verifiers/many-inputs/replay-equivalence.md new file mode 100644 index 0000000..028f5bd --- /dev/null +++ b/verifiers/many-inputs/replay-equivalence.md @@ -0,0 +1,78 @@ +--- +id: replay-equivalence +title: Replay equivalence for event-sourced and journalled state +answers: Is the live state exactly what you get by replaying the log from scratch, and does a refused command leave no trace? +rung: 2 +section: many-inputs +languages: any +kinds: state-machine, money +cost: medium +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- State is built from a log of events or journal lines (event sourcing, write-ahead logs, ledgers, undo stacks). +- Restart, backup restore and replication rebuild state by replay, so any drift between live and replayed state is data loss waiting to happen. +- Commands can be refused (validation, closed period, limits). + +## Do not use when + +- State is stored directly and no log exists. Use `fault-injection-storage` and `round-trip`. + +## Set up + +Expose two things: a way to apply a command (which may append to the log and +change live state) and a way to build state from the log alone. Drive both with +random command sequences, including commands that must be refused. + +## Minimal example (Python) + + from hypothesis import given, strategies as st + + class Store: + def __init__(self): self.log, self.balance = [], 0 + @staticmethod + def fold(log): # state from the log alone + b = 0 + for kind, n in log: + b += n if kind == "dep" else -n + return b + def command(self, kind, n): + if n <= 0 or (kind == "wd" and n > self.balance): + return "refused" + self.log.append((kind, n)) + self.balance += n if kind == "dep" else -n + return "ok" + + cmds = st.lists(st.tuples(st.sampled_from(["dep", "wd"]), st.integers(-3, 50)), max_size=40) + + @given(cmds) + def test_live_equals_replay_and_refusals_leave_no_trace(commands): + s = Store() + for kind, n in commands: + log_before, state_before = list(s.log), s.balance + if s.command(kind, n) == "refused": + assert s.log == log_before # nothing written + assert s.balance == state_before # nothing changed + assert s.balance == Store.fold(s.log) # live == replay, after every command + +## Run + + python3 -m pytest -q test_replay.py + +Passing looks like: `1 passed`, exit 0. Failure shows the shortest command list where live +and replayed state differ, or where a refusal wrote something. + +## As a contract check + + {"id": "replay-equivalence", "claim": "live state equals state replayed from the log after any command sequence, and refused commands change nothing", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_replay.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- Replay may use the same code as the live path, and then agrees trivially. Make replay a separate, simpler fold, or replay through the persisted bytes (write the log, reopen, compare). +- Compare everything observable (balances, indexes, derived reports), not one number; a field left out hides drift. +- Include refused commands in the generator, or the "no trace" half is never tested. Count how many were refused. +- Check the check: make a refused command append to the log, or make replay skip one event type, and see it fail. diff --git a/verifiers/many-inputs/round-trip.md b/verifiers/many-inputs/round-trip.md new file mode 100644 index 0000000..41b58fd --- /dev/null +++ b/verifiers/many-inputs/round-trip.md @@ -0,0 +1,68 @@ +--- +id: round-trip +title: Round-trip properties for encode/decode, serialise/parse and do/undo +answers: Does undoing an operation always return exactly what I started with, for every input I can generate? +rung: 2 +section: many-inputs +languages: any +kinds: parsing, general, money +cost: low +detect: +ran_here: yes +verified: ran +--- + +## Use when + +- A serialiser and a parser, an encoder and a decoder, a compressor and decompressor, or a do and an undo operation exist. +- Data is saved and reloaded (files, wire formats, journal lines, backups). +- You want a cheap check that loses no information, with no oracle needed. + +## Do not use when + +- The encoding is lossy by design; test the part that must survive instead. +- Only one direction exists; use `metamorphic` or `algebraic-laws`. + +## Set up + +Generate values of the in-memory type (not strings of the encoded form), encode, +decode, compare. Also test the other direction where it matters: for any text +the parser accepts, encoding the parsed value gives the canonical text again. + +## Minimal example (Python; JSON of integer cents) + + import json + from hypothesis import given, strategies as st + + entry = st.fixed_dictionaries({ + "memo": st.text(max_size=40), + "cents": st.integers(-2**63, 2**63 - 1), + "tags": st.lists(st.text(max_size=8), max_size=5), + }) + + @given(entry) + def test_value_round_trip(e): + assert json.loads(json.dumps(e)) == e + + @given(entry) + def test_text_is_stable(e): + text = json.dumps(e, sort_keys=True) + assert json.dumps(json.loads(text), sort_keys=True) == text + +## Run + + python3 -m pytest -q test_round_trip.py + +Passing looks like: `2 passed`, exit 0. +Failure shows the shrunk value that came back changed, exit 1. + +## As a contract check + + {"id": "round-trip-entry", "claim": "entries survive serialise then parse unchanged", "kind": "parsing", "rung": 2, "cmd": "python3 -m pytest -q test_round_trip.py", "expect": {"exit": 0, "stdout_contains": "2 passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- It shows no loss, not that the encoding is right: a format that stores the wrong thing round-trips perfectly. Add a golden file or reference parser for the format itself. +- It only covers values the generator makes. Give it the awkward ones: empty, maximum, negative, non-ASCII, a trailing newline, NaN if floats are allowed. +- Equal after the round trip can hide equality that is too loose (`1 == 1.0`, `0 == -0.0`); compare types and canonical text too. +- Check the check: drop a field from the encoder and see the test fail. diff --git a/verifiers/many-inputs/stateful-model-test.md b/verifiers/many-inputs/stateful-model-test.md new file mode 100644 index 0000000..e6d4cb8 --- /dev/null +++ b/verifiers/many-inputs/stateful-model-test.md @@ -0,0 +1,80 @@ +--- +id: stateful-model-test +title: Stateful model testing against a simple in-memory model +answers: After any sequence of operations, does the real system agree with a trivially simple model of what it should do? +rung: 2 +section: many-inputs +languages: rust, python, typescript, go +kinds: state-machine, general, money +cost: medium +detect: python3 -c "import hypothesis" +ran_here: yes +verified: ran +--- + +## Use when + +- The system has state and commands (a store, ledger, cache, queue, editor buffer) and bugs appear only after particular sequences. +- You can write a model in a few dozen lines using lists and dictionaries, with no performance tricks. +- You need to show that refused commands change nothing and that accepted ones do what the model says. + +## Do not use when + +- The model would be as complex as the system. Then the two share bugs; use `model-test-from-spec` or `differential-reference` instead. +- The behaviour is stateless: use `proptest`, `hypothesis` or `fast-check` directly. +- The commands race each other. See the `concurrency` section. + +## Set up + +Python: `pip install hypothesis`. Rust: `cargo add --dev proptest proptest-state-machine`. +TypeScript: `npm i -D fast-check` (`fc.commands`, `fc.modelRun`). Go: `rapid`'s `T.Repeat`. + +## Minimal example (Python, Hypothesis `RuleBasedStateMachine`) + + from hypothesis.stateful import RuleBasedStateMachine, rule, invariant + from hypothesis import strategies as st + + class Stack: # the system under test + def __init__(self): self.items = [] + def push(self, x): self.items.append(x) + def pop(self): return self.items.pop() + + class StackMachine(RuleBasedStateMachine): + def __init__(self): + super().__init__() + self.sut, self.model = Stack(), [] + + @rule(x=st.integers()) + def push(self, x): + self.sut.push(x); self.model.append(x) + + @rule() + def pop(self): + if self.model: # only when the model allows it + assert self.sut.pop() == self.model.pop() + + @invariant() + def same_contents(self): + assert self.sut.items == self.model + + TestStack = StackMachine.TestCase + +## Run + + python3 -m pytest -q test_stack.py + +Passing looks like: `1 passed`, exit 0. +Failure prints the shortest failing sequence as `state.push(x=0)`, `state.push(x=1)`, +`state.pop()`, exit 1. Rust prints `minimal failing input` with the transition list; +fast-check prints `Counterexample: [push(0),push(1),pop()]`. + +## As a contract check + + {"id": "model-stack", "claim": "the stack agrees with a list model after any command sequence", "kind": "state-machine", "rung": 2, "cmd": "python3 -m pytest -q test_stack.py", "expect": {"exit": 0, "stdout_contains": "passed"}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove + +- Sequences are short and random; a bug needing a rare long sequence can hide. Weight the generator toward commands that interact (post then reverse, close then add). +- A model that never reaches interesting states passes vacuously. Count how often each accepted command and each refusal occurs (one reference project's ledger test prints these under `MODEL_STATS=1`; its first version never posted an entry and agreed with the model for the wrong reason). +- Check the check: make the model wrong on purpose (for example allow a second reversal) and see the test fail quickly. +- It compares only what you read back. Compare every observable: results, refusals, and a full read of the state. diff --git a/verifiers/many-inputs/structure-aware-fuzzing.md b/verifiers/many-inputs/structure-aware-fuzzing.md new file mode 100644 index 0000000..ed1daa4 --- /dev/null +++ b/verifiers/many-inputs/structure-aware-fuzzing.md @@ -0,0 +1,79 @@ +--- +id: structure-aware-fuzzing +title: Structure-aware fuzzing with `arbitrary` and grammar-based inputs +answers: Can sequences of valid-looking operations, not just random bytes, break the code or its invariants? +rung: 2 +section: many-inputs +languages: rust +kinds: state-machine, parsing, money +cost: medium +detect: cargo fuzz --version +ran_here: yes +verified: ran +--- + +## Use when + +- Raw bytes almost never form valid input (JSON, command lists, balanced entries), so a plain fuzzer wastes its time on rejections. +- You want the fuzzer to drive a sequence of operations on a state machine and check invariants after each. +- The fuzz target should check more than "no panic": a model, a round trip, "a refused command changes nothing". + +## Do not use when + +- The input really is arbitrary bytes (a file format parser): use `cargo-fuzz` with `&[u8]`. +- You want shrinking and readable counterexamples: `proptest` is better at that. + +## Set up + + cargo add arbitrary --features derive # in the fuzz crate (cargo fuzz init already adds it) + +Derive `Arbitrary` on the input types. For grammar-style input (valid SQL, +JSON), write a small generator that turns the fuzzer's bytes into a valid +document with `Unstructured`, or use a grammar-based fuzzer such as `Grammarinator`. + +## Minimal example (`fuzz/fuzz_targets/fuzz_target_1.rs`) + + #![no_main] + use libfuzzer_sys::fuzz_target; + + // in the library crate: + // #[derive(Debug, arbitrary::Arbitrary)] + // pub enum Op { Deposit(u32), Withdraw(u32) } + // Account::apply(&mut self, &Op) -> Result<(), &'static str> + + fuzz_target!(|ops: Vec| { + let mut acct = mycrate::Account::default(); + let mut model: u64 = 0; + for op in &ops { + let before = acct.cents; + if acct.apply(op).is_ok() { + match op { + mycrate::Op::Deposit(n) => model += *n as u64, + mycrate::Op::Withdraw(n) => model -= *n as u64, + } + } else { + assert_eq!(acct.cents, before, "refused op changed state"); + } + assert_eq!(acct.cents as u64, model, "balance diverged from model"); + } + }); + +## Run + + RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 fuzz/corpus/fuzz_target_1 -- -max_total_time=60 + +Passing looks like: `Done N runs in 60 second(s)`, exit 0. +Failure prints the panic or assertion and the input as the `Debug` of the Rust +value (`[Withdraw(...)]`), then exits 1 with a crash file in `fuzz/artifacts/`. +Print an old crash as Rust values with `cargo fuzz fmt fuzz_target_1 `. + +## As a contract check + + {"id": "fuzz-account-ops", "claim": "no fuzzed operation sequence breaks the account model or changes state on refusal", "kind": "state-machine", "rung": 2, "cmd": "cd fuzz-host && RUSTUP_TOOLCHAIN=nightly cargo fuzz run fuzz_target_1 fuzz/corpus/fuzz_target_1 -- -max_total_time=60", "expect": {"exit": 0, "stdout_contains": "Done"}, "tier": "deep", "timeout_s": 600} + +## What a pass does not prove + +- Only what the run reached in its time budget; a clean run is not a proof. +- A derived `Arbitrary` makes uniform-looking values. If the interesting values (zero, maximum, the same account twice) are rare, bias the generator by hand. +- The invariants are only as good as the asserts. One reference project's operation-sequence target checks that the trial balance balances after any sequence; without that assert the same run would only look for panics. +- Check the check: seed a bug (the example subtracts one extra cent on withdrawal) and see the fuzzer find it within seconds. diff --git a/verifiers/prove/aeneas-rust-to-lean.md b/verifiers/prove/aeneas-rust-to-lean.md new file mode 100644 index 0000000..954603e --- /dev/null +++ b/verifiers/prove/aeneas-rust-to-lean.md @@ -0,0 +1,54 @@ +--- +id: aeneas-rust-to-lean +title: Translating Rust to Lean with Charon and Aeneas to prove real code +answers: Can I prove a property of my actual Rust function, not of a hand-written model of it? +rung: 1 +section: prove +languages: rust +kinds: general, parsing, money +cost: high +detect: aeneas --help +ran_here: no +verified: docs +--- + +## Use when +- The Rust is safe, mostly functional code (no heavy trait objects, little unsafe) and you want an unbounded proof about it. +- You need the proof to be about the compiled-from source, so `proof-bridging` is not enough. + +## Do not use when +- A bounded proof will do. `kani` is far cheaper. +- The code uses features Charon cannot translate (many closures, async, `dyn` traits). Check what it supports first. + +## Set up +Both tools are built from source; there is no package install. From the Aeneas and Charon READMEs (github.com/AeneasVerif/aeneas, .../charon): you need `rustup` (Charon pins its own nightly), OCaml 5 with opam (`opam switch create 5.3.0`, then `opam install src --deps-only --with-test` in the Aeneas checkout), and Lean. In the Aeneas checkout `make setup-charon` builds Charon at the commit in `charon-pin`, and `make` builds `bin/aeneas`. Put `charon` and `aeneas` on PATH. Not installed here, so nothing below was run. + +Translate, from inside the crate: +``` +charon cargo --preset=aeneas # writes .llbc +aeneas -backend lean my_crate.llbc -dest lean/ +``` +`-backend` also takes `fstar`, `coq` and `hol4`. Generated Lean files import the `Aeneas` package, so the Lean project needs it: `lake new`, copy `lean-toolchain` from `backends/lean` in the Aeneas repo, and require it in the lakefile with `[[require]] name = "aeneas" path = "PATH_TO_AENEAS_REPO/backends/lean"` (or `require aeneas from "PATH..."` in a `lakefile.lean`). Aeneas emits definitions in a `Result` monad for panics and overflow. Flags change between releases (both projects publish nightly releases); check `charon --help` and `aeneas --help`. + +## Minimal example +A Rust function to prove things about: +```rust +pub fn add_cents(a: u32, b: u32) -> Option { a.checked_add(b) } +``` +Aeneas emits a Lean `add_cents` returning a `Result`. You then write a theorem in a separate Lean file that says: if the result is `ok (some c)` then `c.val = a.val + b.val`, and prove it with the Aeneas tactics `step` (older releases called it `progress`; `step*` repeats it) and `scalar_tac` (arithmetic on bounded integers). The exact names and goal shapes depend on the generated code and library version, so copy the pattern from the Aeneas repository's `tests/lean/Tutorial/` (`Solutions.lean` uses `step as ⟨ ... ⟩` and `scalar_tac`). Not confirmed by running here. + +## Run +`lake build --wfail` in the Lean project, after regenerating the Lean files from the current Rust. + +Passing looks like: exit 0, and the audit of `lean-axiom-audit` is clean. Failure: Lean errors on the open goal. + +## As a contract check +```json +{"id": "prove-add-cents-aeneas", "claim": "add_cents is exact or None, proved on the Lean translation of the Rust", "kind": "money", "rung": 1, "cmd": "bash -c 'charon cargo --preset=aeneas && aeneas -backend lean my_crate.llbc -dest lean/ && cd lean && lake build --wfail'", "expect": {"exit": 0}, "timeout_s": 3600, "tier": "deep"} +``` + +## What a pass does not prove +- The translation must be regenerated on every Rust change; a stale `lean/` dir proves the old code. The command above regenerates first. +- Aeneas's own semantics are trusted, and the proof assumes the Rust compiler follows them. +- Unsafe code and unsupported features are excluded or axiomatised; read the generated file for `axiom` and `opaque`. +- Not run here: the charon and aeneas invocations, `-dest`, and the tactic names were checked against the READMEs, the Aeneas command-line source and its Lean tutorial, but the example theorem was not compiled. diff --git a/verifiers/prove/cbmc.md b/verifiers/prove/cbmc.md new file mode 100644 index 0000000..141cd75 --- /dev/null +++ b/verifiers/prove/cbmc.md @@ -0,0 +1,67 @@ +--- +id: cbmc +title: CBMC bounded model checking for C +answers: Can this C code overflow, read out of bounds or break an assert for any input within a loop bound? +rung: 1 +section: prove +languages: c +kinds: general, parsing +cost: medium +detect: cbmc --version +ran_here: yes +verified: ran +--- + +## Use when +- C code with buffers, indexes and integer arithmetic needs a check over all inputs up to a loop bound. +- You want memory-safety and overflow checks without writing a contract language. + +## Do not use when +- You need unbounded proofs. Use `frama-c-wp`. +- The code is Rust. Use `kani`, which is built on CBMC. + +## Set up +Install `cbmc` from your package manager or releases (github.com/diffblue/cbmc). Tried with 6.11.0, the binary that Kani bundles (`~/.kani/kani-*/bin/cbmc`). A C compiler is not needed for checking. + +## Minimal example +`a.c`: +```c +#include +#include + +int clamp(int lo, int hi, int x) { return x < lo ? lo : (x > hi ? hi : x); } + +uint32_t sum(const uint8_t *a, unsigned n) { + uint32_t s = 0; + for (unsigned i = 0; i < n; i++) s += a[i]; + return s; +} + +int main(void) { + int lo, hi, x; /* uninitialised = any value */ + __CPROVER_assume(lo <= hi); + int r = clamp(lo, hi, x); + assert(lo <= r && r <= hi); + + uint8_t buf[4]; + unsigned n; + __CPROVER_assume(n <= 4); + assert(sum(buf, n) <= 4 * 255); + return 0; +} +``` + +## Run +`cbmc a.c --bounds-check --pointer-check --signed-overflow-check --unwind 5 --unwinding-assertions` + +Passing looks like: `VERIFICATION SUCCESSFUL`, exit 0, and `** 0 of N failed`. Failure: `VERIFICATION FAILED` and exit 10 (seen after changing the assert to `lo < r`). `--unwinding-assertions` makes a loop that needs more iterations than `--unwind` fail instead of passing silently. + +## As a contract check +```json +{"id": "prove-clamp-cbmc", "claim": "clamp stays in [lo, hi] and sum has no memory errors for n <= 4", "kind": "general", "rung": 1, "cmd": "cbmc a.c --bounds-check --pointer-check --signed-overflow-check --unwind 5 --unwinding-assertions", "expect": {"exit": 0, "stdout_contains": "VERIFICATION SUCCESSFUL"}, "tier": "deep", "timeout_s": 900} +``` + +## What a pass does not prove +- Only paths within the unwind bound and the `assume`s. Omit `--unwinding-assertions` and the bound is not even checked. +- An unsatisfiable `__CPROVER_assume` makes everything pass; add a reachability assertion such as `__CPROVER_assert(0, "reached")` expecting failure, or use `--cover location`, to see the point is reached. +- Library calls without a model are treated as returning any value, which may cause false alarms but not false passes. diff --git a/verifiers/prove/creusot.md b/verifiers/prove/creusot.md new file mode 100644 index 0000000..90545d8 --- /dev/null +++ b/verifiers/prove/creusot.md @@ -0,0 +1,56 @@ +--- +id: creusot +title: Creusot deductive verification for Rust +answers: Does this Rust code satisfy its contracts for all inputs, proved through Why3? +rung: 1 +section: prove +languages: rust +kinds: general +cost: high +detect: cargo creusot --help +ran_here: no +verified: docs +--- + +## Use when +- You want proofs for safe Rust including ownership-heavy code (it models borrows prophetically) and are comfortable with the Why3 ecosystem. +- Contracts as attributes (`#[requires]`, `#[ensures]`, `#[logic]`) suit you better than a separate macro block. + +## Do not use when +- You need low set-up cost. Use `kani`. Creusot needs opam, Why3 and SMT solvers. +- Unsafe or heavily dynamic code is involved. + +## Set up +From the Creusot README and guide ("Installation"): there is no `cargo install`. Needs `rustup`, `opam` (for Why3 and `why3find`) and `curl` (to download the provers alt-ergo, z3, cvc4 and cvc5). Then: + + git clone https://github.com/creusot-rs/creusot + cd creusot + ./INSTALL # a few minutes; makes a private opam switch under ~/.local/share/creusot/_opam + cargo creusot --help # check the install + +Create a project with `cargo creusot new project-name`, or add the contracts crate to an existing one (the crate is now `creusot-std`, imported as `creusot_std`; if the compiler says its items are missing, the guide's troubleshooting section shows a `[patch.crates-io]` entry pointing at the checkout). Not installed here, so the example was not run. + +## Minimal example +```rust +use creusot_std::prelude::*; + +#[requires(a@ + b@ <= u32::MAX@)] +#[ensures(result@ == a@ + b@)] +pub fn add(a: u32, b: u32) -> u32 { a + b } +``` +`x@` is the logical (mathematical) value of `x`. Spec language details change by release; follow the guide's current examples. + +## Run +`cargo creusot` compiles the crate to Coma (into `verif/`) and then runs the provers through Why3find. The two steps can be run separately: `cargo creusot --only=coma` and `cargo creusot --only=prove`. A Coma file can be named to prove just that one; `-i` opens the Why3 IDE when a proof fails; `--replay` only re-checks existing proofs (`proof.json`). There is no `cargo creusot prove` subcommand in the current guide. + +Passing looks like: the guide says a successful run "gives us the certainty that functions defined in this package satisfy their contracts". It does not state what the output or exit status looks like for unproved goals; check on a deliberately wrong contract that `cargo creusot` exits non-zero before relying on exit alone. Only libraries and binaries are compiled, not tests or examples. + +## As a contract check +```json +{"id": "prove-add-creusot", "claim": "add returns the exact sum when it fits in u32", "kind": "general", "rung": 1, "cmd": "cargo creusot", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"} +``` + +## What a pass does not prove +- Only the contracts written; functions marked `#[trusted]` are assumed. Grep for `trusted`. +- Proofs by SMT solvers can time out; whether an unproved goal makes `cargo creusot` exit non-zero is not documented, so test it. +- Not run here; commands come from the Creusot README, guide and command-line reference. `#[trusted]` (also in the guide) skips checking of the function body, and the `x@` notation for the logical value is as in the guide's quick start. diff --git a/verifiers/prove/crosshair.md b/verifiers/prove/crosshair.md new file mode 100644 index 0000000..bf9486f --- /dev/null +++ b/verifiers/prove/crosshair.md @@ -0,0 +1,56 @@ +--- +id: crosshair +title: CrossHair symbolic checking of Python contracts +answers: Can I find any inputs that break this Python function's contract or type annotations? +rung: 2 +section: prove +languages: python +kinds: general, parsing +cost: low +detect: crosshair --version +ran_here: yes +verified: ran +--- + +## Use when +- Pure Python functions with a docstring contract (`pre:` / `post:`) or PEP 316 / icontract / deal contracts. +- You want a solver to hunt for counterexamples before writing property tests. +- You want it to replay found inputs as ordinary tests. + +## Do not use when +- The function does I/O, uses C extensions heavily or hashing-dependent logic: the solver gives up. +- You need a proof. Silence from CrossHair means "none found in the time given", so this is rung 2 here. Use `dafny`, `z3-smt` or `lean4-proofs` for rung 1. + +## Set up +`pip install crosshair-tool` (5.4.1 observed; use a virtualenv). Contracts live in docstrings. + +## Minimal example +`cc.py`: +```python +def clamp(lo: int, hi: int, x: int) -> int: + """ + pre: lo <= hi + post: lo <= __return__ <= hi + """ + if x < lo: + return lo + if x > hi: + return hi + return x +``` +Add a function with a false postcondition to see failure, for example `post: __return__ >= 0` on `return x - 1 if x > 0 else x`. + +## Run +`crosshair check cc.py --per_condition_timeout=30` + +Passing looks like: no output and exit 0. Failure: a line like `cc.py:14: error: false when calling bad(-1) (which returns -1)` and exit 1 (observed). `--per_condition_timeout` bounds the search per function. + +## As a contract check +```json +{"id": "prove-clamp-crosshair", "claim": "clamp satisfies its postcondition for all inputs CrossHair can find in 30 seconds", "kind": "general", "rung": 2, "cmd": "crosshair check cc.py --per_condition_timeout=30", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600} +``` + +## What a pass does not prove +- A time-limited search that found nothing; it does not say it covered all paths. Raise the timeout once and see whether a failure appears. +- It checks only the contract you wrote. A weak or missing `post:` passes everything. +- Add a failing function as a canary to confirm the run really analyses your file. diff --git a/verifiers/prove/dafny.md b/verifiers/prove/dafny.md new file mode 100644 index 0000000..0ebb28a --- /dev/null +++ b/verifiers/prove/dafny.md @@ -0,0 +1,65 @@ +--- +id: dafny +title: Dafny verified algorithms that compile to a target language +answers: Does this algorithm meet its specification for all inputs, and can I run the verified code? +rung: 1 +section: prove +languages: dafny +kinds: general, state-machine +cost: medium +detect: dafny --version +ran_here: yes +verified: ran +--- + +## Use when +- You are writing an algorithm or data structure from scratch and can write it in Dafny, then compile to Python, Go, Java, C# or JavaScript. +- You want pre/postconditions and loop invariants checked by an SMT solver for all inputs. +- A spec-first workflow fits: `requires`/`ensures` first, body second. + +## Do not use when +- The code already exists in Rust, C or Python and must be verified as is. Use `verus`, `kani`, `frama-c-wp` or `crosshair`. +- The compiled output must meet tight performance or integration needs the target backend cannot. + +## Set up +Download the release zip from github.com/dafny-lang/dafny/releases (4.11.0 tried; it includes its own runtime, Z3 included) and unzip. No global install needed: call `./dafny/dafny`. + +## Minimal example +`a.dfy`: +```dafny +method Abs(x: int) returns (y: int) + ensures y >= 0 && (y == x || y == -x) +{ + if x < 0 { y := -x; } else { y := x; } +} + +method SumTo(n: nat) returns (s: nat) + ensures s == n * (n + 1) / 2 +{ + s := 0; + var i := 0; + while i < n + invariant i <= n && s == i * (i + 1) / 2 + { + i := i + 1; + s := s + i; + } +} + +method Main() { var r := Abs(-3); print r, "\n"; } +``` + +## Run +`dafny verify a.dfy`, then `dafny run --target:py a.dfy` to compile and run on Python. + +Passing looks like: exit 0 and `Dafny program verifier finished with 4 verified, 0 errors`. Failure: an error with the failing line and `finished with 3 verified, 1 error`, exit 4 (observed after changing `s + i` to `s + i + 1`). Use `--verification-time-limit ` (default 30) to bound each assertion batch; a timeout is reported as an error. + +## As a contract check +```json +{"id": "prove-sumto-dafny", "claim": "SumTo and Abs satisfy their postconditions for all inputs", "kind": "general", "rung": 1, "cmd": "dafny verify a.dfy", "expect": {"exit": 0, "stdout_contains": "0 errors"}, "tier": "deep", "timeout_s": 600} +``` + +## What a pass does not prove +- Only the written `ensures`. A weak postcondition (say `ensures true`) verifies trivially; review the specs. +- `assume` statements, `{:axiom}` and `{:verify false}` skip proof; grep for them. Termination is checked unless `decreases *` is used. +- The compiled program is trusted to match: the compiler and runtime are not verified. Target-language integers and I/O are outside the proof. diff --git a/verifiers/prove/exhaustive-small-domain.md b/verifiers/prove/exhaustive-small-domain.md new file mode 100644 index 0000000..d3a8c1d --- /dev/null +++ b/verifiers/prove/exhaustive-small-domain.md @@ -0,0 +1,65 @@ +--- +id: exhaustive-small-domain +title: Brute-forcing every input when the domain is small enough +answers: Does this function give the right answer for every possible input, because I tried them all? +rung: 1 +section: prove +languages: any +kinds: general, money, parsing +cost: low +detect: +ran_here: yes +verified: ran +--- + +## Use when +- The input domain is small: every `u8`, every `u16`, every pair of `u8` (65,536), every string up to length 3 over a small alphabet. +- You have a reference you trust (a wider type, a formula, a slow obvious version) to compare against. +- A proof tool would be heavier than a loop that finishes in seconds. + +## Do not use when +- The domain is `u32` pairs or larger (about 1.8e19 cases). Use `kani`, `z3-smt` or a property test (rung 2). +- You would need to sample. Sampling is a property test, not this. + +## Set up +Nothing. Count the cases first: `domain_size = product of each input's range`. Keep it under roughly 1e9 for fast code and write the number in the test. + +## Minimal example +```rust +#[test] +fn every_u8_is_accepted_or_refused_correctly() { + for v in 0..=u8::MAX { + assert_eq!(Percent::new(v).is_some(), v <= 100); + } +} + +#[test] +fn every_u16_checked_add_matches_the_wide_sum() { + let mut n = 0u64; + for a in 0..=u16::MAX { + for b in 0..=u16::MAX { + let w = a as u32 + b as u32; + assert_eq!(a.checked_add(b).map(u32::from), (w <= 65535).then_some(w)); + n += 1; + } + } + assert_eq!(n, 65_536 * 65_536); // proves the loop ran over the whole domain +} +``` +In Python use `itertools.product(range(256), repeat=2)` and assert the count. + +## Run +`cargo test --release every_` + +Passing looks like: exit 0 and `test result: ok. 2 passed`. The full pair loop takes a few seconds in release mode. Failure: the first failing input is in the panic message. + +## As a contract check +```json +{"id": "many-inputs-u16-add", "claim": "checked_add on u16 matches the exact sum for every pair of u16 values", "kind": "general", "rung": 1, "cmd": "cargo test --release every_", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600} +``` + +## What a pass does not prove +- It proves the claim only on that domain. A function on `u64` tested over `u16` is a sample of it, so call it rung 2 then. +- The reference answer can itself be wrong; derive it independently. +- Assert the loop count (as above) so that an edited range or an early `continue` cannot shrink the domain silently. +- If the domain is too large to finish, do not cut it down and still call it exhaustive. diff --git a/verifiers/prove/flux-refinement-types.md b/verifiers/prove/flux-refinement-types.md new file mode 100644 index 0000000..216d4e3 --- /dev/null +++ b/verifiers/prove/flux-refinement-types.md @@ -0,0 +1,60 @@ +--- +id: flux-refinement-types +title: Flux refinement types for Rust +answers: Can my Rust signatures carry value constraints (positive, in range, indexes in bounds) that the compiler checks? +rung: 1 +section: prove +languages: rust +kinds: general +cost: medium +detect: command -v cargo-flux +ran_here: no +verified: docs +--- + +## Use when +- The properties are small value constraints on arguments and results: an index below a length, a non-zero divisor, a sum within a bound. +- You want checking close to type checking, with little proof effort, and mostly automatic inference of loop invariants. + +## Do not use when +- The property is relational or complex (sorted, permutation, money laws). Use `verus`, `lean4-proofs` or `kani`. +- You cannot use Flux's pinned nightly toolchain. + +## Set up +From the Flux book ("Installing and Running Flux"): the only way to use Flux is to build it from source. Requirements: `rustup`, `liquid-fixpoint` (nightly binaries on its GitHub releases) and `z3` 4.15 or later, both on PATH. Then either `curl -fsSL https://raw.githubusercontent.com/flux-rs/flux/main/install.sh | bash`, or: + + git clone https://github.com/flux-rs/flux && cd flux + cargo xtask install # installs `flux` and `cargo-flux`, and the sysroot in ~/.flux/sysroot + +The repository's `rust-toolchain.toml` pins the nightly. To use it in a Cargo package, add to `Cargo.toml`: + + [package.metadata.flux] + enabled = true + [dependencies] + flux-rs = { git = "https://github.com/flux-rs/flux.git" } + +Not installed here, so the example was not run. + +## Minimal example +```rust +use flux_rs::attrs::*; + +#[spec(fn(x: i32{x > 0}) -> i32{v: v > x})] +fn bump(x: i32) -> i32 { x + 1 } +``` +On a single file run with the standalone `flux` binary, write the attribute as `#[flux::spec(...)]` instead. Overflow of `x + 1` is checked only if you switch on `check-overflow` in the `[package.metadata.flux]` section (default `none`; see the book's "Checking Overflows"); this example passes without it. + +## Run +`cargo flux` (a package), or `flux --crate-type=lib path/to/file.rs` (one file; it accepts the same flags as `rustc`). + +Passing looks like: no errors reported. Failure: the book's example shows `error[FLUX]: postcondition might not hold` with the source location (a wrong body such as `x - 1`). The book does not state the exit status; the driver is a rustc wrapper and should exit non-zero on errors, but confirm with a deliberately wrong body. + +## As a contract check +```json +{"id": "prove-bump-flux", "claim": "bump returns a value greater than its positive argument", "kind": "general", "rung": 1, "cmd": "cargo flux", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"} +``` + +## What a pass does not prove +- Only the refinements stated in signatures; unannotated code gets default (weak) types. `#[flux_rs::trusted]` (`#[flux::trusted]` on a single file) skips checking. +- Annotations are written by you; a trivially true refinement verifies trivially. +- Not run here; commands and messages come from the Flux book. Check the check: change the body to `x - 1` and confirm `cargo flux` fails. diff --git a/verifiers/prove/frama-c-wp.md b/verifiers/prove/frama-c-wp.md new file mode 100644 index 0000000..aee4490 --- /dev/null +++ b/verifiers/prove/frama-c-wp.md @@ -0,0 +1,51 @@ +--- +id: frama-c-wp +title: Frama-C WP for C with ACSL contracts +answers: Does this C function meet its contract and avoid undefined behaviour for all inputs? +rung: 1 +section: prove +languages: c +kinds: general, parsing +cost: high +detect: frama-c -version +ran_here: no +verified: docs +--- + +## Use when +- Small, critical C functions (parsers, buffers, arithmetic, drivers) need a proof that holds for all inputs, with no unwinding bounds. +- You can write ACSL contracts (`requires`, `ensures`, `assigns`, loop invariants) in comments. + +## Do not use when +- You only need a bounded check with minimal effort. Use `cbmc`. +- The code relies on heavy pointer aliasing, floating point, or concurrency without a plan. + +## Set up +Install with opam (the Frama-C site's recipe: `opam init --compiler 4.14.1`, `eval $(opam env)`, `opam install frama-c`). Per the WP manual (written for Frama-C 33.0 "Arsenic", July 2026), the WP plug-in ships with Frama-C, needs the Why3 platform and at least one external prover, and opam installs Alt-Ergo and Why3 automatically; WP finds provers on `$PATH` and in the Why3 configuration. Not installed here, so nothing below was run. + +## Minimal example +`abs.c`: +```c +#include +/*@ requires x > INT_MIN; + assigns \nothing; + ensures \result >= 0 && (\result == x || \result == -x); +*/ +int my_abs(int x) { return x < 0 ? -x : x; } +``` + +## Run +`frama-c -wp -wp-rte -wp-timeout 20 abs.c` + +Passing looks like: a line `[wp] Proved goals: N / N` (the manual shows `[wp] Proved goals: 4 / 4`; a run with a failure shows `Proved goals: 6 / 7` and an `Unknown:` count). `-wp-rte` adds the no-undefined-behaviour obligations (overflow, bounds) and `-wp-timeout` is the per-goal prover timeout in seconds (default 2). The manual does not document an exit status for unproved goals, and Frama-C is commonly seen exiting 0 with unproved goals, so the contract tests the text. Real output may pad the numbers with extra spaces, so the pattern allows them: +`frama-c ... | grep -E 'Proved goals: +([0-9]+) / \1$'` (the backreference is GNU grep). + +## As a contract check +```json +{"id": "prove-abs-framac", "claim": "my_abs meets its contract and has no runtime errors when x > INT_MIN", "kind": "general", "rung": 1, "cmd": "bash -c \"frama-c -wp -wp-rte -wp-timeout 20 abs.c | tee /dev/stderr | grep -E 'Proved goals: +([0-9]+) / \\\\1$'\"", "expect": {"exit": 0}, "timeout_s": 900, "tier": "deep"} +``` + +## What a pass does not prove +- Only the written contract, under a memory model that assumes no aliasing the contract does not allow. `assigns` clauses must be right. +- All goals proved means none were skipped by `-wp-timeout`; a timeout counts as unproved, which the `N / N` test catches. +- Not run here; the output format is from the WP manual's examples. Confirm the exit status and spacing of the `Proved goals` line on your version, and check the check by weakening the `ensures` so a goal fails. diff --git a/verifiers/prove/illegal-states-unrepresentable.md b/verifiers/prove/illegal-states-unrepresentable.md new file mode 100644 index 0000000..f11546e --- /dev/null +++ b/verifiers/prove/illegal-states-unrepresentable.md @@ -0,0 +1,66 @@ +--- +id: illegal-states-unrepresentable +title: Making illegal states unrepresentable with types, checked by a compile-fail test +answers: Is it impossible, not just unlikely, for callers to build an invalid value or call an operation in the wrong state? +rung: 1 +section: prove +languages: rust, typescript +kinds: general, state-machine, money +cost: low +detect: cargo --version +ran_here: yes +verified: ran +--- + +## Use when +- A value has a validity rule (a percentage 0 to 100, a non-empty list, a validated email) that is currently checked in many places. +- An object has phases (closed then open, draft then posted) and calls are only legal in some of them. +- You want the compiler to reject misuse, and a test that proves it does. + +## Do not use when +- The rule depends on runtime data the type cannot hold (a balance across accounts). Use a runtime check plus `kani` or tests. +- A quick enum or `Option` already forces the case. Do not add types for show. + +## Set up +Rust: nothing extra. Make fields private and expose a constructor that validates (parse, don't validate: return `Option`/`Result` once at the edge, then pass the type everywhere). Use enums and exhaustive `match` with no `_` arm; use the typestate pattern with a type parameter for phases. For compile-fail tests use `compile_fail` doctests, or the `trybuild` crate (add under `[dev-dependencies]`) to compare compiler output. +TypeScript: see `typescript-type-level`. + +## Minimal example +```rust +pub struct Percent(u8); // private field +impl Percent { + pub fn new(v: u8) -> Option { (v <= 100).then_some(Percent(v)) } + pub fn get(self) -> u8 { self.0 } +} + +pub struct Conn(std::marker::PhantomData); +pub struct Open; pub struct Closed; +impl Conn { pub fn open(self) -> Conn { Conn(std::marker::PhantomData) } } +impl Conn { pub fn send(&self, _b: &[u8]) {} } + +/// ```compile_fail +/// use ise::Percent; +/// let p = Percent(250); // private field: must not compile +/// ``` +/// +/// ```compile_fail +/// use ise::Conn; +/// Conn::new().send(b"x"); // a closed connection has no `send` +/// ``` +pub struct CompileFailTests; +``` +(Add `Conn::new() -> Conn`.) The crate is named `ise` in the doctests. + +## Run +`cargo test --doc` + +Passing looks like: exit 0 and `test src/lib.rs - CompileFailTests (line N) - compile fail ... ok`. Failure: a `compile_fail` test whose code does compile shows `Test compiled successfully, but it's marked 'compile_fail'.` and exits 101. With `trybuild`, `cargo test` compares the real compiler message with a stored `.stderr` file. + +## As a contract check +```json +{"id": "prove-percent-unrepresentable", "claim": "A Percent above 100 and a send on a closed connection cannot be written: both fail to compile", "kind": "general", "rung": 1, "cmd": "cargo test --doc", "expect": {"exit": 0, "stdout_contains": "compile fail"}, "tier": "deep", "timeout_s": 600} +``` + +## What a pass does not prove +- A `compile_fail` test passes on any compile error, including a typo. Observed: adding an error code like `compile_fail,E0451` is not enforced on stable (a wrong code still passed). Use `trybuild`, which pins the message, for tests that must fail for the right reason. +- Rules the type cannot express remain open; construction inside the defining module bypasses private-field checks. Keep the smart constructor the only way in, and review `unsafe` and `Default`/`Deserialize` impls that could build invalid values. diff --git a/verifiers/prove/isabelle.md b/verifiers/prove/isabelle.md new file mode 100644 index 0000000..d472be4 --- /dev/null +++ b/verifiers/prove/isabelle.md @@ -0,0 +1,54 @@ +--- +id: isabelle +title: Isabelle/HOL proofs with Sledgehammer +answers: Is this property proved by machine, with automatic proof search to help? +rung: 1 +section: prove +languages: any +kinds: general, state-machine +cost: high +detect: isabelle version +ran_here: no +verified: docs +--- + +## Use when +- Your team already uses Isabelle, or you build on the Archive of Formal Proofs. +- You want strong automation: Sledgehammer calls external provers and returns a proof line to paste in. +- The claim is about algorithms or specifications over lists, sets and numbers. + +## Do not use when +- You have no existing Isabelle investment. `lean4-proofs` has better command-line tooling for agents. +- A bounded check is enough (`kani`, `cbmc`). + +## Set up +Download the bundle for your platform from isabelle.in.tum.de (current release: Isabelle2026, October 2026; it includes its own Java, ML system and provers). On Linux, unpack it and put its `bin/` on PATH (the install page shows `Isabelle2026/bin/isabelle`). Not installed here, so the example was not run. A session is a directory with a `ROOT` file: +``` +session Demo = HOL + + theories Demo +``` + +## Minimal example +`Demo.thy`: +```isabelle +theory Demo imports Main begin +theorem rev_rev: "rev (rev xs) = xs" + by simp +end +``` +When a goal resists, write `sledgehammer` in the interactive editor, take the proof it prints (`by (metis ...)`), and replace the call. Do not leave `sledgehammer` or `sorry` in committed files. + +## Run +`isabelle build -D .` (`-D DIR` includes a session directory and selects its sessions; `-d DIR` only makes sessions known; `-j N` runs N jobs in parallel; `-v` is verbose). + +Passing looks like: exit 0, with the build log reporting the session `Demo` as finished (exact wording is not in the system manual). The manual says the overall return code is the status of the set of selected sessions, so a session that fails to build gives a non-zero exit (conventionally 1) and the log names the failing theory and step. The manuals read here do not say whether a plain `isabelle build` rejects `sorry` or `oops` (or what the `quick_and_dirty` option changes), so do not rely on the build alone: grep the sources for both, as in the contract below. + +## As a contract check +```json +{"id": "prove-demo-isabelle", "claim": "The Isabelle session builds and contains no sorry", "kind": "general", "rung": 1, "cmd": "bash -c 'isabelle build -D . && ! grep -R -E \"\\\\b(sorry|oops)\\\\b\" --include=*.thy .'", "expect": {"exit": 0}, "timeout_s": 3600, "tier": "deep"} +``` + +## What a pass does not prove +- Only the stated theorem about the Isabelle definitions. +- Not run here. `isabelle build -D`, the `ROOT` syntax and the exit-status rule come from the Isabelle system manual; whether the build itself rejects `sorry` is unconfirmed (see Run). +- The grep also flags the word inside comments, which is the safe direction. Check the check: put a `sorry` in a scratch lemma and confirm the contract fails. diff --git a/verifiers/prove/kani-proof-hygiene.md b/verifiers/prove/kani-proof-hygiene.md new file mode 100644 index 0000000..406516d --- /dev/null +++ b/verifiers/prove/kani-proof-hygiene.md @@ -0,0 +1,56 @@ +--- +id: kani-proof-hygiene +title: Keeping Kani proofs honest: covers, bounds, canary, harness list, time caps +answers: Are my Kani proofs vacuous, silently skipped, or cut off, so that "verified" means less than it says? +rung: 1 +section: prove +languages: rust +kinds: general, money +cost: medium +detect: cargo kani --version +ran_here: yes +verified: ran +--- + +## Use when +- You have Kani harnesses and a CI check that says "all verified". +- Harnesses use `kani::assume`, `unwind`, or restricted inputs, where an over-tight bound makes a proof pass for no reason. +- The suite is slow, or you split it into fast and slow sets. + +## Do not use when +- There are no Kani harnesses yet. See `kani`. + +## Set up +A Rust and Lean 4 project does all of this in `justfile` with a shell wrapper around `cargo kani`. Copy the ideas, not its domain code. + +## Minimal example +1. Cover every interesting case. `kani::cover!(cond, "message")` fails the check if `cond` is unreachable under the harness's assumptions: +```rust +#[kani::proof] +fn vacuous() { + let x: u8 = kani::any(); + kani::assume(x > 10 && x < 5); // impossible: nothing is checked + assert!(x == 99); + kani::cover!(x > 0, "never reached"); +} +``` +2. A canary for a known tool bug: keep a harness marked `#[kani::should_panic]` that exercises the buggy construct; when a Kani upgrade fixes the bug it starts failing and tells you to drop the workaround. +3. A harness list check: enumerate harnesses (`grep` for `#[kani::proof]`), then fail on duplicate names and on a name in the slow list that no harness has. +4. Time caps: `cargo kani -j "$(nproc)" -Z unstable-options --harness-timeout 900s`, and wrap the run in `timeout 1800`. + +## Run +`cargo kani --output-format terse | tee kani.log` then +`grep -E '\*\* [0-9]+ of [0-9]+ cover properties satisfied' kani.log | awk '$2 != $4 {bad=1} END {exit bad}'` + +Passing looks like: for the vacuous harness above, Kani itself prints `** 0 of 1 cover properties satisfied (1 unreachable)` yet `VERIFICATION:- SUCCESSFUL` and exits 0 (observed, 0.68.0). The awk line then exits 1; that is how the check catches it. Also require the line `Complete - N successfully verified harnesses, 0 failures, N total` with N equal to the number of harnesses you listed. A timed-out harness is reported, not silently passed; a missing line means the run was cut off. + +## As a contract check +```json +{"id": "prove-kani-honest", "claim": "All Kani harnesses verify, the expected number ran, and every cover! is satisfiable", "kind": "general", "rung": 1, "cmd": "bash scripts/kani-check.sh", "expect": {"exit": 0, "stdout_contains": "successfully verified harnesses"}, "tier": "deep", "timeout_s": 3600} +``` +`scripts/kani-check.sh` runs steps 3 and 4 and the awk test above. + +## What a pass does not prove +- `cover!` shows each marked case is reachable, not that your marks cover all the cases that matter. Add one for each branch a reviewer would ask about. +- A harness proved on a smaller representation (e.g. `i64`) says nothing about the real type; see `proof-bridging`. +- The canary only watches the one bug you thought of. `--harness-timeout` needs `-Z unstable-options` and may change; check `cargo kani --help` after upgrades. diff --git a/verifiers/prove/kani.md b/verifiers/prove/kani.md new file mode 100644 index 0000000..5e101bd --- /dev/null +++ b/verifiers/prove/kani.md @@ -0,0 +1,67 @@ +--- +id: kani +title: Kani bounded model checking for Rust +answers: Can this Rust function panic, overflow or break an assertion for any input within a bound? +rung: 1 +section: prove +languages: rust +kinds: general, money, parsing +cost: medium +detect: cargo kani --version +ran_here: yes +verified: ran +--- + +## Use when +- A small, mostly pure function (money arithmetic, index maths, bounded parsers, state transitions) must hold for all inputs, not a sample. +- You want "cannot panic or overflow" for every value of the input types, such as every `u32`. +- A property test would be the next best thing but you want a proof within the bound. + +## Do not use when +- The claim needs unbounded sizes or heavy loops over big data; use `lean4-proofs` or `verus`. +- The function does I/O, threads or unsupported FFI. +- You have not read `kani-proof-hygiene`. A Kani pass can be vacuous. + +## Set up +`cargo install --locked kani-verifier && cargo kani setup` (once; downloads a nightly toolchain and CBMC). Put harnesses under `#[cfg(kani)]` so normal builds ignore them. + +## Minimal example +`src/lib.rs`: +```rust +pub fn add_cents(a: u32, b: u32) -> Option { a.checked_add(b) } + +#[cfg(kani)] +mod proofs { + use super::*; + + #[kani::proof] + fn add_cents_is_exact_or_none() { + let a: u32 = kani::any(); + let b: u32 = kani::any(); + let wide = a as u64 + b as u64; + match add_cents(a, b) { + Some(s) => assert_eq!(s as u64, wide), + None => assert!(wide > u32::MAX as u64), + } + kani::cover!(add_cents(a, b).is_none(), "overflow case reachable"); + kani::cover!(add_cents(a, b).is_some(), "ok case reachable"); + } +} +``` +Loops need `#[kani::unwind(N)]`; restrict inputs with `kani::assume(...)`, sparingly. + +## Run +`cargo kani --output-format terse` + +Passing looks like: exit 0, `2 of 2 cover properties satisfied`, `VERIFICATION:- SUCCESSFUL` and `Complete - 1 successfully verified harnesses, 0 failures, 1 total.` (Kani 0.68.0). Failure: `VERIFICATION:- FAILED` with the failing check and a nonzero exit. To select one harness use `--harness --exact`; an unqualified name with `--exact` is refused. + +## As a contract check +```json +{"id": "prove-add-cents-kani", "claim": "add_cents never wraps: Some(sum) is exact and None only when the sum exceeds u32::MAX", "kind": "money", "rung": 1, "cmd": "cargo kani --output-format terse", "expect": {"exit": 0, "stdout_contains": "successfully verified harnesses, 0 failures"}, "tier": "deep", "timeout_s": 1800} +``` + +## What a pass does not prove +- Only inputs within the harness: `unwind` bounds, array lengths, `kani::assume`. Beyond them nothing is claimed. +- An over-tight `assume` or unreachable code makes the pass vacuous. See `kani-proof-hygiene`. +- Harness code can be wrong. Confirm each harness can fail: flip an assertion and see `FAILED`. +- Its model of the standard library has gaps (e.g. known bugs on bulk copies of symbolic length); a pass is not a statement about the real binary. diff --git a/verifiers/prove/klee.md b/verifiers/prove/klee.md new file mode 100644 index 0000000..12dc8e4 --- /dev/null +++ b/verifiers/prove/klee.md @@ -0,0 +1,72 @@ +--- +id: klee +title: KLEE symbolic execution of C programs +answers: Which inputs make this C program crash, overflow or break an assert, found by exploring its paths? +rung: 1 +section: prove +languages: c, c++ +kinds: general, parsing +cost: high +detect: klee --version +ran_here: no +verified: docs +--- + +## Use when +- C programs or functions with many branches where you want generated inputs that reach each path and trigger errors. +- You want concrete test cases for each path as a by-product. + +## Do not use when +- You want a simpler tool: `cbmc` is easier to run and gives a proof within a bound. +- The code does a lot of I/O, threads, floating point or deep loops over symbolic sizes. + +## Set up +Easiest is the Docker image (from the KLEE Docker page; 3.0 is the current tag there): + + docker pull klee/klee:3.0 + docker run --rm -ti --ulimit='stack=-1:-1' klee/klee:3.0 # then `klee --version` inside + +The `--ulimit` avoids stack overflows inside KLEE. Building from source needs LLVM (the site recommends LLVM 18), clang and an SMT solver; see klee-se.org. Programs include `klee/klee.h`; compile with `-I` pointing at KLEE's `include` directory. Not installed here, so the example was not run. + +## Minimal example +`a.c`: +```c +#include +int clamp(int lo, int hi, int x) { return x < lo ? lo : (x > hi ? hi : x); } +int main(void) { + int lo, hi, x; + klee_make_symbolic(&lo, sizeof lo, "lo"); + klee_make_symbolic(&hi, sizeof hi, "hi"); + klee_make_symbolic(&x, sizeof x, "x"); + klee_assume(lo <= hi); + int r = clamp(lo, hi, x); + klee_assert(lo <= r && r <= hi); + return 0; +} +``` + +## Run +``` +clang -I /path/to/klee/include -emit-llvm -c -g -O0 -Xclang -disable-O0-optnone a.c -o a.bc +klee a.bc +``` +The tutorial says `-O0 -Xclang -disable-O0-optnone` is preferred over plain `-O0` on LLVM newer than 5.0. Output goes to `klee-out-N/` (lowest unused N) with a `klee-last` symlink to the newest. + +Passing looks like (from the tutorial): + + KLEE: done: total instructions = 33 + KLEE: done: completed paths = 3 + KLEE: done: partially completed paths = 0 + KLEE: done: generated tests = 3 + +with no `KLEE: ERROR` lines and no `test*.err` files in `klee-last/`. Failure: `KLEE: ERROR: ... ASSERTION FAIL` and a file `test000001.assert.err` next to the `.ktest` that reproduces it (the file docs give the pattern `test..err`; `ktest-tool` prints a `.ktest`). The KLEE docs fetched do not state the exit status; KLEE is generally reported to exit 0 even when it found errors, so test for the `.err` files rather than the exit code, and confirm that on your version. + +## As a contract check +```json +{"id": "prove-clamp-klee", "claim": "KLEE finds no assertion failure or memory error in clamp", "kind": "general", "rung": 1, "cmd": "bash -c 'klee a.bc && ! ls klee-last/*.err 2>/dev/null'", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"} +``` + +## What a pass does not prove +- Only completes if exploration ends before limits (`--max-time`, `--max-memory`); if it stops early the pass is partial. Look for "partially completed paths = 0". +- Symbolic sizes and the modelled environment (`--posix-runtime`, `--libc=uclibc`) bound what is covered. +- Commands and output come from the KLEE tutorial and docs, not from a run here. diff --git a/verifiers/prove/lean-axiom-audit.md b/verifiers/prove/lean-axiom-audit.md new file mode 100644 index 0000000..a90fe5d --- /dev/null +++ b/verifiers/prove/lean-axiom-audit.md @@ -0,0 +1,53 @@ +--- +id: lean-axiom-audit +title: Making a Lean proof trustworthy: no sorry, only the standard axioms +answers: Does my Lean proof really prove the theorem, or does it rely on sorry or an extra axiom? +rung: 1 +section: prove +languages: any +kinds: general +cost: low +detect: lake --version +ran_here: yes +verified: ran +--- + +## Use when +- A Lean project is the evidence for a claim and a green `lake build` must mean the proof is complete. +- An agent wrote or edited proofs; `sorry`, `axiom` and `native_decide` are easy to slip in. +- You want a CI step that fails on anything but the standard axioms. + +## Do not use when +- There is no Lean proof. See `lean4-proofs`. + +## Set up +List the theorems that carry the claim in one file, `Audit.lean`, so the list is reviewed in one place: +```lean +import Demo +#print axioms clamp_le +#print axioms add_zero' +``` + +## Minimal example +``` +lake build --wfail +lake env lean Audit.lean | tee audit.txt +! grep -v -E "depends on axioms: \[(propext|Quot.sound|Classical.choice)(, (propext|Quot.sound|Classical.choice))*\]$|does not depend on any axioms" audit.txt +``` +The third line fails if any output line is not one of the allowed forms. The three allowed axioms are `propext`, `Classical.choice`, `Quot.sound`. This is the filter a Rust and Lean 4 project uses in its `prove` recipe. + +## Run +Put the three lines in a script, `audit-lean.sh`, with `set -euo pipefail`. + +Passing looks like: exit 0 and output such as `'clamp_le' depends on axioms: [propext, Classical.choice, Quot.sound]`. Failure shows `depends on axioms: [sorryAx]` for a theorem that uses `sorry` (observed: `lake build` itself exited 0 and only warned; `--wfail` made it exit 1). `native_decide` shows `Lean.ofReduceBool`, and a custom `axiom` appears by name; both fail the filter. + +## As a contract check +```json +{"id": "prove-lean-axioms", "claim": "The Lean theorems depend on no sorry and only the three standard axioms", "kind": "general", "rung": 1, "cmd": "bash audit-lean.sh", "expect": {"exit": 0, "stdout_contains": "depends on axioms"}, "tier": "deep", "timeout_s": 1800} +``` + +## What a pass does not prove +- That the theorem statements say what you meant. Axiom-clean proofs of the wrong statement pass. +- Only theorems listed in `Audit.lean` are audited; a new theorem not listed is not. Compare the list against the project's theorems in review, or generate it. +- A trailing `sorry` in a file `Audit.lean` does not import is not seen; build the whole library. +- If `Audit.lean` prints nothing (a typo in a name raises an error, which is good) make sure the script checks that the output is non-empty. diff --git a/verifiers/prove/lean4-proofs.md b/verifiers/prove/lean4-proofs.md new file mode 100644 index 0000000..458504e --- /dev/null +++ b/verifiers/prove/lean4-proofs.md @@ -0,0 +1,56 @@ +--- +id: lean4-proofs +title: Proving properties in Lean 4 with a lake project and lake build +answers: Is this property true for all inputs, with a machine-checked proof rather than tests? +rung: 1 +section: prove +languages: any +kinds: general, money, state-machine +cost: high +detect: lake --version +ran_here: yes +verified: ran +--- + +## Use when +- The claim is a law over all inputs of a function you can write in Lean (or a model of your code): sums are conserved, a rounding step is within half a unit, an operation is its own inverse. +- Tests and Kani only cover bounded cases and you need the law at any size. +- You can state the law as a `theorem` and let `lake build` be the judge. + +## Do not use when +- The code under test is Rust or C and you need the proof about that code. Use `aeneas-rust-to-lean`, `kani` or `verus`. +- The property is a quick bounded check. `kani` or `exhaustive-small-domain` cost far less. + +## Set up +``` +lake new demo # then in lakefile.toml set defaultTargets = ["Demo"] and delete the lean_exe stanza and Main.lean +cd demo +``` +`lean-toolchain` pins the Lean version; commit it and `lake-manifest.json`. Mathlib is optional: add `[[require]] name = "mathlib" scope = "leanprover-community"` to `lakefile.toml` only when you need it (a first build downloads a large cache; run `lake exe cache get`). Without Mathlib, the tactics `simp`, `omega` and `decide` already handle most arithmetic. + +## Minimal example +`Demo/Basic.lean`: +```lean +def clamp (lo hi x : Nat) : Nat := if x < lo then lo else if hi < x then hi else x + +theorem clamp_le (lo hi x : Nat) (h : lo ≤ hi) : + lo ≤ clamp lo hi x ∧ clamp lo hi x ≤ hi := by + unfold clamp + split <;> (try split) <;> omega +``` +The agent loop: edit, run `lake build`, read the error (it shows the unsolved goal), adjust. Put `sorry` in one place at a time to see the goal, then replace it. `lake env lean Demo/Basic.lean` checks one file faster. + +## Run +`lake build --wfail` + +Passing looks like: exit 0 with lines like `✔ Built Demo.Basic`. A wrong proof gives `error:` with the goal and exit 1 (observed). Plain `lake build` exits 0 even when a proof contains `sorry` (it only warns), so use `--wfail` and the audit in `lean-axiom-audit`. + +## As a contract check +```json +{"id": "prove-clamp-lean", "claim": "clamp stays within [lo, hi] for all Nat inputs, proved in Lean 4", "kind": "general", "rung": 1, "cmd": "lake build --wfail", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800} +``` + +## What a pass does not prove +- It proves the theorem about the Lean definition. If the definition is not the real code, add a bridge (`proof-bridging`, `aeneas-rust-to-lean`). +- A theorem that is easier than the claim (wrong statement, hypotheses that cannot hold) builds fine. Read the statement, and prove a non-trivial instance with `example`. +- `sorry` and extra axioms pass the build; see `lean-axiom-audit`. diff --git a/verifiers/prove/liquid-haskell.md b/verifiers/prove/liquid-haskell.md new file mode 100644 index 0000000..3400127 --- /dev/null +++ b/verifiers/prove/liquid-haskell.md @@ -0,0 +1,57 @@ +--- +id: liquid-haskell +title: LiquidHaskell refinement types for Haskell +answers: Do my Haskell functions respect value constraints (non-zero divisors, in-range indexes, length-preserving) for all inputs? +rung: 1 +section: prove +languages: haskell +kinds: general +cost: medium +detect: ghc --version +ran_here: no +verified: docs +--- + +## Use when +- Haskell code where totality and value constraints matter: safe division, bounds, sorted or length-indexed lists. +- You want checks written as comments next to the types, so the code still compiles with plain GHC. + +## Do not use when +- The code is not Haskell. See the entries for your language. +- The GHC version you need is newer than the LiquidHaskell release supports: only one GHC version is supported at a time (currently 9.14.1). + +## Set up +From the LiquidHaskell README: install Z3 4.15.1 or newer on PATH, then in the project directory + + cabal install --lib liquidhaskell liquid-prelude liquid-vector --package-env . --force-reinstalls + +(`--package-env .` writes a `.ghc.environment*` file so only GHC runs started from this directory see the plugin). Put `{-# OPTIONS_GHC -fplugin=LiquidHaskell #-}` at the top of each checked module. LiquidHaskell supports exactly one GHC version at a time: the latest release (v0.9.14.1, May 2026) builds with GHC 9.14.1, and the previous release (v0.9.12.2) is the last one for GHC 9.12.2. Use the LiquidHaskell release that matches your GHC. Not installed here (no Haskell toolchain), so the example was not run. + +## Minimal example +```haskell +{-# OPTIONS_GHC -fplugin=LiquidHaskell #-} +module Safe where + +{-@ safeDiv :: Int -> {v:Int | v /= 0} -> Int @-} +safeDiv :: Int -> Int -> Int +safeDiv x y = x `div` y + +ok :: Int +ok = safeDiv 10 2 +-- bad = safeDiv 10 0 -- uncomment: rejected at compile time +``` + +## Run +`ghc -fplugin=LiquidHaskell Safe.hs` (the README's command), or in a Cabal project add `-fplugin=LiquidHaskell` to `ghc-options` with `liquidhaskell` and `liquid-prelude` in `build-depends` and run `cabal build`. GHC does not rerun the plugin on modules it considers up to date, so after a first pass force a rebuild (`-fforce-recomp`, or touch the file) before trusting a pass. + +Passing looks like: the compile succeeds. Failure: a refinement type error from the plugin at the offending call, and a failed compile (non-zero exit as for any GHC error). The exact error wording (older versions printed `Liquid Type Mismatch`; the older `liquid Safe.hs` printed `LIQUID: SAFE`) was not confirmed here. + +## As a contract check +```json +{"id": "prove-safediv-liquid", "claim": "safeDiv is never called with a zero divisor", "kind": "general", "rung": 1, "cmd": "ghc -fforce-recomp -fplugin=LiquidHaskell Safe.hs", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"} +``` + +## What a pass does not prove +- Only annotated specs; `{-@ lazy @-}`, `assume` and `{-@ LIQUID "--no-termination" @-}` weaken or skip checking. Grep for them. +- Modules without the plugin line are not checked at all; make sure the plugin line is on every module that matters. +- Not run here; commands come from the LiquidHaskell README. Check the check: uncomment `bad = safeDiv 10 0` and confirm the compile fails. diff --git a/verifiers/prove/proof-bridging.md b/verifiers/prove/proof-bridging.md new file mode 100644 index 0000000..076ea11 --- /dev/null +++ b/verifiers/prove/proof-bridging.md @@ -0,0 +1,57 @@ +--- +id: proof-bridging +title: Bridging a proof on a simplified type to the real type with a differential test +answers: My proof was done on a simpler representation (like i64); does the real code (like Decimal) behave the same? +rung: 2 +section: prove +languages: any +kinds: money, general +cost: medium +detect: +ran_here: yes +verified: ran +--- + +## Use when +- A proof tool handles only a simple model (Kani on `i64`, Lean on `Nat`, Dafny on `int`) and the production code uses another type (`Decimal`, `BigInt`, floating point, a struct). +- You want to say the proof carries over to the real code, with evidence you can run. + +## Do not use when +- You can prove the real type directly (`aeneas-rust-to-lean`, `verus`). Do that instead. +- The two types differ in the property you proved (rounding, overflow, ordering): then the bridge must show where they agree, and the claim shrinks to that region. + +## Set up +Write the model function and the real function with the same shape. In the test, generate inputs, run both, convert the model result to the real type, and assert equal. Include an independent exact reference (a big-integer or rational one) as a third voice when the model is lossy. Use `proptest` in Rust or `hypothesis` in Python for random inputs, plus a fixed list of edge cases (zero, minimum, maximum, ties, negatives). + +## Minimal example +```rust +fn halve_model(x: i64) -> i64 { x / 2 } // what the proof covers +fn halve_real(x: i128) -> i128 { x / 2 } // what production runs (wider type) + +#[test] +fn bridge_agrees() { + let mut s: u64 = 0x9E37_79B9_7F4A_7C15; // fixed seed: reproducible + for _ in 0..100_000 { + s ^= s << 13; s ^= s >> 7; s ^= s << 17; // xorshift + let x = s as i64; + assert_eq!(halve_model(x) as i128, halve_real(x as i128)); + } +} +``` +State in the test's doc comment which proof it carries (`kani proof halve_is_floor`), over which inputs, and what is assumed equal. + +## Run +`cargo test bridge` + +Passing looks like: exit 0 and `test tests::bridge_agrees ... ok`. Failure: the first disagreeing input in the panic message. + +## As a contract check +```json +{"id": "prove-bridge-i64-to-wide", "claim": "The real halve agrees with the proved i64 model on 100000 seeded inputs and the edge cases", "kind": "money", "rung": 2, "cmd": "cargo test bridge", "expect": {"exit": 0, "stdout_contains": "test result: ok"}, "tier": "deep", "timeout_s": 600} +``` + +## What a pass does not prove +- It samples, so the bridge is rung 2, and the proved claim for the real type is only as strong as the bridge. Say so in the contract claim. +- The bridge must show: same results where both are defined; both refuse (error or `None`) on the same inputs; behaviour at the model's bounds; and every wrapper between the proof and the real call. A wrapper that is not in the bridge is unproved. +- Compare against an independent exact reference where the model truncates (for example integer division drops fractions that `Decimal` keeps), or you test two things that share a flaw. +- Generators that rarely hit edges miss them; list ties, zero, min and max explicitly. diff --git a/verifiers/prove/prusti.md b/verifiers/prove/prusti.md new file mode 100644 index 0000000..1bfaa17 --- /dev/null +++ b/verifiers/prove/prusti.md @@ -0,0 +1,48 @@ +--- +id: prusti +title: Prusti verification for Rust +answers: Does this Rust function satisfy its pre- and postconditions for all inputs? +rung: 1 +section: prove +languages: rust +kinds: general +cost: high +detect: cargo prusti --version +ran_here: no +verified: docs +--- + +## Use when +- You are already on a Rust toolchain Prusti supports and want Viper-based proofs with contract attributes. +- The code is safe Rust with moderate complexity, and unbounded proofs are needed. + +## Do not use when +- Status, checked on the repository: Prusti is not abandoned. It moved from `viperproject/prusti-dev` to `prusti/prusti`, has commits almost daily in November 2026 and publishes nightly pre-release builds. But its last non-pre-release was in February 2024 (`v-2024-02-28-1817`), and the user guide warns that some syntax it describes exists only in the "LatestDev" build. Expect the stable binary to be old; on current Rust prefer `verus`, `creusot` or `kani`, and check which Rust toolchain your Prusti build pins (the repository's `rust-toolchain` pins a nightly, `nightly-2026-08-15` at the time of writing). +- Your Rust is recent and you want the old stable build: it supports only the nightly it was built against, so it often cannot compile modern crates. + +## Set up +Download a precompiled build from github.com/prusti/prusti/releases (Ubuntu, Windows, macOS; "Pre-release" builds are the current ones), or use the VS Code extension "Prusti Assistant", or build from source (`rustup`, `./x.py setup`, `./x.py build --release`). Every option provides `prusti-rustc` and `cargo-prusti`. Add the contracts crate to the project with `cargo add prusti-contracts` and put `use prusti_contracts::*;` in the file. Not installed here, so the example was not run. + +## Minimal example +```rust +use prusti_contracts::*; + +#[requires(a >= 0 && a < i32::MAX)] +#[ensures(result == a + 1)] +fn inc(a: i32) -> i32 { a + 1 } +``` + +## Run +`cargo prusti` from the crate root (Prusti on a single file: `prusti-rustc --edition=2018 path/to/file.rs`). By default Prusti also verifies absence of integer overflow and of reachable `panic!`/`unreachable!`; a `Prusti.toml` can switch overflow checks off. + +Passing looks like: the guide says "Prusti should report that verification succeeded" (exact message not quoted there). Failure is reported like a compiler error with the prefix `Prusti: verification error`, for example `error: [Prusti: verification error] statement might panic`. The guide does not state the exit status; as a rustc wrapper it should exit non-zero on errors, but confirm with a wrong postcondition. + +## As a contract check +```json +{"id": "prove-inc-prusti", "claim": "inc returns a + 1 for every a below i32::MAX", "kind": "general", "rung": 1, "cmd": "cargo prusti", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"} +``` + +## What a pass does not prove +- Only annotated functions; `#[trusted]` ones are assumed. Grep for it. +- Quantifiers and loops need invariants that the tool may fail to use, giving false alarms rather than false passes. +- Not run here; commands come from the Prusti README and user guide. The guide itself notes some syntax needs the LatestDev build, so the snippet may differ by version. diff --git a/verifiers/prove/rocq.md b/verifiers/prove/rocq.md new file mode 100644 index 0000000..36bee72 --- /dev/null +++ b/verifiers/prove/rocq.md @@ -0,0 +1,56 @@ +--- +id: rocq +title: Rocq (formerly Coq) proofs, and when to pick it over Lean +answers: Is this property proved by machine, in a prover with a large existing library of verified programs? +rung: 1 +section: prove +languages: any +kinds: general, state-machine +cost: high +detect: rocq --version +ran_here: no +verified: docs +--- + +## Use when +- You depend on an existing Rocq development (CompCert, Iris, VST, Fiat Crypto, MathComp) or the team already knows it. +- You need extraction of verified code to OCaml or Haskell. +- The proof is about C via VST, or concurrent separation logic via Iris. + +## Do not use when +- You are starting fresh and have no reason to prefer it. Prefer `lean4-proofs`: faster builds, better agent tooling, and `lake build` as one oracle. +- A bounded check will do (`kani`, `cbmc`). + +## Set up +Install through opam (version 2.1 or newer). Rocq packages are not in the default opam repository, so add theirs first: + + opam repo add rocq-released https://rocq-prover.org/opam/released + opam install rocq-prover + rocq -v + +The package is `rocq-prover` (the old name was `coq`); the binary is `rocq`, and the batch compiler is `rocq compile` (alias `rocq c`). The current reference manual documents only `rocq`-prefixed commands and does not mention `coqc`, so on a modern install use `rocq compile`; an older `coq` install has `coqc`. Not installed here, so nothing was run. + +For a Dune build (the manual calls Dune support experimental), `dune-project` has a `(lang dune 3.x)` line and `(using rocq 0.14)` (Dune docs, Dune 3.25; the Rocq language version is not the Rocq version), and a `dune` file has `(rocq.theory (name Demo))`. Without Dune: `rocq makefile -f _CoqProject -o CoqMakefile`, then `make -f CoqMakefile`. + +## Minimal example +`Demo.v`: +```coq +Theorem add_zero_r : forall n : nat, n + 0 = n. +Proof. intros n. induction n; simpl; auto. Qed. +Print Assumptions add_zero_r. +``` + +## Run +`dune build` (or `rocq compile Demo.v` for one file; name the logical path with `-Q . Demo` when needed; the file name must be a valid identifier, so `to-to.v` fails). + +Passing looks like: exit 0 (the manual does not document `rocq compile` exit codes; a Rocq error such as an unsolved goal fails the compile and Dune reports it). `Print Assumptions add_zero_r.` prints `Closed under the global context` when no axioms are used; any listed axiom, or `Admitted.` in the source, means the proof is incomplete. Dune normally hides the output of successful rules, so to see the `Print Assumptions` line compile the file directly with `rocq compile`, and grep the sources as well. + +## As a contract check +```json +{"id": "prove-demo-rocq", "claim": "The Rocq development builds with no Admitted lemmas", "kind": "general", "rung": 1, "cmd": "bash -c 'dune build && ! grep -R -E \"Admitted|admit\\.\" --include=*.v .'", "expect": {"exit": 0}, "timeout_s": 3600, "tier": "deep"} +``` + +## What a pass does not prove +- Only the stated theorem about the Rocq definitions; the link to real code is a separate problem (`proof-bridging`). +- `Admitted` and `Axiom` pass the build; the grep and `Print Assumptions` catch them. +- Not run here. The opam commands, `rocq compile` and the Dune stanzas come from the Rocq install page, refman and Dune docs; the exit status of `rocq compile` is not documented in them. diff --git a/verifiers/prove/spark-ada.md b/verifiers/prove/spark-ada.md new file mode 100644 index 0000000..eb98445 --- /dev/null +++ b/verifiers/prove/spark-ada.md @@ -0,0 +1,70 @@ +--- +id: spark-ada +title: SPARK (Ada) proofs with GNATprove +answers: Is this Ada code free of runtime errors and does it meet its contracts, proved? +rung: 1 +section: prove +languages: ada +kinds: general +cost: medium +detect: gnatprove --version +ran_here: no +verified: docs +--- + +## Use when +- The project is in Ada and needs absence of runtime errors (overflow, range, index) or functional contracts proved. +- Safety standards ask for proof evidence. + +## Do not use when +- The code is not Ada. Choose the entry for its language. + +## Set up +Get GNATprove from Alire (`alr with gnatprove` in an Alire project, then `eval $(alr printenv)`), or install a GNAT toolchain plus GNATprove from AdaCore (see the SPARK user guide, "Installation of GNATprove"). Put `SPARK_Mode` on the code to prove (`pragma SPARK_Mode (On);` in a package spec and body, or `with SPARK_Mode` on declarations) and have a project file. Not installed here, so the example was not run. + +`proj.gpr`: + + project Proj is + for Source_Dirs use ("."); + for Object_Dir use "obj"; + end Proj; + +## Minimal example +`bounds.ads`: + + package Bounds with SPARK_Mode is + function Clamp (Lo, Hi, X : Integer) return Integer + with Pre => Lo <= Hi, + Post => Clamp'Result in Lo .. Hi; + end Bounds; + +`bounds.adb`: + + package body Bounds with SPARK_Mode is + function Clamp (Lo, Hi, X : Integer) return Integer is + begin + if X < Lo then return Lo; + elsif X > Hi then return Hi; + else return X; + end if; + end Clamp; + end Bounds; + +GNATprove checks the postcondition and every runtime check in the body. + +## Run +`gnatprove -P proj.gpr --level=2 --checks-as-errors=on` + +`--level` runs from 0 (fast) to 4 (most powerful); level 2 is cvc5, z3 and Alt-Ergo with a 5 second timeout and counterexamples on. Raise the level or `--timeout` when a prover cannot decide. + +Passing looks like: exit 0 and a summary table in which every check is "Proved". Failure shows messages such as `medium: postcondition might fail` and, only with `--checks-as-errors=on`, exits non-zero. The SPARK user guide states that GNATprove otherwise "returns with an exit status of zero, even when unproved check messages and warnings are issued". Use `--warnings=error` as well if warnings should fail the run. + +## As a contract check +```json +{"id": "prove-clamp-spark", "claim": "Clamp has no runtime errors and satisfies its postcondition", "kind": "general", "rung": 1, "cmd": "gnatprove -P proj.gpr --level=2 --checks-as-errors=on", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"} +``` + +## What a pass does not prove +- Only code in `SPARK_Mode`; code outside it (`SPARK_Mode => Off`) is assumed. Search for `pragma Assume` and `Annotate`. +- Only contracts as written. +- Without `--checks-as-errors=on` a run with unproved checks still exits 0, so a contract on the exit code alone would pass vacuously. Commands and exit-status behaviour come from the SPARK user guide, not from a run here. diff --git a/verifiers/prove/typescript-type-level.md b/verifiers/prove/typescript-type-level.md new file mode 100644 index 0000000..a2ffae4 --- /dev/null +++ b/verifiers/prove/typescript-type-level.md @@ -0,0 +1,68 @@ +--- +id: typescript-type-level +title: TypeScript strict mode, branded types, exhaustive never checks, type tests +answers: Does the TypeScript compiler reject misuse of this API: wrong units, unhandled cases, invalid states? +rung: 1 +section: prove +languages: typescript +kinds: general, money, state-machine +cost: low +detect: npx --no-install tsc --version +ran_here: yes +verified: ran +--- + +## Use when +- Values are easy to mix up (cents vs dollars, user id vs order id) and you want the compiler to stop it. +- A union grows over time and every `switch` over it must handle new members. +- You want type-level behaviour tested, so a refactor cannot silently weaken a type. + +## Do not use when +- The rule is about runtime values only. A brand does not validate; it needs a smart constructor that does. +- You wrote `as any` or `// @ts-ignore` to get it to compile; the check is then worthless. + +## Set up +`npm i -D typescript` (7.0.2 tried; `tsd` 0.33 for dedicated type tests). `tsconfig.json`: `{"compilerOptions": {"strict": true, "noEmit": true, "target": "ES2022", "module": "ES2022", "moduleResolution": "bundler", "types": []}, "include": ["src"]}`. + +## Minimal example +`src/brand.ts`: +```ts +declare const brand: unique symbol; +export type Cents = number & { readonly [brand]: "Cents" }; +export function cents(n: number): Cents { + if (!Number.isInteger(n)) throw new RangeError("cents must be an integer"); + return n as Cents; +} +export type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number }; +export function area(sh: Shape): number { + switch (sh.kind) { + case "circle": return 3 * sh.r * sh.r; + case "square": return sh.s * sh.s; + default: { const _x: never = sh; return _x; } // fails if a case is missing + } +} +export function pay(_c: Cents): void {} +``` +`src/brand.test-d.ts` (type test, type-checked only, never run): +```ts +import { pay, cents } from "./brand"; +pay(cents(5)); +// @ts-expect-error a plain number is not Cents +pay(5); +``` +`@ts-expect-error` itself fails the build if the next line has no error, so the test cannot rot. + +## Run +`npx tsc -p .` + +Passing looks like: no output, exit 0. Failure: `error TS2345: Argument of type 'number' is not assignable to parameter of type 'Cents'` (removing the `@ts-expect-error` line), or `Type '{ kind: "square"; ... }' is not assignable to type 'never'` after deleting the `square` case; exit 2 or 1 (nonzero). With `tsd`, run `npx tsd` and use `expectError` and `expectType`. + +## As a contract check +```json +{"id": "prove-cents-brand", "claim": "A plain number cannot be passed where Cents is required, and area handles every Shape", "kind": "general", "rung": 1, "cmd": "npx tsc -p .", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300} +``` + +## What a pass does not prove +- Types are erased at runtime; data arriving from JSON or the network is unchecked unless parsed by a validator (zod and similar) that returns the branded type. +- `any`, `as` casts, `@ts-ignore` and `@ts-expect-error` placed on the wrong line defeat it. Grep for them and add `noImplicitAny` (part of `strict`). +- TypeScript's type system is intentionally unsound in places (array covariance, index access without `noUncheckedIndexedAccess`). diff --git a/verifiers/prove/verus.md b/verifiers/prove/verus.md new file mode 100644 index 0000000..170a970 --- /dev/null +++ b/verifiers/prove/verus.md @@ -0,0 +1,64 @@ +--- +id: verus +title: Verus deductive verification for Rust +answers: Does this Rust code meet its requires/ensures specification for all inputs, with no size bound? +rung: 1 +section: prove +languages: rust +kinds: general, state-machine +cost: high +detect: verus --version +ran_here: no +verified: docs +--- + +## Use when +- You write new Rust (or a core module) that needs unbounded proofs: data structures, allocators, protocols, algorithms with loops. +- You can accept writing specs and loop invariants inline in the Rust file, and ghost code. +- `kani` bounds are too small and a separate Lean model would drift from the code. + +## Do not use when +- You need to verify existing unmodified Rust with traits and iterators everywhere: Verus supports a subset. +- A bounded proof is enough. `kani` takes minutes to set up. + +## Set up +Download a release binary from github.com/verus-lang/verus/releases (the weekly point releases are recommended), unzip it, and run `./verus`. It tells you which `rustup` toolchain it pins (for example `rustup install 1.86.0-x86_64-unknown-linux-gnu`) and how to install it; repeat until `./verus` stops complaining. For a Cargo project the release also ships `cargo-verus`; put both on PATH, then `cargo verus new --bin my_project`, or in an existing crate `cargo add vstd` and add `[package.metadata.verus]` with `verify = true` to `Cargo.toml` (details in the guide chapter "Using Verus via Cargo"). Not installed here, so the example was not run. + +## Minimal example +`max.rs`: +```rust +use vstd::prelude::*; + +verus! { +fn max(a: u32, b: u32) -> (r: u32) + ensures r >= a, r >= b, r == a || r == b +{ + if a > b { a } else { b } +} +} // verus! + +fn main() {} +``` +Loops need `invariant` and `decreases` clauses; arithmetic overflow is a proof obligation unless the type is `int`. + +## Run +`verus max.rs`, or in a Cargo project `cargo verus verify` (not `cargo verus focus`, which skips the proofs of dependencies). + +Passing looks like (from the guide): + + note: verifying root module + + verification results:: 1 verified, 0 errors + +Failure prints `error: assertion failed` (or a failed `ensures`) with the source location, then `error: aborting due to previous error` and `verification results:: 0 verified, 1 errors`. The guide does not state the process exit status; Verus is a rustc-based driver and should exit non-zero on errors, but confirm it with a deliberately wrong spec before relying on exit alone. The contract below also checks the text. `verus file.rs --compile` additionally builds a binary. + +## As a contract check +```json +{"id": "prove-max-verus", "claim": "max returns one of its arguments and is at least both", "kind": "general", "rung": 1, "cmd": "verus max.rs", "expect": {"exit": 0, "stdout_contains": "verified, 0 errors"}, "timeout_s": 900, "tier": "deep"} +``` + +## What a pass does not prove +- Only the `ensures` you wrote and only functions inside `verus!`; code outside it is trusted. Search for `#[verifier::external]`, `assume(`, `admit(` and `external_body`, which skip proof. +- Verus and its trusted specs of `vstd` are part of what you trust. +- Check the check can fail: weaken the body and confirm an error appears, and that the exit status is non-zero. +- Commands and output format were read from the Verus guide and INSTALL.md, not run here. diff --git a/verifiers/prove/z3-smt.md b/verifiers/prove/z3-smt.md new file mode 100644 index 0000000..a6a454e --- /dev/null +++ b/verifiers/prove/z3-smt.md @@ -0,0 +1,55 @@ +--- +id: z3-smt +title: Encoding a property directly for Z3 (Python or SMT-LIB) +answers: Does a counterexample to this property exist, found by a solver, when no verifier fits my language? +rung: 1 +section: prove +languages: any +kinds: general, money, parsing +cost: medium +detect: python3 -c "import z3" +ran_here: yes +verified: ran +--- + +## Use when +- The property is a bit-level or arithmetic fact (overflow tests, rounding, bit tricks, small state-transition rules) you can restate as formulas. +- No verifier covers your language, or you want a quick independent check of a formula. + +## Do not use when +- You can verify the real code (`kani`, `cbmc`, `dafny`). Re-encoding invites mistakes. +- The claim has unbounded loops, heap structures or floating-point subtleties. + +## Set up +In a throwaway virtualenv: `python3 -m venv .venv && .venv/bin/pip install z3-solver`. The package also provides the `z3` command-line program for SMT-LIB files. + +## Minimal example +`z.py`. Claim: for 32-bit unsigned `a`, `b`, `(a + b) < a` holds exactly when the addition overflowed. +```python +from z3 import BitVec, Solver, ULT, UGE, ZeroExt, sat, unsat + +a, b = BitVec("a", 32), BitVec("b", 32) +wrapped_smaller = ULT(a + b, a) +really_overflowed = UGE(ZeroExt(32, a) + ZeroExt(32, b), 2**32) +s = Solver() +s.add(wrapped_smaller != really_overflowed) # ask for a counterexample +r = s.check() +assert r == unsat, f"counterexample: {s.model()}" if r == sat else f"solver said {r}" +print("proved: overflow test is exact for all 32-bit a, b") +``` +The same in SMT-LIB (`a.smt2`): declare `a`, `b` as `(_ BitVec 32)`, assert the negated claim, `(check-sat)`; expect `unsat`. + +## Run +`python3 z.py` or `z3 a.smt2` + +Passing looks like: `proved: ...` with exit 0; for SMT-LIB the single word `unsat`. Failure: `sat` (a model is a counterexample). Changing `>=` to `>` in `really_overflowed` gave the counterexample `a = 3489660928, b = 805306368` (their sum is exactly 2^32) and exit 1. The result `unknown` (timeout) is not a pass; the script asserts `unsat`. + +## As a contract check +```json +{"id": "prove-overflow-test-z3", "claim": "(a + b) < a is equivalent to unsigned 32-bit overflow", "kind": "general", "rung": 1, "cmd": "python3 z.py", "expect": {"exit": 0, "stdout_contains": "proved"}, "tier": "deep", "timeout_s": 300} +``` + +## What a pass does not prove +- Only the formulas, not your code. A wrong translation proves something else; test the encoding against concrete values with `s.add(a == 3, ...)` expecting `sat`. +- You proved the negation is unsatisfiable. Check the formulas are not trivially unsat: assert that the model without the final constraint is `sat`. +- `z3-solver` versions differ in `unknown` behaviour; set `s.set("timeout", ms)` and treat `unknown` as failure. diff --git a/verifiers/real-world/accessibility-axe.md b/verifiers/real-world/accessibility-axe.md new file mode 100644 index 0000000..ddd4c45 --- /dev/null +++ b/verifiers/real-world/accessibility-axe.md @@ -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 `` without `alt` and confirm `image-alt` appears. diff --git a/verifiers/real-world/agent-surface-evals.md b/verifiers/real-world/agent-surface-evals.md new file mode 100644 index 0000000..0f12bd1 --- /dev/null +++ b/verifiers/real-world/agent-surface-evals.md @@ -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. diff --git a/verifiers/real-world/annotation-behaviour-check.md b/verifiers/real-world/annotation-behaviour-check.md new file mode 100644 index 0000000..99f7c4c --- /dev/null +++ b/verifiers/real-world/annotation-behaviour-check.md @@ -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. diff --git a/verifiers/real-world/clean-clone-build.md b/verifiers/real-world/clean-clone-build.md new file mode 100644 index 0000000..1459740 --- /dev/null +++ b/verifiers/real-world/clean-clone-build.md @@ -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. diff --git a/verifiers/real-world/cli-transcript-tests.md b/verifiers/real-world/cli-transcript-tests.md new file mode 100644 index 0000000..3ca0969 --- /dev/null +++ b/verifiers/real-world/cli-transcript-tests.md @@ -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. diff --git a/verifiers/real-world/contract-testing-pact.md b/verifiers/real-world/contract-testing-pact.md new file mode 100644 index 0000000..4ce21d0 --- /dev/null +++ b/verifiers/real-world/contract-testing-pact.md @@ -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. diff --git a/verifiers/real-world/cross-platform-matrix.md b/verifiers/real-world/cross-platform-matrix.md new file mode 100644 index 0000000..76a32b0 --- /dev/null +++ b/verifiers/real-world/cross-platform-matrix.md @@ -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 --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. diff --git a/verifiers/real-world/doc-tests-and-links.md b/verifiers/real-world/doc-tests-and-links.md new file mode 100644 index 0000000..42a71a3 --- /dev/null +++ b/verifiers/real-world/doc-tests-and-links.md @@ -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). diff --git a/verifiers/real-world/e2e-playwright.md b/verifiers/real-world/e2e-playwright.md new file mode 100644 index 0000000..931694c --- /dev/null +++ b/verifiers/real-world/e2e-playwright.md @@ -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. diff --git a/verifiers/real-world/lighthouse-budget.md b/verifiers/real-world/lighthouse-budget.md new file mode 100644 index 0000000..e4cfa65 --- /dev/null +++ b/verifiers/real-world/lighthouse-budget.md @@ -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. diff --git a/verifiers/real-world/load-test-k6.md b/verifiers/real-world/load-test-k6.md new file mode 100644 index 0000000..34b81c3 --- /dev/null +++ b/verifiers/real-world/load-test-k6.md @@ -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. diff --git a/verifiers/real-world/multi-user-isolation.md b/verifiers/real-world/multi-user-isolation.md new file mode 100644 index 0000000..0b0ec31 --- /dev/null +++ b/verifiers/real-world/multi-user-isolation.md @@ -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//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. diff --git a/verifiers/real-world/packaging-install-upgrade.md b/verifiers/real-world/packaging-install-upgrade.md new file mode 100644 index 0000000..a8094b6 --- /dev/null +++ b/verifiers/real-world/packaging-install-upgrade.md @@ -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. diff --git a/verifiers/real-world/runtime-self-check.md b/verifiers/real-world/runtime-self-check.md new file mode 100644 index 0000000..41d2da7 --- /dev/null +++ b/verifiers/real-world/runtime-self-check.md @@ -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: ; 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. diff --git a/verifiers/real-world/smoke-after-deploy.md b/verifiers/real-world/smoke-after-deploy.md new file mode 100644 index 0000000..6ed9feb --- /dev/null +++ b/verifiers/real-world/smoke-after-deploy.md @@ -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). diff --git a/verifiers/real-world/tool-description-lint.md b/verifiers/real-world/tool-description-lint.md new file mode 100644 index 0000000..27c410a --- /dev/null +++ b/verifiers/real-world/tool-description-lint.md @@ -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). diff --git a/verifiers/regression/api-breaking-schema.md b/verifiers/regression/api-breaking-schema.md new file mode 100644 index 0000000..5a0a574 --- /dev/null +++ b/verifiers/regression/api-breaking-schema.md @@ -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. diff --git a/verifiers/regression/api-semver-rust.md b/verifiers/regression/api-semver-rust.md new file mode 100644 index 0000000..d3cd548 --- /dev/null +++ b/verifiers/regression/api-semver-rust.md @@ -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. diff --git a/verifiers/regression/api-surface-typescript.md b/verifiers/regression/api-surface-typescript.md new file mode 100644 index 0000000..be64fde --- /dev/null +++ b/verifiers/regression/api-surface-typescript.md @@ -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 `/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/.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. diff --git a/verifiers/regression/architecture-lint.md b/verifiers/regression/architecture-lint.md new file mode 100644 index 0000000..9f59637 --- /dev/null +++ b/verifiers/regression/architecture-lint.md @@ -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). diff --git a/verifiers/regression/baseline-before-change.md b/verifiers/regression/baseline-before-change.md new file mode 100644 index 0000000..d7f31a4 --- /dev/null +++ b/verifiers/regression/baseline-before-change.md @@ -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. diff --git a/verifiers/regression/characterization-tests.md b/verifiers/regression/characterization-tests.md new file mode 100644 index 0000000..3ee26ba --- /dev/null +++ b/verifiers/regression/characterization-tests.md @@ -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. diff --git a/verifiers/regression/db-migration-safety.md b/verifiers/regression/db-migration-safety.md new file mode 100644 index 0000000..19470d9 --- /dev/null +++ b/verifiers/regression/db-migration-safety.md @@ -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. diff --git a/verifiers/regression/golden-files-hand-verified.md b/verifiers/regression/golden-files-hand-verified.md new file mode 100644 index 0000000..de1cfc2 --- /dev/null +++ b/verifiers/regression/golden-files-hand-verified.md @@ -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. diff --git a/verifiers/regression/perf-regression.md b/verifiers/regression/perf-regression.md new file mode 100644 index 0000000..eafe76a --- /dev/null +++ b/verifiers/regression/perf-regression.md @@ -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. diff --git a/verifiers/regression/ratchet-floor.md b/verifiers/regression/ratchet-floor.md new file mode 100644 index 0000000..9829115 --- /dev/null +++ b/verifiers/regression/ratchet-floor.md @@ -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 ` (a version of this pattern runs in a reference project): +```sh +#!/bin/bash +set -euo pipefail +base_ref="${1:?usage: floor.sh }" +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 ``, 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`). diff --git a/verifiers/regression/read-only-guarantee.md b/verifiers/regression/read-only-guarantee.md new file mode 100644 index 0000000..3589f5f --- /dev/null +++ b/verifiers/regression/read-only-guarantee.md @@ -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`). diff --git a/verifiers/regression/size-budget.md b/verifiers/regression/size-budget.md new file mode 100644 index 0000000..b5c3fe0 --- /dev/null +++ b/verifiers/regression/size-budget.md @@ -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). diff --git a/verifiers/regression/snapshot-insta.md b/verifiers/regression/snapshot-insta.md new file mode 100644 index 0000000..43aa588 --- /dev/null +++ b/verifiers/regression/snapshot-insta.md @@ -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). diff --git a/verifiers/regression/ui-structure-snapshot.md b/verifiers/regression/ui-structure-snapshot.md new file mode 100644 index 0000000..d9691f2 --- /dev/null +++ b/verifiers/regression/ui-structure-snapshot.md @@ -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. diff --git a/verifiers/regression/visual-regression-native-gui.md b/verifiers/regression/visual-regression-native-gui.md new file mode 100644 index 0000000..57c6364 --- /dev/null +++ b/verifiers/regression/visual-regression-native-gui.md @@ -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 --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. diff --git a/verifiers/regression/visual-regression-web.md b/verifiers/regression/visual-regression-web.md new file mode 100644 index 0000000..2eba174 --- /dev/null +++ b/verifiers/regression/visual-regression-web.md @@ -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. diff --git a/verifiers/regression/zero-warnings.md b/verifiers/regression/zero-warnings.md new file mode 100644 index 0000000..e7ca13a --- /dev/null +++ b/verifiers/regression/zero-warnings.md @@ -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. diff --git a/verifiers/safety/codeql.md b/verifiers/safety/codeql.md new file mode 100644 index 0000000..606e15a --- /dev/null +++ b/verifiers/safety/codeql.md @@ -0,0 +1,56 @@ +--- +id: codeql +title: CodeQL queries for data-flow security and custom bug classes +answers: Can untrusted input reach a dangerous call anywhere in this code? +rung: 2 +section: safety +languages: any +kinds: general, parsing +cost: high +detect: codeql version +ran_here: no +verified: docs +--- + +## Use when +- The claim is about flow: user input reaching SQL, a shell, a file path or a deserialiser through several functions. +- You need a repeatable security scan in CI (GitHub code scanning runs the same engine). +- You want a custom query for a project-specific flow, such as "a value read from the request must pass `sanitize()` before `render()`". + +## Do not use when +- Licence first: the CodeQL CLI terms (codeql-cli-binaries README) say it "can only be used on codebases that are released under an OSI-approved open source license, or to perform academic research" and "can't be used to generate CodeQL databases for or during automated analysis, continuous integration or continuous delivery" outside that; private commercial code needs GitHub code scanning (which is licensed) or a sales contract. Check this before putting it in a contract. +- A pattern match is enough; `static-analysis-semgrep` is far cheaper to set up. +- The language is not supported. The supported list is C/C++, C#, GitHub Actions workflows, Go, Java, Kotlin, JavaScript/TypeScript, Python, Ruby, Rust (editions 2021 and 2024, needs Cargo, no nightly features) and Swift (analysis needs macOS). +- You need to show behaviour is correct rather than safe. + +## Set up +Download the CodeQL bundle (CLI plus the standard query packs) from the +`github/codeql-action` releases (assets `codeql-bundle-*`), unpack it and put +`codeql` on PATH. Then, per project; the database path comes last and must not exist yet: + + codeql database create db --language=python --source-root=. + # compiled languages add: --command="make" + # --build-mode=none exists for C#, Java, JavaScript/TypeScript, Python and Ruby only + +## Minimal example +Run the maintained security suite, then your own query pack: + + codeql database analyze --format=sarifv2.1.0 --output=out.sarif -- db \ + codeql/python-queries:codeql-suites/python-security-extended.qls + +## Run + codeql database analyze --format=sarifv2.1.0 --output=out.sarif -- db + python3 -c "import json,sys; r=json.load(open('out.sarif'))['runs'][0]['results']; print(len(r)); sys.exit(1 if r else 0)" + +Passing looks like: the analyze command exits 0 and the result count is 0. +The CLI manual does not document exit codes for `analyze`; the usual behaviour (not confirmed here, the tool is not installed) is exit 0 even when it finds issues, so the count check is what fails. The manual also says `sarif-latest` output changes between CodeQL versions and is unsuitable for automation, so the pinned `sarifv2.1.0` is used here. `--threads=0` uses every core. + +## As a contract check + {"id": "codeql-security", "claim": "CodeQL security-extended suite reports no results", "kind": "general", "rung": 2, "cmd": "codeql database analyze --format=sarifv2.1.0 --output=out.sarif -- db codeql/python-queries:codeql-suites/python-security-extended.qls && python3 -c \"import json,sys; sys.exit(1 if json.load(open('out.sarif'))['runs'][0]['results'] else 0)\"", "expect": {"exit": 0}, "timeout_s": 1800, "tier": "deep"} + +## What a pass does not prove +Only the flows the queries model are found; custom sinks and sanitisers that +the library does not know produce misses or noise. A stale database +(created before your edit) gives a pass for old code, so recreate it each run. +Check the check: add a known-vulnerable line on a scratch branch and confirm it +is reported. diff --git a/verifiers/safety/dependency-audit-general.md b/verifiers/safety/dependency-audit-general.md new file mode 100644 index 0000000..8494bf3 --- /dev/null +++ b/verifiers/safety/dependency-audit-general.md @@ -0,0 +1,60 @@ +--- +id: dependency-audit-general +title: Vulnerability scans for any ecosystem with osv-scanner, npm audit and pip-audit +answers: Do the packages this project depends on have known vulnerabilities? +rung: 2 +section: safety +languages: any +kinds: general +cost: low +detect: osv-scanner --version +ran_here: no +verified: docs +--- + +Note: `npm audit --help` was read here, and the `pip-audit` commands below +were run here (pip-audit 2.10.1, in a throwaway virtualenv, needs network). `osv-scanner` is not +installed here; its commands and exit codes come from the osv-scanner +documentation (google.github.io/osv-scanner). + +## Use when +- The change adds or upgrades a dependency, or you are about to release. +- The project spans several ecosystems (npm, PyPI, Go, Maven, crates): osv-scanner reads their lockfiles together. +- A scheduled job must catch advisories published after the code was written. + +## Do not use when +- The project is Rust only and wants licence and source rules as well; use `dependency-audit-rust`. +- No lockfile is committed. Scans of loose version ranges give answers about a build nobody ran. + +## Set up + go install github.com/google/osv-scanner/v2/cmd/osv-scanner@latest # needs a recent Go; or: brew install osv-scanner, or a release binary + pipx install pip-audit # needs Python 3.10 or newer + # npm audit ships with npm + +## Minimal example +Commit the lockfiles (`package-lock.json`, `poetry.lock`, `requirements.txt` with +pins, `go.mod`), then scan them. + +## Run + osv-scanner scan source -r . + npm audit --audit-level=high --omit=dev + pip-audit -r requirements.txt --strict + +Passing looks like: osv-scanner exits 0 (the docs define 0 as "packages found, none match a vulnerability"; its exact message is not documented); `npm audit` exits +0 and prints "found 0 vulnerabilities" at or above the chosen level; `pip-audit` +exits 0 and prints "No known vulnerabilities found". Any finding exits 1 for all three. osv-scanner +also exits 128 when it found no packages to scan (wrong directory, no lockfile) and 127 on a general error: both are failures, not passes. +`pip-audit` with unpinned requirements resolves dependencies itself; `--strict` turns a failed resolution into a failure. +`--omit=dev` limits npm to what ships; drop it if build tools run on untrusted input. + +## As a contract check + {"id": "dep-vulns", "claim": "No known vulnerabilities in locked dependencies", "kind": "general", "rung": 2, "cmd": "osv-scanner scan source -r .", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"} + +## What a pass does not prove +osv-scanner reports vulnerabilities of every severity; the docs page for its CLI mentions no severity filter, so the contract above is "none at all", not "none above high". Use `npm audit --audit-level=high` if you want a severity cut. +Only advisories already in the database, for versions the lockfile names. +Network is needed; an offline run that silently skips the database must not +count (check the output says it queried). Ignoring a finding in a config file +is the usual way this check is defeated: review the diff of any ignore list. A +vulnerable package that is installed but unreachable is still reported, and a +reachable vulnerable function in an unreported package is not. diff --git a/verifiers/safety/dependency-audit-rust.md b/verifiers/safety/dependency-audit-rust.md new file mode 100644 index 0000000..06e224f --- /dev/null +++ b/verifiers/safety/dependency-audit-rust.md @@ -0,0 +1,63 @@ +--- +id: dependency-audit-rust +title: cargo-deny and cargo-audit for advisories, yanked crates, licences and sources +answers: Do my Rust dependencies have known vulnerabilities, yanked versions, disallowed licences or untrusted sources? +rung: 2 +section: safety +languages: rust +kinds: general +cost: low +detect: cargo-deny --version +ran_here: yes +verified: ran +--- + +Ran here with cargo-deny 0.20.2 (licenses, bans, sources and advisories on a +tiny crate). cargo-audit was not installed; its command is from memory. + +## Use when +- Any change to `Cargo.toml` or `Cargo.lock`, and on a schedule (new advisories appear without you changing code). +- You must ship under a licence and need to know no dependency conflicts with it. +- Before release, so no yanked crate or unknown git source goes out. + +## Do not use when +- The project is not Rust; see `dependency-audit-general`. +- You want proof the dependency code is correct. This reports known problems only. + +## Set up + cargo install cargo-deny --locked + cargo deny init # writes deny.toml; edit it as below + +## Minimal example +`deny.toml`: + + [advisories] + yanked = "deny" + [licenses] + allow = ["MIT", "Apache-2.0", "BSD-3-Clause", "ISC", "Unicode-3.0"] + [bans] + wildcards = "deny" + [sources] + unknown-registry = "deny" + unknown-git = "deny" + +Record every exception beside its reason and a date, never on the command line. + +## Run + cargo deny check advisories licenses bans sources + cargo audit # alternative advisory-only check + +Passing looks like: `advisories ok, bans ok, licenses ok, sources ok`, exit 0. +Failure exits non-zero (4 in the run here) with `error[rejected]` or +`error[unlicensed]`. The default `deny init` file allows no licence, so a +fresh crate fails until `allow` is filled in. Advisory checks need network to +fetch the RustSec database. + +## As a contract check + {"id": "cargo-deny", "claim": "No known advisories, yanked crates, disallowed licences or unknown sources", "kind": "general", "rung": 2, "cmd": "cargo deny check advisories licenses bans sources", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600} + +## What a pass does not prove +Only known, reported problems. Today's pass says nothing about tomorrow's +advisory, so schedule it (see `check-tiering`). `ignore` entries and loosened +`allow` lists are how this check gets defeated: read the diff of `deny.toml`. +An unmaintained-crate notice is not a vulnerability; decide that on purpose. diff --git a/verifiers/safety/licence-notices.md b/verifiers/safety/licence-notices.md new file mode 100644 index 0000000..89c6245 --- /dev/null +++ b/verifiers/safety/licence-notices.md @@ -0,0 +1,67 @@ +--- +id: licence-notices +title: Generating and checking third-party licence notices +answers: Does the shipped product carry the licence texts and copyright notices its dependencies require? +rung: 3 +section: safety +languages: any +kinds: general +cost: medium +detect: command -v cargo-about +ran_here: no +verified: docs +--- + +Note: cargo-about is not usable here (the mise shim has no version set), so the +script was not run. The cargo-about install command and the `generate` and `init` +flags below were checked against its documentation (EmbarkStudios/cargo-about, +docs/src). The generate-then-compare shape is the one used by a working script in a Rust and Lean 4 +project (a `scripts/notices.sh`), which also calls `cargo about generate --locked --all-features --offline`. + +## Use when +- You ship a binary, package or image that contains other people's code. MIT, BSD, Apache-2.0 and ISC all require their text to travel with copies. +- A dependency was added, removed or upgraded. +- Before release (see `release-gate`). + +## Do not use when +- You only run the code internally and never distribute it. +- The question is "is this licence allowed at all"; that is `dependency-audit-rust` (or the ecosystem's licence checker). + +## Set up +Rust: `cargo install --locked --features cli cargo-about` (the `cli` feature is needed), then `cargo about init` for +`about.toml` and `about.hbs`. `about.toml` must carry an `accepted` list of licence ids (in priority order); cargo-about errors on a crate whose licence it cannot satisfy from that list. Other ecosystems: `pip-licenses`, +`license-checker`, or `go-licenses report`. Commit the generated file. + +## Minimal example +`scripts/notices.sh` generates `THIRD-PARTY-NOTICES.txt`, or with `--check` fails +if the committed copy is stale: + + #!/usr/bin/env bash + set -euo pipefail + tmp=$(mktemp); trap 'rm -f "$tmp"' EXIT + cargo about generate --locked --all-features --fail about.hbs > "$tmp" + if [ "${1:-}" = "--check" ]; then + diff -q "$tmp" THIRD-PARTY-NOTICES.txt >/dev/null \ + || { echo "notices out of date: run scripts/notices.sh" >&2; exit 1; } + else cp "$tmp" THIRD-PARTY-NOTICES.txt; fi + +`--fail` exits non-zero when a crate's licence cannot be determined; without it such crates are skipped. For a workspace add `--workspace`, or point `-m crates/app/Cargo.toml` at the one binary you ship, so the list is what the program contains. `--offline` (never touch the network) makes cargo-about use only the crates' packaged files, losing clarifications that fetch licence text from a repository. `-c about.toml` is the default config path. + +The output must not contain dates or absolute paths, or the byte comparison +fails on every machine. + +## Run + scripts/notices.sh --check + +Passing looks like: exit 0, no output. Failure prints "notices out of date" and +exits 1; regenerate, read the diff, commit. + +## As a contract check + {"id": "notices-current", "claim": "THIRD-PARTY-NOTICES.txt matches the dependencies", "kind": "general", "rung": 3, "cmd": "scripts/notices.sh --check", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"} + +## What a pass does not prove +That the file is current, not that it is packaged. Also check the built package +contains it (see `release-gate`). Generators fall back to a licence's standard +text when a crate's own file does not match, which has a placeholder copyright +line; MIT and BSD want the real notice. Bundled fonts and vendored code are +outside the dependency graph and need their own entries. diff --git a/verifiers/safety/rust-lints-strict.md b/verifiers/safety/rust-lints-strict.md new file mode 100644 index 0000000..c7e2f73 --- /dev/null +++ b/verifiers/safety/rust-lints-strict.md @@ -0,0 +1,61 @@ +--- +id: rust-lints-strict +title: Clippy with warnings denied, pedantic groups and an unsafe policy +answers: Does the Rust code compile with zero warnings and no lint the project has chosen to forbid? +rung: 1 +section: safety +languages: rust +kinds: general, money, parsing +cost: low +detect: cargo clippy --version +ran_here: yes +verified: ran +--- + +## Use when +- Any Rust change: this is the cheapest check there is and catches real bugs (lossy casts, unchecked indexing, missing `#[must_use]`). +- Code handles money or untrusted input, where `as` casts, `unwrap` and `panic` are hazards. +- You want "warnings are errors" stated once, so it is not a matter of taste. + +## Do not use when +- You need to know the code does the right thing. Lints find shapes, not wrong answers. + +## Set up +Put the policy in the manifest so every command sees it (`Cargo.toml`): + + [lints.rust] + unsafe_code = "forbid" + + [lints.clippy] + pedantic = { level = "warn", priority = -1 } + unwrap_used = "deny" + expect_used = "deny" + cast_possible_truncation = "deny" + indexing_slicing = "deny" + +## Minimal example +`src/lib.rs`: + + #[must_use] + pub fn add(a: u64, b: u64) -> Option { a.checked_add(b) } + +## Run + cargo clippy --workspace --all-targets --all-features -- -D warnings + cargo fmt --all --check + +Passing looks like: exit 0 and no `warning:` or `error:` lines. Failure shows as +`error: could not compile` with the lint name; here, dropping `#[must_use]` +fails with `clippy::must_use_candidate` (run here, clippy 0.1.100). `-D +warnings` promotes every enabled pedantic warning to an error, which is the +point. Do not fix a lint with a blanket `#![allow(...)]`; allow one item and +give the reason in a comment. + +## As a contract check + {"id": "clippy-strict", "claim": "Zero clippy warnings including pedantic and the unsafe policy", "kind": "general", "rung": 1, "cmd": "cargo clippy --workspace --all-targets --all-features -- -D warnings", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900} + +## What a pass does not prove +Not that the logic is right. `--all-targets` is needed or tests and examples +are skipped; `--all-features` is needed or feature-gated code is skipped. A +crate with `#![allow(clippy::all)]` or a `[lints]` override passes trivially: +grep for `allow(` additions in the diff. Check the check by adding a +deliberate `.unwrap()` and seeing it fail. diff --git a/verifiers/safety/secret-scanning.md b/verifiers/safety/secret-scanning.md new file mode 100644 index 0000000..c73aab8 --- /dev/null +++ b/verifiers/safety/secret-scanning.md @@ -0,0 +1,61 @@ +--- +id: secret-scanning +title: Secret scanning with gitleaks or trufflehog on the diff and the history +answers: Did this change, or any earlier commit, put a password, key or token into the repository? +rung: 2 +section: safety +languages: any +kinds: general +cost: low +detect: gitleaks version +ran_here: no +verified: docs +--- + +Note: neither gitleaks nor trufflehog is installed here, so nothing below was +run. Commands and exit codes were checked against the gitleaks README (v8.30.x, +which says gitleaks is "feature complete", with security patches only from now on; +the author's new project is Betterleaks, not covered here) and the trufflehog README. + +## Use when +- Every change, before it is committed or pushed. A leaked key must be rotated, so catching it early is the whole value. +- Code touches configuration, tests with credentials, deployment files or `.env` handling. +- Before making a private repository public. + +## Do not use when +- The worry is a secret that is not in the repository but in logs or output; see `sensitive-data-leak-test`. + +## Set up + # gitleaks: brew install gitleaks, the docker image ghcr.io/gitleaks/gitleaks, or a release binary + gitleaks version + # trufflehog: brew install trufflehog, or the install script / docker image in its README + # optional allowlist for known fake values: .gitleaks.toml + +## Minimal example +Scan only what is about to be committed, then the full history: + + gitleaks git --staged --redact -v + gitleaks git --redact -v # all commits (`gitleaks dir` scans files without git history) + +`--redact` keeps the secret itself out of the report, which matters because the +report may be pasted into a log or chat. + +## Run + gitleaks git --redact --exit-code 1 + trufflehog git file://. --results=verified --fail --no-update # alternative; verifies keys against the provider + +Passing looks like: gitleaks exits 0 (README: "0 - no leaks present"). A finding exits 1 (the default, set with `--exit-code`) and names +the file, line and rule; an error also exits 1 and an unknown flag exits 126. trufflehog exits 0 with no results, 1 on an error, and 183 when results were found, which only happens with `--fail`. +`--results=verified` counts only keys the provider confirms are live; use `--results=verified,unknown` to also fail on keys it could not check. +`gitleaks detect` and `protect` still work but are deprecated since 8.19.0. If a real secret is found, rotate it first; removing it +from history does not make it safe again. + +## As a contract check + {"id": "no-secrets", "claim": "No secrets in the working tree or history", "kind": "general", "rung": 2, "cmd": "gitleaks git --redact --exit-code 1", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"} + +## What a pass does not prove +Scanners match known key shapes and high-entropy strings; a custom token format +or a password in prose is missed. A shallow CI clone hides history, so fetch +full depth. An allowlist entry that is too broad hides real leaks: read changes +to `.gitleaks.toml`. Check the check by committing a fake AWS-style key on a +scratch branch and confirming it is flagged. diff --git a/verifiers/safety/sensitive-data-leak-test.md b/verifiers/safety/sensitive-data-leak-test.md new file mode 100644 index 0000000..c01be2c --- /dev/null +++ b/verifiers/safety/sensitive-data-leak-test.md @@ -0,0 +1,61 @@ +--- +id: sensitive-data-leak-test +title: Tests that a secret value never appears in files, logs, free text or errors +answers: Can the secret value (a tax id, a token, a password) appear anywhere it should not? +rung: 3 +section: safety +languages: any +kinds: general +cost: low +detect: +ran_here: yes +verified: ran +--- + +## Use when +- The code handles a value that must be stored in one place only (a vault) or never stored: tax ids, tokens, card numbers, health data. +- A bug report says a secret showed up in a log line, an exception message, a backup, an export or free-text notes. +- You changed logging, error formatting, serialisation or export code near such a value. + +## Do not use when +- You are checking committed files for keys; use `secret-scanning`. +- The value can legitimately appear in output (the user's own page). Test a masked form instead. + +## Set up +No tool. Pick one unmistakable canary value per secret (a real-shaped but fake +tax id such as `123-45-6789`) and list its variants: with and without +separators, reversed, URL-encoded, base64 if the code encodes it. + +## Minimal example +Python, standard library (`test_leak.py`). Run every surface the program can write to +and assert the canary is in none: + + SECRET = "123-45-6789" + VARIANTS = {SECRET, SECRET.replace("-", ""), SECRET[::-1]} + # ... call save_vendor(name, SECRET, outdir, log) and a failing call ... + surfaces = {f.name: f.read_text() for f in Path(d).rglob("*") if f.is_file()} + surfaces["logs"] = "\n".join(captured_log_lines) + surfaces["error"] = str(exc_info.exception) + for where, text in surfaces.items(): + for v in VARIANTS: + assert v not in text, f"{v!r} leaked into {where}" + +Add a test that the check can fail: assert the canary is found in a string you +build to contain it. Also exercise the failure paths (bad input, crash): leaks +live in error messages and tracebacks. + +## Run + python3 -m unittest -q test_leak + +Passing looks like: `OK`. Failure shows `AssertionError: '123-45-6789' leaked +into logs`. Scan the whole data directory, temp files and any export, not only +the files you expect. + +## As a contract check + {"id": "no-secret-leak", "claim": "The secret canary appears in no file, log or error message", "kind": "general", "rung": 3, "cmd": "python3 -m unittest -q test_leak", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120} + +## What a pass does not prove +Only the surfaces and variants you listed. A secret transformed in a way you did +not list (hashed with a weak hash, split across lines) is not caught. Memory, +swap, crash dumps and third-party services are outside it. Rung 3 is honest: +it is examples, not a proof that no path leaks. diff --git a/verifiers/safety/shellcheck.md b/verifiers/safety/shellcheck.md new file mode 100644 index 0000000..3462570 --- /dev/null +++ b/verifiers/safety/shellcheck.md @@ -0,0 +1,50 @@ +--- +id: shellcheck +title: ShellCheck for shell scripts +answers: Do my shell scripts have quoting, word-splitting or portability bugs? +rung: 2 +section: safety +languages: any +kinds: general +cost: low +detect: shellcheck --version +ran_here: yes +verified: ran +--- + +## Use when +- You wrote or changed any `.sh` script, CI step, git hook or `just` recipe body in bash. +- A script deletes, moves or loops over files, where an unquoted variable can be destructive. +- A script must run on more than one shell (`sh`, `dash`, `bash`). + +## Do not use when +- The script is a few lines of fixed commands with no variables. Run it instead. +- You need to know the script produces the right result; ShellCheck cannot say so. Run it on test input. + +## Set up + shellcheck --version # package manager: pacman -S shellcheck, apt install shellcheck + +## Minimal example +`bad.sh`: + + #!/usr/bin/env bash + for f in $(ls *.txt); do rm $f; done + +## Run + shellcheck --severity=warning --shell=bash bad.sh + git ls-files '*.sh' | xargs -r shellcheck -x --severity=warning + +Passing looks like: no output, exit 0. Failure here (run on this machine, +v0.11.0) prints `SC2045 (error): Iterating over ls output is fragile. Use globs.` +and exits 1. `-x` follows `source`d files. Pick the shell with `--shell` or a +`# shellcheck shell=bash` line, or the wrong dialect is checked. Fix the cause; +only disable a code with `# shellcheck disable=SC2034` plus a comment saying why. + +## As a contract check + {"id": "shellcheck", "claim": "All shell scripts pass ShellCheck at warning level", "kind": "general", "rung": 2, "cmd": "git ls-files '*.sh' | xargs -r shellcheck -x --severity=warning", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 120} + +## What a pass does not prove +It checks syntax and well-known pitfalls only. `set -euo pipefail` mistakes, +logic errors, and wrong command arguments pass. Scripts without a `.sh` +extension or only a shebang (`bin/tool`) are skipped by the `git ls-files '*.sh'` +glob, so list them. A file full of `disable=` comments passes: grep the diff. diff --git a/verifiers/safety/static-analysis-semgrep.md b/verifiers/safety/static-analysis-semgrep.md new file mode 100644 index 0000000..ace529f --- /dev/null +++ b/verifiers/safety/static-analysis-semgrep.md @@ -0,0 +1,72 @@ +--- +id: static-analysis-semgrep +title: Semgrep rules, including a custom rule for a project-specific mistake +answers: Does any code match a known-bad pattern, including a mistake this project keeps making? +rung: 2 +section: safety +languages: any +kinds: general, parsing +cost: medium +detect: semgrep --version +ran_here: yes +verified: ran +--- + +## Use when +- You want a scan for a known class of bug (injection, unsafe deserialisation, hard-coded keys) across many languages. +- The project keeps repeating one mistake (calling `float()` on money, using `datetime.now()` where a clock is injected). Write a rule once; every later change is checked. +- You fixed a bug and want to make sure no sibling of it exists elsewhere. + +## Do not use when +- The claim is about behaviour or values. Semgrep matches syntax, so it cannot show a result is right. +- You need data-flow across files and functions that Semgrep's free taint mode cannot follow; see `codeql` (which has licence limits on private code; check it). + +## Set up + pipx install semgrep # README's preferred way; also: uv tool install semgrep, brew install semgrep + mkdir -p rules # not a hidden directory: `semgrep --test` found nothing under `.semgrep/` + +Not installed globally here; the example below was run in a throwaway virtualenv (`pip install semgrep`, version 1.186.0). + +## Minimal example +`rules/no-float-money.yml`: + + rules: + - id: no-float-money + languages: [python] + severity: ERROR + message: Money must be Decimal or integer cents, not float. + pattern-either: + - pattern: float($X) + - pattern: $X = $Y / $Z + paths: + include: ["/src/billing/"] + +`src/billing/bad.py` containing `total = float(price)` is reported. `paths.include` patterns are matched relative to the scan target, so scan from the project root (`.`) and anchor the pattern with a leading `/`. A bare `src/billing/` still works but prints a warning that it will change meaning. + +## Run + semgrep scan --config rules/ --error --metrics=off . + +Passing looks like: exit 0 and `Findings: 0`. With `--error` any finding exits 1; a fatal error (bad rule, bad config) exits 2. Without `--error`, findings still exit 0, so never drop the flag. Check the output also says `Targets scanned: N` with N above 0. + +Test the rule itself. Next to the rule, in a file with the same base name and the language's extension (`rules/no-float-money.py`): + + # ruleid: no-float-money + total = float(price) + # ok: no-float-money + total = price_cents + +then `semgrep scan --test rules/`. It prints `1/1: ✓ All tests passed` and exits 0; a missed `ruleid:` line prints `missed lines: [N]` and exits 1. + +## As a contract check + {"id": "semgrep-project-rules", "claim": "No code matches the project's banned patterns", "kind": "general", "rung": 2, "cmd": "semgrep scan --config rules/ --error --metrics=off . && semgrep scan --test rules/", "expect": {"exit": 0}, "timeout_s": 300, "tier": "deep"} + +## What a pass does not prove +A pass proves only that no code matches the patterns you wrote. A rule that +matches nothing passes forever. Two ways this happened while checking this +entry: a `paths.include` of `src/billing/` with the scan target `src/` scanned +zero files and exited 0, and `--test` against a hidden `.semgrep/` directory +printed "No unit tests found" and exited 0. So keep a `ruleid:` test file, run +`--test`, and read `Targets scanned`. Pattern rules miss aliasing, such as +`f = float; f(x)`. A rule is a sample of bad shapes, not a proof of safety. +Rule ids reported by `scan` carry the directory name as a prefix +(`rules.no-float-money`); the test annotations use the plain id. diff --git a/verifiers/safety/threat-model-checklist.md b/verifiers/safety/threat-model-checklist.md new file mode 100644 index 0000000..e13aeb5 --- /dev/null +++ b/verifiers/safety/threat-model-checklist.md @@ -0,0 +1,60 @@ +--- +id: threat-model-checklist +title: A short written threat model turned into checks +answers: Have I thought about who can attack this change and tested each way in? +rung: 5 +section: safety +languages: any +kinds: general +cost: medium +detect: +ran_here: no +verified: docs +--- + +Note: this technique has no tool; there is nothing to run. `verified: docs` +means the method follows STRIDE as published by Microsoft. + +## Use when +- The change crosses a trust boundary: parses data from outside, adds an endpoint, handles credentials, runs a subprocess, reads a user-supplied path, or changes who may do what. +- A security fix: the model says what attack the fix closes and what else is open. +- A new tool surface for agents, where input is untrusted text. + +## Do not use when +- The change is internal and touches no boundary. A paragraph of ceremony costs more than it saves. + +## Set up +Create `docs/threat-model/.md`. No tool required. + +## Minimal example +Five lines, then one check per threat: + + Asset: the invoice PDF a customer uploads and we render. + Entry points: POST /upload (file, filename), the renderer subprocess. + Who: any signed-in customer; an attacker with a customer account. + Threats (STRIDE) and checks: + T1 Tampering: filename `../../etc/x` writes outside uploads/ -> test_upload_path_traversal + T2 Denial of service: 2 GB file exhausts disk -> test_upload_size_limit (413) + T3 Info disclosure: one customer reads another's PDF -> test_cross_tenant_download (404) + T4 Elevation: renderer runs with the app's environment -> test_renderer_env_is_empty + Out of scope, stated: DDoS at the network layer. + +## Run + python3 - <<'PY' + import re,sys; t=open("docs/threat-model/upload.md").read() + bad=[l for l in t.splitlines() if re.match(r"\s*T\d+ ",l) and "->" not in l] + sys.exit(1 if bad else 0) + PY + pytest -k "traversal or size_limit or cross_tenant or renderer_env" + +Passing looks like: every threat line names a check, and each named check +exists and passes. A threat with no check is listed as open, not dropped. + +## As a contract check + {"id": "threat-checks", "claim": "Every threat in the model has a passing check", "kind": "general", "rung": 3, "cmd": "pytest -q -k 'traversal or size_limit or cross_tenant or renderer_env'", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 300} + +## What a pass does not prove +Only the threats you thought of. The value is the list, so have an independent +reader (a second model, or the human) add threats before you write checks, and +record disagreements. The rung is 5 for the model itself and 3 for the +executable checks derived from it. diff --git a/verifiers/safety/unsafe-audit.md b/verifiers/safety/unsafe-audit.md new file mode 100644 index 0000000..25d7769 --- /dev/null +++ b/verifiers/safety/unsafe-audit.md @@ -0,0 +1,59 @@ +--- +id: unsafe-audit +title: Auditing and forbidding unsafe Rust +answers: Is there any unsafe code in this crate or its dependencies, and is what exists justified and tested? +rung: 1 +section: safety +languages: rust +kinds: general, concurrency +cost: low +detect: cargo --version +ran_here: yes +verified: ran +--- + +Ran here: `#![forbid(unsafe_code)]` refusing an `unsafe` block. Not run here: +`cargo geiger` (not installed) and Miri (component not on this toolchain); +their flags are from memory. + +## Use when +- The crate says it needs no `unsafe`: make the compiler enforce that. +- A change adds `unsafe`, or a dependency is added or upgraded and you want its unsafe footprint. +- Unsafe code exists and you need its undefined behaviour checked (Miri). + +## Do not use when +- The crate is a thin wrapper over FFI, where unsafe is the job; audit each block by hand and test under sanitisers instead. + +## Set up + # forbid: top of src/lib.rs and src/main.rs + #![forbid(unsafe_code)] + cargo install cargo-geiger # counts unsafe in the crate and dependencies + rustup +nightly component add miri + +## Minimal example +`src/lib.rs`: + + #![forbid(unsafe_code)] + pub fn first(v: &[u8]) -> Option { v.first().copied() } + +Adding `unsafe { *v.get_unchecked(0) }` makes the build fail with +"usage of an `unsafe` block". + +## Run + cargo build + cargo geiger --all-features # report; unsafe counts per dependency + cargo +nightly miri test # runs tests under the UB-detecting interpreter + +Passing looks like: `cargo build` exits 0 under forbid; geiger shows 0 used +unsafe in your own crates (`🔒` rows); Miri exits 0. Failure: a compile error, +a non-zero geiger count in your crate, or a Miri "Undefined Behavior" message. +For concurrency, see `miri`, `loom` and `thread-sanitizer` in the concurrency section. + +## As a contract check + {"id": "no-unsafe", "claim": "The crate forbids unsafe code and builds", "kind": "general", "rung": 1, "cmd": "grep -q 'forbid(unsafe_code)' src/lib.rs && cargo build --all-features", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600} + +## What a pass does not prove +`forbid` covers your crate only; dependencies may still use unsafe (that is what +geiger reports, and it counts, it does not judge). Miri finds UB only on paths +the tests run, and cannot run most FFI or I/O. A `forbid` that someone moved +into `#![allow]` is a silent failure: keep the grep in the check. diff --git a/verifiers/test-quality/assertion-strength-review.md b/verifiers/test-quality/assertion-strength-review.md new file mode 100644 index 0000000..b694dbb --- /dev/null +++ b/verifiers/test-quality/assertion-strength-review.md @@ -0,0 +1,53 @@ +--- +id: assertion-strength-review +title: Review that tests assert on outcomes, not just that code ran +answers: Do these tests check the result that matters, or would they pass for wrong behaviour too? +rung: 5 +section: test-quality +languages: any +kinds: general, money, parsing, state-machine +cost: low +detect: +ran_here: no +verified: docs +--- + +## Use when +- You wrote or were handed tests and want to know they would fail on wrong output. +- A suite has high coverage and passes but a bug shipped. +- Before reporting done: a last read of your own new tests, with the checklist below. + +## Do not use when +- A mutation tool is available and fast enough: it measures this mechanically. This review is judgement (rung 5) and is for cases the tool cannot reach or as a quick first pass. + +## Set up +No tool. Read each new test and ask the questions below. A second agent or reviewer, given only the tests and the spec (not your reasoning), makes the review less biased. Cheap mechanical aids: `grep` for the smells; run mutation testing on the changed file (`mutation-on-diff`). + +## Minimal example +Smells and what to do instead: + +| Smell | Why it is weak | Instead | +|---|---|---| +| `assert!(result.is_ok())` | passes for any success value | compare the value: `assert_eq!(result.unwrap(), expected)` | +| Test calls the function and asserts nothing, or "does not panic" | passes if the output is garbage | assert the output, the state change or the error variant | +| Snapshot of the whole output, accepted blindly | records the current behaviour, right or wrong | review the snapshot line by line against the spec; assert key fields too | +| Assertion computed with the same code under test | tests the code against itself | use a hand-calculated constant or an independent oracle | +| `assert!(x > 0)` where an exact value is known | allows many wrong values | assert the exact value | +| Mock returns what the test expects; test checks the mock was called | tests the mock | assert the observable effect | +| Assertion inside a loop over an empty list, or in a callback that may not fire | vacuous | assert the count first; see `vacuity-check` | +| Only the happy path | misses boundaries | add the boundary, the empty input, the error case | + +## Run +For each new test, write down in one line what wrong implementation it would catch. If you cannot name one, the test is weak. Then check it mechanically: temporarily change the code (flip a comparison, return a constant) and run the test; it must fail. + +Passing looks like: every test has a named wrong behaviour it rejects, and the temporary breakage turns it red. Failure: a test stays green under a plausible bug. + +## As a contract check + {"id": "assertion-review", "claim": "Each new test fails when the behaviour it covers is broken", "kind": "general", "rung": 5, "cmd": "cargo mutants --in-diff /tmp/change.diff", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800} + +The review itself is judged; the mechanical stand-in is mutation testing of the diff, with the same limits as in `mutation-on-diff`. + +## What a pass does not prove +- A judged review is only as good as the reviewer's reading of the spec. It can miss subtle gaps. +- Strong assertions on the wrong expected value are still wrong. Derive expected values from the specification, not from the output you just got. +- It does not show the tests were run. See `vacuity-check`. diff --git a/verifiers/test-quality/cargo-mutants.md b/verifiers/test-quality/cargo-mutants.md new file mode 100644 index 0000000..0b77a2f --- /dev/null +++ b/verifiers/test-quality/cargo-mutants.md @@ -0,0 +1,58 @@ +--- +id: cargo-mutants +title: Mutation testing for Rust with cargo-mutants +answers: Would my tests notice if this Rust code were wrong? +rung: 2 +section: test-quality +languages: rust +kinds: general, money, parsing, state-machine +cost: medium +detect: cargo mutants --version +ran_here: yes +verified: ran +--- + +## Use when +- You wrote tests for new or changed logic and want evidence they can fail, not just that they pass. +- The code is money, parsing, validation or a state machine where a flipped comparison is costly. +- Coverage is high but you doubt the assertions. Mutation testing is a check on your other checks: it adds confidence in the tests, which is why it sits at rung 2. + +## Do not use when +- You only touched a few lines and a full run is too slow; use `mutation-on-diff`. +- The tests are slow end-to-end tests; each mutant reruns them. Narrow with `--test-package`. +- The code has no tests yet. Everything survives. + +## Set up + cargo install cargo-mutants # or: cargo binstall cargo-mutants + cargo mutants --version + +Optional `.cargo/mutants.toml` holds `exclude_globs`, `exclude_re`, `timeout_multiplier`. To mark a function as not worth mutating, add the `mutants` crate as a normal dependency and use `#[mutants::skip]` (source: mutants.rs docs). + +## Minimal example +`src/lib.rs`, with a boundary the tests miss: + + pub fn price(qty: u32, unit: u32) -> u32 { + let total = qty * unit; + if qty >= 10 { total - total / 10 } else { total } + } + #[cfg(test)] mod tests { use super::*; + #[test] fn small() { assert_eq!(price(2, 100), 200); } + #[test] fn big() { assert_eq!(price(20, 100), 1800); } } + +## Run + cargo mutants -p mycrate --timeout-multiplier 3 --minimum-test-timeout 60 -j 2 + +Passing looks like: `N mutants tested ...: M caught` with no `MISSED` lines, exit 0. Failure shows `MISSED src/lib.rs:4:12: replace >= with > in price` (here: the `qty >= 10` boundary, caught only after adding `assert_eq!(price(10, 100), 900)`), exit 2. Missed mutants are in `mutants.out/missed.txt`, timeouts in `timeout.txt`, unviable (does not compile) in `unviable.txt`. + +Reading survivors: for each, decide kill or equivalent. Kill it with a test that fails under the mutant. A mutant is equivalent when the changed code cannot alter observable behaviour; record the reason and exclude it with `#[mutants::skip]` or `-E `. Never delete a test or loosen an assertion to make it pass. + +Long runs: `--shard k/n` splits work; `--iterate` reuses `mutants.out` and skips mutants already caught or unviable. Keep `mutants.out` between interrupted runs; the per-mutant build copy is large, so point `TMPDIR` at a disk with space. Use `--list` to preview the mutants without running. + +## As a contract check + {"id": "mutants-core", "claim": "Every viable mutant of the pricing module is caught by tests", "kind": "general", "rung": 2, "cmd": "cargo mutants -p mycrate --file src/pricing.rs --timeout-multiplier 3", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 3600} + +## What a pass does not prove +- Caught mutants show the tests react to those small edits only. They do not show the specification is right. +- Equivalent mutants and `skip`ped code are not checked. List each exclusion and why. +- A timeout counts as caught by default but may mean a hang from a weak test; read `timeout.txt`. +- If the baseline run (unmutated tests) fails, nothing is tested; the exit is non-zero. Do not read it as survivors. diff --git a/verifiers/test-quality/check-the-checker.md b/verifiers/test-quality/check-the-checker.md new file mode 100644 index 0000000..33009b1 --- /dev/null +++ b/verifiers/test-quality/check-the-checker.md @@ -0,0 +1,53 @@ +--- +id: check-the-checker +title: Plant a known bug to confirm the verification pipeline catches it +answers: If the code were wrong, would my whole verification pipeline actually report it? +rung: 2 +section: test-quality +languages: any +kinds: general, concurrency, money, parsing +cost: low +detect: git --version +ran_here: yes +verified: ran +--- + +## Use when +- You wrote a new gate, contract check, CI job or script and want to know it can fail. +- A gate has passed for a long time and you have never seen it red. +- You changed the toolchain, a flag or an environment, and the pass might now be vacuous. + +This is a check on another check; mutation testing is the automated form of it for unit tests. A planted bug (a canary) proves one specific path through the pipeline, so it adds rung 2 confidence in that gate. + +## Do not use when +- You can run a mutation tool over the area: it plants many bugs and reads the result for you. +- The pipeline touches shared or production systems. Plant the bug only in a local copy. + +## Set up +Work in a throwaway branch, worktree or copy so the bug cannot be committed. Choose a canary that the gate is meant to catch: flip a comparison, return a constant, drop a validation, swap two arguments, remove a lock. Keep it small and obvious. + + git worktree add /tmp/canary HEAD && cd /tmp/canary + +## Minimal example +Gate: `cargo test price`. Canary: change `qty >= 10` to `qty > 10`. + + sed -i 's/qty >= 10/qty > 10/' src/lib.rs + cargo test price; echo "exit=$?" # must be non-zero + +Better, keep a permanent canary: a test marked `#[should_panic]` or a script that deliberately feeds a known-bad input into the gate and asserts the gate rejects it (for example, a linter fixture with a known violation, which the lint must flag). + +## Run +Run the full gate, not just the unit test, with the bug in place: the same command the contract uses. + +Passing looks like: the gate fails, naming the canary (the right test, the right message). Failure of the pipeline: it exits 0 with the bug in place. Then restore the file (`git checkout -- src/lib.rs`, or remove the worktree) and confirm the gate passes again. + +## As a contract check + {"id": "canary", "claim": "The gate fails when a known bug is planted and passes when it is removed", "kind": "general", "rung": 2, "cmd": "sed -i 's/qty >= 10/qty > 10/' src/lib.rs && ! cargo test price; r=$?; git checkout -q -- src/lib.rs; test $r -eq 0 && cargo test price", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600} + +The contract above edits the working tree and restores it with `git checkout`. Do not run it with uncommitted changes in that file. + +## What a pass does not prove +- That the gate catches other bugs. One canary shows one path; plant several kinds (value, boundary, state, concurrency). +- A canary that is too blatant is caught by anything. Make it realistic for the change. +- It must fail for the right reason. Read the failure output; a compile error from your sed is not a catch. +- Always revert the canary. A forgotten planted bug is worse than no check. diff --git a/verifiers/test-quality/coverage-floor.md b/verifiers/test-quality/coverage-floor.md new file mode 100644 index 0000000..7f2f1c2 --- /dev/null +++ b/verifiers/test-quality/coverage-floor.md @@ -0,0 +1,51 @@ +--- +id: coverage-floor +title: Coverage as a ratchet that may not fall +answers: Did my change make any code or branch stop being exercised by tests? +rung: 3 +section: test-quality +languages: rust, python, javascript, typescript, go +kinds: general +cost: low +detect: cargo llvm-cov --version +ran_here: yes +verified: ran +--- + +## Use when +- A change might delete, narrow or replace tests, and the loss should not go unnoticed. +- You want a cheap tripwire in CI: a recorded floor that the number may not drop below. +- New code should come with tests that execute it. + +## Do not use when +- You want to know whether the code is correct. Coverage shows what ran, not what was checked. In my run the Python function had 100% line and branch coverage and 3 of 7 mutants survived. Use `cargo-mutants`, `mutmut` or `stryker`. +- You would set a high target and chase it. A floor that only ratchets up is the use; a target invites empty tests. + +## Set up +- Rust: `cargo llvm-cov` (ran 0.9.1). Branch coverage needs nightly: `--branch`. +- Python: `pip install coverage`; `coverage run --branch -m pytest`. +- JavaScript: `npx c8 `, with `--check-coverage --lines 80` (from c8's docs; not run here). Vitest and Jest have built-in coverage with thresholds. +- Go: `go test -cover ./...` and `-coverprofile=c.out`, then `go tool cover -func=c.out` (from the Go docs; not run here). + +## Minimal example +Record the floor in a file (the value of the last good run), then compare: + + cargo llvm-cov --summary-only + # coverage.py + coverage run --branch -m pytest -q && coverage report --fail-under=100 + +The ratchet: store the total in a doc or a file, fail if the new total is more than a small tolerance below it, and raise the stored number when coverage rises. One Rust project does this with a script that reads the TOTAL row of the report, compares line cover to the recorded floor with a 0.5 point tolerance, and is wired in as a recipe. + +## Run + cargo llvm-cov --fail-under-lines 80 + +Passing looks like: the report prints and exit is 0. Failure: exit 1 when lines are below the limit (checked here: 85.71% failed at 100, passed at 80). Python: `coverage report --fail-under=N` exits 2 below N. + +## As a contract check + {"id": "coverage-floor", "claim": "Line coverage has not fallen below the recorded floor of 80", "kind": "general", "rung": 3, "cmd": "cargo llvm-cov --fail-under-lines 80", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1200} + +## What a pass does not prove +- Only that code was executed, not that results were checked. Tests with no assertions give full coverage. +- Excluded files and generated code lower the denominator; list what is excluded. +- Lowering the floor to get a pass defeats the check. A floor change in the diff needs a stated reason. +- Check the check: delete a test and confirm the number drops and the gate fails. diff --git a/verifiers/test-quality/flaky-test-detection.md b/verifiers/test-quality/flaky-test-detection.md new file mode 100644 index 0000000..57de39d --- /dev/null +++ b/verifiers/test-quality/flaky-test-detection.md @@ -0,0 +1,48 @@ +--- +id: flaky-test-detection +title: Detect flaky tests with repeat runs, random order and fixed seeds +answers: Does this test give the same result every time, in any order? +rung: 3 +section: test-quality +languages: any +kinds: general, concurrency +cost: low +detect: cargo nextest --version +ran_here: yes +verified: ran +--- + +## Use when +- You added or changed a test and want to know it is stable before calling it done. +- A test failed once and passed on rerun. +- You suspect order dependence: a test passes alone and fails in the suite. + +## Do not use when +- You are looking for a concurrency bug in the code itself. Repetition samples; use `loom`, `shuttle` or `stress-repeat` with the right framing. +- The failure is deterministic. Fix it; do not repeat it. + +## Set up +- Rust: `cargo install cargo-nextest`. Repeat with `--stress-count N` (also `--stress-duration`), retry with `--retries N`, which marks a test that failed then passed as flaky (nextest 0.9.143; `--flaky-result` controls whether that counts as pass or fail, see `--help`). Shuffled order needs nightly: `cargo +nightly test -- -Zunstable-options --shuffle` (from memory; confirm). +- Python: `pytest-randomly` shuffles by default and prints the seed; rerun with `-p randomly -p no:randomly` to disable, or `--randomly-seed=` to reproduce an order (from its docs). `pytest-repeat` adds `--count=N`. +- Go: `go test -count=20 -shuffle=on -race ./pkg`; it prints `-test.shuffle `, reuse it as `-shuffle=`. +- JavaScript: Vitest `--sequence.shuffle`; Jest `--randomize`. + +## Minimal example +`cargo nextest run --stress-count 50 my_test` reruns one test 50 times. + +## Run + cargo nextest run --stress-count 50 -E 'test(my_test)' + cargo nextest run --retries 2 # report which tests needed a retry + +Passing looks like: every iteration passes and no `FLAKY` label is shown. Failure shows the failing iteration and its output. When a test is flaky, capture the seed, or the shuffle seed, from the first failure before rerunning. + +Quarantining honestly: if a test is flaky and cannot be fixed now, do not delete it or add a blanket retry. Mark it ignored with a comment naming the issue and the date, keep it running in a separate non-gating job so its failure rate stays visible, and list it in the final report as an open problem. A quarantined test is not a passing test. + +## As a contract check + {"id": "no-flaky", "claim": "The new test passes 50 consecutive runs", "kind": "general", "rung": 3, "cmd": "cargo nextest run --stress-count 50 -E 'test(my_test)'", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900} + +## What a pass does not prove +- Fifty passes bound the failure rate only roughly: a 1-in-100 flake passes fifty runs more than half the time. Run more, or use controls from `test-determinism`. +- Order dependence appears only in the orders tried. Record seeds. +- Retries hide flakiness. A contract that relies on `--retries` to pass is hiding the problem; require zero retries. +- Check that the filter matched a test (`no tests to run` exits 4 in nextest unless `--no-tests=pass` is set). diff --git a/verifiers/test-quality/go-mutation.md b/verifiers/test-quality/go-mutation.md new file mode 100644 index 0000000..a654df2 --- /dev/null +++ b/verifiers/test-quality/go-mutation.md @@ -0,0 +1,62 @@ +--- +id: go-mutation +title: Mutation testing for Go with gremlins +answers: Would my Go tests notice if this code were wrong? +rung: 2 +section: test-quality +languages: go +kinds: general, money, parsing +cost: medium +detect: gremlins --version +ran_here: no +verified: docs +--- + +## Use when +- A Go package has tests and you want evidence they can fail. +- Line coverage is high but you doubt the assertions. +- It is a check on other checks; it gives rung 2 confidence in the tests. + +## Do not use when +- Gremlins is maintained slowly, not abandoned: its latest release is v0.6.0 (December 2025) and its last commit was March 2026. A more recently active alternative is the `avito-tech/go-mutesting` fork (commits in October 2026); the original `zimmski/go-mutesting` has been idle since July 2024. Pick one of the first two. +- The package has no tests, or its tests are slow; each mutant reruns them. The README says gremlins works well on smallish modules and takes hours on very big ones. +- You need a stable CLI: the README warns that flags and config can change between 0.x minor releases, and only the current minor is maintained. + +## Set up +Needs Go (the repository's `go.mod` says 1.25). Install a release package (`.deb`, `.rpm`, or a binary from the GitHub releases page; Homebrew via `brew tap go-gremlins/tap && brew install gremlins` on macOS) or: + + go install github.com/go-gremlins/gremlins/cmd/gremlins@v0.6.0 + +Pin the version, as the install page does. Not installed on this machine, so the example below was not run. + +## Minimal example +`price.go`: + + package shop + + func Price(qty, unit int) int { + total := qty * unit + if qty >= 10 { return total - total/10 } + return total + } + +`price_test.go` with `Price(2,100)==200` and `Price(20,100)==1800` only. The boundary mutation (`>=` to `>`) lives, because no test uses `qty == 10`. + +## Run +Run from the module root, with no package argument; gremlins takes its target from the current module: + + gremlins unleash --threshold-efficacy 80 + +Gremlins reports each mutant as KILLED, LIVED, NOT COVERED, TIMED OUT or NOT VIABLE (`RUNNABLE` with `--dry-run`) and prints a test efficacy and mutant coverage figure. Failure shows LIVED mutants with file and line, for example `LIVED CONDITIONALS_BOUNDARY at price.go:5:12`. + +Passing looks like: exit 0. Exit codes from the docs: `--threshold-efficacy N` makes gremlins exit 10 when efficacy is below N; `--threshold-mcover N` exits 11 when mutant coverage is below N. Without either flag gremlins never fails on survivors, so a bare `gremlins unleash` exits 0 with LIVED mutants. `--silent` prints only errors; `--diff origin/main` limits the run to changed code; `--exclude-files REGEX` skips generated files. + +## As a contract check + {"id": "go-mutation", "claim": "Gremlins efficacy for the module meets the threshold", "kind": "general", "rung": 2, "cmd": "gremlins unleash --threshold-efficacy 80 --threshold-mcover 90", "expect": {"exit": 0}, "timeout_s": 3600, "tier": "deep"} + +## What a pass does not prove +- Efficacy is `KILLED / (KILLED + LIVED)`; NOT COVERED mutants (no test reaches the line) are left out of it. Mutant coverage is `(KILLED + LIVED) / (KILLED + LIVED + NOT COVERED)`. That is why the contract sets `--threshold-mcover` too. Read both figures. +- LIVED mutants can be equivalent; justify each. +- The tool covers a fixed set of mutation operators (arithmetic, conditional boundary and negation, and similar), so passing does not mean the tests are thorough. +- Without a threshold flag the exit code says nothing. Check the check: delete an assertion and confirm the run exits 10. +- Commands and flags were read from the project's documentation sources in the repository (docs/docs), not run here. diff --git a/verifiers/test-quality/mutation-on-diff.md b/verifiers/test-quality/mutation-on-diff.md new file mode 100644 index 0000000..b9761bf --- /dev/null +++ b/verifiers/test-quality/mutation-on-diff.md @@ -0,0 +1,49 @@ +--- +id: mutation-on-diff +title: Mutation testing only on the lines a change touched +answers: Do my tests catch wrong versions of the exact code I just changed? +rung: 2 +section: test-quality +languages: rust, javascript, typescript, python, any +kinds: general, money, parsing +cost: low +detect: cargo mutants --version +ran_here: yes +verified: ran +--- + +## Use when +- You changed a handful of functions and a full mutation run (hours) does not fit in one task. +- You want a gate in a pull request: new or changed logic must have tests that can fail. +- It is a check on other checks, so it is rung 2 like the full run, but over a smaller area. + +## Do not use when +- The change deletes code or only edits tests; there is nothing to mutate in a diff of removed lines. +- You need the whole-codebase mutation score. A diff run says nothing about untouched code, and an edit in one place can weaken the tests of another; run the full tool on a schedule. + +## Set up +Rust, with cargo-mutants (ran 27.1.0): `--in-diff ` restricts mutants to lines in a unified diff. The diff must name files with `a/` and `b/` prefixes (or none). If your git config sets `diff.mnemonicPrefix`, the prefixes become `i/` and `w/` and cargo-mutants matches nothing: it prints `No mutants to filter` and exits 0. Force the prefixes: + + git diff --src-prefix=a/ --dst-prefix=b/ main...HEAD > /tmp/change.diff + +Other tools: StrykerJS takes `--mutate "src/file.js:10-40"` line ranges, so generate them from the diff yourself; Stryker.NET has a `--since` option (not confirmed here); mutmut can target names, `mutmut run "module.function*"`; PIT has an SCM goal (see `pitest`; not confirmed). + +## Minimal example +`price` has full tests; a new `shipping` function was added with none. + + pub fn shipping(weight: u32) -> u32 { if weight > 5 { 500 } else { 100 } } + +## Run + git diff --src-prefix=a/ --dst-prefix=b/ > change.diff + cargo mutants --in-diff change.diff + +Passing looks like: `N mutants tested: N caught`, exit 0. Failure: `MISSED src/lib.rs:15:49: replace > with == in shipping`, exit 2. In my run 5 of 5 mutants on the new function were missed; the old function's mutants were not run. Check the count: `cargo mutants --list --in-diff change.diff` must be non-empty, or the check is vacuous. + +## As a contract check + {"id": "mutants-on-diff", "claim": "Tests catch mutants of every line changed against main", "kind": "general", "rung": 2, "cmd": "git diff --src-prefix=a/ --dst-prefix=b/ main...HEAD > /tmp/c.diff && test -s /tmp/c.diff && cargo mutants --in-diff /tmp/c.diff", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800} + +## What a pass does not prove +- Only changed lines were mutated. The rest of the code is untested by this check. +- Non-Rust files, and changes with no mutable code (config, comments, test-only edits), produce zero mutants and so pass. Assert a non-zero mutant count in the contract when the task is meant to change logic. +- The same limits as the full run apply: equivalent mutants, and tests that pass for the wrong reason. +- Check the check: break a changed line in a harmless way and confirm the run fails. diff --git a/verifiers/test-quality/mutmut.md b/verifiers/test-quality/mutmut.md new file mode 100644 index 0000000..60eb393 --- /dev/null +++ b/verifiers/test-quality/mutmut.md @@ -0,0 +1,61 @@ +--- +id: mutmut +title: Mutation testing for Python with mutmut +answers: Would my Python tests notice if this function were wrong? +rung: 2 +section: test-quality +languages: python +kinds: general, money, parsing +cost: medium +detect: mutmut --version +ran_here: yes +verified: ran +--- + +## Use when +- You wrote pytest tests and want proof they fail when the code changes. +- Line coverage is 100% but you doubt the assertions (this is common; see `coverage-floor`). +- The code is pure logic in functions. Mutation testing is a check on other checks, giving rung 2 confidence in the tests. + +## Do not use when +- The target is module-level code outside functions; mutmut 3 mutates functions. mutmut 2 works differently. +- Windows without WSL: mutmut needs `fork`. +- Tests are slow or depend on network. Fix that first. + +## Set up + uv pip install mutmut pytest # or: pip install mutmut + # pyproject.toml + [tool.mutmut] + source_paths = ["src/"] + pytest_add_cli_args_test_selection = ["tests/"] + [tool.pytest.ini_options] + pythonpath = ["src"] + +Tests must import the code by its package name (`from shop.pricing import price`), not through a path like `src.pricing`; the latter fails with `Failed trampoline hit`. Tool version tried: mutmut 3.8.1. An alternative with a different design is `cosmic-ray` (session file, `cosmic-ray init`, `exec`); I did not run it. + +## Minimal example +`src/shop/__init__.py` (empty), `src/shop/pricing.py`: + + def price(qty: int, unit: int) -> int: + total = qty * unit + if qty >= 10: + return total - total // 10 + return total + +`tests/test_pricing.py` with only `price(2, 100) == 200` and `price(20, 100) == 1800`. + +## Run + mutmut run + mutmut results + mutmut show shop.pricing.x_price__mutmut_3 + +Passing looks like: `mutmut results` lists no `survived` lines. Failure shows survivors such as `shop.pricing.x_price__mutmut_3: survived`; `mutmut show` prints the diff (here `qty >= 10` became `qty > 10`). Note: `mutmut run` exits 0 even with survivors, so the contract must test the `results` output. Stop and rerun to resume; delete the `mutants/` directory for a fresh run. `# pragma: no mutate` skips a line. + +## As a contract check + {"id": "mutmut-pricing", "claim": "No surviving mutants in the pricing module", "kind": "general", "rung": 2, "cmd": "mutmut run && test -z \"$(mutmut results | grep survived)\"", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 1800} + +## What a pass does not prove +- It shows the tests kill small edits, not that behaviour matches the requirement. +- Equivalent mutants cannot be killed; mark them `# pragma: no mutate` with a reason, never silently. +- Only functions are mutated. Check `mutmut results` counts a plausible number of mutants, or the run is vacuous (0 mutants, source_paths wrong). +- In my run, 3 of 7 mutants survived while coverage.py reported 100% line and branch coverage. diff --git a/verifiers/test-quality/pitest.md b/verifiers/test-quality/pitest.md new file mode 100644 index 0000000..6cb34d8 --- /dev/null +++ b/verifiers/test-quality/pitest.md @@ -0,0 +1,65 @@ +--- +id: pitest +title: Mutation testing for the JVM with PIT (pitest) +answers: Would my Java or Kotlin tests notice if this code were wrong? +rung: 2 +section: test-quality +languages: java, kotlin +kinds: general, money, parsing +cost: medium +detect: mvn --version +ran_here: no +verified: docs +--- + +## Use when +- A Maven or Gradle JVM project has JUnit tests and you want evidence they can fail. +- You want a pass/fail gate on mutation score in CI. +- It is a check on other checks; it gives rung 2 confidence in the tests. + +## Do not use when +- The build is not on Maven, Gradle or an IDE that PIT supports. +- Tests are slow integration tests; scope `targetTests` tightly. + +## Set up +Not run here (no JDK configured on this machine); taken from pitest.org's Maven quickstart. Add to `pom.xml`: + + + org.pitest + pitest-maven + LATEST + + com.example.pricing* + com.example.pricing* + 80 + true + + + +For JUnit 5, also add the `pitest-junit5-plugin` as a plugin dependency (from memory of the PIT docs; confirm in your version). Gradle uses the separate `info.solidsoft.pitest` plugin (`gradle pitest`; not checked here). + +## Minimal example +`Pricing.java`: + + public class Pricing { + public static int price(int qty, int unit) { + int total = qty * unit; + return qty >= 10 ? total - total / 10 : total; + } + } + +With a JUnit test for `price(2,100)` and `price(20,100)` only, PIT reports a survivor for the boundary `>=` changed to `>`. + +## Run + mvn test-compile org.pitest:pitest-maven:mutationCoverage + +Passing looks like: the build succeeds and the console shows a mutation score at or above `mutationThreshold`; the HTML report is in `target/pit-reports/`. Failure: the build fails with a score below the threshold, and the report lists `SURVIVED` mutations with the line. `withHistory` stores results to speed up reruns. To check only changed code PIT has an SCM goal (`scmMutationCoverage`); I could not confirm its options from the docs I read, so read the PIT docs before relying on it. + +## As a contract check + {"id": "pitest-score", "claim": "Mutation score of the pricing package is at least 80", "kind": "general", "rung": 2, "cmd": "mvn -q test-compile org.pitest:pitest-maven:mutationCoverage", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 3600} + +## What a pass does not prove +- Only the classes matched by `targetClasses` are mutated; a too-narrow glob yields a vacuous pass. Check the report names your classes. +- Surviving mutants may be equivalent; exclude with `excludedMethods` or `avoidCallsTo` and say why. +- A score is a ratio of sampled changes, not correctness. +- With no `mutationThreshold`, the build passes whatever the score. Check it is set. diff --git a/verifiers/test-quality/red-before-green.md b/verifiers/test-quality/red-before-green.md new file mode 100644 index 0000000..10b29bb --- /dev/null +++ b/verifiers/test-quality/red-before-green.md @@ -0,0 +1,52 @@ +--- +id: red-before-green +title: Prove a new test can fail by seeing it fail before the fix +answers: Does this new test actually fail without my change, so its passing means something? +rung: 3 +section: test-quality +languages: any +kinds: general, money, parsing, state-machine +cost: low +detect: git --version +ran_here: yes +verified: ran +--- + +## Use when +- You fixed a bug and wrote a regression test. +- You added a feature and a test for it. +- Any time a test is the evidence for done: a test that cannot fail is not evidence. + +This is a check on another check. The test itself is rung 3 (an example test). Seeing it fail on the old code adds confidence that the test is sensitive to the bug, but it does not raise the claim above rung 3; a property test or mutation run is what reaches rung 2. + +## Do not use when +- The change is a pure refactor with no behaviour change; there is no red to see. Use existing tests and `mutation-on-diff`. +- The failure would only be a compile error because the new API does not exist yet. Stub the API first so the test compiles and fails on behaviour. + +## Set up +Two ways to get the red run. Either write the test first and run it before editing the code, or after the fix revert only the fix and rerun. With git: + + git stash push -- src/ # park the fix, keep the new tests + # or: git checkout HEAD~1 -- src/file # restore the old source + +## Minimal example +Bug: `price(10, 100)` returned 1000 instead of 900. Add the test in a separate file, `tests/threshold.rs`: `#[test] fn threshold_discount() { assert_eq!(mycrate::price(10, 100), 900); }`. If it lives in the same file as the fix, stashing the fix stashes the test too. + + git stash push -- src/ + cargo test threshold_discount # red + git stash pop + cargo test threshold_discount # green + +## Run +Run the exact new test by name on the old code, then on the new code. + +Passing looks like: the first run fails with an assertion about the behaviour you fixed (`left: 1000, right: 900`), the second passes with `1 passed`. Failure of the check: the test passes on the old code (it tests nothing about the bug), or fails for a different reason (a compile error, a missing file, a typo). Read the failure message, not just the exit status. Also confirm the test ran: `0 passed` or `no tests to run` is not red. + +## As a contract check + {"id": "red-green", "claim": "The regression test fails on the pre-fix source and passes on the fixed source", "kind": "general", "rung": 3, "cmd": "git stash push -q -- src/ && ! cargo test threshold_discount; r=$?; git stash pop -q; test $r -eq 0 && cargo test threshold_discount", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600} + +## What a pass does not prove +- That the test fails for the right reason. Inspect the red failure output yourself. +- That the test is strong: it may fail on one input and miss nearby ones. Pair with `cargo-mutants` or a property test. +- If the fix and the test touch the same files, stashing the wrong paths removes the test too; check that the red run still contains the test. +- Always restore the fix afterwards (`git stash pop`) and rerun the green run. diff --git a/verifiers/test-quality/stryker.md b/verifiers/test-quality/stryker.md new file mode 100644 index 0000000..c4ac07c --- /dev/null +++ b/verifiers/test-quality/stryker.md @@ -0,0 +1,61 @@ +--- +id: stryker +title: Mutation testing for JavaScript, TypeScript and C# with Stryker +answers: Would my JS, TS or C# tests notice if this code were wrong? +rung: 2 +section: test-quality +languages: javascript, typescript, csharp +kinds: general, money, parsing, ui +cost: medium +detect: npx --no-install stryker --version +ran_here: yes +verified: ran +--- + +## Use when +- You wrote Vitest, Jest, Mocha or .NET tests and want evidence they can fail. +- You need a numeric gate: Stryker computes a mutation score and exits non-zero below a threshold. +- It is a check on other checks; it gives rung 2 confidence in the tests. + +## Do not use when +- The change is a few lines and a full run is slow; mutate only those files or use `--incremental`; see `mutation-on-diff`. +- Tests are mostly snapshots of rendered output; they may kill many mutants without asserting anything meaningful. + +## Set up +StrykerJS (ran version 10.1.1): + + npm i -D @stryker-mutator/core @stryker-mutator/vitest-runner vitest + # stryker.config.mjs + export default { + testRunner: 'vitest', + mutate: ['src/**/*.js'], + reporters: ['clear-text', 'json'], + thresholds: { high: 90, low: 80, break: 80 }, + }; + +Other runners are separate plugins (`@stryker-mutator/jest-runner`, `mocha-runner`). Stryker.NET (docs only, not run here): `dotnet tool install -g dotnet-stryker`, then `dotnet stryker` from the test project directory; options in `stryker-config.json`. + +## Minimal example +`src/price.js`: + + export function price(qty, unit) { + const total = qty * unit; + if (qty >= 10) return total - Math.floor(total / 10); + return total; + } + +`test/price.test.js` with `price(2,100) === 200` and `price(20,100) === 1800`. + +## Run + npx stryker run + +Passing looks like: the table shows a mutation score at or above `break`, and the log line `Final mutation score of 87.50 is greater than or equal to break threshold 80`, exit 0. Failure: a score below `break` exits 1; survivors are listed with the mutated code (here `qty >= 10` mutated to `qty > 10`). Useful options: `--mutate "src/a.js:10-40"` for line ranges, `--incremental` (state in `reports/stryker-incremental.json`), `--concurrency`, `--timeoutMS`, `coverageAnalysis: 'perTest'` to run only tests that cover a mutant. + +## As a contract check + {"id": "stryker-score", "claim": "Mutation score of src/ is at least 80", "kind": "general", "rung": 2, "cmd": "npx stryker run", "expect": {"exit": 0, "stdout_contains": "Final mutation score"}, "tier": "deep", "timeout_s": 1800} + +## What a pass does not prove +- The score is a percentage over sampled mutations; 80 means 20% of changes went unnoticed. +- Survivors may be equivalent; disable with `// Stryker disable next-line : reason` and list them. +- `break` must be set or the command always exits 0. Check `thresholds` has all three keys (high, low, break) or none. +- A very high score with a tiny mutant count means little. Confirm the intended files were mutated. diff --git a/verifiers/test-quality/test-determinism.md b/verifiers/test-quality/test-determinism.md new file mode 100644 index 0000000..450df97 --- /dev/null +++ b/verifiers/test-quality/test-determinism.md @@ -0,0 +1,52 @@ +--- +id: test-determinism +title: Make tests deterministic with fixed seeds, fake clocks and no network +answers: Will this test give the same result on any machine, at any time, with no network? +rung: 3 +section: test-quality +languages: any +kinds: general, concurrency, money +cost: low +detect: +ran_here: no +verified: docs +--- + +## Use when +- A test uses randomness, the current time, timeouts, sleeps, the file system, the network or environment variables. +- You are writing tests an agent will rerun many times and compare across runs. +- A test result changes with the date, the time zone, the locale or the order of map iteration. + +## Do not use when +- You are testing the integration itself against a real service. Keep that in a separate, labelled suite. + +## Set up +Control each source of nondeterminism: +- Randomness: pass an explicit seed; print it on failure so the run can be replayed. Property tests: proptest stores failures in `proptest-regressions/`; Hypothesis in `.hypothesis/` (use `@seed` or `--hypothesis-seed`). Go: `rand.New(rand.NewSource(seed))`. +- Time: inject a clock. Rust Tokio: `tokio::time::pause()` with `#[tokio::test(start_paused = true)]`. Python: `freezegun` or `time-machine`. JavaScript: `vi.useFakeTimers()` or Jest fake timers. Never call `sleep` to wait for a result; wait on the event. +- Network: no real sockets. Use in-process fakes, a local listener bound to port 0, recorded fixtures or a simulator (see `deterministic-simulation`). Run the suite once with the network off (`unshare -rn cargo test` on Linux, or a sandbox) to prove it. +- Files: use a fresh temp directory per test; set `TMPDIR` explicitly. +- Order: do not depend on map or set iteration order; sort before comparing. Do not share mutable global state between tests. +- Environment: set `TZ=UTC`, `LC_ALL=C`, fixed locale. + +## Minimal example +A test with an explicit seed, and a way to replay it: + + let seed = std::env::var("SEED").ok().and_then(|s| s.parse().ok()).unwrap_or(12345u64); + eprintln!("seed = {seed}"); + let mut rng = StdRng::seed_from_u64(seed); + +## Run + SEED=12345 cargo test my_test + unshare -rn cargo test --offline my_test # no network, Linux user namespace + +Passing looks like: the same result on repeated runs and with the network off. Failure: a test needing the network fails with a connection error, or results differ between two runs with the same seed. Not run here; `unshare` is Linux-specific and needs unprivileged user namespaces. + +## As a contract check + {"id": "hermetic", "claim": "Tests pass with no network access", "kind": "general", "rung": 3, "cmd": "unshare -rn cargo test --offline", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 900} + +## What a pass does not prove +- That the code is correct; it proves the test is repeatable. +- Fixed seeds explore one input. Vary them in a separate property-test job. +- A fake clock hides real timing bugs. Keep a few real-time tests, labelled. +- Check the check: run twice with the same seed and diff the outputs; add `--test-threads=1` and the default to expose shared state. diff --git a/verifiers/test-quality/vacuity-check.md b/verifiers/test-quality/vacuity-check.md new file mode 100644 index 0000000..a505389 --- /dev/null +++ b/verifiers/test-quality/vacuity-check.md @@ -0,0 +1,52 @@ +--- +id: vacuity-check +title: Check that tests and assertions actually ran +answers: Did my tests really execute and assert something, or did the run pass because nothing ran? +rung: 3 +section: test-quality +languages: any +kinds: general, parsing, state-machine +cost: low +detect: +ran_here: yes +verified: ran +--- + +## Use when +- You ran a test with a name filter, a path, or a marker and it said "ok". +- A property or generated test might discard every input, so its body never runs. +- A pass is the only evidence for done. A pass with zero tests is a false finish. + +## Do not use when +- It is not a separate check of the code. It guards the other checks; use it beside them. + +## Set up +Know what "nothing ran" looks like in your runner. Measured here: + +- `cargo test nomatch`: prints `0 passed; ... 2 filtered out`, exit 0. +- `cargo nextest run nomatch`: `error: no tests to run`, exit 4 (nextest 0.9.143). `--no-tests=pass` makes it exit 0, so do not add that flag. +- `pytest -k nomatch`: `2 deselected`, exit 5. An empty collection is exit 5, not 0. +- `go test -run Nomatch`: prints `testing: warning: no tests to run` and exits 0 (from the Go docs, not run here). +- Jest and Vitest fail on no tests by default, unless `--passWithNoTests` is set. + +## Minimal example +Assert that the count of executed tests is at least one. For cargo: + + out=$(cargo test my_test 2>&1); echo "$out" + echo "$out" | grep -E 'test result: ok\. [1-9][0-9]* passed' >/dev/null + +For preconditions: assert the interesting case happened, for example in a property test count how many inputs were accepted and fail if none. In proptest use `prop_assume!` sparingly and check the rejection rate; in Hypothesis use `event()` and `target()`, and read `--hypothesis-show-statistics`; in a loop test keep a counter and `assert!(count > 0)` after the loop. For distributed tests, assert that a fault was actually injected. + +## Run +Run the tests with a name filter, then check the count line as above. Also check skipped and ignored tests: `cargo test -- --include-ignored` runs them; pytest `-rs` lists skips; Go prints `SKIP`. + +Passing looks like: at least one test is reported passed, none skipped that matter, and the assertion-count or event check is above zero. Failure is a zero count, or all tests skipped or filtered out. + +## As a contract check + {"id": "tests-ran", "claim": "At least one test matching the filter ran and passed", "kind": "general", "rung": 3, "cmd": "cargo test my_test 2>&1 | grep -E 'test result: ok\\. [1-9][0-9]* passed'", "expect": {"exit": 0}, "tier": "deep", "timeout_s": 600} + +## What a pass does not prove +- That the assertions inside the tests are meaningful; see `assertion-strength-review`. +- That the test is sensitive to the bug; see `red-before-green`. +- Counting tests does not count assertions. A test with an `if` that skips its assertion, or an assert in a callback that never fires, still passes. Add a counter or use mutation testing. +- Cargo's output format can change; keep the pattern tested against your version.