@deftai/directive-content 0.55.1 → 0.56.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.
Files changed (220) hide show
  1. package/.githooks/pre-commit +143 -0
  2. package/.githooks/pre-push +121 -0
  3. package/QUICK-START.md +13 -3
  4. package/Taskfile.yml +934 -0
  5. package/UPGRADING.md +82 -11
  6. package/events/README.md +3 -3
  7. package/package.json +5 -4
  8. package/packs/skills/skills-pack-0.1.json +22 -22
  9. package/scripts/_agents_md.py +494 -0
  10. package/scripts/_cache_fetch.py +635 -0
  11. package/scripts/_cache_quota.py +529 -0
  12. package/scripts/_cache_refresh.py +163 -0
  13. package/scripts/_cache_validate.py +209 -0
  14. package/scripts/_content_root.py +42 -0
  15. package/scripts/_doctor_state.py +277 -0
  16. package/scripts/_event_detect.py +305 -0
  17. package/scripts/_events.py +514 -0
  18. package/scripts/_lifecycle_hygiene.py +568 -0
  19. package/scripts/_pathspec.py +91 -0
  20. package/scripts/_policy_show_cli.py +266 -0
  21. package/scripts/_precutover.py +92 -0
  22. package/scripts/_project_context.py +224 -0
  23. package/scripts/_project_definition_io.py +164 -0
  24. package/scripts/_relocate_snapshot.py +209 -0
  25. package/scripts/_relocate_states.py +343 -0
  26. package/scripts/_resolve_preflight_path.py +152 -0
  27. package/scripts/_safe_subprocess.py +167 -0
  28. package/scripts/_session_start_hook.py +205 -0
  29. package/scripts/_sor_gate_diff.py +365 -0
  30. package/scripts/_stdio_utf8.py +59 -0
  31. package/scripts/_triage_bootstrap_gitignore.py +904 -0
  32. package/scripts/_triage_classify_cli.py +122 -0
  33. package/scripts/_triage_queue_cli.py +625 -0
  34. package/scripts/_triage_scope_cli.py +343 -0
  35. package/scripts/_triage_scope_drift_cli.py +121 -0
  36. package/scripts/_triage_scope_ignores.py +286 -0
  37. package/scripts/_triage_scope_milestone.py +432 -0
  38. package/scripts/_triage_scope_mutations.py +337 -0
  39. package/scripts/_triage_scope_renderers.py +207 -0
  40. package/scripts/_triage_smoketest_stages.py +674 -0
  41. package/scripts/_triage_subscribe_cli.py +140 -0
  42. package/scripts/_triage_welcome_cli.py +421 -0
  43. package/scripts/_vbrief_build.py +239 -0
  44. package/scripts/_vbrief_fidelity.py +479 -0
  45. package/scripts/_vbrief_legacy.py +589 -0
  46. package/scripts/_vbrief_reconciliation.py +883 -0
  47. package/scripts/_vbrief_routing.py +277 -0
  48. package/scripts/_vbrief_safety.py +778 -0
  49. package/scripts/_vbrief_sources.py +312 -0
  50. package/scripts/_vbrief_speckit.py +262 -0
  51. package/scripts/_vbrief_story_quality.py +353 -0
  52. package/scripts/_vbrief_validation.py +299 -0
  53. package/scripts/build_dist.py +412 -0
  54. package/scripts/cache.py +1078 -0
  55. package/scripts/cache_scanner.py +745 -0
  56. package/scripts/candidates_log.py +432 -0
  57. package/scripts/capacity_backfill.py +680 -0
  58. package/scripts/capacity_show.py +653 -0
  59. package/scripts/ci_local.py +689 -0
  60. package/scripts/code_structure_validate.py +765 -0
  61. package/scripts/codebase_default_extractor.py +495 -0
  62. package/scripts/codebase_map.py +304 -0
  63. package/scripts/codebase_map_fresh.py +104 -0
  64. package/scripts/codebase_projection_registry.py +94 -0
  65. package/scripts/codebase_provider.py +582 -0
  66. package/scripts/doctor.py +2257 -0
  67. package/scripts/framework_commands.py +505 -0
  68. package/scripts/gh_rest.py +882 -0
  69. package/scripts/github_auth_modes.py +437 -0
  70. package/scripts/github_body.py +292 -0
  71. package/scripts/ip_risk.py +531 -0
  72. package/scripts/issue_emit.py +670 -0
  73. package/scripts/issue_ingest.py +1064 -0
  74. package/scripts/migrate_preflight.py +418 -0
  75. package/scripts/migrate_vbrief.py +2677 -0
  76. package/scripts/monitor_pr.py +401 -0
  77. package/scripts/pack_migrate_lessons.py +336 -0
  78. package/scripts/pack_migrate_patterns.py +254 -0
  79. package/scripts/pack_migrate_rules.py +350 -0
  80. package/scripts/pack_migrate_skills.py +423 -0
  81. package/scripts/pack_migrate_strategies.py +311 -0
  82. package/scripts/pack_migrate_swarm_spec.py +250 -0
  83. package/scripts/pack_render.py +434 -0
  84. package/scripts/packs_slice.py +712 -0
  85. package/scripts/platform_capabilities.py +336 -0
  86. package/scripts/policy.py +2826 -0
  87. package/scripts/policy_set.py +324 -0
  88. package/scripts/pr_check_closing_keywords.py +524 -0
  89. package/scripts/pr_check_protected_issues.py +267 -0
  90. package/scripts/pr_merge_readiness.py +1004 -0
  91. package/scripts/pr_wait_mergeable.py +669 -0
  92. package/scripts/prd_render.py +159 -0
  93. package/scripts/preflight_architecture_sor.py +974 -0
  94. package/scripts/preflight_branch.py +289 -0
  95. package/scripts/preflight_cache.py +974 -0
  96. package/scripts/preflight_gh.py +721 -0
  97. package/scripts/preflight_implementation.py +272 -0
  98. package/scripts/preflight_story_start.py +838 -0
  99. package/scripts/preflight_wip_cap.py +149 -0
  100. package/scripts/probe_session.py +545 -0
  101. package/scripts/project_render.py +293 -0
  102. package/scripts/quarantine_ext.py +237 -0
  103. package/scripts/reconcile_issues.py +1442 -0
  104. package/scripts/refresh-path.ps1 +107 -0
  105. package/scripts/release.py +2030 -0
  106. package/scripts/release_e2e.py +1011 -0
  107. package/scripts/release_publish.py +486 -0
  108. package/scripts/release_rollback.py +980 -0
  109. package/scripts/relocate.py +1034 -0
  110. package/scripts/resolve_changelog_unreleased.py +667 -0
  111. package/scripts/resolve_version.py +490 -0
  112. package/scripts/resume_conditions.py +706 -0
  113. package/scripts/ritual_sentinel.py +609 -0
  114. package/scripts/roadmap_render.py +635 -0
  115. package/scripts/rule_ownership_lint.py +325 -0
  116. package/scripts/scm.py +591 -0
  117. package/scripts/scope_audit_log.py +387 -0
  118. package/scripts/scope_decompose.py +654 -0
  119. package/scripts/scope_demote.py +509 -0
  120. package/scripts/scope_lifecycle.py +1126 -0
  121. package/scripts/scope_undo.py +772 -0
  122. package/scripts/session_start.py +406 -0
  123. package/scripts/setup_ghx.py +339 -0
  124. package/scripts/setup_windows.ps1 +220 -0
  125. package/scripts/slice_audit.py +585 -0
  126. package/scripts/slice_record.py +530 -0
  127. package/scripts/slice_record_existing.py +692 -0
  128. package/scripts/slug_normalize.py +178 -0
  129. package/scripts/spec_render.py +477 -0
  130. package/scripts/spec_validate.py +238 -0
  131. package/scripts/subagent_monitor.py +658 -0
  132. package/scripts/swarm_complete_cohort.py +644 -0
  133. package/scripts/swarm_launch.py +1206 -0
  134. package/scripts/swarm_readiness.py +554 -0
  135. package/scripts/swarm_verify_review_clean.py +438 -0
  136. package/scripts/swarm_worktrees.py +497 -0
  137. package/scripts/toolchain-check.py +52 -0
  138. package/scripts/triage_actions.py +871 -0
  139. package/scripts/triage_bootstrap.py +1153 -0
  140. package/scripts/triage_bulk.py +630 -0
  141. package/scripts/triage_classify.py +932 -0
  142. package/scripts/triage_help.py +1685 -0
  143. package/scripts/triage_queue.py +1944 -0
  144. package/scripts/triage_reconcile.py +581 -0
  145. package/scripts/triage_refresh.py +643 -0
  146. package/scripts/triage_scope.py +999 -0
  147. package/scripts/triage_scope_drift.py +575 -0
  148. package/scripts/triage_smoketest.py +396 -0
  149. package/scripts/triage_subscribe.py +399 -0
  150. package/scripts/triage_summary.py +1011 -0
  151. package/scripts/triage_welcome.py +1178 -0
  152. package/scripts/ts_check_lane.py +86 -0
  153. package/scripts/validate-links.py +64 -0
  154. package/scripts/validate_strategy_output.py +212 -0
  155. package/scripts/vbrief_activate.py +228 -0
  156. package/scripts/vbrief_migrate_conformance.py +368 -0
  157. package/scripts/vbrief_reconcile_graph.py +306 -0
  158. package/scripts/vbrief_reconcile_labels.py +460 -0
  159. package/scripts/vbrief_reconcile_umbrellas.py +741 -0
  160. package/scripts/vbrief_validate.py +1195 -0
  161. package/scripts/verify-stubs.py +61 -0
  162. package/scripts/verify_capacity.py +160 -0
  163. package/scripts/verify_encoding.py +699 -0
  164. package/scripts/verify_hooks_installed.py +206 -0
  165. package/scripts/verify_investigation.py +360 -0
  166. package/scripts/verify_judgment_gates.py +827 -0
  167. package/scripts/verify_no_task_runtime.py +171 -0
  168. package/scripts/verify_scm_boundary.py +509 -0
  169. package/scripts/verify_session_ritual.py +389 -0
  170. package/scripts/verify_tools.py +426 -0
  171. package/scripts/verify_vbrief_conformance.py +478 -0
  172. package/skills/deft-directive-swarm/SKILL.md +7 -26
  173. package/skills/deft-directive-sync/SKILL.md +1 -1
  174. package/tasks/architecture.yml +13 -0
  175. package/tasks/cache.yml +69 -0
  176. package/tasks/capacity.yml +38 -0
  177. package/tasks/change.yml +46 -0
  178. package/tasks/changelog.yml +24 -0
  179. package/tasks/ci.yml +49 -0
  180. package/tasks/codebase.yml +47 -0
  181. package/tasks/commit.yml +30 -0
  182. package/tasks/core.yml +126 -0
  183. package/tasks/deployments.yml +54 -0
  184. package/tasks/framework.yml +74 -0
  185. package/tasks/install.yml +60 -0
  186. package/tasks/issue.yml +50 -0
  187. package/tasks/migrate.yml +73 -0
  188. package/tasks/packs.yml +92 -0
  189. package/tasks/policy.yml +75 -0
  190. package/tasks/pr.yml +89 -0
  191. package/tasks/prd.yml +39 -0
  192. package/tasks/project.yml +27 -0
  193. package/tasks/reconcile.yml +32 -0
  194. package/tasks/relocate.yml +56 -0
  195. package/tasks/roadmap.yml +28 -0
  196. package/tasks/scm.yml +126 -0
  197. package/tasks/scope-undo.yml +36 -0
  198. package/tasks/scope.yml +141 -0
  199. package/tasks/session.yml +19 -0
  200. package/tasks/setup.yml +37 -0
  201. package/tasks/slice.yml +69 -0
  202. package/tasks/spec.yml +41 -0
  203. package/tasks/swarm.yml +85 -0
  204. package/tasks/toolchain.yml +13 -0
  205. package/tasks/triage-actions.yml +94 -0
  206. package/tasks/triage-bootstrap.yml +43 -0
  207. package/tasks/triage-bulk.yml +75 -0
  208. package/tasks/triage-classify.yml +30 -0
  209. package/tasks/triage-queue.yml +50 -0
  210. package/tasks/triage-reconcile.yml +29 -0
  211. package/tasks/triage-scope-drift.yml +29 -0
  212. package/tasks/triage-scope.yml +31 -0
  213. package/tasks/triage-smoketest.yml +33 -0
  214. package/tasks/triage-subscribe.yml +36 -0
  215. package/tasks/triage-summary.yml +29 -0
  216. package/tasks/triage-welcome.yml +32 -0
  217. package/tasks/ts.yml +328 -0
  218. package/tasks/vbrief.yml +206 -0
  219. package/tasks/verify.yml +292 -0
  220. package/templates/agents-entry.md +2 -2
