facet-mcp 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.
facet_index.py ADDED
@@ -0,0 +1,2042 @@
1
+ #!/usr/bin/env python
2
+ """facet_index — the derived index over the markdown record.
3
+
4
+ WHAT THIS IS. `docs/index/facet.db` is a SQLite+FTS5 map of this repo's record,
5
+ GENERATED by this file and never hand-edited. The markdown stays canonical:
6
+ corrections in place, prose holdings, the evidence trail. The database exists so a
7
+ session can *query* instead of reading, and then read the forty lines the query
8
+ pointed at rather than the six hundred it would have skimmed. The design ruling is
9
+ docs/context-architecture.md.
10
+
11
+ THE DAY IT IS HAND-EDITED IT IS WRONG BY DEFINITION. Every fold regenerates it;
12
+ `verify` gates the regeneration; a build that fails verify does not commit.
13
+
14
+ THIS FILE NEVER WRITES TO THE RECORD. It parses by the record's own conventions and
15
+ reports what it could not parse. A builder that "fixes" a source document while
16
+ parsing it has failed — malformed-by-convention text is a report item, never an edit.
17
+
18
+ WHAT IT PARSES, AND WHERE THE CONVENTIONS COME FROM. Nothing here was invented; each
19
+ pattern is the shape the record already uses:
20
+
21
+ ## Ruling 25 — TITLE (2026-08-07) numbered rulings E04/E10/E11/E12/E10off
22
+ **25c — TITLE.** body... lettered subs E12 mostly, E04/E10off
23
+ > ### Amendment 32 (advisor, 2026-08-04) amendments E08
24
+ ## Post-ingest addenda 3 (2026-08-07, …) addenda E11
25
+ ## Session handoff 15 (2026-08-07) — … handoffs E04/E12 kickoffs
26
+ **A law's statement.** what it was paid… laws CLAUDE.md
27
+ tools.<tool>.<key> = {value, why, from} decisions profiles/*.json
28
+
29
+ DETERMINISM IS A CONTRACT, NOT AN ASPIRATION. Two builds from an unchanged record
30
+ must be byte-identical. Everything that could vary is pinned: the file list is an
31
+ explicit sorted constant, every traversal is `sorted()`, every insert order is fixed,
32
+ the whole build is ONE transaction, and no timestamp or random value is ever written.
33
+ `verify` tests this rather than trusting it, with a pre-registered `.dump` fallback
34
+ if SQLite's own file header (a change counter, an implementation detail) defeats byte
35
+ equality.
36
+
37
+ ANCHORS COME IN TWO FORMS AND THAT IS DELIBERATE. `anchor` is the human label a
38
+ session reads and cites ("Ruling 25c"). `locator` is the exact string findable in the
39
+ file ("**25c —"), because GitHub mints anchors for `#`-headings only and a bold lead
40
+ is not one. The dangling-pointer gate checks `locator`; the query output prints
41
+ `anchor`.
42
+
43
+ Standards compliance
44
+ PIN_PER_STEP the DB is a pure function of the record at a commit; this file
45
+ is committed beside it; `build` takes no tuning parameters.
46
+ ANDON_AUTHORITY `verify` exits non-zero on any of four legs and prints the
47
+ failing evidence; a parse it cannot do is reported, never
48
+ papered over.
49
+ NAMED_COMPENSATORS writes exactly one path (docs/index/facet.db); undo is deleting
50
+ it. The record is opened read-only.
51
+ DECOMPOSE_BY_SECRETS the parser knows conventions, the schema knows ontology, the
52
+ verifier knows neither's internals — it re-derives its counts
53
+ from the record with its own greps.
54
+ UNCERTAINTY_GATED_HUMANS parse limitations print as findings for the advisor's eye.
55
+ EXTERNAL_VERIFIER the seeded question set is advisory-authored and its expected
56
+ answers are keyed to record anchors this file never reads as
57
+ input; counts are checked against independent greps.
58
+ """
59
+ import argparse
60
+ import io
61
+ import json
62
+ import os
63
+ import re
64
+ import sqlite3
65
+ import sys
66
+ import unicodedata
67
+
68
+ HERE = os.path.dirname(os.path.abspath(__file__))
69
+ REPO = os.path.dirname(HERE)
70
+ DB_REL = "docs/index/facet.db"
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # The record's own file list. Explicit and sorted rather than globbed, so the
74
+ # insert order is a property of this file rather than of a filesystem.
75
+ # ---------------------------------------------------------------------------
76
+
77
+ # RULING DOCUMENTS ARE DISCOVERED, NOT LISTED (E15 Ruling 8b).
78
+ #
79
+ # This was a hardcoded list, and it was written before `E15-ruling.md` existed — so
80
+ # that document's rulings were invisible to the index, and INVISIBLE TO THE GATE TOO,
81
+ # because `verify`'s count checks grepped the same list. The gate could test that no
82
+ # listed file lost a ruling; it could not test that a file was missing from the list.
83
+ # The repo's own law — a gate must test the operation's failure mode, not its success
84
+ # mode — landing on the instrument built to enforce it.
85
+ #
86
+ # The list was explicit for determinism ("insert order is a property of this file
87
+ # rather than of a filesystem"). A SORTED glob satisfies that identically: the order
88
+ # is a pure function of the filenames, which are in git. The trade was made in one
89
+ # direction without measuring the cost; this is the cost, paid back.
90
+ #
91
+ # `verify` prints what this discovers, so the glob's own misses are visible rather
92
+ # than assumed — a discovery rule that cannot be audited is the same defect wearing a
93
+ # different hat.
94
+ RULING_DOC_RE = re.compile(r"^E\d\d-.*ruling.*\.md$")
95
+
96
+
97
+ def ruling_documents():
98
+ """(arc, path) for every ruling document, sorted. Arc derived from the filename.
99
+
100
+ THE ARC LABEL IS DERIVED BY STRIPPING FROM `ruling` ONWARD, not from the leading
101
+ E-number, and that is load-bearing rather than fussy: `E10-offsurface-ruling.md`
102
+ must stay its own arc. Keyed on the E-number alone it would merge into `E10`, and
103
+ twelve rulings and seven rulings would collide on numbers 1–7 — a primary-key
104
+ failure, not a quiet miscount. This derivation reproduces every label the
105
+ hardcoded list carried, byte for byte.
106
+
107
+ Files matching the pattern that carry no numbered content — the E01/E02/E06/E07
108
+ gate-1 rulings, `E08-director-canon-ruling.md` — parse to zero rows harmlessly and
109
+ keep their prose indexing, because prose exclusion is decided by what a file
110
+ actually yielded, not by whether it matched a name.
111
+ """
112
+ out = []
113
+ d = os.path.join(REPO, "docs", "experiments")
114
+ for fn in sorted(os.listdir(d)):
115
+ if not RULING_DOC_RE.match(fn):
116
+ continue
117
+ arc = re.split(r"-?ruling", fn, maxsplit=1)[0].rstrip("-")
118
+ out.append((arc, "docs/experiments/" + fn))
119
+ return out
120
+
121
+ # ruling-class documents that carry NO numbered rulings — topical `##` sections
122
+ # only. They enter the index as prose sections, and that asymmetry is a reported
123
+ # finding, not a defect this parser can fix.
124
+ TOPICAL_RULING_FILES = [
125
+ ("E01", "docs/experiments/E01-ruling-gate1.md"),
126
+ ("E02", "docs/experiments/E02-ruling-gate1.md"),
127
+ ("E06", "docs/experiments/E06-ruling-gate1.md"),
128
+ ("E07", "docs/experiments/E07-ruling-gate1.md"),
129
+ ("E08", "docs/experiments/E08-director-canon-ruling.md"),
130
+ ]
131
+
132
+ # KICKOFF DOCUMENTS ARE DISCOVERED, NOT LISTED (E16-9; E15 Ruling 8b's class, one
133
+ # list over — the comment that used to sit here said so and said "until it lands,
134
+ # every new arc's kickoff is added HERE", which is the manual step this removes).
135
+ #
136
+ # The cost of the listed form was live when this landed: E15's own kickoff carried
137
+ # TWO `## Session handoff` headers and was not on the list, so those two dispatches
138
+ # were invisible to the handoffs table and to `verify`'s count legs alike — a gate
139
+ # that can test whether a listed file lost a row, but not whether a file was missing
140
+ # from the list.
141
+ KICKOFF_DOC_RE = re.compile(r"^E\d\d-.*kickoff.*\.md$")
142
+
143
+
144
+ def handoff_documents():
145
+ """(arc, path) for every kickoff document, sorted. Arc is the leading E-number.
146
+
147
+ Unlike `ruling_documents`, the arc is NOT derived by stripping from the keyword
148
+ onward: that rule exists there because `E10-offsurface-ruling.md` must not merge
149
+ into `E10`, and stripping from `kickoff` here would yield `E04-executor` and
150
+ `E15-context-index` — labels the handoffs table has never used and which would
151
+ break every existing anchor. The leading E-number reproduces the hardcoded list's
152
+ three labels exactly. The collision the ruling docs suffer is possible in
153
+ principle (two kickoffs, one arc, different subjects); it does not exist today,
154
+ and the inverse guard below would not catch it, so it is stated rather than
155
+ guarded — a known edge, not a hidden one.
156
+ """
157
+ out = []
158
+ d = os.path.join(REPO, "docs", "experiments")
159
+ for fn in sorted(os.listdir(d)):
160
+ if not KICKOFF_DOC_RE.match(fn):
161
+ continue
162
+ out.append((fn.split("-", 1)[0], "docs/experiments/" + fn))
163
+ return out
164
+
165
+
166
+ def assert_no_undiscovered_handoffs(discovered):
167
+ """THE INVERSE GUARD: a parsed handoff row in an UNDISCOVERED file fails the run.
168
+
169
+ A discovery rule that only reports what it found cannot report what it missed,
170
+ which is exactly how the listed form failed. This asks the opposite question —
171
+ does any file in the record carry a handoff header that the glob did not reach —
172
+ and it is the check the old list could not express at all. Measured when written:
173
+ four documents carry `## Session handoff` headers and the glob reaches all four.
174
+ """
175
+ known = {rel for _, rel in discovered}
176
+ stray = []
177
+ d = os.path.join(REPO, "docs", "experiments")
178
+ for fn in sorted(os.listdir(d)):
179
+ rel = "docs/experiments/" + fn
180
+ if not fn.endswith(".md") or rel in known:
181
+ continue
182
+ for ln in lines_of(rel):
183
+ if HANDOFF_HDR.match(ln):
184
+ stray.append("%s :: %s" % (rel, ln.rstrip()[:70]))
185
+ break
186
+ assert not stray, (
187
+ "ANDON: %d file(s) carry a session-handoff header that the kickoff glob "
188
+ "(%s) does not reach, so their dispatches would be invisible to the "
189
+ "handoffs table and to verify's counts:\n %s"
190
+ % (len(stray), KICKOFF_DOC_RE.pattern, "\n ".join(stray)))
191
+
192
+ LAW_FILES = ["CLAUDE.md"]
193
+
194
+ PROFILE_FILES = ["profiles/beast.json", "profiles/character.json", "profiles/ship.json"]
195
+
196
+ # prose corpora indexed for FTS with no ontology row of their own
197
+ PROSE_FILES = [
198
+ "README.md",
199
+ "docs/context-architecture.md",
200
+ "docs/experiments/README.md",
201
+ "docs/handbook/index.md",
202
+ "docs/handbook/profiles.md",
203
+ "docs/handbook/subjects.md",
204
+ "docs/profiles-design.md",
205
+ "docs/style-registers.md",
206
+ ]
207
+
208
+ # every markdown file of the record, for artifact / phenomenon extraction. Built
209
+ # by a sorted walk so the traversal cannot depend on directory order.
210
+ def record_markdown():
211
+ out = []
212
+ for rel in ["CLAUDE.md", "README.md"]:
213
+ out.append(rel)
214
+ for root in ["docs"]:
215
+ for dirpath, dirnames, filenames in os.walk(os.path.join(REPO, root)):
216
+ dirnames.sort()
217
+ for fn in sorted(filenames):
218
+ if fn.endswith(".md"):
219
+ p = os.path.join(dirpath, fn)
220
+ out.append(os.path.relpath(p, REPO).replace("\\", "/"))
221
+ return sorted(set(out))
222
+
223
+
224
+ # ---------------------------------------------------------------------------
225
+ # reading helpers
226
+ # ---------------------------------------------------------------------------
227
+
228
+ def read(rel):
229
+ with io.open(os.path.join(REPO, rel), encoding="utf-8") as fh:
230
+ return fh.read().replace("\r\n", "\n")
231
+
232
+
233
+ def lines_of(rel):
234
+ return read(rel).split("\n")
235
+
236
+
237
+ DASH = "[—–-]" # em dash, en dash, hyphen — the record uses all three
238
+ BOLD_LEAD = re.compile(r"^\*\*")
239
+
240
+
241
+ def one_line(text, limit=240):
242
+ """Collapse to a single line. Holdings are quoted in query output."""
243
+ t = re.sub(r"\s+", " ", text).strip()
244
+ t = t.strip(" .")
245
+ if len(t) > limit:
246
+ t = t[: limit - 1].rstrip() + "…"
247
+ return t
248
+
249
+
250
+ def strip_md(text):
251
+ """Remove the markup that would otherwise be indexed as words."""
252
+ t = text
253
+ t = re.sub(r"`([^`]*)`", r"\1", t)
254
+ t = re.sub(r"\*\*([^*]*)\*\*", r"\1", t)
255
+ t = re.sub(r"\*([^*]*)\*", r"\1", t)
256
+ t = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", t)
257
+ t = t.replace(">", " ")
258
+ return t
259
+
260
+
261
+ def github_slug(heading):
262
+ """GitHub's heading anchor algorithm, for `#`-headings only."""
263
+ s = unicodedata.normalize("NFKD", heading)
264
+ s = strip_md(s).strip().lower()
265
+ s = re.sub(r"[^\w\s-]", "", s, flags=re.UNICODE)
266
+ s = re.sub(r"\s+", "-", s)
267
+ return s
268
+
269
+
270
+ DATE_RE = re.compile(r"(\d{4}-\d{2}-\d{2})")
271
+
272
+
273
+ def find_date(text):
274
+ m = DATE_RE.search(text)
275
+ return m.group(1) if m else None
276
+
277
+
278
+ def paragraphs(block_lines, start_line):
279
+ """Split a run of lines into (start_line_number, [lines]) paragraphs.
280
+
281
+ A paragraph boundary is a blank line. This is the discriminator that keeps a
282
+ wrapped `**word**` mid-sentence from being read as a bold-lead heading —
283
+ CLAUDE.md:141 is exactly that case.
284
+ """
285
+ out = []
286
+ cur = []
287
+ cur_start = start_line
288
+ for i, ln in enumerate(block_lines):
289
+ if ln.strip() == "":
290
+ if cur:
291
+ out.append((cur_start, cur))
292
+ cur = []
293
+ cur_start = start_line + i + 1
294
+ else:
295
+ if not cur:
296
+ cur_start = start_line + i
297
+ cur.append(ln)
298
+ if cur:
299
+ out.append((cur_start, cur))
300
+ return out
301
+
302
+
303
+ def bold_lead_title(par_lines):
304
+ """Return (title, rest) for a paragraph opening with `**`, else (None, None).
305
+
306
+ The bold run may span several wrapped lines — `**27d — THE FIFTH SIGNATURE IS
307
+ NAMED FORWARD: dark desaturated crevice` closes on the following line — so the
308
+ closing `**` is searched across the whole paragraph.
309
+ """
310
+ text = "\n".join(par_lines)
311
+ if not text.startswith("**"):
312
+ return None, None
313
+ end = text.find("**", 2)
314
+ if end < 0:
315
+ return None, None
316
+ return text[2:end], text[end + 2:]
317
+
318
+
319
+ # ---------------------------------------------------------------------------
320
+ # parsers — one per convention
321
+ # ---------------------------------------------------------------------------
322
+
323
+ RULING_HDR = re.compile(r"^## Ruling (\d+)\b(.*)$")
324
+ ADDENDA_HDR = re.compile(r"^## Post-ingest addenda\s*(\d*)\b(.*)$")
325
+ AMEND_HDR = re.compile(r"^> ### (?:⚠\s*)?Amendment (\d+) \((.*)$")
326
+
327
+ # MEASURED, not assumed: across all five ruling documents the lettered marker is
328
+ # `**<n><letter> <dash>` — letter, SPACE, dash — 151 times out of 152. The single
329
+ # exception is not a sub-ruling at all but a CLOSURE marker naming the sub-ruling
330
+ # it closes (`**18g-CLOSED (Director, 2026-08-06): "Keep ivory, judge on asset."`),
331
+ # and it carries the Director's own sentence. A dash class that tolerates a bare
332
+ # hyphen swallows it into 18g and loses one of the two holdings. So the space is
333
+ # required, and the suffixed form gets its own pattern and its own row.
334
+ SUB_RULING = re.compile(r"^\*\*(\d+)([a-z])\s+" + DASH)
335
+ SUB_CLOSURE = re.compile(r"^\*\*(\d+)([a-z])-([A-Z][A-Z-]+)\b")
336
+ HANDOFF_HDR = re.compile(r"^## Session handoff\s*(\d*)\s*\((.*)$")
337
+ SECTION_HDR = re.compile(r"^(#{2,3}) +(.*)$")
338
+
339
+ # correction / supersession verbs, directed at a numbered ruling. Conservative by
340
+ # design: a phrase this does not match is under-counted, never mis-attributed.
341
+ SUPERSEDE_RE = re.compile(
342
+ r"(?:Ruling|Amendment)\s+(\d+[a-z]?)(?:'s [^.;:]{0,60}?)?\s+"
343
+ r"(?:is\s+|are\s+)?(?:now\s+)?"
344
+ r"(?:CORRECTED|corrected|WITHDRAWN|withdrawn|SUPERSEDED|superseded|VOID|void)\b"
345
+ )
346
+ SUPERSEDE_TITLE_RE = re.compile(
347
+ r"\b(\d+[a-z]?)\s+(?:is\s+)?(?:corrected in place|CORRECTED IN PLACE|withdrawn|WITHDRAWN)"
348
+ )
349
+
350
+
351
+ def parse_rulings():
352
+ """Numbered rulings, their lettered sub-rulings, amendments and addenda.
353
+
354
+ Every discovered document is offered to all three conventions. Only E08 carries
355
+ `> ### Amendment N (`, only E11 carries `## Post-ingest addenda`, and the patterns
356
+ are specific enough that offering them everywhere costs nothing and means a
357
+ convention appearing in a new document is picked up rather than missed.
358
+ """
359
+ rows = []
360
+ for arc, rel in ruling_documents():
361
+ rows.extend(_parse_numbered(arc, rel, RULING_HDR, "ruling", "Ruling"))
362
+ rows.extend(_parse_numbered(arc, rel, ADDENDA_HDR, "addendum", "Post-ingest addenda"))
363
+ rows.extend(_parse_amendments(arc, rel))
364
+ rows.sort(key=lambda r: (r["arc"], r["sort_num"], r["sort_letter"], r["kind"]))
365
+ return rows
366
+
367
+
368
+ def _header_blocks(ls, pattern):
369
+ """Yield (match, header_line_no, body_lines) for every header match."""
370
+ hits = [(i, pattern.match(ln)) for i, ln in enumerate(ls)]
371
+ hits = [(i, m) for i, m in hits if m]
372
+ for k, (i, m) in enumerate(hits):
373
+ end = hits[k + 1][0] if k + 1 < len(hits) else len(ls)
374
+ # a later `## ` header of another kind also terminates the block
375
+ for j in range(i + 1, end):
376
+ if ls[j].startswith("## "):
377
+ end = j
378
+ break
379
+ yield m, i, ls[i + 1:end]
380
+
381
+
382
+ def _parse_numbered(arc, rel, pattern, kind, label):
383
+ out = []
384
+ ls = lines_of(rel)
385
+ for m, i, body in _header_blocks(ls, pattern):
386
+ num = m.group(1)
387
+ if not num:
388
+ num = "1" # E11's first addendum carries no digit
389
+ tail = m.group(2)
390
+ title = re.sub(r"^\s*" + DASH + r"\s*", "", tail).strip()
391
+ title = re.sub(r"^\(([^)]*)\)\s*" + DASH + r"\s*", "", title).strip()
392
+ anchor = "%s %s" % (label, num)
393
+ subs = _parse_subs(arc, rel, num, kind, body, i + 1, find_date(m.group(0)))
394
+ # A parent's body must NOT re-index its sub-rulings' prose: every sub is its
395
+ # own row, so including their text made Ruling 4 a 3,932-character document
396
+ # that competes with its own five children and dilutes bm25's length
397
+ # normalisation for both. The parent keeps only what belongs to it.
398
+ own = _minus_sub_paragraphs(body, i + 1, subs)
399
+ row = dict(
400
+ arc=arc, number=num, parent=None, kind=kind,
401
+ date=find_date(m.group(0)) or find_date("\n".join(body[:6])),
402
+ holding=one_line(strip_md(title)) or one_line(strip_md(tail)),
403
+ body=strip_md(own),
404
+ file=rel, anchor=anchor, locator=ls[i].rstrip(), line=i + 1,
405
+ sort_num=int(num), sort_letter="",
406
+ )
407
+ out.append(row)
408
+ out.extend(subs)
409
+ return out
410
+
411
+
412
+ def _minus_sub_paragraphs(body, body_start, subs):
413
+ """The parent's own prose: the block minus every paragraph a sub-ruling owns."""
414
+ owned = set()
415
+ for s in subs:
416
+ first = s["line"] - 1 - body_start
417
+ n = len(s["body"].split("\n"))
418
+ for k in range(first, first + n + 1):
419
+ owned.add(k)
420
+ return "\n".join(ln for k, ln in enumerate(body) if k not in owned)
421
+
422
+
423
+ SKIPPED_CROSSREFS = []
424
+
425
+
426
+ def _parse_subs(arc, rel, parent_num, parent_kind, body, body_start, parent_date):
427
+ """Lettered sub-rulings — and closure markers — inside one ruling's body."""
428
+ out = []
429
+ pars = paragraphs(body, body_start)
430
+ for start, par in pars:
431
+ first = par[0]
432
+ m = SUB_RULING.match(first)
433
+ closure = None if m else SUB_CLOSURE.match(first)
434
+ if not m and not closure:
435
+ continue
436
+ g = m or closure
437
+ num, letter = g.group(1), g.group(2)
438
+ if num != parent_num:
439
+ # a lettered marker numbered for a DIFFERENT ruling is a cross-reference
440
+ # opening a paragraph, not this ruling's own sub-ruling. Skipped, and
441
+ # recorded so the report can quote how often it happens.
442
+ SKIPPED_CROSSREFS.append((rel, start + 1, first[:70]))
443
+ continue
444
+ title, rest = bold_lead_title(par)
445
+ if title is None:
446
+ continue
447
+ if closure:
448
+ suffix = "-" + g.group(3)
449
+ number = num + letter + suffix
450
+ anchor = "Ruling %s%s%s" % (num, letter, suffix)
451
+ locator = "**%s%s%s" % (num, letter, suffix)
452
+ kind = "sub-%s-closure" % parent_kind
453
+ title = re.sub(r"^\d+[a-z]-[A-Z-]+\s*:?\s*", "", title)
454
+ else:
455
+ number = num + letter
456
+ anchor = "Ruling %s%s" % (num, letter)
457
+ locator = "**%s%s " % (num, letter)
458
+ kind = "sub-" + parent_kind
459
+ title = re.sub(r"^\d+[a-z]\s*" + DASH + r"\s*", "", title)
460
+ out.append(dict(
461
+ arc=arc, number=number, parent=num, kind=kind,
462
+ date=find_date(g.group(0)) or find_date(title) or parent_date,
463
+ holding=one_line(strip_md(title)),
464
+ body=strip_md("\n".join(par)),
465
+ file=rel, anchor=anchor, locator=locator, line=start + 1,
466
+ sort_num=int(num), sort_letter=letter,
467
+ ))
468
+ return out
469
+
470
+
471
+ def _parse_amendments(arc, rel):
472
+ out = []
473
+ ls = lines_of(rel)
474
+ for m, i, body in _header_blocks(ls, AMEND_HDR):
475
+ num = m.group(1)
476
+ tail = m.group(2)
477
+ author = tail.split(")")[0]
478
+ title = tail.split(")", 1)[1] if ")" in tail else tail
479
+ title = re.sub(r"^\s*" + DASH + r"\s*", "", title).strip()
480
+ out.append(dict(
481
+ arc=arc, number="A" + num, parent=None, kind="amendment",
482
+ date=find_date(author),
483
+ holding=one_line(strip_md(title)),
484
+ body=strip_md("\n".join(body)),
485
+ file=rel, anchor="Amendment %s" % num,
486
+ locator="Amendment %s (" % num, line=i + 1,
487
+ sort_num=int(num), sort_letter="",
488
+ ))
489
+ return out
490
+
491
+
492
+ # The record announces its verdicts in capitals and names its authority in the
493
+ # header. Both are ontology this index was missing: without them, the ruling that IS
494
+ # an acceptance is indistinguishable from the three that merely discuss one, and
495
+ # "when was the pair accepted" ranks the discussion above the event. Ordered most-
496
+ # to least specific; the first hit in the holding wins.
497
+ VERDICTS = [
498
+ "ACCEPTED", "REJECTED", "RATIFIED", "WITHDRAWN", "FALSIFIED", "CONFIRMED",
499
+ "DESIGNATED", "DIRECTED", "ADOPTED", "SUSPENDED", "RELEASED", "CLOSED",
500
+ "CLEARED", "HALTED", "BANKED", "MINTED", "VOID", "RULED",
501
+ ]
502
+
503
+
504
+ def classify(holding):
505
+ """(verdict, authority) for a ruling, from the record's own capitalised marks.
506
+
507
+ THE CAPITALS ARE THE CONVENTION AND MUST NOT BE NORMALISED AWAY. A verdict is
508
+ what a ruling DOES, and the record shouts it: `THE PAIR IS ACCEPTED`,
509
+ `the pair is REJECTED`, `is RATIFIED end to end`, `GATE 1: ACCEPTED`. The same
510
+ word in lower case is an adjective describing an artifact — `D9's wine has no
511
+ cluster on the accepted pair` is not an acceptance. An earlier version of this
512
+ function upper-cased the holding first and so marked three rulings ACCEPTED that
513
+ accept nothing, which put two of them above the actual acceptance in the ranking.
514
+ Match case-sensitively.
515
+ """
516
+ verdict = None
517
+ for v in VERDICTS:
518
+ if re.search(r"\b%s\b" % v, holding):
519
+ verdict = v
520
+ break
521
+ authority = "Director" if re.search(r"\bDirector\b", holding) else "advisor"
522
+ return verdict, authority
523
+
524
+
525
+ def link_supersessions(rulings):
526
+ """Populate supersedes / superseded_by from EXPLICIT correction verbs only.
527
+
528
+ A lower bound by construction: the record also corrects by narrative ("the
529
+ word stands, anchored by…"), which no pattern reads without guessing. The
530
+ report states the coverage rather than implying completeness.
531
+ """
532
+ by_key = {}
533
+ for r in rulings:
534
+ by_key[(r["arc"], r["number"])] = r
535
+ r["supersedes"] = []
536
+ r["superseded_by"] = []
537
+ for r in rulings:
538
+ hay = r["holding"] + " \n " + r["body"][:4000]
539
+ targets = set(SUPERSEDE_RE.findall(hay)) | set(SUPERSEDE_TITLE_RE.findall(r["holding"]))
540
+ for t in sorted(targets):
541
+ if t == r["number"]:
542
+ continue
543
+ tgt = by_key.get((r["arc"], t))
544
+ if tgt is None:
545
+ continue
546
+ if t not in r["supersedes"]:
547
+ r["supersedes"].append(t)
548
+ if r["number"] not in tgt["superseded_by"]:
549
+ tgt["superseded_by"].append(r["number"])
550
+ for r in rulings:
551
+ r["supersedes"] = ",".join(sorted(r["supersedes"])) or None
552
+ r["superseded_by"] = ",".join(sorted(r["superseded_by"])) or None
553
+
554
+
555
+ NUM_RULE = re.compile(r"^(\d+)\. +\*\*")
556
+ LIST_ITEM = re.compile(r"^(?:\d+\.|[-*]) +")
557
+ PAID_RE = re.compile(r"\b(E0[1-9]|E1[0-5])\b")
558
+
559
+
560
+ LIST_LAW = re.compile(r"^(?:\d+\.|[-*]) +\*\*")
561
+
562
+
563
+ def list_items(par):
564
+ """Split a paragraph wherever a list item OPENS IN BOLD — the law shape.
565
+
566
+ Two properties of CLAUDE.md make a plain blank-line splitter lose most of the
567
+ corpus, and both were measured rather than assumed:
568
+
569
+ * lists carry NO blank line between items, so ten numbered role rules read as
570
+ one block and only the first is captured (2 of 10 before this existed, with
571
+ the four `Judging artifacts` and eight `Standing technical constraints`
572
+ bullets absent entirely);
573
+ * an item may itself CONTAIN a blank line — advisor rule 3 runs to two
574
+ paragraphs — after which items 4 and 5 sit in a block that no longer starts
575
+ with a marker, and were lost even once list splitting existed.
576
+
577
+ So the split is on the marker-plus-bold pattern anywhere in the block, not on the
578
+ block's first line. Requiring the `**` immediately after the marker keeps prose
579
+ that merely begins a line with `- ` from being cut into phantom laws.
580
+ """
581
+ if not any(LIST_LAW.match(ln) for ln in par):
582
+ return [par]
583
+ out, cur = [], []
584
+ for ln in par:
585
+ if LIST_LAW.match(ln) and cur:
586
+ out.append(cur)
587
+ cur = [ln]
588
+ else:
589
+ cur.append(ln)
590
+ if cur:
591
+ out.append(cur)
592
+ return out
593
+
594
+
595
+ def parse_laws():
596
+ """The CLAUDE.md law corpus.
597
+
598
+ Three forms, all the file's own: bold-lead paragraphs (`**An inherited claim
599
+ is…**`), numbered role rules (`1. **Never judge…**`) and bulleted constraints
600
+ (`- **Weld before decimating.**`). A law must open its paragraph OR its list
601
+ item — which is what keeps a wrapped mid-sentence `**word**` (CLAUDE.md:141) out
602
+ of the table, while still reaching the items inside a blank-line-free list.
603
+ """
604
+ rows = []
605
+ for rel in LAW_FILES:
606
+ ls = lines_of(rel)
607
+ heads = [(i, ln) for i, ln in enumerate(ls) if ln.startswith("## ")]
608
+ bounds = []
609
+ for k, (i, ln) in enumerate(heads):
610
+ end = heads[k + 1][0] if k + 1 < len(heads) else len(ls)
611
+ bounds.append((ln[3:].strip(), i, end))
612
+ for section, s, e in bounds:
613
+ for start, block in paragraphs(ls[s + 1:e], s + 1):
614
+ offset = 0
615
+ for par in list_items(block):
616
+ line = start + offset
617
+ offset += len(par)
618
+ first = par[0]
619
+ title, kind = None, None
620
+ if BOLD_LEAD.match(first):
621
+ title, _ = bold_lead_title(par)
622
+ kind = "law"
623
+ elif LIST_ITEM.match(first):
624
+ inner = "\n".join(par).split("**", 2)
625
+ # the bold must open the item: anything between the marker
626
+ # and the `**` means the bold is mid-sentence, not a statement
627
+ if len(inner) >= 3 and not LIST_ITEM.sub("", inner[0]).strip():
628
+ title = inner[1]
629
+ kind = "rule" if NUM_RULE.match(first) else "law"
630
+ if title is None:
631
+ continue
632
+ stmt = one_line(strip_md(title))
633
+ if len(stmt) < 12:
634
+ continue
635
+ body = strip_md("\n".join(par))
636
+ paid = sorted(set(PAID_RE.findall(body)))
637
+ rows.append(dict(
638
+ statement=stmt, kind=kind, section=section,
639
+ paid_for_by=",".join(paid) or None, body=body, file=rel,
640
+ anchor="%s · %s" % (section, stmt[:60]),
641
+ locator=first.rstrip(), line=line + 1,
642
+ ))
643
+ return rows
644
+
645
+
646
+ EXP_ROW = re.compile(r"^\| \[?(E\d\d)\]?(?:\([^)]*\))? \| (.*?) \| (.*?) \|\s*$")
647
+
648
+
649
+ def parse_experiments():
650
+ """E01…, from the experiments README table, supplemented by the filesystem.
651
+
652
+ The table is the authored source; it is also STALE by construction (E13/E14/E15
653
+ have no row, E12's row says "Rulings 1-8"). Experiments present on disk but
654
+ absent from the table enter with status `not in the README table` — a reported
655
+ finding, never a silent fill.
656
+ """
657
+ rows = {}
658
+ rel = "docs/experiments/README.md"
659
+ for ln in lines_of(rel):
660
+ m = EXP_ROW.match(ln)
661
+ if not m:
662
+ continue
663
+ eid, question, status = m.group(1), m.group(2), m.group(3)
664
+ rows[eid] = dict(
665
+ id=eid, question=one_line(strip_md(question), 400),
666
+ status=one_line(strip_md(status), 400),
667
+ verdict=_verdict(status), spec_file=None, report_file=None,
668
+ body=strip_md(question + " " + status),
669
+ file=rel, anchor="the experiment table · %s" % eid,
670
+ locator="| [%s]" % eid, line=0,
671
+ )
672
+ # locate each experiment's own files, and discover experiments the table omits
673
+ # .md first, then the rest, each alphabetically — so an experiment discovered
674
+ # from disk is anchored at a document's heading rather than at a JSON's `{`.
675
+ files = sorted(
676
+ (f for f in os.listdir(os.path.join(REPO, "docs/experiments"))
677
+ if re.match(r"^E\d\d[-.]", f)),
678
+ key=lambda f: (0 if f.endswith(".md") else 1, f))
679
+ for f in files:
680
+ eid = f[:3]
681
+ r = rows.get(eid)
682
+ if r is None:
683
+ # E13/E14/E15 have no README-table row. They enter from disk, pointed at
684
+ # their own document's first heading — a locator findable IN that file,
685
+ # rather than the filename, which is not text inside it. The missing
686
+ # table row is a reported finding; this parser does not write one.
687
+ rel_f = "docs/experiments/" + f
688
+ head, head_line = _first_heading(rel_f)
689
+ r = rows[eid] = dict(
690
+ id=eid, question=None,
691
+ status="not in the README table",
692
+ verdict=None, spec_file=None, report_file=None, body="",
693
+ file=rel_f,
694
+ anchor="files on disk · %s" % eid,
695
+ locator=head, line=head_line,
696
+ )
697
+ rp = "docs/experiments/" + f
698
+ if r["spec_file"] is None and re.search(r"(kickoff|spec|-E\d|-the-|-cover-|-paint-|-cull-|-atlas-|-facial-|-texture-|-environment-|-dense-|-context-)", f):
699
+ r["spec_file"] = rp
700
+ if r["report_file"] is None and "report" in f:
701
+ r["report_file"] = rp
702
+ for eid, r in rows.items():
703
+ if r["locator"] == "| [%s]" % eid and r["line"] == 0:
704
+ for i, ln in enumerate(lines_of(rel)):
705
+ if ln.startswith("| [%s]" % eid) or ln.startswith("| %s " % eid):
706
+ r["line"] = i + 1
707
+ r["locator"] = ln[:40].rstrip()
708
+ break
709
+ return [rows[k] for k in sorted(rows)]
710
+
711
+
712
+ def _first_heading(rel):
713
+ """First `#` heading of a file, and its 1-based line. Falls back to line 1."""
714
+ ls = lines_of(rel)
715
+ for i, ln in enumerate(ls):
716
+ if ln.startswith("#"):
717
+ return ln.rstrip(), i + 1
718
+ for i, ln in enumerate(ls):
719
+ if ln.strip():
720
+ return ln.rstrip()[:60], i + 1
721
+ return "", 1
722
+
723
+
724
+ def _verdict(status):
725
+ s = status.upper()
726
+ for word in ("ACCEPTED", "RULED", "IN FLIGHT", "RUN AND RULED", "STAGED", "CLOSED"):
727
+ if word in s:
728
+ return word
729
+ return None
730
+
731
+
732
+ def parse_handoffs():
733
+ """Executor dispatches and halts, arc-scoped because the numbers collide.
734
+
735
+ E04's first handoff carries no number at all (`## Session handoff (2026-08-04,
736
+ evening) — … SUPERSEDED`). It is recorded as number `1` with its unnumbered form
737
+ kept in the locator, because dropping a real dispatch to satisfy a regex would
738
+ lose a row the count check is entitled to see.
739
+ """
740
+ rows = []
741
+ docs = handoff_documents()
742
+ assert_no_undiscovered_handoffs(docs)
743
+ for arc, rel in docs:
744
+ ls = lines_of(rel)
745
+ for m, i, body in _header_blocks(ls, HANDOFF_HDR):
746
+ num = m.group(1) or "1"
747
+ tail = m.group(2)
748
+ date = find_date(tail)
749
+ title = tail.split(")", 1)[1] if ")" in tail else tail
750
+ title = re.sub(r"^\s*" + DASH + r"\s*", "", title).strip()
751
+ txt = "\n".join(body)
752
+ rows.append(dict(
753
+ arc=arc, number=int(num), date=date,
754
+ outcome=one_line(strip_md(title), 300),
755
+ commits=",".join(sorted(set(re.findall(r"`([0-9a-f]{7,40})`", txt)))) or None,
756
+ superseded=1 if "SUPERSEDED" in ls[i] else 0,
757
+ body=strip_md(txt),
758
+ file=rel, anchor="Session handoff %s (%s)" % (num, arc),
759
+ locator=ls[i].rstrip()[:60], line=i + 1,
760
+ ))
761
+ rows.sort(key=lambda r: (r["arc"], r["number"]))
762
+ return rows
763
+
764
+
765
+ def parse_decisions():
766
+ """An INDEX over the profiles' registry. The profile stays canonical.
767
+
768
+ Only `{value, why, from}` entries are indexed — the shape `subject_profile.bind`
769
+ enforces. Keys beginning `_` are the profiles' own meta/marker convention and are
770
+ recorded as status markers rather than as decided values.
771
+ """
772
+ rows = []
773
+ for rel in PROFILE_FILES:
774
+ prof = json.loads(read(rel))
775
+ subject = prof.get("name") or os.path.basename(rel)
776
+ text = read(rel).split("\n")
777
+ # `_still_suspended` is where undecidedness actually lives — and each entry
778
+ # opens with its own disposition (RESOLVED / RULED / DECIDED / CONVERTED /
779
+ # PARTIALLY SUPERSEDED / DERIVED, AWAITING …), so the block is a history of
780
+ # what was suspended and how it closed. Indexed under the pseudo-tool
781
+ # `_still_suspended` so a session can ask what a subject still owes.
782
+ for key in sorted(prof.get("_still_suspended", {})):
783
+ note = str(prof["_still_suspended"][key])
784
+ rows.append(dict(
785
+ subject=subject, tool="_still_suspended", key=key,
786
+ value=one_line(note, 200), status=_decision_status(note),
787
+ ruling=None, why=one_line(note, 400),
788
+ body=strip_md("%s %s" % (key, note)),
789
+ file=rel, anchor="%s · _still_suspended · %s" % (subject, key),
790
+ locator='"%s"' % key, line=_line_of(text, '"%s"' % key),
791
+ ))
792
+ for tool in sorted(prof.get("tools", {})):
793
+ block = prof["tools"][tool]
794
+ for key in sorted(block):
795
+ ent = block[key]
796
+ if key.startswith("_"):
797
+ rows.append(dict(
798
+ subject=subject, tool=tool, key=key,
799
+ value=one_line(str(ent), 200), status="marker",
800
+ ruling=None, why=None,
801
+ body=strip_md("%s %s" % (key, ent)),
802
+ file=rel, anchor="%s · %s · %s" % (subject, tool, key),
803
+ locator='"%s"' % key, line=_line_of(text, '"%s"' % key),
804
+ ))
805
+ continue
806
+ if not isinstance(ent, dict) or "value" not in ent:
807
+ continue
808
+ why = ent.get("why", "")
809
+ rows.append(dict(
810
+ subject=subject, tool=tool, key=key,
811
+ value=one_line(json.dumps(ent["value"], ensure_ascii=False), 200),
812
+ status=_decision_status(why),
813
+ ruling=ent.get("from"),
814
+ why=one_line(why, 400),
815
+ body=strip_md("%s %s %s %s" % (key, ent["value"], why, ent.get("from", ""))),
816
+ file=rel, anchor="%s · %s · %s" % (subject, tool, key),
817
+ locator='"%s"' % key, line=_line_of(text, '"%s"' % key),
818
+ ))
819
+ return rows
820
+
821
+
822
+ CLASS_LABEL = re.compile(r"^([A-Z][A-Z0-9 /_-]{3,44})(?=[:,.(—-]|\s+-\s)")
823
+
824
+
825
+ def _decision_status(why):
826
+ """The entry's class, read ONLY from a capitalised label at the head of `why`.
827
+
828
+ That leading label is the profiles' own convention — `FIRST-RUN OPERATING POINT
829
+ at the accepted route's value`, `PROTECTIVE TRANSCRIPTION (the E04 Ruling 22
830
+ class)`, `SPENT, WITH A BYTE ANCHOR`. Anywhere ELSE in the prose the same words
831
+ are narrative about the past, and reading them as status inverts their meaning:
832
+ an earlier version scanned the whole string and so labelled three entries
833
+ UNDECIDED whose `why` says *"the arc's one deliberately undecided value"* (ruled
834
+ 0.005 by E12 Ruling 25c) and *"Found undecided by Ruling 25's sweep, then
835
+ anchored"*. An index that reports a decided value as undecided is a second
836
+ authority contradicting the record, which is the one thing this design forbids.
837
+
838
+ An entry that carries a `value` at all is DECIDED by the loader's own semantics —
839
+ `subject_profile.bind` applies it to the tool. Undecidedness lives in the
840
+ `_still_suspended` block and the `_`-prefixed markers, both indexed separately.
841
+ """
842
+ m = CLASS_LABEL.match(why.strip())
843
+ if m:
844
+ label = m.group(1).strip()
845
+ if len(label.split()) <= 6:
846
+ return label
847
+ return "decided"
848
+
849
+
850
+ def _line_of(text_lines, needle):
851
+ for i, ln in enumerate(text_lines):
852
+ if needle in ln:
853
+ return i + 1
854
+ return 0
855
+
856
+
857
+ # The record writes Windows paths with BACKSLASHES (`facet_E02\out\atlas_final.png`)
858
+ # and shell fragments with variable prefixes (`"$j\inpainted.png"`). Both are matched;
859
+ # `$` and `%` are excluded from the lookbehind so a variable prefix is not swallowed
860
+ # into the path (which would mint a phantom artifact called `j/inpainted.png`).
861
+ ARTIFACT_RE = re.compile(
862
+ r"(?<![\w/\\.$%-])((?:[A-Za-z0-9_][A-Za-z0-9_.\-]*[/\\])*[A-Za-z0-9_][A-Za-z0-9_.\-]*"
863
+ r"\.(?:glb|png|npy|jsonl|json|obj|ply|ps1|sh))(?![\w])"
864
+ )
865
+ STATUS_WORDS = [
866
+ ("ACCEPTED", r"\bACCEPTED\b"),
867
+ ("REJECTED", r"\bREJECTED\b"),
868
+ ("SUPERSEDED", r"\bSUPERSEDED\b|\bsuperseded\b"),
869
+ ("WITHDRAWN", r"\bWITHDRAWN\b|\bwithdrawn\b"),
870
+ ("FROZEN", r"\bfrozen as canon\b|\bFROZEN\b"),
871
+ ]
872
+ # extensions that are the record's own instruments/inputs rather than artifacts
873
+ ARTIFACT_KIND = {
874
+ "glb": "mesh", "png": "render", "npy": "array", "json": "data",
875
+ "jsonl": "log", "obj": "mesh", "ply": "mesh", "ps1": "script", "sh": "script",
876
+ }
877
+
878
+
879
+ def parse_artifacts(ruling_index):
880
+ """Meshes, renders, sidecars and sheets, extracted by path shape.
881
+
882
+ THE RECORD HAS NO CONVENTION FOR THESE. They are paths in prose. So this is
883
+ extraction, not parsing: every path-shaped token in the markdown record becomes a
884
+ row carrying where it is mentioned, how often, and — only where a status word
885
+ stands in the same paragraph — a status. Absent that, status is NULL rather than
886
+ guessed. `provenance_ruling` is the nearest preceding ruling anchor in the same
887
+ file, which is a locality heuristic and is labelled as one.
888
+ """
889
+ seen = {}
890
+ for rel in record_markdown():
891
+ ls = lines_of(rel)
892
+ pars = paragraphs(ls, 0)
893
+ for start, par in pars:
894
+ text = "\n".join(par)
895
+ status = None
896
+ for name, pat in STATUS_WORDS:
897
+ if re.search(pat, text):
898
+ status = name
899
+ break
900
+ for m in ARTIFACT_RE.finditer(text):
901
+ raw = m.group(1)
902
+ # the KEY is separator-normalised, because `facet_E02\out\x.png` and
903
+ # `facet_E02/out/x.png` are one artifact; the LOCATOR stays raw,
904
+ # because the pointer gate looks for it in the file as written.
905
+ tok = raw.replace("\\", "/")
906
+ if tok.count(".") and tok.split(".")[-1] not in ARTIFACT_KIND:
907
+ continue
908
+ rec = seen.get(tok)
909
+ if rec is None:
910
+ rec = seen[tok] = dict(
911
+ path=tok, kind=ARTIFACT_KIND[tok.split(".")[-1]],
912
+ status=status, mentions=0,
913
+ provenance_ruling=_nearest_ruling(ruling_index, rel, start + 1),
914
+ body="", file=rel, anchor="first mentioned in %s" % rel,
915
+ locator=raw, line=start + 1,
916
+ )
917
+ rec["mentions"] += 1
918
+ if rec["status"] is None and status is not None:
919
+ rec["status"] = status
920
+ if len(rec["body"]) < 1200:
921
+ rec["body"] = (rec["body"] + " " + one_line(strip_md(text), 400)).strip()
922
+ return [seen[k] for k in sorted(seen)]
923
+
924
+
925
+ def _nearest_ruling(ruling_index, rel, line):
926
+ best = None
927
+ for r in ruling_index:
928
+ if r["file"] != rel or r["line"] > line:
929
+ continue
930
+ if best is None or r["line"] > best["line"]:
931
+ best = r
932
+ return best["anchor"] if best else None
933
+
934
+
935
+ # the record's own naming verbs. A phenomenon in this repo is minted out loud.
936
+ PHENOM_PATTERNS = [
937
+ ("banked as a measured phenomenon", r"is BANKED as a measured phenomenon"),
938
+ ("minted", r"IS MINTED|is MINTED"),
939
+ ("named forward", r"IS NAMED FORWARD"),
940
+ ("named", r"\bis NAMED\b|\bIS NAMED\b|\bis named:|\bclass is named\b"),
941
+ ("ledger form", r"the ledger takes the form, named"),
942
+ ("new law", r"a new law for the record"),
943
+ ("banked as", r"\bis BANKED as\b|\bis banked as (?:a|the|this)\b"),
944
+ ]
945
+
946
+
947
+ def parse_phenomena(rulings):
948
+ """The named measured effects.
949
+
950
+ ALSO CONVENTIONLESS, and named with at least seven different verbs. This reads
951
+ the verbs the record actually uses and reports what that catches. A phenomenon
952
+ named without one of them is invisible here, and that is the honest boundary of
953
+ the table rather than a bug to paper over with a hand-kept list — a hand-kept
954
+ list is exactly what the design forbids.
955
+ """
956
+ rows = []
957
+ for r in rulings:
958
+ text = r["holding"] + "\n" + r["body"]
959
+ hit = None
960
+ for name, pat in PHENOM_PATTERNS:
961
+ if re.search(pat, text):
962
+ hit = name
963
+ break
964
+ if hit is None:
965
+ continue
966
+ rows.append(dict(
967
+ name=one_line(r["holding"], 140),
968
+ marker=hit,
969
+ statement=one_line(r["holding"], 300),
970
+ instances=r["arc"],
971
+ body=r["body"][:4000],
972
+ file=r["file"], anchor=r["anchor"], locator=r["locator"], line=r["line"],
973
+ ))
974
+ rows.sort(key=lambda x: (x["file"], x["line"]))
975
+ return rows
976
+
977
+
978
+ def parse_prose(structured_files=None):
979
+ """Every prose section of the record that no structured table already owns.
980
+
981
+ The reports, predictions, halts, specs and kickoffs are where the MEASUREMENTS
982
+ live — a ruling cites them, and a session that can find the ruling but not the
983
+ evidence has half an index. So the whole `docs/experiments/` markdown corpus is
984
+ sectioned by heading here, alongside README, the handbook and the design docs.
985
+
986
+ Sections a structured table already owns are skipped so a holding is not indexed
987
+ twice under two identities: `## Ruling N`, `## Post-ingest addenda N` and
988
+ `## Session handoff N` blocks belong to `rulings` and `handoffs`. The E08
989
+ amendments sit inside a blockquote under `## 3.`, so that document is excluded
990
+ from prose wholesale and reached through its amendment rows.
991
+ """
992
+ owned_hdr = (RULING_HDR, ADDENDA_HDR, HANDOFF_HDR)
993
+ # EXCLUSION IS DECIDED BY WHAT A FILE YIELDED, not by whether its name matched
994
+ # the discovery pattern. The glob matches five documents that carry no numbered
995
+ # rulings — the E01/E02/E06/E07 gate-1 rulings and the Director's canon ruling —
996
+ # and excluding those on a name match would delete their prose rows outright,
997
+ # a regression the ruling counts could not show.
998
+ structured = set(structured_files or ())
999
+ files = list(PROSE_FILES)
1000
+ files += [rel for _, rel in TOPICAL_RULING_FILES]
1001
+ files += [rel for _, rel in handoff_documents()]
1002
+ files += [f for f in record_markdown()
1003
+ if f.startswith("docs/experiments/") and f not in files]
1004
+ rows = []
1005
+ for rel in sorted(set(files)):
1006
+ if rel in structured:
1007
+ continue
1008
+ ls = lines_of(rel)
1009
+ heads = [(i, m) for i, m in ((i, SECTION_HDR.match(ln)) for i, ln in enumerate(ls)) if m]
1010
+ if not heads:
1011
+ # a document with no `##` heading is still evidence; index it whole
1012
+ body = strip_md("\n".join(ls))
1013
+ if len(body.strip()) < 40:
1014
+ continue
1015
+ head, hl = _first_heading(rel)
1016
+ rows.append(dict(title=one_line(strip_md(head).lstrip("# "), 200),
1017
+ body=body, file=rel, anchor="(whole document)",
1018
+ locator=head, line=hl))
1019
+ continue
1020
+ # a `##` block owned by a structured table owns its `###` children too —
1021
+ # otherwise a handoff's task list is indexed twice, once as part of the
1022
+ # handoff row and once on its own, and the two compete in the ranking.
1023
+ owned_spans = []
1024
+ h2 = [i for i, _ in heads if ls[i].startswith("## ")]
1025
+ for k, i in enumerate(h2):
1026
+ if any(h.match(ls[i]) for h in owned_hdr):
1027
+ owned_spans.append((i, h2[k + 1] if k + 1 < len(h2) else len(ls)))
1028
+
1029
+ def is_owned(line_no):
1030
+ return any(a <= line_no < b for a, b in owned_spans)
1031
+
1032
+ # the preamble above the first `##` carries the document's own thesis
1033
+ pre = strip_md("\n".join(ls[:heads[0][0]]))
1034
+ if len(pre.strip()) >= 40:
1035
+ head, hl = _first_heading(rel)
1036
+ rows.append(dict(title=one_line(strip_md(head).lstrip("# "), 200),
1037
+ body=pre, file=rel, anchor="(preamble)",
1038
+ locator=head, line=hl))
1039
+ for k, (i, m) in enumerate(heads):
1040
+ end = heads[k + 1][0] if k + 1 < len(heads) else len(ls)
1041
+ if is_owned(i):
1042
+ continue
1043
+ title = strip_md(m.group(2)).strip()
1044
+ body = strip_md("\n".join(ls[i + 1:end]))
1045
+ if len(body.strip()) < 40:
1046
+ continue
1047
+ rows.append(dict(
1048
+ title=one_line(title, 200), body=body,
1049
+ file=rel, anchor=title[:80], locator=ls[i].rstrip()[:70], line=i + 1,
1050
+ ))
1051
+ rows.sort(key=lambda r: (r["file"], r["line"]))
1052
+ return rows
1053
+
1054
+
1055
+ # ---------------------------------------------------------------------------
1056
+ # build
1057
+ # ---------------------------------------------------------------------------
1058
+
1059
+ SCHEMA = """
1060
+ CREATE TABLE rulings (
1061
+ arc TEXT NOT NULL, number TEXT NOT NULL, parent TEXT, kind TEXT NOT NULL,
1062
+ date TEXT, verdict TEXT, authority TEXT NOT NULL,
1063
+ holding TEXT NOT NULL, file TEXT NOT NULL, anchor TEXT NOT NULL,
1064
+ locator TEXT NOT NULL, line INTEGER NOT NULL,
1065
+ supersedes TEXT, superseded_by TEXT,
1066
+ PRIMARY KEY (arc, number, kind)
1067
+ ) WITHOUT ROWID;
1068
+
1069
+ CREATE TABLE laws (
1070
+ statement TEXT NOT NULL, kind TEXT NOT NULL, section TEXT, paid_for_by TEXT,
1071
+ file TEXT NOT NULL, anchor TEXT NOT NULL, locator TEXT NOT NULL,
1072
+ line INTEGER NOT NULL
1073
+ );
1074
+
1075
+ CREATE TABLE experiments (
1076
+ id TEXT PRIMARY KEY, question TEXT, status TEXT, verdict TEXT,
1077
+ spec_file TEXT, report_file TEXT,
1078
+ file TEXT NOT NULL, anchor TEXT NOT NULL, locator TEXT NOT NULL,
1079
+ line INTEGER NOT NULL
1080
+ ) WITHOUT ROWID;
1081
+
1082
+ CREATE TABLE handoffs (
1083
+ arc TEXT NOT NULL, number INTEGER NOT NULL, date TEXT, outcome TEXT,
1084
+ commits TEXT, superseded INTEGER NOT NULL,
1085
+ file TEXT NOT NULL, anchor TEXT NOT NULL, locator TEXT NOT NULL,
1086
+ line INTEGER NOT NULL,
1087
+ PRIMARY KEY (arc, number)
1088
+ ) WITHOUT ROWID;
1089
+
1090
+ CREATE TABLE artifacts (
1091
+ path TEXT PRIMARY KEY, kind TEXT NOT NULL, status TEXT, mentions INTEGER NOT NULL,
1092
+ provenance_ruling TEXT,
1093
+ file TEXT NOT NULL, anchor TEXT NOT NULL, locator TEXT NOT NULL,
1094
+ line INTEGER NOT NULL
1095
+ ) WITHOUT ROWID;
1096
+
1097
+ CREATE TABLE phenomena (
1098
+ name TEXT NOT NULL, marker TEXT NOT NULL, statement TEXT NOT NULL,
1099
+ instances TEXT,
1100
+ file TEXT NOT NULL, anchor TEXT NOT NULL, locator TEXT NOT NULL,
1101
+ line INTEGER NOT NULL
1102
+ );
1103
+
1104
+ CREATE TABLE decisions (
1105
+ subject TEXT NOT NULL, tool TEXT NOT NULL, key TEXT NOT NULL,
1106
+ value TEXT, status TEXT NOT NULL, ruling TEXT, why TEXT,
1107
+ file TEXT NOT NULL, anchor TEXT NOT NULL, locator TEXT NOT NULL,
1108
+ line INTEGER NOT NULL,
1109
+ PRIMARY KEY (subject, tool, key)
1110
+ ) WITHOUT ROWID;
1111
+
1112
+ -- `title` is the SEARCH surface: a concatenation tuned for retrieval (arc, anchor,
1113
+ -- authority, verdict, holding). `disp` is what a reader sees — the row's own
1114
+ -- one-line holding. They are separate because optimising one degrades the other:
1115
+ -- a search title packed with arc and verdict tokens reads as noise in a result list.
1116
+ CREATE VIRTUAL TABLE fts USING fts5(
1117
+ title, body,
1118
+ tbl UNINDEXED, key UNINDEXED, file UNINDEXED, anchor UNINDEXED,
1119
+ locator UNINDEXED, line UNINDEXED, disp UNINDEXED,
1120
+ tokenize = 'unicode61 remove_diacritics 2'
1121
+ );
1122
+ """
1123
+
1124
+
1125
+ def build(db_path, quiet=False):
1126
+ rulings = parse_rulings()
1127
+ link_supersessions(rulings)
1128
+ laws = parse_laws()
1129
+ experiments = parse_experiments()
1130
+ handoffs = parse_handoffs()
1131
+ decisions = parse_decisions()
1132
+ artifacts = parse_artifacts(rulings)
1133
+ phenomena = parse_phenomena(rulings)
1134
+ prose = parse_prose({r['file'] for r in rulings})
1135
+
1136
+ d = os.path.dirname(db_path)
1137
+ if d and not os.path.isdir(d):
1138
+ os.makedirs(d) # scripts create their own output directories
1139
+ if os.path.exists(db_path):
1140
+ os.remove(db_path) # fresh DB each build; never an incremental update
1141
+
1142
+ con = sqlite3.connect(db_path)
1143
+ con.execute("PRAGMA page_size=4096")
1144
+ con.execute("PRAGMA journal_mode=DELETE")
1145
+ con.executescript(SCHEMA)
1146
+ fts = []
1147
+
1148
+ def add_fts(tbl, key, title, body, file, anchor, locator, line, disp=None):
1149
+ fts.append((title or "", body or "", tbl, key, file, anchor, locator, line,
1150
+ disp if disp is not None else (title or "")))
1151
+
1152
+ with con:
1153
+ for r in rulings:
1154
+ verdict, authority = classify(r["holding"])
1155
+ con.execute(
1156
+ "INSERT INTO rulings VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
1157
+ (r["arc"], r["number"], r["parent"], r["kind"], r["date"],
1158
+ verdict, authority, r["holding"],
1159
+ r["file"], r["anchor"], r["locator"], r["line"],
1160
+ r["supersedes"], r["superseded_by"]))
1161
+ add_fts("rulings", "%s %s" % (r["arc"], r["anchor"]),
1162
+ "%s %s %s %s %s" % (r["arc"], r["anchor"], authority,
1163
+ verdict or "", r["holding"]),
1164
+ r["body"], r["file"], r["anchor"], r["locator"], r["line"],
1165
+ disp=r["holding"])
1166
+ for r in laws:
1167
+ con.execute("INSERT INTO laws VALUES (?,?,?,?,?,?,?,?)",
1168
+ (r["statement"], r["kind"], r["section"], r["paid_for_by"],
1169
+ r["file"], r["anchor"], r["locator"], r["line"]))
1170
+ add_fts("laws", r["statement"][:60], r["statement"], r["body"],
1171
+ r["file"], r["anchor"], r["locator"], r["line"],
1172
+ disp=r["statement"])
1173
+ for r in experiments:
1174
+ con.execute("INSERT INTO experiments VALUES (?,?,?,?,?,?,?,?,?,?)",
1175
+ (r["id"], r["question"], r["status"], r["verdict"],
1176
+ r["spec_file"], r["report_file"],
1177
+ r["file"], r["anchor"], r["locator"], r["line"]))
1178
+ add_fts("experiments", r["id"], "%s %s" % (r["id"], r["question"] or ""),
1179
+ r["body"], r["file"], r["anchor"], r["locator"], r["line"],
1180
+ disp=r["question"] or r["status"])
1181
+ for r in handoffs:
1182
+ con.execute("INSERT INTO handoffs VALUES (?,?,?,?,?,?,?,?,?,?)",
1183
+ (r["arc"], r["number"], r["date"], r["outcome"], r["commits"],
1184
+ r["superseded"], r["file"], r["anchor"], r["locator"], r["line"]))
1185
+ add_fts("handoffs", "%s handoff %d" % (r["arc"], r["number"]),
1186
+ "%s handoff %d %s" % (r["arc"], r["number"], r["outcome"]),
1187
+ r["body"], r["file"], r["anchor"], r["locator"], r["line"],
1188
+ disp=r["outcome"])
1189
+ for r in artifacts:
1190
+ con.execute("INSERT INTO artifacts VALUES (?,?,?,?,?,?,?,?,?)",
1191
+ (r["path"], r["kind"], r["status"], r["mentions"],
1192
+ r["provenance_ruling"], r["file"], r["anchor"],
1193
+ r["locator"], r["line"]))
1194
+ add_fts("artifacts", r["path"], r["path"], r["body"],
1195
+ r["file"], r["anchor"], r["locator"], r["line"],
1196
+ disp="%s [%s%s] %d mentions" % (r["path"], r["kind"],
1197
+ "/" + r["status"] if r["status"] else "", r["mentions"]))
1198
+ for r in phenomena:
1199
+ con.execute("INSERT INTO phenomena VALUES (?,?,?,?,?,?,?,?)",
1200
+ (r["name"], r["marker"], r["statement"], r["instances"],
1201
+ r["file"], r["anchor"], r["locator"], r["line"]))
1202
+ add_fts("phenomena", r["anchor"], r["statement"], r["body"],
1203
+ r["file"], r["anchor"], r["locator"], r["line"],
1204
+ disp=r["statement"])
1205
+ for r in decisions:
1206
+ con.execute("INSERT INTO decisions VALUES (?,?,?,?,?,?,?,?,?,?,?)",
1207
+ (r["subject"], r["tool"], r["key"], r["value"], r["status"],
1208
+ r["ruling"], r["why"], r["file"], r["anchor"],
1209
+ r["locator"], r["line"]))
1210
+ add_fts("decisions", "%s %s %s" % (r["subject"], r["tool"], r["key"]),
1211
+ "%s %s %s %s" % (r["subject"], r["tool"], r["key"], r["value"]),
1212
+ r["body"], r["file"], r["anchor"], r["locator"], r["line"],
1213
+ disp="%s = %s [%s]" % (r["key"], r["value"], r["status"]))
1214
+ for r in prose:
1215
+ add_fts("prose", "%s · %s" % (r["file"], r["title"]),
1216
+ r["title"], r["body"], r["file"], r["anchor"],
1217
+ r["locator"], r["line"], disp=r["title"])
1218
+ con.executemany(
1219
+ "INSERT INTO fts (title, body, tbl, key, file, anchor, locator, line, disp) "
1220
+ "VALUES (?,?,?,?,?,?,?,?,?)", fts)
1221
+ con.execute("VACUUM") # fixed final layout, so two builds compare byte-wise
1222
+ con.close()
1223
+
1224
+ counts = dict(rulings=len(rulings), laws=len(laws), experiments=len(experiments),
1225
+ handoffs=len(handoffs), artifacts=len(artifacts),
1226
+ phenomena=len(phenomena), decisions=len(decisions),
1227
+ prose_sections=len(prose), fts=len(fts))
1228
+ if not quiet:
1229
+ print("[build] %s" % db_path)
1230
+ for k in sorted(counts):
1231
+ print(" %-16s %6d" % (k, counts[k]))
1232
+ return counts
1233
+
1234
+
1235
+ # ---------------------------------------------------------------------------
1236
+ # verify — four legs, non-zero exit on any failure
1237
+ # ---------------------------------------------------------------------------
1238
+
1239
+ SEEDED = [
1240
+ ("canny values for the beast",
1241
+ "canny values beast ratified register",
1242
+ ("docs/experiments/E12-ruling.md", "Ruling 11a")),
1243
+ ("which seed resists terms",
1244
+ "seed view map term resistance",
1245
+ ("docs/experiments/E12-ruling.md", "Ruling 21c")),
1246
+ ("the backdrop word and why",
1247
+ "backdrop word lavender grey background",
1248
+ ("docs/experiments/E12-ruling.md", "Ruling 8a")),
1249
+ ("the backdrop word's correction",
1250
+ "Ruling 8a premise corrected in place word stands",
1251
+ ("docs/experiments/E12-ruling.md", "Ruling 15i")),
1252
+ ("thin_extent on the beast",
1253
+ "thin_extent ruled global artifact criterion",
1254
+ ("docs/experiments/E12-ruling.md", "Ruling 25c")),
1255
+ ("why elevated cameras are closed",
1256
+ "elevated cameras NONE",
1257
+ ("docs/experiments/E12-ruling.md", "Ruling 7a")),
1258
+ ("why elevated cameras stay closed",
1259
+ "elevated re-open closes falsifier up-facing",
1260
+ ("docs/experiments/E12-ruling.md", "Ruling 25b")),
1261
+ ("the dragon's reach ceiling",
1262
+ "ceiling banked valid eight eye-level cameras",
1263
+ ("docs/experiments/E12-ruling.md", "Ruling 6a")),
1264
+ ("what happened to the crop pass",
1265
+ "A0 stands stage 1 crop pass registers",
1266
+ ("docs/experiments/E12-ruling.md", "Ruling 24b")),
1267
+ ("when the pair was accepted",
1268
+ "THE PAIR IS ACCEPTED",
1269
+ ("docs/experiments/E12-ruling.md", "Ruling 14")),
1270
+ ("the fifth brush signature",
1271
+ "fifth signature dark desaturated crevice",
1272
+ ("docs/experiments/E12-ruling.md", "Ruling 27d")),
1273
+ ("what a ruling pays values in",
1274
+ "ruling decides values registry entries not prose",
1275
+ ("docs/experiments/E12-ruling.md", "Ruling 26a")),
1276
+ # Anchors PINNED rather than left file-level. The dispatch's key for these two
1277
+ # named a file and a value; the value was then located in the record — the mix
1278
+ # digits at E04-ruling.md:1658, inside Ruling 27 — and the gate now names the row
1279
+ # that carries it. Left file-level, `the galleon's accepted mix` passed on
1280
+ # Ruling 24, which shares the six query words and carries none of the digits: a
1281
+ # gate that cannot tell the right row from a coincidence is not testing anything.
1282
+ # Pinning makes the condition strictly harder and derives it from the record.
1283
+ ("the retired keying method",
1284
+ "corner-median keying retired failed three times",
1285
+ ("CLAUDE.md",
1286
+ "Rules for everyone · Corner-median keying has failed three times; it is retired")),
1287
+ # WITHDRAWN 2026-08-08 (E14 Ruling 31e), under the standing law's own words:
1288
+ # "withdrawn, never re-crafted, if the live corpus outranks them." The seed
1289
+ # `the galleon's accepted mix` (targets E04-ruling.md Ruling 27 / README The
1290
+ # route / handbook The galleon) regressed the gate to 19/20 when E14's
1291
+ # handoff-9 report restated the comparables AS RULING 30 ORDERED - the
1292
+ # displacing documents legitimately carry the digits, and a route that
1293
+ # restates its comparables per subject will displace their canonical home
1294
+ # once per subject, structurally. The prior comment block here had already
1295
+ # named the class ("the rest are cross-subject comparisons... quoting this
1296
+ # key"). A digit-keyed query whose digits the route deliberately propagates
1297
+ # is a seed with a structural expiry. The entry is removed, not re-crafted;
1298
+ # the history is this comment.
1299
+ # E14 seeds, added 2026-08-07: every phrase ran report-only through q FIRST and
1300
+ # its target ranked <= 3 BEFORE the row entered the gate — seeds are ruled in
1301
+ # from measured ranks, never added and then tuned until green.
1302
+ # WITHDRAWN same fold: "the rings term" (target Ruling 13) — measured rank 2,
1303
+ # then MISSED at the gate minutes later: the live handoff-3 lane had committed
1304
+ # fresh rings-term content (its blind predictions + the handoff row itself)
1305
+ # that legitimately outranks a generic phrase. Withdrawn rather than
1306
+ # re-crafted, per this block's own rule; a Ruling-13 seed can be re-derived
1307
+ # with distinctive language once the arc is quiet. The gate firing on a
1308
+ # measurement made minutes earlier is the leg working, not a defect.
1309
+ ("the hollow finding",
1310
+ "the hollow finding",
1311
+ ("docs/experiments/E14-ruling.md", "Ruling 3")),
1312
+ ("the sword's canny pair",
1313
+ "the sword's canny pair",
1314
+ ("docs/experiments/E14-ruling.md", "Ruling 6")),
1315
+ ("the backdrop word for the sword",
1316
+ "the ruled backdrop word plain lavender",
1317
+ ("docs/experiments/E14-ruling.md", "Ruling 7")),
1318
+ ("why the off-surface class broke",
1319
+ "off-surface margin statistic not a bake constant",
1320
+ ("docs/experiments/E14-ruling.md", "Ruling 9")),
1321
+ ("the prop's ceiling mechanism",
1322
+ "ceiling topology fact not camera count",
1323
+ ("docs/experiments/E14-ruling.md", "Ruling 10b")),
1324
+ ("the activated state",
1325
+ "the activated state",
1326
+ ("docs/experiments/E14-ruling.md", "Ruling 16c")),
1327
+ ]
1328
+
1329
+ # counts the verifier re-derives from the record itself, with its own patterns —
1330
+ # never from the builder's parsers.
1331
+ COUNT_CHECKS = [
1332
+ ("E12 numbered rulings", "docs/experiments/E12-ruling.md", r"^## Ruling (\d+)\b",
1333
+ "rulings", "arc='E12' AND kind='ruling'"),
1334
+ # the measured convention: letter, SPACE, dash. Written here independently of
1335
+ # the parser's constants so the two are not one implementation checking itself.
1336
+ ("E12 lettered sub-rulings", "docs/experiments/E12-ruling.md",
1337
+ r"^\*\*\d+[a-z] +[—–-]", "rulings", "arc='E12' AND kind='sub-ruling'"),
1338
+ ("E12 closure markers", "docs/experiments/E12-ruling.md",
1339
+ r"^\*\*\d+[a-z]-[A-Z]", "rulings", "arc='E12' AND kind='sub-ruling-closure'"),
1340
+ ("E04 lettered sub-rulings", "docs/experiments/E04-ruling.md",
1341
+ r"^\*\*\d+[a-z] +[—–-]", "rulings", "arc='E04' AND kind='sub-ruling'"),
1342
+ ("E10off lettered sub-rulings", "docs/experiments/E10-offsurface-ruling.md",
1343
+ r"^\*\*\d+[a-z] +[—–-]", "rulings", "arc='E10-offsurface' AND kind='sub-ruling'"),
1344
+ ("E04 numbered rulings", "docs/experiments/E04-ruling.md", r"^## Ruling (\d+)\b",
1345
+ "rulings", "arc='E04' AND kind='ruling'"),
1346
+ ("E10 numbered rulings", "docs/experiments/E10-ruling.md", r"^## Ruling (\d+)\b",
1347
+ "rulings", "arc='E10' AND kind='ruling'"),
1348
+ ("E11 numbered rulings", "docs/experiments/E11-ruling.md", r"^## Ruling (\d+)\b",
1349
+ "rulings", "arc='E11' AND kind='ruling'"),
1350
+ ("E11 post-ingest addenda", "docs/experiments/E11-ruling.md",
1351
+ r"^## Post-ingest addenda", "rulings", "arc='E11' AND kind='addendum'"),
1352
+ ("E08 amendments", "docs/experiments/E08-ruling-gate0.md",
1353
+ r"^> ### (?:⚠\s*)?Amendment (\d+) \(", "rulings", "arc='E08' AND kind='amendment'"),
1354
+ ("E15 numbered rulings", "docs/experiments/E15-ruling.md", r"^## Ruling (\d+)\b",
1355
+ "rulings", "arc='E15' AND kind='ruling'"),
1356
+ ("E15 lettered sub-rulings", "docs/experiments/E15-ruling.md",
1357
+ r"^\*\*\d+[a-z] +[—–-]", "rulings", "arc='E15' AND kind='sub-ruling'"),
1358
+ ("E12 handoffs", "docs/experiments/E12-executor-kickoff.md",
1359
+ r"^## Session handoff", "handoffs", "arc='E12'"),
1360
+ ("E04 handoffs", "docs/experiments/E04-executor-kickoff.md",
1361
+ r"^## Session handoff", "handoffs", "arc='E04'"),
1362
+ # E14 legs added 2026-08-07 while E14 is the LIVE arc — the gate had count legs
1363
+ # only for closed arcs, which is backwards: the live record is the one drifting.
1364
+ ("E14 numbered rulings", "docs/experiments/E14-ruling.md", r"^## Ruling (\d+)\b",
1365
+ "rulings", "arc='E14' AND kind='ruling'"),
1366
+ ("E14 lettered sub-rulings", "docs/experiments/E14-ruling.md",
1367
+ r"^\*\*\d+[a-z] +[—–-]", "rulings", "arc='E14' AND kind='sub-ruling'"),
1368
+ ("E14 handoffs", "docs/experiments/E14-executor-kickoff.md",
1369
+ r"^## Session handoff", "handoffs", "arc='E14'"),
1370
+ # E16 legs added 2026-08-08 (E17 T15, the E15 Ruling 8b pattern): the ruling
1371
+ # landed this same day and its rows enter the gate the day they exist. E17's
1372
+ # own legs deliberately did NOT, in that same commit: no E17-ruling.md
1373
+ # existed yet and its kickoff carries no handoff headers, so an E17 leg then
1374
+ # would have grepped a file that is not there — a check that cannot fail.
1375
+ ("E16 numbered rulings", "docs/experiments/E16-ruling.md", r"^## Ruling (\d+)\b",
1376
+ "rulings", "arc='E16' AND kind='ruling'"),
1377
+ ("E16 lettered sub-rulings", "docs/experiments/E16-ruling.md",
1378
+ r"^\*\*\d+[a-z] +[—–-]", "rulings", "arc='E16' AND kind='sub-ruling'"),
1379
+ # E17 legs added on the ruling's own landing (T15b, E17 Ruling 3e) — the
1380
+ # deferred half, unblocked by the file existing. Counts VERIFIED against
1381
+ # source before the legs were written rather than taken from the dispatch:
1382
+ # 4 numbered (1-4) and 10 lettered (1a-1d, 3a-3f), 14 rows, matching both
1383
+ # the fold's reported figure and the DB. No handoffs leg: the E17 kickoff
1384
+ # carries no `## Session handoff` header, so that half stays deferred on
1385
+ # the same reasoning that deferred all of it a commit earlier.
1386
+ ("E17 numbered rulings", "docs/experiments/E17-ruling.md", r"^## Ruling (\d+)\b",
1387
+ "rulings", "arc='E17' AND kind='ruling'"),
1388
+ ("E17 lettered sub-rulings", "docs/experiments/E17-ruling.md",
1389
+ r"^\*\*\d+[a-z] +[—–-]", "rulings", "arc='E17' AND kind='sub-ruling'"),
1390
+ ]
1391
+
1392
+
1393
+ def _grep_count(rel, pattern):
1394
+ rx = re.compile(pattern)
1395
+ return sum(1 for ln in lines_of(rel) if rx.match(ln))
1396
+
1397
+
1398
+ def _sequence_numbers(con, arc, kind):
1399
+ rows = con.execute(
1400
+ "SELECT number FROM rulings WHERE arc=? AND kind=?", (arc, kind)).fetchall()
1401
+ have = set()
1402
+ for (n,) in rows:
1403
+ m = re.match(r"^A?(\d+)$", n)
1404
+ if m:
1405
+ have.add(int(m.group(1)))
1406
+ return sorted(have)
1407
+
1408
+
1409
+ def _sequence_gaps(con, arc, kind, lo, hi):
1410
+ return sorted(set(range(lo, hi + 1)) - set(_sequence_numbers(con, arc, kind)))
1411
+
1412
+
1413
+ # Ordinary English function words. Measured on this corpus BEFORE they were removed:
1414
+ # "the" appears in 94.9% of indexed rows, "is" in 77.9%, "not" in 62.2%. An OR query
1415
+ # carrying them matches nearly everything, and the discriminating term ("galleon",
1416
+ # 10.0%; "mix", 1.7%) is then one weak signal among many. This list is generic — it
1417
+ # is not derived from any question in the seeded set.
1418
+ STOPWORDS = frozenset("""
1419
+ a an and are as at be been but by can did do does for from had has have how i if in
1420
+ into is it its of on or our so than that the their them then there these they this
1421
+ to was we were what when where which who why will with would you your not no nor
1422
+ """.split())
1423
+
1424
+ CANDIDATES = 400 # re-ranking window; fixed, so `q` is deterministic
1425
+
1426
+ # Exact-phrase hits are a BEST-BET SLOT, not a takeover. Uncapped, a phrase that
1427
+ # happens to appear in a pointer document monopolises the page: this repo's own
1428
+ # dispatch quotes every seeded question verbatim, so `q "the fifth brush signature"`
1429
+ # returned three documents that merely POINT at Ruling 27d ahead of the ruling — the
1430
+ # ruling says "fifth signature", not "fifth brush signature", so it is not a phrase
1431
+ # match at all. Three slots keeps the exact match's priority and leaves the rest of
1432
+ # the page to relevance.
1433
+ PHRASE_SLOTS = 3
1434
+
1435
+
1436
+ def fts_terms(phrase):
1437
+ """Content words of a query phrase, lowercased, stopwords dropped."""
1438
+ words = [w.lower() for w in re.findall(r"[A-Za-z0-9_][A-Za-z0-9_.'-]*", phrase)
1439
+ if len(w) > 1]
1440
+ kept = [w for w in words if w not in STOPWORDS]
1441
+ return kept or words # never return an empty query
1442
+
1443
+
1444
+ def fts_or(phrase):
1445
+ return " OR ".join('"%s"' % w for w in fts_terms(phrase))
1446
+
1447
+
1448
+ # ---------------------------------------------------------------------------
1449
+ # claims — the stale-claim sweep. REPORT-ONLY BY RULING, never a gate.
1450
+ #
1451
+ # The diagnostic-vs-gate law is the grounds (E15 handoff 2): this sweep swings on
1452
+ # phrasing and on document class, and neither may decide an exit code. It exits 0
1453
+ # whatever it finds. Stale sites are the advisor's to rule, never this seat's to fix.
1454
+ #
1455
+ # It reads the INDEX's measurements rather than re-deriving them from the record —
1456
+ # the index already did that derivation under the four ratified verify legs, and a
1457
+ # second derivation here would be a second authority.
1458
+ # ---------------------------------------------------------------------------
1459
+
1460
+ # Documents that state their counts AS OF NOW and must match the measurement.
1461
+ CURRENT_STATE = {
1462
+ "README.md",
1463
+ "CLAUDE.md",
1464
+ "docs/context-architecture.md",
1465
+ "docs/style-registers.md",
1466
+ "docs/experiments/README.md",
1467
+ }
1468
+ CURRENT_STATE_DIRS = ("docs/handbook/",)
1469
+ # A kickoff or spec states its counts as of writing, and is correct as written.
1470
+ HISTORICAL_DIRS = ("docs/experiments/", "docs/research/")
1471
+ BANNERED = "docs/advisor-kickoff.md" # current-state ABOVE its supersession banner
1472
+ BANNER_RE = re.compile(r"SUPERSEDED")
1473
+
1474
+
1475
+ def _banner_line(rel):
1476
+ """1-based line of the first supersession banner, or None."""
1477
+ for i, ln in enumerate(lines_of(rel), 1):
1478
+ if BANNER_RE.search(ln):
1479
+ return i
1480
+ return None
1481
+
1482
+
1483
+ def classify_document(rel, line):
1484
+ """(class, why) for a claim at `rel:line`. Printed with every row."""
1485
+ if rel == BANNERED:
1486
+ b = _banner_line(rel)
1487
+ if b is None:
1488
+ return "current-state", "the advisor kickoff, no supersession banner found"
1489
+ if line < b:
1490
+ return "current-state", "advisor kickoff, above the banner at L%d" % b
1491
+ return "historical", "advisor kickoff, below the banner at L%d" % b
1492
+ if rel in CURRENT_STATE or rel.startswith(CURRENT_STATE_DIRS):
1493
+ return "current-state", "on the dispatch's current-state list"
1494
+ if rel.startswith(HISTORICAL_DIRS):
1495
+ return "historical", "a kickoff / spec / report — states its counts as of writing"
1496
+ return "unclassified", "on neither list — reported, not assigned"
1497
+
1498
+
1499
+ # The claim families, each written from a phrasing the record actually uses. A
1500
+ # RANGE claim asserts the highest number; a CARDINAL claim asserts how many exist.
1501
+ # They are different assertions and are compared against different measurements —
1502
+ # E12 carries handoffs numbered to 16 but only 15 of them, because handoff 1 was
1503
+ # never labelled, so conflating the two would manufacture a stale row.
1504
+ CLAIM_FAMILIES = [
1505
+ ("rulings range", "ruling", "max",
1506
+ re.compile(r"\bRulings?\s+1\s*[–—-]\s*(\d+)")),
1507
+ ("rulings cardinal", "ruling", "count",
1508
+ re.compile(r"\b(\d+)\s+rulings\b")),
1509
+ ("amendments cardinal", "amendment", "count",
1510
+ re.compile(r"\b(\d+)\s+amendments\b")),
1511
+ ("addenda cardinal", "addendum", "count",
1512
+ re.compile(r"\b(\d+)\s+addenda\b")),
1513
+ ("handoffs range", "handoff", "max",
1514
+ re.compile(r"\bhandoffs?\s+1\s*[–—-]\s*(\d+)")),
1515
+ ("handoffs cardinal", "handoff", "count",
1516
+ re.compile(r"\b(\d+)\s+handoffs\b")),
1517
+ ("experiment span", "experiment", "max",
1518
+ re.compile(r"\bE01\s*[–—-]\s*E?(\d+)")),
1519
+ ]
1520
+
1521
+ # Modifiers that make a count-claim ambiguous rather than wrong. `29 rulings + the
1522
+ # close` may assert 29 or 30 depending on what "the close" is counted as; choosing a
1523
+ # reading would be inventing a claim to check.
1524
+ AMBIGUOUS_SUFFIX = re.compile(r"\+\s*the\s+close|\bso far\b|\bat least\b|\bor so\b")
1525
+
1526
+ # Anything count-claim-SHAPED. What this matches and no family parses is reported as
1527
+ # unparseable rather than guessed at.
1528
+ #
1529
+ # A RANGE IS ONLY A COUNT-CLAIM IF IT STARTS AT 1. `Rulings 1–30` asserts that thirty
1530
+ # exist; `Rulings 21–23` names three of them and asserts nothing about the total. An
1531
+ # earlier version of this pattern did not make that distinction and reported 35 such
1532
+ # references as unparseable — noise that would have buried the two rows that matter.
1533
+ CLAIM_SHAPED = re.compile(
1534
+ r"\b\d+\s+(?:rulings|amendments|addenda|handoffs|experiments)\b"
1535
+ r"|\b(?:Rulings?|Amendments?|Handoffs?|Addenda)\s+1\s*[–—-]\s*\d+"
1536
+ r"|\bE01\s*[–—-]\s*E?\d\d\b", re.IGNORECASE)
1537
+
1538
+ ARC_RE = re.compile(r"\bE(\d\d)\b")
1539
+
1540
+
1541
+ def measurements(con):
1542
+ """Every count this sweep can check, read from the index."""
1543
+ m = {}
1544
+ for kind in ("ruling", "amendment", "addendum"):
1545
+ for arc, n, mx in con.execute(
1546
+ "SELECT arc, COUNT(*), MAX(CAST(replace(number,'A','') AS INTEGER)) "
1547
+ "FROM rulings WHERE kind=? GROUP BY arc", (kind,)):
1548
+ m[(arc, kind)] = {"count": n, "max": mx}
1549
+ for arc, n, mx in con.execute(
1550
+ "SELECT arc, COUNT(*), MAX(number) FROM handoffs GROUP BY arc"):
1551
+ m[(arc, "handoff")] = {"count": n, "max": mx}
1552
+ n, mx = con.execute(
1553
+ "SELECT COUNT(*), MAX(CAST(substr(id,2) AS INTEGER)) FROM experiments").fetchone()
1554
+ m[("*", "experiment")] = {"count": n, "max": mx}
1555
+ return m
1556
+
1557
+
1558
+ def claims(db_path):
1559
+ con = sqlite3.connect(db_path)
1560
+ meas = measurements(con)
1561
+ con.close() # every measurement is read above; see verify's note
1562
+ rows, unparseable, families_seen = [], [], {}
1563
+
1564
+ for rel in record_markdown():
1565
+ # E15's own documents QUOTE these counts as data — the seeded key, the
1566
+ # predictions, this report. Sweeping them would flag the sweep's own subject
1567
+ # matter, which is the self-reference property already recorded in §5.
1568
+ if os.path.basename(rel).startswith("E15-"):
1569
+ continue
1570
+ for i, ln in enumerate(lines_of(rel), 1):
1571
+ consumed = []
1572
+ for fam, kind, unit, rx in CLAIM_FAMILIES:
1573
+ for m in rx.finditer(ln):
1574
+ consumed.append((m.start(), m.end()))
1575
+ families_seen.setdefault(fam, []).append("%s:%d" % (rel, i))
1576
+ claimed = int(m.group(1))
1577
+ if kind == "experiment":
1578
+ arc = "*"
1579
+ else:
1580
+ # the arc governing this claim: the nearest E-number at or
1581
+ # before the match, which is how the record writes it —
1582
+ # `[E12-ruling.md](…), Rulings 1–30`. The window must span a
1583
+ # markdown link, so the search is over the raw prefix and
1584
+ # not over a dot-free window.
1585
+ pre = ARC_RE.findall(ln[:m.end()])
1586
+ if pre:
1587
+ arc = "E" + pre[-1]
1588
+ else:
1589
+ # A document named for an arc governs the claims it makes
1590
+ # without naming one: E04's kickoff writing "(Rulings
1591
+ # 1–12)" is claiming about E04. Falling back to the
1592
+ # filename is the record's own convention, not a guess.
1593
+ fn = ARC_RE.match(os.path.basename(rel))
1594
+ arc = "E" + fn.group(1) if fn else None
1595
+ if arc is None:
1596
+ unparseable.append((rel, i, m.group(0),
1597
+ "no arc attributable on this line"))
1598
+ continue
1599
+ key = (arc, kind)
1600
+ if key not in meas:
1601
+ unparseable.append((rel, i, m.group(0),
1602
+ "no measurement for %s %s" % (arc, kind)))
1603
+ continue
1604
+ real = meas[key][unit]
1605
+ cls, why = classify_document(rel, i)
1606
+ tail = ln[m.end():m.end() + 40]
1607
+ amb = bool(AMBIGUOUS_SUFFIX.search(tail))
1608
+ if amb:
1609
+ verdict = "AMBIGUOUS"
1610
+ elif claimed == real:
1611
+ verdict = "ok"
1612
+ elif cls == "current-state":
1613
+ verdict = "STALE"
1614
+ else:
1615
+ verdict = "as-of-writing"
1616
+ rows.append(dict(file=rel, line=i, fam=fam, arc=arc, kind=kind,
1617
+ unit=unit, claimed=claimed, measured=real,
1618
+ cls=cls, why=why, verdict=verdict,
1619
+ text=m.group(0).strip(),
1620
+ tail=tail.strip()[:34]))
1621
+ for m in CLAIM_SHAPED.finditer(ln):
1622
+ if any(s <= m.start() < e for s, e in consumed):
1623
+ continue
1624
+ unparseable.append((rel, i, m.group(0).strip(),
1625
+ "count-claim-shaped; no family parses it"))
1626
+
1627
+ print("=" * 78)
1628
+ print("facet_index claims - the stale-claim sweep (REPORT-ONLY; always exits 0)")
1629
+ print("=" * 78)
1630
+ print("\nMeasured, from the index:")
1631
+ for (arc, kind) in sorted(meas, key=lambda k: (k[0], k[1])):
1632
+ v = meas[(arc, kind)]
1633
+ print(" %-16s %-10s count %-4s max %s" % (arc, kind, v["count"], v["max"]))
1634
+
1635
+ order = {"STALE": 0, "AMBIGUOUS": 1, "ok": 2, "as-of-writing": 3}
1636
+ rows.sort(key=lambda r: (order.get(r["verdict"], 9), r["file"], r["line"]))
1637
+ # file:line goes LAST so a long path is never truncated — the whole point of the
1638
+ # row is that a human can open the site it names.
1639
+ print("\n%-14s %-14s %-11s %-11s %s"
1640
+ % ("verdict", "class", "claims", "measured", "file:line"))
1641
+ print("-" * 78)
1642
+ for r in rows:
1643
+ print("%-14s %-14s %-11s %-11s %s:%d"
1644
+ % (r["verdict"], r["cls"],
1645
+ "%s %d" % (r["unit"], r["claimed"]),
1646
+ "%s %s" % (r["unit"], r["measured"]),
1647
+ r["file"], r["line"]))
1648
+ print("%-14s %s - %s - %s" % ("", r["fam"], r["arc"], r["why"]))
1649
+
1650
+ stale = [r for r in rows if r["verdict"] == "STALE"]
1651
+ amb = [r for r in rows if r["verdict"] == "AMBIGUOUS"]
1652
+ print("\n" + "-" * 78)
1653
+ print("STALE (current-state documents disagreeing with the record): %d" % len(stale))
1654
+ for r in stale:
1655
+ print(" %s:%d claims %s %d, record has %s %d [%s]"
1656
+ % (r["file"], r["line"], r["unit"], r["claimed"],
1657
+ r["unit"], r["measured"], r["fam"]))
1658
+ print("\nAMBIGUOUS (a modifier makes the assertion unresolvable): %d" % len(amb))
1659
+ for r in amb:
1660
+ print(" %s:%d \"%s %s\" - reported, not resolved to a number"
1661
+ % (r["file"], r["line"], r["text"], r["tail"]))
1662
+ print("\nUNPARSEABLE (count-claim-shaped, no family): %d" % len(unparseable))
1663
+ for rel, i, txt, why in unparseable:
1664
+ print(" %s:%d \"%s\" - %s" % (rel, i, txt, why))
1665
+
1666
+ print("\nPhrasing families found on the record: %d" % len(families_seen))
1667
+ for fam in sorted(families_seen):
1668
+ sites = families_seen[fam]
1669
+ print(" %-20s %2d site(s) e.g. %s" % (fam, len(sites), sites[0]))
1670
+ missing = [f[0] for f in CLAIM_FAMILIES if f[0] not in families_seen]
1671
+ if missing:
1672
+ print(" families with no site on the current record: %s" % ", ".join(missing))
1673
+
1674
+ print("\nHealthy state is zero STALE rows. This verb never gates: exit 0.")
1675
+ return 0
1676
+
1677
+
1678
+ def query(con, phrase, limit=8):
1679
+ """Two-stage retrieval: exact phrase first, then bm25 scaled by term coverage.
1680
+
1681
+ Why not bm25 alone: the record repeats its vocabulary across four arcs — every
1682
+ subject's mix discussion says "reference brush dilation" — so a disjunction ranks
1683
+ a row matching a few common terms alongside one matching every term. The target
1684
+ is usually the row that matches every term (measured 4/4, 6/6 and 7/7 on three
1685
+ seeded questions), so a row missing terms is penalised in proportion.
1686
+
1687
+ Why coverage SCALES bm25 rather than overriding it: overriding was tried and
1688
+ FALSIFIED — coordination level as the primary sort key scored 9/14 against
1689
+ bm25's 12/14, because it discards length normalisation and long prose sections
1690
+ trivially contain every term. Ranking by title-coverage first was also tried and
1691
+ scored 11/14. Scaling keeps bm25's length normalisation and reached 13/14. Every
1692
+ variant is a generic retrieval mechanism; none knows about a specific document,
1693
+ and no seeded question was altered to fit any of them.
1694
+ """
1695
+ # `disp` is returned for display; `title || body` is returned for coverage
1696
+ # scoring. bm25 weights name the INDEXED columns only: title, then body.
1697
+ sql = ("SELECT file, anchor, disp, line, tbl, "
1698
+ "bm25(fts, 8.0, 1.0) AS r, title || ' ' || body "
1699
+ "FROM fts WHERE fts MATCH ? ORDER BY r, file, line LIMIT ?")
1700
+ out, seen = [], set()
1701
+
1702
+ # STAGE 1 — the exact adjacent phrase, over the FULL word run with stopwords
1703
+ # KEPT, because a phrase is adjacency and dropping "the"/"is" breaks it. This is
1704
+ # what makes a quoted holding find its own ruling: `THE PAIR IS ACCEPTED` is
1705
+ # Ruling 14's title verbatim, while a bag of {pair, accepted} cannot separate the
1706
+ # acceptance from three rulings that merely mention an accepted artifact — the
1707
+ # acceptance loses on length alone (body 2,084 chars against 221, with the
1708
+ # HIGHEST term frequency in the corpus). Measured: this stage is the difference
1709
+ # between 13/14 and 14/14 on the seeded set.
1710
+ words = [w.lower() for w in re.findall(r"[A-Za-z0-9_][A-Za-z0-9_.'-]*", phrase)
1711
+ if len(w) > 1]
1712
+ if len(words) > 1:
1713
+ try:
1714
+ for f, a, t, line, tbl, r, _ in con.execute(
1715
+ sql, ('"%s"' % " ".join(words), PHRASE_SLOTS)).fetchall():
1716
+ if (f, a) not in seen:
1717
+ seen.add((f, a))
1718
+ out.append((f, a, t, line, tbl, r))
1719
+ except sqlite3.OperationalError:
1720
+ pass
1721
+
1722
+ # STAGE 2 — relaxed: content words OR'd, bm25 scaled by term coverage
1723
+ ts = fts_terms(phrase)
1724
+ try:
1725
+ rows = con.execute(
1726
+ sql, (" OR ".join('"%s"' % w for w in ts), CANDIDATES)).fetchall()
1727
+ except sqlite3.OperationalError:
1728
+ return out[:limit]
1729
+ scored = []
1730
+ for f, a, t, line, tbl, r, hay in rows:
1731
+ low = hay.lower()
1732
+ cover = sum(1 for w in ts if w in low)
1733
+ # bm25 is negative-better; scaling a negative score by a fraction < 1 moves
1734
+ # it toward zero, i.e. demotes it. Floor at one term so a row never scores 0.
1735
+ scored.append((r * (max(cover, 1) / float(len(ts))), f, line,
1736
+ (f, a, t, line, tbl, r)))
1737
+ scored.sort(key=lambda s: (s[0], s[1], s[2]))
1738
+ for row in (s[3] for s in scored):
1739
+ if (row[0], row[1]) not in seen:
1740
+ seen.add((row[0], row[1]))
1741
+ out.append(row)
1742
+ return out[:limit]
1743
+
1744
+
1745
+ def verify(db_path, top_n=3):
1746
+ fails = []
1747
+ print("=" * 78)
1748
+ print("facet_index verify - four legs")
1749
+ print("=" * 78)
1750
+
1751
+ # ---- leg 1: determinism -------------------------------------------------
1752
+ # E16 Ruling 3 (the twelfth errand): the temp paths are PER-PROCESS unique,
1753
+ # same directory. Two verifies in one working copy used to write the same
1754
+ # two fixed files (db + ".det_a"/".det_b") and could read each other's
1755
+ # bytes mid-build - both seats hit that independently on the day it was
1756
+ # found (the advisor's fold colliding with E16-1's own verify; retried
1757
+ # clean, flagged). The collision is now impossible by construction rather
1758
+ # than retried on sight. A crashed process can strand its pid-named temps;
1759
+ # they are inert - no later run reads a name it did not mint - and leg 1
1760
+ # removes its own on every path.
1761
+ print("\n[leg 1] determinism - two builds from an unchanged record")
1762
+ tmp_a = db_path + ".det_a.%d" % os.getpid()
1763
+ tmp_b = db_path + ".det_b.%d" % os.getpid()
1764
+ build(tmp_a, quiet=True)
1765
+ build(tmp_b, quiet=True)
1766
+ with open(tmp_a, "rb") as fh:
1767
+ ba = fh.read()
1768
+ with open(tmp_b, "rb") as fh:
1769
+ bb = fh.read()
1770
+ if ba == bb:
1771
+ print(" BYTE-IDENTICAL %d bytes, both builds" % len(ba))
1772
+ det_leg = "byte-identity"
1773
+ else:
1774
+ da = "\n".join(sqlite3.connect(tmp_a).iterdump())
1775
+ db_ = "\n".join(sqlite3.connect(tmp_b).iterdump())
1776
+ if da == db_:
1777
+ first = next((i for i in range(min(len(ba), len(bb))) if ba[i] != bb[i]), -1)
1778
+ print(" byte-identity FAILED (first differing offset %d of %d/%d bytes)"
1779
+ % (first, len(ba), len(bb)))
1780
+ print(" .DUMP-IDENTICAL %d chars - logical determinism holds"
1781
+ % len(da))
1782
+ det_leg = ".dump-identity (pre-registered fallback)"
1783
+ else:
1784
+ print(" FAIL - neither byte- nor .dump-identical")
1785
+ fails.append("determinism: two builds differ logically")
1786
+ det_leg = "NEITHER"
1787
+ for p in (tmp_a, tmp_b):
1788
+ if os.path.exists(p):
1789
+ os.remove(p)
1790
+
1791
+ con = sqlite3.connect(db_path)
1792
+
1793
+ # ---- the discovered corpus, printed so the glob's misses are visible ------
1794
+ # A discovery rule nobody can audit is the hardcoded list's defect wearing a
1795
+ # different hat. This prints what the pattern found and what each file yielded,
1796
+ # so a ruling document that stops matching — or one that never did — is visible
1797
+ # in the transcript rather than inferred from a count that looks plausible.
1798
+ print("\n[corpus] ruling documents discovered by the sorted glob")
1799
+ docs = ruling_documents()
1800
+ for arc, rel in docs:
1801
+ n = con.execute("SELECT COUNT(*) FROM rulings WHERE file=?", (rel,)).fetchone()[0]
1802
+ print(" %-46s arc %-18s %s"
1803
+ % (rel.replace("docs/experiments/", ""), arc,
1804
+ "%d rows" % n if n else "0 rows - prose only"))
1805
+ print(" %d documents matched %s" % (len(docs), RULING_DOC_RE.pattern))
1806
+ indexed = {r[0] for r in con.execute("SELECT DISTINCT file FROM rulings")}
1807
+ orphans = sorted(indexed - {rel for _, rel in docs})
1808
+ if orphans:
1809
+ print(" ROWS FROM UNDISCOVERED FILES: %s" % orphans)
1810
+ fails.append("rulings from files the glob does not discover: %s" % orphans)
1811
+
1812
+ # E16-9: the same audit for kickoffs, so the discovery rule's own misses are
1813
+ # visible rather than assumed on BOTH lists. Symmetric with the block above --
1814
+ # what was found, and whether anything the DB holds came from outside it.
1815
+ print("\n[corpus] kickoff documents discovered by the sorted glob")
1816
+ kdocs = handoff_documents()
1817
+ for arc, rel in kdocs:
1818
+ n = con.execute("SELECT COUNT(*) FROM handoffs WHERE file=?", (rel,)).fetchone()[0]
1819
+ print(" %-46s arc %-18s %s"
1820
+ % (rel.replace("docs/experiments/", ""), arc,
1821
+ "%d rows" % n if n else "0 rows - prose only"))
1822
+ print(" %d documents matched %s" % (len(kdocs), KICKOFF_DOC_RE.pattern))
1823
+ k_indexed = {r[0] for r in con.execute("SELECT DISTINCT file FROM handoffs")}
1824
+ k_orphans = sorted(k_indexed - {rel for _, rel in kdocs})
1825
+ if k_orphans:
1826
+ print(" ROWS FROM UNDISCOVERED FILES: %s" % k_orphans)
1827
+ fails.append("handoffs from files the glob does not discover: %s" % k_orphans)
1828
+
1829
+ # ---- leg 2: counts against the record's own numbering --------------------
1830
+ print("\n[leg 2] counts - the verifier's own grep against the DB")
1831
+ for name, rel, pattern, table, where in COUNT_CHECKS:
1832
+ g = _grep_count(rel, pattern)
1833
+ d = con.execute("SELECT COUNT(*) FROM %s WHERE %s" % (table, where)).fetchone()[0]
1834
+ ok = (g == d)
1835
+ print(" %-28s grep %4d db %4d %s" % (name, g, d, "ok" if ok else "MISMATCH"))
1836
+ if not ok:
1837
+ fails.append("count %s: grep %d != db %d" % (name, g, d))
1838
+
1839
+ # Ranges as DISPATCHED, not as measured. They are pre-registered bounds and are
1840
+ # left exactly where they were written; anything the record carries ABOVE a
1841
+ # dispatched bound prints below as a completeness note rather than silently
1842
+ # widening the gate. (E04 turns out to carry a Ruling 29 — the dispatch and the
1843
+ # experiments README both say 28. That is a finding about the prose, and the
1844
+ # advisor rules on it; this gate does not re-derive itself around it.)
1845
+ seq = [("E12", "ruling", 1, 28), ("E04", "ruling", 1, 28),
1846
+ ("E08", "amendment", 1, 35), ("E11", "ruling", 1, 7),
1847
+ ("E10", "ruling", 1, 12), ("E15", "ruling", 1, 8),
1848
+ # E14's bound is 1-16 as of the 2026-08-07 housekeeping fold (Ruling 16
1849
+ # the latest); the arc is LIVE, so later rulings print as completeness
1850
+ # notes above the bound — the designed behaviour, not a widening.
1851
+ ("E14", "ruling", 1, 16),
1852
+ # E16 closed at Ruling 7 (E16-ruling.md, 2026-08-08); bound as ruled.
1853
+ ("E16", "ruling", 1, 7),
1854
+ # E17 ruled at 4 (E17-ruling.md, 2026-08-08); bound as ruled, and
1855
+ # measured gapless 1-4 before this line was written.
1856
+ ("E17", "ruling", 1, 4)]
1857
+ for arc, kind, lo, hi in seq:
1858
+ gaps = _sequence_gaps(con, arc, kind, lo, hi)
1859
+ print(" %-28s %s %d-%d gaps: %s"
1860
+ % (arc + " sequence", kind, lo, hi, gaps if gaps else "none"))
1861
+ if gaps:
1862
+ fails.append("%s %s sequence gaps %s" % (arc, kind, gaps))
1863
+ above = [n for n in _sequence_numbers(con, arc, kind) if n > hi]
1864
+ if above:
1865
+ # States ONLY what it measured. An earlier version added "<- record
1866
+ # carries more than the prose claims", which was true when written and
1867
+ # false eight hours later: E15 Ruling 5 corrected E04's count to 29 at
1868
+ # three sites, and the line went on asserting the prose was stale. A
1869
+ # verifier that editorialises about a document it does not read will
1870
+ # eventually lie to every session that runs it.
1871
+ print(" %-28s ABOVE the dispatched bound of %d: %s <- measured; the "
1872
+ "bound stays as dispatched (E15 Ruling 3c)"
1873
+ % (" ^ completeness", hi, above))
1874
+
1875
+ hg = sorted(r[0] for r in con.execute(
1876
+ "SELECT number FROM handoffs WHERE arc='E12'").fetchall())
1877
+ missing = sorted(set(range(1, 17)) - set(hg))
1878
+ print(" %-28s present %s missing %s"
1879
+ % ("E12 handoffs 1-16", hg, missing if missing else "none"))
1880
+ if missing != [1]:
1881
+ fails.append("E12 handoff coverage unexpected: missing %s" % missing)
1882
+
1883
+ exp = sorted(r[0] for r in con.execute("SELECT id FROM experiments").fetchall())
1884
+ want = ["E%02d" % i for i in range(1, 16)]
1885
+ miss = [e for e in want if e not in exp]
1886
+ print(" %-28s have %d, missing %s" % ("experiments E01-E15", len(exp),
1887
+ miss if miss else "none"))
1888
+ if miss:
1889
+ fails.append("experiments missing %s" % miss)
1890
+
1891
+ # ---- leg 3: zero dangling pointers ---------------------------------------
1892
+ print("\n[leg 3] pointers - every row's file exists and its locator is findable")
1893
+ cache = {}
1894
+ dangling = 0
1895
+ checked = 0
1896
+ for table in ("rulings", "laws", "experiments", "handoffs",
1897
+ "artifacts", "phenomena", "decisions"):
1898
+ rows = con.execute("SELECT file, anchor, locator FROM %s" % table).fetchall()
1899
+ bad = 0
1900
+ for f, a, loc in rows:
1901
+ checked += 1
1902
+ if f not in cache:
1903
+ p = os.path.join(REPO, f)
1904
+ cache[f] = read(f) if os.path.exists(p) else None
1905
+ src = cache[f]
1906
+ if src is None or loc not in src:
1907
+ bad += 1
1908
+ dangling += bad
1909
+ print(" %-12s %5d rows dangling %d" % (table, len(rows), bad))
1910
+ if bad:
1911
+ fails.append("%s: %d dangling pointers" % (table, bad))
1912
+ fts_bad = 0
1913
+ for f, loc in con.execute("SELECT file, locator FROM fts").fetchall():
1914
+ if f not in cache:
1915
+ p = os.path.join(REPO, f)
1916
+ cache[f] = read(f) if os.path.exists(p) else None
1917
+ if cache[f] is None or loc not in cache[f]:
1918
+ fts_bad += 1
1919
+ print(" %-12s %5d rows dangling %d"
1920
+ % ("fts", con.execute("SELECT COUNT(*) FROM fts").fetchone()[0], fts_bad))
1921
+ if fts_bad:
1922
+ fails.append("fts: %d dangling pointers" % fts_bad)
1923
+ print(" total checked %d, dangling %d" % (checked, dangling + fts_bad))
1924
+
1925
+ # ---- leg 4: the seeded question set --------------------------------------
1926
+ print("\n[leg 4] the seeded question set - target within the top %d" % top_n)
1927
+ hits = 0
1928
+ for question, phrase, want in SEEDED:
1929
+ targets = want if isinstance(want, list) else [want]
1930
+ rows = query(con, phrase, limit=top_n)
1931
+ got = None
1932
+ for rank, (f, a, t, line, tbl, r) in enumerate(rows, 1):
1933
+ if any(f == wf and (wa is None or a == wa) for wf, wa in targets):
1934
+ got = rank
1935
+ break
1936
+ ok = got is not None
1937
+ hits += 1 if ok else 0
1938
+ tgt = " | ".join("%s · %s" % (wf, wa or "(any anchor)") for wf, wa in targets)
1939
+ print(" %-34s %-8s %s" % (question[:34], "rank %d" % got if ok else "MISS", tgt))
1940
+ if not ok:
1941
+ for rank, (f, a, t, line, tbl, r) in enumerate(rows, 1):
1942
+ print(" got %d. %s:%s [%s]" % (rank, f, a, tbl))
1943
+ fails.append("seeded question MISS: %s" % question)
1944
+ print(" %d / %d" % (hits, len(SEEDED)))
1945
+
1946
+ # CLOSE THE HANDLE (E18 D4, found by the live dogfood). This connection was
1947
+ # left open at both exits. Harmless in the CLI - the process ends a
1948
+ # millisecond later - but the MCP server is a LONG-LIVED process that calls
1949
+ # verify and then build in the same interpreter, and `build` starts with
1950
+ # os.remove(db_path). On Windows a removal fails while any handle is open,
1951
+ # so `record_build` after `record_verify` died with
1952
+ # PermissionError WinError 32 and the server reported INTERNAL. The defect
1953
+ # was invisible for as long as every caller exited after one verb; the
1954
+ # first composition surfaced it. Same fix in `claims`, which leaked the
1955
+ # same way - a root cause has as many sites as it has callers.
1956
+ con.close()
1957
+
1958
+ print("\n" + "=" * 78)
1959
+ print("determinism leg that held: %s" % det_leg)
1960
+ if fails:
1961
+ print("VERIFY FAILED - %d" % len(fails))
1962
+ for f in fails:
1963
+ print(" X %s" % f)
1964
+ return 1
1965
+ print("VERIFY PASSED - all four legs")
1966
+ return 0
1967
+
1968
+
1969
+ # ---------------------------------------------------------------------------
1970
+ # main
1971
+ # ---------------------------------------------------------------------------
1972
+
1973
+ def _survivable_stdout():
1974
+ """Make an unencodable character degrade instead of killing the verifier.
1975
+
1976
+ E14 Ruling 31f found the `↑` on the completeness branch crashing this tool
1977
+ under cp1252. Folding the print LITERALS to ASCII (done, 17 sites) does not
1978
+ finish the job, because the loud half of what this tool prints is the
1979
+ RECORD, not its own prose: the DB carries 17 cp1252-unencodable cells right
1980
+ now — `≤` in two ruling locators, `→` in an experiment status, `⚠` in a
1981
+ handoff outcome, `Δ`/`σ` in indexed prose — and legs 3 and 4 print exactly
1982
+ those columns. A literal-only repair moves the crash one leg downstream and
1983
+ leaves it cold until a query happens to surface a row with an arrow in it.
1984
+
1985
+ Folding the DATA to ASCII is the wrong fix — this tool quotes the record and
1986
+ `≤0.24%` is what the record says. So the console's own encoding is kept and
1987
+ only the errors handler is relaxed: under `PYTHONIOENCODING=utf-8` nothing
1988
+ is unencodable and output is byte-for-byte what it was, while under cp1252 a
1989
+ `≤` prints as `\\u2264` instead of taking the process down. A verifier whose
1990
+ FAILURE report cannot print (line 1848's `✗`, the second fatal literal, on
1991
+ the branch that only runs when something is already wrong) is the house's
1992
+ own class: a check that cannot fail.
1993
+ """
1994
+ for stream in (sys.stdout, sys.stderr):
1995
+ try:
1996
+ stream.reconfigure(errors="backslashreplace")
1997
+ except (AttributeError, ValueError): # not a reconfigurable stream
1998
+ pass
1999
+
2000
+
2001
+ def main(argv=None):
2002
+ _survivable_stdout()
2003
+ ap = argparse.ArgumentParser(
2004
+ description="the derived SQLite+FTS5 index over the facet record")
2005
+ ap.add_argument("verb", choices=["build", "verify", "q", "claims"])
2006
+ ap.add_argument("term", nargs="?", default=None, help="query term for `q`")
2007
+ ap.add_argument("--db", default=os.path.join(REPO, DB_REL))
2008
+ ap.add_argument("--limit", type=int, default=8)
2009
+ ap.add_argument("--table", default=None, help="restrict `q` to one table")
2010
+ args = ap.parse_args(argv)
2011
+
2012
+ if args.verb == "build":
2013
+ build(args.db)
2014
+ return 0
2015
+ if args.verb == "verify":
2016
+ return verify(args.db)
2017
+ if args.verb == "claims":
2018
+ return claims(args.db)
2019
+ if not args.term:
2020
+ print("q needs a term", file=sys.stderr)
2021
+ return 2
2022
+ con = sqlite3.connect(args.db)
2023
+ rows = query(con, args.term, limit=args.limit * 6)
2024
+ n = 0
2025
+ for f, a, disp, line, tbl, r in rows:
2026
+ if args.table and tbl != args.table:
2027
+ continue
2028
+ # the dispatch's contract: file:anchor · one-line holding
2029
+ head = "%s:%d" % (f, line)
2030
+ print("%-52s %s" % (head, a))
2031
+ if disp and disp.strip() and disp.strip() != a.strip():
2032
+ print("%-52s - %s" % ("", one_line(disp, 150)))
2033
+ n += 1
2034
+ if n >= args.limit:
2035
+ break
2036
+ if n == 0:
2037
+ print("(no rows)")
2038
+ return 0
2039
+
2040
+
2041
+ if __name__ == "__main__":
2042
+ sys.exit(main())