harness-everything 1.3.0 → 1.3.2

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 (216) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/AGENTS.md +1 -1
  4. package/CHANGELOG.md +14 -0
  5. package/behavioral-evals/ledger-pairs/README.md +53 -0
  6. package/behavioral-evals/ledger-pairs/arm.js +359 -0
  7. package/behavioral-evals/ledger-pairs/fixture.js +138 -0
  8. package/behavioral-evals/ledger-pairs/preflight.js +96 -0
  9. package/behavioral-evals/ledger-pairs/score.js +155 -0
  10. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/README.md +108 -0
  11. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-baseline/arm-plan.json +14 -0
  12. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-baseline/arm-result.json +35 -0
  13. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-treatment/arm-plan.json +14 -0
  14. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-1-treatment/arm-result.json +35 -0
  15. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-baseline/arm-plan.json +14 -0
  16. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-baseline/arm-result.json +35 -0
  17. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-treatment/arm-plan.json +14 -0
  18. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-2-treatment/arm-result.json +35 -0
  19. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-baseline/arm-plan.json +14 -0
  20. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-baseline/arm-result.json +35 -0
  21. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-treatment/arm-plan.json +14 -0
  22. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-3-treatment/arm-result.json +35 -0
  23. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-baseline/arm-plan.json +14 -0
  24. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-baseline/arm-result.json +28 -0
  25. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-treatment/arm-plan.json +14 -0
  26. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/agy/pair-4-treatment/arm-result.json +35 -0
  27. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-baseline/arm-plan.json +13 -0
  28. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-baseline/arm-result.json +56 -0
  29. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-treatment/arm-plan.json +13 -0
  30. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-1-treatment/arm-result.json +56 -0
  31. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-baseline/arm-plan.json +13 -0
  32. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-baseline/arm-result.json +56 -0
  33. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-treatment/arm-plan.json +13 -0
  34. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-2-treatment/arm-result.json +56 -0
  35. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-baseline/arm-plan.json +13 -0
  36. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-baseline/arm-result.json +49 -0
  37. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-treatment/arm-plan.json +13 -0
  38. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-3-treatment/arm-result.json +49 -0
  39. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-baseline/arm-plan.json +13 -0
  40. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-baseline/arm-result.json +49 -0
  41. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-treatment/arm-plan.json +13 -0
  42. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/codex/pair-4-treatment/arm-result.json +56 -0
  43. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-baseline/arm-plan.json +14 -0
  44. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-baseline/arm-result.json +44 -0
  45. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-baseline/receipt.jsonl +17 -0
  46. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-treatment/arm-plan.json +14 -0
  47. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-treatment/arm-result.json +41 -0
  48. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-1-treatment/receipt.jsonl +58 -0
  49. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-baseline/arm-plan.json +14 -0
  50. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-baseline/arm-result.json +50 -0
  51. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-baseline/receipt.jsonl +101 -0
  52. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-treatment/arm-plan.json +14 -0
  53. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-treatment/arm-result.json +44 -0
  54. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-2-treatment/receipt.jsonl +29 -0
  55. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-baseline/arm-plan.json +14 -0
  56. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-baseline/arm-result.json +44 -0
  57. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-baseline/receipt.jsonl +23 -0
  58. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-treatment/arm-plan.json +14 -0
  59. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-treatment/arm-result.json +34 -0
  60. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-3-treatment/receipt.jsonl +24 -0
  61. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-baseline/arm-plan.json +14 -0
  62. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-baseline/arm-result.json +47 -0
  63. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-baseline/receipt.jsonl +69 -0
  64. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-treatment/arm-plan.json +14 -0
  65. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-treatment/arm-result.json +44 -0
  66. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/opencode/pair-4-treatment/receipt.jsonl +65 -0
  67. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/run-order.sh +18 -0
  68. package/benchmarks/results/live-host/ledger-pairs-2026-11-28/score.json +1032 -0
  69. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/README.md +50 -0
  70. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/collect-rerun.txt +3 -0
  71. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/export-report.json +22 -0
  72. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/host-version.txt +1 -0
  73. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/import-report-1.json +18 -0
  74. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/import-report-2.json +18 -0
  75. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/labels-observed-excerpt.jsonl +2 -0
  76. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/observations-index-excerpt.json +26 -0
  77. package/benchmarks/results/live-host/opencode-2026-11-28-397-turn-export/plugin-load-lines.txt +1 -0
  78. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/README.md +46 -0
  79. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/observations-index-excerpt.json +16 -0
  80. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/plugin-load-lines.txt +2 -0
  81. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/run-marks.txt +6 -0
  82. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/steering-probe.js +16 -0
  83. package/benchmarks/results/live-host/opencode-2026-11-28-450-steering-trace/steering-trace.jsonl +167 -0
  84. package/ci/archive/325-prep/README.md +9 -2
  85. package/ci/archive/325-prep/doc-reconciliation-red.js +34 -8
  86. package/ci/fixtures/553-t2a/body-edit/base/.agents/harness-everything/project-docs.json +11 -0
  87. package/ci/fixtures/553-t2a/body-edit/base/docs/a.md +6 -0
  88. package/ci/fixtures/553-t2a/body-edit/base/docs/b.md +1 -0
  89. package/ci/fixtures/553-t2a/body-edit/candidate/docs/a.md +6 -0
  90. package/ci/fixtures/553-t2c/derived-regenerate-must/base/docs/adr/EVID-001-verify-all-evidence.md +11 -0
  91. package/ci/fixtures/553-t2c/derived-regenerate-must/base/docs/governed-index.md +19 -0
  92. package/ci/fixtures/553-t2c/derived-regenerate-must/candidate/docs/adr/EVID-001-verify-all-evidence.md +11 -0
  93. package/ci/fixtures/553-t2c/derived-regenerate-must/candidate/docs/governed-index.md +19 -0
  94. package/ci/fixtures/553-t2c/derived-regenerate-must/config.json +17 -0
  95. package/ci/fixtures/doc-obligations/derive/regression-pins.json +153 -0
  96. package/ci/fixtures/state-persist-post-tool-use/harness.js +206 -0
  97. package/ci/fixtures/state-persist-post-tool-use/off-handoff-golden.json +16 -0
  98. package/ci/fixtures/state-persist-post-tool-use/payload-post-tool-use-success.json +13 -0
  99. package/ci/fixtures/stop/fail-session-writes.js +109 -0
  100. package/ci/fixtures/workflow-contract/cases.json +3355 -0
  101. package/ci/fixtures/workflow-contract/wiring-cases.json +560 -0
  102. package/ci/lib/doc-reconciliation-prep-fixtures.js +4 -9
  103. package/ci/mechanism-2an-workflow-replay.test.js +324 -0
  104. package/ci/mechanism-2ax-doc-lifecycle.test.js +132 -0
  105. package/ci/mechanism-325-3a-doc-evidence.test.js +73 -0
  106. package/ci/mechanism-325-3a-doc-obligations.test.js +61 -0
  107. package/ci/mechanism-325-3b-preparation.test.js +208 -49
  108. package/ci/mechanism-325-3b-s1-review.test.js +20 -828
  109. package/ci/mechanism-325-3b-s3-providers.test.js +59 -0
  110. package/ci/mechanism-325-f3-derived-views.test.js +140 -0
  111. package/ci/mechanism-332-fable-directive.test.js +180 -0
  112. package/ci/mechanism-341-opencode-lane.test.js +164 -284
  113. package/ci/mechanism-35-verification-contract.test.js +246 -0
  114. package/ci/mechanism-365-step-edit-accounting.test.js +5 -6
  115. package/ci/mechanism-383-doc-glob-line-terminators.test.js +0 -30
  116. package/ci/mechanism-397-opencode-observations.test.js +151 -18
  117. package/ci/mechanism-552-ledger-pairs.test.js +159 -0
  118. package/ci/mechanism-553-e1-unhook-credit.test.js +328 -0
  119. package/ci/mechanism-553-p2a-claude-hooks.test.js +98 -0
  120. package/ci/mechanism-553-p3-plan-start.test.js +212 -0
  121. package/ci/mechanism-553-state-persist-post-tool-use.test.js +307 -0
  122. package/ci/mechanism-553-stop.test.js +427 -0
  123. package/ci/mechanism-553-t2a-derive.test.js +110 -0
  124. package/ci/mechanism-553-t2c-derive.test.js +94 -0
  125. package/ci/mechanism-e1-derived-regenerate.test.js +45 -206
  126. package/ci/mechanism-outline-sanitizer.test.js +0 -8
  127. package/ci/mechanism-pr-a-conflict-check.test.js +38 -305
  128. package/ci/mechanism-prb-outline-review.test.js +101 -3283
  129. package/ci/router-workflow-plan.test.js +61 -21
  130. package/docs/adr/DOCS-006-reconciliation-pilot.md +4 -2
  131. package/docs/adr/DOCS-008-obligation-abstraction-bounded-consumer.md +3 -3
  132. package/docs/doc-workflow-reconciliation.md +17 -2
  133. package/docs/document-lifecycle.md +6 -2
  134. package/docs/platform-capabilities.md +63 -16
  135. package/docs/platform-compatibility.json +5 -5
  136. package/harness-everything/SKILL.md +1 -1
  137. package/harness-everything/scripts/routing-keywords.json +0 -2
  138. package/harness-everything/scripts/tier-router.js +105 -11
  139. package/hooks/hooks.json +0 -46
  140. package/hooks/scripts/lib/workflow-obligations.js +0 -55
  141. package/hooks/scripts/state-persist.js +7 -95
  142. package/hooks/scripts/workflow-disposition.js +0 -2
  143. package/hooks/scripts/workflow-stop-gate.js +17 -30
  144. package/opencode-plugin/index.mjs +6 -70
  145. package/opencode-plugin/plugin.json +1 -1
  146. package/package.json +1 -1
  147. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  148. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  149. package/plugins/harness-everything/hooks/scripts/lib/workflow-obligations.js +0 -55
  150. package/plugins/harness-everything/hooks/scripts/state-persist.js +7 -95
  151. package/plugins/harness-everything/hooks/scripts/workflow-disposition.js +0 -2
  152. package/plugins/harness-everything/hooks/scripts/workflow-stop-gate.js +17 -30
  153. package/plugins/harness-everything/plugin.json +1 -1
  154. package/plugins/harness-everything/rules/AGENTS.md +1 -1
  155. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  156. package/plugins/harness-everything/skills/harness-everything/scripts/routing-keywords.json +0 -2
  157. package/plugins/harness-everything/skills/harness-everything/scripts/tier-router.js +105 -11
  158. package/sbom.cdx.json +7 -7
  159. package/ci/fixtures/doc-obligations/reconciliation-s1/cases.json +0 -6854
  160. package/ci/fixtures/doc-obligations/reconciliation-s1/fail-session-writes.js +0 -116
  161. package/ci/fixtures/doc-obligations/reconciliation-s2a/harness.js +0 -507
  162. package/ci/fixtures/doc-obligations/reconciliation-s2a/run13-workflow-requirements.json +0 -42
  163. package/ci/fixtures/doc-obligations/reconciliation-s2a/vectors.json +0 -617
  164. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/harness.js +0 -415
  165. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-post-tool-use-success-minimal.json +0 -9
  166. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-start.json +0 -7
  167. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop-freetext-reject.json +0 -11
  168. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop-reject.json +0 -11
  169. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop.json +0 -11
  170. package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-task-result.json +0 -19
  171. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/off-capture-only.json +0 -99
  172. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/off-legacy.json +0 -67
  173. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-concurrent-writers.json +0 -62
  174. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-lookalikes-runtime-mutations.json +0 -67
  175. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-malformed.json +0 -85
  176. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-normal-session.json +0 -74
  177. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-runtime-drift-later-npm-test.json +0 -58
  178. package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-valid-direct-quoted-review.json +0 -85
  179. package/ci/fixtures/doc-obligations/reconciliation-s2b/f4/cases.json +0 -2267
  180. package/ci/fixtures/doc-obligations/reconciliation-s2b/wiring/cases.json +0 -1110
  181. package/ci/lib/doc-reconciliation-file-spy.js +0 -23
  182. package/ci/lib/doc-reconciliation-qualification-preload.js +0 -37
  183. package/ci/lib/doc-reconciliation-replay.js +0 -104
  184. package/ci/lib/doc-reconciliation-staged-tree.js +0 -102
  185. package/ci/mechanism-325-3b-h1-qualification.test.js +0 -206
  186. package/ci/mechanism-325-3b-s1.test.js +0 -188
  187. package/ci/mechanism-325-3b-s2a-core.test.js +0 -840
  188. package/ci/mechanism-325-3b-s2a-producer.test.js +0 -564
  189. package/ci/mechanism-325-3b-s2b-capture.test.js +0 -566
  190. package/ci/mechanism-325-3b-s2b-wiring.test.js +0 -679
  191. package/ci/mechanism-325-f4-invariants.test.js +0 -606
  192. package/ci/mechanism-325-f4-projections.test.js +0 -392
  193. package/ci/mechanism-325-f4-qualification.test.js +0 -228
  194. package/ci/mechanism-325-f4-trust-boundary.test.js +0 -880
  195. package/ci/mechanism-e1-dependency-artifact-scope.test.js +0 -657
  196. package/hooks/scripts/lib/doc-reconciliation-capture.sanitized.jsonl +0 -26
  197. package/hooks/scripts/lib/doc-reconciliation-core.js +0 -336
  198. package/hooks/scripts/lib/doc-reconciliation-events.js +0 -292
  199. package/hooks/scripts/lib/doc-reconciliation-outline-capture.sanitized.jsonl +0 -24
  200. package/hooks/scripts/lib/doc-reconciliation-pilot.js +0 -482
  201. package/hooks/scripts/lib/doc-reconciliation-producer.js +0 -468
  202. package/hooks/scripts/lib/doc-reconciliation-provider.js +0 -3304
  203. package/hooks/scripts/lib/doc-reconciliation-qualification.json +0 -54
  204. package/hooks/scripts/w6-state-operations.js +0 -239
  205. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-capture.sanitized.jsonl +0 -26
  206. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-core.js +0 -336
  207. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-events.js +0 -292
  208. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-outline-capture.sanitized.jsonl +0 -24
  209. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-pilot.js +0 -482
  210. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-producer.js +0 -468
  211. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-provider.js +0 -3304
  212. package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-qualification.json +0 -54
  213. package/plugins/harness-everything/hooks/scripts/w6-state-operations.js +0 -239
  214. package/scripts/system-one-eval-laya.js +0 -112
  215. /package/ci/fixtures/{doc-obligations/reconciliation-s2b/capture → state-persist-post-tool-use}/payload-post-tool-use-failure.json +0 -0
  216. /package/ci/fixtures/{doc-obligations/reconciliation-s2b/wiring → workflow-contract}/legacy-off-golden.json +0 -0
@@ -1,20 +1,28 @@
1
1
  'use strict';
2
2
 
3
+ // Decoupled workspace-alias session-dir keying contract (T2-C #553):
4
+ // retains the surviving PR-B alias session-keying control (two runs per leg on both
5
+ // source and packaged hooks) without E1 pilot/provider/staged-tree/symlink-citation helpers.
3
6
  const assert = require('assert');
4
7
  const crypto = require('crypto');
5
8
  const fs = require('fs');
6
9
  const os = require('os');
7
10
  const path = require('path');
8
- const { execFileSync } = require('child_process');
9
11
  const { spawnSync } = require('child_process');
10
- const { canonical } = require(path.resolve(__dirname, '../hooks/scripts/lib/workflow-isolation.js'));
11
- const { stage: stageQualificationTree } = require('./lib/doc-reconciliation-staged-tree.js');
12
12
 
13
13
  const ROOT = path.resolve(__dirname, '..');
14
- const provider = require(path.join(ROOT, 'hooks/scripts/lib/doc-reconciliation-provider.js'));
15
- const pilot = require(path.join(ROOT, 'hooks/scripts/lib/doc-reconciliation-pilot.js'));
16
- const { checkDocObligations } = require(path.join(ROOT, 'harness-everything/scripts/doc-evidence.js'));
17
- const internals = provider._internals || {};
14
+ const LEGS = [
15
+ {
16
+ name: 'source',
17
+ harnessState: path.join(ROOT, 'hooks/scripts/lib/harness-state.js'),
18
+ statePersist: path.join(ROOT, 'hooks/scripts/state-persist.js'),
19
+ },
20
+ {
21
+ name: 'packaged',
22
+ harnessState: path.join(ROOT, 'plugins/harness-everything/hooks/scripts/lib/harness-state.js'),
23
+ statePersist: path.join(ROOT, 'plugins/harness-everything/hooks/scripts/state-persist.js'),
24
+ },
25
+ ];
18
26
  const failures = [];
19
27
 
20
28
  function test(name, run) {
@@ -47,13 +55,13 @@ function symlinkUnavailable(type) {
47
55
  }
48
56
  }
49
57
 
