@antoneeo/course-creator 0.1.0-beta.2 → 0.1.0-beta.21

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.
Files changed (31) hide show
  1. package/CHANGELOG.md +243 -0
  2. package/README.md +18 -1
  3. package/gemini-extension.json +1 -1
  4. package/package.json +17 -3
  5. package/scripts/init.js +62 -62
  6. package/scripts/lib.js +98 -98
  7. package/scripts/postinstall.js +16 -16
  8. package/scripts/preuninstall.js +12 -12
  9. package/skills/course-creator/ENFORCEMENT.md +32 -8
  10. package/skills/course-creator/SKILL.md +13 -8
  11. package/skills/course-creator/dispatch.md +2 -2
  12. package/skills/course-creator/docs_site/app.js +1139 -0
  13. package/skills/course-creator/docs_site/index.html +17 -0
  14. package/skills/course-creator/docs_site/strings.js +332 -0
  15. package/skills/course-creator/docs_site/style.css +290 -0
  16. package/skills/course-creator/elicitation.md +26 -9
  17. package/skills/course-creator/guides.md +48 -10
  18. package/skills/course-creator/learning_design.md +1 -1
  19. package/skills/course-creator/memory.md +1 -1
  20. package/skills/course-creator/review.md +76 -5
  21. package/skills/course-creator/routing.md +4 -0
  22. package/skills/course-creator/scripts/course_check.py +158 -2
  23. package/skills/course-creator/scripts/docs_site.py +1462 -0
  24. package/skills/course-creator/scripts/knowledge.py +1532 -84
  25. package/skills/course-creator/scripts/sdlc_check.py +2 -1
  26. package/skills/course-creator/scripts/sdlc_core.py +2005 -97
  27. package/skills/course-creator/scripts/shared_files.py +12 -0
  28. package/skills/course-creator/scripts/shared_manifest.json +24 -13
  29. package/skills/course-creator/slide_content.md +2 -2
  30. package/skills/course-creator/templates.md +121 -9
  31. package/skills/course-creator/vision.md +308 -245
@@ -21,6 +21,8 @@ Commands:
21
21
  stale list areas modified after the last analysis recorded in audit_plan.md (exit 1 if any)
22
22
  mark record paths as ANALYZED with the current reference (git hash, else UTC timestamp)
23
23
  gate PreToolUse hook: block writes on protected paths without an IN_PROGRESS ANALYSIS (exit 2)
24
+ verdict PreToolUse hook: refuse an edit when the session declared no guide-router
25
+ verdict, or never read a guide it names (JSON deny on stdout; always exit 0)
24
26
 
