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/gitx.py ADDED
@@ -0,0 +1,263 @@
1
+ """Git as the observation surface, and git notes as the evidence store.
2
+
3
+ The footprint is the reason this can be exact instead of approximate. A
4
+ retrieval system has to *guess* what is relevant from a task description. A
5
+ repository already knows what changed: the diff is the ground truth about the
6
+ change, and a path is a key into the rule set. So relevance is not a similarity
7
+ search, it is a set membership question.
8
+
9
+ Evidence is written to `refs/notes/canon`, never to the working tree. A commit
10
+ can then carry a proof of what was checked without the repository becoming
11
+ dirty — which is the whole reason the old approach annoyed people.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import os
18
+ import subprocess
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+
22
+ __all__ = [
23
+ "Change",
24
+ "Footprint",
25
+ "git",
26
+ "repo_root",
27
+ "is_repo",
28
+ "tracked_files",
29
+ "footprint",
30
+ "note_put",
31
+ "note_get",
32
+ "note_list",
33
+ "NoteError",
34
+ ]
35
+
36
+ _OPS = {"write", "delete", "commit", "pr", "release", "read", "exec"}
37
+
38
+
39
+ class NoteError(Exception):
40
+ pass
41
+
42
+
43
+ def git(repo: str | Path, *args: str, check: bool = False, timeout: int = 60) -> str:
44
+ proc = subprocess.run(
45
+ ["git", "-C", str(repo), *args],
46
+ capture_output=True,
47
+ text=True,
48
+ timeout=timeout,
49
+ )
50
+ if check and proc.returncode != 0:
51
+ raise NoteError(
52
+ f"git {' '.join(args)} failed ({proc.returncode}): {proc.stderr.strip()}"
53
+ )
54
+ return proc.stdout
55
+
56
+
57
+ def is_repo(path: str | Path) -> bool:
58
+ try:
59
+ out = git(path, "rev-parse", "--is-inside-work-tree")
60
+ except (OSError, subprocess.SubprocessError):
61
+ return False
62
+ return out.strip() == "true"
63
+
64
+
65
+ def repo_root(path: str | Path) -> Path:
66
+ out = git(path, "rev-parse", "--show-toplevel")
67
+ root = out.strip()
68
+ if not root:
69
+ raise NoteError(f"{path} is not inside a git repository")
70
+ return Path(root)
71
+
72
+
73
+ def has_head(repo: str | Path) -> bool:
74
+ return git(repo, "rev-parse", "--verify", "-q", "HEAD").strip() != ""
75
+
76
+
77
+ def tracked_files(repo: str | Path, include_canon: bool = False) -> list[str]:
78
+ out = git(repo, "ls-files", "-z", "--cached")
79
+ files = [p for p in out.split("\0") if p]
80
+ if include_canon:
81
+ return files
82
+ return [f for f in files if f != ".canon" and not f.startswith(".canon/")]
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class Change:
87
+ path: str
88
+ op: str # "write" | "delete"
89
+
90
+ def __str__(self) -> str: # pragma: no cover
91
+ return f"{self.op[0].upper()} {self.path}"
92
+
93
+
94
+ @dataclass
95
+ class Footprint:
96
+ """What change is being judged."""
97
+
98
+ changes: list[Change] = field(default_factory=list)
99
+ ops: set[str] = field(default_factory=set)
100
+ message: str = ""
101
+ base: str = "HEAD"
102
+ staged: bool = False
103
+ revrange: str = ""
104
+
105
+ def paths(self) -> list[str]:
106
+ return [c.path for c in self.changes]
107
+
108
+ def live_paths(self) -> list[str]:
109
+ return [c.path for c in self.changes if c.op != "delete"]
110
+
111
+ def digest(self) -> str:
112
+ body = "\n".join(sorted(f"{c.op}:{c.path}" for c in self.changes))
113
+ body += "\nops:" + ",".join(sorted(self.ops))
114
+ return hashlib.sha256(body.encode("utf-8")).hexdigest()[:16]
115
+
116
+ def summary(self) -> str:
117
+ n_write = sum(1 for c in self.changes if c.op == "write")
118
+ n_del = sum(1 for c in self.changes if c.op == "delete")
119
+ bits = []
120
+ if n_write:
121
+ bits.append(f"{n_write} changed")
122
+ if n_del:
123
+ bits.append(f"{n_del} deleted")
124
+ if not bits:
125
+ bits.append("no file changes")
126
+ return ", ".join(bits)
127
+
128
+
129
+ def _status_map(
130
+ repo: str | Path, args: list[str]
131
+ ) -> list[Change]:
132
+ out = git(repo, *args)
133
+ parts = [p for p in out.split("\0")]
134
+ if parts and parts[-1] == "":
135
+ parts.pop()
136
+ changes: list[Change] = []
137
+ i = 0
138
+ while i + 1 < len(parts):
139
+ status = parts[i].strip()
140
+ path = parts[i + 1]
141
+ i += 2
142
+ if not status:
143
+ continue
144
+ letter = status[0]
145
+ if letter == "D":
146
+ changes.append(Change(path=path, op="delete"))
147
+ elif letter in ("A", "M", "T", "C", "U", "X"):
148
+ changes.append(Change(path=path, op="write"))
149
+ else: # R and anything unexpected: treat as a write
150
+ changes.append(Change(path=path, op="write"))
151
+ return changes
152
+
153
+
154
+ def footprint(
155
+ repo: str | Path,
156
+ *,
157
+ base: str = "HEAD",
158
+ staged: bool = False,
159
+ revrange: str = "",
160
+ extra_ops: set[str] | None = None,
161
+ paths: list[str] | None = None,
162
+ message: str = "",
163
+ include_canon: bool = False,
164
+ ) -> Footprint:
165
+ """Observe the change.
166
+
167
+ Order of precedence: explicit `paths` > `revrange` > `staged` > worktree.
168
+ Untracked files count as writes: an agent creating a new file has changed
169
+ the repository, and a rule may well govern that file.
170
+ """
171
+ repo = Path(repo)
172
+ ops: set[str] = set(extra_ops or ())
173
+ changes: list[Change] = []
174
+
175
+ if paths is not None:
176
+ changes = [
177
+ Change(p, "delete" if not (repo / p).exists() else "write") for p in paths
178
+ ]
179
+ elif revrange:
180
+ changes = _status_map(
181
+ repo, ["diff", "--name-status", "-z", "--no-renames", revrange]
182
+ )
183
+ elif staged:
184
+ if has_head(repo):
185
+ changes = _status_map(
186
+ repo, ["diff", "--cached", "--name-status", "-z", "--no-renames", "HEAD"]
187
+ )
188
+ else:
189
+ changes = _status_map(
190
+ repo, ["diff", "--cached", "--name-status", "-z", "--no-renames"]
191
+ )
192
+ else:
193
+ if has_head(repo):
194
+ changes = _status_map(
195
+ repo, ["diff", "--name-status", "-z", "--no-renames", base]
196
+ )
197
+ else:
198
+ changes = _status_map(
199
+ repo, ["diff", "--cached", "--name-status", "-z", "--no-renames"]
200
+ )
201
+ for p in git(repo, "ls-files", "-o", "--exclude-standard", "-z").split("\0"):
202
+ if p:
203
+ changes.append(Change(p, "write"))
204
+
205
+ if message:
206
+ ops.add("commit")
207
+
208
+ # The rulebook's own files are not the change under judgement. Otherwise
209
+ # every `canon add` would look like a change to the repository and every
210
+ # universal rule would fire on the rulebook itself.
211
+ changes = [
212
+ c
213
+ for c in changes
214
+ if include_canon or not (c.path == ".canon" or c.path.startswith(".canon/"))
215
+ ]
216
+
217
+ ops |= {c.op for c in changes}
218
+ # de-duplicate while keeping order
219
+ seen: set[tuple[str, str]] = set()
220
+ uniq: list[Change] = []
221
+ for c in changes:
222
+ key = (c.path, c.op)
223
+ if key in seen:
224
+ continue
225
+ seen.add(key)
226
+ uniq.append(c)
227
+
228
+ return Footprint(
229
+ changes=uniq,
230
+ ops=ops,
231
+ message=message,
232
+ base=base,
233
+ staged=staged,
234
+ revrange=revrange,
235
+ )
236
+
237
+
238
+ # -- git notes --------------------------------------------------------------
239
+
240
+
241
+ def note_put(repo: str | Path, commit: str, payload: str, ref: str = "canon") -> None:
242
+ git(repo, "notes", f"--ref={ref}", "add", "-f", "-m", payload, commit, check=True)
243
+
244
+
245
+ def note_get(repo: str | Path, commit: str, ref: str = "canon") -> str:
246
+ proc = subprocess.run(
247
+ ["git", "-C", str(repo), "notes", f"--ref={ref}", "show", commit],
248
+ capture_output=True,
249
+ text=True,
250
+ )
251
+ if proc.returncode != 0:
252
+ raise NoteError(proc.stderr.strip() or "no note")
253
+ return proc.stdout
254
+
255
+
256
+ def note_list(repo: str | Path, ref: str = "canon") -> dict[str, str]:
257
+ out = git(repo, "notes", f"--ref={ref}", "list")
258
+ mapping: dict[str, str] = {}
259
+ for line in out.splitlines():
260
+ bits = line.split()
261
+ if len(bits) == 2:
262
+ mapping[bits[0]] = bits[1]
263
+ return mapping
canon/ledger.py ADDED
@@ -0,0 +1,418 @@
1
+ """The ledger: an append-only, content-addressed constraint store.
2
+
3
+ Why a log and not a document
4
+ ----------------------------
5
+ Two agents editing the same markdown file produce a merge conflict, and a merge
6
+ conflict is a *human* being woken up. Two agents appending to the same JSONL
7
+ file produce two lines, and two lines are a valid state. Give git
8
+
9
+ .canon/.gitattributes: *.jsonl merge=union
10
+
11
+ and concurrent writers never conflict again: git concatenates, and this module
12
+ normalises. Normalisation is where the algebra lives.
13
+
14
+ The state is a map `id -> record`. Every record is content-addressed (its
15
+ `hash` is the SHA-256 of its canonical JSON), so duplicate lines are inert and
16
+ re-applying a batch is idempotent. Within an id, the winner is the maximum
17
+ under the total order
18
+
19
+ (lamport, rev, hash)
20
+
21
+ which depends only on the records themselves, never on arrival order. Merge is
22
+ therefore pointwise max: commutative, associative and idempotent. Repeated
23
+ merges of any permutation of any partition of the input converge to the same
24
+ state. Losing revisions are *retained* — a CRDT can converge without losing
25
+ intent, so `canon audit` can still show that two people edited one rule.
26
+
27
+ That is the whole trick, and it is why the file can be the database.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import secrets
36
+ import time
37
+ from dataclasses import dataclass, field
38
+ from pathlib import Path
39
+ from typing import Any, Iterable, Iterator
40
+
41
+ __all__ = ["Ledger", "Rec", "LIMITS", "SEVERITIES", "KINDS", "canonical", "record_hash"]
42
+
43
+ KINDS = ("rule", "fact", "note", "waiver", "meta")
44
+ SEVERITIES = ("hard", "soft", "advice")
45
+ STATUSES = ("active", "retired")
46
+ REQUIRED = ("v", "id", "kind", "text")
47
+
48
+ # Hard caps keep the store honest: a rule that does not fit in a tweet does not
49
+ # get read. OptMem caps a memory at 280 bytes for the same reason.
50
+ LIMITS = {
51
+ "text": 400,
52
+ "why": 400,
53
+ "check_run": 400,
54
+ "id": 64,
55
+ }
56
+
57
+
58
+ def canonical(obj: Any) -> bytes:
59
+ """Canonical JSON: sorted keys, no whitespace, UTF-8. Byte-stable."""
60
+ return json.dumps(
61
+ obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False
62
+ ).encode("utf-8")
63
+
64
+
65
+ def record_hash(rec: dict) -> str:
66
+ body = {k: v for k, v in rec.items() if k not in ("hash", "_seen")}
67
+ return "sha256:" + hashlib.sha256(canonical(body)).hexdigest()
68
+
69
+
70
+ def _now() -> str:
71
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
72
+
73
+
74
+ class LedgerError(Exception):
75
+ pass
76
+
77
+
78
+ @dataclass
79
+ class Rec:
80
+ """A record plus everything derived from it."""
81
+
82
+ data: dict
83
+ hash: str
84
+ prior: list[str] = field(default_factory=list) # losing revisions, retained
85
+
86
+ @property
87
+ def id(self) -> str:
88
+ return str(self.data.get("id", ""))
89
+
90
+ @property
91
+ def kind(self) -> str:
92
+ return str(self.data.get("kind", "rule"))
93
+
94
+ @property
95
+ def text(self) -> str:
96
+ return str(self.data.get("text", ""))
97
+
98
+ @property
99
+ def why(self) -> str:
100
+ return str(self.data.get("why", "") or "")
101
+
102
+ @property
103
+ def sev(self) -> str:
104
+ s = str(self.data.get("sev") or ("hard" if self.kind == "rule" else "advice"))
105
+ return s if s in SEVERITIES else "soft"
106
+
107
+ @property
108
+ def status(self) -> str:
109
+ return str(self.data.get("status", "active"))
110
+
111
+ @property
112
+ def active(self) -> bool:
113
+ return self.status == "active"
114
+
115
+ @property
116
+ def rev(self) -> int:
117
+ try:
118
+ return int(self.data.get("rev", 1))
119
+ except (TypeError, ValueError):
120
+ return 1
121
+
122
+ @property
123
+ def lamport(self) -> int:
124
+ try:
125
+ return int(self.data.get("lamport", 0))
126
+ except (TypeError, ValueError):
127
+ return 0
128
+
129
+ def get(self, key: str, default: Any = None) -> Any:
130
+ return self.data.get(key, default)
131
+
132
+ def __getitem__(self, key: str) -> Any:
133
+ return self.data[key]
134
+
135
+ def to_json(self) -> dict:
136
+ return dict(self.data)
137
+
138
+
139
+ def _rev(rec: dict) -> int:
140
+ try:
141
+ return int(rec.get("rev", 1) or 1)
142
+ except (TypeError, ValueError):
143
+ return 1
144
+
145
+
146
+ def _order(rec: dict, h: str) -> tuple:
147
+ return (
148
+ int(rec.get("lamport", 0) or 0),
149
+ int(rec.get("rev", 1) or 1),
150
+ h,
151
+ )
152
+
153
+
154
+ class Ledger:
155
+ """The store. `load()` is cheap; records are validated lazily."""
156
+
157
+ def __init__(self, path: os.PathLike | str) -> None:
158
+ self.path = Path(path)
159
+ self._records: list[tuple[dict, str]] = []
160
+ self._state: dict[str, Rec] = {}
161
+ self._concurrent: dict[str, dict[int, list[str]]] = {}
162
+ self._by_hash: dict[str, dict] = {}
163
+ self.problems: list[str] = []
164
+
165
+ # -- construction ------------------------------------------------------
166
+ @classmethod
167
+ def open(cls, path: os.PathLike | str) -> "Ledger":
168
+ led = cls(path)
169
+ led.load()
170
+ return led
171
+
172
+ def load(self) -> None:
173
+ self._records.clear()
174
+ self._state.clear()
175
+ self._concurrent.clear()
176
+ self._by_hash.clear()
177
+ self.problems.clear()
178
+ if not self.path.exists():
179
+ return
180
+ text = self.path.read_text(encoding="utf-8")
181
+ for lineno, line in enumerate(text.splitlines(), 1):
182
+ line = line.strip()
183
+ if not line or line.startswith("#"):
184
+ continue
185
+ try:
186
+ rec = json.loads(line)
187
+ except json.JSONDecodeError as exc:
188
+ self.problems.append(f"line {lineno}: bad JSON ({exc.msg})")
189
+ continue
190
+ if not isinstance(rec, dict):
191
+ self.problems.append(f"line {lineno}: not an object")
192
+ continue
193
+ problem = validate(rec)
194
+ if problem:
195
+ self.problems.append(f"line {lineno}: {problem}")
196
+ continue
197
+ h = rec.get("hash") or record_hash(rec)
198
+ if h != record_hash(rec):
199
+ self.problems.append(f"line {lineno}: hash mismatch for {rec.get('id')}")
200
+ continue
201
+ rec = dict(rec, hash=h)
202
+ self._ingest(rec, h)
203
+ self._normalize()
204
+
205
+ def _ingest(self, rec: dict, h: str) -> None:
206
+ self._records.append((rec, h))
207
+ self._by_hash[h] = rec
208
+
209
+ def _normalize(self) -> None:
210
+ groups: dict[str, list[tuple[dict, str]]] = {}
211
+ for rec, h in self._records:
212
+ groups.setdefault(str(rec.get("id")), []).append((rec, h))
213
+ for rid, items in groups.items():
214
+ items.sort(key=lambda it: _order(it[0], it[1]))
215
+ win_rec, win_hash = items[-1]
216
+ prior = [h for _, h in items[:-1] if h != win_hash]
217
+ self._state[rid] = Rec(data=win_rec, hash=win_hash, prior=prior)
218
+
219
+ # A superseded revision is history, not conflict. Conflict is the
220
+ # same revision number claimed by two different records — which is
221
+ # exactly what two people editing one rule offline produce.
222
+ by_rev: dict[int, list[str]] = {}
223
+ for rec, h in items:
224
+ by_rev.setdefault(_rev(rec), []).append(h)
225
+ clashes = {rev: hs for rev, hs in by_rev.items() if len(set(hs)) > 1}
226
+ if clashes:
227
+ self._concurrent[rid] = clashes
228
+
229
+ # -- access ------------------------------------------------------------
230
+ def __len__(self) -> int:
231
+ return len(self._state)
232
+
233
+ def __iter__(self) -> Iterator[Rec]:
234
+ for rid in sorted(self._state):
235
+ yield self._state[rid]
236
+
237
+ def all(self) -> list[Rec]:
238
+ return list(self)
239
+
240
+ def get(self, rid: str) -> Rec | None:
241
+ return self._state.get(rid)
242
+
243
+ def active(self, kind: str | None = None) -> list[Rec]:
244
+ return [
245
+ r
246
+ for r in self
247
+ if r.active and (kind is None or r.kind == kind) and r.kind != "meta"
248
+ ]
249
+
250
+ def diverged(self) -> dict[str, list[str]]:
251
+ """Losing sides of a genuine concurrent revision, unacknowledged."""
252
+ out: dict[str, list[str]] = {}
253
+ for rid, clashes in self._concurrent.items():
254
+ rec = self._state.get(rid)
255
+ acked = set(rec.get("resolved_revs") or []) if rec else set()
256
+ losers: list[str] = []
257
+ for rev, hashes in clashes.items():
258
+ if rev in acked:
259
+ continue
260
+ losers.extend(h for h in hashes if rec is None or h != rec.hash)
261
+ if losers:
262
+ out[rid] = sorted(losers)
263
+ return out
264
+
265
+ def concurrent_revs(self, rid: str) -> list[int]:
266
+ return sorted(self._concurrent.get(rid, {}))
267
+
268
+ def revisions(self, rid: str) -> list[tuple[dict, str]]:
269
+ """Every record that ever claimed this id, oldest first."""
270
+ items = [(r, h) for r, h in self._records if str(r.get("id")) == rid]
271
+ items.sort(key=lambda it: _order(it[0], it[1]))
272
+ return items
273
+
274
+ def by_hash(self, h: str) -> dict | None:
275
+ return self._by_hash.get(h)
276
+
277
+ def hashes(self) -> set[str]:
278
+ return set(self._by_hash)
279
+
280
+ def max_lamport(self) -> int:
281
+ return max((r.lamport for r in self), default=0)
282
+
283
+ def next_id(self, prefix: str = "R") -> str:
284
+ for _ in range(16):
285
+ cand = new_id(prefix)
286
+ if cand not in self._state:
287
+ return cand
288
+ return new_id(prefix, size=12)
289
+
290
+ # -- mutation ----------------------------------------------------------
291
+ def append(self, rec: dict) -> Rec:
292
+ """Append one record. Idempotent: an existing hash is a no-op."""
293
+ rec = dict(rec)
294
+ rec.setdefault("v", 1)
295
+ rec.setdefault("ts", _now())
296
+ if "lamport" not in rec:
297
+ rec["lamport"] = self.max_lamport() + 1
298
+ if "rev" not in rec:
299
+ prior = self._state.get(str(rec.get("id")))
300
+ rec["rev"] = (prior.rev + 1) if prior else 1
301
+ problem = validate(rec)
302
+ if problem:
303
+ raise LedgerError(problem)
304
+ h = record_hash(rec)
305
+ if h in self._by_hash:
306
+ return Rec(data=self._by_hash[h], hash=h)
307
+ rec["hash"] = h
308
+ self.path.parent.mkdir(parents=True, exist_ok=True)
309
+ line = json.dumps(rec, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
310
+ with self.path.open("a", encoding="utf-8") as fh:
311
+ fh.write(line + "\n")
312
+ fh.flush()
313
+ os.fsync(fh.fileno())
314
+ self._ingest(rec, h)
315
+ self._normalize()
316
+ return self._state[str(rec["id"])]
317
+
318
+ def compact(self) -> int:
319
+ """Rewrite the file with winners only, sorted. Returns bytes saved.
320
+
321
+ Safe only when no other writer is active; the append-only invariant is
322
+ preserved for the *state*, not for the file's history. Losers survive
323
+ in git history.
324
+ """
325
+ before = self.path.stat().st_size if self.path.exists() else 0
326
+ rows = [json.dumps(r.data, sort_keys=True, separators=(",", ":")) for r in self]
327
+ tmp = self.path.with_suffix(".jsonl.tmp")
328
+ tmp.write_text("\n".join(rows) + "\n", encoding="utf-8")
329
+ tmp.replace(self.path)
330
+ self.load()
331
+ after = self.path.stat().st_size
332
+ return max(0, before - after)
333
+
334
+ # -- derived -----------------------------------------------------------
335
+ def snapshot(self) -> str:
336
+ """Merkle-ish digest of the *state*, stable under reordering."""
337
+ joined = "\n".join(f"{r.id}:{r.hash}" for r in self)
338
+ return hashlib.sha256(joined.encode("utf-8")).hexdigest()[:16]
339
+
340
+
341
+ def validate(rec: dict) -> str | None:
342
+ for key in REQUIRED:
343
+ if key not in rec:
344
+ return f"missing field {key!r}"
345
+ if rec["kind"] not in KINDS:
346
+ return f"unknown kind {rec['kind']!r}"
347
+ rid = str(rec["id"])
348
+ if not rid or len(rid) > LIMITS["id"]:
349
+ return f"bad id {rid!r}"
350
+ if not all(c.isalnum() or c in "_.:-" for c in rid):
351
+ return f"bad id {rid!r} (use letters, digits, _ . : -)"
352
+ text = rec.get("text")
353
+ if not isinstance(text, str) or not text.strip():
354
+ return f"{rid}: empty text"
355
+ if len(text) > LIMITS["text"]:
356
+ return f"{rid}: text is {len(text)} chars (max {LIMITS['text']}); split it"
357
+ why = rec.get("why")
358
+ if why is not None and len(str(why)) > LIMITS["why"]:
359
+ return f"{rid}: why is too long (max {LIMITS['why']})"
360
+ sev = rec.get("sev")
361
+ if sev is not None and sev not in SEVERITIES:
362
+ return f"{rid}: unknown sev {sev!r}"
363
+ status = rec.get("status")
364
+ if status is not None and status not in STATUSES:
365
+ return f"{rid}: unknown status {status!r}"
366
+ scope = rec.get("scope")
367
+ if scope is not None and not isinstance(scope, (str, list, dict)):
368
+ return f"{rid}: scope must be string, list or object"
369
+ for field_name in ("check", "probe"):
370
+ val = rec.get(field_name)
371
+ if val is None:
372
+ continue
373
+ if isinstance(val, str):
374
+ continue
375
+ if not isinstance(val, dict):
376
+ return f"{rid}: {field_name} must be string or object"
377
+ run = val.get("run")
378
+ if not isinstance(run, str) or not run.strip():
379
+ return f"{rid}: {field_name}.run missing"
380
+ if len(run) > LIMITS["check_run"]:
381
+ return f"{rid}: {field_name}.run too long"
382
+ anchors = rec.get("anchors")
383
+ if anchors is not None:
384
+ if not isinstance(anchors, list):
385
+ return f"{rid}: anchors must be a list"
386
+ for a in anchors:
387
+ if not isinstance(a, dict) or "path" not in a:
388
+ return f"{rid}: anchor needs a path"
389
+ return None
390
+
391
+
392
+ _ID_ALPHABET = "23456789abcdefghjkmnpqrstvwxyz" # Crockford-ish: no i l o u
393
+
394
+
395
+ def new_id(prefix: str = "R", size: int = 6) -> str:
396
+ """A collision-resistant short id.
397
+
398
+ Sequential ids (`R3`) are the obvious choice and the wrong one: two people
399
+ adding a rule offline both compute `R3`, and the merge silently keeps only
400
+ one of them. Identity has to be unique at *creation* time, not at merge
401
+ time, because merge time has no authority to rename anything.
402
+ """
403
+ return prefix + "".join(secrets.choice(_ID_ALPHABET) for _ in range(size))
404
+
405
+
406
+ def meta_record() -> dict:
407
+ return {
408
+ "v": 1,
409
+ "id": "meta",
410
+ "kind": "meta",
411
+ "text": "append-only ledger; see canon(1). Never edit by hand.",
412
+ "schema": 1,
413
+ # fixed forever: every clone must produce the identical record, or the
414
+ # bootstrap itself would show up as a divergence on the first merge.
415
+ "ts": "1970-01-01T00:00:00Z",
416
+ "author": "canon",
417
+ "lamport": 0,
418
+ }