50
- function symlinkCitationPrecondition(linkText, expectedText, target, parse = internals.parseOutlineCitation) {
51
- if (linkText !== expectedText) {
52
- return { unchecked: `symlink text differs from fixture citation bytes: expected ${JSON.stringify(expectedText)}, actual ${JSON.stringify(linkText)}` };
53
- }
54
- assert.strictEqual(parse(Buffer.from(linkText), target).state, 'accepted',
55
- 'citation-looking symlink link text must remain a positive control');
56
- return null;
58
+ function sha(value) {
59
+ return crypto.createHash('sha256').update(value).digest('hex');
60
+ }
61
+
62
+ function writeJson(file, value) {
63
+ fs.mkdirSync(path.dirname(file), { recursive: true });
64
+ fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n');
57
65
  }
58
66
 
59
67
  test('explicitly unchecked controls do not also report PASS', () => {
@@ -66,3293 +74,103 @@ test('explicitly unchecked controls do not also report PASS', () => {
66
74
  assert.deepStrictEqual(output, ['UNCHECKED fixture precondition: EPERM']);
67
75
  });
68
76
 
69
- test('matching symlink citation bytes fail closed when the parser rejects them', () => {
70
- const expectedText = outlineText();
71
- assert.throws(() => symlinkCitationPrecondition(expectedText, expectedText, 'docs/adr/DOCS-001.md', () => ({ state: 'unresolved' })),
72
- /citation-looking symlink link text must remain a positive control/);
73
- });
74
-
75
- function sha(value) {
76
- return crypto.createHash('sha256').update(value).digest('hex');
77
- }
78
-
79
- function writeJson(file, value) {
80
- fs.mkdirSync(path.dirname(file), { recursive: true });
81
- fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n');
82
- }
83
-
84
- const dispatchLine = 'HARNESS_OUTLINE_DISPATCH_V1 taskId=task-prb attemptId=attempt-1 token=token-1 workerRoot=/tmp/prb-worker';
85
-
86
- const syntheticInventory = [
87
- '# Synthetic inventory',
88
- 'run id `synthetic-run` · input SHA `abcdef012345`',
89
- '',
90
- '## Mechanism inventory',
91
- '| # | Mechanism | Evidence |',
92
- '|---|---|---|',
93
- '| 20 | ADR identity | mechanism evidence |',
94
- '',
95
- '## Area grouping + candidate domain prefixes',
96
- '| Area | Rows | Candidate prefix | Why |',
97
- '|---|---|---|---|',
98
- '| Documents | 20–22 | `DOCS` | Synthetic fixture |',
99
- ].join('\n') + '\n';
100
-
101
- function fixtureGit(root, args) {
102
- const env = { ...process.env, GIT_AUTHOR_NAME: 'outline-fixture', GIT_AUTHOR_EMAIL: 'outline-fixture@invalid',
103
- GIT_COMMITTER_NAME: 'outline-fixture', GIT_COMMITTER_EMAIL: 'outline-fixture@invalid' };
104
- for (const key of Object.keys(env)) if (key.startsWith('GIT_') && !/^GIT_(AUTHOR|COMMITTER)_/.test(key)) delete env[key];
105
- try {
106
- return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'] }).trim();
107
- } catch (error) {
108
- throw new Error(`${error.message}: ${String(error.stderr || '').trim()}`);
109
- }
110
- }
111
-
112
- function outlineText({ id = null, complete = false, decisionPlaceholder = false, duplicateDecision = false, titledDecision = false,
113
- indentedDecision = false,
114
- rowId = '20', target = 'docs/adr/DOCS-001.md', domain = 'DOCS' } = {}) {
115
- const decision = complete ? '\n## Decision\nThis is already a complete drafted decision.\n'
116
- : duplicateDecision ? '\n## Decision\n- TBD\n\n## Decision\nThis second Decision section contains substantive text.\n'
117
- : titledDecision ? '\n## Decision — Final choice\nThis titled section contains a complete decision.\n'
118
- : indentedDecision ? '\n ## Decision — Indented final choice\nThis indented section contains substantive text.\n'
119
- : decisionPlaceholder ? '\n## Decision\n- TBD\n' : '';
120
- return `---\nid: ${id || `${domain}-001`}\nstatus: proposed\n---\n\nInventory row: ${rowId}\nTarget: ${target}\nDomain: ${domain}\n\n## Outline\n- Context: TBD\n- Decision: TBD\n${decision}`;
121
- }
122
-
123
- function createOutlineFixture(options = {}) {
124
- const generatedRoot = fs.mkdtempSync(path.join(options.rootDirectory || os.tmpdir(), 'prb-outline-fixture-'));
125
- const root = options.preserveRootSpelling ? generatedRoot : canonical(generatedRoot);
126
- const runtimeBase = options.runtimeLayout === 'packaged' ? path.join(ROOT, 'plugins/harness-everything') : ROOT;
127
- const runtimeProvider = require(path.join(runtimeBase, 'hooks/scripts/lib/doc-reconciliation-provider.js'));
128
- const runtimePilot = require(path.join(runtimeBase, 'hooks/scripts/lib/doc-reconciliation-pilot.js'));
129
- const workspaceRoot = canonical(root);
130
- const retainedInventory = options.retainedInventory === true;
131
- const target = options.target || (retainedInventory ? 'docs/adr/EVID-001.md' : 'docs/adr/DOCS-001.md');
132
- const rowId = options.rowId || (retainedInventory ? '17' : '20');
133
- const domain = options.domain || (retainedInventory ? 'EVID' : 'DOCS');
134
- let taskId = options.taskId || 'task-prb';
135
- let attemptId = options.attemptId || 'attempt-1';
136
- const sessionId = options.sessionId || 'author-session';
137
- const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), 'prb-outline-state-'));
138
- const workerRoot = options.workerRootAlias
139
- ? `${root}${path.sep}..${path.sep}${path.basename(root)}` : root;
140
- let workflowId = 'workflow-prb';
141
- let workflowRevision = 2;
142
- const configValue = options.w6Producer
143
- ? { governed: [{ path: 'docs/adr/*.md', role: 'adr' }], domains: ['EVID'],
144
- derived: [{ path: 'docs/governed-index.md', generator: 'node harness-everything/scripts/doc-lifecycle.js index --workspace . --config .agents/harness-everything/project-docs.json --all' }] }
145
- : { governed: [{ path: options.governedPattern || 'docs/adr/*.md', role: 'adr' }], domains: [domain], derived: [] };
146
- const config = JSON.stringify(configValue, null, 2) + '\n';
147
- let configDigest = sha(config);
148
- const inventoryBytes = retainedInventory
149
- ? fs.readFileSync(path.join(ROOT, 'benchmarks/results/live-host/claude-341-outline-dispatch-2026-10-28/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md'))
150
- : Buffer.from(syntheticInventory);
151
- const pinDigest = sha(inventoryBytes);
152
- const expectedPin = retainedInventory ? internals.OUTLINE_INVENTORY_PIN : {
153
- source: 'synthetic://approved-inventory', sha256: pinDigest, runId: 'synthetic-run', inputSha: 'abcdef012345',
154
- approvalRef: { issue: 325, commentId: 'synthetic-comment', decision: 1 },
155
- retainedArtifactPath: `inventory/${pinDigest}.md`,
156
- };
157
- if (retainedInventory) assert.strictEqual(pinDigest, expectedPin.sha256, 'retained inventory bytes must match the pinned digest');
158
- fs.mkdirSync(path.join(root, '.agents/harness-everything'), { recursive: true });
159
- fs.mkdirSync(path.dirname(path.join(root, target)), { recursive: true });
160
- fs.writeFileSync(path.join(root, '.agents/harness-everything/project-docs.json'), config);
161
- if (options.w6Producer) {
162
- const taskScripts = path.join(root, 'harness-everything/scripts');
163
- fs.mkdirSync(taskScripts, { recursive: true });
164
- for (const name of ['doc-lifecycle.js', 'project-docs-resolver.js']) {
165
- fs.copyFileSync(path.join(ROOT, 'harness-everything/scripts', name), path.join(taskScripts, name));
166
- }
167
- const generated = spawnSync(process.execPath, [path.join(taskScripts, 'doc-lifecycle.js'), 'index', '--workspace', root,
168
- '--config', '.agents/harness-everything/project-docs.json', '--all'], { cwd: root, encoding: 'utf8' });
169
- assert.strictEqual(generated.status, 0, `row-17 baseline index generation: ${generated.stderr || generated.stdout}`);
170
- fs.writeFileSync(path.join(root, 'docs/governed-index.md'), generated.stdout);
171
- }
172
- if (options.targetExistsAtB) fs.writeFileSync(path.join(root, target),
173
- `---\nid: DOCS-001\nstatus: proposed\n---\n\n## Decision\nAn existing B document.\n`);
174
- if (options.unrelatedFileAtB) fs.writeFileSync(path.join(root, options.unrelatedFileAtB), 'unmodified at B\n');
175
- fixtureGit(root, ['init', '-q']);
176
- fixtureGit(root, ['add', '-A']);
177
- fixtureGit(root, ['commit', '-q', '-m', 'B baseline']);
178
- const baselineCommit = fixtureGit(root, ['rev-parse', 'HEAD']);
179
- const baselineTree = fixtureGit(root, ['rev-parse', 'HEAD^{tree}']);
180
- if (options.unrelatedFileAtB) fs.writeFileSync(path.join(root, options.unrelatedFileAtB), 'modified after B\n');
181
- let sessionDir = path.join(stateHome, 'session');
182
- if (options.realHook) {
183
- const priorStateHome = process.env.HARNESS_STATE_HOME;
184
- process.env.HARNESS_STATE_HOME = stateHome;
185
- try {
186
- // Model SessionStart: hook state follows the established root while later payload cwd may keep its alias spelling.
187
- const workspace = require(path.join(ROOT, 'scripts/lib/workspace.js'));
77
+ for (const leg of LEGS) {
78
+ test(`legacy session-dir keying stays aligned through an aliased workspace root [${leg.name}]`, () => {
79
+ const unavailable = symlinkUnavailable('dir');
80
+ if (unavailable) return { unchecked: `directory symlink creation is unavailable (${unavailable})` };
81
+ function driveAliasRootScenario() {
82
+ const realRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'prb-session-root-'));
83
+ const aliasRoot = `${realRoot}-alias`;
84
+ const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), 'prb-session-state-'));
85
+ const sessionId = 'prb-alias-session';
86
+ const preload = path.join(stateHome, 'realpath-alias.js');
87
+ fs.symlinkSync(realRoot, aliasRoot, 'dir');
188
88
  writeJson(path.join(stateHome, 'session-workspaces', `${sha(sessionId)}.json`), {
189
- version: 1, sessionId, workspaceRoot, workspaceKey: workspace.getWorkspaceKey(workspaceRoot),
190
- });
191
- sessionDir = require(path.join(ROOT, 'hooks/scripts/lib/harness-state.js')).getSessionDir(workspaceRoot, sessionId);
192
- }
193
- finally { if (priorStateHome === undefined) delete process.env.HARNESS_STATE_HOME; else process.env.HARNESS_STATE_HOME = priorStateHome; }
194
- }
195
-
196
- const workspaceId = 'ws-' + internals.digestText(internals.captureJson({ workspaceRoot: canonical(root) }));
197
- let taskBinding = null;
198
- const workflowOperationWitnesses = [];
199
- if (options.workflowCli) {
200
- const env = { ...process.env, HARNESS_STATE_HOME: stateHome, HARNESS_WORKSPACE_ROOT: root,
201
- HARNESS_DOC_RECONCILIATION_PILOT: '1' };
202
- const kernelRelative = runtimeBase === ROOT ? 'harness-everything/scripts/kernel-router.js' : 'skills/harness-everything/scripts/kernel-router.js';
203
- const kernel = spawnSync(process.execPath, [path.join(runtimeBase, kernelRelative)], {
204
- cwd: root, env, encoding: 'utf8', input: JSON.stringify({ session_id: sessionId, cwd: root,
205
- prompt: 'Draft the row-17 EVID-001 verification-evidence ADR from an outline, generate the governed index, and verify both.' }),
206
- });
207
- assert.strictEqual(kernel.status, 0, `row-17 plan fixture route: ${kernel.stderr || kernel.stdout}`);
208
- } else {
209
- const requirementIds = ['prb'];
210
- taskBinding = { schema: 'harness.doc-reconciliation-task-pin.v1', taskId, requirementIds,
211
- requirementDigest: sha(JSON.stringify(requirementIds)), baselineCommit, baselineRoot: root,
212
- configDigest, sessionId, workflowId, workspaceId };
213
- writeJson(path.join(sessionDir, 'workflow-run.json'), {
214
- workflowId, revision: workflowRevision, docReconciliationBaseline: { root, commit: baselineCommit, tree: baselineTree },
215
- docReconciliationTask: taskBinding,
216
- });
217
- }
218
-
219
- let hookPreloader = null;
220
- const hookDiagnostics = [];
221
- function actualCaptureSessionDirs() {
222
- const workspacesDir = path.join(stateHome, 'workspaces');
223
- try {
224
- return fs.readdirSync(workspacesDir).flatMap(workspaceKey => {
225
- const sessionsDir = path.join(workspacesDir, workspaceKey, 'state', 'sessions');
226
- try {
227
- return fs.readdirSync(sessionsDir).map(session => path.join(sessionsDir, session))
228
- .filter(dir => fs.readdirSync(path.join(dir, 'doc-reconciliation-capture'))
229
- .some(name => /^\d{8}\.json$/.test(name)));
230
- } catch { return []; }
89
+ version: 1, sessionId, workspaceRoot: aliasRoot,
231
90
  });
232
- } catch { return []; }
233
- }
234
- function capturedRecordsAcrossSessions() {
235
- return actualCaptureSessionDirs().flatMap(dir => runtimeProvider.readCaptureView(dir).records);
236
- }
237
- function logReviewHookDiagnostics() {
238
- console.error('REVIEW-HOOK-CAPTURE-DIAGNOSTICS ' + JSON.stringify({
239
- expectedSessionDir: sessionDir,
240
- writtenSessionDirs: actualCaptureSessionDirs(),
241
- hooks: hookDiagnostics.filter(item => item.agentType === 'reviewer' || item.toolUseId === 'review-dispatch'),
242
- }));
243
- }
244
- function runHook(payload, pilotEnabled = true, usePreload = true) {
245
- if (!options.realHook) throw new Error('real state-persist capture was not enabled for this fixture');
246
- if (usePreload && !hookPreloader) {
247
- hookPreloader = path.join(stateHome, 'outline-test-preload.js');
248
- const providerPath = path.join(runtimeBase, 'hooks/scripts/lib/doc-reconciliation-provider.js');
249
- fs.writeFileSync(hookPreloader, [
250
- ...(options.failPartialDispatchStorage ? [
251
- "const fs=require('fs');",
252
- "const path=require('path');",
253
- "const marker=path.join(process.env.HARNESS_STATE_HOME,'prb-partial-dispatch-faults-used');",
254
- 'const write=fs.writeFileSync;',
255
- 'let tokenFailure=false;',
256
- 'fs.writeFileSync=function(file,data){',
257
- "const target=String(file).replace(/\\\\/g,'/');",
258
- "if(!fs.existsSync(marker)&&/\\/tokens\\/[^/]+\\.json$/.test(target)){tokenFailure=true;const error=new Error('injected token write failure');error.code='EIO';throw error;}",
259
- "if(tokenFailure&&!fs.existsSync(marker)&&/\\/doc-reconciliation-capture\\/\\d{8}\\.json$/.test(target)&&String(data).includes('\\\"state\\\": \\\"unresolved\\\"')){write(marker,'injected');const error=new Error('injected unresolved capture write failure');error.code='EIO';throw error;}",
260
- 'return write.apply(this,arguments);',
261
- '};',
262
- ] : []),
263
- `const p=require(${JSON.stringify(providerPath)});`,
264
- "if(typeof p.captureOutlineDispatch==='function'){",
265
- 'const original=p.captureOutlineDispatch;',
266
- `const pin=${JSON.stringify(expectedPin)};`,
267
- 'p.captureOutlineDispatch=(input)=>original({...input,fixtureExpectedPin:pin});',
91
+ fs.writeFileSync(preload, [
92
+ "const fs=require('fs');",
93
+ "const path=require('path');",
94
+ 'const original=fs.realpathSync;',
95
+ 'const alias=path.resolve(process.env.PRB_TEST_ALIAS_ROOT);',
96
+ 'function realpathSync(target,...args){',
97
+ ' if(typeof target==="string"&&path.resolve(target)===alias)return alias;',
98
+ ' return original.call(fs,target,...args);',
268
99
  '}',
100
+ 'realpathSync.native=original.native;',
101
+ 'fs.realpathSync=realpathSync;',
269
102
  ].join('\n'));
270
- }
271
- const child = spawnSync(process.execPath, [...(usePreload ? ['--require', hookPreloader] : []), path.join(runtimeBase, 'hooks/scripts/state-persist.js')], {
272
- cwd: root, encoding: 'utf8', input: JSON.stringify(payload),
273
- env: { ...process.env, HARNESS_STATE_HOME: stateHome, HARNESS_WORKSPACE_ROOT: root,
274
- HARNESS_DOC_RECONCILIATION_PILOT: pilotEnabled ? '1' : '0' },
275
- });
276
- hookDiagnostics.push({
277
- event: payload.hook_event_name,
278
- toolUseId: payload.tool_use_id || null,
279
- agentId: payload.agent_id || null,
280
- agentType: payload.agent_type || null,
281
- exitCode: child.status,
282
- stderr: child.stderr || '',
283
- });
284
- if (child.status !== 0) {
285
- if (payload.agent_type === 'reviewer' || payload.tool_use_id === 'review-dispatch') logReviewHookDiagnostics();
286
- throw new Error(`state-persist failed open contract: ${child.stderr || child.stdout || child.status}`);
287
- }
288
- return runtimeProvider.readCaptureView(sessionDir).records;
289
- }
290
103
 
291
- function runWorkflowOperation(name, args, allowFailure = false) {
292
- const controller = path.join(runtimeBase, 'hooks/scripts/workflow-disposition.js');
293
- const handoffStateFile = path.join(sessionDir, 'handoff-state.json');
294
- const beforeHandoffState = fs.existsSync(handoffStateFile) ? JSON.parse(fs.readFileSync(handoffStateFile, 'utf8')) : null;
295
- const toolUseId = `w6-${name}-${sessionId}`;
296
- const command = `node "${controller}" ${args.map(value => /[\s'"\\]/.test(value)
297
- ? `'${value.replace(/'/g, "'\\''")}'` : value).join(' ')}`;
298
- const payload = { session_id: sessionId, cwd: root, hook_event_name: 'PreToolUse', tool_name: 'Bash',
299
- tool_use_id: toolUseId, tool_input: { command } };
300
- runHook(payload);
301
- const child = spawnSync(process.execPath, [controller, ...args], { cwd: root,
302
- env: { ...process.env, HARNESS_STATE_HOME: stateHome, HARNESS_WORKSPACE_ROOT: root,
303
- HARNESS_DOC_RECONCILIATION_PILOT: '1' }, encoding: 'utf8' });
304
- if (child.status !== 0 && allowFailure && name === 'step-verify') {
305
- runHook({ ...payload, hook_event_name: 'PostToolUseFailure', is_interrupt: false,
306
- error: child.stderr || child.stdout || `exit ${child.status}`, tool_response: { exitCode: child.status } });
307
- const afterHandoffState = fs.existsSync(handoffStateFile) ? JSON.parse(fs.readFileSync(handoffStateFile, 'utf8')) : null;
308
- workflowOperationWitnesses.push({ name, before: beforeHandoffState, after: afterHandoffState, exitCode: child.status });
309
- return child.stdout;
310
- }
311
- assert.strictEqual(child.status, 0, `row-17 ${name}: ${child.stderr || child.stdout}`);
312
- runHook({ ...payload, hook_event_name: 'PostToolUse',
313
- tool_response: { exitCode: child.status, stdout: child.stdout, stderr: child.stderr, interrupted: false, status: 'completed' } });
314
- const afterHandoffState = fs.existsSync(handoffStateFile) ? JSON.parse(fs.readFileSync(handoffStateFile, 'utf8')) : null;
315
- workflowOperationWitnesses.push({ name, before: beforeHandoffState, after: afterHandoffState });
316
- return child.stdout;
317
- }
318
-
319
- if (options.workflowCli) {
320
- const requirements = [
321
- { id: 'adr-evid', stepType: 'doc-change', summary: 'Draft the row-17 EVID-001 verification-evidence ADR.',
322
- acceptance: 'A real proposed O is independently reviewed before the draft D; D is a strict descendant of O and changes only the ADR.' },
323
- { id: 'verify-row17', stepType: 'verification',
324
- summary: 'Generate the governed index and verify the final ADR through one combined registered check and independent review.',
325
- acceptance: 'All four combined-check capabilities and the ADR-only final review are captured before normal Stop reconciliation.' },
326
- ];
327
- const operations = [
328
- ['plan', ['plan', '--session-id', sessionId, '--strategy', 'iterative-single', '--requirements-json', JSON.stringify(requirements),
329
- '--evidence', 'row17 baseline witness']],
330
- ['start', ['start', '--session-id', sessionId]],
331
- ];
332
- for (const [name, args] of operations) {
333
- runWorkflowOperation(name, args);
334
- }
335
- const workflow = JSON.parse(fs.readFileSync(path.join(sessionDir, 'workflow-run.json'), 'utf8'));
336
- workflowId = workflow.workflowId;
337
- workflowRevision = workflow.revision;
338
- taskBinding = workflow.docReconciliationTask;
339
- taskId = taskBinding.taskId;
340
- configDigest = taskBinding.configDigest;
341
- assert.deepStrictEqual(taskBinding.requirementIds, ['adr-evid', 'verify-row17'], 'plan/start must create the declared row-17 task pin');
342
- }
343
-
344
- function runW6Producer(operation) {
345
- const producer = path.join(runtimeBase, 'hooks/scripts/w6-state-operations.js');
346
- const toolUseId = `w6-${operation}-${sessionId}`;
347
- const command = `node "${producer}" ${operation} --session-id "${sessionId}"`;
348
- const payload = { session_id: sessionId, cwd: root, hook_event_name: 'PreToolUse', tool_name: 'Bash',
349
- tool_use_id: toolUseId, tool_input: { command } };
350
- runHook(payload);
351
- const child = spawnSync(process.execPath, [producer, operation, '--session-id', sessionId], { cwd: root,
352
- env: { ...process.env, HARNESS_STATE_HOME: stateHome, HARNESS_WORKSPACE_ROOT: root,
353
- HARNESS_DOC_RECONCILIATION_PILOT: '1' }, encoding: 'utf8' });
354
- if (child.status !== 0) {
355
- runHook({ ...payload, hook_event_name: 'PostToolUseFailure', is_interrupt: false,
356
- error: child.stderr || child.stdout || `exit ${child.status}`, tool_response: { exitCode: child.status } });
357
- if (options.w6ExpectedProducerFailure) return { error: child.stderr || child.stdout || `exit ${child.status}`, exitCode: child.status };
358
- throw new Error(`row-17 ${operation} producer: ${child.stderr || child.stdout}`);
359
- }
360
- if (operation === 'inventory' && options.w6ProducerFault === 'extra-state-destination') {
361
- writeJson(path.join(sessionDir, 'unauthorized-state-change.json'), { operation: 'inventory' });
362
- }
363
- const post = { ...payload, hook_event_name: 'PostToolUse',
364
- tool_response: { exitCode: child.status, stdout: child.stdout, stderr: child.stderr, interrupted: false, status: 'completed' } };
365
- if (!(operation === 'inventory' && options.w6ProducerFault === 'missing-post')) runHook(post);
366
- if (operation === 'inventory' && options.w6ProducerFault === 'duplicate-post') runHook(post);
367
- return JSON.parse(child.stdout);
368
- }
369
-
370
- function runWorkerCommand(toolName, toolUseId, toolInput, command, execute) {
371
- const payload = { session_id: sessionId, cwd: root, hook_event_name: 'PreToolUse', tool_name: toolName,
372
- tool_use_id: toolUseId, agent_id: 'draft-worker', agent_type: 'worker', tool_input: toolInput };
373
- runHook(payload);
374
- const result = execute();
375
- runHook({ ...payload, hook_event_name: 'PostToolUse', tool_response: {
376
- exitCode: result.exitCode ?? 0, stdout: result.stdout || '', stderr: result.stderr || '', interrupted: false, status: 'completed',
377
- } });
378
- return result;
379
- }
380
-
381
- function runReviewCapture(payload) {
382
- runHook(payload);
383
- }
384
- let inventoryOperation = null;
385
- let outsideInventoryPath = null;
386
- if (options.w6ProducerFault === 'inventory-symlink') {
387
- const inventoryParent = path.join(sessionDir, 'doc-reconciliation/outline-confirmation');
388
- fs.mkdirSync(inventoryParent, { recursive: true });
389
- outsideInventoryPath = path.join(stateHome, 'outside-inventory', 'unexpected.md');
390
- fs.mkdirSync(path.dirname(outsideInventoryPath), { recursive: true });
391
- fs.symlinkSync(path.dirname(outsideInventoryPath), path.join(inventoryParent, 'inventory'), 'dir');
392
- }
393
- if (options.w6Producer) inventoryOperation = runW6Producer('inventory');
394
-
395
- const outlineBytes = Buffer.from(outlineText({
396
- id: options.targetId,
397
- complete: options.completeOutline === true,
398
- decisionPlaceholder: options.decisionPlaceholder === true,
399
- duplicateDecision: options.duplicateDecision === true,
400
- indentedDecision: options.indentedDecision === true,
401
- rowId, target, domain,
402
- }));
403
- let preOutlineOperation = null;
404
- if (options.preOutlineOperation) {
405
- if (!options.realHook) throw new Error('pre-outline operation requires the real state-persist hook');
406
- const operation = options.preOutlineOperation;
407
- const toolUseId = 'pre-outline-' + operation + '-' + sessionId;
408
- const payload = operation === 'write'
409
- ? { session_id: sessionId, cwd: root, hook_event_name: 'PreToolUse', tool_name: 'Write', tool_use_id: toolUseId,
410
- tool_input: { file_path: path.join(root, target), content: outlineBytes.toString('utf8') } }
411
- : { session_id: sessionId, cwd: root, hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_use_id: toolUseId,
412
- tool_input: { command: 'git status --porcelain' } };
413
- const preRecords = runHook(payload, true, false);
414
- let output = '';
415
- if (operation === 'write') fs.writeFileSync(path.join(root, target), outlineBytes);
416
- else output = execFileSync('git', ['status', '--porcelain'], { cwd: root, encoding: 'utf8' });
417
- const postPayload = { ...payload, hook_event_name: 'PostToolUse', tool_response: { exitCode: 0, stdout: output } };
418
- runHook(postPayload, true, false);
419
- const records = runtimeProvider.readCaptureView(sessionDir).records;
420
- const pre = preRecords.find(item => item.event === 'PreToolUse' && item.tool_use_id === toolUseId);
421
- const post = records.find(item => item.event === 'PostToolUse' && item.tool_use_id === toolUseId);
422
- assert.ok(pre && post, operation + ' operation has real PreToolUse and successful PostToolUse captures');
423
- preOutlineOperation = { operation, toolUseId, command: operation === 'status' ? 'git status --porcelain' : null,
424
- output, preRef: pre.ref, postRef: post.ref };
425
- }
426
-
427
- if (!preOutlineOperation || preOutlineOperation.operation !== 'write') fs.writeFileSync(path.join(root, target), outlineBytes);
428
- if (options.symlinkOutlineObject) {
429
- fs.rmSync(path.join(root, target), { force: true });
430
- fs.symlinkSync(outlineBytes.toString('utf8'), path.join(root, target));
431
- }
432
- let capturedCommit = false;
433
- let indexAfterCapturedAdd = null;
434
- let indexAfterOutlineCommit = null;
435
- if (options.capturedOutlineCommit) {
436
- // The coordinator's own git add/commit run through the real hook, so the B→O commit is captured Bash evidence.
437
- if (!options.realHook || !preOutlineOperation || preOutlineOperation.operation !== 'write') {
438
- throw new Error('captured O commit requires the real hook and a captured pre-O write');
439
- }
440
- // extraOutlineFile is an uncaptured write staged into O: only the O commit scope check can reject it.
441
- if (options.extraOutlineFile) fs.writeFileSync(path.join(root, options.extraOutlineFile), 'uncaptured extra\n');
442
- const addArgs = options.capturedOutlineAddArgs || ['add', '--', target];
443
- const commitArgs = options.capturedOutlineCommitArgs || ['commit', '-m', 'O outline'];
444
- const addCommand = typeof options.capturedOutlineAddCommand === 'function'
445
- ? options.capturedOutlineAddCommand({ root, target }) : options.capturedOutlineAddCommand;
446
- const gitOperations = [
447
- ['add', addArgs, addCommand || `git add -- ${target}`],
448
- ['commit', commitArgs, options.capturedOutlineCommitCommand || 'git commit -m "O outline"'],
449
- ];
450
- for (const [name, args, command] of gitOperations) {
451
- const payload = { session_id: sessionId, cwd: root, hook_event_name: 'PreToolUse', tool_name: 'Bash',
452
- tool_use_id: `pre-outline-${name}-${sessionId}`, tool_input: { command } };
453
- runHook(payload, true, false);
454
- if (name === 'add' && options.extraOutlineFile) fixtureGit(root, ['add', '--', options.extraOutlineFile]);
455
- if (name === 'commit' && options.stagedUnrelatedWitness) fixtureGit(root, ['reset', '--', options.unrelatedFileAtB]);
456
- fixtureGit(root, args);
457
- if (name === 'add' && options.stagedUnrelatedWitness) {
458
- indexAfterCapturedAdd = fixtureGit(root, ['diff', '--cached', '--name-only']).split('\n').filter(Boolean).sort();
459
- }
460
- if (name === 'commit' && options.stagedUnrelatedWitness) {
461
- fixtureGit(root, ['add', '--', options.unrelatedFileAtB]);
462
- indexAfterOutlineCommit = fixtureGit(root, ['diff', '--cached', '--name-only']).split('\n').filter(Boolean).sort();
463
- }
464
- runHook({ ...payload, hook_event_name: 'PostToolUse', tool_response: { exitCode: 0, stdout: '' } }, true, false);
465
- }
466
- capturedCommit = true;
467
- }
468
- if (options.stagedUnrelatedWitness) fixtureGit(root, ['reset', '--hard', 'HEAD']);
469
- if (!capturedCommit) {
470
- // revertedExtraOutlineCommit: a non-target file committed inside B..O and removed before O. Only per-commit scope sees it.
471
- if (options.revertedExtraOutlineCommit) {
472
- const extra = options.revertedExtraOutlineCommit;
473
- fs.mkdirSync(path.dirname(path.join(root, extra)), { recursive: true });
474
- fs.writeFileSync(path.join(root, extra), 'scratch content\n');
475
- fixtureGit(root, ['add', '--', extra]);
476
- fixtureGit(root, ['commit', '-q', '-m', 'scratch in O range']);
477
- fs.rmSync(path.join(root, extra));
478
- }
479
- fixtureGit(root, ['add', '-A']);
480
- fixtureGit(root, ['commit', '-q', '-m', 'O outline']);
481
- }
482
- let outlineCommit = fixtureGit(root, ['rev-parse', 'HEAD']);
483
- let outlineTree = fixtureGit(root, ['rev-parse', 'HEAD^{tree}']);
484
- let outlineBlob = fixtureGit(root, ['rev-parse', `HEAD:${target}`]);
485
-
486
- const outlineRoot = path.join(sessionDir, 'doc-reconciliation/outline-confirmation');
487
- const inventoryDir = path.join(outlineRoot, 'inventory');
488
- if (!options.w6Producer || !inventoryOperation?.operation) {
489
- fs.rmSync(inventoryDir, { recursive: true, force: true });
490
- fs.mkdirSync(inventoryDir, { recursive: true });
491
- fs.writeFileSync(path.join(inventoryDir, `${pinDigest}.md`), inventoryBytes);
492
- writeJson(path.join(inventoryDir, 'inventory-pin.json'), expectedPin);
493
- }
494
-
495
-
496
- const inventoryPath = `doc-reconciliation/outline-confirmation/inventory/${pinDigest}.md`;
497
- const reviewerPrincipal = options.reviewerPrincipal || 'outline-reviewer';
498
- const reviewMessage = [
499
- 'Review verdict: approve',
500
- `Reviewed artifact: ${target} sha256:${sha(outlineBytes)}`,
501
- `Reviewed artifact: ${inventoryPath} sha256:${pinDigest}`,
502
- `Summary: Approved inventory row ${rowId} for ${target} in domain ${domain}.`,
503
- ].join('\n');
504
- const reviewResultPayload = {
505
- session_id: sessionId, cwd: root, hook_event_name: 'PostToolUse', tool_name: 'Task',
506
- tool_use_id: 'review-dispatch', tool_input: { command: 'Task' },
507
- tool_response: { agentId: reviewerPrincipal, interrupted: false, status: 'completed' },
508
- };
509
- const reviewStopPayload = {
510
- session_id: sessionId, cwd: root, hook_event_name: 'SubagentStop', agent_id: reviewerPrincipal,
511
- agent_type: 'reviewer', last_assistant_message: reviewMessage,
512
- };
513
- let reviewResult;
514
- let reviewStop;
515
- // Negative-control injection points: each entry is a payload factory run through the real hook at that journal position.
516
- const interleave = options.interleave || {};
517
- const runInterleaved = list => { for (const make of list || []) runHook(make({ root, sessionId, target })); };
518
- const reviewerStartPayload = { session_id: sessionId, cwd: root, hook_event_name: 'SubagentStart',
519
- agent_id: reviewerPrincipal, agent_type: 'reviewer' };
520
- let reviewerStartRecord = null;
521
- if (options.realHook) {
522
- const restoreBeforeReview = options.beforeReviewSetup?.({ root, target });
523
- try { runInterleaved(interleave.beforeReview); }
524
- finally { if (typeof restoreBeforeReview === 'function') restoreBeforeReview(); }
525
- // The live host journals the reviewer's SubagentStart before its launch result (run8 sanitized capture).
526
- if (!options.omitReviewerStart) runHook(reviewerStartPayload);
527
- if (!options.omitReviewResult) runHook(reviewResultPayload);
528
- runInterleaved(interleave.duringReview);
529
- if (options.gitAfterReview) {
530
- // Uncaptured Git rewrite of O inside the review window (not journaled by the hook). The coordinator then
531
- // records the rewritten O in the handoff, so only the identity taken at reviewer start can reject it.
532
- if (options.gitAfterReview === 'amend') fixtureGit(root, ['commit', '--amend', '-q', '-m', 'O outline amended']);
533
- else if (options.gitAfterReview === 'addPath') {
534
- fs.writeFileSync(path.join(root, 'docs/adr/DOCS-002.md'), `---\nid: DOCS-002\nstatus: proposed\n---\n\n## Outline\n- Context: TBD\n`);
535
- fixtureGit(root, ['add', '--', 'docs/adr/DOCS-002.md']);
536
- fixtureGit(root, ['commit', '--amend', '-q', '-m', 'O outline with second target']);
537
- } else {
538
- fixtureGit(root, ['reset', '-q', '--soft', baselineCommit]);
539
- fixtureGit(root, ['commit', '-q', '-m', 'O outline replaced']);
540
- }
541
- outlineCommit = fixtureGit(root, ['rev-parse', 'HEAD']);
542
- outlineTree = fixtureGit(root, ['rev-parse', 'HEAD^{tree}']);
543
- outlineBlob = fixtureGit(root, ['rev-parse', `HEAD:${target}`]);
544
- }
545
- runHook(reviewStopPayload);
546
- const retained = runtimeProvider.readCaptureView(sessionDir).records;
547
- reviewResult = retained.find(item => item.event === 'PostToolUse' && item.tool_use_id === 'review-dispatch');
548
- reviewStop = retained.find(item => item.event === 'SubagentStop' && item.agent_id === reviewerPrincipal);
549
- } else {
550
- reviewResult = runtimeProvider.buildCaptureRecord(reviewResultPayload, 'PostToolUse', root);
551
- reviewStop = runtimeProvider.buildCaptureRecord(reviewStopPayload, 'SubagentStop', root);
552
- reviewResult.observedIdentity = { workflowId, workflowRevision, baselinePin: { root, commit: baselineCommit }, taskPin: taskBinding };
553
- reviewStop.observedIdentity = { workflowId, workflowRevision, baselinePin: { root, commit: baselineCommit }, taskPin: taskBinding };
554
- if (!options.omitReviewerStart) {
555
- reviewerStartRecord = runtimeProvider.buildCaptureRecord(reviewerStartPayload, 'SubagentStart', root);
556
- reviewerStartRecord.observedIdentity = reviewStop.observedIdentity;
557
- // Same identity capture the hook applies at SubagentStart (state-persist persistPilotCapture).
558
- reviewerStartRecord.outlineIdentity = runtimeProvider.captureOutlineStartIdentity({ sessionDir });
559
- }
560
- }
561
- if (!reviewStop || (!reviewResult && !options.omitReviewResult)) {
562
- if (options.realHook) logReviewHookDiagnostics();
563
- throw new Error('review hook captures were not retained');
564
- }
565
- const reviewRecordDigest = runtimeProvider._internals?.captureDigest
566
- ? runtimeProvider._internals.captureDigest(reviewStop)
567
- : sha(JSON.stringify(reviewStop));
568
-
569
- let attemptDir = path.join(outlineRoot, taskId, 'attempts', attemptId);
570
- let lease;
571
- let handoff;
572
- if (options.w6Producer) {
573
- const sealed = runW6Producer('seal');
574
- attemptId = sealed.attemptId;
575
- attemptDir = path.join(outlineRoot, taskId, 'attempts', attemptId);
576
- lease = JSON.parse(fs.readFileSync(path.join(attemptDir, 'writer-lease.json'), 'utf8'));
577
- handoff = JSON.parse(fs.readFileSync(path.join(attemptDir, 'handoff.json'), 'utf8'));
578
- } else {
579
- fs.mkdirSync(attemptDir, { recursive: true });
580
- lease = { schema: 'harness.outline-writer-lease.v1', id: 'lease-1', taskId, attemptId,
581
- principalId: sessionId, root: workerRoot, exclusive: true, active: true,
582
- ...(options.competingWriters ? { competingWriters: ['unknown-writer'] } : {}) };
583
- writeJson(path.join(attemptDir, 'writer-lease.json'), lease);
584
- const leaseDigest = sha(fs.readFileSync(path.join(attemptDir, 'writer-lease.json')));
585
- handoff = {
586
- schema: 'harness.outline-handoff.v1', handoffId: 'handoff-1', taskId, attemptId,
587
- supersedesAttemptId: options.supersedesAttemptId || null,
588
- workspaceId,
589
- workflowId, workflowRevision, sessionId, hostId: 'claude-code',
590
- baseline: { root, commit: baselineCommit, tree: baselineTree, configDigest },
591
- configDigest, targetPaths: [target], draftWorktreeRoot: workerRoot,
592
- outline: { commit: outlineCommit, tree: options.handoffTreeOverride ? 'f'.repeat(40) : outlineTree,
593
- targetBlobs: { [target]: { blobOid: outlineBlob, storedBytesSha256: sha(outlineBytes) } } },
594
- inventory: { ...expectedPin, rowId, domain, targetPaths: [target] },
595
- reviewCaptureRef: reviewStop.ref, reviewCaptureDigest: reviewRecordDigest, reviewDigest: reviewStop.reviewDigest,
596
- coordinatorPrincipal: sessionId, writerLeaseId: lease.id, writerLeaseDigest: leaseDigest,
597
- draftDispatchToken: options.token || 'token-1',
598
- ...(options.handoffOverrides || {}),
599
- };
600
- if (!options.omitHandoff) writeJson(path.join(attemptDir, 'handoff.json'), handoff);
601
- }
602
- const dispatchToken = options.token || (options.w6Producer ? handoff.draftDispatchToken : 'token-1');
603
- const marker = `HARNESS_OUTLINE_DISPATCH_V1 taskId=${taskId} attemptId=${attemptId} token=${dispatchToken} workerRoot=${options.markerRoot || workerRoot}`;
604
-
605
- const payload = {
606
- session_id: sessionId, cwd: root, hook_event_name: 'PreToolUse', tool_name: 'Task',
607
- tool_use_id: options.toolUseId || 'dispatch-1', tool_input: { prompt: marker, run_in_background: false },
608
- };
609
- if (options.blockSeamStorage) {
610
- fs.mkdirSync(path.join(attemptDir, 'seams', `${sha(String(payload.tool_use_id))}.json`), { recursive: true });
611
- }
612
- if (options.blockTokenStorage) fs.writeFileSync(path.join(attemptDir, 'tokens'), 'blocked token directory');
613
- if (options.dirtyBeforeDispatch) fs.writeFileSync(path.join(root, 'untracked-before-dispatch.txt'), 'dirty');
614
- let capture;
615
- let reviewCaptures;
616
- if (options.realHook) {
617
- if (options.omitReview) {
618
- fs.rmSync(path.join(sessionDir, 'doc-reconciliation-capture'), { recursive: true, force: true });
619
- fs.rmSync(path.join(sessionDir, 'doc-reconciliation-capture.json'), { force: true });
620
- }
621
- runInterleaved(interleave.beforeDispatch);
622
- runHook(payload);
623
- const retained = runtimeProvider.readCaptureView(sessionDir).records;
624
- capture = retained.find(item => item.event === 'PreToolUse' && item.tool_use_id === payload.tool_use_id);
625
- reviewCaptures = retained.filter(item => item !== capture);
626
- } else {
627
- capture = runtimeProvider.buildCaptureRecord(payload, 'PreToolUse', root);
628
- capture.observedIdentity = { workflowId, workflowRevision, baselinePin: { root, commit: baselineCommit }, taskPin: taskBinding };
629
- reviewCaptures = options.omitReview ? [] : [...(reviewerStartRecord ? [reviewerStartRecord] : []), reviewResult, reviewStop];
630
- }
631
- if (!capture && !options.allowMissingDispatchCapture) throw new Error('PreToolUse dispatch capture was not retained');
632
- let seam = null;
633
- if (options.realHook) {
634
- seam = capture?.outlineDispatch || null;
635
- } else if (options.captureBeforeReview) {
636
- const noReview = internals.captureOutlineDispatch && internals.captureOutlineDispatch({
637
- payload, capture, sessionDir, workspaceRoot: root, captures: [], fixtureExpectedPin: expectedPin,
638
- });
639
- seam = noReview;
640
- // A later handoff/review cannot repair a dispatch-time miss.
641
- writeJson(path.join(attemptDir, 'handoff.json'), handoff);
642
- } else if (internals.captureOutlineDispatch) {
643
- seam = internals.captureOutlineDispatch({
644
- payload, capture, sessionDir, workspaceRoot: root, captures: reviewCaptures, fixtureExpectedPin: expectedPin,
645
- });
646
- }
647
- if (seam) capture.outlineDispatch = seam;
648
- const workerStartPayload = {
649
- session_id: sessionId, cwd: options.workerStartRoot || root, hook_event_name: 'SubagentStart',
650
- agent_id: options.workerPrincipal || 'draft-worker', agent_type: 'worker',
651
- };
652
- let workerStart;
653
- if (options.realHook) {
654
- runHook(workerStartPayload);
655
- workerStart = runtimeProvider.readCaptureView(sessionDir).records.find(item => item.event === 'SubagentStart'
656
- && item.agent_id === workerStartPayload.agent_id);
657
- } else {
658
- workerStart = runtimeProvider.buildCaptureRecord(workerStartPayload, 'SubagentStart', root);
659
- workerStart.observedIdentity = capture.observedIdentity;
660
- }
661
- const extraCaptures = [];
662
-
663
- function dispatchAgain({ toolUseId = capture.tool_use_id, prompt = payload.tool_input.prompt } = {}) {
664
- const extraPayload = { ...payload, tool_use_id: toolUseId, tool_input: { prompt, run_in_background: false } };
665
- const extra = runtimeProvider.buildCaptureRecord(extraPayload, 'PreToolUse', root);
666
- extra.observedIdentity = capture.observedIdentity;
667
- if (internals.captureOutlineDispatch) {
668
- extra.outlineDispatch = internals.captureOutlineDispatch({
669
- payload: extraPayload, capture: extra, sessionDir, workspaceRoot: root,
670
- captures: reviewCaptures, fixtureExpectedPin: expectedPin,
671
- });
672
- }
673
- extraCaptures.push(extra);
674
- return extra;
675
- }
676
-
677
- function finishDraft({ draft = true, nonDescendant = false, finalReview = false, completeWorkflow = false,
678
- allowDispositionFailure = false, baselineRoot = root,
679
- omitWorkerStart = false, omitWorkerResult = false, omitWorkerStop = false, tamperHandoff = false,
680
- providerSessionId = sessionId, providerTaskId = taskId, providerBaseline = { root, commit: baselineCommit },
681
- runPilot = false, handAuthoredCapture = false, removeSeam = false, mutateAfterFinalReview = false,
682
- workerCompletionOrder = 'result-stop', workerResultAfterFinalReview = false, workerStopAfterFinalReview = false,
683
- finalReviewCompletionOrder = 'result-stop', finalReviewFailure = null, reviewLaunchBeforeWorkerClosure = false,
684
- postWorkerCaptures = [], afterWorkerStop = [] } = {}) {
685
- if (draft) {
686
- if (options.w6Producer) {
687
- const finalAdr = `---\nid: ${domain}-001\nstatus: proposed\n---\n\n# ${domain}-001\n\n## Decision\nFinal evidence decision for row ${rowId}.\n`;
688
- runWorkerCommand('Write', 'w6-draft-write', { file_path: path.join(root, target), content: finalAdr }, null, () => {
689
- fs.writeFileSync(path.join(root, target), finalAdr);
690
- return { exitCode: 0 };
691
- });
692
- const indexCommand = 'node harness-everything/scripts/doc-lifecycle.js index --workspace . --config .agents/harness-everything/project-docs.json --all > docs/governed-index.md';
693
- runWorkerCommand('Bash', 'w6-index-generate', { command: indexCommand }, indexCommand, () => {
694
- const generated = spawnSync(process.execPath, [path.join(root, 'harness-everything/scripts/doc-lifecycle.js'), 'index',
695
- '--workspace', root, '--config', '.agents/harness-everything/project-docs.json', '--all'], { cwd: root, encoding: 'utf8' });
696
- assert.strictEqual(generated.status, 0, `row-17 D index generation: ${generated.stderr || generated.stdout}`);
697
- fs.writeFileSync(path.join(root, 'docs/governed-index.md'), generated.stdout);
698
- return { exitCode: generated.status, stdout: '' };
699
- });
700
- const addCommand = `git add -- ${target} docs/governed-index.md`;
701
- runWorkerCommand('Bash', 'w6-index-stage', { command: addCommand }, addCommand, () => {
702
- fixtureGit(root, ['add', '--', target, 'docs/governed-index.md']);
703
- return { exitCode: 0 };
704
- });
705
- const commitCommand = 'git commit -m "draft EVID ADR and index"';
706
- runWorkerCommand('Bash', 'w6-index-commit', { command: commitCommand }, commitCommand, () => {
707
- fixtureGit(root, ['commit', '-q', '-m', 'draft EVID ADR and index']);
708
- return { exitCode: 0 };
709
- });
710
- const check = runtimeBase === ROOT ? path.join(runtimeBase, 'harness-everything/scripts/doc-check.js')
711
- : path.join(runtimeBase, 'skills/harness-everything/scripts/doc-check.js');
712
- const checkArgs = ['check', '--workspace', root, '--config', '.agents/harness-everything/project-docs.json',
713
- '--changed-path', target, '--base', baselineCommit, '--derived-view', 'docs/governed-index.md', '--conflict-assessment'];
714
- const checkCommand = `node ${shellWord(check)} ${checkArgs.map(value => shellWord(value)).join(' ')}`;
715
- const resolvedCheck = runtimeProvider.resolveDocCheckInvocation(checkCommand, root);
716
- assert.strictEqual(resolvedCheck.kind, 'accepted', `installed combined-check resolution: ${JSON.stringify({ checkCommand, resolvedCheck })}`);
717
- const checked = runWorkerCommand('Bash', 'w6-combined-check', { command: checkCommand }, checkCommand, () => {
718
- const result = spawnSync(process.execPath, [check, ...checkArgs], { cwd: root, encoding: 'utf8' });
719
- assert.strictEqual(result.status, 0, `row-17 combined check: ${result.stderr || result.stdout}`);
720
- const report = JSON.parse(result.stdout);
721
- for (const capability of ['doc-lint', 'link-check', 'derived-regenerate', 'conflict-check']) {
722
- assert.strictEqual(report.capabilities?.[capability]?.state, 'pass', `combined check ${capability} must pass`);
723
- }
724
- return { exitCode: result.status, stdout: result.stdout, stderr: result.stderr };
725
- });
726
- assert.ok(checked.stdout, 'combined check host result retains its real report');
727
- } else {
728
- if (fs.lstatSync(path.join(root, target)).isSymbolicLink()) fs.unlinkSync(path.join(root, target));
729
- fs.writeFileSync(path.join(root, target), `---\nid: ${domain}-001\nstatus: proposed\n---\n\n## Decision\nFinal D for row ${rowId}.\n`);
730
- fixtureGit(root, ['add', '-A']);
731
- fixtureGit(root, ['commit', '-q', '-m', 'D final draft']);
732
- }
733
- }
734
- if (nonDescendant) {
735
- fixtureGit(root, ['checkout', '--orphan', 'unrelated']);
736
- fixtureGit(root, ['rm', '-rf', '.']);
737
- fs.mkdirSync(path.dirname(path.join(root, target)), { recursive: true });
738
- fs.writeFileSync(path.join(root, target), `---\nid: ${domain}-001\nstatus: proposed\n---\n\n## Decision\nUnrelated D for row ${rowId}.\n`);
739
- fixtureGit(root, ['add', '-A']);
740
- fixtureGit(root, ['-c', 'user.name=outline-fixture', '-c', 'user.email=outline-fixture@invalid', 'commit', '-q', '-m', 'unrelated D']);
741
- }
742
- let draftCommit = fixtureGit(root, ['rev-parse', 'HEAD']);
743
- let draftBytes = fs.readFileSync(path.join(root, target));
744
- if (tamperHandoff) {
745
- const handoffFile = path.join(attemptDir, 'handoff.json');
746
- const changed = JSON.parse(fs.readFileSync(handoffFile, 'utf8'));
747
- changed.outline.tree = 'f'.repeat(40);
748
- writeJson(handoffFile, changed);
749
- }
750
- const workerResultPayload = {
751
- session_id: sessionId, cwd: root, hook_event_name: 'PostToolUse', tool_name: 'Task',
752
- tool_use_id: capture.tool_use_id, tool_input: { command: 'Task' },
753
- tool_response: { agentId: options.workerPrincipal || 'draft-worker', interrupted: false, status: 'completed' },
754
- };
755
- const workerStopPayload = {
756
- session_id: sessionId, cwd: root, hook_event_name: 'SubagentStop',
757
- agent_id: options.workerPrincipal || 'draft-worker', agent_type: 'worker',
758
- };
759
- const finalReviewer = 'final-reviewer';
760
- const finalReviewPrePayload = {
761
- session_id: sessionId, cwd: root, hook_event_name: 'PreToolUse', tool_name: 'Task',
762
- tool_use_id: 'final-review-dispatch', tool_input: { prompt: 'Review the final ADR.' },
763
- };
764
- const finalReviewStartPayload = { session_id: sessionId, cwd: root, hook_event_name: 'SubagentStart',
765
- agent_id: finalReviewer, agent_type: 'reviewer' };
766
- const finalResultPayload = {
767
- session_id: sessionId, cwd: root, hook_event_name: 'PostToolUse', tool_name: 'Task',
768
- tool_use_id: 'final-review-dispatch', tool_input: { command: 'Task' },
769
- tool_response: { agentId: finalReviewer, interrupted: false, status: 'completed' },
770
- };
771
- const finalStopPayload = {
772
- session_id: sessionId, cwd: root, hook_event_name: 'SubagentStop', agent_id: finalReviewer,
773
- agent_type: 'reviewer',
774
- last_assistant_message: `Review verdict: approve\nReviewed artifact: ${target} sha256:${sha(draftBytes)}\nSummary: Final candidate reviewed.`,
775
- };
776
- const finalFailurePayload = finalReviewFailure && {
777
- session_id: finalReviewFailure.sessionId || sessionId, cwd: root, hook_event_name: 'PostToolUseFailure', tool_name: 'Task',
778
- tool_use_id: finalReviewFailure.toolUseId || 'final-review-dispatch', tool_input: { command: 'Task' },
779
- is_interrupt: false, error: 'injected final-review failure', tool_response: { exitCode: 1, interrupted: false, status: 'failed' },
780
- };
781
- if (finalReviewFailure) assert.ok(['before-success', 'after-success'].includes(finalReviewFailure.order),
782
- 'final-review failure fixture must declare its order relative to success');
783
- const emitFinalReviewFailure = () => { if (finalFailurePayload) runHook(finalFailurePayload); };
784
- let finalReviewPreCaptured = false;
785
- if (options.realHook) {
786
- if (finalReview && reviewLaunchBeforeWorkerClosure) {
787
- runHook(finalReviewPrePayload);
788
- finalReviewPreCaptured = true;
789
- }
790
- if (workerResultAfterFinalReview) {
791
- if (!omitWorkerStop) runHook(workerStopPayload);
792
- } else if (workerStopAfterFinalReview) {
793
- if (!omitWorkerResult) runHook(workerResultPayload);
794
- } else if (workerCompletionOrder === 'stop-result') {
795
- if (!omitWorkerStop) runHook(workerStopPayload);
796
- if (!omitWorkerResult) runHook(workerResultPayload);
797
- } else {
798
- if (!omitWorkerResult) runHook(workerResultPayload);
799
- if (!omitWorkerStop) runHook(workerStopPayload);
800
- }
801
- for (const make of afterWorkerStop) runHook(make({ root, sessionId, target }));
802
- }
803
- if (finalReview) {
804
- if (options.realHook) {
805
- if (!finalReviewPreCaptured) runHook(finalReviewPrePayload);
806
- runReviewCapture(finalReviewStartPayload);
807
- if (finalReviewFailure?.order === 'before-success') emitFinalReviewFailure();
808
- if (finalReviewCompletionOrder === 'stop-result') {
809
- runHook(finalStopPayload);
810
- runHook(finalResultPayload);
811
- } else {
812
- runHook(finalResultPayload);
813
- runHook(finalStopPayload);
814
- }
815
- if (finalReviewFailure?.order === 'after-success') emitFinalReviewFailure();
816
- } else {
817
- const finalResult = runtimeProvider.buildCaptureRecord(finalResultPayload, 'PostToolUse', root);
818
- const finalStop = runtimeProvider.buildCaptureRecord(finalStopPayload, 'SubagentStop', root);
819
- finalResult.observedIdentity = capture.observedIdentity;
820
- finalStop.observedIdentity = capture.observedIdentity;
821
- extraCaptures.push(finalResult, finalStop);
822
- }
823
- }
824
- if (options.realHook && workerResultAfterFinalReview && !omitWorkerResult) runHook(workerResultPayload);
825
- if (options.realHook && workerStopAfterFinalReview && !omitWorkerStop) runHook(workerStopPayload);
826
- if (completeWorkflow) {
827
- runWorkflowOperation('step-adr', ['step', '--session-id', sessionId, '--step-id', 'adr-evid',
828
- '--disposition', 'pass', '--evidence', 'Independent final ADR review completed']);
829
- runWorkflowOperation('binding-verify', ['binding', '--session-id', sessionId, '--step-id', 'verify-row17',
830
- '--binding-id', 'verification-loop', '--disposition', 'loaded', '--evidence', 'Read the verification-loop skill and ran the combined checker']);
831
- runWorkflowOperation('step-verify', ['step', '--session-id', sessionId, '--step-id', 'verify-row17',
832
- '--disposition', 'pass', '--evidence', 'Combined checker and independent final review completed'], allowDispositionFailure);
833
- }
834
- if (mutateAfterFinalReview) {
835
- fs.writeFileSync(path.join(root, target), `---\nid: DOCS-001\nstatus: proposed\n---\n\n## Decision\nChanged after final review.\n`);
836
- fixtureGit(root, ['add', '-A']);
837
- fixtureGit(root, ['commit', '-q', '-m', 'D changed after review']);
838
- draftCommit = fixtureGit(root, ['rev-parse', 'HEAD']);
839
- draftBytes = fs.readFileSync(path.join(root, target));
840
- }
841
- const captures = options.realHook
842
- ? runtimeProvider.readCaptureView(sessionDir).records
843
- : [...reviewCaptures, capture, ...extraCaptures, ...(!omitWorkerStart ? [workerStart] : []), ...(!omitWorkerResult ? [runtimeProvider.buildCaptureRecord({
844
- session_id: sessionId, cwd: root, hook_event_name: 'PostToolUse', tool_name: 'Task',
845
- tool_use_id: capture.tool_use_id, tool_input: { command: 'Task' },
846
- tool_response: { agentId: options.workerPrincipal || 'draft-worker', interrupted: false, status: 'completed' },
847
- }, 'PostToolUse', root)] : []), ...(!omitWorkerStop ? [runtimeProvider.buildCaptureRecord({
848
- session_id: sessionId, cwd: root, hook_event_name: 'SubagentStop', agent_id: options.workerPrincipal || 'draft-worker', agent_type: 'worker',
849
- }, 'SubagentStop', root)] : []), ...postWorkerCaptures];
850
- const qualification = options.noFakeQualification ? undefined : { source: 'fake-test-fixture', faked: true, toolUseIdPopulated: true,
851
- agentIdPopulated: true, outlineDispatchCaptureVerified: true };
852
- if (removeSeam && capture.outlineDispatch?.seamRef) {
853
- fs.rmSync(path.join(sessionDir, capture.outlineDispatch.seamRef), { force: true });
854
- }
855
- if (handAuthoredCapture) {
856
- const forged = { ...capture, outlineDispatch: { schema: 'harness.outline-dispatch.v1', state: 'accepted',
857
- taskId, attemptId, seamRef: 'doc-reconciliation/outline-confirmation/fake-seam.json',
858
- dispatchInputDigest: sha('candidate-authored') } };
859
- writeJson(path.join(sessionDir, 'doc-reconciliation-capture.json'), { version: 1, records: [forged] });
860
- }
861
- const origin = runtimeProvider.createClaudeOriginProvider({
862
- hostId: 'claude-code', sessionId: providerSessionId, workspaceRoot: root, workflowId, workflowRevision, taskId: providerTaskId,
863
- principals: { author: providerSessionId, executors: [] }, baseline: providerBaseline,
864
- captures, sessionDir, taskBinding,
865
- ...(qualification ? { qualification, outlineFixture: { expectedPin } } : {}),
866
- });
867
- const identity = {
868
- workspaceId: origin.resolveContext({}).context.workspaceId, sessionId: providerSessionId, workflowId, workflowRevision, taskId: providerTaskId,
869
- taskScopeDigest: sha('task-scope'), baselineDigest: sha('baseline-snapshot'),
870
- candidateDigest: sha('candidate-snapshot'), configDigest, prdRoot: 'docs/prd/',
871
- };
872
- const result = origin.resolveEvent({ reference: `${capture.ref}#outline-confirmation`, identity });
873
- let pilotResult = null;
874
- if (runPilot) {
875
- const previousSwitch = process.env.HARNESS_DOC_RECONCILIATION_PILOT;
876
- const previousFactory = runtimeProvider.createClaudeOriginProvider;
877
- runtimeProvider.createClaudeOriginProvider = input => previousFactory({ ...input,
878
- ...(qualification ? { qualification, outlineFixture: { expectedPin } } : {}), taskBinding });
879
- process.env.HARNESS_DOC_RECONCILIATION_PILOT = '1';
880
- const actualWorkflow = options.workflowCli ? JSON.parse(fs.readFileSync(path.join(sessionDir, 'workflow-run.json'), 'utf8')) : null;
881
- const actualSet = options.workflowCli ? JSON.parse(fs.readFileSync(path.join(sessionDir, 'workflow-obligations.json'), 'utf8')) : null;
882
- const context = { root, sessionId, sessionDir, activeHost: 'claude-code', workflow: actualWorkflow || {
883
- workflowId, revision: workflowRevision, strategy: 'iterative-single', state: 'running',
884
- docReconciliationBaseline: { root: baselineRoot, commit: baselineCommit, tree: baselineTree }, docReconciliationTask: taskBinding,
885
- } };
104
+ const previousStateHome = process.env.HARNESS_STATE_HOME;
105
+ const originalRealpathSync = fs.realpathSync;
106
+ let aliasSessionDir;
107
+ let canonicalSessionDir;
886
108
  try {
887
- pilotResult = runtimePilot.assess(context, actualSet || { strategy: 'iterative-single', stepBindingsEnabled: true,
888
- requirements: [{ id: 'prb', summary: 'produce an ADR', acceptance: 'outline review precedes drafting' }] });
109
+ process.env.HARNESS_STATE_HOME = stateHome;
110
+ fs.realpathSync = function realpathSync(target, ...args) {
111
+ if (typeof target === 'string' && path.resolve(target) === path.resolve(aliasRoot)) return path.resolve(aliasRoot);
112
+ return originalRealpathSync.call(fs, target, ...args);
113
+ };
114
+ fs.realpathSync.native = originalRealpathSync.native;
115
+ const { getSessionDir } = require(leg.harnessState);
116
+ aliasSessionDir = getSessionDir(aliasRoot, sessionId);
117
+ canonicalSessionDir = getSessionDir(realRoot, sessionId);
889
118
  } finally {
890
- runtimeProvider.createClaudeOriginProvider = previousFactory;
891
- if (previousSwitch === undefined) delete process.env.HARNESS_DOC_RECONCILIATION_PILOT;
892
- else process.env.HARNESS_DOC_RECONCILIATION_PILOT = previousSwitch;
119
+ fs.realpathSync = originalRealpathSync;
120
+ if (previousStateHome === undefined) delete process.env.HARNESS_STATE_HOME;
121
+ else process.env.HARNESS_STATE_HOME = previousStateHome;
893
122
  }
894
- }
895
- return { captures, origin, identity, draftCommit, draftBytes, result, pilot: pilotResult };
896
- }
897
123
 