@@ -0,0 +1,206 @@
1
+ #!/usr/bin/env python3
2
+ """verify_hooks_installed.py -- honest health check for the deft git hooks (#1463 / #747).
3
+
4
+ Pure stdlib, cross-platform. Invoked from ``task verify:hooks-installed``.
5
+
6
+ Before #1463 the ``verify:hooks-installed`` task only asserted
7
+ ``core.hooksPath == .githooks``. In a vendored consumer (framework at
8
+ ``.deft/core/``) that produced a FALSE GREEN: ``core.hooksPath`` was set but the
9
+ hooks directory did not exist at the repo root and the gate scripts the hooks
10
+ reference (``preflight_branch.py`` / ``verify_encoding.py`` / ``preflight_gh.py``)
11
+ could not be resolved, so the branch / encoding / destructive-gh-verb gates were
12
+ silently inert while the check reported success.
13
+
14
+ This gate now asserts the hooks are not merely *configured* but *functional*:
15
+
16
+ 1. ``core.hooksPath`` is set (non-empty).
17
+ 2. The resolved hooks directory exists.
18
+ 3. The ``pre-commit`` and ``pre-push`` hooks are present in it.
19
+ 4. On POSIX, those hooks are EXECUTABLE -- git silently skips a non-executable
20
+ hook, so a present-but-mode-100644 hook is the #1477 inert-gate class (the
21
+ exec bit is meaningless on Windows, so the check is POSIX-only).
22
+ 5. The gate scripts the hooks reference resolve in THIS layout -- own-repo
23
+ ``scripts/``, canonical vendored ``.deft/core/scripts/``, or legacy
24
+ ``deft/scripts/``.
25
+
26
+ Exit codes (three-state, mirrors ``scripts/preflight_branch.py`` and friends):
27
+
28
+ - ``0`` -- hooks installed AND functional.
29
+ - ``1`` -- hooks NOT installed, OR wired-but-non-functional (the #1463
30
+ false-green class). The message names the exact missing piece.
31
+ - ``2`` -- config error: the project root does not exist, or ``git`` is not on
32
+ PATH so ``core.hooksPath`` cannot be read.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import os
39
+ import subprocess
40
+ import sys
41
+ from pathlib import Path
42
+
43
+ #: Hook scripts the framework ships and the installer wires (#1463). Both must
44
+ #: be present in the resolved hooks directory for the gate to pass.
45
+ REQUIRED_HOOKS = ("pre-commit", "pre-push")
46
+
47
+ #: Gate scripts the hooks dispatch to. ``preflight_branch.py`` is the probe file
48
+ #: used to LOCATE the scripts dir (it must exist in every layout); all three are
49
+ #: then asserted present so a partial payload cannot pass the check.
50
+ SCRIPTS_PROBE = "preflight_branch.py"
51
+ GATE_SCRIPTS = ("preflight_branch.py", "verify_encoding.py", "preflight_gh.py")
52
+
53
+ #: Candidate scripts directories, in the same priority order the layout-aware
54
+ #: hooks (`.githooks/pre-commit`) probe: own-repo, canonical vendored, legacy
55
+ #: vendored. Each is relative to the project root.
56
+ SCRIPTS_DIR_CANDIDATES = ("scripts", ".deft/core/scripts", "deft/scripts")
57
+
58
+
59
+ def _configured_hooks_path(project_root: Path) -> tuple[str | None, str | None]:
60
+ """Return ``(hooks_path, error)`` for the repo at ``project_root``.
61
+
62
+ ``hooks_path`` is ``None`` when ``core.hooksPath`` is unset (``git config
63
+ --get`` exits 1). ``error`` is set ONLY when git itself is unavailable, so
64
+ the caller can map that to the config-error exit (2) rather than the
65
+ not-installed exit (1).
66
+ """
67
+ try:
68
+ proc = subprocess.run(
69
+ ["git", "-C", str(project_root), "config", "--get", "core.hooksPath"],
70
+ capture_output=True,
71
+ text=True,
72
+ encoding="utf-8",
73
+ errors="replace",
74
+ check=False,
75
+ )
76
+ except FileNotFoundError:
77
+ return None, "git executable not found on PATH"
78
+ if proc.returncode != 0:
79
+ # `git config --get` exits 1 when the key is unset -- not an error here.
80
+ return None, None
81
+ value = proc.stdout.strip()
82
+ return (value or None), None
83
+
84
+
85
+ def _resolve_scripts_dir(project_root: Path) -> Path | None:
86
+ """Return the first candidate scripts dir containing the probe script."""
87
+ for rel in SCRIPTS_DIR_CANDIDATES:
88
+ candidate = project_root / Path(rel)
89
+ if (candidate / SCRIPTS_PROBE).is_file():
90
+ return candidate
91
+ return None
92
+
93
+
94
+ def evaluate(project_root: Path) -> tuple[int, str]:
95
+ """Pure function returning ``(exit_code, human_message)``.
96
+
97
+ Separated from :func:`main` so tests can drive every state directly.
98
+ """
99
+ if not project_root.is_dir():
100
+ return 2, (
101
+ f"❌ deft hooks: project root {project_root} does not exist "
102
+ "(config error)."
103
+ )
104
+
105
+ hooks_path, git_err = _configured_hooks_path(project_root)
106
+ if git_err:
107
+ return 2, (
108
+ f"❌ deft hooks: cannot read core.hooksPath -- {git_err}.\n"
109
+ " Recovery: install git (https://git-scm.com/) so the check can run."
110
+ )
111
+ if not hooks_path:
112
+ return 1, (
113
+ "❌ deft hooks not installed: core.hooksPath is unset.\n"
114
+ " Recovery: run `task setup` (or re-run the deft installer)."
115
+ )
116
+
117
+ hooks_dir = Path(hooks_path)
118
+ if not hooks_dir.is_absolute():
119
+ hooks_dir = project_root / hooks_path
120
+
121
+ if not hooks_dir.is_dir():
122
+ return 1, (
123
+ f"❌ deft hooks wired but NON-FUNCTIONAL: core.hooksPath={hooks_path} "
124
+ f"but the directory {hooks_dir} does not exist (#1463 false-green).\n"
125
+ " Recovery: re-run the deft installer / `task setup` to deposit the "
126
+ "hooks."
127
+ )
128
+
129
+ missing_hooks = [h for h in REQUIRED_HOOKS if not (hooks_dir / h).is_file()]
130
+ if missing_hooks:
131
+ return 1, (
132
+ f"❌ deft hooks wired but NON-FUNCTIONAL: {hooks_dir} is missing "
133
+ f"{', '.join(missing_hooks)} (#1463 false-green).\n"
134
+ " Recovery: re-run the deft installer / `task setup`."
135
+ )
136
+
137
+ # On POSIX the hooks MUST be executable or git silently skips them, leaving
138
+ # the branch / encoding / destructive-gh-verb gates inert (#1477). The exec
139
+ # bit does not exist on Windows, so this check is POSIX-only.
140
+ if os.name == "posix":
141
+ non_exec = [h for h in REQUIRED_HOOKS if not os.access(hooks_dir / h, os.X_OK)]
142
+ if non_exec:
143
+ return 1, (
144
+ f"❌ deft hooks wired but NON-FUNCTIONAL: {hooks_dir} hook(s) "
145
+ f"{', '.join(non_exec)} are not executable (git mode is not "
146
+ "100755); git silently skips non-executable hooks on Unix "
147
+ "(#1477).\n"
148
+ " Recovery: re-run the deft installer / `task setup`, or "
149
+ "`chmod +x .githooks/pre-commit .githooks/pre-push`."
150
+ )
151
+
152
+ scripts_dir = _resolve_scripts_dir(project_root)
153
+ if scripts_dir is None:
154
+ return 1, (
155
+ "❌ deft hooks wired but NON-FUNCTIONAL: the gate scripts cannot be "
156
+ "resolved.\n"
157
+ f" Looked for {SCRIPTS_PROBE} under: "
158
+ f"{', '.join(SCRIPTS_DIR_CANDIDATES)} (relative to {project_root}).\n"
159
+ " Recovery: re-run the deft installer so the payload is present."
160
+ )
161
+
162
+ missing_scripts = [s for s in GATE_SCRIPTS if not (scripts_dir / s).is_file()]
163
+ if missing_scripts:
164
+ return 1, (
165
+ f"❌ deft hooks wired but NON-FUNCTIONAL: {scripts_dir} is missing "
166
+ f"gate script(s): {', '.join(missing_scripts)} (#1463 false-green).\n"
167
+ " Recovery: re-run the deft installer to restore the payload."
168
+ )
169
+
170
+ return 0, (
171
+ f"✓ deft hooks installed and functional: core.hooksPath={hooks_path}, "
172
+ f"hooks {', '.join(REQUIRED_HOOKS)} present, gate scripts resolve under "
173
+ f"{scripts_dir}."
174
+ )
175
+
176
+
177
+ def main(argv: list[str] | None = None) -> int:
178
+ parser = argparse.ArgumentParser(
179
+ description=(
180
+ "Assert the deft git hooks are installed AND functional (#1463). "
181
+ "Three-state exit: 0 ok / 1 not-installed-or-non-functional / 2 "
182
+ "config error."
183
+ )
184
+ )
185
+ parser.add_argument(
186
+ "--project-root",
187
+ default=".",
188
+ help="project root to inspect (default: current directory).",
189
+ )
190
+ parser.add_argument(
191
+ "--quiet",
192
+ action="store_true",
193
+ help="suppress the human-readable message (exit code only).",
194
+ )
195
+ args = parser.parse_args(argv)
196
+
197
+ project_root = Path(args.project_root).resolve()
198
+ code, message = evaluate(project_root)
199
+ if not args.quiet:
200
+ stream = sys.stdout if code == 0 else sys.stderr
201
+ print(message, file=stream)
202
+ return code
203
+
204
+
205
+ if __name__ == "__main__":
206
+ sys.exit(main())
@@ -0,0 +1,360 @@
1
+ #!/usr/bin/env python3
2
+ """verify_investigation.py -- deterministic validator for forensic investigation ledgers (#1621).
3
+
4
+ Promotes the prose validator from the vendored ``forensic-research`` reference
5
+ design (``docs/reference/forensic-research/references/investigation-profile.md``
6
+ section "Validator pass") into a deterministic gate. An investigation ledger is
7
+ the thin vBRIEF 0.6 profile (``forensic-research-v1``) written under
8
+ ``.tmp/investigations/<id>/investigation.vbrief.json``; this gate is the
9
+ "before Wave 5 / before any causal chat" close check.
10
+
11
+ Run it against a specific ledger -- it is intentionally NOT part of the
12
+ ``task check`` aggregate (like ``verify:story-ready``), because a generic
13
+ ``task check`` run has no investigation path to supply:
14
+
15
+ task verify:investigation -- --ledger .tmp/investigations/<id>/investigation.vbrief.json
16
+ uv run python scripts/verify_investigation.py --ledger <path> [--json]
17
+
18
+ Hard failures (the close is refused -- exit 1):
19
+
20
+ - ``HF-WAVES`` -- ``metadata.x-investigation.wavesCompleted`` is missing any of
21
+ waves 1-4 set to ``true`` (falsifier + red-team skipped -- the #1 forensic
22
+ discipline failure).
23
+ - ``HF-STATUS`` -- ``plan.status`` is still ``running`` (cannot close an
24
+ investigation that is still in flight).
25
+ - ``HF-FAILED-CLAIM`` -- a claim with ``status: failed`` is missing
26
+ ``ruledOutReason`` or ``evidenceRefs`` (proof-required disproval).
27
+ - ``HF-COMPLETED-CLAIM`` -- a claim with ``status: completed`` is missing
28
+ ``evidenceRefs`` (evidence before narrative).
29
+ - ``HF-DANGLING-EV`` -- a claim cites an ``EV-*`` ref that is absent from
30
+ ``plan.references``.
31
+ - ``HF-BRANCH-NO-EDGE`` -- a branch with ``status: failed`` has no
32
+ ``invalidates`` edge targeting it (a branch is ruled out only by a falsified
33
+ child claim).
34
+
35
+ Soft warnings (printed, do not fail -- the close proceeds):
36
+
37
+ - ``SW-BLOCKED`` -- a live branch carries ``blocked`` (unknown) claims.
38
+ - ``SW-MULTI-SURVIVOR`` -- more than one branch is ``completed`` (multiple
39
+ surviving theories).
40
+
41
+ Exit codes (three-state, mirrors ``scripts/verify_encoding.py``):
42
+
43
+ - ``0`` -- ledger passes the validator (close-ready / clean).
44
+ - ``1`` -- one or more hard failures (close refused).
45
+ - ``2`` -- config error: ledger path missing / unreadable, malformed JSON,
46
+ missing required keys, or not a ``forensic-research`` profile ledger.
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ import argparse
52
+ import json
53
+ import sys
54
+ from dataclasses import dataclass, field
55
+ from pathlib import Path
56
+ from typing import Any
57
+
58
+ REQUIRED_WAVES = ("1", "2", "3", "4")
59
+
60
+
61
+ @dataclass
62
+ class Finding:
63
+ code: str
64
+ message: str
65
+
66
+
67
+ @dataclass
68
+ class ValidationResult:
69
+ hard_failures: list[Finding] = field(default_factory=list)
70
+ soft_warnings: list[Finding] = field(default_factory=list)
71
+
72
+ @property
73
+ def ok(self) -> bool:
74
+ return not self.hard_failures
75
+
76
+
77
+ class LedgerConfigError(Exception):
78
+ """Raised when the ledger cannot be parsed into a validatable shape."""
79
+
80
+
81
+ def _iter_claims(items: list[dict[str, Any]]) -> list[tuple[dict[str, Any], dict[str, Any] | None]]:
82
+ """Flatten branch -> claim items.
83
+
84
+ Returns a list of ``(claim, parent_branch)`` tuples for every nested item
85
+ (depth >= 1). Top-level items are treated as branches; their children are
86
+ claims. Deeper nesting is flattened with the nearest top-level branch as
87
+ parent.
88
+ """
89
+ out: list[tuple[dict[str, Any], dict[str, Any] | None]] = []
90
+
91
+ def walk(node: dict[str, Any], branch: dict[str, Any] | None) -> None:
92
+ for child in node.get("items", []) or []:
93
+ if not isinstance(child, dict):
94
+ continue
95
+ out.append((child, branch))
96
+ walk(child, branch)
97
+
98
+ for top in items:
99
+ if not isinstance(top, dict):
100
+ continue
101
+ walk(top, top)
102
+ return out
103
+
104
+
105
+ def _claim_meta(claim: dict[str, Any]) -> dict[str, Any]:
106
+ meta = claim.get("metadata") or {}
107
+ xclaim = meta.get("x-claim") or {}
108
+ return xclaim if isinstance(xclaim, dict) else {}
109
+
110
+
111
+ def _evidence_refs(xclaim: dict[str, Any]) -> list[str]:
112
+ refs = xclaim.get("evidenceRefs") or []
113
+ return [str(r) for r in refs] if isinstance(refs, list) else []
114
+
115
+
116
+ def load_ledger(path: Path) -> dict[str, Any]:
117
+ """Load + structurally validate a ledger file. Raises LedgerConfigError."""
118
+ if not path.is_file():
119
+ raise LedgerConfigError(f"ledger not found: {path}")
120
+ try:
121
+ raw = path.read_text(encoding="utf-8")
122
+ except OSError as exc: # pragma: no cover - unreadable file
123
+ raise LedgerConfigError(f"ledger unreadable: {path}: {exc}") from exc
124
+ try:
125
+ data = json.loads(raw)
126
+ except json.JSONDecodeError as exc:
127
+ raise LedgerConfigError(f"ledger is not valid JSON: {path}: {exc}") from exc
128
+ if not isinstance(data, dict):
129
+ raise LedgerConfigError(f"ledger root is not an object: {path}")
130
+ plan = data.get("plan")
131
+ if not isinstance(plan, dict):
132
+ raise LedgerConfigError(f"ledger missing 'plan' object: {path}")
133
+ if not isinstance(plan.get("items"), list):
134
+ raise LedgerConfigError(f"ledger missing 'plan.items' array: {path}")
135
+ meta = plan.get("metadata") or {}
136
+ xinv = meta.get("x-investigation") or {}
137
+ profile = xinv.get("profile") if isinstance(xinv, dict) else None
138
+ if profile != "forensic-research-v1":
139
+ raise LedgerConfigError(
140
+ f"ledger is not a forensic-research-v1 profile (got {profile!r}): {path}"
141
+ )
142
+ return data
143
+
144
+
145
+ def validate_ledger(data: dict[str, Any]) -> ValidationResult:
146
+ """Apply the validator checklist to an already-loaded ledger dict."""
147
+ result = ValidationResult()
148
+ plan = data["plan"]
149
+ items = plan["items"]
150
+ meta = plan.get("metadata") or {}
151
+ xinv = meta.get("x-investigation") or {}
152
+
153
+ # HF-WAVES: falsifier + red-team must not be skipped.
154
+ waves = xinv.get("wavesCompleted") or {}
155
+ if not isinstance(waves, dict):
156
+ waves = {}
157
+ missing = [w for w in REQUIRED_WAVES if waves.get(w) is not True]
158
+ if missing:
159
+ result.hard_failures.append(
160
+ Finding(
161
+ "HF-WAVES",
162
+ f"wavesCompleted is missing {missing} -- falsifier (3) + "
163
+ "red-team (4) MUST run before close",
164
+ )
165
+ )
166
+
167
+ # HF-STATUS: cannot close a running investigation.
168
+ status = plan.get("status")
169
+ if status == "running":
170
+ result.hard_failures.append(
171
+ Finding(
172
+ "HF-STATUS",
173
+ "plan.status is still 'running' -- set it to completed/failed "
174
+ "before close",
175
+ )
176
+ )
177
+
178
+ # Build the reference id set for dangling-EV detection. Only the
179
+ # structured `id` counts -- admitting `title` would let a claim cite a
180
+ # reference's human-readable label and bypass HF-DANGLING-EV (Greptile P1).
181
+ ref_ids: set[str] = set()
182
+ for ref in plan.get("references", []) or []:
183
+ if isinstance(ref, dict):
184
+ val = ref.get("id")
185
+ if isinstance(val, str):
186
+ ref_ids.add(val)
187
+
188
+ claims = _iter_claims(items)
189
+ for claim, _branch in claims:
190
+ cid = claim.get("id", "<no-id>")
191
+ cstatus = claim.get("status")
192
+ # Only leaf claims (no children) carry evidence obligations.
193
+ is_branch = bool(claim.get("items"))
194
+ if is_branch:
195
+ continue
196
+ xclaim = _claim_meta(claim)
197
+ refs = _evidence_refs(xclaim)
198
+
199
+ if cstatus == "failed":
200
+ if not xclaim.get("ruledOutReason") or not refs:
201
+ result.hard_failures.append(
202
+ Finding(
203
+ "HF-FAILED-CLAIM",
204
+ f"claim {cid} is 'failed' but missing ruledOutReason "
205
+ "and/or evidenceRefs (proof-required disproval)",
206
+ )
207
+ )
208
+ elif cstatus == "completed":
209
+ if not refs:
210
+ result.hard_failures.append(
211
+ Finding(
212
+ "HF-COMPLETED-CLAIM",
213
+ f"claim {cid} is 'completed' but cites no evidenceRefs "
214
+ "(evidence before narrative)",
215
+ )
216
+ )
217
+ elif cstatus == "blocked":
218
+ result.soft_warnings.append(
219
+ Finding(
220
+ "SW-BLOCKED",
221
+ f"claim {cid} is 'blocked' (unknown) -- residual "
222
+ "uncertainty on a live branch",
223
+ )
224
+ )
225
+
226
+ # HF-DANGLING-EV: every cited ref must exist in plan.references.
227
+ for ref in refs:
228
+ if ref not in ref_ids:
229
+ result.hard_failures.append(
230
+ Finding(
231
+ "HF-DANGLING-EV",
232
+ f"claim {cid} cites evidence ref {ref!r} not present "
233
+ "in plan.references",
234
+ )
235
+ )
236
+
237
+ # HF-BRANCH-NO-EDGE: a failed branch needs an invalidates edge.
238
+ invalidates_targets: set[str] = set()
239
+ for edge in plan.get("edges", []) or []:
240
+ if isinstance(edge, dict) and edge.get("type") == "invalidates":
241
+ tgt = edge.get("to")
242
+ if isinstance(tgt, str):
243
+ invalidates_targets.add(tgt)
244
+
245
+ completed_branches = 0
246
+ for top in items:
247
+ if not isinstance(top, dict):
248
+ continue
249
+ bid = top.get("id", "<no-id>")
250
+ bstatus = top.get("status")
251
+ if bstatus == "failed" and bid not in invalidates_targets:
252
+ result.hard_failures.append(
253
+ Finding(
254
+ "HF-BRANCH-NO-EDGE",
255
+ f"branch {bid} is 'failed' but has no invalidates edge -- "
256
+ "a branch is ruled out only by a falsified child claim",
257
+ )
258
+ )
259
+ if bstatus == "completed":
260
+ completed_branches += 1
261
+
262
+ if completed_branches > 1:
263
+ result.soft_warnings.append(
264
+ Finding(
265
+ "SW-MULTI-SURVIVOR",
266
+ f"{completed_branches} branches are 'completed' -- multiple "
267
+ "surviving theories; note in Outcome",
268
+ )
269
+ )
270
+
271
+ return result
272
+
273
+
274
+ def _build_parser() -> argparse.ArgumentParser:
275
+ parser = argparse.ArgumentParser(
276
+ description="Validate a forensic investigation ledger (#1621).",
277
+ )
278
+ parser.add_argument(
279
+ "--ledger",
280
+ dest="ledger",
281
+ help="Path to investigation.vbrief.json (the forensic-research-v1 ledger).",
282
+ )
283
+ parser.add_argument(
284
+ "ledger_positional",
285
+ nargs="?",
286
+ help="Positional ledger path (alternative to --ledger).",
287
+ )
288
+ parser.add_argument(
289
+ "--project-root",
290
+ default=".",
291
+ help="Project root for resolving a relative --ledger path.",
292
+ )
293
+ parser.add_argument(
294
+ "--json",
295
+ action="store_true",
296
+ help="Emit a machine-readable JSON result.",
297
+ )
298
+ return parser
299
+
300
+
301
+ def main(argv: list[str] | None = None) -> int:
302
+ parser = _build_parser()
303
+ args = parser.parse_args(argv)
304
+
305
+ ledger_arg = args.ledger or args.ledger_positional
306
+ if not ledger_arg:
307
+ print("config error: no ledger path given (--ledger <path>)", file=sys.stderr)
308
+ return 2
309
+
310
+ path = Path(ledger_arg)
311
+ if not path.is_absolute():
312
+ path = (Path(args.project_root) / path).resolve()
313
+
314
+ try:
315
+ data = load_ledger(path)
316
+ except LedgerConfigError as exc:
317
+ if args.json:
318
+ print(json.dumps({"exit": 2, "error": str(exc)}))
319
+ else:
320
+ print(f"config error: {exc}", file=sys.stderr)
321
+ return 2
322
+
323
+ result = validate_ledger(data)
324
+
325
+ if args.json:
326
+ print(
327
+ json.dumps(
328
+ {
329
+ "exit": 0 if result.ok else 1,
330
+ "hard_failures": [
331
+ {"code": f.code, "message": f.message}
332
+ for f in result.hard_failures
333
+ ],
334
+ "soft_warnings": [
335
+ {"code": f.code, "message": f.message}
336
+ for f in result.soft_warnings
337
+ ],
338
+ }
339
+ )
340
+ )
341
+ return 0 if result.ok else 1
342
+
343
+ for warn in result.soft_warnings:
344
+ print(f"warning [{warn.code}]: {warn.message}")
345
+
346
+ if result.ok:
347
+ print(
348
+ f"OK investigation ledger passes the validator: {path} "
349
+ f"({len(result.soft_warnings)} soft warning(s))"
350
+ )
351
+ return 0
352
+
353
+ print(f"investigation ledger NOT close-ready: {path}", file=sys.stderr)
354
+ for fail in result.hard_failures:
355
+ print(f" hard failure [{fail.code}]: {fail.message}", file=sys.stderr)
356
+ return 1
357
+
358
+
359
+ if __name__ == "__main__":
360
+ raise SystemExit(main())