@skathio/somi 4.1.1 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +8 -3
  3. package/.claude-plugin/plugin.json +9 -10
  4. package/.copilot-extension/extension.json +32 -40
  5. package/.copilot-extension/marketplace.json +8 -3
  6. package/README.md +88 -227
  7. package/VERSION +1 -1
  8. package/agents/somi-reviewer.md +21 -40
  9. package/agents/somi-security-reviewer.md +16 -90
  10. package/agents/somi-worker-high.md +11 -0
  11. package/agents/somi-worker-low.md +11 -0
  12. package/agents/somi-worker-medium.md +11 -0
  13. package/agents/somi.md +8 -75
  14. package/commands/somi-config.md +5 -14
  15. package/commands/somi-deliver.md +11 -0
  16. package/commands/somi-quality.md +10 -0
  17. package/commands/somi-review.md +10 -0
  18. package/commands/somi-status.md +11 -0
  19. package/commands/somi.md +10 -0
  20. package/hooks/hooks.json +29 -23
  21. package/hooks/lib/common.mjs +45 -34
  22. package/hooks/pre-tool/apply-tier.mjs +31 -0
  23. package/hooks/pre-tool/block-dangerous-bash.mjs +15 -0
  24. package/hooks/pre-tool/gate-dep-install.mjs +2 -2
  25. package/hooks/pre-tool/guard-protected-paths.mjs +9 -16
  26. package/hooks/pre-tool/guard-tier-config.mjs +17 -0
  27. package/hooks/pre-tool/reviewers-read-only.mjs +11 -0
  28. package/hooks/session-start/inject-digest.mjs +51 -0
  29. package/hooks/stop/review-due.mjs +44 -0
  30. package/hooks/user-prompt/capture-prompt.mjs +17 -0
  31. package/library/lenses/architecture.md +1 -0
  32. package/library/lenses/test-strategy.md +1 -0
  33. package/library/roles/accessibility.md +1 -0
  34. package/library/roles/answer.md +1 -0
  35. package/library/roles/atlas.md +1 -0
  36. package/library/roles/build.md +1 -0
  37. package/library/roles/debug.md +6 -0
  38. package/library/roles/design.md +1 -0
  39. package/library/roles/discover.md +1 -0
  40. package/library/roles/incident.md +1 -0
  41. package/library/roles/migrate.md +1 -0
  42. package/library/roles/perf.md +1 -0
  43. package/library/roles/plan.md +1 -0
  44. package/library/roles/refactor.md +1 -0
  45. package/library/roles/review.md +1 -0
  46. package/library/roles/security-review.md +1 -0
  47. package/library/roles/upgrade.md +1 -0
  48. package/library/skills/accessibility.md +16 -0
  49. package/library/skills/ci-infra-gotchas.md +12 -0
  50. package/library/skills/perf-method.md +10 -0
  51. package/library/skills/secure-coding.md +18 -0
  52. package/library/skills/testing-checklist.md +16 -0
  53. package/library/skills/threat-modeling.md +10 -0
  54. package/package.json +12 -17
  55. package/profiles/claude.json +21 -0
  56. package/profiles/copilot.json +5 -0
  57. package/rules/digest.md +40 -0
  58. package/scripts/check-links.mjs +65 -76
  59. package/scripts/lib/advisor.mjs +207 -0
  60. package/scripts/lib/check.mjs +167 -0
  61. package/scripts/lib/copilot-workflow.mjs +41 -0
  62. package/scripts/lib/doctor.mjs +91 -0
  63. package/scripts/lib/gates.mjs +69 -0
  64. package/scripts/lib/git-tree.mjs +201 -0
  65. package/scripts/lib/init.mjs +23 -0
  66. package/scripts/lib/ledger.mjs +38 -0
  67. package/scripts/lib/mcp-project-root.mjs +63 -67
  68. package/scripts/lib/migrate.mjs +73 -0
  69. package/scripts/lib/path-facts.mjs +2 -2
  70. package/scripts/lib/path-safety.mjs +6 -134
  71. package/scripts/lib/plan.mjs +69 -0
  72. package/scripts/lib/policy.mjs +103 -0
  73. package/scripts/lib/pr.mjs +28 -0
  74. package/scripts/lib/prompt.mjs +72 -0
  75. package/scripts/lib/quality/clones.mjs +76 -0
  76. package/scripts/lib/quality/css.mjs +43 -0
  77. package/scripts/lib/quality/gate.mjs +230 -0
  78. package/scripts/lib/quality/limits.mjs +97 -0
  79. package/scripts/lib/quality/metrics.mjs +159 -0
  80. package/scripts/lib/quality/parse.mjs +73 -0
  81. package/scripts/lib/quality/repo.mjs +69 -0
  82. package/scripts/lib/quality/run.mjs +58 -0
  83. package/scripts/lib/reviews.mjs +132 -0
  84. package/scripts/lib/routes.mjs +108 -0
  85. package/scripts/lib/setup.mjs +34 -0
  86. package/scripts/lib/shards.mjs +166 -0
  87. package/scripts/lib/signals.mjs +110 -0
  88. package/scripts/lib/state.mjs +42 -0
  89. package/scripts/lib/tiers.mjs +42 -0
  90. package/scripts/lib/update-notice.mjs +48 -0
  91. package/scripts/lib/views.mjs +62 -0
  92. package/scripts/lib/workflows.mjs +56 -0
  93. package/scripts/somi-mcp.mjs +182 -323
  94. package/scripts/somi.mjs +208 -0
  95. package/scripts/vendor/tree-sitter/LICENSE.vscode-tree-sitter-wasm +21 -0
  96. package/scripts/vendor/tree-sitter/LICENSE.web-tree-sitter +21 -0
  97. package/scripts/vendor/tree-sitter/cgmanifest.vscode-tree-sitter-wasm.json +16 -0
  98. package/scripts/vendor/tree-sitter/manifest.json +59 -0
  99. package/scripts/vendor/tree-sitter/package.json +3 -0
  100. package/scripts/vendor/tree-sitter/tree-sitter-css.wasm +0 -0
  101. package/scripts/vendor/tree-sitter/tree-sitter-javascript.wasm +0 -0
  102. package/scripts/vendor/tree-sitter/tree-sitter-tsx.wasm +0 -0
  103. package/scripts/vendor/tree-sitter/tree-sitter-typescript.wasm +0 -0
  104. package/scripts/vendor/tree-sitter/web-tree-sitter.js +4081 -0
  105. package/scripts/vendor/tree-sitter/web-tree-sitter.wasm +0 -0
  106. package/skills/somi-expertise/SKILL.md +6 -0
  107. package/workflows/deliver-stages.js +81 -0
  108. package/.claude/settings.json +0 -131
  109. package/agents/somi-architecture-reviewer.md +0 -101
  110. package/agents/somi-atlas.md +0 -100
  111. package/agents/somi-coder.md +0 -60
  112. package/agents/somi-designer.md +0 -36
  113. package/agents/somi-discovery-analyst.md +0 -57
  114. package/agents/somi-flow.md +0 -47
  115. package/agents/somi-general.md +0 -36
  116. package/agents/somi-impact.md +0 -95
  117. package/agents/somi-incident.md +0 -94
  118. package/agents/somi-plan-reviewer.md +0 -68
  119. package/agents/somi-planner.md +0 -57
  120. package/agents/somi-pr.md +0 -99
  121. package/agents/somi-refactor-designer.md +0 -81
  122. package/agents/somi-refactorer.md +0 -99
  123. package/agents/somi-sdlc-reviewer.md +0 -67
  124. package/agents/somi-test-strategist.md +0 -87
  125. package/commands/adopt.md +0 -14
  126. package/commands/architecture-review.md +0 -19
  127. package/commands/atlas.md +0 -19
  128. package/commands/code-loop.md +0 -19
  129. package/commands/code-parallel.md +0 -19
  130. package/commands/code.md +0 -19
  131. package/commands/debug.md +0 -19
  132. package/commands/design.md +0 -19
  133. package/commands/discover.md +0 -19
  134. package/commands/impact.md +0 -19
  135. package/commands/incident.md +0 -19
  136. package/commands/plan-loop.md +0 -19
  137. package/commands/plan.md +0 -19
  138. package/commands/pr.md +0 -19
  139. package/commands/refactor-design.md +0 -19
  140. package/commands/refactor.md +0 -19
  141. package/commands/release-readiness.md +0 -19
  142. package/commands/review-panel.md +0 -19
  143. package/commands/review.md +0 -19
  144. package/commands/security-review.md +0 -19
  145. package/commands/ship-loop.md +0 -19
  146. package/commands/ship.md +0 -19
  147. package/commands/test-strategy.md +0 -19
  148. package/commands/upgrade.md +0 -19
  149. package/examples/README.md +0 -19
  150. package/examples/code-review-example.md +0 -88
  151. package/examples/discovery-example.md +0 -200
  152. package/examples/feature-plan-example.md +0 -377
  153. package/examples/full-pipeline-example.md +0 -188
  154. package/examples/sample-consumer/.claude/settings.json +0 -29
  155. package/examples/sample-consumer/CLAUDE.md +0 -78
  156. package/examples/sample-consumer/README.md +0 -102
  157. package/hooks/post-tool/lint-changed-files.mjs +0 -209
  158. package/hooks/pre-tool/guard-cost-lowering.mjs +0 -192
  159. package/hooks/session-start/detect-repo-instructions.mjs +0 -287
  160. package/hooks/session-start/ensure-default-config.mjs +0 -113
  161. package/hooks/user-prompt-submit/inject-workflow-context.mjs +0 -580
  162. package/rules/00-priorities.md +0 -48
  163. package/rules/10-solid.md +0 -87
  164. package/rules/20-clean-code.md +0 -62
  165. package/rules/30-security-owasp.md +0 -83
  166. package/rules/40-engineering-practices.md +0 -65
  167. package/rules/50-collaboration.md +0 -114
  168. package/rules/99-overrides.md +0 -52
  169. package/rules/CLAUDE.md +0 -200
  170. package/scripts/check-session-artefacts.mjs +0 -149
  171. package/scripts/check-size-budget.mjs +0 -137
  172. package/scripts/generate-digest.mjs +0 -176
  173. package/scripts/lib/agent-info.mjs +0 -85
  174. package/scripts/lib/agent-registry.mjs +0 -92
  175. package/scripts/lib/cost-ceiling.mjs +0 -328
  176. package/scripts/lib/cost-config-edit.mjs +0 -102
  177. package/scripts/lib/cost-config.mjs +0 -64
  178. package/scripts/lib/cost-defaults.mjs +0 -53
  179. package/scripts/lib/cost-lowering.mjs +0 -89
  180. package/scripts/lib/cost-model.mjs +0 -110
  181. package/scripts/lib/dispatch-resolver.mjs +0 -243
  182. package/scripts/lib/escalation-facts.mjs +0 -146
  183. package/scripts/lib/escalation.mjs +0 -129
  184. package/scripts/lib/findings-ledger.mjs +0 -241
  185. package/scripts/lib/install-text.mjs +0 -97
  186. package/scripts/lib/loop-caps.mjs +0 -140
  187. package/scripts/lib/loop-diff.mjs +0 -38
  188. package/scripts/lib/loop-dispatch.mjs +0 -19
  189. package/scripts/lib/loop-engine.mjs +0 -227
  190. package/scripts/lib/loop-escalate.mjs +0 -49
  191. package/scripts/lib/loop-exit.mjs +0 -47
  192. package/scripts/lib/loop-notes-compact.mjs +0 -72
  193. package/scripts/lib/loop-notes.mjs +0 -282
  194. package/scripts/lib/loop-review.mjs +0 -395
  195. package/scripts/lib/loop-state.mjs +0 -44
  196. package/scripts/lib/loop-step-close.mjs +0 -75
  197. package/scripts/lib/loop-step-kit.mjs +0 -179
  198. package/scripts/lib/loop-step-review.mjs +0 -140
  199. package/scripts/lib/loop-step-tool.mjs +0 -89
  200. package/scripts/lib/loop-step.mjs +0 -303
  201. package/scripts/lib/run-budget.mjs +0 -28
  202. package/scripts/lib/run-card.mjs +0 -73
  203. package/scripts/lib/size-tier.mjs +0 -184
  204. package/scripts/lib/tier-record.mjs +0 -82
  205. package/scripts/size-budget-overrides.json +0 -58
  206. package/scripts/somi-card.mjs +0 -39
  207. package/scripts/somi-check.mjs +0 -237
  208. package/scripts/somi-config.mjs +0 -421
  209. package/scripts/somi-dispatch.mjs +0 -141
  210. package/scripts/somi-findings.mjs +0 -100
  211. package/scripts/somi-loop.mjs +0 -139
  212. package/scripts/somi-tier.mjs +0 -393
  213. package/scripts/validate.sh +0 -653
  214. package/skills/api-design/SKILL.md +0 -147
  215. package/skills/clean-code/SKILL.md +0 -142
  216. package/skills/flow-adopt/SKILL.md +0 -92
  217. package/skills/flow-architecture-review/SKILL.md +0 -94
  218. package/skills/flow-atlas/SKILL.md +0 -34
  219. package/skills/flow-code/SKILL.md +0 -167
  220. package/skills/flow-code-loop/SKILL.md +0 -263
  221. package/skills/flow-code-parallel/SKILL.md +0 -160
  222. package/skills/flow-debug/SKILL.md +0 -141
  223. package/skills/flow-design/SKILL.md +0 -170
  224. package/skills/flow-discover/SKILL.md +0 -204
  225. package/skills/flow-impact/SKILL.md +0 -35
  226. package/skills/flow-incident/SKILL.md +0 -49
  227. package/skills/flow-plan/SKILL.md +0 -254
  228. package/skills/flow-plan-loop/SKILL.md +0 -254
  229. package/skills/flow-pr/SKILL.md +0 -34
  230. package/skills/flow-refactor/SKILL.md +0 -58
  231. package/skills/flow-refactor-design/SKILL.md +0 -97
  232. package/skills/flow-release-readiness/SKILL.md +0 -82
  233. package/skills/flow-review/SKILL.md +0 -193
  234. package/skills/flow-review-panel/SKILL.md +0 -154
  235. package/skills/flow-security-review/SKILL.md +0 -83
  236. package/skills/flow-ship/SKILL.md +0 -125
  237. package/skills/flow-ship-loop/SKILL.md +0 -274
  238. package/skills/flow-somi-config/SKILL.md +0 -142
  239. package/skills/flow-status/SKILL.md +0 -43
  240. package/skills/flow-test-strategy/SKILL.md +0 -83
  241. package/skills/flow-upgrade/SKILL.md +0 -82
  242. package/skills/market-research/SKILL.md +0 -125
  243. package/skills/observability/SKILL.md +0 -133
  244. package/skills/owasp-defense/SKILL.md +0 -141
  245. package/skills/plan-review/SKILL.md +0 -83
  246. package/skills/reasoning-craft/SKILL.md +0 -213
  247. package/skills/requirements-engineering/SKILL.md +0 -137
  248. package/skills/role-coder/SKILL.md +0 -247
  249. package/skills/role-designer/SKILL.md +0 -172
  250. package/skills/role-discovery-analyst/SKILL.md +0 -288
  251. package/skills/role-planner/SKILL.md +0 -353
  252. package/skills/role-reviewer/SKILL.md +0 -218
  253. package/skills/rules/SKILL.md +0 -47
  254. package/skills/sdlc-process/SKILL.md +0 -74
  255. package/skills/solid-principles/SKILL.md +0 -143
  256. package/skills/somi-checkpoint/SKILL.md +0 -95
  257. package/skills/somi-dispatch/SKILL.md +0 -259
  258. package/skills/somi-routing/SKILL.md +0 -158
  259. package/skills/testing-playbook/SKILL.md +0 -133
  260. package/skills/threat-modeling/SKILL.md +0 -117
  261. package/templates/ADR.md.tmpl +0 -73
  262. package/templates/ATLAS.md.tmpl +0 -75
  263. package/templates/BRD.md.tmpl +0 -68
  264. package/templates/BRIEF.md.tmpl +0 -119
  265. package/templates/CONTEXT.md.tmpl +0 -74
  266. package/templates/DECISIONS.md.tmpl +0 -105
  267. package/templates/DESIGN.md.tmpl +0 -83
  268. package/templates/DIARY.md.tmpl +0 -70
  269. package/templates/DOD.md.tmpl +0 -90
  270. package/templates/FRD.md.tmpl +0 -64
  271. package/templates/PHASE.md.tmpl +0 -80
  272. package/templates/PROGRESS.md.tmpl +0 -63
  273. package/templates/RCA.md.tmpl +0 -53
  274. package/templates/RD-README.md.tmpl +0 -70
  275. package/templates/RESEARCH.md.tmpl +0 -96
  276. package/templates/REVIEW.md.tmpl +0 -82
  277. package/templates/SDD.md.tmpl +0 -82
  278. package/templates/SOMI-README.md.tmpl +0 -83
  279. package/templates/SPEC.md.tmpl +0 -123
  280. package/templates/SRS.md.tmpl +0 -85
  281. package/templates/TDD.md.tmpl +0 -77
  282. package/tests/hooks/cases/audit-log.json +0 -21
  283. package/tests/hooks/cases/block-dangerous-bash.json +0 -166
  284. package/tests/hooks/cases/block-secret-writes.json +0 -140
  285. package/tests/hooks/cases/detect-repo-instructions.json +0 -105
  286. package/tests/hooks/cases/gate-dep-install.json +0 -42
  287. package/tests/hooks/cases/guard-protected-paths.json +0 -222
  288. package/tests/hooks/cases/inject-workflow-context.json +0 -239
  289. package/tests/hooks/cases/lint-changed-files.json +0 -120
  290. package/tests/hooks/run.sh +0 -392
  291. package/tests/scripts/agent-model-frontmatter.sh +0 -38
  292. package/tests/scripts/agent-names.sh +0 -77
  293. package/tests/scripts/check-frontmatter.sh +0 -37
  294. package/tests/scripts/check-links.sh +0 -105
  295. package/tests/scripts/check-session-artefacts.sh +0 -60
  296. package/tests/scripts/check-size-budget.sh +0 -71
  297. package/tests/scripts/checkpoint-gate.sh +0 -131
  298. package/tests/scripts/convergence-runner.sh +0 -1514
  299. package/tests/scripts/cost-ceiling.sh +0 -255
  300. package/tests/scripts/cost-defaults.sh +0 -130
  301. package/tests/scripts/cost-hardcap.sh +0 -338
  302. package/tests/scripts/cost-lowering.sh +0 -261
  303. package/tests/scripts/cost-model.sh +0 -196
  304. package/tests/scripts/dispatch-guard.sh +0 -108
  305. package/tests/scripts/dispatch-line-gate.sh +0 -61
  306. package/tests/scripts/dispatch-reference-gate.sh +0 -173
  307. package/tests/scripts/ensure-default-config.sh +0 -162
  308. package/tests/scripts/escalation.sh +0 -409
  309. package/tests/scripts/eval-runner.sh +0 -3692
  310. package/tests/scripts/evals-packaging.sh +0 -224
  311. package/tests/scripts/fact-sheet.sh +0 -296
  312. package/tests/scripts/fixtures/legacy-shard-no-schema.json +0 -50
  313. package/tests/scripts/fixtures/mock-stdin-read-throw.cjs +0 -18
  314. package/tests/scripts/fixtures/size-tier-cases.json +0 -87
  315. package/tests/scripts/generate-digest.sh +0 -180
  316. package/tests/scripts/global-config.sh +0 -167
  317. package/tests/scripts/goldens/loop-state-breach.json +0 -1
  318. package/tests/scripts/goldens/loop-state-done.json +0 -1
  319. package/tests/scripts/goldens/somi-findings.json +0 -336
  320. package/tests/scripts/goldens/somi-loop.json +0 -168
  321. package/tests/scripts/lib/adr-shape.mjs +0 -41
  322. package/tests/scripts/lib/agent-registry-tests.mjs +0 -95
  323. package/tests/scripts/lib/brief-only-guard.mjs +0 -27
  324. package/tests/scripts/lib/checkpoint-gate.mjs +0 -91
  325. package/tests/scripts/lib/digest-marker-coupling.mjs +0 -52
  326. package/tests/scripts/lib/dispatch-reference-gate.mjs +0 -121
  327. package/tests/scripts/lib/escalation-facts-tests.mjs +0 -140
  328. package/tests/scripts/lib/escalation-tests.mjs +0 -154
  329. package/tests/scripts/lib/findings-ledger-tests.mjs +0 -118
  330. package/tests/scripts/lib/loop-engine-tests.mjs +0 -287
  331. package/tests/scripts/lib/loop-escalate-tests.mjs +0 -356
  332. package/tests/scripts/lib/loop-flow-gate.mjs +0 -173
  333. package/tests/scripts/lib/loop-notes-tests.mjs +0 -384
  334. package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -156
  335. package/tests/scripts/lib/loop-step-close-tests.mjs +0 -351
  336. package/tests/scripts/lib/loop-step-lenient-tests.mjs +0 -114
  337. package/tests/scripts/lib/loop-step-state-tests.mjs +0 -127
  338. package/tests/scripts/lib/loop-step-tests.mjs +0 -499
  339. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +0 -55
  340. package/tests/scripts/lib/multipass-dependence.mjs +0 -192
  341. package/tests/scripts/lib/multipass-source-identity.mjs +0 -243
  342. package/tests/scripts/lib/path-facts-tests.mjs +0 -198
  343. package/tests/scripts/lib/path-safety-tests.mjs +0 -201
  344. package/tests/scripts/lib/reference-pair.mjs +0 -61
  345. package/tests/scripts/lib/retirement-gate.mjs +0 -172
  346. package/tests/scripts/lib/run-suites.mjs +0 -139
  347. package/tests/scripts/lib/shell-embedded-js.mjs +0 -47
  348. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +0 -52
  349. package/tests/scripts/lib/site-roadmap-gate.mjs +0 -64
  350. package/tests/scripts/lib/size-tier-drift.mjs +0 -74
  351. package/tests/scripts/lib/sizing-score-tests.mjs +0 -210
  352. package/tests/scripts/lib/sizing-set-tests.mjs +0 -131
  353. package/tests/scripts/lib/somi-mcp-client.mjs +0 -102
  354. package/tests/scripts/lib/somi-mcp-config-tests.mjs +0 -92
  355. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +0 -226
  356. package/tests/scripts/lib/somi-mcp-tests.mjs +0 -491
  357. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +0 -64
  358. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +0 -38
  359. package/tests/scripts/loop-engine.sh +0 -22
  360. package/tests/scripts/loop-flow-gate.sh +0 -11
  361. package/tests/scripts/retirement-gate.sh +0 -306
  362. package/tests/scripts/review-panel-seats.sh +0 -32
  363. package/tests/scripts/run-card.sh +0 -57
  364. package/tests/scripts/run-suites.sh +0 -74
  365. package/tests/scripts/run.sh +0 -689
  366. package/tests/scripts/site-roadmap-gate.sh +0 -76
  367. package/tests/scripts/size-tier.sh +0 -562
  368. package/tests/scripts/somi-agent-dispatch-contract.sh +0 -224
  369. package/tests/scripts/somi-config.sh +0 -286
  370. package/tests/scripts/somi-dispatch.sh +0 -465
  371. package/tests/scripts/somi-mcp.sh +0 -15
  372. package/tests/scripts/suite-plan.json +0 -20
@@ -1,3692 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Unit guard for tests/evals/run.mjs.
3
- #
4
- # Hermetic by construction: every case below is `--dry-run` or a direct function call. No model
5
- # invocation, no network, no credential. That is an exit criterion, not a convenience.
6
- set -uo pipefail
7
-
8
- ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
9
- cd "$ROOT"
10
- R=tests/evals/run.mjs
11
- pass=0; fail=0
12
- ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }
13
- bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
14
- check(){ if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (want '$3', got '$2')"; fi; }
15
-
16
- # Run a snippet with run.mjs imported as `M`. Kept as a function so no case can forget the
17
- # import path and silently test nothing.
18
- j() { node --input-type=module -e "const M = await import('$ROOT/$R'); $1" 2>&1; }
19
-
20
- echo "== eval runner =="
21
-
22
- # --- the acceptance bands ---------------------------------------------------------------------
23
- # rubric.md: N=20, pass >=18, fail <=10, unstable at 11-17. These four are named in the phase
24
- # file's acceptance criterion.
25
- check "20/20 grades pass" "$(j 'process.stdout.write(M.grade(20))')" "pass"
26
- check "18/20 grades pass" "$(j 'process.stdout.write(M.grade(18))')" "pass"
27
- check "14/20 grades unstable" "$(j 'process.stdout.write(M.grade(14))')" "unstable"
28
- check "9/20 grades fail" "$(j 'process.stdout.write(M.grade(9))')" "fail"
29
-
30
- # --- the band EDGES, which is where an off-by-one lives ----------------------------------------
31
- check "17/20 is unstable (just below the pass band)" "$(j 'process.stdout.write(M.grade(17))')" "unstable"
32
- check "11/20 is unstable (just above the fail band)" "$(j 'process.stdout.write(M.grade(11))')" "unstable"
33
- check "10/20 is fail (the fail band is inclusive)" "$(j 'process.stdout.write(M.grade(10))')" "fail"
34
- check "0/20 is fail" "$(j 'process.stdout.write(M.grade(0))')" "fail"
35
-
36
- # --- a truncated run must grade as what it is, not rescale silently ----------------------------
37
- # grade() takes n explicitly. If it inferred n from the data, 9 passes out of 9 attempted runs
38
- # would read as `fail` against N=20 -- the run was short, not bad.
39
- check "9/9 grades pass (n is explicit, not inferred)" "$(j 'process.stdout.write(M.grade(9, 9))')" "pass"
40
- check "5/10 grades fail" "$(j 'process.stdout.write(M.grade(5, 10))')" "fail"
41
- check "7/10 grades unstable" "$(j 'process.stdout.write(M.grade(7, 10))')" "unstable"
42
-
43
- # --- invalid outcome counts must throw, not grade ----------------------------------------------
44
- for bad_in in "21, 20" "-1, 20" "5, 0" "1.5, 20"; do
45
- got=$(j "try { M.grade($bad_in); process.stdout.write('NO THROW'); } catch (e) { process.stdout.write(e.constructor.name); }")
46
- check "grade($bad_in) throws rather than grading" "$got" "RangeError"
47
- done
48
-
49
- # --- the comparison rule the later gate depends on ------------------------------------------------------
50
- cmp_case() {
51
- # NOT `j ... | { read -r got; check ...; }` -- a pipeline runs its right side in a SUBSHELL, so
52
- # check()'s increments to pass/fail were discarded and all 8 cases below printed FAIL while the
53
- # suite still reported 0 failed and exited 0. These are the compare() rule the later gate depends on.
54
- local got
55
- got=$(j "const r = M.compare($2, $3); process.stdout.write(String(r.accepted) + ':' + r.regressions.length);")
56
- check "$1" "$got" "$4"
57
- }
58
- cmp_case "identical grades are accepted" \
59
- "{t1:{S1:'pass',S2:'pass'}}" "{t1:{S1:'pass',S2:'pass'}}" "true:0"
60
- cmp_case "pass -> fail is a regression" \
61
- "{t1:{S1:'pass'}}" "{t1:{S1:'fail'}}" "false:1"
62
- cmp_case "pass -> unstable is a regression" \
63
- "{t1:{S1:'pass'}}" "{t1:{S1:'unstable'}}" "false:1"
64
- cmp_case "unstable -> unstable is NOT a regression (already unstable in baseline)" \
65
- "{t1:{S1:'unstable'}}" "{t1:{S1:'unstable'}}" "true:0"
66
- cmp_case "fail -> pass is an improvement, not a regression" \
67
- "{t1:{S1:'fail'}}" "{t1:{S1:'pass'}}" "true:0"
68
- # fail -> unstable ranks as an IMPROVEMENT by grade order, so the ordering check alone cannot see
69
- # it. rubric.md still forbids it: "no dimension is unstable in the candidate set unless it was
70
- # already unstable in the baseline". Mutation-verified -- deleting that branch survived every
71
- # other case here.
72
- cmp_case "fail -> unstable is a regression (became unstable, despite ranking higher)" \
73
- "{t1:{S1:'fail'}}" "{t1:{S1:'unstable'}}" "false:1"
74
- cmp_case "a dimension missing from the candidate is a regression" \
75
- "{t1:{S1:'pass'}}" "{t1:{}}" "false:1"
76
- cmp_case "two regressions are both reported" \
77
- "{t1:{S1:'pass',S2:'pass'}}" "{t1:{S1:'fail',S2:'unstable'}}" "false:2"
78
-
79
- # --- result-file shape: the contract the later gate consumes -------------------------------------------
80
- # S3 is task 01's only GATING dimension; S1/S2 are report-only, so this also
81
- # pins the split buildResult() now performs -- a report-only dimension must still be
82
- # measured and graded, just under `reportOnly`, never under `dimensions`.
83
- shape=$( j "
84
- const src = { ref: 'HEAD', sha: 'abc123def456' };
85
- const tasks = { '01': [
86
- { index: 0, dimensions: { S1: true, S2: false, S3: true, S4: 'n-a' } },
87
- { index: 1, dimensions: { S1: true, S2: true, S3: true, S4: 'n-a' } },
88
- ] };
89
- const r = M.buildResult({ source: src, tasks, runs: 2, dryRun: true, now: new Date('2026-08-01T00:00:00Z') });
90
- const d = r.tasks['01'].dimensions, ro = r.tasks['01'].reportOnly;
91
- process.stdout.write([
92
- r.schema, r.dryRun, r.source.sha, r.runsRequested, r.generated.slice(0,10),
93
- r.tasks['01'].runs.length,
94
- d.S3.passes + '/' + d.S3.n + ':' + d.S3.grade,
95
- ro.S1.passes + '/' + ro.S1.n + ':' + ro.S1.grade,
96
- ro.S2.passes + '/' + ro.S2.n + ':' + ro.S2.grade,
97
- ('S4' in d || 'S4' in ro) ? 'S4-COUNTED' : 'S4-excluded',
98
- ('S1' in d) ? 'S1-GATES' : 'S1-report-only',
99
- ].join('|'));
100
- ")
101
- check "result shape carries schema, sha, run index, and splits gating from report-only dims" \
102
- "$shape" "2|true|abc123def456|2|2026-08-01|2|2/2:pass|2/2:pass|1/2:fail|S4-excluded|S1-report-only"
103
-
104
- # An `n-a` dimension must not be counted at all. A task that does not exercise a dimension
105
- # dragging its grade toward fail would make the corpus report regressions that never happened.
106
- na=$( j "
107
- const r = M.buildResult({ source: {ref:'x',sha:null}, runs: 1,
108
- tasks: { '01': [ { index: 0, dimensions: { S3: 'n-a' } } ] } });
109
- process.stdout.write(JSON.stringify(r.tasks['01'].dimensions));
110
- ")
111
- check "an all-n-a task produces no dimension entries" "$na" "{}"
112
-
113
- # An unversioned --source must record sha: null rather than imply a commit.
114
- check "a path source records sha null" \
115
- "$( j "process.stdout.write(String(M.resolveSource('./tests').sha))" )" "null"
116
-
117
- # --- --source resolution and worktree cleanup --------------------------------------------------
118
- head_sha=$(git rev-parse HEAD)
119
- # `git worktree list` is global state: a concurrent eval run, or another script in the parallel suite,
120
- # can add or remove its own worktree during this test. So "this test leaks none" is checked as sets:
121
- # a leak is a worktree present afterwards that was not there before.
122
- wt_list() { git worktree list --porcelain | grep '^worktree .*somi-eval-src' | sort; }
123
- wt_before=$(wt_list)
124
- res=$( j "
125
- const s = M.resolveSource('HEAD');
126
- const fs = await import('node:fs');
127
- const had = fs.existsSync(s.dir) && fs.existsSync(s.dir + '/package.json');
128
- s.cleanup();
129
- const gone = !fs.existsSync(s.dir);
130
- process.stdout.write(s.sha + '|' + had + '|' + gone);
131
- ")
132
- check "--source HEAD checks out a worktree and cleans it up" "$res" "$head_sha|true|true"
133
- check "this test leaks no worktree" "$(comm -13 <(printf '%s\n' "$wt_before" | grep . || true) <(wt_list) | grep -c . || true)" "0"
134
-
135
- check "an unresolvable --source fails loudly" \
136
- "$( j "try { M.resolveSource('no-such-ref-xyz'); process.stdout.write('NO THROW'); } catch (e) { process.stdout.write('threw'); }" )" \
137
- "threw"
138
-
139
- # --- dry run: a correctly-shaped file, and provably no model invocation -------------------------
140
- out=$(mktemp) || { bad "mktemp failed"; exit 1; }
141
- if node "$R" --dry-run --source HEAD --tasks 01 --runs 3 --out "$out" >/dev/null 2>&1; then
142
- ok "dry run exits 0"
143
- else
144
- bad "dry run exits 0"
145
- fi
146
- dry=$( node -e "
147
- const r = JSON.parse(require('fs').readFileSync('$out','utf8'));
148
- process.stdout.write([r.dryRun, r.runsRequested, r.tasks['01'].runs.length, r.bands.n, r.bands.pass].join('|'));
149
- " 2>&1 )
150
- check "dry-run file has the right shape" "$dry" "true|3|3|20|18"
151
-
152
- # The hermeticity claim, asserted structurally rather than by observing that it happened to work.
153
- if grep -qE 'fetch\(|https?://|ANTHROPIC_API_KEY|api\.anthropic' "$R"; then
154
- bad "run.mjs contains no network call or credential read (dry run cannot leak)"
155
- else
156
- ok "run.mjs contains no network call or credential read (dry run cannot leak)"
157
- fi
158
- # A live run is preflighted before any work. Simulated by clearing PATH and HOME so neither the
159
- # CLI nor a credential resolves -- the runner must refuse with a named reason, not start spending
160
- # and discover the problem on run 14 of 20.
161
- # Keep node reachable; remove only the claude CLI and the credential.
162
- NODE_BIN=$(command -v node)
163
- pre=$(env -i "PATH=$(dirname "$NODE_BIN")" HOME=/nonexistent "$NODE_BIN" "$ROOT/$R" --source HEAD --tasks 01 --runs 1 2>&1 || true)
164
- case "$pre" in
165
- *"cannot run live"*) ok "a live run preflights the CLI and credential before spending" ;;
166
- *) bad "a live run preflights the CLI and credential before spending (got: ${pre:0:80})" ;;
167
- esac
168
- rm -f "$out"
169
-
170
- # --- fixture executor + mutation substitution --------------------------------------------
171
- # The three hand-written candidates under fixtures/_candidates/ are the acceptance criterion.
172
- # Each pins one outcome of scoreExpiryGuard()'s three steps.
173
- FX="$ROOT/tests/evals/fixtures"
174
- # `step` is asserted, not just the verdict. Without it, deleting the control check entirely
175
- # survived every case: `changed-surface` returns `non-attributable` either way -- at (b) because
176
- # the control cannot load, or at (c) because the mutant cannot either. Same verdict, different
177
- # thing measured.
178
- score() { j "
179
- const r = M.scoreExpiryGuard('$FX/_candidates/$1',
180
- { mutant: '$FX/task02-code-mutant.mjs', control: '$FX/task02-code-control.mjs' });
181
- process.stdout.write(r.verdict + '|' + r.step + '|' + (r.observed ?? '-') + '|' + r.attributable);
182
- "; }
183
- check "a correct expiry test passes, attributably" \
184
- "$(score correct-guard)" "pass|mutant|assertion|true"
185
- check "a test that never checks expiry FAILS (green on the mutant)" \
186
- "$(score no-expiry-test)" "fail|mutant|green|true"
187
- check "a changed export surface is caught AT THE CONTROL, non-attributably" \
188
- "$(score changed-surface)" "non-attributable|control|import-error|false"
189
- # The only case exercising step (c)'s non-assertion branch. Green on the control, so the
190
- # substitution fits; red on the mutant from a TypeError, so the test never expressed an opinion
191
- # about expiry. Grading that as a pass would accept a guard that does not guard.
192
- check "a TypeError red on the mutant is NON-ATTRIBUTABLE, not a pass" \
193
- "$(score type-error-red)" "non-attributable|mutant|type-error|false"
194
-
195
- # The classifier is what makes (c) mean anything: an import error graded as "the guard worked"
196
- # passes a test that never checks expiry.
197
- cls() { j "process.stdout.write(M.classifyRed({ pass: 0, fail: 1, crashed: false, output: \`$1\` }))"; }
198
- check "an AssertionError classifies as assertion" "$(cls 'AssertionError [ERR_ASSERTION]: x')" "assertion"
199
- check "a missing named export is import-error, NOT syntax-error" \
200
- "$(cls 'SyntaxError: The requested module ./t.mjs does not provide an export named verifyToken')" "import-error"
201
- check "ERR_MODULE_NOT_FOUND is module-resolution" "$(cls 'Error [ERR_MODULE_NOT_FOUND]: Cannot find module')" "module-resolution"
202
- check "a TypeError is type-error, not assertion" "$(cls 'TypeError: x is not a function')" "type-error"
203
- check "a real SyntaxError still classifies as one" "$(cls 'SyntaxError: Unexpected token }')" "syntax-error"
204
- check "a green suite classifies as green" \
205
- "$(j "process.stdout.write(M.classifyRed({ pass: 3, fail: 0, crashed: false, output: '' }))")" "green"
206
-
207
- # A candidate that is red on its OWN source is not scored -- red-then-red proves nothing.
208
- redfirst=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
209
- cp -r "$FX/_candidates/correct-guard/." "$redfirst"/
210
- printf "\ntest('deliberately red', () => { assert.equal(1, 2); });\n" >> "$redfirst/tests/auth/token.test.mjs"
211
- check "a candidate red on its own source is failed before substitution" \
212
- "$(j "const r = M.scoreExpiryGuard('$redfirst', { mutant: '$FX/task02-code-mutant.mjs', control: '$FX/task02-code-control.mjs' }); process.stdout.write(r.verdict + '|' + r.reason)")" \
213
- "fail|not green on its own source"
214
- rm -rf "$redfirst"
215
-
216
- # The executor must not mutate the candidate it scores -- it works on a copy.
217
- check "scoring leaves the candidate tree untouched" \
218
- "$(j "
219
- const fs = await import('node:fs');
220
- const p = '$FX/_candidates/correct-guard/src/auth/token.mjs';
221
- const before = fs.readFileSync(p, 'utf8');
222
- M.scoreExpiryGuard('$FX/_candidates/correct-guard', { mutant: '$FX/task02-code-mutant.mjs', control: '$FX/task02-code-control.mjs' });
223
- process.stdout.write(String(fs.readFileSync(p, 'utf8') === before));
224
- ")" "true"
225
-
226
- # --- task 02's merged S5 criterion, overlaid from scoreExpiryGuard()'s VERDICT, not OBSERVED -
227
- # The Blocker this closes: an `observed`-based derivation leaves `observed` unset on the own-step
228
- # failure branch (scoreExpiryGuard's real return shape there carries no `observed` field at all),
229
- # so a candidate genuinely red on its own source would map to `null` and get silently discarded
230
- # instead of counted as the fail it is. Each case below pins one branch of `overlayExpiryGuardVerdict`
231
- # end to end -- through toDimensions and buildResult -- so a regression to the observed-based
232
- # derivation is caught at the same layer certify() reads, not just at the overlay function's return
233
- # value.
234
- overlay() { j "
235
- const S = await import('$ROOT/tests/evals/lib/score.mjs');
236
- const crit = [{ n: 1, verdict: '$2', evidence: '-' }, { n: 2, verdict: 'pass', evidence: 'judge: untouched' }];
237
- M.overlayExpiryGuardVerdict(crit, $1);
238
- const dims = S.toDimensions(crit, { 1: ['S5'], 2: ['S3'] });
239
- const res = M.buildResult({ source: { ref: 'x', sha: 'd' }, tasks: { '02': [{ index: 0, dimensions: dims }] }, runs: 1 });
240
- const d = res.tasks['02'].dimensions.S5;
241
- process.stdout.write(crit[0].verdict + '|' + (crit[0].executed ?? 'undefined') + '|' + JSON.stringify(dims.S5) + '|' + d.n + '/' + d.passes);
242
- "; }
243
- # THE case that proves the Blocker is closed: an own-step failure has NO `observed` field (matching
244
- # scoreExpiryGuard's real branch at run.mjs -- verified by reading the source, not assumed), so a
245
- # derivation reading `observed` would see `undefined`, map to `null`, and leave criterion 1's
246
- # pre-existing 'pass' verdict untouched -- exactly the discarded-draw bug. Seeding criterion 1 at
247
- # 'pass' beforehand makes that failure mode visible: if the fix regresses to observed-based
248
- # derivation, this case reads 'pass|undefined|...' instead of 'fail|true|...'.
249
- check "own-fail scores the merged criterion FAIL and counts toward draws (not discarded)" \
250
- "$(overlay "{ verdict: 'fail', step: 'own', reason: 'not green on its own source' }" pass)" \
251
- "fail|true|false|1/0"
252
- check "control-fail (non-load, per classifyRed) scores FAIL" \
253
- "$(overlay "{ verdict: 'fail', step: 'control', reason: 'red on the control', observed: 'assertion' }" fail)" \
254
- "fail|true|false|1/0"
255
- check "mutant-assertion scores PASS" \
256
- "$(overlay "{ verdict: 'pass', step: 'mutant', observed: 'assertion' }" fail)" \
257
- "pass|true|true|1/1"
258
- check "mutant-green scores FAIL (the guard did not guard)" \
259
- "$(overlay "{ verdict: 'fail', step: 'mutant', reason: 'the new test passes against the mutant', observed: 'green' }" pass)" \
260
- "fail|true|false|1/0"
261
-
262
- # Minor, review pass 2: a judge reply omitting criterion 1 must not drop the observation silently.
263
- check "a judge reply missing criterion 1 marks the anomaly on eg, rather than dropping it silently" \
264
- "$(j "
265
- const crit = [{ n: 2, verdict: 'pass', evidence: '-' }];
266
- const eg = { verdict: 'pass', step: 'mutant', observed: 'assertion' };
267
- M.overlayExpiryGuardVerdict(crit, eg);
268
- process.stdout.write(eg.overlaySkipped ?? 'MISSING');
269
- ")" "criterion 1 absent from the judge reply"
270
-
271
- # --- non-attributable: settled 2026-08-12 as ABSENT and RECORDED, not "null/defer" ---------------
272
- # The prior "null/defer" wording let a judge-authored `pass` decide gating dimension S5 (a judge-authored verdict must never decide a gating
273
- # dimension). The fix removes criterion 1
274
- # from the array entirely on this branch, so toDimensions() -- which maps every criterion it is
275
- # GIVEN, judge-authored or not -- never sees it. Seeded at 'pass' below (opposite of a fail-safe
276
- # default): a regression back to "defer" shows up as an S5 key reappearing in `dims`.
277
- nonattr() { j "
278
- const S = await import('$ROOT/tests/evals/lib/score.mjs');
279
- const crit = [{ n: 1, verdict: '$2', evidence: '-' }, { n: 2, verdict: 'pass', evidence: 'judge: untouched' }];
280
- M.overlayExpiryGuardVerdict(crit, $1);
281
- process.stdout.write(String(crit.some((c) => c.n === 1)) + '|' + JSON.stringify(S.toDimensions(crit, { 1: ['S5'], 2: ['S3'] })));
282
- "; }
283
- check "control-fail (a LOAD failure) is EXCLUDED: criterion 1 removed, S5 never reaches dims" \
284
- "$(nonattr "{ verdict: 'non-attributable', step: 'control', reason: 'the control could not load (import-error)', observed: 'import-error' }" pass)" \
285
- 'false|{"S3":true}'
286
- check "mutant-non-attributable is EXCLUDED: criterion 1 removed, S5 never reaches dims" \
287
- "$(nonattr "{ verdict: 'non-attributable', step: 'mutant', reason: 'red on the mutant, but from type-error', observed: 'type-error' }" fail)" \
288
- 'false|{"S3":true}'
289
-
290
- # exclusion is a first-class OUTCOME, not `perRun.length - n`, which
291
- # vanished S5 at 100% exclusion and charged harness faults against every dim.
292
- check "a dimension excluded on every draw still emits a row (0/0), not silence (F-47)" \
293
- "$(j "
294
- const res = M.buildResult({ source: { ref: 'x', sha: 'd' }, tasks: { '02': [
295
- { index: 0, dimensions: { S5: 'excluded', S3: true } },
296
- { index: 1, dimensions: { S5: 'excluded', S3: true } },
297
- { index: 2, dimensions: { S5: 'excluded', S3: true } },
298
- ] }, runs: 3 });
299
- const s5 = res.tasks['02'].dimensions.S5;
300
- process.stdout.write(s5.n + '/' + s5.passes + '/' + s5.excluded + '/' + s5.grade);
301
- ")" "0/0/3/null"
302
- check "a mixed batch counts the excluded draw toward S3 but not S5, and reports the exclusion (S3 is task 02's report-only dim, decisions.md#d11)" \
303
- "$(j "
304
- const res = M.buildResult({ source: { ref: 'x', sha: 'd' }, tasks: { '02': [
305
- { index: 0, dimensions: { S5: 'excluded', S3: true } },
306
- { index: 1, dimensions: { S5: true, S3: true } },
307
- ] }, runs: 2 });
308
- const s5 = res.tasks['02'].dimensions.S5, s3 = res.tasks['02'].reportOnly.S3;
309
- process.stdout.write(s5.n + '/' + s5.passes + '/' + s5.excluded + '|' + s3.n + '/' + s3.passes + '/' + s3.excluded);
310
- ")" "1/1/1|2/2/0"
311
- check "a harness-faulted (empty-dimensions) draw does NOT inflate excluded on unrelated dims (F-48)" \
312
- "$(j "
313
- const res = M.buildResult({ source: { ref: 'x', sha: 'd' }, tasks: { '02': [
314
- { index: 0, dimensions: { S5: true, S3: true } },
315
- { index: 1, dimensions: {} },
316
- ] }, runs: 2 });
317
- const s5 = res.tasks['02'].dimensions.S5, s3 = res.tasks['02'].reportOnly.S3;
318
- process.stdout.write(s5.n + '/' + s5.passes + '/' + s5.excluded + '|' + s3.n + '/' + s3.passes + '/' + s3.excluded);
319
- ")" "1/1/0|1/1/0"
320
-
321
- # `'excluded'` is truthy, so the pre-fix `v ? '+' : '-'` printed an unmeasured gating
322
- # dimension as `S5+` -- identical to a pass. Mutation: reverting the ternary turns this red.
323
- check "the live progress line marks an excluded dimension as neither pass nor fail (F-50)" \
324
- "$(j "process.stdout.write(M.renderDimensions({ S5: 'excluded', S3: true, S1: false, S6: true }))")" \
325
- "S5~ S3+ S1- S6+"
326
-
327
- # --- scoreExpiryGuard()'s catch must fail CLOSED, not silently return S5
328
- # to the judge. The throw is real -- a --source ref predating the mutant/control fixtures throws.
329
- check "scoreExpiryGuard throws when the mutant/control fixtures do not exist (the catch's real precondition)" \
330
- "$(j "
331
- try {
332
- M.scoreExpiryGuard('$FX/_candidates/correct-guard',
333
- { mutant: '/nonexistent/task02-code-mutant.mjs', control: '/nonexistent/task02-code-control.mjs' });
334
- process.stdout.write('NO THROW');
335
- } catch (e) { process.stdout.write('threw'); }
336
- ")" "threw"
337
- check "a harness-fault disposition (step: 'harness') is removed from criteria exactly like any other non-attributable verdict" \
338
- "$(j "
339
- const crit = [{ n: 1, verdict: 'pass', evidence: '-' }, { n: 2, verdict: 'pass', evidence: '-' }];
340
- M.overlayExpiryGuardVerdict(crit, { verdict: 'non-attributable', step: 'harness', reason: 'scoreExpiryGuard threw: ENOENT', observed: null });
341
- process.stdout.write(String(crit.some((c) => c.n === 1)));
342
- ")" "false"
343
-
344
- # session.mjs (criterion 2, S3) must never be touched by ANY task 02 overlay -- report-only, per
345
- # the classification. Proven by running the SAME overlay call used above (which only
346
- # ever looks up criterion n===1) and confirming criterion 2 is byte-identical to what the judge
347
- # said going in, regardless of what scoreExpiryGuard returned.
348
- check "session.mjs's criterion is untouched by the expiry-guard overlay (report-only, not gating)" \
349
- "$(j "
350
- const crit = [{ n: 1, verdict: 'pass', evidence: '-' }, { n: 2, verdict: 'fail', evidence: 'judge: touched, no reason given' }];
351
- M.overlayExpiryGuardVerdict(crit, { verdict: 'pass', step: 'mutant', observed: 'assertion' });
352
- process.stdout.write(crit[1].verdict + '|' + (crit[1].executed ?? 'undefined') + '|' + crit[1].evidence);
353
- ")" \
354
- "fail|undefined|judge: touched, no reason given"
355
- # ...and directly: sessionUntouched()'s own verdict, in the direction a naive gating overlay would
356
- # have flipped, must still not appear anywhere near a criterion's `.verdict` -- exercised through
357
- # boundary.mjs's actual exported function, both directions.
358
- check "sessionUntouched: untouched" \
359
- "$(j "const B = await import('$ROOT/tests/evals/lib/boundary.mjs'); const r = B.sessionUntouched([{status:'M',path:'src/auth/token.mjs'}]); process.stdout.write(r.ok + '|' + r.touched)")" \
360
- "true|false"
361
- check "sessionUntouched: touched" \
362
- "$(j "const B = await import('$ROOT/tests/evals/lib/boundary.mjs'); const r = B.sessionUntouched([{status:'M',path:'src/auth/session.mjs'}]); process.stdout.write(r.ok + '|' + r.touched)")" \
363
- "false|true"
364
-
365
- # --- capture .somi/audit.log, wire task 02's S1 criterion (closes gap 2) -------------------
366
- # The load-bearing claim: this fixture is npm-only, which is what confines the
367
- # invocation space to npm's own CLI forms. Checked directly against the fixture, not assumed.
368
- PKG02="$ROOT/tests/evals/fixtures/task02-code/package.json"
369
- if grep -q '"packageManager"' "$PKG02"; then
370
- bad "task02-code/package.json carries no packageManager field (the closure premise)"
371
- else
372
- ok "task02-code/package.json carries no packageManager field (the closure premise)"
373
- fi
374
- lockhits=$(find "$ROOT/tests/evals/fixtures/task02-code" \( -iname 'yarn.lock' -o -iname 'pnpm-lock.yaml' \) 2>/dev/null)
375
- check "task02-code carries no yarn.lock/pnpm-lock.yaml (confirms an npm-only fixture)" \
376
- "${lockhits:-NONE}" "NONE"
377
- check "task02-code/package.json's declared test script is exactly 'node --test'" \
378
- "$(node -e "process.stdout.write(JSON.parse(require('fs').readFileSync('$PKG02','utf8')).scripts.test)")" \
379
- "node --test"
380
-
381
- # The fifteen aliases, each pinned individually -- a regression to any ONE is caught by name, not
382
- # absorbed into a single "some alias matched" assertion.
383
- alm() { j "const A = await import('$ROOT/tests/evals/lib/audit-log.mjs'); process.stdout.write(String(A.matchesTestInvocation($1)))"; }
384
- check "npm test matches" "$(alm "'npm test'")" "true"
385
- check "npm run test matches" "$(alm "'npm run test'")" "true"
386
- check "npm run-script test matches (npm run's canonical form)" "$(alm "'npm run-script test'")" "true"
387
- check "npm t matches (word-bounded shorthand)" "$(alm "'npm t'")" "true"
388
- check "node --test matches" "$(alm "'node --test'")" "true"
389
- check "node --test with a trailing path still matches" "$(alm "'node --test tests/auth/token.test.mjs'")" "true"
390
- check "bare node <test file>, no --test flag at all, matches" "$(alm "'node tests/auth/token.test.mjs'")" "true"
391
- check "an incidental flag does not produce a false negative" "$(alm "'npm test -- --test-reporter=tap'")" "true"
392
-
393
- # `npm help test`/`npm help run-script`'s OWN documented aliases and interposed npm
394
- # global flags -- confirmed by execution to genuinely run the suite and score `false` pre-fix.
395
- check "npm tst matches (npm test's own documented alias)" "$(alm "'npm tst'")" "true"
396
- check "npm rum test matches (npm run's own documented alias)" "$(alm "'npm rum test'")" "true"
397
- check "npm urn test matches (npm run's own documented alias)" "$(alm "'npm urn test'")" "true"
398
- check "npm --silent test matches (interposed global flag)" "$(alm "'npm --silent test'")" "true"
399
- check "npm -s test matches (interposed short global flag)" "$(alm "'npm -s test'")" "true"
400
- check "npm run --silent test matches (flag between run and test)" "$(alm "'npm run --silent test'")" "true"
401
- check "node --experimental-test-coverage --test matches (interposed node flag)" \
402
- "$(alm "'node --experimental-test-coverage --test'")" "true"
403
-
404
- # The false-POSITIVE side: each is a REAL, different command this fixture's agent could
405
- # plausibly type, and none of them runs the declared test script.
406
- check "npm typecheck does NOT match npm t" \
407
- "$(alm "'npm typecheck'")" "false"
408
- check "npm test-only does NOT match npm test (hyphen continuation is a different script name)" \
409
- "$(alm "'npm test-only'")" "false"
410
- check "npm run test-only does NOT match npm run test (hyphen continuation, run form)" \
411
- "$(alm "'npm run test-only'")" "false"
412
- check "node --test-name-pattern=foo does NOT match node --test (hyphen continuation is a different flag)" \
413
- "$(alm "'node --test-name-pattern=foo'")" "false"
414
- check "pnpm test does NOT match npm test (a different package manager)" \
415
- "$(alm "'pnpm test'")" "false"
416
- check "a non-matching command fails cleanly" \
417
- "$(alm "'echo build complete'")" "false"
418
- check "node on a non-test file does NOT match the bare-node form" \
419
- "$(alm "'node scripts/build.mjs'")" "false"
420
-
421
- # a CLAIM about running the suite (prose, a commit message) must not match, or this
422
- # criterion passes the exact fabrication it exists to catch. Confirmed `true` (wrongly) pre-fix.
423
- check "a prose claim mentioning npm test does NOT match (F-59)" \
424
- "$(alm "'echo \"remember to run npm test later\"'")" "false"
425
- check "a commit message claiming npm test ran does NOT match (F-59)" \
426
- "$(alm "'git commit -m \"ran npm test, all green\"'")" "false"
427
- # ...but the command-position anchor must not reject a REAL compound command using the same words.
428
- check "cd /repo && npm test still matches (compound command, not a claim)" \
429
- "$(alm "'cd /repo && npm test'")" "true"
430
-
431
- # The earlier anchor fix was unmeasured in the false-negative direction -- each of these
432
- # genuinely runs the fixture's suite (verified by execution) and scored `false` before this fix.
433
- check "CI=1 npm test matches (variable-assignment prefix)" "$(alm "'CI=1 npm test'")" "true"
434
- check "NODE_ENV=test npm test matches (variable-assignment prefix)" "$(alm "'NODE_ENV=test npm test'")" "true"
435
- check "time npm test matches (keyword position)" "$(alm "'time npm test'")" "true"
436
- check "if true; then npm test; fi matches (keyword position)" "$(alm "'if true; then npm test; fi'")" "true"
437
- check "for f in a b; do npm test; done matches (keyword position)" "$(alm "'for f in a b; do npm test; done'")" "true"
438
- check "cd /tmp/x && CI=1 npm test matches (separator + assignment, composed)" "$(alm "'cd /tmp/x && CI=1 npm test'")" "true"
439
- # Named residual: adding \`(\` to the separator class closes this but breaks the prose case
440
- # below -- verified worse, so it stays open.
441
- check "(npm test) does NOT match -- named residual, not silently left (F-61)" "$(alm "'(npm test)'")" "false"
442
- check "the residual's own reason for staying open: a paren separator would break prose" "$(alm "'echo \"see (npm test) output\"'")" "false"
443
-
444
- # re-enumerated from npm's whole command surface (\`npm help\`), not the two
445
- # pages the earlier miss was on. \`npm it\` confirmed by execution: runs all 3 tests, exit 0.
446
- check "npm it matches (npm install-test's own documented alias)" "$(alm "'npm it'")" "true"
447
- check "npm install-test matches" "$(alm "'npm install-test'")" "true"
448
- check "npm cit matches (npm install-ci-test's own documented alias)" "$(alm "'npm cit'")" "true"
449
- check "npm sit matches (npm install-ci-test's own documented alias)" "$(alm "'npm sit'")" "true"
450
- check "npm clean-install-test matches (documented alias)" "$(alm "'npm clean-install-test'")" "true"
451
- check "npm install-ci-test matches" "$(alm "'npm install-ci-test'")" "true"
452
- # The rest of npm's command surface (read in full via \`npm help\`) does NOT run the declared
453
- # test script -- these stay negative.
454
- check "npm install does NOT match (no test alias)" "$(alm "'npm install'")" "false"
455
- check "npm i does NOT match (no test alias)" "$(alm "'npm i'")" "false"
456
- check "npm ci does NOT match (ci alone, not install-ci-test)" "$(alm "'npm ci'")" "false"
457
- check "npm init does NOT match (no test alias)" "$(alm "'npm init'")" "false"
458
-
459
- check "TEST_INVOCATION_ALIASES: every documented alias actually matches (ties the doc to the code)" \
460
- "$(j "
461
- const A = await import('$ROOT/tests/evals/lib/audit-log.mjs');
462
- process.stdout.write(A.TEST_INVOCATION_ALIASES.every((c) => A.matchesTestInvocation(c)) + '|' + A.TEST_INVOCATION_ALIASES.length);
463
- ")" "true|15"
464
-
465
- # --- audit-log line parsing: tolerant of a bad line, intolerant of pure garbage -----------------
466
- alp() { j "
467
- const A = await import('$ROOT/tests/evals/lib/audit-log.mjs');
468
- const text = $1;
469
- const e = A.parseAuditLog(text);
470
- process.stdout.write(e === null ? 'null' : e.length + ':' + JSON.stringify(e.map(x => [x.tool, x.command])));
471
- "; }
472
- check "a well-formed Bash cmd line parses, command extracted" \
473
- "$(alp '`2026-08-26T12:00:00Z\tCALL\tBash\tcmd=\"npm test\"`')" \
474
- '1:[["Bash","npm test"]]'
475
- check "a non-Bash entry parses with command null" \
476
- "$(alp '`2026-08-26T12:00:00Z\tCALL\tWrite\tpath=\"src/x.mjs\"`')" \
477
- '1:[["Write",null]]'
478
- check "empty content is malformed (null), not an empty pass" \
479
- "$(alp "''")" "null"
480
- check "garbage with no tab-delimited structure at all is malformed (null)" \
481
- "$(alp "'not an audit log at all'")" "null"
482
- # Corrected: isUnterminatedBash() no longer trusts a trailing quote as a termination
483
- # signal, so this now folds rather than drops -- count stays 1, command still matches (below).
484
- check "one unparseable line among good ones folds in (not dropped) -- count and match still hold" \
485
- "$(alp '`2026-08-26T12:00:00Z\tCALL\tBash\tcmd=\"npm test\"\nthis line has no tabs at all`')" \
486
- '1:[["Bash","npm test\"\nthis line has no tabs at all"]]'
487
- # A literal embedded tab INSIDE the command (the header comment's own documented, unescaped case)
488
- # must stay inside `command`, not be read as a 4th field separator -- manual 3-way splitting
489
- # (not a naive split('\t')) is what this pins.
490
- check "an embedded literal tab inside the command stays inside command, not a false field split" \
491
- "$(alp '`2026-08-26T12:00:00Z\tCALL\tBash\tcmd=\"npm test\t--silent\"`')" \
492
- '1:[["Bash","npm test\t--silent"]]'
493
- # an embedded, unescaped NEWLINE fragments a multi-line Bash command across two
494
- # physical log lines -- traced through the real hook, the pre-fix parser dropped the fragment
495
- # carrying the invocation and a genuine `npm test` run scored `fail`. The fold recombines it.
496
- check "a multi-line Bash command (embedded newline) folds into ONE entry, invocation preserved (F-58)" \
497
- "$(alp '`2026-08-26T12:00:00Z\tCALL\tBash\tcmd=\"cd /tmp/fixture\nnpm test\"`')" \
498
- '1:[["Bash","cd /tmp/fixture\nnpm test"]]'
499
- check "the folded multi-line command is recognized as a real test invocation" \
500
- "$(j "
501
- const A = await import('$ROOT/tests/evals/lib/audit-log.mjs');
502
- const e = A.parseAuditLog('2026-08-26T12:00:00Z\tCALL\tBash\tcmd=\"cd /tmp/fixture\nnpm test\"');
503
- process.stdout.write(String(A.matchesTestInvocation(e[0].command)));
504
- ")" "true"
505
-
506
- # a multi-line command whose FIRST line ends in a literal quote (an ordinary git
507
- # commit message before npm test) used to read as already-terminated -- traced through the real
508
- # hook, this dropped the invocation and scored a genuine run FAIL, the multi-line defect reopened.
509
- check "a quoted first line does NOT falsely read as terminated -- invocation preserved" \
510
- "$(alp '`2026-08-27T00:00:00Z\tCALL\tBash\tcmd=\"git commit -m \"fix: reject expired tokens\"\nnpm test\"`')" \
511
- '1:[["Bash","git commit -m \"fix: reject expired tokens\"\nnpm test"]]'
512
- check "the recovered quoted-first-line command is recognized as a real test invocation" \
513
- "$(j "
514
- const A = await import('$ROOT/tests/evals/lib/audit-log.mjs');
515
- const e = A.parseAuditLog('2026-08-27T00:00:00Z\tCALL\tBash\tcmd=\"git commit -m \"fix: reject expired tokens\"\nnpm test\"');
516
- process.stdout.write(String(A.matchesTestInvocation(e[0].command)));
517
- ")" "true"
518
- # Proves dropping the quote check is safe: every line tries as a new entry FIRST, so a genuine
519
- # second command is never mistaken for a continuation of the first.
520
- check "two separate, complete Bash commands back to back stay two entries, not folded into one" \
521
- "$(alp '`2026-08-27T00:00:00Z\tCALL\tBash\tcmd=\"npm test\"\n2026-08-27T00:00:01Z\tCALL\tBash\tcmd=\"git status\"`')" \
522
- '2:[["Bash","npm test"],["Bash","git status"]]'
523
-
524
- # --- reading the log from a real working tree: absent vs. malformed vs. well-formed -------------
525
- alwd=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
526
- check "readAuditLog: no .somi/audit.log at all -> null (absent)" \
527
- "$(j "const A = await import('$ROOT/tests/evals/lib/audit-log.mjs'); process.stdout.write(String(A.readAuditLog('$alwd')))")" \
528
- "null"
529
- mkdir -p "$alwd/.somi"
530
- printf 'garbage, no tabs, no structure\n' > "$alwd/.somi/audit.log"
531
- check "readAuditLog: content with no tab-delimited lines -> null (malformed)" \
532
- "$(j "const A = await import('$ROOT/tests/evals/lib/audit-log.mjs'); process.stdout.write(String(A.readAuditLog('$alwd')))")" \
533
- "null"
534
- printf '2026-08-26T12:00:00Z\tCALL\tBash\tcmd="npm test"\n' > "$alwd/.somi/audit.log"
535
- check "readAuditLog + scoreTestInvocation: a well-formed log with a matching entry scores PASS" \
536
- "$(j "
537
- const A = await import('$ROOT/tests/evals/lib/audit-log.mjs');
538
- process.stdout.write(String(A.scoreTestInvocation(A.readAuditLog('$alwd'))));
539
- ")" "pass"
540
- printf '2026-08-26T12:00:00Z\tCALL\tBash\tcmd="npm run lint"\n' > "$alwd/.somi/audit.log"
541
- check "scoreTestInvocation: log exists and shows NO matching invocation -> FAIL, not a defer" \
542
- "$(j "
543
- const A = await import('$ROOT/tests/evals/lib/audit-log.mjs');
544
- process.stdout.write(String(A.scoreTestInvocation(A.readAuditLog('$alwd'))));
545
- ")" "fail"
546
- check "scoreTestInvocation: a null auditLog (absent/malformed) -> null, never fail" \
547
- "$(j "const A = await import('$ROOT/tests/evals/lib/audit-log.mjs'); process.stdout.write(String(A.scoreTestInvocation(null)))")" \
548
- "null"
549
- rm -rf "$alwd"
550
-
551
- # --- overlay: EXECUTED overrides the judge whenever the log is readable; null falls back to the
552
- # judge (REPORT-ONLY; this replaces the earlier "EXCLUDES" behaviour) --
553
- otv() { j "
554
- const crit = [{ n: 3, verdict: '$1', evidence: 'judge: prose' }];
555
- M.overlayTestInvocationVerdict(crit, $2);
556
- process.stdout.write(crit[0].verdict + '|' + (crit[0].executed ?? 'undefined') + '|' + crit[0].evidence);
557
- "; }
558
- check "log shows a match: overlays PASS even though the judge (reading prose) said fail" \
559
- "$(otv fail "'pass'")" \
560
- "pass|true|EXECUTED: .somi/audit.log shows a Bash entry matching the test-invocation alias set (not judged)"
561
- # THE motivating case: a final message that CLAIMS tests ran, with a judge fooled by
562
- # the prose into 'pass' -- the audit log overrules it.
563
- check "log shows no match: overlays FAIL even though the judge (fooled by a claim in the prose) said pass" \
564
- "$(otv pass "'fail'")" \
565
- "fail|true|EXECUTED: .somi/audit.log shows no Bash entry matching the test-invocation alias set (not judged)"
566
- # Mutation check: reverting to the pre-correction "splice criterion 3 out on null" would leave
567
- # crit.length at 0, exactly what this assertion catches.
568
- check "null (absent/malformed log): the judge's own verdict stands, report-only (supersedes F-56)" \
569
- "$(j "
570
- const crit = [{ n: 3, verdict: 'pass', evidence: 'judge: prose' }];
571
- M.overlayTestInvocationVerdict(crit, null);
572
- process.stdout.write(String(crit.length) + '|' + crit[0].verdict + '|' + (crit[0].executed ?? 'undefined'));
573
- ")" "1|pass|undefined"
574
- check "null with criterion 3 absent from the judge reply is also a no-op, not a throw" \
575
- "$(j "
576
- const crit = [{ n: 1, verdict: 'pass', evidence: '-' }];
577
- M.overlayTestInvocationVerdict(crit, null);
578
- process.stdout.write(String(crit.length) + '|' + crit[0].verdict);
579
- ")" "1|pass"
580
- # a judge reply OMITTING criterion 3 no longer stays silent -- a decided (non-null) verdict
581
- # is APPENDED, so the executed verdict does not depend on the judge having emitted it at all.
582
- check "a judge reply missing criterion 3 appends the executed verdict rather than staying silent" \
583
- "$(j "
584
- const crit = [{ n: 1, verdict: 'pass', evidence: '-' }];
585
- M.overlayTestInvocationVerdict(crit, 'fail');
586
- process.stdout.write(String(crit.length) + '|' + crit[0].verdict + '|' + crit[1].n + '|' + crit[1].verdict + '|' + crit[1].executed);
587
- ")" "2|pass|3|fail|true"
588
-
589
- # the marking was entirely unpinned -- deleting it left the gate green. Pinned here as
590
- # the generic function it is (S1's own end-to-end pin retired with the report-only demotion above).
591
- check "markDimensionsExcluded marks every named dimension excluded, leaves the rest untouched (F-63)" \
592
- "$(j "
593
- const dims = { S3: true, S6: false };
594
- M.markDimensionsExcluded(dims, ['S5', 'S1']);
595
- process.stdout.write(JSON.stringify(dims));
596
- ")" '{"S3":true,"S6":false,"S5":"excluded","S1":"excluded"}'
597
-
598
- # --- installSomi() now registers the audit-log hook ---------------------------------------------
599
- # --- one quota detector, deliberately asymmetric -----------------------------------
600
- # run.mjs's quota check sat INSIDE `if (!run.ok)`, so a session-limit exit arriving with
601
- # status 0 was graded as draw data -- the same defect class as on the convergence side, where
602
- # it was a Blocker. Hoisting the OLD broad regex would have been worse than the bug: these tasks run
603
- # an agent against this repo, whose docs discuss quota constantly, so every healthy draw would have
604
- # been discarded. The detector is therefore asymmetric, and these checks pin BOTH halves plus the
605
- # discrimination between them.
606
- q() { j "
607
- const I = await import('$ROOT/tests/evals/lib/install.mjs');
608
- process.stdout.write(String(I.isQuotaExit($1, $2)));
609
- "; }
610
-
611
- SIG="You've hit your session limit"
612
-
613
- check "failed run + broad quota text -> quota exit (the evidenced shape, four real incidents)" \
614
- "$(q "{ok:false,timedOut:false,stdout:'fatal: usage limit reached',stderr:''}" "{didWork:false}")" "true"
615
-
616
- check "F-321: ok:true run carrying the EXACT signature, no work done -> quota exit (was graded as data)" \
617
- "$(q "{ok:true,timedOut:false,stdout:\"$SIG\",stderr:''}" "{didWork:false}")" "true"
618
-
619
- # The case that makes the asymmetry necessary rather than decorative.
620
- check "ok:true run carrying the signature but which DID work -> NOT a quota exit (a healthy draw may quote it)" \
621
- "$(q "{ok:true,timedOut:false,stdout:\"discussing $SIG in the docs\",stderr:''}" "{didWork:true}")" "false"
622
-
623
- # The regression the naive hoist would have caused: broad words must not reach an ok:true run.
624
- check "ok:true run merely containing the WORD quota -> NOT a quota exit (broad pattern is failed-runs-only)" \
625
- "$(q "{ok:true,timedOut:false,stdout:'I checked the quota and rate limit docs',stderr:''}" "{didWork:false}")" "false"
626
-
627
- check "an unknown didWork never promotes an ok:true run to a quota exit" \
628
- "$(q "{ok:true,timedOut:false,stdout:\"$SIG\",stderr:''}" "{}")" "false"
629
-
630
- check "a timeout is never a quota exit (it is the wait-cap path's business)" \
631
- "$(q "{ok:false,timedOut:true,stdout:'session limit',stderr:''}" "{didWork:false}")" "false"
632
-
633
- # one literal, not two. convergence.mjs must SOURCE it, not redeclare it.
634
- check "F-322: convergence.mjs re-exports install.mjs's SESSION_LIMIT_SIGNATURE rather than declaring its own" \
635
- "$(j "
636
- const C = await import('$ROOT/tests/evals/convergence.mjs');
637
- const I = await import('$ROOT/tests/evals/lib/install.mjs');
638
- process.stdout.write(String(C.SESSION_LIMIT_SIGNATURE === I.SESSION_LIMIT_SIGNATURE && I.SESSION_LIMIT_SIGNATURE.length > 0));
639
- ")" "true"
640
- check "F-322: convergence.mjs holds no second copy of the literal" \
641
- "$(grep -c "= \"You've hit your session limit\"" "$ROOT/tests/evals/convergence.mjs")" "0"
642
-
643
- # Without this, `.somi/audit.log` is never written on a live run (installSomi() excluded every
644
- # hook until this fix). Functional: the registered command is invoked as Claude Code would.
645
- instw=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
646
- hookcmd=$( j "
647
- const I = await import('$ROOT/tests/evals/lib/install.mjs');
648
- I.installSomi('$ROOT', '$instw');
649
- const fs = await import('node:fs');
650
- const settings = JSON.parse(fs.readFileSync('$instw/.claude/settings.json', 'utf8'));
651
- process.stdout.write(settings.hooks?.PostToolUse?.[0]?.hooks?.[0]?.command ?? '');
652
- ")
653
- # Quoted (Nit): the registered command is `node "<path>"`, not `node <path>` -- strip the
654
- # literal `node "` prefix and the trailing `"`, not just `node `.
655
- hookpath="${hookcmd#node \"}"
656
- hookpath="${hookpath%\"}"
657
- if [ -n "$hookcmd" ] && [ -f "$hookpath" ]; then
658
- ok "installSomi() registers the audit-log hook, at a path that exists"
659
- else
660
- bad "installSomi() registers the audit-log hook, at a path that exists (got: '$hookcmd')"
661
- fi
662
- echo '{"tool_name":"Bash","tool_input":{"command":"npm test"}}' | \
663
- env CLAUDE_PROJECT_DIR="$instw" node "$hookpath" >/dev/null 2>&1
664
- check "the registered hook, invoked as Claude Code would invoke it, writes a matching audit.log entry" \
665
- "$(grep -c 'Bash.*cmd="npm test"' "$instw/.somi/audit.log" 2>/dev/null || echo 0)" "1"
666
- rm -rf "$instw"
667
-
668
- # --- the pooled certification gate, on the SETTLED 2-dimension corpus --------------------
669
- # Real task ids and their real GATING dim (task 01's S3, task 02's S5) -- not the
670
- # earlier synthetic 13-dimension pool, which certify()'s new gating-only filter would ignore.
671
- mk() { j "
672
- const tasks = { '01': [], '02': [] };
673
- for (let r = 0; r < $2; r++) tasks['01'].push({ index: r, dimensions: { S3: r < $1 } });
674
- for (let r = 0; r < $4; r++) tasks['02'].push({ index: r, dimensions: { S5: r < $3 } });
675
- const res = M.buildResult({ source: { ref: 'x', sha: 'deadbeef' }, tasks, runs: Math.max($2, $4) });
676
- const c = M.certify(res);
677
- process.stdout.write([c.certified, c.failures, c.draws, c.sufficientDraws].join('|'));
678
- "; }
679
- # 2 gating dims x CERTIFY_N (120) each = 240 draws. A perfect corpus and one at exactly the
680
- # budget both certify. Args: passes01 n01 passes02 n02.
681
- check "2 gating dims x 120/120 each certifies" "$(mk 120 120 120 120)" "true|0|240|true"
682
- check "5 failures across 240 draws certifies (at the bar)" "$(mk 115 120 120 120)" "true|5|240|true"
683
- check "6 failures across 240 draws does NOT certify" "$(mk 114 120 120 120)" "false|6|240|true"
684
-
685
- # The case the gate exists for: ONE dimension secretly at 0.90 while the other holds. grade()'s
686
- # own per-dimension band (>=18/20, scaled to >=108/120) would call this dimension PASS on its own;
687
- # pooled catches it, because 12 failures from one dimension alone crosses the budget of 5.
688
- check "task 01's S3 quietly at 90% (would grade PASS alone) is caught by the pooled budget" "$(j "
689
- const tasks = { '01': [], '02': [] };
690
- for (let r = 0; r < 120; r++) tasks['01'].push({ index: r, dimensions: { S3: r < 108 } });
691
- for (let r = 0; r < 120; r++) tasks['02'].push({ index: r, dimensions: { S5: true } });
692
- const c = M.certify(M.buildResult({ source: {ref:'x',sha:'d'}, tasks, runs: 120 }));
693
- process.stdout.write([c.certified, c.failures, c.softest[0].task, c.softest[0].rate.toFixed(2)].join('|'));")" \
694
- "false|12|01|0.90"
695
-
696
- # A short run must not read as certified. 0 failures out of 20 draws is not a sharp corpus; it is
697
- # a corpus that has barely been sampled.
698
- mk1() { j "
699
- const tasks = { '01': [] };
700
- for (let r = 0; r < $2; r++) tasks['01'].push({ index: r, dimensions: { S3: r < $1 } });
701
- const c = M.certify(M.buildResult({ source: { ref: 'x', sha: 'deadbeef' }, tasks, runs: $2 }));
702
- process.stdout.write([c.certified, c.failures, c.draws, c.sufficientDraws].join('|'));
703
- "; }
704
- check "a 20-draw run cannot certify, however clean" "$(mk1 20 20)" "false|0|20|false"
705
-
706
- # --- 2.4b acceptance point 2: both directions, at the derived draw count ------------------------
707
- check "a fully-conforming corpus at 240 draws (99.6% pass) certifies" "$(mk 119 120 120 120)" "true|1|240|true"
708
- check "a soft corpus at 240 draws (95% pass) does NOT certify" "$(mk 114 120 114 120)" "false|12|240|true"
709
-
710
- # --- 2.4b acceptance point 1: a report-only dimension never reaches `dimensions` -----------------
711
- check "a report-only dimension appears in reportOnly, absent from dimensions" "$(j "
712
- const r = M.buildResult({ source: {ref:'x',sha:'d'}, tasks: { '01': [{ index: 0, dimensions: { S3: true, S1: true } }] }, runs: 1 });
713
- const d = r.tasks['01'];
714
- process.stdout.write(('S1' in d.dimensions) + '|' + ('S1' in d.reportOnly) + '|' + ('S3' in d.dimensions));
715
- ")" "false|true|true"
716
-
717
- # --- 2.4b acceptance point 4: the drift-guard checks buildResult()'s REAL output, not the table
718
- # a second time -- a table-to-constant comparison alone cannot see a document-vs-code gap.
719
- check "SCOPES.full.draws equals (gating dims buildResult() actually emits for a synthetic full run) x CERTIFY_N" "$(j "
720
- const tasks = { '01': [{ index: 0, dimensions: { S3: true } }], '02': [{ index: 0, dimensions: { S5: true } }] };
721
- const r = M.buildResult({ source: { ref: 'x', sha: 'd' }, tasks, runs: 1 });
722
- let n = 0; for (const t of Object.values(r.tasks)) n += Object.keys(t.dimensions).length;
723
- process.stdout.write(String(M.SCOPES.full.draws === n * M.CERTIFY_N) + '|' + n + '|' + M.CERTIFY_N + '|' + M.SCOPES.full.draws);
724
- ")" "true|2|120|240"
725
-
726
- # --- 2.4b acceptance points 7 and 8: the per-dimension floor, both shapes a missing
727
- # observation takes, through the SAME mechanism. In both, pooled draws/failures look clean --
728
- # only the per-dimension floor (`d.n >= CERTIFY_N` for EVERY gating dim) can catch this.
729
- check "S5 present as {n:0, excluded:N} (100% exclusion) fails the floor though pooled draws/failures look clean" "$(j "
730
- const tasks = { '01': [], '02': [] };
731
- for (let r = 0; r < 240; r++) tasks['01'].push({ index: r, dimensions: { S3: true } });
732
- for (let r = 0; r < 240; r++) tasks['02'].push({ index: r, dimensions: { S5: 'excluded' } });
733
- const c = M.certify(M.buildResult({ source: {ref:'x',sha:'d'}, tasks, runs: 240 }));
734
- process.stdout.write([c.certified, c.draws, c.failures, c.underFloor.length, c.underFloor[0]?.task + '/' + c.underFloor[0]?.dim].join('|'));
735
- ")" "false|240|0|1|02/S5"
736
- check "S5 absent from dimensions entirely (every task-02 draw returned no observation) fails the SAME floor, not a second mechanism" "$(j "
737
- const tasks = { '01': [], '02': [] };
738
- for (let r = 0; r < 240; r++) tasks['01'].push({ index: r, dimensions: { S3: true } });
739
- for (let r = 0; r < 240; r++) tasks['02'].push({ index: r, dimensions: {} });
740
- const r2 = M.buildResult({ source: {ref:'x',sha:'d'}, tasks, runs: 240 });
741
- const c = M.certify(r2);
742
- process.stdout.write([c.certified, c.draws, c.failures, ('S5' in r2.tasks['02'].dimensions), c.underFloor.length, c.underFloor[0]?.task + '/' + c.underFloor[0]?.dim].join('|'));
743
- ")" "false|240|0|false|1|02/S5"
744
-
745
- # --- sharding, resume and merge: what makes a 260-draw certification batchable ------------------
746
- # Certification is hours of wall clock. Each run is persisted the moment it finishes so a crash at
747
- # run 19 does not discard eighteen paid-for runs, and a later invocation skips what is already on
748
- # disk. Tested by writing shards directly -- no model, no network.
749
- SHARD_SHA="testsha$(date +%s)"
750
- # Each task's shard uses its own real GATING dim (task 01's S3, task 02's S5) --
751
- # certify() reads exclusively from `dimensions`, so a shard tagged with any other dim would never
752
- # reach it.
753
- # Built through M.shardRecord() -- the SAME function main()'s drawing loop is meant to write
754
- # through -- not a hand-built literal checked against a hand-built expectation.
755
- mk_shard() { j "
756
- const fs = await import('node:fs');
757
- const dim = '$1' === '01' ? 'S3' : 'S5';
758
- const p = M.shardPath('$SHARD_SHA', '$1', $2);
759
- fs.mkdirSync(p.replace(/\/[^/]+\$/, ''), { recursive: true });
760
- fs.writeFileSync(p, JSON.stringify(M.shardRecord('$SHARD_SHA', '$1', { index: $2, dimensions: { [dim]: $3 }, criteria: null, error: null })));
761
- process.stdout.write('ok');
762
- "; }
763
- mk_shard 01 0 true >/dev/null; mk_shard 01 1 true >/dev/null
764
- mk_shard 01 2 false >/dev/null; mk_shard 02 0 true >/dev/null
765
-
766
- check "shardRecord() produces the shape both the production writer and this fixture share (F-133)" \
767
- "$(j "process.stdout.write(JSON.stringify(M.shardRecord('s','01',{index:0})))")" \
768
- '{"sha":"s","taskId":"01","schema":2,"run":{"index":0}}'
769
- # the check above pins shardRecord()'s OWN shape, not that the live-agent-gated production
770
- # write reaches it -- no test does. Pinned structurally: grepping the FULL `writeFileSync(shard,
771
- # ...)` prefix, not just `shardRecord(...)` alone, which used to also match the docstring's prose.
772
- check "main()'s drawing loop writes the shard through shardRecord(), not a parallel literal (F-136)" \
773
- "$(grep -c 'writeFileSync(shard, JSON.stringify(shardRecord(source\.sha, id, r)' "$ROOT/$R")" "1"
774
-
775
- check "completedIndices sees the shards already on disk" \
776
- "$(j "process.stdout.write([...M.completedIndices('$SHARD_SHA','01',5)].join(','))")" "0,1,2"
777
- check "an unwritten index is not reported complete" \
778
- "$(j "process.stdout.write(String(M.completedIndices('$SHARD_SHA','01',5).has(4)))")" "false"
779
-
780
- merged=$( j "
781
- const r = M.mergeShards('$SHARD_SHA', { runs: 3 });
782
- const d = r.tasks['01'].dimensions.S3;
783
- process.stdout.write([Object.keys(r.tasks).sort().join('+'), r.tasks['01'].runs.length, d.passes + '/' + d.n, r.source.sha].join('|'));
784
- ")
785
- check "mergeShards folds every shard, per task, in index order" "$merged" "01+02|3|2/3|$SHARD_SHA"
786
-
787
- # Shards are keyed by SHA. Pooling draws scored against DIFFERENT definition sets would answer a
788
- # question nobody asked -- and `--source HEAD` is how that happens, because HEAD moves between
789
- # batches.
790
- check "a different sha has no shards" \
791
- "$(j "try { M.mergeShards('${SHARD_SHA}-other'); process.stdout.write('MERGED'); } catch { process.stdout.write('threw'); }")" \
792
- "threw"
793
-
794
- # Certification reads the merged view, so a partial run reports honestly rather than certifying.
795
- part=$( j "
796
- const c = M.certify(M.mergeShards('$SHARD_SHA', { runs: 3 }));
797
- process.stdout.write([c.certified, c.failures, c.draws, c.sufficientDraws].join('|'));
798
- ")
799
- check "a partial corpus cannot certify on few failures alone" "$part" "false|1|4|false"
800
-
801
- rm -rf "$ROOT/tests/evals/results/$SHARD_SHA"
802
- check "shard directory is removable and merge then fails loudly" \
803
- "$(j "try { M.mergeShards('$SHARD_SHA'); process.stdout.write('MERGED'); } catch { process.stdout.write('threw'); }")" \
804
- "threw"
805
-
806
- # --- mergeShards() skips a shard from a prior schema, with a clear message ----------------
807
- # SCHEMA_VERSION was bumped 1 -> 2 but nothing read it back -- this is the pass that gives
808
- # it a job. A trimmed copy of a real shard from before the schema field existed (committed as a
809
- # fixture so this runs on a fresh checkout) is copied into a throwaway SHA, never mutated in place.
810
- legacysha="legacytest$(date +%s)"
811
- legacydir="$ROOT/tests/evals/results/$legacysha"
812
- mkdir -p "$legacydir"
813
- cp "$ROOT/tests/scripts/fixtures/legacy-shard-no-schema.json" "$legacydir/01-000.json"
814
- legacyerrfile=$(mktemp)
815
- legacyout=$(node --input-type=module -e "
816
- const M = await import('$ROOT/$R');
817
- process.stdout.write(String(M.certify(M.mergeShards('$legacysha')).draws));
818
- " 2>"$legacyerrfile")
819
- legacyerr=$(cat "$legacyerrfile"); rm -f "$legacyerrfile"
820
- check "mergeShards() skips a real, schema-less legacy shard rather than merging it" "$legacyout" "0"
821
- case "$legacyerr" in
822
- *"schema"*"01-000.json"*) ok "mergeShards() names the skipped shard and the reason in a clear message" ;;
823
- *) bad "mergeShards() names the skipped shard and the reason in a clear message (got: ${legacyerr:0:200})" ;;
824
- esac
825
- # The guard is per-shard, not "give up on the whole directory": a CURRENT-schema shard alongside
826
- # the skipped legacy one must still merge normally. stdout only (stderr carries the warning above
827
- # and `j()` merges the two, which would corrupt this numeric comparison).
828
- j "
829
- const fs = await import('node:fs');
830
- fs.writeFileSync(M.shardPath('$legacysha','01',1), JSON.stringify({ sha: '$legacysha', taskId: '01', schema: M.SCHEMA_VERSION, run: { index: 1, dimensions: { S3: true }, criteria: null, error: null } }));
831
- " >/dev/null
832
- check "a current-schema shard alongside a skipped legacy one still merges" \
833
- "$(node --input-type=module -e "const M = await import('$ROOT/$R'); process.stdout.write(String(M.certify(M.mergeShards('$legacysha')).draws));" 2>/dev/null)" "1"
834
- # the pass-1 Nit's fix was two halves -- stderr (pinned above via $legacyerr) and stdout,
835
- # the half that actually survives `--certify sha > cert.txt`. stdout only (2>/dev/null): a caller
836
- # reading just the redirected file must still see the pointer.
837
- legacycertout=$(node "$R" --certify "$legacysha" 2>/dev/null)
838
- case "$legacycertout" in
839
- *"(skipped 1 shard(s) from a prior schema -- see stderr, or re-run --rescore to upgrade them)"*)
840
- ok "certify()'s skipped-shard pointer survives a stdout-only redirect (F-143)" ;;
841
- *) bad "certify()'s skipped-shard pointer survives a stdout-only redirect (got: ${legacycertout: -300})" ;;
842
- esac
843
- rm -rf "$legacydir"
844
-
845
- # --- 2.4c (fixed pass 2): the resume-read in main()'s drawing loop applies the SAME schema check
846
- # as mergeShards(), via the shared readShard(). A stale-schema shard used to be resumed
847
- # from silently, carrying judge-authored dimensions from before this version's semantics -- measured
848
- # on a copy of the same real legacy shard above, read back {"S2":true,...,"S3":true} with S3
849
- # judge-authored from before boundaryRespected was wired. Fixed: excluded and warned about, NOT
850
- # redrawn automatically (the settled answer -- a redraw is ~10 minutes of a live agent
851
- # run, the maintainer's call, not this loop's). Both indices below are already shard-backed, so the
852
- # drawing loop never falls through to a live agent or judge call; the `claude` stub only satisfies
853
- # preflight()'s `command -v` check.
854
- resumebin=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
855
- cat > "$resumebin/claude" <<'STUB'
856
- #!/usr/bin/env bash
857
- echo 'unused -- every requested index is already shard-backed'
858
- STUB
859
- chmod +x "$resumebin/claude"
860
- resumedir="$ROOT/tests/evals/results/unversioned"
861
- # NOT a scratch namespace like every other shard test's $(date +%s) sha -- shardPath(null,
862
- # ...) always resolves here, and a real, quota-paid draw can genuinely live at this path. Move it
863
- # aside and restore it; an unconditional rm -rf would silently unpay a real run and report green.
864
- resumedir_backup=""
865
- if [ -d "$resumedir" ]; then
866
- resumedir_backup="$(mktemp -d)/unversioned"
867
- # unchecked, a failed mv (e.g. TMPDIR full) leaves the real directory in place while the
868
- # rest of this block proceeds to write fixtures into it and rm -rf it below -- fail loud instead.
869
- mv "$resumedir" "$resumedir_backup" || { bad "F-135: could not move aside real results/unversioned -- refusing to proceed"; exit 1; }
870
- echo " (moved aside real results/unversioned to $resumedir_backup for restore)"
871
- fi
872
- mkdir -p "$resumedir"
873
- j "
874
- const fs = await import('node:fs');
875
- fs.writeFileSync(M.shardPath(null,'01',0), JSON.stringify(M.shardRecord(null,'01',{ index: 0, dimensions: { S3: true }, criteria: null, error: null })));
876
- " >/dev/null
877
- cp "$ROOT/tests/scripts/fixtures/legacy-shard-no-schema.json" "$resumedir/01-001.json"
878
- resumeout=$(ANTHROPIC_API_KEY=test-stub-key PATH="$resumebin:$PATH" node "$R" --source . --tasks 01 --runs 2 --out "$(mktemp)" 2>&1)
879
- case "$resumeout" in
880
- *"skipped"*"01-001.json"*) ok "the resume-read skips a stale-schema shard rather than resuming from it (F-131)" ;;
881
- *) bad "the resume-read skips a stale-schema shard rather than resuming from it (got: ${resumeout:0:400})" ;;
882
- esac
883
- case "$resumeout" in
884
- *"01 run 1/2: (already done)"*) ok "a current-schema shard alongside the skipped one still resumes normally" ;;
885
- *) bad "a current-schema shard alongside the skipped one still resumes normally (got: ${resumeout:0:400})" ;;
886
- esac
887
- rm -rf "$resumebin" "$resumedir"
888
- [ -n "$resumedir_backup" ] && mv "$resumedir_backup" "$resumedir"
889
-
890
- # --- executed criterion: task 03 criterion 3, scored by running it rather than judging it -------
891
- rep() { j "
892
- const R = await import('$ROOT/tests/evals/lib/reproduce.mjs');
893
- const refs = await (await import('$ROOT/$R')).task03Reference('$ROOT');
894
- process.stdout.write(String(R.reproduces(\`$1\`, refs)));
895
- "; }
896
- check "a cited 31-day date reproduces the defect" "$(rep 'the bug hits on 2026-07-16')" "true"
897
- check "a cited 30-day date does NOT reproduce" "$(rep 'consider 2026-04-16 here')" "false"
898
- check "a named 31-day month reproduces" "$(rep 'on July 16 it under-credits')" "true"
899
- check "a named 30-day month does not" "$(rep 'on June 16 it under-credits')" "false"
900
- # Fails SAFE. A parser returning `false` on an unrecognised phrasing would fail a correct review
901
- # for citing its case in a form nobody anticipated -- the "criterion that fails a conforming run"
902
- # this corpus keeps rediscovering. null means "fall back to the judge".
903
- check "a hedge with no date returns null (judge fallback)" "$(rep 'the proration logic may be wrong')" "null"
904
-
905
- # Reverted after the first agreement check disagreed on 1 of 6 verdicts. `null` means "whatever
906
- # the CLI defaults to" -- the larger model -- not "unset by accident".
907
- check "the judge does NOT default to a cheaper model" \
908
- "$(j "process.stdout.write(String((await import('$ROOT/tests/evals/lib/score.mjs')).DEFAULT_JUDGE_MODEL))")" "null"
909
-
910
- # --- judge-agreement.mjs and --judge-model: the judge machinery is removed -------------
911
- check "judge-agreement.mjs no longer exists" \
912
- "$(j "process.stdout.write(String((await import('node:fs')).existsSync('$ROOT/tests/evals/judge-agreement.mjs')))")" "false"
913
- case "$(node "$R" --judge-model sonnet --dry-run --source HEAD --tasks 01 --runs 1 2>&1; echo "EXIT:$?")" in
914
- *"unknown argument: --judge-model"*"EXIT:1") ok "--judge-model is not a recognized flag (removed outright)" ;;
915
- *) bad "--judge-model is not a recognized flag (removed outright)" ;;
916
- esac
917
-
918
- # --- parseVerdict() rejects a judge reply with duplicate n --------------------------------
919
- # `criteria` is keyed by n, not positional -- a duplicate n is not a shape any
920
- # downstream consumer (toDimensions, the splice-based overlays) can safely reduce over. Mutated
921
- # from a genuinely well-formed reply, not hand-built already-broken, so a reversion of the check
922
- # below is provably what turns this red.
923
- pv() { j "
924
- const S = await import('$ROOT/tests/evals/lib/score.mjs');
925
- const v = S.parseVerdict($1);
926
- process.stdout.write(v.ok ? 'ok' : v.error);
927
- "; }
928
- check "a well-formed reply with distinct n parses ok" \
929
- "$(pv "'{\"criteria\":[{\"n\":1,\"verdict\":\"pass\"},{\"n\":2,\"verdict\":\"fail\"}]}'")" "ok"
930
- check "a duplicate n is rejected, not silently accepted" \
931
- "$(pv "'{\"criteria\":[{\"n\":1,\"verdict\":\"pass\"},{\"n\":1,\"verdict\":\"fail\"}]}'")" \
932
- "duplicate criterion n=1 in judge reply"
933
-
934
- bnd() { j "
935
- const B = await import('$ROOT/tests/evals/lib/boundary.mjs');
936
- const r = B.boundaryRespected($1);
937
- process.stdout.write(r.ok + (r.offenders.length ? ':' + r.offenders.join(',') : ''));
938
- "; }
939
- check "a conforming /plan run respects the boundary" \
940
- "$(bnd "[{path:'.somi/README.md'},{path:'.somi/audit.log'},{path:'.somi/somi-state/x'},{path:'.somi/plans/y/spec.md'}]")" "true"
941
- check "a touched source file is caught, and named" \
942
- "$(bnd "[{path:'src/ingest/handler.mjs'}]")" "false:src/ingest/handler.mjs"
943
- check "a stray root file is caught" \
944
- "$(bnd "[{path:'NOTES.md'}]")" "false:NOTES.md"
945
-
946
- # --- boundaryRespected's `slug` parameter, wired through (was accepted and never used) -----
947
- bnd_slug() { j "
948
- const B = await import('$ROOT/tests/evals/lib/boundary.mjs');
949
- const r = B.boundaryRespected($1, { slug: $2 });
950
- process.stdout.write(r.ok + (r.offenders.length ? ':' + r.offenders.join(',') : ''));
951
- "; }
952
- # boundaryRespected is called only from the taskId === '01' block (run.mjs), so its slug is always
953
- # TASK-01-SHAPED -- `ingest-audit-trail` is a real slug from a stored task-01 shard
954
- # (results/4ff4da62.../01-000.json), used here rather than task02-code's fixture slug (Nit, review
955
- # pass 1: the prior comment named a call that does not exist). A write into a DIFFERENT slug's plan
956
- # directory must be rejected -- unreachable before this fix, since the old unscoped allowlist
957
- # matched any .somi/plans/ path.
958
- check "boundaryRespected REJECTS a write into a different slug's plan directory" \
959
- "$(bnd_slug "[{path:'.somi/plans/other-slug/spec.md'}]" "'ingest-audit-trail'")" \
960
- "false:.somi/plans/other-slug/spec.md"
961
- # Bidirectional: the same slug-scoped allowlist must still accept the running draw's OWN directory.
962
- check "boundaryRespected ACCEPTS a write into the running draw's own slug directory" \
963
- "$(bnd_slug "[{path:'.somi/plans/ingest-audit-trail/progress.md'}]" "'ingest-audit-trail'")" "true"
964
- # The sole fallback path: slug discovery came back null (no plan directory was ever created for
965
- # this draw) -- boundaryRespected must fall back to the broad prefix and ACCEPT, never reject.
966
- # A false `fail` on 1 of 3 gating dimensions is worse than the over-permissiveness this replaces.
967
- check "boundaryRespected: null slug falls back to the broad prefix and ACCEPTS, does not reject" \
968
- "$(bnd_slug "[{path:'.somi/plans/other-slug/spec.md'}]" "null")" "true"
969
-
970
- # --- a slug with regex metacharacters behaves as a plain prefix, not a pattern -------------
971
- # Verified that the OLD `new RegExp` version threw on `fix(auth`, false-failed the
972
- # draw's own write on `plan[1]`, and over-matched `a.b` against `aXb`. These pin all three
973
- # directions as a measurement, not a claim.
974
- check "a slug with regex metacharacters does not throw and accepts the draw's own write" \
975
- "$(bnd_slug "[{path:'.somi/plans/fix(auth/spec.md'}]" "'fix(auth'")" "true"
976
- check "a slug with a character-class metacharacter does not false-fail the draw's own write" \
977
- "$(bnd_slug "[{path:'.somi/plans/plan[1]/spec.md'}]" "'plan[1]'")" "true"
978
- check "a slug with a '.' does not over-match a different, similarly-named slug's directory" \
979
- "$(bnd_slug "[{path:'.somi/plans/aXb/spec.md'}]" "'a.b'")" \
980
- "false:.somi/plans/aXb/spec.md"
981
-
982
- # --- task 01 scored from the ARTIFACT, not the prose -------------------------------------------
983
- # Certification failed with a clean pattern: executed criteria 4/4, near-mechanical 4/4, semantic
984
- # judged ones 3/4, 3/4, 2/4. A model judge cannot deliver the >=99% consistency the error budget
985
- # assumes. The criteria were semantic because prose was all there was to score -- the mandated
986
- # DECISIONS-NEEDED structure is destroyed by the command's relay in --print mode (measured: 0 of 4
987
- # runs emitted the fenced block). decisions.md survives on disk, and parsing it is deterministic.
988
- SAMPLE="$ROOT/tests/evals/fixtures/_candidates/decisions-sample.md"
989
- t01() { j "
990
- const fs = await import('node:fs');
991
- const S = await import('$ROOT/tests/evals/lib/score-task01.mjs');
992
- let md = fs.readFileSync('$SAMPLE','utf8');
993
- $1
994
- const v = S.executedVerdicts(md);
995
- process.stdout.write(Object.keys(v).filter(k=>/^\d+$/.test(k)).sort().map(k=>k+'='+v[k]).join(' '));
996
- "; }
997
- # THE case that invalidated artifact scoring for this task. Task 01 scores the RESEARCH pass,
998
- # which halts before anything is verified, so decisions.md is scaffolded from the template and
999
- # correctly left empty. Reading placeholders as content returned FALSE and manufactured failures
1000
- # on runs that did nothing wrong -- observed live: the run with a scaffold scored S2- S1-, the run
1001
- # with no artifact deferred to the judge and scored S1+.
1002
- check "an unfilled template defers every criterion instead of failing them" \
1003
- "$(t01 "md = '# Decisions — <work item name>\n\n## D1 — <decision title in noun form>\n\n### Decision\n\n<one sentence>\n';")" \
1004
- '1=null 2=null 3=null 4=null 5=null'
1005
- check "a conforming artifact satisfies the structural criteria" \
1006
- "$(t01 '')" '1=null 2=null 3=true 4=null 5=null'
1007
- check "an absent artifact defers every criterion to the judge" \
1008
- "$(t01 "md = '';")" '1=null 2=null 3=null 4=null 5=null'
1009
- check "an invented volume figure fails criterion 3" \
1010
- "$(t01 "md += '\nExpect ~400M rows/yr.';")" '1=null 2=null 3=false 4=null 5=null'
1011
- check "a Reverses field saying only cheaply fails criterion 5" \
1012
- "$(t01 "md = md.replace(/\\*\\*Reverses\\*\\*:[^\\n]*/, '**Reverses**: cheaply');")" \
1013
- '1=null 2=null 3=true 4=null 5=null'
1014
- check "an unnamed ADR fails criterion 4" \
1015
- "$(t01 "md = md.replace(/ADR 0004[^\\n]*/, 'The architecture decision applies.');")" \
1016
- '1=null 2=null 3=true 4=false 5=null'
1017
-
1018
- # --- task 01 scored from the FENCED BLOCK, the third target tried ------------------------------
1019
- # 1. the prose relay -- semantic, so judged, so 2/4-3/4 against a >=99% bar
1020
- # 2. decisions.md -- structured but EMPTY in the research pass; parsing it manufactured failures
1021
- # 3. the fence -- the planner's own block, relayed verbatim, present in every run
1022
- blk() { j "
1023
- const S = await import('$ROOT/tests/evals/lib/score-task01.mjs');
1024
- const body = 'D1: Audit-trail storage architecture\\n Decides: where 7 years of rows live\\n Option A — Partitioned Postgres — RECOMMENDED\\n Pros: no new store\\n Cons: partition maintenance for a two-person team\\n Reverses: detach partitions; the down migration ships in the same PR\\n';
1025
- let out = 'prose\\n\\n\\u0060\\u0060\\u0060decisions-needed\\n' + body + '\\u0060\\u0060\\u0060\\n ADR 0004 requires a migration path.';
1026
- $1
1027
- const v = S.blockVerdicts(out);
1028
- process.stdout.write(Object.keys(v).filter(k=>/^\d+$/.test(k)).sort().map(k=>k+'='+v[k]).join(' '));
1029
- "; }
1030
- check "a conforming fence scores the structural criteria" \
1031
- "$(blk '')" '1=null 2=null 3=true 4=null 5=null'
1032
- # A run predating the relay change, or one that omits the fence, must DEFER -- not be failed for a
1033
- # format it was never given. Same fail-safe the scaffold case needed.
1034
- check "no fence defers every criterion to the judge" \
1035
- "$(blk "out = 'just prose';")" '1=null 2=null 3=null 4=null 5=null'
1036
- check "a missing Reverses field fails criterion 5" \
1037
- "$(blk "out = out.replace(/ Reverses:[^\\n]*\\n/, '');")" \
1038
- '1=null 2=null 3=true 4=null 5=null'
1039
- check "an invented magnitude fails criterion 3" \
1040
- "$(blk "out += ' Expect ~400M rows/yr.';")" '1=null 2=null 3=false 4=null 5=null'
1041
- check "an unnamed ADR fails criterion 4" \
1042
- "$(blk "out = out.replace(/ADR 0004[^\\n]*/, 'the architecture decision');")" \
1043
- '1=null 2=null 3=true 4=false 5=null'
1044
-
1045
- # --- a run already over budget must say so, not keep drawing -----------------------------------
1046
- # Failures only accumulate, so once the count exceeds the budget no sequence of remaining draws
1047
- # can recover it. Without this, task 01 sat at 4 failures against a budget of 2 with 80 draws
1048
- # left -- about seven quota windows -- to confirm an outcome the arithmetic had already fixed.
1049
- over() { j "
1050
- const tasks = { '01': [] };
1051
- for (let i = 0; i < $1; i++) tasks['01'].push({ index: i, dimensions: { S3: i >= $2 } });
1052
- const c = M.certify(M.buildResult({ source: {ref:'x',sha:'d'}, tasks, runs: $1 }));
1053
- process.stdout.write([c.cannotCertify, c.failures, c.maxFailures].join('|'));
1054
- "; }
1055
- check "6 failures against a budget of 5 is unrecoverable" "$(over 10 6)" "true|6|5"
1056
- check "5 failures against a budget of 5 is still open" "$(over 10 5)" "false|5|5"
1057
- check "0 failures is still open" "$(over 10 0)" "false|0|5"
1058
-
1059
- # --- the agent timeout must clear the observed spread ------------------------------------------
1060
- # A timeout is the most expensive possible outcome: the run is fully paid for and nothing is
1061
- # recorded. 900s cost a draw when observed runs already reached 13 minutes.
1062
- check "the agent timeout leaves headroom over the observed 13-minute maximum" \
1063
- "$(j "
1064
- const fs = await import('node:fs');
1065
- const src = fs.readFileSync('$ROOT/tests/evals/lib/install.mjs','utf8');
1066
- const m = src.match(/timeoutMs = ([0-9_]+)/);
1067
- process.stdout.write(String(Number(m[1].replace(/_/g,'')) >= 1500000));
1068
- ")" "true"
1069
-
1070
- # --- SCOPES.task01 is REMOVED, not relabeled; SCOPES.full re-derived from CERTIFY_N -------
1071
- # At 1 gating dimension (S3 alone) the best available budget clears a
1072
- # genuinely-soft corpus 73.58% of the time -- worse than not gating -- so `task01` is gone
1073
- # entirely, and there is exactly one scope left.
1074
- check "SCOPES.task01 no longer exists (removed, not merely relabeled)" \
1075
- "$(j "process.stdout.write(String('task01' in M.SCOPES))")" "false"
1076
- check "CERTIFY_N is a distinct constant from BANDS.n (raising it must not touch routine trim draws)" \
1077
- "$(j "process.stdout.write(M.CERTIFY_N + '|' + M.BANDS.n)")" "120|20"
1078
- # The derived budget, pinned -- not a preference. Re-derived (not scaled) at 2 gating dimensions
1079
- # (after task 02's S1 was demoted to report-only): the same method lands on CERTIFY_N=120,
1080
- # more per dimension than the prior 3-dimension figure (80), since the pooled false-accept target
1081
- # is reached at the same total draw count (240) regardless of how many dimensions share it.
1082
- check "SCOPES.full is derived from CERTIFY_N x 2 gating dimensions: 240 draws, budget 5, ~96.5%/~1.8% power" \
1083
- "$(j "const s = M.SCOPES.full; process.stdout.write([s.draws, s.maxFailures, s.powerGood.toFixed(4), s.powerSoft.toFixed(4), s.covers].join('|'))")" \
1084
- "240|5|0.9651|0.0181|2 of 13 task-dimensions"
1085
- check "power is reported on certify()'s own return value" \
1086
- "$(j "const c = M.certify({tasks:{}}); process.stdout.write(c.powerGood + '/' + c.powerSoft)")" "0.9651/0.0181"
1087
-
1088
- # --- 2.4b acceptance point 6: --scope is fully removed, not silently falling back to full --------
1089
- scopeout=$(node "$R" --scope task01 --dry-run --source HEAD --tasks 01 --runs 1 2>&1; echo "EXIT:$?")
1090
- case "$scopeout" in
1091
- *"unknown argument: --scope"*"EXIT:1") ok "--scope is not a recognized flag (removed outright)" ;;
1092
- *) bad "--scope is not a recognized flag (removed outright) (got: ${scopeout:0:160})" ;;
1093
- esac
1094
-
1095
- # --- 2.4b acceptance point 5: the exact --runs guidance, appended to certify()'s own message ------
1096
- CERT_SHA="certtest$(date +%s)"
1097
- j "
1098
- const fs = await import('node:fs');
1099
- const p = M.shardPath('$CERT_SHA', '01', 0);
1100
- fs.mkdirSync(p.replace(/\/[^/]+\$/, ''), { recursive: true });
1101
- fs.writeFileSync(p, JSON.stringify({ sha: '$CERT_SHA', taskId: '01', schema: M.SCHEMA_VERSION, run: { index: 0, dimensions: { S3: false, S1: false }, criteria: null, error: null } }));
1102
- " >/dev/null
1103
- certout=$(node "$R" --certify "$CERT_SHA" 2>&1)
1104
- case "$certout" in
1105
- *"enough draws: false (need 240, have 1) — draw with --runs 120"*)
1106
- ok "certify()'s 'enough draws: false' message names --runs \$CERTIFY_N exactly, derived from the same constant" ;;
1107
- *)
1108
- bad "certify()'s 'enough draws: false' message names --runs \$CERTIFY_N exactly (got: ${certout:0:300})" ;;
1109
- esac
1110
-
1111
- # --- certified-line parenthetical, UNDER FLOOR block, harnessFaults -- each left 215/0 ----
1112
- case "$certout" in
1113
- *"certified: false (1 gating dimension(s) measured, false-accept 1.81% if all are soft, 27.00% if one alone)"*) ok "certify()'s 'certified:' line states the gating-dimension count and BOTH false-accept rates" ;;
1114
- *) bad "certify()'s 'certified:' line states the gating-dimension count/both false-accept rates (got: ${certout:0:300})" ;;
1115
- esac
1116
- # The single-soft figure is the one a reader actually needs and the one that was missing: a bare
1117
- # 1.81% describes every gating dimension going soft together, while one soft against a healthy
1118
- # sibling certifies 27.00% of the time. Asserted separately so deleting it cannot pass as a
1119
- # reformat of the line above.
1120
- case "$certout" in
1121
- *"27.00% if one alone"*) ok "certify() states the SINGLE-soft-dimension false-accept rate, not only the joint one" ;;
1122
- *) bad "certify() states the single-soft-dimension false-accept rate (got: ${certout:0:400})" ;;
1123
- esac
1124
- # The gate's POWER should be printed on every run, not only its false-accept rate. The
1125
- # figure is `SCOPES.full.powerGood`, the converse error to the 1.81% on the `certified:` line --
1126
- # so this asserts both that it prints and that it is not a second copy of the false-accept rate.
1127
- case "$certout" in
1128
- *"gate power: 96.51%"*) ok "certify() prints the gate's power (§6), distinct from its false-accept rate" ;;
1129
- *) bad "certify() prints the gate's power (§6) (got: ${certout:0:400})" ;;
1130
- esac
1131
-
1132
- case "$certout" in
1133
- *"UNDER FLOOR: 01/S3 (1/120), 02/S5 (0/120)"*) ok "certify()'s UNDER FLOOR block names each under-floor gating dimension" ;;
1134
- *) bad "certify()'s UNDER FLOOR block names each under-floor gating dimension (got: ${certout:0:400})" ;;
1135
- esac
1136
- case "$certout" in
1137
- *"1 failure(s) across 1 draw(s)"*" 01 S3: 0/1"*"report-only 01 S1: 0/1"*) ok "certify()'s summary pools ONLY the gating row, and prints the report-only row after it" ;;
1138
- *) bad "certify()'s summary pools ONLY the gating row, and prints the report-only row after it (got: ${certout:0:400})" ;;
1139
- esac
1140
- # {error:'timeout'} (the shape this check used to write) is not a shape a shard can ever
1141
- # carry -- runOnce()'s timeout/quota/judge-fault path always sets harnessFault:true, which the
1142
- # drawing loop's write guard never persists. The one error a shard CAN carry unflagged is :680's.
1143
- j "const fs = await import('node:fs'); fs.writeFileSync(M.shardPath('$CERT_SHA','01',1), JSON.stringify({sha:'$CERT_SHA',taskId:'01',schema:M.SCHEMA_VERSION,run:{index:1,dimensions:{},criteria:null,error:'no prompt found in the task spec'}}));" >/dev/null
1144
- case "$(node "$R" --certify "$CERT_SHA" 2>&1)" in
1145
- *"harness faults: 1"*) ok "certify()'s harnessFaults count reflects a persistable error-bearing run, not a hardcoded 0" ;;
1146
- *) bad "certify()'s harnessFaults count reflects a persistable error-bearing run" ;;
1147
- esac
1148
- rm -rf "$ROOT/tests/evals/results/$CERT_SHA"
1149
-
1150
- # --- a malformed judge reply must not discard the agent run that preceded it -------------------
1151
- # Observed once in three runs: the judge returned unparseable JSON and a ~12-minute agent run was
1152
- # thrown away. At ~90% of a usage cap per batch that is not affordable. Only a PARSE failure is
1153
- # retried -- a quota outage is not, since the next call fails identically and burns budget proving
1154
- # it. Asserted on the REAL classifier, exported as `isRetryableJudgeError` -- a hand-copied regex
1155
- # literal here could not fail (a regression guard for the shared classifier).
1156
- mal() { node --input-type=module -e "
1157
- const S = await import('$ROOT/tests/evals/lib/score.mjs');
1158
- process.stdout.write(String(S.isRetryableJudgeError('$1')));
1159
- " 2>&1; }
1160
- check "an unparseable reply is retryable" "$(mal 'judge reply is not valid JSON: x')" "true"
1161
- check "a missing criteria array is retryable" "$(mal 'judge reply has no criteria array')" "true"
1162
- check "a quota outage is NOT retryable" "$(mal 'quota exhausted')" "false"
1163
- check "a generic exit is NOT retryable" "$(mal 'judge exited 1')" "false"
1164
- # asserted against the REAL `judge()`, spawning a stubbed `claude` end to end -- the only
1165
- # check here that would catch a break in `judgeOnce()`'s own retry wiring, not just in the
1166
- # classifier `mal()` now shares with it. Stub replies duplicate-n on the FIRST call,
1167
- # well-formed on the SECOND; `judge()` must retry and return the second's verdict.
1168
- dupbin=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1169
- cat > "$dupbin/claude" <<STUB
1170
- #!/usr/bin/env bash
1171
- if [ -e "$dupbin/.hit" ]; then
1172
- echo '{"criteria":[{"n":1,"verdict":"pass","evidence":"e"}]}'
1173
- else
1174
- touch "$dupbin/.hit"
1175
- echo '{"criteria":[{"n":1,"verdict":"pass","evidence":"e"},{"n":1,"verdict":"pass","evidence":"e"}]}'
1176
- fi
1177
- STUB
1178
- chmod +x "$dupbin/claude"
1179
- dupout=$(PATH="$dupbin:$PATH" node --input-type=module -e "
1180
- const S = await import('$ROOT/tests/evals/lib/score.mjs');
1181
- const v = S.judge('spec text', 'evidence text');
1182
- process.stdout.write(v.ok + '|' + (v.retried ?? false));
1183
- " 2>&1)
1184
- check "a duplicate-n reply is retried against the real judge(), not treated as an unrecoverable harness fault (F-130)" \
1185
- "$dupout" "true|true"
1186
- rm -rf "$dupbin"
1187
-
1188
- # --- rescore reads the CURRENT scorer, not the pinned one --------------------------------------
1189
- # Two sources, and conflating them makes rescore silently do nothing. The DEFINITION SET is pinned
1190
- # by the sha (that is what was measured); the TASK SPEC is the SCORER, and the whole reason to
1191
- # rescore is that the scorer changed. Passing the pinned worktree for both re-judges against the
1192
- # criterion you just replaced and reports "unchanged" for every shard -- which is what the first
1193
- # attempt did, convincingly and wrongly.
1194
- check "rescoreShards defaults its spec source to the repo, not a pinned tree" \
1195
- "$(j "process.stdout.write(String(M.rescoreShards.length))")" "1"
1196
-
1197
- # --- applyExecutedOverlays() -- the shared function closing gap 3 --------------------------
1198
- # runOnce() and rescoreShards() now call ONE function for every executed-criterion overlay. Pinned
1199
- # here with data shaped like the real, already-on-disk shard the gap was found against
1200
- # (results/4ff4da62.../01-000.json: decisionsMd null, a fenced decisions-needed block in the
1201
- # transcript, no `changed` field -- that shard predates the schema addition).
1202
- aeo() { j "
1203
- const BT = String.fromCharCode(96).repeat(3), NL = String.fromCharCode(10);
1204
- const crit = $1;
1205
- const dims = {};
1206
- await M.applyExecutedOverlays('$2', crit, dims, $3, $4);
1207
- process.stdout.write(JSON.stringify(crit.map((c) => [c.n, c.verdict, c.executed ?? null])) + '|' + JSON.stringify(dims));
1208
- "; }
1209
- check "criterion 3 reproduces EXECUTED evidence from the transcript's fence alone (decisionsMd null, matching the real shard)" \
1210
- "$(aeo "[{n:3,verdict:'fail',evidence:'judge'}]" 01 "{3:['S7']}" "{decisionsMd:null,transcript:[BT+'decisions-needed','D1: x',' Option A - y',' Pros: p',' Cons: q',BT,'no digits here'].join(NL)}")" \
1211
- '[[3,"pass",true]]|{"S7":true}'
1212
- # 'changed' absent used to leave the JUDGE's own verdict standing
1213
- # for a GATING dimension -- the exact door a judge-authored gating verdict uses, reopened via a missing field instead of a
1214
- # fresh judge call. Now spliced + excluded, the disposition S5 already uses for its own
1215
- # non-attributable case. Reverting the `else` branch in applyExecutedOverlays() (the fix below)
1216
- # turns this red: criterion 6 would stay in `criteria` as the judge's raw 'fail' and S3 would read
1217
- # `false` instead of "excluded" -- a judge-authored gating verdict, exactly what the fix closes.
1218
- check "criterion 6 is EXCLUDED, not judge-authored, when 'changed' is absent -- an older shard" \
1219
- "$(aeo "[{n:6,verdict:'fail',evidence:'judge'}]" 01 "{6:['S3']}" "{transcript:''}")" \
1220
- '[]|{"S3":"excluded"}'
1221
- check "criterion 6 reproduces EXECUTED evidence when 'changed' is present, correctly REJECTING an out-of-allowlist path" \
1222
- "$(aeo "[{n:6,verdict:'pass',evidence:'judge'}]" 01 "{6:['S3']}" "{transcript:'',tree:[{status:'M',path:'src/x.mjs'}],slug:'s'}")" \
1223
- '[[6,"fail",true]]|{"S3":false}'
1224
- check "criterion 6 reproduces EXECUTED evidence and PASSES for an in-allowlist path (Nit, pass 1 review: the accept direction was under-asserted)" \
1225
- "$(aeo "[{n:6,verdict:'fail',evidence:'judge'}]" 01 "{6:['S3']}" "{transcript:'',tree:[{status:'A',path:'.somi/plans/s/context.md'}],slug:'s'}")" \
1226
- '[[6,"pass",true]]|{"S3":true}'
1227
- # Major (pass 2 review, "Also fix" item): a judge reply OMITTING criterion 6 entirely used to make
1228
- # S3 vanish from `dimensions` rather than fail closed -- toDimensions() had nothing tagged S3 to
1229
- # read. Now appended, exactly like criterion 3's sibling overlay already does.
1230
- check "criterion 6 is APPENDED, not silently absent, when the judge's reply omits it and 'changed' is present" \
1231
- "$(aeo "[]" 01 "{6:['S3']}" "{transcript:'',tree:[{status:'M',path:'src/x.mjs'}],slug:'s'}")" \
1232
- '[[6,"fail",true]]|{"S3":false}'
1233
- check "task 02's S5 is driven by the STORED expiryGuard, never recomputed -- excluded key always present, S1 reapplied alongside it (F-55/2.3)" \
1234
- "$(aeo "[{n:1,verdict:'pass',evidence:'judge'},{n:3,verdict:'pass',evidence:'judge'}]" 02 "{1:['S5'],3:['S1']}" "{expiryGuard:{verdict:'non-attributable',step:'mutant',observed:'type-error'},testInvocation:'fail'}")" \
1235
- '[[3,"fail",true]]|{"S1":false,"S5":"excluded"}'
1236
- # the overlay's splice removes only the FIRST `n === 1` entry
1237
- # (`findIndex` + `splice(i, 1)`), so a judge reply carrying criterion 1 TWICE leaves a second entry
1238
- # standing with its own verdict. Outcome-sampling alone (`criteria.some(...)`) still finds that
1239
- # survivor and stays silent -- S5 published the judge's own `true` on a gating dimension, the same
1240
- # door. Reverting the `expiryGuard.verdict` half of the fix above turns this red.
1241
- check "S5 is EXCLUDED, not judge-authored, when the judge reply carries criterion 1 TWICE and expiryGuard is non-attributable (F-86)" \
1242
- "$(aeo "[{n:1,verdict:'pass',evidence:'judge'},{n:1,verdict:'pass',evidence:'judge'}]" 02 "{1:['S5']}" "{expiryGuard:{verdict:'non-attributable',step:'mutant',observed:'type-error'}}")" \
1243
- '[[1,"pass",null]]|{"S5":"excluded"}'
1244
- check "S5 is EXCLUDED, not judge-authored, when expiryGuard is absent entirely -- a shard predating the field (F-76)" \
1245
- "$(aeo "[{n:1,verdict:'pass',evidence:'judge'}]" 02 "{1:['S5']}" "{expiryGuard:null}")" \
1246
- '[[1,"pass",null]]|{"S5":"excluded"}'
1247
- # Major (pass 2 review, "Also fix" item): a judge reply OMITTING criterion 1 while `expiryGuard`
1248
- # genuinely PASSED used to make S5 vanish from `dimensions` entirely (the overlay can only record
1249
- # `overlaySkipped` when the criterion isn't there to mutate -- it cannot fabricate a pass/fail
1250
- # criterion the judge never sent). Now excluded, matching the non-attributable disposition, rather
1251
- # than invisible to certify()'s per-dimension floor.
1252
- check "S5 is EXCLUDED, not silently absent, when the judge's reply omits criterion 1 -- even on a genuine pass" \
1253
- "$(aeo "[{n:3,verdict:'pass',evidence:'judge'}]" 02 "{1:['S5'],3:['S1']}" "{expiryGuard:{verdict:'pass',step:'mutant',observed:'assertion'},testInvocation:null}")" \
1254
- '[[3,"pass",null]]|{"S1":true,"S5":"excluded"}'
1255
- check "task 03 criterion 3 reproduces EXECUTED evidence from the stored transcript alone" \
1256
- "$(aeo "[{n:3,verdict:'fail',evidence:'judge'}]" 03 "{3:['S1']}" "{transcript:'Filed against 2024-03-31.',task03Refs:{correct:(a,b,d)=>({net:1}),patched:(a,b,d)=>({net:2})}}")" \
1257
- '[[3,"pass",true]]|{"S1":true}'
1258
-
1259
- # --- rescoreShards() actually reapplies the overlays, end to end ----------------------------
1260
- # judge() shells out to a real `claude` binary; stubbed here with a script returning a FIXED, WRONG
1261
- # verdict for every criterion, so only a correctly-reapplied overlay can flip the result -- the
1262
- # "mutate one call site, confirm red" proof for the call site runOnce() cannot pin (no test in this
1263
- # hermetic suite reaches runOnce()'s own execution). Reverting rescoreShards to its pre-2.3 body
1264
- # (plain toDimensions(verdict.criteria, tags), no overlay call) was verified by hand to turn this
1265
- # red: false|false|false|true|false|false|false instead of the line below (7 fields since two more were added).
1266
- rsbin=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1267
- cat > "$rsbin/claude" <<'STUB'
1268
- #!/usr/bin/env bash
1269
- echo '{"criteria":[{"n":1,"verdict":"fail","evidence":"judge"},{"n":3,"verdict":"fail","evidence":"judge"},{"n":6,"verdict":"fail","evidence":"judge"}]}'
1270
- STUB
1271
- chmod +x "$rsbin/claude"
1272
- rssha="rescoretest0000000000000000000000000000"
1273
- rsdir="$ROOT/tests/evals/results/$rssha"
1274
- mkdir -p "$rsdir"
1275
- cat > "$rsdir/01-000.json" <<'EOF'
1276
- {"sha":"x","taskId":"01","run":{"index":0,"dimensions":{},"criteria":[],"error":null,"decisionsMd":null,"changed":[{"status":"A","path":".somi/plans/x/context.md"}],"slug":"x","transcript":"```decisions-needed\nD1: x\n Option A - y\n Pros: p\n Cons: q\n```\nno digits here"}}
1277
- EOF
1278
- cat > "$rsdir/02-000.json" <<'EOF'
1279
- {"sha":"x","taskId":"02","run":{"index":0,"dimensions":{},"criteria":[],"error":null,"decisionsMd":null,"transcript":"t","expiryGuard":{"verdict":"non-attributable","step":"mutant","observed":"type-error"},"testInvocation":"fail"}}
1280
- EOF
1281
- # The destructive-write proof: a shard shaped EXACTLY like the real, on-disk
1282
- # results/4ff4da62.../01-003.json -- criterion 6 already EXECUTED, S3 already true, no `changed`/
1283
- # `slug` field (the historical gap). The in-memory-only version of this proof is not enough
1284
- #: the defect was a `writeFileSync` that overwrote real evidence on disk with no undo, so
1285
- # this reads the FILE back after rescoring, not just rescoreShards()'s return value.
1286
- cat > "$rsdir/01-001.json" <<'EOF'
1287
- {"sha":"x","taskId":"01","run":{"index":1,"dimensions":{"S3":true},"criteria":[{"n":3,"verdict":"pass","evidence":"EXECUTED against decisions.md: satisfied (not judged)","executed":true},{"n":6,"verdict":"pass","evidence":"EXECUTED: every changed path is inside the allowlist (slug-scoped: x) (not judged)","executed":true}],"error":null,"decisionsMd":null,"transcript":"no digits here"}}
1288
- EOF
1289
- rsout=$(PATH="$rsbin:$PATH" node --input-type=module -e "
1290
- const M = await import('$ROOT/$R');
1291
- await M.rescoreShards('$rssha', '$ROOT');
1292
- const fs = await import('node:fs');
1293
- const r1 = JSON.parse(fs.readFileSync('$rsdir/01-000.json', 'utf8'));
1294
- const r2 = JSON.parse(fs.readFileSync('$rsdir/02-000.json', 'utf8'));
1295
- const r3 = JSON.parse(fs.readFileSync('$rsdir/01-001.json', 'utf8'));
1296
- const c3 = r1.run.criteria.find((c) => c.n === 3), c6 = r1.run.criteria.find((c) => c.n === 6);
1297
- const c3b = r2.run.criteria.find((c) => c.n === 3);
1298
- const c6legacy = r3.run.criteria.find((c) => c.n === 6);
1299
- process.stdout.write([c3.evidence.startsWith('EXECUTED'), c6.evidence.startsWith('EXECUTED'),
1300
- r2.run.dimensions.S5, 'S5' in r2.run.dimensions, c3b.evidence.startsWith('EXECUTED'),
1301
- c6legacy === undefined, r3.run.dimensions.S3].join('|'));
1302
- " 2>&1)
1303
- check "rescoreShards reapplies task 01's criteria 3+6 and task 02's S5/S1 overlays; a legacy shard's stale EXECUTED criterion 6 is excluded on disk, never overwritten with judge prose (F-71)" \
1304
- "$rsout" "true|true|excluded|true|true|true|excluded"
1305
- rm -rf "$rsbin" "$rsdir"
1306
-
1307
- # --- 2.4c acceptance: "no judged criterion can gate", re-checked at mergeShards()'s output for
1308
- # the --rescore PATH specifically (previously pinned only at the individual-shard/applyExecutedOverlays
1309
- # level, never end to end through mergeShards()+certify()) -------------------------------------
1310
- rs2bin=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1311
- cat > "$rs2bin/claude" <<'STUB'
1312
- #!/usr/bin/env bash
1313
- echo '{"criteria":[{"n":1,"verdict":"pass","evidence":"e"},{"n":2,"verdict":"pass","evidence":"e"},{"n":3,"verdict":"pass","evidence":"e"},{"n":4,"verdict":"pass","evidence":"e"}]}'
1314
- STUB
1315
- chmod +x "$rs2bin/claude"
1316
- rs2sha="rescoretest2$(date +%s)"
1317
- rs2dir="$ROOT/tests/evals/results/$rs2sha"
1318
- mkdir -p "$rs2dir"
1319
- # The stub judge says criterion 1 (S5, GATING) PASSES. The stored expiryGuard -- the mechanical
1320
- # fact -- says it FAILED. If the overlay were bypassed on this path, S5 would read pass/1 below.
1321
- j "
1322
- const fs = await import('node:fs');
1323
- fs.writeFileSync(M.shardPath('$rs2sha','02',0), JSON.stringify({ sha: '$rs2sha', taskId: '02', schema: M.SCHEMA_VERSION, run: { index: 0, dimensions: {}, criteria: [], error: null, transcript: 't', expiryGuard: { verdict: 'fail', step: 'mutant', reason: 'r', observed: 'assertion' }, testInvocation: 'pass' } }));
1324
- " >/dev/null
1325
- PATH="$rs2bin:$PATH" node --input-type=module -e "const M = await import('$ROOT/$R'); await M.rescoreShards('$rs2sha', '$ROOT');" >/dev/null 2>&1
1326
- rs2merge=$(j "
1327
- const c = M.certify(M.mergeShards('$rs2sha'));
1328
- const s5 = c.dimensions.find((d) => d.task === '02' && d.dim === 'S5');
1329
- process.stdout.write(s5 ? s5.passes + '/' + s5.n : 'MISSING');
1330
- ")
1331
- check "mergeShards()+certify() after --rescore reflects the MECHANICAL expiryGuard verdict (fail) on gating dimension S5, never the stub judge's own 'pass'" \
1332
- "$rs2merge" "0/1"
1333
- rm -rf "$rs2bin" "$rs2dir"
1334
-
1335
- # --- 2.4c acceptance: --report is a separate, opt-in pass; its shard cannot change certify() -----
1336
- rptbin=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1337
- cat > "$rptbin/claude" <<'STUB'
1338
- #!/usr/bin/env bash
1339
- echo '{"criteria":[{"n":1,"verdict":"pass","evidence":"e"},{"n":2,"verdict":"pass","evidence":"e"},{"n":3,"verdict":"pass","evidence":"e"},{"n":4,"verdict":"pass","evidence":"e"}]}'
1340
- STUB
1341
- chmod +x "$rptbin/claude"
1342
- rptsha="reporttest$(date +%s)"
1343
- rptdir="$ROOT/tests/evals/results/$rptsha"
1344
- mkdir -p "$rptdir"
1345
- # The STORED gating dimensions are all false; the mechanical facts (expiryGuard/testInvocation)
1346
- # and the stub judge would, if freshly recomputed, produce all true -- deliberately mismatched
1347
- # from what is on disk, so a report-pass leak into the gating namespace is NOT masked by the two
1348
- # computations coincidentally agreeing (mutation-verified: writing report output into the gating
1349
- # namespace directly turns this check red, where a same-valued fixture would not have).
1350
- j "
1351
- const fs = await import('node:fs');
1352
- fs.writeFileSync(M.shardPath('$rptsha','02',0), JSON.stringify({ sha: '$rptsha', taskId: '02', schema: M.SCHEMA_VERSION, run: { index: 0, dimensions: { S5: false, S3: false, S1: false, S6: false }, criteria: [], error: null, transcript: 't', expiryGuard: { verdict: 'pass', step: 'mutant', observed: 'assertion' }, testInvocation: 'pass' } }));
1353
- " >/dev/null
1354
- before=$(j "process.stdout.write(JSON.stringify(M.certify(M.mergeShards('$rptsha'))))")
1355
- rptout=$(PATH="$rptbin:$PATH" node "$R" --report "$rptsha" 2>&1)
1356
- after=$(j "process.stdout.write(JSON.stringify(M.certify(M.mergeShards('$rptsha'))))")
1357
- check "a --report shard present under a SHA does not change that SHA's certify() output" "$after" "$before"
1358
- case "$rptout" in
1359
- *"report-only:"*"report-only 02 S3: 1/1"*) ok "--report prints a report-only: summary line" ;;
1360
- *) bad "--report prints a report-only: summary line (got: ${rptout:0:300})" ;;
1361
- esac
1362
- check "a --report shard lands under results/<sha>/report/, structurally separate from the gating namespace mergeShards()/completedIndices() glob" \
1363
- "$(j "process.stdout.write(String((await import('node:fs')).existsSync('$rptdir/report/02-000.json')))")" "true"
1364
- # the written report record is filtered to the report-only half before it
1365
- # touches disk -- applyExecutedOverlays() writes every TAGGED dimension, gating included, so an
1366
- # unfiltered write would carry a GATING dimension's value (S5, here genuinely true) under this
1367
- # pass's `schema: 2` stamp, the same stamp a real gating shard carries but a different, incompatible
1368
- # record shape.
1369
- check "the written report shard excludes the gating dimension (S5), keeping only report-only ones under the gating schema stamp" \
1370
- "$(j "process.stdout.write(String('S5' in JSON.parse((await import('node:fs')).readFileSync('$rptdir/report/02-000.json','utf8')).run.dimensions))")" \
1371
- "false"
1372
- # `schema: 2` alone still means two incompatible shapes -- readShard() would accept a
1373
- # report record as current if anything ever pointed it at `report/`. `kind: 'report'` fixes that.
1374
- check "the written report shard is discriminated from a gating shard by kind: 'report'" \
1375
- "$(j "process.stdout.write(String(JSON.parse((await import('node:fs')).readFileSync('$rptdir/report/02-000.json','utf8')).kind))")" \
1376
- "report"
1377
-
1378
- # --- --report honors --runs as a real cap on which shards it judges, not a
1379
- # value that reaches the result shape while every shard on disk gets judged regardless (the settled answer for the report pass's own N). Two more gating shards are added
1380
- # for indices 1 and 2; `--runs 1` must judge only index 0 (already report-shard-backed above) and
1381
- # leave 1/2 untouched -- no report/02-001.json, no report/02-002.json.
1382
- j "
1383
- const fs = await import('node:fs');
1384
- fs.writeFileSync(M.shardPath('$rptsha','02',1), JSON.stringify({ sha: '$rptsha', taskId: '02', schema: M.SCHEMA_VERSION, run: { index: 1, dimensions: {}, criteria: [], error: null, transcript: 't1' } }));
1385
- fs.writeFileSync(M.shardPath('$rptsha','02',2), JSON.stringify({ sha: '$rptsha', taskId: '02', schema: M.SCHEMA_VERSION, run: { index: 2, dimensions: {}, criteria: [], error: null, transcript: 't2' } }));
1386
- " >/dev/null
1387
- PATH="$rptbin:$PATH" node "$R" --report "$rptsha" --runs 1 >/dev/null 2>&1
1388
- check "--report honors --runs as a cap on which shards it judges (F-132)" \
1389
- "$(ls "$rptdir/report" | wc -l | tr -d ' ')" "1"
1390
- rm -rf "$rptbin" "$rptdir"
1391
-
1392
- # --- --report threads task03Refs exactly like --rescore does, so both print
1393
- # the SAME EXECUTED verdict for task 03's one report-only dimension (S1) rather than opposite ones
1394
- #. The stub judge says criterion 3 PASSES; the cited date is a 30-day month, so the
1395
- # EXECUTED overlay must override it to FAIL on both paths -- a stub-agreeing fixture would not
1396
- # discriminate a leaked docstring claim from a real fix.
1397
- t3bin=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
1398
- cat > "$t3bin/claude" <<'STUB'
1399
- #!/usr/bin/env bash
1400
- echo '{"criteria":[{"n":1,"verdict":"pass","evidence":"e"},{"n":2,"verdict":"pass","evidence":"e"},{"n":3,"verdict":"pass","evidence":"e"},{"n":4,"verdict":"pass","evidence":"e"},{"n":5,"verdict":"pass","evidence":"e"}]}'
1401
- STUB
1402
- chmod +x "$t3bin/claude"
1403
- t3sha_a="task03refsA$(date +%s)"; t3sha_b="task03refsB$(date +%s)"
1404
- for sha in "$t3sha_a" "$t3sha_b"; do
1405
- mkdir -p "$ROOT/tests/evals/results/$sha"
1406
- j "
1407
- const fs = await import('node:fs');
1408
- fs.writeFileSync(M.shardPath('$sha','03',0), JSON.stringify({ sha: '$sha', taskId: '03', schema: M.SCHEMA_VERSION, run: { index: 0, dimensions: {}, criteria: [], error: null, transcript: 'Filed against 2026-04-16.' } }));
1409
- " >/dev/null
1410
- done
1411
- PATH="$t3bin:$PATH" node --input-type=module -e "const M = await import('$ROOT/$R'); await M.rescoreShards('$t3sha_a', '$ROOT');" >/dev/null 2>&1
1412
- PATH="$t3bin:$PATH" node "$R" --report "$t3sha_b" >/dev/null 2>&1
1413
- rescoreS1=$(j "process.stdout.write(String(JSON.parse((await import('node:fs')).readFileSync('$ROOT/tests/evals/results/$t3sha_a/03-000.json','utf8')).run.dimensions.S1))")
1414
- reportS1=$(j "process.stdout.write(String(JSON.parse((await import('node:fs')).readFileSync('$ROOT/tests/evals/results/$t3sha_b/report/03-000.json','utf8')).run.dimensions.S1))")
1415
- check "--report's task-03 S1 matches --rescore's EXECUTED verdict on the same shard content (F-129)" "$reportS1" "$rescoreS1"
1416
- check "and both are the mechanical 'fail' the citation produces, not the stub judge's raw 'pass'" "$reportS1" "false"
1417
- rm -rf "$t3bin" "$ROOT/tests/evals/results/$t3sha_a" "$ROOT/tests/evals/results/$t3sha_b"
1418
-
1419
- # --- Nit: reportShards() on an unknown SHA throws a clear error, matching
1420
- # mergeShards()'s existsSync guard, not the raw "Command failed: ls" a bare execFileSync produces.
1421
- check "reportShards() on an unknown SHA throws loudly, not with a raw 'ls' failure" \
1422
- "$(j "try { await M.reportShards('${SHARD_SHA}-nope'); process.stdout.write('REPORTED'); } catch (e) { process.stdout.write(e.message); }")" \
1423
- "no shards for ${SHARD_SHA}-nope at $ROOT/tests/evals/results/${SHARD_SHA}-nope"
1424
-
1425
- # --- quota outages are named, not lumped into a generic exit code ------------------------------
1426
- # Both the agent path and the judge path must recognise an exhausted limit. Without it a rescore
1427
- # burned four consecutive judge calls against a dead quota and reported four indistinguishable
1428
- # `judge exited 1` errors -- the caller could not tell "wait and retry" from "malformed reply".
1429
- check "a quota message in judge output is classified as quota" \
1430
- "$(j "
1431
- const S = await import('$ROOT/tests/evals/lib/score.mjs');
1432
- // parseVerdict is the non-error path; the quota branch lives in judge()'s spawn handling, so
1433
- // assert the DETECTOR shape the branch uses rather than spawning a real CLI.
1434
- const out = 'You\\'ve hit your session limit · resets 7:30pm';
1435
- process.stdout.write(String(/session limit|rate limit|usage limit|quota/i.test(out)));
1436
- ")" "true"
1437
- check "an ordinary judge failure is NOT classified as quota" \
1438
- "$(j "process.stdout.write(String(/session limit|rate limit|usage limit|quota/i.test('SyntaxError: unexpected token')))")" "false"
1439
-
1440
- # --- certification cannot pass on a partial run ------------------------------------------------
1441
- # It printed `certified: true` on 25 draws by reading 3 raw failures against a budget defined for
1442
- # 260 -- a rate projecting to ~31 failures, six times over. The vacuous-pass class again, this
1443
- # time in the check that decides whether every other check passed.
1444
- partial=$( j "
1445
- const tasks = { '01': [] };
1446
- for (let i = 0; i < 5; i++) tasks['01'].push({ index: i, dimensions: { S3: i < 2 } });
1447
- const c = M.certify(M.buildResult({ source: {ref:'x',sha:'d'}, tasks, runs: 5 }));
1448
- process.stdout.write([c.certified, c.onTrack, c.projectedFailures, c.sufficientDraws].join('|'));
1449
- ")
1450
- check "a partial run cannot certify, and reports its projection" "$partial" "false|false|144|false"
1451
-
1452
- # --- npm test must not invoke this runner ------------------------------------------------------
1453
- # Structural: a `node --check` glob merely NAMING the directory is
1454
- # explicitly permitted; what is forbidden is executing it.
1455
- # Scoped to what `npm test` reaches. package.json's eval:behavioral script references the runner
1456
- # ON PURPOSE -- that is the escape hatch. The full invariant (packaging + hermeticity) is owned by
1457
- # tests/scripts/evals-packaging.sh; this is the narrow version, kept here so this file's own guard
1458
- # fails if someone wires the runner into validate.sh.
1459
- if grep -nE '(node|bash)[^|]*tests/evals/run\.mjs' scripts/validate.sh >/dev/null 2>&1; then
1460
- bad "validate.sh does not execute the eval runner"
1461
- else
1462
- ok "validate.sh does not execute the eval runner"
1463
- fi
1464
-
1465
- # --- classification.mjs: the diff mechanism itself, unconditional -----------------------
1466
- # These need no file on disk -- they prove `diffClassification` can actually detect a changed
1467
- # verdict and a missing row, and that it reports no difference for two copies of the same table.
1468
- # That is necessary for the decisions.md comparison below to mean anything, but it is NOT the
1469
- # drift check itself: these three run against synthetic tables built from CLASSIFICATION alone and
1470
- # would stay green even if CLASSIFICATION had drifted from the maintained classification table completely.
1471
- check "classification.mjs: 15 criteria, no duplicate (task, criterion) pairs" \
1472
- "$(j "
1473
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1474
- const keys = C.CLASSIFICATION.map((r) => r.task + ':' + r.criterion);
1475
- process.stdout.write(String(C.CLASSIFICATION.length) + '|' + String(new Set(keys).size));
1476
- ")" "15|15"
1477
- check "classification.mjs: 2 of 13 task-dimensions gate (task 01's S3, task 02's S5; task 03 zero)" \
1478
- "$(j "
1479
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1480
- const dims = C.taskDimensions();
1481
- const gating = dims.filter((d) => d.verdict === 'gating').map((d) => d.task + '/' + d.dim).sort();
1482
- process.stdout.write(dims.length + '|' + gating.join(','));
1483
- ")" "13|01/S3,02/S5"
1484
- check "diffClassification: identical tables match" \
1485
- "$(j "
1486
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1487
- process.stdout.write(String(C.diffClassification(C.CLASSIFICATION, C.CLASSIFICATION)));
1488
- ")" "null"
1489
- check "diffClassification: a changed verdict is caught (mutation self-check)" \
1490
- "$(j "
1491
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1492
- const mutated = C.CLASSIFICATION.map((r) => (r.task === '02' && r.criterion === 3) ? { ...r, verdict: 'gating' } : r);
1493
- process.stdout.write(String(C.diffClassification(mutated, C.CLASSIFICATION)));
1494
- ")" "mismatch:02:3:got=S1/gating:want=S1/report-only"
1495
- check "diffClassification: a missing row is caught" \
1496
- "$(j "
1497
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1498
- const truncated = C.CLASSIFICATION.filter((r) => !(r.task === '01' && r.criterion === 6));
1499
- process.stdout.write(String(C.diffClassification(truncated, C.CLASSIFICATION)));
1500
- ")" "missing:01:6"
1501
-
1502
- # --- decisionsMdClassification's multi-table, append-order mechanism, unconditional (including the verdict-cell throw) ---------------------------
1503
- # The classification's corrections to date have every one of them been APPENDED as a new dated section, never
1504
- # an edit to prior text in place. These three cases pin that the parser actually behaves that way on
1505
- # a synthetic (no file involved) classification-shaped span, not merely against today's decisions.md content.
1506
- check "decisionsMdClassification: a later table's copy of a shared row wins over an earlier table's (was reversed)" \
1507
- "$(j "
1508
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1509
- const text = [
1510
- '## D11 -- synthetic',
1511
- '',
1512
- '| task | crit | dim | mechanism | bidirectional? | sound? | verdict |',
1513
- '|---|---|---|---|---|---|---|',
1514
- '| 01 | 6 | S3 | x | yes | yes | GATING |',
1515
- '| 03 | 1 | S4 | x | no | -- | report-only |',
1516
- '',
1517
- 'prose sitting between the two tables',
1518
- '',
1519
- '| task | criterion | dimension | executor | verdict |',
1520
- '|---|---|---|---|---|',
1521
- '| 01 | 6 | S3 | x | report-only |',
1522
- '',
1523
- '## Superseded entries',
1524
- ].join('\n');
1525
- const derived = C.decisionsMdClassification(text);
1526
- process.stdout.write(derived.find((r) => r.task === '01' && r.criterion === 6).verdict);
1527
- ")" "report-only"
1528
- check "decisionsMdClassification: a table appended after the settled resolution overrides it, not invisible (F-84)" \
1529
- "$(j "
1530
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1531
- const settled = [
1532
- '## D11 -- synthetic',
1533
- '',
1534
- '| task | crit | dim | mechanism | bidirectional? | sound? | verdict |',
1535
- '|---|---|---|---|---|---|---|',
1536
- '| 01 | 6 | S3 | x | yes | yes | GATING |',
1537
- '',
1538
- 'prose',
1539
- '',
1540
- '| task | criterion | dimension | executor | verdict |',
1541
- '|---|---|---|---|---|',
1542
- '| 01 | 6 | S3 | x | GATING |',
1543
- '',
1544
- ].join('\n');
1545
- const withLaterCorrection = settled + [
1546
- 'a still later, appended correction',
1547
- '',
1548
- '| task | criterion | dimension | executor | verdict |',
1549
- '|---|---|---|---|---|',
1550
- '| 01 | 6 | S3 | x | report-only |',
1551
- '',
1552
- '## Superseded entries',
1553
- ].join('\n');
1554
- const derived = C.decisionsMdClassification(withLaterCorrection);
1555
- process.stdout.write(derived.find((r) => r.task === '01' && r.criterion === 6).verdict);
1556
- ")" "report-only"
1557
- check "decisionsMdClassification: an off-convention verdict spelling throws, not silently dropped (F-88)" \
1558
- "$(j "
1559
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1560
- const text = ['## D11 -- synthetic', '', '| 01 | 6 | S3 | x | GATING |', '', 'p', '',
1561
- '| 01 | 6 | S3 | x | GATING |', '| 03 | 1 | S4 | x | \`report-only\` |', '', '## End'].join('\n');
1562
- try { C.decisionsMdClassification(text); process.stdout.write('NO THROW'); }
1563
- catch (e) { process.stdout.write(/unrecognized verdict cell/.test(e.message) ? 'threw' : 'wrong:' + e.message); }
1564
- ")" "threw"
1565
-
1566
- # --- classification.mjs vs the live task specs: criterionTags(), tracked everywhere -----------------------------------------------------------------------------------------
1567
- # tests/evals/tasks/*.md are TRACKED (unlike decisions.md), so this runs in CI and in a fresh
1568
- # checkout -- three of CLASSIFICATION's four columns (task, criterion, dim) covered everywhere,
1569
- # strictly more reach than the decisions.md-conditional check below can ever have. `verdict` stays
1570
- # decisions.md-only; nothing here asserts gating/report-only, only that the (task, criterion, dim)
1571
- # triples themselves haven't drifted from what the live spec actually tags.
1572
- check "classification.mjs's (task, criterion, dim) triples match the live task specs' criterionTags()" \
1573
- "$(j "
1574
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1575
- const S = await import('$ROOT/tests/evals/lib/score.mjs');
1576
- const fs = await import('node:fs');
1577
- const dir = '$ROOT/tests/evals/tasks';
1578
- const rows = [];
1579
- for (const f of fs.readdirSync(dir).filter((f) => /^\d\d-.*\.md\$/.test(f))) {
1580
- const task = f.slice(0, 2);
1581
- const tags = S.criterionTags(fs.readFileSync(dir + '/' + f, 'utf8'));
1582
- for (const [n, dims] of Object.entries(tags)) {
1583
- if (dims.length !== 1) { process.stdout.write('multi-tag:' + task + ':' + n); process.exit(0); }
1584
- rows.push(task + ':' + n + ':' + dims[0]);
1585
- }
1586
- }
1587
- const actual = rows.sort().join(',');
1588
- const expected = C.CLASSIFICATION.map((r) => r.task + ':' + r.criterion + ':' + r.dim).sort().join(',');
1589
- process.stdout.write(actual === expected ? 'match' : 'actual=' + actual + '|expected=' + expected);
1590
- ")" "match"
1591
-
1592
- # --- classification.mjs vs the maintained classification's actual content: the real drift check -------
1593
- # `.somi/` is gitignored repo-wide (scripts/check-links.mjs's own header: "`git ls-files` can never
1594
- # produce a path inside it") -- decisions.md exists only on a machine actively working this plan,
1595
- # never in a clean checkout or in CI. So this runs in one of two modes, never a third: present, or
1596
- # loudly skipped when the plan directory itself is absent. There is no silent-pass path, and an
1597
- # absent decisions.md next to a PRESENT plan directory is not the expected-skip case -- that is a
1598
- # real gap (a renamed/moved/deleted file on a machine this check is supposed to protect) and fails
1599
- # loudly rather than reading identically to the honest CI skip. When present, it is genuinely
1600
- # bidirectional -- verified by hand this pass: flipping one row's verdict in
1601
- # CLASSIFICATION with decisions.md untouched, and separately flipping the same row's verdict in
1602
- # decisions.md with CLASSIFICATION untouched, each independently produced the `mismatch:...` line
1603
- # the check below would print, in the opposite direction (got/want swapped) each time, then
1604
- # reverted. Also verified this pass: appending a synthetic dated correction demoting
1605
- # `01|6` reds the check; flipping the SETTLED table's own copy of `01|6` reds it; flipping only the
1606
- # ORIGINAL table's copy (now correctly superseded) does not. Neither direction is covered when
1607
- # decisions.md is absent -- that gap is real and is not claimed to be closed by the checks above.
1608
- D11_PLAN_DIR="$ROOT/.somi/plans/eval-corpus-rebuild"
1609
- D11_DECISIONS="$D11_PLAN_DIR/decisions.md"
1610
- if [ -f "$D11_DECISIONS" ]; then
1611
- drift=$(j "
1612
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1613
- const fs = await import('node:fs');
1614
- const text = fs.readFileSync('$D11_DECISIONS', 'utf8');
1615
- let expected;
1616
- try { expected = C.decisionsMdClassification(text); }
1617
- catch (e) { process.stdout.write('throw:' + e.message); process.exit(0); }
1618
- process.stdout.write(String(C.diffClassification(C.CLASSIFICATION, expected)));
1619
- ")
1620
- check "classification.mjs matches decisions.md#d11's settled table exactly (task, criterion, dimension, verdict)" \
1621
- "$drift" "null"
1622
- elif [ -d "$D11_PLAN_DIR" ]; then
1623
- bad "decisions.md#d11 drift check: $D11_PLAN_DIR exists but decisions.md is missing -- a real gap, not the expected CI/fresh-checkout absence"
1624
- else
1625
- echo " (skipped: $D11_PLAN_DIR not present -- .somi/ is gitignored, this check only runs where the plan directory is on disk)"
1626
- fi
1627
-
1628
- # --- smoke.mjs -- frontmatter-driven, zero-model-call smoke check for the
1629
- # commands the live-model corpus does not gate with a live-model corpus -------------------------------
1630
- # The 3 genuinely gated commands: /plan, /code, /review (the rebuilt task gate).
1631
- # /code-loop's own convergence gate was once unbuilt, and labeling it `gate` excluded it from smoke
1632
- # for a mechanism that did not exist. It then joined THIS tier, the same treatment /ship-loop gets
1633
- # for its own deferred gate. Commands on disk today minus the gated set is what
1634
- # remains in the smoke tier -- both counted below, not assumed (currently 24 minus 4 = 20).
1635
- #
1636
- # this set used to be spelled independently at three sites (now three still --
1637
- # GATED_COMMANDS_JS plus the two hardcoded expected.set('code-loop', ...)/('ship-loop', ...) rows
1638
- # in the cross-check below, both deliberately NOT members of this set) -- one check widening its
1639
- # own copy silently zeroed that check's coverage while the others stayed green (demonstrated before).
1640
- #
1641
- # 'code-loop' MOVES INTO this set here -- its own convergence gate now exists and has
1642
- # a CLI (tests/evals/convergence.mjs), so it is no longer only frontmatter-and-install-checked. The
1643
- # 2.6 cross-check below flips its docs/EVALS.md label to `gate` the moment
1644
- # tests/scripts/convergence-runner.sh exists -- keyed on THAT file rather than on this set, per its
1645
- # own comment; this line is what actually removes it from the smoke tier's 21.
1646
- GATED_COMMANDS_JS="new Set(['plan', 'code', 'review', 'code-loop'])"
1647
-
1648
- # A new command (commands/refactor-design.md) joined the smoke tier like every other ungated
1649
- # reason alone; removing /somi (2.2.1) then took them to 24 and 20.
1650
- # reason alone.
1651
- check "25 commands on disk today (commands/*.md)" \
1652
- "$(ls "$ROOT"/commands/*.md | wc -l | tr -d ' ')" "25"
1653
-
1654
- check "discoverUngatedCommands() finds exactly the 21 D8 scopes this smoke check to (3.4: code-loop moved into GATED_COMMANDS_JS, 21 -> 20; a new command joined the smoke tier, 20 -> 21)" \
1655
- "$(j "
1656
- const S = await import('$ROOT/tests/evals/lib/smoke.mjs');
1657
- const gated = $GATED_COMMANDS_JS;
1658
- process.stdout.write(String(S.discoverUngatedCommands('$ROOT/commands', gated).length));
1659
- ")" "21"
1660
-
1661
- # The load-bearing negative constraint, made structural rather than trusted by intention (this
1662
- # phase has twice needed a grep pin, not trust, to keep "no test reaches this site" honest --
1663
- # the shard-write path, the judge-machinery deletion). Neither check names the model-invoking export in
1664
- # this comment, on purpose -- a docstring quoting it as prose is exactly the false-positive shape
1665
- # the shard-write pin already caught once. Static, so neither survives a ROUTE change (a computed property name,
1666
- # or a call from elsewhere) -- the behavioral pin further below covers that.
1667
- check "smoke.mjs imports ONLY installSomi and DEFINITION_DIRS from install.mjs" \
1668
- "$(grep -c "from './install.mjs';" "$ROOT/tests/evals/lib/smoke.mjs")" "1"
1669
- check "smoke.mjs never references install.mjs's model-invoking export, anywhere in the file" \
1670
- "$(grep -c 'invokeCommand' "$ROOT/tests/evals/lib/smoke.mjs")" "0"
1671
-
1672
- # Behavioral pin: a stub `claude` on PATH proves NO route reaches the model -- not just
1673
- # that the two static greps above hold. Every un-gated command is run through smokeCheck() with
1674
- # the stub in front of the real binary; the sentinel it touches must stay absent no matter how
1675
- # smoke.mjs got to this point.
1676
- stub_bin=$(mktemp -d)
1677
- stub_sentinel="$stub_bin/touched"
1678
- printf '#!/bin/sh\n%s "%s"\nexit 1\n' "$(command -v touch)" "$stub_sentinel" > "$stub_bin/claude"
1679
- chmod +x "$stub_bin/claude"
1680
- stub_iters=$(PATH="$stub_bin:$PATH" node --input-type=module -e "
1681
- const S = await import('$ROOT/tests/evals/lib/smoke.mjs');
1682
- const gated = $GATED_COMMANDS_JS;
1683
- const files = S.discoverUngatedCommands('$ROOT/commands', gated);
1684
- for (const f of files) S.smokeCheck(f); process.stdout.write(String(files.length));
1685
- " 2>/dev/null)
1686
- # proves the loop iterated the shared gated-set constant for real (a throw before the final
1687
- # write also leaves this empty, subsuming the old exit-status check) -- not a stale count reused
1688
- # from a different check.
1689
- check "the stub-claude loop iterated all 21 currently un-gated commands, so ABSENT below can't mean it never ran" \
1690
- "$stub_iters" "21"
1691
- check "no smokeCheck() call reaches a stub claude on PATH (sentinel stays absent)" \
1692
- "$([ -e "$stub_sentinel" ] && echo TOUCHED || echo ABSENT)" "ABSENT"
1693
-
1694
- # Positive control: proves the stub is reachable on PATH at all -- a bad mktemp/chmod would
1695
- # otherwise leave ABSENT true for the wrong reason, with the check reading green regardless.
1696
- PATH="$stub_bin" claude >/dev/null 2>&1
1697
- check "positive control: claude invoked directly under the same stub touches the sentinel" \
1698
- "$([ -e "$stub_sentinel" ] && echo TOUCHED || echo ABSENT)" "TOUCHED"
1699
- rm -rf "$stub_bin"
1700
-
1701
- check "CLAUDE_CODE_TOOLS allowlist is non-empty (D3: a literal constant, not a dependency)" \
1702
- "$(j "const S = await import('$ROOT/tests/evals/lib/smoke.mjs'); process.stdout.write(String(S.CLAUDE_CODE_TOOLS.size > 0));")" "true"
1703
-
1704
- # The acceptance criterion: smokeCheck() succeeds for every one of the 21
1705
- # currently un-gated commands. Real commands are never mutated to make this pass (scope
1706
- # discipline, stated in the coder's own brief) -- a real command failing here is a finding to
1707
- # report, not a fixture to fix.
1708
- allpass=$(j "
1709
- const S = await import('$ROOT/tests/evals/lib/smoke.mjs');
1710
- const gated = $GATED_COMMANDS_JS;
1711
- const files = S.discoverUngatedCommands('$ROOT/commands', gated);
1712
- const failed = files.map((f) => [f, S.smokeCheck(f)]).filter(([, r]) => !r.ok);
1713
- process.stdout.write(failed.length === 0 ? 'ALL PASS' : failed.map(([f, r]) => f + ':' + r.field + ':' + r.reason).join(' | '));
1714
- ")
1715
- check "smokeCheck() succeeds for all 21 currently un-gated commands" "$allpass" "ALL PASS"
1716
-
1717
- # --- 2.5 acceptance: each of the four staged mutations fails with a SPECIFIC, ATTRIBUTABLE reason
1718
- # -- part of the acceptance criterion, not added at review. Staged against a
1719
- # REAL, installed command file (pr.md, arbitrarily -- any un-gated command would do), never a
1720
- # hand-built fixture (adversarial mutations are staged against real, committed inputs).
1721
- # `orig` is read once and held in memory -- copied aside, never `git checkout`'d -- and the mutant
1722
- # lives only in a throwaway `installSomi()` temp dir that is removed at the end of every case;
1723
- # `commands/pr.md` in the repo is never touched.
1724
- smoke_mutation_case() {
1725
- local got
1726
- got=$(j "
1727
- const fs = await import('node:fs');
1728
- const os = await import('node:os');
1729
- const path = await import('node:path');
1730
- const { installSomi } = await import('$ROOT/tests/evals/lib/install.mjs');
1731
- const S = await import('$ROOT/tests/evals/lib/smoke.mjs');
1732
- const mutbin = fs.mkdtempSync(path.join(os.tmpdir(), 'somi-smoke-mut-'));
1733
- installSomi('$ROOT', mutbin);
1734
- const target = path.join(mutbin, '.claude', 'commands', 'pr.md');
1735
- const orig = fs.readFileSync(target, 'utf8');
1736
- $2
1737
- fs.writeFileSync(target, mutated);
1738
- const r = S.smokeCheck(target);
1739
- fs.rmSync(mutbin, { recursive: true, force: true });
1740
- process.stdout.write(r.ok ? 'PASSED-BUT-SHOULD-FAIL' : r.field + ':' + r.reason);
1741
- ")
1742
- check "$1" "$got" "$3"
1743
- }
1744
-
1745
- # Control first (every gate's suite asserts a healthy input is NOT rejected, not only
1746
- # that a degraded one is caught) -- proves the four failures below are attributable to each
1747
- # specific mutation, not to something already wrong with the fixture itself.
1748
- smoke_control=$(j "
1749
- const fs = await import('node:fs');
1750
- const os = await import('node:os');
1751
- const path = await import('node:path');
1752
- const { installSomi } = await import('$ROOT/tests/evals/lib/install.mjs');
1753
- const S = await import('$ROOT/tests/evals/lib/smoke.mjs');
1754
- const mutbin = fs.mkdtempSync(path.join(os.tmpdir(), 'somi-smoke-mut-'));
1755
- installSomi('$ROOT', mutbin);
1756
- const target = path.join(mutbin, '.claude', 'commands', 'pr.md');
1757
- const r = S.smokeCheck(target);
1758
- fs.rmSync(mutbin, { recursive: true, force: true });
1759
- process.stdout.write(r.ok ? 'PASS' : 'field:' + r.field + ' reason:' + r.reason);
1760
- ")
1761
- check "control: the real, unmutated pr.md passes smokeCheck()" "$smoke_control" "PASS"
1762
-
1763
- smoke_mutation_case "staged failure 1/4: a missing description fails, attributed to 'description'" \
1764
- "const mutated = orig.replace(/^description:.*\n/m, '');" \
1765
- "description:pr.md: frontmatter has no non-empty 'description'"
1766
-
1767
- smoke_mutation_case "staged failure 2/4: a non-existent allowed-tools entry fails, attributed to 'allowed-tools'" \
1768
- "const mutated = orig.replace(/^allowed-tools:.*\$/m, 'allowed-tools: Read, Grep, Glob, Bash, FrobnicateTool');" \
1769
- "allowed-tools:pr.md: 'FrobnicateTool' is not a Claude Code tool this repo recognizes (not in CLAUDE_CODE_TOOLS)"
1770
-
1771
- # Commands no longer declare model: at all (the front door dispatches this command's paired agent
1772
- # at the agent's own declared cost/model instead) -- so the mutation for this slot is INSERTING
1773
- # one, not un-recognizing one. pr.md carries no `model:` line post-conversion, so the mutation
1774
- # prepends one right after the frontmatter's opening fence rather than replacing an existing line.
1775
- smoke_mutation_case "staged failure 3/4: a re-added model: on a command fails, attributed to 'model'" \
1776
- "const mutated = orig.replace(/^---\$/m, '---\nmodel: sonnet');" \
1777
- "model:pr.md: frontmatter declares 'model: sonnet' -- commands no longer declare a model of their own; the front door dispatches this command's paired agent at the agent's own declared cost/model instead"
1778
-
1779
- # The fix, proven both ways: FrobnicateTool (not real, above) still fails; TodoWrite (real, but
1780
- # declared by no command in this repo today) now passes -- via the allowlist, not popularity. The
1781
- # old, corpus-only predicate false-failed this case (the check taxed the first adopter of anything).
1782
- smoke_todowrite=$(j "
1783
- const fs = await import('node:fs');
1784
- const os = await import('node:os');
1785
- const path = await import('node:path');
1786
- const { installSomi } = await import('$ROOT/tests/evals/lib/install.mjs');
1787
- const S = await import('$ROOT/tests/evals/lib/smoke.mjs');
1788
- const mutbin = fs.mkdtempSync(path.join(os.tmpdir(), 'somi-smoke-mut-'));
1789
- installSomi('$ROOT', mutbin);
1790
- const target = path.join(mutbin, '.claude', 'commands', 'pr.md');
1791
- const orig = fs.readFileSync(target, 'utf8');
1792
- const mutated = orig.replace(/^allowed-tools:.*\$/m, 'allowed-tools: Read, Grep, Glob, Bash, TodoWrite');
1793
- fs.writeFileSync(target, mutated);
1794
- const r = S.smokeCheck(target);
1795
- fs.rmSync(mutbin, { recursive: true, force: true });
1796
- process.stdout.write(r.ok ? 'PASS' : 'field:' + r.field + ' reason:' + r.reason);
1797
- ")
1798
- check "TodoWrite -- real, but declared by no other command -- passes via the allowlist" \
1799
- "$smoke_todowrite" "PASS"
1800
-
1801
- # DEFINITION_DIRS pinned literally -- installSomi() and smokeCheck() both iterate this one
1802
- # constant, so comparing the two sides against each other (as the mutation below does) can't catch
1803
- # a dropped/renamed entry; only a pin against the literal value can.
1804
- check "DEFINITION_DIRS is pinned literally" \
1805
- "$(j "const { DEFINITION_DIRS } = await import('$ROOT/tests/evals/lib/install.mjs'); process.stdout.write(JSON.stringify(DEFINITION_DIRS));")" \
1806
- '["commands","agents","skills","rules"]'
1807
-
1808
- # The replacement: the path check no longer walks a command's body links (that duplicated
1809
- # scripts/check-links.mjs and reintroduced the fence-blindness it was rewritten to remove). It now
1810
- # asserts the installed tree contains every install.mjs DEFINITION_DIRS entry -- staged here by
1811
- # deleting the installed 'skills' dir before smokeCheck() re-installs from it. The `all 21` check
1812
- # alone is blind to dropping 'skills' from DEFINITION_DIRS -- both sides iterate
1813
- # the same constant, so 0 of 21 go red there; staged failure 4/4 goes red on that drop too.
1814
- smoke_missing_dir=$(j "
1815
- const fs = await import('node:fs');
1816
- const os = await import('node:os');
1817
- const path = await import('node:path');
1818
- const { installSomi } = await import('$ROOT/tests/evals/lib/install.mjs');
1819
- const S = await import('$ROOT/tests/evals/lib/smoke.mjs');
1820
- const mutbin = fs.mkdtempSync(path.join(os.tmpdir(), 'somi-smoke-mut-'));
1821
- installSomi('$ROOT', mutbin);
1822
- fs.rmSync(path.join(mutbin, '.claude', 'skills'), { recursive: true, force: true });
1823
- const target = path.join(mutbin, '.claude', 'commands', 'pr.md');
1824
- const r = S.smokeCheck(target);
1825
- fs.rmSync(mutbin, { recursive: true, force: true });
1826
- const matched = !r.ok && r.field === 'install' && r.reason.includes(\"did not install the 'skills' directory\");
1827
- process.stdout.write(r.ok ? 'PASSED-BUT-SHOULD-FAIL' : (matched ? 'install:MATCH' : r.field + ':' + r.reason));
1828
- ")
1829
- check "staged failure 4/4: the installed tree missing a DEFINITION_DIRS entry (skills/) fails, attributed to 'install'" \
1830
- "$smoke_missing_dir" "install:MATCH"
1831
-
1832
- # --- docs/EVALS.md's coverage table, cross-checked against classification.mjs and the live
1833
- # SCOPES -- not against a second document. A document-to-document comparison cannot see a
1834
- # document-vs-code gap (the lesson applied here to a new pair: the doc and the code it
1835
- # describes, not two hand-authored copies of the same fact). --------------------------------------
1836
-
1837
- # The per-command floor rule, with its zero-dimension exception: zero gating dimensions reads
1838
- # report-only, never partial (even though 0/total is also "fewer than half"); fewer than half reads
1839
- # partial; half or more reads gate. The zero-dimension-label guard: a naive `< 0.5 -> partial` rule
1840
- # with no zero branch would mislabel task 03 (0 of 4) as `partial`, implying gating capability it
1841
- # does not have -- exactly the overstatement the zero-dimension exception exists to forbid.
1842
- check "coverage label floor rule: zero gating reads report-only, never partial (the zero-dimension guard); fewer-than-half reads partial; half-or-more reads gate" \
1843
- "$(j "
1844
- function labelFor(g, t) { if (g === 0) return 'report-only'; return (g / t) < 0.5 ? 'partial' : 'gate'; }
1845
- const cases = [[0, 4], [0, 1], [1, 4], [2, 4], [1, 2], [3, 4]];
1846
- process.stdout.write(cases.map(([g, t]) => labelFor(g, t)).join(','));
1847
- ")" "report-only,report-only,partial,gate,gate,gate"
1848
-
1849
- # The task->command mapping is derived from each task spec's own header line (the same
1850
- # `Command under test: \`/name\`` idiom run.mjs's own taskPrompt() parses), not hand-typed --
1851
- # a task file renamed to a different command would move this, not silently leave it stale.
1852
- check "task-to-command mapping is derived from each task spec's own header, not hardcoded" \
1853
- "$(j "
1854
- const fs = await import('node:fs');
1855
- const dir = '$ROOT/tests/evals/tasks';
1856
- const map = {};
1857
- for (const f of fs.readdirSync(dir).filter((f) => /^\d\d-.*\.md\$/.test(f))) {
1858
- const text = fs.readFileSync(dir + '/' + f, 'utf8');
1859
- const m = text.match(/Command under test: \`\/(\w[\w-]*)\`/);
1860
- map[f.slice(0, 2)] = m ? m[1] : null;
1861
- }
1862
- process.stdout.write(JSON.stringify(map));
1863
- ")" '{"01":"plan","02":"code","03":"review"}'
1864
-
1865
- # The real check: parse docs/EVALS.md's actual coverage table (git-tracked, always present --
1866
- # unlike decisions.md, this runs unconditionally, no CI-skip branch) and compare every row against
1867
- # a label derived from classification.mjs's live CLASSIFICATION table, not from this comment or
1868
- # from decisions.md's prose. /code-loop and /ship-loop sit outside classification.mjs's data model
1869
- # (no task spec, no criteria -- the convergence gate and the deferred ship-loop gate respectively) and are
1870
- # asserted directly for that stated reason, not derived from a table that was never built to cover
1871
- # them; every other command name is read live off commands/*.md, so a 25th command or a rename
1872
- # shows up as a missing/extra row rather than silently passing.
1873
- coverage_check=$(j "
1874
- const fs = await import('node:fs');
1875
- const path = await import('node:path');
1876
- const C = await import('$ROOT/tests/evals/lib/classification.mjs');
1877
- function labelFor(g, t) { if (g === 0) return 'report-only'; return (g / t) < 0.5 ? 'partial' : 'gate'; }
1878
-
1879
- const tasksDir = '$ROOT/tests/evals/tasks';
1880
- const taskToCommand = {};
1881
- for (const f of fs.readdirSync(tasksDir).filter((f) => /^\d\d-.*\.md\$/.test(f))) {
1882
- const text = fs.readFileSync(path.join(tasksDir, f), 'utf8');
1883
- const m = text.match(/Command under test: \`\/(\w[\w-]*)\`/);
1884
- taskToCommand[f.slice(0, 2)] = m[1];
1885
- }
1886
- const byTask = {};
1887
- for (const d of C.taskDimensions()) {
1888
- byTask[d.task] ??= { gating: 0, total: 0 };
1889
- byTask[d.task].total += 1;
1890
- if (d.verdict === 'gating') byTask[d.task].gating += 1;
1891
- }
1892
- const expected = new Map();
1893
- for (const [task, command] of Object.entries(taskToCommand)) {
1894
- const { gating, total } = byTask[task];
1895
- expected.set(command, { label: labelFor(gating, total), ratio: gating + ' of ' + total });
1896
- }
1897
- // F-170: 'smoke'/'phase 3' is only true while phase 3's gate isn't wired. Flip the expectation
1898
- // once it lands, so this pin fails loudly on the transition instead of going stale through it --
1899
- // the exact way /code-loop's 'gate' label went stale the first time (F-163).
1900
- // F-175: keyed on 3.4's own artifact (tests/scripts/convergence-runner.sh), NOT on 3.3's
1901
- // tests/evals/convergence.mjs. 3.3's Files line creates only that module; the instruction to
1902
- // flip this label and move /code-loop into GATED_COMMANDS_JS lives solely in 3.4's Acceptance
1903
- // (phases/03-convergence-gating.md). Keying on 3.3's file would redden this pin the moment 3.3
1904
- // lands -- a full iteration before the fix instruction that explains it exists -- and the
1905
- // cheapest escape from an unexplained red suite is publishing 'gate' before the gate runs
1906
- // (F-163 a third time). \"being built in phase 3, not yet landed\" is still true at the end of
1907
- // 3.3, so the doc row isn't stale there; a pin that reddens before its own claim goes false
1908
- // teaches people to route around it.
1909
- const convergenceBuilt = fs.existsSync('$ROOT/tests/scripts/convergence-runner.sh');
1910
- expected.set('code-loop', convergenceBuilt
1911
- ? { label: 'gate' }
1912
- : { label: 'smoke', mustMention: 'phase 3' });
1913
- expected.set('ship-loop', { label: 'smoke', mustMention: 'deferred' });
1914
- for (const f of fs.readdirSync('$ROOT/commands').filter((f) => f.endsWith('.md'))) {
1915
- const name = f.slice(0, -3);
1916
- if (!expected.has(name)) expected.set(name, { label: 'smoke' });
1917
- }
1918
-
1919
- function parseCoverageTable(text) {
1920
- // F-166: was \`(.+?)\s*\|\$\`, /m -- a lazy group anchored only at END OF LINE doesn't stop at
1921
- // an embedded \`|\`; a future 4th column would silently fold into \`detail\`, so a row could
1922
- // state the wrong ratio in its own cell and still pass on a substring match against the
1923
- // absorbed neighbour. Split into exactly 3 non-empty cells instead; a row with more or fewer
1924
- // fails to match at all (reported \`missing:<name>\`) rather than over-capturing.
1925
- const actual = new Map();
1926
- const re = /^\|([^|\n]*)\|([^|\n]*)\|([^|\n]*)\|\s*\$/gm;
1927
- let m;
1928
- while ((m = re.exec(text))) {
1929
- const nm = m[1].trim().match(/^\`\/([\w-]+)\`\$/);
1930
- const label = m[2].trim(), detail = m[3].trim();
1931
- if (nm && label && detail) {
1932
- if (actual.has(nm[1])) throw new Error('duplicate coverage row: ' + nm[1]);
1933
- actual.set(nm[1], { label, detail });
1934
- }
1935
- }
1936
- return actual;
1937
- }
1938
- function diff(actual, expected) {
1939
- const problems = [];
1940
- for (const [name, exp] of expected) {
1941
- const got = actual.get(name);
1942
- if (!got) { problems.push('missing:' + name); continue; }
1943
- if (got.label !== exp.label) problems.push('label:' + name + ':got=' + got.label + ':want=' + exp.label);
1944
- if (exp.ratio && !got.detail.includes(exp.ratio)) problems.push('ratio:' + name + ':want ' + exp.ratio + ' in \"' + got.detail + '\"');
1945
- if (exp.mustMention && !got.detail.toLowerCase().includes(exp.mustMention)) problems.push('mention:' + name + ':want \"' + exp.mustMention + '\" in \"' + got.detail + '\"');
1946
- }
1947
- for (const name of actual.keys()) if (!expected.has(name)) problems.push('extra:' + name);
1948
- return problems;
1949
- }
1950
-
1951
- const docText = fs.readFileSync('$ROOT/docs/EVALS.md', 'utf8');
1952
- const actual = parseCoverageTable(docText);
1953
- const problems = diff(actual, expected);
1954
- process.stdout.write(problems.length === 0 ? 'MATCH:' + actual.size : problems.join(' | '));
1955
- ")
1956
- check "docs/EVALS.md's coverage table (25 rows) matches labels derived from classification.mjs + D8's floor rule, live -- not copied from the plan" \
1957
- "$coverage_check" "MATCH:25"
1958
-
1959
- # The full-scope numeric row, same discipline: parsed off docs/EVALS.md's actual text, compared
1960
- # against SCOPES.full imported live from run.mjs, formatted exactly as certify()'s own CLI output
1961
- # formats it (toFixed(2)) so the doc and the printed run summary can never read differently.
1962
- check "docs/EVALS.md's \`full\` scope row (draws, budget, all three power figures, covers) matches SCOPES.full live -- 240 draws / 1.81% all-soft / 27.00% one-soft" \
1963
- "$(j "
1964
- const fs = await import('node:fs');
1965
- function parseFullScopeRow(text) {
1966
- const m = text.match(/\|\s*\`full\`\s*\|\s*(\d+)\s*\|\s*≤(\d+)\s*\|\s*([\d.]+)%\s*\|\s*\*{0,2}([\d.]+)%\*{0,2}\s*\|\s*\*{0,2}([\d.]+)%\*{0,2}\s*\|\s*([^|]+?)\s*\|/);
1967
- return m && { draws: Number(m[1]), maxFailures: Number(m[2]), powerGood: m[3], powerSoft: m[4], powerSoftOne: m[5], covers: m[6].trim() };
1968
- }
1969
- const parsed = parseFullScopeRow(fs.readFileSync('$ROOT/docs/EVALS.md', 'utf8'));
1970
- const sc = M.SCOPES.full;
1971
- const expected = { draws: sc.draws, maxFailures: sc.maxFailures, powerGood: (sc.powerGood * 100).toFixed(2), powerSoft: (sc.powerSoft * 100).toFixed(2), powerSoftOne: (sc.powerSoftOne * 100).toFixed(2), covers: sc.covers };
1972
- process.stdout.write(JSON.stringify(parsed) === JSON.stringify(expected) ? 'match' : 'parsed=' + JSON.stringify(parsed) + ' expected=' + JSON.stringify(expected));
1973
- ")" "match"
1974
-
1975
- # the doc restates SCOPES.full.draws again in its own prose sentence, 95 lines below the
1976
- # pinned table above -- pin that copy too, or one number stays free to drift while the other is
1977
- # checked (exactly how "260" survived next to a pinned "240").
1978
- check "docs/EVALS.md's 'A full certification is N draws' sentence matches SCOPES.full.draws live" \
1979
- "$(j "
1980
- const fs = await import('node:fs');
1981
- const t = fs.readFileSync('$ROOT/docs/EVALS.md', 'utf8');
1982
- const m = t.match(/A full certification is (\d+) draws\./);
1983
- process.stdout.write(m ? String(Number(m[1]) === M.SCOPES.full.draws) : 'no-match');
1984
- ")" "true"
1985
-
1986
- # Both failure directions, shipped as permanent regression guards. Neither touches disk -- the
1987
- # doc-direction case mutates a STRING copy of the real file's text in memory; the code-direction
1988
- # case mutates a spread COPY of the real SCOPES.full object -- so neither risks corrupting a real
1989
- # file if interrupted, per the "copy aside, never mutate in place" discipline applied to
1990
- # a check's own fixtures. Also verified this pass against the real files on disk directly (mutate
1991
- # docs/EVALS.md, confirm red, restore from a copy; mutate a copy of run.mjs's CERTIFY_N, confirm
1992
- # red, restore) -- reported once at the time, not re-run on every suite invocation.
1993
- check "the cross-check catches a wrong DOC number (240 -> 260), SCOPES held real" \
1994
- "$(j "
1995
- const fs = await import('node:fs');
1996
- function parseFullScopeRow(text) {
1997
- const m = text.match(/\|\s*\`full\`\s*\|\s*(\d+)\s*\|\s*≤(\d+)\s*\|\s*([\d.]+)%\s*\|\s*\*{0,2}([\d.]+)%\*{0,2}\s*\|\s*\*{0,2}([\d.]+)%\*{0,2}\s*\|\s*([^|]+?)\s*\|/);
1998
- return m && { draws: Number(m[1]), maxFailures: Number(m[2]), powerGood: m[3], powerSoft: m[4], powerSoftOne: m[5], covers: m[6].trim() };
1999
- }
2000
- const real = fs.readFileSync('$ROOT/docs/EVALS.md', 'utf8');
2001
- const mutated = real.replace('| \`full\` | 240 |', '| \`full\` | 260 |');
2002
- const parsed = parseFullScopeRow(mutated);
2003
- const sc = M.SCOPES.full;
2004
- const expected = { draws: sc.draws, maxFailures: sc.maxFailures, powerGood: (sc.powerGood * 100).toFixed(2), powerSoft: (sc.powerSoft * 100).toFixed(2), powerSoftOne: (sc.powerSoftOne * 100).toFixed(2), covers: sc.covers };
2005
- process.stdout.write(String(JSON.stringify(parsed) === JSON.stringify(expected)));
2006
- ")" "false"
2007
- check "the cross-check catches a wrong CODE number (SCOPES.full.draws mutated), doc held real" \
2008
- "$(j "
2009
- const fs = await import('node:fs');
2010
- function parseFullScopeRow(text) {
2011
- const m = text.match(/\|\s*\`full\`\s*\|\s*(\d+)\s*\|\s*≤(\d+)\s*\|\s*([\d.]+)%\s*\|\s*\*{0,2}([\d.]+)%\*{0,2}\s*\|\s*\*{0,2}([\d.]+)%\*{0,2}\s*\|\s*([^|]+?)\s*\|/);
2012
- return m && { draws: Number(m[1]), maxFailures: Number(m[2]), powerGood: m[3], powerSoft: m[4], powerSoftOne: m[5], covers: m[6].trim() };
2013
- }
2014
- const real = fs.readFileSync('$ROOT/docs/EVALS.md', 'utf8');
2015
- const parsed = parseFullScopeRow(real);
2016
- const mutatedScopesFull = { ...M.SCOPES.full, draws: 200 };
2017
- const expected = { draws: mutatedScopesFull.draws, maxFailures: mutatedScopesFull.maxFailures, powerGood: (mutatedScopesFull.powerGood * 100).toFixed(2), powerSoft: (mutatedScopesFull.powerSoft * 100).toFixed(2), powerSoftOne: (mutatedScopesFull.powerSoftOne * 100).toFixed(2), covers: mutatedScopesFull.covers };
2018
- process.stdout.write(String(JSON.stringify(parsed) === JSON.stringify(expected)));
2019
- ")" "false"
2020
-
2021
- # --- convergence extractor -- reads /code-loop's loop-state JSON, classifies cap-breach ----
2022
- # (R3). Two independent extractors -- passesToApprove() (a pure field read) and capBreached() (a
2023
- # status classifier); neither calls the other, keeping the extractors code-disjoint from each other.
2024
- CONV=tests/evals/lib/convergence.mjs
2025
- cj() { node --input-type=module -e "const M = await import('$ROOT/$CONV'); $1" 2>&1; }
2026
-
2027
- echo "== convergence extractor (3.1) =="
2028
-
2029
- # --- passesToApprove(): fails safe (null) on anything that isn't a finite non-negative integer --
2030
- check "passesToApprove(null) is null" "$(cj "process.stdout.write(String(M.passesToApprove(null)));")" "null"
2031
- check "passesToApprove(undefined) is null" "$(cj "process.stdout.write(String(M.passesToApprove(undefined)));")" "null"
2032
- check "passesToApprove({}) is null (no pass field)" "$(cj "process.stdout.write(String(M.passesToApprove({})));")" "null"
2033
- check "passesToApprove('raw json string') is null (not pre-parsed -- fails safe, not JSON.parse'd for you)" \
2034
- "$(cj "process.stdout.write(String(M.passesToApprove('{\"pass\":4}')));")" "null"
2035
- check "passesToApprove({pass:'4'}) is null (string, not number)" "$(cj "process.stdout.write(String(M.passesToApprove({pass:'4'})));")" "null"
2036
- check "passesToApprove({pass:-1}) is null (negative)" "$(cj "process.stdout.write(String(M.passesToApprove({pass:-1})));")" "null"
2037
- check "passesToApprove({pass:1.5}) is null (non-integer)" "$(cj "process.stdout.write(String(M.passesToApprove({pass:1.5})));")" "null"
2038
- check "passesToApprove({pass:0}) is 0 (a real, valid boundary value -- not treated as falsy/missing)" \
2039
- "$(cj "process.stdout.write(String(M.passesToApprove({pass:0})));")" "0"
2040
- check "passesToApprove({pass:4}) is 4 (the ordinary case)" "$(cj "process.stdout.write(String(M.passesToApprove({pass:4})));")" "4"
2041
- # passesToApprove() is deliberately status-blind -- a RUNNING loop's provisional pass count comes
2042
- # back as-is; the caller (the convergence driver) must gate on status/capBreached() separately
2043
- # before treating it as a completed draw. Synthetic, not tied to any real file's live status, so
2044
- # this stays a permanent, deterministic pin of the contract rather than depending on ambient state
2045
- # that changes the moment a real loop finishes (see the guarded block below for why).
2046
- check "passesToApprove() is status-blind: returns a RUNNING loop's provisional pass count as-is" \
2047
- "$(cj "process.stdout.write(String(M.passesToApprove({status:'running', pass:1})));")" "1"
2048
-
2049
- # --- capBreached(): fails safe (null) on anything that isn't a recognised status string ----------
2050
- check "capBreached(null) is null" "$(cj "process.stdout.write(String(M.capBreached(null)));")" "null"
2051
- check "capBreached({}) is null (no status field)" "$(cj "process.stdout.write(String(M.capBreached({})));")" "null"
2052
- check "capBreached({status:123}) is null (not a string)" "$(cj "process.stdout.write(String(M.capBreached({status:123})));")" "null"
2053
- check "capBreached({status:'pending'}) is null (not a documented status at all)" \
2054
- "$(cj "process.stdout.write(String(M.capBreached({status:'pending'})));")" "null"
2055
- check "capBreached({status:'diff-cap-exceded'}) is null (one-letter typo of a real breach status -- exact match, not fuzzy)" \
2056
- "$(cj "process.stdout.write(String(M.capBreached({status:'diff-cap-exceded'})));")" "null"
2057
- # the typo case above REMOVES a letter, so a loosened matcher (substring/prefix/case-fold/
2058
- # trim) also returns null on it and passes -- it does not test exactness at all. These seven are
2059
- # near-misses a loosened matcher would wrongly accept: the first three kill substring/prefix
2060
- # containment (each embeds or extends a real status), 'DONE' kills case-folding and 'done ' kills
2061
- # trimming -- both on the `done` arm. Those two alone left the *breach*-set lookup's own
2062
- # case-fold/trim unmeasured -- `CAP_BREACH_STATUSES.has(status.toLowerCase())` and
2063
- # `CAP_BREACH_STATUSES.has(status.trim())` both survived at 303/0, over-detecting a breach on
2064
- # 'MAX-PASSES-EXCEEDED' where the module answers null. 'MAX-PASSES-EXCEEDED' kills case-folding and
2065
- # 'max-passes-exceeded ' kills trimming on that arm specifically. Real module confirmed to answer
2066
- # null on all seven before writing this.
2067
- NEAR_MISS_STATUSES=('user-stopped' 'not-max-passes-exceeded' 'max-passes-exceeded-recovered' 'DONE' 'done ' 'MAX-PASSES-EXCEEDED' 'max-passes-exceeded ')
2068
- for s in "${NEAR_MISS_STATUSES[@]}"; do
2069
- check "capBreached({status:'$s'}) is null (near-miss of a real status -- exact match, not fuzzy)" \
2070
- "$(cj "process.stdout.write(String(M.capBreached({status:'$s'})));")" "null"
2071
- done
2072
- check "capBreached({status:'done'}) is false" "$(cj "process.stdout.write(String(M.capBreached({status:'done'})));")" "false"
2073
- # Decision, made deliberately rather than defaulted into: a RUNNING loop is neither a confirmed
2074
- # pass nor a confirmed breach. false would assert "confirmed clean" (not yet true); true would mark
2075
- # a live loop as a cap failure it has not committed -- exactly the corpus-measuring-itself trap
2076
- # the standing design brief. null is the only answer that doesn't overclaim either way.
2077
- check "capBreached({status:'running'}) is null, NOT false and NOT true (the deliberate 'not done != breached' decision)" \
2078
- "$(cj "process.stdout.write(String(M.capBreached({status:'running'})));")" "null"
2079
- # Every documented terminal cap-breach status, individually -- catches an implementation that only
2080
- # recognises one or two of the five (`commands/code-loop.md`'s enum), not just the first tried.
2081
- # derived from the module's own exported CAP_BREACH_STATUSES, not retyped -- a status added,
2082
- # renamed, or dropped there is reflected here without a second edit. Reflection is
2083
- # exactly why a RENAME went undetected -- `circuit-breaker` -> `circuit-breakers` passed 306/0,
2084
- # because the loop derived both its subjects AND its only independent check (a count) from the same
2085
- # constant under test. Pinned instead against `commands/code-loop.md`'s own enum -- a source of
2086
- # truth outside the module that a rename cannot drag along with it -- via set-equality, which also
2087
- # subsumes the count (an empty derivation compares "" against 5 real entries and fails loudly on
2088
- # either side alone; both sides empty at once -- un-export AND the doc anchor
2089
- # renamed -- printed `ok` at 300/1 without the sentinel default on DOC_STATUSES below, which
2090
- # breaks that symmetry). This is the "vacuous zero-iteration pass" shape, closed here instead
2091
- # of by counting. Matches this file's own precedent at ~1803: every other command name is read
2092
- # live off `commands/*.md`, not retyped, so drift between the module and the doc shows up here too,
2093
- # not just drift within the module. Filtered on an identifier-safe allowlist -- letters, digits,
2094
- # underscore, hyphen -- rather than the doc's `[a-z-]` alphabet: sharing that
2095
- # alphabet as the filter was itself a blind spot -- a status outside it drops from both sides
2096
- # symmetrically and set-equality still compares equal (measured: `quota-cap-2` added to the module
2097
- # AND documented gives 306/0, the string asserted nowhere). An allowlist, not a denylist of just
2098
- # whitespace/quote/backslash: measured on this un-export mutation's actual stderr, a bare
2099
- # `file:///.../[eval1]:1` frame contains none of those three and would have slipped through as a
2100
- # bogus status. The allowlist keeps the actual concern -- stopping a failed import's stderr
2101
- # from landing as a raw token inside the single-quoted JS literals below -- while still being
2102
- # strictly wider than the doc's alphabet, so a real status outside `[a-z-]` surfaces as a
2103
- # set-equality mismatch instead of vanishing from both sides. Also drops `mapfile` (a minor portability cleanup),
2104
- # this script's only bash-4-only builtin.
2105
- BREACH_STATUSES=()
2106
- while IFS= read -r s; do
2107
- [[ "$s" =~ ^[A-Za-z0-9_-]+$ ]] && BREACH_STATUSES+=("$s")
2108
- done < <(cj "for (const s of M.CAP_BREACH_STATUSES) process.stdout.write(s + '\n');")
2109
- DOC_STATUSES="$(grep -A1 'Loop status:' "$ROOT/skills/flow-code-loop/SKILL.md" | grep -o '`[a-z-]*`' | tr -d '`' | grep -v '^done$' | sort)"
2110
- check "the module's CAP_BREACH_STATUSES matches skills/flow-code-loop/SKILL.md's documented enum exactly (set-equality, not a count)" \
2111
- "$(printf '%s\n' ${BREACH_STATUSES[@]+"${BREACH_STATUSES[@]}"} | sort)" "${DOC_STATUSES:-<doc-derivation-empty>}"
2112
- for s in "${BREACH_STATUSES[@]}"; do
2113
- check "capBreached({status:'$s'}) is true (documented breach terminal)" \
2114
- "$(cj "process.stdout.write(String(M.capBreached({status:'$s'})));")" "true"
2115
- done
2116
- # The literal acceptance criterion: true against a synthetic file staged with
2117
- # status:"max-passes-exceeded" -- restated once more here as its own named check, not only folded
2118
- # into the loop above, so this specific acceptance point has its own visible pass/fail line.
2119
- check "capBreached() on a synthetic file staged with status:\"max-passes-exceeded\" is true (phase 3.1's own acceptance wording)" \
2120
- "$(cj "process.stdout.write(String(M.capBreached({status:'max-passes-exceeded'})));")" "true"
2121
-
2122
- # --- breachReason(): the SPECIFIC cap-breach reason, not merely the
2123
- # boolean capBreached() already returns -- gates on capBreached() === true and strips the same
2124
- # stopped-<reason> prefix capBreached() already strips internally but never exposes.
2125
- # multipass-fixture's own driver fix (tests/evals/convergence.mjs's fillArm()) threads THIS
2126
- # function's return through the breach branch; these are the extractor's own direct tests, same
2127
- # split as capBreached()/classifyDraw() above (the extractor is tested here; the driver call site
2128
- # is tested in the 3.3 section below via fillArm() directly).
2129
- check "breachReason(null) is null" "$(cj "process.stdout.write(String(M.breachReason(null)));")" "null"
2130
- check "breachReason({}) is null (no status field)" "$(cj "process.stdout.write(String(M.breachReason({})));")" "null"
2131
- check "breachReason({status:123}) is null (not a string)" "$(cj "process.stdout.write(String(M.breachReason({status:123})));")" "null"
2132
- check "breachReason({status:'done'}) is null (the success terminal, not a breach)" \
2133
- "$(cj "process.stdout.write(String(M.breachReason({status:'done'})));")" "null"
2134
- check "breachReason({status:'stopped-done'}) is null (F-239's own guard: never legitimately stopped-, and breachReason gates through capBreached() so it inherits that)" \
2135
- "$(cj "process.stdout.write(String(M.breachReason({status:'stopped-done'})));")" "null"
2136
- check "breachReason({status:'running'}) is null (neither converged nor breached yet)" \
2137
- "$(cj "process.stdout.write(String(M.breachReason({status:'running'})));")" "null"
2138
- check "breachReason({status:'pending'}) is null (undocumented status, not a near-miss guess)" \
2139
- "$(cj "process.stdout.write(String(M.breachReason({status:'pending'})));")" "null"
2140
- # Every documented terminal cap-breach status, individually, in BOTH the bare and the documented
2141
- # stopped-<reason> finish-path form -- reuses BREACH_STATUSES (derived above
2142
- # from the module's own exported CAP_BREACH_STATUSES, not retyped), so all five are covered, not
2143
- # just the two named by example, and a status added/renamed/dropped there is
2144
- # reflected here without a second edit.
2145
- for s in "${BREACH_STATUSES[@]}"; do
2146
- check "breachReason({status:'$s'}) is '$s' (bare form)" \
2147
- "$(cj "process.stdout.write(String(M.breachReason({status:'$s'})));")" "$s"
2148
- check "breachReason({status:'stopped-$s'}) is '$s', the BARE reason -- not the prefixed string (documented stopped-<reason> finish form, F-235)" \
2149
- "$(cj "process.stdout.write(String(M.breachReason({status:'stopped-$s'})));")" "$s"
2150
- done
2151
-
2152
- # --- Against the real population the baseline was independently computed from -------------------------
2153
- # .somi/ is gitignored (confirmed: .gitignore lines 3-4/8/34) -- .somi/somi-state/loop/ will not
2154
- # exist on a fresh checkout or in a from-scratch CI clone, same precondition the classification
2155
- # drift check above already handles. Guarded the same way, for the same reason.
2156
- LOOPDIR="$ROOT/.somi/somi-state/loop"
2157
- if [ -d "$LOOPDIR" ]; then
2158
- # NAMED EXPLICITLY, not globbed. .somi/somi-state/loop/*.json has grown to 34 files since
2159
- # the baseline was computed from 21 -- many of the new ones are the maintainers' own in-progress
2160
- # loop-state files. A glob over *.json today would silently validate against a
2161
- # DIFFERENT, still-growing population, not the one the baseline was independently computed from. This list is
2162
- # that population, identified by name: composition cross-checked against its own breakdown
2163
- # before trusting it (9 code + 1 plan under context-economy-overhaul, 4 code + 1 plan under
2164
- # reasoning-craft, 5 code + 1 plan under somi-orchestrator = 21) and its values reproduce the
2165
- # stated mean (2.142857...) and sample sd (1.236354...) exactly -- verified below, not assumed.
2166
- BASELINE_21=(
2167
- context-economy-overhaul.1.1 context-economy-overhaul.1.2 context-economy-overhaul.1.3
2168
- context-economy-overhaul.2.1 context-economy-overhaul.2.2 context-economy-overhaul.2.3
2169
- context-economy-overhaul.3.1 context-economy-overhaul.3.2 context-economy-overhaul.3.3
2170
- context-economy-overhaul
2171
- reasoning-craft.1.1 reasoning-craft.1.2 reasoning-craft.1.3 reasoning-craft.1.4
2172
- reasoning-craft
2173
- somi-orchestrator.1.1 somi-orchestrator.2.1 somi-orchestrator.3.1 somi-orchestrator.3.2 somi-orchestrator.4.1
2174
- somi-orchestrator
2175
- )
2176
- names_js="["
2177
- for n in "${BASELINE_21[@]}"; do names_js+="'$n',"; done
2178
- names_js+="]"
2179
-
2180
- missing=""
2181
- for name in "${BASELINE_21[@]}"; do
2182
- [ -f "$LOOPDIR/$name.json" ] || missing="$missing $name"
2183
- done
2184
- if [ -z "$missing" ]; then
2185
- check "all 21 of context.md §2.2's named baseline files still exist on disk" "present" "present"
2186
- else
2187
- check "all 21 of context.md §2.2's named baseline files still exist on disk" "MISSING:$missing" "present"
2188
- fi
2189
-
2190
- check "passesToApprove() reproduces exactly context.md §2.2's 21 values, by name not by glob" \
2191
- "$(cj "
2192
- const fs = await import('node:fs');
2193
- const names = $names_js;
2194
- const dir = '$LOOPDIR';
2195
- const got = names.map((n) => M.passesToApprove(JSON.parse(fs.readFileSync(dir + '/' + n + '.json', 'utf8'))));
2196
- process.stdout.write(JSON.stringify(got));
2197
- ")" \
2198
- "[4,4,5,2,3,2,3,3,3,3,1,1,1,1,2,1,1,1,1,1,2]"
2199
-
2200
- check "the 21 extracted values' mean/sd match context.md §2.2 exactly (2.142857.../1.236354...)" \
2201
- "$(cj "
2202
- const fs = await import('node:fs');
2203
- const names = $names_js;
2204
- const dir = '$LOOPDIR';
2205
- const p = names.map((n) => M.passesToApprove(JSON.parse(fs.readFileSync(dir + '/' + n + '.json', 'utf8'))));
2206
- const mean = p.reduce((a, b) => a + b, 0) / p.length;
2207
- const sd = Math.sqrt(p.reduce((a, b) => a + (b - mean) ** 2, 0) / (p.length - 1));
2208
- process.stdout.write(mean.toFixed(6) + '/' + sd.toFixed(6));
2209
- ")" \
2210
- "2.142857/1.236354"
2211
-
2212
- check "capBreached() is false for all 21 of context.md §2.2's named files (all real status:\"done\")" \
2213
- "$(cj "
2214
- const fs = await import('node:fs');
2215
- const names = $names_js;
2216
- const dir = '$LOOPDIR';
2217
- const got = names.map((n) => M.capBreached(JSON.parse(fs.readFileSync(dir + '/' + n + '.json', 'utf8'))));
2218
- process.stdout.write(String(got.every((b) => b === false)) + ':' + got.length);
2219
- ")" \
2220
- "true:21"
2221
-
2222
- # The corpus grew a second way since: it now contains loop-state files that are neither
2223
- # done nor a cap-breach -- status:"running" (a few in-progress files). Discovered DYNAMICALLY, by count, rather than by
2224
- # naming these specific files: an in-progress state file WILL flip to "done" the moment
2225
- # its loop finishes, so a check hardcoded to a fixed filename/count would go stale for a reason
2226
- # unrelated to correctness the moment that loop closes. The invariant under test
2227
- # (capBreached() is null for a real running file, never false or true) holds regardless of how
2228
- # many such files exist at any given moment, including zero.
2229
- running_check=$(cj "
2230
- const fs = await import('node:fs');
2231
- const files = fs.readdirSync('$LOOPDIR').filter((f) => f.endsWith('.json'));
2232
- const runningResults = [];
2233
- for (const f of files) {
2234
- const o = JSON.parse(fs.readFileSync('$LOOPDIR/' + f, 'utf8'));
2235
- if (o.status === 'running') runningResults.push(M.capBreached(o));
2236
- }
2237
- process.stdout.write(runningResults.length + ':' + runningResults.every((r) => r === null));
2238
- ")
2239
- running_count="${running_check%%:*}"
2240
- running_all_null="${running_check##*:}"
2241
- if [ "$running_count" = "0" ]; then
2242
- echo " (skipped: no real status:\"running\" loop-state file on disk right now to check capBreached() against)"
2243
- else
2244
- check "capBreached() is null for every real loop-state file currently status:\"running\" ($running_count found right now)" \
2245
- "$running_all_null" "true"
2246
- fi
2247
-
2248
- # the check above is SELF-SELECTING -- it discovers subjects by the exact string
2249
- # (o.status === 'running') it then asserts capBreached() classifies. If the schema renamed
2250
- # 'running' to something else, zero files would match, running_count would read 0, and the block
2251
- # above would print a skip rather than fail -- silent, not loud. Supplemented (not replaced) with
2252
- # a check that scans EVERY real file in $LOOPDIR and asserts its status is one of the documented
2253
- # ones, independent of which specific string it discovers first. This is what actually catches a
2254
- # status the module has never seen, and cannot silently skip -- an empty $LOOPDIR still passes
2255
- # vacuously (nothing to violate), but a non-empty one with an unrecognised status always fails.
2256
- # 'done'/'running' are the two non-breach terminals this module itself recognises; the
2257
- # five breach terminals come from M.CAP_BREACH_STATUSES directly, not a third hardcoded copy.
2258
- known_status_check=$(cj "
2259
- const fs = await import('node:fs');
2260
- const files = fs.readdirSync('$LOOPDIR').filter((f) => f.endsWith('.json'));
2261
- const known = new Set(['done', 'running', ...M.CAP_BREACH_STATUSES]);
2262
- const unknown = [];
2263
- for (const f of files) {
2264
- const o = JSON.parse(fs.readFileSync('$LOOPDIR/' + f, 'utf8'));
2265
- // F-236: bare membership missed the documented stopped-<reason> form -- go through
2266
- // capBreached() itself (it strips the prefix) rather than a second un-prefixed spelling.
2267
- if (!known.has(o.status) && M.capBreached(o) !== true) unknown.push(f + ':' + String(o.status));
2268
- }
2269
- process.stdout.write(unknown.length === 0 ? 'ALL_KNOWN' : unknown.join(','));
2270
- ")
2271
- check "every real loop-state file's status is in {done} ∪ CAP_BREACH_STATUSES ∪ {stopped-<reason> : reason ∈ CAP_BREACH_STATUSES} ∪ {running} ($LOOPDIR)" \
2272
- "$known_status_check" "ALL_KNOWN"
2273
- else
2274
- echo " (skipped: $LOOPDIR not present -- .somi/ is gitignored, this block only runs where real loop-state history is on disk)"
2275
- fi
2276
-
2277
- # --- Mutation testing: staged against COPIES of a real, COMMITTED loop-state file --
2278
- # never against the file itself, and never against inputs invented to be easy to pass. Runs
2279
- # unconditionally -- unlike the block above, this one does NOT read $LOOPDIR (these mutation tests
2280
- # used to read the same gitignored directory, so a "committed" claim was false; a
2281
- # contributor whose loop directory existed but lacked these two exact named files would also have
2282
- # hit an unhandled read failure on this block, the same shape of machine-dependence, just not the
2283
- # one a review happened to test). DONE_FIXTURE is `context-economy-overhaul.2.1.json`, committed
2284
- # verbatim (pass=2, status=done).
2285
- DONE_FIXTURE="$ROOT/tests/scripts/goldens/loop-state-done.json"
2286
- scratch=$(mktemp -d)
2287
-
2288
- check "mutation (wrong field name: pass -> passes) on a COPY of a real, committed loop-state file is caught" \
2289
- "$(cj "
2290
- const fs = await import('node:fs');
2291
- const obj = JSON.parse(fs.readFileSync('$DONE_FIXTURE', 'utf8'));
2292
- obj.passes = obj.pass; delete obj.pass;
2293
- fs.writeFileSync('$scratch/wrong-field.json', JSON.stringify(obj));
2294
- process.stdout.write(String(M.passesToApprove(JSON.parse(fs.readFileSync('$scratch/wrong-field.json', 'utf8')))));
2295
- ")" \
2296
- "null"
2297
- check "...the fixture itself was never touched by that mutation -- passesToApprove() on the original still returns 2" \
2298
- "$(cj "const fs = await import('node:fs'); process.stdout.write(String(M.passesToApprove(JSON.parse(fs.readFileSync('$DONE_FIXTURE', 'utf8')))));")" \
2299
- "2"
2300
-
2301
- check "mutation (swapped status string: done -> diff-cap-exceeded) on a COPY of a real, committed loop-state file is caught" \
2302
- "$(cj "
2303
- const fs = await import('node:fs');
2304
- const obj = JSON.parse(fs.readFileSync('$DONE_FIXTURE', 'utf8'));
2305
- obj.status = 'diff-cap-exceeded';
2306
- fs.writeFileSync('$scratch/swapped-status.json', JSON.stringify(obj));
2307
- process.stdout.write(String(M.capBreached(JSON.parse(fs.readFileSync('$scratch/swapped-status.json', 'utf8')))));
2308
- ")" \
2309
- "true"
2310
- check "...the fixture itself was never touched by that mutation -- capBreached() on the original still returns false" \
2311
- "$(cj "const fs = await import('node:fs'); process.stdout.write(String(M.capBreached(JSON.parse(fs.readFileSync('$DONE_FIXTURE', 'utf8')))));")" \
2312
- "false"
2313
-
2314
- rm -rf "$scratch"
2315
-
2316
- # --- tie-conditional Mann-Whitney U via Monte Carlo, with a real oracle -----------
2317
- # Two independent oracles, both required (an earlier self-referential oracle was rewritten twice and
2318
- # deleted once, so a self-referential check is not trusted here). Oracle 1: published small-n
2319
- # worked examples on UNTIED data, where the tie-conditional distribution this module computes and
2320
- # the classic exact distribution agree (sources cited below). Oracle 2: brute-force permutation
2321
- # enumeration on small TIED data (n1=n2=5 over {1,2,3}, C(10,5)=252 splits -- exhaustive, not
2322
- # sampled), computed HERE, independently of mannWhitneyU's own code.
2323
- MW=tests/evals/lib/mann-whitney.mjs
2324
- # optional 2nd arg overrides the import path (defaults to the real file) -- lets the
2325
- # mutation section below import a scratch COPY instead, without touching every existing call site.
2326
- mwj() { node --input-type=module -e "const M = await import('${2:-$ROOT/$MW}'); $1" 2>&1; }
2327
-
2328
- echo "== tie-conditional Mann-Whitney U (3.2) =="
2329
-
2330
- # --- input validation: throws, never guesses -- mirrors run.mjs's grade() "throws rather than
2331
- # grading" precedent (this file, ~line 40) applied to the new module. ---
2332
- for bad in "[], [1]" "[1], []" "[1,'a'], [1]" "[1], [NaN]" "[1], [Infinity]" "null, [1]" \
2333
- "[1], [1], {resamples:0}" "[1], [1], {resamples:-5}" "[1], [1], {resamples:1.5}" \
2334
- "[1], [1], {resamples:10000001}" "[1], [1], {rng: 5}"; do
2335
- got=$(mwj "try { M.mannWhitneyU($bad); process.stdout.write('NO THROW'); } catch (e) { process.stdout.write(e.constructor.name); }")
2336
- check "mannWhitneyU($bad) throws rather than guessing" "$got" "RangeError"
2337
- done
2338
- check "a valid, minimal call does not throw (the validation above doesn't also reject healthy input)" \
2339
- "$(mwj "try { M.mannWhitneyU([1],[2],{resamples:1000}); process.stdout.write('ok'); } catch (e) { process.stdout.write('THREW:'+e.constructor.name); }")" "ok"
2340
- # every probe above sits on the REJECTING side of both thresholds, so neither accepting
2341
- # edge (resamples===1, resamples===MAX_RESAMPLES) was ever exercised -- a >=-for-> slip and its
2342
- # <=-for-< mirror both passed all 333 checks, measured. Reads M.MAX_RESAMPLES, not a literal, so
2343
- # this can't drift if the cap is ever raised.
2344
- check "mannWhitneyU accepts BOTH true accepting edges: resamples===1 and resamples===MAX_RESAMPLES (F-216)" \
2345
- "$(mwj "
2346
- let ok1 = false, ok2 = false;
2347
- try { M.mannWhitneyU([1],[2],{resamples:1}); ok1 = true; } catch {}
2348
- try { M.mannWhitneyU([1],[2],{resamples:M.MAX_RESAMPLES}); ok2 = true; } catch {}
2349
- process.stdout.write(String(ok1 && ok2));
2350
- ")" "true"
2351
-
2352
- # --- the documented contract itself: resample count and its own stated MC-error formula ---
2353
- check "DEFAULT_RESAMPLES is exported as exactly 200000 (the 'low hundred-thousands' figure this file's own docstring commits to and derives its worst-case SE from)" \
2354
- "$(mwj "process.stdout.write(String(M.DEFAULT_RESAMPLES));")" "200000"
2355
- check "returned mcError matches sqrt(p*(1-p)/resamples) recomputed from the returned p -- the stated formula, not a different one" \
2356
- "$(mwj "
2357
- const r = M.mannWhitneyU([1,2,3,4,5], [2,3,4,5,6], {resamples: 20000});
2358
- const recomputed = Math.sqrt(r.p * (1 - r.p) / 20000);
2359
- process.stdout.write(String(Math.abs(r.mcError - recomputed) < 1e-12));
2360
- ")" "true"
2361
- check "p is bounded away from exact 0 (F-200 add-one correction)" "$(mwj "const r = M.mannWhitneyU(Array(15).fill(1), Array(15).fill(5), {resamples: 20000}); process.stdout.write(String(r.p === 1/20001 && r.mcError > 0));")" "true"
2362
- check "direction is one of the three documented states (A>B / B>A / tie)" \
2363
- "$(mwj "
2364
- const r = M.mannWhitneyU([1,2,3], [4,5,6], {resamples: 5000});
2365
- process.stdout.write(String(['A>B','B>A','tie'].includes(r.direction)));
2366
- ")" "true"
2367
- check "F-203: two mannWhitneyU calls seeded with the same mulberry32(seed) reproduce the identical p (replayable from stored arms)" \
2368
- "$(mwj "
2369
- const a = M.mannWhitneyU([1,2,3,4,5], [3,4,5,6,7], {resamples: 5000, rng: M.mulberry32(7)});
2370
- const b = M.mannWhitneyU([1,2,3,4,5], [3,4,5,6,7], {resamples: 5000, rng: M.mulberry32(7)});
2371
- process.stdout.write(String(a.p === b.p && a.U === b.U));
2372
- ")" "true"
2373
-
2374
- # --- Oracle 1: published worked examples on UNTIED data (known U and exact p from OUTSIDE this
2375
- # module). Tolerance is DERIVED from the resample count under test (the "stated tolerance"
2376
- # requirement), never loosened to fit: the Monte Carlo standard error of a resampled proportion is
2377
- # sqrt(p(1-p)/R); 5x that SE bounds a correct implementation's false-failure rate at ~5.7e-7
2378
- # (two-sided z), tight enough that the 1.5-3.6x conservative bias this test exists to rule out
2379
- # would clear it by roughly two orders of magnitude, not a near-miss.
2380
- ORACLE_RESAMPLES=200000
2381
-
2382
- # shared enumeration helpers -- u() the same rank-sum computation as rankSumU, combos() a
2383
- # k-combination generator, enumeratedP() "what fraction of every C(n,k) index-split is >= U",
2384
- # computed HERE, independently of mannWhitneyU. Oracle 2 originally defined its own copy of
2385
- # u()/combos() inline; shared here so oracle 1a/1b's cited p becomes p enumerated the same way,
2386
- # not a second (or third) off-machine number the acceptance checks below have to trust.
2387
- # run_mw_oracles() below deliberately does NOT reuse MW_ENUM -- it keeps its own cited
2388
- # trueP1/trueP2/0.5 so the mutation evidence stays independent of enumeratedP; the positive
2389
- # control that follows it is what pins those three numbers correct.
2390
- MW_ENUM='
2391
- function u(a,b){ let s=0; for (const bv of b) for (const av of a) { if (bv>av) s+=1; else if (bv===av) s+=0.5; } return s; }
2392
- function combos(n,k){ const res=[]; const idx=Array.from({length:k},(_,i)=>i); while (true) { res.push(idx.slice()); let i=k-1; while (i>=0 && idx[i]===n-k+i) i--; if (i<0) break; idx[i]++; for (let j=i+1;j<k;j++) idx[j]=idx[j-1]+1; } return res; }
2393
- function enumeratedP(a, b, observedU) {
2394
- const pool = a.concat(b), n1 = a.length, N = pool.length;
2395
- const subsets = combos(N, n1);
2396
- let extreme = 0;
2397
- for (const sub of subsets) {
2398
- const inA = new Set(sub);
2399
- const A = [], B = [];
2400
- for (let i = 0; i < N; i++) (inA.has(i) ? A : B).push(pool[i]);
2401
- if (u(A, B) >= observedU) extreme++;
2402
- }
2403
- return extreme / subsets.length;
2404
- }
2405
- '
2406
-
2407
- # Example 1 -- Hollander & Wolfe (1973), "Nonparametric Statistical Methods", pp. 27-33 & 68-75:
2408
- # permeability constants of the human chorioamnion, term (x) vs. 12-26wk gestation (y). This is
2409
- # the canonical worked example in R's own stats::wilcox.test() documentation (Examples section);
2410
- # the pooled 15 values are confirmed distinct (no ties). Exact U and one-sided p (x stochastically
2411
- # greater than y) independently cross-checked via SciPy 1.17.1's
2412
- # scipy.stats.mannwhitneyu(x, y, alternative='greater', method='exact') -- an unrelated,
2413
- # independently-implemented realization of Mann & Whitney's (1947) own exact null-distribution
2414
- # algorithm, not this module's code in any form: U=35, matching this module's own convention. Cited
2415
- # below only as C(15,5)=3003; the exact p itself is now enumerated in-suite, not cited --
2416
- # reusing MW_ENUM removes the only place this suite trusted an off-machine tool. armA is the
2417
- # smaller (y) arm, armB the larger (x) arm, matching this module's tested direction (armB
2418
- # stochastically greater than armA).
2419
- check "C(15,5) = 3003 (oracle 1a's own denominator, verified, not assumed)" \
2420
- "$(node -e "let r=1; for (let i=0;i<5;i++) r=r*(15-i)/(i+1); process.stdout.write(String(Math.round(r)));")" "3003"
2421
- check "oracle 1a (Hollander & Wolfe 1973 permeability data, untied): U matches exactly, p (enumerated over all C(15,5)=3003 splits, not cited) within 5x its own Monte Carlo SE" \
2422
- "$(mwj "$MW_ENUM
2423
- const armA = [1.15, 0.88, 0.90, 0.74, 1.21];
2424
- const armB = [0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64, 0.73, 1.46];
2425
- const r = M.mannWhitneyU(armA, armB, {resamples: $ORACLE_RESAMPLES});
2426
- const pExact = enumeratedP(armA, armB, r.U);
2427
- const tol = 5 * Math.sqrt(pExact * (1 - pExact) / $ORACLE_RESAMPLES);
2428
- process.stdout.write(String(r.U === 35 && Math.abs(r.p - pExact) <= tol));
2429
- ")" "true"
2430
-
2431
- # Example 2 -- Wikipedia, "Mann-Whitney U test", the tortoise/hare illustration: finishing order
2432
- # 'T H H H H H T T T T T H' (6 of each; a permutation of 1..12, no ties). Ascending finish-position
2433
- # values (1 = first place); tortoise as armB, hare as armA, exercising the same B-relative-to-A
2434
- # convention oracle 1a does. The article's own rank-sum arithmetic (32/46, its own reversed-rank
2435
- # convention) reproduces exactly as armA/armB's complementary pair (U_A+U_B=n1*n2=36, confirmed
2436
- # while sourcing this example). Exact one-sided p cross-checked the same way as example 1 (SciPy,
2437
- # method='exact'): U=25 (matching this module's convention); p enumerated in-suite, not
2438
- # cited -- see C(12,6)=924 below.
2439
- check "C(12,6) = 924 (oracle 1b's own denominator, verified, not assumed)" \
2440
- "$(node -e "let r=1; for (let i=0;i<6;i++) r=r*(12-i)/(i+1); process.stdout.write(String(Math.round(r)));")" "924"
2441
- check "oracle 1b (Wikipedia tortoise/hare, untied): U matches exactly, p (enumerated over all C(12,6)=924 splits, not cited) within 5x its own Monte Carlo SE" \
2442
- "$(mwj "$MW_ENUM
2443
- const armA = [2,3,4,5,6,12];
2444
- const armB = [1,7,8,9,10,11];
2445
- const r = M.mannWhitneyU(armA, armB, {resamples: $ORACLE_RESAMPLES});
2446
- const pExact = enumeratedP(armA, armB, r.U);
2447
- const tol = 5 * Math.sqrt(pExact * (1 - pExact) / $ORACLE_RESAMPLES);
2448
- process.stdout.write(String(r.U === 25 && Math.abs(r.p - pExact) <= tol));
2449
- ")" "true"
2450
-
2451
- # --- Oracle 2: brute-force permutation enumeration on small TIED data, computed OUTSIDE
2452
- # mannWhitneyU entirely -- the real oracle for the tie case, sharing none of the implementation's
2453
- # own assumptions. n1=n2=5 over {1,2,3}: C(10,5)=252, exhaustively enumerable (verified below, not
2454
- # assumed). armA=[1,1,2,3,3], armB=[1,2,2,3,3] -- ties both within and across arms, the shape the
2455
- # untied DP recursion (the rejected original method) cannot represent at all.
2456
- check "C(10,5) = 252 (oracle 2's own denominator, verified, not assumed)" \
2457
- "$(node -e "let r=1; for (let i=0;i<5;i++) r=r*(10-i)/(i+1); process.stdout.write(String(Math.round(r)));")" "252"
2458
-
2459
- MW_ORACLE2_SNIPPET="$MW_ENUM"'
2460
- const armA = [1,1,2,3,3];
2461
- const armB = [1,2,2,3,3];
2462
- const observedU = u(armA, armB);
2463
- const r = M.mannWhitneyU(armA, armB, {resamples: '"$ORACLE_RESAMPLES"'});
2464
- const pExact = enumeratedP(armA, armB, observedU);
2465
- const tol = 5 * Math.sqrt(pExact * (1 - pExact) / '"$ORACLE_RESAMPLES"');
2466
- process.stdout.write(String(r.U === observedU && Math.abs(r.p - pExact) <= tol));
2467
- '
2468
- check "oracle 2 (brute-force enumeration, n1=n2=5 over {1,2,3}, all 252 splits): U matches exactly, p within 5x its own Monte Carlo SE of the enumerated exact p" \
2469
- "$(mwj "$MW_ORACLE2_SNIPPET")" "true"
2470
-
2471
- # --- Mutation testing: staged against a COPY of mann-whitney.mjs, never the tracked
2472
- # file itself (following the earlier precedent -- "staged against COPIES ...
2473
- # never against the files themselves"). Both mutants are part of the acceptance
2474
- # criterion, each confirmed caught by re-implementations of all three oracles above (
2475
- # deliberately independent of MW_ENUM's enumeratedP), not by a case the implementation was written
2476
- # to satisfy. mwj's optional path argument (above) is what makes this a one-line change per call
2477
- # site: the scratch copy is mutated and imported directly, so the real file is never written.
2478
- MW_SCRATCH_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
2479
- MW_SCRATCH="$MW_SCRATCH_DIR/mann-whitney.mjs"
2480
- cp "$ROOT/$MW" "$MW_SCRATCH"
2481
- trap 'rm -rf "$MW_SCRATCH_DIR"' EXIT
2482
-
2483
- run_mw_oracles() {
2484
- # returns 'ok1/ok2/ok3', not ok1&&ok2&&ok3 -- a conjunction can't tell "one oracle caught
2485
- # it" from "all three did", and the acceptance requires catching by more than a single check.
2486
- # $1 (optional): import path, forwarded to mwj -- defaults to the real, unmutated file.
2487
- mwj "
2488
- const armA1 = [1.15, 0.88, 0.90, 0.74, 1.21];
2489
- const armB1 = [0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64, 0.73, 1.46];
2490
- const r1 = M.mannWhitneyU(armA1, armB1, {resamples: $ORACLE_RESAMPLES});
2491
- const trueP1 = 382 / 3003;
2492
- const ok1 = r1.U === 35 && Math.abs(r1.p - trueP1) <= 5 * Math.sqrt(trueP1 * (1 - trueP1) / $ORACLE_RESAMPLES);
2493
-
2494
- const armA2 = [2,3,4,5,6,12];
2495
- const armB2 = [1,7,8,9,10,11];
2496
- const r2 = M.mannWhitneyU(armA2, armB2, {resamples: $ORACLE_RESAMPLES});
2497
- const trueP2 = 13 / 84;
2498
- const ok2 = r2.U === 25 && Math.abs(r2.p - trueP2) <= 5 * Math.sqrt(trueP2 * (1 - trueP2) / $ORACLE_RESAMPLES);
2499
-
2500
- const armA3 = [1,1,2,3,3];
2501
- const armB3 = [1,2,2,3,3];
2502
- const r3 = M.mannWhitneyU(armA3, armB3, {resamples: $ORACLE_RESAMPLES});
2503
- const ok3 = r3.U === 14 && Math.abs(r3.p - 0.5) <= 5 * Math.sqrt(0.5 * 0.5 / $ORACLE_RESAMPLES);
2504
-
2505
- process.stdout.write(ok1 + '/' + ok2 + '/' + ok3);
2506
- " "${1:-}"
2507
- }
2508
-
2509
- # positive control -- without this, any harness failure (a drifted literal, a typo in
2510
- # armA3, a changed default) would leave both mutant checks reading "false/false/false" and
2511
- # passing, indistinguishable from a real catch.
2512
- check "positive control: pristine mann-whitney.mjs passes all three oracles" "$(run_mw_oracles)" "true/true/true"
2513
-
2514
- # Mutant 1 -- off-by-one in the resampling logic: the B-side loop starts one index late, silently
2515
- # dropping one pooled element from every resample's B side (a realistic single-character-shift
2516
- # bug: 'n1' -> 'n1 + 1'). The resampled-A subset is still drawn correctly; only which indices count
2517
- # toward B's side of U is wrong.
2518
- node -e "
2519
- const fs = require('fs');
2520
- const p = '$MW_SCRATCH';
2521
- const s = fs.readFileSync(p, 'utf8');
2522
- const FROM = 'for (let bi = n1; bi < N; bi++) {';
2523
- const TO = 'for (let bi = n1 + 1; bi < N; bi++) {';
2524
- if (!s.includes(FROM)) throw new Error('mutant 1 pattern not found in $MW_SCRATCH -- source moved, update this mutation');
2525
- fs.writeFileSync(p, s.replace(FROM, TO));
2526
- "
2527
- check "mutant 1 (off-by-one: B-side resample loop starts at n1+1, dropping one element) fails all three oracles (ok1/ok2/ok3)" \
2528
- "$(run_mw_oracles "$MW_SCRATCH")" "false/false/false"
2529
- cp "$ROOT/$MW" "$MW_SCRATCH" # reset the scratch copy to pristine before mutant 2
2530
-
2531
- # Mutant 2 -- sampling WITH replacement instead of without: the exact defect an earlier
2532
- # review named ('a bootstrap-with-replacement resampler').
2533
- # Breaks tie-conditioning entirely -- every comparison draws independently from the full pool,
2534
- # rather than resampling a fixed n1/n2 split of the pool's actual indices.
2535
- node -e "
2536
- const fs = require('fs');
2537
- const p = '$MW_SCRATCH';
2538
- const s = fs.readFileSync(p, 'utf8');
2539
- const FROM = [
2540
- ' for (let i = 0; i < n1; i++) {',
2541
- ' const j = i + Math.floor(rng() * (N - i));',
2542
- ' const tmp = idx[i]; idx[i] = idx[j]; idx[j] = tmp;',
2543
- ' }',
2544
- ' let uSample = 0;',
2545
- ' for (let bi = n1; bi < N; bi++) {',
2546
- ' const bv = pool[idx[bi]];',
2547
- ' for (let ai = 0; ai < n1; ai++) {',
2548
- ' const av = pool[idx[ai]];',
2549
- ' if (bv > av) uSample += 1;',
2550
- ' else if (bv === av) uSample += 0.5;',
2551
- ' }',
2552
- ' }',
2553
- ].join('\n');
2554
- const TO = [
2555
- ' let uSample = 0;',
2556
- ' for (let bi = 0; bi < n2; bi++) {',
2557
- ' const bv = pool[Math.floor(rng() * N)];',
2558
- ' for (let ai = 0; ai < n1; ai++) {',
2559
- ' const av = pool[Math.floor(rng() * N)];',
2560
- ' if (bv > av) uSample += 1;',
2561
- ' else if (bv === av) uSample += 0.5;',
2562
- ' }',
2563
- ' }',
2564
- ].join('\n');
2565
- if (!s.includes(FROM)) throw new Error('mutant 2 pattern not found in $MW_SCRATCH -- source moved, update this mutation');
2566
- fs.writeFileSync(p, s.replace(FROM, TO));
2567
- "
2568
- check "mutant 2 (sampling WITH replacement -- does not condition on the observed multiset) fails all three oracles (ok1/ok2/ok3)" \
2569
- "$(run_mw_oracles "$MW_SCRATCH")" "false/false/false"
2570
-
2571
- # repeat the positive control against the TRACKED file (no path arg -> mwj's default)
2572
- # after both mutants -- closes the gap where a leaked write to the real file would silently
2573
- # propagate through the next mutant's `cp` reset instead of being caught.
2574
- check "positive control (after mutation): the tracked module is still pristine" "$(run_mw_oracles)" "true/true/true"
2575
-
2576
- # the check above is what pins "the real file was never written", not an argument for it;
2577
- # only $MW_SCRATCH was ever mutated. Cleanup: bash's `trap` for a signal REPLACES the handler, it
2578
- # does not append -- so this registration alone would not survive
2579
- # CVD_SCRATCH_DIR's own `trap` call below (:~2610), which is why THAT later registration names
2580
- # BOTH scratch dirs rather than just its own, and is pinned by its own "names both" check right
2581
- # after it. The combined trap removes both on any normal exit, including SIGINT/SIGTERM (a
2582
- # SIGKILL bypasses any trap, leaking the scratch dir -- not the tracked file).
2583
-
2584
- # --- convergence gate DRIVER. The module is split along its own section divider:
2585
- # classifyDraw, fillArm, safeCleanup; compareArms, estimatePower, runComparison; and
2586
- # loopShardPath/resumeArm/prepareDrawDir/startDraw/drawArmForSha -- the resume/namespace layer and
2587
- # the live-draw mechanism (the workDir-contract and resume-gap checks). Hermetic throughout: every case below is a direct function call against
2588
- # synthetic/injected input, or a setup-only seam (prepareDrawDir), never a live /code-loop
2589
- # invocation (the full driver is run against the model for real only in a live batch).
2590
- CVD=tests/evals/convergence.mjs
2591
- cvj() { node --input-type=module -e "const M = await import('${2:-$ROOT/$CVD}'); $1" 2>&1; }
2592
-
2593
- echo "== convergence gate driver, classification + arm-filling + comparison/verdict + shards/live-draw (3.3a+3.3b+3.3c) =="
2594
-
2595
- # --- point 4 (first half): N_PER_ARM pinned as a literal, independent of any draw outcome -------
2596
- check "N_PER_ARM is exactly 15" "$(cvj "process.stdout.write(String(M.N_PER_ARM));")" "15"
2597
- # REGRESSION_SHIFT pinned as a literal too, same discipline -- the functional pin (does the
2598
- # margin actually BITE at 0.5 and not at 1) lives further down, after the mutation-testing section,
2599
- # since it needs $CVD_SCRATCH's revert-and-reassert idiom, not just a value read.
2600
- check "REGRESSION_SHIFT is exactly 0.5 (D16)" "$(cvj "process.stdout.write(String(M.REGRESSION_SHIFT));")" "0.5"
2601
-
2602
- # --- point 5: classifyDraw distinguishes breach / done / running / malformed -- the two null
2603
- # causes told apart, not conflated under one null-means-skip catch-all --------------------
2604
- check "classifyDraw: a documented breach status is 'breach'" \
2605
- "$(cvj "process.stdout.write(M.classifyDraw({status:'max-passes-exceeded', pass:6}).kind);")" "breach"
2606
- check "classifyDraw: the SAME breach status written with commands/code-loop.md's documented 'stopped-<reason>' finish-path prefix is ALSO 'breach', not malformed/undetermined (F-235)" \
2607
- "$(cvj "process.stdout.write(M.classifyDraw({status:'stopped-max-passes-exceeded', pass:6}).kind);")" "breach"
2608
- check "classifyDraw: status:done with a real pass field is 'done'" \
2609
- "$(cvj "process.stdout.write(M.classifyDraw({status:'done', pass:2}).kind);")" "done"
2610
- check "classifyDraw: status:running is 'running' -- 'not done != breached', distinct from malformed" \
2611
- "$(cvj "process.stdout.write(M.classifyDraw({status:'running', pass:1}).kind);")" "running"
2612
- check "classifyDraw: an unrecognised status is 'malformed', distinct from 'running' (closes F-184)" \
2613
- "$(cvj "process.stdout.write(M.classifyDraw({status:'pending'}).kind);")" "malformed"
2614
- check "classifyDraw(null) is 'malformed'" "$(cvj "process.stdout.write(M.classifyDraw(null).kind);")" "malformed"
2615
- check "classifyDraw: status:done with an unreadable pass field is 'malformed', never silently 'done'" \
2616
- "$(cvj "process.stdout.write(M.classifyDraw({status:'done', pass:'x'}).kind);")" "malformed"
2617
-
2618
- # --- commands/code-loop.md
2619
- # :136 documents `--status stopped-<reason>` as the STOP path's write; lib/convergence.mjs's
2620
- # capBreached() matched only the bare <reason> forms, so a cap-breach recorded through the
2621
- # DOCUMENTED path read null ("undetermined"), not true -- and classifyDraw() above inherited the
2622
- # hole, since it calls capBreached() directly rather than re-matching status itself. Discovered by
2623
- # the first status:"stopped-*" file this corpus ever produced: every real file before it was
2624
- # `done` or `running`, so this branch had never fired against real data. The two checks above
2625
- # already pin classifyDraw()'s own behaviour on the tracked module; this pins capBreached() itself,
2626
- # mutation-verified, against a SCRATCH COPY of lib/convergence.mjs -- never the tracked file, and
2627
- # never through the CVD_SCRATCH/lib symlink below (that symlink points at the REAL lib/ dir, so
2628
- # mutating through it would mutate the repo's own source, not a copy).
2629
- lib_conv_scratch=$(mktemp -d)
2630
- cp "$ROOT/tests/evals/lib/convergence.mjs" "$lib_conv_scratch/convergence.mjs"
2631
- libj() { node --input-type=module -e "const M = await import('$lib_conv_scratch/convergence.mjs'); $1" 2>&1; }
2632
- check "capBreached: the bare reason and commands/code-loop.md's documented stopped-<reason> form both return true (F-235)" \
2633
- "$(libj "process.stdout.write(String(M.capBreached({status:'max-passes-exceeded'})) + '/' + String(M.capBreached({status:'stopped-max-passes-exceeded'})));")" \
2634
- "true/true"
2635
- # Anchor text updated: the strip this mutant targets moved into its own
2636
- # `stripStoppedPrefix()` helper, shared with breachReason() -- the anchor's own resilience covers a
2637
- # change to lines AROUND it, not a change WITHIN the exact line it matches, so this needed a manual
2638
- # update (the SAME "additive field collided with an existing anchor" shape Mutant B
2639
- # already hit once -- caught here by running the suite, not by inspection).
2640
- # Occurrence-count guard adopted while already touching this anchor.
2641
- node -e "
2642
- const fs = require('fs'); const p = '$lib_conv_scratch/convergence.mjs'; const s = fs.readFileSync(p, 'utf8');
2643
- const FROM = 'const reason = stripStoppedPrefix(status);\n if (CAP_BREACH_STATUSES.has(reason)) return true;';
2644
- const TO = 'const reason = status; // MUTANT (F-235): stopped- prefix stripping removed\n if (CAP_BREACH_STATUSES.has(reason)) return true;';
2645
- const count = s.split(FROM).length - 1;
2646
- if (count !== 1) throw new Error('F-235 mutant anchor occurs ' + count + ' time(s), not exactly 1 in lib/convergence.mjs -- source moved, update this mutation');
2647
- fs.writeFileSync(p, s.replace(FROM, TO));
2648
- "
2649
- check "mutant (F-235: stopped- prefix stripping removed) is caught -- the documented stopped-<reason> form reads null again, the bare form is unaffected" \
2650
- "$(libj "process.stdout.write(String(M.capBreached({status:'stopped-max-passes-exceeded'})) + '/' + String(M.capBreached({status:'max-passes-exceeded'})));")" \
2651
- "null/true"
2652
- rm -rf "$lib_conv_scratch"
2653
-
2654
- # --- staged against a COMMITTED fixture, not a live-directory
2655
- # scan -- the scan below is now an opportunistic supplement, never this assertion's only subject.
2656
- # BREACH_FIXTURE is eval-corpus-rebuild.3.3.json, committed verbatim (status:"stopped-user-stop",
2657
- # the DOCUMENTED stop-path write form, closed to that form via the real `somi-loop.mjs finish`
2658
- # command not a hand-edit). Runs unconditionally -- in CI and on every
2659
- # contributor's machine, regardless of whether $LOOPDIR exists or holds a stopped-* file, which is
2660
- # almost none of them. Anchored to a re-runnable
2661
- # command rather than a snapshot count, since a snapshot goes stale as this corpus grows on its own
2662
- # -- this line's earlier "36 of 37" (files NOT stopped-*) already read "37 of 38" one iteration
2663
- # later. The command below reproduces the RARE side of that instead -- a stopped-*
2664
- # file, which is 1 of this repo's own 39 today. Reproduce with:
2665
- # node -e "const fs=require('fs'),d='.somi/somi-state/loop';const f=fs.readdirSync(d)
2666
- # .filter(x=>x.endsWith('.json'));let n=0;for(const x of f){try{if(/^stopped-/.test(
2667
- # JSON.parse(fs.readFileSync(d+'/'+x,'utf8')).status))n++}catch{}}console.log(n+'/'+f.length)"
2668
- # not self-selecting -- the subject is a FIXED committed file, not one discovered by the
2669
- # predicate under test, and the raw `status` string is asserted alongside `kind` rather than only
2670
- # the classifier's own output.
2671
- BREACH_FIXTURE="$ROOT/tests/scripts/goldens/loop-state-breach.json"
2672
- check "classifyDraw on the committed cap-breach fixture is 'breach', raw status is the documented stopped-<reason> form (F-241/F-242)" \
2673
- "$(cvj "
2674
- const fs = await import('node:fs');
2675
- const o = JSON.parse(fs.readFileSync('$BREACH_FIXTURE', 'utf8'));
2676
- process.stdout.write(M.classifyDraw(o).kind + '/' + o.status);
2677
- ")" "breach/stopped-user-stop"
2678
-
2679
- LOOPDIR=".somi/somi-state/loop"
2680
- if [ -d "$ROOT/$LOOPDIR" ]; then
2681
- # the per-file parse below is wrapped in its OWN try/catch, not
2682
- # left to `cvj`'s outer 2>&1 capture -- one unparseable .json (a file killed mid-write) used to
2683
- # throw out of JSON.parse, and the captured stack trace (non-empty) then satisfied `[ -n "$var" ]`
2684
- # below, so the following check tried to read a FILE NAMED BY THE STACK TRACE and failed loudly on
2685
- # the wrong thing. A malformed file is skipped here exactly like an unreadable one -- this scan is
2686
- # an opportunistic supplement and must degrade gracefully on corruption, not just absence.
2687
- running_real=$(cvj "
2688
- const fs = await import('node:fs');
2689
- const files = fs.readdirSync('$ROOT/$LOOPDIR').filter((f) => f.endsWith('.json'));
2690
- let found = '';
2691
- for (const f of files) {
2692
- let o;
2693
- try { o = JSON.parse(fs.readFileSync('$ROOT/$LOOPDIR/' + f, 'utf8')); } catch { continue; }
2694
- if (o.status === 'running') { found = f; break; }
2695
- }
2696
- process.stdout.write(found);
2697
- ")
2698
- if [ -n "$running_real" ]; then
2699
- check "classifyDraw on a real, currently-running loop-state file is 'running' ($running_real)" \
2700
- "$(cvj "const fs = await import('node:fs'); process.stdout.write(M.classifyDraw(JSON.parse(fs.readFileSync('$ROOT/$LOOPDIR/$running_real', 'utf8'))).kind);")" "running"
2701
- else
2702
- echo " (skipped: no real status:\"running\" loop-state file on disk right now)"
2703
- fi
2704
- # Opportunistic supplement to the committed fixture above, not a replacement for it.
2705
- # SELF-SELECTING, same shape running_real's own comment names above -- discovers by
2706
- # the exact predicate (classifyDraw(...).kind === 'breach') it then asserts. An over-admitting
2707
- # classifyDraw would pass this alone; the committed fixture's raw-status assertion is the one
2708
- # that cannot be fooled that way. Degrades gracefully (skips, never fails) when absent OR
2709
- # malformed (same fix as running_real above -- the per-file parse gets its own try/catch
2710
- # rather than relying on `.find()`'s single expression to short-circuit on a thrown parse).
2711
- breach_real=$(cvj "
2712
- const fs = await import('node:fs');
2713
- const files = fs.readdirSync('$ROOT/$LOOPDIR').filter((f) => f.endsWith('.json'));
2714
- let found = '';
2715
- for (const f of files) {
2716
- let o;
2717
- try { o = JSON.parse(fs.readFileSync('$ROOT/$LOOPDIR/' + f, 'utf8')); } catch { continue; }
2718
- if (M.classifyDraw(o).kind === 'breach') { found = f; break; }
2719
- }
2720
- process.stdout.write(found);
2721
- ")
2722
- if [ -n "$breach_real" ]; then
2723
- check "classifyDraw on a real cap-breach loop-state file is 'breach' ($breach_real)" \
2724
- "$(cvj "const fs = await import('node:fs'); process.stdout.write(M.classifyDraw(JSON.parse(fs.readFileSync('$ROOT/$LOOPDIR/$breach_real', 'utf8'))).kind);")" "breach"
2725
- else
2726
- echo " (skipped: no real cap-breach loop-state file on disk right now -- the committed fixture above already covers this branch)"
2727
- fi
2728
- else
2729
- echo " (skipped: $LOOPDIR not present)"
2730
- fi
2731
-
2732
- # Staged on a COPY of a real, COMMITTED loop-state file (the scorer discipline),
2733
- # unconditional for the same reason the mutation tests above are (DONE_FIXTURE, set
2734
- # there, is reused rather than redefined).
2735
- cvd_scratch=$(mktemp -d)
2736
- check "mutation (status: done -> pemding, an unrecognised near-miss) on a COPY is malformed, not silently done" \
2737
- "$(cvj "
2738
- const fs = await import('node:fs');
2739
- const obj = JSON.parse(fs.readFileSync('$DONE_FIXTURE', 'utf8'));
2740
- obj.status = 'pemding';
2741
- fs.writeFileSync('$cvd_scratch/typo-status.json', JSON.stringify(obj));
2742
- process.stdout.write(M.classifyDraw(JSON.parse(fs.readFileSync('$cvd_scratch/typo-status.json', 'utf8'))).kind);
2743
- ")" "malformed"
2744
- check "...the fixture itself was never touched -- classifyDraw on the original is still 'done'" \
2745
- "$(cvj "const fs = await import('node:fs'); process.stdout.write(M.classifyDraw(JSON.parse(fs.readFileSync('$DONE_FIXTURE', 'utf8'))).kind);")" "done"
2746
- rm -rf "$cvd_scratch"
2747
-
2748
- # --- fillArm: draw policy (point 4, second half; point 5 at the arm level) -----------------------
2749
- # seq[i] is the state sequence one draw handle steps through on successive retry()s; a fresh
2750
- # newDraw() call advances to the next slot's sequence -- a REPLACEMENT, never a revisit.
2751
- CVD_HELPERS='
2752
- function mkSeqDraw(seq) {
2753
- let i = 0;
2754
- return () => {
2755
- const states = seq[i++]; let idx = 0;
2756
- return { read: () => states[idx], retry: () => { idx = Math.min(idx + 1, states.length - 1); } };
2757
- };
2758
- }
2759
- '
2760
- check "fillArm: a running draw is waited on and RE-READ from the SAME handle (retry), never replaced" \
2761
- "$(cvj "$CVD_HELPERS
2762
- const r = M.fillArm(mkSeqDraw([[{status:'running'}, {status:'done', pass:3}]]), { n: 1, report: () => {} });
2763
- process.stdout.write(JSON.stringify({ arm: r.arm, stillRunning: r.stillRunning, replaced: r.replaced }));
2764
- ")" '{"arm":[3],"stillRunning":1,"replaced":0}'
2765
- check "fillArm: a malformed draw is discarded and REPLACED with a fresh handle, reported loudly" \
2766
- "$(cvj "$CVD_HELPERS
2767
- let reports = 0;
2768
- const r = M.fillArm(mkSeqDraw([[{status:'bogus'}], [{status:'done', pass:2}]]), { n: 1, report: () => { reports++; } });
2769
- process.stdout.write(JSON.stringify({ arm: r.arm, replaced: r.replaced, reports }));
2770
- ")" '{"arm":[2],"replaced":1,"reports":1}'
2771
- check "fillArm: exhausting the wait budget STOPS filling -- the slot is left unfilled, not topped up (F-194)" \
2772
- "$(cvj "$CVD_HELPERS
2773
- const seq = [[{status:'running'}, {status:'running'}, {status:'running'}], [{status:'done', pass:1}]];
2774
- const r = M.fillArm(mkSeqDraw(seq), { n: 2, maxWaitAttempts: 1, report: () => {} });
2775
- process.stdout.write(JSON.stringify({ breach: r.breach, arm: r.arm, waitExhausted: r.waitExhausted }));
2776
- ")" '{"breach":false,"arm":[],"waitExhausted":true}'
2777
- check "fillArm: a breach fails the WHOLE arm outright, even after usable draws were already collected" \
2778
- "$(cvj "$CVD_HELPERS
2779
- const seq = [[{status:'done', pass:1}], [{status:'max-passes-exceeded', pass:6}]];
2780
- const r = M.fillArm(mkSeqDraw(seq), { n: 2, report: () => {} });
2781
- process.stdout.write(JSON.stringify({ breach: r.breach, arm: r.arm }));
2782
- ")" '{"breach":true,"arm":[1]}'
2783
-
2784
- # --- fillArm()'s breach branch threads the SPECIFIC cap-breach
2785
- # reason, not just the boolean above -- before this change, all five CAP_BREACH_STATUSES read
2786
- # identically as {breach:true}, undiagnosable downstream. The literal acceptance
2787
- # wording, restated as its own named check: a stubbed loop-state carrying the documented
2788
- # stopped-<reason> finish form surfaces the BARE reason on fillArm()'s return.
2789
- check "fillArm: breachReason is threaded through on a breach -- stopped-max-passes-exceeded surfaces as the bare 'max-passes-exceeded' (D6, phase file's own acceptance wording)" \
2790
- "$(cvj "$CVD_HELPERS
2791
- const r = M.fillArm(mkSeqDraw([[{status:'stopped-max-passes-exceeded', pass:6}]]), { n: 1, report: () => {} });
2792
- process.stdout.write(String(r.breachReason));
2793
- ")" "max-passes-exceeded"
2794
- check "fillArm: same, for diff-cap-exceeded (the phase file's second named example)" \
2795
- "$(cvj "$CVD_HELPERS
2796
- const r = M.fillArm(mkSeqDraw([[{status:'stopped-diff-cap-exceeded', pass:2}]]), { n: 1, report: () => {} });
2797
- process.stdout.write(String(r.breachReason));
2798
- ")" "diff-cap-exceeded"
2799
- # All five, not just the two named by example (the gap that kept being found) -- both the bare and the documented stopped-<reason> form, driven end-to-end
2800
- # through fillArm() itself, not just the lib extractor tested above. Reuses BREACH_STATUSES,
2801
- # derived earlier from the module's own CAP_BREACH_STATUSES.
2802
- for s in "${BREACH_STATUSES[@]}"; do
2803
- check "fillArm: breachReason is '$s' on a bare '$s' breach status" \
2804
- "$(cvj "$CVD_HELPERS
2805
- const r = M.fillArm(mkSeqDraw([[{status:'$s', pass:9}]]), { n: 1, report: () => {} });
2806
- process.stdout.write(String(r.breachReason));
2807
- ")" "$s"
2808
- check "fillArm: breachReason is the bare '$s' on a stopped-$s breach status (F-235 finish form)" \
2809
- "$(cvj "$CVD_HELPERS
2810
- const r = M.fillArm(mkSeqDraw([[{status:'stopped-$s', pass:9}]]), { n: 1, report: () => {} });
2811
- process.stdout.write(String(r.breachReason));
2812
- ")" "$s"
2813
- done
2814
- # Additive field, always present (same "absent vs null vs present" convention run.verdict/
2815
- # run.terminal/fixture already established) -- breachReason reads null, not absent/undefined, on
2816
- # every NON-breach terminal path, so a caller never needs an `in` check before reading it.
2817
- check "fillArm: breachReason is null (not absent/undefined) on the wait-exhausted path -- additive field, always present" \
2818
- "$(cvj "$CVD_HELPERS
2819
- const seq = [[{status:'running'}, {status:'running'}], [{status:'done', pass:1}]];
2820
- const r = M.fillArm(mkSeqDraw(seq), { n: 2, maxWaitAttempts: 1, report: () => {} });
2821
- process.stdout.write(JSON.stringify({ has: 'breachReason' in r, value: r.breachReason }));
2822
- ")" '{"has":true,"value":null}'
2823
- check "fillArm: breachReason is null on a clean, fully-filled successful arm" \
2824
- "$(cvj "$CVD_HELPERS
2825
- const r = M.fillArm(mkSeqDraw([[{status:'done', pass:2}]]), { n: 1, report: () => {} });
2826
- process.stdout.write(JSON.stringify({ has: 'breachReason' in r, value: r.breachReason }));
2827
- ")" '{"has":true,"value":null}'
2828
- # --- Ordering: this handle's read() THROWS if ever called again after cleanup() -- if a future
2829
- # edit recomputed breachReason from a fresh draw.read() post-cleanup instead of the already-in-
2830
- # memory `state` local, THIS check fails loudly (an uncaught throw corrupts cvj's captured stdout,
2831
- # which then fails to match), not silently. Detects exactly ONE failure mode -- a fresh read()
2832
- # issued after cleanup() -- not a reorder that still uses the cached `state` local with no read()
2833
- # call at all; nothing in fillArm() itself makes that second reorder impossible (the prior name here claimed "by construction", a guarantee the mechanism doesn't
2834
- # deliver). Mutant F below stages that exact reorder against a REAL startDraw()-shaped handle and
2835
- # is the strongest available check for it short of a refactor.
2836
- check "fillArm: breachReason is derived from the ALREADY-READ state, never a fresh read() issued after cleanup() -- the reason is never read from a spent handle: a post-cleanup read() throws" \
2837
- "$(cvj "
2838
- function mkOrderedBreachDraw(status) {
2839
- let cleaned = false;
2840
- const state = { status, pass: 4 };
2841
- return () => ({
2842
- read: () => { if (cleaned) throw new Error('read() called after cleanup() -- ordering violated'); return state; },
2843
- retry: () => {},
2844
- cleanup: () => { cleaned = true; },
2845
- });
2846
- }
2847
- const r = M.fillArm(mkOrderedBreachDraw('circuit-breaker'), { n: 1, report: () => {} });
2848
- process.stdout.write(String(r.breachReason));
2849
- ")" "circuit-breaker"
2850
-
2851
- # 3.3c: startDraw() is the FIRST real cleanup() a draw handle ever carries (mkSeqDraw above has
2852
- # none, so safeCleanup()'s `draw.cleanup?.()` was a silent no-op in every fillArm test above --
2853
- # none of them could have caught a recurrence). This is the seam that matters now that a real,
2854
- # disk-touching cleanup exists to actually leave uncalled: 1.7 MB / 187 files per draw, ~51 MB per
2855
- # certification. Verified on all four terminal paths a single draw
2856
- # can end on, not just the two (done/malformed) the existing reports/replaced assertions above
2857
- # already exercise indirectly.
2858
- CVD_HELPERS_CLEANUP='
2859
- function mkTrackedDraw(seq) {
2860
- let i = 0; const calls = [];
2861
- const next = () => {
2862
- const states = seq[i]; let idx = 0; const mine = i; i++;
2863
- return { read: () => states[idx], retry: () => { idx = Math.min(idx + 1, states.length - 1); }, cleanup: () => calls.push(mine) };
2864
- };
2865
- next.calls = calls;
2866
- return next;
2867
- }
2868
- '
2869
- check "fillArm calls the draw handle's cleanup() on EVERY terminal path -- breach/done/malformed/wait-exhausted, not just the two the arm-content assertions above already imply (F-226, closed against a REAL cleanup() for the first time now that startDraw provides one)" \
2870
- "$(cvj "$CVD_HELPERS_CLEANUP
2871
- const breachDraw = mkTrackedDraw([[{status:'max-passes-exceeded', pass:6}]]);
2872
- M.fillArm(breachDraw, { n: 1, report: () => {} });
2873
- const doneDraw = mkTrackedDraw([[{status:'done', pass:2}]]);
2874
- M.fillArm(doneDraw, { n: 1, report: () => {} });
2875
- const malformedDraw = mkTrackedDraw([[{status:'bogus'}], [{status:'done', pass:2}]]);
2876
- M.fillArm(malformedDraw, { n: 1, report: () => {} });
2877
- const waitExhaustedDraw = mkTrackedDraw([[{status:'running'}, {status:'running'}]]);
2878
- M.fillArm(waitExhaustedDraw, { n: 1, maxWaitAttempts: 1, report: () => {} });
2879
- process.stdout.write(JSON.stringify({
2880
- breach: breachDraw.calls.length, done: doneDraw.calls.length,
2881
- malformed: malformedDraw.calls.length, waitExhausted: waitExhaustedDraw.calls.length,
2882
- }));
2883
- ")" '{"breach":1,"done":1,"malformed":2,"waitExhausted":1}'
2884
-
2885
- # --- point 3: a cap-breach fails the WHOLE comparison outright, independent of the p-value -------
2886
- check "runComparison: a breach in the CANDIDATE arm fails outright, regardless of the baseline's own values" \
2887
- "$(cvj "$CVD_HELPERS
2888
- const bl = [[{status:'done',pass:1}],[{status:'done',pass:1}],[{status:'done',pass:1}]];
2889
- const cd = [[{status:'done',pass:1}],[{status:'max-passes-exceeded',pass:6}]];
2890
- const r = M.runComparison(mkSeqDraw(bl), mkSeqDraw(cd), { n: 3, report: () => {} });
2891
- process.stdout.write(JSON.stringify({ verdict: r.verdict, breachArm: r.breachArm }));
2892
- ")" '{"verdict":"cap-breach","breachArm":"candidate"}'
2893
- check "runComparison: a breach in the BASELINE arm fails outright -- the candidate is never even drawn" \
2894
- "$(cvj "$CVD_HELPERS
2895
- let candidateDrawn = false;
2896
- const newCandidate = () => { candidateDrawn = true; return mkSeqDraw([[{status:'done',pass:1}]])(); };
2897
- const r = M.runComparison(mkSeqDraw([[{status:'max-passes-exceeded',pass:6}]]), newCandidate, { n: 1, report: () => {} });
2898
- process.stdout.write(JSON.stringify({ verdict: r.verdict, breachArm: r.breachArm, candidateDrawn }));
2899
- ")" '{"verdict":"cap-breach","breachArm":"baseline","candidateDrawn":false}'
2900
- check "runComparison: insufficient-draws (point 4) on a realized shortfall, measured on the actual array, not the requested count" \
2901
- "$(cvj "$CVD_HELPERS
2902
- const bl = [[{status:'running'},{status:'running'},{status:'running'}]];
2903
- const cd = [[{status:'done',pass:2}],[{status:'done',pass:2}]];
2904
- const r = M.runComparison(mkSeqDraw(bl), mkSeqDraw(cd), { n: 2, maxWaitAttempts: 1, report: () => {} });
2905
- process.stdout.write(JSON.stringify({ verdict: r.verdict, deficit: r.deficit }));
2906
- ")" '{"verdict":"insufficient-draws","deficit":{"baseline":2,"candidate":0}}'
2907
- # --- point 6: every OTHER check in this suite bounds a
2908
- # false ACCEPT; none bounded a false BLOCK. A one-line mutant (`verdict = 'inconclusive'` always)
2909
- # passed points 1/2/4/5 AND the old membership assertion below, improving point 2 to 0.0000. Two
2910
- # assertions close it -- the first is this rewritten check itself.
2911
- # margin change (REGRESSION_SHIFT 1 -> 0.5): checked, not assumed -- this arm is TWO constant arms (every
2912
- # draw pass:2), so `shifted` is also constant, strictly less than `baseline` for ANY positive
2913
- # shift; the tie-conditional rank test only sees a fully-separated ordering, which is identical at
2914
- # shift=0.5 and shift=1 (verified directly: equivalence.p is bit-identical, 0.0002, at both). This
2915
- # check is margin-INVARIANT by construction, not because it happens to still pass -- left as-is.
2916
- check "point 6 (1/2) -- a healthy, well-filled comparison returns no-regression ITSELF, not merely membership in the verdict set (F-221: the old '['regression','no-regression','inconclusive'].includes(verdict)' assertion was true of every value compareArms() can return, including a gate that never accepts)" \
2917
- "$(cvj "$CVD_HELPERS
2918
- const arm = Array.from({length:15}, () => [{status:'done',pass:2}]);
2919
- const r = M.runComparison(mkSeqDraw(arm.slice()), mkSeqDraw(arm.slice()), { resamples: 5000, report: () => {} });
2920
- process.stdout.write(r.verdict);
2921
- ")" "no-regression"
2922
-
2923
- # --- the power statement and the top-level censoring
2924
- # counts, both an observability deliverable and an exit criterion.
2925
- check "runComparison's healthy-input result carries a LIVE power estimate in [0,1] (computed from THIS run's own realized arms, not a static 71.6% citation)" \
2926
- "$(cvj "$CVD_HELPERS
2927
- const arm = Array.from({length:15}, () => [{status:'done',pass:2}]);
2928
- const r = M.runComparison(mkSeqDraw(arm.slice()), mkSeqDraw(arm.slice()), { resamples: 5000, report: () => {}, powerTrials: 30, powerResamples: 500 });
2929
- process.stdout.write(String(typeof r.power === 'number' && r.power >= 0 && r.power <= 1));
2930
- ")" "true"
2931
- check "compareArms() does NOT compute power unless asked -- opt-in, so it never nests inside its own estimatePower() trial loop or points 1/2's T=600 mass-simulation loops below" \
2932
- "$(cvj "
2933
- const arm = Array.from({length:15}, () => 2);
2934
- const r = M.compareArms(arm, arm, { resamples: 2000 });
2935
- process.stdout.write(String('power' in r && r.power === undefined));
2936
- ")" "true"
2937
- check "runComparison surfaces stillRunning/replaced at the TOP level on the SUCCESS path too (F-223, point 4's 'censoring stays visible even when the floor is satisfied' -- unmet on this path before)" \
2938
- "$(cvj "$CVD_HELPERS
2939
- const censored = [[{status:'running'}, {status:'done', pass:2}]];
2940
- const plain = Array.from({length:14}, () => [{status:'done',pass:2}]);
2941
- const r = M.runComparison(mkSeqDraw([...censored, ...plain]), mkSeqDraw(Array.from({length:15}, () => [{status:'done',pass:2}])), { resamples: 5000, report: () => {} });
2942
- process.stdout.write(JSON.stringify({ stillRunning: r.stillRunning, replaced: r.replaced }));
2943
- ")" '{"stillRunning":{"baseline":1,"candidate":0},"replaced":{"baseline":0,"candidate":0}}'
2944
-
2945
- # --- convergence shards get their OWN namespace, OWN
2946
- # schema, decoupled from run.mjs's SCHEMA_VERSION -- verified by execution, not merely by reading
2947
- # the source, that the split actually removes the collision (the namespace-split option; see
2948
- # convergence.mjs's own comment above LOOP_SCHEMA_VERSION for the "was schema:1 deliberate?"
2949
- # answer: no, and it now is).
2950
- check "convergence shards land under shardDir(sha)/convergence/ -- run.mjs's REAL mergeShards() (not a mimic of its listing) never sees them (F-249)" \
2951
- "$(cvj "
2952
- const fs = await import('node:fs'); const path = await import('node:path');
2953
- const runMod = await import('$ROOT/tests/evals/run.mjs');
2954
- const sha = 'f225ns' + Date.now();
2955
- const p = M.loopShardPath(sha, M.TASK_ID, 0);
2956
- fs.mkdirSync(path.dirname(p), { recursive: true });
2957
- fs.writeFileSync(p, JSON.stringify({ sha, taskId: M.TASK_ID, schema: M.LOOP_SCHEMA_VERSION, run: { index: 0, pass: 2 } }));
2958
- const dir = runMod.shardDir(sha);
2959
- const merged = runMod.mergeShards(sha, { runs: 3 });
2960
- fs.rmSync(dir, { recursive: true, force: true });
2961
- process.stdout.write(JSON.stringify([Object.keys(merged.tasks).length, merged.skippedShards.length]));
2962
- ")" "[0,0]"
2963
- # --- resumeArm's nextIndex targets the first genuinely MISSING slot, not
2964
- # done.length -- shards {0,2} present must never overwrite shard 2 or leave 1 unwritten forever.
2965
- check "resumeArm: shards {0,2} present -- resume holds both, nextIndex fills the GAP at 1, never targets 2 (F-230)" \
2966
- "$(cvj "
2967
- const fs = await import('node:fs'); const path = await import('node:path');
2968
- const sha = 'f230gap' + Date.now();
2969
- for (const i of [0, 2]) {
2970
- const p = M.loopShardPath(sha, M.TASK_ID, i);
2971
- fs.mkdirSync(path.dirname(p), { recursive: true });
2972
- fs.writeFileSync(p, JSON.stringify({ sha, taskId: M.TASK_ID, schema: M.LOOP_SCHEMA_VERSION, run: { index: i, pass: i + 10 } }));
2973
- }
2974
- const r = M.resumeArm(sha, M.TASK_ID, 3);
2975
- fs.rmSync(path.dirname(path.dirname(M.loopShardPath(sha, M.TASK_ID, 0))), { recursive: true, force: true });
2976
- process.stdout.write(JSON.stringify({ resume: r.resume, nextIndex: r.nextIndex, occupied: [...r.occupied].sort((a,b)=>a-b) }));
2977
- ")" '{"resume":[10,12],"nextIndex":1,"occupied":[0,2]}'
2978
- # A corrupted shard (killed process mid-write) must not crash the read, must not silently push
2979
- # garbage into an arm, and must not have its slot immediately overwritten either -- readShard's
2980
- # own discipline of refusing a stale-schema shard, applied to THIS module's namespace, the third caller
2981
- # that had been skipping it.
2982
- check "resumeArm: a corrupted shard is treated as absent from resume, without crashing, and its slot stays occupied (not silently overwritten) (F-225)" \
2983
- "$(cvj "
2984
- const fs = await import('node:fs'); const path = await import('node:path');
2985
- const sha = 'f225corrupt' + Date.now();
2986
- const p = M.loopShardPath(sha, M.TASK_ID, 0);
2987
- fs.mkdirSync(path.dirname(p), { recursive: true });
2988
- fs.writeFileSync(p, 'not json');
2989
- const r = M.resumeArm(sha, M.TASK_ID, 1);
2990
- fs.rmSync(path.dirname(path.dirname(p)), { recursive: true, force: true });
2991
- process.stdout.write(JSON.stringify({ resume: r.resume, nextIndex: r.nextIndex, occupied: [...r.occupied] }));
2992
- ")" '{"resume":[],"nextIndex":1,"occupied":[0]}'
2993
- # resumeArm's occupied set means nothing if the CONSUMER re-collides
2994
- # with it -- writeNextShard is drawArmForSha's onDraw, exercised directly (no live draw, no quota).
2995
- check "writeNextShard: n=5, shards {0,2} occupied, three sequential draws land exactly on the GAPS -- {1,3,4}, never re-touching 2 (F-248)" \
2996
- "$(cvj "
2997
- const fs = await import('node:fs'); const path = await import('node:path'); const sha = 'f248gap' + Date.now(); const occ = new Set([0, 2]); let i = 1; const w = []; for (let k = 0; k < 3; k++) { i = M.writeNextShard(sha, M.TASK_ID, 5, occ, i, 7) + 1; w.push(i - 1); } const onDisk = fs.readdirSync(path.dirname(M.loopShardPath(sha, M.TASK_ID, 0))).filter(f => f.endsWith('.json')).map(f => Number(f.match(/-(\d+)\.json\$/)[1])).sort((a,b)=>a-b); fs.rmSync(path.dirname(path.dirname(M.loopShardPath(sha, M.TASK_ID, 0))), { recursive: true, force: true }); process.stdout.write(JSON.stringify([w, onDisk]));
2998
- ")" "[[1,3,4],[1,3,4]]"
2999
- check "writeNextShard: n=5, a corrupted-but-occupied shard 0 plus 1,2 valid -- the slot at n=5 throws instead of writing out of range where loopCompletedIndices() could never find it again (F-248)" \
3000
- "$(cvj "
3001
- const fs = await import('node:fs'); const path = await import('node:path'); const sha = 'f248oob' + Date.now(); const occ = new Set([0, 1, 2]); let i = 3; i = M.writeNextShard(sha, M.TASK_ID, 5, occ, i, 7) + 1; i = M.writeNextShard(sha, M.TASK_ID, 5, occ, i, 7) + 1; let threw = false; try { M.writeNextShard(sha, M.TASK_ID, 5, occ, i, 7); } catch (e) { threw = /no free shard slot/.test(e.message); } const onDisk = fs.readdirSync(path.dirname(M.loopShardPath(sha, M.TASK_ID, 0))).filter(f => f.endsWith('.json')).length; fs.rmSync(path.dirname(path.dirname(M.loopShardPath(sha, M.TASK_ID, 0))), { recursive: true, force: true }); process.stdout.write(JSON.stringify([threw, onDisk]));
3002
- ")" "[true,2]"
3003
-
3004
- # --- writeBreachRecord/breachRecordPath: persists fillArm()'s
3005
- # breachReason alongside the fixture-namespaced shard directory, generalizing writeCensorRecord's
3006
- # existing per-fixture convention -- exercised directly (no live draw, no quota), same idiom as
3007
- # writeNextShard's own tests just above.
3008
- check "breachRecordPath: a real fixtureId lands INSIDE that fixture's own shard directory, as a breach/ sibling to the numbered shards (not the flat legacy bucket)" \
3009
- "$(cvj "
3010
- const path = await import('node:path');
3011
- const sha = 'd6ns' + Date.now();
3012
- const bp = M.breachRecordPath(sha, M.TASK_ID, 0, 'fixtureA');
3013
- const shardDirForFixtureA = path.dirname(M.loopShardPath(sha, M.TASK_ID, 0, 'fixtureA'));
3014
- process.stdout.write(JSON.stringify({ underShardDir: path.dirname(bp) === path.join(shardDirForFixtureA, 'breach'), basename: path.basename(bp) }));
3015
- ")" '{"underShardDir":true,"basename":"loop-code-loop-000.json"}'
3016
- check "writeBreachRecord: fixtureId='fixA' writes under fixA's own namespace, as a breach/ sibling to the numbered shards -- what THIS proves is the write side lands in the right place; no read path exists yet to close the F-284/F-285 write-moved/read-didn't class against (F-44 -- the class stays deferred, not closed, until phases/04 reads a breach record). Cleanup anchored on run.mjs's OWN shardDir(sha) (F-225's precedent below), not hand-counted dirname() calls -- a hand-counted depth is exactly the kind of arithmetic that is easy to get wrong without leaving evidence (verified against this test's own first draft, which did)." \
3017
- "$(cvj "
3018
- const fs = await import('node:fs');
3019
- const runMod = await import('$ROOT/tests/evals/run.mjs');
3020
- const sha = 'd6iso' + Date.now();
3021
- M.writeBreachRecord(sha, M.TASK_ID, 'max-passes-exceeded', 'fixA');
3022
- const fixAHasIt = fs.existsSync(M.breachRecordPath(sha, M.TASK_ID, 0, 'fixA'));
3023
- fs.rmSync(runMod.shardDir(sha), { recursive: true, force: true });
3024
- process.stdout.write(JSON.stringify({ fixAHasIt }));
3025
- ")" '{"fixAHasIt":true}'
3026
- check "writeBreachRecord: two DIFFERENT fixtures under the SAME sha never collide -- independent seq counters, each starting at 0" \
3027
- "$(cvj "
3028
- const fs = await import('node:fs');
3029
- const runMod = await import('$ROOT/tests/evals/run.mjs');
3030
- const sha = 'd6two' + Date.now();
3031
- const seqA = M.writeBreachRecord(sha, M.TASK_ID, 'diff-cap-exceeded', 'fixA');
3032
- const seqB = M.writeBreachRecord(sha, M.TASK_ID, 'scope-expansion', 'fixB');
3033
- const contentA = JSON.parse(fs.readFileSync(M.breachRecordPath(sha, M.TASK_ID, 0, 'fixA'), 'utf8'));
3034
- const contentB = JSON.parse(fs.readFileSync(M.breachRecordPath(sha, M.TASK_ID, 0, 'fixB'), 'utf8'));
3035
- fs.rmSync(runMod.shardDir(sha), { recursive: true, force: true });
3036
- process.stdout.write(JSON.stringify({ seqA, seqB, reasonA: contentA.breachReason, reasonB: contentB.breachReason, fixtureA: contentA.fixture, fixtureB: contentB.fixture }));
3037
- ")" '{"seqA":0,"seqB":0,"reasonA":"diff-cap-exceeded","reasonB":"scope-expansion","fixtureA":"fixA","fixtureB":"fixB"}'
3038
- check "writeBreachRecord: self-healing first-free-slot write, same idiom as writeCensorRecord/writeNextShard -- a second call to the SAME fixture advances to seq 1, never overwrites seq 0" \
3039
- "$(cvj "
3040
- const fs = await import('node:fs');
3041
- const runMod = await import('$ROOT/tests/evals/run.mjs');
3042
- const sha = 'd6seq' + Date.now();
3043
- const seq0 = M.writeBreachRecord(sha, M.TASK_ID, 'circuit-breaker', 'fixA');
3044
- const seq1 = M.writeBreachRecord(sha, M.TASK_ID, 'user-stop', 'fixA');
3045
- const first = JSON.parse(fs.readFileSync(M.breachRecordPath(sha, M.TASK_ID, 0, 'fixA'), 'utf8'));
3046
- fs.rmSync(runMod.shardDir(sha), { recursive: true, force: true });
3047
- process.stdout.write(JSON.stringify({ seq0, seq1, firstUntouched: first.breachReason === 'circuit-breaker' }));
3048
- ")" '{"seq0":0,"seq1":1,"firstUntouched":true}'
3049
- # unlike writeNextShard()/writeCensorRecord(), breach records are NEW
3050
- # -- there is no legacy fixture-less data sitting in a flat bucket for a defaulted
3051
- # fixtureId to stay compatible with, so an omitted/null fixtureId is never a legitimate "unknown
3052
- # fixture" read here. The prior version of this check entrenched exactly the hazard a
3053
- # review measured (a qualified write, an unqualified default-arg read, silently landing in a
3054
- # DIFFERENT directory with no error) -- replaced with the throw that closes it: a loud TypeError
3055
- # at the call site instead of a quiet empty read at whatever future reader queries the
3056
- # wrong path.
3057
- check "writeBreachRecord: fixtureId omitted throws -- no flat legacy bucket for breach records to fall back to (F-42)" \
3058
- "$(cvj "
3059
- let threw = false, isTypeError = false, mentionsFixtureId = false;
3060
- try { M.writeBreachRecord('d6nofix' + Date.now(), M.TASK_ID, 'max-passes-exceeded'); }
3061
- catch (e) { threw = true; isTypeError = e instanceof TypeError; mentionsFixtureId = /fixtureId/.test(e.message); }
3062
- process.stdout.write(JSON.stringify({ threw, isTypeError, mentionsFixtureId }));
3063
- ")" '{"threw":true,"isTypeError":true,"mentionsFixtureId":true}'
3064
- check "writeBreachRecord: fixtureId explicitly null (not merely omitted) throws the same way -- 'not a real fixture' has exactly one spelling here, not two" \
3065
- "$(cvj "
3066
- let threw = false;
3067
- try { M.writeBreachRecord('d6nofix2' + Date.now(), M.TASK_ID, 'max-passes-exceeded', null); }
3068
- catch (e) { threw = e instanceof TypeError; }
3069
- process.stdout.write(String(threw));
3070
- ")" "true"
3071
- check "breachRecordPath: fixtureId omitted throws too -- same guard, reachable directly, not only through writeBreachRecord's own call into it" \
3072
- "$(cvj "
3073
- let threw = false;
3074
- try { M.breachRecordPath('d6nofix3' + Date.now(), M.TASK_ID, 0); } catch (e) { threw = e instanceof TypeError; }
3075
- process.stdout.write(String(threw));
3076
- ")" "true"
3077
-
3078
- # the fillArm() -> writeBreachRecord() ASSEMBLY drawArmForSha() uses,
3079
- # driven for real through fillArm() with a synthetic (non-live) draw handle -- no /code-loop
3080
- # invocation, no quota spent. Mirrors convergence-runner.sh:461-476's identical censor-assembly
3081
- # precedent (and the other "the exact assembly drawArmForSha() uses" wiring tests) -- the
3082
- # precedent a review found was checkably wrong to cite as untestable:
3083
- # that precedent tests exactly this shape of composition, hermetically, so this does too, threading
3084
- # the REAL r.breachReason (not a literal) into the REAL writer at the REAL namespace.
3085
- check "the exact assembly drawArmForSha() uses (fillArm's breach return + writeBreachRecord) persists a breached draw's specific reason, without a live draw (F-43)" \
3086
- "$(cvj "$CVD_HELPERS
3087
- const fs = await import('node:fs');
3088
- const runMod = await import('$ROOT/tests/evals/run.mjs');
3089
- const sha = 'd6wiring' + Date.now();
3090
- const r = M.fillArm(mkSeqDraw([[{status:'stopped-diff-cap-exceeded', pass:6}]]), { n: 1, report: () => {} });
3091
- const seq = r.breach ? M.writeBreachRecord(sha, M.TASK_ID, r.breachReason, 'fixW') : null;
3092
- const rec = seq === null ? null : JSON.parse(fs.readFileSync(M.breachRecordPath(sha, M.TASK_ID, seq, 'fixW'), 'utf8'));
3093
- fs.rmSync(runMod.shardDir(sha), { recursive: true, force: true });
3094
- process.stdout.write(JSON.stringify({ breach: r.breach, persistedReason: rec ? rec.breachReason : null }));
3095
- ")" '{"breach":true,"persistedReason":"diff-cap-exceeded"}'
3096
-
3097
- # --- prepareDrawDir() is startDraw()'s setup ONLY
3098
- # (no invocation), the injection seam neither disclosed deviation had coverage through before this
3099
- # -- the seam that would have caught the missing scripts/ copy by evidence, not by reasoning.
3100
- check "prepareDrawDir: workDir contains scripts/somi-loop.mjs and .claude/commands/, zero model calls (F-227)" \
3101
- "$(cvj "
3102
- const fs = await import('node:fs'); const path = await import('node:path');
3103
- const work = M.prepareDrawDir('$ROOT', '$ROOT/tests/evals/fixtures/task02-code');
3104
- const ok = fs.existsSync(path.join(work, 'scripts', 'somi-loop.mjs')) && fs.existsSync(path.join(work, '.claude', 'commands'));
3105
- fs.rmSync(work, { recursive: true, force: true });
3106
- process.stdout.write(String(ok));
3107
- ")" "true"
3108
- check "prepareDrawDir: throws when scripts/ is missing at the source, named and immediate -- not silently skipped into six wasted model calls (F-228)" \
3109
- "$(cvj "
3110
- const fs = await import('node:fs'); const os = await import('node:os'); const path = await import('node:path');
3111
- const emptySource = fs.mkdtempSync(path.join(os.tmpdir(), 'somi-eval-nosource-'));
3112
- let threw = false;
3113
- try { M.prepareDrawDir(emptySource, '$ROOT/tests/evals/fixtures/task02-code'); } catch (e) { threw = /scripts.*missing/.test(e.message); }
3114
- fs.rmSync(emptySource, { recursive: true, force: true });
3115
- process.stdout.write(String(threw));
3116
- ")" "true"
3117
-
3118
- # --- drawArmForSha() preflights before any work, matching run.mjs's own precedent
3119
- # (:150-165 above) -- simulated the same way, by stripping PATH/HOME so neither the CLI nor a
3120
- # credential resolves, never by mocking preflight() itself.
3121
- NODE_BIN=$(command -v node)
3122
- cvd_preflight=$(env -i "PATH=$(dirname "$NODE_BIN")" HOME=/nonexistent "$NODE_BIN" --input-type=module -e "
3123
- const M = await import('$ROOT/$CVD');
3124
- try { M.drawArmForSha('$ROOT', '$ROOT/tests/evals/fixtures/task02-code', 'f229preflight', { n: 1 }); process.stdout.write('no-throw'); }
3125
- catch (e) { process.stdout.write(e.message); }
3126
- " 2>&1)
3127
- case "$cvd_preflight" in
3128
- *"not ready to draw"*) ok "drawArmForSha preflights the CLI and credential before spending any quota (F-229)" ;;
3129
- *) bad "drawArmForSha preflights the CLI and credential before spending any quota (F-229) (got: ${cvd_preflight:0:80})" ;;
3130
- esac
3131
-
3132
- # --- Mutation testing: staged against a COPY of convergence.mjs, never the tracked
3133
- # file, following the mann-whitney scratch-copy precedent -- one scratch dir, reset via `cp` between mutants.
3134
- CVD_SCRATCH_DIR=$(mktemp -d) || { bad "mktemp failed"; exit 1; }
3135
- CVD_SCRATCH="$CVD_SCRATCH_DIR/convergence.mjs"
3136
- # `trap ... EXIT` REPLACES the handler, it does not
3137
- # append -- registering `rm -rf "$CVD_SCRATCH_DIR"' alone here would silently drop :2380's
3138
- # MW_SCRATCH_DIR cleanup (measured: baseline d9421b3's runner cleans it, this one did not, until
3139
- # this line named both). Name every scratch dir the suite has created so far, not just this one.
3140
- trap 'rm -rf "$MW_SCRATCH_DIR" "$CVD_SCRATCH_DIR"' EXIT
3141
- # `trap -p EXIT` prints the REGISTERED command text verbatim (single-quoted at registration, so
3142
- # the variable REFERENCES are still literal `$MW_SCRATCH_DIR`/`$CVD_SCRATCH_DIR` text, not their
3143
- # expanded paths) -- pin on the variable names, which is what proves both are named in the SAME
3144
- # trap command, not on their runtime values.
3145
- check "F-222: the EXIT trap names BOTH scratch dirs (trap REPLACES, not appends -- a registration naming only its own dir silently drops every earlier one)" \
3146
- "$(trap -p EXIT | grep -qF 'MW_SCRATCH_DIR' && trap -p EXIT | grep -qF 'CVD_SCRATCH_DIR' && echo true || echo false)" "true"
3147
- # Symlinked, not copied: only convergence.mjs itself is ever mutated; its relative imports
3148
- # (lib/, run.mjs) resolve straight through to the real, pristine files -- same isolation guarantee
3149
- # as MW_SCRATCH's single-file copy, extended to a module with real sibling dependencies (3.3c adds
3150
- # the top-level `import { shardDir } from './run.mjs'`, so the scratch copy needs run.mjs
3151
- # resolvable too, not just lib/).
3152
- ln -s "$ROOT/tests/evals/lib" "$CVD_SCRATCH_DIR/lib"
3153
- ln -s "$ROOT/tests/evals/run.mjs" "$CVD_SCRATCH_DIR/run.mjs"
3154
- cp "$ROOT/$CVD" "$CVD_SCRATCH"
3155
-
3156
- # CVD_SIM: shared population/trial-loop preamble for points 1, 2 and 6, and for mutant D's second
3157
- # check below (all draw from the tied historical MIXED-HISTORY histogram,
3158
- # {1:9,2:4,3:5,4:2,5:1}, sd~1.24). Defined here, before the mutation section, since mutant D needs
3159
- # it too.
3160
- # TWO independent seeded streams, not one shared between arm
3161
- # generation and the rank test's own resampling -- compareArms() short-circuits on p < alpha, so a
3162
- # single shared stream let the number of rng() calls consumed per trial depend on that trial's own
3163
- # outcome, and no single trial could be replayed in isolation. dataRng draws the synthetic arms;
3164
- # testRng is the ONLY stream compareArms()/mannWhitneyU ever consumes.
3165
- #
3166
- # it was measured that this is NOT the population a real
3167
- # /code-loop draws are shaped like -- the real baseline has sd 0.5164,
3168
- # materially tighter than this histogram's ~1.24. Every target/floor computed under CVD_SIM below
3169
- # is calibrated to THIS wider, tied-mixed-history population, and states how the verdict logic
3170
- # behaves under HIGH VARIANCE -- a genuine, deliberately kept stress case -- not what the margin-gated
3171
- # comparison the real gate runs actually accepts or rejects on real draws. Read a CVD_SIM
3172
- # target/floor as "how the logic holds up under stress," never as a claim about the operative
3173
- # gate's real accept rate; CVD_SIM_D13 below (bootstrapped from the real baseline) is what states
3174
- # that instead.
3175
- CVD_SIM='
3176
- const MWmod = await import("'"$ROOT"'/tests/evals/lib/mann-whitney.mjs");
3177
- const dataRng = MWmod.mulberry32(1234);
3178
- const testRng = MWmod.mulberry32(5678);
3179
- const weights = [[1,9],[2,4],[3,5],[4,2],[5,1]];
3180
- const total = weights.reduce((s,[,w]) => s + w, 0);
3181
- function drawOne() { let r = dataRng() * total; for (const [v,w] of weights) { if (r < w) return v; r -= w; } return weights.at(-1)[0]; }
3182
- function drawArm(n) { return Array.from({ length: n }, drawOne); }
3183
- const T = 600, RESAMPLES = 3000, N = 15;
3184
- '
3185
-
3186
- # CVD_SIM_D13: same shared preamble SHAPE as CVD_SIM (the two-independent-streams discipline),
3187
- # but the population is bootstrap-resampled WITH REPLACEMENT from the real measured 15-draw
3188
- # baseline arm ([2,1,2,1,2,1,1,2,1,1,2,2,2,1,2], mean 1.5333, sd 0.5164) instead
3189
- # of the mixed-history histogram -- the population the margin-gated /code-loop comparison actually
3190
- # draws from. `dataRng` draws the bootstrap sample (both baseline's and candidate's shared
3191
- # draws, same convention as CVD_SIM's `drawArm`); `bumpRng` is a THIRD independent stream, used only
3192
- # by the point-2 analogue further down, for the "gains a pass with probability 0.5" degradation
3193
- # model the earlier resampling scripts used to report "+0.5 pass"
3194
- # (the earlier resampling scripts) -- kept separate from `dataRng` for the same reason
3195
- # the suite separates `dataRng` from `testRng`: no single stream's call count may depend on another
3196
- # draw's own outcome. `testRng` is the ONLY stream compareArms()/mannWhitneyU ever consumes, same
3197
- # as CVD_SIM. Independently derived by Monte Carlo, not copied from the earlier scripts (which
3198
- # share one rng stream where this suite's discipline keeps three -- a design difference, NOT
3199
- # the reason the two readings differ; the point-2 analogue below carries the arithmetic), so
3200
- # the two are expected to agree in magnitude, not to the decimal, as independent estimates -- checked: this harness's own CVD_SIM point-6-equivalent measurement of the already-
3201
- # published 0.4250 (margin 0.5, historical population) reproduces bit-for-bit (see point 6 below), which is
3202
- # the cross-check that this harness is faithful to the real module before trusting new numbers from it.
3203
- CVD_SIM_D13='
3204
- const MWmod = await import("'"$ROOT"'/tests/evals/lib/mann-whitney.mjs");
3205
- const D13_ARM = [2,1,2,1,2,1,1,2,1,1,2,2,2,1,2];
3206
- const dataRng = MWmod.mulberry32(1234);
3207
- const bumpRng = MWmod.mulberry32(4321);
3208
- const testRng = MWmod.mulberry32(5678);
3209
- function drawOne() { return D13_ARM[Math.floor(dataRng() * D13_ARM.length)]; }
3210
- function drawArm(n) { return Array.from({ length: n }, drawOne); }
3211
- const T = 600, RESAMPLES = 3000, N = 15;
3212
- '
3213
-
3214
- # Mutant A -- reintroduces the running-as-done defect: collapses capBreached()'s null (running OR malformed) into the
3215
- # non-breach/done branch -- the natural-but-wrong `if (!capBreached(o)) arm.push(...)` shape.
3216
- node -e "
3217
- const fs = require('fs'); const p = '$CVD_SCRATCH'; const s = fs.readFileSync(p, 'utf8');
3218
- const FROM = 'if (breach === true) return { kind: \'breach\' };\n if (breach === false) {';
3219
- const TO = 'if (breach === true) return { kind: \'breach\' };\n if (breach !== true) {';
3220
- if (!s.includes(FROM)) throw new Error('mutant A pattern not found -- source moved');
3221
- fs.writeFileSync(p, s.replace(FROM, TO));
3222
- "
3223
- check "mutant A (F-182: null collapsed into done) is caught -- a running loop's pass count reads as 'done', not 'running'" \
3224
- "$(cvj "process.stdout.write(M.classifyDraw({status:'running', pass:0}).kind);" "$CVD_SCRATCH")" "done"
3225
- cp "$ROOT/$CVD" "$CVD_SCRATCH"
3226
-
3227
- # Mutant B -- reintroduces the re-draw defect: exhausting the wait budget re-draws a FRESH handle instead of
3228
- # stopping, re-rolling exactly the censored draw and pulling the arm mean down.
3229
- # Anchored on the return statement alone, not the surrounding block (a later change
3230
- # added a diagnostic censor record and a comment ahead of this same return inside convergence.mjs's
3231
- # own scope) -- narrowing the anchor here keeps this guard resilient to that kind of addition
3232
- # without needing to track every line around it. Anchor text updated
3233
- # for the additive `breachReason: null` field this same return statement now also carries -- the
3234
- # anchor's OWN resilience covers a change to lines AROUND it, not a change WITHIN the exact
3235
- # return statement it matches, so this one line's text needed a manual update; what the check
3236
- # below asserts (arm/waitExhausted) is unchanged.
3237
- # Occurrence count asserted, not just presence: an anchor
3238
- # edit (above) demonstrated a bare .includes() guard can silently match the wrong thing once a
3239
- # nearby line changes -- adopting the same discipline the fixture-identity anchors already use
3240
- # (see convergence-runner.sh), not just a presence check.
3241
- node -e "
3242
- const fs = require('fs'); const p = '$CVD_SCRATCH'; const s = fs.readFileSync(p, 'utf8');
3243
- const FROM = 'return { breach: false, arm, stillRunning, replaced, waitExhausted: true, censor, breachReason: null };';
3244
- const TO = 'replaced++; break; // MUTANT: re-roll instead of stopping';
3245
- const count = s.split(FROM).length - 1;
3246
- if (count !== 1) throw new Error('mutant B pattern occurs ' + count + ' time(s), not exactly 1 -- source moved, update this mutation');
3247
- fs.writeFileSync(p, s.replace(FROM, TO));
3248
- "
3249
- check "mutant B (F-194: wait-exhaustion re-rolls instead of stopping) is caught -- the censored slot gets topped up, not left short" \
3250
- "$(cvj "$CVD_HELPERS
3251
- const seq = [[{status:'running'}, {status:'running'}, {status:'running'}], [{status:'done', pass:1}]];
3252
- const r = M.fillArm(mkSeqDraw(seq), { n: 1, maxWaitAttempts: 1, report: () => {} });
3253
- process.stdout.write(JSON.stringify({ arm: r.arm, waitExhausted: r.waitExhausted }));
3254
- " "$CVD_SCRATCH")" '{"arm":[1],"waitExhausted":false}'
3255
- cp "$ROOT/$CVD" "$CVD_SCRATCH"
3256
-
3257
- # Mutant C -- reintroduces the collapsed-verdict bug points 1/2 exist to catch: no-regression
3258
- # whenever p >= alpha (the exact "p >= alpha alone is no-regression" shape spec.md forbids). Arms
3259
- # below are a real inconclusive pair under the PRISTINE module (primary.p=0.137, unaffected by
3260
- # REGRESSION_SHIFT since `shift` is never read before the primary-test return; equiv.p=0.084 at
3261
- # the previous margin of 1, re-measured at ~0.38 under the new 0.5 -- both readings >= alpha, so this
3262
- # is still a genuine inconclusive pair at the new margin, just less marginal -- found by
3263
- # simulation, not hand-picked to be easy), so the mutant's forced flip to 'no-regression' is a
3264
- # visible change from the correct verdict, not masked by an earlier primary-regression return.
3265
- # the paragraph above ASSERTED the pristine premise only in prose --
3266
- # closed with a direct check, against the tracked module, before the mutation below is applied.
3267
- check "mutant C's pair is a genuine inconclusive pair UNDER THE UNMODIFIED module (F-313) -- the premise the mutation below is supposed to visibly change, checked directly rather than only claimed in a comment" \
3268
- "$(cvj "
3269
- const a = [1,3,2,3,1,3,1,1,1,3,1,1,1,3,1];
3270
- const b = [1,2,3,2,1,2,3,1,3,5,2,1,5,1,2];
3271
- process.stdout.write(M.compareArms(a, b, { resamples: 20000 }).verdict);
3272
- ")" "inconclusive"
3273
- node -e "
3274
- const fs = require('fs'); const p = '$CVD_SCRATCH'; const s = fs.readFileSync(p, 'utf8');
3275
- const FROM = \"const shifted = candidateArm.map((v) => v - shift);\n const equivalence = mannWhitneyU(shifted, baselineArm, mwOpts);\n const verdict = equivalence.p < alpha ? 'no-regression' : 'inconclusive';\n return { verdict, primary, equivalence, alpha, shift, power };\";
3276
- const TO = \"const verdict = 'no-regression'; // MUTANT\n return { verdict, primary, alpha, shift, power };\";
3277
- if (!s.includes(FROM)) throw new Error('mutant C pattern not found -- source moved');
3278
- fs.writeFileSync(p, s.replace(FROM, TO));
3279
- "
3280
- check "mutant C ('p >= alpha alone is no-regression') is caught -- a real inconclusive pair now reads no-regression" \
3281
- "$(cvj "
3282
- const a = [1,3,2,3,1,3,1,1,1,3,1,1,1,3,1];
3283
- const b = [1,2,3,2,1,2,3,1,3,5,2,1,5,1,2];
3284
- process.stdout.write(M.compareArms(a, b, { resamples: 20000 }).verdict);
3285
- " "$CVD_SCRATCH")" "no-regression"
3286
- cp "$ROOT/$CVD" "$CVD_SCRATCH"
3287
-
3288
- # Mutant D -- reintroduces the NEVER-ACCEPTS direction:
3289
- # a gate that can never return no-regression. Every other check in this suite bounds a false
3290
- # ACCEPT; this is the direction only point 6 (below) bounds. Short-circuits compareArms() to a
3291
- # hardcoded verdict -- the rest of the function body is then dead code, which is fine, this is a
3292
- # staged mutant, not shipped source.
3293
- node -e "
3294
- const fs = require('fs'); const p = '$CVD_SCRATCH'; const s = fs.readFileSync(p, 'utf8');
3295
- const FROM = 'export function compareArms(baselineArm, candidateArm, opts = {}) {';
3296
- const TO = 'export function compareArms(baselineArm, candidateArm, opts = {}) { return { verdict: \'inconclusive\' }; // MUTANT (F-221): never accepts';
3297
- if (!s.includes(FROM)) throw new Error('mutant D pattern not found -- source moved');
3298
- fs.writeFileSync(p, s.replace(FROM, TO));
3299
- "
3300
- check "mutant D (F-221: verdict is always 'inconclusive') is caught by point 6's FIRST half -- a clean, healthy pair now reads inconclusive, not no-regression" \
3301
- "$(cvj "$CVD_HELPERS
3302
- const arm = Array.from({length:15}, () => [{status:'done',pass:2}]);
3303
- const r = M.runComparison(mkSeqDraw(arm.slice()), mkSeqDraw(arm.slice()), { resamples: 5000, report: () => {} });
3304
- process.stdout.write(r.verdict);
3305
- " "$CVD_SCRATCH")" "inconclusive"
3306
- check "mutant D is ALSO caught by point 6's SECOND half -- the no-regression rate on unshifted pairs collapses to 0, far below point 6's floor (D16, re-derived below for REGRESSION_SHIFT=0.5)" \
3307
- "$(cvj "$CVD_SIM
3308
- process.stdout.write(String(M.estimatePower(drawOne, N, { rng: testRng, resamples: RESAMPLES, trials: 50 })));
3309
- " "$CVD_SCRATCH")" "0"
3310
- # the never-accepting direction is caught the SAME way on the baseline-population
3311
- # analogue (defined below) -- staged here, on the SAME mutant, rather than re-mutating a second
3312
- # scratch copy, since the mutation itself doesn't depend on which population later draws from it.
3313
- check "mutant D is ALSO caught by the D13-population point 6 analogue (F-309) -- the healthy-pair no-regression rate collapses to 0 there too, independent of which population is used" \
3314
- "$(cvj "$CVD_SIM_D13
3315
- process.stdout.write(String(M.estimatePower(drawOne, N, { rng: testRng, resamples: RESAMPLES, trials: 50 })));
3316
- " "$CVD_SCRATCH")" "0"
3317
- cp "$ROOT/$CVD" "$CVD_SCRATCH"
3318
-
3319
- check "positive control: the tracked convergence.mjs is pristine after all four mutants (F-231: now also exercises fillArm, the seam mutant B mutates -- reusing the n:2/maxWaitAttempts:1 case)" \
3320
- "$(cvj "$CVD_HELPERS
3321
- const a = [1,3,2,3,1,3,1,1,1,3,1,1,1,3,1];
3322
- const b = [1,2,3,2,1,2,3,1,3,5,2,1,5,1,2];
3323
- const seq = [[{status:'running'}, {status:'running'}, {status:'running'}], [{status:'done', pass:1}]];
3324
- const fr = M.fillArm(mkSeqDraw(seq), { n: 2, maxWaitAttempts: 1, report: () => {} });
3325
- process.stdout.write(M.classifyDraw({status:'running', pass:0}).kind + '/' + M.compareArms(a, b, { resamples: 20000 }).verdict + '/' + JSON.stringify({ arm: fr.arm, waitExhausted: fr.waitExhausted }));
3326
- ")" 'running/inconclusive/{"arm":[],"waitExhausted":true}'
3327
-
3328
- # Mutant E -- the literal PRE-FIX code path: fillArm()'s breach branch
3329
- # reverted to dropping breachReason entirely, exactly as it read before the fix
3330
- # (`return { breach: true, arm, stillRunning, replaced, waitExhausted: false, censor: null };`,
3331
- # as it read before). The "shown to fail, shown to pass"
3332
- # discipline, applied here as a genuine mutation-test rather than only the direct checks above.
3333
- node -e "
3334
- const fs = require('fs'); const p = '$CVD_SCRATCH'; const s = fs.readFileSync(p, 'utf8');
3335
- const FROM = 'return { breach: true, arm, stillRunning, replaced, waitExhausted: false, censor: null, breachReason: reason };';
3336
- const TO = 'return { breach: true, arm, stillRunning, replaced, waitExhausted: false, censor: null }; // MUTANT (D6): pre-fix -- breachReason dropped entirely';
3337
- if (!s.includes(FROM)) throw new Error('mutant E pattern not found -- source moved');
3338
- fs.writeFileSync(p, s.replace(FROM, TO));
3339
- "
3340
- check "mutant E (D6 pre-fix: breachReason dropped from the breach return) is caught -- a documented breach status no longer surfaces its specific reason" \
3341
- "$(cvj "$CVD_HELPERS
3342
- const r = M.fillArm(mkSeqDraw([[{status:'stopped-max-passes-exceeded', pass:6}]]), { n: 1, report: () => {} });
3343
- process.stdout.write(String(r.breachReason));
3344
- " "$CVD_SCRATCH")" "undefined"
3345
- cp "$ROOT/$CVD" "$CVD_SCRATCH"
3346
- check "mutant E reverted -- the tracked convergence.mjs's breach branch threads breachReason again" \
3347
- "$(cvj "$CVD_HELPERS
3348
- const r = M.fillArm(mkSeqDraw([[{status:'stopped-max-passes-exceeded', pass:6}]]), { n: 1, report: () => {} });
3349
- process.stdout.write(String(r.breachReason));
3350
- " "$CVD_SCRATCH")" "max-passes-exceeded"
3351
-
3352
- # Mutant F -- an INTENTIONALLY-BROKEN threading, distinct from mutant E's plain omission: reads
3353
- # the reason via a FRESH draw.read() issued AFTER safeCleanup(draw), instead of the
3354
- # already-captured `state` local -- the exact ordering mistake to watch for (a naive re-read after the workDir is gone). startDraw()'s real read() returns
3355
- # `null` once statePath no longer exists (existsSync guard), so this mutant's breachReason
3356
- # collapses to null on every real breach -- caught by the SAME direct check already used for the
3357
- # stopped-<reason> case above, no new assertion shape needed.
3358
- node -e "
3359
- const fs = require('fs'); const p = '$CVD_SCRATCH'; const s = fs.readFileSync(p, 'utf8');
3360
- const FROM = 'const reason = breachReason(state);\n safeCleanup(draw);\n return { breach: true, arm, stillRunning, replaced, waitExhausted: false, censor: null, breachReason: reason };';
3361
- const TO = 'safeCleanup(draw);\n const reason = breachReason(draw.read()); // MUTANT (D6): re-read AFTER cleanup, not the cached state\n return { breach: true, arm, stillRunning, replaced, waitExhausted: false, censor: null, breachReason: reason };';
3362
- if (!s.includes(FROM)) throw new Error('mutant F pattern not found -- source moved');
3363
- fs.writeFileSync(p, s.replace(FROM, TO));
3364
- "
3365
- check "mutant F (D6: reason re-read from draw.read() AFTER safeCleanup, not the cached state) is caught -- against a REAL startDraw()-shaped handle whose read() returns null once the workDir is gone, this reads null instead of the real reason" \
3366
- "$(cvj "
3367
- function mkPostCleanupNullDraw(status) {
3368
- let cleaned = false;
3369
- const state = { status, pass: 6 };
3370
- return () => ({
3371
- read: () => (cleaned ? null : state), // mirrors startDraw()'s own read(): null once the statePath is gone
3372
- retry: () => {},
3373
- cleanup: () => { cleaned = true; },
3374
- });
3375
- }
3376
- const r = M.fillArm(mkPostCleanupNullDraw('stopped-max-passes-exceeded'), { n: 1, report: () => {} });
3377
- process.stdout.write(String(r.breachReason));
3378
- " "$CVD_SCRATCH")" "null"
3379
- cp "$ROOT/$CVD" "$CVD_SCRATCH"
3380
- check "mutant F reverted -- the same post-cleanup-null handle now correctly reads the reason from the state captured BEFORE cleanup" \
3381
- "$(cvj "
3382
- function mkPostCleanupNullDraw(status) {
3383
- let cleaned = false;
3384
- const state = { status, pass: 6 };
3385
- return () => ({
3386
- read: () => (cleaned ? null : state),
3387
- retry: () => {},
3388
- cleanup: () => { cleaned = true; },
3389
- });
3390
- }
3391
- const r = M.fillArm(mkPostCleanupNullDraw('stopped-max-passes-exceeded'), { n: 1, report: () => {} });
3392
- process.stdout.write(String(r.breachReason));
3393
- " "$CVD_SCRATCH")" "max-passes-exceeded"
3394
-
3395
- # --- margin pin: the margin's EFFECT, not just its literal value -- a fixed baseline/candidate pair
3396
- # that reads no-regression at shift=1 and reads something else at the DEFAULT shift (module's own
3397
- # REGRESSION_SHIFT). `baseline` is the real measured 15-draw arm ([2,1,2,1,2,1,1,2,1,1,2,2,2,1,2],
3398
- # ); `candidate` bumps its first 4 draws by one pass each -- found by grid search
3399
- # over "how many draws bumped" (0/2 draws: no-regression at both margins; 8+: regression at both,
3400
- # shift never even read; 4 draws is the band between, verified stable across 5 independent rng
3401
- # seeds before picking it). A fixed `rng` (mulberry32) makes this deterministic -- Math.random()
3402
- # would make a boundary-straddling pair flaky across runs, unlike Mutant C's pair above, which only
3403
- # needs a stable VERDICT under a mutant that ignores the data outright.
3404
- # Addendum: this pin's (1/2)-vs-(2/2) contrast only proves the
3405
- # constant separates a margin of 1 from something strictly BELOW 1 -- on integer pass counts every
3406
- # value in (0,1) is functionally identical (`c - s < b` <=> `c <= b`), so this pin cannot and does
3407
- # not claim 0.5 itself is a meaningful tolerance; it would read identically if the module held 0.25
3408
- # or 0.9 instead of 0.5. The exact literal 0.5 is pinned only by the separate "REGRESSION_SHIFT is
3409
- # exactly 0.5" literal check (point 4's own discipline, above the classifyDraw section) -- that is
3410
- # the ONLY check in this suite that would fail if 0.5 moved to another sub-1 value.
3411
- CVD_PIN_DATA='
3412
- const baseline = [2,1,2,1,2,1,1,2,1,1,2,2,2,1,2];
3413
- const candidate = [3,2,3,2,2,1,1,2,1,1,2,2,2,1,2];
3414
- const MWmod = await import("'"$ROOT"'/tests/evals/lib/mann-whitney.mjs");
3415
- '
3416
- check "D16 pin (1/2): explicit shift:1 on the constructed pair reads no-regression -- doesn't depend on the module constant at all (opts.shift passed explicitly)" \
3417
- "$(cvj "$CVD_PIN_DATA
3418
- const r = M.compareArms(baseline, candidate, { resamples: 20000, shift: 1, rng: MWmod.mulberry32(20260914) });
3419
- process.stdout.write(r.verdict);
3420
- ")" "no-regression"
3421
- check "D16 pin (2/2): the SAME pair through the DEFAULT shift (no opts.shift -- reads REGRESSION_SHIFT off the module) reads inconclusive, not no-regression -- this is what actually proves the constant is 0.5, not 1" \
3422
- "$(cvj "$CVD_PIN_DATA
3423
- const r = M.compareArms(baseline, candidate, { resamples: 20000, rng: MWmod.mulberry32(20260914) });
3424
- process.stdout.write(r.verdict);
3425
- ")" "inconclusive"
3426
- # Staged: revert REGRESSION_SHIFT to 1 (the previous margin) on the scratch copy and show pin (2/2) turns red --
3427
- # once the constant is 1 again, the DEFAULT-shift call becomes identical to pin (1/2)'s explicit
3428
- # shift:1 call, so it reads no-regression instead of the expected inconclusive.
3429
- node -e "
3430
- const fs = require('fs'); const p = '$CVD_SCRATCH'; const s = fs.readFileSync(p, 'utf8');
3431
- const FROM = 'export const REGRESSION_SHIFT = 0.5;';
3432
- const TO = 'export const REGRESSION_SHIFT = 1; // MUTANT (D16 reverted): pre-tightening margin';
3433
- if (!s.includes(FROM)) throw new Error('REGRESSION_SHIFT literal not found -- source moved');
3434
- fs.writeFileSync(p, s.replace(FROM, TO));
3435
- "
3436
- check "mutant (REGRESSION_SHIFT reverted to 1) is caught -- pin (2/2) now reads no-regression, not the expected inconclusive, proving the pin is load-bearing on the actual constant" \
3437
- "$(cvj "$CVD_PIN_DATA
3438
- const r = M.compareArms(baseline, candidate, { resamples: 20000, rng: MWmod.mulberry32(20260914) });
3439
- process.stdout.write(r.verdict);
3440
- " "$CVD_SCRATCH")" "no-regression"
3441
- cp "$ROOT/$CVD" "$CVD_SCRATCH"
3442
-
3443
- # --- confirm, by direct execution, that CVD_SIM's own point-6 floor
3444
- # barely discriminates a moderately over-conservative gate -- mutating ALPHA to 0.025 on a
3445
- # scratch copy and re-running CVD_SIM's own point-6 trial loop (unchanged T=600/RESAMPLES=3000,
3446
- # committed seeds) below. The review's own report cited this mutant as "passing only by
3447
- # floating-point rounding" (power 0.3000 read as >= a 0.30000000000000004 floor); reproduced here
3448
- # EXACTLY on the two headline numbers (180/600 accepted, floor 0.30000000000000004), but the
3449
- # STRICT comparison this suite's own `power >= floor` actually evaluates is the other way: 180/600
3450
- # is 0.29999999999999998890 as a double, one ULP-scale hair BELOW the floor, not above it -- this
3451
- # specific mutant is (barely) CAUGHT under the exact committed seeds, not a silent pass. The
3452
- # underlying concern stands regardless of which side of that hair this run lands on: 181 accepted
3453
- # trials instead of 180 (one trial out of 600) would flip `power >= floor` to true and let the
3454
- # mutant through -- the floor has essentially ZERO real margin against this specific mutant either
3455
- # way, which is the actual defect this comment records. Not staged as a `check` -- there is nothing
3456
- # stable to gate on a margin this thin; the committed guard against the underlying weakness is the
3457
- # baseline-population mutant staged right after, which has a real (non-hair-width) margin instead.
3458
- node -e "
3459
- const fs = require('fs'); const p = '$CVD_SCRATCH'; const s = fs.readFileSync(p, 'utf8');
3460
- const FROM = 'export const ALPHA = 0.05; // D5.';
3461
- const TO = 'export const ALPHA = 0.025; // MUTANT (F-310 confirm): moderately over-conservative gate';
3462
- if (!s.includes(FROM)) throw new Error('ALPHA literal not found -- source moved');
3463
- fs.writeFileSync(p, s.replace(FROM, TO));
3464
- "
3465
- F310_CONFIRM=$(cvj "$CVD_SIM
3466
- const power = M.estimatePower(drawOne, N, { rng: testRng, resamples: RESAMPLES, trials: T });
3467
- const target = 0.40, floor = target - 5 * Math.sqrt(target * (1 - target) / T);
3468
- process.stdout.write(power.toPrecision(20) + ' >= ' + floor.toPrecision(20) + ' -> ' + (power >= floor));
3469
- " "$CVD_SCRATCH")
3470
- echo " (F-310 confirm -- CVD_SIM point 6 under ALPHA=0.025 mutant: $F310_CONFIRM)"
3471
- cp "$ROOT/$CVD" "$CVD_SCRATCH"
3472
-
3473
- # the ALPHA=0.01 mutant staged here was reasoned about BACKWARDS --
3474
- # "0.01 is stricter than the earlier 0.025, so at least as hard a case" is wrong: a LOWER alpha
3475
- # suppresses `equivalence.p < alpha` MORE, so the healthy-pair no-regression rate FALLS further,
3476
- # which makes 0.01 the EASIER mutant to catch, not the harder one. Measured directly at the OLD
3477
- # T=600/RESAMPLES=3000: pristine 0.8300, ALPHA=0.025 -> 0.7283 (passed the OLD 0.6954 floor -- NOT
3478
- # caught), ALPHA=0.01 -> 0.6150 (caught). The case actually intended -- 0.025 -- escaped this
3479
- # guard exactly as it escaped CVD_SIM's own, though it was reported fixed regardless.
3480
- #
3481
- # The root cause is the floor's WIDTH, not its target: 5x its own Monte Carlo SE at T=600 is
3482
- # +/-0.0846 around 0.78, ~8 SE below the true ~0.83 rate -- room enough for a moderately
3483
- # over-conservative gate to hide inside it. Fixed by widening T/RESAMPLES for THIS check (and the
3484
- # mutant staged against it) alone -- to T=3000/RESAMPLES=1500 (~2.5x wall cost, single-digit
3485
- # seconds), not by moving the target: 5x SE shrinks to ~0.0378, floor ~0.7422. Re-derived by my own
3486
- # scan (10 independent seed/resample/trial-count combinations, T in [1500,4000], resamples in
3487
- # [1000,1800]): pristine range [0.7847, 0.8304] (committed seeds 0.8300, matching the old T=600
3488
- # reading to 4 decimals -- expected, since raising T narrows precision, not the expected value);
3489
- # ALPHA=0.025 mutant range [0.6700, 0.7228] across the SAME combinations, under the new 0.7422 floor
3490
- # at every one (margin >=0.0194, >=58 trials at T=3000; committed seeds 0.7120, margin 0.0302, ~90
3491
- # trials). ALPHA=0.01 is therefore SUBSUMED -- anything that catches 0.025 with real margin catches
3492
- # every stricter (lower) alpha too -- and is dropped as the committed mutant; staging both would
3493
- # test nothing 0.025 alone doesn't.
3494
- node -e "
3495
- const fs = require('fs'); const p = '$CVD_SCRATCH'; const s = fs.readFileSync(p, 'utf8');
3496
- const FROM = 'export const ALPHA = 0.05; // D5.';
3497
- const TO = 'export const ALPHA = 0.025; // MUTANT (F-314): the case F-310 named, moderately over-conservative';
3498
- if (!s.includes(FROM)) throw new Error('ALPHA literal not found -- source moved');
3499
- fs.writeFileSync(p, s.replace(FROM, TO));
3500
- "
3501
- D13_ALPHA025=$(cvj "$CVD_SIM_D13
3502
- const T6 = 3000, RESAMPLES6 = 1500; // F-314: trials raised 600 -> 3000 (resamples traded down 3000 -> 1500 to hold cost at ~2.5x); the floor's width depends on T alone. This check only.
3503
- const power = M.estimatePower(drawOne, N, { rng: testRng, resamples: RESAMPLES6, trials: T6 });
3504
- const target = 0.78, floor = target - 5 * Math.sqrt(target * (1 - target) / T6);
3505
- process.stdout.write(power.toFixed(4) + '>=' + floor.toFixed(4) + ' ' + (power >= floor));
3506
- " "$CVD_SCRATCH")
3507
- echo " (D13 point 6 analogue under ALPHA=0.025 mutant, T=3000/RESAMPLES=1500: $D13_ALPHA025)"
3508
- check "ALPHA=0.025 mutant (F-310's own case; F-314) is caught by the D13-population point 6 analogue with real margin at the widened T -- not the easier ALPHA=0.01 substitute" \
3509
- "$(echo "$D13_ALPHA025" | awk '{print $2}')" "false"
3510
- cp "$ROOT/$CVD" "$CVD_SCRATCH"
3511
-
3512
- # --- points 1, 2 and 6: Monte-Carlo property bounds on the verdict logic built atop the already-
3513
- # oracle-verified rank procedure (3.2 owns rank-procedure correctness; this does not re-check it).
3514
- # All three draw from the tied historical histogram ({1:9,2:4,3:5,4:2,5:1}) via CVD_SIM,
3515
- # defined above (before the mutation section, since mutant D's second check needs it too). Trial/
3516
- # resample counts are stated so every tolerance is derived, never loosened to fit.
3517
- #
3518
- # margin change (REGRESSION_SHIFT 1 -> 0.5): point 1's target is UNCHANGED -- `regression` is decided from
3519
- # `primary.p < alpha` alone, before `compareArms()` ever reads `shift` (see the early return above
3520
- # `shifted` is computed), so this rate is a function of ALPHA and the historical sigma only, never the margin.
3521
- # Checked directly, not assumed: re-run against the tracked module with shift explicitly 1 and 0.5,
3522
- # both gave 0.0367 to four decimals, same seeds. Left as-is; this is the original-sigma case, left alone and noted rather than re-derived.
3523
- POINT1=$(cvj "$CVD_SIM
3524
- let regressions = 0;
3525
- for (let t = 0; t < T; t++) {
3526
- const r = M.compareArms(drawArm(N), drawArm(N), { resamples: RESAMPLES, rng: testRng });
3527
- if (r.verdict === 'regression') regressions++;
3528
- }
3529
- const rate = regressions / T, bound = 0.05 + 5 * Math.sqrt(0.05 * 0.95 / T);
3530
- process.stdout.write(rate.toFixed(4) + '<=' + bound.toFixed(4) + ' ' + (rate <= bound));
3531
- ")
3532
- echo " (point 1 measured: $POINT1)"
3533
- check "point 1 -- one-sided size bound: empirical regression rate on UNSHIFTED (null) pairs <= 0.05 + 5x its own Monte Carlo SE, T=600 (one-sided, not a tight two-sided interval; margin-invariant, D16 -- see comment above)" \
3534
- "$(echo "$POINT1" | awk '{print $2}')" "true"
3535
-
3536
- # Margin change: this bound DOES depend on the margin, and is re-derived, not left in place. The scenario is
3537
- # unchanged (a genuinely +1-pass-degraded arm) but the margin no longer sits AT that effect size --
3538
- # at REGRESSION_SHIFT=1 the shifted candidate reduces to a resample of the baseline's own
3539
- # distribution (a null test, false-accept rate near ALPHA, which is why the old target was 0.08).
3540
- # At 0.5 the shifted candidate is still elevated 0.5 passes over baseline, so equivalence rarely
3541
- # reads significant. Re-measured (this exact CVD_SIM population/seeds, module REGRESSION_SHIFT=0.5):
3542
- # 0.33% at T=600; independently reconfirmed across 5 other seed/resample/trial-count combinations
3543
- # (T up to 6000) at 0.20%-0.33%, never above -- the range this target is drawn from, same method
3544
- # used to set the original 0.08 from its own "4.7-8% depending on resample count" scan.
3545
- # Target 0.005 sits above every measured reading, not fitted to the committed run's own 0.33%.
3546
- POINT2=$(cvj "$CVD_SIM
3547
- let falseAccepts = 0;
3548
- for (let t = 0; t < T; t++) {
3549
- const r = M.compareArms(drawArm(N), drawArm(N).map((v) => v + 1), { resamples: RESAMPLES, rng: testRng });
3550
- if (r.verdict === 'no-regression') falseAccepts++;
3551
- }
3552
- const rate = falseAccepts / T, bound = 0.005 + 5 * Math.sqrt(0.005 * 0.995 / T);
3553
- process.stdout.write(rate.toFixed(4) + '<=' + bound.toFixed(4) + ' ' + (rate <= bound));
3554
- ")
3555
- echo " (point 2 measured: $POINT2)"
3556
- check "point 2 -- bound the false no-regression rate on truly-shifted (+1 pass, degraded) arms: <= 0.005 + 5x its own Monte Carlo SE, T=600 -- re-derived for D16's 0.5 margin (was 0.08 at margin 1; see comment above), the number the three-state verdict exists to control" \
3557
- "$(echo "$POINT2" | awk '{print $2}')" "true"
3558
-
3559
- # point 6's SECOND half: a lower bound on the no-regression rate for UNSHIFTED
3560
- # (healthy) pairs -- the direction NOTHING else in this suite bounds. Reuses estimatePower()
3561
- # itself (built once inside convergence.mjs), not a hand-rolled reimplementation of the
3562
- # same trial loop -- CVD_SIM's own `drawOne` is passed straight through.
3563
- #
3564
- # Margin change: the old floor was the original STATED normal-approximation power for a +1-pass shift (0.716),
3565
- # which happened to sit within ~1 point of this test's own tie-conditional measurement (~0.72) at
3566
- # margin 1 -- a coincidence of that specific margin, not a property of the method. At margin
3567
- # 0.5 the same normal-approximation formula (d = 0.5/1.236354, n=15, the original
3568
- # Phi(d*sqrt(n/2) - z_0.05)) predicts ~29.6% -- but the ACTUAL tie-conditional Monte Carlo rate
3569
- # (the real, in-use test) measures materially higher: 39.8%-42.65% across 5 independent
3570
- # seed/resample/trial-count combinations, including the committed seeds' own 42.5%. The normal
3571
- # approximation is known invalid for this heavily-tied integer data (a known correction) -- more
3572
- # so the smaller the effect, since ties dominate a smaller shift more. The floor below is derived
3573
- # from the MEASURED range -- target 0.40 is CLOSE to that range, NOT below every reading in it (the
3574
- # lowest scan, 39.8%, sits below 0.40 -- corrected here: an earlier version of this
3575
- # comment claimed the opposite, "sits at/below every reading," which was false by inspection of its
3576
- # own cited numbers). The real safety margin is the floor's own 5x-Monte-Carlo-SE subtraction (0.40
3577
- # -> 0.30), which every one of the 39.8%-42.65% readings clears comfortably; the target itself is
3578
- # not, and does not need to be, a lower bound on the scan -- only the floor does that job.
3579
- #
3580
- # this is CVD_SIM's stress-case population (sd~1.24) -- see the
3581
- # relabeling comment at CVD_SIM's own definition above. This floor is also known WEAK against a
3582
- # moderately over-conservative gate specifically: an ALPHA=0.025 mutant measures 180/600=0.3000
3583
- # here, against a floor of 0.30000000000000004 -- one ULP-scale hair below it (verified above: this
3584
- # specific committed run is barely CAUGHT, not a silent pass, but a single trial's outcome either
3585
- # way, 179 or 181 of 600, would flip the verdict). Effectively zero real margin either direction,
3586
- # which is the actual weakness -- not fixed here since CVD_SIM is the deliberate stress case.
3587
- # The baseline-population analogue below does not share this weakness -- staged against the SAME
3588
- # ALPHA=0.025 mutant that nearly slipped past CVD_SIM's own floor here (not the easier
3589
- # ALPHA=0.01 substitute this comment cited before), at a widened T=3000/RESAMPLES=1500 (the floor's
3590
- # WIDTH, not its target, was the actual gap), it is caught with a real (non-hair-width) margin,
3591
- # 0.7120 against a 0.7422 floor -- ~90 trials at T=3000, not a single-trial hair.
3592
- POINT6=$(cvj "$CVD_SIM
3593
- const power = M.estimatePower(drawOne, N, { rng: testRng, resamples: RESAMPLES, trials: T });
3594
- const target = 0.40; // measured tie-conditional floor at REGRESSION_SHIFT=0.5, D16 -- see comment above
3595
- const floor = target - 5 * Math.sqrt(target * (1 - target) / T);
3596
- process.stdout.write(power.toFixed(4) + '>=' + floor.toFixed(4) + ' ' + (power >= floor));
3597
- ")
3598
- echo " (point 6 measured: $POINT6)"
3599
- check "point 6 (2/2) -- lower bound on the no-regression rate for UNSHIFTED (healthy) pairs, >= 0.40 (measured tie-conditional floor, D16 -- was D2's stated 0.716 at margin 1) minus 5x its own Monte Carlo SE, T=600 -- bounds the direction F-221 found unbounded" \
3600
- "$(echo "$POINT6" | awk '{print $2}')" "true"
3601
-
3602
- # --- baseline-population analogues: it was measured that the real
3603
- # baseline ([2,1,2,1,2,1,1,2,1,1,2,2,2,1,2], mean 1.5333, sd 0.5164) is the
3604
- # population the margin-gated /code-loop comparison actually draws from, NOT the wider mixed-history
3605
- # one CVD_SIM uses (point 2/6 above). Re-derived independently here by bootstrap resampling
3606
- # (CVD_SIM_D13, defined near CVD_SIM above), own committed seeds. T differs per check: the point-2 analogue below runs at the preamble's own T=600/RESAMPLES=3000; the
3607
- # point-6 analogue runs at T=3000/RESAMPLES=1500, widened because the floor's width
3608
- # depends on T alone. Not copied from the earlier resampling scripts
3609
- # (which share one rng stream where this suite's discipline keeps three -- a design
3610
- # difference, NOT the reason the two readings differ; see the point-2 analogue's own note below),
3611
- # so the two are expected to agree in MAGNITUDE, not to the decimal, as independent Monte Carlo
3612
- # estimates of the same quantity.
3613
-
3614
- # baseline point 6 analogue: healthy-pair (no injected degradation) no-regression rate.
3615
- #
3616
- # T/RESAMPLES for THIS check widened from the shared CVD_SIM_D13
3617
- # preamble's T=600/RESAMPLES=3000 to T=3000/RESAMPLES=1500 -- trials raised, resamples traded down,
3618
- # ~2.5x wall cost (single-digit seconds); the floor's width depends on T alone
3619
- # -- the floor's WIDTH, not its target, was what let a moderately over-conservative gate
3620
- # (ALPHA=0.025, the intended case) escape at T=600: 5x this floor's own Monte Carlo SE there is
3621
- # 0.0846, ~8 SE below the true ~0.83 rate, room enough to hide a real weakening of the gate's own
3622
- # strictness. At T=3000 the same 5x SE shrinks to ~0.0378 -- see the ALPHA mutant staged against
3623
- # this exact check, in the mutation section above (it also subsumes the
3624
- # easier ALPHA=0.01 substitute).
3625
- #
3626
- # Re-scanned at the new T (my own scan, not pasted from the review): 10 independent
3627
- # seed/resample/trial-count combinations, T in [1500,4000], resamples in [1000,1800]: range
3628
- # [0.7847, 0.8304] (committed seeds 0.8300, unchanged from the old T=600 reading to 4 decimals --
3629
- # expected, since a larger T narrows precision, not the expected value). Target stays 0.78. It sits
3630
- # below every reading in THIS scan, but that is not relied on as a guaranteed property of the
3631
- # population -- the "strictly below" framing this comment used to make is exactly the overclaim
3632
- # found elsewhere in this file (a wider scan can always turn up a lower reading, as
3633
- # it did for the CVD_SIM point 6 target and for this same target at the old T=600 width). The real
3634
- # safety margin is the floor's own 5x-Monte-Carlo-SE subtraction (0.78 -> ~0.7422 at T=3000), which
3635
- # every one of the 10 readings above clears with real room (>=0.0425).
3636
- D13_POINT6=$(cvj "$CVD_SIM_D13
3637
- const T6 = 3000, RESAMPLES6 = 1500; // F-314: widened from the shared T/RESAMPLES above, this check only
3638
- const power = M.estimatePower(drawOne, N, { rng: testRng, resamples: RESAMPLES6, trials: T6 });
3639
- const target = 0.78; // measured floor, D13 population, F-309/F-314 -- see comment above
3640
- const floor = target - 5 * Math.sqrt(target * (1 - target) / T6);
3641
- process.stdout.write(power.toFixed(4) + '>=' + floor.toFixed(4) + ' ' + (power >= floor));
3642
- ")
3643
- echo " (D13 point 6 analogue measured, T=3000/RESAMPLES=1500: $D13_POINT6)"
3644
- check "D13-population point 6 analogue -- lower bound on the no-regression rate for UNSHIFTED (healthy) pairs drawn from the REAL baseline population, >= 0.78 minus 5x its own Monte Carlo SE, T=3000 (F-309/F-314: this is what the operative D16 gate's real accept rate looks like, not CVD_SIM's stress-case figure)" \
3645
- "$(echo "$D13_POINT6" | awk '{print $2}')" "true"
3646
-
3647
- # baseline point 2 analogue: false no-regression rate under a genuinely +0.5-pass DEGRADED candidate --
3648
- # the SAME "each draw gains a pass with probability 0.5" model the earlier resampling used to
3649
- # report "+0.5 pass" (distinct from points 1/2's own flat +1 CVD_SIM shift above, which models the
3650
- # original alternative hypothesis). Scanned across 8 independent seed/resample/trial-count combinations: range measured
3651
- # [0.0533, 0.0883] (committed seeds: 0.0767). Target set to 0.10, strictly ABOVE every reading in
3652
- # that scan -- comfortably clear of the earlier cited ~5.3%.
3653
- #
3654
- # a prior version of this comment attributed the gap between this
3655
- # harness's reading (0.0767) and the earlier cited ~5.3% to rng-stream discipline (three independent
3656
- # streams here vs. one shared stream in the earlier script). Wrong on two counts, checked
3657
- # directly rather than assumed. (1) The degradation model does NOT differ: both apply
3658
- # a Bernoulli draw with p=0.5, plus 1, to the same bootstrapped draw (`bumpRng() < 0.5 ? 1 : 0` here;
3659
- # `rng() < 0.5 ? v+1 : v` in the earlier resampling script -- read side by side, not
3660
- # just described). (2) Stream-sharing reads HIGHER than three streams, not lower -- the opposite
3661
- # sign a "three streams understate it" story would need: an independent scan (shared-stream mean
3662
- # 0.0700 across 10 seeds vs. three-stream mean 0.0680 across 10 combinations, both at
3663
- # T=600/RESAMPLES=3000) shows no systematic direction from stream count at all.
3664
- #
3665
- # The gap is Monte Carlo noise, not methodology. The earlier cited 5.3% is 16 of 300 trials at its own
3666
- # script's defaults (SE = sqrt(0.053*0.947/300) ~= 1.3%); re-running that SAME script
3667
- # (the earlier resampling script, unedited, its own defaults) just now gives **7.0%** --
3668
- # about 1.3 SE from the recorded 5.3%, i.e. ordinary trial-to-trial noise at TRIALS=300, not a
3669
- # discrepancy needing a cause. This harness's own three-stream committed reading is 0.0767; an
3670
- # independent 10+10-seed scan combining both stream disciplines spans [0.0483, 0.0850]. All of this
3671
- # sits well inside the target's own 0.10 bound. The three-independent-streams discipline itself
3672
- # stays (the no-shared-call-count-dependency reasoning, restated at CVD_SIM_D13's
3673
- # definition above) -- it is a design choice made for its own reason, not an explanation for a
3674
- # discrepancy that turned out to be ordinary sampling noise.
3675
- D13_POINT2=$(cvj "$CVD_SIM_D13
3676
- let falseAccepts = 0;
3677
- for (let t = 0; t < T; t++) {
3678
- const baseline = drawArm(N);
3679
- const candidate = drawArm(N).map((v) => v + (bumpRng() < 0.5 ? 1 : 0));
3680
- const r = M.compareArms(baseline, candidate, { resamples: RESAMPLES, rng: testRng });
3681
- if (r.verdict === 'no-regression') falseAccepts++;
3682
- }
3683
- const rate = falseAccepts / T, bound = 0.10 + 5 * Math.sqrt(0.10 * 0.90 / T);
3684
- process.stdout.write(rate.toFixed(4) + '<=' + bound.toFixed(4) + ' ' + (rate <= bound));
3685
- ")
3686
- echo " (D13 point 2 analogue measured: $D13_POINT2)"
3687
- check "D13-population point 2 analogue -- bound the false no-regression rate on a truly +0.5-pass-degraded arm (Bernoulli model, D15/D16), drawn from the REAL baseline population: <= 0.10 + 5x its own Monte Carlo SE, T=600 (F-309)" \
3688
- "$(echo "$D13_POINT2" | awk '{print $2}')" "true"
3689
-
3690
- echo
3691
- printf ' %d passed, %d failed\n' "$pass" "$fail"
3692
- [ "$fail" -eq 0 ]