@skathio/somi 4.1.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +83 -228
  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 +28 -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 +40 -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 +165 -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 +73 -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 +38 -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 +181 -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,351 +0,0 @@
1
- #!/usr/bin/env node
2
- // Tests of the composite steps that end a pass and a loop, `after-review` and `close` (scripts/lib/loop-step-review.mjs,
3
- // loop-step-close.mjs): parity with the primitives, the circuit breaker, kill and replay after each sub-step, the diff-gate
4
- // tie, validation and confinement, the closing notes, and the engine's endLoop.
5
- // Run by tests/scripts/loop-engine.sh.
6
-
7
- import { createHash } from 'node:crypto';
8
- import { execFileSync } from 'node:child_process';
9
- import { existsSync, lstatSync, lutimesSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs';
10
- import { tmpdir } from 'node:os';
11
- import path from 'node:path';
12
- import { fileURLToPath } from 'node:url';
13
- import { isDeepStrictEqual } from 'node:util';
14
- import { BUDGET, FIELDS, runStep } from '../../../scripts/lib/loop-step.mjs';
15
- import { checkDiff, documentedStatus, finish, init, pass as passPrim, recordDispatch, recordPass, reviewScope, STOP_REASONS } from '../../../scripts/lib/loop-engine.mjs';
16
- import { CAP_BREACH_STATUSES } from '../../evals/lib/convergence.mjs';
17
- import { ARG, MODES, SUB_STEPS } from '../../../scripts/lib/loop-step-kit.mjs';
18
- import { recordFindings, resolveFinding } from '../../../scripts/lib/findings-ledger.mjs';
19
- import { stateFile } from '../../../scripts/lib/loop-state.mjs';
20
-
21
- const SOMI = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
22
- let pass = 0; let fail = 0;
23
- const check = (name, got, want) => {
24
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
25
- };
26
- const tmp = mkdtempSync(path.join(tmpdir(), 'loop-step-review-'));
27
- process.on('exit', () => rmSync(tmp, { recursive: true, force: true }));
28
-
29
- const NOW = '2026-10-29T09:30:00Z';
30
- const ROWS = '# Progress — p1\n\n## Iteration progress\n\n| Iteration | Title | Status | Reviewed | Last activity |\n|---|---|---|---|---|\n| 1.1 | one | not-started | — | — |\n\n**Last activity**: 2026-10-28 — seeded\n';
31
- const DIARY = '# Diary — p1\n\n---\n\n## 2026-10-28 10:00 — Plan\n\n**Category**: `note`\n**Phase**: 1\n\nbody\n\n---\n\n';
32
- const prim = { slug: 'p1', loop: 'code', iteration: '1.1', files: 'a.js', force: false, status: '', maxPasses: '', diffCap: '', severity: '', maxMinutes: '', verdict: '', blockers: '0', majors: '0', agent: '' };
33
- const F = (n, severity = 'Major') => ({ file: `f${n}.js`, symbol: 's', title: `finding ${n} here`, severity, confidence: 'High' });
34
- let n = 0;
35
- function repo() {
36
- const root = path.join(tmp, `r${n++}`); mkdirSync(root);
37
- const git = (...a) => execFileSync('git', ['-C', root, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a]);
38
- git('init', '-q'); writeFileSync(path.join(root, 'a.js'), '1\n'); git('add', 'a.js'); git('commit', '-q', '-m', 'base');
39
- for (const slug of ['p1', 'pl']) { mkdirSync(path.join(root, '.somi', 'plans', slug, 'phases'), { recursive: true }); writeFileSync(path.join(root, '.somi', 'plans', slug, 'diary.md'), DIARY); writeFileSync(path.join(root, '.somi', 'plans', slug, 'progress.md'), ROWS); }
40
- const ctx = (env = {}, o = {}) => ({ root, env: { SOMI_GLOBAL_CONFIG: '', ...env }, stateDir: path.join(root, '.somi', 'somi-state', 'loop'), installRoot: SOMI, now: () => NOW, via: 'mcp', ...o });
41
- const sf = stateFile(ctx().stateDir, 'p1', '1.1');
42
- return { root, ctx, sf, state: () => JSON.parse(readFileSync(sf, 'utf8')), put: (fn) => writeFileSync(sf, JSON.stringify(fn(JSON.parse(readFileSync(sf, 'utf8'))))), file: (f, t) => writeFileSync(path.join(root, f), t),
43
- diary: () => readFileSync(path.join(root, '.somi', 'plans', 'p1', 'diary.md'), 'utf8'), ledger: () => JSON.parse(readFileSync(path.join(root, '.somi', 'reviews', 'p1', 'findings.json'), 'utf8')) };
44
- }
45
- const step = (r, name, args = {}, env, o) => runStep(r.ctx(env, o), { step: name, slug: 'p1', iteration: '1.1', ...args });
46
- const open = (r, args = {}, env, o) => step(r, 'open', { files: 'a.js', ...args }, env, o);
47
- const after = (r, args = {}) => step(r, 'after-code', { agent: 'somi-coder', ...args });
48
- const close = (r, args = {}, env, o) => step(r, 'close', { status: 'done', ...args }, env, o);
49
- const progress = (r) => readFileSync(path.join(r.root, '.somi', 'plans', 'p1', 'progress.md'), 'utf8');
50
- const review = (r, args = {}, env, o) => step(r, 'after-review', { reviewers: ['somi-reviewer'], verdict: 'approve', blockers: 0, majors: 0, review: 'r1.md', ...args }, env, o);
51
- // A repo at an after-code that passed, with a.js changed by `lines` lines.
52
- const gated = (lines = 3, env) => { const r = repo(); open(r, {}, env); r.file('a.js', '1\n'.repeat(lines)); after(r); return r; };
53
- const bytes = (x) => Buffer.byteLength(JSON.stringify(x));
54
- const tree = (root) => Object.fromEntries(readdirSync(root, { recursive: true }).filter((f) => !f.startsWith('.git')).sort().map((f) => [f, lstatSync(path.join(root, f)).isFile() ? createHash('sha256').update(readFileSync(path.join(root, f))).digest('hex') : 'dir']));
55
- const entries = (r) => r.diary().split('\n').filter((l) => l.startsWith('## ')).length;
56
- const dies = (fn) => { try { fn(); } catch (e) { return e.message; } return 'no throw'; };
57
- // What criterion 2 compares: the state's history, dispatches and caps with times and tree ids dropped, and the ledger with dates dropped.
58
- const norm = (r) => { const s = r.state(); const l = (() => { try { return r.ledger(); } catch { return null; } })();
59
- return { st: s.status, pass: s.pass, caps: s.caps, co: s.cap_overrides, d: s.dispatches, h: s.history.map(({ at, tree: t, ...h }) => h), l: l && { ...l, findings: l.findings.map((f) => ({ ...f, seen: f.seen.map(({ date, ...x }) => x) })) } }; };
60
- const DATE = () => '2026-10-29';
61
-
62
- console.log('== parity with the primitives (criterion 2) ==');
63
- {
64
- const a = repo(); const b = repo(); const bf = (over) => ({ ...prim, ...over });
65
- const run = (args) => ({ root: b.root, slug: 'p1', run: b.state().started, now: DATE, ...args });
66
- open(a); a.file('a.js', '1\n2\n3\n'); after(a);
67
- const clean = review(a); const closed = close(a);
68
- init(b.ctx(), prim); passPrim(b.ctx(), prim); b.file('a.js', '1\n2\n3\n'); recordDispatch(b.ctx(), bf({ agent: 'somi-coder' })); checkDiff(b.ctx(), prim); reviewScope(b.ctx(), prim);
69
- recordDispatch(b.ctx(), bf({ agent: 'somi-reviewer' })); recordPass(b.ctx(), bf({ verdict: 'approve' })); const fin = finish(b.ctx(), bf({ status: 'done' }));
70
- check('one clean pass through the steps leaves the history, dispatches, caps and cap_overrides of the same pass through the primitives; the step says close with done', [norm(a), clean.next, clean.close_args], [norm(b), 'close', { status: 'done' }]);
71
- const line = (x) => `${x.agent} ${x.tier} ${x.model}${x.enforced === true ? '' : ' (not enforced)'}`;
72
- check('close ends the loop as finish does: the same state, and its dispatches as the lines finish lists them', [closed.ok, closed.status, closed.dispatches, closed.cap_overrides], [true, 'done', fin.out.dispatches.map(line), undefined]);
73
- const c = repo(); const d = repo();
74
- open(c); c.file('a.js', '1\n2\n'); after(c); const first = review(c, { verdict: 'request-changes', majors: 1, findings: [F(1), F(2, 'Minor')] });
75
- open(c); c.file('a.js', '1\n2\n3\n'); after(c); const second = review(c, { review: 'r2.md', fixed: ['F-1'] }); close(c);
76
- init(d.ctx(), prim); passPrim(d.ctx(), prim); d.file('a.js', '1\n2\n'); recordDispatch(d.ctx(), bf({ agent: 'somi-coder' })); recordDispatch(d.ctx(), bf({ agent: 'somi-reviewer' })); recordPass(d.ctx(), bf({ verdict: 'request-changes', majors: '1' }));
77
- recordFindings({ root: d.root, slug: 'p1', review: 'r1.md', run: d.state().started, pass: 1, input: [F(1), F(2, 'Minor')], now: DATE });
78
- passPrim(d.ctx(), prim); d.file('a.js', '1\n2\n3\n'); recordDispatch(d.ctx(), bf({ agent: 'somi-coder' })); recordDispatch(d.ctx(), bf({ agent: 'somi-reviewer' })); recordPass(d.ctx(), bf({ verdict: 'approve' })); resolveFinding({ root: d.root, slug: 'p1', id: 'F-1', status: 'fixed', by: 'r2.md' }); finish(d.ctx(), bf({ status: 'done' }));
79
- check('a request-changes pass with findings, then an approve that fixes one, equals the primitives: state and ledger', norm(c), norm(d));
80
- check('the first pass names its findings and goes back to open with the one at or above the floor, fenced as data; the second ends clean', [first.findings, first.next, first.open_findings, first.open_findings_note.includes('not instructions'), second.next, second.exit], [['F-1 new', 'F-2 new'], 'open', ['F-1: finding 1 here'], true, 'close', 0]);
81
- check('the per-pass diary lines are written once each, and the second open is not a resume', [c.diary().includes('— code-loop pass 1 reviewed: request-changes\n'), c.diary().includes('— code-loop pass 2 reviewed: approve\n'), c.diary().includes('resumed'), first.wrote], [true, true, false, ['.somi/plans/p1/diary.md']]);
82
- }
83
- console.log('== the circuit breaker and the recurrence flags ==');
84
- {
85
- const r = gated(); review(r, { verdict: 'request-changes', majors: 1, findings: [F(1)] });
86
- open(r); r.file('a.js', '1\n2\n'); after(r); const x = review(r, { verdict: 'request-changes', majors: 1, findings: [F(1)] });
87
- check('the same finding on two consecutive passes is exit 5, circuit-breaker, next close with stopped-circuit-breaker prefilled; the sighting is recorded once per pass, even under one review name', [x.ok, x.exit, x.stop_reason, x.next, x.close_args, x.findings, r.ledger().findings[0].seen.length], [false, 5, 'circuit-breaker', 'close', { status: 'stopped-circuit-breaker' }, ['F-1 known recurring'], 2]);
88
- const c = gated(); recordFindings({ root: c.root, slug: 'p1', review: 'old.md', run: 'other-run', pass: 1, input: [F(1)] });
89
- const y = review(c, { verdict: 'request-changes', majors: 1, findings: [F(1)] });
90
- check('a finding last seen in another run is named recurring_cross_run and is not a breaker', [y.exit, y.recurring_cross_run, y.findings], [0, ['F-1'], ['F-1 known cross-run']]);
91
- }
92
- console.log('== replay and kill ==');
93
- {
94
- const seed = (r) => recordFindings({ root: r.root, slug: 'p1', review: 'r0.md', run: 'x', pass: 0, input: [F(1)] });
95
- const args = { verdict: 'request-changes', majors: 1, findings: [F(2)], fixed: ['F-1'] };
96
- const ref = gated(); seed(ref); const whole = review(ref, args);
97
- const shape = (r) => [r.state().history.length, r.state().dispatches.length, r.ledger().findings.map((f) => [f.id, f.status, f.seen.length]), entries(r)];
98
- const got = ['dispatch', 'record', 'findings', 'resolve', 'diary'].map((sub) => { const r = gated(); seed(r); const k = dies(() => review(r, args, {}, { failAfter: sub })); const done = review(r, args); return [k, done.ok, done.next, done.findings, shape(r)]; });
99
- check('after-review killed after each of its five sub-steps and retried leaves one history entry, one reviewer dispatch, one sighting and one diary line, as one uninterrupted call does', got, ['dispatch', 'record', 'findings', 'resolve', 'diary'].map((s) => [`failAfter ${s}`, true, whole.next, whole.findings, shape(ref)]));
100
- const k = gated(); seed(k); dies(() => review(k, args, {}, { failAfter: 'record' }));
101
- check('the status step lists the new sub-steps of an unfinished after-review', step(k, 'status').cursor.at(-1), { key: '1:after-review', via: 'mcp', done: ['dispatch', 'record'], complete: false });
102
- check('the after-review cursor holds the arguments\' signature and no copy of the review file name', ['sig', 'file'].map((f) => f in ref.state().steps['1:after-review']), [true, false]);
103
- const again = review(ref, args);
104
- check('a finished after-review repeats as replayed with the same answer and writes nothing more', [again.replayed, again.next, again.findings, shape(ref)], [true, whole.next, whole.findings, shape(ref)]);
105
- const diff = review(ref, { ...args, review: 'r9.md' });
106
- check('a repeat with other arguments is refused 64 and changes nothing', [diff.exit, diff.error?.split(':')[0], shape(ref)], [64, 'arguments', shape(ref)]);
107
- const g = gated(); recordFindings({ root: g.root, slug: 'p1', review: 'r1.md', run: g.state().started, pass: 1, input: [F(1)] });
108
- review(g, { verdict: 'request-changes', majors: 1, findings: [F(1)] });
109
- check('a ledger write that landed before its mark (a crash between the two) is not counted again on retry: one sighting', g.ledger().findings[0].seen.length, 1);
110
- }
111
- console.log('== the diff gate is tied to the tree (an unmeasured tree is not gated) ==');
112
- {
113
- const stale = gated(); stale.file('a.js', 'changed after the gate\n'); const before = [tree(stale.root), stale.state()];
114
- const x = review(stale);
115
- check('a working tree changed after the passing after-code is refused 64 naming after-code as the remedy, and nothing is written', [x.exit, x.error?.includes('call after-code'), tree(stale.root), stale.state()], [64, true, ...before]);
116
- const gone = gated(); gone.put((s) => { delete s.steps['1:after-code'].measured; return s; });
117
- const open1 = repo(); open(open1);
118
- check('a pass whose after-code stored no measured tree, or that had no after-code at all, is refused the same way', [review(gone).exit, review(open1).exit, review(open1).error?.includes('call after-code')], [64, 64, true]);
119
- const resumed = gated(); dies(() => review(resumed, {}, {}, { failAfter: 'record' })); resumed.file('a.js', 'x\n'.repeat(9));
120
- check('once the pass is recorded a resume is not blocked by a tree that moved since', review(resumed).ok, true);
121
- const p = repo(); runStep(p.ctx(), { step: 'open', slug: 'pl', loop: 'plan' }); runStep(p.ctx(), { step: 'after-code', slug: 'pl', loop: 'plan', agent: 'somi-planner' });
122
- const pr = runStep(p.ctx(), { step: 'after-review', slug: 'pl', loop: 'plan', reviewers: ['somi-reviewer'], verdict: 'approve', blockers: 0, majors: 0, review: 'r1.md' });
123
- check('a plan loop needs no gate: its after-review records the pass and says close', [pr.ok, pr.next, JSON.parse(readFileSync(stateFile(p.ctx().stateDir, 'pl', ''), 'utf8')).history.length], [true, 'close', 1]);
124
- }
125
- console.log('== what comes next, and the size of the answer ==');
126
- {
127
- const r = gated(); recordFindings({ root: r.root, slug: 'p1', review: 'r0.md', run: 'x', pass: 0, input: Array.from({ length: 300 }, (_, i) => F(i + 1)) });
128
- const x = review(r, { verdict: 'request-changes', majors: 100, findings: Array.from({ length: 100 }, (_, i) => F(i + 1)) });
129
- const more = Number(/^\(\+(\d+) more/.exec(x.open_findings?.at(-1))?.[1]);
130
- check('300 open findings and 100 recorded: the answer fits the budget, lists 12 of the 100 and counts the rest, and counts what the open list cuts', [bytes(x) <= BUDGET, x.findings.length, x.findings_total, x.open_findings.length - 1 + more], [true, 12, 100, 300]);
131
- const m = gated(); const y = review(m, { verdict: 'request-changes', findings: [F(1, 'Minor')] });
132
- check('a request-changes with nothing at or above the floor ends clean: close with done', [y.next, y.close_args], ['close', { status: 'done' }]);
133
- const u = gated(); const z = review(u, { verdict: 'request-changes', majors: 1, findings: [F(1)] });
134
- const v = gated(); recordFindings({ root: v.root, slug: 'p1', review: 'r0.md', run: 'x', pass: 0, input: [F(1, 'Minor')] }); const w = review(v);
135
- check('a request-changes with an open Major goes back to open; an approve ends the loop whatever sits below the floor in the ledger', [z.next, z.close_args, w.next, w.close_args], ['open', undefined, 'close', { status: 'done' }]);
136
- }
137
- console.log('== arguments and confinement: refused 64 naming the field, nothing written ==');
138
- {
139
- const r = gated(); const before = tree(r.root);
140
- const bad = [['reviewers', { reviewers: [] }], ['reviewers', { reviewers: ['a', 'b', 'c', 'd', 'e'] }], ['reviewers', { reviewers: ['../x'] }], ['verdict', { verdict: 'fine' }], ['review', { review: '../x' }], ['review', { review: 'a/b.md' }], ['review', { review: '..' }],
141
- ['blockers', { blockers: -1 }], ['majors', { majors: 'x' }], ['findings', { findings: [{ file: 'a.js' }] }], ['findings', { findings: [{ file: 'a.js', title: 't', severity: 'Huge' }] }], ['findings', { findings: [{ file: 'a\n.js', title: 't' }] }],
142
- ['findings', { findings: Array.from({ length: 101 }, () => F(1)) }], ['fixed', { fixed: ['F-1; rm'] }],
143
- ['blockers', { blockers: 3 }], ['majors', { majors: 1 }], ['findings', { findings: [{ file: 'a.js', title: 't' }] }], ['verdict', { majors: 1, findings: [F(1)] }], ['verdict', { verdict: 'approve-with-comments', blockers: 1, findings: [F(1, 'Blocker')] }],
144
- ['reviewers', { reviewers: ['somi-coder'] }], ['reviewers', { reviewers: ['somi-reviewer', 'somi-coder'] }], ['reviewers', { reviewers: ['no-such-agent'] }], ['reviewers', { reviewers: ['somi-reviewer', 'somi-reviewer'] }], ['findings', { findings: [{ ...F(1), title: 'a\u202eb' }] }], ['findings', { findings: [{ ...F(1), title: 'a\u2028b' }] }],
145
- ['fixed', { verdict: 'request-changes', majors: 1, findings: [F(1)], fixed: ['F-1'] }], ['fixed', { fixed: 'F-1' }], ['agent', { agent: 'somi-coder' }], ['diff_cap', { diff_cap: 1 }]];
146
- const got = bad.map(([f, a]) => { const x = review(r, a); return [x.exit, new RegExp(`^${f}(\\[\\d+\\](\\.\\w+)?)?:`).test(x.error ?? '')]; }); // a finding is named by its index and field
147
- check('a bad reviewers list, verdict, review name, count, finding, fixed id or foreign field exits 64 naming its field', got, bad.map(() => [64, true]));
148
- check('none of these wrote anything: the tree is byte-identical and no cursor was made', [tree(r.root), Object.keys(r.state().steps)], [before, ['1:open', '1:after-code']]);
149
- const shapes = ['{"next_id":"x","findings":[]}', '{"next_id":1000000,"findings":[]}', '{"next_id":1,"findings":[{"id":"F-1","key":"k","status":"open","seen":[5]}]}', '{"next_id":1,"findings":[{"id":"F-1","key":"k","seen":[]}]}'];
150
- const shaped = shapes.map((json) => { const m = gated(); mkdirSync(path.join(m.root, '.somi', 'reviews', 'p1'), { recursive: true }); writeFileSync(path.join(m.root, '.somi', 'reviews', 'p1', 'findings.json'), json); const t = tree(m.root); const x = review(m, { verdict: 'request-changes', majors: 1, findings: [F(1)] });
151
- return [x.exit, x.error?.includes('findings ledger'), isDeepStrictEqual(tree(m.root), t), Object.keys(m.state().steps).length]; });
152
- check('a ledger not in the shape the ledger functions assume (next_id, a sighting, a missing status) is refused 64 before any step is recorded', shaped, shapes.map(() => [64, true, true, 2]));
153
- for (const [name, link] of [['a symlinked reviews directory', 'reviews'], ['a symlinked findings.json', 'reviews/p1/findings.json']]) {
154
- const s = gated(); mkdirSync(path.join(s.root, 'elsewhere')); mkdirSync(path.join(s.root, '.somi', 'reviews', 'p1'), { recursive: true });
155
- if (link === 'reviews') { rmSync(path.join(s.root, '.somi', 'reviews'), { recursive: true }); symlinkSync(path.join(s.root, 'elsewhere'), path.join(s.root, '.somi', 'reviews')); } else symlinkSync(path.join(s.root, 'elsewhere', 'f.json'), path.join(s.root, '.somi', link));
156
- const t = tree(s.root); const x = review(s, { verdict: 'request-changes', majors: 1, findings: [F(1)] });
157
- check(`${name} is refused 64 before anything is recorded, and nothing is written`, [x.exit, x.error?.includes('findings ledger'), tree(s.root)], [64, true, t]);
158
- }
159
- }
160
- console.log('== the pass\'s own checks: reviewer lens, fixed ids, the saved ledger, the signature ==');
161
- {
162
- const lens = (env, rev, tweak = (r) => r) => { const r = repo(); open(r); r.file('a.js', '1\n2\n'); step(r, 'after-code', { agent: 'somi-coder' }, env); tweak(r); return review(r, { reviewers: rev }).exit; };
163
- const R = 'somi-reviewer'; const S = 'somi-security-reviewer'; const sec = { SOMI_CODE_LOOP_REVIEW: 'security' }; const pan = { SOMI_CODE_LOOP_REVIEW: 'panel' };
164
- check('the generalist is always required; security mode and a sizing record of security also need the security lens; a panel needs a second code-review lens', [lens({}, [S]), lens(sec, [R]), lens(sec, [R, S]), lens(pan, [R]), lens(pan, [R, 'somi-plan-reviewer']), lens(pan, [R, 'somi-architecture-reviewer']), lens({}, [R], (r) => r.put((s) => ({ ...s, review_min: 'security' }))), lens({}, [R, S], (r) => r.put((s) => ({ ...s, review_min: 'security' })))], [64, 64, 0, 64, 64, 0, 64, 0]);
165
- const p = repo(); runStep(p.ctx(), { step: 'open', slug: 'pl', loop: 'plan' }); runStep(p.ctx(), { step: 'after-code', slug: 'pl', loop: 'plan', agent: 'somi-planner' });
166
- const pr = (rev) => runStep(p.ctx(), { step: 'after-review', slug: 'pl', loop: 'plan', reviewers: rev, verdict: 'approve', blockers: 0, majors: 0, review: 'r1.md' }).exit;
167
- check('a plan loop needs its plan reviewer or the generalist', [pr(['somi-test-strategist']), pr(['somi-plan-reviewer'])], [64, 0]);
168
- const f = gated(); recordFindings({ root: f.root, slug: 'p1', review: 'r0.md', run: 'x', pass: 0, input: [F(1), F(2), F(3, 'Blocker')] }); resolveFinding({ root: f.root, slug: 'p1', id: 'F-1', status: 'accepted', by: 'person' });
169
- const x = review(f, { verdict: 'request-changes', majors: 1, findings: [F(4)], fixed: ['F-1', 'F-2', 'F-3', 'F-3'], review: 'r2.md' });
170
- const st = Object.fromEntries(f.ledger().findings.map((y) => [y.id, [y.status, y.resolved_by]]));
171
- check('fixed resolves the open findings it names, as id and severity in the answer and the diary; a repeated id counts once, and a status a person set is skipped and unchanged', [x.exit, x.resolved, x.skipped, st['F-1'], st['F-2'], st['F-3'], f.diary().includes('fixed: F-2 Major, F-3 Blocker')], [0, ['F-2 Major', 'F-3 Blocker'], ['F-1'], ['accepted', 'person'], ['fixed', 'r2.md'], ['fixed', 'r2.md'], true]);
172
- const b = gated(); review(b, { verdict: 'request-changes', majors: 1, findings: [F(1)] }); open(b); b.file('a.js', '1\n2\n'); after(b);
173
- const trick = { verdict: 'request-changes', majors: 1, findings: [F(1)], fixed: ['F-1'] }; const t = tree(b.root);
174
- check('reporting a finding and fixing it in the same call is refused 64 and writes nothing, so the third pass of one finding reaches exit 5', [review(b, trick).exit, tree(b.root), review(b, { ...trick, fixed: [] }).exit], [64, t, 5]);
175
- const one = gated(); review(one, { verdict: 'request-changes', majors: 2, findings: [F(1), F(1)] });
176
- check('two findings of one locus in one call leave one finding with one sighting', one.ledger().findings.map((y) => y.seen.length), [1]);
177
- const sg = gated(); recordFindings({ root: sg.root, slug: 'p1', review: 'r0.md', run: 'x', pass: 0, input: [F(8), F(9)] });
178
- const base = { reviewers: ['somi-reviewer', S], verdict: 'request-changes', majors: 2, findings: [F(1), F(2)], fixed: ['F-1', 'F-2'], review: 'r1.md' };
179
- review(sg, base); const flipped = { review: 'r1.md', findings: [{ title: F(2).title, file: 'f2.js', severity: 'Major', symbol: 's', confidence: 'High' }, { severity: 'Major', file: 'f1.js', symbol: 's', title: F(1).title, confidence: 'High' }], majors: 2, blockers: 0, verdict: 'request-changes', fixed: ['F-2', 'F-1'], reviewers: [S, 'somi-reviewer'] };
180
- const rp = runStep(sg.ctx(), { step: 'after-review', slug: 'p1', iteration: '1.1', ...flipped });
181
- check('a retry with its keys and lists in another order is the same call: replayed, not refused', [rp.replayed, rp.exit], [true, 0]);
182
- const v = gated(); const away = path.join(tmp, 'victim.txt'); mkdirSync(path.join(v.root, '.somi', 'reviews', 'p1'), { recursive: true }); writeFileSync(away, 'untouched'); symlinkSync(away, path.join(v.root, '.somi', 'reviews', 'p1', 'findings.json.tmp'));
183
- const w = review(v, { verdict: 'request-changes', majors: 1, findings: [F(1)] });
184
- check('a link planted at the ledger\'s old temp name is not followed: its target is untouched and the finding is recorded', [w.exit, readFileSync(away, 'utf8'), v.ledger().findings.length], [0, 'untouched', 1]);
185
- const nope = review(gated(), { fixed: ['F-9'] });
186
- check('a fixed id that is not in the ledger is refused 64 and says so', [nope.exit, nope.error?.includes('not in the findings ledger')], [64, true]);
187
- const rs = (by) => { const q = gated(); recordFindings({ root: q.root, slug: 'p1', review: 'r0.md', run: 'x', pass: 0, input: [F(1)] }); resolveFinding({ root: q.root, slug: 'p1', id: 'F-1', status: 'fixed', by }); return review(q, { verdict: 'request-changes', majors: 1, findings: [F(2)], fixed: ['F-1'] }); };
188
- check('a finding this same review already fixed (a retry after the write landed) is reported resolved; one fixed by another review is skipped', [rs('r1.md').resolved, rs('r0.md').skipped], [['F-1 Major'], ['F-1']]);
189
- const e = gated(); const next = (r, txt) => { r.file('a.js', txt); open(r); after(r); };
190
- review(e, { verdict: 'request-changes', majors: 1, findings: [F(1), F(2, 'Minor')] }); next(e, '1\n2\n');
191
- review(e, { review: 'r2.md', verdict: 'request-changes', majors: 1, findings: [F(3)], fixed: ['F-1'] }); next(e, '1\n2\n3\n4\n');
192
- const up = review(e, { review: 'r3.md', verdict: 'request-changes', blockers: 1, findings: [{ ...F(2), severity: 'Blocker' }], fixed: ['F-3'] });
193
- check('a Minor finding listed again as a Blocker is raised to Blocker, and the loop does not close as done', [up.next, e.ledger().findings.find((y) => y.id === 'F-2').severity], ['open', 'Blocker']);
194
- const sa = gated(); review(sa, { verdict: 'request-changes', blockers: 1, findings: [F(1, 'Blocker')] }); next(sa, '1\n2\n');
195
- const stale = review(sa, { review: 'r2.md' }); const kept = tree(sa.root);
196
- check('an approve while an earlier Blocker is open and neither listed nor fixed is refused 64 naming it, and writes nothing; with the id in fixed it closes', [stale.exit, stale.error?.includes('F-1 Blocker') && stale.error.includes('accepted/wontfix'), isDeepStrictEqual(tree(sa.root), kept), review(sa, { review: 'r2.md', fixed: ['F-1'] }).next], [64, true, true, 'close']);
197
- const d = repo(); mkdirSync(path.join(d.root, '.somi', 'reviews', 'p1'), { recursive: true }); const made = path.join(tmp, 'made.json'); symlinkSync(made, path.join(d.root, '.somi', 'reviews', 'p1', 'findings.json'));
198
- check('the ledger is not seeded through a dangling link: the call fails and nothing is created at the link target', [dies(() => recordFindings({ root: d.root, slug: 'p1', review: 'r', run: 'x', pass: 1, input: [F(1)] })) !== 'no throw', existsSync(made)], [true, false]);
199
- const cf = gated(); writeFileSync(path.join(cf.root, '.somi', 'config.json'), '{ not json'); const cs = readFileSync(cf.sf, 'utf8'); const cx = review(cf);
200
- check('a dispatch the resolver refuses (a malformed config) is refused with its code and leaves the loop state byte-identical', [cx.exit, readFileSync(cf.sf, 'utf8') === cs], [67, true]);
201
- const sv = gated(); recordFindings({ root: sv.root, slug: 'p1', review: 'r0.md', run: sv.state().started, pass: 0, input: [F(1, 'high')] });
202
- const lst = review(sv, { verdict: 'request-changes', findings: [F(2, 'Minor')] }); sv.file('a.js', '1\n2\n'); open(sv); after(sv);
203
- const blocked = review(sv, { review: 'r2.md' }); const fixedU = review(sv, { review: 'r2.md', fixed: ['F-1'] });
204
- check('a finding with a severity outside the four names (as the CLI stores it) is listed in open_findings, blocks an approve, and fixing it leaves a readable state where the next open works', [lst.next, lst.open_findings, blocked.exit, blocked.error?.includes('F-1 Unrated'), fixedU.resolved, open(sv).exit], ['open', ['F-1: finding 1 here'], 64, true, ['F-1 Unrated'], 0]);
205
- const nb = repo(); recordFindings({ root: nb.root, slug: 'p1', review: 'r0.md', run: 'x', pass: 0, input: [F(1, 'blocker'), F(2, 'weird')] });
206
- check('the ledger writer stores blocker as Blocker and any other severity as given', nb.ledger().findings.map((y) => y.severity), ['Blocker', 'weird']);
207
- const rn = gated(); recordFindings({ root: rn.root, slug: 'p1', review: 'r0.md', run: 'another-loop', pass: 0, input: [F(1)] });
208
- const rq = gated(); recordFindings({ root: rq.root, slug: 'p1', review: 'r0.md', run: 'another-loop', pass: 0, input: [F(1)] });
209
- check('an open Major sighted only in another loop run blocks neither an approve nor the end of a request-changes pass with nothing of its own at the floor (a Major from this run does: the test above)', [review(rn).next, review(rq, { verdict: 'request-changes' }).next], ['close', 'close']);
210
- const up2 = repo(); const rec = (sev) => recordFindings({ root: up2.root, slug: 'p1', review: 'r0.md', run: 'x', pass: 1, input: [F(1, sev)] }); rec('Minor'); rec('Blocker'); rec('Nit');
211
- check('somi-findings record raises a known open finding to a stronger severity, notes it on the sighting, and never lowers it', [up2.ledger().findings[0].severity, up2.ledger().findings[0].seen.map((q) => q.severity)], ['Blocker', [undefined, 'Blocker', undefined]]);
212
- const pc = gated(); const before = pc.state().history.length;
213
- check('record-pass refuses a verdict with a control character or counts that are not numbers (64), and records nothing', [recordPass(pc.ctx(), { ...prim, verdict: 'a\nb' }).code, recordPass(pc.ctx(), { ...prim, verdict: 'approve', blockers: 'x' }).code, pc.state().history.length], [64, 64, before]);
214
- const l = repo(); open(l, { max_passes: 1 }); l.file('a.js', '1\n2\n'); after(l); const last = review(l, { verdict: 'request-changes', majors: 1, findings: [F(1)] }); const stop = open(l);
215
- check('request-changes on the last pass says open, and that open is the max-passes stop (exit 2, close)', [last.next, stop.exit, stop.stop_reason, stop.next], ['open', 2, 'max-passes-exceeded', 'close']);
216
- const c = gated(); recordPass(c.ctx(), { ...prim, verdict: 'approve' });
217
- check('a pass the CLI already recorded is refused with a message that says so', review(c).error?.includes('outside the step tool'), true);
218
- }
219
- console.log('== close: the loop ends, the row moves once, the answer carries what the flow reports ==');
220
- {
221
- const approved = (env, args) => { const r = repo(); open(r, args, env); r.file('a.js', '1\n2\n3\n'); after(r); review(r); return r; };
222
- const r = repo(); open(r, { max_passes: 2 });
223
- const inProgress = /\| 1\.1 \| one \| in-progress \|/.test(progress(r)); r.file('a.js', '1\n2\n3\n'); after(r); review(r);
224
- const x = close(r);
225
- check('open marks a not-started row in-progress (one recorded sub-step); close with done ends the loop and answers with the verdict, the diff, the caps and the pointer to the reviews', [inProgress, x.ok, x.exit, x.status, x.next, x.stop_reason, x.pass, x.verdict, x.diff, x.caps.max_passes, x.reviews, r.state().status, r.state().finished], [true, true, 0, 'done', 'summarise', null, 1, 'approve', { lines: 2, weighted: 2, out_of_scope: [] }, 2, '.somi/reviews/p1/', 'done', NOW]);
226
- check('close with done marks the row once (Status, Reviewed, Last activity), sets the Last activity line and writes a note-category diary entry that folds in the cap overrides', [/\| done +\| approve \| 2026-10-29 — code-loop done at pass 1; verdict approve \|/.test(progress(r)), progress(r).includes('**Last activity**: 2026-10-29 — code-loop done at pass 1; verdict approve for iteration 1.1\n'), /code-loop done at pass 1; verdict approve\n\n\*\*Category\*\*: `note`/.test(r.diary()), r.diary().includes('cap overrides: max_passes 3 -> 2 (tool, after pass 0)'), x.cap_overrides, x.wrote],
227
- [true, true, true, true, ['max_passes 3 -> 2 (tool, after pass 0)'], ['.somi/plans/p1/diary.md', '.somi/plans/p1/progress.md']]);
228
- check('close lists every dispatch as agent, tier and model, naming each start the host chose', [x.dispatches.length, x.dispatches.map((d) => d.split(' ')[0])], [2, ['somi-coder', 'somi-reviewer']]);
229
- const again = close(r); const t = tree(r.root);
230
- check('a repeat of a finished close is replayed with the same answer and writes nothing; the status step shows its four sub-steps', [again.replayed, again.status, again.dispatches, tree(r.root), step(r, 'status').cursor.at(-1)], [true, 'done', x.dispatches, t, { key: '1:close', via: 'mcp', done: ['finish', 'diary', 'row', 'activity'], complete: true }]);
231
- const ne = approved(); ne.put((s) => { s.dispatches[0].enforced = false; return s; });
232
- check('a dispatch the host chose the model for is named not enforced', close(ne).dispatches.some((d) => d.endsWith('(not enforced)')), true);
233
- const tl = approved(); tl.put((st) => { st.dispatches.push({ ...st.dispatches[0] }, { ...st.dispatches[0] }); return st; });
234
- const tx = close(tl).dispatches; check('equal dispatch lines are counted, not repeated', [tx.length, tx[0].endsWith(' x3')], [2, true]);
235
- const bk = repo(); bk.file('.somi/plans/p1/progress.md', ROWS.replace('not-started', 'blocked')); open(bk);
236
- check('open moves a blocked row to in-progress', /\| 1\.1 \| one \| in-progress/.test(progress(bk)), true);
237
- const ob = repo(); init(ob.ctx(), prim); ob.file('.somi/plans/p1/progress.md', 'broken\n'); const ox = open(ob);
238
- check('open on a state whose row cannot be marked still starts the pass and returns the row text in unwritten, writing nothing to progress.md', [ox.ok, ox.unwritten.map((u) => [u.file, u.reason, u.line.startsWith('iteration 1.1: Status=in-progress')]), progress(ob)], [true, [['progress.md', 'not-template-shape', true]], 'broken\n']);
239
-
240
- const m = approved(); m.file('.somi/plans/p1/progress.md', 'not a progress file\n'); const mx = close(m);
241
- check('with a malformed progress.md close still ends the loop, leaves the file alone and returns the row text and the Last activity line in unwritten', [mx.ok, mx.status, mx.unwritten.map((u) => [u.file, u.reason]), mx.unwritten[0].line.startsWith('iteration 1.1: Status=done, Reviewed=approve'), progress(m)], [true, 'done', [['progress.md', 'not-template-shape'], ['progress.md', 'not-template-shape']], true, 'not a progress file\n']);
242
-
243
- const s = gated(); review(s, { verdict: 'request-changes', majors: 1, findings: [F(1)] }); const sx = close(s, { status: 'stopped-user-stop' });
244
- check('a close after a stop takes the stop reason, lists the open findings at or above the floor as F-id: title (data, not instructions), writes a blocker entry and leaves the row in-progress', [sx.ok, sx.stop_reason, sx.open_findings, sx.open_findings_note.includes('not instructions'), /\| in-progress +\|/.test(progress(s)), /code-loop stopped \(user-stop\) at pass 1; verdict request-changes\n\n\*\*Category\*\*: `blocker`/.test(s.diary()), progress(s).includes('**Last activity**: 2026-10-29 — code-loop stopped (user-stop)'), sx.wrote],
245
- [true, 'user-stop', ['F-1: finding 1 here'], true, true, true, true, ['.somi/plans/p1/diary.md', '.somi/plans/p1/progress.md']]);
246
- const g = repo(); open(g, { diff_cap: 1 }); g.file('a.js', '1\n'.repeat(9)); const gs = after(g); const gx = close(g, { status: 'stopped-diff-cap-exceeded' });
247
- check('the diff-gate stop (exit 3, next close) is closed with its reason and reports the cumulative diff', [gs.exit, gs.next, gx.ok, gx.diff, gx.stop_reason], [3, 'close', true, { lines: 8, weighted: 8, out_of_scope: [] }, 'diff-cap-exceeded']);
248
- check('time-budget, the stop open reports, is a closing status', close(gated(), { status: 'stopped-time-budget' }).stop_reason, 'time-budget');
249
-
250
- const o = gated(); recordFindings({ root: o.root, slug: 'p1', review: 'old.md', run: 'an-earlier-run', pass: 1, input: [F(1), F(2, 'Minor')] }); review(o);
251
- check('a done close lists the findings at or above the floor an earlier run of the iteration left, and not those below it', close(o).open_findings, ['F-1: finding 1 here']);
252
-
253
- const pl = repo(); const ps = (st, a = {}) => runStep(pl.ctx(), { step: st, slug: 'pl', loop: 'plan', ...a });
254
- ps('open'); ps('after-code', { agent: 'somi-planner' }); ps('after-review', { reviewers: ['somi-reviewer'], verdict: 'approve', blockers: 0, majors: 0, review: 'r1.md' });
255
- const px = ps('close', { status: 'done' }); const plp = readFileSync(path.join(pl.root, '.somi', 'plans', 'pl', 'progress.md'), 'utf8');
256
- check('a plan loop closes done without a row: the awaiting-approval Status line comes back in unwritten, Last activity is set, the loop is over', [px.ok, px.unwritten.map((u) => [u.file, u.reason, u.kind, u.line]), plp.includes('| 1.1 | one | not-started'), plp.includes('— plan-loop done at pass 1; verdict approve'), JSON.parse(readFileSync(stateFile(pl.ctx().stateDir, 'pl', ''), 'utf8')).status], [true, [['progress.md', 'status-not-set-by-tool', 'status-line', 'set the Status line to awaiting-approval']], true, true, 'done']);
257
-
258
- const big = approved(); big.put((st) => ({ ...st, dispatches: Array.from({ length: 40 }, (_, i) => ({ pass: 1, agent: `agent-${i}`, tier: 'medium', model: 'model-x', enforced: i % 2 === 0 })), cap_overrides: Array.from({ length: 30 }, (_, i) => ({ field: 'max_passes', from: 30 - i, to: 29 - i, source: 'tool', after_pass: 1, at: NOW })) }));
259
- recordFindings({ root: big.root, slug: 'p1', review: 'old.md', run: 'an-earlier-run', pass: 1, input: Array.from({ length: 300 }, (_, i) => F(i + 1)) }); const bx = close(big);
260
- check('40 dispatches, 30 cap overrides and 300 open findings: the answer fits the budget, every list counts what it cuts', [bx.ok, bytes(bx) <= BUDGET, bx.truncated, [bx.dispatches, bx.cap_overrides, bx.open_findings].map((l) => l.at(-1).startsWith('(+'))], [true, true, undefined, [true, true, true]]);
261
- check('the fold of dispatches and cap overrides does not point at the loop state, which is not kept in the repository', [bx.dispatches, bx.cap_overrides].map((l) => l.at(-1).includes('loop state')), [false, false]);
262
- }
263
- console.log('== close: what it refuses, and what a kill or a failed measurement leaves ==');
264
- {
265
- const reviewed = (args) => { const r = gated(); if (args) review(r, args); else review(r); return r; };
266
- const two = reviewed({ verdict: 'request-changes', majors: 1, findings: [F(1)] }); open(two); two.file('a.js', '1\n2\n'); after(two); review(two, { verdict: 'request-changes', majors: 1, findings: [F(1)] });
267
- const refused = [['no after-review yet', gated(), {}], ['request-changes with a Major open', reviewed({ verdict: 'request-changes', majors: 1, findings: [F(1)] }), {}], ['the circuit breaker', two, {}], ['status finished', reviewed(), { status: 'finished' }], ['an undocumented reason', reviewed(), { status: 'stopped-whatever' }], ['an empty reason', reviewed(), { status: 'stopped-' }],
268
- ['no status', reviewed(), { status: undefined }], ['status as a list', reviewed(), { status: ['done'] }], ['a plan loop asked to close a code loop\'s slug', reviewed(), { loop: 'plan', iteration: undefined }]];
269
- const got = refused.map(([, r, a]) => { const t = tree(r.root); const x = close(r, a); return [x.exit, x.error?.startsWith(a.loop ? 'no running loop' : 'status:'), isDeepStrictEqual(tree(r.root), t), r.state().status, '1:close' in r.state().steps]; });
270
- check('a done close without an ending after-review, an undocumented or missing status and a wrong loop are each refused 64 naming the field or the missing state, with the loop still running and nothing written', got, refused.map(() => [64, true, true, 'running', false]));
271
- check('the breaker pass is closed with its own reason', close(two, { status: 'stopped-circuit-breaker' }).stop_reason, 'circuit-breaker');
272
- const fin = reviewed(); finish(fin.ctx(), { ...prim, status: 'done' }); const ft = tree(fin.root); const fx = close(fin);
273
- check('a loop that was finished outside the step is refused 64 as already finished, and nothing is written', [fx.exit, fx.error?.includes('already finished'), tree(fin.root)], [64, true, ft]);
274
- const dn = reviewed(); close(dn); const dt = tree(dn.root); const other = close(dn, { status: 'stopped-user-stop' });
275
- check('a finished close repeated with another status is refused 64, not answered with the stored one', [other.exit, other.error?.startsWith('status:'), tree(dn.root)], [64, true, dt]);
276
-
277
- const whole = reviewed(); const wx = close(whole);
278
- const shape = (r) => [r.state().status, r.state().finished, entries(r), (progress(r).match(/\| done /g) ?? []).length, progress(r).match(/\*\*Last activity\*\*.*/)[0]];
279
- const kills = ['finish', 'diary', 'row', 'activity'].map((sub) => { const r = reviewed(); const k = dies(() => close(r, {}, {}, { failAfter: sub })); const x = close(r); return [k, x.ok, x.replayed, x.wrote, x.status, shape(r)]; });
280
- check('close killed after each of its four sub-steps and retried ends the loop once: one diary entry, one done row, one Last activity line, the same answer as an uninterrupted call', kills, ['finish', 'diary', 'row', 'activity'].map((s) => [`failAfter ${s}`, true, false, wx.wrote, 'done', shape(whole)]));
281
-
282
- const gf = reviewed(); const sha = gf.state().baseline_sha; gf.put((s) => ({ ...s, baseline_sha: 'f'.repeat(40) })); const before = readFileSync(gf.sf, 'utf8'); const gx = close(gf);
283
- check('when the cumulative diff cannot be measured the loop is left running and untouched (no closing entry), and the same close succeeds once it can', [gx.ok, readFileSync(gf.sf, 'utf8') === before, entries(gf), (gf.put((s) => ({ ...s, baseline_sha: sha })), close(gf).ok), gf.state().status], [false, true, 3, true, 'done']);
284
-
285
- const tamper = (fn) => { const r = reviewed(); r.put((s) => { fn(s.steps['1:open']); return s; }); return step(r, 'status').exit; };
286
- check('a stored cursor with a diff or a status of the wrong shape makes the state unreadable', [tamper((e) => { e.diff = { lines: 'x', weighted: 1, out_of_scope: [] }; }), tamper((e) => { e.status = 'stopped-x'; }), tamper((e) => { e.diff = { lines: 1, weighted: 1, out_of_scope: [] }; e.status = 'done'; })], [64, 64, 0]);
287
- }
288
- console.log('== close: stopped loops, plan loops, gate stops, and the resume path of open ==');
289
- {
290
- const rc = { verdict: 'request-changes', majors: 1, findings: [F(1)] };
291
- const lp = gated(); review(lp, rc); open(lp); const lx = close(lp, { status: 'stopped-user-stop' });
292
- check('a loop stopped in a pass that has no review yet names the last recorded verdict as that pass\'s: in the diary, the Last activity line and the answer', [lx.verdict, lx.verdict_pass, lx.pass, lp.diary().includes('code-loop stopped (user-stop) at pass 2; last verdict request-changes (pass 1)\n'), progress(lp).includes('— code-loop stopped (user-stop) at pass 2; last verdict request-changes (pass 1) for iteration 1.1')], ['request-changes', 1, 2, true, true]);
293
-
294
- const st = gated(); review(st, rc); const stx = close(st, { status: 'stopped-user-stop' });
295
- const dn = gated(); recordFindings({ root: dn.root, slug: 'p1', review: 'old.md', run: 'an-earlier-run', pass: 1, input: [F(1)] }); review(dn); const dnx = close(dn);
296
- check('the closing diary entry lists the open findings at or above the floor by id', [st.diary().includes('open at or above Major: F-1'), dn.diary().includes('open at or above Major: F-1')], [true, true]);
297
- check('the note on the open findings is specific to the close: a stop says to record each as a follow-up by id, a done close only says they are still open at close and asks for nothing', [stx.open_findings_note.includes('record each in progress.md as a follow-up, by its id'), dnx.open_findings_note.includes('still open at close'), dnx.open_findings_note.includes('follow-up') || dnx.open_findings_note.includes('earlier runs')], [true, true, false]);
298
- const ks = gated(); review(ks, rc); const kerr = dies(() => close(ks, { status: 'stopped-user-stop' }, {}, { failAfter: 'finish' }));
299
- recordFindings({ root: ks.root, slug: 'p1', review: 'r9.md', run: ks.state().started, pass: 1, input: [F(2)] }); close(ks, { status: 'stopped-user-stop' });
300
- check('a closing diary entry written on a retry lists the findings read when the loop was ended, not those recorded since', [kerr, /open at or above Major: F-1(?!,)/.test(ks.diary()), entries(ks)], ['failAfter finish', true, 4]);
301
-
302
- const sa = gated(); review(sa, rc); const sax = close(sa, { status: 'stopped-user-stop' });
303
- const sb = gated(); review(sb, rc); finish(sb.ctx(), { ...prim, status: 'stopped-user-stop' });
304
- check('a stopped close leaves the state that finish --status stopped-user-stop leaves', [sax.ok, norm(sa), sa.state().finished], [true, norm(sb), sb.state().finished]);
305
-
306
- const rs = repo(); init(rs.ctx(), prim); passPrim(rs.ctx(), prim); recordPass(rs.ctx(), { ...prim, verdict: 'request-changes', majors: '1' }); const rx = open(rs);
307
- check('open on a pass the primitives recorded is a resume: the row moves to in-progress and the diary entry says resumed', [rx.ok, /\| 1\.1 \| one \| in-progress/.test(progress(rs)), rs.diary().includes('resumed from pass 1')], [true, true, true]);
308
- const rk = repo(); init(rk.ctx(), prim); passPrim(rk.ctx(), prim); recordPass(rk.ctx(), { ...prim, verdict: 'request-changes', majors: '1' }); const rkerr = dies(() => open(rk, {}, {}, { failAfter: 'diary' })); const rkx = open(rk);
309
- check('a resume killed after its diary entry moves the row on the retry and writes the entry once', [rkerr, rkx.ok, /\| 1\.1 \| one \| in-progress/.test(progress(rk)), entries(rk)], ['failAfter diary', true, true, 2]);
310
- const rb = repo(); rb.file('.somi/plans/p1/progress.md', ROWS.replace('not-started', 'blocked')); init(rb.ctx(), prim); passPrim(rb.ctx(), prim); recordPass(rb.ctx(), { ...prim, verdict: 'request-changes', majors: '1' }); const rbx = open(rb);
311
- check('a resumed open leaves a row a person marked blocked as it is, says so in unwritten, and still starts the pass and writes the entry', [rbx.ok, rbx.pass, /\| 1\.1 \| one \| blocked/.test(progress(rb)), rb.diary().includes('resumed from pass 1'), rbx.unwritten.map((u) => [u.file, u.reason, u.kind])], [true, 2, true, true, [['progress.md', 'row-left-blocked', 'notice']]]);
312
-
313
- const pg = repo(); const pp = (name, a = {}) => runStep(pg.ctx(), { step: name, slug: 'pl', loop: 'plan', ...a });
314
- pp('open'); pp('after-code', { agent: 'somi-planner' }); const t0 = tree(pg.root); const early = pp('close', { status: 'done' });
315
- pp('after-review', { reviewers: ['somi-reviewer'], verdict: 'request-changes', blockers: 0, majors: 1, review: 'r1.md', findings: [F(1)] }); const t1 = tree(pg.root); const mid = pp('close', { status: 'done' });
316
- check('a plan loop is gated like a code loop: done is refused 64 before any after-review and after one that did not end the loop, the loop stays running and nothing is written', [early.exit, mid.exit, early.error?.startsWith('status:'), isDeepStrictEqual(tree(pg.root), t1), t0 === t1, JSON.parse(readFileSync(stateFile(pg.ctx().stateDir, 'pl', ''), 'utf8')).status], [64, 64, true, true, false, 'running']);
317
-
318
- const g1 = repo(); open(g1, { max_passes: 1 }); g1.file('a.js', '1\n2\n'); after(g1); review(g1, rc); const e2 = open(g1);
319
- const g3 = repo(); open(g3, { diff_cap: 1 }); g3.file('a.js', '1\n'.repeat(9)); const e3 = after(g3);
320
- const g4 = repo(); mkdirSync(path.join(g4.root, '.somi', 'somi-state', 'run'), { recursive: true }); writeFileSync(path.join(g4.root, '.somi', 'somi-state', 'run', 'p1.json'), JSON.stringify({ started: '2020-01-01T00:00:00.000Z', max_minutes: 1 })); const e4 = open(g4);
321
- check('a gate stop (max passes, diff cap, time budget) carries the status to close with, and close accepts it', [e2, e3, e4].map((x) => [x.exit, x.close_args?.status === `stopped-${x.stop_reason}`, documentedStatus(x.close_args?.status)]), [[2, true, true], [3, true, true], [4, true, true]]);
322
- check('the exported step tables and the stop reasons cannot be changed by a caller', [STOP_REASONS, FIELDS, ...Object.values(FIELDS)].every(Object.isFrozen), true);
323
- }
324
- console.log('== close and the step tool: cursors from an earlier build, labels, finding keys ==');
325
- {
326
- const ok = gated(); review(ok, { verdict: 'request-changes', majors: 1, findings: [F(1)] }); dies(() => close(ok, { status: 'stopped-user-stop' }, {}, { failAfter: 'finish' }));
327
- ok.put((s) => { delete s.steps['1:close'].open; return s; }); const okx = close(ok, { status: 'stopped-user-stop' });
328
- check('a close resumed from a cursor that was finished without its open-findings record reads the ledger now instead of failing', [okx.ok, okx.exit, okx.open_findings, ok.diary().includes('open at or above Major: F-1')], [true, 0, ['F-1: finding 1 here'], true]);
329
-
330
- const wa = gated(); const wb = review(wa, { findings: [{ ...F(1, 'Minor'), extra: { a: { b: 1 } } }], verdict: 'approve' });
331
- check('a finding with a key outside file, symbol, title, severity and confidence is recorded with the key dropped', [wb.exit, readFileSync(path.join(wa.root, '.somi', 'reviews', 'p1', 'findings.json'), 'utf8').includes('extra')], [0, false]);
332
-
333
- const np = gated(); review(np, { verdict: 'request-changes', majors: 1, findings: [F(1)] }); open(np); np.put((s) => { delete s.history[0].pass; return s; }); const npx = close(np, { status: 'stopped-user-stop' });
334
- check('a history entry without a pass number is named by its verdict alone, never "(pass null)"', [npx.ok, np.diary().includes('null'), np.diary().includes('last verdict request-changes\n'), npx.verdict_pass], [true, false, true, null]);
335
- }
336
- console.log('== endLoop, the statuses close accepts, the shared constants, the ledger temp sweep ==');
337
- {
338
- const e = repo(); init(e.ctx(), prim); finish(e.ctx(), { ...prim, status: 'approved' }); const once = readFileSync(e.sf, 'utf8'); const twice = finish(e.ctx(), { ...prim, status: 'stopped-user-stop' });
339
- check('finish keeps accepting the statuses the CLI always took, and a loop that is over cannot be finished again: 64, and the state is unchanged', [twice.code, twice.message.includes('cannot be finished again'), readFileSync(e.sf, 'utf8') === once], [64, true, true]);
340
- check('the documented closing statuses are done and stopped- with a reason the code loop documents, time-budget included, and cover every cap-breach status the eval reads', [['done', 'stopped-user-stop', 'stopped-time-budget', 'stopped-circuit-breaker'].map(documentedStatus), ['approved', 'stopped-done', 'stopped-', 'stopped-x', 'stopped-__proto__', '', null, ['done']].map(documentedStatus), [...CAP_BREACH_STATUSES].every((r) => STOP_REASONS.includes(r))], [Array(4).fill(true), Array(8).fill(false), true]);
341
- check('the exported sub-step, mode and argument tables cannot be changed by a caller', [MODES, ARG, SUB_STEPS].map(Object.isFrozen), [true, true, true]);
342
-
343
- const r = repo(); const dir = path.join(r.root, '.somi', 'reviews', 'p1'); mkdirSync(dir, { recursive: true });
344
- const old = new Date(Date.now() - 2 * 3600 * 1000); const plant = (name, text = 'x') => { writeFileSync(path.join(dir, name), text); utimesSync(path.join(dir, name), old, old); };
345
- plant('findings.json.0123456789ab.tmp'); plant('findings.json.0123456789ac.tmp'); plant('findings.json.short.tmp'); plant('notes.txt'); writeFileSync(path.join(dir, 'findings.json.0123456789ad.tmp'), 'fresh');
346
- const away = path.join(tmp, 'sweep-target.txt'); writeFileSync(away, 'untouched'); symlinkSync(away, path.join(dir, 'findings.json.0123456789ae.tmp')); lutimesSync(path.join(dir, 'findings.json.0123456789ae.tmp'), old, old);
347
- recordFindings({ root: r.root, slug: 'p1', review: 'r', run: 'x', pass: 1, input: [F(1)] });
348
- check('a save sweeps the temp files of killed writes that are old regular files, and leaves a young one, a link, other names and the link target alone', [readdirSync(dir).sort(), readFileSync(away, 'utf8')], [['findings.json', 'findings.json.0123456789ad.tmp', 'findings.json.0123456789ae.tmp', 'findings.json.short.tmp', 'notes.txt'], 'untouched']);
349
- }
350
- console.log(`loop step review and close tests: ${pass} ok, ${fail} failed`);
351
- process.exit(fail === 0 ? 0 : 1);
@@ -1,114 +0,0 @@
1
- #!/usr/bin/env node
2
- // The step tool's leniency: the calls a model makes by habit (no files, host and project_dir on every call, no review file, an
3
- // extra key on a finding, a progress table of its own columns, a diary with only its heading) go through, each where it loses no
4
- // gate. First one scripted pass through the real server on a copy of the task02 eval fixture, counting refused calls; then the
5
- // edges in-process: what stays refused. Run by tests/scripts/loop-engine.sh.
6
-
7
- import { execFileSync } from 'node:child_process';
8
- import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
9
- import { tmpdir } from 'node:os';
10
- import path from 'node:path';
11
- import { fileURLToPath } from 'node:url';
12
- import { isDeepStrictEqual } from 'node:util';
13
- import { McpClient } from './somi-mcp-client.mjs';
14
- import { runStep } from '../../../scripts/lib/loop-step.mjs';
15
-
16
- const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
17
- const FIXTURE = path.join(ROOT, 'tests', 'evals', 'fixtures', 'task02-code');
18
- let pass = 0; let fail = 0;
19
- const check = (name, got, want) => {
20
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
21
- };
22
- const tmp = mkdtempSync(path.join(tmpdir(), 'loop-lenient-'));
23
- process.on('exit', () => rmSync(tmp, { recursive: true, force: true }));
24
- let n = 0;
25
- // A git repo holding a copy of the fixture, its _somi directory as .somi.
26
- function fixture() {
27
- const root = path.join(tmp, `r${n++}`);
28
- cpSync(FIXTURE, root, { recursive: true });
29
- cpSync(path.join(FIXTURE, '_somi'), path.join(root, '.somi'), { recursive: true }); rmSync(path.join(root, '_somi'), { recursive: true });
30
- const git = (...a) => execFileSync('git', ['-C', root, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a]);
31
- git('init', '-q'); git('add', '.'); git('commit', '-q', '-m', 'base');
32
- return root;
33
- }
34
- const plan = (root, ...p) => path.join(root, '.somi', 'plans', 'expired-token', ...p);
35
- const text = (f) => { try { return readFileSync(f, 'utf8'); } catch { return '{}'; } }; // a file the code under test did not write reads as empty, so the check fails instead of the run
36
- const CAPS_OFF = { SOMI_CODE_LOOP_MAX_PASSES: '', SOMI_CODE_LOOP_DIFF_CAP: '', SOMI_CODE_LOOP_REVIEW: '', SOMI_CODE_LOOP_REVIEW_SCOPE: '', SOMI_CODE_LOOP_SEVERITY_FLOOR: '', SOMI_GLOBAL_CONFIG: '' };
37
-
38
- console.log('== one pass through the server on the task02 fixture, with every habit of the model ==');
39
- {
40
- const root = fixture(); const calls = [];
41
- const client = new McpClient(path.join(ROOT, 'scripts', 'somi-mcp.mjs'), { env: { ...CAPS_OFF, CLAUDE_PROJECT_DIR: root } });
42
- try {
43
- await client.initialize({});
44
- const call = async (step, args) => { // host and project_dir ride on every call, as a model sends them
45
- const r = await client.request('tools/call', { name: 'somi_loop', arguments: { step, slug: 'expired-token', iteration: '1.1', host: 'claude-code', project_dir: root, ...args } });
46
- const body = JSON.parse(r.content[0].text); calls.push({ step, refused: r.isError === true, exit: body.exit, error: body.error }); return body;
47
- };
48
- const o = await call('open');
49
- writeFileSync(path.join(root, 'src', 'auth', 'token.mjs'), `${text(path.join(root, 'src', 'auth', 'token.mjs'))}// expiry checked\n`);
50
- await call('after-code', { agent: 'somi-coder' });
51
- const finding = { file: 'src/auth/token.mjs', title: 'no test for the boundary second', severity: 'Minor', confidence: 'High', rationale: 'a key the ledger has no use for', line: 12 };
52
- const ar = await call('after-review', { reviewers: ['somi-reviewer'], verdict: 'approve-with-comments', blockers: 0, majors: 0, findings: [finding], fixed: [] });
53
- const cl = await call('close', { status: ar.close_args?.status });
54
- const state = JSON.parse(text(path.join(root, '.somi', 'somi-state', 'loop', 'expired-token.1.1.json')));
55
- const row = text(plan(root, 'progress.md')).split('\n').find((l) => l.startsWith('| 1.1 |'));
56
- const titles = text(plan(root, 'diary.md')).split('\n').filter((l) => l.startsWith('## ')).map((l) => l.split(' — ')[1]);
57
- check('no call of the pass is refused', calls.filter((c) => c.refused), []);
58
- check('open took the scope from the "Files (approx)" line of the phase file', state.iteration_files, ['src/auth/token.mjs', 'tests/auth/token.test.mjs', '.somi/plans/expired-token/progress.md', '.somi/plans/expired-token/diary.md']);
59
- check('the pass ended done, and the card the coder is briefed with lists those files', [state.status, cl.status, o.brief?.includes('src/auth/token.mjs')], ['done', 'done', true]);
60
- check('the tool wrote the three diary entries into the header-only diary', titles, ['code-loop done at pass 1; verdict approve-with-comments', 'code-loop pass 1 reviewed: approve-with-comments', 'code-loop started for iteration 1.1']);
61
- check('the four-column row was updated in place (Status done, Reviewed the verdict) and the file keeps its other sections', [/\| 1\.1 \| Reject an expired token \| done +\| approve-with-comments +\|$/.test(row), text(plan(root, 'progress.md')).includes('## Currently in flight')], [true, true]);
62
- check('the finding with an extra key is in the ledger without it', [(JSON.parse(text(path.join(root, '.somi', 'reviews', 'expired-token', 'findings.json'))).findings ?? []).map((f) => [f.title, 'rationale' in f, 'line' in f])], [[['no test for the boundary second', false, false]]]);
63
- } finally { client.close(); }
64
- }
65
-
66
- console.log('== what stays refused ==');
67
- {
68
- const root = fixture();
69
- const ctx = { root, env: { SOMI_GLOBAL_CONFIG: '' }, stateDir: path.join(root, '.somi', 'somi-state', 'loop'), installRoot: ROOT, via: 'mcp' };
70
- const step = (args) => runStep(ctx, { slug: 'expired-token', iteration: '1.1', ...args });
71
- const phase = plan(root, 'phases', '01-reject-expired.md'); const phaseText = text(phase); const progress = plan(root, 'progress.md'); const progressText = text(progress);
72
- const refusal = (r) => [r.exit, r.error?.split(':')[0]];
73
- writeFileSync(phase, phaseText.replace('src/auth/token.mjs`, `tests', '../evil`, `tests'));
74
- check('a derived path is checked as a given one: a .. segment is refused naming files', refusal(step({ step: 'open' })), [64, 'files']);
75
- writeFileSync(phase, phaseText.replace('- **Files (approx)**', '- **Files**'));
76
- check('a phase file without the Files (approx) line still refuses a missing files argument', [step({ step: 'open' }).error], ['files: required to start a code loop']);
77
- writeFileSync(phase, phaseText.replace('### Iteration 1.1', '### Iteration 1.2'));
78
- check('the line of another iteration is not taken for this one', [step({ step: 'open' }).error], ['files: required to start a code loop']);
79
- rmSync(phase);
80
- check('no phase file: the same refusal', [step({ step: 'open' }).error], ['files: required to start a code loop']);
81
- writeFileSync(phase, phaseText);
82
- const own = step({ step: 'open', files: ['src/auth/session.mjs'] });
83
- check('an explicit files argument wins over the phase file', [own.ok, JSON.parse(text(path.join(root, '.somi', 'somi-state', 'loop', 'expired-token.1.1.json'))).iteration_files], [true, ['src/auth/session.mjs']]);
84
-
85
- const other = fixture(); const oc = { ...ctx, root: other, stateDir: path.join(other, '.somi', 'somi-state', 'loop') };
86
- const attempt = (progressBody) => { writeFileSync(plan(other, 'progress.md'), progressBody); rmSync(oc.stateDir, { recursive: true, force: true }); const r = runStep(oc, { step: 'open', slug: 'expired-token', iteration: '1.1' }); return [r.exit, r.stop_reason]; };
87
- check('a table with the row missing is not-declared; so are one marked done, one with another row width and one with no heading', [attempt(progressText.replace('| 1.1 | Reject an expired token | not-started | — |', '| 1.2 | x | not-started | — |')), attempt(progressText.replace('not-started', 'done')), attempt(progressText.replace('not-started | — |', 'not-started |')), attempt(progressText.replace('## Iteration progress', '## Iterations'))], Array(4).fill([64, 'not-declared']));
88
- check('a row a person marked blocked still starts, as before', attempt(progressText.replace('not-started', 'blocked')), [0, null]);
89
-
90
- const lone = fixture(); const lc = { ...ctx, root: lone, stateDir: path.join(lone, '.somi', 'somi-state', 'loop') };
91
- const go = (args) => runStep(lc, { slug: 'expired-token', iteration: '1.1', ...args });
92
- go({ step: 'open' });
93
- check('host and project_dir are ignored on every step, even with a value the step would refuse; any other foreign key is still refused', [go({ step: 'status', host: 'vim', project_dir: '/x' }).ok, go({ step: 'status', bogus: 1 }).error, go({ step: 'close', host: 'claude-code', status: 'stopped-user-stop' }).ok], [true, 'bogus: is not an argument of step status', true]);
94
- const bad = fixture(); const bc = { ...ctx, root: bad, stateDir: path.join(bad, '.somi', 'somi-state', 'loop') };
95
- runStep(bc, { step: 'open', slug: 'expired-token', iteration: '1.1' }); writeFileSync(path.join(bad, 'src', 'auth', 'token.mjs'), 'x\n');
96
- runStep(bc, { step: 'after-code', slug: 'expired-token', iteration: '1.1', agent: 'somi-coder' });
97
- const rv = (over) => runStep(bc, { step: 'after-review', slug: 'expired-token', iteration: '1.1', reviewers: ['somi-reviewer'], verdict: 'request-changes', blockers: 0, majors: 1, findings: [{ file: 'a.js', title: 't', severity: 'Major' }], ...over });
98
- const ledgerOf = () => JSON.parse(text(path.join(bad, '.somi', 'reviews', 'expired-token', 'findings.json'))).findings ?? [];
99
- check('a finding is still refused for a missing field or a bad value, each naming the field and the index, and a review name with a path is still refused', [{ findings: [{ file: 'a.js', severity: 'Major', extra: 1 }] }, { findings: [{ file: 'a.js', title: 't', severity: 'Huge' }] }, { findings: [{ file: 'a.js', title: 't', severity: 'Major' }, { file: 'b.js', title: 't', severity: 'Major', confidence: 'certain secret' }] }, { findings: ['x'] }, { review: 'a/b.md' }].map((o) => rv(o).error), ['findings[0].title: is required', 'findings[0].severity: must be one of Blocker|Major|Minor|Nit', 'findings[1].confidence: must be one of High|Medium|Low', 'findings[0]: must be an object {file, title, severity, symbol?, confidence?}', 'review: must be the review file name, without a path']);
100
- check('nothing was recorded by the refused calls', ledgerOf(), []);
101
- const first = rv({}); const again = rv({});
102
- const led = ledgerOf();
103
- check('with no review name the same one is generated for a retry of the pass: replayed, one finding, one sighting', [first.exit, again.replayed, led.length, led[0]?.seen.length, /^pass-1-\d{12}$/.test(led[0]?.introduced_by)], [0, true, 1, 1, true]);
104
-
105
- const low = fixture(); const lw = { ...ctx, root: low, stateDir: path.join(low, '.somi', 'somi-state', 'loop') };
106
- runStep(lw, { step: 'open', slug: 'expired-token', iteration: '1.1' }); writeFileSync(path.join(low, 'src', 'auth', 'token.mjs'), 'x\n');
107
- runStep(lw, { step: 'after-code', slug: 'expired-token', iteration: '1.1', agent: 'somi-coder' });
108
- const lower = runStep(lw, { step: 'after-review', slug: 'expired-token', iteration: '1.1', reviewers: ['somi-reviewer'], verdict: 'request-changes', blockers: 0, majors: 1, findings: [{ file: 'a.js', title: 'lower case', severity: 'major', confidence: 'high' }, { file: 'b.js', title: 'upper case', severity: 'MINOR', confidence: 'LOW' }] });
109
- const stored = (JSON.parse(text(path.join(low, '.somi', 'reviews', 'expired-token', 'findings.json'))).findings ?? []).map((f) => [f.title, f.severity, f.confidence]);
110
- check('severity and confidence in any letter case are recorded in the canonical spelling', [lower.exit, stored], [0, [['lower case', 'Major', 'High'], ['upper case', 'Minor', 'Low']]]);
111
- }
112
-
113
- console.log(`loop step leniency tests: ${pass} ok, ${fail} failed`);
114
- process.exit(fail === 0 ? 0 : 1);