harness-everything 1.2.2 → 1.3.1

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 (147) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +29 -0
  4. package/ci/archive/325-prep/README.md +9 -2
  5. package/ci/archive/325-prep/doc-reconciliation-red.js +34 -8
  6. package/ci/fixtures/468-dispatch/agy-quota-PROVENANCE.md +19 -0
  7. package/ci/fixtures/468-dispatch/agy-quota-direct-individual.stderr +2 -0
  8. package/ci/fixtures/468-dispatch/agy-quota-direct-third-party.stderr +2 -0
  9. package/ci/fixtures/468-dispatch/agy-quota-exec-individual.log +3 -0
  10. package/ci/fixtures/553-t2a/body-edit/base/.agents/harness-everything/project-docs.json +11 -0
  11. package/ci/fixtures/553-t2a/body-edit/base/docs/a.md +6 -0
  12. package/ci/fixtures/553-t2a/body-edit/base/docs/b.md +1 -0
  13. package/ci/fixtures/553-t2a/body-edit/candidate/docs/a.md +6 -0
  14. package/ci/fixtures/553-t2c/derived-regenerate-must/base/docs/adr/EVID-001-verify-all-evidence.md +11 -0
  15. package/ci/fixtures/553-t2c/derived-regenerate-must/base/docs/governed-index.md +19 -0
  16. package/ci/fixtures/553-t2c/derived-regenerate-must/candidate/docs/adr/EVID-001-verify-all-evidence.md +11 -0
  17. package/ci/fixtures/553-t2c/derived-regenerate-must/candidate/docs/governed-index.md +19 -0
  18. package/ci/fixtures/553-t2c/derived-regenerate-must/config.json +17 -0
  19. package/ci/fixtures/doc-obligations/derive/regression-pins.json +153 -0
  20. package/ci/fixtures/state-persist-post-tool-use/harness.js +206 -0
  21. package/ci/fixtures/state-persist-post-tool-use/off-handoff-golden.json +16 -0
  22. package/ci/fixtures/state-persist-post-tool-use/payload-post-tool-use-success.json +13 -0
  23. package/ci/fixtures/stop/fail-session-writes.js +109 -0
  24. package/ci/fixtures/workflow-contract/cases.json +3355 -0
  25. package/ci/fixtures/workflow-contract/wiring-cases.json +560 -0
  26. package/ci/lib/doc-reconciliation-prep-fixtures.js +4 -9
  27. package/ci/mechanism-2an-workflow-replay.test.js +324 -0
  28. package/ci/mechanism-2ax-doc-lifecycle.test.js +132 -0
  29. package/ci/mechanism-325-3a-doc-evidence.test.js +73 -0
  30. package/ci/mechanism-325-3a-doc-obligations.test.js +61 -0
  31. package/ci/mechanism-325-3b-preparation.test.js +208 -49
  32. package/ci/mechanism-325-3b-s1-review.test.js +20 -828
  33. package/ci/mechanism-325-3b-s3-providers.test.js +59 -0
  34. package/ci/mechanism-325-f3-derived-views.test.js +140 -0
  35. package/ci/mechanism-341-opencode-lane.test.js +164 -284
  36. package/ci/mechanism-35-verification-contract.test.js +246 -0
  37. package/ci/mechanism-365-step-edit-accounting.test.js +5 -6
  38. package/ci/mechanism-383-doc-glob-line-terminators.test.js +0 -30
  39. package/ci/mechanism-397-opencode-observations.test.js +151 -18
  40. package/ci/mechanism-468-dispatch-cli.test.js +1496 -4
  41. package/ci/mechanism-548-bigint-identity.test.js +531 -0
  42. package/ci/mechanism-553-e1-unhook-credit.test.js +328 -0
  43. package/ci/mechanism-553-p2a-claude-hooks.test.js +98 -0
  44. package/ci/mechanism-553-p3-plan-start.test.js +212 -0
  45. package/ci/mechanism-553-state-persist-post-tool-use.test.js +307 -0
  46. package/ci/mechanism-553-stop.test.js +427 -0
  47. package/ci/mechanism-553-t2a-derive.test.js +110 -0
  48. package/ci/mechanism-553-t2c-derive.test.js +94 -0
  49. package/ci/mechanism-e1-derived-regenerate.test.js +45 -206
  50. package/ci/mechanism-error-ledger-oracle.test.js +786 -3
  51. package/ci/mechanism-error-ledger-scan.test.js +981 -0
  52. package/ci/mechanism-outline-sanitizer.test.js +0 -8
  53. package/ci/mechanism-pr-a-conflict-check.test.js +38 -305
  54. package/ci/mechanism-prb-outline-review.test.js +101 -3283
  55. package/ci/mechanism-report-writer.test.js +45 -0
  56. package/docs/adr/DOCS-006-reconciliation-pilot.md +4 -2
  57. package/docs/adr/DOCS-008-obligation-abstraction-bounded-consumer.md +3 -3
  58. package/docs/doc-workflow-reconciliation.md +17 -2
  59. package/docs/document-lifecycle.md +6 -2
  60. package/docs/error-handling/details/c8-dispatch-cli.md +109 -13
  61. package/docs/platform-capabilities.md +35 -5
  62. package/error-ledger-bootstrap/SKILL.md +1 -1
  63. package/error-ledger-bootstrap/references/workflow.md +42 -7
  64. package/error-ledger-bootstrap/scripts/promote.js +8 -6
  65. package/error-ledger-bootstrap/scripts/scan.js +525 -12
  66. package/hooks/hooks.json +0 -46
  67. package/hooks/scripts/lib/workflow-obligations.js +0 -55
  68. package/hooks/scripts/state-persist.js +7 -95
  69. package/hooks/scripts/workflow-disposition.js +0 -2
  70. package/hooks/scripts/workflow-stop-gate.js +17 -30
  71. package/opencode-plugin/index.mjs +6 -70
  72. package/opencode-plugin/plugin.json +1 -1
  73. package/package.json +1 -1
  74. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  75. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  76. package/plugins/harness-everything/hooks/scripts/lib/workflow-obligations.js +0 -55
  77. package/plugins/harness-everything/hooks/scripts/state-persist.js +7 -95
  78. package/plugins/harness-everything/hooks/scripts/workflow-disposition.js +0 -2
  79. package/plugins/harness-everything/hooks/scripts/workflow-stop-gate.js +17 -30
  80. package/plugins/harness-everything/plugin.json +1 -1
  81. package/plugins/harness-everything/skills/error-ledger-bootstrap/SKILL.md +1 -1
  82. package/plugins/harness-everything/skills/error-ledger-bootstrap/references/workflow.md +42 -7
  83. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/promote.js +8 -6
  84. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/scan.js +525 -12
  85. package/sbom.cdx.json +7 -7
  86. package/scripts/dispatch.js +499 -87
  87. package/scripts/error-ledger-oracle.js +521 -27
  88. package/scripts/errors-sync.js +4 -3
  89. package/scripts/report-writer.js +4 -3
  90. package/ci/fixtures/doc-obligations/reconciliation-s1/cases.json +0 -6854
  91. package/ci/fixtures/doc-obligations/reconciliation-s1/fail-session-writes.js +0 -116
  92. package/ci/fixtures/doc-obligations/reconciliation-s2a/harness.js +0 -507
  93. package/ci/fixtures/doc-obligations/reconciliation-s2a/run13-workflow-requirements.json +0 -42
  94. package/ci/fixtures/doc-obligations/reconciliation-s2a/vectors.json +0 -617
  95. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/harness.js +0 -415
  96. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-post-tool-use-success-minimal.json +0 -9
  97. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-start.json +0 -7
  98. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop-freetext-reject.json +0 -11
  99. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop-reject.json +0 -11
  100. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop.json +0 -11
  101. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-task-result.json +0 -19
  102. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/off-capture-only.json +0 -99
  103. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/off-legacy.json +0 -67
  104. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-concurrent-writers.json +0 -62
  105. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-lookalikes-runtime-mutations.json +0 -67
  106. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-malformed.json +0 -85
  107. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-normal-session.json +0 -74
  108. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-runtime-drift-later-npm-test.json +0 -58
  109. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-valid-direct-quoted-review.json +0 -85
  110. package/ci/fixtures/doc-obligations/reconciliation-s2b/f4/cases.json +0 -2267
  111. package/ci/fixtures/doc-obligations/reconciliation-s2b/wiring/cases.json +0 -1110
  112. package/ci/lib/doc-reconciliation-file-spy.js +0 -23
  113. package/ci/lib/doc-reconciliation-qualification-preload.js +0 -37
  114. package/ci/lib/doc-reconciliation-replay.js +0 -104
  115. package/ci/lib/doc-reconciliation-staged-tree.js +0 -102
  116. package/ci/mechanism-325-3b-h1-qualification.test.js +0 -206
  117. package/ci/mechanism-325-3b-s1.test.js +0 -188
  118. package/ci/mechanism-325-3b-s2a-core.test.js +0 -840
  119. package/ci/mechanism-325-3b-s2a-producer.test.js +0 -564
  120. package/ci/mechanism-325-3b-s2b-capture.test.js +0 -566
  121. package/ci/mechanism-325-3b-s2b-wiring.test.js +0 -679
  122. package/ci/mechanism-325-f4-invariants.test.js +0 -606
  123. package/ci/mechanism-325-f4-projections.test.js +0 -392
  124. package/ci/mechanism-325-f4-qualification.test.js +0 -228
  125. package/ci/mechanism-325-f4-trust-boundary.test.js +0 -880
  126. package/ci/mechanism-e1-dependency-artifact-scope.test.js +0 -657
  127. package/hooks/scripts/lib/doc-reconciliation-capture.sanitized.jsonl +0 -26
  128. package/hooks/scripts/lib/doc-reconciliation-core.js +0 -336
  129. package/hooks/scripts/lib/doc-reconciliation-events.js +0 -292
  130. package/hooks/scripts/lib/doc-reconciliation-outline-capture.sanitized.jsonl +0 -24
  131. package/hooks/scripts/lib/doc-reconciliation-pilot.js +0 -482
  132. package/hooks/scripts/lib/doc-reconciliation-producer.js +0 -468
  133. package/hooks/scripts/lib/doc-reconciliation-provider.js +0 -3304
  134. package/hooks/scripts/lib/doc-reconciliation-qualification.json +0 -54
  135. package/hooks/scripts/w6-state-operations.js +0 -239
  136. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-capture.sanitized.jsonl +0 -26
  137. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-core.js +0 -336
  138. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-events.js +0 -292
  139. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-outline-capture.sanitized.jsonl +0 -24
  140. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-pilot.js +0 -482
  141. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-producer.js +0 -468
  142. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-provider.js +0 -3304
  143. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-qualification.json +0 -54
  144. package/plugins/harness-everything/hooks/scripts/w6-state-operations.js +0 -239
  145. package/scripts/system-one-eval-laya.js +0 -112
  146. /package/ci/fixtures/{doc-obligations/reconciliation-s2b/capture → state-persist-post-tool-use}/payload-post-tool-use-failure.json +0 -0
  147. /package/ci/fixtures/{doc-obligations/reconciliation-s2b/wiring → workflow-contract}/legacy-off-golden.json +0 -0
