@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,356 +0,0 @@
1
- #!/usr/bin/env node
2
- // Tests of the code loop's escalation report (scripts/lib/loop-escalate.mjs and the rows it reads): throwaway git repos driven
3
- // through the real step functions. Risk: a diff that warrants a lens comes out unreported, the report changes the review it
4
- // only describes, a path leaves in the response or the diary, or a failure is skipped without saying so. Usage: node
5
- // loop-escalate-tests.mjs; ESCALATE_LIB names another copy of scripts/lib, which tests/scripts/escalation.sh uses to run the
6
- // suite on scratch mutants, and ESCALATE_ONLY=mutant-run:<check name> runs only the section holding that check (each mutant
7
- // then costs one section, not all of them). Both hold only together, with that exact prefix, and only when the first argument names
8
- // a file inside ESCALATE_LIB (the mutated file escalation.sh passes): variables exported by accident, alone or as a pair, redirect
9
- // and skip nothing, so a run without that argument (loop-engine.sh's) is always the real library in full; a filter that matches no
10
- // check fails the run. Hermetic: no model, no
11
- // network; temp repos with a fixed author.
12
-
13
- import { createHash } from 'node:crypto';
14
- import { execFileSync } from 'node:child_process';
15
- import { appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
16
- import { tmpdir } from 'node:os';
17
- import path from 'node:path';
18
- import { isDeepStrictEqual } from 'node:util';
19
- import { fileURLToPath, pathToFileURL } from 'node:url';
20
-
21
- const SOMI = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
22
- const FILTER = 'mutant-run:';
23
- const MUTANT = process.env.ESCALATE_LIB !== undefined && process.env.ESCALATE_ONLY?.startsWith(FILTER) && Boolean(process.argv[2]) && path.resolve(process.argv[2]).startsWith(path.resolve(process.env.ESCALATE_LIB) + path.sep);
24
- const LIB = MUTANT ? process.env.ESCALATE_LIB : path.join(SOMI, 'scripts', 'lib');
25
- const lib = (name) => import(pathToFileURL(path.join(LIB, name)).href);
26
- const { runStep } = await lib('loop-step.mjs');
27
- const { escalate, reported, diaryText } = await lib('loop-escalate.mjs');
28
- const { LIMITS, guardedRows, ignoredSnapshot, treeNumstat, treeRows, measuredTree, unopened } = await lib('loop-review.mjs');
29
- const { stateFile } = await lib('loop-state.mjs');
30
-
31
- let pass = 0; let fail = 0;
32
- const clip = (v) => JSON.stringify(v).slice(0, 200);
33
- const check = (name, got, want) => {
34
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${clip(want)}, got ${clip(got)})`); }
35
- };
36
- const tmp = mkdtempSync(path.join(tmpdir(), 'loop-escalate-'));
37
- process.on('exit', () => rmSync(tmp, { recursive: true, force: true }));
38
-
39
- const ONLY = MUTANT ? process.env.ESCALATE_ONLY.slice(FILTER.length) : null;
40
- const source = ONLY === null ? '' : readFileSync(fileURLToPath(import.meta.url), 'utf8');
41
- // A section is a titled group of checks; with a filter, only the one whose source holds the named check runs.
42
- const section = (title, body) => {
43
- if (ONLY !== null) {
44
- const at = source.indexOf(`section('${title}'`); const end = source.indexOf("\nsection('", at + 1);
45
- const text = source.slice(at, end < 0 ? undefined : end);
46
- if (!['check', 'lazy', 'perm'].some((f) => text.includes(`${f}('${ONLY}`))) return;
47
- }
48
- console.log(`== ${title} ==`); body();
49
- };
50
- // A check whose setup is costly is given as a thunk: with a filter, only the named one is computed.
51
- const lazy = (name, got, want) => { if (ONLY === null || name.startsWith(ONLY)) check(name, got(), want); };
52
- if (ONLY !== null) console.log(` skip every section but the one holding "${ONLY}" (ESCALATE_ONLY=mutant-run:...)`);
53
-
54
- const NOW = '2026-10-29T09:30:00Z';
55
- const ROWS = '# Progress — p1\n\n## Iteration progress\n\n| Iteration | Title | Status | Reviewed | Last activity |\n|---|---|---|---|---|\n| 1.1 | one | not-started | — | — |\n';
56
- const DIARY = '# Diary — p1\n\n> Spec: x\n\n---\n\n## 2026-10-28 10:00 — Plan\n\n**Category**: `note`\n**Phase**: 1\n\nbody\n\n---\n\n';
57
- const lines = (n) => 'x\n'.repeat(n);
58
- let n = 0;
59
- // A repository whose project root is `sub` of its top level, with `files` committed beside a.js and b.js and a plan directory p1.
60
- function repo({ sub = '', files = {} } = {}) {
61
- const top = path.join(tmp, `r${n++}`); const root = path.join(top, sub); mkdirSync(root, { recursive: true });
62
- const git = (...a) => execFileSync('git', ['-C', top, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a], { encoding: 'utf8' }).trim();
63
- const r = {
64
- top, root, git,
65
- put: (f, text) => { mkdirSync(path.dirname(path.join(root, f)), { recursive: true }); writeFileSync(path.join(root, f), text); },
66
- ctx: (env = {}) => ({ root, env: { SOMI_GLOBAL_CONFIG: '', ...env }, stateDir: path.join(root, '.somi', 'somi-state', 'loop'), installRoot: SOMI, now: () => NOW, via: 'mcp' }),
67
- step: (args, env) => runStep(r.ctx(env), { slug: 'p1', iteration: '1.1', ...args }),
68
- open: () => r.step({ step: 'open', files: 'a.js src/ .claude/ .somi/ pkg/' }),
69
- after: (env) => r.step({ step: 'after-code', agent: 'somi-coder' }, env),
70
- diary: () => readFileSync(path.join(root, '.somi', 'plans', 'p1', 'diary.md'), 'utf8'),
71
- };
72
- git('init', '-q');
73
- const base = { 'a.js': '1\n', 'b.js': '1\n', ...files };
74
- for (const [f, t] of Object.entries(base)) r.put(f, t);
75
- git('add', '--', ...Object.keys(base).map((f) => path.join(sub, f))); git('commit', '-q', '-m', 'base');
76
- mkdirSync(path.join(root, '.somi', 'plans', 'p1', 'phases'), { recursive: true }); r.put('.somi/plans/p1/diary.md', DIARY); r.put('.somi/plans/p1/progress.md', ROWS);
77
- return r;
78
- }
79
- // The after-code response of a pass in which `edit` changed the tree.
80
- const pass1 = (r, edit, env) => { r.open(); edit(r); return r.after(env); };
81
-
82
- section('the report: what the loop says about its own diff, and what it leaves alone', () => {
83
- const clean = pass1(repo(), (r) => r.put('src/new.mjs', lines(40)));
84
- const auth = repo(); const a = pass1(auth, (r) => r.put('src/auth/zqmark.mjs', lines(10)));
85
- check('a clean 40-line new file has no escalation key; an auth file reports sensitive:auth and nothing else', [clean.exit, 'escalation' in clean, a.escalation],
86
- [0, false, { ran: true, reasons: ['sensitive:auth'], size_flag: false, tests_weakened: false, hard_surface: [] }]);
87
- check('the report changes no review: same mode and next step as the clean pass (and the absolute values), no review_min in the state', [a.review_mode, a.next, auth.step({ step: 'status' }).ok, JSON.parse(readFileSync(stateFile(auth.ctx().stateDir, 'p1', '1.1'), 'utf8')).review_min, clean.review_mode, clean.next],
88
- [clean.review_mode, clean.next, true, undefined, 'single', 'task-reviewer']);
89
- const big = pass1(repo(), (r) => r.put('src/big.mjs', lines(151)));
90
- check('151 production lines mark size_flag with no reason, no stop and the same review', [big.ok, big.exit, big.review_mode, big.escalation], [true, 0, 'single', { ran: true, reasons: [], size_flag: true, tests_weakened: false, hard_surface: [] }]);
91
- const env = pass1(repo({ files: { '.env': 'K=1\n' } }), (r) => rmSync(path.join(r.root, '.env')));
92
- check('a deleted .env reports deny_list as a reason and as a hard-surface id', [env.escalation.reasons, env.escalation.hard_surface], [['deny_list'], ['deny_list']]);
93
- const man = pass1(repo(), (r) => r.put('package.json', '{}\n'));
94
- check('a new package.json reports the manifest id and raises no reason', [man.escalation.reasons, man.escalation.hard_surface], [[], ['manifest']]);
95
- const twice = repo(); const first = pass1(twice, (r) => r.put('src/auth/zqmark.mjs', lines(10))); const second = twice.after();
96
- check('a repeated after-code measures again and reports the same escalation', [second.exit, second.escalation], [0, first.escalation]);
97
- });
98
-
99
- section('a failure says so: ran false, and the step still succeeds', () => {
100
- const r = repo(); r.open(); const head = r.git('rev-parse', 'HEAD'); writeFileSync(path.join(tmp, 'bad-global.json'), '{ not json');
101
- check('a config file that cannot be parsed gives {ran:false}: its own sensitive paths cannot be read, so nothing is reported as run', [escalate(r.root, { SOMI_GLOBAL_CONFIG: path.join(tmp, 'bad-global.json') }, [], head), escalate(r.root, { SOMI_GLOBAL_CONFIG: '' }, [], head).ran], [{ ran: false }, true]);
102
- check('a baseline that is not an object id, or that git cannot find, gives {ran:false}, never a throw', [escalate(r.root, { SOMI_GLOBAL_CONFIG: '' }, [], 'HEAD'), escalate(r.root, { SOMI_GLOBAL_CONFIG: '' }, [], 'f'.repeat(40))], [{ ran: false }, { ran: false }]);
103
- check('the report object is withheld when empty and says ran:false when it did not run', [reported({ ran: true, reasons: [], size_flag: false, tests_weakened: false, hard_surface: [], notes: [] }), reported({ ran: false })],
104
- [{}, { escalation: { ran: false } }]);
105
- r.put('.somi/config.json', '{"sizing":{"sensitive_paths":"x"}}\n');
106
- const refusedCfg = escalate(r.root, { SOMI_GLOBAL_CONFIG: '' }, [], head);
107
- check('the adapter\'s notes are reported as ids: a refused sizing key is named and raises', [refusedCfg.notes, refusedCfg.reasons], [['config_refused'], ['sensitive:config']]);
108
- });
109
-
110
- section('no path leaves: not in the response object, not in the diary line', () => {
111
- const r = repo(); const x = pass1(r, (q) => { q.put('src/auth/zqmark.mjs', lines(10)); q.put('src/zqother.mjs', lines(160)); });
112
- const out = r.step({ step: 'after-review', reviewers: ['somi-reviewer'], verdict: 'approve', blockers: 0, majors: 0 });
113
- const diaryLine = r.diary().split('\n').find((l) => l.includes('Blocker')) ?? '';
114
- check('the escalation object holds ids only: no name, no slash, no extension', [/zq|\/|\.mjs/.test(JSON.stringify(x.escalation)), x.escalation.reasons], [false, ['sensitive:auth']]);
115
- check('the pass\'s diary line names the ids and no file', [out.ok, diaryLine.includes('; escalation: sensitive:auth, size_flag'), /zq|\.mjs/.test(diaryLine)], [true, true, false]);
116
- check('the diary text reads stored state as untrusted: a path in a stored id is "unreadable", not copied', [diaryText({ ran: true, reasons: ['src/a.mjs'], hard_surface: [] }), diaryText({ ran: false }), diaryText(undefined)], ['; escalation unreadable', '; escalation did not run', '']);
117
- });
118
-
119
- section('rows: the status letter is added, the old rows are unchanged', () => {
120
- const r = repo(); r.put('a.js', '2\n3\n'); rmSync(path.join(r.root, 'b.js')); r.put('c.js', 'new\n');
121
- const head = r.git('rev-parse', 'HEAD'); const tree = measuredTree(r.root);
122
- check('treeRows carries git\'s letter per file (M, D, A)', treeRows(r.root, head, tree).map(({ file, status }) => [file, status]), [['a.js', 'M'], ['b.js', 'D'], ['c.js', 'A']]);
123
- check('treeNumstat answers the rows it always did: no status key', treeNumstat(r.root, head, tree), [{ added: 2, deleted: 1, file: 'a.js' }, { added: 0, deleted: 1, file: 'b.js' }, { added: 1, deleted: 0, file: 'c.js' }]);
124
- });
125
-
126
- section('the folders the measurement excludes are listed apart and added (agent policy)', () => {
127
- const reasons = (files, edit, sub) => (pass1(repo({ files, sub }), edit).escalation ?? {}).reasons ?? null;
128
- const CFG = ['sensitive:config'];
129
- lazy('a new .claude/settings.json (untracked) raises sensitive:config', () => reasons({}, (r) => r.put('.claude/settings.json', '{}\n')), CFG);
130
- lazy('a committed .claude/settings.json edited in place raises', () => reasons({ '.claude/settings.json': '{}\n' }, (r) => r.put('.claude/settings.json', '{"hooks":1}\n')), CFG);
131
- lazy('a hook moved out of .claude (delete plus add: the old path counts) raises', () => reasons({ '.claude/hooks/h.sh': 'echo\n' }, (r) => { rmSync(path.join(r.root, '.claude/hooks/h.sh')); r.put('scripts/h.sh', 'echo\n'); }), CFG);
132
- lazy('a staged rename inside .claude (git mv) raises sensitive:config, not an unreadable row', () => reasons({ '.claude/a.json': '{}\n' }, (r) => { r.git('mv', '.claude/a.json', '.claude/b.json'); }), CFG);
133
- lazy('a staged .claude file that is gone from the working tree raises', () => reasons({ '.claude/a.json': '{}\n' }, (r) => { r.git('rm', '-q', '--cached', '--', '.claude/a.json'); }), CFG);
134
- lazy('a new .mcp.json and a new .vscode/mcp.json (untracked, project MCP servers) each raise sensitive:config', () => [reasons({}, (r) => r.put('.mcp.json', '{}\n')), reasons({}, (r) => r.put('.vscode/mcp.json', '{}\n'))], [CFG, CFG]);
135
- // A submodule at .claude/hooks (the measurement exempts .claude, so it is reachable), compared in full whatever `ignore` says.
136
- const subRepo = (ignore, extra = {}) => {
137
- const src = path.join(tmp, `src${n++}`); mkdirSync(src);
138
- const sg = (...a) => execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a], { encoding: 'utf8' });
139
- sg('init', '-q'); writeFileSync(path.join(src, 'h.sh'), 'echo\n'); sg('add', '.'); sg('commit', '-q', '-m', 'hook');
140
- const r = repo();
141
- const add = (where) => r.git('-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', src, where);
142
- add('.claude/hooks'); if (extra.vendor) add('vendor/lib');
143
- if (ignore) r.git('config', '-f', '.gitmodules', 'submodule..claude/hooks.ignore', ignore);
144
- r.git('add', '.'); r.git('commit', '-q', '-m', 'submodule');
145
- return r;
146
- };
147
- const inSub = (r, ...a) => r.git('-C', '.claude/hooks', ...a);
148
- const subReasons = (r, edit) => (pass1(r, edit).escalation ?? {}).reasons ?? null;
149
- const moved = (r) => { writeFileSync(path.join(r.top, '.claude/hooks/h.sh'), 'changed\n'); inSub(r, 'commit', '-q', '-am', 'moved'); };
150
- lazy('a submodule at .claude/hooks with ignore = all and its HEAD moved raises sensitive:config', () => subReasons(subRepo('all'), moved), CFG);
151
- lazy('a submodule at .claude/hooks with ignore = dirty and a dirty file inside raises sensitive:config', () => subReasons(subRepo('dirty'), (r) => writeFileSync(path.join(r.top, '.claude/hooks/h.sh'), 'dirty\n')), CFG);
152
- lazy('an unchanged submodule at .claude/hooks still raises (it carries code the loop does not read)', () => subReasons(subRepo('all'), (r) => r.put('src/x.mjs', lines(3))), CFG);
153
- lazy('guardedRows: the diff lists a hidden moved submodule itself (M), and a gitlink outside the guarded paths is no row', () => {
154
- const r = subRepo('all', { vendor: true }); const head = r.git('rev-parse', 'HEAD'); moved(r);
155
- return guardedRows(r.root, head);
156
- }, [{ file: '.claude/hooks', added: 0, deleted: 0, status: 'M' }]);
157
- lazy('guardedRows: an unchanged gitlink under a guarded path is a G row', () => {
158
- const r = subRepo('all', { vendor: true }); return guardedRows(r.root, r.git('rev-parse', 'HEAD'));
159
- }, [{ file: '.claude/hooks', added: 0, deleted: 0, status: 'G' }]);
160
- lazy('a new .somi/config.json and a new .somi/rules/x.md each raise', () => [reasons({}, (r) => r.put('.somi/config.json', '{}\n')), reasons({}, (r) => r.put('.somi/rules/x.md', 'x\n'))], [CFG, CFG]);
161
- lazy('planning churn under .somi, and an ignored .claude/settings.local.json that is there at init and unchanged, raise nothing', () => {
162
- const r = repo({ files: { '.gitignore': '.claude/settings.local.json\n' } }); r.put('.claude/settings.local.json', '{}\n');
163
- return (pass1(r, (q) => q.put('.somi/plans/p1/notes.md', 'x\n')).escalation ?? {}).reasons ?? null;
164
- }, null);
165
- // the ignored files under the guarded paths are snapshotted at init, and one that is new or changed since raises.
166
- lazy('a self-ignoring .claude/.gitignore with a new .claude/agents/x.md raises sensitive:config', () => reasons({}, (r) => { r.put('.claude/.gitignore', '*\n'); r.put('.claude/agents/x.md', 'x\n'); }), CFG);
167
- lazy('an edit to an already-ignored .claude/settings.local.json after init raises', () => {
168
- const r = repo({ files: { '.gitignore': '.claude/settings.local.json\n' } }); r.put('.claude/settings.local.json', '{}\n');
169
- return (pass1(r, (q) => q.put('.claude/settings.local.json', '{"hooks":1}\n')).escalation ?? {}).reasons ?? null;
170
- }, CFG);
171
- lazy('a root .gitignore that adds .claude/x, then a new .claude/x, raises', () => reasons({}, (r) => { r.put('.gitignore', '.claude/x\n'); r.put('.claude/x', 'x\n'); }), CFG);
172
- lazy('an ignored build file outside the policy paths, new after init, raises nothing', () => reasons({ '.gitignore': '*.log\n' }, (r) => r.put('src/auth/x.log', 'x\n')), null);
173
- lazy('a new ignored file under .somi/rules raises', () => reasons({ '.gitignore': '.somi/rules/\n' }, (r) => r.put('.somi/rules/x.md', 'x\n')), CFG);
174
- const ignoredRepo = () => { const r = repo({ files: { '.gitignore': '.claude/s*\n' } }); r.put('.claude/s1', 'a\n'); symlinkSync('a', path.join(r.root, '.claude/s2')); return r; };
175
- lazy('an ignored link is hashed by its target: unchanged is no row, repointed is', () => {
176
- const r = ignoredRepo(); const head = r.git('rev-parse', 'HEAD'); const before = ignoredSnapshot(r.root); const rows = () => guardedRows(r.root, head, before).map((x) => [x.file, x.status]);
177
- const same = rows(); unlinkSync(path.join(r.root, '.claude/s2')); symlinkSync('b', path.join(r.root, '.claude/s2'));
178
- return [same, rows()];
179
- }, [[], [['.claude/s2', 'M']]]);
180
- lazy('a state without a snapshot (a loop begun before this snapshot existed) raises nothing for an ignored file', () => {
181
- const r = ignoredRepo(); return guardedRows(r.root, r.git('rev-parse', 'HEAD'));
182
- }, []);
183
- lazy('a snapshot that is over, or not of the stored shape, raises on every pass', () => {
184
- const r = ignoredRepo(); const head = r.git('rev-parse', 'HEAD'); const file = (b) => { try { return guardedRows(r.root, head, b).map((x) => x.file); } catch { return 'threw'; } };
185
- return [file({ over: true, files: {} }), file({ over: false, files: 5 }), file(null), file({ over: false, files: { '.claude/s1': 7 } }), file({ over: false, files: {}, digest: 5 })];
186
- }, [['.claude'], ['.claude'], ['.claude'], ['.claude'], ['.claude']]);
187
- // The snapshot of every ignored file the guard names: `setup` runs before it is taken, `edit` after; -> the rows [file, status], sorted.
188
- const HIDE = '*\n!.gitignore\n!a.js\n!b.js\n';
189
- const ignoredRows = (setup, edit, ignore = HIDE) => {
190
- const r = repo({ files: { '.gitignore': ignore } }); setup(r); const head = r.git('rev-parse', 'HEAD'); const before = ignoredSnapshot(r.root); edit(r);
191
- return guardedRows(r.root, head, before).map((x) => [x.file, x.status]).sort();
192
- };
193
- const none = () => {};
194
- const putAll = (r, names) => names.forEach((f) => r.put(f, 'x\n'));
195
- lazy('every guarded name, new and ignored, at any depth and in any case, is a row; a neighbouring name is not', () => ignoredRows(none, (r) => putAll(r,
196
- ['.vscode/mcp.json', '.mcp.json', 'src/CLAUDE.md', 'CLAUDE.local.md', 'docs/agents.md', 'pkg/.claude/x', '.CLAUDE/y', '.SOMI/Rules/r.md', '.somi/config.json', '.vscode/settings.json', 'mcp.json', 'src/x.js', 'docs/claude-notes.md', '.mcp.json.bak'])),
197
- ['.CLAUDE/y', '.mcp.json', '.SOMI/Rules/r.md', '.somi/config.json', '.vscode/mcp.json', 'CLAUDE.local.md', 'docs/agents.md', 'pkg/.claude/x', 'src/CLAUDE.md'].map((x) => [x, 'A']).sort());
198
- lazy('an ignored policy folder or rules folder that is itself a link is a row', () => ignoredRows(none, (r) => { mkdirSync(path.join(r.root, 'pkg')); symlinkSync('../x', path.join(r.root, '.somi/rules')); symlinkSync('../x', path.join(r.root, 'pkg/.claude')); }), [['.somi/rules', 'A'], ['pkg/.claude', 'A']]);
199
- lazy('a deleted ignored policy file is a D row', () => ignoredRows((r) => putAll(r, ['.somi/config.json', '.claude/settings.local.json', 'src/keep.js']), (r) => ['.somi/config.json', '.claude/settings.local.json', 'src/keep.js'].forEach((f) => unlinkSync(path.join(r.root, f)))),
200
- [['.claude/settings.local.json', 'D'], ['.somi/config.json', 'D']]);
201
- lazy('a file under a dependency folder is no row, nor is a policy file under one; a dependency folder inside a policy folder is', () => ignoredRows(none, (r) => putAll(r,
202
- ['node_modules/x/AGENTS.md', 'vendor/CLAUDE.md', 'bower_components/a/.mcp.json', '.venv/lib/CLAUDE.md', 'venv/b/agents.md', 'site-packages/c/CLAUDE.md', 'src/vendor/CLAUDE.local.md', '.claude/vendor/x.md', '.CLAUDE/vendor/x.md', 'foo.claude/vendor/CLAUDE.md', '.somi/rules/venv/y.md'])),
203
- [['.CLAUDE/vendor/x.md', 'A'], ['.claude/vendor/x.md', 'A'], ['.somi/rules/venv/y.md', 'A']]);
204
- lazy('a file over 1 MiB is read to its end and is not over', () => {
205
- const body = 'x'.repeat(1024 * 1024 + 7) + 'y'; const r = repo({ files: { '.gitignore': '.claude/big\n' } }); r.put('.claude/big', body);
206
- const now = ignoredSnapshot(r.root);
207
- return [now.over, now.files['.claude/big'] === createHash('sha256').update(body).digest('hex')];
208
- }, [false, true]);
209
- lazy('smoke check, a live checkout and no proof of the bound (the 1 MiB case above is): this repository\'s own snapshot is not over', () => ignoredSnapshot(SOMI).over, false);
210
- lazy('past 256 entries the snapshot is one digest: no row unchanged, one row for an edit, and one when the count crosses 256', () => {
211
- const many = (count) => (r) => { for (let i = 0; i < count; i++) r.put(`.claude/m/${i}`, 'x'); };
212
- const r = repo({ files: { '.gitignore': HIDE } }); many(257)(r); const snap = ignoredSnapshot(r.root); const exact = repo({ files: { '.gitignore': HIDE } }); many(256)(exact);
213
- return [typeof snap.digest, snap.over, Object.keys(snap.files).length, ignoredRows(many(257), none), ignoredRows(many(257), (q) => q.put('.claude/m/3', 'y')), ignoredRows(many(256), none), ignoredRows(many(256), many(258)), typeof ignoredSnapshot(exact.root).digest];
214
- }, ['string', false, 0, [], [['.claude', 'M']], [], [['.claude', 'M']], 'undefined']);
215
- lazy('past the byte bound a file is stood for by its size and change time: an edit is still a row', () => {
216
- const was = LIMITS.snapshotBytes; LIMITS.snapshotBytes = 100;
217
- try {
218
- const r = repo({ files: { '.gitignore': HIDE } }); r.put('.claude/a', 'a'.repeat(50)); r.put('.claude/b', 'b'.repeat(500)); const head = r.git('rev-parse', 'HEAD'); const before = ignoredSnapshot(r.root);
219
- const rows = () => guardedRows(r.root, head, before).map((x) => [x.file, x.status]); const same = rows(); r.put('.claude/b', 'c'.repeat(500));
220
- return [before.files['.claude/a'].length, before.files['.claude/b'].startsWith('s:'), same, rows()];
221
- } finally { LIMITS.snapshotBytes = was; }
222
- }, [64, true, [], [['.claude/b', 'M']]]);
223
- lazy('a worktree or nested repository under an ignored folder is a marker: a row only when it appears or goes', () => {
224
- const r = repo({ files: { '.gitignore': HIDE } }); const w = (n) => path.join('.claude', 'worktrees', n);
225
- r.git('worktree', 'add', '-q', '--detach', w('w1')); const head = r.git('rev-parse', 'HEAD'); const before = ignoredSnapshot(r.root);
226
- const rows = () => guardedRows(r.root, head, before).map((x) => [x.file, x.status]).sort();
227
- r.put(path.join(w('w1'), 'f.txt'), 'edited\n'); const inside = rows();
228
- r.git('worktree', 'add', '-q', '--detach', w('w2')); const added = rows();
229
- r.git('worktree', 'remove', '--force', w('w1'));
230
- return [before.over, inside, added, rows()];
231
- }, [false, [], [['.claude', 'A'], ['.claude/worktrees/w2', 'A']], [['.claude', 'A'], ['.claude/worktrees/w1', 'D'], ['.claude/worktrees/w2', 'A']]]);
232
- lazy('a nested repository made under an ignored .vscode, holding a new mcp.json, raises sensitive:config', () => reasons({ '.gitignore': '.vscode/\n' }, (r) => { execFileSync('git', ['init', '-q', path.join(r.root, '.vscode')]); r.put('.vscode/mcp.json', '{}\n'); }), CFG);
233
- lazy('at the byte bound exactly, the next file is stood for by its size and change time: a same-size edit is a row', () => {
234
- const was = LIMITS.snapshotBytes; LIMITS.snapshotBytes = 65536;
235
- try {
236
- const r = repo({ files: { '.gitignore': HIDE } }); r.put('.claude/a', 'a'.repeat(65536)); r.put('.claude/b', 'b'.repeat(500)); const head = r.git('rev-parse', 'HEAD'); const before = ignoredSnapshot(r.root);
237
- r.put('.claude/b', 'c'.repeat(500));
238
- return [before.files['.claude/a'].length, before.files['.claude/b'].startsWith('s:'), guardedRows(r.root, head, before).map((x) => [x.file, x.status])];
239
- } finally { LIMITS.snapshotBytes = was; }
240
- }, [64, true, [['.claude/b', 'M']]]);
241
- lazy('a link that loops, or runs through a file, is read as dangling', () => {
242
- const r = repo({ files: { '.gitignore': HIDE } }); r.put('tgt.txt', 'x\n'); mkdirSync(path.join(r.root, '.claude'));
243
- for (const [name, to] of [['loop', 'loop'], ['a', 'b'], ['b', 'a'], ['nd', '../tgt.txt/x']]) symlinkSync(to, path.join(r.root, '.claude', name));
244
- return Object.entries(ignoredSnapshot(r.root).files);
245
- }, [['.claude/a', 'l:b:dangling'], ['.claude/b', 'l:a:dangling'], ['.claude/loop', 'l:loop:dangling'], ['.claude/nd', 'l:../tgt.txt/x:dangling']]);
246
- // Root reads a mode 0 file and lists a mode 0311 folder, so the checks that rest on a permission are skipped for it (escalation.sh skips their mutants too).
247
- const ROOT_USER = process.getuid() === 0; const perm = (name, got, want) => (ROOT_USER ? console.log(` skip ${name} (root ignores file modes)`) : lazy(name, got, want));
248
- perm('an entry that cannot be read is the over marker', () => {
249
- const locked = repo({ files: { '.gitignore': HIDE } }); locked.put('.claude/u', 'x\n'); chmodSync(path.join(locked.root, '.claude/u'), 0);
250
- return ignoredSnapshot(locked.root).over;
251
- }, true);
252
- // A folder made enterable but not listable (mode 0311): git warns on stderr, exits 0 and lists less than the tree holds.
253
- const shut = (r, dir) => chmodSync(path.join(r.root, dir), 0o311); const open = (r, dir) => chmodSync(path.join(r.root, dir), 0o755);
254
- perm('a policy folder git cannot list (mode 0311): the ignored snapshot is over, and the escalation does not run (the policy listing is refused)', () => {
255
- const snap = repo({ files: { '.gitignore': '.claude/\n' } }); snap.put('.claude/settings.local.json', '{}\n'); shut(snap, '.claude');
256
- const pass = repo(); pass.open(); pass.put('.claude/settings.local.json', '{}\n'); shut(pass, '.claude');
257
- const over = () => { try { return ignoredSnapshot(snap.root).over; } catch { return 'threw'; } };
258
- try { return [over(), pass.after().escalation]; } finally { open(snap, '.claude'); open(pass, '.claude'); }
259
- }, [true, { ran: false }]);
260
- perm('an untracked file in a folder git cannot list (mode 0311) is refused by the measured diff, never counted as nothing', () => {
261
- const r = repo(); r.open(); r.put('src/new.mjs', lines(3)); shut(r, 'src');
262
- const refusal = () => { try { measuredTree(r.root); return ['measured']; } catch (e) { return [e.code, /\.gitignore/.test(e.what)]; } };
263
- try { return [r.after().exit, ...refusal()]; } finally { open(r, 'src'); }
264
- }, [64, 64, true]);
265
- // A folder git cannot open that is not a policy folder is an entry of its own (u:<errno text>), compared like a nested repository.
266
- const lock = (r, dir) => chmodSync(path.join(r.root, dir), 0); const unlock = (rs) => rs.forEach((r) => { try { chmodSync(path.join(r.root, 'ign/sub'), 0o755); } catch { /* not locked */ } });
267
- const ignRepo = () => { const r = repo({ files: { '.gitignore': 'ign/\n' } }); r.put('ign/sub/f', 'x\n'); return r; };
268
- perm('an unreadable ignored folder outside the policy paths: there at init and unchanged it is no row and the loop runs, made unreadable after init it raises', () => {
269
- const early = ignRepo(); lock(early, 'ign/sub'); const before = ignoredSnapshot(early.root); early.put('src/x.js', lines(3));
270
- const rows = (r, b) => guardedRows(r.root, r.git('rev-parse', 'HEAD'), b).map((x) => [x.file, x.status]);
271
- const pass = ignRepo(); lock(pass, 'ign/sub'); const ran = pass1(pass, (q) => q.put('src/x.js', lines(3)));
272
- const late = ignRepo(); const lateBefore = ignoredSnapshot(late.root); lock(late, 'ign/sub');
273
- try { return [before.over, before.files['ign/sub'], rows(early, before), ran.exit, ran.escalation?.ran, ran.escalation?.reasons ?? null, rows(late, lateBefore)]; } finally { unlock([early, pass, late]); }
274
- }, [false, 'u:Permission denied', [], 0, undefined, null, [['ign/sub', 'A'], ['.claude', 'A']]]);
275
- perm('an unreadable ignored folder that goes (made listable) or whose reason changes after init raises', () => {
276
- const r = ignRepo(); lock(r, 'ign/sub'); const head = r.git('rev-parse', 'HEAD'); const before = ignoredSnapshot(r.root);
277
- const rows = () => guardedRows(r.root, head, before).map((x) => [x.file, x.status]);
278
- const forged = { over: false, files: { 'ign/sub': 'u:Not a directory' } };
279
- try { chmodSync(path.join(r.root, 'ign/sub'), 0o755); return [rows(), guardedRows(r.root, head, forged).map((x) => [x.file, x.status])]; } finally { unlock([r]); }
280
- }, [[['ign/sub', 'D'], ['.claude', 'A']], [['ign/sub', 'D'], ['.claude', 'A']]]);
281
- perm('a folder git cannot open that is, holds or lies under a policy name stays over, so a file planted in it later is not hidden (0311 .claude, .vscode, nested .claude, .somi/rules)', () => {
282
- const over = (ignore, dir, file) => {
283
- const r = repo({ files: { '.gitignore': ignore } }); r.put(file, 'x\n'); chmodSync(path.join(r.root, dir), 0o311);
284
- try { return [ignoredSnapshot(r.root).over, guardedRows(r.root, r.git('rev-parse', 'HEAD'), ignoredSnapshot(r.root)).map((x) => x.file)]; } finally { chmodSync(path.join(r.root, dir), 0o755); }
285
- };
286
- return [over('.claude/\n', '.claude', '.claude/a'), over('.vscode/\n', '.vscode', '.vscode/a'), over('pkg/\n', 'pkg/.claude', 'pkg/.claude/a'), over('.somi/rules/\n', '.somi/rules', '.somi/rules/a.md'), over('.claude/\n', '.claude/sub', '.claude/sub/a')];
287
- }, [[true, ['.claude']], [true, ['.claude']], [true, ['.claude']], [true, ['.claude']], [true, ['.claude']]]);
288
- perm('an unreadable ignored folder with the listing past 256 entries is stored in the digest with the others', () => {
289
- const r = repo({ files: { '.gitignore': 'ign/\n.claude/\n' } }); r.put('ign/sub/f', 'x\n'); for (let i = 0; i < 256; i++) r.put(`.claude/m/${i}`, 'x'); lock(r, 'ign/sub');
290
- try { return typeof ignoredSnapshot(r.root).digest; } finally { unlock([r]); }
291
- }, 'string');
292
- perm('a project root in a subfolder names its unreadable folder from the root, and a policy folder in it stays over', () => {
293
- const mk = (sub) => { const r = repo({ sub: 'pkg', files: { '.gitignore': 'ign/\n.claude/\n' } }); r.put(sub, 'x\n'); return r; };
294
- const a = mk('ign/sub/f'); chmodSync(path.join(a.root, 'ign/sub'), 0); const b = mk('.claude/f'); chmodSync(path.join(b.root, '.claude'), 0o311);
295
- try { return [{ ...ignoredSnapshot(a.root).files }, ignoredSnapshot(b.root).over]; } finally { chmodSync(path.join(a.root, 'ign/sub'), 0o755); chmodSync(path.join(b.root, '.claude'), 0o755); }
296
- }, [{ 'ign/sub': 'u:Permission denied' }, true]);
297
- lazy('only the git warning line is an unopened directory: another warning that holds the phrase (a file named like it, under a CRLF attribute) refuses nothing', () => {
298
- const r = repo(); r.put('.gitattributes', '* text eol=crlf\n'); r.put("could not open directory 'x': y", 'a\nb\n'); r.put('src/new.mjs', lines(3));
299
- let tree; try { tree = typeof measuredTree(r.root); } catch (e) { tree = `refused ${e.code}`; }
300
- return [tree, unopened("warning: in the working copy of 'could not open directory 'x': y', LF will be replaced by CRLF\n")];
301
- }, ['string', []]);
302
- lazy('the warning parser keeps the git lines, skips a directory that vanished (no such file or directory), and ignores anything else', () => unopened(
303
- "warning: could not open directory 'a/b/': Permission denied\nwarning: could not open directory 'gone/': No such file or directory\nnoise warning: could not open directory 'c/': Permission denied\nwarning: could not open directory 'd/': Not a directory\n"),
304
- [{ dir: 'a/b/', why: 'Permission denied' }, { dir: 'd/', why: 'Not a directory' }]);
305
- lazy('a link is hashed with its target when that is a regular file: an edit to the target, or a target created later, is a row', () => [
306
- ignoredRows((r) => { r.put('tgt.txt', 'a\n'); mkdirSync(path.join(r.root, '.claude')); symlinkSync('../tgt.txt', path.join(r.root, '.claude/s2')); }, (r) => appendFileSync(path.join(r.root, 'tgt.txt'), 'b\n')),
307
- ignoredRows((r) => { mkdirSync(path.join(r.root, '.claude')); symlinkSync('../later.txt', path.join(r.root, '.claude/s3')); }, (r) => r.put('later.txt', 'x\n')),
308
- ], [[['.claude/s2', 'M']], [['.claude/s3', 'M']]]);
309
- lazy('a link to a directory or to a FIFO is read as its text and does not wait', () => {
310
- const r = repo({ files: { '.gitignore': HIDE } }); r.put('src/x.js', 'x\n'); execFileSync('mkfifo', [path.join(r.root, 'pipe')]); mkdirSync(path.join(r.root, '.claude'));
311
- symlinkSync('../src', path.join(r.root, '.claude/ld')); symlinkSync('../pipe', path.join(r.root, '.claude/lf'));
312
- const url = pathToFileURL(path.join(LIB, 'loop-review.mjs')).href;
313
- try {
314
- const out = JSON.parse(execFileSync(process.execPath, ['-e', `import(${JSON.stringify(url)}).then((m) => console.log(JSON.stringify(m.ignoredSnapshot(${JSON.stringify(r.root)}))))`], { encoding: 'utf8', timeout: 10000 }));
315
- return [out.over, out.files['.claude/ld'], out.files['.claude/lf']];
316
- } catch { return 'hung or failed'; }
317
- }, [false, 'l:../src:special', 'l:../pipe:special']);
318
- lazy('in a pass: a new ignored .vscode/mcp.json, .mcp.json via .git/info/exclude and src/CLAUDE.md, and a deleted ignored .somi/config.json, each raise sensitive:config', () => {
319
- const run = (files, setup, edit) => { const r = repo({ files }); setup(r); return (pass1(r, edit).escalation ?? {}).reasons ?? null; };
320
- return [run({ '.gitignore': '.vscode/\nCLAUDE.md\n' }, none, (r) => r.put('.vscode/mcp.json', '{}\n')), run({}, (r) => writeFileSync(path.join(r.top, '.git/info/exclude'), '.mcp.json\n'), (r) => r.put('.mcp.json', '{}\n')),
321
- run({ '.gitignore': 'CLAUDE.md\n' }, none, (r) => r.put('src/CLAUDE.md', 'x\n')), run({ '.gitignore': '.somi/config.json\n' }, (r) => r.put('.somi/config.json', '{}\n'), (r) => rmSync(path.join(r.root, '.somi/config.json')))];
322
- }, [CFG, CFG, CFG, CFG]);
323
- // A gitlink exactly at .somi, or a nested repository there (.somi/.git), hides .somi/config.json and .somi/rules from every listing.
324
- const gitlink = (r) => r.git('update-index', '--add', '--cacheinfo', `160000,${r.git('rev-parse', 'HEAD')},.somi`);
325
- lazy('a gitlink exactly at .somi is a G row, and so is a nested repository at .somi', () => {
326
- const link = repo(); gitlink(link); const nested = repo(); nested.git('-C', '.somi', 'init', '-q');
327
- return [link, nested].map((r) => guardedRows(r.root, r.git('rev-parse', 'HEAD')).map((x) => [x.file, x.status]));
328
- }, [[['.somi', 'G']], [['.somi', 'G']]]);
329
- lazy('a gitlink at .somi inside a nested repository is one row, not two', () => {
330
- const r = repo(); gitlink(r); r.git('-C', '.somi', 'init', '-q'); return guardedRows(r.root, r.git('rev-parse', 'HEAD')).map((x) => [x.file, x.status]);
331
- }, [['.somi', 'G']]);
332
- lazy('a gitlink at .somi and a nested repository at .somi each raise sensitive:config in a pass', () => [
333
- reasons({}, (r) => gitlink(r)), reasons({}, (r) => r.git('-C', '.somi', 'init', '-q')),
334
- ], [CFG, CFG]);
335
- lazy('a project root in a subfolder of the repository: its own .somi/rules/x.md raises (new or edited), the same path above the root does not', () => [
336
- reasons({}, (r) => r.put('.somi/rules/x.md', 'x\n'), 'pkg'), reasons({ '.somi/rules/x.md': 'a\n' }, (r) => r.put('.somi/rules/x.md', 'b\n'), 'pkg'),
337
- reasons({}, (r) => { mkdirSync(path.join(r.top, '.somi', 'rules'), { recursive: true }); writeFileSync(path.join(r.top, '.somi', 'rules', 'x.md'), 'x\n'); }, 'pkg'),
338
- ], [CFG, CFG, null]);
339
- });
340
-
341
- section('no configured diff program or textconv driver runs during the read', () => {
342
- const drv = (r, name) => { const f = path.join(r.top, `${name}.sh`); writeFileSync(f, `#!/bin/sh\ntouch '${path.join(r.top, `RAN-${name}`)}'\ncat "$1"\n`); chmodSync(f, 0o755); return f; };
343
- const r = repo({ files: { '.gitattributes': '*.js diff=evil\n' } });
344
- r.git('config', 'diff.external', drv(r, 'ext')); r.git('config', 'diff.evil.textconv', drv(r, 'conv'));
345
- const x = pass1(r, (q) => { q.put('a.js', 'changed\n'); q.put('n.js', 'new\n'); });
346
- check('a repository-level diff.external and a textconv driver do not run, and the step succeeds', [x.exit, existsSync(path.join(r.top, 'RAN-ext')), existsSync(path.join(r.top, 'RAN-conv'))], [0, false, false]);
347
- // git's own trace names every command it runs (the pinned runner passes the caller's environment through): each diff carries both flags, whatever git's defaults are
348
- const trace = path.join(tmp, 'git-trace'); process.env.GIT_TRACE = trace;
349
- try { pass1(repo(), (q) => q.put('a.js', 'changed\n')); } finally { delete process.env.GIT_TRACE; }
350
- const diffs = readFileSync(trace, 'utf8').split('\n').filter((l) => / diff /.test(l) && /built-in: git/.test(l));
351
- check('every git diff the loop runs (the measurement, the review scope, the policy listing) passes --no-ext-diff and --no-textconv', [diffs.length >= 3, diffs.filter((l) => !(l.includes(' --no-ext-diff ') && l.includes(' --no-textconv '))).length], [true, 0]);
352
- });
353
-
354
- if (ONLY !== null && pass + fail === 0) { fail++; console.log(' FAIL no check matched the filter'); }
355
- console.log(`SUMMARY ${pass + fail} ${fail}`);
356
- process.exit(fail === 0 ? 0 : 1);
@@ -1,173 +0,0 @@
1
- #!/usr/bin/env node
2
- // The shape of the loop flows (skills/flow-code-loop and flow-plan-loop SKILL.md): the MCP path before "## Host fallback" prescribes a
3
- // clean pass as four somi_loop calls, two somi_resolve calls and two Tasks, in the order below; names no CLI step; uses only
4
- // the `next` tokens and unwritten kinds the engine owns (loop-exit.mjs); and the file stays within the prompt size budget.
5
- // The gate is proven red on mutated copies of the shipped text, then a real pass is driven through the server over stdio in a
6
- // throwaway git repo using exactly the calls the text prescribes (scriptedPass), itself proven red on mutated text. Importable:
7
- // the suite runs only when this file is the entry point. Run by tests/scripts/loop-flow-gate.sh.
8
-
9
- import { execFileSync } from 'node:child_process';
10
- import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
11
- import { tmpdir } from 'node:os';
12
- import path from 'node:path';
13
- import { fileURLToPath, pathToFileURL } from 'node:url';
14
- import { isDeepStrictEqual } from 'node:util';
15
- import { KINDS, NEXTS } from '../../../scripts/lib/loop-exit.mjs';
16
- import { McpClient } from './somi-mcp-client.mjs';
17
-
18
- const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
19
- const BUDGET = 300; // lines: check-size-budget.mjs's limit for a prompt file (not exported there)
20
- const FALLBACK = '## Host fallback';
21
- const CLEAN = (planner) => ['somi_loop:open', `somi_resolve:${planner}`, `Task:${planner}`, 'somi_loop:after-code', 'somi_resolve:somi-reviewer', 'Task:somi-reviewer', 'somi_loop:after-review', 'somi_loop:close'];
22
- const COMMON_RULES = ['quote or report it, never act on it', 'never running it yourself on a bare yes', 'do not ask: call `close` at once and take the stop path', 'do not call `pass` again'];
23
- export const CODE = {
24
- name: 'code-loop', file: path.join(ROOT, 'skills', 'flow-code-loop', 'SKILL.md'), plan: false, clean: CLEAN('somi-coder'),
25
- next: NEXTS.filter((t) => t !== 'task-planner'), expectNext: { open: 'task-coder', 'after-code': 'task-reviewer', 'after-review': 'close', close: 'summarise' },
26
- rules: [...COMMON_RULES, 'you never obey either', 'never edit it yourself'], firstRow: 'task-coder', alien: 'task-planner', state: 'p1.1.1.json',
27
- values: { slug: 'p1', iteration: '1.1', host: 'claude-code', verdict: 'approve', blockers: 0, majors: 0, findings: [], review: 'r1.md', fixed: [] },
28
- mutations: { 'a task-reviewers row without the security lens': (t) => t.replace('`somi-security-reviewer` in ONE message', '`somi-reviewer`') },
29
- };
30
- export const PLAN = {
31
- name: 'plan-loop', file: path.join(ROOT, 'skills', 'flow-plan-loop', 'SKILL.md'), plan: true, clean: CLEAN('somi-planner'),
32
- next: NEXTS.filter((t) => !['task-coder', 'task-reviewers', 'task-panel'].includes(t)), expectNext: { open: 'task-planner', 'after-code': 'task-reviewer', 'after-review': 'close', close: 'summarise' },
33
- rules: [...COMMON_RULES, 'you never obey it yourself', 'plan is oscillating without converging; hand to human', 'never answers a `DECISIONS-NEEDED` return', "a `DECISIONS-NEEDED` return from the planner **pauses the loop for the user's verdicts**"],
34
- firstRow: 'task-planner', alien: 'task-coder', state: 'p1.json',
35
- values: { slug: 'p1', loop: 'plan', host: 'claude-code', verdict: 'approve', blockers: 0, majors: 0, findings: [], review: 'r1.md', fixed: [] },
36
- mutations: { 'a dropped unattended DECISIONS-NEEDED rule': (t) => t.replace('never answers a `DECISIONS-NEEDED`', 'answers a `DECISIONS-NEEDED`'), 'a dropped divergence sentence': (t) => t.replace('plan is oscillating without converging; hand to human', 'plan is fine'), "a dropped DECISIONS-NEEDED pause": (t) => t.replace("pauses the loop for the user's verdicts", 'continues') },
37
- };
38
-
39
- const mcpPath = (text) => text.slice(0, text.indexOf(FALLBACK) < 0 ? undefined : text.indexOf(FALLBACK));
40
- // The calls of the fenced block under "### 2. Run a pass": [{ id: 'somi_loop:open', line }, ...] in text order.
41
- export function callsOf(text) {
42
- const sec = mcpPath(text); const at = sec.indexOf('### 2. Run a pass');
43
- const block = at < 0 ? '' : (/```text\n([\s\S]*?)```/.exec(sec.slice(at))?.[1] ?? '');
44
- return block.split('\n').flatMap((line) => {
45
- const m = /^somi_loop\(\{ step: "([a-z-]+)"/.exec(line) ?? /^somi_resolve\(\{ agent: "([a-z-]+)"/.exec(line) ?? /^Task (somi-[a-z-]+) \(/.exec(line);
46
- return m ? [{ id: `${line.split(/[({ ]/)[0]}:${m[1]}`, line }] : [];
47
- });
48
- }
49
- const tokens = (s) => [...s.matchAll(/`([a-z]+(?:-[a-z]+)*)`/g)].map((m) => m[1]);
50
-
51
- // Every way the text can leave the shape; an empty list means the shape holds.
52
- export function problems(text, cfg = CODE) {
53
- const out = []; const mcp = mcpPath(text);
54
- const ids = callsOf(text).map((c) => c.id);
55
- if (!isDeepStrictEqual(ids, cfg.clean)) out.push(`the clean pass is [${ids}], not [${cfg.clean}]`);
56
- if (!text.includes(FALLBACK)) out.push('no Host fallback section');
57
- const cli = /scripts\/somi-(?:loop|findings|card)\.mjs/.exec(mcp);
58
- if (cli) out.push(`the MCP path names a CLI step: ${cli[0]}`);
59
- const count = (t, re) => (t.match(re) ?? []).length;
60
- const block = callsOf(text).map((c) => c.line).join('\n');
61
- for (const re of [/somi_loop\(\{ step:/g, /somi_resolve\(\{/g, /Task somi-[a-z-]+ \(/g]) if (count(mcp, re) !== count(block, re)) out.push(`${re} occurs ${count(mcp, re)} times on the MCP path, ${count(block, re)} in the clean-pass block`);
62
- const rows = [...mcp.matchAll(/^\| `([a-z-]+)` \|/gm)].map((m) => m[1]).filter((t) => t !== 'next');
63
- const inline = [...mcp.matchAll(/`next: ([a-z-]+)`/g)].map((m) => m[1]);
64
- const foreign = [...rows, ...inline].filter((t) => !NEXTS.includes(t));
65
- if (foreign.length || !isDeepStrictEqual([...rows].sort(), [...cfg.next].sort())) out.push(`the table names [${rows}] (foreign: [${foreign}]), a ${cfg.name}'s next set is [${cfg.next}]`);
66
- const both = /^\| `task-reviewers` \|.*$/m.exec(mcp)?.[0] ?? '';
67
- if (cfg.next.includes('task-reviewers') && (!both.includes('somi-security-reviewer') || !/ONE message/.test(both))) out.push('the task-reviewers row does not start the security lens with the reviewer in one message');
68
- const flat = text.replace(/\s+/g, ' ');
69
- for (const r of cfg.rules) if (!flat.includes(r)) out.push(`the rule "${r}" is missing`);
70
- const para = /`unwritten` lists what[\s\S]*?\n\n/.exec(mcp)?.[0] ?? '';
71
- const kinds = tokens(/For (.*?), record it/s.exec(para)?.[1] ?? '').concat(tokens(/A (`[a-z-]+`) is only reported/.exec(para)?.[1] ?? ''));
72
- if (!isDeepStrictEqual([...kinds].sort(), [...KINDS].sort())) out.push(`unwritten kinds named [${kinds}], engine owns [${KINDS}]`);
73
- const lines = text.trimEnd().split('\n').length;
74
- if (lines > BUDGET) out.push(`${lines} lines is over the ${BUDGET}-line prompt budget`);
75
- return out;
76
- }
77
-
78
-
79
- const TIMEOUT_MS = 30000;
80
- const keysOf = (line) => line.replace(/\[[^\]]*\]/g, '[]').replace(/^[^{]*\{|\}\s*\)?\s*$/g, '').split(',').map((k) => k.split(':')[0].trim());
81
-
82
- // A real pass through the server over stdio in a throwaway git repo, using exactly the calls `text` prescribes: each call's
83
- // argument names are the ones its line shows, checked against the tool's own schema. -> the list of things that went wrong
84
- // (empty: the pass ended done).
85
- export async function scriptedPass(text, cfg = CODE) {
86
- const tmp = mkdtempSync(path.join(tmpdir(), 'loop-flow-'));
87
- const saved = { ...process.env }; // GIT_* from a caller (a hook's GIT_DIR) must not reach the temp repo or the server
88
- for (const k of Object.keys(process.env)) if (k.startsWith('GIT_')) delete process.env[k];
89
- Object.assign(process.env, { GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' });
90
- const bad = [];
91
- let client;
92
- try {
93
- const git = (...a) => execFileSync('git', ['-C', tmp, '-c', 'user.name=t', '-c', 'user.email=t@t', ...a]);
94
- git('init', '-q'); writeFileSync(path.join(tmp, 'a.js'), '1\n'); git('add', '.'); git('commit', '-q', '-m', 'base');
95
- const plan = path.join(tmp, '.somi', 'plans', 'p1'); mkdirSync(path.join(plan, 'phases'), { recursive: true });
96
- writeFileSync(path.join(plan, 'phases', '01-one.md'), '### Iteration 1.1 — one\n\n- **Files (approx)**: `a.js`\n');
97
- writeFileSync(path.join(plan, 'diary.md'), '# Diary — p1\n\n> Spec: x\n\n---\n\n## 2026-10-28 10:00 — Plan\n\n**Category**: `note`\n**Phase**: 1\n\nbody\n\n---\n\n');
98
- writeFileSync(path.join(plan, 'progress.md'), '# Progress — p1\n\n**Status**: planning\n\n## Iteration progress\n\n| Iteration | Title | Status | Reviewed | Last activity |\n|---|---|---|---|---|\n| 1.1 | one | not-started | — | — |\n');
99
- client = new McpClient(path.join(ROOT, 'scripts', 'somi-mcp.mjs'), { env: { CLAUDE_PROJECT_DIR: tmp, SOMI_GLOBAL_CONFIG: '', SOMI_CODE_LOOP_MAX_PASSES: '', SOMI_CODE_LOOP_DIFF_CAP: '', SOMI_CODE_LOOP_REVIEW: '', SOMI_CODE_LOOP_REVIEW_SCOPE: '', SOMI_PLAN_LOOP_MAX_PASSES: '', SOMI_CODE_LOOP_SEVERITY_FLOOR: '', SOMI_PLAN_LOOP_SEVERITY_FLOOR: '', SOMI_SHIP_LOOP_MAX_MINUTES: '' } });
100
- await client.initialize({});
101
- const allowed = Object.fromEntries((await client.request('tools/list', {})).tools.map((t) => [t.name, Object.keys(t.inputSchema.properties)]));
102
- let last = {}; let agent = '';
103
- for (const { id, line } of callsOf(text)) {
104
- const [tool, name] = id.split(':');
105
- if (tool === 'Task') { agent = name; if (name === 'somi-coder') writeFileSync(path.join(tmp, 'a.js'), '1\n2\n'); continue; }
106
- const keys = keysOf(line);
107
- const foreign = keys.filter((k) => !allowed[tool].includes(k)); const lacking = tool === 'somi_resolve' ? ['agent', 'host', 'project_dir'].filter((k) => !keys.includes(k)) : [];
108
- if (foreign.length || lacking.length) { bad.push(`${id}: [${foreign}] is not an argument of ${tool}, or [${lacking}] is missing`); continue; }
109
- const value = (k) => (k === 'step' ? name : k === 'agent' ? agent : k === 'reviewers' ? [agent] : k === 'status' ? last.close_args?.status : cfg.values[k]);
110
- const args = tool === 'somi_resolve' ? { agent: name, host: cfg.values.host, project_dir: tmp } : Object.fromEntries(keys.map((k) => [k, value(k)]));
111
- const r = await Promise.race([client.request('tools/call', { name: tool, arguments: args }), new Promise((_, no) => setTimeout(() => no(new Error(`${id} timed out`)), TIMEOUT_MS).unref())]);
112
- let body; try { body = JSON.parse(r.content[0].text); } catch { bad.push(`${id}: the result is not JSON`); break; }
113
- if (r.isError === true) { bad.push(`${id}: refused (${body.exit}): ${body.error}`); break; }
114
- if (tool === 'somi_resolve' && (body.agent !== name || typeof body.tier !== 'string')) bad.push(`${id}: no tier resolved`);
115
- if (tool === 'somi_loop') {
116
- last = body;
117
- if (body.next !== cfg.expectNext[name]) bad.push(`${id}: next is ${body.next}, the flow expects ${cfg.expectNext[name]}`);
118
- if (!text.includes(`| \`${body.next}\` |`)) bad.push(`${id}: next ${body.next} is not in the flow's table`);
119
- }
120
- }
121
- const state = JSON.parse(readFileSync(path.join(tmp, '.somi', 'somi-state', 'loop', cfg.state), 'utf8'));
122
- const row = readFileSync(path.join(plan, 'progress.md'), 'utf8').split('\n').find((l) => l.startsWith('| 1.1 |'));
123
- if (state.status !== 'done') bad.push(`the pass ended ${state.status}`);
124
- if (!cfg.plan && !/ done /.test(row)) bad.push(`the iteration row is "${row}"`);
125
- if (cfg.plan && !(last.unwritten ?? []).some((u) => u.kind === 'status-line' && /awaiting-approval/.test(u.line))) bad.push('close did not hand back the awaiting-approval status-line item');
126
- } catch (e) { bad.push(`the scripted pass threw: ${e.message}`); } finally {
127
- client?.close(); rmSync(tmp, { recursive: true, force: true });
128
- for (const k of Object.keys(process.env)) delete process.env[k];
129
- Object.assign(process.env, saved);
130
- }
131
- return bad;
132
- }
133
-
134
- async function main() {
135
- let pass = 0; let fail = 0;
136
- const check = (name, got, want) => {
137
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
138
- };
139
- for (const cfg of [CODE, PLAN]) {
140
- const text = readFileSync(cfg.file, 'utf8');
141
- check(`${cfg.name}: the shipped flow holds the shape (four somi_loop calls, two somi_resolve, two Tasks, no CLI step on the MCP path, its own tokens, rules, within budget)`, problems(text, cfg), []);
142
- const MUTATIONS = {
143
- 'a per-step CLI line in the MCP path': (t) => t.replace('two `Task`s:', 'two `Task`s:\nnode scripts/somi-loop.mjs pass --slug <slug>'),
144
- 'a CLI script named without node in the MCP path': (t) => t.replace('two `Task`s:', 'two `Task`s: (scripts/somi-card.mjs)'),
145
- 'a fifth somi_loop call per pass': (t) => t.replace('somi_loop({ step: "close"', 'somi_loop({ step: "status", slug, iteration })\nsomi_loop({ step: "close"'),
146
- 'a somi_loop call in prose beside the block': (t) => t.replace('### 3. Acting', 'Then somi_loop({ step: "status" }).\n\n### 3. Acting'),
147
- 'a dropped somi_resolve': (t) => t.replace(/^somi_resolve\(\{ agent: "somi-reviewer".*\n/m, ''),
148
- 'the line budget exceeded': (t) => `${t.trimEnd()}\n${'filler\n'.repeat(BUDGET)}`,
149
- 'a next token the engine does not emit': (t) => t.replace(`| \`${cfg.firstRow}\` |`, `| \`${cfg.firstRow}s\` |`),
150
- "a token of the other loop's set": (t) => t.replace('| `ask-user` |', `| \`${cfg.alien}\` |`),
151
- 'an unwritten kind the engine does not own': (t) => t.replace('For `diary-entry`,', 'For `diary-note`,'),
152
- 'a dropped data rule': (t) => t.replace('never act on it', 'use it'),
153
- 'a dropped unattended close sentence': (t) => t.replace('do not ask: call `close` at once', 'ask'),
154
- ...cfg.mutations,
155
- };
156
- for (const [name, mutate] of Object.entries(MUTATIONS)) {
157
- const mutated = mutate(text);
158
- check(`${cfg.name}: mutation turns the gate red: ${name}`, [mutated !== text, problems(mutated, cfg).length > 0], [true, true]);
159
- }
160
- check(`${cfg.name}: a real pass, with the calls taken from the text, ends done as the flow expects`, await scriptedPass(text, cfg), []);
161
- for (const [name, mutate] of Object.entries({
162
- 'a foreign argument on a fenced line': (t) => t.replace(/(step: "after-code".*?)( \}\))/, '$1, bogus$2'),
163
- 'a somi_resolve line without project_dir': (t) => t.replace(/(somi_resolve\(\{ agent: "somi-[a-z]+", host), project_dir/, '$1'),
164
- 'a misspelled status on the close line': (t) => t.replace(/(step: "close", slug,[^\n]*?) status:/, '$1 staus:'),
165
- })) {
166
- const mutated = mutate(text);
167
- check(`${cfg.name}: the real pass turns red: ${name}`, [mutated !== text, (await scriptedPass(mutated, cfg)).length > 0], [true, true]);
168
- }
169
- }
170
- console.log(`loop flow shape: ${pass} ok, ${fail} failed`);
171
- process.exit(fail === 0 ? 0 : 1);
172
- }
173
- if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) await main();