@skathio/somi 4.1.0 → 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 -226
  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 -278
  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 -301
  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 -128
  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 -371
  334. package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -141
  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,408 +1,271 @@
1
1
  #!/usr/bin/env node
2
- // somi-mcp.mjs — a zero-dependency stdio MCP server bundling scripts/lib/dispatch-resolver.mjs's
3
- // resolveDispatch() as the `somi_resolve` tool, plus a command-procedure text reader as the
4
- // `somi_command` tool, a skill-text reader as the `somi_skill` tool and an agent-instructions
5
- // reader as the `somi_agent` tool, and the read-only `somi_agent_info` lookup. Both Claude Code and
6
- // Copilot CLI launch a plugin's bundled MCP server with its root already expanded
7
- // (${CLAUDE_PLUGIN_ROOT} / ${PLUGIN_ROOT}), so a prompt calling these tools never needs to know
8
- // where SoMi is installed — unlike scripts/somi-dispatch.mjs, which a prompt can only shell out to
9
- // via a path it has to already know. That CLI stays the other consumer of the identical
10
- // resolveDispatch() — this file's test harness and the fallback for a host with a shell but no
11
- // MCP. Neither surface re-derives the composition or validation order. `somi_skill` exists for the
12
- // identical reason `somi_command` does: a skill reference that's a relative link into SoMi's own
13
- // install directory can't be followed from a consuming project, so its text is served over the
14
- // same stdio channel instead.
2
+ // somi-mcp.mjs: a zero-dependency stdio MCP server with six tools. They give advice and keep a small record, and none of them holds up the
3
+ // conversation: a question, a follow-up or a change of mind never needs to go through here.
15
4
  //
16
- // The tool logic lives in scripts/lib/, one module per tool family: loop-step-tool.mjs (`somi_loop`),
17
- // install-text.mjs (`somi_command`, `somi_skill`, `somi_agent`) and agent-info.mjs (`somi_agent_info`).
18
- // This file keeps the JSON-RPC framing, the roots/list round trip and the tool table.
5
+ // MCP servers run outside the OS sandbox on Claude Code, so this path never executes project commands. It only reads git and SoMi's own files,
6
+ // and runs SoMi's own quality gate, which parses them.
19
7
  //
20
- // Hand-rolled, on purpose (zero dependencies — no MCP SDK): newline-delimited JSON-RPC 2.0 over
21
- // stdio, one JSON object per line either direction, matching the MCP stdio transport's own framing
22
- // rule. Nothing but JSON-RPC ever reaches stdout; every diagnostic goes to stderr, so a stray
23
- // future console.log can never corrupt the wire format.
24
- //
25
- // Methods handled: `initialize`, `notifications/initialized`, `tools/list`, `tools/call`, `ping`.
26
- // Anything else is a JSON-RPC method-not-found when it arrived as a request (has an `id`); an
27
- // unrecognized NOTIFICATION (no `id`) is logged to stderr and dropped. Malformed JSON gets a parse
28
- // error with `id: null` — the server keeps running; one bad line must never kill in-flight calls.
8
+ // Framing is newline-delimited JSON-RPC 2.0. Nothing but JSON-RPC reaches stdout; diagnostics go to stderr.
29
9
 
30
10
  import { createInterface } from 'node:readline';
31
- import { spawnSync } from 'node:child_process';
32
11
  import fs from 'node:fs';
33
12
  import path from 'node:path';
34
13
  import { fileURLToPath } from 'node:url';
35
- import { resolveDispatch, validateDispatchArgs } from './lib/dispatch-resolver.mjs';
14
+ import { ConfigFileError, loadConfig } from './lib/config-files.mjs';
15
+ import { advise, shardAdvice } from './lib/advisor.mjs';
16
+ import { repoRoot, stateIsTracked } from './lib/git-tree.mjs';
17
+ import { addToLedger } from './lib/ledger.mjs';
36
18
  import { resolveProjectRoot } from './lib/mcp-project-root.mjs';
37
- import { AGENT_INFO_TOOL, agentInfo } from './lib/agent-info.mjs';
38
- import { INSTALL_TEXT_TOOLS, installText } from './lib/install-text.mjs';
39
- import { LOOP_TOOL, callLoopStep } from './lib/loop-step-tool.mjs';
40
- import { SIGNAL_IDS } from './lib/size-tier.mjs';
41
-
42
- const PROG = 'somi-dispatch'; // shared identity with the CLI: this is the SAME resolver speaking.
19
+ import { ReviewInputError } from './lib/policy.mjs';
20
+ import { closePlan, markMilestoneDone, planStatus, savePlan } from './lib/plan.mjs';
21
+ import { pullRequest } from './lib/pr.mjs';
22
+ import { CHANGE_SCOPES, SCOPES } from './lib/quality/limits.mjs';
23
+ import { describeAll, runQuality } from './lib/quality/run.mjs';
24
+ import { readPrompt } from './lib/prompt.mjs';
25
+ import { recordReviews, reviewPlan } from './lib/reviews.mjs';
26
+ import { ShardError } from './lib/shards.mjs';
27
+ import { SECURITY_SIGNALS } from './lib/signals.mjs';
28
+ import { StateError } from './lib/state.mjs';
29
+ import { detectHost } from './lib/tiers.mjs';
43
30
 