@@ -1,24 +0,0 @@
1
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","effort":{"level":"medium"},"tool_name":"Bash","tool_input":{"command":"cat /sanitized/run8/stage1.txt"},"tool_use_id":"<tool-use-1>","event":"PreToolUse"}
2
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","effort":{"level":"medium"},"tool_name":"Bash","tool_input":{"command":"cat /sanitized/run8/stage1.txt"},"tool_response":{"stdout":"STAGE1 READY\nOutline file: /sanitized/run8/project/docs/adr/VERI-001.md\nInventory file: /sanitized/run8/state/workspaces/project-c3344fec53f4/state/sessions/<session-1>/doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md\nReviewer must end its reply with exactly these four lines:\nReview verdict: approve\nReviewed artifact: docs/adr/VERI-001.md sha256:7e03847cc8ceae735bfb76d85f4fcdf09ea0cd6e84299405ee44733e4917b6b8\nReviewed artifact: doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md sha256:2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6\nSummary: Approved inventory row 16 for docs/adr/VERI-001.md in domain VERI.","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"<tool-use-1>","duration_ms":415,"event":"PostToolUse"}
3
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","effort":{"level":"medium"},"tool_name":"Agent","tool_input":{"description":"Review outline","prompt":"STAGE1 READY\nOutline file: /sanitized/run8/project/docs/adr/VERI-001.md\nInventory file: /sanitized/run8/state/workspaces/project-c3344fec53f4/state/sessions/<session-1>/doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md\nReviewer must end its reply with exactly these four lines:\nReview verdict: approve\nReviewed artifact: docs/adr/VERI-001.md sha256:7e03847cc8ceae735bfb76d85f4fcdf09ea0cd6e84299405ee44733e4917b6b8\nReviewed artifact: doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md sha256:2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6\nSummary: Approved inventory row 16 for docs/adr/VERI-001.md in domain VERI.\n\nReview the outline against the inventory row","subagent_type":"outline-reviewer","run_in_background":false},"tool_use_id":"<tool-use-2>","event":"PreToolUse"}
4
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","agent_id":"<agent-1>","agent_type":"outline-reviewer","event":"SubagentStart"}
5
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-1>","agent_type":"outline-reviewer","effort":{"level":"medium"},"tool_name":"Read","tool_input":{"file_path":"/sanitized/run8/project/docs/adr/VERI-001.md"},"tool_use_id":"<tool-use-3>","event":"PreToolUse"}
6
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-1>","agent_type":"outline-reviewer","effort":{"level":"medium"},"tool_name":"Read","tool_input":{"file_path":"/sanitized/run8/project/docs/adr/VERI-001.md"},"tool_response":{"type":"text","file":{"filePath":"/sanitized/run8/project/docs/adr/VERI-001.md","content":"---\nid: VERI-001\nstatus: proposed\n---\n\nInventory row: 16\nTarget: docs/adr/VERI-001.md\nDomain: VERI\n\n## Outline\n- Context: verification is recorded as observed, timed evidence (verify-gate).\n- Decision: TBD\n","numLines":13,"startLine":1,"totalLines":13}},"tool_use_id":"<tool-use-3>","duration_ms":2,"event":"PostToolUse"}
7
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-1>","agent_type":"outline-reviewer","effort":{"level":"medium"},"tool_name":"Read","tool_input":{"file_path":"/sanitized/run8/state/workspaces/project-c3344fec53f4/state/sessions/<session-1>/doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md"},"tool_use_id":"<tool-use-4>","event":"PreToolUse"}
8
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-1>","agent_type":"outline-reviewer","effort":{"level":"medium"},"tool_name":"Read","tool_input":{"file_path":"/sanitized/run8/state/workspaces/project-c3344fec53f4/state/sessions/<session-1>/doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md"},"tool_response":{"type":"text","file":{"filePath":"/sanitized/run8/state/workspaces/project-c3344fec53f4/state/sessions/<session-1>/doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md","content":"# Report INV — existing-mechanism inventory for retroactive ADRs\n\nrun id `e1-inv-1` · packet rev 1 · input SHA `0ef0541c6cae550e8269ba712e03797e0e987dfb` (verified: `git rev-parse HEAD` — **executed**).\nFacts only, no decisions. Issue states: **executed** via read-only `gh issue view N --json state` (57 numbers queried 2026-10-27). File/test/issue-number mapping: **source-traced** (grep of `ci/`, `docs/*.md`, `git log --oneline --all --grep`, code citations). ADR shape: **source-traced** (code citations, no execution). Status flags: my classification of those facts.\n\n## 1. ADR shape — the exact minimum file this repo's checker accepts\n\nChecker: `harness-everything/scripts/doc-lifecycle.js` (run via `doc-check.js`; config from `project-docs-resolver.js`). `describes:` is **not** recognized by `doc-lifecycle.js` (absent — grep, **source-traced**).\n\n| Rule | Value | Citation |\n| --- | --- | --- |\n| ID regex | `/^([A-Z][A-Z0-9]{1,9})-(\\d{3,})$/` — domain 2–10 uppercase alnum chars, number ≥ 3 digits | doc-lifecycle.js:20 |\n| ID required | `missing-id` when `id` absent/empty | doc-lifecycle.js:1075–1076 |\n| ID malformed | `invalid-id` when regex fails | doc-lifecycle.js:1077 |\n| Domain declared | `unknown-domain` unless domain ∈ `config.domains` (set from config, doc-lifecycle.js:1035; never hardcoded) | doc-lifecycle.js:1078 |\n| Status required | `missing-status` / `invalid-status` vs `ROLE_STATUSES.adr` | doc-lifecycle.js:1070–1073 |\n| ADR status vocabulary | exactly `proposed` / `accepted` / `rejected` / `superseded` | doc-lifecycle.js:14 |\n| Frontmatter `role` | optional; if present must equal path role (`role-mismatch`) | doc-lifecycle.js:1063–1064 |\n| Frontmatter fields recognized | `id`, `role`, `status`, `aliases`, `supersedes`, `conflicts_with` (+ PRD-only fields); leading `---` YAML subset, no tabs | doc-lifecycle.js:119–147, 1082–1092, 1210–1221, 1315–1321 |\n| `aliases[]` | strings matching ID pattern; no `legacy:` prefix, not self (`invalid-alias`); collisions → `alias-collision` | doc-lifecycle.js:1082–1092, 1159+ |\n| `supersedes` | list of resolvable refs; effective edge requires target `status: superseded`; self/cycle → `supersede-cycle` | doc-lifecycle.js:1210–1221, 1259–1268 |\n| `conflicts_with` | refs must resolve or stay `recorded-conflict` until an effective `supersedes` | doc-lifecycle.js:1315–1321 |\n| Location | **config-driven, not hardcoded**: file must match a `governed` glob entry carrying `role: \"adr\"` (collection doc-lifecycle.js:295–300; `roleAtPath` 2147–2152; no `docs/adr` hardcode in the checker). Resolver infers `docs/adr`/`docs/decisions` only when *generating* config | project-docs-resolver.js:578,599 |\n| Ratchet | schema checks apply to governed files named in `changedPaths`; full mode only with `--all` | docs/document-lifecycle.md:132 |\n\nMinimum accepted new ADR (given a config that declares the domain and an ADR glob):\n\n```markdown\n---\nid: ROUTE-001\nstatus: accepted\n---\n\n# ROUTE-001 — <title>\n\n## Decision\n<text>\n```\n\nThat is the whole required shape: `id` + `status` (+ declared domain). `Decision`-section presence matters only for D6.5 normative-trigger classification, not lint. Pending/edge extras: optional `role`, `aliases`, `supersedes` (with target `superseded`), `conflicts_with`.\n\n## 2. Mechanism inventory\n\nPath abbreviations: **H/** `hooks/scripts/`, **R/** `harness-everything/scripts/`, **C/** `ci/`. States: `M`=merged PR, `C`=closed, `O`=open. All issue states **executed**; attributions **source-traced**.\n\n| # | Mechanism | Decision it embodies | Implementing file(s) | Tests (grep C/) | Issues (state) | Flag |\n| --- | --- | --- | --- | --- | --- | --- |\n| 01 | Kernel routing | Route before execute: tier/strategy/invariants before mutation | R/kernel-router.js, R/tier-router.js, R/router-contract.js, R/routing-keywords.json | C/invariant-routing, C/router-workflow-plan, C/router-phase2-safety, C/prompt-contract-regressions, C/skill-routing-check | #142 (M), #217 (C) | CONSISTENT |\n| 02 | Step-scoped binding resolution | Disclose only active-step knowledge; unknown stays visible | R/kernel-router.js, H/lib/binding-resolver.js, R/kernel-router-core.js | C/mechanism-2ar-binding-resolution, C/invariant-routing | #297 (C) | CONSISTENT |\n| 03 | Workflow lifecycle evidence | Objective evidence before completion; explicit dispositions | H/workflow-stop-gate.js, H/workflow-disposition.js, H/lib/workflow-obligations.js, H/lib/fable-contracts.js | C/mechanism-2an, C/mechanism-2ah, C/mechanism-2as, C/mechanism-2az, C/workflow-execution-contract | #143 (M), #242 (C) | CONSISTENT |\n| 04 | Worktree/Fable isolation | Isolate broad mutation before it starts | H/lib/workflow-isolation.js, R/kernel-router.js | C/mechanism-2af, C/mechanism-2ai, C/mechanism-34-worktree-submodule-reachability | #150,#152,#154,#156,#158 (all M) | CONSISTENT |\n| 05 | Harness Status protocol | One user-visible status block for non-trivial work (semantic, no lock) | skill text (routing docs); no dedicated runtime file | C/reference-check only (no mechanism test) | NO-ISSUE found | NO-TEST |\n| 06 | Action gate | Explicit approval for destructive/external side effects (hard block) | H/action-gate.js, H/action-gate-rules.json, H/codex-action-gate-pre.js, H/codex-action-gate-post.js, H/codex-permission-request.js | C/action-gate, C/mechanism-2ad, C/mechanism-2aa, C/mechanism-2au, C/action-gate-platform-doc | #144 (M); live approval matrix #100 (C) | CONSISTENT |\n| 07 | Rule-of-3 / zoom-out | Stop after 3 same-signature failures; hard boundary | H/rule-of-3.js, H/rule-of-3-tracker.js, H/reset-circuit-breaker.js | C/mechanism-2a-rule-of-3, C/self-evolve-loop | #201 (C) | CONSISTENT |\n| 08 | Stop gate | No completion without observed successful verification | H/stop-gate.js | C/mechanism-2f-stop-gate | #190 (C) | CONSISTENT |\n| 09 | Advisory guard trio | Warn about broad searches, blind overwrites, context pressure (fail-open) | H/boundary-guard.js, H/depth-guard.js, H/context-compact.js | C/mechanism-2b (boundary only); depth/context **no test** | #190 (C) | NO-TEST (2 of 3) |\n| 10 | State persistence / WAL | Persist tool outcomes, mutations, verification milestones | H/state-persist.js, H/lib/harness-state.js | C/mechanism-2c, C/mechanism-2ah, C/telemetry | #160 (M), #147 (M) | CONSISTENT |\n| 11 | Subagent scope guard + contract test | Snapshot/diff around subagent bursts; inter-agent contract testing | H/subagent-scope-guard.js, H/contract-test.js | C/mechanism-2e, C/workflow-plan-consumers, C/workflow-plan-consumers-edge | NO-ISSUE found | NO-ISSUE |\n| 12 | Memory capability token | One-time workflow-bound capability for memory writes | R/kernel-router.js (`issueMemoryCapability`) | **no function-level test** (adjacent: C/phase4-ensemble-memory) | #145 (M) | NO-TEST |\n| 13 | Ensemble policy | MAY-level multi-agent composition under high uncertainty | R/ensemble-policy.js | C/phase4-ensemble-memory | NO-ISSUE found | NO-ISSUE |\n| 14 | Bootstrap / self-repo guard / self-heal | Session bootstrap, env detection, environment repair | R/bootstrap.js, R/self-heal.js, R/runtime-paths.js | C/mechanism-2m-self-repo-guard, C/mechanism-2an-environment-detection-readonly | NO-ISSUE found | NO-ISSUE |\n| 15 | Contract-integrity audit | Prove artifact↔spec traceability | contract-integrity/scripts/audit.js | C/contract-integrity.test | #84 (C), #58 (C) | CONSISTENT |\n| 16 | Verify gate | Treat verification as observed, timed evidence | R/verify-gate.js | C/mechanism-35-verification-contract, C/mechanism-36-verify-timeout | #242 (C) | CONSISTENT |\n| 17 | verify:all aggregate gate | One CI-ordered gate list with PASS/FAIL/UNCHECKED report | scripts/verify-all.js | C/mechanism-38-verify-all (self-regression subset) | NO-ISSUE found | CONSISTENT (see Open Q1) |\n| 18 | Paired behavioral / benchmark evidence | No \"improved\" claim without paired baseline-vs-treatment evidence | behavioral-evals/run.js, benchmarks/run.js, C/ab-test-harness.js | C/mechanism-2j, C/mechanism-32, C/mechanism-335, C/mechanism-2v | #71 (**O**), #130 (M), #242 (C) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 19 | Doc config resolution (D5) | Committed host-neutral config wholly overrides host manifests; AGENTS.md never config | R/project-docs-resolver.js, R/doc-check.js | C/mechanism-2aw, C/reference-check | #325 (**O**) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 20 | ADR/REQ identity + supersession + index (D6.1–D6.4) | Domain-scoped IDs, aliases, legacy refs, generated index | R/doc-lifecycle.js | C/mechanism-2ax, C/reference-check | #325 (**O**) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 21 | PRD revision contract (D6.9) | Effective PRD = frozen revision chain with approval record | R/doc-lifecycle.js | C/mechanism-2ay | #325 (**O**) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 22 | `doc-change` step type | Explicit doc-edit step type, no implicit TDD binding | H/lib/step-types.json, H/lib/workflow-obligations.js | C/mechanism-2az-step-type-registry | #326 (C), #328 (M) | CONSISTENT |\n| 23 | Doc obligations + evidence producer (3a) | Fail-closed doc MUSTs with trusted-producer identity binding | R/doc-obligations.js, R/doc-evidence.js, R/doc-evidence-capture.js | C/mechanism-325-3a-doc-obligations, C/mechanism-325-3a-doc-evidence, C/mechanism-335-baseline-evidence | #334 (M), #335 (C, fixed by #342 — executed state for #342 not queried, result merged) | CONSISTENT |\n| 24 | Reconciliation pilot S1/F4 | Default-OFF opt-in gate; limited credit for `doc-lint`/`link-check` only | H/lib/doc-reconciliation-*.js, H/codex-user-prompt.js (switch) | C/mechanism-325-3b-preparation, C/mechanism-325-3b-s1-review, C/mechanism-341-opencode-lane | #341 (**O**), #350 (**O**), #358 (M), #375 (M: E1 zero qualifying cycles) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 25 | Shared doc craft + derived views (F2/F3) | Regenerate-equals for authorized generators; shared references | R/doc-obligations.js, harness-everything/references/documentation/_shared/ | C/mechanism-325-f3-derived-views, C/reference-check | #356 (M), #357 (M) | CONSISTENT |\n| 26 | #320 obligation abstraction (bounded consumer) | Doc workflow reconciliation consumes workflow abstractions; broad promotion gated | H/lib/doc-reconciliation-core.js + R/doc-obligations.js | same as #24 tests | #320 (**O**) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 27 | System One observation capture | Local, content-private turn observation; fail-open, silent | H/observation-hook.js, hooks/scripts/lib/telemetry.js | C/mechanism-34-observations, C/mechanism-2am-observations-session-import | #233 (**O**) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 28 | System One engine (tier-4 experimental) | Learned intent routing + resident/eval pipeline | scripts/system-one-*.js/py, R/system-one/ (install) | C/mechanism-system-one-*.test.js suite; ci.yml Windows S1 lanes | #233 (**O**) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 29 | S1 intent/suggestion/noise gates | Weak-intent gating with Laya teacher; `rule_v2` noise gate | docs-system-one-* scripts (corpus/evaluate/label) | C/mechanism-system-one-evaluation, C/system-one-*.py | #255 (**O**), #265 (**O**), #297 (C) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 30 | Skill telemetry | Privacy-safe skill load start/close telemetry window | H/telemetry-adapter.js, H/lib/telemetry.js, telemetry/scripts/ | C/telemetry.test | #147 (M), #37 (C), #122 top-level blocker (**O**) | CONSISTENT |\n| 31 | OpenCode plugin | Project-scope `.js` loading + edit/verify state on OpenCode 1.18.31 (macOS, retained evidence only) | opencode-plugin/ | C/mechanism-2n, C/mechanism-30-loadability, C/mechanism-31-hardlock-evidence, C/mechanism-2p, C/mechanism-39, C/mechanism-341-opencode-lane | #128 (M), #129 (M), #82 (**O**) | **ISSUE-OPEN-BUT-SHIPPED** (live claim bounded) |\n| 32 | Codex plugin hooks compat | Codex hook adapters/package-level parity with Claude hooks | H/lib/platforms/codex.js, scripts/codex-hooks-compat.js | C/mechanism-2al, C/mechanism-2au, C/mechanism-2ao | #110 (**O**), #122 (**O**), #135 (C), #98 (M), #109 (C) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 33 | Platform adapter matrix | Per-host capability/evidence claims centralized and claimed as tested contract | H/lib/platforms/ (claude/codex/cursor/copilot/continue/hermes), docs/platform-capabilities.md | C/mechanism-2w-platform-compatibility, C/mechanism-2t-platform-skill-targets, C/mechanism-2g-platform-ignore | #82 (**O**), #123 (M), #127 (C), #135 (C) | **ISSUE-OPEN-BUT-SHIPPED** |\n| 34 | Plugin packaging (Claude + OpenAI + submission) | Generated distribution manifests are facts, byte-consistent copies | scripts/stage-claude-plugin.js, scripts/validate-claude-plugin.js, scripts/sync-openai-plugin.js, scripts/build-openai-submission.js, .claude-plugin/ | C/mechanism-2z, C/openai-plugin-package, C/openai-plugin-submission, C/openai-plugin-runtime, C/mechanism-packaging-bytecode | #123 (M), #128 (M), #129 (M) | CONSISTENT |\n| 35 | Release automation | semantic-release owns SemVer; nested versions synced; skip-CI version bumps | scripts/sync-release-version.js, .github/workflows/release.yml, scripts/generate-sbom.js | C/mechanism-2x (×2), C/mechanism-2y, C/mechanism-2ap-sbom, C/mechanism-2u-issue-44, C/semantic-release-analyzer | #20 (C) | CONSISTENT |\n| 36 | Manifest sync across hosts | All distribution manifests generated from canonical skills | scripts/plugin-sync.js (.sh/.ps1), scripts/repository-contract.js | C/mechanism-2ao, C/mechanism-2ab, C/repository-contract.test | #123 (M) | CONSISTENT |\n| 37 | Installer | Interactive/non-interactive install, verify, uninstall, shared store | scripts/installer.js, bin/cli.js | C/installer-roundtrip, C/mechanism-2h, C/mechanism-2i (×2), C/mechanism-2p-installer-links, C/mechanism-2q, C/mechanism-2r | NO-ISSUE found | NO-ISSUE |\n| 38 | Skill routing evals / collision gate | Every routed skill has a trigger eval; descriptions must not collide | evals/<skill>/eval.yaml, C/description-collision.js, C/skill-routing-check.js | (these files are the gates) | NO-ISSUE found | CONSISTENT (see Open Q1) |\n| 39 | Commit discipline | Conventional commits enforced locally via husky+commitlint | commitlint.config.js, .husky/ | C/mechanism-33-issues-205-207, C/mechanism-2x-release-commit-message | #205 (C), #207 (C) | CONSISTENT |\n\nCounts: 39 rows · CONSISTENT 21 · ISSUE-OPEN-BUT-SHIPPED 11 · NO-ISSUE 5 · NO-TEST 2 (02 rows flagged NO-TEST cover 3 sub-mechanisms).\n\n## 3. Area grouping + candidate domain prefixes\n\nFormats follow `^[A-Z][A-Z0-9]{1,9}$` (checked against doc-lifecycle.js:20 ADR_ID domain form). No domains are declared today (`.agents/harness-everything/project-docs.json` governs two `reference` files only, no `domains` key) — so every candidate is new, and adopting any requires editing `project-docs.json`, which under #325 D6.8 is the project's own declared list (Harness never hard-codes it).\n\n| Area | Rows | Candidate prefix | Why |\n| --- | --- | --- | --- |\n| Routing & workflow contract | 01–05 | `ROUTE` | Kernel routing / topology / bindings are one decision family |\n| Enforcement & safety boundaries | 06–15 | `ENFC` | Approval, breaker, stop evidence, persistence — the hook-path contract |\n| Verification & evidence | 16–18, 15 | `VERI` | Shared \"objective evidence before claiming done\" decision |\n| Document lifecycle (#325) | 19–26 | `DOCS` | Already contract-scoped to #325; natural domain |\n| System One (experimental) | 27–29 | `SONE` | Clearly-labeled tier-4 experimental family |\n| Platform, packaging, release | 30–39 | `DIST` | Distribution/platform claims and tooling |\n\nZero-commit numbers (#71, #84, #109, #110, #122, #127, #135, #217, #350 — doc-referenced only in this clone) are kept **with state flags** rather than dropped, so a future ADR citing them shows they lack commit-message anchors in this SHA's history.\n\n**Single-domain alternative:** one prefix `HARN` for every retroactive ADR (Harness-wide decisions), splitting later via `supersedes`/aliases once areas stabilize. Cheaper to ship (one `domains` entry, no per-area risk of overlap collisions); loses the ability to grep decisions by area from the ID alone.\n\n## 4. Mismatch list (non-CONSISTENT rows) — the \"功能與 issues 狀態\" findings\n\n1. **depth-guard.js, context-compact.js — NO-TEST.** Shipped on the hook path (`hooks/hooks.json:99–115`) under closed issue #190, but their basenames appear nowhere in `ci/` outside `archive/`. Candidate: ISSUE-CLOSED-BUT-MISSING *test coverage*, not mechanism.\n2. **memory capability token (kernel-router.js#issueMemoryCapability) — NO-TEST** despite merged #145. Function itself untested; only adjacent ensemble-memory policy tests exist.\n3. **Harness Status protocol (row 05) — NO-TEST.** Mandated in AGENTS.md #11 and docs/routing.md; no mechanism test exists (it is semantic, not enforced — #11 itself says \"Not a hard lock\").\n4. **#71 OPEN vs shipped policy.** architecture.md and the validation boundary require paired behavioral evidence for lifecycle-effectiveness claims — the requirement is live and unmet while the machinery (rows 18, 24) ships around it: the classic \"shipped, gate pending\" split. #375 (merged) reports E1 with zero qualifying cycles.\n5. **#341/#350 OPEN vs shipped default-OFF pilot.** S1 + F4 shipped as opt-in (`HARNESS_DOC_RECONCILIATION_PILOT=1`) with fail-closed withholding; expansion explicitly not approved (E1 gate). Consistent-with-docs but issue-open → flagged.\n6. **#82/#110/#122 OPEN: live-host verification umbrella.** platform-capabilities claims are held to mechanism-package evidence; live-host firing is still open for Codex (#110, #122 mount/attribution blocker) and the #82 compatibility program. All OpenCode/Codex live rows inherit this.\n7. **#233/#255/#265 OPEN vs shipped System One.** Experimental engine, gates and Windows CI lanes are live in `ci.yml` while their governing experiment issues are open — intentional (labeled experimental) but must be reflected, not hidden, in the ADR set.\n8. **#325 OPEN vs merged doc-lifecycle slices.** The owner-decision umbrella (#325) stays open by design; all shipped phases (#327/#334/#356/#357/#358, …) flag ISSUE-OPEN-BUT-SHIPPED. Not a defect — a structural fact for the retroactive ADRs' status choices.\n9. **#201 as Rule-of-3 anchor (row 07) is the only issue found** — \"advisory re-trip contract (#201)\" from this clone's log. Earlier origin of the mechanism may be unreferenced; treating #201 as governing is an inference (label: source-traced, weak).\n\n## 5. Open questions\n\n1. **Q1 — CI routing-gate coverage (inconclusive):** `package.json` exposes `test:routing:skills`/`test:routing:invariants` and `scripts/verify-all.js` runs them, but `.github/workflows/ci.yml` jobs do not invoke them by name (consistency job runs `test:consistency`, `test:references`, `test:release`, `test:collision`, `test:plugin:openai`, `test:plugin:submission`, `test:platform:compatibility`, `test:portability`; self-regression job runs `npm test` + `test:mutations`). Whether `npm test` self-regression reaches the routing tests was not traced end to end — rows 01 and 38 keep CONSISTENT subject to Q1.\n2. **Q2 — ADR scope boundary:** does \"已經存在的機制\" (existing mechanisms) cover semantic/instruction-only contracts (rows 05, plus skill-text obligations), or only runtime code with hooks/tests? Recommendation-shaped, not a fact: mechanism code first.\n3. **Q3 — domain assignment ownership:** adopting `ROUTE/ENFC/…` (or `HARN`) requires a `project-docs.json` `domains` edit + ADR glob + `project-overrides-host` warning reconciliation under D5; owner decides under #325.\n4. **Q4 — #342 executed state:** #335's own state was queried (closed, executed) but the first fix PR #342's state was not queried in the batch (its merge is source-traced from docs only).\n5. **Q5 — alias stability:** issues with zero commit-message matches in this clone (71, 84, 109, 110, 122, 127, 135, 217, 350) may exist in other branches/clone histories; anchor-richness is lower than for #233/#325.\n\n<!-- harness-label {\"judgement\":\"facts-only inventory report per packet; no repo writes\",\"risk\":\"none\"} -->\nSTATUS: DONE\n","numLines":129,"startLine":1,"totalLines":129}},"tool_use_id":"<tool-use-4>","duration_ms":1,"event":"PostToolUse"}
9
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-1>","agent_type":"outline-reviewer","effort":{"level":"medium"},"stop_hook_active":false,"agent_transcript_path":"/sanitized/run8/agent-transcripts/transcript-1.jsonl","last_assistant_message":"The outline passes all four checks against the inventory.\n\n- **Inventory row:** The outline cites \"Inventory row: 16\". Row 16 in the inventory is \"Verify gate\", \"Treat verification as observed, timed evidence\", implemented in `R/verify-gate.js`. The outline's context line matches it.\n- **Target path:** `docs/adr/VERI-001.md` is the file reviewed. Its frontmatter `id: VERI-001` fits the checker's ID pattern, and `status: proposed` is an allowed ADR status.\n- **Domain:** The outline says \"Domain: VERI\". Section 3 of the inventory assigns rows 16–18 and 15 to the candidate prefix `VERI`.\n- **Decision:** The line reads \"Decision: TBD\", so there is no substantive Decision yet.\n\nI did not compute the SHA-256 hashes. The two `Reviewed artifact` lines below use the values you gave me unchanged.\n\nFiles reviewed:\n- `/sanitized/run8/project/docs/adr/VERI-001.md`\n- `/sanitized/run8/state/workspaces/project-c3344fec53f4/state/sessions/<session-1>/doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md`\n\nReview verdict: approve\nReviewed artifact: docs/adr/VERI-001.md sha256:7e03847cc8ceae735bfb76d85f4fcdf09ea0cd6e84299405ee44733e4917b6b8\nReviewed artifact: doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md sha256:2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6\nSummary: Approved inventory row 16 for docs/adr/VERI-001.md in domain VERI.","background_tasks":[],"session_crons":[],"event":"SubagentStop"}
10
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","effort":{"level":"medium"},"tool_name":"Agent","tool_input":{"description":"Review outline","prompt":"STAGE1 READY\nOutline file: /sanitized/run8/project/docs/adr/VERI-001.md\nInventory file: /sanitized/run8/state/workspaces/project-c3344fec53f4/state/sessions/<session-1>/doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md\nReviewer must end its reply with exactly these four lines:\nReview verdict: approve\nReviewed artifact: docs/adr/VERI-001.md sha256:7e03847cc8ceae735bfb76d85f4fcdf09ea0cd6e84299405ee44733e4917b6b8\nReviewed artifact: doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md sha256:2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6\nSummary: Approved inventory row 16 for docs/adr/VERI-001.md in domain VERI.\n\nReview the outline against the inventory row","subagent_type":"outline-reviewer","run_in_background":false},"tool_response":{"status":"completed","prompt":"STAGE1 READY\nOutline file: /sanitized/run8/project/docs/adr/VERI-001.md\nInventory file: /sanitized/run8/state/workspaces/project-c3344fec53f4/state/sessions/<session-1>/doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md\nReviewer must end its reply with exactly these four lines:\nReview verdict: approve\nReviewed artifact: docs/adr/VERI-001.md sha256:7e03847cc8ceae735bfb76d85f4fcdf09ea0cd6e84299405ee44733e4917b6b8\nReviewed artifact: doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md sha256:2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6\nSummary: Approved inventory row 16 for docs/adr/VERI-001.md in domain VERI.\n\nReview the outline against the inventory row","agentId":"<agent-1>","agentType":"outline-reviewer","toolsUsed":["Read"],"harnessNoteCount":1,"harnessTailCount":0,"harnessSectionHash":"510238c68f070d12","content":[{"type":"text","text":"<tools-used-before-summary>Read</tools-used-before-summary>\n"},{"type":"text","text":"The outline passes all four checks against the inventory.\n\n- **Inventory row:** The outline cites \"Inventory row: 16\". Row 16 in the inventory is \"Verify gate\", \"Treat verification as observed, timed evidence\", implemented in `R/verify-gate.js`. The outline's context line matches it.\n- **Target path:** `docs/adr/VERI-001.md` is the file reviewed. Its frontmatter `id: VERI-001` fits the checker's ID pattern, and `status: proposed` is an allowed ADR status.\n- **Domain:** The outline says \"Domain: VERI\". Section 3 of the inventory assigns rows 16–18 and 15 to the candidate prefix `VERI`.\n- **Decision:** The line reads \"Decision: TBD\", so there is no substantive Decision yet.\n\nI did not compute the SHA-256 hashes. The two `Reviewed artifact` lines below use the values you gave me unchanged.\n\nFiles reviewed:\n- `/sanitized/run8/project/docs/adr/VERI-001.md`\n- `/sanitized/run8/state/workspaces/project-c3344fec53f4/state/sessions/<session-1>/doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md`\n\nReview verdict: approve\nReviewed artifact: docs/adr/VERI-001.md sha256:7e03847cc8ceae735bfb76d85f4fcdf09ea0cd6e84299405ee44733e4917b6b8\nReviewed artifact: doc-reconciliation/outline-confirmation/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md sha256:2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6\nSummary: Approved inventory row 16 for docs/adr/VERI-001.md in domain VERI."}],"resolvedModel":"claude-sonnet-5-5","totalDurationMs":12002,"totalTokens":14638,"totalToolUseCount":2,"usage":{"output_tokens_details":{"thinking_tokens":85},"input_tokens":2,"cache_creation_input_tokens":10723,"cache_read_input_tokens":2956,"output_tokens":957,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":10723},"inference_geo":"global","iterations":[{"input_tokens":2,"output_tokens":957,"cache_read_input_tokens":2956,"cache_creation_input_tokens":10723,"cache_creation":{"ephemeral_5m_input_tokens":10723,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard","fallback_credit":null},"toolStats":{"readCount":2,"searchCount":0,"bashCount":0,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0},"canContinueAgent":true},"tool_use_id":"<tool-use-2>","duration_ms":12003,"event":"PostToolUse"}
11
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","effort":{"level":"medium"},"tool_name":"Bash","tool_input":{"command":"cat /sanitized/run8/stage2.txt"},"tool_use_id":"<tool-use-5>","event":"PreToolUse"}
12
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","effort":{"level":"medium"},"tool_name":"Bash","tool_input":{"command":"cat /sanitized/run8/stage2.txt"},"tool_response":{"stdout":"STAGE2 READY\nWorker prompt (first line verbatim):\nHARNESS_OUTLINE_DISPATCH_V1 taskId=task-veri16+verify attemptId=attempt-1 token=sanitized-dispatch-token-1 workerRoot=/sanitized/run8/project","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"<tool-use-5>","duration_ms":12,"event":"PostToolUse"}
13
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","effort":{"level":"medium"},"tool_name":"Agent","tool_input":{"description":"Draft ADR","prompt":"HARNESS_OUTLINE_DISPATCH_V1 taskId=task-veri16+verify attemptId=attempt-1 token=sanitized-dispatch-token-1 workerRoot=/sanitized/run8/project\nDraft the ADR as instructed.","subagent_type":"outline-drafter","run_in_background":false},"tool_use_id":"<tool-use-6>","event":"PreToolUse"}
14
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","agent_id":"<agent-2>","agent_type":"outline-drafter","event":"SubagentStart"}
15
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-2>","agent_type":"outline-drafter","effort":{"level":"medium"},"tool_name":"Read","tool_input":{"file_path":"/sanitized/run8/project/docs/adr/VERI-001.md"},"tool_use_id":"<tool-use-7>","event":"PreToolUse"}
16
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-2>","agent_type":"outline-drafter","effort":{"level":"medium"},"tool_name":"Read","tool_input":{"file_path":"/sanitized/run8/project/docs/adr/VERI-001.md"},"tool_response":{"type":"text","file":{"filePath":"/sanitized/run8/project/docs/adr/VERI-001.md","content":"---\nid: VERI-001\nstatus: proposed\n---\n\nInventory row: 16\nTarget: docs/adr/VERI-001.md\nDomain: VERI\n\n## Outline\n- Context: verification is recorded as observed, timed evidence (verify-gate).\n- Decision: TBD\n","numLines":13,"startLine":1,"totalLines":13}},"tool_use_id":"<tool-use-7>","duration_ms":1,"event":"PostToolUse"}
17
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-2>","agent_type":"outline-drafter","effort":{"level":"medium"},"tool_name":"Write","tool_input":{"file_path":"/sanitized/run8/project/docs/adr/VERI-001.md","content":"---\nid: VERI-001\nstatus: proposed\n---\n\nInventory row: 16\nTarget: docs/adr/VERI-001.md\nDomain: VERI\n\n## Context\nWithout a shared standard, claims that work is verified can rest on anything from a test run to a quick read of the code.\n\n## Decision\nVerification is accepted only as observed, timed command evidence, meaning a command that was actually run with its output and duration recorded. Claims made from reading code are not verification.\n"},"tool_use_id":"<tool-use-8>","event":"PreToolUse"}
18
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-2>","agent_type":"outline-drafter","effort":{"level":"medium"},"tool_name":"Write","tool_input":{"file_path":"/sanitized/run8/project/docs/adr/VERI-001.md","content":"---\nid: VERI-001\nstatus: proposed\n---\n\nInventory row: 16\nTarget: docs/adr/VERI-001.md\nDomain: VERI\n\n## Context\nWithout a shared standard, claims that work is verified can rest on anything from a test run to a quick read of the code.\n\n## Decision\nVerification is accepted only as observed, timed command evidence, meaning a command that was actually run with its output and duration recorded. Claims made from reading code are not verification.\n"},"tool_response":{"type":"update","filePath":"/sanitized/run8/project/docs/adr/VERI-001.md","content":"---\nid: VERI-001\nstatus: proposed\n---\n\nInventory row: 16\nTarget: docs/adr/VERI-001.md\nDomain: VERI\n\n## Context\nWithout a shared standard, claims that work is verified can rest on anything from a test run to a quick read of the code.\n\n## Decision\nVerification is accepted only as observed, timed command evidence, meaning a command that was actually run with its output and duration recorded. Claims made from reading code are not verification.\n","structuredPatch":[{"oldStart":7,"oldLines":6,"newStart":7,"newLines":8,"lines":[" Target: docs/adr/VERI-001.md"," Domain: VERI"," ","-## Outline","-- Context: verification is recorded as observed, timed evidence (verify-gate).","-- Decision: TBD","+## Context","+Without a shared standard, claims that work is verified can rest on anything from a test run to a quick read of the code.","+","+## Decision","+Verification is accepted only as observed, timed command evidence, meaning a command that was actually run with its output and duration recorded. Claims made from reading code are not verification."]}],"originalFile":"---\nid: VERI-001\nstatus: proposed\n---\n\nInventory row: 16\nTarget: docs/adr/VERI-001.md\nDomain: VERI\n\n## Outline\n- Context: verification is recorded as observed, timed evidence (verify-gate).\n- Decision: TBD\n","userModified":false},"tool_use_id":"<tool-use-8>","duration_ms":2,"event":"PostToolUse"}
19
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-2>","agent_type":"outline-drafter","effort":{"level":"medium"},"tool_name":"Bash","tool_input":{"command":"git add docs/adr/VERI-001.md"},"tool_use_id":"<tool-use-9>","event":"PreToolUse"}
20
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-2>","agent_type":"outline-drafter","effort":{"level":"medium"},"tool_name":"Bash","tool_input":{"command":"git add docs/adr/VERI-001.md"},"tool_response":{"stdout":"","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"<tool-use-9>","duration_ms":15,"event":"PostToolUse"}
21
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-2>","agent_type":"outline-drafter","effort":{"level":"medium"},"tool_name":"Bash","tool_input":{"command":"git commit -q -m \"D: draft VERI-001\""},"tool_use_id":"<tool-use-10>","event":"PreToolUse"}
22
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-2>","agent_type":"outline-drafter","effort":{"level":"medium"},"tool_name":"Bash","tool_input":{"command":"git commit -q -m \"D: draft VERI-001\""},"tool_response":{"stdout":"","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"tool_use_id":"<tool-use-10>","duration_ms":23,"event":"PostToolUse"}
23
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","agent_id":"<agent-2>","agent_type":"outline-drafter","effort":{"level":"medium"},"stop_hook_active":false,"agent_transcript_path":"/sanitized/run8/agent-transcripts/transcript-2.jsonl","last_assistant_message":"worker done.","background_tasks":[],"session_crons":[],"event":"SubagentStop"}
24
- {"session_id":"<session-1>","cwd":"/sanitized/run8/project","prompt_id":"<prompt-1>","permission_mode":"default","effort":{"level":"medium"},"tool_name":"Agent","tool_input":{"description":"Draft ADR","prompt":"HARNESS_OUTLINE_DISPATCH_V1 taskId=task-veri16+verify attemptId=attempt-1 token=sanitized-dispatch-token-1 workerRoot=/sanitized/run8/project\nDraft the ADR as instructed.","subagent_type":"outline-drafter","run_in_background":false},"tool_response":{"status":"completed","prompt":"HARNESS_OUTLINE_DISPATCH_V1 taskId=task-veri16+verify attemptId=attempt-1 token=sanitized-dispatch-token-1 workerRoot=/sanitized/run8/project\nDraft the ADR as instructed.","agentId":"<agent-2>","agentType":"outline-drafter","toolsUsed":["Bash","Read","Write"],"harnessNoteCount":1,"harnessTailCount":0,"harnessSectionHash":"f724eae3efefe206","content":[{"type":"text","text":"<tools-used-before-summary>Write</tools-used-before-summary>\n"},{"type":"text","text":"worker done."}],"resolvedModel":"claude-sonnet-5-5","totalDurationMs":16376,"totalTokens":6343,"totalToolUseCount":4,"usage":{"output_tokens_details":{"thinking_tokens":0},"input_tokens":2,"cache_creation_input_tokens":79,"cache_read_input_tokens":6256,"output_tokens":6,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":79},"inference_geo":"global","iterations":[{"input_tokens":2,"output_tokens":6,"cache_read_input_tokens":6256,"cache_creation_input_tokens":79,"cache_creation":{"ephemeral_5m_input_tokens":79,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard","fallback_credit":null},"toolStats":{"readCount":1,"searchCount":0,"bashCount":2,"editFileCount":1,"linesAdded":15,"linesRemoved":0,"otherToolCount":0},"canContinueAgent":true},"tool_use_id":"<tool-use-6>","duration_ms":16376,"event":"PostToolUse"}
@@ -1,482 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
- const crypto = require('crypto');
6
- const { execFileSync } = require('child_process');
7
- const { atomicWriteJson } = require('./fable-contracts');
8
- const { canonical, key } = require('./workflow-isolation');
9
-
10
- const enabled = () => process.env.HARNESS_DOC_RECONCILIATION_PILOT === '1';
11
- const text = value => typeof value === 'string' && value.trim().length > 0;
12
-
13
- function git(root, args) {
14
- const env = { ...process.env };
15
- for (const key of Object.keys(env)) if (key.startsWith('GIT_')) delete env[key];
16
- try {
17
- return execFileSync('git', ['-C', root, ...args], {
18
- env, encoding: 'utf8', timeout: 10000, maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'],
19
- });
20
- } catch (cause) {
21
- throw new Error('baseline-unavailable', { cause });
22
- }
23
- }
24
-
25
- function runtimeModule(name) {
26
- for (const relative of ['../../../harness-everything/scripts', '../../../skills/harness-everything/scripts']) {
27
- const file = path.resolve(__dirname, relative, name + '.js');
28
- if (fs.existsSync(file)) return require(file);
29
- }
30
- throw new Error('document runtime unavailable');
31
- }
32
-
33
- // Only capture at plan/start. A later credit assessment must never advance the baseline to HEAD.
34
- function captureBaseline(context) {
35
- if (!enabled()) return;
36
- try {
37
- if (!context.workflow.docReconciliationBaseline) {
38
- const root = canonical(git(context.root, ['rev-parse', '--show-toplevel']).trim());
39
- const commit = git(root, ['rev-parse', '--verify', 'HEAD^{commit}']).trim();
40
- const tree = git(root, ['rev-parse', '--verify', `${commit}^{tree}`]).trim();
41
- context.workflow.docReconciliationBaseline = { root, commit, tree };
42
- } else if (!context.workflow.docReconciliationBaseline.tree) {
43
- const pin = context.workflow.docReconciliationBaseline;
44
- pin.tree = git(pin.root, ['rev-parse', '--verify', `${pin.commit}^{tree}`]).trim();
45
- }
46
- if (!context.workflow.docReconciliationTask) {
47
- const plan = context.workflow.pendingPlan || context.workflow.workflowPlan;
48
- // workflow-obligations is a hook-lib sibling in every layout, not a skill runtime script.
49
- const loaded = plan && require('./workflow-obligations').loadObligationSet(context, plan);
50
- const requirementIds = loaded?.set?.requirements?.map(item => item.id);
51
- if (Array.isArray(requirementIds) && requirementIds.length && requirementIds.every(id => typeof id === 'string' && id)) {
52
- const baseline = context.workflow.docReconciliationBaseline;
53
- const resolver = runtimeModule('project-docs-resolver');
54
- const configSources = configSourcePaths(resolver).map(relative => {
55
- const bytes = bytesAtBaseline(baseline.root, baseline.commit, relative);
56
- return [relative, bytes === null ? null : crypto.createHash('sha256').update(bytes).digest('hex')];
57
- });
58
- const hash = value => crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
59
- const workspaceId = 'ws-' + hash({ workspaceRoot: canonical(baseline.root) });
60
- context.workflow.docReconciliationTask = {
61
- schema: 'harness.doc-reconciliation-task-pin.v1',
62
- taskId: `task-${requirementIds.join('+')}`, requirementIds,
63
- requirementDigest: hash(requirementIds), sessionId: context.sessionId,
64
- workflowId: context.workflow.workflowId, workspaceId,
65
- baselineCommit: baseline.commit, baselineRoot: baseline.root,
66
- configDigest: hash(configSources),
67
- };
68
- }
69
- }
70
- } catch {
71
- // Absence is intentionally retained; credit assessment will fail closed.
72
- }
73
- }
74
-
75
- // PR #351 review P1 (config authority): derivation runs on the current config, so a candidate
76
- // config edit could de-scope a baseline-governed path. Every resolver-selectable config source —
77
- // `.agents/harness-everything/project-docs.json` and each host `<home>/harness-everything/manifest.json`
78
- // for the resolver's PLATFORM_HOMES — is byte-compared at the recorded baseline commit and in the
79
- // working tree. An edit, an addition or a removal all fail closed before derivation; absence of a
80
- // source on either side is allowed and only a difference is fatal.
81
- const PROJECT_DOCS_CONFIG_RELPATH = '.agents/harness-everything/project-docs.json';
82
-
83
- function configSourcePaths(resolver) {
84
- return [
85
- PROJECT_DOCS_CONFIG_RELPATH,
86
- ...(resolver.PLATFORM_HOMES || []).map(home => `${home}/harness-everything/manifest.json`),
87
- ];
88
- }
89
-
90
- function bytesAtBaseline(root, commit, relative) {
91
- const listed = git(root, ['ls-tree', '-r', '--name-only', '-z', commit, '--', relative]);
92
- if (!listed.split('\0').includes(relative)) return null; // absent at the baseline is allowed
93
- return git(root, ['show', `${commit}:${relative}`]); // other Git failures stay baseline-unavailable
94
- }
95
-
96
- function bytesInTree(root, relative) {
97
- try {
98
- return fs.readFileSync(path.join(root, relative), 'utf8');
99
- } catch (error) {
100
- if (error.code === 'ENOENT') return null; // absent in the working tree is allowed
101
- throw error;
102
- }
103
- }
104
-
105
- function assertConfigScopeUnchanged(root, baseline, resolver) {
106
- for (const relative of configSourcePaths(resolver)) {
107
- if (bytesAtBaseline(root, baseline.commit, relative) !== bytesInTree(root, relative)) {
108
- throw new Error('config-scope-changed');
109
- }
110
- }
111
- }
112
-
113
- function collect(context) {
114
- const baseline = context.workflow.docReconciliationBaseline;
115
- if (!baseline) throw new Error('baseline-unavailable');
116
- const root = canonical(git(context.root, ['rev-parse', '--show-toplevel']).trim());
117
- if (!text(baseline.root) || key(root) !== key(baseline.root)
118
- || !/^[0-9a-f]{40,64}$/.test(baseline.commit)) throw new Error('baseline-unavailable');
119
- const resolver = runtimeModule('project-docs-resolver');
120
- const resolved = resolver.resolveDocsConfig(root);
121
- if (!['project', 'host'].includes(resolved.status)) throw new Error('config-unavailable');
122
- assertConfigScopeUnchanged(root, baseline, resolver);
123
- const { readGitBaseInventory, scanWorkspaceFiles } = runtimeModule('doc-lifecycle');
124
- // Broaden artifact discovery only, never the config passed to obligation derivation. Code/REQ-test
125
- // facts require baseline bytes outside governed document globs as well.
126
- const base = readGitBaseInventory(root, baseline.commit, { governed: [{ path: '**/*', role: 'reference' }] });
127
- const basePaths = git(root, ['ls-tree', '-r', '--name-only', '-z', baseline.commit]).split('\0').filter(Boolean);
128
- if (!base.available) throw new Error('baseline-unavailable');
129
- if (base.files.length !== basePaths.length) throw new Error('scope-unavailable');
130
- const paths = [...new Set(git(root, ['ls-files', '-c', '-o', '--exclude-standard', '-z']).split('\0').filter(Boolean))];
131
- const existing = paths.filter(relative => {
132
- try {
133
- if (!fs.lstatSync(path.join(root, relative)).isFile()) throw new Error('scope-unavailable');
134
- return true;
135
- } catch (error) {
136
- if (error.code === 'ENOENT') return false; // tracked deletion
137
- throw error;
138
- }
139
- });
140
- const candidate = scanWorkspaceFiles(root, { paths: existing });
141
- if (candidate.length !== existing.length) throw new Error('scope-unavailable');
142
- const snapshots = files => ({ files: Object.fromEntries(files.map(item => [item.path, item.bytes.toString('utf8')])) });
143
- const { deriveDocFacts, deriveDocObligations } = runtimeModule('doc-obligations');
144
- const { facts } = deriveDocFacts({ base: snapshots(base.files), candidate: snapshots(candidate), config: resolved.config, inventory: { complete: true } });
145
- return deriveDocObligations(facts).filter(item => item.strength === 'MUST' && item.applicability !== 'N/A');
146
- }
147
-
148
- // S2b credit chain (F4): produce the snapshot, accept the origin-provider events, and check them against the expected
149
- // MUSTs. Credit only when the core marks the evidence eligible. Production has no qualification, so it stays withheld.
150
- function creditChain(context, set, dependencies = {}) {
151
- const hostId = activeHostFor(context);
152
- const providerModule = require('./doc-reconciliation-provider');
153
- const captureView = hostId === 'opencode' ? providerModule.readOpencodeCaptureView(context.sessionDir)
154
- : hostId === 'claude-code' ? providerModule.readCaptureView(context.sessionDir)
155
- : { records: [], tampered: false };
156
- if (captureView.tampered) {
157
- return { eligible: false, outlineEvidence: { outcome: 'none', observation: 'unresolved', reason: 'journal-tampered' },
158
- diagnostics: [{ code: 'journal-tampered', message: 'the capture journal no longer matches its immutable event records' }] };
159
- }
160
- if (!['claude-code', 'opencode'].includes(hostId)) {
161
- return { eligible: false, outlineEvidence: { outcome: 'none', observation: 'unresolved', reason: 'unsupported-host' },
162
- diagnostics: [{ code: 'unsupported-host', message: `no document origin provider is registered for ${String(hostId)}` }] };
163
- }
164
- const { produceDocSnapshot } = require('./doc-reconciliation-producer');
165
- const { acceptDocEvents } = require('./doc-reconciliation-events');
166
- const { checkAcceptedDocEvidence } = require('./doc-reconciliation-core');
167
- const baseline = context.workflow.docReconciliationBaseline;
168
- const requirements = Array.isArray(set?.requirements) ? set.requirements : [];
169
- const requirementIds = requirements.map(item => item.id);
170
- const derivedTaskId = `task-${requirementIds.join('+') || 'none'}`;
171
- const taskBinding = context.workflow.docReconciliationTask || null;
172
- const taskId = taskBinding?.taskId || derivedTaskId;
173
- if (taskBinding && (taskBinding.taskId !== derivedTaskId || taskBinding.workflowId !== context.workflow.workflowId
174
- || taskBinding.sessionId !== context.sessionId || taskBinding.baselineCommit !== baseline?.commit
175
- || !text(taskBinding.baselineRoot) || !text(baseline?.root)
176
- || key(taskBinding.baselineRoot) !== key(baseline.root)
177
- || taskBinding.requirementDigest !== crypto.createHash('sha256').update(JSON.stringify(requirementIds)).digest('hex')) ) {
178
- return { eligible: false, outlineEvidence: { outcome: 'none', observation: 'unresolved', reason: 'task-binding-mismatch' },
179
- diagnostics: [{ code: 'task-binding-mismatch', message: 'the requirement set or original B differs from the task pin' }] };
180
- }
181
- const sessionId = context.sessionId;
182
- const { createClaudeOriginProvider, createOpencodeOriginProvider, journalExecutors } = providerModule;
183
- const captures = captureView.records;
184
- const principals = hostId === 'opencode'
185
- ? { author: sessionId, executors: [sessionId] }
186
- : { author: sessionId, executors: journalExecutors(captures, sessionId) };
187
- const createOriginProvider = hostId === 'opencode' ? createOpencodeOriginProvider : createClaudeOriginProvider;
188
- const providerInput = {
189
- hostId,
190
- sessionId,
191
- workspaceRoot: context.root,
192
- workflowId: context.workflow.workflowId,
193
- workflowRevision: context.workflow.revision,
194
- taskId,
195
- sessionDir: context.sessionDir,
196
- taskBinding,
197
- principals,
198
- baseline,
199
- captures,
200
- allowInFlightW6ToolUseId: dependencies.allowInFlightW6ToolUseId || null,
201
- };
202
- const originProvider = dependencies.originProvider || createOriginProvider(providerInput);
203
- const produced = produceDocSnapshot({
204
- workspaceRoot: context.root,
205
- baseline,
206
- workflow: { workflowId: context.workflow.workflowId, sessionId, workflowRevision: context.workflow.revision },
207
- task: { taskId, requirements },
208
- scope: { prdRoot: 'docs/prd/' },
209
- activeHost: hostId,
210
- prdRoot: 'docs/prd/',
211
- }, { originProvider });
212
- if (produced.state !== 'ready' || !produced.snapshot) return {
213
- eligible: false,
214
- outlineEvidence: { outcome: 'none', observation: 'unresolved', reason: produced.diagnostics?.[0]?.code || 'snapshot-unavailable' },
215
- diagnostics: produced.diagnostics || [],
216
- unsatisfied: [],
217
- };
218
- const eventRefs = captureReferences(context);
219
- const accepted = acceptDocEvents({ snapshot: produced.snapshot, eventRefs }, { originProvider });
220
- const checked = checkAcceptedDocEvidence({ snapshot: produced.snapshot, accepted, mode: 'verification' });
221
- // Credit covers only the expected MUSTs that were both accepted and satisfied (passing, observed). N/A never counts.
222
- const passing = new Set((checked.results || []).filter(r => r.observation === 'observed' && r.outcome === 'pass').map(r => r.obligationId));
223
- const expected = new Set(checked.checkedMustIds || []);
224
- const satisfied = produced.snapshot.obligations.filter(o => o.strength === 'MUST' && o.applicability !== 'N/A' && expected.has(o.id) && passing.has(o.id));
225
- const outlineObligation = produced.snapshot.obligations.find(item => item.capability === 'outline-confirmation');
226
- const outlineResult = outlineObligation && (checked.results || []).find(item => item.obligationId === outlineObligation.id);
227
- const outlineRefs = Object.entries(accepted.acceptedIndex || {}).filter(([, item]) => item.capability === 'outline-confirmation').map(([ref]) => ref);
228
- const outlineEvidence = {
229
- status: outlineResult?.observation === 'observed' && outlineResult?.outcome === 'pass' ? 'pass' : 'unresolved',
230
- outcome: outlineResult?.outcome || 'none',
231
- observation: outlineResult?.observation || 'unresolved',
232
- recordRefs: outlineResult?.recordRefs || [],
233
- acceptedRefs: outlineRefs,
234
- diagnostics: [...(accepted.diagnostics || []), ...(accepted.rejected || []), ...(checked.diagnostics || [])]
235
- .filter(item => !item?.obligationId || item.obligationId === outlineObligation?.id),
236
- };
237
- return {
238
- eligible: checked.eligible === true,
239
- capabilities: checked.eligible === true ? [...new Set(satisfied.map(o => o.capability))] : [],
240
- satisfiedObligationIds: satisfied.map(o => o.id),
241
- unsatisfied: checked.unsatisfied || [],
242
- acceptedRefs: Object.keys(accepted.acceptedIndex || {}),
243
- outlineEvidence,
244
- diagnostics: [...(accepted.diagnostics || []), ...(checked.diagnostics || [])],
245
- rejected: accepted.rejected || [],
246
- };
247
- }
248
-
249
- // Report diagnostics are objects with the obligation they concern (F12); a global fault has obligationId null.
250
- function diagnosticOf(item) {
251
- if (item && typeof item === 'object') return { ...item, code: item.code || 'unknown', obligationId: item.obligationId ?? null };
252
- return { code: String(item), obligationId: null };
253
- }
254
-
255
- // Review-mode refusal (F4 I2a): with the pilot ON in a supported (non-Fable) workflow, a review step PASS needs an
256
- // independent quality-review record. The provider's own independence rules decide it: a host agent_id that differs from
257
- // the author session, an explicit approve verdict, a non-empty summary and the bound final-artifact digest.
258
- function reviewRequired(set) {
259
- return enabled() && set?.stepBindingsEnabled === true && !String(set?.strategy || '').startsWith('fable-');
260
- }
261
-
262
- // The review step is independent of credit qualification: the step records host-observed independence, while document
263
- // credit itself still needs the validated qualification (assess).
264
- function independentReviewAccepted(context) {
265
- if (activeHostFor(context) !== 'claude-code') return false;
266
- const { reviewRecordIndependent, journalExecutors } = require('./doc-reconciliation-provider');
267
- const view = require('./doc-reconciliation-provider').readCaptureView(context.sessionDir);
268
- if (view.tampered) return false;
269
- const captures = view.records;
270
- const principals = { author: context.sessionId, executors: journalExecutors(captures, context.sessionId) };
271
- const pin = context.workflow.docReconciliationBaseline;
272
- return captures.some(item => recordOf(item) && item.session_id === context.sessionId
273
- && recordOf(item.observedIdentity) && item.observedIdentity.workflowId === context.workflow.workflowId
274
- && item.observedIdentity.workflowRevision === context.workflow.revision
275
- && (!pin || (recordOf(item.observedIdentity.baselinePin) && item.observedIdentity.baselinePin.commit === pin.commit))
276
- && reviewRecordIndependent(item, captures, principals));
277
- }
278
-
279
- function recordOf(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
280
-
281
- function activeHostFor(context) {
282
- return context.activeHost === undefined || context.activeHost === null ? 'claude-code' : context.activeHost;
283
- }
284
-
285
- // The session capture records are the only host-event source. A missing journal means no events; a journal that no longer
286
- // equals its immutable event files is tampered and yields no events, so the chain withholds.
287
- function readCaptures(context) {
288
- const provider = require('./doc-reconciliation-provider');
289
- const hostId = activeHostFor(context);
290
- if (hostId === 'opencode') return provider.readOpencodeCaptureView(context.sessionDir).records;
291
- if (hostId === 'claude-code') return provider.readCaptureView(context.sessionDir).records;
292
- return [];
293
- }
294
-
295
- // Only explicit PostToolUse doc-check candidates are offered; ordinary Edit or Agent results are not (R3-01).
296
- const docCheckCandidate = item => item.event === 'PostToolUse'
297
- && require('./doc-reconciliation-provider').resolveDocCheckInvocation(item.command, item.cwd).kind !== 'not-candidate';
298
-
299
- function outlineReviewCaptureRefs(sessionDir, taskId) {
300
- const refs = new Set();
301
- if (!text(taskId)) return refs;
302
- const attempts = path.join(sessionDir, 'doc-reconciliation', 'outline-confirmation', taskId, 'attempts');
303
- try {
304
- for (const entry of fs.readdirSync(attempts, { withFileTypes: true })) {
305
- if (!entry.isDirectory()) continue;
306
- try {
307
- const handoff = JSON.parse(fs.readFileSync(path.join(attempts, entry.name, 'handoff.json'), 'utf8'));
308
- if (handoff.taskId === taskId && typeof handoff.reviewCaptureRef === 'string') refs.add(handoff.reviewCaptureRef);
309
- } catch { /* malformed handoff cannot add review credit */ }
310
- }
311
- } catch { /* no attempts yet */ }
312
- return refs;
313
- }
314
-
315
- function outlineDispatchReferences(captures, taskId, sessionDir) {
316
- if (!text(taskId)) return [];
317
- const candidates = (Array.isArray(captures) ? captures : []).filter(item => recordOf(item)
318
- && item.event === 'PreToolUse' && ['Task', 'Agent'].includes(item.tool_name)
319
- && text(item.ref) && item.outlineDispatch?.taskId === taskId && text(item.outlineDispatch.attemptId));
320
- if (!candidates.length) return [];
321
- if (text(sessionDir)) {
322
- const provider = require('./doc-reconciliation-provider');
323
- const attemptIds = [...new Set(candidates.map(item => item.outlineDispatch.attemptId))];
324
- const resolved = attemptIds.map(attemptId => ({ attemptId,
325
- attempt: provider._internals.resolveOutlineAttempt({ sessionDir, taskId, attemptId }) }));
326
- const current = resolved.filter(item => item.attempt.state === 'accepted');
327
- if (current.length === 1) {
328
- const dispatches = candidates.filter(item => item.outlineDispatch.attemptId === current[0].attemptId);
329
- return dispatches.length ? [`${dispatches[0].ref}#outline-confirmation`] : [];
330
- }
331
- if (current.length > 1 || attemptIds.length > 1) return [];
332
- }
333
- const tuples = [...new Set(candidates.map(item => `${item.outlineDispatch.attemptId}\0${item.tool_use_id || ''}\0${item.outlineDispatch.dispatchInputDigest || ''}`))];
334
- if (tuples.length > 1 && !candidates.some(item => item.outlineDispatch.state === 'unresolved')) return [];
335
- return [`${candidates[0].ref}#outline-confirmation`];
336
- }
337
-
338
- function captureReferences(context) {
339
- const captures = readCaptures(context);
340
- if (activeHostFor(context) === 'opencode') {
341
- return captures.filter(item => typeof item?.call_id === 'string' && item.call_id.trim())
342
- .flatMap(item => ['doc-lint', 'link-check'].map(capability => `${item.call_id}#${capability}`));
343
- }
344
- const candidates = captures
345
- .filter(item => item && typeof item.ref === 'string' && (item.event === 'SubagentStop' || docCheckCandidate(item)))
346
- .filter(item => item.event !== 'SubagentStop');
347
- const taskId = context.workflow.docReconciliationTask?.taskId;
348
- const outlineReviews = outlineReviewCaptureRefs(context.sessionDir, taskId);
349
- const reviews = captures.filter(item => item && typeof item.ref === 'string' && item.event === 'SubagentStop'
350
- && ['approve', 'reject'].includes(item.reviewVerdict) && !outlineReviews.has(item.ref));
351
- const references = [];
352
- for (const [index, capability] of ['doc-lint', 'link-check'].entries()) {
353
- const ordered = index ? candidates.slice(1).concat(candidates.slice(0, 1)) : candidates;
354
- references.push(...ordered.map(item => `${item.ref}#${capability}`));
355
- }
356
- const provider = require('./doc-reconciliation-provider');
357
- references.push(...candidates.filter(item => provider.resolveDocCheckInvocation(item.command, item.cwd).conflictAssessment === true)
358
- .map(item => `${item.ref}#conflict-check`));
359
- references.push(...candidates.filter(item => provider.resolveDocCheckInvocation(item.command, item.cwd).derivedView)
360
- .map(item => `${item.ref}#derived-regenerate`));
361
- references.push(...outlineDispatchReferences(captures, taskId, context.sessionDir));
362
- // The adapter accepts one event per capability; rotating candidate order lets separate valid runs fill each capability.
363
- return [...references, ...reviews.map(item => `${item.ref}#quality-review`)];
364
- }
365
-
366
- // R3-02: verification recorded before an installed-runtime change is withdrawn once the live doc-check leaves the pin.
367
- // Capture time sees the pristine runtime, so only assessment can catch a later change. Scoped to sessions that ran a doc-check.
368
- function withdrawChangedRuntimeVerification(context) {
369
- try {
370
- const provider = require('./doc-reconciliation-provider');
371
- const installed = provider.installedDocCheck();
372
- if (!installed || provider.fileDigest(installed) === provider.SHIPPED_DOC_CHECK_DIGEST) return;
373
- if (!readCaptures(context).some(item => {
374
- if (!item || item.event !== 'PostToolUse') return false;
375
- const invocation = provider.resolveDocCheckInvocation(item.command, item.cwd);
376
- return invocation.kind === 'accepted' || invocation.reason === 'implementation-pin-mismatch';
377
- })) return;
378
- const file = path.join(context.sessionDir, 'handoff-state.json');
379
- const handoff = JSON.parse(fs.readFileSync(file, 'utf8'));
380
- const genericAt = handoff.lastGenericVerifyAt;
381
- const hasGeneric = typeof genericAt === 'number' && Number.isFinite(genericAt);
382
- const hasDoc = typeof handoff.lastDocVerifyAt === 'number' && Number.isFinite(handoff.lastDocVerifyAt);
383
- if (!hasGeneric && !hasDoc && handoff.lastVerifyAt === undefined) return;
384
- delete handoff.lastDocVerifyAt;
385
- delete handoff.lastDocVerifyExitCode;
386
- if (hasGeneric) {
387
- handoff.lastVerifyAt = genericAt;
388
- if (Object.prototype.hasOwnProperty.call(handoff, 'lastGenericVerifyExitCode')) {
389
- handoff.lastVerifyExitCode = handoff.lastGenericVerifyExitCode;
390
- } else {
391
- delete handoff.lastVerifyExitCode;
392
- }
393
- } else {
394
- // Older aggregate-only state has unknown ownership; do not preserve it as unaffected evidence.
395
- delete handoff.lastVerifyAt;
396
- delete handoff.lastVerifyExitCode;
397
- }
398
- atomicWriteJson(file, handoff);
399
- } catch { /* fail-open: no handoff state yet, or nothing to withdraw */ }
400
- }
401
-
402
- // Assessment is deliberately negative-credit only in S1. Unsupported topologies never enter
403
- // generic step reconciliation, and failures (including report persistence) never escape to Stop.
404
- function assess(context, set, dependencies = {}) {
405
- if (!enabled()) return { withhold: false };
406
- withdrawChangedRuntimeVerification(context);
407
- const report = {
408
- schemaVersion: 1, reportOrigin: 'runtime', pilotStatus: 'unavailable', pilotCredit: false,
409
- identity: null, expectedMustIds: [], results: [], unsatisfied: [], diagnostics: [],
410
- outlineEvidence: { status: 'unresolved', outcome: 'none', observation: 'unresolved', acceptedRefs: [], recordRefs: [], diagnostics: [] },
411
- };
412
- const supported = set?.stepBindingsEnabled === true && !String(context.workflow.strategy || '').startsWith('fable-');
413
- let withhold = false;
414
- if (!supported) report.diagnostics.push('unsupported-workflow');
415
- else {
416
- try {
417
- const musts = collect(context);
418
- withhold = musts.length > 0;
419
- report.pilotStatus = 'unresolved';
420
- report.expectedMustIds = musts.map(item => item.id);
421
- report.unsatisfied = musts.map(item => ({
422
- obligationId: item.id, state: item.applicability === 'unknown' ? 'unknown' : 'pending',
423
- reasonCode: item.applicability === 'unknown' ? 'unknown-applicability' : 'producer-unavailable',
424
- }));
425
- if (!withhold) report.diagnostics.push('trusted-non-document-scope');
426
- const hasOutlineCapture = captureReferences(context).some(reference => reference.endsWith('#outline-confirmation'));
427
- if (withhold || hasOutlineCapture) {
428
- let chain;
429
- try { chain = creditChain(context, set, dependencies); }
430
- catch (error) { chain = { eligible: false, outlineEvidence: { status: 'unresolved', outcome: 'none',
431
- observation: 'unresolved', reason: 'collector-unavailable', acceptedRefs: [], recordRefs: [], diagnostics: [] },
432
- diagnostics: [{ code: 'collector-unavailable', message: String(error.message) }] }; }
433
- report.outlineEvidence = chain.outlineEvidence || report.outlineEvidence;
434
- report.acceptedRefs = chain.acceptedRefs || [];
435
- report.diagnostics.push(...(chain.diagnostics || []));
436
- if (withhold) {
437
- // The unsatisfied list is rewritten from the chain: a MUST that the chain did not satisfy stays listed (F3).
438
- const satisfied = new Set(chain.satisfiedObligationIds || []);
439
- report.unsatisfied = [
440
- ...musts.filter(item => !satisfied.has(item.id)).map(item => ({
441
- obligationId: item.id, state: item.applicability === 'unknown' ? 'unknown' : 'pending',
442
- reasonCode: item.applicability === 'unknown' ? 'unknown-applicability' : 'producer-unavailable',
443
- })),
444
- ...(chain.unsatisfied || []),
445
- ];
446
- report.creditedCapabilities = chain.eligible === true ? chain.capabilities : [];
447
- // Credit needs an empty unsatisfied list across both sources and at least one satisfied capability.
448
- withhold = !(chain.eligible === true && report.unsatisfied.length === 0 && report.creditedCapabilities.length > 0);
449
- report.pilotCredit = !withhold;
450
- report.pilotStatus = report.pilotCredit ? 'credited' : 'unresolved';
451
- }
452
- }
453
- } catch (error) {
454
- withhold = true;
455
- const reason = ['baseline-unavailable', 'config-unavailable', 'scope-unavailable', 'config-scope-changed'].includes(error.message)
456
- ? error.message : 'collector-unavailable';
457
- report.diagnostics.push(reason);
458
- report.unsatisfied.push({ obligationId: 'doc-change:scope', state: 'unavailable', reasonCode: reason });
459
- }
460
- }
461
- if (!withhold && dependencies.allowInFlightW6ToolUseId) {
462
- report.pilotCredit = false;
463
- report.pilotStatus = 'pending';
464
- report.creditedCapabilities = [];
465
- report.acceptedRefs = [];
466
- report.outlineEvidence = { status: 'pending', outcome: 'none', observation: 'pending',
467
- acceptedRefs: [], recordRefs: [], diagnostics: [{ code: 'state-operation-in-flight',
468
- message: 'the verification state operation has not completed its host result', obligationId: null }] };
469
- report.diagnostics.push({ code: 'state-operation-in-flight',
470
- message: 'the verification state operation has not completed its host result', obligationId: null });
471
- }
472
- report.diagnostics = report.diagnostics.map(diagnosticOf);
473
- try { atomicWriteJson(path.join(context.sessionDir, 'doc-reconciliation-pilot.json'), report); }
474
- catch {
475
- if (supported) withhold = true;
476
- console.error('[Workflow Reminder] Document pilot report unavailable; no document verification credit.');
477
- }
478
- return { withhold, report };
479
- }
480
-
481
- module.exports = { enabled, captureBaseline, assess, reviewRequired, independentReviewAccepted,
482
- _internals: { captureReferences, outlineDispatchReferences, outlineReviewCaptureRefs } };