25
27
  Hybrid/devPNT mode: pass --hybrid explicitly on check/stale (skips audit-plan
26
28
  staleness, delegated to devPNT/KL) and on gate (also unlocks when an approved
@@ -33,6 +35,7 @@ but are deprecated: new documents should use the English forms.
33
35
  Standard library only (Python >= 3.8). Windows and POSIX compatible.
34
36
  """
35
37
  import argparse
38
+ import base64
36
39
  import hashlib
37
40
  import json
38
41
  import os
@@ -89,6 +92,22 @@ ARCHITECT_PASS_EPOCH = "2026-07-28"
89
92
  # row. Same grandfathering discipline as the pass above -- never nag work that
90
93
  # predates the rule.
91
94
  DESIGN_REVIEW_EPOCH = "2026-07-28"
95
+ # Chronology (F-073): an L3 ANALYSIS started, or an L3 HANDOFF updated, on/after
96
+ # this date is read for undated Diary text and a multi-step `next:`. Advisories,
97
+ # like the two gates above: a fixed epoch cannot protect a late upgrader, so a
98
+ # warning here would redden --strict CI on work written before the upgrade.
99
+ CHRONOLOGY_EPOCH = "2026-10-18"
100
+ # Guide check (F-078): an L3 code ANALYSIS started on/after this date owes a
101
+ # filled '## Guide check'. The day AFTER the rule was written, so the analyses
102
+ # opened that day by parallel units (which never saw the template) stay quiet.
103
+ GUIDE_CHECK_EPOCH = "2026-10-24"
104
+ # Owner design approval (F-087): an L3 started on/after this date owes a request-
105
+ # record entry labelled `design approved` before implementation. The day AFTER the
106
+ # rule was written, like GUIDE_CHECK_EPOCH.
107
+ DESIGN_APPROVAL_EPOCH = "2026-10-31"
108
+ NEXT_MAX_CHARS = 240 # this repository's longest `next:` was 214 at the epoch
109
+ ID_SCAN_MAX_REFS = 300 # A3 is skipped above it (one advisory says so, T9)
110
+ ID_SCAN_REFS_PER_CALL = 50 # keeps one git command line far below 32k chars
92
111
  def review_log_rel():
93
112
  return f"{docs_dir()}/audit/reviews/REVIEW_LOG.md"
94
113
  # Component Map 'Where' refs: a dotted token counts as a path only with one of
@@ -251,6 +270,7 @@ REQUIRED_CAPABILITIES = frozenset({
251
270
  OPTIONAL_CAPABILITIES = frozenset({
252
271
  "architect_pass", # does the component already exist? (code overlay)
253
272
  "interaction_contract", # actor-facing surface spec between use cases and solution (code overlay)
273
+ "preservation_constraints", # the Impact's P table, and validate's note on its absence (code overlay)
254
274
  "taxonomy_pass", # do the categories/topics already exist? (knowledge overlay)
255
275
  "comprehension_guides", # source_kind: code maps of complex components
256
276
  "tdd", # test-first discipline
@@ -388,8 +408,17 @@ def orient_docs():
388
408
  ("Guide router (when-to-consult)", f"{d}/reference/INDEX.md"),
389
409
  ("Last session handoff", f"{d}/audit/handoff.md"),
390
410
  ]
391
- ORIENT_PER_DOC_CHARS = 6000 # per-doc truncation
392
- ORIENT_MAX_TOTAL_CHARS = 16000 # total ingestion cap (P-TM T2); tunable
411
+ # F-075: the WHOLE output -- the knowledge layer's append included -- stays under
412
+ # Claude Code's 10,000-character hook cap. Above it the client saves the output
413
+ # to a file and injects a 2,000-character preview, and the agent never opens the
414
+ # file: the router printed third, after README and INDEX, never reached a session.
415
+ ORIENT_MAX_TOTAL_CHARS = 9500 # whole output (P-TM T2)
416
+ ORIENT_APPEND_RESERVE = 2000 # left for the knowledge layer's append, which cuts itself to it
417
+ ORIENT_ROUTER_CHARS = 3000 # ~20 guides; the full router stays one read away
418
+ ORIENT_REGISTRY_CHARS = 2600 # registry rows + project-wide notes
419
+ ORIENT_TRIAGE_LINE = ("Triage every request (Rule Zero): L1 trivial - L2 small - L3 significant "
420
+ "- Spike. Declare the level with the guide-router verdict (a guide below, "
421
+ "or \"no match\"). When in doubt, pick the higher level.")
393
422
 
394
423
 
395
424
  # ----------------------------------------------------------------- utilities
@@ -516,12 +545,55 @@ def has_etdd_shadow(root):
516
545
  return any("tdd" in p.name.lower() for p in sol.glob("SHADOW_*.md"))
517
546
 
518
547
 
548
+ def newest_shadow(solutions_dir, doc_key):
549
+ """The newest devPNT shadow of `doc_key` in `solutions_dir`, or None.
550
+ Only `SHADOW_<doc_key>_v<N>[.<N>...].md` counts -- the exact key, so
551
+ `<doc_key>_extra` is another key -- and versions compare number by number
552
+ (v1.10 above v1.9, v1.0 above v1). Names outside that rule are ignored.
553
+ F-081: the Hybrid target of a claim marker; reusable by any consumer."""
554
+ if not Path(solutions_dir).is_dir():
555
+ return None
556
+ best = None
557
+ for p in Path(solutions_dir).iterdir():
558
+ v = _shadow_version(p.name, doc_key)
559
+ if v is not None and p.is_file():
560
+ if best is None or v > best[0]:
561
+ best = (v, p)
562
+ return best[1] if best else None
563
+
564
+
565
+ def _shadow_version(name, doc_key):
566
+ """The version tuple of `SHADOW_<doc_key>_v<N>[.<N>...].md`, else None."""
567
+ m = re.match(r"^SHADOW_%s_v(\d+(?:\.\d+)*)\.md$" % re.escape(doc_key), name)
568
+ return tuple(int(x) for x in m.group(1).split(".")) if m else None
569
+
570
+
571
+ def stray_shadow(solutions_dir, doc_key):
572
+ """A file of the same exact key that `newest_shadow` does not read
573
+ (`SHADOW_<doc_key>.md`, `..._v1.2a.md`), or None -- the name a user needs
574
+ to see when no shadow resolves. A longer key is never a stray."""
575
+ if not Path(solutions_dir).is_dir():
576
+ return None
577
+ rx = re.compile(r"^SHADOW_%s(?:_v[^_]*)?\.md$" % re.escape(doc_key))
578
+ return next((p.name for p in sorted(Path(solutions_dir).iterdir())
579
+ if rx.match(p.name) and _shadow_version(p.name, doc_key) is None),
580
+ None)
581
+
582
+
583
+ def skip_dir(name):
584
+ """The one definition of a directory that holds no project files: VCS and
585
+ dependency/build directories, every dot-directory, and the docs root (by
586
+ name, at any depth). `iter_files` and the knowledge layer's inventory both
587
+ walk by it, so the two can never disagree about what the project is."""
588
+ return name in SKIP_DIRS or name == docs_dir() or name.startswith(".")
589
+
590
+
519
591
  def iter_files(target):
520
592
  if target.is_file():
521
593
  yield target
522
594
  return
523
595
  for dirpath, dirnames, filenames in os.walk(target):
524
- dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and d != docs_dir() and not d.startswith(".")]
596
+ dirnames[:] = [d for d in dirnames if not skip_dir(d)]
525
597
  for name in filenames:
526
598
  yield Path(dirpath) / name
527
599
 
@@ -834,6 +906,10 @@ def build_registry(root):
834
906
  return ""
835
907
  stamp = max(str(m.get("updated") or m.get("since") or "").strip() or "0000-00-00"
836
908
  for _p, m in rows)
909
+ return _render_registry(root, rows, stamp)
910
+
911
+
912
+ def _render_registry(root, rows, stamp):
837
913
  lines = ["# Handoff — workstream registry",
838
914
  f"Date: {stamp} (UTC)",
839
915
  "",
@@ -858,15 +934,44 @@ def parse_registry_rows(text):
858
934
  """Workstream ids in a registry table, hand-written or generated."""
859
935
  ids = []
860
936
  for line in text.splitlines():
861
- s = line.strip()
862
- if not s.startswith("|") or set(s) <= {"|", "-", " ", ":"}:
937
+ cells = _table_cells(line)
938
+ if not cells:
863
939
  continue
864
- first = s.strip("|").split("|")[0].strip()
940
+ first = cells[0]
865
941
  if first and first.lower() != "workstream":
866
942
  ids.append(first)
867
943
  return ids
868
944
 
869
945
 
946
+ def is_generated_registry(text):
947
+ # "Ours" = written by ANY family entry point: the header is WRITTEN with
948
+ # entry_script(), so recognition must not hard-code one distribution's
949
+ # script name (a registry generated by mkt_check.py is just as generated).
950
+ return bool(re.search(r"GENERATED by \S+ index - do not edit by hand", text))
951
+
952
+
953
+ def generated_registry_rows(text):
954
+ """Workstream rows of a generated registry, ignoring the project notes
955
+ (free text that may carry tables of its own)."""
956
+ return parse_registry_rows(text.split("\n## Project-wide notes", 1)[0])
957
+
958
+
959
+ def build_empty_registry(root, existing):
960
+ """The generated registry once the last source is gone (F1, found by F-068).
961
+
962
+ Only for a registry that is already ours: a hand-written handoff with no
963
+ sources is a project that never converted, and stays untouched. The Date is
964
+ kept while the view is already empty -- re-running index on a clean tree
965
+ must not change it -- and becomes today's when rows are being dropped:
966
+ there is no source left whose `updated:` could date the closure."""
967
+ m = re.search(r"Date:\s*(\d{4}-\d{2}-\d{2})", existing)
968
+ if m and not generated_registry_rows(existing):
969
+ stamp = m.group(1)
970
+ else:
971
+ stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d")
972
+ return _render_registry(root, [], stamp)
973
+
974
+
870
975
  def registry_conversion_blockers(root):
871
976
  """What stops `index` from writing over a hand-written handoff.md.
872
977
 
@@ -879,10 +984,7 @@ def registry_conversion_blockers(root):
879
984
  if not hand.is_file():
880
985
  return []
881
986
  text = read_text(hand)
882
- # "Already ours" = written by ANY family entry point: the header is WRITTEN
883
- # with entry_script(), so recognition must not hard-code one distribution's
884
- # script name (a registry generated by mkt_check.py is just as generated).
885
- if re.search(r"GENERATED by \S+ index - do not edit by hand", text):
987
+ if is_generated_registry(text):
886
988
  return []
887
989
  blockers = []
888
990
  known = {str(m.get("workstream")).strip() for _p, m in list_workstreams(root)}
@@ -1015,10 +1117,21 @@ def cmd_index(root):
1015
1117
  def rc_registry(root):
1016
1118
  """Write the generated workstream registry, or refuse and say why (F-028)."""
1017
1119
  ws = list_workstreams(root)
1120
+ hand = ai_path(root, "audit", "handoff.md")
1018
1121
  if not ws:
1019
- return 0 # no sources: a hand-written handoff is untouched
1122
+ # No sources: a hand-written handoff is untouched; a generated one is
1123
+ # emptied, or the last closed workstream would stay listed forever.
1124
+ if not hand.is_file():
1125
+ return 0
1126
+ existing = read_text(hand)
1127
+ if not is_generated_registry(existing):
1128
+ return 0
1129
+ empty = build_empty_registry(root, existing)
1130
+ if norm_text(existing) != norm_text(empty):
1131
+ hand.write_text(empty, encoding="utf-8")
1132
+ print(f"[ok] workstream registry emptied (no open workstreams): {hand}")
1133
+ return 0
1020
1134
  blockers = registry_conversion_blockers(root)
1021
- hand = ai_path(root, "audit", "handoff.md")
1022
1135
  if blockers:
1023
1136
  print(f"[ERROR] {docs_dir()}/audit/handoff.md NOT regenerated -- it still holds "
1024
1137
  "state no source accounts for:")
@@ -1060,17 +1173,364 @@ def section_body(text, aliases):
1060
1173
  return None
1061
1174
 
1062
1175
 
1063
- def design_review_due(meta):
1064
- """True when an L3 ANALYSIS owes a design-review row (review.md moment 1):
1065
- implementation has started or finished, and it began on/after the gate
1066
- shipped. PLANNED is exempt -- the review is due at the END of Phase 3, so an
1067
- analysis still being drafted is not late."""
1176
+ def section_lines(text, aliases):
1177
+ """(heading_line, body) for the first matching `## ` section, or None: the
1178
+ body NOT stripped, so body line n is file line heading_line + n, and an
1179
+ indented first line keeps its indentation. The readers below use it; a
1180
+ stripped body would shift every line number and move ` - DATE` to column 0."""
1181
+ lines = (text or "").splitlines()
1182
+ for i, line in enumerate(lines):
1183
+ if any(line.startswith(a) for a in aliases):
1184
+ body = []
1185
+ for nxt in lines[i + 1:]:
1186
+ if nxt.startswith("## "):
1187
+ break
1188
+ body.append(nxt)
1189
+ return i + 1, "\n".join(body)
1190
+ return None
1191
+
1192
+
1193
+ # ---------------------------------------------------------------- chronology
1194
+ # One grammar for a dated entry (F-073), read by the validator and by any
1195
+ # consumer that lists events (F-072's chronology): both call these readers, so
1196
+ # they cannot disagree on what an event is. The readers return openers only --
1197
+ # date, label, line -- and format nothing for display.
1198
+
1199
+ DIARY_SECTION = next(s for s in ANALYSIS_SECTIONS if s[0] == "## Diary")
1200
+ _ISO = r"\d{4}-\d{2}-\d{2}"
1201
+ # At column 0: optional list marker, optional `###`/`####`, optional bold, then
1202
+ # the ISO date and a word boundary. The date FIRST is the rule; markup is
1203
+ # tolerated so the dated forms already written stay readable with no migration.
1204
+ ENTRY_OPENER = re.compile(r"^(?:([-*]) |(#{3,4}) )?(\*\*)?(" + _ISO + r")\b(.*)$")
1205
+ _LABEL_SEP = re.compile(r"^(?:\*\*)?\s*(?:[—–:-])?\s*")
1206
+ _REQUEST_HEADING = re.compile(r"^### (R\d+) [—–-] (" + _ISO + r") [—–-] (.+)$")
1207
+ _ADR_BODY_DATE = re.compile(r"^\**Date:\**\s*(" + _ISO + r")\b", re.M)
1208
+ _ADR_NAME_DATE = re.compile(r"^ADR_(" + _ISO + r")_", re.I)
1209
+ UNIT_ID_RE = re.compile(r"\b([A-Z]-\d{3,})\b")
1210
+
1211
+
1212
+ def _entry_label(bold, rest):
1213
+ rest = _LABEL_SEP.sub("", rest, count=1)
1214
+ if bold and "**" in rest:
1215
+ rest = rest.split("**", 1)[0]
1216
+ else:
1217
+ rest = re.split(r"(?<=[.!?])\s", rest, maxsplit=1)[0]
1218
+ return rest.strip(" .:—–-*")[:120]
1219
+
1220
+
1221
+ def _opener_at(lines, i):
1222
+ """The match when lines[i] opens an entry. It must also START A BLOCK -- the
1223
+ line above is blank, absent or a heading, or the line is itself a list item
1224
+ or a heading -- so a hard-wrapped prose line that happens to begin with a
1225
+ date is never an event. (A separator after the date is NOT required: real
1226
+ openers read `DATE (qualifier)` and `DATE word`.)"""
1227
+ m = ENTRY_OPENER.match(lines[i])
1228
+ if not m:
1229
+ return None
1230
+ prev = lines[i - 1] if i else ""
1231
+ if not prev.strip() or prev.startswith("#") or m.group(1) or m.group(2):
1232
+ return m
1233
+ return None
1234
+
1235
+
1236
+ def malformed_openers(body):
1237
+ """[(line, text)] -- dated openers whose bold does not pair: `**DATE …` with no
1238
+ closing `**` on the line, or a bare `DATE …` that closes one. Either way the
1239
+ chronology shows a label running into the entry's body (field case 2026-10-19:
1240
+ two release notes in project_notes.md)."""
1241
+ lines = _blank_comments(body).splitlines()
1242
+ out = []
1243
+ for i in range(len(lines)):
1244
+ m = _opener_at(lines, i)
1245
+ if m and bool(m.group(3)) != ("**" in m.group(5)):
1246
+ out.append((i + 1, lines[i]))
1247
+ return out
1248
+
1249
+
1250
+ def entry_openers(body):
1251
+ """[(date, label, line)] -- one per dated entry opener; line is 1-based
1252
+ within `body`. An undated paragraph belongs to the entry above it. Comments
1253
+ are blanked first, exactly as `undated_diary_lines` does, so an entry
1254
+ written under the template's comment is an event to both."""
1255
+ lines = _blank_comments(body).splitlines()
1256
+ out = []
1257
+ for i in range(len(lines)):
1258
+ m = _opener_at(lines, i)
1259
+ if m:
1260
+ out.append((m.group(4), _entry_label(m.group(3), m.group(5)), i + 1))
1261
+ return out
1262
+
1263
+
1264
+ def _blank_comments(text):
1265
+ # comments become blank lines, so line numbers still point at the file's lines
1266
+ return re.sub(r"<!--.*?-->", lambda m: "\n" * m.group(0).count("\n"), text or "",
1267
+ flags=re.S)
1268
+
1269
+
1270
+ def undated_diary_lines(body):
1271
+ """[(line, text)] a Diary body cannot date: text before the first opener,
1272
+ and any `### ` heading that is not an opener. `####` and deeper headings are
1273
+ sub-structure of an entry and stay legal. Comments are ignored."""
1274
+ lines = _blank_comments(body).splitlines()
1275
+ out, seen_opener = [], False
1276
+ for i, line in enumerate(lines):
1277
+ if _opener_at(lines, i):
1278
+ seen_opener = True
1279
+ elif line.startswith("### "):
1280
+ out.append((i + 1, line.strip()))
1281
+ elif not seen_opener and line.strip():
1282
+ out.append((i + 1, line.strip()))
1283
+ return out
1284
+
1285
+
1286
+ def request_entries(text):
1287
+ """(entries, unparsed) for a request record: entries are
1288
+ [(rid, date, label, line)]; a `### ` heading that does not match
1289
+ `### R<n> — YYYY-MM-DD — <label>` is returned in unparsed as (line, text),
1290
+ never dropped."""
1291
+ entries, unparsed = [], []
1292
+ for i, line in enumerate((text or "").splitlines()):
1293
+ if not line.startswith("### "):
1294
+ continue
1295
+ m = _REQUEST_HEADING.match(line.rstrip())
1296
+ if m:
1297
+ entries.append((m.group(1), m.group(2), m.group(3).strip(), i + 1))
1298
+ else:
1299
+ unparsed.append((i + 1, line.rstrip()))
1300
+ return entries, unparsed
1301
+
1302
+
1303
+ def adr_date(name, text):
1304
+ """An ADR's date: `**Date:** YYYY-MM-DD` in the body, else the
1305
+ `ADR_YYYY-MM-DD_*` file name, else None."""
1306
+ m = _ADR_BODY_DATE.search(text or "") or _ADR_NAME_DATE.match(name or "")
1307
+ return m.group(1) if m else None
1308
+
1309
+
1310
+ def _meta_date(meta, key):
1311
+ return parse_iso(str(meta.get(key) or "").strip().strip("'\"")[:10])
1312
+
1313
+
1314
+ def chronology_advisories(root):
1315
+ """A1 (undated Diary text) and A2 (`next:` is not one step), as advisory
1316
+ strings. Gated on `level: L3` and on a date the file carries -- never an
1317
+ mtime -- so L1/L2 work and anything written before the epoch see nothing."""
1318
+ epoch = parse_iso(CHRONOLOGY_EPOCH)
1319
+ out = []
1320
+ for p, meta, text in list_analyses(root):
1321
+ started = _meta_date(meta, "start_date")
1322
+ if str(meta.get("level", "")).upper() != "L3" or not started or started < epoch:
1323
+ continue
1324
+ section = section_lines(text, DIARY_SECTION)
1325
+ if section is None:
1326
+ continue
1327
+ head, body = section
1328
+ rel = "solutions/" + p.name
1329
+ lines = undated_diary_lines(body)
1330
+ preface = [(n, t) for n, t in lines if not t.startswith("### ")]
1331
+ if preface:
1332
+ out.append(f"{rel}: line {head + preface[0][0]}: Diary text '{preface[0][1][:60]}' "
1333
+ "comes before the first dated entry -- open entries with "
1334
+ "**YYYY-MM-DD — label.**, and write the current state as the latest "
1335
+ "dated entry")
1336
+ for n, t in lines:
1337
+ if t.startswith("### "):
1338
+ out.append(f"{rel}: line {head + n}: Diary heading '{t[:60]}' is not a dated "
1339
+ "entry -- open entries with **YYYY-MM-DD — label.**")
1340
+ for p, meta in list_workstreams(root):
1341
+ updated = _meta_date(meta, "updated")
1342
+ if str(meta.get("level", "")).upper() != "L3" or not updated or updated < epoch:
1343
+ continue
1344
+ nxt = str(meta.get("next") or "").strip()
1345
+ if len(nxt) > NEXT_MAX_CHARS:
1346
+ out.append(f"audit/{p.name}: next: is {len(nxt)} chars (> {NEXT_MAX_CHARS}): one "
1347
+ "next step here, the state goes to the Diary as a dated entry")
1348
+ notes = ai_path(root, "audit", PROJECT_NOTES)
1349
+ if notes.is_file():
1350
+ for n, t in malformed_openers(read_text(notes)):
1351
+ out.append(f"audit/{PROJECT_NOTES}: line {n}: dated entry '{t[:60]}' has unpaired "
1352
+ "bold -- open entries with **YYYY-MM-DD — label.**")
1353
+ return out
1354
+
1355
+
1356
+ def _open_units(root):
1357
+ """{id: {analysis name}} for the tree's open L3 units: an L3 ANALYSIS that is
1358
+ PLANNED or IN_PROGRESS, or a request record (L3 only, r26) whose `analysis:`
1359
+ is absent from the tree or names such an open ANALYSIS. A closed unit's
1360
+ record, kept forever, does not count."""
1361
+ units, present, open_names = {}, set(), set()
1362
+ for p, meta, _ in list_analyses(root):
1363
+ present.add(p.name)
1364
+ if (str(meta.get("level", "")).upper() == "L3"
1365
+ and meta.get("status") in ("PLANNED", "IN_PROGRESS")):
1366
+ m = UNIT_ID_RE.search(str(meta.get("id") or ""))
1367
+ if m:
1368
+ open_names.add(p.name)
1369
+ units.setdefault(m.group(1), set()).add(p.name)
1370
+ req = ai_path(root, "audit", "requests")
1371
+ if req.is_dir():
1372
+ for p in sorted(req.glob("REQUEST_*.md")):
1373
+ meta = load_frontmatter(read_text(p).splitlines())
1374
+ name = str(meta.get("analysis") or "").strip().strip("'\"`")
1375
+ m = UNIT_ID_RE.search(str(meta.get("unit") or meta.get("id") or ""))
1376
+ if m and name and (name not in present or name in open_names):
1377
+ units.setdefault(m.group(1), set()).add(name)
1378
+ return units
1379
+
1380
+
1381
+ def _git_out(root, *args, timeout=30, env=None):
1382
+ # `env` is merged into the inherited environment, never a replacement: a bare
1383
+ # dict would drop PATH and fail silently on Windows.
1384
+ r = subprocess.run(["git", *args], cwd=str(root), capture_output=True, text=True,
1385
+ encoding="utf-8", errors="replace", timeout=timeout,
1386
+ env={**os.environ, **env} if env else None)
1387
+ return r.stdout if r.returncode == 0 else None
1388
+
1389
+
1390
+ def ids_on_other_refs(root, max_refs=ID_SCAN_MAX_REFS):
1391
+ """[(id, mine, theirs, [refs])] -- an open unit's id that another ref (heads,
1392
+ remotes, tags) uses for a DIFFERENT analysis. Identity is the ANALYSIS file
1393
+ name, declared by the ANALYSIS or announced by a request record's
1394
+ `analysis:`. One `git grep` over local refs, fixed arguments only (T8);
1395
+ as fresh as the last fetch. [] with no open L3 unit or no git; None when
1396
+ skipped -- above `max_refs` refs, or git failed or timed out -- so the
1397
+ caller can say the check did not run instead of reporting it clean."""
1398
+ mine = _open_units(root)
1399
+ if not mine or not git_available(root):
1400
+ return []
1401
+ try:
1402
+ head = (_git_out(root, "rev-parse", "HEAD") or "").strip()
1403
+ listing = _git_out(root, "for-each-ref",
1404
+ "--format=%(objectname) %(objecttype) %(*objecttype) %(refname)",
1405
+ "refs/heads", "refs/remotes", "refs/tags")
1406
+ if listing is None:
1407
+ return None
1408
+ refs = []
1409
+ for line in listing.split("\n"):
1410
+ parts = line.split(" ")
1411
+ if len(parts) == 3: # %(*objecttype) empty: not a tag
1412
+ parts.insert(2, "")
1413
+ if len(parts) != 4:
1414
+ continue
1415
+ sha, kind, peeled, ref = parts
1416
+ # only refs that resolve to a commit can be grepped (a tag on a blob
1417
+ # would fail the whole batch); the tree's own commit is not "another
1418
+ # ref"; symbolic HEADs repeat a branch
1419
+ if "commit" not in (kind, peeled) or ref.endswith("/HEAD") or sha == head:
1420
+ continue
1421
+ refs.append(ref)
1422
+ if not refs:
1423
+ return []
1424
+ if len(refs) > max_refs:
1425
+ return None
1426
+ # Pathspecs are relative to cwd=root, so a docs root inside a monorepo
1427
+ # subdirectory is found. -z keeps a path with ':' or non-ASCII intact
1428
+ # (quotePath off); -n plus the fence lines confine hits to frontmatter.
1429
+ docs = docs_dir()
1430
+ chunks = []
1431
+ for i in range(0, len(refs), ID_SCAN_REFS_PER_CALL): # command-line length
1432
+ r = subprocess.run(
1433
+ ["git", "-c", "core.quotePath=false", "grep", "-z", "-n", "-I", "-E",
1434
+ r"^(id|unit|analysis):|^---\s*$", *refs[i:i + ID_SCAN_REFS_PER_CALL],
1435
+ "--", f"{docs}/solutions/ANALYSIS_*.md", f"{docs}/audit/requests/REQUEST_*.md"],
1436
+ cwd=str(root), capture_output=True, text=True, encoding="utf-8",
1437
+ errors="replace", timeout=60)
1438
+ if r.returncode not in (0, 1): # 1 = no match
1439
+ return None
1440
+ chunks.append(r.stdout)
1441
+ except Exception:
1442
+ return None
1443
+ per = {}
1444
+ for line in "".join(chunks).split("\n"): # not splitlines: \x1c.. are content
1445
+ parts = line.split("\0")
1446
+ if len(parts) != 3 or ":" not in parts[0] or not parts[1].isdigit():
1447
+ continue
1448
+ ref, path = parts[0].split(":", 1) # a ref name cannot hold ':'
1449
+ content = parts[2].rstrip("\r")
1450
+ st = per.setdefault((ref, path), {"fences": 0, "kv": {}})
1451
+ if int(parts[1]) == 1 and content.strip() == "---":
1452
+ st["fences"] = 1 # frontmatter opens on line 1
1453
+ elif st["fences"] == 1 and content.strip() == "---":
1454
+ st["fences"] = 2 # ...and closes here
1455
+ elif st["fences"] == 1:
1456
+ key, _, val = content.partition(":")
1457
+ st["kv"].setdefault(key, val.strip())
1458
+ found = {}
1459
+ for (ref, path), st in per.items():
1460
+ kv = st["kv"]
1461
+ fname = path.replace("\\", "/").rsplit("/", 1)[-1]
1462
+ name = fname if fname.startswith("ANALYSIS_") else kv.get("analysis", "").strip("'\"`")
1463
+ m = UNIT_ID_RE.search(kv.get("id") or kv.get("unit") or "")
1464
+ if not (m and name) or m.group(1) not in mine or name in mine[m.group(1)]:
1465
+ continue
1466
+ short = re.sub(r"^refs/(heads|remotes|tags)/", "", ref)
1467
+ found.setdefault((m.group(1), name), [])
1468
+ if short not in found[(m.group(1), name)]:
1469
+ found[(m.group(1), name)].append(short)
1470
+ return sorted((fid, ", ".join(sorted(mine[fid])), theirs, sorted(refs_))
1471
+ for (fid, theirs), refs_ in found.items())
1472
+
1473
+
1474
+ def id_advisories(root):
1475
+ """A3 as advisory strings, for every entry point's `check`."""
1476
+ hits = ids_on_other_refs(root)
1477
+ if hits is None:
1478
+ return [f"id check skipped (more than {ID_SCAN_MAX_REFS} refs, or git grep failed "
1479
+ "or timed out) -- choose a new unit's id after fetching, as the first id "
1480
+ "free on every ref"]
1481
+ out = []
1482
+ for fid, mine, theirs, refs in hits:
1483
+ more = f" (+{len(refs) - 1} more)" if len(refs) > 1 else ""
1484
+ out.append(f"id {fid} ({mine}) is also used by {theirs} on {refs[0]}{more}: choose "
1485
+ "the first id free on every ref -- if this is the same unit under its "
1486
+ "old name, ignore it")
1487
+ return out
1488
+
1489
+
1490
+ def _l3_in_work_since(meta, epoch):
1491
+ """True when an L3 ANALYSIS is in implementation or done and began on/after
1492
+ `epoch` (an ISO date string)."""
1068
1493
  if meta.get("level", "").upper() != "L3":
1069
1494
  return False
1070
1495
  if meta.get("status") not in ("IN_PROGRESS", "COMPLETED"):
1071
1496
  return False
1072
1497
  started = parse_iso((meta.get("start_date") or "").strip().strip("'\""))
1073
- return started is not None and started >= parse_iso(DESIGN_REVIEW_EPOCH)
1498
+ return started is not None and started >= parse_iso(epoch)
1499
+
1500
+
1501
+ def design_review_due(meta):
1502
+ """True when an L3 ANALYSIS owes a design-review row (review.md moment 1):
1503
+ implementation has started or finished, and it began on/after the gate
1504
+ shipped. PLANNED is exempt -- the review is due at the END of Phase 3, so an
1505
+ analysis still being drafted is not late."""
1506
+ return _l3_in_work_since(meta, DESIGN_REVIEW_EPOCH)
1507
+
1508
+
1509
+ def design_approval_due(meta):
1510
+ """True when an L3 ANALYSIS owes the owner's design approval (review.md
1511
+ section When a review is due): in implementation or done, begun on/after
1512
+ DESIGN_APPROVAL_EPOCH. PLANNED is exempt -- the question comes after the PASS."""
1513
+ return _l3_in_work_since(meta, DESIGN_APPROVAL_EPOCH)
1514
+
1515
+
1516
+ def requests_naming(root, analysis_name):
1517
+ """The request records whose `analysis:` field names this ANALYSIS file."""
1518
+ req = ai_path(root, "audit", "requests")
1519
+ if not req.is_dir():
1520
+ return []
1521
+ return [r for r in sorted(req.glob("REQUEST_*.md"))
1522
+ if str(load_frontmatter(read_text(r).splitlines()).get("analysis") or "")
1523
+ .strip().strip("'\"`") == analysis_name]
1524
+
1525
+
1526
+ def design_approval_logged(root, analysis_name):
1527
+ """True when a request record naming this ANALYSIS has an entry whose LABEL
1528
+ begins `design approved` (case-insensitive). Only the label is read, never
1529
+ the quoted words: a quotation is data, and a 'design approved?' inside a
1530
+ refusal approves nothing."""
1531
+ return any(label.lower().startswith("design approved")
1532
+ for r in requests_naming(root, analysis_name)
1533
+ for _, _, label, _ in request_entries(read_text(r))[0])
1074
1534
 
1075
1535
 
1076
1536
  def review_logged(root, analysis_name):
@@ -1113,10 +1573,30 @@ def has_ledger_heading(text):
1113
1573
  opens a comment at the start of a line -- nuking to EOF on an inline
1114
1574
  mention (or an unclosed example inside a fence) made a document that
1115
1575
  HAS its ledger get told it has none."""
1576
+ return bool(re.search(r"^##[ \t]+Capability Ledger[ \t]*$", strip_non_prose(text), re.M))
1577
+
1578
+
1579
+ def strip_non_prose(text):
1580
+ """Text without fenced code blocks and HTML comments (see has_ledger_heading)."""
1116
1581
  stripped = re.sub(r"^(```|~~~).*?^\1", "", text, flags=re.M | re.S)
1117
1582
  stripped = re.sub(r"<!--.*?-->", "", stripped, flags=re.S)
1118
- stripped = re.sub(r"^[ \t]*<!--(?!.*?-->).*\Z", "", stripped, flags=re.M | re.S)
1119
- return bool(re.search(r"^##[ \t]+Capability Ledger[ \t]*$", stripped, re.M))
1583
+ return re.sub(r"^[ \t]*<!--(?!.*?-->).*\Z", "", stripped, flags=re.M | re.S)
1584
+
1585
+
1586
+ def has_guide_check(text):
1587
+ """True when a real '## Guide check' heading carries an answer: the template's
1588
+ comment alone answers nothing, so a copied-but-unfilled section still owes it."""
1589
+ m = re.search(r"^##[ \t]+Guide check[ \t]*$(.*?)(?=^#{1,2}[ \t]|\Z)",
1590
+ strip_non_prose(text), re.M | re.S)
1591
+ return bool(m and m.group(1).strip())
1592
+
1593
+
1594
+ def guide_check_due(meta, domain):
1595
+ """True when an ANALYSIS owes the Phase-3 guide question (SKILL.md): a code-lens
1596
+ L3 started on/after GUIDE_CHECK_EPOCH. Same grandfathering as ledger_due."""
1597
+ return domain == "code" and ledger_due(meta) and (
1598
+ parse_iso((meta.get("start_date") or "").strip().strip("'\""))
1599
+ >= parse_iso(GUIDE_CHECK_EPOCH))
1120
1600
 
1121
1601
 
1122
1602
  def ledger_due(meta):
@@ -1362,9 +1842,31 @@ def cmd_validate(root, strict=False, hybrid=False):
1362
1842
  advisories.append(f"{rel}: L3 in implementation with no design-review row in "
1363
1843
  f"{review_log_rel()} -- the design was reviewed by nobody but its "
1364
1844
  "author before code was written (review.md moment 1)")
1845
+ if (not hybrid and design_approval_due(meta)
1846
+ and not design_approval_logged(root, p.name)):
1847
+ advisories.append(f"{rel}: L3 in implementation with no design approval in its "
1848
+ "request record (no entry whose label begins 'design approved') -- the "
1849
+ "owner never said the design was what they meant before the "
1850
+ "work started (review.md, When a review is due)")
1365
1851
  if ledger_due(meta) and not has_ledger_heading(text):
1366
1852
  advisories.append(f"{rel}: L3 without '## Capability Ledger' -- the architect pass "
1367
1853
  "left no record (architect.md); run it before the Impact")
1854
+ if guide_check_due(meta, domain) and not has_guide_check(text):
1855
+ advisories.append(f"{rel}: L3 without a filled '## Guide check' -- does a CURRENT "
1856
+ "guide cover what this touches, and did understanding it force "
1857
+ "a model of a complex component no guide covers (guides.md, section 1)?")
1858
+ # F-085 FS7: code lens only (R12: the lens, not merely the domain -- a kb
1859
+ # install validating a code-domain unit sees no change), open L3 only, a
1860
+ # note and never an error, so no `--strict` exit changes (P5).
1861
+ impact = section_body(text, IMPACT_SECTION)
1862
+ if (has_capability("preservation_constraints") and domain == "code"
1863
+ and str(level or "").upper() == "L3"
1864
+ and status in ("PLANNED", "IN_PROGRESS")
1865
+ and impact is not None and not has_preservation_record(impact)):
1866
+ advisories.append(f"{rel}: open L3 whose '## Impact' has neither the "
1867
+ f"'{PRESERVATION_HEADING}' table nor the line "
1868
+ f"'{NO_SYMBOL_LINE}' -- what existing code must keep "
1869
+ "doing is not extractable (templates.md)")
1368
1870
 
1369
1871
  # Generated index aligned
1370
1872
  hist = ai / "strategic" / "features_history.md"
@@ -1496,6 +1998,12 @@ def cmd_validate(root, strict=False, hybrid=False):
1496
1998
  "workstream — decide which file owns it")
1497
1999
  else:
1498
2000
  seen[wid] = p.name
2001
+ elif hand.is_file():
2002
+ text = read_text(hand)
2003
+ if is_generated_registry(text) and generated_registry_rows(text):
2004
+ errors.append(f"{docs_dir()}/audit/handoff.md lists workstreams no HANDOFF_*.md "
2005
+ "source exists for any more: run 'sdlc_check.py index' to drop "
2006
+ "the closed rows")
1499
2007
  if hand.is_file():
1500
2008
  m = re.search(r"(?:Date|Data):\s*(\d{4}-\d{2}-\d{2})", read_text(hand))
1501
2009
  if not m:
@@ -1509,6 +2017,7 @@ def cmd_validate(root, strict=False, hybrid=False):
1509
2017
  except ValueError:
1510
2018
  warnings.append("audit/handoff.md: date not parseable")
1511
2019
 
2020
+ advisories.extend(chronology_advisories(root)) # A1, A2 (F-073)
1512
2021
  for a in advisories:
1513
2022
  print(f"[note] {a}")
1514
2023
  for w in warnings:
@@ -1653,7 +2162,8 @@ def cmd_stale(root, hybrid=False):
1653
2162
  except ValueError: # symlink out of the tree: report absolute, never crash
1654
2163
  name = str(fp)
1655
2164
  changed.append(name)
1656
- changed = [c for c in changed if c != plan_rel]
2165
+ docs_rel = docs_root_rel(root)
2166
+ changed = [c for c in changed if c != plan_rel and not _in_docs_root(c, docs_rel)]
1657
2167
  if changed:
1658
2168
  stale.append((rel, changed))
1659
2169
 
@@ -1674,9 +2184,54 @@ def cmd_stale(root, hybrid=False):
1674
2184
  return 1 # stale areas dominate: rc already implied
1675
2185
 
1676
2186
 
1677
- def cmd_mark(root, paths):
2187
+ def add_dated_note(root, note, day=None):
2188
+ """Write `**DAY — note.**` into audit/project_notes.md, above the newest dated
2189
+ entry (below any undated preface), so the note opens with the shared grammar and
2190
+ the chronology reads it. The day defaults to today (local)."""
2191
+ import datetime as _dt
2192
+ day = day or _dt.date.today().isoformat()
2193
+ entry = "**%s — %s.**" % (day, note.strip().rstrip("."))
2194
+ f = ai_path(root, "audit", PROJECT_NOTES)
2195
+ if not f.is_file():
2196
+ f.parent.mkdir(parents=True, exist_ok=True)
2197
+ f.write_text(entry + "\n", encoding="utf-8")
2198
+ return entry
2199
+ raw = f.read_bytes()
2200
+ crlf = b"\r\n" in raw
2201
+ lines = raw.decode("utf-8", errors="replace").replace("\r\n", "\n").split("\n")
2202
+ at = next((i for i in range(len(lines)) if _opener_at(lines, i)), None)
2203
+ if at is None:
2204
+ while lines and not lines[-1].strip():
2205
+ lines.pop()
2206
+ lines += ["", entry, ""] if lines else [entry, ""]
2207
+ else:
2208
+ lines[at:at] = [entry, ""]
2209
+ text = "\n".join(lines)
2210
+ f.write_bytes((text.replace("\n", "\r\n") if crlf else text).encode("utf-8"))
2211
+ return entry
2212
+
2213
+
2214
+ def docs_root_rel(root):
2215
+ """The docs root (ai_docs/, mkt_docs/ ...) relative to the project root, or None.
2216
+ It is governance, not an analyzable area: `validate` checks it directly, so `stale`
2217
+ never counts its files and `mark` never records it."""
2218
+ try:
2219
+ return ai_path(root).resolve().relative_to(Path(root).resolve()).as_posix()
2220
+ except ValueError:
2221
+ return None
2222
+
2223
+
2224
+ def _in_docs_root(rel, docs_rel):
2225
+ rel = rel.replace("\\", "/").rstrip("/")
2226
+ return bool(docs_rel) and (rel == docs_rel or rel.startswith(docs_rel + "/"))
2227
+
2228
+
2229
+ def cmd_mark(root, paths, note=None):
1678
2230
  if not require_ai_docs(root, "mark"):
1679
2231
  return 1
2232
+ if note is not None and (not note.strip() or "**" in note or "\n" in note):
2233
+ print("[ERROR] --note must be one line of text without '**'. Nothing was written.")
2234
+ return 1
1680
2235
  f, lines, rows = parse_audit_plan(root)
1681
2236
  use_git_ref = git_available(root) and not any(
1682
2237
  git_has_changes(root, raw.replace("\\", "/").rstrip("/")) for raw in paths
@@ -1703,6 +2258,10 @@ def cmd_mark(root, paths):
1703
2258
  "refusing to mark (use a project-relative path, '.' for the root). "
1704
2259
  "Nothing was written.")
1705
2260
  return 1
2261
+ if _in_docs_root(key, docs_root_rel(root)):
2262
+ print(f"[note] {raw}: the docs root is not an area to mark -- `validate` checks it "
2263
+ "directly. Skipped.")
2264
+ continue
1706
2265
  keys.append(key)
1707
2266
 
1708
2267
  appended = []
@@ -1722,6 +2281,13 @@ def cmd_mark(root, paths):
1722
2281
 
1723
2282
  f.parent.mkdir(parents=True, exist_ok=True)
1724
2283
  f.write_text("\n".join(lines) + "\n", encoding="utf-8")
2284
+ if note is not None:
2285
+ print(f"[ok] dated entry added to audit/{PROJECT_NOTES}: {add_dated_note(root, note)}")
2286
+ elif not _open_units(root):
2287
+ # no open unit's Diary covers this work: a release, a fix after closure
2288
+ print(f"[note] no open unit records this work. If it is a release or a change worth "
2289
+ f"finding later, re-run with --note \"<what was done>\": mark writes the "
2290
+ f"dated entry in audit/{PROJECT_NOTES} for you.")
1725
2291
  if use_git_ref:
1726
2292
  # F-056: the reference is born here, so this is where the gestures that
1727
2293
  # orphan it are named. An amend was the observed one.
@@ -1752,6 +2318,29 @@ ORIENT_HOOK_CONFIG_CAP = 1024 * 1024 # settings are tiny; cap pathological file
1752
2318
  _ORIENT_HOOK_CMD_RE = re.compile(r" orient(\s|$)")
1753
2319
  _ORIENT_HOOK_TOKEN_RE = re.compile(r'"([^"]*)"|(\S+)')
1754
2320
 
2321
+ # Same fixed, versioned carrier as scripts/lib.js; only JSON data is decoded.
2322
+ _CODEX_HOOK_WRAPPER = "import base64,json,subprocess,sys;d=json.loads(base64.b64decode(sys.argv[2]));subprocess.run([sys.executable,d['validator'],*d['argv']],input=sys.stdin.buffer.read())"
2323
+
2324
+
2325
+ def _decode_hook_invocation(command):
2326
+ middle = ' -c "' + _CODEX_HOOK_WRAPPER + '" agentic-sdlc-hook-v1 '
2327
+ if not isinstance(command, str) or middle not in command:
2328
+ return None
2329
+ prefix, encoded = command.split(middle, 1)
2330
+ if not re.fullmatch(r'[\w.-]+|"[^"$`\r\n]+"', prefix):
2331
+ return None
2332
+ try:
2333
+ data = json.loads(base64.b64decode(encoded, validate=True))
2334
+ if (not isinstance(data, dict) or data.get("client") != "codex"
2335
+ or not isinstance(data.get("validator"), str)
2336
+ or not isinstance(data.get("argv"), list) or not data["argv"]
2337
+ or not all(isinstance(a, str) for a in data["argv"])
2338
+ or data["argv"][0] not in ("orient", "remind", "verdict", "constraints")):
2339
+ return None
2340
+ return data
2341
+ except (ValueError, TypeError):
2342
+ return None
2343
+
1755
2344
 
1756
2345
  def _orient_entries_in(p):
1757
2346
  """Yield the SessionStart commands invoking an orient entry point from ONE
@@ -1762,11 +2351,20 @@ def _orient_entries_in(p):
1762
2351
  try:
1763
2352
  if not p.is_file() or p.stat().st_size > ORIENT_HOOK_CONFIG_CAP:
1764
2353
  return
1765
- data = json.loads(p.read_text(encoding="utf-8-sig"))
2354
+ if p.suffix == ".toml":
2355
+ import tomllib
2356
+ data = tomllib.loads(p.read_text(encoding="utf-8-sig"))
2357
+ else:
2358
+ data = json.loads(p.read_text(encoding="utf-8-sig"))
1766
2359
  except Exception:
1767
2360
  return
1768
2361
  if not isinstance(data, dict):
1769
2362
  return
2363
+ features = data.get("features")
2364
+ if p.name in ("hooks.json", "config.toml") and (
2365
+ isinstance(features, dict) and features.get("hooks") is False
2366
+ or data.get("allow_managed_hooks_only") is True):
2367
+ return
1770
2368
  hooks = data.get("hooks")
1771
2369
  groups = hooks.get("SessionStart") if isinstance(hooks, dict) else None
1772
2370
  if groups is None:
@@ -1776,12 +2374,20 @@ def _orient_entries_in(p):
1776
2374
  for group in groups:
1777
2375
  if not isinstance(group, dict):
1778
2376
  continue
2377
+ codex = p.name in ("hooks.json", "config.toml")
2378
+ if codex and group.get("enabled") is False:
2379
+ continue
1779
2380
  inner = group.get("hooks")
1780
2381
  for h in inner if isinstance(inner, list) else [group]:
2382
+ if codex and (not isinstance(h, dict) or h.get("enabled") is False or h.get("type") != "command"):
2383
+ continue
1781
2384
  cmd = h.get("command") if isinstance(h, dict) else None
1782
- if (isinstance(cmd, str)
1783
- and any(n in cmd for n in ORIENT_HOOK_ENTRY_POINTS)
1784
- and _ORIENT_HOOK_CMD_RE.search(cmd)):
2385
+ if isinstance(h, dict) and p.name in ("hooks.json", "config.toml") and os.name == "nt":
2386
+ cmd = h.get("commandWindows") or h.get("command_windows") or cmd
2387
+ invocation = _decode_hook_invocation(cmd)
2388
+ if ((invocation and invocation["argv"][0] == "orient") or
2389
+ (isinstance(cmd, str) and any(n in cmd for n in ORIENT_HOOK_ENTRY_POINTS)
2390
+ and _ORIENT_HOOK_CMD_RE.search(cmd))):
1785
2391
  yield cmd
1786
2392
 
1787
2393
 
@@ -1800,16 +2406,110 @@ def _orient_user_settings_path():
1800
2406
  return (Path(cfg) if cfg else Path.home() / ".claude") / "settings.json"
1801
2407
 
1802
2408
 
2409
+ def _codex_hook_config(root):
2410
+ """Observable Codex policy across sources; no trust or execution assertion."""
2411
+ home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
2412
+ disabled, unverified, disabled_entries = False, False, False
2413
+ for directory in (home, Path(root) / ".codex"):
2414
+ for name in ("hooks.json", "config.toml"):
2415
+ p = directory / name
2416
+ if not p.exists():
2417
+ continue
2418
+ try:
2419
+ if not p.is_file() or p.stat().st_size > ORIENT_HOOK_CONFIG_CAP:
2420
+ raise ValueError("unreadable configuration")
2421
+ text = p.read_text(encoding="utf-8-sig")
2422
+ if p.suffix == ".toml":
2423
+ import tomllib
2424
+ data = tomllib.loads(text)
2425
+ else:
2426
+ data = json.loads(text)
2427
+ if not isinstance(data, dict):
2428
+ raise ValueError("unknown configuration shape")
2429
+ features = data.get("features", {})
2430
+ hooks = data.get("hooks", {})
2431
+ if not isinstance(features, dict) or not isinstance(hooks, dict):
2432
+ raise ValueError("unknown policy or hooks shape")
2433
+ disabled |= features.get("hooks") is False or data.get("allow_managed_hooks_only") is True
2434
+ groups = hooks.get("SessionStart", data.get("SessionStart", []))
2435
+ if not isinstance(groups, list):
2436
+ raise ValueError("unknown hook groups")
2437
+ for group in groups:
2438
+ if not isinstance(group, dict):
2439
+ raise ValueError("unknown hook group")
2440
+ inner = group.get("hooks", [group])
2441
+ if not isinstance(inner, list) or not all(isinstance(h, dict) for h in inner):
2442
+ raise ValueError("unknown handlers")
2443
+ disabled_entries |= group.get("enabled") is False or any(h.get("enabled") is False for h in inner)
2444
+ except Exception:
2445
+ unverified = True
2446
+ policy = "disabled-by-policy" if disabled else "unverified" if unverified else "enabled"
2447
+ return {"policy": policy, "disabled_entries": disabled_entries}
2448
+
2449
+
1803
2450
  def _orient_hook_commands(root):
1804
- """Yield (command, at_user_level) across every known client config: the
1805
- three project-relative files, then the machine-global user settings --
2451
+ """Yield (command, at_user_level, place) across every known client config:
2452
+ the three project-relative files, then the machine-global user settings --
1806
2453
  the file the installer wires (F-042), without which a fixed machine's
1807
- projects would read as unwired forever."""
2454
+ projects would read as unwired forever. `place` is a display label, never a
2455
+ home path (F-075 prints it)."""
2456
+ codex_policy = _codex_hook_config(root)["policy"]
1808
2457
  for rel in ORIENT_HOOK_CONFIG_FILES:
2458
+ if rel.startswith(".codex/") and codex_policy != "enabled":
2459
+ continue
1809
2460
  for cmd in _orient_entries_in(Path(root) / rel):
1810
- yield cmd, False
2461
+ yield cmd, False, rel
1811
2462
  for cmd in _orient_entries_in(_orient_user_settings_path()):
1812
- yield cmd, True
2463
+ yield cmd, True, "user settings"
2464
+ if codex_policy != "enabled":
2465
+ return
2466
+ home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
2467
+ for name in ("hooks.json", "config.toml"):
2468
+ for cmd in _orient_entries_in(home / name):
2469
+ yield cmd, True, "codex user " + name
2470
+ for cmd in _orient_entries_in(Path(root) / ".codex" / name) if name == "config.toml" else ():
2471
+ yield cmd, False, ".codex/" + name
2472
+
2473
+
2474
+ def _orient_entry_live(root, cmd, at_user_level):
2475
+ """True unless the entry names a validator that does not resolve.
2476
+
2477
+ A matching entry whose tokens name no validator is "cannot tell" and counts
2478
+ as live (the lib.js contract: never report broken on cannot-tell). Relative
2479
+ tokens resolve against the project root (the vendored-validator
2480
+ convention); a USER-level relative token has no cwd to resolve against and
2481
+ is treated as cannot-tell."""
2482
+ invocation = _decode_hook_invocation(cmd)
2483
+ token = invocation["validator"] if invocation else None
2484
+ for m in _ORIENT_HOOK_TOKEN_RE.finditer(cmd):
2485
+ tok = m.group(1) if m.group(1) is not None else m.group(2)
2486
+ if any(tok.endswith(n) for n in ORIENT_HOOK_ENTRY_POINTS):
2487
+ token = tok
2488
+ break
2489
+ if token is None:
2490
+ return True
2491
+ tp = Path(token)
2492
+ if not tp.is_absolute():
2493
+ if at_user_level:
2494
+ return True
2495
+ tp = Path(root) / tp
2496
+ return tp.exists()
2497
+
2498
+
2499
+ def orient_wiring(root):
2500
+ """{client: {command: place}} for the LIVE orient entries, per client.
2501
+
2502
+ Per client because two clients never read each other's settings: a Codex
2503
+ entry beside a Claude Code one is two clients oriented once each, not one
2504
+ session oriented twice. Identical command strings count once. A dead entry
2505
+ delivers no copy and is left out (F-075 FS3)."""
2506
+ out = {}
2507
+ for cmd, at_user_level, place in _orient_hook_commands(root):
2508
+ if not _orient_entry_live(root, cmd, at_user_level):
2509
+ continue
2510
+ client = "codex" if place.startswith((".codex", "codex ")) else "claude"
2511
+ out.setdefault(client, {}).setdefault(cmd.strip(), place)
2512
+ return out
1813
2513
 
1814
2514
 
1815
2515
  def orient_hook_state(root):
@@ -1824,22 +2524,9 @@ def orient_hook_state(root):
1824
2524
  the project root (the vendored-validator convention); a USER-level relative
1825
2525
  token has no cwd to resolve against and is treated as cannot-tell."""
1826
2526
  matched = False
1827
- for cmd, at_user_level in _orient_hook_commands(root):
2527
+ for cmd, at_user_level, _place in _orient_hook_commands(root):
1828
2528
  matched = True
1829
- token = None
1830
- for m in _ORIENT_HOOK_TOKEN_RE.finditer(cmd):
1831
- tok = m.group(1) if m.group(1) is not None else m.group(2)
1832
- if any(tok.endswith(n) for n in ORIENT_HOOK_ENTRY_POINTS):
1833
- token = tok
1834
- break
1835
- if token is None:
1836
- return "wired"
1837
- tp = Path(token)
1838
- if not tp.is_absolute():
1839
- if at_user_level:
1840
- return "wired" # cannot tell: no cwd exists at user level
1841
- tp = Path(root) / tp
1842
- if tp.exists():
2529
+ if _orient_entry_live(root, cmd, at_user_level):
1843
2530
  return "wired"
1844
2531
  return "dead" if matched else "unwired"
1845
2532
 
@@ -1854,6 +2541,13 @@ def print_orient_hook_note(root):
1854
2541
  does): the note is check-layer behaviour, whoever owns the check."""
1855
2542
  try:
1856
2543
  state = orient_hook_state(root)
2544
+ codex = _codex_hook_config(root)
2545
+ if codex["policy"] != "enabled" or codex["disabled_entries"]:
2546
+ detail = codex["policy"] if codex["policy"] != "enabled" else "disabled definitions present"
2547
+ print(f"[note] Codex hook configuration: {detail}. Disabled or unverified "
2548
+ "definitions are excluded from wiring counts; trust and native delivery are not verified.")
2549
+ if state == "unwired":
2550
+ return
1857
2551
  if state == "unwired":
1858
2552
  print("[note] agent sessions start without automatic orientation on this "
1859
2553
  "machine (no session-orientation hook found at project or user level). "
@@ -1878,6 +2572,10 @@ def cmd_check(root, strict=False, hybrid=False, extra_validate=None, extra_secti
1878
2572
  rc_v = cmd_validate(root, strict=strict, hybrid=hybrid)
1879
2573
  if extra_validate is not None:
1880
2574
  rc_v = max(rc_v, extra_validate())
2575
+ # A3 (F-073): check only -- it reads git refs, and validate stays file-local.
2576
+ # Advisory: printed, never part of any rc.
2577
+ for a in id_advisories(root):
2578
+ print(f"[note] {a}")
1881
2579
  print("\n===== stale =====")
1882
2580
  rc_s = cmd_stale(root, hybrid=hybrid)
1883
2581
  rcs = [("validate", rc_v), ("stale", rc_s)]
@@ -1887,10 +2585,64 @@ def cmd_check(root, strict=False, hybrid=False, extra_validate=None, extra_secti
1887
2585
  failed = any(rc for _, rc in rcs)
1888
2586
  print(f"\ncheck: {'NOT CLEAN' if failed else 'CLEAN'} "
1889
2587
  f"({', '.join(f'{title} rc={rc}' for title, rc in rcs)})")
1890
- print_orient_hook_note(root)
2588
+ print_check_notes(root)
1891
2589
  return 1 if failed else 0
1892
2590
 
1893
2591
 
2592
+ def _attr_pattern(path):
2593
+ """A .gitattributes pattern matching exactly `path`. Order matters (probed):
2594
+ a backslash, glob characters and a leading `#` or `!` (comment, negation)
2595
+ are escaped first, then the result is C-quoted when it holds whitespace,
2596
+ `"` or a backslash."""
2597
+ p = re.sub(r"([\\\[*?])", r"\\\1", path)
2598
+ if p.startswith(("#", "!")):
2599
+ p = "\\" + p
2600
+ if re.search(r'[\s"\\]', p):
2601
+ p = '"' + p.replace("\\", "\\\\").replace('"', '\\"') + '"'
2602
+ return p
2603
+
2604
+
2605
+ def review_log_union_note(root):
2606
+ """F-090: the note for a review log git would not merge with union, or None.
2607
+
2608
+ Git itself is asked (`check-attr`), so patterns and nested files count;
2609
+ personal and system attribute files do not, so the answer is the one a
2610
+ teammate's clone gets. Only `unspecified` is a gap: `union` or any other
2611
+ driver is a choice. Residual: `.git/info/attributes` is still read. Any
2612
+ failure -- no git, not a work tree, timeout -- is no note: `check` never
2613
+ breaks on it."""
2614
+ try:
2615
+ log = ai_path(root, "audit", "reviews", "REVIEW_LOG.md")
2616
+ if not log.is_file():
2617
+ return None
2618
+ prefix = _git_out(root, "rev-parse", "--show-prefix", timeout=3)
2619
+ if prefix is None:
2620
+ return None
2621
+ rel = log.resolve().relative_to(Path(root).resolve()).as_posix()
2622
+ out = _git_out(root, "-c", "core.attributesFile=", "check-attr", "-z", "merge",
2623
+ "--", rel, timeout=3, env={"GIT_ATTR_NOSYSTEM": "1"})
2624
+ if out is None:
2625
+ return None
2626
+ fields = out.split("\0")
2627
+ if len(fields) < 3 or fields[2] != "unspecified":
2628
+ return None
2629
+ path = prefix.rstrip("\r\n") + rel # a folder may begin with a space
2630
+ return (f"[note] {path} has no merge attribute: two branches that both add review "
2631
+ "rows conflict when merged. Fix: add this line to .gitattributes at the "
2632
+ f"repository root: {_attr_pattern(path)} merge=union")
2633
+ except Exception:
2634
+ return None
2635
+
2636
+
2637
+ def print_check_notes(root):
2638
+ """Every check-layer note, informational and never an exit code. The one
2639
+ place an overlay that replaces `check` calls, so a new note cannot miss it."""
2640
+ print_orient_hook_note(root)
2641
+ note = review_log_union_note(root)
2642
+ if note:
2643
+ print(note)
2644
+
2645
+
1894
2646
  # --------------------------------------------------------------------- gate
1895
2647
 
1896
2648
  # --- UserPromptSubmit reminder hook (F-046) --------------------------------
@@ -1901,7 +2653,9 @@ def cmd_check(root, strict=False, hybrid=False, extra_validate=None, extra_secti
1901
2653
  #
1902
2654
  # The carrier is kb's (F-041 item B), lifted here so all three lenses share one
1903
2655
  # machine instead of two that do the same thing. Its contract is kept: the line
1904
- # is CONSTANT and reads NOTHING -- nothing repo- or session-controlled may ride
2656
+ # is CONSTANT and reads NOTHING repo- or session-controlled (F-093 / r44: it does
2657
+ # read which family lenses the machine has installed, names only) -- nothing
2658
+ # repo- or session-controlled may ride
1905
2659
  # text injected every turn, and zero reads is what keeps the per-turn cost flat.
1906
2660
  # What changed is the payload's first duty and the wiring. First duty: decide
1907
2661
  # whether the skill governs this work and, if it does, read it once -- an
@@ -1917,33 +2671,98 @@ REMIND_FALLBACK = (
1917
2671
  )
1918
2672
 
1919
2673
 
2674
+ # F-075: constant, for every lens -- with sibling lenses installed nothing per
2675
+ # turn said to choose the lens. r19's bound rose to 600 for it (r32, owner).
2676
+ REMIND_LENS_SUFFIX = (" Above L1, with sibling lenses installed: choose the lens with "
2677
+ "routing.md and declare it.")
2678
+
2679
+ # F-093: the family wires ONE shared reminder, the first installer's, so its
2680
+ # own text led a knowledge task to the code lens. With siblings installed the
2681
+ # suffix names every installed lens and its domain. The owner accepted the cost
2682
+ # (REQUEST_family_hook_wiring.md R3, rulings r19/r32 amended): the skills
2683
+ # directories are read each turn, names only, filtered by routing.md's table.
2684
+ REMIND_LENS_NAMED = (" Installed lenses: {lenses}. Above L1, choose the one that "
2685
+ "governs this work with routing.md, load it and declare it.")
2686
+
2687
+
2688
+ def remind_lens_suffix():
2689
+ """The lens-choice suffix: the constant one on a single-lens install, the
2690
+ named one when a sibling lens is installed. Never raises."""
2691
+ try:
2692
+ siblings = installed_sibling_lenses()
2693
+ if not siblings:
2694
+ return REMIND_LENS_SUFFIX
2695
+ family = lens_table()
2696
+ names = sorted(set(siblings) | {profile()["skill_name"]})
2697
+ return REMIND_LENS_NAMED.format(lenses=", ".join(
2698
+ f"{n} ({family[n]})" if n in family else n for n in names))
2699
+ except Exception:
2700
+ return REMIND_LENS_SUFFIX
2701
+
2702
+
1920
2703
  def cmd_remind(args):
1921
- """UserPromptSubmit hook: print the lens's constant per-turn line. Always 0.
2704
+ """UserPromptSubmit hook: print the lens's per-turn line. Always 0.
1922
2705
 
1923
- argv is ignored whole and nothing is read: a hook surface must not fail, and
1924
- a flag typo must not cost a turn's context."""
2706
+ argv is ignored whole and nothing repo- or session-controlled is read: a
2707
+ hook surface must not fail, and a flag typo must not cost a turn's context.
2708
+ The one input is which family lenses this machine has installed (F-093)."""
1925
2709
  try:
1926
2710
  prof = profile()
1927
2711
  line = prof.get("remind_line") or REMIND_FALLBACK.format(skill=prof["skill_name"])
1928
- print(f"{prof['skill_name']}: {line}")
2712
+ print(f"{prof['skill_name']}: {line}{remind_lens_suffix()}")
1929
2713
  except Exception:
1930
2714
  pass
1931
2715
  return 0
1932
2716
 
2717
+ def read_hook_payload():
2718
+ """The hook event JSON on stdin as a dict, or None when it cannot be read.
2719
+
2720
+ bytes -> utf-8-sig: the payload is UTF-8 JSON regardless of the console code
2721
+ page; '-sig' strips the BOM (PowerShell pipes)."""
2722
+ try:
2723
+ raw = sys.stdin.buffer.read().decode("utf-8-sig", errors="replace")
2724
+ payload = json.loads(raw)
2725
+ except Exception:
2726
+ return None
2727
+ return payload if isinstance(payload, dict) else None
2728
+
2729
+
2730
+ def hook_project(target, root=None, docs_name=None):
2731
+ """The project root an edit hook judges, with its docs root name set, or None
2732
+ when two docs roots sit side by side. The hook runs in the session's current
2733
+ directory, which a `cd` moves (live probe 2026-10-27): the project AND its docs
2734
+ root name are the ones holding the edited file, never the ones around the
2735
+ working directory. An explicit root (--root) is kept as given."""
2736
+ start = Path(root) if root is not None else Path(target).resolve().parent
2737
+ try:
2738
+ found_root, name = resolve_docs_dir(argparse.Namespace(docs_dir=docs_name), start)
2739
+ except AmbiguousDocsRoot:
2740
+ return None
2741
+ set_docs_dir(name)
2742
+ if root is not None:
2743
+ return Path(root)
2744
+ if found_root is not None:
2745
+ return found_root
2746
+ found_root = find_project_root(start) # an explicit name: discovery did not run
2747
+ # No docs root above the edited file: the session's own project, as before the
2748
+ # hook resolved from the file -- the file's folder would unprotect a gated path.
2749
+ return found_root if ai_path(found_root).is_dir() else find_project_root()
2750
+
2751
+
1933
2752
  def cmd_gate(args):
1934
2753
  file_path = args.file or ""
1935
2754
  if args.hook:
2755
+ payload = read_hook_payload()
1936
2756
  try:
1937
- # bytes -> utf-8-sig: the hook payload is UTF-8 JSON regardless of the
1938
- # console code page; '-sig' strips the BOM (PowerShell pipes)
1939
- raw = sys.stdin.buffer.read().decode("utf-8-sig", errors="replace")
1940
- payload = json.loads(raw)
1941
2757
  file_path = (payload.get("tool_input") or {}).get("file_path") or ""
1942
- except Exception:
2758
+ except AttributeError:
1943
2759
  return 0 # unparseable input: do not block
1944
- if not file_path:
2760
+ if not isinstance(file_path, str) or not file_path:
1945
2761
  return 0
1946
- root = Path(args.root).resolve() if args.root else find_project_root()
2762
+ root = hook_project(file_path, Path(args.root).resolve() if args.root else None,
2763
+ getattr(args, "docs_dir", None))
2764
+ if root is None:
2765
+ return 0 # two docs roots side by side: cannot tell which governs
1947
2766
  try:
1948
2767
  rel = str(Path(file_path).resolve().relative_to(root)).replace("\\", "/")
1949
2768
  except ValueError:
@@ -1970,10 +2789,885 @@ def cmd_gate(args):
1970
2789
  sys.stderr.write(
1971
2790
  f"[sdlc gate] '{rel}' is on a protected path but no ANALYSIS_*.md is IN_PROGRESS. "
1972
2791
  "If your analysis already exists, set its frontmatter to 'status: IN_PROGRESS' "
1973
- "(that flip is what opens the gate); otherwise write it first (Phase 3).\n")
2792
+ "(that flip is what opens the gate; at L3, only after the owner's design approval, "
2793
+ "review.md); otherwise write it first (Phase 3).\n")
1974
2794
  return 2
1975
2795
 
1976
2796
 
2797
+ # ------------------------------------------------------------------ verdict
2798
+ # F-076: Rule Zero's router verdict, checked at the edit. A field agent edited
2799
+ # without declaring one and said nothing stopped it. This reads the session
2800
+ # transcript the client hands every hook and refuses the edit (JSON deny, exit
2801
+ # 0) only on certainty; whatever it cannot tell resolves to silence. It never
2802
+ # prints `allow` -- that would skip the user's permission prompt. Owner: block
2803
+ # (REQUEST_guide_verdict_check.md R3), wired by default (R4, rulings.md r34).
2804
+ #
2805
+ # F-094: a named guide counts as read only when the session read EVERY line of
2806
+ # it. Before, the guide's name anywhere in a non-edit tool's input was a read, so
2807
+ # `Read offset=1 limit=130` of a 225-line guide, `head -30` or a Grep on it all
2808
+ # passed (field scan: 157 partial Reads of guides against 118 whole ones), and
2809
+ # the agent applied the part it had seen. A read is now a line span: a Read call
2810
+ # (offset is the 1-based first line, probed 2026-11-12; no limit = the client's
2811
+ # READ_DEFAULT_LIMIT), a literal shell `cat`/`Get-Content` (whole, or its
2812
+ # -TotalCount), a get_file_content (whole). Grep, head, sed, an Agent prompt
2813
+ # naming the guide: no span. The guide is read when the spans cover 1..its last
2814
+ # line. Owner: REQUEST_whole_guide_read.md R1.
2815
+
2816
+ VERDICT_EDIT_TOOLS = ("Edit", "Write", "MultiEdit", "NotebookEdit")
2817
+ READ_DEFAULT_LIMIT = 2000 # Claude Code's Read without `limit` stops at line 2000
2818
+ GUIDE_COUNT_MAX = 8 * 1024 * 1024 # a larger guide: cannot afford to count its lines
2819
+ VERDICT_MAX_BYTES = 256 * 1024 * 1024 # a larger transcript: cannot afford to tell
2820
+ VERDICT_LINE_MAX = 1024 * 1024 # assistant lines are small; skip the rest unparsed
2821
+ # Markdown emphasis between the word and the colon ("**router**: no match") and
2822
+ # "Router verdict:" are the same declaration.
2823
+ _VERDICT_ROUTER_RE = re.compile(r"router(?:[\s*_`]+verdict)?[\s*_`]*:(.*)", re.IGNORECASE)
2824
+ # A declaration line may open with markdown: emphasis, quote, heading, bullet or a
2825
+ # numbered item ("## Level: L1", "1. Level: L1", "• router: no match").
2826
+ _LINE_OPEN = r"^[ \t>*_`#+•-]*(?:\d+[.)][ \t*_`]*)?"
2827
+ _LEVEL_WORD = r"(?:level|livello|niveau|nivel|stufe)\b[ \t*_`:·—–-]*(?:è[ \t]+)?"
2828
+ # ...and only on a line that opens with `router` or with a level (`L2`, `Spike`): a
2829
+ # verdict quoted inside a sentence is not one.
2830
+ _VERDICT_LINE_RE = re.compile(
2831
+ _LINE_OPEN + r"(?:router\b|" + _LEVEL_WORD + r"(?:(?:research[ \t]+)?spike|[A-Z][123])\b)", re.IGNORECASE)
2832
+ _VERDICT_NONE_RE = re.compile(r"[\s`*_\"'(]*(no match|absent)", re.IGNORECASE)
2833
+ # A level is DECLARED by a line that opens with the level word, in the form Rule
2834
+ # Zero prescribes -- level 1 alone, 2/3 with `router` on the same line -- so a level
2835
+ # quoted inside a sentence is not one. The letter is the lens's own (`L1`, `E1`):
2836
+ # groups are (letter, "1" or "", "2"/"3" or "").
2837
+ _DECLARATION_RE = re.compile(
2838
+ _LINE_OPEN + _LEVEL_WORD +
2839
+ r"([A-Z])(?:(1)\b|([23])\b(?=[^\n]*\brouter\b))", re.IGNORECASE | re.MULTILINE)
2840
+ _GUIDE_NAME_RE = re.compile(r"GUIDE_[A-Za-z0-9_-]+\.md")
2841
+
2842
+
2843
+ def _hint_path(value, cwd):
2844
+ if not isinstance(value, str) or not value:
2845
+ return None
2846
+ p = Path(value)
2847
+ if not p.is_absolute():
2848
+ if not cwd or not Path(cwd).is_absolute():
2849
+ return None
2850
+ p = Path(cwd) / p
2851
+ return str(p.resolve())
2852
+
2853
+
2854
+ def hook_edits(payload):
2855
+ """Parse the complete native apply_patch syntax without executing it.
2856
+
2857
+ Unknown or incomplete input yields no partial target set. Move checks both
2858
+ the old and new paths; file membership is evaluated by the existing gate.
2859
+ """
2860
+ command = (payload.get("tool_input") or {}).get("command")
2861
+ if not isinstance(command, str) or len(command.encode("utf-8")) > VERDICT_LINE_MAX:
2862
+ return None
2863
+ lines = command.strip().splitlines()
2864
+ if not lines or lines[0] != "*** Begin Patch" or lines[-1] != "*** End Patch":
2865
+ return None
2866
+ edits, current, mode, changed = [], None, None, False
2867
+ for line in lines[1:-1]:
2868
+ match = re.fullmatch(r"\*\*\* (Add|Update|Delete) File: (.+)", line)
2869
+ if match:
2870
+ if current is not None and mode != "Delete" and not changed:
2871
+ return None
2872
+ mode, value = match.groups()
2873
+ target = _hint_path(value, payload.get("cwd"))
2874
+ if not target:
2875
+ return None
2876
+ current = {"path": target, "new_text": ""}
2877
+ edits.append(current)
2878
+ changed = False
2879
+ elif line.startswith("*** Move to: ") and current is not None and mode == "Update" and not changed:
2880
+ target = _hint_path(line[len("*** Move to: "):], payload.get("cwd"))
2881
+ if not target:
2882
+ return None
2883
+ current = {"path": target, "new_text": ""}
2884
+ edits.append(current)
2885
+ elif current is not None and mode != "Delete" and (
2886
+ line.startswith(("+", "-", " ", "@@")) or line == "*** End of File"):
2887
+ if mode == "Add" and not line.startswith("+"):
2888
+ return None
2889
+ if line.startswith(("+", "-")):
2890
+ changed = True
2891
+ if line.startswith("+"):
2892
+ current["new_text"] += line[1:] + "\n"
2893
+ else:
2894
+ return None
2895
+ if current is not None and mode != "Delete" and not changed:
2896
+ return None
2897
+ return edits or None
2898
+
2899
+
2900
+ def shell_read_paths(command, cwd, workdir=None):
2901
+ """Literal Get-Content/cat reads only: no shell expansion or execution."""
2902
+ found = shell_read(command, cwd, workdir)
2903
+ return found[0] if found else None
2904
+
2905
+
2906
+ def shell_read(command, cwd, workdir=None):
2907
+ """(paths, line count or None) of a literal Get-Content/cat read, else None.
2908
+ The count is Get-Content's -TotalCount (F-094): those lines only, not the file."""
2909
+ if not isinstance(command, str) or re.search(r"[$`\r\n;|&<>\x00]", command):
2910
+ return None
2911
+ token_re = re.compile(r"\s*(?:'([^']*)'|\"([^\"]*)\"|([^\s'\"]+))")
2912
+ tokens, pos = [], 0
2913
+ while pos < len(command.rstrip()):
2914
+ match = token_re.match(command, pos)
2915
+ if not match:
2916
+ return None
2917
+ token = next(x for x in match.groups() if x is not None)
2918
+ tokens.append(token)
2919
+ pos = match.end()
2920
+ if not tokens or tokens[0].lower() not in ("get-content", "cat"):
2921
+ return None
2922
+ paths, i, count = [], 1, None
2923
+ while i < len(tokens):
2924
+ token = tokens[i]
2925
+ if tokens[0].lower() == "get-content" and token.lower() in ("-literalpath", "-path", "-raw"):
2926
+ if token.lower() != "-raw" and i + 1 == len(tokens):
2927
+ return None
2928
+ elif tokens[0].lower() == "get-content" and token.lower() == "-totalcount":
2929
+ i += 1
2930
+ if i == len(tokens) or not tokens[i].isdigit():
2931
+ return None
2932
+ count = int(tokens[i])
2933
+ elif tokens[0] == "cat" and token == "--":
2934
+ pass
2935
+ elif token.startswith("-") or re.search(r"[*?\[\],]", token):
2936
+ return None
2937
+ else:
2938
+ base = _hint_path(workdir, cwd) if workdir else cwd
2939
+ resolved = _hint_path(token, base)
2940
+ if not resolved:
2941
+ return None
2942
+ paths.append(resolved)
2943
+ i += 1
2944
+ return (paths, count) if paths else None
2945
+
2946
+
2947
+ def _codex_literal_calls(code):
2948
+ """Recognize a small non-executable JS carrier grammar, otherwise nothing."""
2949
+ if not isinstance(code, str):
2950
+ return []
2951
+ calls, pos = [], 0
2952
+ pattern = re.compile(r"\s*(?:text\(\s*)?await\s+tools\.exec_command\((\{.*?\})\)\s*\)?\s*;?", re.DOTALL)
2953
+ field = re.compile(r'\s*(?:"(cmd|workdir)"|(cmd|workdir))\s*:\s*("(?:[^"\\]|\\.)*")\s*(,|$)')
2954
+ while pos < len(code.rstrip()):
2955
+ match = pattern.match(code, pos)
2956
+ if not match:
2957
+ return []
2958
+ obj, off, args = match[1][1:-1], 0, {}
2959
+ while off < len(obj.rstrip()):
2960
+ item = field.match(obj, off)
2961
+ if not item or (item[1] or item[2]) in args:
2962
+ return []
2963
+ try:
2964
+ args[item[1] or item[2]] = json.loads(item[3])
2965
+ except ValueError:
2966
+ return []
2967
+ off = item.end()
2968
+ if "cmd" not in args:
2969
+ return []
2970
+ calls.append(args)
2971
+ pos = match.end()
2972
+ return calls
2973
+
2974
+
2975
+ def transcript_events(path):
2976
+ """Yield legacy assistant blocks, plus normalized recognized Codex blocks.
2977
+
2978
+ This is read-only and bounded by the existing transcript limits. Historical
2979
+ cwd is taken from host metadata, never guessed from the present process.
2980
+ """
2981
+ cwd = None
2982
+ with Path(path).open("rb") as fh:
2983
+ for raw in fh:
2984
+ if len(raw) > VERDICT_LINE_MAX:
2985
+ continue
2986
+ try:
2987
+ entry = json.loads(raw.decode("utf-8", errors="replace"))
2988
+ except ValueError:
2989
+ continue
2990
+ if not isinstance(entry, dict):
2991
+ continue
2992
+ if entry.get("type") == "assistant":
2993
+ yield entry
2994
+ continue
2995
+ data = entry.get("payload")
2996
+ if not isinstance(data, dict):
2997
+ continue
2998
+ if entry.get("type") in ("session_meta", "turn_context"):
2999
+ if isinstance(data.get("cwd"), str):
3000
+ cwd = data["cwd"]
3001
+ continue
3002
+ if entry.get("type") != "response_item":
3003
+ continue
3004
+ blocks = []
3005
+ if data.get("type") == "message" and data.get("role") == "assistant":
3006
+ blocks = [{"type": "text", "text": x.get("text", "")}
3007
+ for x in (data.get("content") if isinstance(data.get("content"), list) else []) if isinstance(x, dict) and x.get("type") == "output_text"]
3008
+ elif data.get("type") in ("function_call", "custom_tool_call"):
3009
+ name = data.get("name")
3010
+ calls = []
3011
+ if name in ("exec_command", "Bash"):
3012
+ try:
3013
+ args = json.loads(data.get("arguments", "{}"))
3014
+ except (ValueError, TypeError):
3015
+ args = None
3016
+ if isinstance(args, dict):
3017
+ calls = [args]
3018
+ elif name == "exec":
3019
+ calls = _codex_literal_calls(data.get("input"))
3020
+ elif name == "apply_patch":
3021
+ command = data.get("input")
3022
+ if command is None:
3023
+ try:
3024
+ command = json.loads(data.get("arguments", "{}" )).get("command")
3025
+ except (ValueError, TypeError, AttributeError):
3026
+ pass
3027
+ for edit in hook_edits({"tool_input": {"command": command}, "cwd": cwd}) or []:
3028
+ blocks.append({"type": "tool_use", "name": "Write", "input": {"file_path": edit["path"]}})
3029
+ for args in calls:
3030
+ found = shell_read(args.get("cmd", args.get("command")), cwd, args.get("workdir"))
3031
+ for target in (found[0] if found else []):
3032
+ # F-094: the shell read is whole (no limit) unless -TotalCount
3033
+ inp = {"file_path": target}
3034
+ inp.update({"limit": found[1]} if found[1] is not None else {"whole": True})
3035
+ blocks.append({"type": "tool_use", "name": "Read", "input": inp})
3036
+ if blocks:
3037
+ yield {"type": "assistant", "isSidechain": bool(entry.get("agent_id") or data.get("agent_id")),
3038
+ "message": {"content": blocks}}
3039
+
3040
+
3041
+ def transcript_facts(path):
3042
+ """What the session transcript shows about the verdict duty, or None when it
3043
+ cannot be read within the bounds.
3044
+
3045
+ Returns {"assistant": entries parsed, "sidechain": a subagent's own transcript
3046
+ (Claude Code marks every entry of one `isSidechain`), "declared": a router verdict seen,
3047
+ "trivial": a level-1 declaration seen (`Level: L1`, `E1`), "named": guides the verdicts name,
3048
+ "read": guide name -> the line spans the session read of it (F-094, _read_spans)}."""
3049
+ facts = {"assistant": 0, "sidechain": False, "declared": False, "trivial": False,
3050
+ "named": set(), "read": {}}
3051
+ try:
3052
+ p = Path(path)
3053
+ if not p.is_file() or p.stat().st_size > VERDICT_MAX_BYTES:
3054
+ return None
3055
+ for entry in transcript_events(p):
3056
+ if not isinstance(entry, dict) or entry.get("type") != "assistant":
3057
+ continue
3058
+ content = (entry.get("message") or {}).get("content")
3059
+ if not isinstance(content, list):
3060
+ continue
3061
+ facts["assistant"] += 1
3062
+ if entry.get("isSidechain") is True:
3063
+ facts["sidechain"] = True
3064
+ for block in content:
3065
+ if not isinstance(block, dict):
3066
+ continue
3067
+ if block.get("type") == "text":
3068
+ for line in str(block.get("text") or "").splitlines():
3069
+ d = _DECLARATION_RE.match(line)
3070
+ if d and d.group(2):
3071
+ facts["trivial"] = True
3072
+ m = _VERDICT_ROUTER_RE.search(line)
3073
+ if m and (d or _VERDICT_LINE_RE.match(line)):
3074
+ facts["declared"] = True
3075
+ if not _VERDICT_NONE_RE.match(m.group(1)):
3076
+ facts["named"].update(_GUIDE_NAME_RE.findall(m.group(1)))
3077
+ elif block.get("type") == "tool_use":
3078
+ base = entry.get("cwd") if isinstance(entry.get("cwd"), str) else None
3079
+ for name, span in _read_spans(block, base or str(p.parent)):
3080
+ facts["read"].setdefault(name, []).append(span)
3081
+ except (OSError, ValueError, TypeError, AttributeError):
3082
+ return None
3083
+ return facts
3084
+
3085
+
3086
+ def _read_spans(block, cwd):
3087
+ """(guide name, (first line, last line or None = end of file)) for each guide
3088
+ this tool call read (F-094). Only reads that return the file's lines count; a
3089
+ search, an excerpt command or a prompt naming the guide reads nothing. `cwd`
3090
+ only anchors a relative shell path: the guide is matched by its name."""
3091
+ name, inp = block.get("name"), block.get("input")
3092
+ if not isinstance(inp, dict):
3093
+ return []
3094
+ if name == "Read" and isinstance(inp.get("file_path"), str):
3095
+ if inp.get("whole") is True:
3096
+ span = (1, None)
3097
+ else:
3098
+ offset, limit = inp.get("offset"), inp.get("limit")
3099
+ for v in (offset, limit): # present but not a plain int: cannot tell, no credit
3100
+ if v is not None and (not isinstance(v, int) or isinstance(v, bool)):
3101
+ return []
3102
+ if limit is not None and limit <= 0:
3103
+ return []
3104
+ first = offset if offset is not None and offset > 1 else 1
3105
+ count = limit if limit is not None else READ_DEFAULT_LIMIT
3106
+ span = (first, first + count - 1)
3107
+ return [(g, span) for g in _GUIDE_NAME_RE.findall(Path(inp["file_path"]).name)]
3108
+ if name in ("Bash", "PowerShell"):
3109
+ found = shell_read(inp.get("command"), cwd)
3110
+ if not found:
3111
+ return []
3112
+ span = (1, found[1]) if found[1] is not None else (1, None)
3113
+ return [(g, span) for path in found[0] for g in _GUIDE_NAME_RE.findall(Path(path).name)]
3114
+ if isinstance(name, str) and name.endswith("get_file_content"):
3115
+ paths = inp.get("paths") if isinstance(inp.get("paths"), list) else []
3116
+ return [(g, (1, None)) for path in paths if isinstance(path, str)
3117
+ for g in _GUIDE_NAME_RE.findall(Path(path).name)]
3118
+ return []
3119
+
3120
+
3121
+ def _guide_lines(path):
3122
+ """The guide's line count, or None when it cannot be counted within the bounds."""
3123
+ try:
3124
+ if path.stat().st_size > GUIDE_COUNT_MAX:
3125
+ return None
3126
+ text = path.read_bytes()
3127
+ except OSError:
3128
+ return None
3129
+ return text.count(b"\n") + (0 if not text or text.endswith(b"\n") else 1)
3130
+
3131
+
3132
+ def _read_whole(spans, lines):
3133
+ """True when the spans cover lines 1..lines. Unknown size: any read counts."""
3134
+ if not spans:
3135
+ return False
3136
+ if lines is None:
3137
+ return True
3138
+ reached = 0
3139
+ for first, last in sorted(spans, key=lambda s: s[0]):
3140
+ if first > reached + 1:
3141
+ break
3142
+ reached = max(reached, lines if last is None else last)
3143
+ return reached >= lines
3144
+
3145
+
3146
+ def verdict_reason(payload, root=None, docs_name=None):
3147
+ """The refusal line for this edit event, or None when the edit may proceed.
3148
+ Without a root, the project is the one holding the edited file (hook_project)."""
3149
+ if payload.get("tool_name") == "apply_patch" and not payload.get("agent_id"):
3150
+ for edit in hook_edits(payload) or []:
3151
+ reason = verdict_reason({**payload, "tool_name": "Edit", "tool_input": {
3152
+ "file_path": edit["path"], "new_string": edit["new_text"]}}, root, docs_name)
3153
+ if reason:
3154
+ return reason
3155
+ return None
3156
+ if payload.get("tool_name") not in VERDICT_EDIT_TOOLS or payload.get("agent_id"):
3157
+ return None
3158
+ tool_input = payload.get("tool_input") or {}
3159
+ target = tool_input.get("file_path") or tool_input.get("notebook_path")
3160
+ transcript = payload.get("transcript_path")
3161
+ if not isinstance(target, str) or not target or not transcript:
3162
+ return None
3163
+ root = hook_project(target, root, docs_name)
3164
+ if root is None:
3165
+ return None # two docs roots side by side: cannot tell which governs
3166
+ try:
3167
+ Path(target).resolve().relative_to(root)
3168
+ except (ValueError, OSError):
3169
+ return None # outside the project: not this check's concern
3170
+ ref = ai_path(root, "reference")
3171
+ if not ref.is_dir():
3172
+ return None
3173
+ guides = {g.name for g in ref.glob("GUIDE_*.md") if g.is_file()}
3174
+ if not guides:
3175
+ return None
3176
+ facts = transcript_facts(transcript)
3177
+ if not facts or not facts["assistant"]:
3178
+ return None # unreadable, oversized or an unknown format: cannot tell
3179
+ if facts["sidechain"]:
3180
+ return None # a subagent works under its orchestrator's verdict
3181
+ if not (facts["declared"] or facts["trivial"]):
3182
+ return ("[sdlc verdict] No guide-router verdict in this session; this project has "
3183
+ f"guides ({docs_dir()}/reference/INDEX.md). Declare it with the level, e.g. "
3184
+ "\"Level: L2 · router: no match\" or \"router: GUIDE_x.md -> read\" "
3185
+ "(L1: \"Level: L1\"), then retry.")
3186
+ unread = sorted(g for g in facts["named"] & guides
3187
+ if not _read_whole(facts["read"].get(g), _guide_lines(ref / g)))
3188
+ if unread:
3189
+ return (f"[sdlc verdict] The router verdict names {', '.join(unread)}, not read "
3190
+ "whole in this session. Read every line (no offset or limit; past the read "
3191
+ "cap, in chunks to the end), then retry.")
3192
+ return None
3193
+
3194
+
3195
+ def cmd_verdict(args):
3196
+ """PreToolUse hook: print a JSON refusal or nothing. Always 0 -- exit 2 would
3197
+ block blind, and the wired command adds `; exit 0` for validators that cannot
3198
+ run this at all (missing, or older than it)."""
3199
+ if not args.hook:
3200
+ return 0
3201
+ try:
3202
+ payload = read_hook_payload()
3203
+ if payload is None:
3204
+ return 0
3205
+ root = Path(args.root).resolve() if args.root else None
3206
+ reason = verdict_reason(payload, root, getattr(args, "docs_dir", None))
3207
+ if reason:
3208
+ print(json.dumps({"hookSpecificOutput": {
3209
+ "hookEventName": "PreToolUse",
3210
+ "permissionDecision": "deny",
3211
+ "permissionDecisionReason": reason}}, ensure_ascii=False))
3212
+ except Exception:
3213
+ pass
3214
+ return 0
3215
+
3216
+
3217
+ # -------------------------------------------------------------- constraints
3218
+ # F-085: the constraint reader. It reads what an ANALYSIS already states in
3219
+ # extractable form -- id'd use cases, spec items and threats, and the rows of
3220
+ # the `### Preservation constraints` table -- and binds each to the files it
3221
+ # names. It names no feature and computes nothing: no count, rank or marker
3222
+ # reaches the output, and every view ends with CONSTRAINTS_SENTENCE naming what
3223
+ # it could not extract, so a short view never reads as a complete one.
3224
+
3225
+ CONSTRAINT_SECTIONS = (("## Use Cases",), ("## Functional Spec",), SECURITY_SECTION)
3226
+ INTERFACE_SECTION = ("## Interface Contract",)
3227
+ IMPACT_SECTION = ANALYSIS_SECTIONS[2]
3228
+ PRESERVATION_HEADING = "### Preservation constraints"
3229
+ NO_SYMBOL_LINE = "No existing symbol changed."
3230
+ CONSTRAINTS_SENTENCE = ("This view shows only the constraints written in extractable "
3231
+ "form and never replaces the ANALYSIS")
3232
+ CONSTRAINT_LINE_MAX = 300
3233
+
3234
+ _ITEM_RE = re.compile(r"^\s*([-*+]\s+|#{3,4}\s+|\|\s*)(?:\*\*|__)?(?:UC|FS|T)\d+\b")
3235
+ _P_ROW_RE = re.compile(r"^\|\s*(?:\*\*)?(P\d+)\b")
3236
+ _ITEM_ID_RE = re.compile(r"(UC|FS|T)\d+")
3237
+ _CITE_RE = re.compile(r"\b(UC|FS|T)(\d+)(?:\s*[–-]\s*(?:UC|FS|T)?(\d+))?\b")
3238
+ _BACKTICK_RE = re.compile(r"`([^`\n]+)`")
3239
+ _PATH_TOKEN_RE = re.compile(r"^[A-Za-z0-9_.\-/]+(?:::[A-Za-z0-9_.]+)?$")
3240
+ _PATH_EXT_RE = re.compile(r"[^./]\.[A-Za-z0-9]+$")
3241
+ _SENTENCE_END_RE = re.compile(r"[.!?](?=\s|$)")
3242
+ _CELL_SPLIT_RE = re.compile(r"(?<!\\)\|")
3243
+ _CONTROL_RE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")
3244
+
3245
+
3246
+ def _norm_rel(path):
3247
+ """Repository-relative, forward slashes, case-folded where the filesystem is."""
3248
+ p = path.replace("\\", "/")
3249
+ while p.startswith("./"):
3250
+ p = p[2:]
3251
+ return p.casefold() if os.name == "nt" else p
3252
+
3253
+
3254
+ def _path_tokens(text, need_slash):
3255
+ """The backticked file paths in `text`; `path::symbol` yields its path. An elided
3256
+ (`...`), globbed, placeholder or parent-relative path binds nothing; in prose
3257
+ (`need_slash`) a bare file name is a mention, not a binding."""
3258
+ out = set()
3259
+ for token in _BACKTICK_RE.findall(text or ""):
3260
+ t = token.strip()
3261
+ if "..." in t or "*" in t or t.startswith("/") or not _PATH_TOKEN_RE.match(t):
3262
+ continue
3263
+ path = t.split("::", 1)[0]
3264
+ while path.startswith("./"):
3265
+ path = path[2:]
3266
+ if ".." in path.split("/") or not _PATH_EXT_RE.search(path):
3267
+ continue
3268
+ if need_slash and "/" not in path:
3269
+ continue
3270
+ out.add(_norm_rel(path))
3271
+ return out
3272
+
3273
+
3274
+ def _first_sentence(text):
3275
+ """Up to the first sentence end outside a backticked span (so `a.py` never ends
3276
+ one); a bold title such as `**FS1 Ids.**` ends nothing either."""
3277
+ masked = _BACKTICK_RE.sub(lambda m: "`" + "x" * len(m.group(1)) + "`", text)
3278
+ m = _SENTENCE_END_RE.search(masked)
3279
+ return text[:m.end()] if m else text
3280
+
3281
+
3282
+ def _cells(row):
3283
+ return [c.strip() for c in _CELL_SPLIT_RE.split(row.strip().strip("|"))]
3284
+
3285
+
3286
+ def _cited_ids(text):
3287
+ """Ids cited in `text`, a range such as `FS3–FS7` expanded."""
3288
+ out = set()
3289
+ for prefix, start, end in _CITE_RE.findall(text or ""):
3290
+ a = int(start)
3291
+ b = int(end) if end else a
3292
+ if b < a or b - a > 50:
3293
+ b = a
3294
+ out.update(f"{prefix}{n}" for n in range(a, b + 1))
3295
+ return out
3296
+
3297
+
3298
+ def parse_constraints(text):
3299
+ """Every constraint `text` states in extractable form, in document order: a dict
3300
+ with `id`, `kind` (`item` or `P`), `section` (its `## ` heading), `line`
3301
+ (1-based), `statement`, `bindings` (normalized paths), `evidence` and
3302
+ `released` (a P row's release reference, or None)."""
3303
+ lines = (text or "").splitlines()
3304
+ items, impact_rows = [], []
3305
+ section, extracted, impact, preservation = None, False, False, False
3306
+ for n, line in enumerate(lines):
3307
+ if line.startswith("## "):
3308
+ section = line.strip()
3309
+ extracted = any(line.startswith(a) for s in CONSTRAINT_SECTIONS for a in s)
3310
+ impact = any(line.startswith(a) for a in IMPACT_SECTION)
3311
+ preservation = False
3312
+ continue
3313
+ if impact:
3314
+ if line.startswith("### "):
3315
+ preservation = line.strip().lower() == PRESERVATION_HEADING.lower()
3316
+ continue
3317
+ if not line.lstrip().startswith("|"):
3318
+ continue
3319
+ cells = _cells(line)
3320
+ if preservation:
3321
+ m = _P_ROW_RE.match(line.strip())
3322
+ if m and len(cells) >= 5:
3323
+ must = cells[3]
3324
+ released = None
3325
+ if must.startswith("RELEASED (") and ")" in must:
3326
+ released = must[len("RELEASED ("):must.index(")")]
3327
+ items.append({"id": m.group(1), "kind": "P", "section": section,
3328
+ "line": n + 1, "statement": must,
3329
+ "bindings": _path_tokens(cells[1], False),
3330
+ "evidence": cells[4], "released": released})
3331
+ elif cells:
3332
+ paths = _path_tokens(cells[0], False)
3333
+ if paths:
3334
+ impact_rows.append((paths, _cited_ids(" | ".join(cells[1:]))))
3335
+ continue
3336
+ if not extracted:
3337
+ continue
3338
+ m = _ITEM_RE.match(line)
3339
+ if not m:
3340
+ continue
3341
+ marker = m.group(1).strip()
3342
+ body = []
3343
+ if not marker.startswith("|"):
3344
+ for nxt in lines[n + 1:]:
3345
+ if nxt.startswith("#") or _ITEM_RE.match(nxt):
3346
+ break
3347
+ if marker.startswith("#"):
3348
+ if nxt.strip():
3349
+ body.append(nxt.strip())
3350
+ elif nxt.strip() and nxt[:1].isspace():
3351
+ body.append(nxt.strip())
3352
+ else:
3353
+ break
3354
+ if marker.startswith("|"):
3355
+ statement = _first_sentence(" | ".join(_cells(line)))
3356
+ whole = line
3357
+ elif marker.startswith("#"):
3358
+ title = line.lstrip("#").strip()
3359
+ rest = " ".join(body)
3360
+ statement = title + (" — " + _first_sentence(rest) if rest else "")
3361
+ whole = " ".join([line] + body)
3362
+ else:
3363
+ joined = " ".join([line.strip()[len(marker):].strip()] + body)
3364
+ statement = _first_sentence(joined)
3365
+ whole = joined
3366
+ items.append({"id": _ITEM_ID_RE.search(line).group(0), "kind": "item",
3367
+ "section": section, "line": n + 1, "statement": statement,
3368
+ "bindings": _path_tokens(whole, True), "evidence": None,
3369
+ "released": None})
3370
+ for paths, ids in impact_rows:
3371
+ for c in items:
3372
+ if c["kind"] == "item" and c["id"] in ids:
3373
+ c["bindings"] |= paths
3374
+ return items
3375
+
3376
+
3377
+ def has_preservation_record(impact_body):
3378
+ """True when an Impact body holds the preservation table or the no-symbol line."""
3379
+ return any(b.strip().lower() == PRESERVATION_HEADING.lower() or b.strip() == NO_SYMBOL_LINE
3380
+ for b in (impact_body or "").splitlines())
3381
+
3382
+
3383
+ def unread_sections(text, items=None):
3384
+ """The `## ` headings the view could not extract, in document order: the
3385
+ Interface Contract (its items carry no id), an extracted section holding prose
3386
+ but no id'd item, and an Impact with neither the preservation table nor the
3387
+ no-symbol line."""
3388
+ items = parse_constraints(text) if items is None else items
3389
+ homes = {c["section"] for c in items if c["kind"] == "item"}
3390
+ lines = (text or "").splitlines()
3391
+ names = []
3392
+ for i, line in enumerate(lines):
3393
+ if not line.startswith("## "):
3394
+ continue
3395
+ body = []
3396
+ for nxt in lines[i + 1:]:
3397
+ if nxt.startswith("## "):
3398
+ break
3399
+ body.append(nxt)
3400
+ heading = line.strip()
3401
+ if any(line.startswith(a) for a in INTERFACE_SECTION):
3402
+ names.append(heading)
3403
+ elif any(line.startswith(a) for s in CONSTRAINT_SECTIONS for a in s):
3404
+ if any(b.strip() for b in body) and heading not in homes:
3405
+ names.append(heading)
3406
+ elif any(line.startswith(a) for a in IMPACT_SECTION):
3407
+ if not has_preservation_record("\n".join(body)):
3408
+ names.append(heading)
3409
+ return names
3410
+
3411
+
3412
+ def constraints_sentence(names):
3413
+ if not names:
3414
+ return CONSTRAINTS_SENTENCE + "."
3415
+ return CONSTRAINTS_SENTENCE + "; read in full: " + ", ".join(f"`{n}`" for n in names) + "."
3416
+
3417
+
3418
+ def _clip(line):
3419
+ line = _CONTROL_RE.sub("", line)
3420
+ return line if len(line) <= CONSTRAINT_LINE_MAX else line[:CONSTRAINT_LINE_MAX - 1] + "…"
3421
+
3422
+
3423
+ def constraint_lines(home, items, grouped):
3424
+ """FS4's lines: `ID — statement — home:line`, a P row followed by its evidence;
3425
+ `grouped` puts each home heading before its first item."""
3426
+ out, current = [], None
3427
+ for c in items:
3428
+ if grouped and c["section"] != current:
3429
+ current = c["section"]
3430
+ out.append(_clip(current))
3431
+ out.append(_clip(f"{c['id']} — {c['statement']} — {home}:{c['line']}"))
3432
+ if c["kind"] == "P" and c["evidence"]:
3433
+ out.append(_clip(f" evidence: {c['evidence']}"))
3434
+ return out
3435
+
3436
+
3437
+ def unit_constraints(root, unit):
3438
+ """[(path, meta, items, unread)] for the ANALYSIS files of `unit` -- an id such
3439
+ as F-001, or a file name with or without `.md`; [] when none matches."""
3440
+ key = str(unit or "").strip()
3441
+ name = key if key.endswith(".md") else key + ".md"
3442
+ out = []
3443
+ for p, meta, text in list_analyses(root):
3444
+ m = UNIT_ID_RE.search(str(meta.get("id") or ""))
3445
+ if p.name == name or (m and m.group(1) == key):
3446
+ items = parse_constraints(text)
3447
+ out.append((p, meta, items, unread_sections(text, items)))
3448
+ return out
3449
+
3450
+
3451
+ def project_relative(root, path):
3452
+ """`path` relative to `root`, normalized as bindings are, or None outside it."""
3453
+ raw = str(path or "").replace("\\", "/")
3454
+ if not raw:
3455
+ return None
3456
+ p = Path(raw)
3457
+ if not p.is_absolute():
3458
+ p = Path.cwd() / p
3459
+ try:
3460
+ rel = p.resolve().relative_to(Path(root).resolve())
3461
+ except (ValueError, OSError):
3462
+ return None
3463
+ return _norm_rel(rel.as_posix())
3464
+
3465
+
3466
+ def open_code_units(root):
3467
+ """[(path, meta, text)] for the tree's open L3 units of the code domain. Open
3468
+ units come from `_open_units`, unchanged (P1)."""
3469
+ if not ai_path(root).is_dir():
3470
+ return []
3471
+ open_names = {n for names in _open_units(root).values() for n in names}
3472
+ if not open_names:
3473
+ return []
3474
+ default = project_default_domain(root)
3475
+ return [(p, meta, text) for p, meta, text in list_analyses(root)
3476
+ if p.name in open_names
3477
+ and str(meta.get("level", "")).upper() == "L3"
3478
+ and meta.get("status") in ("PLANNED", "IN_PROGRESS")
3479
+ and resolve_domain(meta, default)[0] == "code"]
3480
+
3481
+
3482
+ def file_constraints(root, path):
3483
+ """[(path, meta, bound items, unread)] for each open L3 unit of the code domain
3484
+ with an unreleased constraint bound to `path`."""
3485
+ rel = project_relative(root, path)
3486
+ if rel is None:
3487
+ return []
3488
+ out = []
3489
+ for p, meta, text in open_code_units(root):
3490
+ items = parse_constraints(text)
3491
+ bound = [c for c in items if not c["released"] and rel in c["bindings"]]
3492
+ if bound:
3493
+ out.append((p, meta, bound, unread_sections(text, items)))
3494
+ return out
3495
+
3496
+
3497
+ # The recall hook (FS6). It informs, never decides: its JSON carries no
3498
+ # `permissionDecision`, so the user's permission flow is the one without it
3499
+ # (P6). A level is read with the verdict hook's `_DECLARATION_RE`; only the code
3500
+ # lens's `L` levels count here.
3501
+ CONSTRAINTS_HOOK_LINES = 15
3502
+ _WORK_TOOLS = VERDICT_EDIT_TOOLS + ("Read",)
3503
+
3504
+
3505
+ def transcript_work(path):
3506
+ """What the session transcript shows about the work, or None when it cannot be
3507
+ read within the verdict hook's bounds: {"assistant": entries parsed,
3508
+ "sidechain": a subagent's transcript, "level": the last declared level ("1",
3509
+ "2", "3") or None, "touched": normalized absolute paths this session read or
3510
+ wrote}."""
3511
+ work = {"assistant": 0, "sidechain": False, "level": None, "touched": set()}
3512
+ try:
3513
+ p = Path(path)
3514
+ if not p.is_file() or p.stat().st_size > VERDICT_MAX_BYTES:
3515
+ return None
3516
+ for entry in transcript_events(p):
3517
+ if not isinstance(entry, dict) or entry.get("type") != "assistant":
3518
+ continue
3519
+ content = (entry.get("message") or {}).get("content")
3520
+ if not isinstance(content, list):
3521
+ continue
3522
+ work["assistant"] += 1
3523
+ if entry.get("isSidechain") is True:
3524
+ work["sidechain"] = True
3525
+ for block in content:
3526
+ if not isinstance(block, dict):
3527
+ continue
3528
+ if block.get("type") == "text":
3529
+ for letter, one, other in _DECLARATION_RE.findall(
3530
+ str(block.get("text") or "")):
3531
+ if letter.upper() == "L":
3532
+ work["level"] = one or other
3533
+ elif block.get("type") == "tool_use" and block.get("name") in _WORK_TOOLS:
3534
+ inp = block.get("input") or {}
3535
+ target = inp.get("file_path") or inp.get("notebook_path")
3536
+ if isinstance(target, str) and target:
3537
+ try:
3538
+ work["touched"].add(_norm_rel(Path(target).resolve().as_posix()))
3539
+ except (OSError, ValueError):
3540
+ pass
3541
+ except (OSError, ValueError, TypeError, AttributeError):
3542
+ return None
3543
+ return work
3544
+
3545
+
3546
+ def _hook_new_text(tool_input):
3547
+ """The text an edit is about to write: Edit, Write, MultiEdit, NotebookEdit."""
3548
+ parts = [tool_input.get(k) for k in ("new_string", "content", "new_source")]
3549
+ for e in tool_input.get("edits") or []:
3550
+ if isinstance(e, dict):
3551
+ parts.append(e.get("new_string"))
3552
+ return "\n".join(x for x in parts if isinstance(x, str))
3553
+
3554
+
3555
+ def _unit_documents(root, p):
3556
+ """Normalized absolute paths of a unit's ANALYSIS, request records and handoff:
3557
+ reading or writing any of them is working on the unit."""
3558
+ slug = p.stem[len("ANALYSIS_"):]
3559
+ docs = {p, ai_path(root, "audit", f"HANDOFF_{slug}.md")}
3560
+ for r in requests_naming(root, p.name):
3561
+ docs.add(r)
3562
+ docs.add(ai_path(root, "audit", f"HANDOFF_{r.stem[len('REQUEST_'):]}.md"))
3563
+ return {_norm_rel(d.resolve().as_posix()) for d in docs}
3564
+
3565
+
3566
+ def constraints_hook_context(payload, root=None, docs_name=None):
3567
+ """The context to recall before this edit, or None (FS6): an edit tool, outside
3568
+ a subagent, on a file of a project whose open L3 code unit binds it (or the
3569
+ unit's own ANALYSIS, about to name a path a P row binds -- UC6), by a session
3570
+ that worked on that unit and last declared L3."""
3571
+ if payload.get("tool_name") == "apply_patch" and not payload.get("agent_id"):
3572
+ lines = []
3573
+ for edit in hook_edits(payload) or []:
3574
+ context = constraints_hook_context({**payload, "tool_name": "Edit", "tool_input": {
3575
+ "file_path": edit["path"], "new_string": edit["new_text"]}}, root, docs_name)
3576
+ for line in (context or "").splitlines():
3577
+ if line not in lines:
3578
+ lines.append(line)
3579
+ if len(lines) > CONSTRAINTS_HOOK_LINES:
3580
+ lines = lines[:CONSTRAINTS_HOOK_LINES - 1] + [lines[-1]]
3581
+ return "\n".join(lines) or None
3582
+ if payload.get("tool_name") not in VERDICT_EDIT_TOOLS or payload.get("agent_id"):
3583
+ return None
3584
+ tool_input = payload.get("tool_input") or {}
3585
+ target = tool_input.get("file_path") or tool_input.get("notebook_path")
3586
+ transcript = payload.get("transcript_path")
3587
+ if not isinstance(target, str) or not target or not transcript:
3588
+ return None
3589
+ root = hook_project(target, root, docs_name)
3590
+ if root is None or not ai_path(root, "solutions").is_dir():
3591
+ return None
3592
+ found = file_constraints(root, target)
3593
+ rel = project_relative(root, target)
3594
+ named = _path_tokens(_hook_new_text(tool_input), False)
3595
+ if named and rel and rel.startswith(_norm_rel(f"{docs_dir()}/solutions/ANALYSIS_")):
3596
+ for p, meta, text in open_code_units(root):
3597
+ if _norm_rel(f"{docs_dir()}/solutions/{p.name}") != rel:
3598
+ continue
3599
+ items = parse_constraints(text)
3600
+ bound = [c for c in items if c["kind"] == "P"
3601
+ and not c["released"] and c["bindings"] & named]
3602
+ if bound and not any(f[0] == p for f in found):
3603
+ found.append((p, meta, bound, unread_sections(text, items)))
3604
+ if not found:
3605
+ return None
3606
+ work = transcript_work(transcript)
3607
+ if not work or not work["assistant"] or work["sidechain"] or work["level"] != "3":
3608
+ return None
3609
+ # One budget for the whole recall, whatever the number of units; a P line and
3610
+ # its evidence line are kept together or left out together.
3611
+ out, budget = [], CONSTRAINTS_HOOK_LINES
3612
+ for p, meta, items, unread in found:
3613
+ if not (_unit_documents(root, p) & work["touched"]):
3614
+ continue
3615
+ home = f"solutions/{p.name}"
3616
+ unit = meta.get("id") or p.stem
3617
+ out.append(_clip(f"[sdlc constraints] {unit} — {home}"))
3618
+ shown = 0
3619
+ for c in items:
3620
+ chunk = constraint_lines(home, [c], False)
3621
+ if len(chunk) > budget:
3622
+ break
3623
+ out.extend(chunk)
3624
+ budget -= len(chunk)
3625
+ shown += 1
3626
+ if shown < len(items):
3627
+ out.append(_clip(f"More: sdlc_check.py constraints --unit {unit}"))
3628
+ out.append(_clip(constraints_sentence(unread)))
3629
+ return "\n".join(out) if out else None
3630
+
3631
+
3632
+ def cmd_constraints_hook(args):
3633
+ """PreToolUse hook: print a context-only JSON or nothing. Always 0 -- exit 2
3634
+ would block the edit, and the wired command adds `; exit 0` for validators
3635
+ that cannot run this at all (T2)."""
3636
+ try:
3637
+ payload = read_hook_payload()
3638
+ if payload is None:
3639
+ return 0
3640
+ root = Path(args.root).resolve() if args.root else None
3641
+ context = constraints_hook_context(payload, root, getattr(args, "docs_dir", None))
3642
+ if context:
3643
+ print(json.dumps({"hookSpecificOutput": {
3644
+ "hookEventName": "PreToolUse",
3645
+ "additionalContext": context}}, ensure_ascii=False))
3646
+ except Exception:
3647
+ pass
3648
+ return 0
3649
+
3650
+
3651
+ def cmd_constraints(root, args):
3652
+ if args.unit:
3653
+ found = unit_constraints(root, args.unit)
3654
+ if not found:
3655
+ print(f"[ERROR] unknown unit '{args.unit}': give an id such as F-001 "
3656
+ "or an ANALYSIS file name")
3657
+ return 1
3658
+ groups = [(p, meta, items, unread, True) for p, meta, items, unread in found]
3659
+ else:
3660
+ groups = [(p, meta, items, unread, False)
3661
+ for p, meta, items, unread in file_constraints(root, args.file)]
3662
+ for p, meta, items, unread, grouped in groups:
3663
+ home = f"solutions/{p.name}"
3664
+ print(_clip(f"{meta.get('id') or p.stem} — {home}"))
3665
+ for line in constraint_lines(home, items, grouped):
3666
+ print(line)
3667
+ print(_clip(constraints_sentence(unread)))
3668
+ return 0
3669
+
3670
+
1977
3671
  # --------------------------------------------------------------------- plan
1978
3672
  # Subagent Execution (Feature A). Zero-execution surface: this section and
1979
3673
  # everything it calls MUST NOT spawn a process (no subprocess/os.system/eval/
@@ -2173,15 +3867,23 @@ REVIEW_POSITIONAL = {
2173
3867
  }
2174
3868
 
2175
3869
 
3870
+ _UNESCAPED_PIPE_RE = re.compile(r"(?<!\\)\|")
3871
+
3872
+
2176
3873
  def _table_cells(line):
2177
3874
  """Cells of a Markdown table row, or None when the line is not one.
2178
- Separator rows (---, :---:, any alignment colons) are not data."""
3875
+ Separator rows (---, :---:, any alignment colons) are not data. A cell may
3876
+ carry an escaped pipe (`\\|`, as `index` writes them): it does not split the
3877
+ row, and it reads back as `|` (F-075)."""
2179
3878
  s = line.strip()
2180
3879
  if not s.startswith("|"):
2181
3880
  return None
2182
3881
  if set(s) <= set("|-: "):
2183
3882
  return None
2184
- return [c.strip() for c in s.strip("|").split("|")]
3883
+ body = s[1:]
3884
+ if body.endswith("|") and not body.endswith("\\|"):
3885
+ body = body[:-1]
3886
+ return [c.strip().replace("\\|", "|") for c in _UNESCAPED_PIPE_RE.split(body)]
2185
3887
 
2186
3888
 
2187
3889
  def parse_review_log(text):
@@ -2246,6 +3948,13 @@ def _is_pass(verdict):
2246
3948
  return re.search(r"\bPASS\b", (verdict or "").upper()) is not None
2247
3949
 
2248
3950
 
3951
+ def _is_not_due(verdict):
3952
+ """A review ruled not due (review.md, a delta that only restates judged
3953
+ work): logged so a skip stays visible, but it is neither a review nor a
3954
+ finding, so it stays out of every count below (F-071)."""
3955
+ return (verdict or "").strip().upper().startswith("NOT DUE")
3956
+
3957
+
2249
3958
  def _print_read_cost():
2250
3959
  """The cost side, printed with the benefit and NEVER without it: a catch
2251
3960
  rate with no cost term justifies unbounded doctrine, and a cost term with
@@ -2286,6 +3995,12 @@ def cmd_benefit(root):
2286
3995
  _print_read_cost()
2287
3996
  return 0
2288
3997
  rows, unparsed = parse_review_log(read_text(log))
3998
+ not_due = [r for r in rows if _is_not_due(r["verdict"])]
3999
+ rows = [r for r in rows if not _is_not_due(r["verdict"])]
4000
+ # F-085 FS10: a `post-merge` row is the owner's report of a defect that got
4001
+ # past every review -- not a review, so it stays out of every review figure.
4002
+ post_merge = [r for r in rows if r["tier"].lower().startswith("post-merge")]
4003
+ rows = [r for r in rows if not r["tier"].lower().startswith("post-merge")]
2289
4004
  # `tier` carries the MOMENT in Standalone (design / closure) and the
2290
4005
  # reviewer WEIGHT in Hybrid (deep / light / code / guide / vision). A
2291
4006
  # Hybrid row is a real review whose moment this column does not state, so
@@ -2310,9 +4025,14 @@ def cmd_benefit(root):
2310
4025
  unstated_code += n
2311
4026
  classified = moments["design"] + moments["closure"]
2312
4027
  print("rows parsed: %d rows unparsed: %d%s"
2313
- % (len(rows), len(unparsed),
4028
+ % (len(rows) + len(not_due) + len(post_merge), len(unparsed),
2314
4029
  (" -> " + "; ".join("line %d: %s" % u for u in unparsed[:5]))
2315
4030
  if unparsed else ""))
4031
+ print("reviews ruled not due (logged, counted in no figure below): %d"
4032
+ % len(not_due))
4033
+ if post_merge:
4034
+ print("defects reported after merge (tier post-merge, not reviews, "
4035
+ "counted in no figure below): %d" % len(post_merge))
2316
4036
  print("reviews with a stated moment: %d moment not stated by `tier`: %d%s"
2317
4037
  % (len(classified), sum(unstated.values()),
2318
4038
  (" (" + ", ".join("%s x%d" % (t, n) for t, n
@@ -2378,48 +4098,209 @@ def cmd_benefit(root):
2378
4098
  return 0
2379
4099
 
2380
4100
 
4101
+ # --- orient helpers (F-075) ---------------------------------------------------
4102
+ SKILL_MD_CAP = 64 * 1024 # a SKILL.md is read for its name only
4103
+
4104
+
4105
+ def orient_fit(lines, budget, rel):
4106
+ """The lines that fit `budget` characters (one newline each), cut at a line
4107
+ boundary and closed by a pointer to the file holding the rest. A single line
4108
+ wider than the room left shows its head. Never raises."""
4109
+ out, used = [], 0
4110
+ for i, line in enumerate(lines):
4111
+ if used + len(line) + 1 <= budget:
4112
+ out.append(line)
4113
+ used += len(line) + 1
4114
+ continue
4115
+ rest = len(lines) - i
4116
+
4117
+ def ptr(n):
4118
+ return f"(+{n} more lines -- read {rel})"
4119
+ room = budget - used - len(ptr(rest)) - 1
4120
+ if room > 40:
4121
+ head = line[:room - 4] + "..."
4122
+ out.append(head)
4123
+ used += len(head) + 1
4124
+ while out and used + len(ptr(rest)) + 1 > budget:
4125
+ used -= len(out.pop()) + 1
4126
+ rest += 1
4127
+ out.append(ptr(rest))
4128
+ return out
4129
+ return out
4130
+
4131
+
4132
+ def lens_table(skill_dir=None):
4133
+ """{skill_name: lens} from the running skill's own `routing.md` par.0 table.
4134
+
4135
+ The Python twin of lib.js `lensTable()`, same parse: a row whose lens cell is
4136
+ `[a-z]+` and whose skill cell is a backticked `[a-z0-9-]+`. `routing.md` is a
4137
+ byte-identical shared file, so the family list cannot drift between
4138
+ distributions -- a literal list here is how kb and mkt once announced
4139
+ themselves as the code lens. Fail-open: {} on any failure."""
4140
+ try:
4141
+ base = Path(skill_dir) if skill_dir else Path(__file__).resolve().parent.parent
4142
+ table = {}
4143
+ for line in read_text(base / "routing.md").splitlines():
4144
+ cells = [c.strip() for c in line.split("|")]
4145
+ if len(cells) < 4:
4146
+ continue
4147
+ lens, skill = cells[1], cells[2]
4148
+ if re.fullmatch(r"[a-z]+", lens) and re.fullmatch(r"`[a-z0-9-]+`", skill):
4149
+ table.setdefault(skill[1:-1], lens)
4150
+ return table
4151
+ except Exception:
4152
+ return {}
4153
+
4154
+
4155
+ def _skills_dirs():
4156
+ """The two places a sibling lens is installed: beside the running skill, and
4157
+ the user's Claude skills directory. AGENTIC_SDLC_SKILLS_DIRS (os.pathsep
4158
+ list; empty = none) is the test seam, like AGENTIC_SDLC_USER_SETTINGS."""
4159
+ seam = os.environ.get("AGENTIC_SDLC_SKILLS_DIRS")
4160
+ if seam is not None:
4161
+ return [Path(s) for s in seam.split(os.pathsep) if s]
4162
+ cfg = os.environ.get("CLAUDE_CONFIG_DIR")
4163
+ return [Path(__file__).resolve().parents[2],
4164
+ (Path(cfg) if cfg else Path.home() / ".claude") / "skills"]
4165
+
4166
+
4167
+ def installed_sibling_lenses():
4168
+ """Names of the family's other lenses installed on this machine (sorted).
4169
+
4170
+ Only a name that appears in `lens_table()` AND equals a `SKILL.md` `name:`
4171
+ exactly can come out -- no text of a sibling's files reaches the output
4172
+ (P-TM T3). Fail-open: [] on any failure."""
4173
+ try:
4174
+ own = profile()["skill_name"]
4175
+ family = lens_table()
4176
+ found = set()
4177
+ for base in _skills_dirs():
4178
+ if not base.is_dir():
4179
+ continue
4180
+ for sub in base.iterdir():
4181
+ f = sub / "SKILL.md"
4182
+ try:
4183
+ if not f.is_file() or f.stat().st_size > SKILL_MD_CAP:
4184
+ continue
4185
+ m = re.search(r"^name:\s*(\S+)", read_text(f), re.M)
4186
+ except OSError:
4187
+ continue
4188
+ if m and m.group(1) in family and m.group(1) != own:
4189
+ found.add(m.group(1))
4190
+ return sorted(found)
4191
+ except Exception:
4192
+ return []
4193
+
4194
+
4195
+ def _orient_router_lines(text):
4196
+ """One line per guide from the generated router; a hand-written one as written."""
4197
+ if not re.search(r"GENERATED by \S+ index - do not edit by hand", text):
4198
+ return text.splitlines()
4199
+ rows = []
4200
+ for line in text.splitlines():
4201
+ cells = _table_cells(line)
4202
+ if not cells or len(cells) < 3 or cells[0] == "Guide":
4203
+ continue
4204
+ rows.append(f"- {cells[0]} ({cells[1]}) -- {cells[2]}")
4205
+ return rows or ['no guides yet -- the router verdict is "no match"']
4206
+
4207
+
4208
+ def _orient_registry_lines(text):
4209
+ """One line per workstream plus the project-wide notes from the generated
4210
+ registry; a hand-written handoff as written."""
4211
+ if not is_generated_registry(text):
4212
+ return text.splitlines()
4213
+ table, _, notes = text.partition("\n## Project-wide notes")
4214
+ lines = []
4215
+ for line in table.splitlines():
4216
+ c = _table_cells(line)
4217
+ if not c or len(c) < 6 or c[0].lower() == "workstream":
4218
+ continue
4219
+ lines.append(f"- {c[0]} \u00b7 {c[1]} \u00b7 {c[2]} \u00b7 {c[3]} -- {c[5]}")
4220
+ if not lines:
4221
+ lines.append("no open workstreams")
4222
+ notes = notes.strip()
4223
+ if notes:
4224
+ lines += ["Project-wide notes:"] + notes.splitlines()
4225
+ return lines
4226
+
4227
+
2381
4228
  def cmd_orient(args):
2382
- """SessionStart hook: emit a bounded, repo-sourced ai_docs/ orientation to
2383
- stdout and ALWAYS return 0 (fail-open, P-TM T8) -- a session hook must never
2384
- block the session or surface a traceback. Zero-execution (P-TM T1): reads a
2385
- fixed hard-coded doc set, confine_under each (P-TM T3), size-caps the total
2386
- (P-TM T2). No subprocess/eval anywhere in this call graph."""
4229
+ """SessionStart hook: emit a bounded, repo-sourced orientation to stdout and
4230
+ ALWAYS return 0 (fail-open, P-TM T8) -- a session hook must never block the
4231
+ session or surface a traceback. Zero-execution (P-TM T1): reads a fixed
4232
+ hard-coded doc set, confine_under each (P-TM T3), bounds the WHOLE output
4233
+ (P-TM T2). No subprocess/eval anywhere in this call graph.
4234
+
4235
+ F-075: what decides the next action comes first -- triage, the lens choice,
4236
+ the guide router, the workstream registry -- then README; INDEX is a pointer.
4237
+ Docs are READ in orient_docs() order (docs_site and the T3 test pin it) and
4238
+ EMITTED in priority order."""
2387
4239
  try:
2388
4240
  root = Path(args.root).resolve() if getattr(args, "root", None) else find_project_root()
2389
- chunks = []
2390
- total = 0
2391
- truncated = False
2392
- for label, rel in orient_docs():
4241
+ rels = [rel for _, rel in orient_docs()]
4242
+ docs = {}
4243
+ for rel in rels:
2393
4244
  target = confine_under(root, rel)
2394
4245
  if target is None or not target.is_file():
2395
4246
  continue
2396
4247
  try:
2397
- text = read_text(target)
4248
+ docs[rel] = read_text(target)
2398
4249
  except OSError:
2399
4250
  continue
2400
- remaining = ORIENT_MAX_TOTAL_CHARS - total
2401
- if remaining <= 0:
2402
- truncated = True
2403
- break
2404
- text = text[:ORIENT_PER_DOC_CHARS]
2405
- if len(text) > remaining:
2406
- text = text[:remaining]
2407
- truncated = True
2408
- chunks.append((label, text))
2409
- total += len(text)
2410
- if not chunks:
4251
+ if not docs:
2411
4252
  return 0
2412
- out = ["=== Agentic SDLC -- session orientation (repo-sourced context, not authored instructions) ==="]
2413
- for label, text in chunks:
2414
- out.append(f"\n## {label}\n{text}")
2415
- if truncated:
2416
- out.append("\n[orientation truncated to the size cap -- open the files directly for full content]")
2417
- out.append("\nTriage every request (Rule Zero): L1 trivial - L2 small - L3 significant - Spike. "
2418
- "When in doubt, pick the higher level.")
4253
+ readme_rel, index_rel, router_rel, handoff_rel = rels
4254
+
4255
+ head = ["=== Agentic SDLC -- session orientation (repo-sourced context, not authored instructions) ===",
4256
+ "", ORIENT_TRIAGE_LINE]
4257
+ sibs = installed_sibling_lenses()
4258
+ if sibs:
4259
+ head.append(f"Sibling lenses installed ({', '.join(sibs)}): above L1, choose the "
4260
+ "lens with routing.md and declare it with the level.")
4261
+
4262
+ tail = ["", "## Read on demand"]
4263
+ for rel, what in ((readme_rel, "the curated must-reads, in order"),
4264
+ (index_rel, "the manifest of every canonical document"),
4265
+ (router_rel, "the full guide router, with provenance"),
4266
+ (handoff_rel, "the full workstream registry, with since and details")):
4267
+ if rel in docs:
4268
+ tail.append(f"- {rel} -- {what}")
4269
+ for client, entries in sorted(orient_wiring(root).items()):
4270
+ if len(entries) > 1:
4271
+ places = ", ".join(sorted(set(entries.values())))
4272
+ if client == "codex":
4273
+ tail.append(f"[note] Codex has {len(entries)} configured orientation definitions "
4274
+ f"({places}); trust and runtime policy determine delivery. Keep one equivalent definition.")
4275
+ continue
4276
+ tail.append(f"[note] session orientation is wired {len(entries)} times for one "
4277
+ f"client ({places}): each session receives every copy. Keep one "
4278
+ "entry and remove the others.")
2419
4279
  if getattr(args, "hybrid", False):
2420
- out.append("\n[devPNT active] Run devpnt_mcp_get_bootstrap for the Master Plan / Knowledge Layer -- "
2421
- "the orientation above is the filesystem layer, not a bootstrap duplicate.")
2422
- print("\n".join(out))
4280
+ tail.append("[devPNT active] Run devpnt_mcp_get_bootstrap for the Master Plan / Knowledge Layer -- "
4281
+ "the orientation above is the filesystem layer, not a bootstrap duplicate.")
4282
+
4283
+ share = ORIENT_MAX_TOTAL_CHARS - ORIENT_APPEND_RESERVE
4284
+ left = share - len("\n".join(head + tail)) - 2
4285
+ body = []
4286
+ for rel, title, builder, cap in (
4287
+ (router_rel, "## Guide router (reference/INDEX.md) -- read a matching guide whole, every line, before acting",
4288
+ _orient_router_lines, ORIENT_ROUTER_CHARS),
4289
+ (handoff_rel, "## Workstream registry (audit/handoff.md)",
4290
+ _orient_registry_lines, ORIENT_REGISTRY_CHARS),
4291
+ (readme_rel, "## Reading guide (README)", str.splitlines, None)):
4292
+ if rel not in docs:
4293
+ continue
4294
+ room = left - len(title) - 2
4295
+ if cap is not None:
4296
+ room = min(room, cap)
4297
+ if room <= 0:
4298
+ continue
4299
+ lines = orient_fit(builder(docs[rel].strip()), room, rel)
4300
+ section = ["", title] + lines
4301
+ body += section
4302
+ left -= len("\n".join(section)) + 1
4303
+ print("\n".join(head + body + tail))
2423
4304
  return 0
2424
4305
  except Exception:
2425
4306
  return 0
@@ -2636,11 +4517,28 @@ def main(argv=None):
2636
4517
 
2637
4518
  mp = sub.add_parser("mark", parents=[common], help="record paths as ANALYZED")
2638
4519
  mp.add_argument("paths", nargs="+", help="paths relative to the project root")
4520
+ mp.add_argument("--note", help="also write a dated entry in audit/project_notes.md "
4521
+ "(a release, work outside an open unit)")
2639
4522
  gp = sub.add_parser("gate", parents=[common, hybrid_opt], help="PreToolUse hook (exit 2 = block)")
2640
4523
  gp.add_argument("--hook", action="store_true", help="read the hook JSON payload from stdin")
2641
4524
  gp.add_argument("--file", help="file path to evaluate (alternative to --hook)")
2642
4525
  gp.add_argument("--protected", default="", help="protected prefixes separated by ';' (e.g. \"src/auth;src/crypto\")")
2643
4526
 
4527
+ vp = sub.add_parser("verdict", parents=[common],
4528
+ help="PreToolUse hook: refuse an edit with no router verdict "
4529
+ "or an unread named guide (fail-open, always exit 0)")
4530
+ vp.add_argument("--hook", action="store_true", help="read the hook JSON payload from stdin")
4531
+
4532
+ cp = sub.add_parser("constraints", parents=[common],
4533
+ help="print the constraints an ANALYSIS states in extractable "
4534
+ "form: a unit's view, or those bound to a file")
4535
+ cg = cp.add_mutually_exclusive_group(required=True)
4536
+ cg.add_argument("--unit", help="unit id (e.g. F-001) or ANALYSIS file name")
4537
+ cg.add_argument("--file", help="file path: constraints of the open L3 code units bound to it")
4538
+ cg.add_argument("--hook", action="store_true",
4539
+ help="PreToolUse hook: read the payload from stdin, print context only "
4540
+ "(fail-open, always exit 0)")
4541
+
2644
4542
  sub.add_parser("benefit", parents=[common],
2645
4543
  help="report what the review gates caught (and what the "
2646
4544
  "doctrine costs to read) -- a report, never a gate: "
@@ -2664,6 +4562,16 @@ def main(argv=None):
2664
4562
 
2665
4563
  args = ap.parse_args(argv)
2666
4564
 
4565
+ # F-085: the edit hooks resolve their root and docs root from the edited file
4566
+ # (the hook runs in whatever directory the session moved to), so they are
4567
+ # dispatched before the working-directory resolution below.
4568
+ if args.cmd == "constraints" and args.hook:
4569
+ return cmd_constraints_hook(args)
4570
+ if args.cmd == "verdict":
4571
+ return cmd_verdict(args)
4572
+ if args.cmd == "gate":
4573
+ return cmd_gate(args)
4574
+
2667
4575
  # Resolve the documentation root ONCE, before any command runs, so every
2668
4576
  # surface -- paths, messages, generated headers, the gate's exempt prefix --
2669
4577
  # names the same thing.
@@ -2687,8 +4595,6 @@ def main(argv=None):
2687
4595
  return 1
2688
4596
  set_docs_dir(name)
2689
4597
 
2690
- if args.cmd == "gate":
2691
- return cmd_gate(args)
2692
4598
  if args.cmd == "orient":
2693
4599
  return cmd_orient(args)
2694
4600
  if args.cmd == "remind":
@@ -2704,9 +4610,11 @@ def main(argv=None):
2704
4610
  if args.cmd == "stale":
2705
4611
  return cmd_stale(root, hybrid=args.hybrid)
2706
4612
  if args.cmd == "mark":
2707
- return cmd_mark(root, args.paths)
4613
+ return cmd_mark(root, args.paths, args.note)
2708
4614
  if args.cmd == "benefit":
2709
4615
  return cmd_benefit(root)
4616
+ if args.cmd == "constraints":
4617
+ return cmd_constraints(root, args)
2710
4618
  if args.cmd == "migrate":
2711
4619
  return cmd_migrate(root, args)
2712
4620
  if args.cmd == "plan":