44
- // A small allowlist, not an echo of whatever `protocolVersion` the client sent -- that would be a
45
- // promise this server never checked it can keep. `LATEST_PROTOCOL_VERSION` is the fallback.
46
31
  const SUPPORTED_PROTOCOL_VERSIONS = Object.freeze(['2024-11-05', '2025-06-18']);
47
32
  const LATEST_PROTOCOL_VERSION = '2025-06-18';
48
-
49
- function installRoot() {
50
- return path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
51
- }
33
+ const ROOTS_TIMEOUT_MS = 2000;
52
34
 
53
35
  function serverVersion() {
54
36
  try {
55
- const pkg = JSON.parse(fs.readFileSync(path.join(installRoot(), 'package.json'), 'utf8'));
56
- return typeof pkg.version === 'string' ? pkg.version : 'unknown';
57
- } catch {
58
- return 'unknown';
59
- }
37
+ return JSON.parse(fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8')).version;
38
+ } catch { return 'unknown'; }
60
39
  }
61
40
 
62
- function log(msg) {
63
- process.stderr.write(`somi-mcp: ${msg}\n`);
64
- }
65
-
66
- // --- JSON-RPC framing ----------------------------------------------------------------------
41
+ const write = (obj) => process.stdout.write(`${JSON.stringify(obj)}\n`);
42
+ const respond = (id, result) => write({ jsonrpc: '2.0', id, result });
43
+ const respondError = (id, code, message) => write({ jsonrpc: '2.0', id, error: { code, message } });
67
44
 
68
- let nextOutgoingId = 1;
69
- const pendingOutgoing = new Map(); // id -> {resolve, reject}
45
+ let nextId = 1;
70
46
  let clientCapabilities = {};
47
+ const pending = new Map();
71
48
 
