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/select.py ADDED
@@ -0,0 +1,173 @@
1
+ """Selection: which rules govern this change, and what does it cost to say so.
2
+
3
+ The core claim of this module is that applicability is *decidable and exact*.
4
+ A rule governs a change iff the rule's operation set meets the change's and the
5
+ rule's path scope meets at least one changed path. No embeddings, no top-k, no
6
+ similarity threshold. If a rule governs the change it is returned; if it is
7
+ returned it governs the change. The index below only prunes candidates; the
8
+ oracle is the filter, and the test suite checks that the two agree.
9
+
10
+ Ordering is declared, not positional. Severity is the primary key, then
11
+ specificity (deeper scope = narrower jurisdiction wins), then id for stability.
12
+ That is a total order, so two machines produce byte-identical briefs.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass, field
18
+
19
+ from .gitx import Footprint
20
+ from .ledger import Ledger, Rec
21
+ from .scope import Scope, coerce_scope
22
+
23
+ __all__ = [
24
+ "Jurisdiction",
25
+ "jurisdiction",
26
+ "applies",
27
+ "applicable",
28
+ "all_rules",
29
+ "rank",
30
+ "select",
31
+ "estimate_tokens",
32
+ "token_budget",
33
+ ]
34
+
35
+ _SEV_RANK = {"hard": 3, "soft": 2, "advice": 1}
36
+
37
+
38
+ @dataclass
39
+ class Jurisdiction:
40
+ """A rule together with the evidence that it applies here."""
41
+
42
+ rec: Rec
43
+ scope: Scope
44
+ matched: list[str] = field(default_factory=list)
45
+ reason: str = ""
46
+
47
+ @property
48
+ def id(self) -> str:
49
+ return self.rec.id
50
+
51
+ @property
52
+ def sev(self) -> str:
53
+ return self.rec.sev
54
+
55
+ def cost(self) -> int:
56
+ """Rough token cost of showing this rule in a brief."""
57
+ rec = self.rec
58
+ body = rec.text + " " + rec.why
59
+ chk = rec.get("check")
60
+ if isinstance(chk, str):
61
+ body += " " + chk
62
+ elif isinstance(chk, dict):
63
+ body += " " + str(chk.get("run", ""))
64
+ return estimate_tokens(body) + 8 # + id / marker overhead
65
+
66
+
67
+ def jurisdiction(rec: Rec) -> Scope:
68
+ return coerce_scope(rec.get("scope"))
69
+
70
+
71
+ def estimate_tokens(text: str) -> int:
72
+ """Deliberately cheap and conservative: ~4 characters per token."""
73
+ return (len(text) + 3) // 4
74
+
75
+
76
+ def applies(scope: Scope, fp: Footprint) -> list[str] | None:
77
+ """Changed paths governed by `scope`, or None if the rule is out of court."""
78
+ if scope.ops and not (set(scope.ops) & fp.ops):
79
+ return None
80
+ if scope.covers_all():
81
+ return fp.paths()
82
+ matched = [c.path for c in fp.changes if scope.matches(c.path)]
83
+ return matched or None
84
+
85
+
86
+ def applicable(
87
+ ledger: Ledger,
88
+ fp: Footprint,
89
+ *,
90
+ kinds: tuple[str, ...] = ("rule", "fact"),
91
+ ) -> list[Jurisdiction]:
92
+ out: list[Jurisdiction] = []
93
+ for rec in ledger.active():
94
+ if rec.kind not in kinds:
95
+ continue
96
+ scope = jurisdiction(rec)
97
+ matched = applies(scope, fp)
98
+ if matched is None:
99
+ continue
100
+ out.append(Jurisdiction(rec=rec, scope=scope, matched=matched))
101
+ out.sort(key=rank)
102
+ return out
103
+
104
+
105
+ def all_rules(
106
+ ledger: Ledger, *, kinds: tuple[str, ...] = ("rule", "fact")
107
+ ) -> list[Jurisdiction]:
108
+ """Every active record, unscoped by a footprint. Used to orient a session."""
109
+ out = [
110
+ Jurisdiction(rec=rec, scope=jurisdiction(rec), matched=[])
111
+ for rec in ledger.active()
112
+ if rec.kind in kinds
113
+ ]
114
+ out.sort(key=rank)
115
+ return out
116
+
117
+
118
+ def rank(j: Jurisdiction) -> tuple:
119
+ """Total order. Deterministic across machines and runs."""
120
+ return (-_SEV_RANK.get(j.sev, 0), -j.scope.specificity, j.id)
121
+
122
+
123
+ def token_budget(rules: list[Jurisdiction], max_tokens: int | None) -> tuple[list, list]:
124
+ """Keep the most important rules inside a budget.
125
+
126
+ Invariant (tested): a `hard` rule is never dropped. If the budget cannot
127
+ hold them all, the brief reports the overflow instead of silently cutting —
128
+ silent truncation is how a rulebook becomes a lie.
129
+ """
130
+ if max_tokens is None:
131
+ return list(rules), []
132
+ kept: list[Jurisdiction] = []
133
+ omitted: list[Jurisdiction] = []
134
+ used = 0
135
+ for j in rules:
136
+ cost = j.cost()
137
+ if j.sev == "hard" or used + cost <= max_tokens:
138
+ kept.append(j)
139
+ used += cost
140
+ else:
141
+ omitted.append(j)
142
+ return kept, omitted
143
+
144
+
145
+ def select(
146
+ ledger: Ledger,
147
+ fp: Footprint,
148
+ *,
149
+ max_tokens: int | None = None,
150
+ kinds: tuple[str, ...] = ("rule", "fact"),
151
+ include_all: bool = False,
152
+ ) -> tuple[list[Jurisdiction], list[Jurisdiction]]:
153
+ js = applicable(ledger, fp, kinds=kinds)
154
+ if include_all:
155
+ return js, []
156
+ return token_budget(js, max_tokens)
157
+
158
+
159
+ def uncovered(
160
+ ledger: Ledger, files: list[str], *, min_sev: str = "hard"
161
+ ) -> list[str]:
162
+ """Tracked files that no rule of at least `min_sev` governs.
163
+
164
+ This is the empirical coverage measure: over the repository that exists,
165
+ not over all possible strings. Honest, cheap and falsifiable.
166
+ """
167
+ scopes: list[Scope] = []
168
+ threshold = _SEV_RANK.get(min_sev, 3)
169
+ for rec in ledger.active("rule"):
170
+ if _SEV_RANK.get(rec.sev, 0) < threshold:
171
+ continue
172
+ scopes.append(jurisdiction(rec))
173
+ return [f for f in files if not any(s.matches(f) for s in scopes)]
canon/verify.py ADDED
@@ -0,0 +1,399 @@
1
+ """Evaluation: turning a rule into a verdict, honestly.
2
+
3
+ Verdicts are three-valued. `PASS`, `FAIL`, and `UNKNOWN`. There is no fourth
4
+ state in which a rule quietly becomes true because nobody looked. That
5
+ asymmetry is the point: the failure mode of a markdown rulebook is that
6
+ everything *appears* satisfied because nothing is ever evaluated.
7
+
8
+ `UNKNOWN` is not an error. It is the correct answer for a rule that has no
9
+ mechanical predicate, and it is reported as a number rather than hidden. Under
10
+ `--strict` it blocks the change, because a human decided it should.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import os
17
+ import re
18
+ import subprocess
19
+ import time
20
+ from dataclasses import dataclass, field
21
+ from enum import Enum
22
+ from pathlib import Path
23
+
24
+ from .gitx import Footprint
25
+ from .ledger import Ledger
26
+ from .select import Jurisdiction
27
+
28
+ __all__ = ["Verdict", "Evidence", "Result", "Outcome", "run", "aggregate",
29
+ "active_waiver", "has_predicate"]
30
+
31
+
32
+ class Verdict(str, Enum):
33
+ PASS = "PASS"
34
+ FAIL = "FAIL"
35
+ UNKNOWN = "UNKNOWN"
36
+ WAIVED = "WAIVED"
37
+
38
+
39
+ @dataclass
40
+ class Evidence:
41
+ kind: str
42
+ detail: str = ""
43
+ exit: int | None = None
44
+ ms: int = 0
45
+ out: str = ""
46
+ at: str = ""
47
+ sha: str = ""
48
+
49
+ def to_dict(self) -> dict:
50
+ return {
51
+ "kind": self.kind,
52
+ "detail": self.detail,
53
+ "exit": self.exit,
54
+ "ms": self.ms,
55
+ "out": self.out,
56
+ "at": self.at,
57
+ "sha": self.sha,
58
+ }
59
+
60
+ @classmethod
61
+ def make(
62
+ cls,
63
+ kind: str,
64
+ detail: str = "",
65
+ exit_code: int | None = None,
66
+ ms: int = 0,
67
+ out: str = "",
68
+ ) -> "Evidence":
69
+ out = (out or "")[:2000]
70
+ return cls(
71
+ kind=kind,
72
+ detail=detail,
73
+ exit=exit_code,
74
+ ms=ms,
75
+ out=out,
76
+ at=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
77
+ sha="sha256:" + hashlib.sha256(out.encode("utf-8")).hexdigest()[:16],
78
+ )
79
+
80
+
81
+ @dataclass
82
+ class Result:
83
+ jurisdiction: Jurisdiction
84
+ verdict: Verdict
85
+ evidence: Evidence
86
+ note: str = ""
87
+
88
+ @property
89
+ def id(self) -> str:
90
+ return self.jurisdiction.id
91
+
92
+ @property
93
+ def sev(self) -> str:
94
+ return self.jurisdiction.sev
95
+
96
+ def to_dict(self) -> dict:
97
+ return {
98
+ "id": self.id,
99
+ "rev": self.jurisdiction.rec.rev,
100
+ "hash": self.jurisdiction.rec.hash,
101
+ "sev": self.sev,
102
+ "verdict": self.verdict.value,
103
+ "text": self.jurisdiction.rec.text,
104
+ "note": self.note,
105
+ "evidence": self.evidence.to_dict(),
106
+ }
107
+
108
+
109
+ @dataclass
110
+ class Outcome:
111
+ results: list[Result] = field(default_factory=list)
112
+ strict: bool = False
113
+
114
+ @property
115
+ def counts(self) -> dict[str, int]:
116
+ c = {v.value: 0 for v in Verdict}
117
+ for r in self.results:
118
+ c[r.verdict.value] += 1
119
+ return c
120
+
121
+ @property
122
+ def failures(self) -> list[Result]:
123
+ return [r for r in self.results if r.verdict is Verdict.FAIL]
124
+
125
+ @property
126
+ def blocking(self) -> list[Result]:
127
+ """Failures that make the change invalid.
128
+
129
+ Severity is load-bearing. A hard rule is a gate; a soft rule is a
130
+ reviewer's comment; `advice` is a tip. `--strict` promotes soft to
131
+ blocking, which is how a team can tighten without editing rules.
132
+ """
133
+ if self.strict:
134
+ return self.failures
135
+ return [r for r in self.failures if r.sev == "hard"]
136
+
137
+ @property
138
+ def advisories(self) -> list[Result]:
139
+ blocking = {id(r) for r in self.blocking}
140
+ return [r for r in self.failures if id(r) not in blocking]
141
+
142
+ @property
143
+ def unknowns(self) -> list[Result]:
144
+ return [r for r in self.results if r.verdict is Verdict.UNKNOWN]
145
+
146
+ @property
147
+ def ok(self) -> bool:
148
+ if self.blocking:
149
+ return False
150
+ if self.strict and self.unknowns:
151
+ return False
152
+ return True
153
+
154
+ def exit_code(self) -> int:
155
+ return 0 if self.ok else 1
156
+
157
+ def summary(self) -> str:
158
+ c = self.counts
159
+ bits: list[str] = []
160
+ if c["PASS"]:
161
+ bits.append(f"{c['PASS']} pass")
162
+ if self.blocking:
163
+ bits.append(f"{len(self.blocking)} fail")
164
+ if self.advisories:
165
+ bits.append(f"{len(self.advisories)} advisory")
166
+ if c["UNKNOWN"]:
167
+ bits.append(f"{c['UNKNOWN']} unknown")
168
+ if c["WAIVED"]:
169
+ bits.append(f"{c['WAIVED']} waived")
170
+ return " · ".join(bits) or "nothing to check"
171
+
172
+
173
+ def aggregate(results: list[Result], strict: bool = False) -> Outcome:
174
+ return Outcome(results=results, strict=strict)
175
+
176
+
177
+ def has_predicate(rec) -> bool:
178
+ """Can this rule ever be FAIL? A `manual` check cannot; a `none` cannot."""
179
+ spec = rec.get("check")
180
+ if isinstance(spec, str):
181
+ return bool(spec.strip())
182
+ if isinstance(spec, dict):
183
+ kind = str(spec.get("kind", "shell"))
184
+ return kind not in ("none", "manual") and bool(str(spec.get("run", "")).strip())
185
+ return False
186
+
187
+
188
+ def active_waiver(ledger: Ledger, rid: str, today: str | None = None) -> Rec | None:
189
+ today = today or time.strftime("%Y-%m-%d", time.gmtime())
190
+ for rec in ledger.active("waiver"):
191
+ if str(rec.get("waives", "")) != rid:
192
+ continue
193
+ expires = str(rec.get("expires", "") or "")
194
+ if expires and expires < today:
195
+ continue
196
+ return rec
197
+ return None
198
+
199
+
200
+ def _env(repo: Path, j: Jurisdiction, fp: Footprint) -> dict[str, str]:
201
+ env = dict(os.environ)
202
+ env.update(
203
+ {
204
+ "CANON": "1",
205
+ "CANON_RULE": j.id,
206
+ "CANON_SEV": j.sev,
207
+ "CANON_REPO": str(repo),
208
+ "CANON_PATHS": " ".join(j.matched),
209
+ "CANON_BASE": fp.base,
210
+ "CANON_MESSAGE": fp.message,
211
+ "CANON_FOOTPRINT": fp.digest(),
212
+ }
213
+ )
214
+ return env
215
+
216
+
217
+ def _shell(
218
+ run: str, repo: Path, env: dict[str, str], expect: str, timeout: int
219
+ ) -> tuple[Verdict, Evidence]:
220
+ started = time.monotonic()
221
+ try:
222
+ proc = subprocess.run(
223
+ run,
224
+ shell=True,
225
+ cwd=str(repo),
226
+ env=env,
227
+ capture_output=True,
228
+ text=True,
229
+ timeout=timeout,
230
+ )
231
+ except subprocess.TimeoutExpired:
232
+ return (
233
+ Verdict.UNKNOWN,
234
+ Evidence.make("shell", f"timed out after {timeout}s", None, timeout * 1000),
235
+ )
236
+ except OSError as exc:
237
+ return Verdict.UNKNOWN, Evidence.make("shell", f"could not run: {exc}")
238
+ ms = int((time.monotonic() - started) * 1000)
239
+ out = (proc.stdout or "") + (proc.stderr or "")
240
+ verdict = _judge_exit(proc.returncode, out, expect)
241
+ return verdict, Evidence.make("shell", run, proc.returncode, ms, out)
242
+
243
+
244
+ def _judge_exit(code: int, out: str, expect: str) -> Verdict:
245
+ expect = (expect or "exit0").strip()
246
+ if expect.startswith("exit"):
247
+ want = expect[4:].strip() or "0"
248
+ return Verdict.PASS if str(code) == want else Verdict.FAIL
249
+ if expect == "empty":
250
+ return Verdict.PASS if not out.strip() else Verdict.FAIL
251
+ if expect.startswith("output:"):
252
+ pattern = expect[len("output:") :]
253
+ return Verdict.PASS if re.search(pattern, out) else Verdict.FAIL
254
+ return Verdict.PASS if code == 0 else Verdict.FAIL
255
+
256
+
257
+ def _grep(
258
+ j: Jurisdiction, repo: Path, pattern: str, expect: str
259
+ ) -> tuple[Verdict, Evidence]:
260
+ try:
261
+ rx = re.compile(pattern)
262
+ except re.error as exc:
263
+ return Verdict.UNKNOWN, Evidence.make("grep", f"bad regex: {exc}")
264
+ hits: list[str] = []
265
+ for rel in j.matched:
266
+ path = repo / rel
267
+ if not path.is_file():
268
+ continue
269
+ try:
270
+ text = path.read_text(encoding="utf-8", errors="replace")
271
+ except OSError:
272
+ continue
273
+ for lineno, line in enumerate(text.splitlines(), 1):
274
+ if rx.search(line):
275
+ hits.append(f"{rel}:{lineno}: {line.strip()[:160]}")
276
+ found = bool(hits)
277
+ want = (expect or "match") != "no-match"
278
+ ok = found == want
279
+ detail = f"grep {pattern!r} -> {'found' if found else 'absent'} in {len(j.matched)} file(s)"
280
+ return (
281
+ Verdict.PASS if ok else Verdict.FAIL,
282
+ Evidence.make("grep", detail, 0 if ok else 1, 0, "\n".join(hits[:20])),
283
+ )
284
+
285
+
286
+ def _path(j: Jurisdiction, repo: Path, spec: str, expect: str) -> tuple[Verdict, Evidence]:
287
+ want_exists = (expect or "exists") != "absent"
288
+ target = repo / spec
289
+ exists = target.exists()
290
+ ok = exists == want_exists
291
+ return (
292
+ Verdict.PASS if ok else Verdict.FAIL,
293
+ Evidence.make(
294
+ "path", f"{spec} {'exists' if exists else 'missing'}", 0 if ok else 1
295
+ ),
296
+ )
297
+
298
+
299
+ def _diff_packet(j: Jurisdiction, fp: Footprint, limit: int = 12000) -> str:
300
+ lines = [
301
+ f"RULE {j.id} [{j.sev}]: {j.rec.text}",
302
+ f"SCOPE: {j.scope.describe()}",
303
+ ]
304
+ if j.rec.why:
305
+ lines.append(f"RATIONALE: {j.rec.why}")
306
+ lines.append("CHANGED PATHS:")
307
+ lines.extend(f" {c.op}: {c.path}" for c in fp.changes)
308
+ if fp.message:
309
+ lines.append(f"COMMIT MESSAGE:\n{fp.message}")
310
+ return "\n".join(lines)[:limit]
311
+
312
+
313
+ def _judge(
314
+ j: Jurisdiction, fp: Footprint, repo: Path, cmd: str, env: dict[str, str], timeout: int
315
+ ) -> tuple[Verdict, Evidence]:
316
+ packet = _diff_packet(j, fp)
317
+ started = time.monotonic()
318
+ try:
319
+ proc = subprocess.run(
320
+ cmd,
321
+ shell=True,
322
+ cwd=str(repo),
323
+ env=env,
324
+ input=packet,
325
+ capture_output=True,
326
+ text=True,
327
+ timeout=timeout,
328
+ )
329
+ except subprocess.TimeoutExpired:
330
+ return Verdict.UNKNOWN, Evidence.make("judge", f"timed out after {timeout}s")
331
+ except OSError as exc:
332
+ return Verdict.UNKNOWN, Evidence.make("judge", f"could not run: {exc}")
333
+ ms = int((time.monotonic() - started) * 1000)
334
+ out = (proc.stdout or "") + (proc.stderr or "")
335
+ verdict = Verdict.PASS if proc.returncode == 0 else Verdict.FAIL
336
+ return verdict, Evidence.make("judge", cmd, proc.returncode, ms, out)
337
+
338
+
339
+ def run(
340
+ j: Jurisdiction,
341
+ fp: Footprint,
342
+ repo: str | Path,
343
+ *,
344
+ ledger: Ledger | None = None,
345
+ timeout: int | None = None,
346
+ run_judges: bool = True,
347
+ ) -> Result:
348
+ repo = Path(repo)
349
+ rec = j.rec
350
+
351
+ if ledger is not None:
352
+ waiver = active_waiver(ledger, j.id)
353
+ if waiver is not None:
354
+ return Result(
355
+ j,
356
+ Verdict.WAIVED,
357
+ Evidence.make("waiver", f"waived by {waiver.id}"),
358
+ note=waiver.text,
359
+ )
360
+
361
+ spec = rec.get("check")
362
+ if spec is None:
363
+ return Result(
364
+ j,
365
+ Verdict.UNKNOWN,
366
+ Evidence.make("none", "no mechanical check"),
367
+ note="declared, not proven",
368
+ )
369
+ if isinstance(spec, str):
370
+ spec = {"run": spec}
371
+ if not isinstance(spec, dict):
372
+ return Result(j, Verdict.UNKNOWN, Evidence.make("none", "malformed check"))
373
+
374
+ kind = str(spec.get("kind", "shell"))
375
+ rn = str(spec.get("run", ""))
376
+ expect = str(spec.get("expect", ""))
377
+ tmo = int(spec.get("timeout", timeout or 180))
378
+ env = _env(repo, j, fp)
379
+
380
+ if kind == "none":
381
+ return Result(j, Verdict.UNKNOWN, Evidence.make("none", "no mechanical check"))
382
+ if kind == "manual":
383
+ return Result(
384
+ j,
385
+ Verdict.UNKNOWN,
386
+ Evidence.make("manual", "requires human judgement"),
387
+ note="use `canon waive` to record a dispensation",
388
+ )
389
+ if kind == "grep":
390
+ v, e = _grep(j, repo, rn, expect)
391
+ elif kind == "path":
392
+ v, e = _path(j, repo, rn, expect)
393
+ elif kind == "judge":
394
+ if not run_judges:
395
+ return Result(j, Verdict.UNKNOWN, Evidence.make("judge", "skipped"))
396
+ v, e = _judge(j, fp, repo, rn, env, tmo)
397
+ else:
398
+ v, e = _shell(rn, repo, env, expect, tmo)
399
+ return Result(j, v, e)