898
- return { root, sessionDir, target, taskId, attemptId, sessionId, workflowId, workflowRevision, preOutlineOperation,
899
- baselineCommit, baselineTree, outlineCommit, outlineTree, outlineBlob, outlineBytes, configDigest,
900
- indexAfterCapturedAdd, indexAfterOutlineCommit,
901
- expectedPin, taskBinding, attemptDir, handoff, payload, capture, reviewCaptures, workerStart,
902
- extraCaptures, dispatchAgain, finishDraft, runHook, capturedRecordsAcrossSessions, stateHome, inventoryOperation, workflowOperationWitnesses,
903
- runtimeProvider, runtimePilot, outsideInventoryPath,
904
- faultMarker: path.join(stateHome, 'prb-partial-dispatch-faults-used'),
905
- cleanup: () => {
906
- fs.rmSync(root, { recursive: true, force: true });
907
- fs.rmSync(stateHome, { recursive: true, force: true });
908
- } };
909
- }
910
-
911
- test('strict dispatch parser accepts one exact block and rejects duplicate/free-form/alternate-field tokens', () => {
912
- assert.strictEqual(typeof internals.parseOutlineDispatchPrompt, 'function', 'missing strict tool_input.prompt parser');
913
- const parse = internals.parseOutlineDispatchPrompt;
914
- const valid = parse(`Review complete.\n${dispatchLine}\nStart drafting after the outline review.`);
915
- assert.strictEqual(valid.taskId, 'task-prb');
916
- assert.strictEqual(valid.attemptId, 'attempt-1');
917
- assert.strictEqual(valid.token, 'token-1');
918
- assert.strictEqual(valid.workerRoot, '/tmp/prb-worker');
919
- assert.strictEqual(parse(`${dispatchLine}\n${dispatchLine}`), null, 'two marker blocks are ambiguous');
920
- assert.strictEqual(parse(`token-1\n${dispatchLine.replace('HARNESS_OUTLINE_DISPATCH_V1 ', '')}`), null,
921
- 'a free-form token or alternate-field marker cannot dispatch');
922
- assert.strictEqual(parse({ prompt: dispatchLine }), null, 'only tool_input.prompt text is parsed');
923
- });
924
-
925
- test('outline classifier checks every Decision section before awarding pre-draft status', () => {
926
- assert.strictEqual(typeof internals.parseOutlineCitation, 'function', 'missing all-section outline completeness check');
927
- const target = 'docs/adr/DOCS-001.md';
928
- const placeholder = internals.parseOutlineCitation(Buffer.from(outlineText({ decisionPlaceholder: true })), target);
929
- assert.strictEqual(placeholder.state, 'accepted', 'one placeholder Decision section is an outline');
930
- const duplicate = internals.parseOutlineCitation(Buffer.from(outlineText({ duplicateDecision: true })), target);
931
- assert.strictEqual(duplicate.state, 'unresolved');
932
- assert.strictEqual(duplicate.reason, 'outline-already-draft', 'later substantive Decision text cannot hide behind a placeholder');
933
- const titled = internals.parseOutlineCitation(Buffer.from(outlineText({ titledDecision: true })), target);
934
- assert.strictEqual(titled.state, 'unresolved');
935
- assert.strictEqual(titled.reason, 'outline-already-draft', 'a titled Decision heading cannot evade draft detection');
936
- const indented = internals.parseOutlineCitation(Buffer.from(outlineText({ indentedDecision: true })), target);
937
- assert.strictEqual(indented.state, 'unresolved');
938
- assert.strictEqual(indented.reason, 'outline-already-draft', 'a valid indented Markdown Decision heading cannot evade draft detection');
939
- });
940
-
941
- test('coordinator-seeded inventory pin requires exact bytes, all fixed fields, and one row/domain match', () => {
942
- assert.strictEqual(typeof internals.validateOutlineInventoryPin, 'function', 'missing pinned-inventory validator');
943
- const content = [
944
- '# Synthetic inventory',
945
- 'run id `synthetic-run` · input SHA `abcdef012345`',
946
- '',
947
- '## Mechanism inventory',
948
- '| # | Mechanism | Evidence |',
949
- '|---|---|---|',
950
- '| 20 | ADR identity | mechanism evidence |',
951
- '',
952
- '## Area grouping + candidate domain prefixes',
953
- '| Area | Rows | Candidate prefix | Why |',
954
- '|---|---|---|---|',
955
- '| Documents | 20–22 | `DOCS` | Synthetic fixture |',
956
- ].join('\n') + '\n';
957
- const pin = {
958
- source: 'synthetic://approved-inventory',
959
- sha256: sha(content),
960
- runId: 'synthetic-run',
961
- inputSha: 'abcdef012345',
962
- approvalRef: { issue: 325, commentId: 'synthetic-comment', decision: 1 },
963
- retainedArtifactPath: 'inventory/' + sha(content) + '.md',
964
- };
965
- const valid = internals.validateOutlineInventoryPin({ bytes: Buffer.from(content), pin, expectedPin: pin });
966
- assert.strictEqual(valid.state, 'accepted');
967
- assert.deepStrictEqual(internals.resolveInventoryRow(valid, '20').row, { rowId: '20', domain: 'DOCS' });
968
- const changed = internals.validateOutlineInventoryPin({ bytes: Buffer.from(content + '\nchanged\n'), pin, expectedPin: pin });
969
- assert.strictEqual(changed.state, 'unresolved', 'a self-consistent-looking replacement cannot match the pinned bytes');
970
- const stale = internals.validateOutlineInventoryPin({ bytes: Buffer.from(content), pin: { ...pin, runId: 'stale-run' }, expectedPin: pin });
971
- assert.strictEqual(stale.state, 'unresolved', 'stale metadata cannot be repaired by matching rows');
972
- const staleInput = internals.validateOutlineInventoryPin({ bytes: Buffer.from(content), pin: { ...pin, inputSha: 'feedface' }, expectedPin: pin });
973
- assert.strictEqual(staleInput.state, 'unresolved', 'stale input revision is not a fallback candidate');
974
- const unavailableLocator = internals.validateOutlineInventoryPin({ bytes: Buffer.from(content),
975
- pin: { ...pin, retainedArtifactPath: 'repo-local-copy.md' }, expectedPin: pin });
976
- assert.strictEqual(unavailableLocator.state, 'unresolved', 'an unavailable locator has no candidate-selected fallback');
977
- const missing = internals.validateOutlineInventoryPin({ bytes: null, pin, expectedPin: pin });
978
- assert.strictEqual(missing.state, 'unresolved', 'unavailable source has no fallback');
979
- const duplicate = content.replace('| 20 | ADR identity', '| 20 | duplicate\n| 20 | ADR identity');
980
- const duplicatePin = { ...pin, sha256: sha(duplicate), retainedArtifactPath: 'inventory/' + sha(duplicate) + '.md' };
981
- const duplicateResult = internals.validateOutlineInventoryPin({ bytes: Buffer.from(duplicate), pin: duplicatePin, expectedPin: duplicatePin });
982
- assert.strictEqual(internals.resolveInventoryRow(duplicateResult, '20').state, 'unresolved', 'duplicate row ids are ambiguous');
983
- const multiDomain = content.replace('| Documents | 20–22 | `DOCS` | Synthetic fixture |',
984
- '| Documents | 20–22 | `DOCS` | Synthetic fixture |\n| Other documents | 20 | `ENFC` | Ambiguous mapping |');
985
- const multiDomainPin = { ...pin, sha256: sha(multiDomain), retainedArtifactPath: 'inventory/' + sha(multiDomain) + '.md' };
986
- const multiDomainResult = internals.validateOutlineInventoryPin({ bytes: Buffer.from(multiDomain),
987
- pin: multiDomainPin, expectedPin: multiDomainPin });
988
- assert.strictEqual(internals.resolveInventoryRow(multiDomainResult, '20').state, 'unresolved', 'ambiguous domain mapping is unresolved');
989
- });
990
-
991
- test('the trusted inventory pin maps only owner-approved VERI rows 15–18 to EVID', () => {
992
- const pin = internals.OUTLINE_INVENTORY_PIN;
993
- const bytes = fs.readFileSync(path.join(ROOT,
994
- 'benchmarks/results/live-host/claude-341-outline-dispatch-2026-10-28/inventory/2741bd4514d2cd68f57d93a2b3ce94cbe597ca62d30e26f0ca58e882df5b03c6.md'));
995
- const mapping = [{ rowIds: ['15', '16', '17', '18'], sourceDomain: 'VERI', domain: 'EVID',
996
- approvalRef: 'https://github.com/dyphn1/Harness-everything/issues/325#issuecomment-6706805112' }];
997
- assert.deepStrictEqual(pin.rowDomainMappings, mapping, 'the owner approval is part of the trusted pin');
998
- const valid = internals.validateOutlineInventoryPin({ bytes, pin, expectedPin: pin });
999
- assert.strictEqual(valid.state, 'accepted');
1000
- for (const rowId of ['15', '16', '17', '18']) {
1001
- assert.deepStrictEqual(internals.resolveInventoryRow(valid, rowId).row, { rowId, domain: 'EVID' });
1002
- }
1003
- const substituted = { ...pin, rowDomainMappings: [{ ...mapping[0], domain: 'VERI' }] };
1004
- const stale = internals.validateOutlineInventoryPin({ bytes, pin: substituted, expectedPin: pin });
1005
- assert.strictEqual(stale.state, 'unresolved', 'a substituted domain cannot change the trusted mapping');
1006
- assert.strictEqual(stale.reason, 'inventory-pin-mismatch');
1007
- });
1008
-
1009
- test('pilot offers structured SubagentStop reviews only and preserves drafter independence rejection', () => {
1010
- const sessionDir = fs.mkdtempSync(path.join(os.tmpdir(), 'prb-review-candidates-'));
1011
- const author = 'author-session';
1012
- const draft = provider.buildCaptureRecord({ session_id: author, hook_event_name: 'PostToolUse', tool_name: 'Task',
1013
- tool_use_id: 'draft-dispatch', tool_response: { agentId: 'draft-worker', status: 'completed' } }, 'PostToolUse', '/tmp');
1014
- const ordinary = provider.buildCaptureRecord({ session_id: author, hook_event_name: 'SubagentStop', agent_id: 'draft-worker',
1015
- last_assistant_message: 'Draft complete. The document is ready.' }, 'SubagentStop', '/tmp');
1016
- const reviewResult = provider.buildCaptureRecord({ session_id: author, hook_event_name: 'PostToolUse', tool_name: 'Task',
1017
- tool_use_id: 'review-dispatch', tool_response: { agentId: 'independent-reviewer', status: 'completed' } }, 'PostToolUse', '/tmp');
1018
- const approval = provider.buildCaptureRecord({ session_id: author, hook_event_name: 'SubagentStop', agent_id: 'independent-reviewer',
1019
- last_assistant_message: `Review verdict: approve\nReviewed artifact: docs/adr/EVID-001.md sha256:${'a'.repeat(64)}\nSummary: exact ADR reviewed.` }, 'SubagentStop', '/tmp');
1020
- for (const record of [draft, ordinary, reviewResult, approval]) provider.writeImmutableEvent(sessionDir, record);
1021
- provider.rebuildJournalView(sessionDir);
1022
- const context = { sessionDir, activeHost: 'claude-code', workflow: { docReconciliationTask: { taskId: 'task-review-selection' } } };
1023
- const captures = provider.readCaptureView(sessionDir).records;
1024
- const reviewRefs = pilot._internals.captureReferences(context).filter(ref => ref.endsWith('#quality-review'));
1025
- assert.deepStrictEqual(reviewRefs, [`${approval.ref}#quality-review`], 'ordinary draft completion is not a review candidate');
1026
- assert.strictEqual(provider.reviewRecordIndependent(approval, captures, { author, executors: ['draft-worker'] }), true);
1027
-
1028
- const drafterApproval = provider.buildCaptureRecord({ session_id: author, hook_event_name: 'SubagentStop', agent_id: 'draft-worker',
1029
- last_assistant_message: `Review verdict: approve\nReviewed artifact: docs/adr/EVID-001.md sha256:${'a'.repeat(64)}\nSummary: self approval.` }, 'SubagentStop', '/tmp');
1030
- provider.writeImmutableEvent(sessionDir, drafterApproval);
1031
- provider.rebuildJournalView(sessionDir);
1032
- const withDrafterApproval = provider.readCaptureView(sessionDir).records;
1033
- assert.ok(pilot._internals.captureReferences(context).includes(`${drafterApproval.ref}#quality-review`),
1034
- 'an explicit approval remains visible to the provider independence check');
1035
- assert.strictEqual(provider.reviewRecordIndependent(drafterApproval, withDrafterApproval,
1036
- { author, executors: ['draft-worker'] }), false, 'a drafter cannot approve its own work');
1037
- fs.rmSync(sessionDir, { recursive: true, force: true });
1038
- });
1039
-
1040
- test('review-step rejects a correlated launch failure while keeping positive controls', () => {
1041
- const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), 'prb-review-step-'));
1042
- const previousStateHome = process.env.HARNESS_STATE_HOME;
1043
- const previousWorkspaceRoot = process.env.HARNESS_WORKSPACE_ROOT;
1044
- process.env.HARNESS_STATE_HOME = stateHome;
1045
- process.env.HARNESS_WORKSPACE_ROOT = ROOT;
1046
- const { getSessionDir } = require(path.join(ROOT, 'hooks/scripts/lib/harness-state.js'));
1047
- const kernel = path.join(ROOT, 'harness-everything/scripts/kernel-router.js');
1048
- const controller = path.join(ROOT, 'hooks/scripts/workflow-disposition.js');
1049
- const run = (script, args = [], input) => spawnSync(process.execPath, [script, ...args], {
1050
- cwd: ROOT, encoding: 'utf8', input,
1051
- env: { ...process.env, HARNESS_DOC_RECONCILIATION_PILOT: '1' },
1052
- });
1053
- function scenario(sessionId, failureToolUseId) {
1054
- const payload = { session_id: sessionId, cwd: ROOT, prompt: 'Fix this checkout bug and add a regression test.' };
1055
- assert.strictEqual(run(kernel, [], JSON.stringify(payload)).status, 0, 'route reaches the workflow controller');
1056
- const sessionDir = getSessionDir(ROOT, sessionId, payload);
1057
- const requirements = JSON.stringify([
1058
- { id: 'req-review', stepType: 'review', summary: 'Review the checkout change', acceptance: 'independent review is captured' },
1059
- { id: 'req-verify', stepType: 'verification', summary: 'Verify the review', acceptance: 'objective evidence exists' },
1060
- ]);
1061
- assert.strictEqual(run(controller, ['plan', '--session-id', sessionId, '--requirements-json', requirements,
1062
- '--strategy', 'iterative-single', '--evidence', 'review-step result-correlation fixture']).status, 0);
1063
- assert.strictEqual(run(controller, ['start', '--session-id', sessionId]).status, 0);
1064
- const workflow = JSON.parse(fs.readFileSync(path.join(sessionDir, 'workflow-run.json'), 'utf8'));
1065
- const observedIdentity = { workflowId: workflow.workflowId, workflowRevision: workflow.revision,
1066
- ...(workflow.docReconciliationBaseline ? { baselinePin: workflow.docReconciliationBaseline } : {}) };
1067
- const records = [
1068
- provider.buildCaptureRecord({ session_id: sessionId, cwd: ROOT, hook_event_name: 'PostToolUse', tool_name: 'Task',
1069
- tool_use_id: 'review-launch', tool_response: { agentId: 'independent-reviewer', interrupted: false, status: 'completed' } }, 'PostToolUse', ROOT),
1070
- provider.buildCaptureRecord({ session_id: sessionId, cwd: ROOT, hook_event_name: 'SubagentStop',
1071
- agent_id: 'independent-reviewer', agent_type: 'reviewer',
1072
- last_assistant_message: `Review verdict: approve\nReviewed artifact: README.md sha256:${'a'.repeat(64)}\nSummary: Independent review completed.` }, 'SubagentStop', ROOT),
1073
- ];
1074
- for (const record of records) {
1075
- record.observedIdentity = observedIdentity;
1076
- provider.writeImmutableEvent(sessionDir, record);
1077
- }
1078
- let failure;
1079
- if (failureToolUseId) {
1080
- failure = provider.buildCaptureRecord({ session_id: sessionId, cwd: ROOT, hook_event_name: 'PostToolUseFailure',
1081
- tool_name: 'Task', tool_use_id: failureToolUseId, tool_input: { command: 'Task' },
1082
- is_interrupt: false, error: 'injected launch failure' }, 'PostToolUseFailure', ROOT);
1083
- provider.writeImmutableEvent(sessionDir, failure);
1084
- }
1085
- provider.rebuildJournalView(sessionDir);
1086
- const result = run(controller, ['step', '--session-id', sessionId, '--step-id', 'req-review', '--disposition', 'pass',
1087
- '--evidence', 'independent review was captured']);
1088
- return { result, failure, state: JSON.parse(fs.readFileSync(path.join(sessionDir, 'workflow-obligations.json'), 'utf8')) };
1089
- }
1090
-
1091
- try {
1092
- const matching = scenario('prb-review-matching-failure', 'review-launch');
1093
- assert.strictEqual(matching.failure.session_id, 'prb-review-matching-failure');
1094
- assert.strictEqual(matching.failure.tool_use_id, 'review-launch');
1095
- assert.strictEqual(matching.failure.agent_id, undefined, 'failure-side agent_id is absent');
1096
- assert.notStrictEqual(matching.result.status, 0, 'matching launch failure rejects review step PASS');
1097
- assert.match(matching.result.stderr, /review pending/);
1098
- assert.strictEqual(matching.state.activeStepId, 'req-review');
1099
- assert.strictEqual(scenario('prb-review-success-only', null).result.status, 0, 'success-only review remains accepted');
1100
- assert.strictEqual(scenario('prb-review-unmatched-failure', 'other-launch').result.status, 0,
1101
- 'unmatched failure remains accepted');
1102
- } finally {
1103
- if (previousStateHome === undefined) delete process.env.HARNESS_STATE_HOME;
1104
- else process.env.HARNESS_STATE_HOME = previousStateHome;
1105
- if (previousWorkspaceRoot === undefined) delete process.env.HARNESS_WORKSPACE_ROOT;
1106
- else process.env.HARNESS_WORKSPACE_ROOT = previousWorkspaceRoot;
1107
- fs.rmSync(stateHome, { recursive: true, force: true });
1108
- }
1109
- });
1110
-
1111
- test('generic successful execution or waiver cannot pass outline-confirmation', () => {
1112
- const target = 'docs/adr/DOCS-001.md';
1113
- const digest = sha('final D bytes');
1114
- const baselineDigest = sha('original B');
1115
- const obligation = {
1116
- id: 'outline-confirmation', capability: 'outline-confirmation', strength: 'MUST',
1117
- applicability: 'applicable', scope: { paths: [target] },
1118
- };
1119
- const genericExecution = {
1120
- id: 'generic-exec', obligationId: 'outline-confirmation', kind: 'execution',
1121
- command: 'echo done', exitCode: 0, paths: [target], artifactDigests: { [target]: digest },
1122
- baseDigest: baselineDigest, provenance: 'ordinary shell command',
1123
- };
1124
- const genericWaiver = {
1125
- id: 'generic-waiver', obligationId: 'outline-confirmation', kind: 'waiver', reason: 'approved',
1126
- citedRecordIds: ['generic-exec'], paths: [target], artifactDigests: { [target]: digest }, baseDigest: baselineDigest,
1127
- };
1128
- const output = checkDocObligations({
1129
- obligations: [obligation], artifacts: { [target]: { digest } }, baseline: { digest: baselineDigest },
1130
- executionRecords: [genericExecution], reviewRecords: [genericWaiver],
1131
- });
1132
- assert.notStrictEqual(output.results[0].outcome, 'pass', 'outline-confirmation must bypass generic execution and waiver lanes');
1133
- assert.strictEqual(output.results[0].observation, 'unresolved');
1134
- });
1135
-
1136
- test('outline checker reports a validated O/review/handoff/seam and strict O-to-D as a separate result', () => {
1137
- const target = 'docs/adr/DOCS-001.md';
1138
- const digest = sha('final D bytes');
1139
- const baselineDigest = sha('original B');
1140
- const evidence = {
1141
- schema: 'harness.outline-confirmation.v1', state: 'validated',
1142
- taskId: 'task-prb', attemptId: 'attempt-1', inventoryRowId: '20', domain: 'DOCS',
1143
- inventoryPinDigest: sha('pin'), inventoryArtifactDigest: sha('inventory'),
1144
- baselineCommit: 'a'.repeat(40), outlineCommit: 'b'.repeat(40), draftCommit: 'c'.repeat(40), mergedCommit: 'c'.repeat(40),
1145
- handoffDigest: sha('handoff'), reviewDigest: sha('review'), seamDigest: sha('seam'),
1146
- reviewCaptureDigest: sha('review-capture'), dispatchInputDigest: sha('dispatch'), writerLeaseDigest: sha('lease'),
1147
- dispatchToolUseId: 'dispatch-1',
1148
- ancestry: 'strict-descendant', targetPaths: [target],
1149
- mergeCorrespondence: null,
1150
- outlineArtifactDigests: { [target]: sha('outline O bytes') },
1151
- draftArtifactDigests: { [target]: digest },
1152
- reviewerPrincipal: 'reviewer-agent', coordinatorPrincipal: 'author-session', workerPrincipal: 'worker-agent',
1153
- };
1154
- const output = checkDocObligations({
1155
- obligations: [{ id: 'outline-confirmation', capability: 'outline-confirmation', strength: 'MUST',
1156
- applicability: 'applicable', scope: { paths: [target] } }],
1157
- artifacts: { [target]: { digest } }, baseline: { digest: baselineDigest }, executionRecords: [],
1158
- reviewRecords: [{ id: 'outline-event', obligationId: 'outline-confirmation', kind: 'outline-confirmation',
1159
- provenance: 'validated pre-draft outline evidence', paths: [target], baseDigest: baselineDigest,
1160
- artifactDigests: { [target]: digest }, outlineEvidence: evidence }],
1161
- });
1162
- assert.strictEqual(output.results[0].outcome, 'pass', JSON.stringify({ result: output.results[0], diagnostics: output.diagnostics }));
1163
- assert.strictEqual(output.results[0].observation, 'observed');
1164
- const incomplete = checkDocObligations({
1165
- obligations: [{ id: 'outline-confirmation', capability: 'outline-confirmation', strength: 'MUST',
1166
- applicability: 'applicable', scope: { paths: [target] } }],
1167
- artifacts: { [target]: { digest } }, baseline: { digest: baselineDigest }, executionRecords: [], reviewRecords: [],
1168
- });
1169
- assert.strictEqual(incomplete.results[0].outcome, 'none');
1170
- assert.strictEqual(incomplete.results[0].observation, 'unresolved', 'missing D remains incomplete');
1171
- });
1172
-
1173
- test('PreToolUse capture stores only narrow dispatch evidence and remains fail-open when handoff is absent', () => {
1174
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'prb-outline-capture-'));
1175
- const stateHome = path.join(root, 'state');
1176
- const workspace = path.join(root, 'workspace');
1177
- fs.mkdirSync(workspace, { recursive: true });
1178
- try {
1179
- const payload = {
1180
- session_id: 'outline-author', cwd: workspace, hook_event_name: 'PreToolUse',
1181
- tool_name: 'Task', tool_use_id: 'dispatch-1', tool_input: { prompt: dispatchLine, alternatePrompt: dispatchLine },
1182
- };
1183
- const driven = spawnSync(process.execPath, [path.join(ROOT, 'hooks/scripts/state-persist.js')], {
1184
- cwd: workspace, encoding: 'utf8', input: JSON.stringify(payload),
1185
- env: { ...process.env, HARNESS_STATE_HOME: stateHome, HARNESS_WORKSPACE_ROOT: workspace, HARNESS_DOC_RECONCILIATION_PILOT: '1' },
1186
- });
1187
- assert.strictEqual(driven.status, 0, 'capture failure remains fail-open to the host');
1188
- const journals = [];
1189
- const walk = dir => {
1190
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1191
- const full = path.join(dir, entry.name);
1192
- if (entry.isDirectory()) walk(full);
1193
- else if (entry.name === 'doc-reconciliation-capture.json') journals.push(full);
1194
- }
1195
- };
1196
- walk(stateHome);
1197
- assert.strictEqual(journals.length, 1, 'real state-persist hook captured the dispatch');
1198
- const capture = JSON.parse(fs.readFileSync(journals[0], 'utf8')).records[0];
1199
- assert.strictEqual(capture.outlineDispatch.state, 'unresolved', 'missing handoff cannot earn later credit');
1200
- assert.ok(!Object.hasOwn(capture, 'prompt'), 'raw prompt text is not retained');
1201
- assert.ok(/^[a-f0-9]{64}$/.test(capture.outlineDispatch.promptDigest));
1202
- } finally {
1203
- fs.rmSync(root, { recursive: true, force: true });
1204
- }
1205
- });
1206
-
1207
- test('seam persistence failure consumes the token, keeps tools fail-open, and cannot be repaired on retry', () => {
1208
- const fixture = createOutlineFixture({ realHook: true, blockSeamStorage: true });
1209
- try {
1210
- assert.strictEqual(fixture.capture.outlineDispatch.state, 'unresolved');
1211
- const tokenDigest = sha('token-1');
1212
- const tokenFile = path.join(fixture.attemptDir, 'tokens', `${tokenDigest}.json`);
1213
- assert.ok(fs.existsSync(tokenFile), 'token is consumed before the seam write can fail');
1214
- const replay = fixture.runHook(fixture.payload);
1215
- const last = replay.filter(item => item.event === 'PreToolUse').at(-1);
1216
- assert.strictEqual(last.outlineDispatch.state, 'unresolved', 'retry cannot recreate a missing seam');
1217
- assert.ok(fs.existsSync(tokenFile));
1218
- } finally { fixture.cleanup(); }
1219
- });
1220
-
1221
- test('failed token persistence invalidates the attempt; same-attempt retry requires a fresh token/attempt', () => {
1222
- const fixture = createOutlineFixture({ realHook: true, blockTokenStorage: true });
1223
- try {
1224
- assert.strictEqual(fixture.capture.outlineDispatch.state, 'unresolved');
1225
- const blocked = path.join(fixture.attemptDir, 'tokens');
1226
- assert.ok(fs.existsSync(blocked));
1227
- fs.rmSync(blocked, { force: true });
1228
- const retried = fixture.runHook(fixture.payload);
1229
- const latest = retried.filter(item => item.event === 'PreToolUse').at(-1);
1230
- assert.strictEqual(latest.outlineDispatch.state, 'unresolved', 'an earlier failed token write invalidates this attempt');
1231
- assert.strictEqual(fs.existsSync(path.join(fixture.attemptDir, 'seams', `${sha(String(fixture.capture.tool_use_id))}.json`)), false);
1232
- } finally { fixture.cleanup(); }
1233
- });
1234
-
1235
- test('configured PreToolUse capture observes competing file writers before completion callbacks', () => {
1236
- const manifest = JSON.parse(fs.readFileSync(path.join(ROOT, 'hooks/hooks.json'), 'utf8'));
1237
- const captureHook = manifest.hooks?.PreToolUse?.find(item => item.id === 'harness:pre:pilot-capture');
1238
- const matcher = captureHook?.matcher || '';
1239
- const results = [];
1240
- for (const tool of ['Write', 'Edit', 'apply_patch']) {
1241
- const fixture = createOutlineFixture({ realHook: true });
1242
- try {
1243
- const toolUseId = `competing-${tool}`;
1244
- const input = tool === 'Write' ? { file_path: fixture.target, content: 'competing writer' }
1245
- : tool === 'Edit' ? { file_path: fixture.target, old_string: 'before', new_string: 'after' }
1246
- : { patch: '*** Begin Patch\n*** Update File: docs/adr/DOCS-001.md\n*** End Patch\n' };
1247
- const captures = fixture.runHook({ session_id: fixture.sessionId, cwd: fixture.root,
1248
- hook_event_name: 'PreToolUse', tool_name: tool, tool_use_id: toolUseId,
1249
- agent_id: `competing-principal-${tool}`, agent_type: 'worker', tool_input: input });
1250
- const start = captures.find(item => item.event === 'PreToolUse' && item.tool_use_id === toolUseId);
1251
- const completed = fixture.finishDraft({ runPilot: true });
1252
- results.push({ tool, manifestRouted: matcher.split('|').includes(tool), captured: Boolean(start),
1253
- competingIdentityRetained: start?.agent_id === `competing-principal-${tool}`,
1254
- classifierRejected: JSON.stringify(completed.result).includes('outline-writer-activity-ambiguous'),
1255
- noOutlinePass: completed.pilot?.report?.outlineEvidence?.outcome !== 'pass' });
1256
- } finally { fixture.cleanup(); }
1257
- }
1258
-
1259
- const positive = createOutlineFixture({ realHook: true });
1260
- let positiveResult;
1261
- try {
1262
- const captures = positive.runHook({ session_id: positive.sessionId, cwd: positive.root,
1263
- hook_event_name: 'PreToolUse', tool_name: 'Write', tool_use_id: 'worker-write',
1264
- agent_id: 'draft-worker', agent_type: 'worker',
1265
- tool_input: { file_path: positive.target, content: 'the correlated worker writes' } });
1266
- const start = captures.find(item => item.event === 'PreToolUse' && item.tool_use_id === 'worker-write');
1267
- const completed = positive.finishDraft({ runPilot: true });
1268
- positiveResult = { manifestRouted: matcher.split('|').includes('Write'), captured: Boolean(start),
1269
- eligible: completed.pilot?.report?.outlineEvidence?.outcome === 'pass' };
1270
- } finally { positive.cleanup(); }
1271
-
1272
- const off = createOutlineFixture({ realHook: true });
1273
- let offRemainsWriteFree;
1274
- try {
1275
- const before = provider.readCaptureView(off.sessionDir).records.length;
1276
- off.runHook({ session_id: off.sessionId, cwd: off.root, hook_event_name: 'PreToolUse',
1277
- tool_name: 'Write', tool_use_id: 'pilot-off-write', tool_input: { file_path: off.target, content: 'off' } }, false);
1278
- offRemainsWriteFree = provider.readCaptureView(off.sessionDir).records.length === before;
1279
- } finally { off.cleanup(); }
1280
-
1281
- assert.strictEqual(offRemainsWriteFree, true, 'pilot OFF must remain capture-write-free for file tools');
1282
- assert.strictEqual(positiveResult.eligible, true,
1283
- `the correlated worker remains eligible as a positive control: ${JSON.stringify(positiveResult)}`);
1284
- assert.ok(results.every(item => item.manifestRouted && item.captured && item.competingIdentityRetained
1285
- && item.classifierRejected && item.noOutlinePass)
1286
- && positiveResult.manifestRouted && positiveResult.captured,
1287
- `each configured file-writer start must reach the classifier without a completion callback: ${JSON.stringify({ results, positiveResult })}`);
1288
- });
1289
-
1290
- test('partial seal without token, seam, or retained failure cannot be reused; a fresh successor can recover', () => {
1291
- function faultedFixture() {
1292
- return createOutlineFixture({ realHook: true, failPartialDispatchStorage: true,
1293
- allowMissingDispatchCapture: true });
1294
- }
1295
- function firstFailureIsUnrecorded(fixture) {
1296
- const token = path.join(fixture.attemptDir, 'tokens', `${sha('token-1')}.json`);
1297
- const seam = path.join(fixture.attemptDir, 'seams', `${sha('dispatch-1')}.json`);
1298
- return fs.existsSync(path.join(fixture.attemptDir, 'handoff-seal.json'))
1299
- && fs.existsSync(fixture.faultMarker) && !fs.existsSync(token) && !fs.existsSync(seam)
1300
- && !provider.readCaptureView(fixture.sessionDir).records.some(item => item.tool_use_id === 'dispatch-1');
1301
- }
1302
-
1303
- const sameId = faultedFixture();
1304
- let sameIdRetry;
1305
- let successor;
1306
- try {
1307
- const initialState = firstFailureIsUnrecorded(sameId);
1308
- const sameIdRecords = sameId.runHook(sameId.payload);
1309
- const sameIdCapture = sameIdRecords.filter(item => item.event === 'PreToolUse'
1310
- && item.tool_use_id === sameId.payload.tool_use_id).at(-1);
1311
- sameIdRetry = { retry: sameIdCapture?.outlineDispatch || null, retryCaptured: Boolean(sameIdCapture), initialState };
1312
- const secondAttemptId = 'attempt-2';
1313
- const secondAttemptDir = path.join(path.dirname(sameId.attemptDir), secondAttemptId);
1314
- const lease = { schema: 'harness.outline-writer-lease.v1', id: 'lease-2', taskId: sameId.taskId,
1315
- attemptId: secondAttemptId, principalId: sameId.sessionId, root: sameId.root, exclusive: true, active: true };
1316
- const leaseFile = path.join(secondAttemptDir, 'writer-lease.json');
1317
- writeJson(leaseFile, lease);
1318
- writeJson(path.join(secondAttemptDir, 'handoff.json'), { ...sameId.handoff,
1319
- attemptId: secondAttemptId, handoffId: 'handoff-2', supersedesAttemptId: sameId.attemptId,
1320
- draftDispatchToken: 'token-2', writerLeaseId: lease.id,
1321
- writerLeaseDigest: sha(fs.readFileSync(leaseFile)) });
1322
- const successorPayload = { ...sameId.payload, tool_use_id: 'dispatch-successor', tool_input: {
1323
- prompt: `HARNESS_OUTLINE_DISPATCH_V1 taskId=${sameId.taskId} attemptId=${secondAttemptId} token=token-2 workerRoot=${sameId.root}` } };
1324
- const successorCapture = sameId.runHook(successorPayload).find(item => item.event === 'PreToolUse'
1325
- && item.tool_use_id === successorPayload.tool_use_id);
1326
- successor = successorCapture?.outlineDispatch || null;
1327
- sameIdRetry = { ...sameIdRetry, successor };
1328
- } finally { sameId.cleanup(); }
1329
-
1330
- const differentId = faultedFixture();
1331
- let differentIdRetry;
1332
- try {
1333
- const initialState = firstFailureIsUnrecorded(differentId);
1334
- const retryPayload = { ...differentId.payload, tool_use_id: 'dispatch-different-id' };
1335
- const retryCapture = differentId.runHook(retryPayload).find(item => item.event === 'PreToolUse'
1336
- && item.tool_use_id === retryPayload.tool_use_id);
1337
- differentIdRetry = { initialState, retry: retryCapture?.outlineDispatch || null, retryCaptured: Boolean(retryCapture),
1338
- tokenCreated: fs.existsSync(path.join(differentId.attemptDir, 'tokens', `${sha('token-1')}.json`)),
1339
- seamCreated: fs.existsSync(path.join(differentId.attemptDir, 'seams', `${sha(retryPayload.tool_use_id)}.json`)) };
1340
- } finally { differentId.cleanup(); }
1341
-
1342
- assert.ok(sameIdRetry.initialState && differentIdRetry.initialState,
1343
- `fault injection must leave only each seal, losing both token and failure capture: ${JSON.stringify({ sameIdRetry, differentIdRetry })}`);
1344
- assert.strictEqual(sameIdRetry.successor?.state, 'accepted',
1345
- `a fresh successor attempt can recover while retaining its interrupted predecessor: ${JSON.stringify(sameIdRetry.successor)}`);
1346
- assert.ok(sameIdRetry.retry?.state === 'unresolved' && differentIdRetry.retry?.state === 'unresolved'
1347
- && !differentIdRetry.tokenCreated && !differentIdRetry.seamCreated,
1348
- `neither same-ID nor different-ID retry may reconstruct the interrupted seam: ${JSON.stringify({ sameIdRetry, differentIdRetry })}`);
1349
- });
1350
-
1351
- test('pilot exposes a real-capture-only outline reference resolver', () => {
1352
- assert.strictEqual(typeof pilot._internals?.outlineDispatchReferences, 'function',
1353
- 'missing pilot reference discovery from retained capture records');
1354
- const resolve = pilot._internals.outlineDispatchReferences;
1355
- const captured = [{
1356
- ref: 'PreToolUse:fixture', event: 'PreToolUse', tool_name: 'Task', tool_use_id: 'dispatch-1',
1357
- outlineDispatch: { state: 'accepted', taskId: 'task-prb', attemptId: 'attempt-1' },
1358
- }];
1359
- assert.deepStrictEqual(resolve(captured, 'task-prb'), ['PreToolUse:fixture#outline-confirmation']);
1360
- assert.deepStrictEqual(resolve([], 'task-prb'), [], 'hand-authored JSON with no host capture creates no event ref');
1361
- });
1362
-
1363
- test('shipped route + plan/start CLI pins the outline task binding in canonical and packaged layouts', () => {
1364
- // Live run 2026-10-28: the pilot's module lookup missed workflow-obligations, so no task pin was ever written.
1365
- for (const [layout, base] of [['canonical', ROOT], ['packaged', path.join(ROOT, 'plugins/harness-everything')]]) {
1366
- const root = canonical(fs.mkdtempSync(path.join(os.tmpdir(), 'prb-task-pin-')));
1367
- const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), 'prb-task-pin-state-'));
1368
- try {
1369
- fixtureGit(root, ['init', '-q']);
1370
- fs.writeFileSync(path.join(root, 'README.md'), 'B\n');
1371
- fixtureGit(root, ['add', '-A']);
1372
- fixtureGit(root, ['commit', '-q', '-m', 'B baseline']);
1373
- const sessionId = `task-pin-${layout}`;
1374
- const env = { ...process.env, HARNESS_STATE_HOME: stateHome, HARNESS_WORKSPACE_ROOT: root, HARNESS_DOC_RECONCILIATION_PILOT: '1' };
1375
- const kernel = layout === 'canonical' ? path.join(base, 'harness-everything/scripts/kernel-router.js')
1376
- : path.join(base, 'skills/harness-everything/scripts/kernel-router.js');
1377
- const run = (script, args, input) => {
1378
- const child = spawnSync(process.execPath, [script, ...args], { cwd: root, env, encoding: 'utf8', input });
1379
- assert.strictEqual(child.status, 0, `${layout} ${path.basename(script)} ${args[0] || ''}: ${child.stderr || child.stdout}`);
124
+ const env = {
125
+ ...process.env,
126
+ HARNESS_STATE_HOME: stateHome,
127
+ HARNESS_WORKSPACE_ROOT: aliasRoot,
128
+ PRB_TEST_ALIAS_ROOT: aliasRoot,
1380
129
  };
1381
- run(kernel, [], JSON.stringify({ session_id: sessionId, cwd: root, prompt: 'Draft an ADR from the reviewed outline and verify it' }));
1382
- const controller = path.join(base, 'hooks/scripts/workflow-disposition.js');
1383
- run(controller, ['plan', '--session-id', sessionId, '--strategy', 'iterative-single', '--evidence', 'task pin fixture',
1384
- '--requirements-json', JSON.stringify([
1385
- { id: 'adr', stepType: 'doc-change', summary: 'draft ADR', acceptance: 'outline review precedes drafting' },
1386
- { id: 'verify', stepType: 'verification', summary: 'verify', acceptance: 'checker runs' }])]);
1387
- run(controller, ['start', '--session-id', sessionId]);
1388
- const prior = process.env.HARNESS_STATE_HOME;
1389
- process.env.HARNESS_STATE_HOME = stateHome;
1390
- let sessionDir;
1391
- try { sessionDir = require(path.join(ROOT, 'hooks/scripts/lib/harness-state.js')).getSessionDir(root, sessionId); }
1392
- finally { if (prior === undefined) delete process.env.HARNESS_STATE_HOME; else process.env.HARNESS_STATE_HOME = prior; }
1393
- const workflow = JSON.parse(fs.readFileSync(path.join(sessionDir, 'workflow-run.json'), 'utf8'));
1394
- assert.ok(workflow.docReconciliationBaseline, `${layout}: baseline pin is captured`);
1395
- assert.strictEqual(workflow.docReconciliationTask?.taskId, 'task-adr+verify', `${layout}: task pin is captured at plan/start`);
1396
- } finally {
1397
- fs.rmSync(root, { recursive: true, force: true });
1398
- fs.rmSync(stateHome, { recursive: true, force: true });
1399
- }
1400
- }
1401
- });
130
+ const runHook = payload => spawnSync(process.execPath,
131
+ ['--require', preload, leg.statePersist], {
132
+ cwd: aliasRoot,
133
+ input: JSON.stringify(payload),
134
+ encoding: 'utf8',
135
+ env,
136
+ });
1402
137
 