72
- function writeMessage(obj) {
73
- process.stdout.write(`${JSON.stringify(obj)}\n`);
74
- }
75
-
76
- function respond(id, result) {
77
- writeMessage({ jsonrpc: '2.0', id, result });
78
- }
79
-
80
- function respondError(id, code, message) {
81
- writeMessage({ jsonrpc: '2.0', id, error: { code, message } });
82
- }
83
-
84
- // Sends a request FROM this server TO the client (e.g. `roots/list`) and returns a promise for
85
- // its result. Timed out rather than left to hang forever — a client that never declared (or
86
- // never actually implements) `roots` would otherwise stall somi_resolve indefinitely.
87
- function requestFromClient(method, params, timeoutMs = 2000) {
88
- const id = `srv-${nextOutgoingId++}`;
49
+ function requestFromClient(method, params) {
50
+ const id = `srv-${nextId++}`;
89
51
  return new Promise((resolve, reject) => {
90
- const timer = setTimeout(() => {
91
- pendingOutgoing.delete(id);
92
- reject(new Error(`timed out waiting for the client's response to ${method}`));
93
- }, timeoutMs);
94
- pendingOutgoing.set(id, {
95
- resolve: (v) => { clearTimeout(timer); resolve(v); },
96
- reject: (e) => { clearTimeout(timer); reject(e); },
97
- });
98
- writeMessage({ jsonrpc: '2.0', id, method, params });
52
+ const timer = setTimeout(() => { pending.delete(id); reject(new Error(`no answer to ${method}`)); }, ROOTS_TIMEOUT_MS);
53
+ pending.set(id, { resolve: (v) => { clearTimeout(timer); resolve(v); }, reject: (e) => { clearTimeout(timer); reject(e); } });
54
+ write({ jsonrpc: '2.0', id, method, params });
99
55
  });
100
56
  }
101
57
 
102
- // Returns the RAW `uri` strings from the client's roots/list answer, unfiltered and undecoded —
103
- // mcp-project-root.mjs owns deciding what counts as a usable root, so that logic lives in one
104
- // place. Returns undefined when the client never declared `roots` at initialize, so its host-root
105
- // lookup contributes nothing rather than attempting a round trip that was never going to answer.
106
58
  async function listClientRoots() {
107
- if (!clientCapabilities || !clientCapabilities.roots) return undefined;
59
+ if (!clientCapabilities?.roots) return undefined;
108
60
  const result = await requestFromClient('roots/list', {});
109
- const roots = Array.isArray(result?.roots) ? result.roots : [];
110
- return roots.map((r) => (typeof r?.uri === 'string' ? r.uri : null)).filter((u) => u !== null);
61
+ return (Array.isArray(result?.roots) ? result.roots : []).map((r) => r?.uri).filter((u) => typeof u === 'string');
111
62
  }
112
63
 
113
- // --- tool definitions ------------------------------------------------------------------------
114
-
64
+ const PROJECT_DIR = { type: 'string', description: 'Absolute path of the project, when the host does not supply it.' };
115
65
  const TOOLS = [
116
66
  {
117
- name: 'somi_resolve',
118
- description:
119
- "Resolve one agent's dispatch tier and model: its cost.agents override from .somi/config.json, " +
120
- 'else the current session ceiling itself (a hard cap) — the ' +
121
- 'MCP-native equivalent of `node scripts/somi-dispatch.mjs resolve`. Same validation, same ' +
122
- 'four-code failure family (64 usage / 65 unknown agent / 66 no default tier / ' +
123
- '67 project environment failure — including "no project root could be established": no ' +
124
- 'CLAUDE_PROJECT_DIR, no usable MCP roots, and no project_dir given), reported in the tool ' +
125
- 'result text on failure.',
67
+ name: 'somi_route',
68
+ description: 'Ask once when the user wants work done: a change, a bug, a plan, a review, a release or a ticket. Says which workflow and tier fit, and where to do it.',
126
69
  inputSchema: {
127
70
  type: 'object',
71
+ additionalProperties: false,
128
72
  properties: {
129
- agent: { type: 'string', description: 'agent name, e.g. "somi-coder" (matches ^[a-z][a-z0-9-]*$)' },
130
- host: { type: 'string', description: 'e.g. "claude-code" or "copilot"; defaults to "claude-code"' },
131
- ceiling: {
132
- type: 'string',
133
- description:
134
- 'one of low|medium|high. Used for this call and remembered as an explicitly set ' +
135
- 'value, but cost.ceiling in .somi/config.json is read live and outranks it, so it ' +
136
- 'does not last where the config sets one — omit it unless the user actually asked ' +
137
- 'to change the ceiling.',
138
- },
139
- project_dir: {
140
- type: 'string',
141
- description:
142
- 'absolute path to the CONSUMING project (where .somi/ lives). Only needed when ' +
143
- 'CLAUDE_PROJECT_DIR is unset and the client offers no MCP roots. When the host DOES ' +
144
- 'supply a root, this must be that root or a directory inside it — narrows it, never ' +
145
- 'overrides it; an outside value is refused (64), nothing read or written.',
146
- },
73
+ request: { type: 'string', description: 'The work: what the user wants, plus anything from the conversation it depends on, so that it reads on its own.' },
74
+ hint: { type: 'string', description: 'A route name, when the user or an earlier answer named one.' },
75
+ sensitive: { type: 'boolean', description: 'True only when the user has said this work is security-sensitive. Otherwise SoMi decides from the diff once the work is done.' },
76
+ staged: { type: 'boolean', description: 'True only when the user typed /somi-deliver, asking for this work to run as the staged workflow.' },
77
+ ticket: { type: 'object' },
78
+ project_dir: PROJECT_DIR,
147
79
  },
148
- required: ['agent'],
149
80
  },
150
81
  },
151
- AGENT_INFO_TOOL,
152
- ...INSTALL_TEXT_TOOLS,
153
82
  {
154
- name: 'somi_config',
155
- description:
156
- 'Show the cost settings (the user\'s global config with the project\'s .somi/config.json merged over it) or change the project file, by running ' +
157
- '`node scripts/somi-config.mjs`, and return its one JSON line unchanged. Actions: show ' +
158
- '(every agent\'s effective tier and warnings), get, set, unset, init (create the default file ' +
159
- 'when absent). cost.ceiling and cost.agents.<name> take low|medium|high; ' +
160
- 'cost.mapping.<host>.<tier> takes a model id or a comma-separated preference list (unset ' +
161
- 'cost.mapping.<host> removes a host map). Any lowering or remap needs the user; ' +
162
- 'the change is live, since the config is read on every dispatch. Failures report the CLI exit ' +
163
- 'code: 64 usage (bad key, tier or name), 67 the project\'s config or .somi is unusable.',
83
+ name: 'somi_review',
84
+ description: 'With no reviews, reads the diff and names the reviewers it needs. With reviews, records them and says what blocks the change.',
164
85
  inputSchema: {
165
86
  type: 'object',
87
+ additionalProperties: false,
166
88
  properties: {
167
- action: { type: 'string', description: 'show, get, set, unset or init' },
168
- key: { type: 'string', description: 'cost.ceiling, cost.agents.<name>, or cost.mapping.<host>[.<tier>] (get, set, unset)' },
169
- value: { type: 'string', description: 'set: low, medium or high; for cost.mapping.<host>.<tier>, model-id[,model-id...]' },
170
- project_dir: { type: 'string', description: 'absolute path of the project, as for somi_resolve' },
171
- host: { type: 'string', description: 'show only: the host this session runs on (claude-code, copilot), as for somi_resolve; adds a warning when it has no model mapping' },
89
+ reviews: { type: 'array', items: { type: 'object' }, description: 'An array with every reviewer\'s JSON object, unchanged.' },
90
+ tree: { type: 'string', description: 'The tree from the answer that listed the reviewers.' },
91
+ always: { type: 'boolean', description: 'Review even if nothing in the diff calls for it.' },
92
+ security: { type: 'boolean', description: 'Include the security reviewer even if nothing in the diff calls for it.' },
93
+ base: { type: 'string', description: 'What to compare against, when it is not the default branch.' },
94
+ project_dir: PROJECT_DIR,
172
95
  },
173
- required: ['action'],
174
96
  },
175
97
  },
176
98
  {
177
- name: 'somi_tier',
178
- description:
179
- "Size a request: run `node scripts/somi-tier.mjs resolve` (no --record) on the signals you " +
180
- 'extracted and return its one JSON line unchanged (tier, effective, source, floor, security_lens, reasons, ' +
181
- 'basis). The rubric is the skill somi-routing, section Size tiers; this tool states no ' +
182
- 'thresholds. The signal ids in `signals` are exact: use these names and no others. A name that ' +
183
- 'is not one is ignored and listed back as `unrecognized` next to `expected`, and a missing ' +
184
- 'signal is read as its worst case. Failures report the CLI exit code: 64 usage/input, 65 refused (a downward ' +
185
- 'override below the security floor). It writes nothing: the tier record and the approval ' +
186
- 'stamp need the CLI itself with --record and approve. SoMi is installed at ' + installRoot() +
187
- ': run `node <that path>/scripts/somi-tier.mjs ...` from the project directory.',
99
+ name: 'somi_note',
100
+ description: 'Record a lasting decision or limit, so it survives compaction and reaches later workers.',
188
101
  inputSchema: {
189
102
  type: 'object',
190
- properties: {
191
- signals: {
192
- type: 'object',
193
- description: 'One entry per rubric signal id, with exactly these names: { value, evidence }. What each means and how to extract it is in the skill somi-routing, section Size tiers.',
194
- properties: Object.fromEntries(SIGNAL_IDS.map((id) => [id, {
195
- type: 'object',
196
- properties: { value: { description: 'true or false, or a whole number for a count signal; null when it cannot be determined' }, evidence: { type: 'string', description: 'files and lines you opened' } },
197
- required: ['value', 'evidence'],
198
- }])),
199
- required: [...SIGNAL_IDS],
200
- },
201
- override: { type: 'string', description: 'small or full; only after a human reply' },
202
- },
203
- required: ['signals'],
103
+ additionalProperties: false,
104
+ properties: { kind: { type: 'string', enum: ['decision', 'constraint', 'pointer'] }, text: { type: 'string' }, project_dir: PROJECT_DIR },
105
+ required: ['kind', 'text'],
106
+ },
107
+ },
108
+ {
109
+ name: 'somi_plan',
110
+ description: 'The plan file for large work. text saves it, one "Milestone N: what it delivers" line each; done marks milestone N; close ends it; nothing shows progress.',
111
+ inputSchema: {
112
+ type: 'object',
113
+ additionalProperties: false,
114
+ properties: { text: { type: 'string' }, done: { type: 'integer', minimum: 1 }, close: { type: 'boolean' }, project_dir: PROJECT_DIR },
115
+ },
116
+ },
117
+ {
118
+ name: 'somi_quality',
119
+ description: 'Checks code against the quality limits: the branch by default, one commit, or the whole codebase for a cleanup. Use when the user asks about code quality.',
120
+ inputSchema: {
121
+ type: 'object',
122
+ additionalProperties: false,
123
+ properties: { scope: { type: 'string', enum: [...SCOPES], description: 'pr, the default, is the branch; commit is what a commit adds; repo is the whole codebase.' }, project_dir: PROJECT_DIR },
124
+ },
125
+ },
126
+ {
127
+ name: 'somi_pr',
128
+ description: 'The pull request text for this branch. Refuses an unreviewed or blocked change unless unreviewed is true, and then says so at the top.',
129
+ inputSchema: {
130
+ type: 'object',
131
+ additionalProperties: false,
132
+ properties: { unreviewed: { type: 'boolean', description: 'Only when the user has said to go ahead without the review.' }, base: { type: 'string' }, project_dir: PROJECT_DIR },
204
133
  },
205
134
  },
206
- LOOP_TOOL,
207
135
  ];
208
136
 
209
- // --- tool implementations --------------------------------------------------------------------
210
-
211
- function textResult(text, isError = false) {
212
- return isError ? { content: [{ type: 'text', text }], isError: true } : { content: [{ type: 'text', text }] };
137
+ async function context(projectDir, env = process.env) {
138
+ const resolved = await resolveProjectRoot({ projectDirArg: projectDir, listRoots: listClientRoots });
139
+ if (!resolved.ok) throw new StateError(`${resolved.message}. Call again with project_dir set to your working directory.`);
140
+ const root = repoRoot(resolved.root);
141
+ if (!env.SOMI_STATE_DIR && stateIsTracked(root)) throw new StateError('.somi/state is committed to this repository, so SoMi will not trust it. Stop tracking it with `git rm -r --cached .somi/state`.');
142
+ let layers = [];
143
+ let config = {};
144
+ try {
145
+ const loaded = loadConfig(root, env);
146
+ layers = [loaded.global.config, loaded.project.config];
147
+ config = loaded.config;
148
+ } catch (e) { if (!(e instanceof ConfigFileError)) throw e; }
149
+ return { root, env, config, configLayers: layers, host: detectHost(env), now: () => env.SOMI_CLOCK || new Date().toISOString().replace(/\.\d{3}Z$/, 'Z') };
213
150
  }
214
151
 
215
- async function callSomiResolve(args) {
216
- // Validated BEFORE the project-root lookup below (can be a 2s roots/list round trip). Raw args
217
- // pass through unmodified -- validateDispatchArgs distinguishes "not given" (undefined) from
218
- // "given but the wrong shape" (an array, an object, ''); silently coercing a wrong-shaped value
219
- // to '' here, as an earlier version did, is exactly what let a bad host/ceiling default silently.
220
- const validated = validateDispatchArgs({ agent: args?.agent, host: args?.host, ceiling: args?.ceiling });
221
- if (!validated.ok) {
222
- return textResult(`${PROG}: ${validated.message} (exit ${validated.code})`, true);
223
- }
152
+ const textResult = (value, isError = false) => ({ content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value) }], ...(isError ? { isError: true } : {}) });
224
153
 
