canon-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
canon/cli.py ADDED
@@ -0,0 +1,1143 @@
1
+ """canon — the rulebook, compiled.
2
+
3
+ One CLI. One pasted block. No daemon, no server, no vendor cooperation.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import re
13
+ import shlex
14
+ import shutil
15
+ import stat
16
+ import sys
17
+ import time
18
+ from pathlib import Path
19
+
20
+ from . import __version__
21
+ from . import activate
22
+ from . import audit as A
23
+ from . import brief as B
24
+ from . import gitx
25
+ from . import prompt as P
26
+ from .ledger import KINDS, SEVERITIES, Ledger, LedgerError, meta_record
27
+ from .select import all_rules as select_all
28
+ from .select import applicable, jurisdiction, select, token_budget
29
+ from .verify import Verdict, aggregate, has_predicate, run as run_check
30
+
31
+ __all__ = ["main"]
32
+
33
+ EXIT_OK = 0
34
+ EXIT_VIOLATION = 1
35
+ EXIT_USAGE = 2
36
+
37
+
38
+ # -- plumbing ---------------------------------------------------------------
39
+
40
+
41
+ class Ctx:
42
+ def __init__(self, repo: Path, led: Ledger) -> None:
43
+ self.repo = repo
44
+ self.ledger = led
45
+
46
+ @property
47
+ def cache(self) -> Path:
48
+ d = self.repo / ".canon" / "cache"
49
+ d.mkdir(parents=True, exist_ok=True)
50
+ return d
51
+
52
+
53
+ def _repo(args: argparse.Namespace) -> Path:
54
+ explicit = getattr(args, "repo", None)
55
+ start = Path(explicit or os.getcwd())
56
+ if gitx.is_repo(start):
57
+ return gitx.repo_root(start)
58
+ return start.resolve()
59
+
60
+
61
+ def _ctx(args: argparse.Namespace) -> Ctx:
62
+ root = _repo(args)
63
+ path = Path(getattr(args, "ledger", "") or root / ".canon" / "ledger.jsonl")
64
+ led = Ledger.open(path)
65
+ return Ctx(root, led)
66
+
67
+
68
+ def _ledger_path(root: Path) -> Path:
69
+ return root / ".canon" / "ledger.jsonl"
70
+
71
+
72
+ def _footprint(args: argparse.Namespace, root: Path) -> gitx.Footprint:
73
+ paths = getattr(args, "paths", None)
74
+ if getattr(args, "all_files", False):
75
+ paths = gitx.tracked_files(root)
76
+ return gitx.footprint(
77
+ root,
78
+ base=getattr(args, "base", "HEAD") or "HEAD",
79
+ staged=getattr(args, "staged", False),
80
+ revrange=getattr(args, "range", "") or "",
81
+ paths=paths,
82
+ message=getattr(args, "message", "") or "",
83
+ )
84
+
85
+
86
+ def _emit(text: str) -> None:
87
+ sys.stdout.write(text if text.endswith("\n") else text + "\n")
88
+
89
+
90
+ def _err(text: str) -> None:
91
+ sys.stderr.write(text if text.endswith("\n") else text + "\n")
92
+
93
+
94
+ def _author(root: Path) -> str:
95
+ """Who wrote this record. Knowledge without an owner is folklore."""
96
+ for key in ("user.email", "user.name"):
97
+ try:
98
+ who = gitx.git(root, "config", key).strip()
99
+ except (gitx.NoteError, OSError):
100
+ who = ""
101
+ if who:
102
+ return who[:120]
103
+ return "unknown"
104
+
105
+
106
+ _PREFIX = {"rule": "R", "fact": "F", "note": "N", "waiver": "W"}
107
+
108
+
109
+ def _sha(path: Path) -> str:
110
+ try:
111
+ return hashlib.sha256(path.read_bytes()).hexdigest()
112
+ except OSError:
113
+ return ""
114
+
115
+
116
+ # -- commands ---------------------------------------------------------------
117
+
118
+
119
+ def _bootstrap(root: Path) -> bool:
120
+ """Create the ledger and its git wiring. Returns True if it was new."""
121
+ ledger_path = _ledger_path(root)
122
+ created = False
123
+ if not ledger_path.exists():
124
+ led = Ledger(ledger_path)
125
+ led.append(meta_record())
126
+ led.append(
127
+ {
128
+ "v": 1,
129
+ "id": "R1",
130
+ "author": "canon",
131
+ "ts": "1970-01-01T00:00:00Z",
132
+ "kind": "rule",
133
+ "sev": "hard",
134
+ "text": "Conventional Commits only; the version and changelog are derived.",
135
+ "why": "Changelogs and versions are generated from commit types, so a "
136
+ "non-conforming subject silently drops a release note.",
137
+ "scope": {"ops": ["commit"]},
138
+ "check": {
139
+ "kind": "shell",
140
+ "run": "printf '%s' \"$CANON_MESSAGE\" | grep -Eq "
141
+ "'^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert|"
142
+ "security)(\\([a-z0-9._-]+\\))?!?: '",
143
+ },
144
+ "lamport": 1,
145
+ }
146
+ )
147
+ created = True
148
+
149
+ canon_dir = root / ".canon"
150
+ attrs = canon_dir / ".gitattributes"
151
+ if not attrs.exists():
152
+ attrs.write_text(
153
+ "# Concurrent writers converge: git concatenates, canon normalises.\n"
154
+ "*.jsonl merge=union\n",
155
+ encoding="utf-8",
156
+ )
157
+ ignore = canon_dir / ".gitignore"
158
+ if not ignore.exists():
159
+ ignore.write_text("cache/\n", encoding="utf-8")
160
+ return created
161
+
162
+
163
+ def cmd_init(args: argparse.Namespace) -> int:
164
+ root = _repo(args)
165
+ created = _bootstrap(root)
166
+ exported = _import_agents(root, _ledger_path(root))
167
+ if exported:
168
+ _err(f"imported {exported} section(s) from AGENTS.md as advisory facts")
169
+
170
+ _emit(
171
+ ("created " if created else "already initialised: ")
172
+ + str(_ledger_path(root).relative_to(root))
173
+ )
174
+ _emit("")
175
+ _emit("Paste this block into your AGENTS.md (or CLAUDE.md, or GEMINI.md):")
176
+ _emit("")
177
+ _emit(P.block())
178
+ _emit("")
179
+ _emit("Then: `canon activate` for every harness at once, `canon mcp` for MCP tools.")
180
+ return EXIT_OK
181
+
182
+
183
+ def cmd_activate(args: argparse.Namespace) -> int:
184
+ root = _repo(args)
185
+ _bootstrap(root)
186
+ names = activate.expected(root, all_harnesses=args.all, only=args.harness)
187
+
188
+ if args.check:
189
+ problems = activate.check(root, names)
190
+ if problems:
191
+ for problem in problems:
192
+ _err(problem)
193
+ return EXIT_VIOLATION
194
+ _emit(f"activation current: {', '.join(names)}")
195
+ return EXIT_OK
196
+
197
+ for rel, action in activate.install(root, names):
198
+ _emit(f" {action:<9} {rel}")
199
+ _emit("")
200
+ _emit("tier 2 — MCP: tools in the model's tool list, plus protocol-level instructions")
201
+ _emit(activate.mcp_snippet())
202
+ _emit("")
203
+ _emit("tier 0 — commit gate: the only layer a session cannot skip")
204
+ _emit(" canon hook install")
205
+ _emit("")
206
+ _emit("check drift in CI with: canon activate --check")
207
+ return EXIT_OK
208
+
209
+
210
+ def cmd_mcp(args: argparse.Namespace) -> int:
211
+ from .mcp import serve
212
+
213
+ return serve(Path(args.repo) if getattr(args, "repo", "") else None)
214
+
215
+
216
+ def _import_agents(root: Path, ledger_path: Path) -> int:
217
+ """Seed the ledger from an existing AGENTS.md, so day one is not a rewrite."""
218
+ src = None
219
+ for name in ("AGENTS.md", "CLAUDE.md", "GEMINI.md"):
220
+ candidate = root / name
221
+ if candidate.exists():
222
+ src = candidate
223
+ break
224
+ if src is None:
225
+ return 0
226
+ text = src.read_text(encoding="utf-8", errors="replace")
227
+ sections = re.split(r"(?m)^##\s+", text)
228
+ led = Ledger.open(ledger_path)
229
+ if len(led.active()) > 1 or led.get("R1") is None:
230
+ return 0
231
+ n = 0
232
+ for section in sections[1:]:
233
+ lines = section.splitlines()
234
+ if not lines:
235
+ continue
236
+ title = lines[0].strip()
237
+ body = " ".join(ln.strip() for ln in lines[1:] if ln.strip())
238
+ body = re.sub(r"\s+", " ", body)
239
+ if not body:
240
+ continue
241
+ n += 1
242
+ digest = hashlib.sha256(f"{src.name}#{title}".encode("utf-8")).hexdigest()[:6]
243
+ led.append(
244
+ {
245
+ "v": 1,
246
+ "id": "F" + digest,
247
+ "kind": "fact",
248
+ "sev": "advice",
249
+ "text": (title + " — " + body)[:390],
250
+ "why": f"imported from {src.name}",
251
+ "scope": {"paths": ["**"], "ops": ["write", "delete", "commit"]},
252
+ "status": "active",
253
+ "imported_from": f"{src.name}#{title}",
254
+ # deterministic, so two clones importing the same file dedup
255
+ "author": "canon-import",
256
+ "ts": "1970-01-01T00:00:00Z",
257
+ "lamport": 1,
258
+ }
259
+ )
260
+ return n
261
+
262
+
263
+ def cmd_add(args: argparse.Namespace) -> int:
264
+ ctx = _ctx(args)
265
+ rec: dict = {
266
+ "v": 1,
267
+ "id": args.id or ctx.ledger.next_id(_PREFIX.get(args.kind, "R")),
268
+ "kind": args.kind,
269
+ "text": args.text,
270
+ "sev": args.sev or ("hard" if args.kind == "rule" else "advice"),
271
+ "author": _author(ctx.repo),
272
+ "scope": _scope_from_args(args),
273
+ }
274
+ if args.why:
275
+ rec["why"] = args.why
276
+ if args.key:
277
+ rec["key"] = args.key
278
+ if args.value:
279
+ rec["value"] = args.value
280
+ if args.check:
281
+ rec["check"] = _check_from_args(args)
282
+ if args.probe:
283
+ rec["probe"] = {"run": args.probe, "kind": "shell"}
284
+ if args.anchor:
285
+ anchors = []
286
+ for rel in args.anchor:
287
+ full = ctx.repo / rel
288
+ anchors.append({"path": rel, "sha256": _sha(full)})
289
+ if not full.exists():
290
+ _err(f"warning: anchor {rel} does not exist yet")
291
+ rec["anchors"] = anchors
292
+ try:
293
+ got = ctx.ledger.append(rec)
294
+ except LedgerError as exc:
295
+ _err(f"canon: {exc}")
296
+ return EXIT_USAGE
297
+ _emit(f"{got.id} added (rev {got.rev}) — {got.text}")
298
+ debt = A.debt(ctx.ledger)
299
+ if (got.kind == "rule") and got.sev == "hard" and not has_predicate(got):
300
+ _emit(f" unproven: normative debt is now {debt['unproven']}/{debt['hard']}")
301
+ _emit(" it can only ever be UNKNOWN. Either add --check '<cmd>',")
302
+ _emit(" or route it to a judge: --sev soft --check-kind judge --check '<cmd>'.")
303
+ return EXIT_OK
304
+
305
+
306
+ def _scope_from_args(args: argparse.Namespace) -> dict:
307
+ paths = [p for p in (args.scope or []) if p]
308
+ ops = [o for o in (args.ops or []) if o]
309
+ scope: dict = {"paths": paths, "ops": ops or ["write"]}
310
+ if args.not_path:
311
+ scope["not"] = list(args.not_path)
312
+ return scope
313
+
314
+
315
+ def _check_from_args(args: argparse.Namespace) -> dict:
316
+ spec: dict = {"kind": args.check_kind, "run": args.check}
317
+ if args.expect:
318
+ spec["expect"] = args.expect
319
+ if args.timeout:
320
+ spec["timeout"] = args.timeout
321
+ return spec
322
+
323
+
324
+ def cmd_edit(args: argparse.Namespace) -> int:
325
+ ctx = _ctx(args)
326
+ rec = ctx.ledger.get(args.id)
327
+ if rec is None:
328
+ _err(f"canon: no rule {args.id}")
329
+ return EXIT_USAGE
330
+ data = {k: v for k, v in rec.data.items() if k not in ("hash", "rev", "lamport")}
331
+ if args.text:
332
+ data["text"] = args.text
333
+ if args.why:
334
+ data["why"] = args.why
335
+ if args.sev:
336
+ data["sev"] = args.sev
337
+ if args.scope:
338
+ data["scope"] = _scope_from_args(args)
339
+ if args.check is not None:
340
+ data["check"] = _check_from_args(args) if args.check else None
341
+ if not args.check:
342
+ data.pop("check", None)
343
+ if args.key:
344
+ data["key"] = args.key
345
+ if args.value:
346
+ data["value"] = args.value
347
+ data["supersedes"] = rec.hash
348
+ data["author"] = _author(ctx.repo)
349
+ got = ctx.ledger.append(data)
350
+ _emit(f"{got.id} amended (rev {got.rev})")
351
+ if got.prior:
352
+ _emit(f" {len(got.prior)} earlier revision(s) retained")
353
+ return EXIT_OK
354
+
355
+
356
+ def cmd_retire(args: argparse.Namespace) -> int:
357
+ ctx = _ctx(args)
358
+ rec = ctx.ledger.get(args.id)
359
+ if rec is None:
360
+ _err(f"canon: no rule {args.id}")
361
+ return EXIT_USAGE
362
+ data = {k: v for k, v in rec.data.items() if k not in ("hash", "rev", "lamport")}
363
+ data["status"] = "retired"
364
+ data["supersedes"] = rec.hash
365
+ if args.reason:
366
+ data["retired_reason"] = args.reason
367
+ got = ctx.ledger.append(data)
368
+ _emit(f"{got.id} retired")
369
+ return EXIT_OK
370
+
371
+
372
+ def cmd_waive(args: argparse.Namespace) -> int:
373
+ ctx = _ctx(args)
374
+ if ctx.ledger.get(args.id) is None:
375
+ _err(f"canon: no rule {args.id}")
376
+ return EXIT_USAGE
377
+ rec = {
378
+ "v": 1,
379
+ "id": args.waiver_id or ctx.ledger.next_id("W"),
380
+ "kind": "waiver",
381
+ "text": args.reason,
382
+ "waives": args.id,
383
+ "scope": {"paths": ["**"], "ops": ["write", "delete", "commit"]},
384
+ "status": "active",
385
+ "author": _author(ctx.repo),
386
+ }
387
+ if args.expires:
388
+ rec["expires"] = args.expires
389
+ got = ctx.ledger.append(rec)
390
+ _emit(f"{got.id} waives {got.get('waives')}" + (f" until {args.expires}" if args.expires else " forever"))
391
+ _emit(" waivers are auditable: `canon audit` lists them, `canon retire` removes one.")
392
+ return EXIT_OK
393
+
394
+
395
+ def cmd_remember(args: argparse.Namespace) -> int:
396
+ """Record knowledge an agent learned. Untrusted until a human confirms it."""
397
+ ctx = _ctx(args)
398
+ rec = {
399
+ "v": 1,
400
+ "id": args.id or ctx.ledger.next_id("F"),
401
+ "kind": "fact",
402
+ "sev": "advice",
403
+ "text": args.text,
404
+ "why": args.why or "learned while working in this repository",
405
+ "scope": _scope_from_args(args),
406
+ "author": _author(ctx.repo),
407
+ "reviewed": False,
408
+ }
409
+ got = ctx.ledger.append(rec)
410
+ _emit(f"{got.id} remembered (unreviewed)")
411
+ _emit(f" a teammate confirms it: `canon review {got.id}`; `canon review` lists the queue.")
412
+ return EXIT_OK
413
+
414
+
415
+ def cmd_review(args: argparse.Namespace) -> int:
416
+ ctx = _ctx(args)
417
+ if not args.id:
418
+ queue = [r for r in ctx.ledger.active("fact") if not r.get("reviewed", True)]
419
+ if not queue:
420
+ _emit("nothing awaiting review")
421
+ return EXIT_OK
422
+ _emit(f"{len(queue)} unreviewed fact(s):")
423
+ for r in queue:
424
+ _emit(f" {r.id} {str(r.get('author', '?'))[:24]:<24} {r.text}")
425
+ _emit("")
426
+ _emit("confirm: `canon review <id>` drop: `canon retire <id>`")
427
+ return EXIT_OK
428
+ rec = ctx.ledger.get(args.id)
429
+ if rec is None:
430
+ _err(f"canon: no record {args.id}")
431
+ return EXIT_USAGE
432
+ data = {k: v for k, v in rec.data.items() if k not in ("hash", "rev", "lamport")}
433
+ data["reviewed"] = True
434
+ data["reviewed_by"] = _author(ctx.repo)
435
+ data["supersedes"] = rec.hash
436
+ got = ctx.ledger.append(data)
437
+ _emit(f"{got.id} confirmed by {data['reviewed_by']}")
438
+ return EXIT_OK
439
+
440
+
441
+ def cmd_history(args: argparse.Namespace) -> int:
442
+ """Every version that ever claimed this id — including losing ones."""
443
+ ctx = _ctx(args)
444
+ items = ctx.ledger.revisions(args.id)
445
+ if not items:
446
+ _err(f"canon: no record {args.id}")
447
+ return EXIT_USAGE
448
+ current = ctx.ledger.get(args.id)
449
+ losers = set(ctx.ledger.diverged().get(args.id, []))
450
+ _emit(f"{args.id}: {len(items)} revision(s)")
451
+ for rec, h in items:
452
+ if current is not None and h == current.hash:
453
+ mark = "current"
454
+ elif h in losers:
455
+ mark = "concurrent"
456
+ else:
457
+ mark = "superseded"
458
+ _emit("")
459
+ _emit(
460
+ f" {mark:<11} rev {rec.get('rev', '?')} {h[:19]} "
461
+ f"{str(rec.get('author', '?'))[:24]} {rec.get('ts', '')}"
462
+ )
463
+ _emit(f" {rec.get('text', '')}")
464
+ if rec.get("resolved_revs"):
465
+ _emit(f" acknowledged rev(s) {rec['resolved_revs']}")
466
+ if losers:
467
+ _emit("")
468
+ _emit(f" {len(losers)} concurrent revision(s) are retained, not applied.")
469
+ _emit(f" acknowledge: `canon resolve {args.id}`")
470
+ return EXIT_OK
471
+
472
+
473
+ def cmd_resolve(args: argparse.Namespace) -> int:
474
+ ctx = _ctx(args)
475
+ rec = ctx.ledger.get(args.id)
476
+ if rec is None:
477
+ _err(f"canon: no record {args.id}")
478
+ return EXIT_USAGE
479
+ revs = ctx.ledger.concurrent_revs(args.id)
480
+ if not revs:
481
+ _emit(f"{args.id}: no concurrent revisions to resolve")
482
+ return EXIT_OK
483
+ losers = ctx.ledger.diverged().get(args.id, [])
484
+ data = {k: v for k, v in rec.data.items() if k not in ("hash", "rev", "lamport")}
485
+ data["resolved_revs"] = sorted(set(data.get("resolved_revs") or []) | set(revs))
486
+ data["author"] = _author(ctx.repo)
487
+ got = ctx.ledger.append(data)
488
+ _emit(f"{got.id}: revision(s) {', '.join(map(str, revs))} acknowledged ({len(losers)} losing side)")
489
+ _emit(f" the losing text is still readable: `canon history {got.id}`")
490
+ return EXIT_OK
491
+
492
+
493
+ def cmd_list(args: argparse.Namespace) -> int:
494
+ ctx = _ctx(args)
495
+ rows = ctx.ledger.active() if args.active else [
496
+ r for r in ctx.ledger if r.kind != "meta"
497
+ ]
498
+ if args.json:
499
+ _emit(json.dumps([r.data for r in rows], indent=2, sort_keys=True))
500
+ return EXIT_OK
501
+ if not rows:
502
+ _emit("no rules yet — `canon add \"...\" --scope 'src/**' --why \"...\"`")
503
+ return EXIT_OK
504
+ _emit(f"{'ID':<9}{'SEV':<7}{'REV':<5}{'SCOPE':<26}TEXT")
505
+ for r in rows:
506
+ scope = jurisdiction(r).describe()
507
+ if len(scope) > 24:
508
+ scope = scope[:23] + "…"
509
+ text = r.text if len(r.text) <= 60 else r.text[:59] + "…"
510
+ _emit(f"{r.id:<9}{r.sev:<7}{r.rev:<5}{scope:<26}{text}")
511
+ return EXIT_OK
512
+
513
+
514
+ def cmd_show(args: argparse.Namespace) -> int:
515
+ ctx = _ctx(args)
516
+ rec = ctx.ledger.get(args.id)
517
+ if rec is None:
518
+ _err(f"canon: no rule {args.id}")
519
+ return EXIT_USAGE
520
+ _emit(json.dumps(rec.data, indent=2, sort_keys=True))
521
+ if rec.prior:
522
+ _emit("")
523
+ _emit(f"prior revisions retained: {', '.join(h[:20] for h in rec.prior)}")
524
+ return EXIT_OK
525
+
526
+
527
+ def cmd_brief(args: argparse.Namespace) -> int:
528
+ ctx = _ctx(args)
529
+ fp = _footprint(args, ctx.repo)
530
+ kept, omitted, map_entries, orientation = B.compile_for(
531
+ ctx.ledger, fp, max_tokens=args.max_tokens, include_all=args.all
532
+ )
533
+ out = B.render(
534
+ kept,
535
+ omitted,
536
+ fp,
537
+ ctx.ledger.snapshot(),
538
+ task=args.task,
539
+ orientation=orientation,
540
+ map_entries=map_entries,
541
+ )
542
+ if args.json:
543
+ payload = B.render_json(kept, omitted, fp, ctx.ledger.snapshot(), task=args.task)
544
+ payload["orientation"] = orientation
545
+ payload["tokens"] = out.tokens
546
+ payload["map"] = [{"scope": k, "ids": v} for k, v in map_entries]
547
+ _emit(json.dumps(payload, indent=2))
548
+ return EXIT_OK
549
+ _emit(out.text)
550
+ return EXIT_OK
551
+
552
+
553
+ def cmd_check(args: argparse.Namespace) -> int:
554
+ ctx = _ctx(args)
555
+ fp = _footprint(args, ctx.repo)
556
+ js = applicable(ctx.ledger, fp, kinds=("rule",))
557
+ results = [
558
+ run_check(j, fp, ctx.repo, ledger=ctx.ledger, timeout=args.timeout, run_judges=not args.no_judge)
559
+ for j in js
560
+ ]
561
+ outcome = aggregate(results, strict=args.strict)
562
+ A.record_stats(ctx.repo, results)
563
+
564
+ if args.json:
565
+ payload = {
566
+ "snapshot": ctx.ledger.snapshot(),
567
+ "footprint": fp.digest(),
568
+ "ok": outcome.ok,
569
+ "counts": outcome.counts,
570
+ "results": [r.to_dict() for r in results],
571
+ }
572
+ if args.note:
573
+ _attach_note(ctx.repo, payload, staged=args.staged)
574
+ _emit(json.dumps(payload, indent=2))
575
+ return outcome.exit_code()
576
+
577
+ if not results:
578
+ _emit(f"canon check · nothing governs this change ({fp.summary()})")
579
+ if args.note:
580
+ _attach_note(
581
+ ctx.repo,
582
+ {
583
+ "snapshot": ctx.ledger.snapshot(),
584
+ "footprint": fp.digest(),
585
+ "ok": True,
586
+ "counts": outcome.counts,
587
+ "results": [],
588
+ },
589
+ staged=args.staged,
590
+ )
591
+ _emit("certificate recorded")
592
+ return EXIT_OK
593
+
594
+ for r in outcome.blocking:
595
+ j = r.jurisdiction
596
+ _emit(f"FAIL {r.id} {j.rec.text}")
597
+ if j.rec.why:
598
+ _emit(f" why {j.rec.why}")
599
+ if not j.scope.covers_all():
600
+ _emit(f" when {j.scope.describe()}")
601
+ _emit(f" check {r.evidence.detail}")
602
+ if r.evidence.out.strip():
603
+ tail = r.evidence.out.strip().splitlines()[-8:]
604
+ for line in tail:
605
+ _emit(f" | {line[:160]}")
606
+ _emit(f" fix the change; `canon explain {r.id}` for the history.")
607
+ _emit("")
608
+
609
+ for r in outcome.advisories:
610
+ j = r.jurisdiction
611
+ _emit(f"note {r.id} [{r.sev}] {j.rec.text}")
612
+ if r.evidence.out.strip():
613
+ for line in r.evidence.out.strip().splitlines()[:4]:
614
+ _emit(f" | {line[:160]}")
615
+ _emit(" non-blocking: fix it or leave it, but it is recorded.")
616
+ _emit("")
617
+
618
+ if outcome.unknowns and not args.quiet:
619
+ ids = ", ".join(r.id for r in outcome.unknowns)
620
+ _emit(f"unknown: {ids} — no mechanical check (declared, not proven)")
621
+
622
+ _emit(f"canon check · snapshot {ctx.ledger.snapshot()} · {outcome.summary()}")
623
+ if args.note:
624
+ where = _attach_note(
625
+ ctx.repo,
626
+ {
627
+ "snapshot": ctx.ledger.snapshot(),
628
+ "footprint": fp.digest(),
629
+ "ok": outcome.ok,
630
+ "counts": outcome.counts,
631
+ "results": [r.to_dict() for r in results],
632
+ },
633
+ staged=args.staged,
634
+ )
635
+ if where == "pending":
636
+ _emit("certificate queued for the new commit (post-commit attaches it)")
637
+ elif where:
638
+ _emit(f"certificate attached to {where[:10]}")
639
+ if not outcome.ok and outcome.blocking:
640
+ _emit("")
641
+ _emit("refusing: the change does not satisfy the rulebook.")
642
+ return outcome.exit_code()
643
+
644
+
645
+ def _attach_note(repo: Path, payload: dict, *, staged: bool = False) -> str:
646
+ """Put the certificate outside the tree.
647
+
648
+ While staged, the commit does not exist yet, so the certificate is queued in
649
+ the cache and `canon certify` attaches it from the post-commit hook. A
650
+ refused change produces no certificate at all: a certificate attests
651
+ compliance, and there is nothing to attest.
652
+ """
653
+ if not payload.get("ok"):
654
+ return ""
655
+ body = json.dumps(payload, sort_keys=True, indent=1)
656
+ if staged:
657
+ path = repo / ".canon" / "cache" / "pending.json"
658
+ path.parent.mkdir(parents=True, exist_ok=True)
659
+ path.write_text(body, encoding="utf-8")
660
+ return "pending"
661
+ try:
662
+ sha = gitx.git(repo, "rev-parse", "HEAD").strip()
663
+ if not sha:
664
+ return ""
665
+ gitx.note_put(repo, sha, body)
666
+ return sha
667
+ except (gitx.NoteError, OSError):
668
+ return ""
669
+
670
+
671
+ def cmd_certify(args: argparse.Namespace) -> int:
672
+ ctx = _ctx(args)
673
+ pending = ctx.repo / ".canon" / "cache" / "pending.json"
674
+ if not pending.exists():
675
+ _err("canon: no pending certificate — run `canon check --staged --note` first")
676
+ return EXIT_USAGE
677
+ sha = gitx.git(ctx.repo, "rev-parse", "HEAD").strip()
678
+ if not sha:
679
+ _err("canon: no commit to certify")
680
+ return EXIT_USAGE
681
+ try:
682
+ gitx.note_put(ctx.repo, sha, pending.read_text(encoding="utf-8"))
683
+ except (gitx.NoteError, OSError) as exc:
684
+ _err(f"canon: could not write note: {exc}")
685
+ return EXIT_USAGE
686
+ pending.unlink()
687
+ _emit(f"certificate attached to {sha[:10]}")
688
+ return EXIT_OK
689
+
690
+
691
+ def cmd_audit(args: argparse.Namespace) -> int:
692
+ ctx = _ctx(args)
693
+ text, payload = A.report(ctx.repo, ctx.ledger, record=args.probe, probe_limit=args.probe_limit)
694
+ if args.json:
695
+ _emit(json.dumps(payload, indent=2))
696
+ else:
697
+ _emit(text)
698
+ return EXIT_OK if payload["ok"] else EXIT_VIOLATION
699
+
700
+
701
+ def cmd_lint(args: argparse.Namespace) -> int:
702
+ ctx = _ctx(args)
703
+ files = gitx.tracked_files(ctx.repo)
704
+ findings = (
705
+ A.contradictions(ctx.ledger)
706
+ + A.dead_scopes(ctx.ledger, files)
707
+ + A.redundant(ctx.ledger, files)
708
+ + A.diverged(ctx.ledger)
709
+ )
710
+ if args.json:
711
+ _emit(json.dumps([f.to_dict() for f in findings], indent=2))
712
+ elif not findings:
713
+ _emit(f"canon lint · clean ({len(files)} files, {len(ctx.ledger.active('rule'))} rules)")
714
+ else:
715
+ for f in findings:
716
+ _emit(str(f))
717
+ return EXIT_VIOLATION if any(f.level == "error" for f in findings) else EXIT_OK
718
+
719
+
720
+ def cmd_render(args: argparse.Namespace) -> int:
721
+ ctx = _ctx(args)
722
+ if args.format == "prompt":
723
+ _emit(P.block())
724
+ return EXIT_OK
725
+ if args.format == "json":
726
+ _emit(json.dumps([r.data for r in ctx.ledger], indent=2, sort_keys=True))
727
+ return EXIT_OK
728
+ if args.format == "ledger":
729
+ for r in ctx.ledger:
730
+ _emit(json.dumps(r.data, sort_keys=True, separators=(",", ":")))
731
+ return EXIT_OK
732
+ # format == agents
733
+ lines = [P.block().rstrip(), "", "<!-- everything below is generated; source: .canon/ledger.jsonl -->", ""]
734
+ for sev, title in (("hard", "Hard rules"), ("soft", "Soft rules"), ("advice", "Tips")):
735
+ group = [r for r in ctx.ledger.active("rule") if r.sev == sev]
736
+ if not group:
737
+ continue
738
+ lines.append(f"### {title}")
739
+ for r in group:
740
+ scope = jurisdiction(r)
741
+ tail = "" if scope.covers_all() else f" _(scope: `{scope.describe()}`)_"
742
+ lines.append(f"- **{r.id}** — {r.text}{tail}")
743
+ if r.why:
744
+ lines.append(f" - {r.why}")
745
+ lines.append("")
746
+ facts = ctx.ledger.active("fact")
747
+ if facts:
748
+ lines.append("### Facts")
749
+ for r in facts:
750
+ lines.append(f"- **{r.id}** — {r.text}")
751
+ lines.append("")
752
+ _emit("\n".join(lines).rstrip())
753
+ return EXIT_OK
754
+
755
+
756
+ def cmd_stats(args: argparse.Namespace) -> int:
757
+ ctx = _ctx(args)
758
+ data = A.load_cache(ctx.repo, "stats.json")
759
+ rows = A.stats(ctx.ledger, data)
760
+ if args.json:
761
+ _emit(json.dumps(rows, indent=2))
762
+ return EXIT_OK
763
+ if not rows:
764
+ _emit("no telemetry yet — run `canon check` in a repository with hooks installed")
765
+ return EXIT_OK
766
+ _emit(f"{'ID':<9}{'SEV':<7}{'HITS':>5}{'CATCH':>7}{'WAIVED':>8} TEXT")
767
+ for rid, sev, hits, catches, waived, text in rows:
768
+ t = text if len(text) <= 52 else text[:51] + "…"
769
+ _emit(f"{rid:<9}{sev:<7}{hits:>5}{catches:>7}{waived:>8} {t}")
770
+ _emit("")
771
+ _emit("a rule with hits and no catches has never prevented anything: consider retiring it.")
772
+ return EXIT_OK
773
+
774
+
775
+ PRE_HOOK = """#!/bin/sh
776
+ # canon pre-commit: proves the staged change satisfies the rulebook.
777
+ # Remove with `canon hook uninstall`.
778
+ {env}{chain}canon_run() {{
779
+ {invoke} "$@"
780
+ }}
781
+ MSG=$(cat .git/COMMIT_EDITMSG 2>/dev/null || true)
782
+ canon_run check --staged --quiet --note --message "$MSG" || {{
783
+ echo "canon: commit refused. Fix the change, do not bypass the hook." >&2
784
+ exit 1
785
+ }}
786
+ """
787
+
788
+ POST_HOOK = """#!/bin/sh
789
+ # canon post-commit: attach the certificate the pre-commit run queued.
790
+ {env}canon_run() {{
791
+ {invoke} "$@"
792
+ }}
793
+ [ -f .canon/cache/pending.json ] && canon_run certify >/dev/null 2>&1
794
+ exit 0
795
+ """
796
+
797
+
798
+ def _hook_invocation() -> tuple[str, str]:
799
+ """How this installation of canon is reached from a git hook.
800
+
801
+ Bake the answer at install time. A hook that guesses runs in an environment
802
+ with a different PATH; a hook that has been told does not.
803
+ """
804
+ binary = shutil.which("canon")
805
+ if binary:
806
+ return "", f"{shlex.quote(binary)}"
807
+ root = str(Path(__file__).resolve().parents[1])
808
+ env = f'export PYTHONPATH="{root}${{PYTHONPATH:+:$PYTHONPATH}}"\n'
809
+ return env, f"{shlex.quote(sys.executable or 'python3')} -m canon"
810
+
811
+
812
+ def cmd_hook(args: argparse.Namespace) -> int:
813
+ ctx = _ctx(args)
814
+ if not gitx.is_repo(ctx.repo):
815
+ _err("canon: not a git repository")
816
+ return EXIT_USAGE
817
+ hooks = ctx.repo / ".git" / "hooks"
818
+ hooks.mkdir(parents=True, exist_ok=True)
819
+ target = hooks / "pre-commit"
820
+ backup = hooks / "pre-commit.canon-original"
821
+
822
+ if args.action == "uninstall":
823
+ if target.exists() and "canon pre-commit" in target.read_text(errors="replace"):
824
+ target.unlink()
825
+ if backup.exists():
826
+ backup.rename(target)
827
+ post = hooks / "post-commit"
828
+ if post.exists() and "canon post-commit" in post.read_text(errors="replace"):
829
+ post.unlink()
830
+ _emit("canon hooks removed")
831
+ return EXIT_OK
832
+ _emit("no canon hook installed")
833
+ return EXIT_OK
834
+
835
+ chain = ""
836
+ if target.exists() and "canon pre-commit" not in target.read_text(errors="replace"):
837
+ target.rename(backup)
838
+ chain = f'"{backup}" "$@" || exit $?'
839
+ env, invoke = _hook_invocation()
840
+ body = PRE_HOOK.format(chain=chain, env=env, invoke=invoke)
841
+ target.write_text(body, encoding="utf-8")
842
+ target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
843
+ post = hooks / "post-commit"
844
+ if not post.exists() or "canon post-commit" in post.read_text(errors="replace"):
845
+ post.write_text(POST_HOOK.format(env=env, invoke=invoke), encoding="utf-8")
846
+ post.chmod(post.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
847
+ _emit("installed .git/hooks/pre-commit -> canon check --staged")
848
+ _emit("installed .git/hooks/post-commit -> canon certify (certificate, not residue)")
849
+ if chain:
850
+ _emit(f" chained the previous hook from {backup.name}")
851
+ _emit(" bypassing with --no-verify is possible; `canon check` in CI is not.")
852
+ return EXIT_OK
853
+
854
+
855
+ def cmd_compact(args: argparse.Namespace) -> int:
856
+ ctx = _ctx(args)
857
+ saved = ctx.ledger.compact()
858
+ _emit(f"compacted to {len(ctx.ledger)} record(s), {saved} bytes saved")
859
+ return EXIT_OK
860
+
861
+
862
+ def cmd_import(args: argparse.Namespace) -> int:
863
+ root = _repo(args)
864
+ src = Path(args.file)
865
+ if not src.is_absolute():
866
+ src = root / src
867
+ if not src.exists():
868
+ _err(f"canon: no such file {src}")
869
+ return EXIT_USAGE
870
+ text = src.read_text(encoding="utf-8", errors="replace")
871
+ sections = re.split(r"(?m)^##\s+", text)
872
+ led = Ledger.open(_ledger_path(root))
873
+ n = 0
874
+ for section in sections[1:]:
875
+ lines = section.splitlines()
876
+ if not lines:
877
+ continue
878
+ title = lines[0].strip()
879
+ body = re.sub(r"\s+", " ", " ".join(ln.strip() for ln in lines[1:] if ln.strip()))
880
+ if not body:
881
+ continue
882
+ n += 1
883
+ digest = hashlib.sha256(f"{src.name}#{title}".encode("utf-8")).hexdigest()[:6]
884
+ led.append(
885
+ {
886
+ "v": 1,
887
+ "id": "F" + digest,
888
+ "kind": "fact",
889
+ "sev": "advice",
890
+ "text": (title + " — " + body)[:390],
891
+ "why": f"imported from {src.name}",
892
+ "scope": {"paths": ["**"], "ops": ["write", "delete", "commit"]},
893
+ "imported_from": f"{src.name}#{title}",
894
+ "author": "canon-import",
895
+ "ts": "1970-01-01T00:00:00Z",
896
+ "lamport": 1,
897
+ }
898
+ )
899
+ _emit(f"imported {n} section(s) as advisory facts. Split them into scoped rules with `canon add`.")
900
+ return EXIT_OK
901
+
902
+
903
+ def cmd_explain(args: argparse.Namespace) -> int:
904
+ ctx = _ctx(args)
905
+ rec = ctx.ledger.get(args.id)
906
+ if rec is None:
907
+ _err(f"canon: no rule {args.id}")
908
+ return EXIT_USAGE
909
+ scope = jurisdiction(rec)
910
+ _emit(f"{rec.id} [{rec.sev}] rev {rec.rev} {rec.status}")
911
+ _emit(rec.text)
912
+ if rec.get("author"):
913
+ _emit(f"by {rec.get('author')} {rec.get('ts', '')}")
914
+ if rec.why:
915
+ _emit("")
916
+ _emit(f"why {rec.why}")
917
+ _emit(f"when {scope.describe()}")
918
+ check = rec.get("check")
919
+ if isinstance(check, str):
920
+ _emit(f"check {check}")
921
+ elif isinstance(check, dict):
922
+ _emit(f"check [{check.get('kind', 'shell')}] {check.get('run')}")
923
+ else:
924
+ _emit("check none — this rule can only ever be UNKNOWN")
925
+ if rec.get("probe"):
926
+ _emit(f"probe {rec.get('probe')}")
927
+ for anchor in rec.get("anchors") or []:
928
+ _emit(f"anchor {anchor.get('path')} @ {str(anchor.get('sha256'))[:16]}…")
929
+ if rec.get("imported_from"):
930
+ _emit(f"from {rec.get('imported_from')}")
931
+ if rec.prior:
932
+ _emit(f"prior {', '.join(h[:16] + '…' for h in rec.prior)}")
933
+ _emit(f"hash {rec.hash}")
934
+ return EXIT_OK
935
+
936
+
937
+ def cmd_version(args: argparse.Namespace) -> int:
938
+ _emit(f"canon {__version__}")
939
+ return EXIT_OK
940
+
941
+
942
+ # -- parser -----------------------------------------------------------------
943
+
944
+
945
+ def _add_footprint_flags(p: argparse.ArgumentParser) -> None:
946
+ p.add_argument("--base", default="HEAD", help="git ref to diff against (default HEAD)")
947
+ p.add_argument("--staged", action="store_true", help="judge the index, not the worktree")
948
+ p.add_argument("--range", default="", help="git range, e.g. origin/main..HEAD")
949
+ p.add_argument("--paths", nargs="*", default=None, help="explicit paths (CI)")
950
+ p.add_argument("--message", default="", help="commit message, enables ops:commit rules")
951
+ p.add_argument(
952
+ "--all-files", action="store_true", help="judge every tracked file, not just the diff"
953
+ )
954
+
955
+
956
+ def build_parser() -> argparse.ArgumentParser:
957
+ p = argparse.ArgumentParser(
958
+ prog="canon",
959
+ description="The rulebook, compiled: scoped, verifiable repository rules.",
960
+ )
961
+ p.add_argument("--repo", default="", help="repository root (default: discover)")
962
+ p.add_argument("--version", action="version", version=f"canon {__version__}")
963
+ sub = p.add_subparsers(dest="cmd", required=False)
964
+
965
+ s = sub.add_parser("init", help="create .canon/ and print the integration block")
966
+ s.set_defaults(func=cmd_init)
967
+
968
+ s = sub.add_parser("add", help="add a rule or fact")
969
+ s.add_argument("text")
970
+ s.add_argument("--scope", action="append", help="path glob (repeatable)")
971
+ s.add_argument("--not", dest="not_path", action="append", help="excluded glob")
972
+ s.add_argument("--ops", nargs="*", default=None, help="write delete commit pr release")
973
+ s.add_argument("--sev", default="", choices=["", *SEVERITIES])
974
+ s.add_argument("--kind", default="rule", choices=[k for k in KINDS if k != "meta"])
975
+ s.add_argument("--why", default="")
976
+ s.add_argument("--check", default="", help="shell command that proves the rule")
977
+ s.add_argument("--check-kind", default="shell", choices=["shell", "grep", "path", "judge", "manual", "none"])
978
+ s.add_argument("--expect", default="")
979
+ s.add_argument("--timeout", type=int, default=0)
980
+ s.add_argument("--probe", default="", help="command that proves the rule is still true")
981
+ s.add_argument("--key", default="", help="shared subject, enables contradiction detection")
982
+ s.add_argument("--value", default="", help="this rule's claim about the subject")
983
+ s.add_argument("--anchor", action="append", help="file this rule is based on")
984
+ s.add_argument("--id", default="")
985
+ s.set_defaults(func=cmd_add)
986
+
987
+ s = sub.add_parser("edit", help="amend a rule (keeps history)")
988
+ s.add_argument("id")
989
+ s.add_argument("--text", default="")
990
+ s.add_argument("--why", default="")
991
+ s.add_argument("--sev", default="", choices=["", *SEVERITIES])
992
+ s.add_argument("--scope", action="append")
993
+ s.add_argument("--not", dest="not_path", action="append")
994
+ s.add_argument("--ops", nargs="*", default=None)
995
+ s.add_argument("--check", default=None)
996
+ s.add_argument("--check-kind", default="shell")
997
+ s.add_argument("--expect", default="")
998
+ s.add_argument("--timeout", type=int, default=0)
999
+ s.add_argument("--key", default="")
1000
+ s.add_argument("--value", default="")
1001
+ s.set_defaults(func=cmd_edit)
1002
+
1003
+ s = sub.add_parser("retire", help="retire a rule")
1004
+ s.add_argument("id")
1005
+ s.add_argument("--reason", default="")
1006
+ s.set_defaults(func=cmd_retire)
1007
+
1008
+ s = sub.add_parser("waive", help="record an auditable dispensation")
1009
+ s.add_argument("id")
1010
+ s.add_argument("--reason", required=True)
1011
+ s.add_argument("--expires", default="", help="YYYY-MM-DD")
1012
+ s.add_argument("--waiver-id", default="")
1013
+ s.set_defaults(func=cmd_waive)
1014
+
1015
+ s = sub.add_parser("remember", help="record knowledge an agent learned (unreviewed)")
1016
+ s.add_argument("text")
1017
+ s.add_argument("--scope", action="append")
1018
+ s.add_argument("--not", dest="not_path", action="append")
1019
+ s.add_argument("--ops", nargs="*", default=None)
1020
+ s.add_argument("--why", default="")
1021
+ s.add_argument("--id", default="")
1022
+ s.set_defaults(func=cmd_remember)
1023
+
1024
+ s = sub.add_parser("review", help="confirm or list unreviewed knowledge")
1025
+ s.add_argument("id", nargs="?", default="")
1026
+ s.set_defaults(func=cmd_review)
1027
+
1028
+ s = sub.add_parser("history", help="every revision of a rule, including losing ones")
1029
+ s.add_argument("id")
1030
+ s.set_defaults(func=cmd_history)
1031
+
1032
+ s = sub.add_parser("resolve", help="acknowledge concurrent revisions of one rule")
1033
+ s.add_argument("id")
1034
+ s.set_defaults(func=cmd_resolve)
1035
+
1036
+ s = sub.add_parser("list", help="list rules")
1037
+ s.add_argument("--active", action="store_true")
1038
+ s.add_argument("--json", action="store_true")
1039
+ s.set_defaults(func=cmd_list)
1040
+
1041
+ s = sub.add_parser("show", help="show one record as JSON")
1042
+ s.add_argument("id")
1043
+ s.set_defaults(func=cmd_show)
1044
+
1045
+ s = sub.add_parser("explain", help="explain a rule in prose")
1046
+ s.add_argument("id")
1047
+ s.set_defaults(func=cmd_explain)
1048
+
1049
+ s = sub.add_parser("brief", help="compile the rules that govern this change")
1050
+ s.add_argument("--task", default="")
1051
+ s.add_argument("--max-tokens", type=int, default=1200)
1052
+ s.add_argument("--all", action="store_true", help="ignore the budget")
1053
+ s.add_argument("--json", action="store_true")
1054
+ _add_footprint_flags(s)
1055
+ s.set_defaults(func=cmd_brief)
1056
+
1057
+ s = sub.add_parser("check", help="evaluate the change against the rulebook")
1058
+ s.add_argument("--strict", action="store_true", help="UNKNOWN blocks the change")
1059
+ s.add_argument("--json", action="store_true")
1060
+ s.add_argument("--note", action="store_true", help="attach the certificate to git notes")
1061
+ s.add_argument("--no-judge", action="store_true", help="skip LLM-judged rules")
1062
+ s.add_argument("--quiet", action="store_true")
1063
+ s.add_argument("--timeout", type=int, default=0)
1064
+ _add_footprint_flags(s)
1065
+ s.set_defaults(func=cmd_check)
1066
+
1067
+ s = sub.add_parser("audit", help="the rulebook examines itself")
1068
+ s.add_argument("--json", action="store_true")
1069
+ s.add_argument("--probe", action="store_true", help="run due freshness probes")
1070
+ s.add_argument("--probe-limit", type=int, default=3)
1071
+ s.set_defaults(func=cmd_audit)
1072
+
1073
+ s = sub.add_parser("lint", help="static checks: conflict, death, redundancy")
1074
+ s.add_argument("--json", action="store_true")
1075
+ s.set_defaults(func=cmd_lint)
1076
+
1077
+ s = sub.add_parser("render", help="project the ledger into text")
1078
+ s.add_argument("--format", default="agents", choices=["agents", "prompt", "json", "ledger"])
1079
+ s.set_defaults(func=cmd_render)
1080
+
1081
+ s = sub.add_parser("stats", help="hits and catches per rule")
1082
+ s.add_argument("--json", action="store_true")
1083
+ s.set_defaults(func=cmd_stats)
1084
+
1085
+ s = sub.add_parser("hook", help="install or remove the git hook")
1086
+ s.add_argument("action", choices=["install", "uninstall"])
1087
+ s.set_defaults(func=cmd_hook)
1088
+
1089
+ s = sub.add_parser("import", help="seed the ledger from a markdown file")
1090
+ s.add_argument("file")
1091
+ s.set_defaults(func=cmd_import)
1092
+
1093
+ s = sub.add_parser("compact", help="rewrite the ledger without losing revisions")
1094
+ s.set_defaults(func=cmd_compact)
1095
+
1096
+ s = sub.add_parser("certify", help="attach the queued certificate to HEAD")
1097
+ s.set_defaults(func=cmd_certify)
1098
+
1099
+ s = sub.add_parser("activate", help="make future sessions notice canon")
1100
+ s.add_argument("--check", action="store_true", help="verify, do not write (CI)")
1101
+ s.add_argument("--all", action="store_true", help="create every harness file")
1102
+ s.add_argument("--harness", action="append", help="agents|claude|gemini|copilot|cursor")
1103
+ s.set_defaults(func=cmd_activate)
1104
+
1105
+ s = sub.add_parser("mcp", help="run the MCP server on stdio")
1106
+ s.set_defaults(func=cmd_mcp)
1107
+
1108
+ s = sub.add_parser("version")
1109
+ s.set_defaults(func=cmd_version)
1110
+
1111
+ return p
1112
+
1113
+
1114
+ GUIDE = """\
1115
+ canon {version} — the rulebook, compiled.
1116
+
1117
+ canon brief --task "<your task>" rules that govern this change
1118
+ canon check prove the change satisfies them
1119
+
1120
+ canon activate write the block every harness already reads
1121
+ canon mcp expose brief/check/remember as MCP tools
1122
+ canon hook install refuse commits that break a hard rule
1123
+ canon remember "<fact>" keep knowledge; unreviewed until a human confirms
1124
+ canon audit debt, coverage, stale rules, conflicts
1125
+ canon --help all 20 commands
1126
+ """
1127
+
1128
+
1129
+ def main(argv: list[str] | None = None) -> int:
1130
+ parser = build_parser()
1131
+ args = parser.parse_args(argv)
1132
+ if getattr(args, "cmd", None) is None:
1133
+ _emit(GUIDE.format(version=__version__))
1134
+ return EXIT_OK
1135
+ try:
1136
+ return int(args.func(args))
1137
+ except LedgerError as exc:
1138
+ _err(f"canon: {exc}")
1139
+ return EXIT_USAGE
1140
+ except BrokenPipeError:
1141
+ return EXIT_OK
1142
+ except KeyboardInterrupt:
1143
+ return 130