Skip to main content

canon

The rulebook, compiled. Your repository's rules are a database, not a document.

canon brief --task "add a refund endpoint"   # what governs this work
canon check                                   # prove the change satisfies it

The problem is not that agents don't read AGENTS.md

They read it. Then they stop applying it. The evidence is unusually clear:

  • Instruction compliance decays with conversation length even when the instruction is still in context — omission constraints fall from 73% at turn 5 to 33% at turn 16 (ICML 2026), and failures are behavioural drift, not forgetting (EMNLP 2026).
  • When two rules conflict, "no order holds throughout… where the hierarchy fails, position decides" — across 10,835 trials (NeurIPS 2026 workshop).
  • Models notice contradictions and stay silent: 73% of runs noticed a disagreement, 0% of 110 unprompted runs mentioned it (Google AI).
  • Context files do not generally improve task success while raising inference cost over 20% (arXiv:2602.11988), and no agent in a 4-week study repaired a stale one (arXiv:2611.09802).
  • The harness vendors say it outright: CLAUDE.md "files are naively dropped into context up front", "they aren't enforced configuration", and "no matter how strongly you word it… it is still Claude's call" (memory docs, best practices).

So the file is not the problem. Prose is the problem. It has no scope, no precedence, no predicate, and no failure mode. A MUST in markdown is a wish with formatting.

The one idea

A rule is not a paragraph. It is a predicate over a set of changes.

Give each rule three things and everything else follows:

a scope — which paths and operations it governs a set, so set algebra applies
a predicate — how to tell whether it holds pass / fail / unknown
a location — which version of the rule content-addressed, so merges converge

Once a rule has a scope, "which rules apply to this change?" is not a retrieval problem, it is a membership test. The diff already tells you the change. No embeddings, no top-k, no similarity threshold, no luck.

Once a rule has a predicate, "did the agent comply?" is not a judgement, it is a verdict — and unknown is a verdict, not a pass.

Once scopes are sets, you can analyse the rulebook itself: two rules that contradict are two sets that intersect, and the intersection yields a witness path. Dead rules are rules whose scope matches no file. Coverage is a percentage. None of that is possible over prose.

See it

$ canon lint
ERROR   CONTRADICTION  R4k9x2/R9c1de  money.repr='integer-minor-units' vs 'decimal'
      both govern `backend/ledger/x` — R4k9x2: 'Money is integer minor units…' / R9c1de: 'Money is a Decimal…'