225
- // project_dir passes through RAW too -- resolveProjectRoot's own validateDir() turns "not a
226
- // string" into a clean 64, rather than this function quietly treating it as "not given".
227
- const rootOutcome = await resolveProjectRoot({
228
- projectDirArg: args?.project_dir,
229
- listRoots: () => listClientRoots(),
230
- });
231
- if (!rootOutcome.ok) {
232
- return textResult(`${PROG}: ${rootOutcome.message} (exit ${rootOutcome.code})`, true);
233
- }
234
-
235
- // agent/host/ceiling are already validated above; resolveDispatch re-runs the same cheap check.
236
- const outcome = resolveDispatch({
237
- agent: args.agent,
238
- host: args.host,
239
- ceiling: args.ceiling,
240
- projectRoot: rootOutcome.root,
241
- installRoot: installRoot(),
242
- });
154
+ // Some hosts send what a model made up without checking it against the schema, and a field nobody reads would pass for a clean answer.
155
+ function unknownFields(name, a) {
156
+ const known = Object.keys(TOOLS.find((t) => t.name === name).inputSchema.properties);
157
+ const unknown = Object.keys(a).filter((k) => !known.includes(k));
158
+ return unknown.length > 0 ? textResult(`${name} has no field ${unknown.join(', ')}. It takes ${known.join(', ')}. Call it again with those.`, true) : null;
159
+ }
243
160
 
