@antoneeo/kb-agentic-skill 1.0.0

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.
@@ -0,0 +1,1996 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """Mechanical validator for the Agentic SDLC family — the shared core.
4
+
5
+ This module is the SPINE: it is authored once here and shipped verbatim in every
6
+ distribution of the family (code, knowledge, marketing). It carries nothing that
7
+ belongs to a single domain. Each distribution ships a thin entry point beside it —
8
+ `sdlc_check.py` for code, `mkt_check.py` for marketing — which names the domain it
9
+ implements and delegates everything else here. A drift guard fails CI when the
10
+ copies diverge, so do not fork this file: fix it once and copy it.
11
+
12
+ It is also runnable on its own (`python sdlc_core.py check`) for the same reason
13
+ the entry points are thin: the behaviour is here, not in them.
14
+
15
+ Commands:
16
+ check single closure gate: validate + stale in one command (exit 1 if either fails)
17
+ validate verify the structural coherence of the docs root (default ai_docs/; exit 1 on
18
+ errors; --strict also fails on warnings or on a missing docs root, for CI)
19
+ index regenerate the generated indexes: strategic/features_history.md (from the
20
+ frontmatter of ANALYSIS_*.md files) and ai_docs/INDEX.md (manifest of canonical docs)
21
+ stale list areas modified after the last analysis recorded in audit_plan.md (exit 1 if any)
22
+ mark record paths as ANALYZED with the current reference (git hash, else UTC timestamp)
23
+ gate PreToolUse hook: block writes on protected paths without an IN_PROGRESS ANALYSIS (exit 2)
24
+
25
+ Hybrid/devPNT mode: pass --hybrid explicitly on check/stale (skips audit-plan
26
+ staleness, delegated to devPNT/KL) and on gate (also unlocks when an approved
27
+ E-TDD shadow, solutions/SHADOW_*tdd*.md, exists).
28
+
29
+ Canonical language is English. Legacy Italian frontmatter keys (stato, livello,
30
+ data_inizio, data_fine) and section headings are still accepted for existing projects,
31
+ but are deprecated: new documents should use the English forms.
32
+
33
+ Standard library only (Python >= 3.8). Windows and POSIX compatible.
34
+ """
35
+ import argparse
36
+ import hashlib
37
+ import json
38
+ import os
39
+ import re
40
+ import subprocess
41
+ import sys
42
+ from datetime import datetime, timedelta, timezone
43
+ from pathlib import Path
44
+
45
+ VALID_STATES = {"PLANNED", "IN_PROGRESS", "COMPLETED", "CANCELLED"}
46
+ VALID_LEVELS = {"L1", "L2", "L3", "SPIKE"}
47
+ VISION_FILES = ("project_vision.md", "roadmap.md", "principles.md")
48
+ SKIP_DIRS = {".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv",
49
+ "dist", "build", ".idea", ".vs"} # the docs root is excluded separately: its
50
+ # name is resolved per invocation, so it cannot live in a frozen set (see docs_dir()).
51
+ INDEX_HEADER = ("<!-- GENERATED by sdlc_check.py index - do not edit by hand. "
52
+ "Source of truth: frontmatter of the ANALYSIS_*.md files -->")
53
+ def manifest_header():
54
+ return ("<!-- GENERATED by sdlc_check.py index - do not edit by hand. "
55
+ f"Source of truth: the headers of the canonical documents in {docs_dir()}/. -->")
56
+ # Directories whose .md files are durable canonical documents: manifested in INDEX.md.
57
+ # audit/ and solutions/ stay discovery-by-grep (session / process artifacts), not manifested.
58
+ MANIFEST_DIRS = ("vision", "reference", "architecture", "functional", "strategic")
59
+ # Recognized states: canonical docs (CURRENT/SUPERSEDED/...), vision (DRAFT/APPROVED),
60
+ # ADR (Accepted/Proposed/Rejected). Union, to avoid false warnings on conventions in use.
61
+ CANONICAL_STATES = {"CURRENT", "SUPERSEDED", "DRAFT", "DEPRECATED",
62
+ "APPROVED", "ACCEPTED", "PROPOSED", "REJECTED"}
63
+ GENERATED_DOCS = {"features_history.md", "INDEX.md"} # generated: never manifest entries
64
+ MTIME_GRACE = timedelta(seconds=2)
65
+ def guide_index_header():
66
+ return ("<!-- GENERATED by sdlc_check.py index - do not edit by hand. "
67
+ f"Source of truth: the headers of the GUIDE_*.md files in {docs_dir()}/reference/. -->")
68
+ GUIDE_PROVENANCE_KEYS = ("source", "distilled_from", "source_hash") # source_version optional
69
+ # a guide section is "covered" when it carries a source marker or an explicit gap marker
70
+ GUIDE_MARKER_RE = re.compile(r"\[(?:source:[^\]]+|not covered by source)\]")
71
+ # Agent-global KB (Feature B unit 2): ONE client-agnostic root under home.
72
+ # AGENTIC_SDLC_KB_ROOT env var is a TEST/CI seam only (scenario battery must
73
+ # not touch the real user KB); the documented product path is fixed.
74
+ DEFAULT_KB_ROOT = Path(os.environ.get("AGENTIC_SDLC_KB_ROOT", "")) if os.environ.get("AGENTIC_SDLC_KB_ROOT") else Path.home() / ".agentic-sdlc"
75
+ # Subagent Execution (Feature A): a PLAN_[feature].md task must carry these keys,
76
+ # plus at least one of paths/produces (checked separately in cmd_plan).
77
+ PLAN_TASK_REQUIRED = ("id", "title", "verify")
78
+
79
+ # Deprecated Italian frontmatter keys, mapped to the canonical English ones.
80
+ LEGACY_KEYS = {"stato": "status", "livello": "level",
81
+ "data_inizio": "start_date", "data_fine": "end_date"}
82
+
83
+ # Architect pass (F-020): the Capability Ledger is due for ACTIVE L3 analyses
84
+ # born on/after the day the pass shipped. Grandfathering by start_date -- an
85
+ # in-flight analysis from before the pass existed never nags (same lazy-convert
86
+ # doctrine as the pre-1.17 narrative handoff).
87
+ ARCHITECT_PASS_EPOCH = "2026-07-28"
88
+ # Design-review gate (F-021): an L3 started on/after this date owes a REVIEW_LOG
89
+ # row. Same grandfathering discipline as the pass above -- never nag work that
90
+ # predates the rule.
91
+ DESIGN_REVIEW_EPOCH = "2026-07-28"
92
+ def review_log_rel():
93
+ return f"{docs_dir()}/audit/reviews/REVIEW_LOG.md"
94
+ # Component Map 'Where' refs: a dotted token counts as a path only with one of
95
+ # these suffixes. Deliberately a closed list -- a generic ".\w{1,5}$" turns
96
+ # `app.core`, `OrderStore.save` and `1.18.0` into "the map is rotting".
97
+ FILE_SUFFIXES = ("md", "py", "js", "mjs", "cjs", "ts", "tsx", "jsx", "json", "yaml",
98
+ "yml", "toml", "ini", "cfg", "sh", "bat", "ps1", "go", "rs", "java",
99
+ "kt", "rb", "php", "cs", "swift", "c", "h", "cpp", "hpp", "sql",
100
+ "css", "scss", "html", "vue", "svelte", "tf", "proto", "txt")
101
+
102
+ # ANALYSIS sections: (canonical English heading, legacy Italian heading).
103
+ SECURITY_SECTION = ("## Security", "## Sicurezza")
104
+ ANALYSIS_SECTIONS = (
105
+ ("## Objective", "## Obiettivo"),
106
+ ("## Feature Vision", "## Vision della Feature"),
107
+ ("## Impact", "## Impatto"),
108
+ ("## Action Plan", "## Piano d'Azione"),
109
+ ("## Test Strategy", "## Strategia di Test"),
110
+ ("## Diary", "## Diario"),
111
+ )
112
+
113
+ # ------------------------------------------------------------------- docs root
114
+ # `ai_docs/` is the ONE surviving documentation root and the default everywhere.
115
+ # The name is a parameter for exactly two reasons, both temporary by nature: a
116
+ # project that predates the convention has to be READ before it can be migrated,
117
+ # and the migration tool has to see both sides. It is not an invitation to keep a
118
+ # second permanent root -- which is why `init.js` has no rename knob.
119
+ DEFAULT_DOCS_DIR = "ai_docs"
120
+ DOCS_DIR_CANDIDATES = ("ai_docs", "mkt_docs")
121
+ DOCS_DIR_ENV = "AGENTIC_SDLC_DOCS_DIR" # test/CI seam, read per invocation
122
+ _DOCS_DIR = {"name": DEFAULT_DOCS_DIR}
123
+
124
+
125
+ def docs_dir():
126
+ """The resolved documentation root NAME for this invocation."""
127
+ return _DOCS_DIR["name"]
128
+
129
+
130
+ def set_docs_dir(name):
131
+ _DOCS_DIR["name"] = name or DEFAULT_DOCS_DIR
132
+
133
+
134
+ def ai_path(root, *parts):
135
+ """A path inside the resolved documentation root."""
136
+ return Path(root).joinpath(docs_dir(), *parts)
137
+
138
+
139
+ def resolve_docs_dir(args=None, start=None):
140
+ """Explicit beats guessed, exactly like --hybrid.
141
+
142
+ Order: --docs-dir, then the env seam (read now, not at import, or it could not
143
+ be varied by a test), then discovery, then the default. Returns (root, name);
144
+ the root is None when discovery did not run.
145
+ """
146
+ explicit = getattr(args, "docs_dir", None) or os.environ.get(DOCS_DIR_ENV)
147
+ if explicit:
148
+ return None, explicit
149
+ return discover_docs_root(start)
150
+
151
+
152
+ def discover_docs_root(start=None):
153
+ """Walk up looking for a candidate root. PER LEVEL: the nearest one wins.
154
+
155
+ Two candidates at the SAME level is the shape of a half-migrated project.
156
+ Returning either would validate half of it and print a verdict, so it refuses
157
+ -- naming both -- and the caller exits without a verdict.
158
+ """
159
+ cur = Path(start or os.getcwd()).resolve()
160
+ for p in [cur] + list(cur.parents):
161
+ found = [c for c in DOCS_DIR_CANDIDATES if (p / c).is_dir()]
162
+ if len(found) > 1:
163
+ raise AmbiguousDocsRoot(p, found)
164
+ if found:
165
+ return p, found[0]
166
+ return None, DEFAULT_DOCS_DIR
167
+
168
+
169
+ class AmbiguousDocsRoot(Exception):
170
+ """Two documentation roots side by side: a verdict here would be a guess."""
171
+
172
+ def __init__(self, where, found):
173
+ self.where = where
174
+ self.found = found
175
+ super().__init__(
176
+ f"{where} contains more than one documentation root ({', '.join(found)}): "
177
+ "refusing to guess which one this project uses. Pass --docs-dir <name> "
178
+ "to say which, or finish the migration so only one remains.")
179
+
180
+
181
+ # --------------------------------------------------------------------- domains
182
+ # One entry per lens of the family. The DATA lives here, in the shared core, so a
183
+ # mixed tree is validated identically from every installed distribution: an entry
184
+ # point never picks rules, it only declares which portable checks it can run.
185
+ #
186
+ # The exclusive part of a rule set -- template, mandatory sections, the risk slot
187
+ # -- has exactly one owner per document. It is the part that never composes:
188
+ # unioning it would demand every domain's ceremony of every document, intersecting
189
+ # it would demand nothing. The risk slot is translated per domain, never dropped.
190
+ DOMAINS = {
191
+ "code": {
192
+ "risk_section": SECURITY_SECTION,
193
+ "risk_label": "## Security and Threat Model",
194
+ "id_prefix": "F-",
195
+ },
196
+ "knowledge": {
197
+ "risk_section": ("## Sources and Verification",),
198
+ "risk_label": "## Sources and Verification",
199
+ "id_prefix": "K-",
200
+ },
201
+ "marketing": {
202
+ "risk_section": ("## Threat Map / Plan Risks", "## Threat Map"),
203
+ "risk_label": "## Threat Map / Plan Risks",
204
+ "id_prefix": "M-",
205
+ },
206
+ }
207
+ # Absent everything -- no `default_domain:` line, no `domain:` field -- a project is
208
+ # `code`. That is what every project created before this field existed already is,
209
+ # so the default is chosen to leave them untouched, not because code is special.
210
+ DEFAULT_DOMAIN = "code"
211
+
212
+ # Portable checks: composable, opt-in per document via `checks:`. An imported check
213
+ # may only ADD findings, never relax what the owning domain requires -- monotonic, so
214
+ # importing one is safe by construction. Registered by name `<domain>.<check>`.
215
+ PORTABLE_CHECKS = {}
216
+ # Which check namespaces this distribution actually carries. Set by the entry point;
217
+ # a `checks:` entry outside it WARNS visibly rather than passing silently.
218
+ _ENTRY_POINT = {"domain": DEFAULT_DOMAIN, "provides": ()}
219
+
220
+
221
+ # --- distribution profile ----------------------------------------------------
222
+ # Each distribution declares what it carries. The battery reads this instead of
223
+ # assuming the code overlay, which is what lets one shared battery run in three
224
+ # distributions without either failing on files a domain legitimately does not have
225
+ # or quietly excusing a domain from doctrine it owes.
226
+ #
227
+ # REQUIRED_CAPABILITIES is the spine: process discipline that is domain-neutral, so
228
+ # no distribution may drop it. A profile missing one fails a shared test -- editing
229
+ # your own profile is therefore NOT a way out of the doctrine, only a way to declare
230
+ # an overlay you genuinely do not have.
231
+ REQUIRED_CAPABILITIES = frozenset({
232
+ "triage", # Rule Zero, with the router verdict as a declared output
233
+ "write_triggers", # one event, one destination
234
+ "workstream_registry", # audit/handoff.md as a parallel-safe registry
235
+ "vision_gate", # DRAFT informs, APPROVED binds, blind check before promotion
236
+ "design_review_gate", # a design reviewed by somebody other than its author
237
+ "guide_router", # the mandatory pre-work lookup
238
+ "worktree_hygiene", # isolate the work
239
+ })
240
+ # Optional overlays: real capabilities that a domain may legitimately not have.
241
+ # Listed here so "this distribution does not claim it" is a visible decision.
242
+ OPTIONAL_CAPABILITIES = frozenset({
243
+ "architect_pass", # does the component already exist? (code overlay)
244
+ "taxonomy_pass", # do the categories/topics already exist? (knowledge overlay)
245
+ "comprehension_guides", # source_kind: code maps of complex components
246
+ "tdd", # test-first discipline
247
+ "subagent_dispatch", # opt-in PLAN_[feature].md execution
248
+ "legacy_narrative_handoff", # published before the registry format: owes a migration clause
249
+ "question_discipline", # when a question to the user is legal (elicitation.md);
250
+ # spine candidate once every sibling's elicitation carries it
251
+ })
252
+ # `unit_noun` is vocabulary, not structure: the code domain works on a "feature",
253
+ # the knowledge domain on a "topic". The shared battery asserts the SHAPE
254
+ # (HANDOFF_[<unit>].md) and reads the word from here, so a domain keeps its own
255
+ # language without either weakening the assertion or forking the test.
256
+ # `design_gate_between` is the pair of SKILL.md headings the design review must sit
257
+ # between: after the design exists, before the work is executed. The headings are each
258
+ # domain's own wording -- the code overlay runs five phases, the marketing overlay nine
259
+ # -- so the battery asserts the ORDER, never a shared phase name.
260
+ _PROFILE = {
261
+ "skill_name": "agentic-sdlc",
262
+ "unit_noun": "feature",
263
+ "support_files": (),
264
+ "capabilities": frozenset(),
265
+ "design_gate_between": (),
266
+ }
267
+
268
+
269
+ def set_profile(skill_name, support_files=(), capabilities=(), unit_noun="feature",
270
+ design_gate_between=()):
271
+ _PROFILE.update(skill_name=skill_name,
272
+ unit_noun=unit_noun,
273
+ support_files=tuple(support_files),
274
+ capabilities=frozenset(capabilities),
275
+ design_gate_between=tuple(design_gate_between))
276
+
277
+
278
+ def profile():
279
+ return dict(_PROFILE)
280
+
281
+
282
+ def has_capability(name):
283
+ return name in _PROFILE["capabilities"]
284
+
285
+
286
+ def portable_check(name):
287
+ """Register a portable check. The callable takes (rel, meta, text) and returns
288
+ a list of (severity, message) with severity in {'error', 'warning', 'advisory'}."""
289
+ def register(fn):
290
+ PORTABLE_CHECKS[name] = fn
291
+ return fn
292
+ return register
293
+
294
+
295
+ def set_entry_point(domain, provides=()):
296
+ """Declare which domain this distribution is and which check namespaces it ships."""
297
+ _ENTRY_POINT["domain"] = domain
298
+ _ENTRY_POINT["provides"] = tuple(provides)
299
+
300
+
301
+ def project_default_domain(root):
302
+ """The project's answer for every artifact that declares no `domain:`.
303
+
304
+ Read once from `ai_docs/README.md`'s frontmatter. Project-level ON PURPOSE: a
305
+ per-distribution default would give the same tree two different verdicts
306
+ depending on which lens the agent happened to load."""
307
+ readme = ai_path(root, "README.md")
308
+ if not readme.is_file():
309
+ return DEFAULT_DOMAIN
310
+ meta = load_frontmatter(read_text(readme).splitlines())
311
+ declared = (meta.get("default_domain") or "").strip().strip("'\"").lower()
312
+ return declared if declared in DOMAINS else DEFAULT_DOMAIN
313
+
314
+
315
+ def resolve_domain(meta, default):
316
+ """(domain, declared_but_unknown) for one artifact. The field RECORDS the answer;
317
+ it never invents one, and an unrecognized value is reported, not obeyed."""
318
+ declared = (meta.get("domain") or "").strip().strip("'\"").lower()
319
+ if not declared:
320
+ return default, None
321
+ if declared not in DOMAINS:
322
+ return default, declared
323
+ return declared, None
324
+
325
+
326
+ def declared_checks(meta):
327
+ """The `checks:` list, accepted as `[a, b]` or as a comma-separated string."""
328
+ raw = (meta.get("checks") or "").strip()
329
+ if not raw:
330
+ return []
331
+ return [c.strip().strip("'\"") for c in raw.strip("[]").split(",") if c.strip()]
332
+
333
+
334
+ def run_portable_checks(rel, meta, text, errors, warnings, advisories):
335
+ """Run the checks a document imported. Findings are ADDED to the owning domain's;
336
+ an unavailable check is a visible warning -- never a silent pass."""
337
+ for name in declared_checks(meta):
338
+ namespace = name.split(".", 1)[0]
339
+ if name not in PORTABLE_CHECKS:
340
+ if namespace in _ENTRY_POINT["provides"]:
341
+ warnings.append(f"{rel}: check '{name}' is unknown (no such portable check)")
342
+ else:
343
+ warnings.append(
344
+ f"{rel}: check '{name}' is not available in this distribution "
345
+ f"(it ships {', '.join(_ENTRY_POINT['provides']) or 'no checks'}): "
346
+ "the document was NOT checked against it")
347
+ continue
348
+ for severity, message in PORTABLE_CHECKS[name](rel, meta, text) or []:
349
+ {"error": errors, "warning": warnings}.get(severity, advisories).append(
350
+ f"{rel}: [{name}] {message}")
351
+
352
+
353
+ try:
354
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
355
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
356
+ except Exception:
357
+ pass
358
+
359
+
360
+ # --- orient (SessionStart hook) ---
361
+ # Fixed, hard-coded doc set (label, path-relative-to-root). No content- or
362
+ # user-derived paths -> no traversal input (P-TM T3); confine_under is
363
+ # defense-in-depth. Emitted at session start by the orient subcommand.
364
+ def orient_docs():
365
+ d = docs_dir()
366
+ return [
367
+ ("Reading guide (README)", f"{d}/README.md"),
368
+ ("Canonical manifest (INDEX)", f"{d}/INDEX.md"),
369
+ ("Guide router (when-to-consult)", f"{d}/reference/INDEX.md"),
370
+ ("Last session handoff", f"{d}/audit/handoff.md"),
371
+ ]
372
+ ORIENT_PER_DOC_CHARS = 6000 # per-doc truncation
373
+ ORIENT_MAX_TOTAL_CHARS = 16000 # total ingestion cap (P-TM T2); tunable
374
+
375
+
376
+ # ----------------------------------------------------------------- utilities
377
+
378
+ def utc_now_iso():
379
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
380
+
381
+
382
+ def find_project_root(start=None):
383
+ cur = Path(start or os.getcwd()).resolve()
384
+ for p in [cur] + list(cur.parents):
385
+ if (p / docs_dir()).is_dir():
386
+ return p
387
+ return cur
388
+
389
+
390
+ def require_ai_docs(root, command):
391
+ """Fail fast when the docs root is missing: prevents silently creating a second
392
+ documentation root in the wrong working directory."""
393
+ if not ai_path(root).is_dir():
394
+ print(f"[ERROR] {ai_path(root)} not found: refusing to run '{command}' here. "
395
+ "Run agentic-sdlc-init first, or pass --root <project_root>.")
396
+ return False
397
+ return True
398
+
399
+
400
+ def confine_under(base, rel):
401
+ """Fail-closed path confinement: resolve `rel` under `base` and require the
402
+ result to stay inside `base`. Returns None (reject) if `rel` is absolute,
403
+ contains a '..' part, or resolves outside `base` (including an OSError
404
+ during resolution, e.g. an unresolvable/reparse-point path on Windows).
405
+ Single source for path confinement (T2/T3): reused by check_kb_collisions'
406
+ `overrides:` check and cmd_validate's `distilled_from` check, and by the
407
+ new `plan` command's paths/consumes/produces/guides confinement."""
408
+ p = Path(rel)
409
+ if p.is_absolute() or ".." in p.parts:
410
+ return None
411
+ try:
412
+ t = (base / rel).resolve()
413
+ t.relative_to(base.resolve())
414
+ return t
415
+ except (ValueError, OSError):
416
+ return None
417
+
418
+
419
+ def read_text(path):
420
+ # utf-8-sig: strips a leading BOM (files authored on Windows) so the
421
+ # frontmatter '---' on line 0 stays recognizable; reads plain utf-8 otherwise.
422
+ return path.read_text(encoding="utf-8-sig", errors="replace")
423
+
424
+
425
+ def sha256_file(path):
426
+ # CRLF->LF before hashing: a Windows checkout with core.autocrlf=true
427
+ # rewrites snapshot files, and a raw-byte hash would flag every guide
428
+ # [stale] on a fresh clone. Recorded hashes are LF-based, so normalizing
429
+ # maps CRLF copies back to the same digest.
430
+ h = hashlib.sha256()
431
+ h.update(path.read_bytes().replace(b"\r\n", b"\n"))
432
+ return h.hexdigest()
433
+
434
+
435
+ def parse_iso(value):
436
+ if not value:
437
+ return None
438
+ try:
439
+ dt = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
440
+ if dt.tzinfo is None:
441
+ dt = dt.replace(tzinfo=timezone.utc)
442
+ return dt
443
+ except ValueError:
444
+ return None
445
+
446
+
447
+ def norm_text(s):
448
+ return "\n".join(line.rstrip() for line in s.strip().splitlines())
449
+
450
+
451
+ def load_frontmatter(lines):
452
+ meta = {}
453
+ if not lines or lines[0].strip() != "---":
454
+ return meta
455
+ for line in lines[1:60]:
456
+ if line.strip() == "---":
457
+ break
458
+ m = re.match(r"^([A-Za-z_][\w-]*):\s*(.*)$", line)
459
+ if m:
460
+ meta[m.group(1).strip().lower()] = m.group(2).strip()
461
+ # Legacy Italian keys: accepted, normalized to canonical English (deprecated).
462
+ for legacy, canon in LEGACY_KEYS.items():
463
+ if legacy in meta and canon not in meta:
464
+ meta[canon] = meta[legacy]
465
+ return meta
466
+
467
+
468
+ def is_shadow(path, first_line):
469
+ """A shadow mirror of a devPNT-governed document, not an authoritative ANALYSIS.
470
+ Recognized by filename (SHADOW_*) or by the marker comment on the FIRST line
471
+ (legacy shadows saved under an ANALYSIS_* name)."""
472
+ return path.name.startswith("SHADOW") or first_line.lstrip().startswith("<!-- SHADOW")
473
+
474
+
475
+ def list_analyses(root):
476
+ """Returns [(path, frontmatter, text)] for the ANALYSIS_*.md files (shadows excluded)."""
477
+ sol = ai_path(root, "solutions")
478
+ out = []
479
+ if not sol.is_dir():
480
+ return out
481
+ for p in sorted(sol.glob("ANALYSIS_*.md")):
482
+ text = read_text(p)
483
+ first_line = text.splitlines()[0] if text else ""
484
+ if is_shadow(p, first_line):
485
+ continue
486
+ out.append((p, load_frontmatter(text.splitlines()), text))
487
+ return out
488
+
489
+
490
+ def has_etdd_shadow(root):
491
+ """True if an E-TDD shadow exported from devPNT exists in solutions/.
492
+ In Hybrid mode the approved E-TDD (exported BEFORE implementation) is the
493
+ design authorization that replaces the IN_PROGRESS ANALYSIS."""
494
+ sol = ai_path(root, "solutions")
495
+ if not sol.is_dir():
496
+ return False
497
+ return any("tdd" in p.name.lower() for p in sol.glob("SHADOW_*.md"))
498
+
499
+
500
+ def iter_files(target):
501
+ if target.is_file():
502
+ yield target
503
+ return
504
+ for dirpath, dirnames, filenames in os.walk(target):
505
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS and d != docs_dir() and not d.startswith(".")]
506
+ for name in filenames:
507
+ yield Path(dirpath) / name
508
+
509
+
510
+ # ---------------------------------------------------------------------- git
511
+
512
+ def git_available(root):
513
+ try:
514
+ r = subprocess.run(["git", "rev-parse", "--is-inside-work-tree"],
515
+ cwd=str(root), capture_output=True, text=True, timeout=10)
516
+ return r.returncode == 0 and r.stdout.strip() == "true"
517
+ except Exception:
518
+ return False
519
+
520
+
521
+ def git_head(root):
522
+ try:
523
+ r = subprocess.run(["git", "rev-parse", "--short=12", "HEAD"],
524
+ cwd=str(root), capture_output=True, text=True, timeout=10)
525
+ return r.stdout.strip() if r.returncode == 0 else ""
526
+ except Exception:
527
+ return ""
528
+
529
+
530
+ def git_has_changes(root, rel_path):
531
+ """True if there are tracked/untracked changes under rel_path."""
532
+ try:
533
+ rel = rel_path.replace("\\", "/")
534
+ r = subprocess.run(["git", "status", "--porcelain", "--", rel],
535
+ cwd=str(root), capture_output=True, text=True, timeout=30)
536
+ return r.returncode == 0 and bool(r.stdout.strip())
537
+ except Exception:
538
+ return False
539
+
540
+
541
+ def git_changed_since(root, ref, rel_path):
542
+ """Files changed (tracked + untracked) under rel_path since ref. None if ref unresolvable."""
543
+ try:
544
+ r = subprocess.run(["git", "diff", "--name-only", ref, "--", rel_path],
545
+ cwd=str(root), capture_output=True, text=True, timeout=30)
546
+ if r.returncode != 0:
547
+ return None
548
+ changed = [l.strip() for l in r.stdout.splitlines() if l.strip()]
549
+ r2 = subprocess.run(["git", "ls-files", "--others", "--exclude-standard", "--", rel_path],
550
+ cwd=str(root), capture_output=True, text=True, timeout=30)
551
+ if r2.returncode == 0:
552
+ changed += [l.strip() for l in r2.stdout.splitlines() if l.strip()]
553
+ return sorted(set(changed))
554
+ except Exception:
555
+ return None
556
+
557
+
558
+ # -------------------------------------------------------------------- index
559
+
560
+ def build_index(root):
561
+ analyses = list_analyses(root)
562
+ # SYNTACTIC predicate, on purpose: the column appears when some analysis WRITES
563
+ # a `domain:` field, not when one resolves to a domain (every analysis does).
564
+ # So the generated file is a function of the tree alone -- identical from every
565
+ # entry point, and byte-identical on every tree that predates the field.
566
+ tagged = any((meta.get("domain") or "").strip() for _, meta, _ in analyses)
567
+ default_domain = project_default_domain(root) if tagged else None
568
+ rows = []
569
+ for p, meta, _ in analyses:
570
+ row = [
571
+ meta.get("id", "?"),
572
+ meta.get("feature", p.stem.replace("ANALYSIS_", "")),
573
+ meta.get("level", ""),
574
+ meta.get("status", "?"),
575
+ meta.get("start_date", ""),
576
+ meta.get("end_date", ""),
577
+ "solutions/" + p.name,
578
+ ]
579
+ if tagged:
580
+ row.insert(2, resolve_domain(meta, default_domain)[0])
581
+ rows.append(tuple(row))
582
+ rows.sort(key=lambda r: r[0])
583
+ header = "| ID | Feature | Level | Status | Started | Finished | Doc |"
584
+ sep = "|---|---|---|---|---|---|---|"
585
+ if tagged:
586
+ header = "| ID | Feature | Domain | Level | Status | Started | Finished | Doc |"
587
+ sep = "|---|---|---|---|---|---|---|---|"
588
+ lines = [INDEX_HEADER,
589
+ "# Feature History (generated)",
590
+ "",
591
+ header,
592
+ sep]
593
+ for r in rows:
594
+ lines.append("| " + " | ".join(r) + " |")
595
+ return "\n".join(lines) + "\n"
596
+
597
+
598
+ # "Status:"/"Stato:" line in the body (with or without ** **), prefix before the description
599
+ _STATUS_LINE = re.compile(r"^\**\s*(?:status|stato)\s*\**\s*:\s*\**\s*([A-Za-z][\w-]*)", re.I)
600
+ # pure metadata lines to skip when picking the fallback description
601
+ _META_LINE = re.compile(r"^\**\s*(date|data|task ref|version|versione|owner|autore|branch|agente|agent|created|creato|updated|aggiornato)\b", re.I)
602
+
603
+
604
+ def extract_doc_meta(path):
605
+ """(title, description, status, supersedes) of a canonical doc.
606
+
607
+ Recognizes TWO header conventions: the YAML-lite frontmatter
608
+ (description/status/supersedes/title) and the in-body `**Status:** X`
609
+ line (used by ADRs and legacy docs). As a fallback it derives the title
610
+ from the first '# H1' and the description from the first prose line,
611
+ skipping metadata lines.
612
+ """
613
+ text = read_text(path)
614
+ lines = text.splitlines()
615
+ meta = load_frontmatter(lines)
616
+ body = lines
617
+ if lines and lines[0].strip() == "---":
618
+ for i in range(1, min(len(lines), 60)):
619
+ if lines[i].strip() == "---":
620
+ body = lines[i + 1:]
621
+ break
622
+
623
+ title = meta.get("title", "")
624
+ if not title:
625
+ for line in body:
626
+ m = re.match(r"^#\s+(.*)$", line)
627
+ if m:
628
+ title = m.group(1).strip()
629
+ break
630
+ title = title or path.stem
631
+
632
+ status = meta.get("status", "").upper()
633
+ if not status:
634
+ for line in body[:25]:
635
+ m = _STATUS_LINE.match(line.strip())
636
+ if m:
637
+ status = m.group(1).upper()
638
+ break
639
+
640
+ desc = meta.get("description", "")
641
+ if not desc:
642
+ in_comment = False
643
+ for line in body:
644
+ s = line.strip()
645
+ # track HTML-comment state across lines: skipping only the OPENING
646
+ # line made line 2 of a multi-line comment the manifest description
647
+ # (the shipped vision template opens with a 3-line comment, so the
648
+ # most-read row of the manifest read '... -->')
649
+ if in_comment:
650
+ if "-->" in s:
651
+ in_comment = False
652
+ s = s.split("-->", 1)[1].strip()
653
+ if not s:
654
+ continue
655
+ else:
656
+ continue
657
+ elif s.startswith("<!--"):
658
+ if "-->" not in s:
659
+ in_comment = True
660
+ continue
661
+ s = s.split("-->", 1)[1].strip()
662
+ if not s:
663
+ continue
664
+ # a table row or a bare bullet is not a description: the manifest is
665
+ # the first thing an agent reads to orient, and '| Milestone | ... |'
666
+ # in that column is a row carrying no information
667
+ if (not s or s.startswith("#") or s.startswith("|") or s.startswith("---")
668
+ or re.match(r"^[-*+]\s", s) or _META_LINE.match(s)):
669
+ continue
670
+ if s.startswith(">"):
671
+ s = s.lstrip(">").strip()
672
+ m = _STATUS_LINE.match(s)
673
+ if m:
674
+ # "Status: X — description": keep the part after the status; if empty, skip
675
+ rest = s[m.end():].strip(" *—–-:.")
676
+ if not rest:
677
+ continue
678
+ s = rest
679
+ if s:
680
+ desc = s
681
+ break
682
+ desc = re.sub(r"\s+", " ", desc).strip()
683
+ if len(desc) > 160:
684
+ desc = desc[:157].rstrip() + "..."
685
+ return title, desc, status, meta.get("supersedes", "").strip()
686
+
687
+
688
+ def list_canonical_docs(root):
689
+ """[(rel_to_ai_docs, path, (title, desc, status, supersedes))] for canonical docs."""
690
+ ai = ai_path(root)
691
+ out = []
692
+ for d in MANIFEST_DIRS:
693
+ base = ai / d
694
+ if not base.is_dir():
695
+ continue
696
+ for p in sorted(base.rglob("*.md")):
697
+ rel_parts = p.relative_to(base).parts
698
+ if any(part.startswith(".") for part in rel_parts[:-1]):
699
+ continue # dot-subdirs (e.g. reference/.sources/) are never canonical
700
+ if p.name in GENERATED_DOCS or p.name == "README.md":
701
+ continue
702
+ out.append((p.relative_to(ai).as_posix(), p, extract_doc_meta(p)))
703
+ return out
704
+
705
+
706
+ def build_manifest(root):
707
+ docs = list_canonical_docs(root)
708
+ lines = [manifest_header(),
709
+ f"# `{docs_dir()}/` document index (generated)",
710
+ "",
711
+ "Complete manifest of the canonical documents. For the reading priority",
712
+ "(must-reads) see the hand-curated `README.md`. The ANALYSIS history is in",
713
+ "`strategic/features_history.md`. `audit/` and `solutions/` are discovery-by-grep,",
714
+ "not manifested here."]
715
+ by_dir = {}
716
+ for rel, _, meta in docs:
717
+ by_dir.setdefault(rel.split("/", 1)[0], []).append((rel, meta))
718
+ for top in MANIFEST_DIRS:
719
+ rows = by_dir.get(top)
720
+ if not rows:
721
+ continue
722
+ lines += ["", f"## {top}/", "",
723
+ "| Document | Status | Description |", "|---|---|---|"]
724
+ for rel, (title, desc, status, _sup) in rows:
725
+ d = (desc or title).replace("|", "\\|")
726
+ lines.append(f"| `{rel}` | {status or '-'} | {d} |")
727
+ return "\n".join(lines).rstrip() + "\n"
728
+
729
+
730
+ def list_guides(root):
731
+ """[(rel_to_ai_docs, path, meta, text)] for ai_docs/reference/GUIDE_*.md."""
732
+ ref = ai_path(root, "reference")
733
+ out = []
734
+ if not ref.is_dir():
735
+ return out
736
+ for p in sorted(ref.glob("GUIDE_*.md")):
737
+ text = read_text(p)
738
+ out.append((p.relative_to(ai_path(root)).as_posix(), p,
739
+ load_frontmatter(text.splitlines()), text))
740
+ return out
741
+
742
+
743
+ def check_kb_collisions(root, project_guides, errors, warnings):
744
+ """Cross-root awareness (unit 2): project-wins precedence, declared via 'overrides:'."""
745
+ kb_root = DEFAULT_KB_ROOT
746
+ # The agent-global KB is client-agnostic and shared across lenses: it keeps its
747
+ # own fixed layout and NEVER follows a project's docs-root name (TS16).
748
+ kb_ref = (kb_root / "ai_docs" / "reference")
749
+ try:
750
+ if root.resolve() == kb_root.resolve():
751
+ return # validating the KB itself: no self-comparison
752
+ except OSError:
753
+ return
754
+ if not kb_ref.is_dir():
755
+ return # no KB on this machine: zero behavior change
756
+ kb_names = {p.name for _, p, _, _ in list_guides(kb_root)}
757
+ for rel, p, meta, _ in project_guides:
758
+ ov = (meta.get("overrides") or "").strip()
759
+ if ov:
760
+ # T6: untrusted cross-root pointer — distilled_from parity, fail closed
761
+ target = confine_under(kb_ref, ov)
762
+ if target is None:
763
+ errors.append(f"{rel}: overrides '{ov}' is absolute, contains '..', or escapes the KB "
764
+ "reference dir — rejected (fail closed)")
765
+ continue
766
+ if not target.is_file():
767
+ warnings.append(f"{rel}: overrides target '{ov}' not found in KB ({kb_ref})")
768
+ if p.name in kb_names and ov != p.name:
769
+ warnings.append(f"{rel}: undeclared collision with KB guide '{p.name}' (project wins) — declare overrides: {p.name}")
770
+
771
+
772
+ def build_guide_index(root):
773
+ lines = [guide_index_header(),
774
+ "# Operative guides (generated router)",
775
+ "",
776
+ "One row per guide. `description` is the when-to-consult line; provenance",
777
+ "shows what the guide was distilled from. Freshness: run `sdlc_check.py stale`.",
778
+ "",
779
+ "| Guide | Status | When to consult | Source | Source version |",
780
+ "|---|---|---|---|---|"]
781
+ for rel, p, meta, _ in list_guides(root):
782
+ lines.append("| `{}` | {} | {} | {} | {} |".format(
783
+ p.name, meta.get("status", "-") or "-",
784
+ (meta.get("description", "") or "-").replace("|", "\\|"),
785
+ (meta.get("source", "") or "-").replace("|", "\\|"),
786
+ meta.get("source_version", "") or "-"))
787
+ return "\n".join(lines) + "\n"
788
+
789
+
790
+ def cmd_index(root):
791
+ if not require_ai_docs(root, "index"):
792
+ return 1
793
+ hist = ai_path(root, "strategic", "features_history.md")
794
+ hist.parent.mkdir(parents=True, exist_ok=True)
795
+ hist.write_text(build_index(root), encoding="utf-8")
796
+ print(f"[ok] ANALYSIS index regenerated: {hist}")
797
+ # INDEX.md only if canonical docs exist: no empty manifest on minimal projects
798
+ if list_canonical_docs(root):
799
+ manifest = ai_path(root, "INDEX.md")
800
+ manifest.write_text(build_manifest(root), encoding="utf-8")
801
+ print(f"[ok] document manifest regenerated: {manifest}")
802
+ else:
803
+ print("[info] no canonical documents: INDEX.md not generated")
804
+ guides = list_guides(root)
805
+ gidx = ai_path(root, "reference", "INDEX.md")
806
+ if guides:
807
+ gidx.write_text(build_guide_index(root), encoding="utf-8")
808
+ print(f"[ok] guide router regenerated: {gidx}")
809
+ else:
810
+ # An EMPTY router still gets written: Rule Zero makes reading it a
811
+ # mandatory, declared step, and `no match` may not be faked. Without the
812
+ # stub, the required verdict is unsatisfiable on every new project --
813
+ # and a rule that cannot be obeyed on first contact gets discarded.
814
+ gidx.parent.mkdir(parents=True, exist_ok=True)
815
+ gidx.write_text(guide_index_header() + "\n# Operative guides (generated router)\n\n"
816
+ "No guides in this project yet. This file exists so the Rule Zero "
817
+ "router lookup has something to read: the honest verdict here is "
818
+ "`router: no match`.\n\n"
819
+ "A guide is written when the user hands over indications to follow "
820
+ "(`source_kind: document`), or when a high-complexity component needs "
821
+ "a comprehension map (`source_kind: code`) -- see `guides.md`.\n",
822
+ encoding="utf-8")
823
+ print(f"[ok] guide router regenerated (empty stub): {gidx}")
824
+ return 0
825
+
826
+
827
+ # ----------------------------------------------------------------- validate
828
+
829
+ def has_section(text, aliases):
830
+ return any(a in text for a in aliases)
831
+
832
+
833
+ def section_body(text, aliases):
834
+ """The body of the first matching `## ` section, or None if no alias is present.
835
+
836
+ Portable checks read a section rather than the whole document, so a phrase that
837
+ happens to appear elsewhere cannot satisfy a check about this section."""
838
+ lines = text.splitlines()
839
+ for i, line in enumerate(lines):
840
+ if not any(line.startswith(a) for a in aliases):
841
+ continue
842
+ body = []
843
+ for nxt in lines[i + 1:]:
844
+ if nxt.startswith("## "):
845
+ break
846
+ body.append(nxt)
847
+ return "\n".join(body).strip()
848
+ return None
849
+
850
+
851
+ def design_review_due(meta):
852
+ """True when an L3 ANALYSIS owes a design-review row (review.md moment 1):
853
+ implementation has started or finished, and it began on/after the gate
854
+ shipped. PLANNED is exempt -- the review is due at the END of Phase 3, so an
855
+ analysis still being drafted is not late."""
856
+ if meta.get("level", "").upper() != "L3":
857
+ return False
858
+ if meta.get("status") not in ("IN_PROGRESS", "COMPLETED"):
859
+ return False
860
+ started = parse_iso((meta.get("start_date") or "").strip().strip("'\""))
861
+ return started is not None and started >= parse_iso(DESIGN_REVIEW_EPOCH)
862
+
863
+
864
+ def review_logged(root, analysis_name):
865
+ """True when REVIEW_LOG.md carries a design-moment row naming this ANALYSIS.
866
+ The filename matches anywhere in the row (loose on purpose: a freshness
867
+ signal must not turn a formatting slip into a false 'you skipped the
868
+ review'), but the moment is read from the `tier` COLUMN -- the schema
869
+ reserves it for exactly this, and matching 'design' anywhere in the row let
870
+ a CLOSURE row saying 'conformance to the design' satisfy the check."""
871
+ log = root / review_log_rel()
872
+ if not log.is_file():
873
+ return False
874
+ stem = analysis_name[:-3] if analysis_name.endswith(".md") else analysis_name
875
+ # match the filename on a word boundary: a plain substring lets a longer
876
+ # sibling (ANALYSIS_vision_clarity) satisfy a shorter one (ANALYSIS_vision)
877
+ name_re = re.compile(r"(?<![\w-])" + re.escape(stem) + r"(?![\w-])")
878
+ tier_idx = None
879
+ for line in read_text(log).splitlines():
880
+ line = line.strip()
881
+ if not line.startswith("|"):
882
+ continue
883
+ cells = [c.strip() for c in line.strip("|").split("|")]
884
+ if tier_idx is None:
885
+ lowered = [c.lower() for c in cells]
886
+ if "tier" in lowered: # header found: trust it over position
887
+ tier_idx = lowered.index("tier")
888
+ continue
889
+ if not name_re.search(line):
890
+ continue
891
+ # schema: | date | doc_key | tier | reviewer | raised | real | verdict | rounds |
892
+ idx = tier_idx if tier_idx is not None else 2
893
+ if len(cells) > idx and re.match(r"design\b", cells[idx], re.I):
894
+ return True
895
+ return False
896
+
897
+
898
+ def has_ledger_heading(text):
899
+ """True when a REAL '## Capability Ledger' heading exists: fenced code
900
+ blocks are removed first, then HTML comments. An unterminated '<!--' only
901
+ opens a comment at the start of a line -- nuking to EOF on an inline
902
+ mention (or an unclosed example inside a fence) made a document that
903
+ HAS its ledger get told it has none."""
904
+ stripped = re.sub(r"^(```|~~~).*?^\1", "", text, flags=re.M | re.S)
905
+ stripped = re.sub(r"<!--.*?-->", "", stripped, flags=re.S)
906
+ stripped = re.sub(r"^[ \t]*<!--(?!.*?-->).*\Z", "", stripped, flags=re.M | re.S)
907
+ return bool(re.search(r"^##[ \t]+Capability Ledger[ \t]*$", stripped, re.M))
908
+
909
+
910
+ def ledger_due(meta):
911
+ """True when an ANALYSIS owes a '## Capability Ledger' (architect.md):
912
+ an L3 started on/after the day the pass shipped. Grandfathered by
913
+ start_date ALONE -- deliberately NOT by status: closure flips the ANALYSIS
914
+ to COMPLETED before `check` runs (SKILL.md phase 5), so a status filter
915
+ would silence the backstop at the only moment the process mandates the
916
+ validator. A malformed/absent start_date is not due (fail-open: cmd_validate
917
+ already errors on a missing one, and guessing an epoch from garbage would
918
+ nag projects the pass never reached)."""
919
+ if meta.get("level", "").upper() != "L3":
920
+ return False
921
+ if meta.get("status") == "CANCELLED":
922
+ return False # abandoned work has no legitimate way to satisfy this
923
+ started = parse_iso((meta.get("start_date") or "").strip().strip("'\""))
924
+ return started is not None and started >= parse_iso(ARCHITECT_PASS_EPOCH)
925
+
926
+
927
+ MAP_SECTION_RE = re.compile(r"^#{2,3}[ \t]+Component Map\b.*?$(.*?)(?=^#{1,3}[ \t]+\S|\Z)",
928
+ re.M | re.S | re.I)
929
+
930
+
931
+ def map_where_refs(arch_text):
932
+ """Normalized, symbol-stripped paths from the Component Map's 'Where' column
933
+ ONLY -- never from the whole document. Harvesting the whole file let the
934
+ canonical template's own '## Directory Structure' backticks satisfy the check
935
+ and silently disable it on every project that fills that section in.
936
+ Returns None when the document has no Component Map at all."""
937
+ m = MAP_SECTION_RE.search(arch_text)
938
+ if not m:
939
+ return None
940
+ refs, where_idx = [], None
941
+ for ln in m.group(1).splitlines():
942
+ ln = ln.strip()
943
+ if not ln.startswith("|"):
944
+ continue
945
+ cells = [c.strip() for c in ln.strip("|").split("|")]
946
+ if len(cells) < 2 or not cells[0] or set(cells[0]) <= {"-", ":"}:
947
+ continue
948
+ if where_idx is None:
949
+ lowered = [c.lower() for c in cells]
950
+ if "where" not in lowered:
951
+ return [] # no Where column: nothing is mapped
952
+ where_idx = lowered.index("where")
953
+ continue
954
+ if where_idx < len(cells):
955
+ for _ref, path_part, _sym in _map_refs(cells[where_idx]):
956
+ refs.append(path_part.lstrip("./").strip("/"))
957
+ return refs
958
+
959
+
960
+ def _map_refs(where):
961
+ """Backticked refs in a 'Where' cell that are file paths: they contain a
962
+ separator, or end in a KNOWN source-file suffix. Windows separators are
963
+ normalized. Everything else in that cell is prose and must stay silent --
964
+ a false 'the map is rotting' teaches readers to ignore the output, which is
965
+ worse than the rot. `app.core`, `OrderStore.save` and `1.18.0` are prose."""
966
+ out = []
967
+ for ref in re.findall(r"`([^`]+)`", where):
968
+ path_part, _, symbol = ref.partition("#")
969
+ path_part = path_part.replace("\\", "/").strip()
970
+ if not path_part or "://" in path_part:
971
+ continue # a URL is not a repo path
972
+ # A slash-less token counts only if it looks like a FILENAME. The one
973
+ # real false-positive class is `Next.js` / `Node.js` / `Vue.js`: a
974
+ # CamelCase stem with a `.js` tail is a framework name, not a file.
975
+ # The exclusion is scoped to that suffix ON PURPOSE -- a blanket
976
+ # CamelCase rule would silence `App.tsx`, `Program.cs`, `Main.java`,
977
+ # which are exactly what React/C#/Java projects put in a Where cell.
978
+ stem, _, suffix = path_part.rsplit("/", 1)[-1].rpartition(".")
979
+ framework_name = (suffix.lower() == "js"
980
+ and bool(re.fullmatch(r"[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)*", stem)))
981
+ looks_like_path = "/" in path_part or (
982
+ bool(re.search(r"\.(" + "|".join(FILE_SUFFIXES) + r")$", path_part, re.I))
983
+ and not framework_name)
984
+ if looks_like_path:
985
+ out.append((ref, path_part, symbol.strip()))
986
+ return out
987
+
988
+
989
+ def check_component_map(root, text, advisories):
990
+ """Anti-rot for the '## Component Map' of strategic/architecture.md
991
+ (architect.md): every path-shaped backticked ref in the 'Where' column must
992
+ still resolve on disk, and its '#symbol' must still appear as a whole word
993
+ in a matched file. This is the map's equivalent of the guides' source_hash.
994
+ ADVISORY: a freshness signal, never a gate -- not even under --strict (the
995
+ accepted ceremony budget was a warning, not a blocked pipeline)."""
996
+ m = MAP_SECTION_RE.search(text) # one regex for both checks: they cannot drift
997
+ if not m:
998
+ return
999
+ rows = [ln.strip() for ln in m.group(1).splitlines() if ln.strip().startswith("|")]
1000
+ where_idx, header_cells, checked, data_rows, ragged = None, 0, 0, 0, 0
1001
+ for row in rows:
1002
+ cells = [c.strip() for c in row.strip("|").split("|")]
1003
+ if len(cells) < 2 or not cells[0] or set(cells[0]) <= {"-", ":"}:
1004
+ continue
1005
+ if where_idx is None: # the first non-separator row is the header
1006
+ lowered = [c.lower() for c in cells]
1007
+ if "where" not in lowered:
1008
+ advisories.append("strategic/architecture.md: Component Map has no 'Where' "
1009
+ "column in its header -- the anti-rot check cannot run; "
1010
+ "give the table a Where column of `path/to/file#Symbol` refs")
1011
+ return
1012
+ where_idx, header_cells = lowered.index("where"), len(cells)
1013
+ continue
1014
+ if all(c in ("", "...", "…") for c in cells):
1015
+ continue # untouched template placeholder row
1016
+ data_rows += 1
1017
+ if len(cells) != header_cells: # ragged: never silently unchecked
1018
+ ragged += 1
1019
+ continue
1020
+ component, where = cells[0], cells[where_idx]
1021
+ for ref, path_part, symbol in _map_refs(where):
1022
+ checked += 1
1023
+ if confine_under(root, re.sub(r"[*?\[\]]", "x", path_part)) is None:
1024
+ advisories.append(f"strategic/architecture.md: Component Map row '{component}': "
1025
+ f"ref '{ref}' escapes the project root: rejected")
1026
+ continue
1027
+ target = root / path_part
1028
+ try:
1029
+ if target.exists(): # literal first: `app/[id]/page.tsx` is a real path
1030
+ matches = [target]
1031
+ elif any(c in path_part for c in "*?["):
1032
+ matches = list(root.glob(path_part))
1033
+ else:
1034
+ matches = []
1035
+ except (ValueError, OSError):
1036
+ matches = []
1037
+ if not matches:
1038
+ advisories.append(f"strategic/architecture.md: Component Map row '{component}': "
1039
+ f"'{path_part}' no longer exists -- the map is rotting, "
1040
+ "update the row or drop it")
1041
+ continue
1042
+ files = [f for f in matches if f.is_file()]
1043
+ if symbol and files:
1044
+ word = re.compile(r"(?<![A-Za-z0-9_])" + re.escape(symbol) + r"(?![A-Za-z0-9_])")
1045
+ if not any(word.search(read_text(f)) for f in files):
1046
+ advisories.append(f"strategic/architecture.md: Component Map row '{component}': "
1047
+ f"symbol '{symbol}' not found in '{path_part}' -- renamed or "
1048
+ "removed, update the row")
1049
+ if ragged:
1050
+ advisories.append(f"strategic/architecture.md: Component Map has {ragged} row(s) whose "
1051
+ "column count differs from the header -- unchecked; an escaped '|' in "
1052
+ "a cell shifts the columns")
1053
+ if data_rows and not checked and not ragged:
1054
+ # only once the map claims real components: a freshly seeded project
1055
+ # carries the template placeholder and must NOT be nagged on day zero
1056
+ advisories.append("strategic/architecture.md: Component Map has rows but no checkable "
1057
+ "path in its 'Where' column -- the anti-rot check is inert; write refs "
1058
+ "as `path/to/file#Symbol`")
1059
+
1060
+
1061
+ def cmd_validate(root, strict=False, hybrid=False):
1062
+ # advisories: architect-pass freshness signals. Reported, never escalated by
1063
+ # --strict -- the accepted ceremony budget (project_vision.md "no ceremony
1064
+ # ratchet") was a warning, and a warning that reddens CI is a gate.
1065
+ errors, warnings, advisories = [], [], []
1066
+ ai = ai_path(root)
1067
+ if not ai.is_dir():
1068
+ if strict:
1069
+ print(f"[ERROR] {ai} does not exist: nothing to validate. In --strict mode this "
1070
+ "fails so a wrong working directory cannot produce a green pipeline.")
1071
+ return 1
1072
+ print(f"[info] {ai} does not exist: nothing to validate (project without SDLC docs).")
1073
+ return 0
1074
+
1075
+ # Vision: presence and declared state
1076
+ for name in VISION_FILES:
1077
+ f = ai / "vision" / name
1078
+ if not f.is_file():
1079
+ warnings.append(f"vision/{name} missing")
1080
+ continue
1081
+ head = "\n".join(read_text(f).splitlines()[:12])
1082
+ m = re.search(r"(?:Status|Stato):\s*(DRAFT|APPROVED)", head)
1083
+ if not m:
1084
+ errors.append(f"vision/{name}: missing 'Status: DRAFT|APPROVED' in the first lines")
1085
+ elif m.group(1) == "DRAFT":
1086
+ # advisory, not a warning: bootstrap MANDATES DRAFT, so a warning here
1087
+ # makes `validate --strict` red on every freshly bootstrapped project
1088
+ # until a human runs the blind check -- and teams delete the CI step
1089
+ # rather than block on it. DRAFT is a state, not a defect.
1090
+ advisories.append(f"vision/{name} is DRAFT: not a gating authority, "
1091
+ "have the user validate it")
1092
+
1093
+ # ANALYSIS: frontmatter and mandatory sections
1094
+ # Ids are unique WITHIN a domain (prefixes F-/K-/M- keep them apart in practice):
1095
+ # two lenses over one tree must not collide on a number neither of them chose.
1096
+ seen_ids = {}
1097
+ default_domain = project_default_domain(root)
1098
+ analyses = list_analyses(root)
1099
+ for p, meta, text in analyses:
1100
+ rel = "solutions/" + p.name
1101
+ if not meta:
1102
+ errors.append(f"{rel}: frontmatter missing")
1103
+ continue
1104
+ domain, unknown_domain = resolve_domain(meta, default_domain)
1105
+ if unknown_domain:
1106
+ warnings.append(f"{rel}: domain '{unknown_domain}' not recognized "
1107
+ f"({'/'.join(sorted(DOMAINS))}): validated as '{domain}'")
1108
+ fid = meta.get("id")
1109
+ if not fid:
1110
+ errors.append(f"{rel}: 'id' field missing")
1111
+ elif (domain, fid) in seen_ids:
1112
+ errors.append(f"{rel}: id '{fid}' duplicated (already used in {seen_ids[(domain, fid)]})")
1113
+ else:
1114
+ seen_ids[(domain, fid)] = rel
1115
+ status = meta.get("status", "")
1116
+ if status not in VALID_STATES:
1117
+ errors.append(f"{rel}: status '{status}' not valid ({'/'.join(sorted(VALID_STATES))})")
1118
+ if not meta.get("start_date"):
1119
+ errors.append(f"{rel}: 'start_date' missing")
1120
+ if status == "COMPLETED" and not meta.get("end_date"):
1121
+ errors.append(f"{rel}: COMPLETED without 'end_date'")
1122
+ level = meta.get("level")
1123
+ if level and level.upper() not in VALID_LEVELS:
1124
+ warnings.append(f"{rel}: level '{level}' not recognized ({'/'.join(sorted(VALID_LEVELS))})")
1125
+ # The risk slot is translated per domain, never dropped: whichever lens owns
1126
+ # the document, it owes ITS account of what could go wrong.
1127
+ rules = DOMAINS[domain]
1128
+ if not has_section(text, rules["risk_section"]):
1129
+ errors.append(f"{rel}: section '{rules['risk_label']}' missing (mandatory)")
1130
+ for en, it in ANALYSIS_SECTIONS:
1131
+ if not has_section(text, (en, it)):
1132
+ warnings.append(f"{rel}: section '{en}' missing")
1133
+ run_portable_checks(rel, meta, text, errors, warnings, advisories)
1134
+ if not level and (parse_iso((meta.get("start_date") or "").strip().strip("'\"")) or
1135
+ parse_iso("1970-01-01")) >= parse_iso(ARCHITECT_PASS_EPOCH):
1136
+ # advisory + epoch-gated, exactly like the check it guards: a warning
1137
+ # here would redden --strict CI on every pre-1.18 analysis that never
1138
+ # carried the optional field. (Same defect the advisories bucket was
1139
+ # invented to prevent -- reintroduced once, caught in review.)
1140
+ advisories.append(f"{rel}: 'level' missing (L1/L2/L3/Spike) -- risk-proportional "
1141
+ "checks cannot apply, and dropping the line is cheaper than "
1142
+ "doing the work it triggers")
1143
+ # comment-stripped, anchored: a '<!-- TODO: the ## Capability Ledger -->'
1144
+ # must not read as the section being present
1145
+ # Hybrid: the design lives in devPNT and its §4.5 gate owns this slot
1146
+ # (SKILL.md ownership matrix: "run ONE of them, never both"), and its log
1147
+ # rows are keyed on e_isp_/e_tdd_ doc_keys, not on this filename -- so
1148
+ # firing here would be a permanent, unfixable false positive.
1149
+ if not hybrid and design_review_due(meta) and not review_logged(root, p.name):
1150
+ advisories.append(f"{rel}: L3 in implementation with no design-review row in "
1151
+ f"{review_log_rel()} -- the design was reviewed by nobody but its "
1152
+ "author before code was written (review.md moment 1)")
1153
+ if ledger_due(meta) and not has_ledger_heading(text):
1154
+ advisories.append(f"{rel}: L3 without '## Capability Ledger' -- the architect pass "
1155
+ "left no record (architect.md); run it before the Impact")
1156
+
1157
+ # Generated index aligned
1158
+ hist = ai / "strategic" / "features_history.md"
1159
+ if analyses:
1160
+ if not hist.is_file():
1161
+ errors.append("strategic/features_history.md missing: run 'sdlc_check.py index'")
1162
+ elif norm_text(read_text(hist)) != norm_text(build_index(root)):
1163
+ errors.append("strategic/features_history.md not aligned with the ANALYSIS files: run 'sdlc_check.py index'")
1164
+
1165
+ # Canonical document manifest aligned (Poka-Yoke: unindexed file = dirty closure)
1166
+ docs = list_canonical_docs(root)
1167
+ manifest = ai / "INDEX.md"
1168
+ if docs:
1169
+ if not manifest.is_file():
1170
+ errors.append(f"{docs_dir()}/INDEX.md missing: run 'sdlc_check.py index'")
1171
+ elif norm_text(read_text(manifest)) != norm_text(build_manifest(root)):
1172
+ errors.append(f"{docs_dir()}/INDEX.md not aligned with the canonical documents: run 'sdlc_check.py index'")
1173
+
1174
+ # Canonical document lifecycle: declared status + supersedes coherence
1175
+ canon_status = {rel: meta[2] for rel, _, meta in docs}
1176
+ for rel, _, (title, desc, status, supersedes) in docs:
1177
+ if not status:
1178
+ warnings.append(f"{rel}: missing 'status:' in the header (CURRENT/SUPERSEDED/DRAFT/DEPRECATED)")
1179
+ elif status not in CANONICAL_STATES:
1180
+ warnings.append(f"{rel}: status '{status}' not recognized ({'/'.join(sorted(CANONICAL_STATES))})")
1181
+ if supersedes:
1182
+ base = os.path.basename(supersedes)
1183
+ for other, ost in canon_status.items():
1184
+ if (other == supersedes or other.endswith("/" + supersedes)
1185
+ or os.path.basename(other) == base) and ost == "CURRENT":
1186
+ warnings.append(f"{other}: still CURRENT but superseded by {rel} (set status: SUPERSEDED)")
1187
+
1188
+ # Component Map anti-rot (architect.md): rows must still resolve on disk
1189
+ arch = ai / "strategic" / "architecture.md"
1190
+ if arch.is_file():
1191
+ arch_text = read_text(arch)
1192
+ check_component_map(root, arch_text, advisories)
1193
+ # the missing half of the loop: `mark` asserts an area was read closely
1194
+ # enough to name its capability owners, and nothing verified that claim.
1195
+ # An ANALYZED area with no map row is how the brownfield guard is
1196
+ # disarmed -- the area looks read, so the map's silence becomes groundable.
1197
+ _, _, plan_rows = parse_audit_plan(root)
1198
+ mapped = map_where_refs(arch_text)
1199
+ if plan_rows and mapped is not None:
1200
+ for prow in plan_rows:
1201
+ if prow["status"] != "ANALYZED":
1202
+ continue
1203
+ if confine_under(root, prow["path"]) is None:
1204
+ continue # stale already rejects these
1205
+ if re.search(r"owns no component", prow.get("note", ""), re.I):
1206
+ continue # declared, not forgotten: the opt-out
1207
+ area = prow["path"].replace("\\", "/").strip("/")
1208
+ if area.startswith("./"):
1209
+ area = area[2:]
1210
+ if area in ("", "."):
1211
+ continue # the whole root: every row is inside it
1212
+ if not (root / area).exists():
1213
+ continue # gone from disk: not a mapping gap
1214
+ if not any(mp == area or mp.startswith(area + "/") for mp in mapped):
1215
+ advisories.append(
1216
+ f"strategic/architecture.md: '{prow['path']}' is ANALYZED in the audit "
1217
+ "plan but owns no Component Map row -- marking asserts the area was read "
1218
+ "closely enough to name what it owns, and the map's silence there is now "
1219
+ "groundable for a MISSING verdict (architect.md). If it genuinely owns no "
1220
+ "component, say so in the audit plan's Notes column: 'owns no component'")
1221
+
1222
+ # Guide checks (ai_docs/reference/GUIDE_*.md): structure only — freshness is stale's job
1223
+ guides = list_guides(root)
1224
+ for rel, p, meta, text in guides:
1225
+ missing = [k for k in GUIDE_PROVENANCE_KEYS if not meta.get(k)]
1226
+ if missing:
1227
+ warnings.append(f"{rel}: guide missing provenance key(s): {', '.join(missing)}")
1228
+ # (b) per-section fidelity markers: every '## ' section body must carry a marker
1229
+ body = text.split("---", 2)[-1]
1230
+ sections = re.split(r"^##\s+", body, flags=re.M)[1:]
1231
+ unmarked = [s.splitlines()[0].strip() for s in sections if not GUIDE_MARKER_RE.search(s)]
1232
+ if unmarked:
1233
+ warnings.append(f"{rel}: section(s) without [source: ...] / [not covered by source] marker: "
1234
+ + "; ".join(unmarked[:5]))
1235
+ # (c) distilled_from confinement — fail closed (P-TM T6, distilled_from vector)
1236
+ df = meta.get("distilled_from", "")
1237
+ if df and confine_under(root, df) is None:
1238
+ errors.append(f"{rel}: distilled_from '{df}' is absolute, contains '..', or resolves "
1239
+ "outside the project root: rejected")
1240
+ check_kb_collisions(root, guides, errors, warnings)
1241
+ # guide-router alignment (mirror of the root-manifest check)
1242
+ gidx = ai_path(root, "reference", "INDEX.md")
1243
+ if not gidx.is_file() and not guides:
1244
+ # zero guides: the stub is a convenience for the mandatory Rule Zero read
1245
+ advisories.append(f"{docs_dir()}/reference/INDEX.md missing: Rule Zero requires reading the "
1246
+ "guide router and forbids faking its verdict, so the router exists "
1247
+ "even with zero guides -- run 'sdlc_check.py index'")
1248
+ if guides:
1249
+ if not gidx.is_file():
1250
+ # guides EXIST and the router does not: the agent's mandatory lookup
1251
+ # finds nothing and legally declares 'absent', so the guide that
1252
+ # governs the work is never consulted. An absent router must not be
1253
+ # graded below a merely stale one.
1254
+ errors.append(f"{docs_dir()}/reference/INDEX.md missing while GUIDE_*.md files exist: "
1255
+ "the router is the only thing that routes work to them -- "
1256
+ "run 'sdlc_check.py index'")
1257
+ elif norm_text(read_text(gidx)) != norm_text(build_guide_index(root)):
1258
+ errors.append(f"{docs_dir()}/reference/INDEX.md not aligned with the guides: run 'sdlc_check.py index'")
1259
+
1260
+ # Handoff: header and freshness
1261
+ hand = ai / "audit" / "handoff.md"
1262
+ if hand.is_file():
1263
+ m = re.search(r"(?:Date|Data):\s*(\d{4}-\d{2}-\d{2})", read_text(hand))
1264
+ if not m:
1265
+ warnings.append("audit/handoff.md without a 'Date: YYYY-MM-DD' header")
1266
+ else:
1267
+ try:
1268
+ stamp = datetime.strptime(m.group(1), "%Y-%m-%d").replace(tzinfo=timezone.utc)
1269
+ age = (datetime.now(timezone.utc) - stamp).days
1270
+ if age > 14:
1271
+ warnings.append(f"audit/handoff.md is {age} days old: treat it as history, not current state")
1272
+ except ValueError:
1273
+ warnings.append("audit/handoff.md: date not parseable")
1274
+
1275
+ for a in advisories:
1276
+ print(f"[note] {a}")
1277
+ for w in warnings:
1278
+ print(f"[warn] {w}")
1279
+ for e in errors:
1280
+ print(f"[ERROR] {e}")
1281
+ print(f"\nValidation: {len(errors)} errors, {len(warnings)} warnings, "
1282
+ f"{len(advisories)} advisories.")
1283
+ if advisories:
1284
+ print("[note] advisories are freshness signals: never fail a build, not even --strict.")
1285
+ if strict and warnings and not errors:
1286
+ print("[strict] warnings are failures in --strict mode.")
1287
+ return 1 if errors or (strict and warnings) else 0
1288
+
1289
+
1290
+ # ------------------------------------------------------------- audit_plan
1291
+
1292
+ def parse_audit_plan(root):
1293
+ f = ai_path(root, "audit", "audit_plan.md")
1294
+ rows, lines = [], []
1295
+ if f.is_file():
1296
+ lines = read_text(f).splitlines()
1297
+ for i, line in enumerate(lines):
1298
+ if not line.strip().startswith("|"):
1299
+ continue
1300
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
1301
+ if len(cells) < 2:
1302
+ continue
1303
+ if cells[0].lower() in ("path", "percorso") or set(cells[0]) <= set("-: "):
1304
+ continue
1305
+ rows.append({
1306
+ "line": i,
1307
+ "path": cells[0],
1308
+ "status": cells[1].upper(),
1309
+ "ref": cells[2] if len(cells) > 2 else "",
1310
+ "note": cells[3] if len(cells) > 3 else "",
1311
+ })
1312
+ return f, lines, rows
1313
+
1314
+
1315
+ def cmd_stale(root, hybrid=False):
1316
+ rc = 0
1317
+ # --- guide freshness (source_hash vs snapshot) — runs in EVERY mode
1318
+ drifted = []
1319
+ for rel, p, meta, _ in list_guides(root):
1320
+ df, rec = meta.get("distilled_from", ""), meta.get("source_hash", "")
1321
+ if not df or not rec:
1322
+ continue # structure problems are validate's job
1323
+ src = root / df
1324
+ if not src.is_file():
1325
+ print(f"[warn] {rel}: distilled_from '{df}' not found — snapshot missing")
1326
+ rc = 1
1327
+ continue
1328
+ if sha256_file(src) != rec:
1329
+ drifted.append((rel, df))
1330
+ for rel, df in drifted:
1331
+ print(f"[stale] {rel}: source snapshot '{df}' changed since distillation — regenerate the guide")
1332
+ if drifted:
1333
+ rc = 1
1334
+ # --- audit-plan staleness — delegated to devPNT/KL in hybrid
1335
+ if hybrid:
1336
+ print("[info] hybrid mode: audit-plan staleness is delegated to devPNT/KL, skipping.")
1337
+ return rc # was: implicit skip-all; guide rc survives
1338
+ f, _, rows = parse_audit_plan(root)
1339
+ if not rows:
1340
+ print(f"[info] no rows in {f}: nothing to check "
1341
+ "(audit not initialized, or Hybrid mode where mapping is delegated to devPNT).")
1342
+ return rc # was: return 0 — MUST carry guide rc
1343
+ use_git = git_available(root)
1344
+ stale = []
1345
+ for row in rows:
1346
+ if row["status"] != "ANALYZED":
1347
+ continue
1348
+ rel, ref = row["path"], row["ref"]
1349
+ # Confine BEFORE touching the filesystem: audit_plan.md is document
1350
+ # content, so an absolute row ('/'), a drive-relative one or a '..'
1351
+ # escape would otherwise walk outside the project (P-TM T2/T3). A bare
1352
+ # '/' is the row init.js used to seed, and `root / "/"` is the drive.
1353
+ target = confine_under(root, rel)
1354
+ if target is None:
1355
+ print(f"[warn] {rel}: path is absolute, contains '..', or resolves outside "
1356
+ "the project root: rejected (use a project-relative path, '.' for the root)")
1357
+ continue
1358
+ if not target.exists():
1359
+ print(f"[warn] {rel}: path does not exist")
1360
+ continue
1361
+ changed = []
1362
+ if use_git and re.fullmatch(r"[0-9a-fA-F]{7,40}", ref or ""):
1363
+ res = git_changed_since(root, ref, rel.replace("\\", "/"))
1364
+ if res is None:
1365
+ print(f"[warn] {rel}: git ref '{ref}' unresolvable, cannot evaluate")
1366
+ continue
1367
+ changed = res
1368
+ else:
1369
+ ts = parse_iso(ref)
1370
+ if ts is None:
1371
+ print(f"[warn] {rel}: reference '{ref}' not parseable (neither git hash nor ISO UTC)")
1372
+ continue
1373
+ for fp in iter_files(target):
1374
+ mtime = datetime.fromtimestamp(fp.stat().st_mtime, tz=timezone.utc)
1375
+ if mtime > ts + MTIME_GRACE:
1376
+ try:
1377
+ name = str(fp.relative_to(root)).replace("\\", "/")
1378
+ except ValueError: # symlink out of the tree: report absolute, never crash
1379
+ name = str(fp)
1380
+ changed.append(name)
1381
+ if changed:
1382
+ stale.append((rel, changed))
1383
+
1384
+ if not stale:
1385
+ print("[ok] no analyzed area was modified after its last recorded analysis.")
1386
+ return rc # was: return 0 — MUST carry guide rc
1387
+ print("Areas modified after the last recorded analysis:")
1388
+ for rel, changed in stale:
1389
+ print(f" {rel} ({len(changed)} files)")
1390
+ for c in changed[:10]:
1391
+ print(f" - {c}")
1392
+ if len(changed) > 10:
1393
+ print(f" ... and {len(changed) - 10} more")
1394
+ print("\nAfter re-analyzing, record it with: sdlc_check.py mark <path>")
1395
+ return 1 # stale areas dominate: rc already implied
1396
+
1397
+
1398
+ def cmd_mark(root, paths):
1399
+ if not require_ai_docs(root, "mark"):
1400
+ return 1
1401
+ f, lines, rows = parse_audit_plan(root)
1402
+ use_git_ref = git_available(root) and not any(
1403
+ git_has_changes(root, raw.replace("\\", "/").rstrip("/")) for raw in paths
1404
+ )
1405
+ ref = git_head(root) if use_git_ref else utc_now_iso()
1406
+ by_path = {r["path"].replace("\\", "/").rstrip("/"): r for r in rows}
1407
+
1408
+ if not lines:
1409
+ lines = ["# Audit Plan", "",
1410
+ "| Path | Status | Reference | Notes |",
1411
+ "|---|---|---|---|"]
1412
+ rows = []
1413
+
1414
+ def row_text(path, note):
1415
+ return f"| {path} | ANALYZED | {ref} | {note} |"
1416
+
1417
+ # validate EVERY path before printing or mutating anything: a rejection
1418
+ # after an '[ok] ... added as ANALYZED' line is a lie the agent will act on
1419
+ keys = []
1420
+ for raw in paths:
1421
+ key = raw.replace("\\", "/").rstrip("/") or "."
1422
+ if confine_under(root, key) is None:
1423
+ print(f"[ERROR] {raw}: absolute, '..'-escaping, or outside the project root: "
1424
+ "refusing to mark (use a project-relative path, '.' for the root). "
1425
+ "Nothing was written.")
1426
+ return 1
1427
+ keys.append(key)
1428
+
1429
+ appended = []
1430
+ for key in keys:
1431
+ display = key + ("/" if (root / key).is_dir() and key != "." else "")
1432
+ existing = by_path.get(key)
1433
+ if existing:
1434
+ lines[existing["line"]] = row_text(existing["path"], existing["note"])
1435
+ print(f"[ok] {existing['path']} -> ANALYZED ({ref})")
1436
+ else:
1437
+ appended.append(row_text(display, ""))
1438
+ print(f"[ok] {display} added as ANALYZED ({ref})")
1439
+
1440
+ if appended:
1441
+ insert_at = (max(r["line"] for r in rows) + 1) if rows else len(lines)
1442
+ lines[insert_at:insert_at] = appended
1443
+
1444
+ f.parent.mkdir(parents=True, exist_ok=True)
1445
+ f.write_text("\n".join(lines) + "\n", encoding="utf-8")
1446
+ return 0
1447
+
1448
+
1449
+ def cmd_check(root, strict=False, hybrid=False):
1450
+ print("===== validate =====")
1451
+ rc_v = cmd_validate(root, strict=strict, hybrid=hybrid)
1452
+ print("\n===== stale =====")
1453
+ rc_s = cmd_stale(root, hybrid=hybrid)
1454
+ print(f"\ncheck: {'CLEAN' if not (rc_v or rc_s) else 'NOT CLEAN'} "
1455
+ f"(validate rc={rc_v}, stale rc={rc_s})")
1456
+ return 1 if (rc_v or rc_s) else 0
1457
+
1458
+
1459
+ # --------------------------------------------------------------------- gate
1460
+
1461
+ def cmd_gate(args):
1462
+ file_path = args.file or ""
1463
+ if args.hook:
1464
+ try:
1465
+ # bytes -> utf-8-sig: the hook payload is UTF-8 JSON regardless of the
1466
+ # console code page; '-sig' strips the BOM (PowerShell pipes)
1467
+ raw = sys.stdin.buffer.read().decode("utf-8-sig", errors="replace")
1468
+ payload = json.loads(raw)
1469
+ file_path = (payload.get("tool_input") or {}).get("file_path") or ""
1470
+ except Exception:
1471
+ return 0 # unparseable input: do not block
1472
+ if not file_path:
1473
+ return 0
1474
+ root = Path(args.root).resolve() if args.root else find_project_root()
1475
+ try:
1476
+ rel = str(Path(file_path).resolve().relative_to(root)).replace("\\", "/")
1477
+ except ValueError:
1478
+ return 0 # outside the project: not this gate's concern
1479
+ if rel.startswith((docs_dir() + "/", "tests/", "test/")):
1480
+ return 0
1481
+ protected = [p.strip().replace("\\", "/").rstrip("/")
1482
+ for p in (args.protected or "").split(";") if p.strip()]
1483
+ if not protected:
1484
+ return 0
1485
+ if not any(rel == p or rel.startswith(p + "/") for p in protected):
1486
+ return 0
1487
+ for _, meta, _ in list_analyses(root):
1488
+ if meta.get("status") == "IN_PROGRESS":
1489
+ return 0
1490
+ if args.hybrid and has_etdd_shadow(root):
1491
+ return 0 # Hybrid design gate: an approved E-TDD shadow authorizes the change
1492
+ if args.hybrid:
1493
+ sys.stderr.write(
1494
+ f"[sdlc gate] '{rel}' is on a protected path but no E-TDD shadow "
1495
+ "(solutions/SHADOW_*tdd*.md) exists and no ANALYSIS_*.md is IN_PROGRESS. "
1496
+ "In Hybrid mode, export the approved E-TDD shadow from devPNT before implementing.\n")
1497
+ return 2
1498
+ sys.stderr.write(
1499
+ f"[sdlc gate] '{rel}' is on a protected path but no ANALYSIS_*.md is IN_PROGRESS. "
1500
+ "If your analysis already exists, set its frontmatter to 'status: IN_PROGRESS' "
1501
+ "(that flip is what opens the gate); otherwise write it first (Phase 3).\n")
1502
+ return 2
1503
+
1504
+
1505
+ # --------------------------------------------------------------------- plan
1506
+ # Subagent Execution (Feature A). Zero-execution surface: this section and
1507
+ # everything it calls MUST NOT spawn a process (no subprocess/os.system/eval/
1508
+ # exec, no git_* helper). It validates a PLAN_[feature].md and prints a task
1509
+ # brief as text; the orchestrator (dispatch.md) is the sole executor.
1510
+
1511
+ _PLAN_JSON_RE = re.compile(r"```json\s*\n(.*?)```", re.DOTALL)
1512
+
1513
+
1514
+ def extract_plan_json(text):
1515
+ """Extract the first fenced ```json block from a PLAN_[feature].md body.
1516
+ Returns (data, "") on success, or (None, reason) on any failure. Never
1517
+ raises: a malformed or missing block is a validation failure, not a crash."""
1518
+ m = _PLAN_JSON_RE.search(text or "")
1519
+ if not m:
1520
+ return None, "no fenced ```json block found in the plan file"
1521
+ try:
1522
+ data = json.loads(m.group(1))
1523
+ except (ValueError, TypeError) as e:
1524
+ return None, f"malformed JSON in the plan block: {e}"
1525
+ if not isinstance(data, dict):
1526
+ return None, "plan JSON block must be a JSON object"
1527
+ return data, ""
1528
+
1529
+
1530
+ def load_ledger(path):
1531
+ """Read the sidecar ledger {"<task_id>": {"status", "verify_result",
1532
+ "timestamp"}}. Absent file -> ({}, ""). Malformed/unreadable -> ({}, reason).
1533
+ Never raises, never hangs: the ledger is untrusted state read on every call."""
1534
+ if not path.is_file():
1535
+ return {}, ""
1536
+ try:
1537
+ raw = read_text(path)
1538
+ data = json.loads(raw)
1539
+ except (ValueError, TypeError, OSError) as e:
1540
+ return {}, f"ledger '{path}' unreadable/malformed, treating as empty: {e}"
1541
+ if not isinstance(data, dict):
1542
+ return {}, f"ledger '{path}' is not a JSON object, treating as empty"
1543
+ return data, ""
1544
+
1545
+
1546
+ def _confine_or_reject(base, rel, label, rel_label, errors):
1547
+ t = confine_under(base, rel)
1548
+ if t is None:
1549
+ errors.append(f"{rel_label}: {label} '{rel}' is absolute, contains '..', or escapes "
1550
+ f"'{base}' — rejected (fail closed)")
1551
+ return t
1552
+
1553
+
1554
+ def _validate_plan_tasks(root, data, rel_label, errors, warnings):
1555
+ """Shared core of `plan validate`/`plan brief`: schema + confinement checks.
1556
+ Returns the task list (possibly empty) on success; errors/warnings are
1557
+ appended in place. Callers decide the exit code."""
1558
+ tasks = data.get("tasks")
1559
+ if not isinstance(tasks, list) or not tasks:
1560
+ errors.append(f"{rel_label}: 'tasks' must be a non-empty JSON array")
1561
+ return []
1562
+ ref_dir = ai_path(root, "reference")
1563
+ kb_ref = DEFAULT_KB_ROOT / "ai_docs" / "reference"
1564
+ seen_ids = set()
1565
+ for i, task in enumerate(tasks):
1566
+ loc = f"{rel_label}: task[{i}]"
1567
+ if not isinstance(task, dict):
1568
+ errors.append(f"{loc}: not a JSON object")
1569
+ continue
1570
+ missing = [k for k in PLAN_TASK_REQUIRED if not task.get(k)]
1571
+ if missing:
1572
+ errors.append(f"{loc}: missing required field(s): {', '.join(missing)}")
1573
+ if not task.get("paths") and not task.get("produces"):
1574
+ errors.append(f"{loc}: must declare at least one of 'paths'/'produces'")
1575
+ tid = task.get("id")
1576
+ if tid:
1577
+ if tid in seen_ids:
1578
+ errors.append(f"{loc}: duplicate task id '{tid}'")
1579
+ seen_ids.add(tid)
1580
+ for key in ("paths", "consumes", "produces"):
1581
+ for p in (task.get(key) or []):
1582
+ _confine_or_reject(root, p, key, loc, errors)
1583
+ for g in (task.get("guides") or []):
1584
+ in_project = confine_under(ref_dir, g)
1585
+ in_kb = confine_under(kb_ref, g)
1586
+ if in_project is None and in_kb is None:
1587
+ errors.append(f"{loc}: guide '{g}' is not confined under the project reference "
1588
+ f"dir ({ref_dir}) or the agent KB reference dir ({kb_ref}) — rejected")
1589
+ return tasks
1590
+
1591
+
1592
+ def cmd_plan(root, args):
1593
+ """Zero-execution: validates/briefs a PLAN_[feature].md. Never spawns a
1594
+ process, never calls a git_* helper, never runs the opaque `verify` text —
1595
+ it is printed, not executed."""
1596
+ plan_path = Path(args.file)
1597
+ if not plan_path.is_absolute():
1598
+ plan_path = root / plan_path
1599
+ if not plan_path.is_file():
1600
+ sys.stderr.write(f"[plan] plan file not found: {plan_path}\n")
1601
+ return 2
1602
+ rel_label = str(plan_path)
1603
+ data, reason = extract_plan_json(read_text(plan_path))
1604
+ if data is None:
1605
+ sys.stderr.write(f"[plan] {rel_label}: {reason}\n")
1606
+ return 2
1607
+
1608
+ errors, warnings = [], []
1609
+ tasks = _validate_plan_tasks(root, data, rel_label, errors, warnings)
1610
+
1611
+ ledger_path = plan_path.with_name(plan_path.stem + ".ledger.json")
1612
+ ledger, ledger_reason = load_ledger(ledger_path)
1613
+ if ledger_reason:
1614
+ warnings.append(ledger_reason)
1615
+ if not errors:
1616
+ task_ids = {t.get("id") for t in tasks if isinstance(t, dict)}
1617
+ for lid in ledger:
1618
+ if lid not in task_ids:
1619
+ warnings.append(f"ledger id '{lid}' not found in {rel_label}: orphaned entry (not fatal)")
1620
+
1621
+ for w in warnings:
1622
+ sys.stderr.write(f"[warn] {w}\n")
1623
+ for e in errors:
1624
+ sys.stderr.write(f"[ERROR] {e}\n")
1625
+
1626
+ if args.plan_cmd == "validate":
1627
+ if errors:
1628
+ sys.stderr.write(f"\n[plan] validate: {len(errors)} errors, {len(warnings)} warnings.\n")
1629
+ return 2
1630
+ print(f"[ok] {rel_label}: plan valid ({len(tasks)} task(s), {len(warnings)} warning(s)).")
1631
+ return 0
1632
+
1633
+ # brief
1634
+ if errors:
1635
+ sys.stderr.write(f"\n[plan] brief: plan is invalid, refusing to brief ({len(errors)} errors).\n")
1636
+ return 2
1637
+ target = None
1638
+ for t in tasks:
1639
+ if isinstance(t, dict) and t.get("id") == args.task:
1640
+ target = t
1641
+ break
1642
+ if target is None:
1643
+ sys.stderr.write(f"[plan] brief: task id '{args.task}' not found in {rel_label}\n")
1644
+ return 2
1645
+
1646
+ print(f"# Task: {target.get('id')} — {target.get('title', '')}")
1647
+ print()
1648
+ print("## Task block")
1649
+ print(json.dumps(target, indent=2))
1650
+ print()
1651
+ print("## Produces of prior-order tasks (interfaces)")
1652
+ prior_produces = []
1653
+ for t in tasks:
1654
+ if not isinstance(t, dict):
1655
+ continue
1656
+ if t.get("id") == target.get("id"):
1657
+ break
1658
+ prior_produces.extend(t.get("produces") or [])
1659
+ if prior_produces:
1660
+ for p in prior_produces:
1661
+ print(f"- {p}")
1662
+ else:
1663
+ print("(none)")
1664
+ print()
1665
+ print("## Guide pointers (paths, not content)")
1666
+ guides = target.get("guides") or []
1667
+ if guides:
1668
+ for g in guides:
1669
+ print(f"- {g}")
1670
+ else:
1671
+ print("(none)")
1672
+ print()
1673
+ print("## Verify (opaque text — orchestrator runs this out of band, NOT executed here)")
1674
+ print(target.get("verify", ""))
1675
+ return 0
1676
+
1677
+
1678
+ def cmd_orient(args):
1679
+ """SessionStart hook: emit a bounded, repo-sourced ai_docs/ orientation to
1680
+ stdout and ALWAYS return 0 (fail-open, P-TM T8) -- a session hook must never
1681
+ block the session or surface a traceback. Zero-execution (P-TM T1): reads a
1682
+ fixed hard-coded doc set, confine_under each (P-TM T3), size-caps the total
1683
+ (P-TM T2). No subprocess/eval anywhere in this call graph."""
1684
+ try:
1685
+ root = Path(args.root).resolve() if getattr(args, "root", None) else find_project_root()
1686
+ chunks = []
1687
+ total = 0
1688
+ truncated = False
1689
+ for label, rel in orient_docs():
1690
+ target = confine_under(root, rel)
1691
+ if target is None or not target.is_file():
1692
+ continue
1693
+ try:
1694
+ text = read_text(target)
1695
+ except OSError:
1696
+ continue
1697
+ remaining = ORIENT_MAX_TOTAL_CHARS - total
1698
+ if remaining <= 0:
1699
+ truncated = True
1700
+ break
1701
+ text = text[:ORIENT_PER_DOC_CHARS]
1702
+ if len(text) > remaining:
1703
+ text = text[:remaining]
1704
+ truncated = True
1705
+ chunks.append((label, text))
1706
+ total += len(text)
1707
+ if not chunks:
1708
+ return 0
1709
+ out = ["=== Agentic SDLC -- session orientation (repo-sourced context, not authored instructions) ==="]
1710
+ for label, text in chunks:
1711
+ out.append(f"\n## {label}\n{text}")
1712
+ if truncated:
1713
+ out.append("\n[orientation truncated to the size cap -- open the files directly for full content]")
1714
+ out.append("\nTriage every request (Rule Zero): L1 trivial - L2 small - L3 significant - Spike. "
1715
+ "When in doubt, pick the higher level.")
1716
+ if getattr(args, "hybrid", False):
1717
+ out.append("\n[devPNT active] Run devpnt_mcp_get_bootstrap for the Master Plan / Knowledge Layer -- "
1718
+ "the orientation above is the filesystem layer, not a bootstrap duplicate.")
1719
+ print("\n".join(out))
1720
+ return 0
1721
+ except Exception:
1722
+ return 0
1723
+
1724
+
1725
+ # --- portable checks carried by the core ------------------------------------
1726
+ # Portable means portable: a check that any distribution may expose lives HERE, so
1727
+ # three copies of the same twenty lines cannot drift apart. What a distribution
1728
+ # actually offers is its `provides` declaration, not what it happens to have copied.
1729
+ # Domain-specific machinery (mkt's budget and funnel arithmetic) stays in its own
1730
+ # entry point -- that is the line between portable and proprietary.
1731
+ # Opt-in per document via `checks:`. They may only ADD findings: a document that
1732
+ # imports one still owes its own domain everything it owed before, so importing a
1733
+ # check can never be a way to be validated less.
1734
+
1735
+ @portable_check("code.threat_model")
1736
+ def _code_threat_model(rel, meta, text):
1737
+ """The security section names a real surface, or justifies claiming none."""
1738
+ section = section_body(text, ("## Security and Threat Model", "## Security"))
1739
+ if section is None:
1740
+ return [] # the owning domain already reports a missing section; no double finding
1741
+ surfaces = ("external input", "authn", "authz", "auth", "crypto", "network",
1742
+ "personal data", "filesystem", "supply chain")
1743
+ low = section.lower()
1744
+ if any(s in low for s in surfaces):
1745
+ return []
1746
+ if "no security impact" in low or "no new security" in low:
1747
+ if len(section.split()) < 15:
1748
+ return [("warning", "'no security impact' is declared, not justified: "
1749
+ "say which surfaces you checked and why none is touched")]
1750
+ return []
1751
+ return [("warning", "no security surface named (external input, authN/authZ, crypto, "
1752
+ "network, personal data, filesystem, supply chain) and no justified "
1753
+ "claim that none is touched")]
1754
+
1755
+
1756
+ @portable_check("knowledge.sources")
1757
+ def _knowledge_sources(rel, meta, text):
1758
+ """A knowledge artifact says what it was written from AND how that was verified."""
1759
+ section = section_body(text, ("## Sources and Verification",))
1760
+ if section is None:
1761
+ return []
1762
+ findings = []
1763
+ if not re.search(r"(?m)^\s*[-*|]|\bhttps?://|\.(?:md|pdf|docx?|csv|xlsx?)\b", section):
1764
+ findings.append(("warning", "no source is named: a distillation whose origin cannot "
1765
+ "be reopened is model knowledge, not knowledge work"))
1766
+ if not re.search(r"verif|cross-check|checked against|confirmed", section, re.I):
1767
+ findings.append(("warning", "sources are listed but not verified: say how each was "
1768
+ "confirmed, or mark explicitly what could not be"))
1769
+ return findings
1770
+
1771
+
1772
+ # ------------------------------------------------------------------- migrate
1773
+
1774
+ def _migration_plan(root, src_name, dst_name):
1775
+ """(files, refs, conflicts) for a docs-root move. Reads only."""
1776
+ src = root / src_name
1777
+ dst = root / dst_name
1778
+ files, refs, conflicts = [], [], []
1779
+ if not src.is_dir():
1780
+ return None, None, None
1781
+ for p in sorted(src.rglob("*")):
1782
+ if not p.is_file():
1783
+ continue
1784
+ rel = p.relative_to(src)
1785
+ target = dst / rel
1786
+ if target.exists():
1787
+ conflicts.append(rel.as_posix())
1788
+ files.append(rel.as_posix())
1789
+ if p.suffix.lower() in (".md", ".txt", ".json", ".yml", ".yaml"):
1790
+ try:
1791
+ if f"{src_name}/" in p.read_text(encoding="utf-8", errors="replace"):
1792
+ refs.append(rel.as_posix())
1793
+ except OSError:
1794
+ pass
1795
+ return files, refs, conflicts
1796
+
1797
+
1798
+ def _external_references(root, src_name):
1799
+ """Files OUTSIDE both roots that mention the old root.
1800
+
1801
+ Reported, never edited: the protocol pointers (CLAUDE.md, AGENTS.md,
1802
+ .cursorrules) are user-authored, and a tool that rewrites them is the one thing
1803
+ `init` has refused to do since day one."""
1804
+ out = []
1805
+ for p in sorted(root.rglob("*")):
1806
+ if not p.is_file() or p.suffix.lower() not in (".md", ".txt", ".json", ".yml", ".yaml"):
1807
+ continue
1808
+ rel = p.relative_to(root)
1809
+ if rel.parts and rel.parts[0] in (src_name, ".git"):
1810
+ continue
1811
+ if any(part in SKIP_DIRS for part in rel.parts):
1812
+ continue
1813
+ try:
1814
+ if f"{src_name}/" in p.read_text(encoding="utf-8", errors="replace"):
1815
+ out.append(rel.as_posix())
1816
+ except OSError:
1817
+ pass
1818
+ return out
1819
+
1820
+
1821
+ def cmd_migrate(root, args):
1822
+ """Relocate the documentation root. Dry-run by default; never deletes.
1823
+
1824
+ Reversibility is structural, not promised: the old root is COPIED, never moved,
1825
+ so undoing the migration is deleting the new directory. Both roots stay
1826
+ readable throughout, which is what lets a team switch over one session at a
1827
+ time instead of in one jump.
1828
+ """
1829
+ src_name = args.from_dir
1830
+ dst_name = args.to_dir
1831
+ if src_name == dst_name:
1832
+ print(f"[ERROR] --from and --to are both '{src_name}': nothing to do.")
1833
+ return 1
1834
+ src = root / src_name
1835
+ if not src.is_dir():
1836
+ print(f"[ERROR] {src} not found: nothing to migrate.")
1837
+ return 1
1838
+
1839
+ files, refs, conflicts = _migration_plan(root, src_name, dst_name)
1840
+ external = _external_references(root, src_name)
1841
+
1842
+ print(f"=== migrate {src_name}/ -> {dst_name}/ ===")
1843
+ print(f" {len(files)} file(s) to copy, {len(refs)} carrying '{src_name}/' references")
1844
+ for rel in files[:20]:
1845
+ print(f" {src_name}/{rel} -> {dst_name}/{rel}")
1846
+ if len(files) > 20:
1847
+ print(f" ... and {len(files) - 20} more")
1848
+ if conflicts:
1849
+ print(f"\n[ERROR] {len(conflicts)} file(s) already exist under {dst_name}/:")
1850
+ for rel in conflicts[:10]:
1851
+ print(f" {dst_name}/{rel}")
1852
+ print(" Refusing to overwrite. Move them aside, or migrate into an empty root.")
1853
+ return 1
1854
+ if external:
1855
+ print(f"\n[note] {len(external)} file(s) OUTSIDE the docs roots mention "
1856
+ f"'{src_name}/'. They are NOT touched -- protocol pointers and READMEs are "
1857
+ "yours to edit:")
1858
+ for rel in external[:10]:
1859
+ print(f" {rel}")
1860
+
1861
+ if not args.apply:
1862
+ print("\n[dry-run] Nothing was written. Re-run with --apply to perform the copy.")
1863
+ print(" The old root is kept: this migration is undone by deleting "
1864
+ f"{dst_name}/.")
1865
+ return 0
1866
+
1867
+ if git_available(root) and git_has_changes(root, "."):
1868
+ print("\n[ERROR] the working tree has uncommitted changes. Commit or stash first: "
1869
+ "a migration you cannot diff is a migration you cannot review.")
1870
+ return 1
1871
+
1872
+ written = 0
1873
+ for rel in files:
1874
+ source = src / rel
1875
+ target = root / dst_name / rel
1876
+ target.parent.mkdir(parents=True, exist_ok=True)
1877
+ if rel in refs:
1878
+ text = source.read_text(encoding="utf-8", errors="replace")
1879
+ target.write_text(text.replace(f"{src_name}/", f"{dst_name}/"), encoding="utf-8")
1880
+ else:
1881
+ target.write_bytes(source.read_bytes())
1882
+ written += 1
1883
+ print(f"\n[ok] copied {written} file(s) into {dst_name}/. "
1884
+ f"{src_name}/ is untouched -- delete it yourself once you are satisfied.")
1885
+ print(f" Next: run `validate --docs-dir {dst_name}` and compare it with "
1886
+ f"`validate --docs-dir {src_name}`. They should say the same thing.")
1887
+ return 0
1888
+
1889
+
1890
+
1891
+ # --------------------------------------------------------------------- main
1892
+
1893
+ def main(argv=None):
1894
+ common = argparse.ArgumentParser(add_help=False)
1895
+ common.add_argument("--root", help="project root (default: walk up until a docs root is found)")
1896
+ common.add_argument("--docs-dir", dest="docs_dir",
1897
+ help="name of the documentation root (default: ai_docs; "
1898
+ "use it to reach a legacy root such as mkt_docs, "
1899
+ "or to disambiguate a half-migrated tree)")
1900
+
1901
+ strict_opt = argparse.ArgumentParser(add_help=False)
1902
+ strict_opt.add_argument("--strict", action="store_true",
1903
+ help="fail on warnings and on a missing docs root (for CI)")
1904
+
1905
+ hybrid_opt = argparse.ArgumentParser(add_help=False)
1906
+ hybrid_opt.add_argument("--hybrid", action="store_true",
1907
+ help="Hybrid/devPNT mode: audit-plan staleness is delegated to devPNT/KL; "
1908
+ "the gate also unlocks on an E-TDD shadow")
1909
+
1910
+ ap = argparse.ArgumentParser(prog="sdlc_check.py",
1911
+ description="Mechanical validator for Agentic SDLC")
1912
+ sub = ap.add_subparsers(dest="cmd", required=True)
1913
+ sub.add_parser("check", parents=[common, strict_opt, hybrid_opt],
1914
+ help="closure gate: validate + stale in one command")
1915
+ sub.add_parser("validate", parents=[common, strict_opt, hybrid_opt],
1916
+ help="verify docs-root coherence")
1917
+ sub.add_parser("index", parents=[common], help="regenerate features_history.md + ai_docs/INDEX.md")
1918
+ sub.add_parser("stale", parents=[common, hybrid_opt], help="areas modified after the last analysis")
1919
+ gp_mig = sub.add_parser("migrate", parents=[common],
1920
+ help="relocate the documentation root (dry-run by default)")
1921
+ gp_mig.add_argument("--from", dest="from_dir", required=True,
1922
+ help="current docs root name, e.g. mkt_docs")
1923
+ gp_mig.add_argument("--to", dest="to_dir", default=DEFAULT_DOCS_DIR,
1924
+ help=f"target docs root name (default: {DEFAULT_DOCS_DIR})")
1925
+ gp_mig.add_argument("--apply", action="store_true",
1926
+ help="actually copy (default is a dry run; never deletes)")
1927
+
1928
+ mp = sub.add_parser("mark", parents=[common], help="record paths as ANALYZED")
1929
+ mp.add_argument("paths", nargs="+", help="paths relative to the project root")
1930
+ gp = sub.add_parser("gate", parents=[common, hybrid_opt], help="PreToolUse hook (exit 2 = block)")
1931
+ gp.add_argument("--hook", action="store_true", help="read the hook JSON payload from stdin")
1932
+ gp.add_argument("--file", help="file path to evaluate (alternative to --hook)")
1933
+ gp.add_argument("--protected", default="", help="protected prefixes separated by ';' (e.g. \"src/auth;src/crypto\")")
1934
+
1935
+ sub.add_parser("orient", parents=[common, hybrid_opt],
1936
+ help="SessionStart hook: emit docs-root orientation to stdout (fail-open, zero-execution)")
1937
+
1938
+ pp = sub.add_parser("plan", parents=[common],
1939
+ help="Subagent Execution: validate/brief a PLAN_[feature].md (zero-execution)")
1940
+ pp_sub = pp.add_subparsers(dest="plan_cmd", required=True)
1941
+ pv = pp_sub.add_parser("validate", help="schema + confinement + ledger cross-check (exit 2 on error)")
1942
+ pv.add_argument("file", help="path to the PLAN_[feature].md file")
1943
+ pb = pp_sub.add_parser("brief", help="print a task's brief to stdout (verify text is NOT executed)")
1944
+ pb.add_argument("file", help="path to the PLAN_[feature].md file")
1945
+ pb.add_argument("--task", required=True, help="task id to brief")
1946
+
1947
+ args = ap.parse_args(argv)
1948
+
1949
+ # Resolve the documentation root ONCE, before any command runs, so every
1950
+ # surface -- paths, messages, generated headers, the gate's exempt prefix --
1951
+ # names the same thing.
1952
+ try:
1953
+ discovered, name = resolve_docs_dir(args, getattr(args, "root", None))
1954
+ except AmbiguousDocsRoot as exc:
1955
+ if args.cmd == "migrate":
1956
+ # A tree with two roots is not an obstacle to `migrate`: it is the state
1957
+ # `migrate` exists to resolve, and both names come from --from/--to, so
1958
+ # nothing is being guessed. Refusing here would make the guard block the
1959
+ # one command that ends the ambiguity.
1960
+ discovered, name = None, args.from_dir
1961
+ elif args.cmd == "orient":
1962
+ # The SessionStart hook is fail-open by contract: it must never block a
1963
+ # session, not even on a half-migrated tree. It orients on the default
1964
+ # and says so rather than exiting non-zero.
1965
+ print(f"[note] {exc}")
1966
+ discovered, name = None, DEFAULT_DOCS_DIR
1967
+ else:
1968
+ print(f"[ERROR] {exc}")
1969
+ return 1
1970
+ set_docs_dir(name)
1971
+
1972
+ if args.cmd == "gate":
1973
+ return cmd_gate(args)
1974
+ if args.cmd == "orient":
1975
+ return cmd_orient(args)
1976
+
1977
+ root = Path(args.root).resolve() if args.root else (discovered or find_project_root())
1978
+ if args.cmd == "check":
1979
+ return cmd_check(root, strict=args.strict, hybrid=args.hybrid)
1980
+ if args.cmd == "validate":
1981
+ return cmd_validate(root, strict=args.strict, hybrid=args.hybrid)
1982
+ if args.cmd == "index":
1983
+ return cmd_index(root)
1984
+ if args.cmd == "stale":
1985
+ return cmd_stale(root, hybrid=args.hybrid)
1986
+ if args.cmd == "mark":
1987
+ return cmd_mark(root, args.paths)
1988
+ if args.cmd == "migrate":
1989
+ return cmd_migrate(root, args)
1990
+ if args.cmd == "plan":
1991
+ return cmd_plan(root, args)
1992
+ return 0
1993
+
1994
+
1995
+ if __name__ == "__main__":
1996
+ sys.exit(main())