@deftai/directive-content 0.58.0 → 0.60.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 (187) hide show
  1. package/.githooks/pre-push +10 -9
  2. package/Taskfile.yml +57 -67
  3. package/UPGRADING.md +1 -1
  4. package/docs/assets/directive-lifecycle-diagram.png +0 -0
  5. package/docs/directive-lifecycle.md +73 -0
  6. package/docs/getting-started.md +5 -1
  7. package/package.json +3 -3
  8. package/packs/rules/rules-pack-0.1.json +3 -3
  9. package/packs/skills/skills-pack-0.1.json +22 -22
  10. package/scm/github.md +20 -2
  11. package/tasks/change.yml +16 -31
  12. package/tasks/ci.yml +8 -0
  13. package/tasks/commit.yml +12 -19
  14. package/tasks/core.yml +10 -0
  15. package/tasks/engine.yml +42 -0
  16. package/tasks/framework.yml +3 -0
  17. package/tasks/install.yml +20 -19
  18. package/tasks/migrate.yml +26 -15
  19. package/tasks/project.yml +16 -0
  20. package/tasks/relocate.yml +18 -48
  21. package/tasks/toolchain.yml +15 -5
  22. package/tasks/vbrief.yml +4 -3
  23. package/tasks/verify.yml +12 -14
  24. package/templates/agents-entry.md +1 -2
  25. package/scripts/_agents_md.py +0 -494
  26. package/scripts/_cache_fetch.py +0 -635
  27. package/scripts/_cache_quota.py +0 -529
  28. package/scripts/_cache_refresh.py +0 -163
  29. package/scripts/_cache_validate.py +0 -209
  30. package/scripts/_content_root.py +0 -42
  31. package/scripts/_doctor_state.py +0 -277
  32. package/scripts/_event_detect.py +0 -305
  33. package/scripts/_events.py +0 -514
  34. package/scripts/_lifecycle_hygiene.py +0 -568
  35. package/scripts/_pathspec.py +0 -91
  36. package/scripts/_policy_show_cli.py +0 -266
  37. package/scripts/_precutover.py +0 -92
  38. package/scripts/_project_context.py +0 -224
  39. package/scripts/_project_definition_io.py +0 -164
  40. package/scripts/_relocate_snapshot.py +0 -209
  41. package/scripts/_relocate_states.py +0 -343
  42. package/scripts/_resolve_preflight_path.py +0 -152
  43. package/scripts/_safe_subprocess.py +0 -167
  44. package/scripts/_session_start_hook.py +0 -205
  45. package/scripts/_sor_gate_diff.py +0 -365
  46. package/scripts/_stdio_utf8.py +0 -59
  47. package/scripts/_triage_bootstrap_gitignore.py +0 -904
  48. package/scripts/_triage_classify_cli.py +0 -122
  49. package/scripts/_triage_queue_cli.py +0 -625
  50. package/scripts/_triage_scope_cli.py +0 -343
  51. package/scripts/_triage_scope_drift_cli.py +0 -121
  52. package/scripts/_triage_scope_ignores.py +0 -286
  53. package/scripts/_triage_scope_milestone.py +0 -432
  54. package/scripts/_triage_scope_mutations.py +0 -337
  55. package/scripts/_triage_scope_renderers.py +0 -207
  56. package/scripts/_triage_smoketest_stages.py +0 -674
  57. package/scripts/_triage_subscribe_cli.py +0 -140
  58. package/scripts/_triage_welcome_cli.py +0 -421
  59. package/scripts/_vbrief_build.py +0 -239
  60. package/scripts/_vbrief_fidelity.py +0 -479
  61. package/scripts/_vbrief_legacy.py +0 -589
  62. package/scripts/_vbrief_reconciliation.py +0 -883
  63. package/scripts/_vbrief_routing.py +0 -277
  64. package/scripts/_vbrief_safety.py +0 -778
  65. package/scripts/_vbrief_sources.py +0 -312
  66. package/scripts/_vbrief_speckit.py +0 -262
  67. package/scripts/_vbrief_story_quality.py +0 -353
  68. package/scripts/_vbrief_validation.py +0 -299
  69. package/scripts/build_dist.py +0 -412
  70. package/scripts/cache.py +0 -1078
  71. package/scripts/cache_scanner.py +0 -745
  72. package/scripts/candidates_log.py +0 -432
  73. package/scripts/capacity_backfill.py +0 -680
  74. package/scripts/capacity_show.py +0 -653
  75. package/scripts/ci_local.py +0 -689
  76. package/scripts/code_structure_validate.py +0 -765
  77. package/scripts/codebase_default_extractor.py +0 -495
  78. package/scripts/codebase_map.py +0 -304
  79. package/scripts/codebase_map_fresh.py +0 -104
  80. package/scripts/codebase_projection_registry.py +0 -94
  81. package/scripts/codebase_provider.py +0 -582
  82. package/scripts/doctor.py +0 -2551
  83. package/scripts/framework_commands.py +0 -505
  84. package/scripts/gh_rest.py +0 -882
  85. package/scripts/github_auth_modes.py +0 -437
  86. package/scripts/github_body.py +0 -292
  87. package/scripts/ip_risk.py +0 -531
  88. package/scripts/issue_emit.py +0 -670
  89. package/scripts/issue_ingest.py +0 -1064
  90. package/scripts/migrate_preflight.py +0 -418
  91. package/scripts/migrate_vbrief.py +0 -2677
  92. package/scripts/monitor_pr.py +0 -401
  93. package/scripts/pack_migrate_lessons.py +0 -336
  94. package/scripts/pack_migrate_patterns.py +0 -254
  95. package/scripts/pack_migrate_rules.py +0 -350
  96. package/scripts/pack_migrate_skills.py +0 -423
  97. package/scripts/pack_migrate_strategies.py +0 -311
  98. package/scripts/pack_migrate_swarm_spec.py +0 -250
  99. package/scripts/pack_render.py +0 -434
  100. package/scripts/packs_slice.py +0 -712
  101. package/scripts/platform_capabilities.py +0 -336
  102. package/scripts/policy.py +0 -2826
  103. package/scripts/policy_set.py +0 -324
  104. package/scripts/pr_check_closing_keywords.py +0 -524
  105. package/scripts/pr_check_protected_issues.py +0 -267
  106. package/scripts/pr_merge_readiness.py +0 -1004
  107. package/scripts/pr_wait_mergeable.py +0 -669
  108. package/scripts/prd_render.py +0 -159
  109. package/scripts/preflight_architecture_sor.py +0 -974
  110. package/scripts/preflight_branch.py +0 -289
  111. package/scripts/preflight_cache.py +0 -974
  112. package/scripts/preflight_gh.py +0 -721
  113. package/scripts/preflight_implementation.py +0 -272
  114. package/scripts/preflight_story_start.py +0 -838
  115. package/scripts/preflight_wip_cap.py +0 -149
  116. package/scripts/probe_session.py +0 -545
  117. package/scripts/project_render.py +0 -293
  118. package/scripts/quarantine_ext.py +0 -237
  119. package/scripts/reconcile_issues.py +0 -1442
  120. package/scripts/refresh-path.ps1 +0 -107
  121. package/scripts/release.py +0 -2030
  122. package/scripts/release_e2e.py +0 -1011
  123. package/scripts/release_publish.py +0 -486
  124. package/scripts/release_rollback.py +0 -980
  125. package/scripts/relocate.py +0 -1034
  126. package/scripts/resolve_changelog_unreleased.py +0 -667
  127. package/scripts/resolve_version.py +0 -490
  128. package/scripts/resume_conditions.py +0 -706
  129. package/scripts/ritual_sentinel.py +0 -609
  130. package/scripts/roadmap_render.py +0 -635
  131. package/scripts/rule_ownership_lint.py +0 -325
  132. package/scripts/scm.py +0 -591
  133. package/scripts/scope_audit_log.py +0 -387
  134. package/scripts/scope_decompose.py +0 -654
  135. package/scripts/scope_demote.py +0 -509
  136. package/scripts/scope_lifecycle.py +0 -1126
  137. package/scripts/scope_undo.py +0 -772
  138. package/scripts/session_start.py +0 -406
  139. package/scripts/setup_ghx.py +0 -339
  140. package/scripts/setup_windows.ps1 +0 -220
  141. package/scripts/slice_audit.py +0 -585
  142. package/scripts/slice_record.py +0 -530
  143. package/scripts/slice_record_existing.py +0 -692
  144. package/scripts/slug_normalize.py +0 -178
  145. package/scripts/spec_render.py +0 -477
  146. package/scripts/spec_validate.py +0 -238
  147. package/scripts/subagent_monitor.py +0 -658
  148. package/scripts/swarm_complete_cohort.py +0 -644
  149. package/scripts/swarm_launch.py +0 -1206
  150. package/scripts/swarm_readiness.py +0 -554
  151. package/scripts/swarm_verify_review_clean.py +0 -438
  152. package/scripts/swarm_worktrees.py +0 -497
  153. package/scripts/toolchain-check.py +0 -52
  154. package/scripts/triage_actions.py +0 -871
  155. package/scripts/triage_bootstrap.py +0 -1153
  156. package/scripts/triage_bulk.py +0 -630
  157. package/scripts/triage_classify.py +0 -932
  158. package/scripts/triage_help.py +0 -1685
  159. package/scripts/triage_queue.py +0 -1944
  160. package/scripts/triage_reconcile.py +0 -581
  161. package/scripts/triage_refresh.py +0 -643
  162. package/scripts/triage_scope.py +0 -999
  163. package/scripts/triage_scope_drift.py +0 -575
  164. package/scripts/triage_smoketest.py +0 -396
  165. package/scripts/triage_subscribe.py +0 -399
  166. package/scripts/triage_summary.py +0 -1011
  167. package/scripts/triage_welcome.py +0 -1178
  168. package/scripts/ts_check_lane.py +0 -86
  169. package/scripts/validate-links.py +0 -64
  170. package/scripts/validate_strategy_output.py +0 -212
  171. package/scripts/vbrief_activate.py +0 -228
  172. package/scripts/vbrief_migrate_conformance.py +0 -368
  173. package/scripts/vbrief_reconcile_graph.py +0 -306
  174. package/scripts/vbrief_reconcile_labels.py +0 -460
  175. package/scripts/vbrief_reconcile_umbrellas.py +0 -741
  176. package/scripts/vbrief_validate.py +0 -1144
  177. package/scripts/verify-stubs.py +0 -61
  178. package/scripts/verify_capacity.py +0 -160
  179. package/scripts/verify_encoding.py +0 -699
  180. package/scripts/verify_hooks_installed.py +0 -206
  181. package/scripts/verify_investigation.py +0 -360
  182. package/scripts/verify_judgment_gates.py +0 -827
  183. package/scripts/verify_no_task_runtime.py +0 -171
  184. package/scripts/verify_scm_boundary.py +0 -509
  185. package/scripts/verify_session_ritual.py +0 -389
  186. package/scripts/verify_tools.py +0 -426
  187. package/scripts/verify_vbrief_conformance.py +0 -478
@@ -1,206 +0,0 @@
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())
@@ -1,360 +0,0 @@
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())