244
- if (!outcome.ok) {
245
- return textResult(`${PROG}: ${outcome.message} (exit ${outcome.code})`, true);
246
- }
247
- return textResult(JSON.stringify(outcome.result));
161
+ // A model can call a tool before it has loaded the tool's fields. The user's own words were kept as they arrived, so they stand in.
162
+ function userWordsStandIn(ctx, name, a) {
163
+ if (name !== 'somi_route' || typeof a.request === 'string' || typeof a.hint === 'string') return null;
164
+ const said = readPrompt(ctx.root, ctx.env);
165
+ if (!said.trim()) return textResult('somi_route needs request set to the work. Call it again now, with request set to what the user asked for.', true);
166
+ a.request = said;
167
+ return null;
248
168
  }
249
169
 
250
- // Read-only agent lookup; the logic lives in lib/agent-info.mjs, this only supplies the project root.
251
- async function callSomiAgentInfo(args) {
252
- const outcome = await agentInfo(args, {
253
- resolveRoot: () => resolveProjectRoot({ projectDirArg: args?.project_dir, listRoots: () => listClientRoots() }),
254
- installRoot: installRoot(),
255
- });
256
- return outcome.ok ? textResult(JSON.stringify(outcome.result)) : textResult(`somi-agent-info: ${outcome.message} (exit ${outcome.code})`, true);
170
+ function planTool(ctx, a) {
171
+ if (a.close === true) return textResult(closePlan(ctx.root, ctx.env));
172
+ if (Number.isInteger(a.done)) return textResult(markMilestoneDone(ctx.root, a.done));
173
+ if (typeof a.text === 'string') return textResult({ saved: savePlan(ctx.root, a.text), ...planStatus(ctx.root) });
174
+ return textResult(planStatus(ctx.root) ?? { plan: null, advice: 'No plan is open.' });
257
175
  }
258
176
 
259
- // Install-root text tools; the logic lives in lib/install-text.mjs, this only supplies the install root.
260
- function callInstallText(kind, args) {
261
- const outcome = installText(kind, args, { installRoot: installRoot() });
262
- return outcome.ok ? textResult(outcome.text) : textResult(`somi-${kind}: ${outcome.message} (exit ${outcome.code})`, true);
177
+ function prTool(ctx, a) {
178
+ const result = pullRequest(ctx, { base: a.base, unreviewed: a.unreviewed === true });
179
+ return textResult(result.ok ? { ...result, ...shardAdvice(ctx, 'pr.open') } : result, !result.ok);
263
180
  }
264
181
 
265
- // Loop steps; the logic lives in lib/loop-step-tool.mjs, this only supplies the root lookup, the env and the install root.
266
- async function callSomiLoop(args) {
267
- const out = await callLoopStep(args, { resolveRoot: (projectDirArg) => resolveProjectRoot({ projectDirArg, listRoots: () => listClientRoots() }), env: process.env, installRoot: installRoot() });
268
- return textResult(out.text, out.isError);
182
+ const QUALITY_ADVICE = 'Tell the user what failed, worst first, in a few lines. Fix it only if they ask, or if it is code you changed in this conversation: refactor until it passes with the tests still green, and never add a somi-gate-allow exemption to get past it. To change a limit, the user sets it under quality in their own config, which somi_route with hint config explains.';
183
+
184
+ function qualityTool(ctx, a) {
185
+ const scope = a.scope ?? 'pr';
186
+ if (!SCOPES.includes(scope)) return textResult(`scope is one of ${SCOPES.join(', ')}.`, true);
187
+ const r = runQuality(ctx.root, { scope, env: ctx.env });
188
+ if (r.error) return textResult(r.error, true);
189
+ const worst = CHANGE_SCOPES.includes(scope) ? {} : { most_complex: r.summary.most_complex.slice(0, 5), most_findings: r.summary.most_findings.slice(0, 5) };
190
+ const ignored = r.ignored_config ? { ignored_config: r.ignored_config } : {};
191
+ return textResult({ ok: r.ok, scope, failures: describeAll(r.violations, scope), scored: r.scored, unanalyzed: r.unanalyzed.length, ...worst, ...ignored, advice: r.ok ? 'Everything is within the limits. Say so in one line.' : QUALITY_ADVICE });
269
192
  }
270
193
 
271
- // Runs the sizing CLI itself, so the result and the exit codes are the CLI's, byte for byte.
272
- function callSomiTier(args) {
273
- if (args.signals === null || typeof args.signals !== 'object' || Array.isArray(args.signals)) {
274
- return textResult('somi-tier: signals must be an object (exit 64)', true);
275
- }
276
- const argv = [path.join(installRoot(), 'scripts', 'somi-tier.mjs'), 'resolve', '--signals', '-'];
277
- if (args.override !== undefined) argv.push('--override', String(args.override));
278
- const r = spawnSync(process.execPath, argv, { input: JSON.stringify(args.signals), encoding: 'utf8', timeout: 10000 });
279
- if (r.status === 0) return textResult(r.stdout.trimEnd());
280
- return textResult(`${(r.stderr || 'somi-tier: failed').trim()} (exit ${r.status ?? 'none'})`, true);
194
+ function reviewAdvice(plan) {
195
+ if (plan.covered) return 'An earlier review still covers this change, and nothing since calls for another. Do not run the reviewers again. Carry on.';
196
+ if (plan.needed) return 'Start each listed reviewer as a fresh agent on its model, in the foreground, with its brief unchanged and nothing added. Start them together if the host allows it. Then call somi_review with reviews set to an array of every reviewer\'s JSON unchanged, and tree set to the tree above.';
197
+ return 'No review is needed for this change. Carry on.';
281
198
  }
282
199
 
283
- // Runs the config CLI itself (never a shell), so output and exit codes are the CLI's, byte for byte.
284
- async function callSomiConfig(args) {
285
- const text = (v) => v === undefined || typeof v === 'string';
286
- if (typeof args.action !== 'string' || !['show', 'get', 'set', 'unset', 'init'].includes(args.action)) {
287
- return textResult('somi-config: action must be one of show, get, set, unset, init (exit 64)', true);
288
- }
289
- if (args.host !== undefined && (args.action !== 'show' || typeof args.host !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(args.host))) {
290
- return textResult('somi-config: host applies to show only and must be a lowercase host name (exit 64)', true);
291
- }
292
- if (!text(args.key) || !text(args.value) || [args.key, args.value].some((v) => v !== undefined && (v === '' || v.startsWith('-') || /[\u0000-\u001f\u007f]/.test(v)))) {
293
- return textResult('somi-config: key and value must be non-empty strings without control characters that do not start with a dash (exit 64)', true);
294
- }
295
- const rootOutcome = await resolveProjectRoot({ projectDirArg: args.project_dir, listRoots: () => listClientRoots() });
296
- // Writes need a root the HOST supplied: a model-supplied project_dir alone could point a write anywhere.
297
- const writes = args.action !== 'show' && args.action !== 'get';
298
- if (!rootOutcome.ok && (rootOutcome.hosted !== false || !writes)) return textResult(`somi-config: ${rootOutcome.message} (exit ${rootOutcome.code})`, true);
299
- if (writes && rootOutcome.hosted !== true) {
300
- return textResult('somi-config: no host project root; run the CLI yourself (node scripts/somi-config.mjs) to change the config (exit 67)', true);
301
- }
302
- const argv = [path.join(installRoot(), 'scripts', 'somi-config.mjs'), args.action];
303
- if (args.key !== undefined) argv.push(args.key);
304
- if (args.value !== undefined) argv.push(args.value);
305
- if (args.host !== undefined) argv.push('--host', args.host);
306
- // Lowering a tier or remapping a model needs the user. Where Claude Code runs the SoMi plugin's hooks
307
- // (CLAUDE_PLUGIN_ROOT set) the cost-lowering PreToolUse hook asks; elsewhere nothing can ask, so the CLI
308
- // refuses. Copilot CLI also sets CLAUDE_PLUGIN_ROOT, but names this tool `somi-somi_config`, which the
309
- // hook's matcher does not catch (verified live on 1.0.103), so COPILOT_PLUGIN_ROOT means "refuse".
310
- // A heuristic for "a hook can ask", failing closed on any host it does not recognise.
311
- const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT;
312
- const hookCanAsk = pluginRoot && !pluginRoot.includes('${') && !process.env.COPILOT_PLUGIN_ROOT;
313
- if ((args.action === 'set' || args.action === 'unset') && !hookCanAsk) argv.push('--refuse-lowering');
314
- argv.push('--project-dir', fs.realpathSync(rootOutcome.root));
315
- const r = spawnSync(process.execPath, argv, { encoding: 'utf8', timeout: 10000 });
316
- if (r.status === 0) return textResult(r.stdout.trimEnd());
317
- return textResult(`${(r.stderr || 'somi-config: failed').trim()} (exit ${r.status ?? 'none'})`, true);
200
+ function reviewTool(ctx, a) {
201
+ const options = { base: a.base, always: a.always === true, security: a.security === true };
202
+ // A model may send the array as text. The content is what matters, and it is validated either way.
203
+ if (typeof a.reviews === 'string') { try { a.reviews = JSON.parse(a.reviews); } catch { return textResult('reviews is not valid JSON. Send an array with every reviewer\'s JSON object.', true); } }
204
+ if (a.reviews) return textResult({ ...recordReviews(ctx, { ...options, reviews: a.reviews, tree: a.tree }), ...shardAdvice(ctx, 'review.done') });
205
+ const plan = reviewPlan(ctx, options);
206
+ const security = plan.signals.some((s) => SECURITY_SIGNALS.includes(s)) ? { security: 'Security signals fired on this diff, so the security reviewer runs on the high tier, and any fix stays in this conversation, not on a cheaper worker.' } : {};
207
+ return textResult({ ...plan, ...security, advice: reviewAdvice(plan) });
318
208
  }
319
209
 
320
- // Returns null for an unrecognized tool name — the caller turns that into a JSON-RPC error, since
321
- // an unknown TOOL is the protocol failing to find it at all, distinct from a known tool that ran
322
- // and failed (which reports isError:true in an otherwise-successful JSON-RPC response).
210
+ const TOOL_HANDLERS = {
211
+ somi_route: (ctx, a) => textResult(advise(ctx, { request: typeof a.request === 'string' ? a.request : undefined, hint: a.hint, ticket: a.ticket, sensitive: a.sensitive, staged: a.staged })),
212
+ somi_note: (ctx, a) => textResult(addToLedger(ctx.root, { kind: a.kind, text: a.text }, ctx.env)),
213
+ somi_plan: planTool,
214
+ somi_pr: prTool,
215
+ somi_quality: qualityTool,
216
+ somi_review: reviewTool,
217
+ };
218
+
323
219
  async function callTool(name, args) {
324
- switch (name) {
325
- case 'somi_resolve': return await callSomiResolve(args || {});
326
- case 'somi_agent_info': return await callSomiAgentInfo(args || {});
327
- case 'somi_command': return callInstallText('command', args || {});
328
- case 'somi_skill': return callInstallText('skill', args || {});
329
- case 'somi_agent': return callInstallText('agent', args || {});
330
- case 'somi_tier': return callSomiTier(args || {});
331
- case 'somi_config': return await callSomiConfig(args || {});
332
- case 'somi_loop': return await callSomiLoop(args || {});
333
- default: return null;
220
+ const a = args !== null && typeof args === 'object' ? args : {};
221
+ try {
222
+ const refused = unknownFields(name, a);
223
+ if (refused) return refused;
224
+ const ctx = await context(typeof a.project_dir === 'string' ? a.project_dir : undefined);
225
+ const missing = userWordsStandIn(ctx, name, a);
226
+ if (missing) return missing;
227
+ return (TOOL_HANDLERS[name] ?? reviewTool)(ctx, a);
228
+ } catch (e) {
229
+ const expected = e instanceof ReviewInputError || e instanceof StateError || e instanceof ShardError;
230
+ if (!expected) process.stderr.write(`somi-mcp: ${e.stack ?? e}\n`);
231
+ return textResult(expected ? e.message : `${name} failed; see the server log`, true);
334
232
  }
335
233
  }
336
234
 
337
- // --- JSON-RPC method dispatch -----------------------------------------------------------------
338
-
339
235
  async function handleRequest(id, method, params) {
340
236
  switch (method) {
341
- case 'initialize': {
237
+ case 'initialize':
342
238
  clientCapabilities = params?.capabilities && typeof params.capabilities === 'object' ? params.capabilities : {};
343
- // A version this server actually supports, never an echo of the client's request.
344
- const requested = params?.protocolVersion;
345
- const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;
346
239
  respond(id, {
347
- protocolVersion,
240
+ protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(params?.protocolVersion) ? params.protocolVersion : LATEST_PROTOCOL_VERSION,
348
241
  capabilities: { tools: {} },
349
242
  serverInfo: { name: 'somi', version: serverVersion() },
350
243
  });
351
244
  return;
352
- }
353
- case 'ping':
354
- respond(id, {});
355
- return;
356
- case 'tools/list':
357
- respond(id, { tools: TOOLS });
358
- return;
359
- case 'tools/call': {
360
- const toolName = params?.name;
361
- const result = await callTool(toolName, params?.arguments);
362
- if (result === null) {
363
- respondError(id, -32602, `Unknown tool: ${toolName}`);
364
- return;
365
- }
366
- respond(id, result);
245
+ case 'ping': respond(id, {}); return;
246
+ case 'tools/list': respond(id, { tools: TOOLS }); return;
247
+ case 'tools/call':
248
+ if (!TOOLS.some((t) => t.name === params?.name)) { respondError(id, -32602, `Unknown tool: ${params?.name}`); return; }
249
+ respond(id, await callTool(params.name, params.arguments));
367
250
  return;
368
- }
369
- default:
370
- respondError(id, -32601, `Method not found: ${method}`);
251
+ default: respondError(id, -32601, `Method not found: ${method}`);
371
252
  }
372
253
  }
373
254
 
374
- function handleNotification(method) {
375
- if (method === 'notifications/initialized') return; // nothing to do; acknowledged implicitly
376
- log(`ignoring unrecognized notification: ${method}`);
377
- }
378
-
379
255
  function handleMessage(msg) {
380
- if (msg === null || typeof msg !== 'object' || Array.isArray(msg)) {
381
- respondError(null, -32600, 'Invalid Request');
382
- return;
383
- }
384
- // A response TO one of our own outgoing requests (e.g. roots/list) carries no `method` — route
385
- // it to the pending promise instead of treating it as an inbound request.
256
+ if (msg === null || typeof msg !== 'object' || Array.isArray(msg)) { respondError(null, -32600, 'Invalid Request'); return; }
386
257
  if (msg.method === undefined) {
387
- if (msg.result !== undefined || msg.error !== undefined) {
388
- const pending = pendingOutgoing.get(msg.id);
389
- if (pending) {
390
- pendingOutgoing.delete(msg.id);
391
- if (msg.error) pending.reject(new Error(msg.error.message));
392
- else pending.resolve(msg.result);
393
- }
394
- return;
258
+ const waiting = pending.get(msg.id);
259
+ if (waiting) {
260
+ pending.delete(msg.id);
261
+ if (msg.error) waiting.reject(new Error(msg.error.message)); else waiting.resolve(msg.result);
395
262
  }
396
- respondError(msg.id ?? null, -32600, 'Invalid Request');
397
- return;
398
- }
399
- if (msg.id === undefined) {
400
- handleNotification(msg.method);
401
263
  return;
402
264
  }
265
+ if (msg.id === undefined) return;
403
266
  handleRequest(msg.id, msg.method, msg.params).catch((e) => {
404
- log(`error handling ${msg.method}: ${e.stack || e}`);
405
- respondError(msg.id, -32603, `Internal error: ${e.message}`);
267
+ process.stderr.write(`somi-mcp: ${e.stack ?? e}\n`);
268
+ respondError(msg.id, -32603, 'Internal error');
406
269
  });
407
270
  }
408
271
 
@@ -410,12 +273,7 @@ const rl = createInterface({ input: process.stdin, terminal: false });
410
273
  rl.on('line', (line) => {
411
274
  if (!line.trim()) return;
412
275
  let msg;
413
- try {
414
- msg = JSON.parse(line);
415
- } catch (e) {
416
- respondError(null, -32700, `Parse error: ${e.message}`);
417
- return;
418
- }
276
+ try { msg = JSON.parse(line); } catch { respondError(null, -32700, 'Parse error'); return; }
419
277
  handleMessage(msg);
420
278
  });
421
279
  rl.on('close', () => process.exit(0));