@skathio/somi 2.2.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +8 -2
  3. package/.copilot-extension/extension.json +9 -8
  4. package/.copilot-extension/marketplace.json +2 -2
  5. package/README.md +45 -33
  6. package/VERSION +1 -1
  7. package/agents/architecture-reviewer.md +16 -0
  8. package/agents/atlas.md +102 -0
  9. package/agents/coder.md +66 -22
  10. package/agents/designer.md +20 -16
  11. package/agents/discovery-analyst.md +6 -5
  12. package/agents/impact.md +97 -0
  13. package/agents/incident.md +96 -0
  14. package/agents/plan-reviewer.md +70 -0
  15. package/agents/planner.md +77 -20
  16. package/agents/pr.md +101 -0
  17. package/agents/refactor-designer.md +82 -0
  18. package/agents/refactorer.md +30 -24
  19. package/agents/reviewer.md +28 -25
  20. package/agents/sdlc-reviewer.md +69 -0
  21. package/agents/security-reviewer.md +17 -0
  22. package/agents/somi.md +204 -153
  23. package/agents/test-strategist.md +16 -1
  24. package/commands/adopt.md +21 -7
  25. package/commands/architecture-review.md +8 -5
  26. package/commands/atlas.md +24 -72
  27. package/commands/code-loop.md +46 -15
  28. package/commands/code-parallel.md +6 -4
  29. package/commands/code.md +29 -21
  30. package/commands/debug.md +17 -11
  31. package/commands/design.md +48 -31
  32. package/commands/discover.md +26 -16
  33. package/commands/impact.md +16 -54
  34. package/commands/incident.md +22 -55
  35. package/commands/plan-loop.md +43 -17
  36. package/commands/plan.md +64 -26
  37. package/commands/pr.md +19 -66
  38. package/commands/refactor-design.md +98 -0
  39. package/commands/refactor.md +22 -23
  40. package/commands/release-readiness.md +16 -7
  41. package/commands/review-panel.md +31 -10
  42. package/commands/review.md +21 -14
  43. package/commands/security-review.md +12 -3
  44. package/commands/ship-loop.md +71 -54
  45. package/commands/ship.md +17 -13
  46. package/commands/test-strategy.md +6 -4
  47. package/commands/upgrade.md +10 -8
  48. package/examples/discovery-example.md +2 -2
  49. package/examples/sample-consumer/CLAUDE.md +41 -7
  50. package/examples/sample-consumer/README.md +36 -22
  51. package/hooks/lib/common.mjs +66 -20
  52. package/hooks/post-tool/audit-log.mjs +7 -11
  53. package/hooks/post-tool/lint-changed-files.mjs +8 -11
  54. package/hooks/pre-tool/block-dangerous-bash.mjs +32 -44
  55. package/hooks/pre-tool/block-secret-writes.mjs +6 -9
  56. package/hooks/pre-tool/gate-dep-install.mjs +18 -27
  57. package/hooks/pre-tool/guard-protected-paths.mjs +9 -11
  58. package/hooks/session-start/detect-repo-instructions.mjs +21 -23
  59. package/hooks/user-prompt-submit/inject-workflow-context.mjs +190 -42
  60. package/mcp.json +10 -0
  61. package/package.json +5 -2
  62. package/rules/CLAUDE.md +22 -19
  63. package/scripts/check-links.mjs +218 -0
  64. package/scripts/check-session-artefacts.mjs +149 -0
  65. package/scripts/check-size-budget.mjs +137 -0
  66. package/scripts/generate-digest.mjs +176 -0
  67. package/scripts/lib/cost-ceiling.mjs +317 -0
  68. package/scripts/lib/cost-model.mjs +95 -0
  69. package/scripts/lib/dispatch-resolver.mjs +224 -0
  70. package/scripts/lib/mcp-project-root.mjs +183 -0
  71. package/scripts/size-budget-overrides.json +74 -0
  72. package/scripts/somi-check.mjs +6 -13
  73. package/scripts/somi-dispatch.mjs +141 -0
  74. package/scripts/somi-findings.mjs +4 -5
  75. package/scripts/somi-loop.mjs +181 -13
  76. package/scripts/somi-mcp.mjs +357 -0
  77. package/scripts/validate.sh +690 -29
  78. package/skills/clean-code/SKILL.md +1 -1
  79. package/skills/plan-review/SKILL.md +79 -0
  80. package/skills/rules/SKILL.md +47 -0
  81. package/skills/sdlc-process/SKILL.md +74 -0
  82. package/skills/somi-dispatch/SKILL.md +220 -0
  83. package/skills/somi-routing/SKILL.md +31 -6
  84. package/skills/{test-strategy → testing-playbook}/SKILL.md +1 -1
  85. package/templates/ATLAS.md.tmpl +4 -4
  86. package/templates/BRIEF.md.tmpl +23 -22
  87. package/templates/DECISIONS.md.tmpl +1 -0
  88. package/templates/DESIGN.md.tmpl +5 -5
  89. package/templates/DIARY.md.tmpl +10 -5
  90. package/templates/DOD.md.tmpl +24 -0
  91. package/templates/PROGRESS.md.tmpl +3 -16
  92. package/templates/SOMI-README.md.tmpl +3 -3
  93. package/tests/hooks/cases/inject-workflow-context.json +120 -7
  94. package/tests/hooks/run.sh +20 -11
  95. package/tests/scripts/check-links.sh +105 -0
  96. package/tests/scripts/check-session-artefacts.sh +60 -0
  97. package/tests/scripts/check-size-budget.sh +71 -0
  98. package/tests/scripts/checkpoint-gate.sh +90 -0
  99. package/tests/scripts/convergence-runner.sh +1510 -0
  100. package/tests/scripts/cost-ceiling.sh +343 -0
  101. package/tests/scripts/cost-model.sh +192 -0
  102. package/tests/scripts/dispatch-guard.sh +108 -0
  103. package/tests/scripts/dispatch-reference-gate.sh +173 -0
  104. package/tests/scripts/eval-runner.sh +3691 -0
  105. package/tests/scripts/evals-packaging.sh +117 -0
  106. package/tests/scripts/fixtures/legacy-shard-no-schema.json +50 -0
  107. package/tests/scripts/generate-digest.sh +180 -0
  108. package/tests/scripts/goldens/loop-state-breach.json +1 -0
  109. package/tests/scripts/goldens/loop-state-done.json +1 -0
  110. package/tests/scripts/goldens/somi-loop.json +1 -1
  111. package/tests/scripts/lib/adr-shape.mjs +41 -0
  112. package/tests/scripts/lib/checkpoint-gate.mjs +54 -0
  113. package/tests/scripts/lib/digest-marker-coupling.mjs +52 -0
  114. package/tests/scripts/lib/dispatch-reference-gate.mjs +112 -0
  115. package/tests/scripts/lib/multipass-dependence.mjs +192 -0
  116. package/tests/scripts/lib/multipass-source-identity.mjs +243 -0
  117. package/tests/scripts/lib/reference-pair.mjs +61 -0
  118. package/tests/scripts/lib/retirement-gate.mjs +167 -0
  119. package/tests/scripts/lib/shell-embedded-js.mjs +47 -0
  120. package/tests/scripts/lib/somi-mcp-client.mjs +102 -0
  121. package/tests/scripts/lib/somi-mcp-tests.mjs +401 -0
  122. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +38 -0
  123. package/tests/scripts/retirement-gate.sh +287 -0
  124. package/tests/scripts/review-panel-seats.sh +32 -0
  125. package/tests/scripts/run.sh +184 -2
  126. package/tests/scripts/somi-agent-dispatch-contract.sh +195 -0
  127. package/tests/scripts/somi-dispatch.sh +354 -0
  128. package/tests/scripts/somi-mcp.sh +12 -0
