@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,140 +0,0 @@
1
- // loop-caps.mjs -- cap resolution for the loop engine, lifted out of somi-loop.mjs unchanged apart from its
2
- // inputs: the environment arrives as a parameter and this file never reads process.env, so an in-process
3
- // caller (the MCP tool) resolves against the env it was handed and a test can prove the isolation.
4
- //
5
- // --- mid-loop cap re-resolution --------------------------------------------
6
- // `init` resolves caps once (CLI flag > env var > .somi/config.json > default) and
7
- // freezes them into state -- deliberately, so the diff baseline and pass history stay
8
- // stable across a whole loop. But commands/code-loop.md's Guardrails document a
9
- // remedy for a gate that's wrong for the work at hand: "the user adjusts the env var
10
- // explicitly and re-runs -- the loop does not 'decide' to widen its own bounds." That
11
- // remedy needs a path that re-reads the override on the SAME subcommand (`pass`,
12
- // `check-diff`), without `init --force` (which discards `pass`/`history`).
13
- //
14
- // `pass` and `check-diff` (lib/loop-engine.mjs) call reresolveCap() before their gate check.
15
- // Precedence matches what's documented: CLI flag > env var > .somi/config.json >
16
- // default -- an explicit CLI flag or env var THIS invocation is the only thing that
17
- // can move the cap; absent one, the cap already in force for the loop stands (a
18
- // `.somi/config.json` edit made while a loop is running must NOT silently reopen an
19
- // already-resolved gate). A resolved value that differs from what's stored is
20
- // persisted into `caps` immediately, with an entry appended to a `cap_overrides`
21
- // audit trail (field, from, to, source, after_pass, at) -- the after-the-fact record
22
- // the documented remedy needs, since the env var itself lives only in a shell that
23
- // may since have exited. `cap_overrides` is created lazily, only on the first real
24
- // override, so a loop that never overrides anything keeps exactly today's state
25
- // shape (no golden-fixture regeneration forced by this fix). `baseline_sha`,
26
- // `started`, `pass`, and `history` are never touched here.
27
- //
28
- // Every value that reaches `Number()` on this path is user input (a CLI flag, an env
29
- // var, or a config value) and is validated before use: `Number()` on a malformed
30
- // string (`"1,000"`, `"unlimited"`) yields NaN, which is false against BOTH gate
31
- // comparisons (`cur + 1 > max`, `weighted > cap`) -- silently switching the gate off
32
- // -- and `JSON.stringify` then persists that NaN as `null`, which the next bare call
33
- // falls through past (via `firstDefined`) to re-arm at the default, with no
34
- // `cap_overrides` entry recording the reversion. `validateCap()` rejects rather than
35
- // coerces, so a malformed value dies loudly instead of disabling a gate.
36
-
37
- import { usageError } from './loop-exit.mjs';
38
-
39
- export function configVal(config, keys) {
40
- let cur = config;
41
- for (const k of keys) {
42
- if (cur === undefined || cur === null) return undefined;
43
- cur = cur[k];
44
- }
45
- return cur === null ? undefined : cur;
46
- }
47
-
48
- // Mirrors bash's `${a:-${b:-$c}}` — first arg that is neither unset nor an
49
- // empty string wins (a numeric 0 counts as "set", matching bash treating the
50
- // non-empty string "0" as set).
51
- export function firstDefined(...vals) {
52
- for (const v of vals) {
53
- if (v === undefined || v === null) continue;
54
- if (typeof v === 'string' && v === '') continue;
55
- return v;
56
- }
57
- return undefined;
58
- }
59
-
60
- const CAP_ENV = {
61
- code: { max_passes: 'SOMI_CODE_LOOP_MAX_PASSES', diff_cap_lines: 'SOMI_CODE_LOOP_DIFF_CAP' },
62
- plan: { max_passes: 'SOMI_PLAN_LOOP_MAX_PASSES' },
63
- };
64
- const CAP_FLAG = { max_passes: '--max-passes', diff_cap_lines: '--diff-cap' };
65
- const CAP_CONFIG_SECTION = { code: 'code_loop', plan: 'plan_loop' };
66
- const CAP_DEFAULT = { max_passes: 3, diff_cap_lines: 400 };
67
-
68
- // Rejects a malformed cap value rather than letting `Number()` coerce it to NaN.
69
- // `label` names the source in the error so the error points at what to fix
70
- // (a specific flag, env var, or the generic field name at `init`, where the value
71
- // may have come from any of CLI/env/config).
72
- export function validateCap(raw, label) {
73
- const n = Number(raw);
74
- if (!Number.isInteger(n) || n < 0) {
75
- throw usageError(`${label}: expected a non-negative integer, got "${raw}"`);
76
- }
77
- return n;
78
- }
79
-
80
- // Resolves one cap at `init`, reading the same CAP_ENV / CAP_CONFIG_SECTION /
81
- // CAP_DEFAULT tables reresolveCap() uses, so the two paths cannot silently diverge
82
- // on an env var name, a config key, or a default value.
83
- export function resolveInitCap(env, config, family, field, argVal) {
84
- if (field === 'diff_cap_lines' && family === 'plan') return 0; // plan loops have no diff cap
85
- const envVar = CAP_ENV[family][field];
86
- const fromConfig = configVal(config, [CAP_CONFIG_SECTION[family], field]);
87
- const picked = firstDefined(argVal, env[envVar], fromConfig, CAP_DEFAULT[field]);
88
- return validateCap(picked, field);
89
- }
90
-
91
- // `at` is the timestamp an override entry records, supplied by the caller so this file keeps no clock.
92
- export function reresolveCap(env, state, field, argVal, at) {
93
- const family = state.loop === 'plan' ? 'plan' : 'code';
94
- if (field === 'diff_cap_lines' && family === 'plan') {
95
- return { resolved: 0, override: null }; // plan loops have no diff cap (see `init`)
96
- }
97
- const envVar = CAP_ENV[family][field];
98
- const stored = state.caps[field];
99
- const explicit = firstDefined(argVal, env[envVar]);
100
- const isCli = argVal !== undefined && argVal !== '';
101
- const resolved = explicit === undefined
102
- ? stored
103
- : validateCap(explicit, isCli ? CAP_FLAG[field] : envVar);
104
- let override = null;
105
- if (explicit !== undefined && resolved !== stored) {
106
- override = {
107
- field,
108
- from: stored,
109
- to: resolved,
110
- source: isCli ? 'cli' : 'env',
111
- after_pass: state.pass,
112
- at,
113
- };
114
- }
115
- return { resolved, override };
116
- }
117
-
118
- // Mutates `state.caps[field]` and appends the audit entry. Caller still owns calling
119
- // saveState() -- kept separate so `pass`/`check-diff` persist the override BEFORE
120
- // their gate check can throw, not only on the success path.
121
- export function applyCapOverride(state, override) {
122
- state.caps[override.field] = override.to;
123
- if (!Array.isArray(state.cap_overrides)) state.cap_overrides = [];
124
- state.cap_overrides.push(override);
125
- }
126
-
127
- // Cap arguments that arrive from a tool may only tighten the cap in force: above it is refused with 64, equal is no
128
- // change, below returns the override entry (source `tool`) for the caller to apply. A diff cap of 0 is the gate off,
129
- // so any positive value tightens it and 0 against a live cap is an attempt to raise it. `argVal` was shape-checked
130
- // by the caller; undefined means no argument.
131
- export function tightenCap(state, field, argVal, at, label = field) {
132
- if (argVal === undefined) return null;
133
- const stored = state.caps[field];
134
- const limit = (v) => (field === 'diff_cap_lines' && v === 0 ? Infinity : v);
135
- if (limit(argVal) > limit(stored)) {
136
- throw usageError(`${label}: ${argVal} is above the cap in force (${stored}); arguments only tighten, raise it with the CLI flag or env var`);
137
- }
138
- if (argVal === stored) return null;
139
- return { field, from: stored, to: argVal, source: 'tool', after_pass: state.pass, at };
140
- }
@@ -1,38 +0,0 @@
1
- // loop-diff.mjs -- the code loop's diff measurement: the weighted cumulative diff of the working tree against the
2
- // loop's baseline, untracked files included.
3
-
4
- import { measuredTree, treeRows } from './loop-review.mjs';
5
-
6
- // Weighted cumulative diff vs baseline. Out-of-scope lines count double.
7
- // Measured between the baseline and a snapshot tree of the whole working tree (tracked, staged and untracked
8
- // files; .somi and .claude excluded), the same tree the review scope diffs, so the cap and the reviewer see one
9
- // file set. A brand-new file is in the snapshot though git has never been told about it, and names are read
10
- // NUL-separated, so no file is skipped for how it is spelled. When the tree cannot be measured this throws a
11
- // refusal (exit 64) instead of returning a smaller diff. `iterationFiles` entries and the reported file names are
12
- // relative to `root` (the project directory), not to the repository's top level. `rows` are the per-file rows as git
13
- // reports them ({file, added, deleted, status}), for the escalation.
14
- export function computeDiff(root, baseline, iterationFiles) {
15
- const rows = treeRows(root, baseline, measuredTree(root));
16
- let total = 0;
17
- let weighted = 0;
18
- const outOfScope = [];
19
- for (const { added, deleted, file } of rows) {
20
- const lines = added + deleted;
21
- total += lines;
22
- let inScope = false;
23
- for (const entry of iterationFiles) {
24
- if (!entry) continue;
25
- if (file === entry || (entry.endsWith('/') && file.startsWith(entry))) {
26
- inScope = true;
27
- break;
28
- }
29
- }
30
- if (inScope) {
31
- weighted += lines;
32
- } else {
33
- weighted += 2 * lines;
34
- outOfScope.push(file);
35
- }
36
- }
37
- return { total, weighted, outOfScope, rows };
38
- }
@@ -1,19 +0,0 @@
1
- // loop-dispatch.mjs -- the dispatch record of a loop: for every agent a loop starts, what SoMi resolved for it
2
- // (tier, model, whether the model was enforced, the host, why not). Shared by scripts/somi-loop.mjs.
3
- //
4
- // The entry is computed here from the same resolver somi_resolve uses (read-only, nothing persisted), never
5
- // copied from the orchestrator's arguments, so it cannot claim a tier or model the resolver did not give. It
6
- // records the decision SoMi made; which model the host then actually ran is not visible to a plugin, and the
7
- // `enforced: false` entries are exactly the ones where the host's own choice applied.
8
-
9
- import { resolveDispatch } from './dispatch-resolver.mjs';
10
-
11
- // -> { ok: true, entry } | { ok: false, code, message }
12
- export function dispatchEntry({ root, installRoot, agent, host, pass }) {
13
- const r = resolveDispatch({ agent, host, projectRoot: root, installRoot, persist: false });
14
- if (!r.ok) return r;
15
- const x = r.result;
16
- const entry = { pass, agent: x.agent, host: host || 'claude-code', tier: x.tier, degraded: x.degraded, model: x.model, enforced: x.enforced, ceiling: x.ceiling };
17
- if (x.reason) entry.reason = x.reason;
18
- return { ok: true, entry };
19
- }
@@ -1,227 +0,0 @@
1
- // loop-engine.mjs -- the handlers of the loop engine: the lifecycle (init, resume, pass, finish), the measuring
2
- // ones (check-diff, review-scope) and the recording ones (run-start, record-dispatch, record-pass).
3
- // A handler takes a context ({root, env, stateDir, installRoot}, optional `now` clock) and the parsed arguments
4
- // and returns a result ({out, code, message}, see loop-exit.mjs); it never prints or exits, and it reads the
5
- // environment only from ctx.env (the one inheritance of the process env is the git subprocess in loop-review.mjs's snapshotTree).
6
-
7
- import fs from 'node:fs';
8
- import path from 'node:path';
9
- import { verifyBriefOnly } from './tier-record.mjs';
10
- import { REVIEW_SCOPES, headCommit, ignoredSnapshot, refuseSubmodules, reviewMinFor, reviewScope as scopeOf, snapshotTree } from './loop-review.mjs';
11
- import { computeDiff } from './loop-diff.mjs';
12
- import { dispatchEntry } from './loop-dispatch.mjs';
13
- import { checkRun, startRun } from './run-budget.mjs';
14
- import { loadConfig } from './config-files.mjs';
15
- import { EXIT_DIFF_CAP, EXIT_MAX_PASSES, EXIT_TIME_BUDGET, LoopExit, PROG, ok, refuse, usageError } from './loop-exit.mjs';
16
- import { applyCapOverride, configVal, firstDefined, resolveInitCap, reresolveCap, validateCap } from './loop-caps.mjs';
17
- import { loadState, nowIso, requireState, saveState, stateFile } from './loop-state.mjs';
18
- import { SEVERITIES } from './findings-ledger.mjs';
19
-
20
- // The effective config; an unreadable or invalid file reads as unconfigured, so the defaults apply.
21
- export function readConfig(root, env) {
22
- try {
23
- return loadConfig(root, env).config;
24
- } catch {
25
- return {};
26
- }
27
- }
28
-
29
- // A thrown LoopExit reaches the caller as the result it stands for.
30
- function guarded(body) {
31
- return (ctx, args) => {
32
- try {
33
- return body(ctx, args);
34
- } catch (e) {
35
- if (e instanceof LoopExit) return refuse(e.code, e.message);
36
- throw e;
37
- }
38
- };
39
- }
40
-
41
- const withReviewMin = (state) => (state.review_min ? { review_min: state.review_min } : {});
42
-
43
- export const init = guarded(({ env, root, stateDir, now = nowIso }, args) => {
44
- const { slug, loop, iteration, force } = args;
45
- const sf = stateFile(stateDir, slug, iteration);
46
- if (fs.existsSync(sf) && !force) {
47
- let status;
48
- try {
49
- status = loadState(sf).status;
50
- } catch {
51
- status = undefined;
52
- }
53
- if (status === 'running') {
54
- throw usageError(`loop state already running at ${sf} — use 'resume' to continue it, or 'init --force' to discard`);
55
- }
56
- }
57
-
58
- // A brief-only work item (a plan directory with no phases/) exists only for the sized, human-
59
- // approved small tier of /ship-loop: refuse it without the tier record's approval stamp.
60
- const planDir = path.join(root, '.somi', 'plans', slug);
61
- if (loop === 'code' && fs.existsSync(planDir) && !fs.existsSync(path.join(planDir, 'phases'))) {
62
- const v = verifyBriefOnly(root, slug);
63
- if (!v.ok) throw usageError(`brief-only work item refused: ${v.reason}; use /plan or /ship-loop`);
64
- }
65
-
66
- // Cap resolution: CLI > env > config > default, validated (see loop-caps.mjs).
67
- const config = readConfig(root, env);
68
- const plan = loop === 'plan';
69
- const maxPasses = resolveInitCap(env, config, plan ? 'plan' : 'code', 'max_passes', args.maxPasses);
70
- const sevFloor = firstDefined(
71
- args.severity,
72
- plan ? env.SOMI_PLAN_LOOP_SEVERITY_FLOOR : env.SOMI_CODE_LOOP_SEVERITY_FLOOR,
73
- configVal(config, [plan ? 'plan_loop' : 'code_loop', 'severity_floor']),
74
- 'Major',
75
- );
76
- if (!SEVERITIES.includes(sevFloor)) throw usageError(`severity_floor: ${sevFloor} must be one of ${SEVERITIES.join('|')}`);
77
- if (args.files.includes(',')) throw usageError('--files: a path holds a comma: separate the paths with spaces, not commas');
78
- const diffCap = plan ? 0 : resolveInitCap(env, config, 'code', 'diff_cap_lines', args.diffCap); // plan loops have no diff cap
79
-
80
- if (!plan) refuseSubmodules(root); // a repository the diff gate cannot measure is refused before any coder pass
81
- const baseline = headCommit(root);
82
-
83
- const state = {
84
- slug,
85
- loop,
86
- iteration,
87
- baseline_sha: baseline,
88
- started: now(),
89
- status: 'running',
90
- caps: { max_passes: maxPasses, diff_cap_lines: diffCap, severity_floor: sevFloor },
91
- iteration_files: args.files.split(' ').filter((s) => s.length > 0),
92
- pass: 0,
93
- history: [],
94
- };
95
- if (loop === 'code') state.review_min = reviewMinFor(root, slug) ?? undefined; // undefined: not serialised
96
- if (loop === 'code') state.ignored_guarded = ignoredSnapshot(root); // the ignored files under the policy paths now; the escalation raises any that is new or changed later
97
- fs.mkdirSync(stateDir, { recursive: true }); // only now: a refused init leaves no directory behind
98
- saveState(sf, state);
99
- return ok({ baseline_sha: state.baseline_sha, caps: state.caps, state_file: sf, ...withReviewMin(state) });
100
- });
101
-
102
- export const resume = guarded(({ stateDir }, { slug, iteration }) => {
103
- const sf = stateFile(stateDir, slug, iteration);
104
- requireState(sf);
105
- return ok(loadState(sf));
106
- });
107
-
108
- export const pass = guarded(({ env, stateDir, now = nowIso }, args) => {
109
- const sf = stateFile(stateDir, args.slug, args.iteration);
110
- requireState(sf);
111
- const state = loadState(sf);
112
- const { resolved: max, override } = reresolveCap(env, state, 'max_passes', args.maxPasses, now());
113
- if (override) {
114
- applyCapOverride(state, override);
115
- saveState(sf, state); // persist the raise even if the gate below still fails
116
- }
117
- const cur = state.pass;
118
- if (cur + 1 > max) throw new LoopExit(EXIT_MAX_PASSES, `max-passes-exceeded: pass ${cur + 1} > cap ${max}`);
119
- const run = checkRun(path.dirname(stateDir), args.slug, Date.parse(now()));
120
- if (run?.over) throw new LoopExit(EXIT_TIME_BUDGET, `time-budget-exceeded: ${run.elapsed_minutes} of ${run.max_minutes} minutes used by this run`);
121
- state.pass = cur + 1;
122
- saveState(sf, state);
123
- return ok({ pass: state.pass, max_passes: max, ...withReviewMin(state) });
124
- });
125
-
126
- // The reasons a stopped loop is closed with (`stopped-<reason>`): the code loop's documented stops, plus the time budget `open` reports.
127
- export const STOP_REASONS = Object.freeze(['max-passes-exceeded', 'diff-cap-exceeded', 'scope-expansion', 'circuit-breaker', 'user-stop', 'time-budget']);
128
- export const documentedStatus = (s) => s === 'done' || (typeof s === 'string' && s.startsWith('stopped-') && STOP_REASONS.includes(s.slice(8)));
129
-
130
- // Ends a running loop: the status and the time it ended, and the summary `finish` prints. Shared by `finish` and the `close` step.
131
- // A loop that is already over is refused, so a second finish cannot rewrite how the first ended.
132
- export function endLoop(state, status, at) {
133
- if (state.status !== 'running') throw usageError(`the loop is not running (status ${JSON.stringify(String(state.status).slice(0, 40))}); it cannot be finished again`);
134
- state.status = status;
135
- state.finished = at;
136
- return {
137
- status,
138
- pass: state.pass,
139
- history: state.history.length,
140
- cap_overrides: state.cap_overrides || [],
141
- ...(state.dispatches ? { dispatches: state.dispatches } : {}),
142
- };
143
- }
144
-
145
- export const finish = guarded(({ stateDir, now = nowIso }, args) => {
146
- const sf = stateFile(stateDir, args.slug, args.iteration);
147
- requireState(sf);
148
- if (!args.status) throw usageError('finish requires --status');
149
- const state = loadState(sf);
150
- const summary = endLoop(state, args.status, now());
151
- saveState(sf, state);
152
- return ok(summary);
153
- });
154
-
155
- export const runStart = guarded(({ env, root, stateDir }, args) => {
156
- const raw = firstDefined(args.maxMinutes, env.SOMI_SHIP_LOOP_MAX_MINUTES, configVal(readConfig(root, env), ['ship_loop', 'max_minutes']));
157
- const max = raw === undefined ? null : validateCap(raw, 'max_minutes');
158
- if (max === 0) throw usageError('max_minutes: 0 would disable the budget; leave it unset instead');
159
- return ok(startRun(path.dirname(stateDir), args.slug, max, { force: args.force }));
160
- });
161
-
162
- // Over the cap it is a refusal that still carries its JSON: the CLI prints stdout, then the stderr line.
163
- export const checkDiff = guarded(({ env, root, stateDir, now = nowIso }, args) => {
164
- const sf = stateFile(stateDir, args.slug, args.iteration);
165
- requireState(sf);
166
- const state = loadState(sf);
167
- const { resolved: cap, override } = reresolveCap(env, state, 'diff_cap_lines', args.diffCap, now());
168
- if (override) {
169
- applyCapOverride(state, override);
170
- saveState(sf, state); // persist the raise even if the gate below still fails
171
- }
172
- const { total, weighted, outOfScope } = computeDiff(root, state.baseline_sha, state.iteration_files);
173
- const out = { diff_lines: total, weighted_lines: weighted, cap, out_of_scope: outOfScope };
174
- if (cap > 0 && weighted > cap) return refuse(EXIT_DIFF_CAP, `diff-cap-exceeded: weighted ${weighted} > cap ${cap} (out-of-scope counts double)`, out);
175
- return ok(out);
176
- });
177
-
178
- export const reviewScope = guarded(({ env, root, stateDir }, args) => {
179
- const sf = stateFile(stateDir, args.slug, args.iteration);
180
- requireState(sf);
181
- const state = loadState(sf);
182
- const setting = firstDefined(env.SOMI_CODE_LOOP_REVIEW_SCOPE, configVal(readConfig(root, env), ['code_loop', 'review_scope']), 'delta');
183
- if (!REVIEW_SCOPES.includes(setting)) throw usageError(`review scope must be one of ${REVIEW_SCOPES.join('|')}, got ${JSON.stringify(setting)}`);
184
- return ok({ ...scopeOf(root, state, setting), ...withReviewMin(state) });
185
- });
186
-
187
- export const recordDispatch = guarded(({ root, installRoot, stateDir }, args) => {
188
- const sf = stateFile(stateDir, args.slug, args.iteration);
189
- requireState(sf);
190
- if (!args.agent) throw usageError('record-dispatch requires --agent');
191
- const state = loadState(sf);
192
- const d = dispatchEntry({ root, installRoot, agent: args.agent, host: args.host, pass: state.pass });
193
- if (!d.ok) return refuse(d.code, `${PROG}: ${d.message}`);
194
- (state.dispatches ??= []).push(d.entry);
195
- saveState(sf, state);
196
- return ok(d.entry);
197
- });
198
-
199
- // A pass entry the step reads back: a short verdict without control characters, counts that are numbers (null: unrecorded).
200
- export const entryOk = (h) => typeof h.verdict === 'string' && h.verdict.length <= 60 && !/\p{Cc}/u.test(h.verdict) && [h.blockers, h.majors].every((n) => n == null || (Number.isFinite(n) && n >= 0));
201
- // The history entry of the pass in progress: the verdict and counts as given, the cumulative diff and the tree reviewed
202
- // (the next pass's delta starts there). Shared by `record-pass` and the composite steps, which store it under their cursor.
203
- export function passEntry(root, state, args, at) {
204
- const { total } = computeDiff(root, state.baseline_sha, state.iteration_files);
205
- const entry = {
206
- pass: state.pass,
207
- verdict: args.verdict,
208
- blockers: Number(args.blockers),
209
- majors: Number(args.majors),
210
- diff_lines: total,
211
- tree: snapshotTree(root) ?? undefined,
212
- at,
213
- };
214
- if (!entryOk(entry)) throw usageError('verdict must be at most 60 characters without control characters, and --blockers and --majors non-negative numbers');
215
- return entry;
216
- }
217
-
218
- export const recordPass = guarded(({ root, stateDir, now = nowIso }, args) => {
219
- const sf = stateFile(stateDir, args.slug, args.iteration);
220
- requireState(sf);
221
- if (!args.verdict) throw usageError('record-pass requires --verdict');
222
- const state = loadState(sf);
223
- const entry = passEntry(root, state, args, now());
224
- state.history.push(entry);
225
- saveState(sf, state);
226
- return ok(entry);
227
- });
@@ -1,49 +0,0 @@
1
- // loop-escalate.mjs -- the code loop's report of what its own cumulative diff warrants. Glue between the diff rows, the facts
2
- // adapter (escalation-facts.mjs) and the pure rules (escalation.mjs), so loop-step.mjs stays small. It reports only: nothing
3
- // here changes a review mode, a cap or a stop.
4
- //
5
- // escalate(root, env, rows, baseline, ignoredBefore) -> { ran: true, reasons, size_flag, tests_weakened, hard_surface, notes } or { ran: false }.
6
- // `rows` are the measured diff's rows ({file, added, deleted, status}); the folders the measurement excludes (.claude, and the
7
- // two .somi paths that carry policy) are listed here and added, because a change there is the one an injected coder would make
8
- // to loosen its own limits. Everything the object carries is an id from a closed list; a path or file text never goes in. Any
9
- // failure (a config file that cannot be read, which would drop the user's own sensitive paths; a git call that fails; an id of an
10
- // unexpected shape) is `{ ran: false }`: the response says the escalation did not run, it is never skipped silently.
11
- import { loadConfig } from './config-files.mjs';
12
- import { diffFacts } from './escalation-facts.mjs';
13
- import { escalation } from './escalation.mjs';
14
- import { guardedRows } from './loop-review.mjs';
15
-
16
- const ID = /^[a-z_]{1,32}(:[a-z_]{1,32})?$/;
17
- const MAX_IDS = 24;
18
- const ids = (list) => {
19
- if (!Array.isArray(list) || list.length > MAX_IDS || !list.every((x) => typeof x === 'string' && ID.test(x))) throw new TypeError('not an id list');
20
- return list;
21
- };
22
-
23
- export function escalate(root, env, rows, baseline, ignoredBefore) {
24
- try {
25
- const all = [...rows, ...guardedRows(root, baseline, ignoredBefore)];
26
- const { facts, notes } = diffFacts(all, { config: loadConfig(root, env) }); // its {global, project}, never the merged `.config`
27
- const e = escalation(facts);
28
- return { ran: true, reasons: ids(e.reasons), size_flag: e.size_flag === true, tests_weakened: e.tests_weakened === true, hard_surface: ids(e.hard_surface), notes: ids(notes) };
29
- } catch {
30
- return { ran: false };
31
- }
32
- }
33
-
34
- // What a step response carries: the object only when it has something to say.
35
- export const reported = (e) => (e.ran === false || e.reasons.length > 0 || e.size_flag || e.tests_weakened || e.hard_surface.length > 0 || e.notes.length > 0
36
- ? { escalation: { ran: e.ran, ...(e.ran ? { reasons: e.reasons, size_flag: e.size_flag, tests_weakened: e.tests_weakened, hard_surface: e.hard_surface, ...(e.notes.length ? { notes: e.notes } : {}) } : {}) } }
37
- : {});
38
-
39
- // The pass's diary text from a stored response's escalation; stored state is read as untrusted, so only ids of the closed shape pass.
40
- export function diaryText(e) {
41
- if (e === null || typeof e !== 'object') return '';
42
- if (e.ran === false) return '; escalation did not run';
43
- try {
44
- const parts = [...ids(e.reasons), ...ids(e.hard_surface).map((h) => `hard:${h}`), ...(e.size_flag === true ? ['size_flag'] : []), ...(e.notes === undefined ? [] : ids(e.notes).map((n) => `note:${n}`))];
45
- return parts.length ? `; escalation: ${parts.join(', ')}` : '';
46
- } catch {
47
- return '; escalation unreadable';
48
- }
49
- }
@@ -1,47 +0,0 @@
1
- // loop-exit.mjs -- the exit model of the loop engine, as data. A handler never prints or exits: it returns a
2
- // result ({out, code, message}) or throws a LoopExit, and the caller (the CLI today, a tool later) decides
3
- // how to deliver it. `message` is the exact stderr text, without the trailing newline. It also owns the words a step
4
- // response is built from: the gate exits, and the `next` and unwritten `kind` tokens a caller branches on.
5
-
6
- export const PROG = 'somi-loop';
7
-
8
- // The exits that are an outcome of a gate, not a refusal (each is a normal result of a step); any other nonzero exit is a
9
- // refusal. 70 is an internal error: the step did not complete and nothing of the error is echoed.
10
- export const EXIT_MAX_PASSES = 2;
11
- export const EXIT_DIFF_CAP = 3;
12
- export const EXIT_TIME_BUDGET = 4;
13
- export const EXIT_CIRCUIT_BREAKER = 5;
14
- export const EXIT_INTERNAL = 70;
15
- export const GATE_STOPS = Object.freeze([EXIT_MAX_PASSES, EXIT_DIFF_CAP, EXIT_TIME_BUDGET, EXIT_CIRCUIT_BREAKER]);
16
-
17
- // What a response's `next` may be (null when a step names none) and what an unwritten item's `kind` may be. A record kind is
18
- // something the caller writes into the file the item names; `notice` is only reported, never written. `reason` and a
19
- // response's `stop_reason` are text for a person: a flow branches on `next` and `exit` only. Every `next` a step emits is a
20
- // member of NEXT, never a literal (a test scans the step files).
21
- export const NEXT = Object.freeze({ taskCoder: 'task-coder', taskPlanner: 'task-planner', taskReviewer: 'task-reviewer', taskReviewers: 'task-reviewers', taskPanel: 'task-panel', open: 'open', close: 'close', summarise: 'summarise', askUser: 'ask-user' });
22
- export const NEXTS = Object.freeze(Object.values(NEXT));
23
- export const KIND = Object.freeze({ diaryEntry: 'diary-entry', iterationRow: 'iteration-row', lastActivity: 'last-activity', statusLine: 'status-line', notice: 'notice' });
24
- export const KINDS = Object.freeze(Object.values(KIND));
25
-
26
- // Thrown to unwind out of a handler with an exit code and the stderr line that goes with it.
27
- export class LoopExit extends Error {
28
- constructor(code, message) {
29
- super(message);
30
- this.code = code;
31
- }
32
- }
33
-
34
- // Exit 64: a usage or environment error, prefixed with the program name as the CLI always printed it.
35
- export function usageError(msg) {
36
- return new LoopExit(64, `${PROG}: ${msg}`);
37
- }
38
-
39
- // A handler's success: `out` is the one JSON-serialisable object it prints.
40
- export function ok(out) {
41
- return { out, code: 0, message: '' };
42
- }
43
-
44
- // A handler's refusal: no stdout, a code and a stderr line. Pass `out` when the CLI printed before failing.
45
- export function refuse(code, message, out) {
46
- return out === undefined ? { out: undefined, code, message } : { out, code, message };
47
- }
@@ -1,72 +0,0 @@
1
- // loop-notes-compact.mjs -- the text half of the diary writer: one entry's shape, where it goes, and the 40/15
2
- // compaction rule of templates/DIARY.md.tmpl. Pure string functions, no file access (loop-notes.mjs does the IO
3
- // and the path confinement). Callers pass already-sanitised one-line fields; nothing here reads the environment.
4
-
5
- export const CATEGORIES = ['plan-change', 'blocker', 'unblock', 'discovery', 'decision-change', 'note', 'review-feedback'];
6
- const MOVABLE = new Set(['note', 'discovery', 'unblock', 'blocker', 'review-feedback']);
7
- export const MAX_ENTRIES = 40;
8
- export const KEEP_NEWEST = 15;
9
-
10
- // An entry starts at a line beginning `## `; text before the first one is the file's preamble.
11
- const SPLIT = /^(?=## )/m;
12
- const withNewline = (s) => (s.endsWith('\n') ? s : `${s}\n`);
13
-
14
- // A diary or archive in template shape: a `# ` title first, and no carriage returns (a CRLF file is not ours).
15
- export const archiveShape = (text) => text.startsWith('# ') && !text.includes('\r');
16
- export const diaryShape = (text) => archiveShape(text) && text.split(SPLIT).length > 1;
17
-
18
- export const archiveHead = (slug) => `# Diary archive — ${slug}\n\n> Entries moved out of [\`diary.md\`](./diary.md) by compaction, verbatim: batches oldest first, newest first within a batch.\n\n`;
19
-
20
- export function formatEntry({ stamp, title, category, phase, body }) {
21
- return `## ${stamp} — ${title}\n\n**Category**: \`${category}\`\n**Phase**: ${phase}\n\n${body ? `${body}\n\n` : ''}---\n\n`;
22
- }
23
-
24
- // Newest first: the new entry goes in front of the first existing one. Null when the file is not a diary.
25
- export function insertEntry(text, entry) {
26
- if (!diaryShape(text)) return null;
27
- const at = text.search(/^## /m);
28
- return text.slice(0, at) + entry + text.slice(at);
29
- }
30
-
31
- // Replay guard: the newest entry is, text for text, the one about to be written (stamp, title, category, phase, body).
32
- export const isReplay = (text, entry) => text.split(SPLIT)[1]?.trimEnd() === entry.trimEnd();
33
-
34
- // A title that reads as a running summary is reserved: only compactDiary writes one.
35
- export const isSummaryTitle = (title) => /^\s*compacted\s*:/i.test(title);
36
-
37
- // Category lives in the first lines under the heading; an entry whose category cannot be read is never moved.
38
- const categoryOf = (chunk) => /^\*\*Category\*\*: `?([a-z-]+)`?/m.exec(chunk.split('\n').slice(1, 6).join('\n'))?.[1];
39
- const summaryEntry = (stamp, from, to, count) => formatEntry({
40
- stamp, title: `Compacted: ${from} .. ${to}`, category: 'note', phase: 'work-item-wide',
41
- body: `${count} older entries moved verbatim to [\`diary-archive.md\`](./diary-archive.md); decision-change and plan-change entries stay here.`,
42
- });
43
- const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
44
- // A prior summary is one whose whole chunk is what summaryEntry emits (so a hand-made or forged entry is never
45
- // "ours"), with a count of at most six digits (always a safe integer). Groups: 1 = from, 2 = to, 3 = count.
46
- const RUNNING = new RegExp(`^${escapeRe(summaryEntry('<stamp>', '<from>', '<to>', '<count>').trimEnd())}\\s*$`
47
- .replace('<stamp>', '\\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d').replace('<from>', '(\\d{4}-\\d\\d-\\d\\d)')
48
- .replace('<to>', '(\\d{4}-\\d\\d-\\d\\d)').replace('<count>', '(\\d{1,6})'));
49
- // An undated heading has no place in the summary's span.
50
- const dateOf = (chunk) => /^## (\d{4}-\d{2}-\d{2})/.exec(chunk)?.[1];
51
-
52
- // More than MAX_ENTRIES entries: every movable entry older than the newest KEEP_NEWEST leaves, and one `Compacted:`
53
- // entry takes the place of the newest of them -- or, when an earlier Compacted entry of our own shape exists, replaces
54
- // it with the date span widened and the count summed, so the diary keeps one running summary. An entry that only
55
- // resembles a summary is not ours and is left alone. decision-change, plan-change and Compacted entries never move.
56
- // Null when the diary is within bounds or nothing is movable; else { diary, archived } where `archived` is the moved
57
- // text, verbatim.
58
- export function compactDiary(text, stamp) {
59
- const [head, ...chunks] = text.split(SPLIT);
60
- if (chunks.length <= MAX_ENTRIES) return null;
61
- const moves = chunks.map((c, i) => i >= KEEP_NEWEST && MOVABLE.has(categoryOf(c)) && !/^## [\d-]+ [\d:]+ — Compacted: /.test(c));
62
- const moved = chunks.filter((_, i) => moves[i]);
63
- if (moved.length === 0) return null;
64
- const prior = chunks.findIndex((c) => RUNNING.test(c));
65
- const before = prior < 0 ? null : RUNNING.exec(chunks[prior]);
66
- const dates = moved.map(dateOf).filter(Boolean).concat(before ? [before[1], before[2]] : []).sort();
67
- if (dates.length === 0) dates.push(stamp.slice(0, 10)); // every moved heading undated: the summary's own day
68
- const summary = summaryEntry(stamp, dates[0], dates[dates.length - 1], moved.length + (before ? Number(before[3]) : 0));
69
- const at = before ? prior : moves.indexOf(true);
70
- const kept = chunks.flatMap((c, i) => (i === at ? [summary] : moves[i] ? [] : [withNewline(c)]));
71
- return { diary: head + kept.join(''), archived: moved.map(withNewline).join('') };
72
- }