1403
- test('pre-dispatch seam requires review, exact worker root, clean O tree, lease, pin, and immutable handoff', () => {
1404
- assert.strictEqual(typeof internals.captureOutlineDispatch, 'function', 'missing synchronous pre-dispatch seam');
1405
- const differentWorkerRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'prb-outline-different-worker-'));
1406
- try {
1407
- for (const [name, options, reason] of [
1408
- ['dispatch before review cannot be repaired by later review/handoff', { captureBeforeReview: true }, 'review was absent at dispatch'],
1409
- ['draft worktree mutation after handoff is caught before dispatch', { dirtyBeforeDispatch: true }, 'worker root was not clean at O'],
1410
- ['missing writer identity or lease stays unresolved', { omitHandoff: true }, 'handoff/lease absent'],
1411
- ['a no-force-push policy is not evidence of pre-draft ordering', { omitHandoff: true }, 'no force-push cannot replace a handoff'],
1412
- ['prompt token must exactly equal the coordinator handoff token', { handoffOverrides: { draftDispatchToken: 'coordinator-token' } }, 'prompt token is not handoff-issued'],
1413
- ['an outline already containing a complete decision is not pre-draft evidence', { completeOutline: true }, 'O is already a draft'],
1414
- ['a second substantive Decision heading cannot hide after a placeholder section', { duplicateDecision: true }, 'later Decision text makes O a draft'],
1415
- ['a one-to-three-space indented Markdown Decision heading is still substantive', { indentedDecision: true }, 'indented Decision text makes O a draft'],
1416
- ['target present at B cannot be treated as a new document', { targetExistsAtB: true }, 'target existed at original B'],
1417
- ['same author and reviewer is not independent', { reviewerPrincipal: 'author-session' }, 'reviewer is the author'],
1418
- ['wrong row or domain mapping does not resolve inventory scope', { rowId: '99' }, 'row is absent from pinned inventory'],
1419
- ]) {
1420
- const fixture = createOutlineFixture(options);
1421
138
  try {
1422
- assert.strictEqual(fixture.capture.outlineDispatch.state, 'unresolved', reason);
1423
- const later = fixture.finishDraft().result;
1424
- assert.notStrictEqual(later.status, 'accepted', `${name}: later evidence cannot repair the seam`);
1425
- } finally { fixture.cleanup(); }
1426
- }
1427
- const wrongRoot = createOutlineFixture({ markerRoot: differentWorkerRoot });
1428
- try {
1429
- assert.notStrictEqual(canonical(wrongRoot.root), canonical(differentWorkerRoot), 'negative uses an existing, distinct directory');
1430
- assert.strictEqual(wrongRoot.capture.outlineDispatch.state, 'unresolved', 'a different existing root stays unresolved');
1431
- assert.notStrictEqual(wrongRoot.finishDraft().result.status, 'accepted', 'later evidence cannot repair the root mismatch');
1432
- } finally { wrongRoot.cleanup(); }
1433
- } finally { fs.rmSync(differentWorkerRoot, { recursive: true, force: true }); }
1434
- });
1435
-
1436
- test('canonical root identity accepts an alias across marker, handoff, lease, and worker capture', () => {
1437
- const fixture = createOutlineFixture({ workerRootAlias: true });
1438
- try {
1439
- assert.strictEqual(fixture.capture.outlineDispatch.state, 'accepted', JSON.stringify(fixture.capture.outlineDispatch));
1440
- assert.strictEqual(fixture.finishDraft().result.status, 'accepted', 'worker CWD and aliased root identify one directory');
1441
- } finally { fixture.cleanup(); }
1442
- });
1443
-
1444
- test('one-use token deduplicates identical seams but replayed tool-use records stay unresolved', () => {
1445
- assert.strictEqual(typeof internals.captureOutlineDispatch, 'function', 'missing token-consuming seam');
1446
- const duplicate = createOutlineFixture();
1447
- try {
1448
- const same = duplicate.dispatchAgain();
1449
- assert.strictEqual(same.outlineDispatch.state, 'accepted', JSON.stringify(same.outlineDispatch));
1450
- assert.strictEqual(same.outlineDispatch.duplicate, true);
1451
- assert.notStrictEqual(duplicate.finishDraft().result.status, 'accepted', 'a replayed host PreToolUse record is not a unique dispatch anchor');
1452
- } finally { duplicate.cleanup(); }
1453
-
1454
- for (const [name, replay] of [
1455
- ['same token on a different tool_use_id', { toolUseId: 'dispatch-2' }],
1456
- ['same tool_use_id with changed dispatch input', { prompt: dispatchLine + '\nchanged input' }],
1457
- ]) {
1458
- const fixture = createOutlineFixture();
1459
- try {
1460
- const replayed = fixture.dispatchAgain(replay);
1461
- assert.strictEqual(replayed.outlineDispatch.state, 'unresolved', name);
1462
- const completed = fixture.finishDraft();
1463
- assert.notStrictEqual(completed.result.status, 'accepted', `${name} cannot earn later credit: ${JSON.stringify(completed.captures.filter(item => item.event === 'PreToolUse').map(item => ({ id: item.tool_use_id, dispatch: item.outlineDispatch })))}`);
1464
- } finally { fixture.cleanup(); }
1465
- }
1466
-
1467
- const consumed = createOutlineFixture();
1468
- try {
1469
- const seamFile = path.join(consumed.attemptDir, 'seams', `${sha(consumed.capture.tool_use_id)}.json`);
1470
- fs.rmSync(seamFile, { force: true });
1471
- const retry = consumed.dispatchAgain();
1472
- assert.strictEqual(retry.outlineDispatch.state, 'unresolved', 'a consumed token with a missing seam is never recreated');
1473
- } finally { consumed.cleanup(); }
1474
- });
1475
-
1476
- test('outline evidence binds exact task, B, O blobs, independent review, worker start/result, and strict O-to-D', () => {
1477
- assert.strictEqual(typeof internals.captureOutlineDispatch, 'function', 'missing pre-dispatch evidence');
1478
- const valid = createOutlineFixture();
1479
- try {
1480
- const completed = valid.finishDraft({ finalReview: true });
1481
- assert.strictEqual(valid.capture.outlineDispatch.state, 'accepted');
1482
- assert.strictEqual(completed.result.status, 'accepted', JSON.stringify(completed.result));
1483
- assert.strictEqual(completed.result.event.capability, 'outline-confirmation');
1484
- } finally { valid.cleanup(); }
1485
-
1486
- const placeholder = createOutlineFixture({ decisionPlaceholder: true });
1487
- try {
1488
- assert.strictEqual(placeholder.capture.outlineDispatch.state, 'accepted',
1489
- 'one placeholder Decision heading is still a valid outline');
1490
- assert.strictEqual(placeholder.finishDraft().result.status, 'accepted');
1491
- } finally { placeholder.cleanup(); }
1492
-
1493
- const delayedWriter = createOutlineFixture();
1494
- try {
1495
- delayedWriter.reviewCaptures.unshift(provider.buildCaptureRecord({
1496
- session_id: delayedWriter.sessionId, cwd: delayedWriter.root, hook_event_name: 'PostToolUse',
1497
- tool_name: 'Edit', tool_use_id: 'delayed-edit', agent_id: delayedWriter.sessionId,
1498
- tool_input: { file_path: delayedWriter.target }, tool_response: { interrupted: false },
1499
- }, 'PostToolUse', delayedWriter.root));
1500
- assert.notStrictEqual(delayedWriter.finishDraft().result.status, 'accepted',
1501
- 'a delayed write/edit callback from the coordinator remains visible and blocks ambiguous writer history');
1502
- } finally { delayedWriter.cleanup(); }
1503
-
1504
- // Live run 2026-10-28: a non-isolated reviewer starts in O; only a stop journaled before the dispatch clears it.
1505
- const reviewerStart = fixture => provider.buildCaptureRecord({ session_id: fixture.sessionId, cwd: fixture.root,
1506
- hook_event_name: 'SubagentStart', agent_id: 'outline-reviewer', agent_type: 'reviewer' }, 'SubagentStart', fixture.root);
1507
- const stoppedReviewer = createOutlineFixture();
1508
- try {
1509
- // The default fixture already journals the reviewer's single Start before its Stop.
1510
- const completed = stoppedReviewer.finishDraft();
1511
- assert.strictEqual(completed.result.status, 'accepted',
1512
- `a reviewer that started and stopped in O before the dispatch is not a competing writer: ${JSON.stringify(completed.result)}`);
1513
- } finally { stoppedReviewer.cleanup(); }
1514
-
1515
- const postDraftReviewer = createOutlineFixture();
1516
- try {
1517
- const reviewer = 'post-draft-reviewer';
1518
- const captures = [
1519
- provider.buildCaptureRecord({ session_id: postDraftReviewer.sessionId, cwd: postDraftReviewer.root,
1520
- hook_event_name: 'SubagentStart', agent_id: reviewer, agent_type: 'reviewer' }, 'SubagentStart', postDraftReviewer.root),
1521
- provider.buildCaptureRecord({ session_id: postDraftReviewer.sessionId, cwd: postDraftReviewer.root,
1522
- hook_event_name: 'PostToolUse', tool_name: 'Read', tool_use_id: 'post-draft-read', agent_id: reviewer,
1523
- tool_input: { file_path: postDraftReviewer.target }, tool_response: { interrupted: false } }, 'PostToolUse', postDraftReviewer.root),
1524
- provider.buildCaptureRecord({ session_id: postDraftReviewer.sessionId, cwd: postDraftReviewer.root,
1525
- hook_event_name: 'PostToolUse', tool_name: 'Task', tool_use_id: 'post-draft-review',
1526
- tool_response: { agentId: reviewer, status: 'completed' } }, 'PostToolUse', postDraftReviewer.root),
1527
- provider.buildCaptureRecord({ session_id: postDraftReviewer.sessionId, cwd: postDraftReviewer.root,
1528
- hook_event_name: 'SubagentStop', agent_id: reviewer, agent_type: 'reviewer' }, 'SubagentStop', postDraftReviewer.root),
1529
- ];
1530
- const completed = postDraftReviewer.finishDraft({ postWorkerCaptures: captures });
1531
- assert.strictEqual(completed.result.status, 'accepted',
1532
- `a same-root reviewer starting after the draft worker's Stop does not overlap the draft interval: ${JSON.stringify(completed.result)}`);
1533
- } finally { postDraftReviewer.cleanup(); }
1534
-
1535
- for (const [name, arrange] of [
1536
- ['post-stop reviewer missing Stop', fixture => [
1537
- provider.buildCaptureRecord({ session_id: fixture.sessionId, cwd: fixture.root,
1538
- hook_event_name: 'SubagentStart', agent_id: 'post-draft-reviewer', agent_type: 'reviewer' }, 'SubagentStart', fixture.root),
1539
- ]],
1540
- ['post-stop reviewer with duplicate Starts', fixture => {
1541
- const start = provider.buildCaptureRecord({ session_id: fixture.sessionId, cwd: fixture.root,
1542
- hook_event_name: 'SubagentStart', agent_id: 'post-draft-reviewer', agent_type: 'reviewer' }, 'SubagentStart', fixture.root);
1543
- return [start, { ...start, ref: `${start.ref}:dup`, captureId: `${start.captureId}:dup` }, provider.buildCaptureRecord({
1544
- session_id: fixture.sessionId, cwd: fixture.root, hook_event_name: 'SubagentStop',
1545
- agent_id: 'post-draft-reviewer', agent_type: 'reviewer' }, 'SubagentStop', fixture.root)];
1546
- }],
1547
- ['post-stop reviewer Stop before Start', fixture => [
1548
- provider.buildCaptureRecord({ session_id: fixture.sessionId, cwd: fixture.root,
1549
- hook_event_name: 'SubagentStop', agent_id: 'post-draft-reviewer', agent_type: 'reviewer' }, 'SubagentStop', fixture.root),
1550
- provider.buildCaptureRecord({ session_id: fixture.sessionId, cwd: fixture.root,
1551
- hook_event_name: 'SubagentStart', agent_id: 'post-draft-reviewer', agent_type: 'reviewer' }, 'SubagentStart', fixture.root),
1552
- ]],
1553
- ]) {
1554
- const fixture = createOutlineFixture();
1555
- try {
1556
- const completed = fixture.finishDraft({ postWorkerCaptures: arrange(fixture) });
1557
- assert.ok(completed.result.diagnostics?.some(item => item.code === 'outline-competing-writer-start'),
1558
- `${name} cannot use the post-stop exception: ${JSON.stringify(completed.result)}`);
1559
- } finally { fixture.cleanup(); }
1560
- }
1561
-
1562
- const postDraftWriter = createOutlineFixture();
1563
- try {
1564
- const reviewer = 'post-draft-reviewer';
1565
- const captures = [
1566
- provider.buildCaptureRecord({ session_id: postDraftWriter.sessionId, cwd: postDraftWriter.root,
1567
- hook_event_name: 'SubagentStart', agent_id: reviewer, agent_type: 'reviewer' }, 'SubagentStart', postDraftWriter.root),
1568
- provider.buildCaptureRecord({ session_id: postDraftWriter.sessionId, cwd: postDraftWriter.root,
1569
- hook_event_name: 'PostToolUse', tool_name: 'Edit', tool_use_id: 'post-draft-edit', agent_id: reviewer,
1570
- tool_input: { file_path: postDraftWriter.target }, tool_response: { interrupted: false } }, 'PostToolUse', postDraftWriter.root),
1571
- provider.buildCaptureRecord({ session_id: postDraftWriter.sessionId, cwd: postDraftWriter.root,
1572
- hook_event_name: 'PostToolUse', tool_name: 'Task', tool_use_id: 'post-draft-review',
1573
- tool_response: { agentId: reviewer, status: 'completed' } }, 'PostToolUse', postDraftWriter.root),
1574
- provider.buildCaptureRecord({ session_id: postDraftWriter.sessionId, cwd: postDraftWriter.root,
1575
- hook_event_name: 'SubagentStop', agent_id: reviewer, agent_type: 'reviewer' }, 'SubagentStop', postDraftWriter.root),
1576
- ];
1577
- const completed = postDraftWriter.finishDraft({ postWorkerCaptures: captures });
1578
- assert.ok(completed.result.diagnostics?.some(item => item.code === 'outline-writer-activity-ambiguous'),
1579
- `a write after the post-stop reviewer start remains ambiguous: ${JSON.stringify(completed.result)}`);
1580
- } finally { postDraftWriter.cleanup(); }
1581
-
1582
- for (const [name, arrange] of [
1583
- ['reviewer stop after the dispatch', fixture => {
1584
- const stop = fixture.reviewCaptures.findIndex(item => item.event === 'SubagentStop');
1585
- fixture.extraCaptures.push(...fixture.reviewCaptures.splice(stop, 1));
1586
- fixture.reviewCaptures.unshift(reviewerStart(fixture));
1587
- }],
1588
- ['reviewer start without a stop', fixture => {
1589
- fixture.reviewCaptures.unshift(provider.buildCaptureRecord({ session_id: fixture.sessionId, cwd: fixture.root,
1590
- hook_event_name: 'SubagentStart', agent_id: 'other-agent', agent_type: 'reviewer' }, 'SubagentStart', fixture.root));
1591
- }],
1592
- ['reviewer start after its stop', fixture => { fixture.reviewCaptures.push(reviewerStart(fixture)); }],
1593
- ['duplicate reviewer start with one stop before the dispatch', fixture => {
1594
- fixture.reviewCaptures.unshift(reviewerStart(fixture), reviewerStart(fixture));
1595
- }],
1596
- ['reviewer start with duplicate stops before the dispatch', fixture => {
1597
- const stop = fixture.reviewCaptures.find(item => item.event === 'SubagentStop');
1598
- fixture.reviewCaptures.unshift(reviewerStart(fixture));
1599
- fixture.reviewCaptures.push({ ...stop, ref: `${stop.ref}:dup`, captureId: `${stop.captureId}:dup` });
1600
- }],
1601
- ['reviewer start after the dispatch', fixture => { fixture.extraCaptures.push(reviewerStart(fixture)); }],
1602
- ]) {
1603
- const fixture = createOutlineFixture();
1604
- try {
1605
- arrange(fixture);
1606
- const completed = fixture.finishDraft();
1607
- assert.ok(completed.result.diagnostics?.some(item => item.code === 'outline-competing-writer-start'),
1608
- `${name} stays a competing writer start: ${JSON.stringify(completed.result)}`);
1609
- } finally { fixture.cleanup(); }
1610
- }
1611
-
1612
- const unqualified = createOutlineFixture();
1613
- try {
1614
- const completed = unqualified.finishDraft();
1615
- const noRetainedMapping = provider.createClaudeOriginProvider({
1616
- hostId: 'claude-code', sessionId: unqualified.sessionId, workspaceRoot: unqualified.root,
1617
- workflowId: unqualified.workflowId, workflowRevision: unqualified.workflowRevision, taskId: unqualified.taskId,
1618
- principals: { author: unqualified.sessionId, executors: [] },
1619
- baseline: { root: unqualified.root, commit: unqualified.baselineCommit },
1620
- captures: completed.captures, sessionDir: unqualified.sessionDir, taskBinding: unqualified.taskBinding,
1621
- qualification: { source: 'fake-test-fixture', faked: true, toolUseIdPopulated: true, agentIdPopulated: true },
1622
- outlineFixture: { expectedPin: unqualified.expectedPin },
1623
- });
1624
- assert.notStrictEqual(noRetainedMapping.resolveEvent({ reference: `${unqualified.capture.ref}#outline-confirmation`,
1625
- identity: completed.identity }).status, 'accepted', 'unqualified live prompt/root mapping never earns positive credit');
1626
- } finally { unqualified.cleanup(); }
1627
-
1628
- for (const [name, fixtureOptions, finishOptions] of [
1629
- ['wrong task', {}, { providerTaskId: 'task-other' }],
1630
- ['wrong session after restart', {}, { providerSessionId: 'different-session' }],
1631
- ['wrong baseline/config/O tree/blob binding', { handoffOverrides: { configDigest: 'f'.repeat(64) } }, {}],
1632
- ['missing O Git object', { handoffOverrides: { outline: { commit: 'f'.repeat(40), tree: 'e'.repeat(40), targetBlobs: {} } } }, {}],
1633
- ['wrong target path binding', { handoffOverrides: { targetPaths: ['docs/adr/DOCS-999.md'] } }, {}],
1634
- ['wrong O tree/blob binding', { handoffOverrides: { outline: { commit: 'a'.repeat(40), tree: 'f'.repeat(40), targetBlobs: {} } } }, {}],
1635
- ['missing Git object', {}, { draft: false }],
1636
- ['D is not a strict descendant of O', {}, { nonDescendant: true }],
1637
- ['no final D', {}, { draft: false }],
1638
- ['worker start/root/principal absent', {}, { omitWorkerStart: true }],
1639
- ['eventual Task result absent', {}, { omitWorkerResult: true }],
1640
- ['outline reviewer is also the draft worker', { reviewerPrincipal: 'draft-worker' }, {}],
1641
- ['unknown competing writer has no positive lease evidence', { competingWriters: true }, {}],
1642
- ]) {
1643
- const fixture = createOutlineFixture(fixtureOptions);
1644
- try {
1645
- const completed = fixture.finishDraft(finishOptions);
1646
- assert.notStrictEqual(completed.result.status, 'accepted', `${name} is rejected or unresolved`);
1647
- } finally { fixture.cleanup(); }
1648
- }
1649
- });
1650
-
1651
- test('baseline integrity, callback order, delayed result, stash/restore, and unobservable writer channels stay unresolved', () => {
1652
- assert.strictEqual(typeof internals.captureOutlineDispatch, 'function', 'missing pre-dispatch seam validation');
1653
- for (const [name, fixtureOptions] of [
1654
- ['a write before review', { dirtyBeforeDispatch: true }],
1655
- ['a missing pre-dispatch handoff', { omitHandoff: true }],
1656
- ['a target deleted and re-added after it existed at B', { targetExistsAtB: true }],
1657
- ['a complete draft merely labelled as an outline', { completeOutline: true }],
1658
- ]) {
1659
- const fixture = createOutlineFixture(fixtureOptions);
1660
- try {
1661
- assert.strictEqual(fixture.capture.outlineDispatch.state, 'unresolved', name);
1662
- const delayed = fixture.finishDraft({ omitWorkerResult: true });
1663
- assert.notStrictEqual(delayed.result.status, 'accepted', `${name}; delayed callback/result cannot repair the seam`);
1664
- } finally { fixture.cleanup(); }
1665
- }
1666
-
1667
- const movedBaseline = createOutlineFixture({
1668
- handoffOverrides: { baseline: { root: '/tmp/other-root', commit: 'd'.repeat(40), tree: 'e'.repeat(40), configDigest: 'f'.repeat(64) } },
1669
- });
1670
- try {
1671
- assert.strictEqual(movedBaseline.capture.outlineDispatch.state, 'unresolved', 'B cannot be reset to O or another root');
1672
- } finally { movedBaseline.cleanup(); }
1673
-
1674
- const changedAfterReview = createOutlineFixture();
1675
- try {
1676
- fs.writeFileSync(path.join(changedAfterReview.root, changedAfterReview.target), 'changed after O review');
1677
- assert.strictEqual(internals.captureOutlineDispatch({
1678
- payload: changedAfterReview.payload, capture: changedAfterReview.capture, sessionDir: changedAfterReview.sessionDir,
1679
- workspaceRoot: changedAfterReview.root, captures: changedAfterReview.reviewCaptures,
1680
- fixtureExpectedPin: changedAfterReview.expectedPin,
1681
- }).state, 'unresolved', 'stash/restore or any draft bytes before dispatch make the worker root dirty');
1682
- } finally { changedAfterReview.cleanup(); }
1683
-
1684
- const shellWriter = createOutlineFixture();
1685
- try {
1686
- shellWriter.reviewCaptures.unshift(provider.buildCaptureRecord({
1687
- session_id: shellWriter.sessionId, cwd: shellWriter.root, hook_event_name: 'PostToolUse',
1688
- tool_name: 'Bash', tool_use_id: 'shell-writer-1', agent_id: shellWriter.sessionId,
1689
- tool_input: { command: 'node ./mutate.js' }, tool_response: { interrupted: false },
1690
- }, 'PostToolUse', shellWriter.root));
1691
- assert.notStrictEqual(shellWriter.finishDraft().result.status, 'accepted',
1692
- 'an unclassified script-capable shell from a non-worker remains unresolved');
1693
- } finally { shellWriter.cleanup(); }
1694
- });
1695
-
1696
- const outlineMappingV2 = {
1697
- version: 'claude-outline-dispatch-mapping/2',
1698
- promptField: 'tool_input.prompt',
1699
- dispatchKey: 'session_id+tool_use_id',
1700
- runInBackgroundField: 'tool_input.run_in_background',
1701
- isolationPresenceField: 'tool_input.isolation',
1702
- resultAgentIdField: 'tool_response.agentId',
1703
- resultStatusField: 'tool_response.status',
1704
- workerStartEvent: 'SubagentStart',
1705
- workerStopEvent: 'SubagentStop',
1706
- workerIdentity: 'session_id+agent_id',
1707
- workerRootField: 'cwd',
1708
- };
1709
-
1710
- test('valid separate outline export opens outline qualification', () => {
1711
- const staged = stageQualificationTree('source');
1712
- try {
1713
- const records = [qualificationDispatch(), qualificationStart(), qualificationResult(), qualificationStop()];
1714
- const bytes = Buffer.from(records.map(record => JSON.stringify(record)).join('\n') + '\n');
1715
- const file = 'doc-reconciliation-outline-capture.sanitized.jsonl';
1716
- fs.writeFileSync(path.join(staged.libDir, file), bytes);
1717
- staged.writeExport(staged.validExport({
1718
- outlineDispatchCapture: { mapping: outlineMappingV2, file, sha256: sha(bytes), hostVersion: '2.1.312',
1719
- run: 'run8', baseline: '1bd0f805031c5577a6e7f72a9bc5b41618b71fc1' },
1720
- }));
1721
- const outcome = require(path.join(staged.libDir, 'doc-reconciliation-provider.js'))
1722
- ._internals.validateOutlineCaptureQualification({ hostId: 'claude-code' });
1723
- assert.strictEqual(outcome.open, true, JSON.stringify(outcome));
1724
- } finally { staged.cleanup(); }
1725
- });
1726
-
1727
- function qualificationDispatch({ id = 'dispatch-1', promptId = 'shared-prompt', background = false, hasBackground = true,
1728
- isolation, hasIsolation = false, session = 'coordinator' } = {}) {
1729
- const toolInput = { prompt: dispatchLine, ...(hasBackground ? { run_in_background: background } : {}) };
1730
- if (hasIsolation) toolInput.isolation = isolation;
1731
- return { event: 'PreToolUse', tool_name: 'Task', tool_use_id: id, session_id: session, prompt_id: promptId, tool_input: toolInput };
1732
- }
1733
-
1734
- function qualificationStart(agentId = 'worker', { session = 'coordinator', cwd = '/tmp/prb-worker', id } = {}) {
1735
- return { event: 'SubagentStart', ...(id ? { tool_use_id: id } : {}), agent_id: agentId, session_id: session, cwd };
1736
- }
1737
-
1738
- function qualificationStop(agentId = 'worker', { session = 'coordinator', cwd = '/tmp/prb-worker' } = {}) {
1739
- return { event: 'SubagentStop', agent_id: agentId, session_id: session, cwd };
1740
- }
1741
-
1742
- function qualificationResult(id = 'dispatch-1', agentId = 'worker', status = 'completed', { session = 'coordinator', legacyAgentId } = {}) {
1743
- const toolResponse = { agentId };
1744
- if (status !== null) toolResponse.status = status;
1745
- return { event: 'PostToolUse', tool_name: 'Task', tool_use_id: id, session_id: session,
1746
- ...(legacyAgentId !== undefined ? { agent_id: legacyAgentId } : {}), tool_response: toolResponse };
1747
- }
1748
-
1749
- function stagedOutlineOutcome(staged) {
1750
- return require(path.join(staged.libDir, 'doc-reconciliation-provider.js'))
1751
- ._internals.validateOutlineCaptureQualification({ hostId: 'claude-code' });
1752
- }
1753
-
1754
- function writeStagedOutlineEvidence(staged, records) {
1755
- const file = 'doc-reconciliation-outline-capture.sanitized.jsonl';
1756
- const bytes = Buffer.from(records.map(record => JSON.stringify(record)).join('\n') + '\n');
1757
- fs.writeFileSync(path.join(staged.libDir, file), bytes);
1758
- const wrapper = { mapping: outlineMappingV2, file, sha256: sha(bytes), hostVersion: '2.1.312', run: 'run8',
1759
- baseline: '1bd0f805031c5577a6e7f72a9bc5b41618b71fc1' };
1760
- staged.writeExport(staged.validExport({ outlineDispatchCapture: wrapper }));
1761
- return { wrapper, filePath: path.join(staged.libDir, file), bytes };
1762
- }
1763
-
1764
- test('shipped run8 capture opens production qualification without DI', () => {
1765
- const qualification = internals.validateOutlineCaptureQualification({ hostId: 'claude-code' });
1766
- assert.strictEqual(qualification.open, true, JSON.stringify(qualification));
1767
- assert.strictEqual(qualification.source, 'validated-export');
1768
- assert.strictEqual(qualification.captureFile, 'doc-reconciliation-outline-capture.sanitized.jsonl');
1769
- });
1770
-
1771
- test('shipped run8 export resolves the real-hook integrated fixture without fake qualification', () => {
1772
- const originalFactory = provider.createClaudeOriginProvider;
1773
- let originInput;
1774
- provider.createClaudeOriginProvider = input => {
1775
- originInput = input;
1776
- return originalFactory(input);
1777
- };
1778
- const fixture = createOutlineFixture({ realHook: true, retainedInventory: true, noFakeQualification: true });
1779
- try {
1780
- const completed = fixture.finishDraft();
1781
- assert.strictEqual(completed.result.status, 'accepted', JSON.stringify(completed.result));
1782
- assert.strictEqual(Object.hasOwn(originInput, 'qualification'), false, 'production resolution must use the shipped export');
1783
- } finally {
1784
- provider.createClaudeOriginProvider = originalFactory;
1785
- fixture.cleanup();
1786
- }
1787
- });
1788
-
1789
- test('mapped row 17 dispatch accepts EVID-001 while the old VERI request and a substituted domain reject', () => {
1790
- const valid = createOutlineFixture({ retainedInventory: true, noFakeQualification: true });
1791
- try {
1792
- const completed = valid.finishDraft();
1793
- assert.strictEqual(completed.result.status, 'accepted', JSON.stringify(completed.result));
1794
- assert.strictEqual(completed.result.event.outlineEvidence.inventoryRowId, '17');
1795
- assert.strictEqual(completed.result.event.outlineEvidence.domain, 'EVID');
1796
- } finally { valid.cleanup(); }
1797
-
1798
- const unapprovedVeri = createOutlineFixture({ retainedInventory: true, rowId: '16',
1799
- target: 'docs/adr/VERI-001.md', domain: 'VERI' });
1800
- try {
1801
- assert.strictEqual(unapprovedVeri.capture.outlineDispatch.state, 'unresolved');
1802
- assert.ok(unapprovedVeri.capture.outlineDispatch.reasons.includes('outline-inventory-binding-mismatch'));
1803
- } finally { unapprovedVeri.cleanup(); }
1804
-
1805
- const unchangedRun8 = createOutlineFixture({ retainedInventory: true, rowId: '17',
1806
- target: 'docs/adr/EVID-001-verify-all-evidence.md', domain: 'EVID' });
1807
- try {
1808
- assert.strictEqual(unchangedRun8.capture.outlineDispatch.state, 'unresolved');
1809
- assert.ok(unchangedRun8.capture.outlineDispatch.reasons.includes('outline-domain-target-mismatch'),
1810
- 'the original descriptive filename still fails the citation-id/basename check');
1811
- } finally { unchangedRun8.cleanup(); }
1812
-
1813
- const substituted = createOutlineFixture({ retainedInventory: true,
1814
- handoffOverrides: { inventory: { ...internals.OUTLINE_INVENTORY_PIN, rowId: '17', domain: 'VERI',
1815
- targetPaths: ['docs/adr/EVID-001.md'] } } });
1816
- try {
1817
- assert.strictEqual(substituted.capture.outlineDispatch.state, 'unresolved');
1818
- assert.ok(substituted.capture.outlineDispatch.reasons.includes('outline-inventory-binding-mismatch'));
1819
- } finally { substituted.cleanup(); }
1820
- });
1821
-
1822
- test('separate outline export failures stay closed for digest, path, file, wrapper, mapping, and chain corruption', () => {
1823
- const staged = stageQualificationTree('source');
1824
- const validRecords = [qualificationDispatch(), qualificationStart(), qualificationResult(), qualificationStop()];
1825
- try {
1826
- const closed = (name, mutate, records = validRecords) => {
1827
- const { wrapper, filePath } = writeStagedOutlineEvidence(staged, records);
1828
- mutate(wrapper, filePath);
1829
- const outcome = stagedOutlineOutcome(staged);
1830
- assert.strictEqual(outcome.open, false, `${name}: ${JSON.stringify(outcome)}`);
1831
- };
1832
- closed('wrong digest', wrapper => {
1833
- wrapper.sha256 = '0'.repeat(64);
1834
- staged.writeExport(staged.validExport({ outlineDispatchCapture: wrapper }));
1835
- });
1836
- closed('unsafe filename', wrapper => {
1837
- wrapper.file = '../doc-reconciliation-outline-capture.sanitized.jsonl';
1838
- staged.writeExport(staged.validExport({ outlineDispatchCapture: wrapper }));
1839
- });
1840
- closed('missing file', (_wrapper, filePath) => fs.rmSync(filePath));
1841
- closed('malformed file', (wrapper, filePath) => {
1842
- const bytes = Buffer.from('{malformed json}\n');
1843
- fs.writeFileSync(filePath, bytes);
1844
- wrapper.sha256 = sha(bytes);
1845
- staged.writeExport(staged.validExport({ outlineDispatchCapture: wrapper }));
1846
- });
1847
- closed('malformed wrapper', () => staged.writeExport(staged.validExport({ outlineDispatchCapture: null })));
1848
- closed('mapping mismatch', wrapper => {
1849
- wrapper.mapping = { ...outlineMappingV2, workerRootField: 'cwd.unobserved' };
1850
- staged.writeExport(staged.validExport({ outlineDispatchCapture: wrapper }));
1851
- });
1852
- const crossSession = validRecords.map(record => ({ ...record }));
1853
- crossSession[2].session_id = 'other-coordinator';
1854
- closed('only dispatch chain crosses coordinator sessions', () => {}, crossSession);
1855
- const wrongRoot = validRecords.map(record => ({ ...record }));
1856
- wrongRoot[1].cwd = '/tmp/other-worker';
1857
- closed('only dispatch chain has a worker-root mismatch', () => {}, wrongRoot);
1858
- } finally { staged.cleanup(); }
1859
- });
1860
-
1861
- function outlineCorrelation(records, anchor = records.find(item => item.event === 'PreToolUse')) {
1862
- return internals.correlateOutlineDispatch(records, anchor, '/tmp/prb-worker');
1863
- }
1864
-
1865
- test('live qualification accepts the versioned Claude 2.1.312 dispatch/result/worker field contract', () => {
1866
- assert.strictEqual(typeof internals.outlineCaptureMappingValid, 'function', 'missing qualification correlation validator');
1867
- assert.deepStrictEqual(internals.OUTLINE_CAPTURE_MAPPING, outlineMappingV2, 'mapping field contract must be explicitly versioned');
1868
- const pre = qualificationDispatch();
1869
- const records = [pre, qualificationStart(), qualificationResult(), qualificationStop()];
1870
- assert.strictEqual(internals.outlineCaptureMappingValid(outlineMappingV2, records), true,
1871
- 'PreToolUse → completed tool_response.agentId → unique Start/Stop is the 2.1.312 host shape');
1872
- const crossSession = records.map(item => ({ ...item }));
1873
- crossSession[2].session_id = 'different-session';
1874
- assert.strictEqual(internals.outlineCaptureMappingValid(outlineMappingV2, crossSession), false,
1875
- 'matching tool IDs across different coordinator sessions do not qualify the live mapping');
1876
- const wrongRoot = records.map(item => ({ ...item }));
1877
- wrongRoot[1].cwd = '/tmp/other-worker';
1878
- assert.strictEqual(internals.outlineCaptureMappingValid(outlineMappingV2, wrongRoot), false);
1879
- });
1880
-
1881
- test('capture record retains only explicit outline result and dispatch fields', () => {
1882
- const pre = provider.buildCaptureRecord({ session_id: 'coordinator', tool_name: 'Task', tool_use_id: 'explicit',
1883
- tool_input: { prompt: dispatchLine, run_in_background: false } }, 'PreToolUse', '/tmp/prb-worker');
1884
- assert.strictEqual(pre.run_in_background, false);
1885
- assert.strictEqual(pre.isolationSet, false);
1886
- const omitted = provider.buildCaptureRecord({ session_id: 'coordinator', tool_name: 'Agent', tool_use_id: 'omitted',
1887
- tool_input: { prompt: dispatchLine } }, 'PreToolUse', '/tmp/prb-worker');
1888
- assert.strictEqual(Object.hasOwn(omitted, 'run_in_background'), false, 'missing background input stays absent');
1889
- const isolated = provider.buildCaptureRecord({ session_id: 'coordinator', tool_name: 'Agent', tool_use_id: 'isolated',
1890
- tool_input: { prompt: dispatchLine, run_in_background: false, isolation: null } }, 'PreToolUse', '/tmp/prb-worker');
1891
- assert.strictEqual(isolated.isolationSet, true, 'present null isolation is not normalized to absence');
1892
- const result = provider.buildCaptureRecord({ session_id: 'coordinator', tool_name: 'Task', tool_use_id: 'result',
1893
- tool_response: { agentId: 'worker', status: 'completed' } }, 'PostToolUse', '/tmp/prb-worker');
1894
- assert.strictEqual(result.tool_response_status, 'completed');
1895
- const noStatus = provider.buildCaptureRecord({ session_id: 'coordinator', tool_name: 'Task', tool_use_id: 'no-status',
1896
- tool_response: { agentId: 'worker' } }, 'PostToolUse', '/tmp/prb-worker');
1897
- assert.strictEqual(Object.hasOwn(noStatus, 'tool_response_status'), false, 'missing result status stays absent');
1898
- });
1899
-
1900
- test('unknown cwd stays unknown for PreToolUse writers without erasing PostToolUse verification context', () => {
1901
- const direct = provider.buildCaptureRecord({ session_id: 'coordinator', tool_name: 'Write', tool_use_id: 'missing-cwd-write',
1902
- tool_input: { file_path: 'docs/adr/DOCS-001.md', content: 'outline' } }, 'PreToolUse', ROOT);
1903
- assert.strictEqual(Object.hasOwn(direct, 'cwd'), false, 'a file writer cannot inherit a guessed cwd');
1904
- const add = provider.buildCaptureRecord({ session_id: 'coordinator', cwd: undefined, tool_name: 'Bash',
1905
- tool_input: { command: 'git add -- docs/adr/DOCS-001.md' } }, 'PreToolUse', ROOT);
1906
- assert.strictEqual(Object.hasOwn(add, 'cwd'), false, 'a Git-add writer cannot inherit a guessed cwd');
1907
- const verification = provider.buildCaptureRecord({ session_id: 'coordinator', tool_name: 'Bash',
1908
- tool_input: { command: `node ${path.join(ROOT, 'harness-everything/scripts/doc-check.js')}` },
1909
- tool_response: { exitCode: 0, stdout: '' } }, 'PostToolUse', ROOT);
1910
- assert.strictEqual(verification.cwd, ROOT, 'other PostToolUse shell evidence retains the established root fallback');
1911
- });
1912
-
1913
- for (const [name, make, reason] of [
1914
- ['concurrent same-session dispatches cannot reuse one worker result', () => {
1915
- const one = qualificationDispatch({ id: 'dispatch-1' });
1916
- const two = qualificationDispatch({ id: 'dispatch-2' });
1917
- return { records: [one, two, qualificationStart(), qualificationResult('dispatch-1'),
1918
- qualificationResult('dispatch-2'), qualificationStop()], anchor: one };
1919
- }, 'outline-worker-agent-id-replayed'],
1920
- ['a shared prompt_id cannot replace the target tool_use_id', () => {
1921
- const one = qualificationDispatch({ id: 'dispatch-1' });
1922
- const two = qualificationDispatch({ id: 'dispatch-2' });
1923
- return { records: [one, two, qualificationStart('worker-2'), qualificationResult('dispatch-2', 'worker-2'),
1924
- qualificationStop('worker-2')], anchor: one };
1925
- }, 'outline-worker-result-missing-or-ambiguous'],
1926
- ['reordered Stop-before-Start is unresolved', () => {
1927
- const pre = qualificationDispatch();
1928
- return { records: [pre, qualificationStop(), qualificationStart(), qualificationResult()], anchor: pre };
1929
- }, 'outline-worker-stop-before-start'],
1930
- ['Start-before-Pre is unresolved', () => {
1931
- const pre = qualificationDispatch();
1932
- return { records: [qualificationStart(), pre, qualificationResult(), qualificationStop()], anchor: pre };
1933
- }, 'outline-worker-start-before-dispatch'],
1934
- ['missing result is unresolved', () => {
1935
- const pre = qualificationDispatch();
1936
- return { records: [pre, qualificationStart(), qualificationStop()], anchor: pre };
1937
- }, 'outline-worker-result-missing-or-ambiguous'],
1938
- ['duplicate result is unresolved', () => {
1939
- const pre = qualificationDispatch();
1940
- return { records: [pre, qualificationStart(), qualificationResult(), qualificationResult(), qualificationStop()], anchor: pre };
1941
- }, 'outline-worker-result-missing-or-ambiguous'],
1942
- ['duplicate worker start is unresolved', () => {
1943
- const pre = qualificationDispatch();
1944
- return { records: [pre, qualificationStart(), qualificationStart(), qualificationResult(), qualificationStop()], anchor: pre };
1945
- }, 'outline-worker-start-missing-or-ambiguous'],
1946
- ['duplicate worker stop is unresolved', () => {
1947
- const pre = qualificationDispatch();
1948
- return { records: [pre, qualificationStart(), qualificationResult(), qualificationStop(), qualificationStop()], anchor: pre };
1949
- }, 'outline-worker-stop-missing-or-ambiguous'],
1950
- ['conflicting top-level and observed agentId is unresolved', () => {
1951
- const pre = qualificationDispatch();
1952
- return { records: [pre, qualificationStart(), qualificationResult('dispatch-1', 'worker', 'completed', { legacyAgentId: 'other-worker' }),
1953
- qualificationStop()], anchor: pre };
1954
- }, 'outline-worker-result-agent-id-conflict'],
1955
- ['async_launched is unresolved', () => {
1956
- const pre = qualificationDispatch();
1957
- return { records: [pre, qualificationStart(), qualificationResult('dispatch-1', 'worker', 'async_launched'), qualificationStop()], anchor: pre };
1958
- }, 'outline-worker-result-async'],
1959
- ['absent result status is unresolved', () => {
1960
- const pre = qualificationDispatch();
1961
- return { records: [pre, qualificationStart(), qualificationResult('dispatch-1', 'worker', null), qualificationStop()], anchor: pre };
1962
- }, 'outline-worker-result-status-missing'],
1963
- ['failed result status is unresolved', () => {
1964
- const pre = qualificationDispatch();
1965
- return { records: [pre, qualificationStart(), qualificationResult('dispatch-1', 'worker', 'failed'), qualificationStop()], anchor: pre };
1966
- }, 'outline-worker-result-failed'],
1967
- ['cancelled result status is unresolved', () => {
1968
- const pre = qualificationDispatch();
1969
- return { records: [pre, qualificationStart(), qualificationResult('dispatch-1', 'worker', 'cancelled'), qualificationStop()], anchor: pre };
1970
- }, 'outline-worker-result-failed'],
1971
- ['missing Stop is unresolved', () => {
1972
- const pre = qualificationDispatch();
1973
- return { records: [pre, qualificationStart(), qualificationResult()], anchor: pre };
1974
- }, 'outline-worker-stop-missing-or-ambiguous'],
1975
- ['worker-root mismatch is unresolved', () => {
1976
- const pre = qualificationDispatch();
1977
- return { records: [pre, qualificationStart('worker', { cwd: '/tmp/other-worker' }), qualificationResult(), qualificationStop()], anchor: pre };
1978
- }, 'outline-worker-root-mismatch'],
1979
- ['worktree isolation is unresolved', () => {
1980
- const pre = qualificationDispatch({ hasIsolation: true, isolation: 'worktree' });
1981
- return { records: [pre, qualificationStart(), qualificationResult(), qualificationStop()], anchor: pre };
1982
- }, 'outline-dispatch-isolation-unsupported'],
1983
- ['present null isolation is unresolved', () => {
1984
- const pre = qualificationDispatch({ hasIsolation: true, isolation: null });
1985
- return { records: [pre, qualificationStart(), qualificationResult(), qualificationStop()], anchor: pre };
1986
- }, 'outline-dispatch-isolation-unsupported'],
1987
- ['omitted run_in_background is unresolved', () => {
1988
- const pre = qualificationDispatch({ hasBackground: false });
1989
- return { records: [pre, qualificationStart(), qualificationResult(), qualificationStop()], anchor: pre };
1990
- }, 'outline-dispatch-background-unobserved'],
1991
- ['an Agent PostToolUseFailure invalidates a completed result', () => {
1992
- const pre = qualificationDispatch();
1993
- return { records: [pre, qualificationStart(), qualificationResult(),
1994
- { event: 'PostToolUseFailure', tool_name: 'Task', tool_use_id: 'dispatch-1', session_id: 'coordinator' }, qualificationStop()], anchor: pre };
1995
- }, 'outline-worker-result-failed'],
1996
- ]) {
1997
- test(`outline correlation rejects ${name}`, () => {
1998
- const { records, anchor } = make();
1999
- const result = outlineCorrelation(records, anchor);
2000
- assert.deepStrictEqual(result, { state: 'unresolved', reason });
2001
- });
2002
- }
2003
-
2004
- test('runtime resolution accepts Stop after the completed result through the synthetic qualification seam', () => {
2005
- const fixture = createOutlineFixture();
2006
- try {
2007
- const completed = fixture.finishDraft();
2008
- assert.strictEqual(completed.result.status, 'accepted', JSON.stringify(completed.result));
2009
- const workerResultIndex = completed.captures.findIndex(item => item.event === 'PostToolUse'
2010
- && item.tool_use_id === fixture.capture.tool_use_id);
2011
- const workerStopIndex = completed.captures.findIndex(item => item.event === 'SubagentStop'
2012
- && item.agent_id === 'draft-worker');
2013
- assert.ok(workerResultIndex >= 0 && workerStopIndex > workerResultIndex,
2014
- 'the 2.1.312 field shape allows result before Stop; no Stop-before-result condition is implied');
2015
- } finally { fixture.cleanup(); }
2016
- });
2017
-
2018
- test('missing outline wrapper keeps outline-live-gate-unmet', () => {
2019
- const staged = stageQualificationTree('source');
2020
- try {
2021
- staged.writeExport(staged.validExport());
2022
- const qualification = stagedOutlineOutcome(staged);
2023
- assert.strictEqual(qualification.open, false, JSON.stringify(qualification));
2024
- } finally { staged.cleanup(); }
2025
- });
2026
-
2027
- test('original B and immutable attempt chain survive reconfirmation; stale attempts/tokens never cover new scope', () => {
2028
- assert.strictEqual(typeof internals.resolveOutlineAttempt, 'function', 'missing immutable attempt-chain resolver');
2029
- const fixture = createOutlineFixture();
2030
- try {
2031
- const resolved = internals.resolveOutlineAttempt({ sessionDir: fixture.sessionDir, taskId: fixture.taskId, attemptId: fixture.attemptId });
2032
- assert.strictEqual(resolved.state, 'accepted');
2033
- const originalBaseline = fixture.baselineCommit;
2034
- const secondId = 'attempt-2';
2035
- const secondDir = path.join(fixture.sessionDir, 'doc-reconciliation/outline-confirmation', fixture.taskId, 'attempts', secondId);
2036
- fs.mkdirSync(secondDir, { recursive: true });
2037
- const lease2 = { schema: 'harness.outline-writer-lease.v1', id: 'lease-2', taskId: fixture.taskId,
2038
- attemptId: secondId, principalId: fixture.sessionId, root: fixture.root, exclusive: true, active: true };
2039
- writeJson(path.join(secondDir, 'writer-lease.json'), lease2);
2040
- const second = { ...fixture.handoff, attemptId: secondId, handoffId: 'handoff-2', supersedesAttemptId: fixture.attemptId,
2041
- draftDispatchToken: 'token-2', writerLeaseId: lease2.id,
2042
- writerLeaseDigest: sha(fs.readFileSync(path.join(secondDir, 'writer-lease.json'))) };
2043
- writeJson(path.join(secondDir, 'handoff.json'), second);
2044
- const secondResolved = internals.resolveOutlineAttempt({ sessionDir: fixture.sessionDir, taskId: fixture.taskId, attemptId: secondId });
2045
- assert.strictEqual(secondResolved.state, 'accepted', 'current attempt links to one retained predecessor');
2046
- assert.strictEqual(secondResolved.handoff.baseline.commit, originalBaseline, 'B never moves to O');
2047
- assert.notStrictEqual(internals.resolveOutlineAttempt({ sessionDir: fixture.sessionDir, taskId: fixture.taskId, attemptId: fixture.attemptId }).state,
2048
- 'accepted', 'superseded dispatch cannot cover the new scope');
2049
- const reusedToken = { ...second, draftDispatchToken: fixture.handoff.draftDispatchToken };
2050
- writeJson(path.join(secondDir, 'handoff.json'), reusedToken);
2051
- assert.strictEqual(internals.resolveOutlineAttempt({ sessionDir: fixture.sessionDir, taskId: fixture.taskId, attemptId: secondId }).state,
2052
- 'unresolved', 'a token consumed by a predecessor cannot be reused by a retry');
2053
- const movedB = { ...second, baseline: { ...second.baseline, commit: fixture.outlineCommit } };
2054
- writeJson(path.join(secondDir, 'handoff.json'), movedB);
2055
- assert.strictEqual(internals.resolveOutlineAttempt({ sessionDir: fixture.sessionDir, taskId: fixture.taskId, attemptId: secondId }).state,
2056
- 'unresolved', 'the task baseline cannot move from B to O');
2057
- const changedScope = { ...second, targetPaths: ['docs/adr/DOCS-002.md'],
2058
- inventory: { ...second.inventory, targetPaths: ['docs/adr/DOCS-002.md'] } };
2059
- writeJson(path.join(secondDir, 'handoff.json'), changedScope);
2060
- const changedPrompt = `HARNESS_OUTLINE_DISPATCH_V1 taskId=${fixture.taskId} attemptId=${secondId} token=token-2 workerRoot=${fixture.root}`;
2061
- const changedPayload = { ...fixture.payload, tool_use_id: 'dispatch-scope-change', tool_input: { prompt: changedPrompt } };
2062
- const changedCapture = provider.buildCaptureRecord(changedPayload, 'PreToolUse', fixture.root);
2063
- changedCapture.observedIdentity = fixture.capture.observedIdentity;
2064
- assert.strictEqual(internals.captureOutlineDispatch({ payload: changedPayload, capture: changedCapture,
2065
- sessionDir: fixture.sessionDir, workspaceRoot: fixture.root, captures: fixture.reviewCaptures,
2066
- fixtureExpectedPin: fixture.expectedPin }).state, 'unresolved',
2067
- 'changed attempt scope cannot reuse an old O review/handoff');
2068
- second.supersedesAttemptId = 'missing-predecessor';
2069
- writeJson(path.join(secondDir, 'handoff.json'), second);
2070
- assert.strictEqual(internals.resolveOutlineAttempt({ sessionDir: fixture.sessionDir, taskId: fixture.taskId, attemptId: secondId }).state,
2071
- 'unresolved', 'broken attempt chains stay unresolved');
2072
- } finally { fixture.cleanup(); }
2073
- });
2074
-
2075
- test('squash correspondence retains only identical O/D target blobs and requires available Git objects', () => {
2076
- assert.strictEqual(typeof internals.verifyOutlineMergeCorrespondence, 'function', 'missing squash correspondence validator');
2077
- const fixture = createOutlineFixture();
2078
- try {
2079
- const completed = fixture.finishDraft();
2080
- const draftBlob = fixtureGit(fixture.root, ['rev-parse', `${completed.draftCommit}:${fixture.target}`]);
2081
- fs.writeFileSync(path.join(fixture.root, 'merge-marker.txt'), 'squash metadata');
2082
- fixtureGit(fixture.root, ['add', '-A']);
2083
- fixtureGit(fixture.root, ['commit', '-q', '-m', 'identical squash target']);
2084
- const mergedCommit = fixtureGit(fixture.root, ['rev-parse', 'HEAD']);
2085
- const identical = internals.verifyOutlineMergeCorrespondence({
2086
- root: fixture.root, outlineCommit: fixture.outlineCommit, draftCommit: completed.draftCommit,
2087
- mergedCommit, targetPaths: [fixture.target], record: { outlineCommit: fixture.outlineCommit,
2088
- draftCommit: completed.draftCommit, mergedCommit, targetBlobs: { [fixture.target]: { draft: draftBlob, merged: draftBlob } } },
2089
- });
2090
- assert.strictEqual(identical.state, 'accepted');
2091
- fs.writeFileSync(path.join(fixture.root, fixture.target), 'changed during merge');
2092
- fixtureGit(fixture.root, ['add', '-A']);
2093
- fixtureGit(fixture.root, ['commit', '-q', '-m', 'changed squash target']);
2094
- const changedMerge = fixtureGit(fixture.root, ['rev-parse', 'HEAD']);
2095
- const changedBlob = fixtureGit(fixture.root, ['rev-parse', `${changedMerge}:${fixture.target}`]);
2096
- const changed = internals.verifyOutlineMergeCorrespondence({
2097
- root: fixture.root, outlineCommit: fixture.outlineCommit, draftCommit: completed.draftCommit,
2098
- mergedCommit: changedMerge, targetPaths: [fixture.target], record: { outlineCommit: fixture.outlineCommit,
2099
- draftCommit: completed.draftCommit, mergedCommit: changedMerge,
2100
- targetBlobs: { [fixture.target]: { draft: draftBlob, merged: changedBlob } } },
2101
- });
2102
- assert.strictEqual(changed.state, 'changed', 'changed final bytes do not inherit the old final review');
2103
- const missing = internals.verifyOutlineMergeCorrespondence({ root: fixture.root,
2104
- outlineCommit: fixture.outlineCommit, draftCommit: completed.draftCommit, mergedCommit,
2105
- targetPaths: [fixture.target], record: null });
2106
- assert.strictEqual(missing.state, 'unresolved');
2107
- } finally { fixture.cleanup(); }
2108
- });
2109
-
2110
- test('overwriting a dispatched predecessor handoff invalidates the retained attempt chain', () => {
2111
- assert.strictEqual(typeof internals.resolveOutlineAttempt, 'function');
2112
- const fixture = createOutlineFixture();
2113
- try {
2114
- const secondId = 'attempt-2';
2115
- const secondDir = path.join(fixture.sessionDir, 'doc-reconciliation/outline-confirmation', fixture.taskId, 'attempts', secondId);
2116
- fs.mkdirSync(secondDir, { recursive: true });
2117
- const lease = { schema: 'harness.outline-writer-lease.v1', id: 'lease-2', taskId: fixture.taskId,
2118
- attemptId: secondId, principalId: fixture.sessionId, root: fixture.root, exclusive: true, active: true };
2119
- writeJson(path.join(secondDir, 'writer-lease.json'), lease);
2120
- const second = { ...fixture.handoff, attemptId: secondId, handoffId: 'handoff-2',
2121
- supersedesAttemptId: fixture.attemptId, draftDispatchToken: 'token-2', writerLeaseId: lease.id,
2122
- writerLeaseDigest: sha(fs.readFileSync(path.join(secondDir, 'writer-lease.json'))) };
2123
- writeJson(path.join(secondDir, 'handoff.json'), second);
2124
- assert.strictEqual(internals.resolveOutlineAttempt({ sessionDir: fixture.sessionDir,
2125
- taskId: fixture.taskId, attemptId: secondId }).state, 'accepted');
2126
- const predecessorFile = path.join(fixture.attemptDir, 'handoff.json');
2127
- fs.rmSync(path.join(fixture.attemptDir, 'tokens'), { recursive: true, force: true });
2128
- fs.rmSync(path.join(fixture.attemptDir, 'seams'), { recursive: true, force: true });
2129
- const overwritten = JSON.parse(fs.readFileSync(predecessorFile, 'utf8'));
2130
- overwritten.handoffId = 'hand-off-overwritten-after-dispatch';
2131
- writeJson(predecessorFile, overwritten);
2132
- assert.strictEqual(internals.resolveOutlineAttempt({ sessionDir: fixture.sessionDir,
2133
- taskId: fixture.taskId, attemptId: secondId }).state, 'unresolved',
2134
- 'the retained handoff seal still detects overwrites after token/seam files are removed');
2135
- } finally { fixture.cleanup(); }
2136
- });
2137
-
2138
- test('W6 whole row-17 path accepts captured state operations through source and packaged producers', () => {
2139
- const completionOrders = [
2140
- { runtimeLayout: 'source', workerCompletionOrder: 'result-stop', finalReviewCompletionOrder: 'result-stop' },
2141
- { runtimeLayout: 'packaged', workerCompletionOrder: 'stop-result', finalReviewCompletionOrder: 'stop-result' },
2142
- ];
2143
- for (const { runtimeLayout, workerCompletionOrder, finalReviewCompletionOrder } of completionOrders) {
2144
- const fixture = createOutlineFixture({ realHook: true, retainedInventory: true, workflowCli: true, w6Producer: true,
2145
- runtimeLayout, sessionId: `w6-${runtimeLayout}`, preOutlineOperation: 'write', capturedOutlineCommit: true });
2146
- try {
2147
- assert.strictEqual(fixture.inventoryOperation?.operation, 'inventory', `${runtimeLayout}: actual inventory producer ran at B`);
2148
- const completed = fixture.finishDraft({ finalReview: true, completeWorkflow: true, runPilot: true,
2149
- workerCompletionOrder, finalReviewCompletionOrder });
2150
- assert.strictEqual(completed.result.status, 'accepted',
2151
- `${runtimeLayout}: captured row-17 state writers retain outline credit: ${JSON.stringify(completed.result.diagnostics)}`);
2152
- assert.strictEqual(completed.pilot?.report?.pilotCredit, true,
2153
- `${runtimeLayout}: post-operation pilot assessment is complete: ${JSON.stringify({
2154
- status: completed.pilot?.report?.pilotStatus, credit: completed.pilot?.report?.pilotCredit,
2155
- unsatisfied: completed.pilot?.report?.unsatisfied, diagnostics: completed.pilot?.report?.diagnostics,
2156
- outlineEvidence: completed.pilot?.report?.outlineEvidence,
2157
- workflow: JSON.parse(fs.readFileSync(path.join(fixture.sessionDir, 'workflow-run.json'), 'utf8')).state,
2158
- requirements: JSON.parse(fs.readFileSync(path.join(fixture.sessionDir, 'workflow-obligations.json'), 'utf8')).requirements.map(row => [row.id, row.status]),
2159
- })}`);
2160
- assert.strictEqual(completed.pilot?.report?.outlineEvidence?.outcome, 'pass');
2161
- assert.notStrictEqual(completed.draftCommit, fixture.outlineCommit, 'D is a strict descendant of O');
2162
- assert.deepStrictEqual(fixtureGit(fixture.root, ['diff-tree', '--no-commit-id', '--name-only', '-r', completed.draftCommit])
2163
- .split('\n').filter(Boolean).sort(), [fixture.target, 'docs/governed-index.md'].sort(),
2164
- 'the correlated worker commits the ADR and generated index together');
2165
- const captures = provider.readCaptureView(fixture.sessionDir).records;
2166
- const stateCommands = captures.filter(item => item.event === 'PreToolUse' && item.stateOperation?.schema === 'harness.w6-state-operation.v1');
2167
- assert.deepStrictEqual(stateCommands.map(item => item.stateOperation.operation),
2168
- ['plan', 'start', 'inventory', 'seal', 'step-adr', 'binding-verify', 'step-verify'],
2169
- `${runtimeLayout}: retained journal keeps every bounded operation in phase order`);
2170
- const decision = provider._internals.evaluateW6StateOperations(captures, fixture.sessionDir);
2171
- assert.strictEqual(decision.complete, true, `${runtimeLayout}: shared validator accepts the complete operation sequence`);
2172
- assert.ok(decision.results.length > 0 && decision.results.every(item => item.accepted),
2173
- `${runtimeLayout}: every captured writer disposition is accepted`);
2174
- const finalReviewStop = captures.find(item => item.event === 'SubagentStop' && item.agent_id === 'final-reviewer');
2175
- assert.ok(finalReviewStop, `${runtimeLayout}: final reviewer Stop was captured`);
2176
- assert.strictEqual(completed.origin.resolveEvent({ reference: `${finalReviewStop.ref}#quality-review`, identity: completed.identity }).status,
2177
- 'accepted', `${runtimeLayout}: final quality review remains independently accepted`);
2178
- const verifyState = fixture.workflowOperationWitnesses.find(item => item.name === 'step-verify');
2179
- assert.ok(verifyState?.before && verifyState?.after, `${runtimeLayout}: verify disposition has host state before and after`);
2180
- for (const field of ['lastEditAt', 'lastVerifyAt', 'lastGenericVerifyAt', 'lastDocVerifyAt']) {
2181
- assert.strictEqual(verifyState.before[field], verifyState.after[field], `${runtimeLayout}: state-only verification disposition preserves ${field}`);
2182
- }
2183
- const stop = spawnSync(process.execPath, [path.join(runtimeLayout === 'source' ? ROOT : path.join(ROOT, 'plugins/harness-everything'),
2184
- 'hooks/scripts/workflow-stop-gate.js')], { cwd: fixture.root, encoding: 'utf8',
2185
- input: JSON.stringify({ session_id: fixture.sessionId, cwd: fixture.root, hook_event_name: 'Stop' }),
2186
- env: { ...process.env, HARNESS_STATE_HOME: fixture.stateHome, HARNESS_WORKSPACE_ROOT: fixture.root,
2187
- HARNESS_DOC_RECONCILIATION_PILOT: '1' } });
2188
- assert.strictEqual(stop.status, 0, `${runtimeLayout}: normal Stop stays fail-open: ${stop.stderr}`);
2189
- const workflow = JSON.parse(fs.readFileSync(path.join(fixture.sessionDir, 'workflow-run.json'), 'utf8'));
2190
- const report = JSON.parse(fs.readFileSync(path.join(fixture.sessionDir, 'doc-reconciliation-pilot.json'), 'utf8'));
2191
- assert.strictEqual(workflow.state, 'satisfied', `${runtimeLayout}: real Stop reconciliation resolves the workflow; unresolved=${JSON.stringify(workflow.unresolved)}; stop=${stop.stderr}; pilot=${JSON.stringify({
2192
- status: report.pilotStatus, credit: report.pilotCredit, unsatisfied: report.unsatisfied, diagnostics: report.diagnostics,
2193
- })}; editVerify=${JSON.stringify(fixture.workflowOperationWitnesses.map(item => ({ name: item.name,
2194
- before: [item.before?.lastEditAt, item.before?.lastVerifyAt], after: [item.after?.lastEditAt, item.after?.lastVerifyAt] })))}; final=${JSON.stringify(JSON.parse(fs.readFileSync(path.join(fixture.sessionDir, 'handoff-state.json'), 'utf8')))} `);
2195
- assert.strictEqual(report.pilotCredit, true, `${runtimeLayout}: completed host operation results earn final pilot credit`);
2196
- } finally { fixture.cleanup(); }
2197
- }
2198
- });
2199
-
2200
- test('W6 rejects final-review launch before both correlated worker completion surfaces', () => {
2201
- for (const scenario of [
2202
- { name: 'worker result', options: { workerResultAfterFinalReview: true } },
2203
- { name: 'worker Stop', options: { workerStopAfterFinalReview: true } },
2204
- ]) {
2205
- const fixture = createOutlineFixture({ realHook: true, retainedInventory: true, workflowCli: true, w6Producer: true,
2206
- runtimeLayout: 'source', sessionId: `w6-late-${scenario.name.replace(' ', '-')}`, preOutlineOperation: 'write', capturedOutlineCommit: true });
2207
- try {
2208
- const completed = fixture.finishDraft({ finalReview: true, completeWorkflow: true, ...scenario.options,
2209
- finalReviewCompletionOrder: 'stop-result', allowDispositionFailure: true, runPilot: true });
2210
- assert.notStrictEqual(completed.result.status, 'accepted',
2211
- `late ${scenario.name} cannot authorize W6 outline credit: ${JSON.stringify(completed.result)}`);
2212
- assert.notStrictEqual(completed.pilot?.report?.outlineEvidence?.outcome, 'pass',
2213
- `the final consumer withholds outline credit after the late ${scenario.name}`);
2214
- const captures = fixture.runtimeProvider.readCaptureView(fixture.sessionDir).records;
2215
- const decision = fixture.runtimeProvider._internals.evaluateW6StateOperations(captures, fixture.sessionDir);
2216
- assert.strictEqual(decision.complete, false, `late ${scenario.name} cannot complete the W6 writer disposition`);
2217
- const finalReviewStop = captures.find(item => item.event === 'SubagentStop' && item.agent_id === 'final-reviewer');
2218
- const finalReview = completed.origin.resolveEvent({ reference: `${finalReviewStop.ref}#quality-review`, identity: completed.identity });
2219
- assert.notStrictEqual(finalReview.status, 'accepted', 'task-scoped final quality review is not eligible');
2220
- assert.strictEqual(completed.pilot?.report?.pilotCredit, false, 'pilot credit stays withheld');
2221
- } finally { fixture.cleanup(); }
2222
- }
2223
- });
2224
-
2225
- test('outline-backed no-W6 task rejects final quality review launched before worker result', () => {
2226
- const fixture = createOutlineFixture({ realHook: true, runtimeLayout: 'source', sessionId: 'no-w6-late-worker-result' });
2227
- try {
2228
- const completed = fixture.finishDraft({ finalReview: true, workerResultAfterFinalReview: true,
2229
- finalReviewCompletionOrder: 'stop-result', runPilot: true });
2230
- const finalReviewStop = completed.captures.find(item => item.event === 'SubagentStop' && item.agent_id === 'final-reviewer');
2231
- const finalReview = completed.origin.resolveEvent({ reference: `${finalReviewStop.ref}#quality-review`, identity: completed.identity });
2232
- assert.notStrictEqual(finalReview.status, 'accepted',
2233
- `the outline-backed sibling lane must share worker closure eligibility: ${JSON.stringify(finalReview)}`);
2234
- assert.strictEqual(completed.pilot?.report?.outlineEvidence?.outcome, 'pass',
2235
- 'the earlier O review remains a separate accepted outline result');
2236
- assert.ok(!completed.pilot?.report?.acceptedRefs?.some(ref => ref === `${finalReviewStop.ref}#quality-review`),
2237
- 'the early final review is absent from accepted pilot evidence');
2238
- assert.strictEqual(completed.pilot?.report?.pilotCredit, false,
2239
- 'the sibling lane cannot use an early final review for pilot credit');
2240
- } finally { fixture.cleanup(); }
2241
- });
2242
-
2243
- test('outline-backed no-W6 positive final review accepts both callback orders through source and package', () => {
2244
- const completionOrders = [
2245
- { runtimeLayout: 'source', workerCompletionOrder: 'result-stop', finalReviewCompletionOrder: 'stop-result' },
2246
- { runtimeLayout: 'packaged', workerCompletionOrder: 'stop-result', finalReviewCompletionOrder: 'result-stop' },
2247
- ];
2248
- for (const { runtimeLayout, workerCompletionOrder, finalReviewCompletionOrder } of completionOrders) {
2249
- const fixture = createOutlineFixture({ realHook: true, runtimeLayout, sessionId: `no-w6-${runtimeLayout}` });
2250
- try {
2251
- const completed = fixture.finishDraft({ finalReview: true, workerCompletionOrder, finalReviewCompletionOrder, runPilot: true });
2252
- const finalReviewStop = completed.captures.find(item => item.event === 'SubagentStop' && item.agent_id === 'final-reviewer');
2253
- const finalReview = completed.origin.resolveEvent({ reference: `${finalReviewStop.ref}#quality-review`, identity: completed.identity });
2254
- assert.strictEqual(finalReview.status, 'accepted', `${runtimeLayout}: completed task-scoped final review is eligible`);
2255
- assert.strictEqual(completed.pilot?.report?.outlineEvidence?.outcome, 'pass', `${runtimeLayout}: O review remains accepted`);
2256
- assert.ok(completed.pilot?.report?.acceptedRefs?.includes(`${finalReviewStop.ref}#quality-review`),
2257
- `${runtimeLayout}: the final review reaches the no-W6 pilot seam`);
2258
- assert.strictEqual(completed.pilot?.report?.pilotCredit, false,
2259
- `${runtimeLayout}: unrelated outstanding MUSTs still withhold full pilot credit`);
2260
- } finally { fixture.cleanup(); }
2261
- }
2262
- });
2263
-
2264
- test('matching final-review failures veto W6 eligibility and disposition in either callback order', () => {
2265
- const observations = [];
2266
- for (const { order, runtimeLayout } of [
2267
- { order: 'before-success', runtimeLayout: 'source' },
2268
- { order: 'after-success', runtimeLayout: 'packaged' },
2269
- ]) {
2270
- const fixture = createOutlineFixture({ realHook: true, retainedInventory: true, workflowCli: true, w6Producer: true,
2271
- runtimeLayout, sessionId: `w6-failure-${order}`, preOutlineOperation: 'write', capturedOutlineCommit: true });
2272
- try {
2273
- const completed = fixture.finishDraft({ finalReview: true, completeWorkflow: true, runPilot: true,
2274
- allowDispositionFailure: true, finalReviewFailure: { order }, finalReviewCompletionOrder: 'result-stop' });
2275
- const finalReviewStop = completed.captures.find(item => item.event === 'SubagentStop' && item.agent_id === 'final-reviewer');
2276
- const finalReview = completed.origin.resolveEvent({ reference: `${finalReviewStop.ref}#quality-review`, identity: completed.identity });
2277
- const failure = completed.captures.find(item => item.event === 'PostToolUseFailure'
2278
- && item.session_id === fixture.sessionId && item.tool_use_id === 'final-review-dispatch');
2279
- assert.ok(failure, `${runtimeLayout}/${order}: failure was captured through state-persist`);
2280
- assert.strictEqual(failure.agent_id, undefined, `${runtimeLayout}/${order}: failure-side agent_id is absent`);
2281
- observations.push({ runtimeLayout, order, finalReviewStatus: finalReview.status,
2282
- outlineOutcome: completed.pilot?.report?.outlineEvidence?.outcome, pilotCredit: completed.pilot?.report?.pilotCredit });
2283
- } finally { fixture.cleanup(); }
2284
- }
2285
- assert.ok(observations.every(item => item.finalReviewStatus !== 'accepted'
2286
- && item.outlineOutcome !== 'pass' && item.pilotCredit === false),
2287
- `matching failure before/after success must veto final-review eligibility, outline outcome and pilot credit: ${JSON.stringify(observations)}`);
2288
- });
2289
-
2290
- test('matching final-review failures veto the no-W6 final review in either callback order', () => {
2291
- const observations = [];
2292
- for (const { order, runtimeLayout } of [
2293
- { order: 'before-success', runtimeLayout: 'packaged' },
2294
- { order: 'after-success', runtimeLayout: 'source' },
2295
- ]) {
2296
- const fixture = createOutlineFixture({ realHook: true, runtimeLayout, sessionId: `no-w6-failure-${order}` });
2297
- try {
2298
- const completed = fixture.finishDraft({ finalReview: true, runPilot: true,
2299
- finalReviewFailure: { order }, finalReviewCompletionOrder: 'stop-result' });
2300
- const finalReviewStop = completed.captures.find(item => item.event === 'SubagentStop' && item.agent_id === 'final-reviewer');
2301
- const finalReview = completed.origin.resolveEvent({ reference: `${finalReviewStop.ref}#quality-review`, identity: completed.identity });
2302
- const failure = completed.captures.find(item => item.event === 'PostToolUseFailure'
2303
- && item.session_id === fixture.sessionId && item.tool_use_id === 'final-review-dispatch');
2304
- assert.ok(failure, `${runtimeLayout}/${order}: failure was captured through state-persist`);
2305
- assert.strictEqual(failure.agent_id, undefined, `${runtimeLayout}/${order}: failure-side agent_id is absent`);
2306
- observations.push({ runtimeLayout, order, finalReviewStatus: finalReview.status,
2307
- outlineOutcome: completed.pilot?.report?.outlineEvidence?.outcome, pilotCredit: completed.pilot?.report?.pilotCredit });
2308
- } finally { fixture.cleanup(); }
2309
- }
2310
- assert.ok(observations.every(item => item.finalReviewStatus !== 'accepted'
2311
- && item.outlineOutcome === 'pass' && item.pilotCredit === false),
2312
- `matching failure before/after success must veto final review while retaining the separate O outcome: ${JSON.stringify(observations)}`);
2313
- });
2314
-
2315
- test('unmatched final-review failures do not poison a valid W6 launch', () => {
2316
- for (const scenario of [
2317
- { name: 'other session', runtimeLayout: 'source', failure: { sessionId: 'unrelated-review-session' } },
2318
- { name: 'other tool-use ID', runtimeLayout: 'packaged', failure: { toolUseId: 'unrelated-review-tool' } },
2319
- ]) {
2320
- const fixture = createOutlineFixture({ realHook: true, retainedInventory: true, workflowCli: true, w6Producer: true,
2321
- runtimeLayout: scenario.runtimeLayout, sessionId: `w6-unmatched-${scenario.name.replaceAll(' ', '-')}`,
2322
- preOutlineOperation: 'write', capturedOutlineCommit: true });
2323
- try {
2324
- const completed = fixture.finishDraft({ finalReview: true, completeWorkflow: true, runPilot: true,
2325
- finalReviewFailure: { order: 'after-success', ...scenario.failure } });
2326
- const finalReviewStop = completed.captures.find(item => item.event === 'SubagentStop' && item.agent_id === 'final-reviewer');
2327
- const finalReview = completed.origin.resolveEvent({ reference: `${finalReviewStop.ref}#quality-review`, identity: completed.identity });
2328
- const failure = fixture.capturedRecordsAcrossSessions().find(item => item.event === 'PostToolUseFailure'
2329
- && item.session_id === (scenario.failure.sessionId || fixture.sessionId)
2330
- && item.tool_use_id === (scenario.failure.toolUseId || 'final-review-dispatch'));
2331
- assert.ok(failure, `${scenario.name}: unmatched failure was captured through state-persist`);
2332
- assert.strictEqual(failure.agent_id, undefined, `${scenario.name}: failure-side agent_id is absent`);
2333
- assert.strictEqual(finalReview.status, 'accepted', `${scenario.name}: valid final review remains eligible`);
2334
- assert.strictEqual(completed.result.status, 'accepted', `${scenario.name}: outline result remains accepted`);
2335
- assert.strictEqual(completed.pilot?.report?.outlineEvidence?.outcome, 'pass', `${scenario.name}: outline outcome remains pass`);
2336
- assert.strictEqual(completed.pilot?.report?.pilotCredit, true, `${scenario.name}: valid launch retains pilot credit`);
2337
- } finally { fixture.cleanup(); }
2338
- }
2339
- });
2340
-
2341
- test('outline-backed no-W6 final review rejects a worker Stop that arrives after launch', () => {
2342
- const fixture = createOutlineFixture({ realHook: true, runtimeLayout: 'source', sessionId: 'no-w6-late-worker-stop' });
2343
- try {
2344
- const completed = fixture.finishDraft({ finalReview: true, workerStopAfterFinalReview: true,
2345
- finalReviewCompletionOrder: 'stop-result', runPilot: true });
2346
- const finalReviewStop = completed.captures.find(item => item.event === 'SubagentStop' && item.agent_id === 'final-reviewer');
2347
- const finalReview = completed.origin.resolveEvent({ reference: `${finalReviewStop.ref}#quality-review`, identity: completed.identity });
2348
- assert.notStrictEqual(finalReview.status, 'accepted', 'a late worker Stop cannot retroactively authorize the launch');
2349
- assert.ok(!completed.pilot?.report?.acceptedRefs?.includes(`${finalReviewStop.ref}#quality-review`));
2350
- assert.strictEqual(completed.pilot?.report?.pilotCredit, false);
2351
- } finally { fixture.cleanup(); }
2352
- });
2353
-
2354
- test('W6 requires a captured final-review launch to follow worker closure even when its Start is later', () => {
2355
- const fixture = createOutlineFixture({ realHook: true, retainedInventory: true, workflowCli: true, w6Producer: true,
2356
- runtimeLayout: 'source', sessionId: 'w6-early-review-pre', preOutlineOperation: 'write', capturedOutlineCommit: true });
2357
- try {
2358
- const completed = fixture.finishDraft({ finalReview: true, completeWorkflow: true,
2359
- reviewLaunchBeforeWorkerClosure: true, allowDispositionFailure: true, runPilot: true });
2360
- assert.notStrictEqual(completed.result.status, 'accepted',
2361
- 'a late SubagentStart cannot hide a final-review PreToolUse captured before worker closure');
2362
- assert.notStrictEqual(completed.pilot?.report?.outlineEvidence?.outcome, 'pass');
2363
- assert.strictEqual(completed.pilot?.report?.pilotCredit, false);
2364
- } finally { fixture.cleanup(); }
2365
- });
2366
-
2367
- test('W6 state operation identity, phase, schema, and destination drift withhold pilot credit', () => {
2368
- const fixture = createOutlineFixture({ realHook: true, retainedInventory: true, workflowCli: true, w6Producer: true,
2369
- runtimeLayout: 'source', sessionId: 'w6-negative-identity', preOutlineOperation: 'write', capturedOutlineCommit: true });
2370
- const previousSwitch = process.env.HARNESS_DOC_RECONCILIATION_PILOT;
2371
- const originalFactory = fixture.runtimeProvider.createClaudeOriginProvider;
2372
- try {
2373
- const completed = fixture.finishDraft({ finalReview: true, completeWorkflow: true, runPilot: true });
2374
- assert.strictEqual(completed.pilot && completed.pilot.report.pilotCredit, true, 'positive control: exact captured operation fields credit');
2375
- fixture.runtimeProvider.createClaudeOriginProvider = input => originalFactory({ ...input,
2376
- qualification: { source: 'fake-test-fixture', faked: true, toolUseIdPopulated: true,
2377
- agentIdPopulated: true, outlineDispatchCaptureVerified: true }, outlineFixture: { expectedPin: fixture.expectedPin },
2378
- taskBinding: fixture.taskBinding });
2379
- process.env.HARNESS_DOC_RECONCILIATION_PILOT = '1';
2380
- const view = fixture.runtimeProvider.readCaptureView(fixture.sessionDir);
2381
- const inventoryPre = view.records.find(item => item.event === 'PreToolUse' && item.stateOperation && item.stateOperation.operation === 'inventory');
2382
- assert.ok(inventoryPre, 'real inventory PreToolUse capture exists');
2383
- const eventDir = path.join(fixture.sessionDir, 'doc-reconciliation-capture');
2384
- const eventFile = fs.readdirSync(eventDir).map(name => path.join(eventDir, name))
2385
- .find(file => JSON.parse(fs.readFileSync(file, 'utf8')).ref === inventoryPre.ref);
2386
- assert.ok(eventFile, 'inventory PreToolUse has an immutable event file');
2387
- const original = fs.readFileSync(eventFile);
2388
- const context = { root: fixture.root, sessionId: fixture.sessionId, sessionDir: fixture.sessionDir, activeHost: 'claude-code',
2389
- workflow: JSON.parse(fs.readFileSync(path.join(fixture.sessionDir, 'workflow-run.json'), 'utf8')) };
2390
- const set = JSON.parse(fs.readFileSync(path.join(fixture.sessionDir, 'workflow-obligations.json'), 'utf8'));
2391
- for (const [field, value] of [
2392
- ['principalId', 'draft-worker'],
2393
- ['sessionId', 'other-session'],
2394
- ['workflowId', 'other-workflow'],
2395
- ['phase', 'post-final-review'],
2396
- ['destinations', ['workflow-run.json']],
2397
- ['schema', 'harness.unrecognized-state-operation.v1'],
2398
- ]) {
2399
- const changed = JSON.parse(original.toString('utf8'));
2400
- changed.stateOperation[field] = value;
2401
- writeJson(eventFile, changed);
2402
- fixture.runtimeProvider.rebuildJournalView(fixture.sessionDir);
2403
- const assessment = fixture.runtimePilot.assess(context, set);
2404
- assert.strictEqual(assessment.withhold, true, 'changed ' + field + ' cannot authorize the captured operation');
2405
- assert.strictEqual(assessment.report.pilotCredit, false, 'changed ' + field + ' withholds pilot credit');
2406
- assert.notStrictEqual(assessment.report.outlineEvidence && assessment.report.outlineEvidence.outcome, 'pass',
2407
- 'changed ' + field + ' withholds outline credit');
2408
- fs.writeFileSync(eventFile, original);
2409
- fixture.runtimeProvider.rebuildJournalView(fixture.sessionDir);
2410
- }
2411
- const restored = fixture.runtimePilot.assess(context, set);
2412
- assert.strictEqual(restored.withhold, false, 'restored positive control returns to the same production consumer');
2413
- assert.strictEqual(restored.report.pilotCredit, true, 'restored exact state-operation evidence credits');
2414
- } finally {
2415
- fixture.runtimeProvider.createClaudeOriginProvider = originalFactory;
2416
- if (previousSwitch === undefined) delete process.env.HARNESS_DOC_RECONCILIATION_PILOT;
2417
- else process.env.HARNESS_DOC_RECONCILIATION_PILOT = previousSwitch;
2418
- fixture.cleanup();
2419
- }
2420
- });
2421
-
2422
- test('W6 rejects extra destinations, replayed results, and missing host completion', () => {
2423
- for (const fault of ['extra-state-destination', 'duplicate-post', 'missing-post', 'inventory-symlink']) {
2424
- if (fault === 'inventory-symlink') {
2425
- const unavailable = symlinkUnavailable('dir');
2426
- if (unavailable) return { unchecked: `directory symlink escape control unavailable (${unavailable})` };
2427
- }
2428
- const fixture = createOutlineFixture({ realHook: true, retainedInventory: true, workflowCli: true, w6Producer: true,
2429
- w6ProducerFault: fault, w6ExpectedProducerFailure: fault === 'inventory-symlink',
2430
- sessionId: 'w6-negative-' + fault, preOutlineOperation: 'write', capturedOutlineCommit: true });
2431
- try {
2432
- if (fault === 'inventory-symlink') {
2433
- assert.ok(fixture.inventoryOperation?.error, 'symlinked destination makes the producer fail before writing');
2434
- assert.strictEqual(fs.existsSync(fixture.outsideInventoryPath), false, 'the outside destination receives no file');
2435
- }
2436
- const completed = fixture.finishDraft({ finalReview: true, completeWorkflow: true, allowDispositionFailure: true, runPilot: true });
2437
- assert.notStrictEqual(completed.result.status, 'accepted', fault + ': unsupported operation effect cannot credit outline');
2438
- assert.notStrictEqual(completed.pilot && completed.pilot.report.outlineEvidence && completed.pilot.report.outlineEvidence.outcome,
2439
- 'pass', fault + ': final consumer withholds outline credit');
2440
- const captures = fixture.runtimeProvider.readCaptureView(fixture.sessionDir).records;
2441
- const decision = fixture.runtimeProvider._internals.evaluateW6StateOperations(captures, fixture.sessionDir);
2442
- const inventory = decision.results.find(item => item.operation === 'inventory');
2443
- assert.strictEqual(inventory && inventory.accepted, false, fault + ': shared validator rejects inventory effect/result');
2444
- } finally { fixture.cleanup(); }
2445
- }
2446
- });
2447
-
2448
- test('W6 shell boundary rejects compound writer activity even when the task tree is restored', () => {
2449
- const fixture = createOutlineFixture({ realHook: true, retainedInventory: true, workflowCli: true, w6Producer: true,
2450
- sessionId: 'w6-negative-compound', preOutlineOperation: 'write', capturedOutlineCommit: true });
2451
- try {
2452
- const helper = path.join(ROOT, 'hooks/scripts/w6-state-operations.js');
2453
- const plain = 'node "' + helper + '" seal --session-id "' + fixture.sessionId + '"';
2454
- const compound = plain + '; printf mutated > .agents/harness-everything/project-docs.json; git checkout -- .agents/harness-everything/project-docs.json';
2455
- const previousStateHome = process.env.HARNESS_STATE_HOME;
2456
- process.env.HARNESS_STATE_HOME = fixture.stateHome;
2457
- try {
2458
- assert.strictEqual(fixture.runtimeProvider.isW6StateCommand(plain, fixture.root, fixture.root,
2459
- { toolName: 'Bash', sessionId: fixture.sessionId }), true, 'positive control: exact installed producer resolves');
2460
- assert.strictEqual(fixture.runtimeProvider.isW6StateCommand(compound, fixture.root, fixture.root,
2461
- { toolName: 'Bash', sessionId: fixture.sessionId }), false, 'compound trailing work is outside the fixed operation');
2462
- } finally {
2463
- if (previousStateHome === undefined) delete process.env.HARNESS_STATE_HOME;
2464
- else process.env.HARNESS_STATE_HOME = previousStateHome;
2465
- }
2466
- const file = path.join(fixture.root, '.agents/harness-everything/project-docs.json');
2467
- const original = fs.readFileSync(file);
2468
- const payload = { session_id: fixture.sessionId, cwd: fixture.root, hook_event_name: 'PreToolUse', tool_name: 'Bash',
2469
- tool_use_id: 'w6-compound-writer', tool_input: { command: compound } };
2470
- fixture.runHook(payload);
2471
- const rejectedProducer = spawnSync(process.execPath, [helper, 'seal', '--session-id', fixture.sessionId], {
2472
- cwd: fixture.root, encoding: 'utf8', env: { ...process.env, HARNESS_STATE_HOME: fixture.stateHome,
2473
- HARNESS_WORKSPACE_ROOT: fixture.root, HARNESS_DOC_RECONCILIATION_PILOT: '1' },
2474
- });
2475
- assert.strictEqual(rejectedProducer.status, 2, 'the installed producer refuses a compound host command');
2476
- fs.writeFileSync(file, 'mutated\n');
2477
- fs.writeFileSync(file, original);
2478
- fixture.runHook({ ...payload, hook_event_name: 'PostToolUse',
2479
- tool_response: { exitCode: 0, stdout: '', interrupted: false, status: 'completed' } });
2480
- assert.deepStrictEqual(fs.readFileSync(file), original, 'the negative restores the exact task-tree bytes');
2481
- const writer = fixture.runtimeProvider.readCaptureView(fixture.sessionDir).records.find(item => item.tool_use_id === payload.tool_use_id);
2482
- assert.ok(writer && !writer.stateOperation, 'compound invocation receives no bounded operation record');
2483
- const completed = fixture.finishDraft({ finalReview: true, completeWorkflow: true,
2484
- allowDispositionFailure: true, runPilot: true });
2485
- assert.notStrictEqual(completed.result.status, 'accepted', 'an unrecognized compound writer cannot earn outline credit');
2486
- assert.ok(completed.result.diagnostics && completed.result.diagnostics.some(item =>
2487
- ['outline-writer-activity-ambiguous', 'outline-state-operation-unresolved'].includes(item.code)),
2488
- 'unknown compound writer or missing bounded state path stays visible');
2489
- } finally { fixture.cleanup(); }
2490
- });
2491
-
2492
- test('captured pre-O coordinator Write of the pinned target earns outline credit, like the paired read-only control', () => {
2493
- const legs = [];
2494
- for (const [name, operation, sessionId] of [
2495
- ['writer', 'write', 'coordinator-writer-session'],
2496
- ['control', 'status', 'coordinator-control-session'],
2497
- ]) {
2498
- const fixture = createOutlineFixture({ realHook: true, preOutlineOperation: operation, sessionId });
2499
- try {
2500
- const completed = fixture.finishDraft({ runPilot: true });
2501
- const captures = completed.captures;
2502
- const preOperation = captures.find(item => item.ref === fixture.preOutlineOperation.preRef);
2503
- const postOperation = captures.find(item => item.ref === fixture.preOutlineOperation.postRef);
2504
- const reviewResult = captures.find(item => item.event === 'PostToolUse' && item.tool_use_id === 'review-dispatch');
2505
- const reviewStop = captures.find(item => item.ref === fixture.handoff.reviewCaptureRef);
2506
- const dispatch = captures.find(item => item.event === 'PreToolUse' && item.tool_use_id === fixture.payload.tool_use_id);
2507
- const correlation = internals.correlateOutlineDispatch(captures, dispatch, fixture.root);
2508
- const reviewIndependent = provider.reviewRecordIndependent(reviewStop, captures, {
2509
- author: fixture.sessionId, executors: provider.journalExecutors(captures, fixture.sessionId),
2510
- });
2511
- assert.ok(preOperation && postOperation && reviewResult && reviewStop && dispatch);
2512
- assert.strictEqual(preOperation.event, 'PreToolUse');
2513
- assert.strictEqual(postOperation.event, 'PostToolUse');
2514
- assert.strictEqual(preOperation.session_id, fixture.sessionId);
2515
- assert.strictEqual(preOperation.tool_name, operation === 'write' ? 'Write' : 'Bash');
2516
- if (operation === 'status') assert.strictEqual(preOperation.command, 'git status --porcelain');
2517
- assert.ok(!Object.prototype.hasOwnProperty.call(preOperation, 'agent_id'),
2518
- 'pre-O operation retains the root coordinator identity shape');
2519
- assert.strictEqual(fixture.capture.outlineDispatch.state, 'accepted', name + ' dispatch seam accepted');
2520
- assert.strictEqual(dispatch.outlineDispatch.state, 'accepted', name + ' retained dispatch seam accepted');
2521
- assert.strictEqual(reviewIndependent, true, name + ' independent exact-O reviewer remains valid');
2522
- assert.strictEqual(correlation.state, 'accepted', name + ' worker dispatch/result/start/stop correlation accepted');
2523
- assert.strictEqual(correlation.agentId, 'draft-worker');
2524
- assert.strictEqual(correlation.workerRoot, fixture.root);
2525
-
2526
- const eventRefs = [preOperation.ref, postOperation.ref, reviewResult.ref, reviewStop.ref, dispatch.ref,
2527
- correlation.start.ref, correlation.result.ref, correlation.stop.ref];
2528
- const eventIndexes = eventRefs.map(ref => captures.findIndex(item => item.ref === ref));
2529
- assert.ok(eventIndexes.every(index => index >= 0));
2530
- assert.ok(eventIndexes.every((index, position) => position === 0 || eventIndexes[position - 1] < index),
2531
- name + ' retained events preserve Pre/Post → review → dispatch → worker lifecycle order');
2532
- fixtureGit(fixture.root, ['merge-base', '--is-ancestor', fixture.baselineCommit, fixture.outlineCommit]);
2533
- fixtureGit(fixture.root, ['merge-base', '--is-ancestor', fixture.outlineCommit, completed.draftCommit]);
2534
- assert.notStrictEqual(fixture.outlineCommit, completed.draftCommit, name + ' D is a strict descendant of O');
2535
-
2536
- const report = completed.pilot?.report;
2537
- assert.ok(report, name + ' used the actual pilot.assess() consumer');
2538
- const diagnosticCodes = (completed.result.diagnostics || []).map(item => item.code);
2539
- const outlineEvidence = report.outlineEvidence;
2540
- const pilotDiagnosticCodes = (outlineEvidence.diagnostics || []).map(item => item.code);
2541
- if (name === 'writer') {
2542
- // W2: the coordinator Write of the pinned target before review is the captured B→O write, so it earns credit.
2543
- assert.strictEqual(preOperation.tool_name, 'Write');
2544
- assert.ok(!diagnosticCodes.includes('outline-writer-activity-ambiguous'), JSON.stringify(completed.result));
2545
- assert.ok(!pilotDiagnosticCodes.includes('outline-writer-activity-ambiguous'), JSON.stringify(report));
2546
- assert.strictEqual(completed.result.status, 'accepted', JSON.stringify(completed.result));
2547
- assert.strictEqual(outlineEvidence.outcome, 'pass', JSON.stringify(report));
2548
- } else {
2549
- assert.strictEqual(fixture.preOutlineOperation.output, '', 'clean B produces the real empty git status output');
2550
- assert.strictEqual(completed.result.status, 'accepted', JSON.stringify(completed.result));
2551
- assert.strictEqual(outlineEvidence.outcome, 'pass', JSON.stringify(report));
139
+ const legacy = runHook({
140
+ hook_event_name: 'PostToolUse', session_id: sessionId, cwd: aliasRoot,
141
+ tool_name: 'Bash', tool_input: { command: 'echo legacy-state-probe' },
142
+ tool_response: { exitCode: 0, stdout: '', stderr: '' },
143
+ });
144
+ assert.strictEqual(legacy.status, 0, `generic PostToolUse state-persist remains fail-open: ${legacy.stderr}`);
145
+ return {
146
+ legacyExit: legacy.status,
147
+ handoffInAliasSession: fs.existsSync(path.join(aliasSessionDir, 'handoff-state.json')),
148
+ handoffInCanonicalSession: fs.existsSync(path.join(canonicalSessionDir, 'handoff-state.json')),
149
+ };
150
+ } finally {
151
+ fs.rmSync(stateHome, { recursive: true, force: true });
152
+ fs.rmSync(aliasRoot, { force: true });
153
+ fs.rmSync(realRoot, { recursive: true, force: true });
2552
154
  }
2553
- legs.push({ name, operation: fixture.preOutlineOperation, target: fixture.target, targetSha256: sha(fixture.outlineBytes),
2554
- taskId: fixture.taskId, requirementIds: fixture.taskBinding.requirementIds,
2555
- baselineCommit: fixture.baselineCommit, outlineCommit: fixture.outlineCommit, draftCommit: completed.draftCommit,
2556
- outlineBlob: fixture.outlineBlob, outlineEvidenceOutcome: outlineEvidence.outcome,
2557
- expectedMustIds: report.expectedMustIds, unsatisfied: report.unsatisfied,
2558
- diagnosticCodes, providerStatus: completed.result.status,
2559
- reviewer: { resultRef: reviewResult.ref, stopRef: reviewStop.ref, principal: reviewStop.agent_id, independent: reviewIndependent },
2560
- dispatch: { ref: dispatch.ref, seamState: dispatch.outlineDispatch.state },
2561
- worker: { startRef: correlation.start.ref, resultRef: correlation.result.ref, stopRef: correlation.stop.ref,
2562
- principal: correlation.agentId, root: correlation.workerRoot },
2563
- orderedEventRefs: eventRefs });
2564
- } finally { fixture.cleanup(); }
2565
- }
2566
-
2567
- assert.deepStrictEqual(legs[0].expectedMustIds, legs[1].expectedMustIds,
2568
- 'both legs retain the same applicable MUST obligations');
2569
- assert.ok(legs[0].expectedMustIds.includes('doc-change:outline-confirmation'),
2570
- 'the same outline-confirmation MUST remains applicable in both legs');
2571
- assert.deepStrictEqual(
2572
- [legs[0].taskId, legs[0].requirementIds, legs[0].target, legs[0].targetSha256],
2573
- [legs[1].taskId, legs[1].requirementIds, legs[1].target, legs[1].targetSha256],
2574
- 'both legs use the same task, obligation inputs, target and O bytes');
2575
- const unrelatedMustResults = leg => leg.unsatisfied
2576
- .filter(item => item.obligationId.startsWith('doc-change:') && item.obligationId !== 'doc-change:outline-confirmation')
2577
- .map(item => [item.obligationId, item.state, item.reasonCode]);
2578
- assert.deepStrictEqual(unrelatedMustResults(legs[0]), unrelatedMustResults(legs[1]),
2579
- 'remaining aggregate MUST failures are identical and unrelated to outline credit');
2580
- assert.strictEqual(legs[0].targetSha256, legs[1].targetSha256);
2581
- assert.strictEqual(legs[0].outlineBlob, legs[1].outlineBlob, 'same O bytes produce the same target blob');
2582
- console.log('WITNESS ' + JSON.stringify(legs));
2583
- });
2584
-
2585
- // Writer-policy controls (#341 W1–W5). Each control enters the real state-persist hook at a named journal position and
2586
- // must withhold outline credit through provider → pilot.assess(). The positive controls take the same path and earn it.
2587
- const ctxOf = fixture => ({ root: fixture.root, sessionId: fixture.sessionId, target: fixture.target });
2588
- const writerRecord = ({ toolUseId, file = null, filePath = null, patch = null, cwd = null, omitCwd = false,
2589
- toolInput = null, agentId = null, tool = 'Write', command = null }) => ctx => {
2590
- const rawPath = typeof file === 'function' ? file(ctx) : file || ctx.target;
2591
- const inputPath = filePath || (path.isAbsolute(rawPath) ? rawPath : path.join(ctx.root, rawPath));
2592
- const inputPatch = typeof patch === 'function' ? patch(ctx) : patch;
2593
- const inputCommand = typeof command === 'function' ? command(ctx) : command;
2594
- return {
2595
- session_id: ctx.sessionId, ...(omitCwd ? {} : { cwd: cwd || ctx.root }), hook_event_name: 'PreToolUse', tool_name: tool, tool_use_id: toolUseId,
2596
- ...(agentId ? { agent_id: agentId, agent_type: 'worker' } : {}),
2597
- tool_input: toolInput || (tool === 'Bash' ? { command: inputCommand } : tool === 'apply_patch'
2598
- ? { patch: inputPatch || `*** Update File: ${rawPath}\n@@\n-old\n+new\n` }
2599
- : tool === 'Edit' ? { file_path: inputPath, old_string: 'old', new_string: 'new' }
2600
- : { file_path: inputPath, content: 'injected writer' }),
2601
- };
2602
- };
2603
- const WRITER_AMBIGUOUS = 'outline-writer-activity-ambiguous';
2604
- const SEAM_UNRESOLVED = 'outline-pre-dispatch-seam-unresolved';
2605
-
2606
- function runWriterControl(name, options, arrange = () => {}) {
2607
- const { inspectWriterUseId, capturePayload, ...fixtureOptions } = options;
2608
- const fixture = createOutlineFixture({ realHook: true, ...fixtureOptions });
2609
- try {
2610
- arrange(fixture);
2611
- const completed = fixture.finishDraft({ runPilot: true });
2612
- const outline = completed.pilot?.report?.outlineEvidence;
2613
- const codes = [...(completed.result.diagnostics || []), ...(outline?.diagnostics || [])]
2614
- .flatMap(item => [item.code, item.reason]).filter(Boolean);
2615
- const writer = inspectWriterUseId
2616
- ? provider.readCaptureView(fixture.sessionDir).records.find(item => item.event === 'PreToolUse' && item.tool_use_id === inspectWriterUseId)
2617
- : undefined;
2618
- return { control: name, writer, payload: capturePayload?.(), status: completed.result.status, outcome: outline?.outcome ?? null, codes };
2619
- } finally { fixture.cleanup(); }
2620
- }
2621
-
2622
- function runCapturedWriterControl(name, toolUseId, makeRecord, options = {}) {
2623
- const interleave = options.interleave || {};
2624
- let payload;
2625
- const captureRecord = ctx => { payload = makeRecord(ctx); return payload; };
2626
- return runWriterControl(name, { ...options, inspectWriterUseId: toolUseId,
2627
- interleave: { ...interleave, beforeReview: [...(interleave.beforeReview || []), captureRecord] },
2628
- capturePayload: () => payload });
2629
- }
2630
-
2631
- function writerPayloadFor(tool, toolUseId, value, options = {}) {
2632
- return ctx => {
2633
- const raw = typeof value === 'function' ? value(ctx) : value;
2634
- const cwd = typeof options.cwd === 'function' ? options.cwd(ctx) : options.cwd;
2635
- const patch = typeof options.patch === 'function' ? options.patch(ctx, raw) : options.patch;
2636
- const command = typeof options.command === 'function' ? options.command(ctx, raw) : options.command;
2637
- return writerRecord({ toolUseId, tool, filePath: raw, cwd, omitCwd: options.omitCwd,
2638
- patch: patch || `*** Begin Patch\n*** Update File: ${raw}\n@@\n-old\n+new\n*** End Patch\n`,
2639
- command: command || `git add -- ${shellWord(raw)}`, toolInput: options.toolInput?.(ctx, raw) })(ctx);
2640
- };
2641
- }
2642
-
2643
- function shellWord(value) {
2644
- return /[\s'"\\]/.test(value)
2645
- ? `"${String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\$/g, '\\$').replace(/`/g, '\\`')}"`
2646
- : value;
2647
- }
2648
-
2649
- function rawTargetsFromPayload(tool, payload) {
2650
- const input = payload.tool_input || {};
2651
- if (tool === 'Bash') return input.command;
2652
- if (tool !== 'apply_patch') {
2653
- const file = input.file_path || input.path;
2654
- return typeof file === 'string' && file.length ? [file] : [];
2655
- }
2656
- const patch = typeof input === 'string' ? input : String(input.patch || input.input || '');
2657
- const targets = [];
2658
- for (const match of patch.matchAll(/^\*\*\* ([^\r\n]*)(?:\r?$)/gm)) {
2659
- if (['Begin Patch', 'End Patch', 'End of File'].includes(match[1])) continue;
2660
- const fileHeader = /^(?:Add File|Update File|Delete File|Move to): (.*)$/.exec(match[1]);
2661
- if (!fileHeader) return null;
2662
- targets.push(fileHeader[1]);
2663
- }
2664
- return targets;
2665
- }
2666
-
2667
- function replaceOutlinePathForWriterCapture(root, target, kind) {
2668
- const file = path.join(root, target);
2669
- const parent = path.dirname(file);
2670
- const backup = `${parent}-prb-original`;
2671
- const outside = `${root}-outside`;
2672
- const original = fs.readFileSync(file);
2673
- if (kind === 'outward-leaf' || kind === 'inward-leaf' || kind === 'dangling-leaf' || kind === 'directory-leaf') {
2674
- fs.rmSync(file, { recursive: true, force: true });
2675
- if (kind === 'outward-leaf') {
2676
- fs.mkdirSync(outside, { recursive: true });
2677
- fs.writeFileSync(path.join(outside, 'outside.md'), original);
2678
- fs.symlinkSync(path.join(outside, 'outside.md'), file);
2679
- } else if (kind === 'inward-leaf') {
2680
- fs.writeFileSync(path.join(parent, 'OTHER-001.md'), original);
2681
- fs.symlinkSync('OTHER-001.md', file);
2682
- } else if (kind === 'dangling-leaf') fs.symlinkSync(path.join(outside, 'missing.md'), file);
2683
- else fs.mkdirSync(file);
2684
- return () => {
2685
- fs.rmSync(file, { recursive: true, force: true });
2686
- fs.rmSync(path.join(parent, 'OTHER-001.md'), { force: true });
2687
- fs.writeFileSync(file, original);
2688
- fs.rmSync(outside, { recursive: true, force: true });
2689
- };
2690
- }
2691
- fs.renameSync(parent, backup);
2692
- if (kind === 'parent-file-error') fs.writeFileSync(parent, 'not a directory');
2693
- else {
2694
- fs.mkdirSync(outside, { recursive: true });
2695
- if (kind === 'parent-outward-existing') fs.writeFileSync(path.join(outside, path.basename(file)), original);
2696
- fs.symlinkSync(outside, parent, 'dir');
2697
- }
2698
- return () => {
2699
- fs.rmSync(parent, { recursive: true, force: true });
2700
- fs.renameSync(backup, parent);
2701
- fs.rmSync(outside, { recursive: true, force: true });
2702
- };
2703
- }
2704
-
2705
- test('writer topology at PreToolUse is checked through the real hook, provider and pilot.assess()', () => {
2706
- const target = 'docs/adr/DOCS-001.md';
2707
- const unavailable = { file: symlinkUnavailable('file'), dir: symlinkUnavailable('dir') };
2708
- const cases = [
2709
- ['outward leaf symlink', 'outward-leaf', 'file'],
2710
- ['inward leaf symlink', 'inward-leaf', 'file'],
2711
- ['dangling leaf symlink', 'dangling-leaf', 'file'],
2712
- ['outward symlinked parent with regular leaf', 'parent-outward-existing', 'dir'],
2713
- ['outward symlinked parent with missing leaf', 'parent-outward-missing', 'dir'],
2714
- ['directory leaf', 'directory-leaf', null],
2715
- ['filesystem error from non-directory parent', 'parent-file-error', null],
2716
- ];
2717
- const controls = cases.flatMap(([name, kind, symlinkType], index) => ['Write', 'Edit', 'apply_patch', 'Bash'].map(tool => ({
2718
- name: `${name} (${tool})`, kind, symlinkType, tool, index,
2719
- })));
2720
- const observed = [];
2721
- const problems = [];
2722
- for (const { name, kind, symlinkType, tool, index } of controls) {
2723
- if (symlinkType && unavailable[symlinkType]) {
2724
- observed.push({ name, status: 'unchecked', reason: unavailable[symlinkType] });
2725
- continue;
2726
- }
2727
- const result = runWriterControl(name, {
2728
- beforeReviewSetup: ({ root }) => replaceOutlinePathForWriterCapture(root, target, kind),
2729
- interleave: { beforeReview: [writerRecord({ toolUseId: `topology-${index}-${tool}`, tool,
2730
- command: tool === 'Bash' ? `git add -- ${target}` : null })] },
2731
- });
2732
- observed.push({ name, ...result });
2733
- if (result.status === 'accepted' || result.outcome === 'pass' || !result.codes.includes(WRITER_AMBIGUOUS)) {
2734
- problems.push(`${name}: expected ${WRITER_AMBIGUOUS}, got ${result.status}/${result.outcome} (${result.codes.join(', ')})`);
2735
- }
2736
- }
2737
- console.log('WRITER-TOPOLOGY-CONTROLS ' + JSON.stringify(observed));
2738
- assert.deepStrictEqual(problems, [], 'writer topology controls');
2739
- const unavailableTypes = Object.entries(unavailable).filter(([, reason]) => reason).map(([type]) => type);
2740
- if (unavailableTypes.length) return { unchecked: `${unavailableTypes.join(' and ')} symlink controls were unavailable (${unavailableTypes.map(type => unavailable[type]).join(', ')})` };
2741
- });
2742
-
2743
- test('pinned O symlink with citation-looking link text gets no outline credit when the worktree leaf is regular', () => {
2744
- const unavailable = symlinkUnavailable('file');
2745
- if (unavailable) return { unchecked: `file symlink creation is unavailable (${unavailable})` };
2746
- const fixture = createOutlineFixture({ realHook: true, symlinkOutlineObject: true });
2747
- try {
2748
- const linkText = fs.readlinkSync(path.join(fixture.root, fixture.target));
2749
- const citationPrecondition = symlinkCitationPrecondition(linkText, fixture.outlineBytes.toString('utf8'), fixture.target);
2750
- const completed = fixture.finishDraft({ runPilot: true });
2751
- const outline = completed.pilot?.report?.outlineEvidence;
2752
- const codes = [...(completed.result.diagnostics || []), ...(outline?.diagnostics || [])]
2753
- .flatMap(item => [item.code, item.reason]).filter(Boolean);
2754
- assert.notStrictEqual(completed.result.status, 'accepted', JSON.stringify(completed.result));
2755
- assert.notStrictEqual(outline?.outcome, 'pass', JSON.stringify(outline));
2756
- assert.ok(codes.includes('outline-target-object-not-regular'),
2757
- `expected pinned O mode rejection before citation acceptance; got ${codes.join(', ')}`);
2758
- assert.ok(fs.statSync(path.join(fixture.root, fixture.target)).isFile(), 'D leaves a regular worktree target after O');
2759
- if (citationPrecondition) return citationPrecondition;
2760
- } finally { fixture.cleanup(); }
2761
- });
2762
-
2763
- test('captured git add of an absent outline target is not positive staging evidence', () => {
2764
- const target = 'docs/adr/DOCS-001.md';
2765
- const result = runWriterControl('git add before target creation', {
2766
- beforeReviewSetup: ({ root }) => {
2767
- const file = path.join(root, target);
2768
- const bytes = fs.readFileSync(file);
2769
- fs.unlinkSync(file);
2770
- return () => fs.writeFileSync(file, bytes);
2771
- },
2772
- interleave: { beforeReview: [writerRecord({ toolUseId: 'absent-target-add', tool: 'Bash', command: `git add -- ${target}` })] },
2773
- });
2774
- assert.notStrictEqual(result.status, 'accepted', JSON.stringify(result));
2775
- assert.notStrictEqual(result.outcome, 'pass', JSON.stringify(result));
2776
- assert.ok(result.codes.includes(WRITER_AMBIGUOUS), `expected ${WRITER_AMBIGUOUS}; got ${result.codes.join(', ')}`);
2777
- });
2778
-
2779
- test('writer-policy negative controls withhold outline credit through the real hook, provider and pilot.assess()', () => {
2780
- const target = 'docs/adr/DOCS-001.md';
2781
- const gitCommandControls = [
2782
- ['git add -A', 'git add -A'],
2783
- ['git add --all', 'git add --all'],
2784
- ['git add current directory', 'git add .'],
2785
- ['git add target and unrelated plain operands', `git add ${target} unrelated.md`],
2786
- ['git add target and unrelated after --', `git add -- ${target} unrelated.md`],
2787
- ['git add pathspec file input', 'git add --pathspec-from-file=x'],
2788
- ['git add patch mode', `git add -p ${target}`],
2789
- ['git add unknown option', `git add --unknown ${target}`],
2790
- ['git add pathspec magic', `git add -- :(top)${target}`],
2791
- ['git add outside root', `git add ../${target}`],
2792
- ['git commit -a', 'git commit -a -m x'],
2793
- ['git commit --all', 'git commit --all -m x'],
2794
- ['git commit --include', `git commit --include ${target} -m x`],
2795
- ['git commit interactive mode', 'git commit --interactive -m x'],
2796
- ['git commit patch mode', 'git commit --patch -m x'],
2797
- ['git commit alternate pathspec', `git commit -m x -- ${target}`],
2798
- ['git commit pathspec file input', 'git commit --pathspec-from-file=x -m x'],
2799
- ].map(([name, command], index) => [name, {
2800
- interleave: { beforeReview: [writerRecord({ toolUseId: `nc-git-${index}`, tool: 'Bash', command })] },
2801
- }, [WRITER_AMBIGUOUS]]);
2802
- const controls = [
2803
- ['unauthorized target before review', { interleave: { beforeReview: [writerRecord({ toolUseId: 'nc-target', file: 'docs/adr/OTHER-001.md' })] } }, [WRITER_AMBIGUOUS]],
2804
- ['wrong phase: coordinator writes O during review', { interleave: { duringReview: [writerRecord({ toolUseId: 'nc-review' })] } }, [WRITER_AMBIGUOUS]],
2805
- ['edit to O after review, before dispatch', { interleave: { beforeDispatch: [writerRecord({ toolUseId: 'nc-edit' })] } }, [WRITER_AMBIGUOUS]],
2806
- ['write-and-restore of O between review and dispatch', { interleave: { beforeDispatch: [
2807
- writerRecord({ toolUseId: 'nc-write' }), writerRecord({ toolUseId: 'nc-restore' })] } }, [WRITER_AMBIGUOUS]],
2808
- ['coordinator write after dispatch', {}, [WRITER_AMBIGUOUS],
2809
- f => f.runHook(writerRecord({ toolUseId: 'nc-after-dispatch' })(ctxOf(f)))],
2810
- ['competing worker writes during the draft window', {}, ['outline-competing-writer-start', WRITER_AMBIGUOUS],
2811
- f => {
2812
- f.runHook({ session_id: f.sessionId, cwd: f.root, hook_event_name: 'SubagentStart', agent_id: 'rival-worker', agent_type: 'worker' });
2813
- f.runHook(writerRecord({ toolUseId: 'nc-rival', agentId: 'rival-worker' })(ctxOf(f)));
2814
- }],
2815
- ['ambiguous shell effect: chained git commit', { interleave: { beforeReview: [writerRecord({ toolUseId: 'nc-shell', tool: 'Bash',
2816
- command: 'git commit -q -m "O outline" && node ./mutate.js' })] } }, [WRITER_AMBIGUOUS]],
2817
- ['ambiguous shell effect: git add with a trailing script', { interleave: { beforeReview: [writerRecord({ toolUseId: 'nc-shell-2', tool: 'Bash',
2818
- command: 'git add -- docs/adr/DOCS-001.md; node ./mutate.js' })] } }, [WRITER_AMBIGUOUS]],
2819
- ['replayed coordinator B→O write record', { sessionId: 'coordinator-writer-session', preOutlineOperation: 'write',
2820
- interleave: { beforeDispatch: [writerRecord({ toolUseId: 'pre-outline-write-coordinator-writer-session' })] } }, [WRITER_AMBIGUOUS]],
2821
- ['reviewer writes during review', { interleave: { duringReview: [writerRecord({ toolUseId: 'nc-reviewer', agentId: 'outline-reviewer' })] } }, [WRITER_AMBIGUOUS]],
2822
- ['reviewer is the coordinator', { reviewerPrincipal: 'author-session' }, [SEAM_UNRESOLVED]],
2823
- // Multiple launch results for the same reviewer make its independent result decision ambiguous.
2824
- ['reviewer is the draft worker', { reviewerPrincipal: 'draft-worker' }, ['outline-review-not-independent']],
2825
- ['missing reviewer lifecycle', { omitReviewResult: true }, [SEAM_UNRESOLVED]],
2826
- ['review digest mismatch at dispatch', { handoffOverrides: { reviewDigest: 'f'.repeat(64) } }, [SEAM_UNRESOLVED]],
2827
- ['task mismatch at dispatch', { handoffOverrides: { taskId: 'task-other' } }, [SEAM_UNRESOLVED]],
2828
- ['O commit mismatch at dispatch', { handoffOverrides: { outline: { commit: 'a'.repeat(40), tree: 'b'.repeat(40), targetBlobs: {} } } },
2829
- [SEAM_UNRESOLVED]],
2830
- ['O commit carries an uncaptured extra file', { preOutlineOperation: 'write', capturedOutlineCommit: true,
2831
- extraOutlineFile: 'docs/adr/EXTRA-001.md' }, ['outline-commit-scope-invalid']],
2832
- ...gitCommandControls,
2833
- ];
2834
- const witness = [];
2835
- const problems = [];
2836
- for (const [name, options, expected, arrange] of controls) {
2837
- const result = runWriterControl(name, options, arrange);
2838
- witness.push({ ...result, expected });
2839
- if (result.status === 'accepted') problems.push(`${name}: origin must not accept`);
2840
- if (result.outcome === 'pass') problems.push(`${name}: outline must not pass`);
2841
- if (!expected.some(code => result.codes.includes(code))) problems.push(`${name}: expected ${expected.join(' | ')}; got ${[...new Set(result.codes)].join(', ')}`);
2842
- }
2843
- console.log('WRITER-NEGATIVE-CONTROLS ' + JSON.stringify(witness));
2844
- assert.deepStrictEqual(problems, [], 'writer-policy negative controls');
2845
- });
2846
-
2847
- test('pre-review writer positive controls earn outline credit on the same real path', () => {
2848
- const target = 'docs/adr/DOCS-001.md';
2849
- const controls = [
2850
- ['coordinator Write of the pinned target before review', { interleave: { beforeReview: [writerRecord({ toolUseId: 'pc-target' })] } }],
2851
- ['coordinator Edit of the pinned target before review', { interleave: { beforeReview: [writerRecord({ toolUseId: 'pc-edit', tool: 'Edit' })] } }],
2852
- ['coordinator apply_patch of the pinned target before review', { interleave: { beforeReview: [writerRecord({ toolUseId: 'pc-patch', tool: 'apply_patch' })] } }],
2853
- ['coordinator apply_patch with exact CRLF header path before review', { interleave: { beforeReview: [writerRecord({ toolUseId: 'pc-patch-crlf', tool: 'apply_patch',
2854
- patch: ctx => `*** Begin Patch\r\n*** Update File: ${ctx.target}\r\n@@\r\n-old\r\n+new\r\n*** End Patch\r\n` })] } }],
2855
- ['captured git add -- target and git commit -m x', { preOutlineOperation: 'write', capturedOutlineCommit: true,
2856
- capturedOutlineCommitCommand: 'git commit -m x', capturedOutlineCommitArgs: ['commit', '-m', 'x'] }],
2857
- ['captured plain git add target', { preOutlineOperation: 'write', capturedOutlineCommit: true,
2858
- capturedOutlineAddCommand: `git add ${target}`, capturedOutlineAddArgs: ['add', target],
2859
- capturedOutlineCommitCommand: 'git commit -m x', capturedOutlineCommitArgs: ['commit', '-m', 'x'] }],
2860
- ['captured quoted git add target', { preOutlineOperation: 'write', capturedOutlineCommit: true,
2861
- capturedOutlineAddCommand: `git add -- "${target}"`, capturedOutlineAddArgs: ['add', '--', target],
2862
- capturedOutlineCommitCommand: 'git commit -m x', capturedOutlineCommitArgs: ['commit', '-m', 'x'] }],
2863
- ['captured escaped exact git add target', { preOutlineOperation: 'write', capturedOutlineCommit: true,
2864
- capturedOutlineAddCommand: String.raw`git add -- docs/adr/DOCS-001\.md`, capturedOutlineAddArgs: ['add', '--', target],
2865
- capturedOutlineCommitCommand: 'git commit -m x', capturedOutlineCommitArgs: ['commit', '-m', 'x'] }],
2866
- ['captured quoted git commit message', { preOutlineOperation: 'write', capturedOutlineCommit: true,
2867
- capturedOutlineCommitCommand: 'git commit -m "a b"', capturedOutlineCommitArgs: ['commit', '-m', 'a b'] }],
2868
- ];
2869
- for (const [name, options] of controls) {
2870
- const result = runWriterControl(name, options);
2871
- assert.strictEqual(result.status, 'accepted', `${name}: ${result.codes.join(', ')}`);
2872
- assert.strictEqual(result.outcome, 'pass', name);
2873
- }
2874
- });
2875
-
2876
- test('writer spelling controls preserve raw capture and bind identity before normalization', () => {
2877
- const cases = [
2878
- ['Write dot-segment alias', 'spelling-write-dotdot', ctx => writerRecord({ toolUseId: 'spelling-write-dotdot',
2879
- file: `${ctx.root}/docs/adr/sub/../DOCS-001.md` })(ctx)],
2880
- ['Edit dot-segment alias', 'spelling-edit-dot', ctx => writerRecord({ toolUseId: 'spelling-edit-dot',
2881
- tool: 'Edit', file: `${ctx.root}/docs/adr/./DOCS-001.md` })(ctx)],
2882
- ['apply_patch trailing-space alias', 'spelling-patch-space', ctx => writerRecord({ toolUseId: 'spelling-patch-space', tool: 'apply_patch',
2883
- patch: `*** Begin Patch\n*** Update File: ${ctx.target} \r\n@@\n-old\n+new\n*** End Patch\n` })(ctx)],
2884
- ['Git-add dot-segment operand', 'spelling-git-dotdot', ctx => writerRecord({ toolUseId: 'spelling-git-dotdot', tool: 'Bash',
2885
- command: 'git add -- docs/adr/sub/../DOCS-001.md' })(ctx)],
2886
- ];
2887
- const outcomes = [];
2888
- const problems = [];
2889
- for (const [name, toolUseId, makePayload] of cases) {
2890
- const result = runCapturedWriterControl(name, toolUseId, makePayload);
2891
- const expectedRaw = name === 'apply_patch trailing-space alias' ? ['docs/adr/DOCS-001.md '] : null;
2892
- if (expectedRaw && JSON.stringify(result.writer?.writeTargets) !== JSON.stringify(expectedRaw)) {
2893
- problems.push(`${name}: raw capture ${JSON.stringify(result.writer?.writeTargets)} !== ${JSON.stringify(expectedRaw)}`);
2894
- }
2895
- if (result.status === 'accepted' || result.outcome === 'pass') {
2896
- problems.push(`${name}: expected no credit, got ${result.status}/${result.outcome}`);
2897
155
  }
2898
- outcomes.push({ name, raw: result.writer?.writeTargets, status: result.status, outcome: result.outcome, codes: result.codes });
2899
- }
2900
- console.log('WRITER-SPELLING-RED ' + JSON.stringify(outcomes));
2901
- assert.deepStrictEqual(problems, [], 'exact target spelling and raw capture controls');
2902
- });
2903
156
 