@@ -0,0 +1,1510 @@
1
+ #!/usr/bin/env bash
2
+ # Unit guard for tests/evals/convergence.mjs's CLI section: argument
3
+ # parsing, --dry-run's shape/zero-model-call contract, --merge/--certify's shard-fold report, and
4
+ # the sha boundary check.
5
+ #
6
+ # Hermetic by construction: every case here is --dry-run, --merge/--certify (read-only, no
7
+ # --source resolution, no credential), or a direct call into an exported CLI helper -- never a
8
+ # live /code-loop draw. eval-runner.sh already covers the non-CLI logic (the extractor, the
9
+ # rank test, classifyDraw/fillArm/compareArms/the shard/resume layer); this file is scoped to what
10
+ # the CLI alone adds, so the two stay disjoint rather than duplicating each other.
11
+ #
12
+ # Exception: terminalVerdict()/writeNextShard()'s new
13
+ # `verdict` param/makeShardWriter() are shard/resume-layer additions, eval-runner.sh's stated home
14
+ # -- pinned here instead because the scope here was exactly these three files, not
15
+ # eval-runner.sh. Still fully hermetic (synthetic loop-state objects and scratch shas only, per
16
+ # this pass's own instruction not to spend a live draw), so it belongs with everything else in
17
+ # this file that shares that property, disjointness convention notwithstanding.
18
+ set -uo pipefail
19
+
20
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
21
+ cd "$ROOT"
22
+ CVD=tests/evals/convergence.mjs
23
+ pass=0; fail=0
24
+ ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }
25
+ bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
26
+ check(){ if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (want '$3', got '$2')"; fi; }
27
+
28
+ # Run a snippet with convergence.mjs imported as `M` -- same idiom eval-runner.sh's own `cj()`
29
+ # uses for lib/convergence.mjs, kept as a function so no case can forget the import path.
30
+ cj() { node --input-type=module -e "const M = await import('$ROOT/$CVD'); $1" 2>&1; }
31
+
32
+ echo "== convergence gate CLI (3.4) =="
33
+
34
+ # --- sha is a documented CLI input surface now; validateSha() is the boundary check ------
35
+ # `sha` reaches join() inside loopShardPath()/loopShardDir() unvalidated -- these cases pin the
36
+ # boundary check itself, both directions (a gate's suite must not only catch the bad
37
+ # input, it must also let a genuinely conforming one through).
38
+ check "validateSha accepts a real (40-char) git sha" \
39
+ "$(cj "process.stdout.write(M.validateSha('7c0ac2615fe6a14e3135d645645c59f1e38bd3bf'))")" \
40
+ "7c0ac2615fe6a14e3135d645645c59f1e38bd3bf"
41
+ check "validateSha accepts a short (7-char) sha, git's own minimum" \
42
+ "$(cj "process.stdout.write(M.validateSha('7c0ac26'))")" "7c0ac26"
43
+
44
+ f251_rejects() {
45
+ local got
46
+ got=$(cj "try { M.validateSha($2); process.stdout.write('NO THROW'); } catch { process.stdout.write('threw'); }")
47
+ check "validateSha rejects $1" "$got" "threw"
48
+ }
49
+ f251_rejects "a path-traversal attempt" "'../../../etc/passwd'"
50
+ f251_rejects "an absolute path" "'/etc/passwd'"
51
+ f251_rejects "uppercase hex (git shas print lowercase)" "'ABCDEF1'"
52
+ f251_rejects "a sha shorter than 7 chars" "'abc12'"
53
+ LONG41=$(printf 'a%.0s' $(seq 1 41))
54
+ f251_rejects "a sha longer than 40 chars" "'$LONG41'"
55
+ f251_rejects "a non-string" "42"
56
+ f251_rejects "null" "null"
57
+
58
+ # The underlying primitive has no traversal protection of its own -- proving WHY the boundary
59
+ # check has to exist, not just that it does: loopShardPath()/loopShardDir() join() sha straight
60
+ # into a path with no sanitising. Demonstrated by resolving the path a traversal sha WOULD
61
+ # produce and confirming it lands outside results/ -- read-only (path.resolve, no file touched).
62
+ escape_check=$(cj "
63
+ const path = await import('node:path');
64
+ const p = path.resolve(M.loopShardPath('../../../tmp/f251-probe', M.TASK_ID, 0));
65
+ const resultsDir = path.resolve('$ROOT/tests/evals/results');
66
+ process.stdout.write(String(!p.startsWith(resultsDir + path.sep)));
67
+ ")
68
+ check "loopShardPath() itself has no traversal guard -- a raw '../../../tmp/f251-probe' sha resolves OUTSIDE results/ (this is what validateSha() at the CLI boundary exists to prevent)" \
69
+ "$escape_check" "true"
70
+
71
+ # Staged against a SCRATCH COPY, never the tracked file: neuter validateSha()'s own
72
+ # regex test so it can never throw, then drive the REAL CLI entrypoint (`--merge`) against it with
73
+ # the same traversal string above. The mutant must reach loopShardPath() with the traversal intact
74
+ # -- caught by checking the mutant's own reportArm() computes a path outside results/, the exact
75
+ # consequence the boundary check exists to prevent. Reverting restores the guard; the pristine file is checked last so this
76
+ # suite ends by re-confirming the shipped behaviour, not the mutant's.
77
+ F251_SCRATCH_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
78
+ trap 'rm -rf "$F251_SCRATCH_DIR"' EXIT
79
+ F251_SCRATCH="$F251_SCRATCH_DIR/convergence.mjs"
80
+ cp "$ROOT/$CVD" "$F251_SCRATCH"
81
+ ln -s "$ROOT/tests/evals/lib" "$F251_SCRATCH_DIR/lib"
82
+ ln -s "$ROOT/tests/evals/run.mjs" "$F251_SCRATCH_DIR/run.mjs"
83
+ node -e "
84
+ const fs = require('fs'); const p = '$F251_SCRATCH'; const s = fs.readFileSync(p, 'utf8');
85
+ const FROM = \"if (typeof sha !== 'string' || !/^[0-9a-f]{7,40}\$/.test(sha)) {\";
86
+ const TO = 'if (false) { // MUTANT (F-251): the boundary check never fires';
87
+ if (!s.includes(FROM)) throw new Error('F-251 mutant pattern not found in convergence.mjs -- source moved, update this mutation');
88
+ fs.writeFileSync(p, s.replace(FROM, TO));
89
+ "
90
+ mutant_escape=$(node --input-type=module -e "
91
+ const M = await import('$F251_SCRATCH');
92
+ const path = await import('node:path');
93
+ const p = path.resolve(M.loopShardPath(M.validateSha('../../../tmp/f251-probe'), M.TASK_ID, 0));
94
+ const resultsDir = path.resolve('$ROOT/tests/evals/results');
95
+ process.stdout.write(String(!p.startsWith(resultsDir + path.sep)));
96
+ " 2>&1)
97
+ check "mutant (F-251: validateSha() neutered) lets a traversal sha through to loopShardPath() unrejected, landing outside results/" \
98
+ "$mutant_escape" "true"
99
+ pristine_rejects=$(cj "try { M.validateSha('../../../tmp/f251-probe'); process.stdout.write('NO THROW'); } catch { process.stdout.write('threw'); }")
100
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still rejects the same traversal sha" \
101
+ "$pristine_rejects" "threw"
102
+ rm -rf "$F251_SCRATCH_DIR"
103
+ trap - EXIT
104
+
105
+ # --- --dry-run: well-formed shape, mirroring run.mjs --dry-run's own contract -------------------
106
+ dryrun_out=$(node "$CVD" --dry-run --source HEAD)
107
+ dryrun_check=$(printf '%s' "$dryrun_out" | node -e "
108
+ let s=''; process.stdin.on('data', d=>s+=d).on('end', () => {
109
+ const o = JSON.parse(s);
110
+ const ok = o.dryRun === true && o.taskId === 'loop-code-loop' && Array.isArray(o.arm) && o.arm.length === 0
111
+ && o.breach === false && o.runsRequested === 15 && typeof o.source.sha === 'string' && o.source.sha.length === 40
112
+ && o.maxWaitAttempts === 2;
113
+ process.stdout.write(String(ok));
114
+ });
115
+ ")
116
+ check "--dry-run produces a well-formed shape (dryRun:true, empty arm, breach:false, a real resolved sha, maxWaitAttempts echoing DEFAULT_MAX_WAIT_ATTEMPTS)" "$dryrun_check" "true"
117
+ check "--dry-run --runs 5 threads the requested count through" \
118
+ "$(node "$CVD" --dry-run --source HEAD --runs 5 | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>process.stdout.write(String(JSON.parse(s).runsRequested)))")" \
119
+ "5"
120
+
121
+ # --- --dry-run echoes the wait budget a live draw would actually use -- previously silent
122
+ # on it, so nothing confirmed a --max-wait-attempts value (or the implied default above) was the
123
+ # one that would apply before spending quota on the real draw.
124
+ check "--dry-run --max-wait-attempts 6 echoes the SUPPLIED value, not the default" \
125
+ "$(node "$CVD" --dry-run --source HEAD --max-wait-attempts 6 | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>process.stdout.write(String(JSON.parse(s).maxWaitAttempts)))")" \
126
+ "6"
127
+
128
+ # Mutation: prove the dry-run echo can actually fail to reflect the real value. Staged on a scratch
129
+ # copy, never the tracked file. Unversioned source (--source ., sha null) so this stays hermetic
130
+ # and quick, the same choice the fixture-pin mutation test below makes for the same reason.
131
+ F300_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
132
+ trap 'rm -rf "$F300_MUT_DIR"' EXIT
133
+ F300_MUT="$F300_MUT_DIR/convergence.mjs"
134
+ cp "$ROOT/$CVD" "$F300_MUT"
135
+ ln -s "$ROOT/tests/evals/lib" "$F300_MUT_DIR/lib"
136
+ ln -s "$ROOT/tests/evals/run.mjs" "$F300_MUT_DIR/run.mjs"
137
+ node -e "
138
+ const fs = require('fs'); const p = '$F300_MUT'; const s = fs.readFileSync(p, 'utf8');
139
+ const FROM = 'maxWaitAttempts: args.maxWaitAttempts ?? DEFAULT_MAX_WAIT_ATTEMPTS,';
140
+ const TO = 'maxWaitAttempts: null, // MUTANT (F-300): dry-run no longer echoes the wait budget';
141
+ if (!s.includes(FROM)) throw new Error('F-300 mutant pattern not found in convergence.mjs -- source moved, update this mutation');
142
+ fs.writeFileSync(p, s.replace(FROM, TO));
143
+ "
144
+ mutant_dryrun_wait=$(node "$F300_MUT" --dry-run --source . --max-wait-attempts 6 | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>process.stdout.write(String(JSON.parse(s).maxWaitAttempts)))")
145
+ check "mutant (F-300: dry-run maxWaitAttempts forced null) no longer echoes the supplied --max-wait-attempts 6, catching the regression the checks above exist for" \
146
+ "$mutant_dryrun_wait" "null"
147
+ pristine_dryrun_wait=$(node "$CVD" --dry-run --source . --max-wait-attempts 6 | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>process.stdout.write(String(JSON.parse(s).maxWaitAttempts)))")
148
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still echoes maxWaitAttempts:6" \
149
+ "$pristine_dryrun_wait" "6"
150
+ rm -rf "$F300_MUT_DIR"
151
+ trap - EXIT
152
+
153
+ # --dry-run leaves no worktree behind (resolveSource's own cleanup, exercised through this CLI).
154
+ wt_before=$(git worktree list | wc -l | tr -d ' ')
155
+ node "$CVD" --dry-run --source HEAD >/dev/null
156
+ wt_after=$(git worktree list | wc -l | tr -d ' ')
157
+ check "--dry-run cleans up its resolved worktree (no leak)" "$wt_after" "$wt_before"
158
+
159
+ # --- --dry-run: zero model calls, proven by execution (the same technique as eval-runner.sh), not by reading ---
160
+ # A stub `claude` on PATH proves NO route reaches the model -- not just that reading the dry-run
161
+ # branch shows no invokeCommand() call.
162
+ stub_bin=$(mktemp -d)
163
+ stub_sentinel="$stub_bin/touched"
164
+ printf '#!/bin/sh\n%s "%s"\nexit 1\n' "$(command -v touch)" "$stub_sentinel" > "$stub_bin/claude"
165
+ chmod +x "$stub_bin/claude"
166
+ PATH="$stub_bin:$PATH" node "$CVD" --dry-run --source HEAD >/dev/null 2>&1
167
+ check "no route from --dry-run reaches a stub claude on PATH (sentinel stays absent)" \
168
+ "$([ -e "$stub_sentinel" ] && echo TOUCHED || echo ABSENT)" "ABSENT"
169
+ # Positive control (same technique as eval-runner.sh): proves the stub is reachable on PATH at all.
170
+ PATH="$stub_bin" claude >/dev/null 2>&1
171
+ check "positive control: claude invoked directly under the same stub touches the sentinel" \
172
+ "$([ -e "$stub_sentinel" ] && echo TOUCHED || echo ABSENT)" "TOUCHED"
173
+ rm -rf "$stub_bin"
174
+
175
+ # --- live mode preflights BEFORE resolveSource's worktree checkout ------------------------------
176
+ # Simulated by stripping PATH/HOME so neither the CLI nor a credential resolves (the same technique as
177
+ # eval-runner.sh), never by mocking preflight() itself. A worktree created despite this would
178
+ # mean the CLI paid for a checkout it could never use.
179
+ NODE_BIN=$(command -v node)
180
+ wt_before2=$(git worktree list | wc -l | tr -d ' ')
181
+ preflight_msg=$(env -i "PATH=$(dirname "$NODE_BIN")" HOME=/nonexistent "$NODE_BIN" "$CVD" --source HEAD --runs 1 2>&1)
182
+ wt_after2=$(git worktree list | wc -l | tr -d ' ')
183
+ case "$preflight_msg" in
184
+ *"not ready to draw"*) ok "live mode preflights before spending any quota (message names the reason)" ;;
185
+ *) bad "live mode preflights before spending any quota (got: ${preflight_msg:0:120})" ;;
186
+ esac
187
+ check "the preflight failure above never reached resolveSource -- no worktree was created" "$wt_after2" "$wt_before2"
188
+
189
+ # --- --merge / --certify: fold shards already on disk, no live draw -----------------------------
190
+ MERGE_SHA="deadbeefcafe1234567890"
191
+ cj "
192
+ const occ = new Set();
193
+ M.writeNextShard('$MERGE_SHA', M.TASK_ID, 15, occ, 0, 2);
194
+ M.writeNextShard('$MERGE_SHA', M.TASK_ID, 15, occ, 1, 3);
195
+ M.writeNextShard('$MERGE_SHA', M.TASK_ID, 15, occ, 2, 1);
196
+ " >/dev/null
197
+ merge_out=$(node "$CVD" --merge "$MERGE_SHA" --runs 15)
198
+ check "--merge folds 3 shards into an arm of 3 usable draws" \
199
+ "$(printf '%s' "$merge_out" | grep -c '^deadbeefcafe: 3/15 usable draw(s) on disk$')" "1"
200
+ check "--merge computes the arm's mean correctly ([2,3,1] -> 2.0000)" \
201
+ "$(printf '%s' "$merge_out" | grep -c 'mean: 2.0000$')" "1"
202
+ check "--merge computes the arm's sample sd correctly ([2,3,1], n-1 denominator -> 1.0000)" \
203
+ "$(printf '%s' "$merge_out" | grep -c 'sd: 1.0000$')" "1"
204
+ certify_out=$(node "$CVD" --certify "$MERGE_SHA" --runs 15)
205
+ check "--certify is the SAME report as --merge (folding IS the report, no second scope here)" \
206
+ "$certify_out" "$merge_out"
207
+ rm -rf "$ROOT/tests/evals/results/$MERGE_SHA"
208
+
209
+ check "--merge on a sha with zero shards on disk reports 0/N, mean/sd n/a rather than throwing" \
210
+ "$(node "$CVD" --merge deadbeef00 --runs 15 | tr '\n' '|')" \
211
+ "deadbeef00: 0/15 usable draw(s) on disk| arm: []| mean: n/a| sd: n/a (need >= 2 draws)|"
212
+
213
+ check "--merge with an invalid sha is rejected before anything is read (F-251, at the CLI itself)" \
214
+ "$(node "$CVD" --merge '../../../etc/passwd' >/dev/null 2>&1; echo $?)" "1"
215
+
216
+ # --- shards carry the loop's terminal verdict alongside its pass count -------------------
217
+ # The first live batch showed task02-code sitting at
218
+ # the pass-count floor (arm [1,1,1], mean 1.0, sd 0.0) with no retained artifact able to say WHY
219
+ # -- the shard carried only `pass`, and cleanup() correctly destroys the workDir the
220
+ # instant a draw completes. terminalVerdict() (lib/convergence.mjs) is the read side;
221
+ # writeNextShard()'s new `verdict` param and makeShardWriter() (this module) are the write side
222
+ # that threads it into the shard.
223
+ LCONV=tests/evals/lib/convergence.mjs
224
+ lj() { node --input-type=module -e "const L = await import('$ROOT/$LCONV'); $1" 2>&1; }
225
+
226
+ # terminalVerdict() fails safe, same posture as passesToApprove()/capBreached() -- those two's own
227
+ # extractor-level tests live in eval-runner.sh's extractor section; terminalVerdict() is pinned here
228
+ # instead per this file's own exception above.
229
+ check "terminalVerdict(null) is null (fails safe)" \
230
+ "$(lj "process.stdout.write(String(L.terminalVerdict(null)));")" "null"
231
+ check "terminalVerdict(undefined) is null" \
232
+ "$(lj "process.stdout.write(String(L.terminalVerdict(undefined)));")" "null"
233
+ check "terminalVerdict(42) is null (non-object input, not coerced)" \
234
+ "$(lj "process.stdout.write(String(L.terminalVerdict(42)));")" "null"
235
+ check "terminalVerdict({}) is null (no history field at all -- the three real F-266 shards' own shape, pre-F-267)" \
236
+ "$(lj "process.stdout.write(String(L.terminalVerdict({})));")" "null"
237
+ check "terminalVerdict({history:[]}) is null (empty history)" \
238
+ "$(lj "process.stdout.write(String(L.terminalVerdict({history:[]})));")" "null"
239
+ check "terminalVerdict({history:'nope'}) is null (history not an array, not coerced)" \
240
+ "$(lj "process.stdout.write(String(L.terminalVerdict({history:'nope'})));")" "null"
241
+ check "terminalVerdict({history:[{pass:1}]}) is null (entry present, no verdict field)" \
242
+ "$(lj "process.stdout.write(String(L.terminalVerdict({history:[{pass:1}]})));")" "null"
243
+ check "terminalVerdict({history:[{verdict:7}]}) is null (verdict not a string, not coerced)" \
244
+ "$(lj "process.stdout.write(String(L.terminalVerdict({history:[{verdict:7}]})));")" "null"
245
+ check "terminalVerdict on a single-pass history returns that pass's verdict" \
246
+ "$(lj "process.stdout.write(String(L.terminalVerdict({history:[{pass:1,verdict:'approve'}]})));")" "approve"
247
+ check "terminalVerdict on a two-pass history returns the LAST entry's verdict, not the first -- 'terminal', not 'initial'" \
248
+ "$(lj "process.stdout.write(String(L.terminalVerdict({history:[{pass:1,verdict:'request-changes'},{pass:2,verdict:'approve'}]})));")" "approve"
249
+
250
+ # Mutation: prove the "LAST, not first" assertion above can actually fail. Staged on a scratch
251
+ # copy (mktemp -d), never the tracked file.
252
+ F267_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
253
+ trap 'rm -rf "$F267_MUT_DIR"' EXIT
254
+ F267_MUT="$F267_MUT_DIR/convergence.mjs"
255
+ cp "$ROOT/$LCONV" "$F267_MUT"
256
+ node -e "
257
+ const fs = require('fs'); const p = '$F267_MUT'; const s = fs.readFileSync(p, 'utf8');
258
+ const FROM = 'const last = history[history.length - 1];';
259
+ const TO = 'const last = history[0]; // MUTANT (F-267): reads the FIRST pass, not the terminal one';
260
+ if (!s.includes(FROM)) throw new Error('F-267 mutant pattern not found in lib/convergence.mjs -- source moved, update this mutation');
261
+ fs.writeFileSync(p, s.replace(FROM, TO));
262
+ "
263
+ mutant_verdict=$(node --input-type=module -e "
264
+ const L = await import('$F267_MUT');
265
+ process.stdout.write(String(L.terminalVerdict({history:[{pass:1,verdict:'request-changes'},{pass:2,verdict:'approve'}]})));
266
+ ")
267
+ check "mutant (F-267: terminalVerdict reads history[0]) returns the FIRST verdict ('request-changes'), catching the exact regression the 'LAST, not first' test above exists for" \
268
+ "$mutant_verdict" "request-changes"
269
+ pristine_verdict=$(lj "process.stdout.write(String(L.terminalVerdict({history:[{pass:1,verdict:'request-changes'},{pass:2,verdict:'approve'}]})));")
270
+ check "pristine lib/convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still returns the terminal verdict ('approve')" \
271
+ "$pristine_verdict" "approve"
272
+ rm -rf "$F267_MUT_DIR"
273
+ trap - EXIT
274
+
275
+ # --- terminalVerdict() alone can't tell a real coder/reviewer round trip from a loop that
276
+ # approved an untouched tree ({pass:1, verdict:'approve'} is exactly what a do-nothing loop would
277
+ # also write) -- terminalOutcome() widens the extraction to the whole terminal entry. Same
278
+ # fail-safe posture, each field independently null -- a missing count reads as "unknown", not 0.
279
+ check "terminalOutcome(null) is null (fails safe)" \
280
+ "$(lj "process.stdout.write(String(L.terminalOutcome(null)));")" "null"
281
+ check "terminalOutcome({}) is null (no history -- the three real F-266 shards' own shape)" \
282
+ "$(lj "process.stdout.write(String(L.terminalOutcome({})));")" "null"
283
+ check "terminalOutcome({history:[]}) is null (empty history)" \
284
+ "$(lj "process.stdout.write(String(L.terminalOutcome({history:[]})));")" "null"
285
+ check "terminalOutcome extracts all four fields from the TERMINAL (not first) entry" \
286
+ "$(lj "process.stdout.write(JSON.stringify(L.terminalOutcome({history:[{pass:1,verdict:'request-changes',blockers:2,majors:1,diff_lines:40},{pass:2,verdict:'approve',blockers:0,majors:0,diff_lines:58}]})));")" \
287
+ '{"verdict":"approve","blockers":0,"majors":0,"diffLines":58}'
288
+ check "terminalOutcome: entry missing blockers/majors/diff_lines -- each independently null, not defaulted to 0" \
289
+ "$(lj "process.stdout.write(JSON.stringify(L.terminalOutcome({history:[{verdict:'approve'}]})));")" \
290
+ '{"verdict":"approve","blockers":null,"majors":null,"diffLines":null}'
291
+ check "terminalOutcome: wrong-typed/negative counts are not coerced -- null, not passed through" \
292
+ "$(lj "process.stdout.write(JSON.stringify(L.terminalOutcome({history:[{verdict:'approve',blockers:'2',majors:-1,diff_lines:1.5}]})));")" \
293
+ '{"verdict":"approve","blockers":null,"majors":null,"diffLines":null}'
294
+
295
+ # --- writeNextShard(): the new `verdict` parameter, and backward compatibility for every
296
+ # pre-verdict 6-arg call site (this file's own MERGE_SHA writes above, eval-runner.sh's shard-write tests) -
297
+ F267_SHA1="f267verdict$(date +%s)"
298
+ verdict_written=$(cj "
299
+ const fs = await import('node:fs');
300
+ const occ = new Set();
301
+ const idx = M.writeNextShard('$F267_SHA1', M.TASK_ID, 5, occ, 0, 2, 'approve');
302
+ const rec = JSON.parse(fs.readFileSync(M.loopShardPath('$F267_SHA1', M.TASK_ID, idx), 'utf8'));
303
+ process.stdout.write(JSON.stringify(rec.run));
304
+ ")
305
+ check "writeNextShard(..., verdict) writes it into run.verdict (run.terminal an explicit null, F-268, when not passed)" \
306
+ "$verdict_written" '{"index":0,"pass":2,"verdict":"approve","terminal":null}'
307
+ rm -rf "$ROOT/tests/evals/results/$F267_SHA1"
308
+
309
+ F267_SHA2="f267noverdict$(date +%s)"
310
+ verdict_defaulted=$(cj "
311
+ const fs = await import('node:fs');
312
+ const occ = new Set();
313
+ const idx = M.writeNextShard('$F267_SHA2', M.TASK_ID, 5, occ, 0, 3);
314
+ const rec = JSON.parse(fs.readFileSync(M.loopShardPath('$F267_SHA2', M.TASK_ID, idx), 'utf8'));
315
+ process.stdout.write(JSON.stringify(rec.run) + '|' + ('verdict' in rec.run) + '|' + ('terminal' in rec.run));
316
+ ")
317
+ check "writeNextShard called with NO verdict/terminal arg (every pre-F-267 call site's own shape) still writes both as explicit null keys, not omitted ones" \
318
+ "$verdict_defaulted" '{"index":0,"pass":3,"verdict":null,"terminal":null}|true|true'
319
+ rm -rf "$ROOT/tests/evals/results/$F267_SHA2"
320
+
321
+ # --- makeShardWriter(): the real onDraw wiring drawArmForSha() uses, driven through the REAL
322
+ # fillArm() with a synthetic (non-live) draw handle -- no /code-loop invocation, no quota spent ---
323
+ F267_SHA3="f267wiring$(date +%s)"
324
+ wiring_check=$(cj "
325
+ const fs = await import('node:fs');
326
+ const state = { status: 'done', pass: 2, history: [{ pass: 1, verdict: 'request-changes' }, { pass: 2, verdict: 'approve', blockers: 0, majors: 0, diff_lines: 58 }] };
327
+ const makeDraw = () => ({ read: () => state, retry() {}, cleanup() {} });
328
+ const occ = new Set();
329
+ const { newDraw, onDraw } = M.makeShardWriter(makeDraw, '$F267_SHA3', M.TASK_ID, 1, occ, 0);
330
+ const r = M.fillArm(newDraw, { n: 1, onDraw });
331
+ const rec = JSON.parse(fs.readFileSync(M.loopShardPath('$F267_SHA3', M.TASK_ID, 0), 'utf8'));
332
+ process.stdout.write(JSON.stringify({ arm: r.arm, verdict: rec.run.verdict, terminal: rec.run.terminal }));
333
+ ")
334
+ check "makeShardWriter()'s onDraw, driven for real through fillArm(), writes the TERMINAL verdict AND the widened terminal object (F-268) from a two-entry history -- the exact assembly drawArmForSha() uses, without a live draw" \
335
+ "$wiring_check" '{"arm":[2],"verdict":"approve","terminal":{"verdict":"approve","blockers":0,"majors":0,"diffLines":58}}'
336
+ rm -rf "$ROOT/tests/evals/results/$F267_SHA3"
337
+
338
+ # --- constraint 1: a shard with NO run.verdict key at all (the real, pre-fix shape -- see
339
+ # diary.md, 2026-09-05; independently checked by hand against the actual quota-paid shards at
340
+ # tests/evals/results/39411eb.../convergence/, gitignored and session-specific, so NOT reproduced
341
+ # here as a committed dependency -- see the coder's own report) must still fold as a usable draw:
342
+ # never discarded, never an error. Staged as a synthetic legacy shard so this guard stays hermetic
343
+ # and portable across clones/CI that don't carry that local, gitignored quota-paid data.
344
+ F267_LEGACY_SHA="f267legacy$(date +%s)"
345
+ cj "
346
+ const fs = await import('node:fs');
347
+ const path = await import('node:path');
348
+ const p = M.loopShardPath('$F267_LEGACY_SHA', M.TASK_ID, 0);
349
+ fs.mkdirSync(path.dirname(p), { recursive: true });
350
+ fs.writeFileSync(p, JSON.stringify({ sha: '$F267_LEGACY_SHA', taskId: M.TASK_ID, schema: M.LOOP_SCHEMA_VERSION, run: { index: 0, pass: 1 } }) + '\n');
351
+ " >/dev/null
352
+ legacy_resume() { cj "process.stdout.write(JSON.stringify(M.resumeArm('$F267_LEGACY_SHA', M.TASK_ID, 1).resume));"; }
353
+ check "F-267/constraint 1: a shard with NO run.verdict key at all (the real, pre-fix shape) still folds as a usable draw" \
354
+ "$(legacy_resume)" "[1]"
355
+
356
+ # Mutation: prove the guard above can actually fail. readLoopShard()'s schema gate is mutated to
357
+ # ALSO require a verdict -- the exact shape of regression constraint 1 forbids -- staged on a
358
+ # scratch copy, read against the SAME on-disk legacy shard (read-only; confirmed untouched by the
359
+ # final re-check below).
360
+ F267_C1_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
361
+ trap 'rm -rf "$F267_C1_DIR"' EXIT
362
+ F267_C1="$F267_C1_DIR/convergence.mjs"
363
+ cp "$ROOT/$CVD" "$F267_C1"
364
+ ln -s "$ROOT/tests/evals/lib" "$F267_C1_DIR/lib"
365
+ ln -s "$ROOT/tests/evals/run.mjs" "$F267_C1_DIR/run.mjs"
366
+ node -e "
367
+ const fs = require('fs'); const p = '$F267_C1'; const s = fs.readFileSync(p, 'utf8');
368
+ const FROM = 'return rec?.schema === LOOP_SCHEMA_VERSION ? rec : null;';
369
+ const TO = 'return rec?.schema === LOOP_SCHEMA_VERSION \&\& rec.run?.verdict != null ? rec : null; // MUTANT (F-267): wrongly requires a verdict to fold';
370
+ if (!s.includes(FROM)) throw new Error('F-267 constraint-1 mutant pattern not found in convergence.mjs -- source moved, update this mutation');
371
+ fs.writeFileSync(p, s.replace(FROM, TO));
372
+ "
373
+ mutant_resume=$(node --input-type=module -e "
374
+ const M = await import('$F267_C1');
375
+ process.stdout.write(JSON.stringify(M.resumeArm('$F267_LEGACY_SHA', M.TASK_ID, 1).resume));
376
+ ")
377
+ check "mutant (F-267: readLoopShard wrongly requires a verdict) discards the legacy shard -- [] not [1], catching the exact regression constraint 1 forbids" \
378
+ "$mutant_resume" "[]"
379
+ pristine_resume=$(legacy_resume)
380
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still folds the legacy shard, [1]" \
381
+ "$pristine_resume" "[1]"
382
+ rm -rf "$F267_C1_DIR"
383
+ trap - EXIT
384
+ rm -rf "$ROOT/tests/evals/results/$F267_LEGACY_SHA"
385
+
386
+ # --- a censored draw retains a diagnostic record (elapsed wall-clock, wait attempts, ------
387
+ # last-seen loop state) -- the first live batch showed three draws
388
+ # read back as still-`running`; once the wait budget is exhausted, fillArm() previously discarded
389
+ # the last-read state entirely -- no shard is written and the workDir is cleaned up, so "the loop
390
+ # was genuinely slow" (cost-correlated) and "the subprocess died in thirty seconds"
391
+ # (uncorrelated with cost) were indistinguishable from any retained artifact. censoredDrawSnapshot()
392
+ # (lib/convergence.mjs) is the read side; fillArm()'s new `censor` field and writeCensorRecord()
393
+ # (this module) are the write side. Does NOT change what counts as a usable draw or the censoring
394
+ # policy itself (still exactly `waitAttempts > maxWaitAttempts`) -- only what gets recorded.
395
+ MK_SEQ_DRAW='
396
+ function mkSeqDraw(seq) {
397
+ let i = 0;
398
+ return () => {
399
+ const states = seq[i++]; let idx = 0;
400
+ return { read: () => states[idx], retry: () => { idx = Math.min(idx + 1, states.length - 1); } };
401
+ };
402
+ }
403
+ '
404
+
405
+ # censoredDrawSnapshot() fails safe, same posture as terminalVerdict()/terminalOutcome() above --
406
+ # always an object (the caller only calls this once a censoring event is already known to have
407
+ # happened); status/historyEmpty independently null on an unrecognised shape, stateReadable always
408
+ # a determinate boolean. `pass`/`lastVerdict` are added below, same fail-safe posture -- see the function's own docstring.
409
+ # `completedPasses` added alongside: `pass` alone is the pass most recently
410
+ # STARTED, possibly still in progress, never "the last completed pass" -- `completedPasses`
411
+ # (`history.length`) is the disambiguator that says which pass `lastVerdict` actually belongs to.
412
+ check "censoredDrawSnapshot(null) is {status:null,historyEmpty:null,stateReadable:false,pass:null,completedPasses:null,lastVerdict:null} (fails safe)" \
413
+ "$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot(null)));")" \
414
+ '{"status":null,"historyEmpty":null,"stateReadable":false,"pass":null,"completedPasses":null,"lastVerdict":null}'
415
+ check "censoredDrawSnapshot(undefined) is the same" \
416
+ "$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot(undefined)));")" \
417
+ '{"status":null,"historyEmpty":null,"stateReadable":false,"pass":null,"completedPasses":null,"lastVerdict":null}'
418
+ check "censoredDrawSnapshot(42) is the same (non-object input, not coerced)" \
419
+ "$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot(42)));")" \
420
+ '{"status":null,"historyEmpty":null,"stateReadable":false,"pass":null,"completedPasses":null,"lastVerdict":null}'
421
+ check "censoredDrawSnapshot({}) -- stateReadable true (it IS an object), status/historyEmpty/pass/completedPasses/lastVerdict still null (no fields to read)" \
422
+ "$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({})));")" \
423
+ '{"status":null,"historyEmpty":null,"stateReadable":true,"pass":null,"completedPasses":null,"lastVerdict":null}'
424
+ check "censoredDrawSnapshot({status:'running'}) reports the status; historyEmpty/pass/completedPasses/lastVerdict null (no history or pass field to read)" \
425
+ "$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running'})));")" \
426
+ '{"status":"running","historyEmpty":null,"stateReadable":true,"pass":null,"completedPasses":null,"lastVerdict":null}'
427
+ check "censoredDrawSnapshot({status:'running',history:[]}) -- empty history means no pass has COMPLETED yet (scripts/somi-loop.mjs init's own pre-work state), NOT proof the loop died immediately -- a stalled pass 1 reads identically (F-277, code-loop pass 2 review); completedPasses:0, the same 'no pass finished yet' fact historyEmpty already states, read off history.length directly" \
428
+ "$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running',history:[]})));")" \
429
+ '{"status":"running","historyEmpty":true,"stateReadable":true,"pass":null,"completedPasses":0,"lastVerdict":null}'
430
+ check "censoredDrawSnapshot({status:'running',history:[{pass:1}]}) -- non-empty history is the 'at least one pass completed' shape; pass stays null (the top-level pass field, not history[i].pass, is what passesToApprove() reads); completedPasses:1 (one history entry); lastVerdict stays null (the entry has no verdict field)" \
431
+ "$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running',history:[{pass:1}]})));")" \
432
+ '{"status":"running","historyEmpty":false,"stateReadable":true,"pass":null,"completedPasses":1,"lastVerdict":null}'
433
+ check "censoredDrawSnapshot: wrong-typed status/history are not coerced -- null, not passed through; stateReadable still true (an object WAS read, however malformed its fields); completedPasses null too (history isn't a readable array)" \
434
+ "$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:7,history:'nope'})));")" \
435
+ '{"status":null,"historyEmpty":null,"stateReadable":true,"pass":null,"completedPasses":null,"lastVerdict":null}'
436
+ check "F-279: stateReadable now separates 'no readable state at all' (null) from 'state read but malformed' ({status:7,...}) -- previously both collapsed to the identical {status:null,historyEmpty:null} record" \
437
+ "$(lj "process.stdout.write(JSON.stringify([L.censoredDrawSnapshot(null).stateReadable, L.censoredDrawSnapshot({status:7,history:'nope'}).stateReadable]));")" \
438
+ '[false,true]'
439
+ # a draw that HAS iterated (a real top-level pass count, a real prior verdict in
440
+ # history) surfaces the new fields with real, non-null values -- not merely a null-shaped
441
+ # addition every case above would also pass if pass/lastVerdict were wired to always return null.
442
+ # This case's history has exactly ONE entry (completedPasses:1), so `pass:2` reads as "mid-pass 2"
443
+ # -- lastVerdict belongs to the ALREADY-completed pass 1, not to `pass` itself.
444
+ check "censoredDrawSnapshot({status:'running',pass:2,history:[{pass:1,verdict:'approve-with-comments'}]}) reports the real pass count and the real last verdict; completedPasses:1 -- pass 2 is still IN PROGRESS, one pass behind pass" \
445
+ "$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running',pass:2,history:[{pass:1,verdict:'approve-with-comments'}]})));")" \
446
+ '{"status":"running","historyEmpty":false,"stateReadable":true,"pass":2,"completedPasses":1,"lastVerdict":"approve-with-comments"}'
447
+ # the OTHER ambiguous case `pass` alone cannot distinguish from the one above -- pass 2
448
+ # has ALSO just been recorded (completedPasses:2 == pass), and lastVerdict is pass 2's OWN verdict,
449
+ # not pass 1's. Two-entry history with DIFFERING verdicts also closes the terminal-entry case (a mutant reading
450
+ # history[0] instead of the terminal entry would report 'request-changes', the FIRST verdict, not
451
+ # 'approve-with-comments').
452
+ check "censoredDrawSnapshot({status:'running',pass:2,history:[pass1,pass2]}) -- completedPasses:2 (pass 2 already recorded), lastVerdict is pass 2's OWN verdict (the LAST entry), not pass 1's -- the case F-296's disambiguation exists to distinguish from the completedPasses:1 case above" \
453
+ "$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running',pass:2,history:[{pass:1,verdict:'request-changes'},{pass:2,verdict:'approve-with-comments'}]})));")" \
454
+ '{"status":"running","historyEmpty":false,"stateReadable":true,"pass":2,"completedPasses":2,"lastVerdict":"approve-with-comments"}'
455
+
456
+ # Mutation: prove pass/lastVerdict can actually fail to be extracted, not merely present-as-null.
457
+ # Staged on a scratch copy of lib/convergence.mjs, never the tracked file.
458
+ F295_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
459
+ trap 'rm -rf "$F295_MUT_DIR"' EXIT
460
+ F295_MUT="$F295_MUT_DIR/convergence.mjs"
461
+ cp "$ROOT/$LCONV" "$F295_MUT"
462
+ node -e "
463
+ const fs = require('fs'); const p = '$F295_MUT'; const s = fs.readFileSync(p, 'utf8');
464
+ const FROM = 'const pass = passesToApprove(loopStateJson);\n const lastVerdict = terminalVerdict(loopStateJson);';
465
+ const TO = 'const pass = null; const lastVerdict = null; // MUTANT (F-295): forced null, reproducing the pre-fix gap';
466
+ if (!s.includes(FROM)) throw new Error('F-295 mutant pattern not found in lib/convergence.mjs -- source moved, update this mutation');
467
+ fs.writeFileSync(p, s.replace(FROM, TO));
468
+ "
469
+ mutant_pass_verdict=$(node --input-type=module -e "
470
+ const L = await import('$F295_MUT');
471
+ process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running',pass:2,history:[{pass:1,verdict:'approve-with-comments'}]})));
472
+ ")
473
+ check "mutant (F-295: pass/lastVerdict forced null) reproduces the exact pre-fix gap -- a real pass 2/real verdict draw reads null,null, catching the regression the check above exists for" \
474
+ "$mutant_pass_verdict" '{"status":"running","historyEmpty":false,"stateReadable":true,"pass":null,"completedPasses":1,"lastVerdict":null}'
475
+ pristine_pass_verdict=$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running',pass:2,history:[{pass:1,verdict:'approve-with-comments'}]})));")
476
+ check "pristine lib/convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still reports the real pass and verdict" \
477
+ "$pristine_pass_verdict" '{"status":"running","historyEmpty":false,"stateReadable":true,"pass":2,"completedPasses":1,"lastVerdict":"approve-with-comments"}'
478
+ rm -rf "$F295_MUT_DIR"
479
+ trap - EXIT
480
+
481
+ # Mutation: prove completedPasses can actually fail to be extracted -- forced null, the
482
+ # exact ambiguity this field exists to resolve. Staged on a scratch copy, never the tracked file.
483
+ F296_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
484
+ trap 'rm -rf "$F296_MUT_DIR"' EXIT
485
+ F296_MUT="$F296_MUT_DIR/convergence.mjs"
486
+ cp "$ROOT/$LCONV" "$F296_MUT"
487
+ node -e "
488
+ const fs = require('fs'); const p = '$F296_MUT'; const s = fs.readFileSync(p, 'utf8');
489
+ const FROM = 'const completedPasses = Array.isArray(history) ? history.length : null;';
490
+ const TO = 'const completedPasses = null; // MUTANT (F-296): forced null, reproducing the pass-vs-completedPasses ambiguity this field exists to resolve';
491
+ if (!s.includes(FROM)) throw new Error('F-296 mutant pattern not found in lib/convergence.mjs -- source moved, update this mutation');
492
+ fs.writeFileSync(p, s.replace(FROM, TO));
493
+ "
494
+ mutant_completed_passes=$(node --input-type=module -e "
495
+ const L = await import('$F296_MUT');
496
+ process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running',pass:2,history:[{pass:1,verdict:'request-changes'},{pass:2,verdict:'approve-with-comments'}]})));
497
+ ")
498
+ check "mutant (F-296: completedPasses forced null) reads completedPasses:null on a real 2-entry-history draw, reproducing the exact ambiguity ('pass:2' alone can't say whether pass 2 is in progress or already recorded) that this field exists to resolve -- historyEmpty also reads null, since it is defined in terms of completedPasses, not independently" \
499
+ "$mutant_completed_passes" '{"status":"running","historyEmpty":null,"stateReadable":true,"pass":2,"completedPasses":null,"lastVerdict":"approve-with-comments"}'
500
+ pristine_completed_passes=$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running',pass:2,history:[{pass:1,verdict:'request-changes'},{pass:2,verdict:'approve-with-comments'}]})));")
501
+ check "pristine lib/convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still reports completedPasses:2" \
502
+ "$pristine_completed_passes" '{"status":"running","historyEmpty":false,"stateReadable":true,"pass":2,"completedPasses":2,"lastVerdict":"approve-with-comments"}'
503
+ rm -rf "$F296_MUT_DIR"
504
+ trap - EXIT
505
+
506
+ # Mutation: prove lastVerdict actually reads the TERMINAL entry, not the first one -- every
507
+ # censoredDrawSnapshot() case above the two-entry one has at most ONE history entry, so a mutant
508
+ # that reads history[0] instead of the last entry is indistinguishable from the correct
509
+ # implementation on all of them; only the differing-verdicts two-entry case above can tell them
510
+ # apart. Staged on a scratch copy, never the tracked file.
511
+ F297_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
512
+ trap 'rm -rf "$F297_MUT_DIR"' EXIT
513
+ F297_MUT="$F297_MUT_DIR/convergence.mjs"
514
+ cp "$ROOT/$LCONV" "$F297_MUT"
515
+ node -e "
516
+ const fs = require('fs'); const p = '$F297_MUT'; const s = fs.readFileSync(p, 'utf8');
517
+ const FROM = 'const lastVerdict = terminalVerdict(loopStateJson);';
518
+ const TO = 'const lastVerdict = (stateReadable && Array.isArray(loopStateJson.history) && loopStateJson.history.length && typeof loopStateJson.history[0].verdict === \"string\") ? loopStateJson.history[0].verdict : null; // MUTANT (F-297): reads the FIRST entry, not the terminal one';
519
+ if (!s.includes(FROM)) throw new Error('F-297 mutant pattern not found in lib/convergence.mjs -- source moved, update this mutation');
520
+ fs.writeFileSync(p, s.replace(FROM, TO));
521
+ "
522
+ mutant_first_verdict=$(node --input-type=module -e "
523
+ const L = await import('$F297_MUT');
524
+ process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running',pass:2,history:[{pass:1,verdict:'request-changes'},{pass:2,verdict:'approve-with-comments'}]})));
525
+ ")
526
+ check "mutant (F-297: lastVerdict reads history[0]) returns the FIRST verdict ('request-changes') on the differing-verdicts two-entry case, catching the exact regression that case exists for" \
527
+ "$mutant_first_verdict" '{"status":"running","historyEmpty":false,"stateReadable":true,"pass":2,"completedPasses":2,"lastVerdict":"request-changes"}'
528
+ pristine_first_verdict=$(lj "process.stdout.write(JSON.stringify(L.censoredDrawSnapshot({status:'running',pass:2,history:[{pass:1,verdict:'request-changes'},{pass:2,verdict:'approve-with-comments'}]})));")
529
+ check "pristine lib/convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still returns the terminal verdict ('approve-with-comments')" \
530
+ "$pristine_first_verdict" '{"status":"running","historyEmpty":false,"stateReadable":true,"pass":2,"completedPasses":2,"lastVerdict":"approve-with-comments"}'
531
+ rm -rf "$F297_MUT_DIR"
532
+ trap - EXIT
533
+
534
+ # fillArm(): the `censor` field on the wait-exhausted path. `now` is injectable (defaults to
535
+ # Date.now) so elapsedMs is deterministic under test, the same seam newDraw/report/resume already
536
+ # are.
537
+ check "fillArm: wait-exhaustion returns a real censor record -- elapsedMs from the injected clock, waitAttempts the loop's own count, lastState from the last-read (still-running) state" \
538
+ "$(cj "$MK_SEQ_DRAW
539
+ let t = 1000;
540
+ const now = () => (t += 1000);
541
+ const seq = [[{status:'running'}, {status:'running'}, {status:'running'}]];
542
+ const r = M.fillArm(mkSeqDraw(seq), { n: 1, maxWaitAttempts: 2, report: () => {}, now });
543
+ process.stdout.write(JSON.stringify(r.censor));
544
+ ")" '{"elapsedMs":1000,"waitAttempts":3,"lastState":{"status":"running","historyEmpty":null,"stateReadable":true,"pass":null,"completedPasses":null,"lastVerdict":null}}'
545
+ check "fillArm: censor.lastState.historyEmpty is true when the last-read state's history is empty (no pass has completed yet -- not proof nothing started; see censoredDrawSnapshot()'s docstring, F-277); completedPasses:0 for the same reason" \
546
+ "$(cj "$MK_SEQ_DRAW
547
+ const seq = [[{status:'running',history:[]}]];
548
+ const r = M.fillArm(mkSeqDraw(seq), { n: 1, maxWaitAttempts: 0, report: () => {} });
549
+ process.stdout.write(JSON.stringify(r.censor.lastState));
550
+ ")" '{"status":"running","historyEmpty":true,"stateReadable":true,"pass":null,"completedPasses":0,"lastVerdict":null}'
551
+ check "fillArm: elapsedMs includes the span newDraw() itself consumes before returning a handle, not just the retries after it (F-278, code-loop pass 2 review -- mkSeqDraw above can't pin this, since its newDraw() never calls now() and is instantaneous either way)" \
552
+ "$(cj "
553
+ let f278t = 0;
554
+ const f278NewDraw = () => { f278t += 60000; return { read: () => ({ status: 'running' }), retry: () => {}, cleanup: () => {} }; };
555
+ const r = M.fillArm(f278NewDraw, { n: 1, maxWaitAttempts: 0, report: () => {}, now: () => f278t });
556
+ process.stdout.write(String(r.censor.elapsedMs));
557
+ ")" "60000"
558
+ check "fillArm: censor is null on the breach path (only the wait-exhausted path retains anything)" \
559
+ "$(cj "$MK_SEQ_DRAW
560
+ const r = M.fillArm(mkSeqDraw([[{status:'max-passes-exceeded',pass:6}]]), { n: 1, report: () => {} });
561
+ process.stdout.write(String(r.censor));
562
+ ")" "null"
563
+ check "fillArm: censor is null on the done path" \
564
+ "$(cj "$MK_SEQ_DRAW
565
+ const r = M.fillArm(mkSeqDraw([[{status:'done',pass:2}]]), { n: 1, report: () => {} });
566
+ process.stdout.write(String(r.censor));
567
+ ")" "null"
568
+
569
+ # writeCensorRecord()/censorRecordPath(): persisting the record, own namespace, self-healing slot.
570
+ F276_SHA="f276censor$(date +%s)"
571
+ censor_written=$(cj "
572
+ const fs = await import('node:fs');
573
+ const seq = M.writeCensorRecord('$F276_SHA', M.TASK_ID, { elapsedMs: 278000, waitAttempts: 3, lastState: { status: 'running', historyEmpty: true } });
574
+ const p = M.censorRecordPath('$F276_SHA', M.TASK_ID, seq);
575
+ const rec = JSON.parse(fs.readFileSync(p, 'utf8'));
576
+ process.stdout.write(JSON.stringify({ seq, sha: rec.sha, taskId: rec.taskId, schema: rec.schema, censor: rec.censor }));
577
+ ")
578
+ check "writeCensorRecord() persists the record at seq 0 with the module's schema, sha and taskId alongside it" \
579
+ "$censor_written" \
580
+ "{\"seq\":0,\"sha\":\"$F276_SHA\",\"taskId\":\"loop-code-loop\",\"schema\":1,\"censor\":{\"elapsedMs\":278000,\"waitAttempts\":3,\"lastState\":{\"status\":\"running\",\"historyEmpty\":true}}}"
581
+ check "writeCensorRecord() called again for the same sha self-heals to the NEXT free slot (seq 1), never overwriting the first" \
582
+ "$(cj "
583
+ const seq = M.writeCensorRecord('$F276_SHA', M.TASK_ID, { elapsedMs: 1000, waitAttempts: 1, lastState: { status: 'running', historyEmpty: false } });
584
+ process.stdout.write(String(seq));
585
+ ")" "1"
586
+ check "a censored draw's record lives OUTSIDE the numbered shard namespace -- resumeArm() sees no usable draw from it (F-276 does not change what counts as usable, constraint 1)" \
587
+ "$(cj "process.stdout.write(JSON.stringify(M.resumeArm('$F276_SHA', M.TASK_ID, 15).resume));")" \
588
+ "[]"
589
+ rm -rf "$ROOT/tests/evals/results/$F276_SHA"
590
+
591
+ # The exact assembly drawArmForSha() uses (fillArm's censor return, persisted via
592
+ # writeCensorRecord()) -- without a live /code-loop invocation, no quota spent.
593
+ F276_WIRING_SHA="f276wiring$(date +%s)"
594
+ wiring_censor=$(cj "
595
+ const fs = await import('node:fs');
596
+ const makeDraw = () => ({ read: () => ({ status: 'running', history: [] }), retry() {}, cleanup() {} });
597
+ const occ = new Set();
598
+ const { newDraw, onDraw } = M.makeShardWriter(makeDraw, '$F276_WIRING_SHA', M.TASK_ID, 1, occ, 0);
599
+ const r = M.fillArm(newDraw, { n: 1, maxWaitAttempts: 1, onDraw, report: () => {} });
600
+ const seq = r.censor ? M.writeCensorRecord('$F276_WIRING_SHA', M.TASK_ID, r.censor) : null;
601
+ const rec = seq === null ? null : JSON.parse(fs.readFileSync(M.censorRecordPath('$F276_WIRING_SHA', M.TASK_ID, seq), 'utf8'));
602
+ process.stdout.write(JSON.stringify({ arm: r.arm, waitExhausted: r.waitExhausted, persisted: rec ? rec.censor.lastState : null }));
603
+ ")
604
+ check "the exact assembly drawArmForSha() uses (fillArm's censor return + writeCensorRecord) persists a censored draw's evidence, without a live draw" \
605
+ "$wiring_censor" '{"arm":[],"waitExhausted":true,"persisted":{"status":"running","historyEmpty":true,"stateReadable":true,"pass":null,"completedPasses":0,"lastVerdict":null}}'
606
+ rm -rf "$ROOT/tests/evals/results/$F276_WIRING_SHA"
607
+
608
+ # the SAME real assembly, but the synthetic draw HAS iterated (a real pass count, a
609
+ # real prior verdict) -- proving pass/lastVerdict aren't just structurally present-and-null through
610
+ # this path, they carry the REAL returned snapshot's values end to end.
611
+ F295_WIRING_SHA="f295wiring$(date +%s)"
612
+ wiring_pass_verdict=$(cj "
613
+ const fs = await import('node:fs');
614
+ const makeDraw = () => ({ read: () => ({ status: 'running', pass: 2, history: [{ pass: 1, verdict: 'approve-with-comments' }] }), retry() {}, cleanup() {} });
615
+ const occ = new Set();
616
+ const { newDraw, onDraw } = M.makeShardWriter(makeDraw, '$F295_WIRING_SHA', M.TASK_ID, 1, occ, 0);
617
+ const r = M.fillArm(newDraw, { n: 1, maxWaitAttempts: 1, onDraw, report: () => {} });
618
+ const seq = r.censor ? M.writeCensorRecord('$F295_WIRING_SHA', M.TASK_ID, r.censor) : null;
619
+ const rec = seq === null ? null : JSON.parse(fs.readFileSync(M.censorRecordPath('$F295_WIRING_SHA', M.TASK_ID, seq), 'utf8'));
620
+ process.stdout.write(JSON.stringify({ persisted: rec ? rec.censor.lastState : null }));
621
+ ")
622
+ check "F-295: a censored draw that HAS iterated persists BOTH new fields with real values through the real makeShardWriter -> fillArm -> writeCensorRecord assembly, not a hand-typed literal; completedPasses:1 -- pass 2 still IN PROGRESS, one behind pass" \
623
+ "$wiring_pass_verdict" '{"persisted":{"status":"running","historyEmpty":false,"stateReadable":true,"pass":2,"completedPasses":1,"lastVerdict":"approve-with-comments"}}'
624
+ rm -rf "$ROOT/tests/evals/results/$F295_WIRING_SHA"
625
+
626
+ # the SAME real assembly again, but with a two-entry history whose verdicts differ --
627
+ # completedPasses:2 (pass 2 already recorded, not merely in progress) and lastVerdict is pass 2's
628
+ # OWN verdict, distinguishing this real end-to-end case from the completedPasses:1 case above the
629
+ # same way the two unit-level censoredDrawSnapshot() cases distinguish each other.
630
+ F296_WIRING_SHA="f296wiring$(date +%s)"
631
+ wiring_completed_passes=$(cj "
632
+ const fs = await import('node:fs');
633
+ const makeDraw = () => ({ read: () => ({ status: 'running', pass: 2, history: [{ pass: 1, verdict: 'request-changes' }, { pass: 2, verdict: 'approve-with-comments' }] }), retry() {}, cleanup() {} });
634
+ const occ = new Set();
635
+ const { newDraw, onDraw } = M.makeShardWriter(makeDraw, '$F296_WIRING_SHA', M.TASK_ID, 1, occ, 0);
636
+ const r = M.fillArm(newDraw, { n: 1, maxWaitAttempts: 1, onDraw, report: () => {} });
637
+ const seq = r.censor ? M.writeCensorRecord('$F296_WIRING_SHA', M.TASK_ID, r.censor) : null;
638
+ const rec = seq === null ? null : JSON.parse(fs.readFileSync(M.censorRecordPath('$F296_WIRING_SHA', M.TASK_ID, seq), 'utf8'));
639
+ process.stdout.write(JSON.stringify({ persisted: rec ? rec.censor.lastState : null }));
640
+ ")
641
+ check "F-296: the real assembly with a two-entry, differing-verdicts history persists completedPasses:2 and pass 2's OWN verdict, not pass 1's" \
642
+ "$wiring_completed_passes" '{"persisted":{"status":"running","historyEmpty":false,"stateReadable":true,"pass":2,"completedPasses":2,"lastVerdict":"approve-with-comments"}}'
643
+ rm -rf "$ROOT/tests/evals/results/$F296_WIRING_SHA"
644
+
645
+ # Mutation: prove the retained record can actually fail to be retained. Staged on a scratch copy,
646
+ # never the tracked file.
647
+ F276_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
648
+ trap 'rm -rf "$F276_MUT_DIR"' EXIT
649
+ F276_MUT="$F276_MUT_DIR/convergence.mjs"
650
+ cp "$ROOT/$CVD" "$F276_MUT"
651
+ ln -s "$ROOT/tests/evals/lib" "$F276_MUT_DIR/lib"
652
+ ln -s "$ROOT/tests/evals/run.mjs" "$F276_MUT_DIR/run.mjs"
653
+ node -e "
654
+ const fs = require('fs'); const p = '$F276_MUT'; const s = fs.readFileSync(p, 'utf8');
655
+ const FROM = 'const censor = { elapsedMs: now() - drawStartedAt, waitAttempts, lastState: censoredDrawSnapshot(state) };';
656
+ const TO = 'const censor = null; // MUTANT (F-276): the censored draw retains nothing, same as before this pass';
657
+ if (!s.includes(FROM)) throw new Error('F-276 mutant pattern not found in convergence.mjs -- source moved, update this mutation');
658
+ fs.writeFileSync(p, s.replace(FROM, TO));
659
+ "
660
+ mutant_censor=$(node --input-type=module -e "
661
+ const M = await import('$F276_MUT');
662
+ $MK_SEQ_DRAW
663
+ const r = M.fillArm(mkSeqDraw([[{status:'running'}, {status:'running'}, {status:'running'}]]), { n: 1, maxWaitAttempts: 2, report: () => {} });
664
+ process.stdout.write(String(r.censor));
665
+ ")
666
+ check "mutant (F-276: censor forced to null) reproduces the exact pre-fix gap -- a censored draw retains nothing, catching the regression the tests above exist for" \
667
+ "$mutant_censor" "null"
668
+ pristine_censor=$(cj "$MK_SEQ_DRAW
669
+ const r = M.fillArm(mkSeqDraw([[{status:'running'}, {status:'running'}, {status:'running'}]]), { n: 1, maxWaitAttempts: 2, report: () => {} });
670
+ process.stdout.write(String(r.censor !== null));
671
+ ")
672
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still retains a real censor record" \
673
+ "$pristine_censor" "true"
674
+ rm -rf "$F276_MUT_DIR"
675
+ trap - EXIT
676
+
677
+ # --- argument parsing ----------------------------------------------------------------------------
678
+ help_out=$(node "$CVD" --help)
679
+ help_flags_present=true
680
+ for flag in --source --fixture --runs --max-wait-attempts --merge --certify --dry-run; do
681
+ printf '%s' "$help_out" | grep -qF -- "$flag" || help_flags_present=false
682
+ done
683
+ check "--help prints usage naming every documented flag" "$help_flags_present" "true"
684
+ check "an unknown argument exits non-zero" "$(node "$CVD" --bogus >/dev/null 2>&1; echo $?)" "1"
685
+ check "--runs 0 is rejected (must be a positive integer)" "$(node "$CVD" --dry-run --runs 0 >/dev/null 2>&1; echo $?)" "1"
686
+ check "--runs -1 is rejected" "$(node "$CVD" --dry-run --runs -1 >/dev/null 2>&1; echo $?)" "1"
687
+ # same validation SHAPE as --runs above, not a second hand-rolled check.
688
+ check "--max-wait-attempts 0 is rejected (must be a positive integer)" "$(node "$CVD" --dry-run --max-wait-attempts 0 >/dev/null 2>&1; echo $?)" "1"
689
+ check "--max-wait-attempts -1 is rejected" "$(node "$CVD" --dry-run --max-wait-attempts -1 >/dev/null 2>&1; echo $?)" "1"
690
+ check "--max-wait-attempts 1.5 is rejected (not an integer)" "$(node "$CVD" --dry-run --max-wait-attempts 1.5 >/dev/null 2>&1; echo $?)" "1"
691
+ check "--max-wait-attempts 3 is accepted" "$(node "$CVD" --dry-run --max-wait-attempts 3 >/dev/null 2>&1; echo $?)" "0"
692
+ for flag in --source --fixture --runs --model --max-wait-attempts --merge --certify; do check "$flag with no operand is rejected, not silently defaulted (F-252/F-253)" "$(node "$CVD" "$flag" >/dev/null 2>&1; echo $?)" "1"; done
693
+ for flag in --merge --certify; do check "$flag with an empty operand is rejected (F-259)" "$(node "$CVD" "$flag" "" >/dev/null 2>&1; echo $?)" "1"; done
694
+
695
+ # --- --fixture/--source/--model have exactly ONE defender (val()'s own `v === ''` clause),
696
+ # no downstream validator the way --merge/--certify have (val() + the `!== null` guard +
697
+ # validateSha()) -- so this case, unlike the --merge case, had no committed test at all before this pass.
698
+ for flag in --source --fixture --model; do check "$flag with an empty operand is rejected" "$(node "$CVD" --dry-run "$flag" "" >/dev/null 2>&1; echo $?)" "1"; done
699
+ check "--fixture -h is rejected as a flag-shaped operand, not silently accepted as a literal value (F-262)" \
700
+ "$(node "$CVD" --dry-run --fixture -h >/dev/null 2>&1; echo $?)" "1"
701
+ check "--max-wait-attempts with an empty operand is rejected (F-294, same val() layer as --runs)" \
702
+ "$(node "$CVD" --dry-run --max-wait-attempts "" >/dev/null 2>&1; echo $?)" "1"
703
+ check "--max-wait-attempts -h is rejected as a flag-shaped operand, not silently accepted as a literal value" \
704
+ "$(node "$CVD" --dry-run --max-wait-attempts -h >/dev/null 2>&1; echo $?)" "1"
705
+
706
+ stub_bin=$(mktemp -d)
707
+ stub_sentinel="$stub_bin/touched"
708
+ printf '#!/bin/sh\n%s "%s"\nexit 1\n' "$(command -v touch)" "$stub_sentinel" > "$stub_bin/claude"
709
+ chmod +x "$stub_bin/claude"
710
+ PATH="$stub_bin:$PATH" node "$CVD" --merge "" >/dev/null 2>&1
711
+ check "F-259: --merge with an empty operand no longer reaches a stub claude on PATH (sentinel stays absent)" "$([ -e "$stub_sentinel" ] && echo TOUCHED || echo ABSENT)" "ABSENT"
712
+ PATH="$stub_bin" claude >/dev/null 2>&1
713
+ check "positive control: same stub still reachable (F-259 re-confirmation)" "$([ -e "$stub_sentinel" ] && echo TOUCHED || echo ABSENT)" "TOUCHED"
714
+ rm -rf "$stub_bin"
715
+
716
+ # Mutation: prove the empty-operand cases above actually depend on val()'s `v === ''` clause -- the
717
+ # measurement was that they would NOT redden if it were removed. Staged on a
718
+ # scratch copy, never the tracked file.
719
+ F263_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
720
+ trap 'rm -rf "$F263_MUT_DIR"' EXIT
721
+ F263_MUT="$F263_MUT_DIR/convergence.mjs"
722
+ cp "$ROOT/$CVD" "$F263_MUT"
723
+ ln -s "$ROOT/tests/evals/lib" "$F263_MUT_DIR/lib"
724
+ ln -s "$ROOT/tests/evals/run.mjs" "$F263_MUT_DIR/run.mjs"
725
+ node -e "
726
+ const fs = require('fs'); const p = '$F263_MUT'; const s = fs.readFileSync(p, 'utf8');
727
+ const FROM = \"v === undefined || v === '' || /^-/.test(v)\";
728
+ const TO = \"v === undefined || /^-/.test(v)\"; // MUTANT (F-263): empty-string operand no longer rejected
729
+ if (!s.includes(FROM)) throw new Error('F-263 mutant pattern not found in convergence.mjs -- source moved, update this mutation');
730
+ fs.writeFileSync(p, s.replace(FROM, TO));
731
+ "
732
+ mutant_exit=$(node "$F263_MUT" --dry-run --source "" >/dev/null 2>&1; echo $?)
733
+ check "mutant (F-263: val()'s v === '' clause removed) lets --source \"\" through -- the F-261 case above would now go GREEN on a broken guard, confirming it currently depends on this exact clause" \
734
+ "$mutant_exit" "0"
735
+ pristine_exit=$(node "$CVD" --dry-run --source "" >/dev/null 2>&1; echo $?)
736
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still rejects --source \"\"" \
737
+ "$pristine_exit" "1"
738
+ rm -rf "$F263_MUT_DIR"
739
+ trap - EXIT
740
+
741
+ # --- --max-wait-attempts reaches fillArm(), not just parseArgs() -------------------------
742
+ # "This repo has repeatedly had flags that parse correctly and do nothing" (a standing instruction) -- so this drives the REAL parseArgs() output into the REAL fillArm(),
743
+ # rather than asserting only that parseArgs() produces the right field under the right key. A
744
+ # synthetic single-slot arm reports 'running' three times before completing: at the DEFAULT budget
745
+ # (DEFAULT_MAX_WAIT_ATTEMPTS = 2) it exhausts (waitAttempts 3 > 2); parsed through
746
+ # --max-wait-attempts 5, the SAME draw completes -- proving the parsed value changed fillArm()'s
747
+ # own control flow, not merely parseArgs()'s output.
748
+ F294_SEQ='[[{status:"running"},{status:"running"},{status:"running"},{status:"done",pass:1}]]'
749
+ check "no --max-wait-attempts (parses to null): fillArm falls through to its own DEFAULT_MAX_WAIT_ATTEMPTS (2) -- a draw needing 3 waits censors" \
750
+ "$(cj "$MK_SEQ_DRAW
751
+ const args = M.parseArgs(['--dry-run']);
752
+ const seq = $F294_SEQ;
753
+ const r = M.fillArm(mkSeqDraw(seq), { n: 1, maxWaitAttempts: args.maxWaitAttempts, report: () => {} });
754
+ process.stdout.write(JSON.stringify({ waitExhausted: r.waitExhausted, arm: r.arm }));
755
+ ")" '{"waitExhausted":true,"arm":[]}'
756
+ check "--max-wait-attempts 5 (parsed via the real parseArgs()): the SAME synthetic draw now completes" \
757
+ "$(cj "$MK_SEQ_DRAW
758
+ const args = M.parseArgs(['--dry-run', '--max-wait-attempts', '5']);
759
+ const seq = $F294_SEQ;
760
+ const r = M.fillArm(mkSeqDraw(seq), { n: 1, maxWaitAttempts: args.maxWaitAttempts, report: () => {} });
761
+ process.stdout.write(JSON.stringify({ waitExhausted: r.waitExhausted, arm: r.arm }));
762
+ ")" '{"waitExhausted":false,"arm":[1]}'
763
+
764
+ # --- the anchor above USED TO BE a `grep -c` for the literal substring
765
+ # 'maxWaitAttempts: args.maxWaitAttempts' -- a substring match a mutant can satisfy while changing
766
+ # what the code DOES: `args.maxWaitAttempts && 0` still contains that exact text (the review's own
767
+ # measurement: this mutant survived the full 134/0 suite untouched) while silently collapsing any
768
+ # real, truthy --max-wait-attempts value to 0, censoring every draw on its first `running` read.
769
+ # Fixed by extracting the opts-building step into `liveDrawOpts()` (exported, same reasoning
770
+ # `validateSha()`/`parseArgs()` were already exported for) so a test drives the REAL function and
771
+ # checks the REAL value it returns, not a text pattern main() happens to still contain.
772
+ check "liveDrawOpts() carries a real --max-wait-attempts value through unchanged" \
773
+ "$(cj "process.stdout.write(JSON.stringify(M.liveDrawOpts(M.parseArgs(['--dry-run', '--runs', '15', '--max-wait-attempts', '5']))));")" \
774
+ '{"n":15,"model":null,"maxWaitAttempts":5}'
775
+ check "liveDrawOpts() carries null through when --max-wait-attempts is absent (fillArm's own default then applies)" \
776
+ "$(cj "process.stdout.write(JSON.stringify(M.liveDrawOpts(M.parseArgs(['--dry-run', '--runs', '15']))));")" \
777
+ '{"n":15,"model":null,"maxWaitAttempts":null}'
778
+
779
+ # Mutation: `args.maxWaitAttempts && 0` -- the EXACT mutant the review found surviving the old
780
+ # grep-anchored test. A real (truthy) value collapses to 0; parseArgs() itself never produces a
781
+ # literal 0 (rejected by the positive-integer check), so this corruption is reachable ONLY through
782
+ # a broken liveDrawOpts(), never through a value parseArgs() would emit on its own. Staged on a
783
+ # scratch copy, never the tracked file.
784
+ F298_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
785
+ trap 'rm -rf "$F298_MUT_DIR"' EXIT
786
+ F298_MUT="$F298_MUT_DIR/convergence.mjs"
787
+ cp "$ROOT/$CVD" "$F298_MUT"
788
+ ln -s "$ROOT/tests/evals/lib" "$F298_MUT_DIR/lib"
789
+ ln -s "$ROOT/tests/evals/run.mjs" "$F298_MUT_DIR/run.mjs"
790
+ node -e "
791
+ const fs = require('fs'); const p = '$F298_MUT'; const s = fs.readFileSync(p, 'utf8');
792
+ const FROM = 'return { n: args.runs, model: args.model, maxWaitAttempts: args.maxWaitAttempts };';
793
+ const TO = 'return { n: args.runs, model: args.model, maxWaitAttempts: args.maxWaitAttempts && 0 }; // MUTANT (F-298): a real value collapses to 0, censoring every draw on its first running read';
794
+ if (!s.includes(FROM)) throw new Error('F-298 mutant pattern not found in convergence.mjs -- source moved, update this mutation');
795
+ fs.writeFileSync(p, s.replace(FROM, TO));
796
+ "
797
+ mutant_livedrawopts=$(node --input-type=module -e "
798
+ const M = await import('$F298_MUT');
799
+ process.stdout.write(JSON.stringify(M.liveDrawOpts(M.parseArgs(['--dry-run', '--max-wait-attempts', '5']))));
800
+ ")
801
+ check "mutant (F-298: args.maxWaitAttempts && 0) collapses a real --max-wait-attempts 5 down to 0, catching the exact regression a text anchor could not" \
802
+ "$mutant_livedrawopts" '{"n":15,"model":null,"maxWaitAttempts":0}'
803
+ pristine_livedrawopts=$(cj "process.stdout.write(JSON.stringify(M.liveDrawOpts(M.parseArgs(['--dry-run', '--max-wait-attempts', '5']))));")
804
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still carries maxWaitAttempts:5 through liveDrawOpts() unchanged" \
805
+ "$pristine_livedrawopts" '{"n":15,"model":null,"maxWaitAttempts":5}'
806
+ rm -rf "$F298_MUT_DIR"
807
+ trap - EXIT
808
+
809
+ # The one link liveDrawOpts()'s own tests above still can't close by execution: whether main()'s
810
+ # live-draw branch actually CALLS liveDrawOpts(args) and forwards its return value into
811
+ # drawArmForSha() -- main() itself isn't exported and spends quota, so it can't be driven directly.
812
+ # Pure argument-passing has no value transform left to mutate the way the opts VALUES above did, so
813
+ # a source anchor on the exact call expression is the honest residual, not a value-changing gap: it
814
+ # proves the wiring exists, not that liveDrawOpts()'s output is correct (that part is covered above).
815
+ check "main()'s live-draw branch literally calls drawArmForSha(source.dir, fixtureDir, source.sha, liveDrawOpts(args))" \
816
+ "$(grep -c 'drawArmForSha(source.dir, fixtureDir, source.sha, liveDrawOpts(args))' "$ROOT/$CVD")" "1"
817
+
818
+ # Mutation 1: prove --max-wait-attempts's positive-integer guard actually depends on the check
819
+ # added this pass. Staged on a scratch copy, never the tracked file.
820
+ F294_VALIDATE_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
821
+ trap 'rm -rf "$F294_VALIDATE_MUT_DIR"' EXIT
822
+ F294_VALIDATE_MUT="$F294_VALIDATE_MUT_DIR/convergence.mjs"
823
+ cp "$ROOT/$CVD" "$F294_VALIDATE_MUT"
824
+ ln -s "$ROOT/tests/evals/lib" "$F294_VALIDATE_MUT_DIR/lib"
825
+ ln -s "$ROOT/tests/evals/run.mjs" "$F294_VALIDATE_MUT_DIR/run.mjs"
826
+ node -e "
827
+ const fs = require('fs'); const p = '$F294_VALIDATE_MUT'; const s = fs.readFileSync(p, 'utf8');
828
+ const FROM = 'a.maxWaitAttempts !== null && (!Number.isInteger(a.maxWaitAttempts) || a.maxWaitAttempts <= 0)';
829
+ const TO = 'false /* MUTANT (F-294): positive-integer guard neutered */';
830
+ if (!s.includes(FROM)) throw new Error('F-294 validation mutant pattern not found in convergence.mjs -- source moved, update this mutation');
831
+ fs.writeFileSync(p, s.replace(FROM, TO));
832
+ "
833
+ mutant_validate_exit=$(node "$F294_VALIDATE_MUT" --dry-run --max-wait-attempts 0 >/dev/null 2>&1; echo $?)
834
+ check "mutant (F-294: positive-integer guard neutered) lets --max-wait-attempts 0 through -- confirming the check above currently depends on it" \
835
+ "$mutant_validate_exit" "0"
836
+ pristine_validate_exit=$(node "$CVD" --dry-run --max-wait-attempts 0 >/dev/null 2>&1; echo $?)
837
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still rejects --max-wait-attempts 0" \
838
+ "$pristine_validate_exit" "1"
839
+ rm -rf "$F294_VALIDATE_MUT_DIR"
840
+ trap - EXIT
841
+
842
+ # Mutation 2: prove fillArm()'s own read of opts.maxWaitAttempts is what the "reaches fillArm()"
843
+ # checks above depend on, not some other unrelated path to the same numbers.
844
+ F294_WIRING_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
845
+ trap 'rm -rf "$F294_WIRING_MUT_DIR"' EXIT
846
+ F294_WIRING_MUT="$F294_WIRING_MUT_DIR/convergence.mjs"
847
+ cp "$ROOT/$CVD" "$F294_WIRING_MUT"
848
+ ln -s "$ROOT/tests/evals/lib" "$F294_WIRING_MUT_DIR/lib"
849
+ ln -s "$ROOT/tests/evals/run.mjs" "$F294_WIRING_MUT_DIR/run.mjs"
850
+ node -e "
851
+ const fs = require('fs'); const p = '$F294_WIRING_MUT'; const s = fs.readFileSync(p, 'utf8');
852
+ const FROM = 'const maxWaitAttempts = opts.maxWaitAttempts ?? DEFAULT_MAX_WAIT_ATTEMPTS;';
853
+ const TO = 'const maxWaitAttempts = DEFAULT_MAX_WAIT_ATTEMPTS; // MUTANT (F-294): opts.maxWaitAttempts ignored entirely';
854
+ if (!s.includes(FROM)) throw new Error('F-294 wiring mutant pattern not found in convergence.mjs -- source moved, update this mutation');
855
+ fs.writeFileSync(p, s.replace(FROM, TO));
856
+ "
857
+ mutant_wiring=$(node --input-type=module -e "
858
+ const M = await import('$F294_WIRING_MUT');
859
+ $MK_SEQ_DRAW
860
+ const args = M.parseArgs(['--dry-run', '--max-wait-attempts', '5']);
861
+ const seq = $F294_SEQ;
862
+ const r = M.fillArm(mkSeqDraw(seq), { n: 1, maxWaitAttempts: args.maxWaitAttempts, report: () => {} });
863
+ process.stdout.write(JSON.stringify({ waitExhausted: r.waitExhausted, arm: r.arm }));
864
+ ")
865
+ check "mutant (F-294: fillArm ignores opts.maxWaitAttempts) reproduces the exact pre-fix gap -- --max-wait-attempts 5 no longer prevents censoring, catching the regression the checks above exist for" \
866
+ "$mutant_wiring" '{"waitExhausted":true,"arm":[]}'
867
+ pristine_wiring=$(cj "$MK_SEQ_DRAW
868
+ const args = M.parseArgs(['--dry-run', '--max-wait-attempts', '5']);
869
+ const seq = $F294_SEQ;
870
+ const r = M.fillArm(mkSeqDraw(seq), { n: 1, maxWaitAttempts: args.maxWaitAttempts, report: () => {} });
871
+ process.stdout.write(JSON.stringify({ waitExhausted: r.waitExhausted, arm: r.arm }));
872
+ ")
873
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still lets --max-wait-attempts 5 prevent censoring" \
874
+ "$pristine_wiring" '{"waitExhausted":false,"arm":[1]}'
875
+ rm -rf "$F294_WIRING_MUT_DIR"
876
+ trap - EXIT
877
+
878
+ # --- the shard namespace carries no fixture identity.
879
+ # Before this, loopShardPath() took no fixture component at all -- task02's draw 0 and a NEW
880
+ # fixture's draw 0 landed at the byte-identical path, and resumeArm() folded both as one arm,
881
+ # mixing two fixtures' draws into a single mean/sd. Demonstrated below by construction, then by a
882
+ # mutation that reproduces the exact collision.
883
+ F284_SHA="f284ns$(date +%s)"
884
+ check "loopShardPath: two DIFFERENT fixtureIds at the SAME sha/index now resolve to DIFFERENT paths -- the collision is gone" \
885
+ "$(cj "process.stdout.write(String(M.loopShardPath('$F284_SHA', M.TASK_ID, 0, 'task02-code') !== M.loopShardPath('$F284_SHA', M.TASK_ID, 0, 'task02-code-degraded')));")" \
886
+ "true"
887
+ check "loopShardPath: fixtureId OMITTED still reads the flat path -- unchanged from every shard on disk before this iteration (constraint 1)" \
888
+ "$(cj "process.stdout.write(String(M.loopShardPath('$F284_SHA', M.TASK_ID, 0) === M.loopShardPath('$F284_SHA', M.TASK_ID, 0, null)));")" \
889
+ "true"
890
+
891
+ # resumeArm folds STRICTLY per fixtureId -- two fixtures' shards written at the SAME index of the
892
+ # SAME sha never merge into one arm.
893
+ cj "
894
+ const occA = new Set(); M.writeNextShard('$F284_SHA', M.TASK_ID, 5, occA, 0, 3, null, null, 'task02-code');
895
+ const occB = new Set(); M.writeNextShard('$F284_SHA', M.TASK_ID, 5, occB, 0, 9, null, null, 'task02-code-degraded');
896
+ " >/dev/null
897
+ check "resumeArm(sha, taskId, n, 'task02-code') folds only its OWN fixture's shard, [3] -- not the OTHER fixture's [9] written at the same index" \
898
+ "$(cj "process.stdout.write(JSON.stringify(M.resumeArm('$F284_SHA', M.TASK_ID, 5, 'task02-code').resume));")" "[3]"
899
+ check "resumeArm(sha, taskId, n, 'task02-code-degraded') folds only [9], not [3]" \
900
+ "$(cj "process.stdout.write(JSON.stringify(M.resumeArm('$F284_SHA', M.TASK_ID, 5, 'task02-code-degraded').resume));")" "[9]"
901
+ check "writeNextShard: the record itself carries fixture identity (F-284), not only the path -- rec.fixture" \
902
+ "$(cj "const fs = await import('node:fs'); const rec = JSON.parse(fs.readFileSync(M.loopShardPath('$F284_SHA', M.TASK_ID, 0, 'task02-code'), 'utf8')); process.stdout.write(rec.fixture);")" \
903
+ "task02-code"
904
+ rm -rf "$ROOT/tests/evals/results/$F284_SHA"
905
+
906
+ # makeShardWriter()/writeNextShard(): fixtureId threads through the EXACT assembly drawArmForSha()
907
+ # uses, without a live draw -- same style as the shard-verdict wiring checks above.
908
+ F284_WIRING_SHA="f284wiring$(date +%s)"
909
+ check "the exact assembly drawArmForSha() uses threads fixtureId into both the shard's path and its record" \
910
+ "$(cj "
911
+ const fs = await import('node:fs');
912
+ const makeDraw = () => ({ read: () => ({ status: 'done', pass: 2 }), retry() {}, cleanup() {} });
913
+ const occ = new Set();
914
+ const { newDraw, onDraw } = M.makeShardWriter(makeDraw, '$F284_WIRING_SHA', M.TASK_ID, 1, occ, 0, 'task02-code');
915
+ M.fillArm(newDraw, { n: 1, onDraw });
916
+ const p = M.loopShardPath('$F284_WIRING_SHA', M.TASK_ID, 0, 'task02-code');
917
+ process.stdout.write(JSON.stringify({ shardAtFixturePath: fs.existsSync(p), recordFixture: JSON.parse(fs.readFileSync(p, 'utf8')).fixture }));
918
+ ")" '{"shardAtFixturePath":true,"recordFixture":"task02-code"}'
919
+ rm -rf "$ROOT/tests/evals/results/$F284_WIRING_SHA"
920
+
921
+ # writeCensorRecord() also records fixture identity -- the censored/ evidence stream gets
922
+ # the same honesty about which fixture it came from, even though (unlike numbered shards) it stays
923
+ # unqualified by directory, since nothing folds censor records back into an arm (a known gap).
924
+ F284_CENSOR_SHA="f284censor$(date +%s)"
925
+ check "writeCensorRecord(..., fixtureId) persists it alongside the censor payload" \
926
+ "$(cj "
927
+ const fs = await import('node:fs');
928
+ const seq = M.writeCensorRecord('$F284_CENSOR_SHA', M.TASK_ID, { elapsedMs: 1, waitAttempts: 1, lastState: { status: 'running', historyEmpty: true, stateReadable: true } }, 'task02-code');
929
+ process.stdout.write(JSON.parse(fs.readFileSync(M.censorRecordPath('$F284_CENSOR_SHA', M.TASK_ID, seq), 'utf8')).fixture);
930
+ ")" "task02-code"
931
+ rm -rf "$ROOT/tests/evals/results/$F284_CENSOR_SHA"
932
+
933
+ # Legacy shards (every shard written before fixture identity existed, including the five quota-paid ones
934
+ # the committed baseline rests on) carry NO fixture key at all -- taken to mean UNKNOWN, never assumed to be
935
+ # task02-code (the default) or any other fixture. Staged as a synthetic legacy shard so this stays
936
+ # hermetic and portable across clones/CI that don't carry the real, gitignored quota-paid data.
937
+ F284_LEGACY_SHA="f284legacy$(date +%s)"
938
+ cj "
939
+ const fs = await import('node:fs'); const path = await import('node:path');
940
+ const p = M.loopShardPath('$F284_LEGACY_SHA', M.TASK_ID, 0);
941
+ fs.mkdirSync(path.dirname(p), { recursive: true });
942
+ fs.writeFileSync(p, JSON.stringify({ sha: '$F284_LEGACY_SHA', taskId: M.TASK_ID, schema: M.LOOP_SCHEMA_VERSION, run: { index: 0, pass: 1 } }) + '\n');
943
+ " >/dev/null
944
+ check "a legacy shard (no fixture key at all) still folds via resumeArm() with fixtureId OMITTED -- the unqualified/unknown bucket" \
945
+ "$(cj "process.stdout.write(JSON.stringify(M.resumeArm('$F284_LEGACY_SHA', M.TASK_ID, 1).resume));")" "[1]"
946
+ check "the SAME legacy shard is invisible when a REAL fixtureId is asked for -- 'unknown' is never silently treated as 'task02-code'" \
947
+ "$(cj "process.stdout.write(JSON.stringify(M.resumeArm('$F284_LEGACY_SHA', M.TASK_ID, 1, 'task02-code').resume));")" "[]"
948
+ rm -rf "$ROOT/tests/evals/results/$F284_LEGACY_SHA"
949
+
950
+ # Mutation: revert loopShardPath() to its pre-fix shape (fixtureId accepted but ignored) and
951
+ # reproduce the EXACT collision the original defect demonstrated by hand -- two different fixtures'
952
+ # draw 0 landing at the byte-identical path. Staged on a scratch copy, never the tracked file.
953
+ # Occurrence count asserted, not just presence (standing discipline): this exact anchor is unique
954
+ # in the file, unlike e.g. `mkdirSync(dirname(p), { recursive: true });`, which occurs twice and
955
+ # would select the wrong one positionally under a plain .replace().
956
+ F284_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
957
+ trap 'rm -rf "$F284_MUT_DIR"' EXIT
958
+ F284_MUT="$F284_MUT_DIR/convergence.mjs"
959
+ cp "$ROOT/$CVD" "$F284_MUT"
960
+ ln -s "$ROOT/tests/evals/lib" "$F284_MUT_DIR/lib"
961
+ ln -s "$ROOT/tests/evals/run.mjs" "$F284_MUT_DIR/run.mjs"
962
+ node -e "
963
+ const fs = require('fs'); const p = '$F284_MUT'; const s = fs.readFileSync(p, 'utf8');
964
+ const FROM = 'const dir = fixtureId == null ? loopShardDir(sha) : join(loopShardDir(sha), fixtureId);';
965
+ const TO = 'const dir = loopShardDir(sha); // MUTANT (F-284): fixtureId accepted but ignored, the pre-fix shape';
966
+ const count = s.split(FROM).length - 1;
967
+ if (count !== 1) throw new Error('F-284 mutant anchor occurs ' + count + ' time(s), not exactly 1 -- update this mutation');
968
+ fs.writeFileSync(p, s.replace(FROM, TO));
969
+ "
970
+ mutant_collision=$(node --input-type=module -e "
971
+ const M = await import('$F284_MUT');
972
+ process.stdout.write(String(M.loopShardPath('$F284_SHA', M.TASK_ID, 0, 'task02-code') === M.loopShardPath('$F284_SHA', M.TASK_ID, 0, 'task02-code-degraded')));
973
+ ")
974
+ check "mutant (F-284: fixtureId ignored, the pre-fix shape) reproduces the EXACT collision the original defect demonstrated by hand -- task02's draw 0 and a NEW fixture's draw 0 land at the SAME path" \
975
+ "$mutant_collision" "true"
976
+ pristine_collision=$(cj "process.stdout.write(String(M.loopShardPath('$F284_SHA', M.TASK_ID, 0, 'task02-code') === M.loopShardPath('$F284_SHA', M.TASK_ID, 0, 'task02-code-degraded')));")
977
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) no longer collides" \
978
+ "$pristine_collision" "false"
979
+ rm -rf "$F284_MUT_DIR"
980
+ trap - EXIT
981
+
982
+ # --- --merge/--certify ignored --fixture entirely, so a fixture-qualified arm on
983
+ # disk silently underreported as 0/N through the unqualified read -- disjoint from the write side.
984
+ F285_SHA="f285$(date +%s)"
985
+ cj "const occ = new Set(); M.writeNextShard('$F285_SHA', M.TASK_ID, 5, occ, 0, 4, null, null, 'tests/evals/fixtures/task02-code');" >/dev/null
986
+ check "--merge --fixture <id> folds that fixture's own arm, [4] -- the read side now agrees with the write side (F-285)" \
987
+ "$(node "$CVD" --merge "$F285_SHA" --fixture tests/evals/fixtures/task02-code --runs 5 | grep -c 'arm: \[4\]')" "1"
988
+ check "--merge WITHOUT --fixture on the SAME sha now WARNS a fixture-qualified sibling exists, instead of silently reading 0/N (F-285)" \
989
+ "$(node "$CVD" --merge "$F285_SHA" --runs 5 2>&1 >/dev/null | grep -c 'also has fixture-qualified draws')" "1"
990
+
991
+ # Mutation: drop --fixture from reportArm()'s call site, reproducing the disjoint read.
992
+ F285_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
993
+ trap 'rm -rf "$F285_MUT_DIR"' EXIT
994
+ F285_MUT="$F285_MUT_DIR/convergence.mjs"
995
+ cp "$ROOT/$CVD" "$F285_MUT"
996
+ ln -s "$ROOT/tests/evals/lib" "$F285_MUT_DIR/lib"
997
+ ln -s "$ROOT/tests/evals/run.mjs" "$F285_MUT_DIR/run.mjs"
998
+ node -e "
999
+ const fs = require('fs'); const p = '$F285_MUT'; const s = fs.readFileSync(p, 'utf8');
1000
+ const FROM = 'reportArm(validateSha(args.merge ?? args.certify), args.runs, resolveFixtureId(args.fixture));';
1001
+ const TO = 'reportArm(validateSha(args.merge ?? args.certify), args.runs); // MUTANT (F-285): --fixture never threaded';
1002
+ const count = s.split(FROM).length - 1;
1003
+ if (count !== 1) throw new Error('F-285 mutant anchor occurs ' + count + ' time(s), not exactly 1 -- update this mutation');
1004
+ fs.writeFileSync(p, s.replace(FROM, TO));
1005
+ "
1006
+ mutant_merge=$(node "$F285_MUT" --merge "$F285_SHA" --fixture tests/evals/fixtures/task02-code --runs 5 | grep -c 'arm: \[4\]')
1007
+ check "mutant (F-285: --fixture dropped before reportArm) can no longer see the fixture-qualified arm -- 0, not 1" \
1008
+ "$mutant_merge" "0"
1009
+ pristine_merge=$(node "$CVD" --merge "$F285_SHA" --fixture tests/evals/fixtures/task02-code --runs 5 | grep -c 'arm: \[4\]')
1010
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) sees it again, 1" \
1011
+ "$pristine_merge" "1"
1012
+ rm -rf "$F285_MUT_DIR"
1013
+ trap - EXIT
1014
+ rm -rf "$ROOT/tests/evals/results/$F285_SHA"
1015
+
1016
+ # --- --fixture is now pinned to the drawn SHA's own worktree, refused (not
1017
+ # warned) if it escapes that tree or is git-dirty there. assertFixturePinned() is the guard;
1018
+ # resolveFixtureDir()/drawArmForSha() are its call sites.
1019
+ PIN_SRC=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1020
+ trap 'rm -rf "$PIN_SRC"' EXIT
1021
+ mkdir -p "$PIN_SRC/fixtures/task02-code"
1022
+ echo hello > "$PIN_SRC/fixtures/task02-code/a.txt"
1023
+ check "assertFixturePinned: a fixture path INSIDE sourceDir is accepted (unversioned source, sha null -- no git-dirty check applies)" \
1024
+ "$(cj "try { M.assertFixturePinned('$PIN_SRC', '$PIN_SRC/fixtures/task02-code', null); process.stdout.write('ok'); } catch (e) { process.stdout.write('threw: ' + e.message); }")" \
1025
+ "ok"
1026
+ PIN_OUTSIDE=$(mktemp -d)
1027
+ check "assertFixturePinned: a fixture path OUTSIDE sourceDir is refused, not silently accepted" \
1028
+ "$(cj "try { M.assertFixturePinned('$PIN_SRC', '$PIN_OUTSIDE', null); process.stdout.write('NO THROW'); } catch { process.stdout.write('threw'); }")" \
1029
+ "threw"
1030
+ rm -rf "$PIN_OUTSIDE"
1031
+
1032
+ # The git-dirty half needs a REAL repo (git status is the assertion, not a comment claiming
1033
+ # nothing touches the worktree) -- built and torn down here, never the tracked repo.
1034
+ (cd "$PIN_SRC" && git init -q -b main && git config user.email x@x.invalid && git config user.name x && git add -A && git commit -qm baseline) >/dev/null 2>&1
1035
+ check "assertFixturePinned: a CLEAN worktree (freshly committed, nothing touched since) passes even with a real sha" \
1036
+ "$(cj "try { M.assertFixturePinned('$PIN_SRC', '$PIN_SRC/fixtures/task02-code', 'deadbeef'); process.stdout.write('ok'); } catch (e) { process.stdout.write('threw: ' + e.message); }")" \
1037
+ "ok"
1038
+ echo modified > "$PIN_SRC/fixtures/task02-code/a.txt"
1039
+ check "assertFixturePinned: an uncommitted edit to the fixture inside the worktree is refused as DIRTY relative to the drawn SHA" \
1040
+ "$(cj "try { M.assertFixturePinned('$PIN_SRC', '$PIN_SRC/fixtures/task02-code', 'deadbeef'); process.stdout.write('NO THROW'); } catch (e) { process.stdout.write(/dirty/.test(e.message) ? 'threw-dirty' : 'threw-other: ' + e.message); }")" \
1041
+ "threw-dirty"
1042
+ check "assertFixturePinned: the SAME dirty worktree is NOT checked when the source is unversioned (sha null) -- resolveSource() already documents that case as non-reproducible" \
1043
+ "$(cj "try { M.assertFixturePinned('$PIN_SRC', '$PIN_SRC/fixtures/task02-code', null); process.stdout.write('ok'); } catch (e) { process.stdout.write('threw: ' + e.message); }")" \
1044
+ "ok"
1045
+
1046
+ # --fixture IS sourceDir -- relative() returns '', join()'s no-op aliases onto the bucket.
1047
+ check "assertFixturePinned: --fixture . (rel === '') is refused, not aliased onto the unqualified bucket (F-286)" \
1048
+ "$(cj "try { M.assertFixturePinned('$PIN_SRC', '$PIN_SRC', null); process.stdout.write('NO THROW'); } catch { process.stdout.write('threw'); }")" \
1049
+ "threw"
1050
+ mkdir -p "$PIN_SRC/..scratch" # a CONTAINED sibling merely named like a parent ref
1051
+ check "assertFixturePinned: a CONTAINED dir named ..scratch is accepted, not falsely refused as an escape (F-287)" \
1052
+ "$(cj "try { M.assertFixturePinned('$PIN_SRC', '$PIN_SRC/..scratch', null); process.stdout.write('ok'); } catch (e) { process.stdout.write('threw: ' + e.message); }")" \
1053
+ "ok"
1054
+ rm -rf "$PIN_SRC"
1055
+ trap - EXIT
1056
+
1057
+ # CLI integration: an explicit --fixture given as a path RELATIVE TO THE SOURCE TREE resolves
1058
+ # inside the checked-out worktree (not this shell's cwd) -- the SHA-pin actually takes effect, not
1059
+ # merely accepted.
1060
+ dryrun_pinned=$(node "$CVD" --dry-run --source HEAD --fixture tests/evals/fixtures/task02-code)
1061
+ dryrun_pinned_fixture=$(printf '%s' "$dryrun_pinned" | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>process.stdout.write(JSON.parse(s).fixture))")
1062
+ check "--dry-run --fixture <source-relative path> resolves to a path INSIDE the checked-out worktree, not \$ROOT (F-284 actually took effect, not merely accepted)" \
1063
+ "$(case "$dryrun_pinned_fixture" in "$ROOT"/*) echo "still-rooted-at-ROOT" ;; *task02-code) echo "inside-worktree" ;; *) echo "unexpected: $dryrun_pinned_fixture" ;; esac)" \
1064
+ "inside-worktree"
1065
+ # assert the MESSAGE -- git itself refuses an out-of-worktree pathspec independent of our
1066
+ # guard, so exit 1 alone can't attribute the refusal (neutering the check below still exits 1).
1067
+ escape_head_out=$(node "$CVD" --dry-run --source HEAD --fixture /tmp 2>&1 >/dev/null)
1068
+ check "--dry-run --fixture <path escaping the resolved source tree> is refused BY OUR OWN GUARD, not merely exit 1 (F-288)" \
1069
+ "$(printf '%s' "$escape_head_out" | grep -c 'must resolve to a real subdirectory')" "1"
1070
+
1071
+ # Mutation: neuter assertFixturePinned()'s containment check and confirm the escape above is no
1072
+ # longer refused -- the guard is load-bearing, not decorative.
1073
+ F284_PIN_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1074
+ trap 'rm -rf "$F284_PIN_MUT_DIR"' EXIT
1075
+ F284_PIN_MUT="$F284_PIN_MUT_DIR/convergence.mjs"
1076
+ cp "$ROOT/$CVD" "$F284_PIN_MUT"
1077
+ ln -s "$ROOT/tests/evals/lib" "$F284_PIN_MUT_DIR/lib"
1078
+ ln -s "$ROOT/tests/evals/run.mjs" "$F284_PIN_MUT_DIR/run.mjs"
1079
+ node -e "
1080
+ const fs = require('fs'); const p = '$F284_PIN_MUT'; const s = fs.readFileSync(p, 'utf8');
1081
+ const FROM = \"if (rel === '' || rel === '..' || rel.startsWith('..' + sep)) {\";
1082
+ const TO = 'if (false) { // MUTANT (F-284/F-286/F-287): the containment check never fires';
1083
+ const count = s.split(FROM).length - 1;
1084
+ if (count !== 1) throw new Error('F-284 pin mutant anchor occurs ' + count + ' time(s), not exactly 1 -- update this mutation');
1085
+ fs.writeFileSync(p, s.replace(FROM, TO));
1086
+ "
1087
+ # Unversioned source (--source ., sha null) so the git-dirty defense-in-depth check (which itself
1088
+ # refuses a path outside the repo, git's own error, not this module's) is out of the picture --
1089
+ # containment is the ONLY guard standing, isolating exactly what this mutation tests.
1090
+ mutant_pin_exit=$(node "$F284_PIN_MUT" --dry-run --source . --fixture /tmp >/dev/null 2>&1; echo $?)
1091
+ check "mutant (F-284/F-286/F-287: assertFixturePinned's containment check neutered) lets --fixture /tmp through -- confirming the guard above currently depends on this exact check" \
1092
+ "$mutant_pin_exit" "0"
1093
+ pristine_pin_exit=$(node "$CVD" --dry-run --source . --fixture /tmp >/dev/null 2>&1; echo $?)
1094
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still refuses --fixture /tmp" \
1095
+ "$pristine_pin_exit" "1"
1096
+ rm -rf "$F284_PIN_MUT_DIR"
1097
+ trap - EXIT
1098
+
1099
+ # --- committed hash baseline for the five quota-paid shards the baseline rests on (results/ is
1100
+ # gitignored, so a git-diff check there is vacuously empty) -- MANIFEST.sha256 (`git add -f`'d past
1101
+ # the ignore) is verified when present, skipped VISIBLY when absent, never silently.
1102
+ CONV_DIR="$ROOT/tests/evals/results/39411eb4d2785c47e1491e0b6c54be174a3ac753/convergence"
1103
+ conv_n=$(ls "$CONV_DIR"/loop-code-loop-*.json 2>/dev/null | wc -l | tr -d ' ')
1104
+ if [ "$conv_n" = "5" ]; then
1105
+ (cd "$CONV_DIR" && sha256sum -c --status MANIFEST.sha256)
1106
+ check "F-289: the five quota-paid shards match the committed MANIFEST.sha256 baseline" "$?" "0"
1107
+ elif [ "$conv_n" = "0" ]; then
1108
+ echo " (skipped: $CONV_DIR's shards not present -- results/ is gitignored except MANIFEST.sha256, expected on a fresh clone/CI)"
1109
+ else
1110
+ bad "F-289: $CONV_DIR has $conv_n of 5 quota-paid shards on disk -- a real gap, not the expected all-or-nothing fresh-clone absence"
1111
+ fi
1112
+ # Guard shown to fail: verified BY HAND against a mktemp -d copy of the real shards, never the
1113
+ # tracked files (sha256sum -c is external, already battle-tested, not re-proven here) -- corrupt
1114
+ # flips OK to FAILED, restore flips back; real shards hashed identical before/after. Coder's report.
1115
+
1116
+ # --- a session-limit (or other hard-invocation-failure) exit must not be recorded as draw --
1117
+ # data. `startDraw()`'s `retry` used to discard `invokeCommand()`'s result outright, so a spawned
1118
+ # `claude` that hit the account's session limit read as `malformed` (before loop state existed) or
1119
+ # `running` (after) -- both a harness-EXTERNAL condition misrecorded as a fact about the definition
1120
+ # set. Hermetic throughout: every invocation below is a canned {ok,status,timedOut,stdout,stderr,
1121
+ # error} object or a stub `claude` binary that never reaches a model -- no live draw anywhere here.
1122
+ MK_INVOCATION_DRAW='
1123
+ function mkInvocationDraw(steps) {
1124
+ // steps[0] covers the OPENING invocation (mirrors startDraw()'"'"'s own eager retry() call);
1125
+ // steps[i] covers the i-th LATER retry() call. An exhausted sequence repeats its last step.
1126
+ return () => {
1127
+ let i = 0;
1128
+ let cur = steps[0];
1129
+ return {
1130
+ read: () => cur.state,
1131
+ retry: () => { i = Math.min(i + 1, steps.length - 1); cur = steps[i]; },
1132
+ cleanup() {},
1133
+ lastInvocation: () => cur.invocation,
1134
+ };
1135
+ };
1136
+ }
1137
+ '
1138
+
1139
+ check "isHardInvocationFailure: undefined/null (every EXISTING synthetic handle in this suite -- none implement lastInvocation) reads as no info, never a failure" \
1140
+ "$(cj "process.stdout.write(JSON.stringify([M.isHardInvocationFailure(undefined), M.isHardInvocationFailure(null)]));")" \
1141
+ "[false,false]"
1142
+
1143
+ check "isHardInvocationFailure({}): an invocation object with NO recognizable field actually set reads the same as no info (F-326 -- the docstring's promise, now true of the code: status must be genuinely present and non-zero to count, not merely undefined !== 0)" \
1144
+ "$(cj "process.stdout.write(String(M.isHardInvocationFailure({})));")" "false"
1145
+
1146
+ # Staged: revert the status fix (invocation.status ?? 0 -> bare invocation.status) and confirm the
1147
+ # {} case above flips from false to true -- undefined !== 0 reads as a failure again.
1148
+ F326_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1149
+ trap 'rm -rf "$F326_MUT_DIR"' EXIT
1150
+ F326_MUT="$F326_MUT_DIR/convergence.mjs"
1151
+ cp "$ROOT/$CVD" "$F326_MUT"
1152
+ ln -s "$ROOT/tests/evals/lib" "$F326_MUT_DIR/lib"
1153
+ ln -s "$ROOT/tests/evals/run.mjs" "$F326_MUT_DIR/run.mjs"
1154
+ node -e "
1155
+ const fs = require('fs'); const p = '$F326_MUT'; const s = fs.readFileSync(p, 'utf8');
1156
+ const FROM = \"if ((invocation.status ?? 0) !== 0 || Boolean(invocation.error)) return true;\";
1157
+ const TO = 'if (invocation.status !== 0 || Boolean(invocation.error)) return true; // MUTANT (F-326): absent-status guard removed';
1158
+ const count = s.split(FROM).length - 1;
1159
+ if (count !== 1) throw new Error('F-326 mutant anchor occurs ' + count + ' time(s), not exactly 1 -- update this mutation');
1160
+ fs.writeFileSync(p, s.replace(FROM, TO));
1161
+ "
1162
+ mutant_326=$(node --input-type=module -e "
1163
+ const M = await import('$F326_MUT');
1164
+ process.stdout.write(String(M.isHardInvocationFailure({})));
1165
+ ")
1166
+ check "mutant (F-326: absent-status guard reverted to bare !== 0) reintroduces the false positive -- isHardInvocationFailure({}) reads true again" \
1167
+ "$mutant_326" "true"
1168
+ pristine_326=$(cj "process.stdout.write(String(M.isHardInvocationFailure({})));")
1169
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still reads false" \
1170
+ "$pristine_326" "false"
1171
+ rm -rf "$F326_MUT_DIR"
1172
+ trap - EXIT
1173
+
1174
+ check "fillArm: the OPENING invocation hitting the session-limit text throws HardInvocationFailureError immediately, distinguishable message, reason:'session-limit' (F-323)" \
1175
+ "$(cj "$MK_INVOCATION_DRAW
1176
+ const inv = { ok:false, status:0, timedOut:false, stdout: 'prefix ' + M.SESSION_LIMIT_SIGNATURE + ' suffix', stderr:'', error:null };
1177
+ let caught = null;
1178
+ try { M.fillArm(mkInvocationDraw([{ invocation: inv, state: null }]), { n: 1, report: () => {} }); } catch (e) { caught = e; }
1179
+ process.stdout.write(JSON.stringify({ isHardFailure: caught instanceof M.HardInvocationFailureError, reason: caught ? caught.reason : null, message: caught ? caught.message : null }));
1180
+ ")" \
1181
+ '{"isHardFailure":true,"reason":"session-limit","message":"convergence: invocation hard-failed (account session limit) -- stopping the arm now; not recorded as a censored or malformed draw, and no replacement is drawn for it (F-308)"}'
1182
+
1183
+ check "fillArm: a LATER retry() hitting the session-limit text (after one genuine 'running' read) also throws HardInvocationFailureError -- the same check, not just an opening-call special case" \
1184
+ "$(cj "$MK_INVOCATION_DRAW
1185
+ const okInv = { ok:true, status:0, timedOut:false, stdout:'', stderr:'', error:null };
1186
+ const badInv = { ok:false, status:0, timedOut:false, stdout: M.SESSION_LIMIT_SIGNATURE, stderr:'', error:null };
1187
+ const seq = [{ invocation: okInv, state: { status:'running' } }, { invocation: badInv, state: { status:'running' } }];
1188
+ let caught = null;
1189
+ try { M.fillArm(mkInvocationDraw(seq), { n: 1, maxWaitAttempts: 3, report: () => {} }); } catch (e) { caught = e; }
1190
+ process.stdout.write(String(caught instanceof M.HardInvocationFailureError));
1191
+ ")" "true"
1192
+
1193
+ check "fillArm: a non-zero status with NO session-limit text is the SAME failure class, message names the status, reason:'nonzero-exit'" \
1194
+ "$(cj "$MK_INVOCATION_DRAW
1195
+ const inv = { ok:false, status:1, timedOut:false, stdout:'', stderr:'', error:null };
1196
+ let caught = null;
1197
+ try { M.fillArm(mkInvocationDraw([{ invocation: inv, state: null }]), { n: 1, report: () => {} }); } catch (e) { caught = e; }
1198
+ process.stdout.write(JSON.stringify({ isHardFailure: caught instanceof M.HardInvocationFailureError, reason: caught ? caught.reason : null, namesStatus: /status 1/.test(caught ? caught.message : '') }));
1199
+ ")" '{"isHardFailure":true,"reason":"nonzero-exit","namesStatus":true}'
1200
+
1201
+ check "fillArm: a set spawn-level error with no text/status signal is ALSO the same failure class, message names it, reason:'spawn-error'" \
1202
+ "$(cj "$MK_INVOCATION_DRAW
1203
+ const inv = { ok:false, status:null, timedOut:false, stdout:'', stderr:'', error:'ENOENT' };
1204
+ let caught = null;
1205
+ try { M.fillArm(mkInvocationDraw([{ invocation: inv, state: null }]), { n: 1, report: () => {} }); } catch (e) { caught = e; }
1206
+ process.stdout.write(JSON.stringify({ isHardFailure: caught instanceof M.HardInvocationFailureError, reason: caught ? caught.reason : null, namesError: /spawn error: ENOENT/.test(caught ? caught.message : '') }));
1207
+ ")" '{"isHardFailure":true,"reason":"spawn-error","namesError":true}'
1208
+
1209
+ check "isHardInvocationFailure: status GENUINELY omitted (undefined) but every other field present and normal reads as no failure, same as F-326's fully-empty {} -- (invocation.status ?? 0) !== 0 only neutralises an ABSENT status, it is not fooled into treating undefined as some nonzero value" \
1210
+ "$(cj "process.stdout.write(String(M.isHardInvocationFailure({ ok:true, timedOut:false, stdout:'', stderr:'', error:null })));")" "false"
1211
+
1212
+ # F-324b: the text branch alone is gated on the draw's OWN resulting state not already showing a
1213
+ # completed pass -- a healthy draw's own closing summary IS this invocation's stdout under
1214
+ # --print, and can echo SESSION_LIMIT_SIGNATURE as prose (about this very guard) without that
1215
+ # being the incident. status/error stay unconditional regardless of state, checked separately
1216
+ # above. Uses the committed `done` golden (tests/scripts/goldens/loop-state-done.json) --
1217
+ # real data, not a hand-typed shape that could drift from what classifyDraw() actually requires.
1218
+ F324_DONE_STATE=$(node -e "process.stdout.write(JSON.stringify(JSON.parse(require('fs').readFileSync('$ROOT/tests/scripts/goldens/loop-state-done.json','utf8'))))")
1219
+ check "isHardInvocationFailure: text match ALONE is suppressed when the resulting state already shows a completed draw (a real 'done' golden, pass 2) -- the false-positive surface F-324 exists to close" \
1220
+ "$(cj "
1221
+ const doneState = $F324_DONE_STATE;
1222
+ const inv = { ok:false, status:0, timedOut:false, stdout: 'Done. Added a guard for the text \"' + M.SESSION_LIMIT_SIGNATURE + '\" per the plan.', stderr:'', error:null };
1223
+ process.stdout.write(String(M.isHardInvocationFailure(inv, doneState)));
1224
+ ")" "false"
1225
+ check "isHardInvocationFailure: the SAME text match is NOT suppressed when the resulting state is still running (not done) -- the gate narrows to completed draws only, it does not blunt the branch generally" \
1226
+ "$(cj "
1227
+ const inv = { ok:false, status:0, timedOut:false, stdout: M.SESSION_LIMIT_SIGNATURE, stderr:'', error:null };
1228
+ process.stdout.write(String(M.isHardInvocationFailure(inv, { status:'running' })));
1229
+ ")" "true"
1230
+ check "isHardInvocationFailure: a non-zero status is NOT suppressed by a completed state -- only the text branch is gated, status/error stay unconditional per the review's own instruction" \
1231
+ "$(cj "
1232
+ const doneState = $F324_DONE_STATE;
1233
+ const inv = { ok:false, status:1, timedOut:false, stdout:'', stderr:'', error:null };
1234
+ process.stdout.write(String(M.isHardInvocationFailure(inv, doneState)));
1235
+ ")" "true"
1236
+
1237
+ # Staged: revert the F-324b gate (text branch reads unconditionally again, the pre-fix shape) and
1238
+ # confirm the healthy-draw false positive above flips from suppressed to thrown.
1239
+ F324_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1240
+ trap 'rm -rf "$F324_MUT_DIR"' EXIT
1241
+ F324_MUT="$F324_MUT_DIR/convergence.mjs"
1242
+ cp "$ROOT/$CVD" "$F324_MUT"
1243
+ ln -s "$ROOT/tests/evals/lib" "$F324_MUT_DIR/lib"
1244
+ ln -s "$ROOT/tests/evals/run.mjs" "$F324_MUT_DIR/run.mjs"
1245
+ node -e "
1246
+ const fs = require('fs'); const p = '$F324_MUT'; const s = fs.readFileSync(p, 'utf8');
1247
+ const FROM = \"if (loopStateJson != null && isTerminalDrawKind(classifyDraw(loopStateJson).kind)) return false;\";
1248
+ const TO = 'if (false) return false; // MUTANT (F-324b): completion gate removed';
1249
+ const count = s.split(FROM).length - 1;
1250
+ if (count !== 1) throw new Error('F-324b gate mutant anchor occurs ' + count + ' time(s), not exactly 1 -- update this mutation');
1251
+ fs.writeFileSync(p, s.replace(FROM, TO));
1252
+ "
1253
+ mutant_324=$(node --input-type=module -e "
1254
+ const M = await import('$F324_MUT');
1255
+ const doneState = $F324_DONE_STATE;
1256
+ const inv = { ok:false, status:0, timedOut:false, stdout: 'Done. Added a guard for the text \"' + M.SESSION_LIMIT_SIGNATURE + '\" per the plan.', stderr:'', error:null };
1257
+ process.stdout.write(String(M.isHardInvocationFailure(inv, doneState)));
1258
+ ")
1259
+ check "mutant (F-324b: completion gate removed) reintroduces the false positive -- a healthy, completed draw now reads as a hard failure again" \
1260
+ "$mutant_324" "true"
1261
+ pristine_324=$(cj "
1262
+ const doneState = $F324_DONE_STATE;
1263
+ const inv = { ok:false, status:0, timedOut:false, stdout: 'Done. Added a guard for the text \"' + M.SESSION_LIMIT_SIGNATURE + '\" per the plan.', stderr:'', error:null };
1264
+ process.stdout.write(String(M.isHardInvocationFailure(inv, doneState)));
1265
+ ")
1266
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still suppresses it" \
1267
+ "$pristine_324" "false"
1268
+ rm -rf "$F324_MUT_DIR"
1269
+ trap - EXIT
1270
+
1271
+ check "fillArm: timedOut:true stays on the EXISTING running/censor path -- never this new outcome, even though a real timeout also sets its own error field" \
1272
+ "$(cj "$MK_INVOCATION_DRAW
1273
+ const inv = { ok:false, status:null, timedOut:true, stdout:'', stderr:'', error:'ETIMEDOUT' };
1274
+ const r = M.fillArm(mkInvocationDraw([{ invocation: inv, state: { status:'running' } }]), { n: 1, maxWaitAttempts: 0, report: () => {} });
1275
+ process.stdout.write(JSON.stringify({ waitExhausted: r.waitExhausted, censorPresent: r.censor !== null }));
1276
+ ")" '{"waitExhausted":true,"censorPresent":true}'
1277
+
1278
+ # The exact assembly drawArmForSha() uses (makeShardWriter -> fillArm -> conditional persistence),
1279
+ # same style as the shard/censor/fixture wiring checks above: (a) the arm stops (throws), (b) no censor
1280
+ # record is written, (c) no replacement/shard slot is consumed -- resumeArm() sees nothing.
1281
+ F308_SHA="f308quota$(date +%s)"
1282
+ f308_assembly=$(node --input-type=module -e "
1283
+ const M = await import('$ROOT/$CVD');
1284
+ const fs = await import('node:fs');
1285
+ const path = await import('node:path');
1286
+ $MK_INVOCATION_DRAW
1287
+ const inv = { ok:false, status:0, timedOut:false, stdout: M.SESSION_LIMIT_SIGNATURE, stderr:'', error:null };
1288
+ const makeDraw = mkInvocationDraw([{ invocation: inv, state: null }]);
1289
+ const occ = new Set();
1290
+ const { newDraw, onDraw } = M.makeShardWriter(makeDraw, '$F308_SHA', M.TASK_ID, 1, occ, 0);
1291
+ let caught = null;
1292
+ try {
1293
+ const result = M.fillArm(newDraw, { n: 1, onDraw, report: () => {} });
1294
+ if (result.censor) M.writeCensorRecord('$F308_SHA', M.TASK_ID, result.censor);
1295
+ if (result.breach) M.writeBreachRecord('$F308_SHA', M.TASK_ID, result.breachReason);
1296
+ } catch (e) { caught = e; }
1297
+ const shardPath = M.loopShardPath('$F308_SHA', M.TASK_ID, 0);
1298
+ const censorDir = path.join(path.dirname(shardPath), 'censored');
1299
+ process.stdout.write(JSON.stringify({
1300
+ threwHardFailure: caught instanceof M.HardInvocationFailureError,
1301
+ shardExists: fs.existsSync(shardPath),
1302
+ censorDirExists: fs.existsSync(censorDir),
1303
+ resume: M.resumeArm('$F308_SHA', M.TASK_ID, 1).resume,
1304
+ }));
1305
+ " 2>&1)
1306
+ check "the exact assembly drawArmForSha() uses: a quota-exhausted opening invocation throws, writes NO shard, NO censor record, and consumes NO replacement slot (resumeArm sees nothing)" \
1307
+ "$f308_assembly" \
1308
+ '{"threwHardFailure":true,"shardExists":false,"censorDirExists":false,"resume":[]}'
1309
+ rm -rf "$ROOT/tests/evals/results/$F308_SHA"
1310
+
1311
+ # "The driver exits non-zero" (the acceptance point for the driver), proven WITHOUT a live-mode
1312
+ # CLI invocation of this file's own --source/--fixture/--runs shape -- evals-packaging.sh's
1313
+ # check audits every CLI call in this file for a dry-run/merge/certify/help/negative-argument
1314
+ # exemption specifically so nothing here can reach a real model unnoticed, and a PATH-stubbed live
1315
+ # call would need a whole new exemption category to stay honestly covered by that audit. Proven two
1316
+ # cheaper ways instead, for a property this module already establishes structurally:
1317
+ check "letting a hard invocation failure escape fillArm() UNCAUGHT (exactly what main() below does -- it has no try/catch of its own around drawArmForSha()) makes the PROCESS exit non-zero, Node's own default for an uncaught exception" \
1318
+ "$(node --input-type=module -e "
1319
+ const M = await import('$ROOT/$CVD');
1320
+ $MK_INVOCATION_DRAW
1321
+ const inv = { ok:false, status:0, timedOut:false, stdout: 'prefix ' + M.SESSION_LIMIT_SIGNATURE + ' suffix', stderr:'', error:null };
1322
+ M.fillArm(mkInvocationDraw([{ invocation: inv, state: null }]), { n: 1, report: () => {} });
1323
+ " >/dev/null 2>&1; echo $?)" "1"
1324
+ F308_MAIN_CATCH='.catch((err) => { process.stderr.write(`convergence: ${err.message}\n`); process.exit(1); });'
1325
+ check "the module-level .catch(...) chain (below main()'s own closing brace) is present exactly once -- this alone is a PRESENCE fact, not proof that nothing upstream of it intercepts a hard-invocation-failure throw first (see F-320's absence checks below for that)" \
1326
+ "$(grep -cF "$F308_MAIN_CATCH" "$ROOT/$CVD")" "1"
1327
+
1328
+ # the presence check above was staged against wrapping main()'s own
1329
+ # drawArmForSha() call in `catch (e) { if (e instanceof HardInvocationFailureError) return 0; throw
1330
+ # e; }` -- exit 0 on a quota wall, violating acceptance (c)/(d) -- and stayed green: a PRESENCE count
1331
+ # cannot prove an ABSENCE. Fixed with absence assertions in the two places such a catch could be
1332
+ # added: drawArmForSha()'s own body, and main()'s live-draw branch (the only branch that calls it).
1333
+ # awk-extracted from the real function boundary (this file's own convention: every top-level
1334
+ # function/branch closes flush left; nothing nested does), not eyeballed off a line range that could
1335
+ # drift as the file changes.
1336
+ extract_fn_body() {
1337
+ # $1 = file, $2 = a substring unique to the FIRST line of the body to extract. Prints from that
1338
+ # line through the next column-0 '}' (inclusive) -- the same brace-flush-left convention this
1339
+ # file's own mutation-staging code relies on elsewhere (e.g. the sha scratch-copy checks above).
1340
+ awk -v pat="$2" 'index($0, pat) && !p {p=1} p{print} p && /^}/{exit}' "$1"
1341
+ }
1342
+ # extract_fn_body prints NOTHING when its anchor matches no line, and
1343
+ # `grep -c` over nothing is 0 -- which is exactly what the check below asserts, so a drifted anchor
1344
+ # (e.g. the signature gaining `async`) would pass green forever. Link C is already controlled by its
1345
+ # paired mutant check asserting 1; link A had nothing. Pin the extraction non-empty first.
1346
+ dafs_body=$(extract_fn_body "$ROOT/$CVD" 'export function drawArmForSha(')
1347
+ check "F-328: drawArmForSha()'s body actually extracted (sentinel present, so the 0-catch count below cannot pass on an empty extraction)" \
1348
+ "$(printf '%s\n' "$dafs_body" | grep -c 'const pf = preflight();')" "1"
1349
+ dafs_catches=$(printf '%s\n' "$dafs_body" | grep -c 'catch')
1350
+ check "drawArmForSha()'s own body has zero catch clauses (awk-extracted, not eyeballed) -- nothing here could intercept fillArm()'s F-308 throw before it leaves this function (link A is closed structurally, not by a presence count)" \
1351
+ "$dafs_catches" "0"
1352
+ main_live_catches=$(extract_fn_body "$ROOT/$CVD" "Checked BEFORE resolveSource's worktree checkout" | grep -c 'catch')
1353
+ check "main()'s live-draw branch (awk-extracted from its own preflight comment through main()'s closing brace) has zero catch clauses -- nothing here could intercept drawArmForSha()'s F-308 throw before it reaches the module-level .catch() above (link C, the gap F-320 named, is now closed structurally)" \
1354
+ "$main_live_catches" "0"
1355
+
1356
+ # Staged against the EXACT mutation that exposed the gap: wrap main()'s own drawArmForSha() call so a
1357
+ # HardInvocationFailureError exits 0 instead of propagating. The presence check above (re-run here
1358
+ # on the mutant) must stay green, unchanged -- reproducing why it was insensitive; the new
1359
+ # live-draw-branch absence check must go red.
1360
+ F320_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1361
+ trap 'rm -rf "$F320_MUT_DIR"' EXIT
1362
+ F320_MUT="$F320_MUT_DIR/convergence.mjs"
1363
+ cp "$ROOT/$CVD" "$F320_MUT"
1364
+ ln -s "$ROOT/tests/evals/lib" "$F320_MUT_DIR/lib"
1365
+ ln -s "$ROOT/tests/evals/run.mjs" "$F320_MUT_DIR/run.mjs"
1366
+ node -e "
1367
+ const fs = require('fs'); const p = '$F320_MUT'; const s = fs.readFileSync(p, 'utf8');
1368
+ const FROM = 'const result = drawArmForSha(source.dir, fixtureDir, source.sha, liveDrawOpts(args));';
1369
+ const TO = 'let result; try { result = drawArmForSha(source.dir, fixtureDir, source.sha, liveDrawOpts(args)); } catch (e) { if (e instanceof HardInvocationFailureError) return 0; throw e; } // MUTANT (F-320): exit 0 on a quota wall';
1370
+ const count = s.split(FROM).length - 1;
1371
+ if (count !== 1) throw new Error('F-320 mutant anchor occurs ' + count + ' time(s), not exactly 1 -- update this mutation');
1372
+ fs.writeFileSync(p, s.replace(FROM, TO));
1373
+ "
1374
+ mutant_320_presence=$(grep -cF "$F308_MAIN_CATCH" "$F320_MUT")
1375
+ mutant_320_live=$(extract_fn_body "$F320_MUT" "Checked BEFORE resolveSource's worktree checkout" | grep -c 'catch')
1376
+ check "mutant (F-320: main() swallows HardInvocationFailureError and returns 0 -- exit 0 on a quota wall) -- the OLD presence check stays green, unchanged (reproducing the exact insensitivity the review found)" \
1377
+ "$mutant_320_presence" "1"
1378
+ check "mutant (F-320, same mutation): the NEW live-draw-branch absence check goes red -- a catch now exists where the review's own staged mutation put one" \
1379
+ "$mutant_320_live" "1"
1380
+ rm -rf "$F320_MUT_DIR"
1381
+ trap - EXIT
1382
+ pristine_320_live=$(extract_fn_body "$ROOT/$CVD" "Checked BEFORE resolveSource's worktree checkout" | grep -c 'catch')
1383
+ check "pristine convergence.mjs (a fresh read of the tracked file, not the mutated scratch copy) still reads zero -- the mutation above never touched the tracked file" \
1384
+ "$pristine_320_live" "0"
1385
+
1386
+ # Mutation 1 (the load-bearing one): remove BOTH failOnHardInvocationFailure() call sites in
1387
+ # fillArm() -- reproduces the EXACT pre-fix bug this guard exists to catch: a session-limit
1388
+ # exit falls through to classifyDraw(null), reads 'malformed', and after maxReplacements is
1389
+ # exhausted throws the OLD generic harness-fault Error, not HardInvocationFailureError. Staged on a
1390
+ # scratch copy, never the tracked file.
1391
+ F308_GUARD_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1392
+ trap 'rm -rf "$F308_GUARD_MUT_DIR"' EXIT
1393
+ F308_GUARD_MUT="$F308_GUARD_MUT_DIR/convergence.mjs"
1394
+ cp "$ROOT/$CVD" "$F308_GUARD_MUT"
1395
+ ln -s "$ROOT/tests/evals/lib" "$F308_GUARD_MUT_DIR/lib"
1396
+ ln -s "$ROOT/tests/evals/run.mjs" "$F308_GUARD_MUT_DIR/run.mjs"
1397
+ node -e "
1398
+ const fs = require('fs'); const p = '$F308_GUARD_MUT'; const s = fs.readFileSync(p, 'utf8');
1399
+ const FROM = 'failOnHardInvocationFailure(draw);';
1400
+ const TO = '/* MUTANT (F-308): guard removed */;';
1401
+ const count = s.split(FROM).length - 1;
1402
+ if (count !== 2) throw new Error('F-308 guard mutant anchor occurs ' + count + ' time(s), not exactly 2 -- update this mutation');
1403
+ fs.writeFileSync(p, s.split(FROM).join(TO));
1404
+ "
1405
+ mutant_guard=$(node --input-type=module -e "
1406
+ const M = await import('$F308_GUARD_MUT');
1407
+ $MK_INVOCATION_DRAW
1408
+ const inv = { ok:false, status:0, timedOut:false, stdout: 'prefix ' + M.SESSION_LIMIT_SIGNATURE + ' suffix', stderr:'', error:null };
1409
+ let caught = null;
1410
+ try { M.fillArm(mkInvocationDraw([{ invocation: inv, state: null }]), { n: 1, report: () => {} }); } catch (e) { caught = e; }
1411
+ process.stdout.write(JSON.stringify({ isHardFailure: caught instanceof M.HardInvocationFailureError, isOldHarnessFault: /malformed loop-state draws/.test(caught ? caught.message : '') }));
1412
+ ")
1413
+ check "mutant (F-308: both failOnHardInvocationFailure() call sites removed) reproduces the EXACT pre-fix misclassification -- a session-limit exit becomes '6 malformed loop-state draws ... harness fault', not HardInvocationFailureError" \
1414
+ "$mutant_guard" '{"isHardFailure":false,"isOldHarnessFault":true}'
1415
+ pristine_guard=$(cj "$MK_INVOCATION_DRAW
1416
+ const inv = { ok:false, status:0, timedOut:false, stdout: 'prefix ' + M.SESSION_LIMIT_SIGNATURE + ' suffix', stderr:'', error:null };
1417
+ let caught = null;
1418
+ try { M.fillArm(mkInvocationDraw([{ invocation: inv, state: null }]), { n: 1, report: () => {} }); } catch (e) { caught = e; }
1419
+ process.stdout.write(JSON.stringify({ isHardFailure: caught instanceof M.HardInvocationFailureError, isOldHarnessFault: /malformed loop-state draws/.test(caught ? caught.message : '') }));
1420
+ ")
1421
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still throws HardInvocationFailureError on the very first attempt" \
1422
+ "$pristine_guard" '{"isHardFailure":true,"isOldHarnessFault":false}'
1423
+ rm -rf "$F308_GUARD_MUT_DIR"
1424
+ trap - EXIT
1425
+
1426
+ # Mutation 2: neuter isHardInvocationFailure()'s TEXT-match branch alone (status/error checks left
1427
+ # intact). Correction: no observed session-limit incident records its exit
1428
+ # status through THIS harness's OWN invocation capture -- the old code discarded that value
1429
+ # outright, which is the defect being guarded -- so the status:0/error:null pairing used
1430
+ # below is an ASSUMED test shape, not an evidenced one (a prior version of this comment claimed
1431
+ # otherwise). `run.mjs:733-740` records a real counter-example the other way: four session-limit
1432
+ # exits it caught arrived `ok:false` via its own `!run.ok` gate. The text branch is therefore the
1433
+ # UNPROVEN half of this detector, kept as defence in depth against a shape this harness has not
1434
+ # itself captured -- this mutation proves the branch is load-bearing for THAT assumed shape, not
1435
+ # that the shape is confirmed real.
1436
+ F308_TEXT_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1437
+ trap 'rm -rf "$F308_TEXT_MUT_DIR"' EXIT
1438
+ F308_TEXT_MUT="$F308_TEXT_MUT_DIR/convergence.mjs"
1439
+ cp "$ROOT/$CVD" "$F308_TEXT_MUT"
1440
+ ln -s "$ROOT/tests/evals/lib" "$F308_TEXT_MUT_DIR/lib"
1441
+ ln -s "$ROOT/tests/evals/run.mjs" "$F308_TEXT_MUT_DIR/run.mjs"
1442
+ node -e "
1443
+ const fs = require('fs'); const p = '$F308_TEXT_MUT'; const s = fs.readFileSync(p, 'utf8');
1444
+ const FROM = 'if (text.includes(SESSION_LIMIT_SIGNATURE)) return true;';
1445
+ const TO = 'if (false) return true; // MUTANT (F-308): text signature match disabled';
1446
+ const count = s.split(FROM).length - 1;
1447
+ if (count !== 1) throw new Error('F-308 text mutant anchor occurs ' + count + ' time(s), not exactly 1 -- update this mutation');
1448
+ fs.writeFileSync(p, s.replace(FROM, TO));
1449
+ "
1450
+ mutant_text=$(node --input-type=module -e "
1451
+ const M = await import('$F308_TEXT_MUT');
1452
+ $MK_INVOCATION_DRAW
1453
+ const inv = { ok:false, status:0, timedOut:false, stdout: 'prefix ' + M.SESSION_LIMIT_SIGNATURE + ' suffix', stderr:'', error:null };
1454
+ let caught = null;
1455
+ try { M.fillArm(mkInvocationDraw([{ invocation: inv, state: null }]), { n: 1, report: () => {} }); } catch (e) { caught = e; }
1456
+ process.stdout.write(String(caught instanceof M.HardInvocationFailureError));
1457
+ ")
1458
+ check "mutant (F-308: text-signature branch disabled) misses an assumed status:0/error:null shape where only the text signals it (unproven, not evidenced -- see comment above) -- no longer throws HardInvocationFailureError" \
1459
+ "$mutant_text" "false"
1460
+ pristine_text=$(cj "$MK_INVOCATION_DRAW
1461
+ const inv = { ok:false, status:0, timedOut:false, stdout: 'prefix ' + M.SESSION_LIMIT_SIGNATURE + ' suffix', stderr:'', error:null };
1462
+ let caught = null;
1463
+ try { M.fillArm(mkInvocationDraw([{ invocation: inv, state: null }]), { n: 1, report: () => {} }); } catch (e) { caught = e; }
1464
+ process.stdout.write(String(caught instanceof M.HardInvocationFailureError));
1465
+ ")
1466
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still catches it" \
1467
+ "$pristine_text" "true"
1468
+ rm -rf "$F308_TEXT_MUT_DIR"
1469
+ trap - EXIT
1470
+
1471
+ # Mutation 3: remove the timedOut carve-out -- proves it is load-bearing, not decorative. A real
1472
+ # timeout also sets its own `error` field, so without this carve-out FIRST the status/error fallback
1473
+ # would wrongly promote a genuinely still-running (merely slow) draw into HardInvocationFailureError.
1474
+ F308_TIMEOUT_MUT_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1475
+ trap 'rm -rf "$F308_TIMEOUT_MUT_DIR"' EXIT
1476
+ F308_TIMEOUT_MUT="$F308_TIMEOUT_MUT_DIR/convergence.mjs"
1477
+ cp "$ROOT/$CVD" "$F308_TIMEOUT_MUT"
1478
+ ln -s "$ROOT/tests/evals/lib" "$F308_TIMEOUT_MUT_DIR/lib"
1479
+ ln -s "$ROOT/tests/evals/run.mjs" "$F308_TIMEOUT_MUT_DIR/run.mjs"
1480
+ node -e "
1481
+ const fs = require('fs'); const p = '$F308_TIMEOUT_MUT'; const s = fs.readFileSync(p, 'utf8');
1482
+ const FROM = 'if (invocation == null || invocation.timedOut) return false;';
1483
+ const TO = 'if (invocation == null) return false; // MUTANT (F-308): timedOut carve-out removed';
1484
+ const count = s.split(FROM).length - 1;
1485
+ if (count !== 1) throw new Error('F-308 timeout mutant anchor occurs ' + count + ' time(s), not exactly 1 -- update this mutation');
1486
+ fs.writeFileSync(p, s.replace(FROM, TO));
1487
+ "
1488
+ mutant_timeout=$(node --input-type=module -e "
1489
+ const M = await import('$F308_TIMEOUT_MUT');
1490
+ $MK_INVOCATION_DRAW
1491
+ const inv = { ok:false, status:null, timedOut:true, stdout:'', stderr:'', error:'ETIMEDOUT' };
1492
+ let caught = null;
1493
+ try { M.fillArm(mkInvocationDraw([{ invocation: inv, state: { status:'running' } }]), { n: 1, maxWaitAttempts: 0, report: () => {} }); } catch (e) { caught = e; }
1494
+ process.stdout.write(String(caught instanceof M.HardInvocationFailureError));
1495
+ ")
1496
+ check "mutant (F-308: timedOut carve-out removed) wrongly promotes a genuine timeout into HardInvocationFailureError, via the status/error fallback its own error field trips" \
1497
+ "$mutant_timeout" "true"
1498
+ pristine_timeout=$(cj "$MK_INVOCATION_DRAW
1499
+ const inv = { ok:false, status:null, timedOut:true, stdout:'', stderr:'', error:'ETIMEDOUT' };
1500
+ const r = M.fillArm(mkInvocationDraw([{ invocation: inv, state: { status:'running' } }]), { n: 1, maxWaitAttempts: 0, report: () => {} });
1501
+ process.stdout.write(JSON.stringify({ waitExhausted: r.waitExhausted, censorPresent: r.censor !== null }));
1502
+ ")
1503
+ check "pristine convergence.mjs (mutation reverted -- a fresh copy, not the mutated scratch file) still routes a genuine timeout through the normal censor path" \
1504
+ "$pristine_timeout" '{"waitExhausted":true,"censorPresent":true}'
1505
+ rm -rf "$F308_TIMEOUT_MUT_DIR"
1506
+ trap - EXIT
1507
+
1508
+ echo
1509
+ printf ' %d passed, %d failed\n' "$pass" "$fail"
1510
+ [ "$fail" -eq 0 ]