WARNING DEAD           R7m2fp  scope frontend/** [write] matches none of 3 tracked files

$ canon brief --task "add a refund endpoint"
# canon brief
snapshot 1453129c7e20f64f · 2 rule(s) · 1 changed
task   add a refund endpoint
change backend/api/views.py

## HARD — the change is rejected if these fail
Rap1x4 An API view never reads a tenant id from the request.
          why    The workspace comes from the session; a client id is an escalation.
          when   backend/api/** [write]
          check  grep 'tenant_id' in changed files  (expect no-match)

$ canon check
FAIL  Rap1x4  An API view never reads a tenant id from the request.
      why    The workspace comes from the session; a client id is an escalation.
      when   backend/api/** [write]
      check  grep 'tenant_id' -> found in 1 file(s)
      | backend/api/views.py:2: tid = request.GET["tenant_id"]
      fix the change; `canon explain Rap1x4` for the history.

canon check · snapshot ea8ea32935f95c94 · 1 fail
refusing: the change does not satisfy the rulebook.

The brief is hundreds of tokens, not hundreds of thousands — the reported monorepo case is 600k of always-on rules (Cursor forum). Only rules whose scope meets this diff are in it, ordered by a declared total order, under a budget that can never silently drop a hard rule.

How it works

Five mechanisms, each doing one job.

1. A log, not a file. .canon/ledger.jsonl — one content-addressed record per line, append-only. Add

.canon/.gitattributes:  *.jsonl merge=union

and two agents editing the rulebook cannot produce a merge conflict: git concatenates, canon normalises. Within an id the winner is max(lamport, rev, hash) — a total order that depends only on the records, never on arrival order. Merge is pointwise max: commutative, associative, idempotent. Any permutation of any partition converges to the same state (tested). Losing revisions are retained, so a concurrent edit surfaces as DIVERGED instead of vanishing.

2. Scopes are automata. A scope is a segment glob compiled to an epsilon-NFA. "Do these two rules overlap?" is a product construction; when it finds an accepting pair it returns the path it walked. That is why canon says "both govern backend/ledger/x" and not "possible conflict". ** matches zero or more segments; * never crosses /.

3. Verdicts are three-valued. PASS, FAIL, UNKNOWN, WAIVED. A rule with no predicate is UNKNOWN — reported as a number, never rounded up to success. --strict makes unknown block. A waiver is a ledger record, so every dispensation is auditable and can expire.

4. Freshness is checked, not hoped for. A rule may carry a probe (is this still true?) and anchors (the files its rationale rests on, by hash). A rule whose probe fails is STALE; one whose anchor changed is ANCHOR-DRIFT; one whose scope matches nothing is DEAD. Probes run at most three at a time, during normal use — no daemon, no cron, O(1) amortised maintenance.

5. Proof lives outside the tree. canon check --note writes the certificate to refs/notes/canon. git status stays clean. A commit can carry what was checked, against which snapshot, with which verdicts — and anyone can re-run it.

6. The always-loaded file is an index. AGENTS.md is paid for on every turn of every session, and past a few kilobytes the harness truncates it — so an unbounded dump is not "all the rules", it is an arbitrary prefix of them with nothing saying where the cut fell. canon render therefore prints only the rules whose scope covers the whole repository in full, names every scoped rule by id under its scope, and states what it left out. Reachability is the point: a scoped rule that is absent from the file is still decidable from it, because canon brief loads the rule the moment a change touches its paths. --all restores the complete dump. A universal HARD rule is never cut — over budget is reported, never silently absorbed.

Working with people

The rulebook is a normal git artifact: reviewed in PRs, line-granular diffs, git log -p .canon/ledger.jsonl as its history, git blame as attribution.

Three things are enforced rather than hoped for:

  • Two people add rules offline. They get ids generated at creation, so neither can shadow the other. (The first implementation used R3, R4; two clones both computed R3 and one rule silently vanished on merge. That bug is why ids are random.)
  • Two people edit one rule offline. The ledger converges, both texts are retained, and canon lint exits 1 until a human reads them with canon history and acknowledges with canon resolve. A CRDT converges but can drop intent; failing the build is how intent gets a human.
  • An agent learns something. canon remember stores it unreviewed, marks it in every brief, and queues it for canon review. A rule that can fail a build is a commitment; a fact an agent inferred is a rumour. They must not look the same.

The long version, including what canon does not solve, is in docs/TEAM.md.

What prose cannot give you

AGENTS.md canon
Applies only where relevant ✗ whole file, always ✓ scope ∩ diff
Conflict between two rules silent, position decides error, with a witness path
Rule that governs nothing invisible forever DEAD, computable
Rule whose rationale rotted invisible ANCHOR-DRIFT
Predicate failed nothing happens exit 1, commit refused
Not mechanically checkable looks identical to one that is UNKNOWN, counted as debt
Concurrent edits merge conflict converges (union + LWW)
Token cost grows with the file bounded by budget, omissions named
Which rules applied to commit X unknowable certificate in refs/notes/canon
Per-rule value guessed hits vs. catches, per rule

That last row is the quiet one. Because every evaluation is recorded, canon can tell you which rules have never once prevented anything. The research says context files cost 20% more inference for no measurable gain; the only honest response is to make each rule justify itself and delete the rest.

Install

pip install canon-cli        # provides the `canon` command; stdlib only, no deps

Published on PyPI: pypi.org/project/canon-cli · source and releases: github.com/Infrasynth-org/canon.

# or run it straight from a checkout, no install:
python3 -m canon --help

Python 3.10+. No runtime dependencies. No server. No API key.

cd your-repo
canon init                   # creates .canon/, prints one block to paste
canon add "Money is integer minor units; never floats." \
  --scope 'backend/ledger/**' \
  --why "Float drift breaks reconciliation." \
  --check-kind grep --check '/ *100\.0' --expect no-match
canon activate               # write the block every harness already reads
canon hook install           # pre-commit gate (chains an existing hook)
canon remember "…"          # capture knowledge; unreviewed until `canon review`

The entire integration

Paste this once, into whatever your harness already reads. It is the only prose canon adds to your repository, and it is deliberately small enough that the cost of ignoring it is visible:

## Rules

This repository's rules are a database in `.canon/ledger.jsonl`, read with `canon`.

- Before your first edit: `canon brief --task "<the task you were given>"`
- Before you commit: `canon check`

Every line `canon brief` prints is binding. A HARD rule that fails makes the
change invalid: fix the change, never the rule. If `canon` is not installed,
use `python3 -m canon`. For a rule's reason: `canon explain <id>`.
To keep a durable rule: `canon add "<one sentence>" --scope '<glob>' --why "<why>"`.

Never edit `.canon/ledger.jsonl` by hand, and never bypass the check.

That is the whole harness-agnostic move: a CLI, and a block small enough to paste. Anything with a shell can use it — Claude Code, Codex, Cursor, Aider, Goose, OpenHands, a bash script, a Makefile, your own agent next year. No protocol, no plugin, no vendor cooperation. (This delivery model is borrowed with admiration from OptMem, which proved that a 426-token block plus a CLI is enough. canon adds the part OptMem deliberately omits: rules that are scoped, checkable, and merge-safe.)

Making future sessions use it

A fresh session starts with three channels and only three: context the harness injects, tools the harness offers, and commands it must run to finish. So activation is layered by what each layer guarantees:

tier mechanism guaranteed?
0 canon hook install — the commit gate yes, every agent commits
1 CI — check --strict, lint, activate --check yes
2 canon mcp — tools in the list + initialize.instructions no, but very likely
3 canon activate — the AGENTS.md block no, but universal

Two details make tier 2 better than another markdown file: tool descriptions are re-sent on every turn (so "call canon_brief before editing" stays salient instead of decaying), and MCP's handshake has an instructions field that canon fills with the hard rules at startup — protocol-level context injection, not a vendor feature. canon_check returns isError: true on a violation so the harness treats it as a failure rather than a paragraph.

The block itself is delimited and generated:

<!-- canon:begin — generated by `canon activate`; edit rules with `canon add` -->
## Rules
…
<!-- canon:end -->

Everything outside the markers is yours; everything inside is rebuilt by canon activate, and canon activate --check fails CI when it drifts. That is the answer to "it goes stale": it is not maintained, it is regenerated.

Full tier-by-tier guide, including the session-hook shape canon deliberately does not generate: docs/ACTIVATION.md.

The design in one line

A rulebook is a set of scoped predicates; a change is a footprint; compliance is membership plus evaluation; the store is a join-semilattice; the text is a projection.

Each of those is a well-understood object, which is why the guarantees are provable rather than aspirational. See SPEC.md for the model, the seven guarantees, and their proofs; docs/WHY.md for the research this is built on; docs/MIGRATION.md for the zero-risk path off AGENTS.md, and docs/DESIGN-RULES.md for the judgement-heavy case (design rules: structural, judged, and taste).

Honest limits

  • canon does not make a model smarter. The evidence says context files barely move success rates. canon's claim is narrower and stronger: it makes rules enforceable, complete, auditable and cheap, and it gives you a number for how much of your rulebook is still unproven prose.
  • Commit-time enforcement is bypassable (--no-verify). That is what CI is for: canon check --range origin/main..HEAD --strict in a pipeline is not bypassable.
  • UNKNOWN is common at first. That is the point — canon audit reports normative debt, and the number is supposed to fall.
  • Conflict detection needs a declared key. Two rules conflict when they claim the same key with different value and their scopes intersect. That one extra field buys decidability; without it, "these rules disagree" is a natural-language judgement.
  • Subset checks are repo-relative, over tracked files, not over all possible strings. Checking language inclusion in general is PSPACE-complete; checking it over the files that exist is a loop.

Prior art, and why this is different

AGENTS.md and friends are the interface; canon is the substrate. It does not compete with them — it compiles to them.

what it is why it isn't this
AGENTS.md / CLAUDE.md prose dropped into context advisory by construction; no scope, predicate, or failure mode
Cursor / Continue / Cody rules per-vendor glob-activated rules re-implements precedence per vendor; no cross-harness semantics, no proof
OPA / Rego, Cedar policy engines over structured input needs an integration point and a policy language; "the agent edited a file" is not an input
pre-commit, linters deterministic checks no notion of which rule, no scope algebra, no audit trail, no brief
ADRs decisions with rationale rationale, not obligation; rots identically
OptMem, mem0, Zep, Letta agent memory descriptive (what happened), not normative (what must hold); no verdicts
Cline memory bank agent-maintained markdown agent-authored prose self-reinforces drift; nothing verifies it

The gap none of them fill: in-repo, agent-agnostic, scoped, verifiable, merge-safe rules with a certificate.

Status

0.1.0 — the core is complete and tested. The 66-test suite covers convergence under permutation, witness soundness and completeness against a finite universe, budget invariants, clean-tree behaviour, determinism, the hook gate refusing then certifying, and the multi-person cases: concurrent adds keeping both rules, concurrent edits surfacing both texts and failing the build, and agent-learned facts staying unreviewed until a human confirms them, plus activation idempotency, drift detection, the MCP handshake, and the severity dial that keeps a soft rule advisory instead of a gate. Next: canon prompt for per-harness renderings, an ablate command that measures a rule's causal value, and a --judge adapter presets file.

MIT.

Metadata

Release files for canon-cli 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for canon-cli 0.2.0
File Size Uploaded Provenance Actions
canon_cli-0.2.0.tar.gz 70.5 kB Without provenance Details for canon_cli-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for canon-cli 0.2.0
File Interpreter ABI Platform Actions
canon_cli-0.2.0-py3-none-any.whl Python 3 none any Details for canon_cli-0.2.0-py3-none-any.whl

Total release size: 129.2 kB

Release files / canon_cli-0.2.0.tar.gz

Download URL canon_cli-0.2.0.tar.gz
Size 70.5 kB
Tags Source
SHA-256 checksum
How to use checksums
a5543a9a91c99ca8ee220b1756686ee594005dc763dca93f87e7bbc126aacd78
BLAKE2b-256 checksum
How to use checksums
387384f820eba2bf9bab452b906756d917d5543185d33e8004eedf011334b77c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Release files / canon_cli-0.2.0-py3-none-any.whl

Download URL canon_cli-0.2.0-py3-none-any.whl
Size 58.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
523949d371b35bb48c2339a96f61f7ca7339f26cdef9419e2fd6a480a78c3bb7
BLAKE2b-256 checksum
How to use checksums
7741827b467bab97d8a48d168f57d5b9dfc066214df25bedecb0f05e0f1e174f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Security for canon-cli 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page