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/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """canon — the rulebook, compiled."""
2
+
3
+ __version__ = "0.1.0"
canon/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
canon/activate.py ADDED
@@ -0,0 +1,143 @@
1
+ """Activation: getting a future session to notice canon at all.
2
+
3
+ There is no magic here, and pretending otherwise would be the dishonest part of
4
+ this project. A fresh session begins with exactly three channels:
5
+
6
+ 1. context the harness injects (AGENTS.md and friends) — passive, universal
7
+ 2. tools the harness offers (MCP, CLI help) — salient, still optional
8
+ 3. commands the session must run to finish (git) — deterministic, unavoidable
9
+
10
+ This module writes channel 1 for every harness that has a file, generates
11
+ channel 2's MCP configuration, and leaves channel 3 to `canon hook install`.
12
+ The marked block is the only prose canon adds, and `--check` makes it
13
+ impossible for it to go stale silently.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ from pathlib import Path
20
+
21
+ from . import prompt
22
+
23
+ MARK_BEGIN = "<!-- canon:begin — generated by `canon activate`; edit rules with `canon add` -->"
24
+ MARK_END = "<!-- canon:end -->"
25
+
26
+ MCP_CONFIG = {
27
+ "mcpServers": {
28
+ "canon": {
29
+ "command": "canon",
30
+ "args": ["mcp"],
31
+ }
32
+ }
33
+ }
34
+
35
+ # name -> (path, kind, create-by-default)
36
+ HARNESSES: dict[str, tuple[str, str, bool]] = {
37
+ "agents": ("AGENTS.md", "block", True),
38
+ "claude": ("CLAUDE.md", "block", False),
39
+ "gemini": ("GEMINI.md", "block", False),
40
+ "copilot": (".github/copilot-instructions.md", "block", False),
41
+ "cursor": (".cursor/rules/canon.mdc", "mdc", False),
42
+ }
43
+
44
+ MDC = """---
45
+ description: This repository's rules (canon). Read before editing.
46
+ alwaysApply: true
47
+ ---
48
+ """
49
+
50
+
51
+ def marked_block() -> str:
52
+ return f"{MARK_BEGIN}\n{prompt.block().rstrip()}\n{MARK_END}\n"
53
+
54
+
55
+ def upsert(text: str, block: str) -> str:
56
+ """Replace the marked region, or append one. Idempotent by construction."""
57
+ if MARK_BEGIN in text and MARK_END in text:
58
+ head = text[: text.index(MARK_BEGIN)]
59
+ tail = text[text.index(MARK_END) + len(MARK_END) :]
60
+ tail = tail.lstrip("\n")
61
+ joined = head + block
62
+ if tail:
63
+ joined += "\n" + tail
64
+ return joined
65
+ if not text.strip():
66
+ return block
67
+ return text.rstrip("\n") + "\n\n" + block
68
+
69
+
70
+ def expected(repo: Path, *, all_harnesses: bool, only: list[str] | None) -> list[str]:
71
+ """Which harness files this repository should have.
72
+
73
+ Default is respectful: AGENTS.md always, and any other harness file the team
74
+ already uses. `--all` creates the rest; `--harness x` names one explicitly.
75
+ """
76
+ chosen: list[str] = []
77
+ for name, (rel, _kind, create) in HARNESSES.items():
78
+ if only and name not in only:
79
+ continue
80
+ exists = (repo / rel).exists()
81
+ if only or all_harnesses or create or exists:
82
+ chosen.append(name)
83
+ return chosen
84
+
85
+
86
+ def _render(repo: Path, name: str) -> tuple[Path, str] | None:
87
+ rel, kind, _ = HARNESSES[name]
88
+ path = repo / rel
89
+ block = marked_block()
90
+ if kind == "mdc":
91
+ return path, MDC + "\n" + block
92
+ return path, block
93
+
94
+
95
+ def install(repo: Path, names: list[str]) -> list[tuple[str, str]]:
96
+ """Write the block everywhere it belongs. Returns (path, action)."""
97
+ report: list[tuple[str, str]] = []
98
+ for name in names:
99
+ rendered = _render(repo, name)
100
+ if rendered is None:
101
+ continue
102
+ path, block = rendered
103
+ before = path.read_text(encoding="utf-8") if path.exists() else ""
104
+ if HARNESSES[name][1] == "mdc":
105
+ after = block if not before else block
106
+ else:
107
+ after = upsert(before, block)
108
+ if after == before:
109
+ report.append((str(path.relative_to(repo)), "unchanged"))
110
+ continue
111
+ path.parent.mkdir(parents=True, exist_ok=True)
112
+ path.write_text(after, encoding="utf-8")
113
+ report.append((str(path.relative_to(repo)), "created" if not before else "updated"))
114
+ return report
115
+
116
+
117
+ def check(repo: Path, names: list[str]) -> list[str]:
118
+ """Problems a CI job should fail on."""
119
+ problems: list[str] = []
120
+ for name in names:
121
+ rendered = _render(repo, name)
122
+ if rendered is None:
123
+ continue
124
+ path, block = rendered
125
+ rel = str(path.relative_to(repo))
126
+ if not path.exists():
127
+ problems.append(f"{rel}: missing (run `canon activate`)")
128
+ continue
129
+ text = path.read_text(encoding="utf-8")
130
+ if HARNESSES[name][1] == "mdc":
131
+ if text.strip() != block.strip():
132
+ problems.append(f"{rel}: out of date (run `canon activate`)")
133
+ continue
134
+ if MARK_BEGIN not in text or MARK_END not in text:
135
+ problems.append(f"{rel}: no canon block (run `canon activate`)")
136
+ continue
137
+ if path.read_text(encoding="utf-8") != upsert(text, block):
138
+ problems.append(f"{rel}: block is stale (run `canon activate`)")
139
+ return problems
140
+
141
+
142
+ def mcp_snippet() -> str:
143
+ return json.dumps(MCP_CONFIG, indent=2)
canon/audit.py ADDED
@@ -0,0 +1,418 @@
1
+ """Audit: the rulebook examining itself.
2
+
3
+ Four things a prose rulebook cannot do, and this module does:
4
+
5
+ 1. **Contradiction.** Two rules that declare the same `key` and disagree on
6
+ `value` are a build error, and the report names a concrete path where both
7
+ apply. Position never decides a conflict, because a conflict is never
8
+ resolved — it is reported.
9
+ 2. **Death.** A rule whose scope matches no file in the repository governs
10
+ nothing. That is rot you can compute, not rot you discover a year later.
11
+ 3. **Drift.** A rule that cites an anchor carries the hash of what it cited.
12
+ When the anchor changes, the rationale is suspect and the rule says so.
13
+ 4. **Debt.** Hard rules with no mechanical check are the unproven surface. The
14
+ number should fall over time. That is the project's health metric: not how
15
+ much documentation you have, but how little of it is still prose.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import json
22
+ import time
23
+ from dataclasses import dataclass, field
24
+ from pathlib import Path
25
+
26
+ from .gitx import Footprint, git, tracked_files
27
+ from .ledger import Ledger, Rec
28
+ from .select import _SEV_RANK, jurisdiction, uncovered
29
+ from .verify import Evidence, Verdict, active_waiver, has_predicate
30
+
31
+ __all__ = [
32
+ "Finding",
33
+ "contradictions",
34
+ "dead_scopes",
35
+ "redundant",
36
+ "diverged",
37
+ "anchor_drift",
38
+ "coverage",
39
+ "debt",
40
+ "probe_due",
41
+ "run_probes",
42
+ "report",
43
+ "load_cache",
44
+ "save_cache",
45
+ "record_stats",
46
+ "stats",
47
+ ]
48
+
49
+
50
+ @dataclass
51
+ class Finding:
52
+ code: str
53
+ subject: str
54
+ message: str
55
+ evidence: str = ""
56
+ level: str = "error"
57
+
58
+ def to_dict(self) -> dict:
59
+ return {
60
+ "code": self.code,
61
+ "subject": self.subject,
62
+ "message": self.message,
63
+ "evidence": self.evidence,
64
+ "level": self.level,
65
+ }
66
+
67
+ def __str__(self) -> str:
68
+ ev = f"\n {self.evidence}" if self.evidence else ""
69
+ return f"{self.level.upper():<7} {self.code:<14} {self.subject:<17} {self.message}{ev}"
70
+
71
+
72
+ # -- cache ------------------------------------------------------------------
73
+
74
+
75
+ def _cache_path(repo: Path, name: str) -> Path:
76
+ d = repo / ".canon" / "cache"
77
+ d.mkdir(parents=True, exist_ok=True)
78
+ return d / name
79
+
80
+
81
+ def load_cache(repo: Path, name: str) -> dict:
82
+ path = _cache_path(repo, name)
83
+ if not path.exists():
84
+ return {}
85
+ try:
86
+ return json.loads(path.read_text(encoding="utf-8"))
87
+ except (json.JSONDecodeError, OSError):
88
+ return {}
89
+
90
+
91
+ def save_cache(repo: Path, name: str, data: dict) -> None:
92
+ path = _cache_path(repo, name)
93
+ path.write_text(json.dumps(data, indent=1, sort_keys=True), encoding="utf-8")
94
+
95
+
96
+ # -- detectors --------------------------------------------------------------
97
+
98
+
99
+ def contradictions(ledger: Ledger) -> list[Finding]:
100
+ """Same key, different value, overlapping jurisdiction -> witness."""
101
+ out: list[Finding] = []
102
+ keyed = [r for r in ledger.active("rule") if r.get("key")]
103
+ for i, a in enumerate(keyed):
104
+ for b in keyed[i + 1 :]:
105
+ if a.get("key") != b.get("key"):
106
+ continue
107
+ if a.get("value") == b.get("value"):
108
+ continue
109
+ witness = jurisdiction(a).witness_with(jurisdiction(b))
110
+ if witness is None:
111
+ continue
112
+ out.append(
113
+ Finding(
114
+ "CONTRADICTION",
115
+ f"{a.id}/{b.id}",
116
+ f"{a.get('key')}={a.get('value')!r} vs {b.get('value')!r}",
117
+ f"both govern `{witness}` — {a.id}: {a.text!r} / {b.id}: {b.text!r}",
118
+ )
119
+ )
120
+ return out
121
+
122
+
123
+ def dead_scopes(ledger: Ledger, files: list[str]) -> list[Finding]:
124
+ out: list[Finding] = []
125
+ if not files: # a fresh repository has no evidence either way
126
+ return out
127
+ for rec in ledger.active("rule"):
128
+ scope = jurisdiction(rec)
129
+ if scope.covers_all():
130
+ continue
131
+ if any(scope.matches(f) for f in files):
132
+ continue
133
+ out.append(
134
+ Finding(
135
+ "DEAD",
136
+ rec.id,
137
+ f"scope {scope.describe()} matches none of {len(files)} tracked files",
138
+ "retire it with `canon retire " + rec.id + "` or fix the glob",
139
+ level="warning",
140
+ )
141
+ )
142
+ return out
143
+
144
+
145
+ def redundant(ledger: Ledger, files: list[str]) -> list[Finding]:
146
+ """A rule whose whole jurisdiction is already covered by a twin."""
147
+ out: list[Finding] = []
148
+ rules = [r for r in ledger.active("rule") if r.get("key")]
149
+ for i, a in enumerate(rules):
150
+ sa = jurisdiction(a)
151
+ fa = {f for f in files if sa.matches(f)}
152
+ if not fa:
153
+ continue
154
+ for b in rules:
155
+ if a.id == b.id or a.get("key") != b.get("key"):
156
+ continue
157
+ if a.get("value") != b.get("value"):
158
+ continue
159
+ sb = jurisdiction(b)
160
+ if fa <= {f for f in files if sb.matches(f)}:
161
+ out.append(
162
+ Finding(
163
+ "REDUNDANT",
164
+ a.id,
165
+ f"fully covered by {b.id} (same key and value, {len(fa)} file(s))",
166
+ "delete one of the two",
167
+ level="warning",
168
+ )
169
+ )
170
+ break
171
+ return out
172
+
173
+
174
+ def diverged(ledger: Ledger) -> list[Finding]:
175
+ out: list[Finding] = []
176
+ for rid, losers in ledger.diverged().items():
177
+ rec = ledger.get(rid)
178
+ winner = rec.rev if rec else "?"
179
+ # An error, deliberately. Two people edited this rule offline and one
180
+ # intent is not in force; the build should stop until a human decides.
181
+ out.append(
182
+ Finding(
183
+ "DIVERGED",
184
+ rid,
185
+ f"{len(losers)} concurrent revision(s) at rev {winner} — one intent is not in force",
186
+ "read both with `canon history " + rid + "`, then `canon resolve " + rid + "`",
187
+ level="error",
188
+ )
189
+ )
190
+ return out
191
+
192
+
193
+ def anchor_drift(repo: Path, ledger: Ledger) -> list[Finding]:
194
+ out: list[Finding] = []
195
+ # facts too: a design decision is exactly the thing whose rationale rots
196
+ for rec in ledger.active():
197
+ if rec.kind not in ("rule", "fact"):
198
+ continue
199
+ anchors = rec.get("anchors") or []
200
+ for anchor in anchors:
201
+ rel = str(anchor.get("path", ""))
202
+ want = str(anchor.get("sha256", ""))
203
+ path = repo / rel
204
+ if not path.exists():
205
+ out.append(
206
+ Finding(
207
+ "ANCHOR-GONE",
208
+ rec.id,
209
+ f"anchor `{rel}` no longer exists",
210
+ "the rule cites something that was deleted; re-derive it",
211
+ level="warning",
212
+ )
213
+ )
214
+ continue
215
+ got = hashlib.sha256(path.read_bytes()).hexdigest()
216
+ if want and not got.startswith(want.replace("sha256:", "")):
217
+ out.append(
218
+ Finding(
219
+ "ANCHOR-DRIFT",
220
+ rec.id,
221
+ f"anchor `{rel}` changed since the rule was written",
222
+ f"recorded {want[:20]}… now {got[:20]}…",
223
+ level="warning",
224
+ )
225
+ )
226
+ return out
227
+
228
+
229
+ def coverage(ledger: Ledger, files: list[str], *, min_sev: str = "hard") -> dict:
230
+ holes = uncovered(ledger, files, min_sev=min_sev)
231
+ total = len(files) or 1
232
+ return {
233
+ "files": len(files),
234
+ "uncovered": len(holes),
235
+ "percent": round(100.0 * (len(files) - len(holes)) / total, 1),
236
+ "examples": holes[:12],
237
+ }
238
+
239
+
240
+ def debt(ledger: Ledger) -> dict:
241
+ hard = [r for r in ledger.active("rule") if r.sev == "hard"]
242
+ unproven = [r for r in hard if not has_predicate(r)]
243
+ judged = [r for r in hard if isinstance(r.get("check"), dict) and r["check"].get("kind") == "judge"]
244
+ return {
245
+ "hard": len(hard),
246
+ "unproven": len(unproven),
247
+ "judged": len(judged),
248
+ "ratio": round(100.0 * len(unproven) / len(hard), 1) if hard else 0.0,
249
+ "ids": [r.id for r in unproven],
250
+ }
251
+
252
+
253
+ def probe_due(ledger: Ledger, cache: dict, *, days: int = 7, limit: int = 3) -> list[Rec]:
254
+ now = time.time()
255
+ due: list[tuple[float, Rec]] = []
256
+ for rec in ledger.active("rule"):
257
+ spec = rec.get("probe")
258
+ if not spec:
259
+ continue
260
+ entry = cache.get(rec.id) or {}
261
+ last = float(entry.get("at", 0) or 0)
262
+ every = float((spec.get("every_days") if isinstance(spec, dict) else None) or days)
263
+ if now - last >= every * 86400:
264
+ due.append((last, rec))
265
+ due.sort(key=lambda t: t[0])
266
+ return [rec for _, rec in due[:limit]]
267
+
268
+
269
+ def run_probes(
270
+ repo: Path, ledger: Ledger, limit: int = 3, *, quiet: bool = True
271
+ ) -> tuple[list[Finding], dict]:
272
+ """Run at most `limit` due probes. Bounded work, cooperative maintenance."""
273
+ from .select import Jurisdiction
274
+ from .verify import run as run_check
275
+
276
+ cache = load_cache(repo, "probes.json")
277
+ due = probe_due(ledger, cache, limit=limit)
278
+ findings: list[Finding] = []
279
+ fp = Footprint()
280
+ for rec in due:
281
+ scope = jurisdiction(rec)
282
+ j = Jurisdiction(rec=rec, scope=scope, matched=[])
283
+ probe = dict(rec.get("probe") or {})
284
+ probe.setdefault("kind", "shell")
285
+ synthetic = Rec(data=dict(rec.data, check=probe), hash=rec.hash)
286
+ j2 = Jurisdiction(rec=synthetic, scope=scope, matched=[])
287
+ res = run_check(j2, fp, repo, run_judges=False)
288
+ ok = res.verdict is Verdict.PASS
289
+ cache[rec.id] = {"at": time.time(), "ok": ok, "out": res.evidence.out[:400]}
290
+ if ok:
291
+ continue
292
+ findings.append(
293
+ Finding(
294
+ "STALE",
295
+ rec.id,
296
+ "its probe no longer holds — the rule may be false",
297
+ (res.evidence.out or res.evidence.detail)[:300],
298
+ )
299
+ )
300
+ save_cache(repo, "probes.json", cache)
301
+ return findings, cache
302
+
303
+
304
+ def record_stats(repo: Path, results: list) -> None:
305
+ """Hit/catch telemetry. This is what makes rule deletion defensible."""
306
+ data = load_cache(repo, "stats.json")
307
+ for r in results:
308
+ entry = data.setdefault(r.id, {"hits": 0, "catches": 0, "waived": 0})
309
+ entry["hits"] = int(entry.get("hits", 0)) + 1
310
+ if r.verdict is Verdict.FAIL:
311
+ entry["catches"] = int(entry.get("catches", 0)) + 1
312
+ if r.verdict is Verdict.WAIVED:
313
+ entry["waived"] = int(entry.get("waived", 0)) + 1
314
+ save_cache(repo, "stats.json", data)
315
+
316
+
317
+ def stats(ledger: Ledger, data: dict) -> list[tuple]:
318
+ rows = []
319
+ for rec in ledger.active():
320
+ if rec.kind == "meta":
321
+ continue
322
+ entry = data.get(rec.id) or {}
323
+ rows.append(
324
+ (
325
+ rec.id,
326
+ rec.sev,
327
+ int(entry.get("hits", 0)),
328
+ int(entry.get("catches", 0)),
329
+ int(entry.get("waived", 0)),
330
+ rec.text,
331
+ )
332
+ )
333
+ rows.sort(key=lambda r: (-r[3], -r[2], r[0]))
334
+ return rows
335
+
336
+
337
+ # -- report -----------------------------------------------------------------
338
+
339
+
340
+ def report(
341
+ repo: Path,
342
+ ledger: Ledger,
343
+ files: list[str] | None = None,
344
+ *,
345
+ record: bool = False,
346
+ probe_limit: int = 3,
347
+ ) -> tuple[str, dict]:
348
+ files = tracked_files(repo) if files is None else files
349
+ findings: list[Finding] = []
350
+ findings += contradictions(ledger)
351
+ findings += dead_scopes(ledger, files)
352
+ findings += redundant(ledger, files)
353
+ findings += diverged(ledger)
354
+ findings += anchor_drift(repo, ledger)
355
+ probed: dict = {}
356
+ if record:
357
+ stale, probed = run_probes(repo, ledger, limit=probe_limit)
358
+ findings += stale
359
+
360
+ cov = coverage(ledger, files)
361
+ dbt = debt(ledger)
362
+ rules = [r for r in ledger.active("rule")]
363
+ facts = [r for r in ledger.active("fact")]
364
+ waivers = [r for r in ledger.active("waiver")]
365
+ unreviewed = [r for r in facts if not r.get("reviewed", True)]
366
+ errors = [f for f in findings if f.level == "error"]
367
+
368
+ lines: list[str] = []
369
+ lines.append(f"canon audit · snapshot {ledger.snapshot()}")
370
+ hard_count = sum(1 for r in rules if r.sev == "hard")
371
+ lines.append(
372
+ f"{len(rules)} rule(s) ({hard_count} hard), "
373
+ f"{len(facts)} fact(s), {len(waivers)} waiver(s)"
374
+ )
375
+ lines.append("")
376
+ lines.append(
377
+ f"normative debt {dbt['unproven']}/{dbt['hard']} hard rules have no mechanical check "
378
+ f"({dbt['ratio']}%)"
379
+ )
380
+ lines.append(
381
+ f"coverage {cov['percent']}% of {cov['files']} tracked files governed by a hard rule"
382
+ )
383
+ lines.append(f"findings {len(errors)} error(s), {len(findings) - len(errors)} warning(s)")
384
+ if unreviewed:
385
+ lines.append(
386
+ f"unreviewed {len(unreviewed)} fact(s) learned by agents await a human: "
387
+ + ", ".join(r.id for r in unreviewed[:8])
388
+ )
389
+ if cov["uncovered"] and cov["examples"]:
390
+ lines.append("")
391
+ lines.append("ungoverned paths (first 12):")
392
+ for p in cov["examples"]:
393
+ lines.append(f" {p}")
394
+ if findings:
395
+ lines.append("")
396
+ for f in findings:
397
+ lines.append(str(f))
398
+ if dbt["ids"]:
399
+ lines.append("")
400
+ lines.append("unproven hard rules: " + ", ".join(dbt["ids"]))
401
+ if record:
402
+ lines.append("")
403
+ lines.append(f"probes: {len(probed)} checked this run")
404
+
405
+ payload = {
406
+ "snapshot": ledger.snapshot(),
407
+ "findings": [f.to_dict() for f in findings],
408
+ "coverage": cov,
409
+ "debt": dbt,
410
+ "counts": {
411
+ "rules": len(rules),
412
+ "facts": len(facts),
413
+ "waivers": len(waivers),
414
+ "unreviewed": len(unreviewed),
415
+ },
416
+ "ok": not errors,
417
+ }
418
+ return "\n".join(lines) + "\n", payload