2904
- test('canonical-root absolute Git-add rendering remains credited when /tmp has a distinct product-canonical root', () => {
2905
- const canonicalTmp = canonical('/tmp');
2906
- if (process.platform !== 'darwin' || canonicalTmp === '/tmp') {
2907
- return { unchecked: 'this host has no distinct canonical root for /tmp' };
2908
- }
2909
- const result = runWriterControl('canonical-root Git-add rendering', {
2910
- rootDirectory: '/tmp',
2911
- preserveRootSpelling: true,
2912
- preOutlineOperation: 'write',
2913
- capturedOutlineCommit: true,
2914
- capturedOutlineAddCommand: ({ root, target }) => `git add -- ${canonical(root)}/${target}`,
2915
- capturedOutlineAddArgs: ['add', '--', 'docs/adr/DOCS-001.md'],
2916
- capturedOutlineCommitCommand: 'git commit -m x',
2917
- capturedOutlineCommitArgs: ['commit', '-m', 'x'],
157
+ const first = driveAliasRootScenario();
158
+ const second = driveAliasRootScenario();
159
+ assert.deepStrictEqual(first, second, 'identical alias-root inputs must produce the same normalized state and exits');
160
+ assert.strictEqual(first.legacyExit, 0, 'generic PostToolUse remains fail-open');
161
+ assert.deepStrictEqual({
162
+ handoffInAliasSession: first.handoffInAliasSession,
163
+ handoffInCanonicalSession: first.handoffInCanonicalSession,
164
+ }, {
165
+ handoffInAliasSession: true,
166
+ handoffInCanonicalSession: false,
167
+ }, `generic handoff must stay in the bound alias session directory: ${JSON.stringify(first)}`);
2918
168
  });
2919
- assert.strictEqual(result.status, 'accepted', `${result.codes.join(', ')}`);
2920
- assert.strictEqual(result.outcome, 'pass');
2921
- });
2922
-
2923
- test('captured and product-canonical roots accept exact R/T and C/T spellings on all writer surfaces', () => {
2924
- const rootDirectory = process.platform === 'win32' || !fs.existsSync('/tmp') ? os.tmpdir() : '/tmp';
2925
- const targetSpelling = (ctx, tool) => tool === 'Bash' ? ctx.target : ctx.target.split('/').join(path.sep);
2926
- const forms = [
2927
- ['captured root R', (ctx, tool) => `${ctx.root}${path.sep}${targetSpelling(ctx, tool)}`, null],
2928
- ['product-canonical root C', (ctx, tool) => `${canonical(ctx.root)}${path.sep}${targetSpelling(ctx, tool)}`, null],
2929
- ['product-canonical cwd C with relative T', targetSpelling, ctx => canonical(ctx.root)],
2930
- ];
2931
- const problems = [];
2932
- const observed = [];
2933
- for (const [form, spelling, cwd] of forms) for (const tool of ['Write', 'Edit', 'apply_patch', 'Bash']) {
2934
- const toolUseId = `root-spelling-${form === 'captured root R' ? 'R' : 'C'}-${tool}`;
2935
- const result = runCapturedWriterControl(`${form} (${tool})`, toolUseId,
2936
- writerPayloadFor(tool, toolUseId, ctx => spelling(ctx, tool), { ...(cwd ? { cwd } : {}) }),
2937
- { rootDirectory, preserveRootSpelling: true });
2938
- observed.push({ form, tool, status: result.status, outcome: result.outcome, raw: tool === 'Bash'
2939
- ? result.writer?.command : result.writer?.writeTargets });
2940
- if (result.status !== 'accepted' || result.outcome !== 'pass') {
2941
- problems.push(`${form}/${tool}: expected positive control, got ${result.status}/${result.outcome} (${result.codes.join(', ')})`);
2942
- }
2943
- }
2944
- console.log('WRITER-ROOT-SPELLINGS ' + JSON.stringify(observed));
2945
- assert.deepStrictEqual(problems, [], 'exact root spellings');
2946
- });
2947
-
2948
- test('option-looking Git-add path values require an explicit -- marker', () => {
2949
- const target = '-A/DOCS-001.md';
2950
- const fixtureOptions = { target, governedPattern: '-A/*.md' };
2951
- const withoutMarkerId = 'option-looking-git-path-no-marker';
2952
- const withoutMarker = runCapturedWriterControl('option-looking path without marker', withoutMarkerId,
2953
- writerPayloadFor('Bash', withoutMarkerId, ctx => ctx.target, { command: () => 'git add -A/DOCS-001.md' }), fixtureOptions);
2954
- assert.notStrictEqual(withoutMarker.status, 'accepted');
2955
- assert.notStrictEqual(withoutMarker.outcome, 'pass');
2956
- assert.ok(withoutMarker.codes.includes(WRITER_AMBIGUOUS), withoutMarker.codes.join(', '));
2957
-
2958
- const withMarkerId = 'option-looking-git-path-with-marker';
2959
- const withMarker = runCapturedWriterControl('option-looking path with marker', withMarkerId,
2960
- writerPayloadFor('Bash', withMarkerId, ctx => ctx.target, { command: () => 'git add -- -A/DOCS-001.md' }), fixtureOptions);
2961
- assert.strictEqual(withMarker.status, 'accepted', withMarker.codes.join(', '));
2962
- assert.strictEqual(withMarker.outcome, 'pass');
2963
- });
2964
-
2965
- test('writer path family sweep keeps every captured path operand distinct through hook, provider and pilot.assess()', () => {
2966
- const nativeTarget = ctx => ctx.target.split('/').join(path.sep);
2967
- const rootTarget = ctx => `${ctx.root}${path.sep}${nativeTarget(ctx)}`;
2968
- const rows = [
2969
- ['dot-segment', 'Write', ctx => `${ctx.root}${path.sep}docs${path.sep}adr${path.sep}sub${path.sep}..${path.sep}DOCS-001.md`],
2970
- ['dot-segment', 'Edit', ctx => `${ctx.root}${path.sep}docs${path.sep}adr${path.sep}.${path.sep}DOCS-001.md`],
2971
- ['dot-segment', 'apply_patch', 'docs/adr/./DOCS-001.md'],
2972
- ['dot-segment', 'Bash', 'docs/adr/sub/../DOCS-001.md'],
2973
- ['leading-dot-segment', 'Write', './docs/adr/DOCS-001.md'],
2974
- ['leading-dot-segment', 'Edit', './docs/adr/DOCS-001.md'],
2975
- ['leading-dot-segment', 'apply_patch', './docs/adr/DOCS-001.md'],
2976
- ['leading-dot-segment', 'Bash', './docs/adr/DOCS-001.md'],
2977
- ['repeated-dot-segments', 'Write', ctx => `${ctx.root}${path.sep}docs${path.sep}adr${path.sep}sub${path.sep}..${path.sep}sub${path.sep}..${path.sep}DOCS-001.md`],
2978
- ['repeated-dot-segments', 'Edit', 'docs/adr/sub/../../adr/DOCS-001.md'],
2979
- ['repeated-dot-segments', 'apply_patch', 'docs/adr/sub/.././DOCS-001.md'],
2980
- ['repeated-dot-segments', 'Bash', 'docs/adr/sub/.././DOCS-001.md'],
2981
- ['repeated-or-trailing-separator', 'Write', ctx => `${ctx.root}${path.sep}${nativeTarget(ctx)}${path.sep}`],
2982
- ['repeated-or-trailing-separator', 'Edit', ctx => `${ctx.root}${path.sep}docs${path.sep}${path.sep}adr${path.sep}DOCS-001.md`],
2983
- ['repeated-or-trailing-separator', 'apply_patch', 'docs//adr//DOCS-001.md'],
2984
- ['repeated-or-trailing-separator', 'Bash', 'docs//adr//DOCS-001.md'],
2985
- ['mixed-separators', 'Write', ctx => `${ctx.root}\\docs/adr\\DOCS-001.md`],
2986
- ['mixed-separators', 'Edit', ctx => `${ctx.root}${path.sep}docs\\adr/DOCS-001.md`],
2987
- ['mixed-separators', 'apply_patch', 'docs\\adr/DOCS-001.md'],
2988
- ['mixed-separators', 'Bash', 'docs\\adr/DOCS-001.md'],
2989
- ['outside-root', 'Write', ctx => `${ctx.root}-outside${path.sep}docs${path.sep}adr${path.sep}DOCS-001.md`],
2990
- ['sibling-root-prefix', 'Edit', ctx => `${ctx.root}-sibling${path.sep}docs${path.sep}adr${path.sep}DOCS-001.md`],
2991
- ['root-itself', 'apply_patch', ctx => ctx.root],
2992
- ['directory-operand', 'Bash', 'docs/adr'],
2993
- ['unrelated-cwd', 'Write', rootTarget, { cwd: ctx => path.join(ctx.root, 'docs') }],
2994
- ['unknown-cwd', 'Edit', 'docs/adr/DOCS-001.md', { omitCwd: true }],
2995
- ['unrelated-cwd', 'apply_patch', rootTarget, { cwd: ctx => path.join(ctx.root, 'docs') }],
2996
- ['unrelated-cwd', 'Bash', 'docs/adr/DOCS-001.md', { cwd: ctx => path.join(ctx.root, 'docs') }],
2997
- ['target-case-variant', 'Write', 'docs/adr/docs-001.md'],
2998
- ['target-case-variant', 'Edit', 'docs/adr/docs-001.md'],
2999
- ['target-case-variant', 'apply_patch', 'docs/adr/docs-001.md'],
3000
- ['target-case-variant', 'Bash', 'docs/adr/docs-001.md'],
3001
- ['windows-drive-relative', 'Write', 'C:docs\\adr\\DOCS-001.md'],
3002
- ['windows-alternate-drive', 'Edit', 'D:\\docs\\adr\\DOCS-001.md'],
3003
- ['windows-root-relative', 'Edit', '\\docs\\adr\\DOCS-001.md'],
3004
- ['windows-device-namespace', 'apply_patch', () => ['\\\\', '?', '\\', 'C', String.fromCharCode(58), '\\docs\\adr\\DOCS-001.md'].join('')],
3005
- ['windows-unc-namespace', 'Bash', '\\\\server\\share\\docs\\adr\\DOCS-001.md'],
3006
- ['home-expansion', 'Write', '~/docs/adr/DOCS-001.md'],
3007
- ['environment-expression', 'Edit', '$ROOT/docs/adr/DOCS-001.md'],
3008
- ['file-url-and-encoding', 'apply_patch', 'file:///docs/adr/DOCS-001.md'],
3009
- ['percent-encoded-alias', 'Bash', 'docs/adr/%2e%2e/DOCS-001.md'],
3010
- ['escaped-dot-segment-alias', 'Bash', 'docs/adr/./DOCS-001.md', {
3011
- command: () => String.raw`git add -- docs/adr/\./DOCS-001.md` }],
3012
- ['trailing-filename-space', 'Write', 'docs/adr/DOCS-001.md '],
3013
- ['leading-filename-space', 'Edit', ' docs/adr/DOCS-001.md'],
3014
- ['tab-filename-byte', 'Write', 'docs/adr/\tDOCS-001.md'],
3015
- ['newline-filename-byte', 'Edit', 'docs/adr/DOCS-001.md\n'],
3016
- ['patch-header-trailing-space', 'apply_patch', 'docs/adr/DOCS-001.md ', {
3017
- patch: (ctx, raw) => `*** Begin Patch\n*** Update File: ${raw}\r\n@@\n-old\n+new\n*** End Patch\n`,
3018
- expectedRaw: 'docs/adr/DOCS-001.md ' }],
3019
- ['quoted-trailing-filename-space', 'Bash', 'docs/adr/DOCS-001.md '],
3020
- ['nul-path', 'Write', '\0docs/adr/DOCS-001.md'],
3021
- ['non-string-path', 'Edit', null, { toolInput: () => ({ file_path: 7, old_string: 'old', new_string: 'new' }) }],
3022
- ['unextractable-patch', 'apply_patch', '', { patch: () => '*** Begin Patch\n*** End Patch\n', expectedRaw: [] }],
3023
- ['empty-git-operand', 'Bash', '', { command: () => 'git add -- ""' }],
3024
- ['multiple-patch-sections', 'apply_patch', 'docs/adr/DOCS-001.md', {
3025
- patch: ctx => `*** Begin Patch\n*** Update File: ${ctx.target}\n@@\n-old\n+new\n*** Update File: docs/adr/OTHER-001.md\n@@\n-old\n+new\n*** End Patch\n`,
3026
- expectedRaw: ['docs/adr/DOCS-001.md', 'docs/adr/OTHER-001.md'] }],
3027
- ['move-source-and-destination', 'apply_patch', 'docs/adr/DOCS-001.md', {
3028
- patch: ctx => `*** Begin Patch\n*** Update File: ${ctx.target}\n*** Move to: docs/adr/OTHER-001.md\n@@\n-old\n+new\n*** End Patch\n`,
3029
- expectedRaw: ['docs/adr/DOCS-001.md', 'docs/adr/OTHER-001.md'] }],
3030
- ['unrecognized-patch-effect-with-valid-target', 'apply_patch', 'docs/adr/DOCS-001.md', {
3031
- patch: ctx => `*** Begin Patch\n*** Update File: ${ctx.target}\n*** Rename from: docs/adr/OTHER-001.md\n@@\n-old\n+new\n*** End Patch\n`,
3032
- expectedRaw: null }],
3033
- ['multiple-git-operands', 'Bash', 'docs/adr/DOCS-001.md', {
3034
- command: () => 'git add -- docs/adr/DOCS-001.md unrelated.md' }],
3035
- ];
3036
- const observed = [];
3037
- const problems = [];
3038
- for (let index = 0; index < rows.length; index += 1) {
3039
- const [family, tool, spelling, options = {}] = rows[index];
3040
- const toolUseId = `class-sweep-${index}`;
3041
- let result;
3042
- try {
3043
- result = runCapturedWriterControl(`${family} (${tool})`, toolUseId,
3044
- writerPayloadFor(tool, toolUseId, spelling, options), options.fixtureOptions || {});
3045
- } catch (error) {
3046
- problems.push(`${family}/${tool}: fixture or capture failed (${error.message})`);
3047
- observed.push({ family, tool, status: 'unrun', error: error.message });
3048
- continue;
3049
- }
3050
- const rawExpected = rawTargetsFromPayload(tool, result.payload);
3051
- const rawActual = tool === 'Bash' ? result.writer?.command : result.writer?.writeTargets;
3052
- if (JSON.stringify(rawActual) !== JSON.stringify(rawExpected)) {
3053
- problems.push(`${family}/${tool}: raw capture ${JSON.stringify(rawActual)} !== input spelling ${JSON.stringify(rawExpected)}`);
3054
- }
3055
- const expectedRaw = options.expectedRaw === undefined ? undefined
3056
- : options.expectedRaw === null ? null : Array.isArray(options.expectedRaw) ? options.expectedRaw : [options.expectedRaw];
3057
- if (options.expectedRaw !== undefined && JSON.stringify(result.writer?.writeTargets) !== JSON.stringify(expectedRaw)) {
3058
- problems.push(`${family}/${tool}: raw capture ${JSON.stringify(result.writer?.writeTargets)} !== ${JSON.stringify(expectedRaw)}`);
3059
- }
3060
- if (result.status === 'accepted' || result.outcome === 'pass') {
3061
- problems.push(`${family}/${tool}: expected no credit, got ${result.status}/${result.outcome}`);
3062
- }
3063
- observed.push({ family, tool, raw: tool === 'Bash' ? result.writer?.command : result.writer?.writeTargets,
3064
- status: result.status, outcome: result.outcome, codes: result.codes });
3065
- }
3066
-
3067
- const unicodeTarget = 'docs/adré/DOCS-001.md';
3068
- for (const tool of ['Write', 'Edit', 'apply_patch', 'Bash']) {
3069
- const toolUseId = `unicode-${tool}`;
3070
- const result = runCapturedWriterControl(`unicode-normalization (${tool})`, toolUseId,
3071
- writerPayloadFor(tool, toolUseId, ctx => ctx.target.normalize('NFD')),
3072
- { target: unicodeTarget, governedPattern: 'docs/adré/*.md' });
3073
- if (result.status === 'accepted' || result.outcome === 'pass') {
3074
- problems.push(`unicode-normalization/${tool}: expected no credit, got ${result.status}/${result.outcome}`);
3075
- }
3076
- observed.push({ family: 'unicode-normalization', tool, raw: tool === 'Bash' ? result.writer?.command : result.writer?.writeTargets,
3077
- equivalentPathExists: result.writer?.outlineWriteTopology?.[0]?.state === 'regular',
3078
- status: result.status, outcome: result.outcome, codes: result.codes });
3079
- }
3080
- console.log('WRITER-PATH-FAMILY-SWEEP ' + JSON.stringify(observed));
3081
- assert.deepStrictEqual(problems, [], 'writer path-family sweep');
3082
- });
3083
-
3084
- test('captured git add cannot stage unrelated content even when O commits only the pinned target', () => {
3085
- const target = 'docs/adr/DOCS-001.md';
3086
- const fixture = createOutlineFixture({ realHook: true, unrelatedFileAtB: 'unrelated.md',
3087
- preOutlineOperation: 'write', capturedOutlineCommit: true, stagedUnrelatedWitness: true,
3088
- capturedOutlineAddCommand: `git add -- ${target} unrelated.md`,
3089
- capturedOutlineAddArgs: ['add', '--', target, 'unrelated.md'],
3090
- capturedOutlineCommitCommand: 'git commit -m x', capturedOutlineCommitArgs: ['commit', '-m', 'x'] });
3091
- try {
3092
- assert.deepStrictEqual(fixture.indexAfterCapturedAdd, [target, 'unrelated.md'],
3093
- 'git diff --cached --name-only shows both modified files after the captured add');
3094
- assert.deepStrictEqual(fixture.indexAfterOutlineCommit, ['unrelated.md'],
3095
- 'git diff --cached --name-only shows unrelated content remains staged and uncommitted after O');
3096
- assert.deepStrictEqual(fixtureGit(fixture.root, ['diff', '--name-only', fixture.baselineCommit, fixture.outlineCommit]).split('\n').filter(Boolean), [target],
3097
- 'B..O commits only the pinned target');
3098
- const completed = fixture.finishDraft({ runPilot: true });
3099
- const outline = completed.pilot?.report?.outlineEvidence;
3100
- const codes = [...(completed.result.diagnostics || []), ...(outline?.diagnostics || [])]
3101
- .flatMap(item => [item.code, item.reason]).filter(Boolean);
3102
- assert.notStrictEqual(completed.result.status, 'accepted', JSON.stringify(completed.result));
3103
- assert.notStrictEqual(outline?.outcome, 'pass', JSON.stringify(outline));
3104
- assert.ok(codes.includes(WRITER_AMBIGUOUS), `expected ${WRITER_AMBIGUOUS}; got ${codes.join(', ')}`);
3105
- } finally { fixture.cleanup(); }
3106
- });
3107
-
3108
- // #341 step 1 (owner clarification 6708822276): O identity is recorded by Harness at reviewer SubagentStart and must equal
3109
- // the handoff identity at dispatch. Every control below changes O or its identity after review and must fail closed.
3110
- test('outline identity recorded at reviewer start is bound to the review and revalidated at dispatch', () => {
3111
- const identityControls = [
3112
- ['git commit --amend of O after review start', { gitAfterReview: 'amend' }],
3113
- ['O replaced by a new commit with identical target bytes after review', { gitAfterReview: 'replace' }],
3114
- ['tree mismatch at dispatch', { handoffTreeOverride: true }],
3115
- // O gains a second target after review and the handoff re-declares it: the declared scope matches, only the identity differs.
3116
- ['target path set changed after review', { gitAfterReview: 'addPath',
3117
- handoffOverrides: { targetPaths: ['docs/adr/DOCS-001.md', 'docs/adr/DOCS-002.md'] } }],
3118
- ];
3119
- const witness = [];
3120
- const problems = [];
3121
- for (const [name, options] of identityControls) {
3122
- const result = runWriterControl(name, options);
3123
- witness.push(result);
3124
- if (result.status === 'accepted') problems.push(`${name}: origin must not accept`);
3125
- if (result.outcome === 'pass') problems.push(`${name}: outline must not pass`);
3126
- if (!result.codes.includes('outline-identity-mismatch')) {
3127
- problems.push(`${name}: expected outline-identity-mismatch; got ${[...new Set(result.codes)].join(', ')}`);
3128
- }
3129
- }
3130
- const positive = runWriterControl('positive: unchanged O after review start', {});
3131
- witness.push(positive);
3132
- console.log('OUTLINE-IDENTITY-CONTROLS ' + JSON.stringify(witness.map(({ control, status, outcome, codes }) => ({ control, status, outcome, codes: [...new Set(codes)] }))));
3133
- assert.strictEqual(positive.status, 'accepted', `positive control: ${positive.codes.join(', ')}`);
3134
- assert.strictEqual(positive.outcome, 'pass', 'positive control outcome');
3135
- assert.deepStrictEqual(problems, [], 'outline identity controls');
3136
- });
3137
-
3138
- test('real capture→provider→adapter→checker→pilot discovers one outline event without injected refs', () => {
3139
- const fixture = createOutlineFixture({ realHook: true });
3140
- try {
3141
- const completed = fixture.finishDraft({ finalReview: true, runPilot: true });
3142
- const report = completed.pilot?.report;
3143
- assert.ok(report, 'pilot produced its runtime report');
3144
- assert.strictEqual(report.outlineEvidence?.outcome, 'pass', JSON.stringify(report));
3145
- assert.ok(report.acceptedRefs.some(ref => ref.endsWith('#outline-confirmation')),
3146
- 'pilot discovered the pre-tool capture reference itself');
3147
- assert.ok(report.acceptedRefs.some(ref => ref.endsWith('#quality-review')),
3148
- 'the existing final exact-D quality-review lane remains independently discoverable');
3149
- assert.strictEqual(report.pilotCredit, false, 'other B→D MUSTs remain independently unsatisfied');
3150
- } finally { fixture.cleanup(); }
3151
- });
3152
-
3153
- test('pilot compares the current Git root with an aliased pinned baseline root', () => {
3154
- const fixture = createOutlineFixture({ realHook: true });
3155
- try {
3156
- const baselineRoot = `${fixture.root}${path.sep}..${path.sep}${path.basename(fixture.root)}`;
3157
- const completed = fixture.finishDraft({ finalReview: true, runPilot: true, baselineRoot });
3158
- assert.strictEqual(completed.pilot.report.outlineEvidence?.outcome, 'pass', JSON.stringify(completed.pilot.report));
3159
- assert.ok(!completed.pilot.report.diagnostics.some(item => item.code === 'baseline-unavailable'),
3160
- 'equivalent root spellings do not make the baseline unavailable');
3161
- } finally { fixture.cleanup(); }
3162
- });
3163
-
3164
- test('scope-preserving D edits keep outline approval but stale final review cannot transfer to new bytes', () => {
3165
- const fixture = createOutlineFixture({ realHook: true });
3166
- try {
3167
- const completed = fixture.finishDraft({ finalReview: true, mutateAfterFinalReview: true, runPilot: true });
3168
- const report = completed.pilot.report;
3169
- assert.strictEqual(report.outlineEvidence?.outcome, 'pass');
3170
- assert.ok(report.acceptedRefs.some(ref => ref.endsWith('#outline-confirmation')));
3171
- assert.ok(!report.acceptedRefs.some(ref => ref.endsWith('#quality-review')),
3172
- 'the prior review digest does not bind changed final D bytes');
3173
- assert.strictEqual(report.pilotCredit, false);
3174
- } finally { fixture.cleanup(); }
3175
- });
3176
-
3177
- test('legacy session-dir keying stays aligned through an aliased workspace root', () => {
3178
- const unavailable = symlinkUnavailable('dir');
3179
- if (unavailable) return { unchecked: `directory symlink creation is unavailable (${unavailable})` };
3180
- function driveAliasRootScenario() {
3181
- const realRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'prb-session-root-'));
3182
- const aliasRoot = `${realRoot}-alias`;
3183
- const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), 'prb-session-state-'));
3184
- const sessionId = 'prb-alias-session';
3185
- const preload = path.join(stateHome, 'realpath-alias.js');
3186
- fs.symlinkSync(realRoot, aliasRoot, 'dir');
3187
- writeJson(path.join(stateHome, 'session-workspaces', `${sha(sessionId)}.json`), {
3188
- version: 1, sessionId, workspaceRoot: aliasRoot,
3189
- });
3190
- fs.writeFileSync(preload, [
3191
- "const fs=require('fs');",
3192
- "const path=require('path');",
3193
- 'const original=fs.realpathSync;',
3194
- 'const alias=path.resolve(process.env.PRB_TEST_ALIAS_ROOT);',
3195
- 'function realpathSync(target,...args){',
3196
- ' if(typeof target==="string"&&path.resolve(target)===alias)return alias;',
3197
- ' return original.call(fs,target,...args);',
3198
- '}',
3199
- 'realpathSync.native=original.native;',
3200
- 'fs.realpathSync=realpathSync;',
3201
- ].join('\n'));
3202
-
3203
- const previousStateHome = process.env.HARNESS_STATE_HOME;
3204
- const originalRealpathSync = fs.realpathSync;
3205
- let aliasSessionDir;
3206
- let canonicalSessionDir;
3207
- try {
3208
- process.env.HARNESS_STATE_HOME = stateHome;
3209
- fs.realpathSync = function realpathSync(target, ...args) {
3210
- if (typeof target === 'string' && path.resolve(target) === path.resolve(aliasRoot)) return path.resolve(aliasRoot);
3211
- return originalRealpathSync.call(fs, target, ...args);
3212
- };
3213
- fs.realpathSync.native = originalRealpathSync.native;
3214
- const { getSessionDir } = require(path.join(ROOT, 'hooks/scripts/lib/harness-state.js'));
3215
- aliasSessionDir = getSessionDir(aliasRoot, sessionId);
3216
- canonicalSessionDir = getSessionDir(realRoot, sessionId);
3217
- } finally {
3218
- fs.realpathSync = originalRealpathSync;
3219
- if (previousStateHome === undefined) delete process.env.HARNESS_STATE_HOME;
3220
- else process.env.HARNESS_STATE_HOME = previousStateHome;
3221
- }
3222
-
3223
- const env = {
3224
- ...process.env,
3225
- HARNESS_STATE_HOME: stateHome,
3226
- HARNESS_WORKSPACE_ROOT: aliasRoot,
3227
- HARNESS_DOC_RECONCILIATION_PILOT: '0',
3228
- PRB_TEST_ALIAS_ROOT: aliasRoot,
3229
- };
3230
- const runHook = (relative, payload, pilotEnabled = false) => spawnSync(process.execPath,
3231
- ['--require', preload, path.join(ROOT, relative)], {
3232
- cwd: aliasRoot,
3233
- input: JSON.stringify(payload),
3234
- encoding: 'utf8',
3235
- env: { ...env, HARNESS_DOC_RECONCILIATION_PILOT: pilotEnabled ? '1' : '0' },
3236
- });
3237
-
3238
- try {
3239
- const legacy = runHook('hooks/scripts/state-persist.js', {
3240
- hook_event_name: 'PostToolUse', session_id: sessionId, cwd: aliasRoot,
3241
- tool_name: 'Bash', tool_input: { command: 'echo legacy-state-probe' },
3242
- tool_response: { exitCode: 0, stdout: '', stderr: '' },
3243
- });
3244
- const pilotOffCaptureCount = provider.readCaptureView(aliasSessionDir).records.length
3245
- + provider.readCaptureView(canonicalSessionDir).records.length;
3246
- const pilot = runHook('hooks/scripts/state-persist.js', {
3247
- hook_event_name: 'PreToolUse', session_id: sessionId, cwd: aliasRoot,
3248
- tool_name: 'Agent', tool_use_id: 'pilot-alias-capture', agent_type: 'worker',
3249
- tool_input: { prompt: 'alias capture probe' },
3250
- }, true);
3251
- assert.strictEqual(legacy.status, 0, `pilot-OFF state-persist must remain fail-open: ${legacy.stderr}`);
3252
- assert.strictEqual(pilot.status, 0, `pilot capture must remain fail-open: ${pilot.stderr}`);
3253
- return {
3254
- legacyExit: legacy.status,
3255
- pilotOffCaptureCount,
3256
- handoffInAliasSession: fs.existsSync(path.join(aliasSessionDir, 'handoff-state.json')),
3257
- handoffInCanonicalSession: fs.existsSync(path.join(canonicalSessionDir, 'handoff-state.json')),
3258
- pilotCaptureInAliasSession: provider.readCaptureView(aliasSessionDir).records.some(item => item.tool_use_id === 'pilot-alias-capture'),
3259
- pilotCaptureInCanonicalSession: provider.readCaptureView(canonicalSessionDir).records.some(item => item.tool_use_id === 'pilot-alias-capture'),
3260
- };
3261
- } finally {
3262
- fs.rmSync(stateHome, { recursive: true, force: true });
3263
- fs.rmSync(aliasRoot, { force: true });
3264
- fs.rmSync(realRoot, { recursive: true, force: true });
3265
- }
3266
- }
3267
-
3268
- const first = driveAliasRootScenario();
3269
- const second = driveAliasRootScenario();
3270
- assert.deepStrictEqual(first, second, 'identical alias-root inputs must produce the same normalized state and exits');
3271
- assert.strictEqual(first.legacyExit, 0, 'pilot OFF remains fail-open');
3272
- assert.strictEqual(first.pilotOffCaptureCount, 0, 'pilot OFF writes no capture record');
3273
- assert.deepStrictEqual({
3274
- handoffInAliasSession: first.handoffInAliasSession,
3275
- handoffInCanonicalSession: first.handoffInCanonicalSession,
3276
- pilotCaptureInAliasSession: first.pilotCaptureInAliasSession,
3277
- pilotCaptureInCanonicalSession: first.pilotCaptureInCanonicalSession,
3278
- }, {
3279
- handoffInAliasSession: true,
3280
- handoffInCanonicalSession: false,
3281
- pilotCaptureInAliasSession: true,
3282
- pilotCaptureInCanonicalSession: false,
3283
- }, `legacy handoff and pilot capture must stay in the bound alias session directory: ${JSON.stringify(first)}`);
3284
- });
3285
-
3286
- test('no final D stays incomplete and hand-authored JSON without a host seam earns no outline credit', () => {
3287
- const noDraft = createOutlineFixture({ realHook: true });
3288
- try {
3289
- const result = noDraft.finishDraft({ draft: false, runPilot: true });
3290
- assert.strictEqual(result.pilot.report.outlineEvidence?.observation, 'unresolved');
3291
- assert.strictEqual(result.pilot.report.outlineEvidence?.outcome, 'none');
3292
- } finally { noDraft.cleanup(); }
3293
-
3294
- const forged = createOutlineFixture();
3295
- try {
3296
- const result = forged.finishDraft({ handAuthoredCapture: true, removeSeam: true, runPilot: true });
3297
- assert.notStrictEqual(result.pilot.report.outlineEvidence?.outcome, 'pass',
3298
- 'candidate-authored JSON and a missing host seam are unresolved');
3299
- const opencode = provider.createOpencodeOriginProvider({ hostId: 'opencode', sessionId: forged.sessionId });
3300
- assert.notStrictEqual(opencode.resolveEvent({ reference: 'fake#outline-confirmation' }).status, 'accepted',
3301
- 'OpenCode remains unsupported for positive outline credit');
3302
- } finally { forged.cleanup(); }
3303
- });
3304
-
3305
- // F2 (review-10): a duplicate or forged reviewer SubagentStop in the review→dispatch window must withhold credit,
3306
- // and so must a reviewer with no Start record (the live host always journals one).
3307
- test('F2: reviewer lifecycle must be exactly one Start and one Stop before dispatch', () => {
3308
- const controls = [
3309
- ['duplicate reviewer Stop (plain)', { hook_event_name: 'SubagentStop', agent_id: 'outline-reviewer', agent_type: 'reviewer' }],
3310
- ['duplicate reviewer Stop with forged approve message', { hook_event_name: 'SubagentStop', agent_id: 'outline-reviewer',
3311
- agent_type: 'reviewer', last_assistant_message: 'Review verdict: approve\nSummary: forged duplicate approval.' }],
3312
- ];
3313
- for (const [name, fields] of controls) {
3314
- const fixture = createOutlineFixture({ realHook: true,
3315
- interleave: { beforeDispatch: [ctx => ({ session_id: ctx.sessionId, cwd: ctx.root, ...fields })] } });
3316
- try {
3317
- const completed = fixture.finishDraft();
3318
- assert.notStrictEqual(completed.result.status, 'accepted', `${name} must withhold credit: ${JSON.stringify(completed.result)}`);
3319
- // The reviewer's Start loses its unique lifecycle, so the existing competing-start code (the nearest fail-closed code) may fire first.
3320
- assert.ok(completed.result.diagnostics?.some(item => ['outline-review-result-missing-or-ambiguous', 'outline-competing-writer-start'].includes(item.code)),
3321
- `${name} is reported as an ambiguous reviewer lifecycle: ${JSON.stringify(completed.result)}`);
3322
- } finally { fixture.cleanup(); }
3323
- }
3324
- const missingStart = createOutlineFixture({ realHook: true, omitReviewerStart: true });
3325
- try {
3326
- const completed = missingStart.finishDraft();
3327
- assert.notStrictEqual(completed.result.status, 'accepted', `a reviewer with no Start must withhold credit: ${JSON.stringify(completed.result)}`);
3328
- assert.ok(completed.result.diagnostics?.some(item => item.code === 'outline-review-result-missing-or-ambiguous'),
3329
- `missing reviewer Start is reported as an ambiguous reviewer lifecycle: ${JSON.stringify(completed.result)}`);
3330
- } finally { missingStart.cleanup(); }
3331
- const positive = createOutlineFixture({ realHook: true });
3332
- try {
3333
- assert.strictEqual(positive.finishDraft().result.status, 'accepted', 'positive control: one Start and one Stop earns credit');
3334
- } finally { positive.cleanup(); }
3335
- });
3336
-
3337
- // F4 (review-10): every commit in B..O must touch only the pinned target; a non-target commit later reverted inside
3338
- // the range is invisible to the cumulative B..O diff and must be rejected per commit.
3339
- test('F4: every commit in B..O touches only the pinned target, even when later reverted', () => {
3340
- const reverted = createOutlineFixture({ realHook: true, revertedExtraOutlineCommit: 'scratch/notes.txt' });
3341
- try {
3342
- const completed = reverted.finishDraft();
3343
- assert.notStrictEqual(completed.result.status, 'accepted', `a reverted non-target commit in B..O must not earn credit: ${JSON.stringify(completed.result)}`);
3344
- assert.ok(completed.result.diagnostics?.some(item => item.code === 'outline-commit-scope-invalid'),
3345
- `the reverted range is reported as outline-commit-scope-invalid: ${JSON.stringify(completed.result)}`);
3346
- } finally { reverted.cleanup(); }
3347
- const clean = createOutlineFixture({ realHook: true });
3348
- try {
3349
- assert.strictEqual(clean.finishDraft().result.status, 'accepted', 'positive control: a target-only O range earns credit');
3350
- } finally { clean.cleanup(); }
3351
- });
169
+ }
3352
170
 
3353
171
  if (failures.length) {
3354
- console.error(`\n${failures.length} PR-B RED assertion(s) failed.`);
172
+ console.error(`\n${failures.length} PR-B workspace-alias assertion(s) failed.`);
3355
173
  process.exitCode = 1;
3356
174
  } else {
3357
- console.log('\nAll PR-B outline mechanism checks passed.');
175
+ console.log('\nAll PR-B workspace-alias mechanism checks passed.');
3358
176
  }