@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
@@ -54,7 +54,7 @@ export class HookExit extends Error {
54
54
  // The standard wrapper every hook should use at its top level,
55
55
  // so denyPretool()'s early-exit contract works without each hook file
56
56
  // re-declaring the same try/catch boilerplate (the somi-loop.mjs/
57
- // somi-findings.mjs/somi-check.mjs precedent, centralized here since EVERY
57
+ // same precedent as the CLI, centralized here since EVERY
58
58
  // hook that calls denyPretool needs exactly this).
59
59
  export function runHook(main) {
60
60
  try {
@@ -79,19 +79,23 @@ export function runHook(main) {
79
79
  // here as the ONE copy every hook imports, rather than re-duplicating the
80
80
  // `.includes('${')` check per file. (Note: scripts/*.mjs — a separate module
81
81
  // graph — still carry their own copy; unifying those is a follow-up.)
82
+ // A host can start in a subfolder of a repository. State and the audit log belong to the repository, so walk up to it.
82
83
  export function projectRoot() {
83
- let base = process.env.CLAUDE_PROJECT_DIR || process.cwd();
84
+ let base = process.env.CLAUDE_PROJECT_DIR || process.env.COPILOT_PROJECT_DIR || process.cwd();
84
85
  if (base.includes('${')) base = process.cwd();
85
- return base;
86
+ for (let d = path.resolve(base); ; d = path.dirname(d)) {
87
+ if (fs.existsSync(path.join(d, '.git'))) return d;
88
+ if (path.dirname(d) === d) return base;
89
+ }
86
90
  }
87
91
 
88
92
  // plugin_root() — the directory containing SoMi's OWN shipped content (rules/, skills/, etc.),
89
93
  // as distinct from projectRoot() above (the CONSUMING project's root). A hook needs this to read
90
- // rules/CLAUDE.md's digest regardless of whether SoMi is running as an installed plugin, a
94
+ // rules/digest.md's digest regardless of whether SoMi is running as an installed plugin, a
91
95
  // vendored copy, or this repo's own dev/test checkout.
92
96
  //
93
97
  // Resolution order, EACH candidate existence-validated, not merely presence-checked — accepted
94
- // only if `<candidate>/rules/CLAUDE.md` is actually readable, else the search continues to the
98
+ // only if `<candidate>/rules/digest.md` is actually readable, else the search continues to the
95
99
  // next candidate:
96
100
  // (a) CLAUDE_PLUGIN_ROOT — Claude Code's documented, confirmed-exported plugin-install path.
97
101
  // (b) SOMI_VENDOR_ROOT — a vendored-install convention, set via `.claude/settings.json`'s `env`
@@ -99,7 +103,7 @@ export function projectRoot() {
99
103
  // (`${CLAUDE_PROJECT_DIR}/.claude/plugins/somi`) that does not exist here — a
100
104
  // presence-only chain would accept this branch, find nothing inside it, and never reach
101
105
  // (c), silently delivering an empty digest in this repo's own dogfooding sessions while
102
- // appearing to work everywhere validate.sh's checks pass. Existence-validation is exactly
106
+ // appearing to work everywhere the test suite passes. Existence-validation is exactly
103
107
  // what prevents that.
104
108
  // (c) import.meta.url, walked up two levels — this file lives at
105
109
  // `<plugin-root>/hooks/lib/common.mjs`, the same relative-import pattern every hook port
@@ -125,7 +129,7 @@ export function pluginRoot() {
125
129
 
126
130
  for (const candidate of candidates) {
127
131
  try {
128
- if (fs.statSync(path.join(candidate, 'rules', 'CLAUDE.md')).isFile()) return candidate;
132
+ if (fs.statSync(path.join(candidate, 'rules', 'digest.md')).isFile()) return candidate;
129
133
  } catch {
130
134
  // ENOENT, EACCES, or a non-file at that path — not a usable candidate; try the next one.
131
135
  }
@@ -266,27 +270,35 @@ export function config(fieldPath) {
266
270
  return typeof cur === 'string' ? cur : JSON.stringify(cur);
267
271
  }
268
272
 
269
- // Append a structured line to the audit log. Frozen contract:
270
- // "timestamp\tkind\ttool\tdetail\n", byte-exact — any deviation here is a
271
- // regression, not a style choice.
272
273
  // Creates `dir` (and missing parents) without fs.mkdirSync's recursive mode, which spins forever on some
273
274
  // paths (for example under /proc): find the nearest existing ancestor within a bounded walk, then make each
274
275
  // missing level one step at a time, so an impossible path fails fast with the OS error instead of hanging.
275
- function ensureDir(dir) {
276
+ // True when `d` is a directory, false when nothing is there. Anything else there throws, since nothing can be made below it.
277
+ function isDirectory(d) {
278
+ try {
279
+ if (fs.statSync(d).isDirectory()) return true;
280
+ throw Object.assign(new Error(`${d} is not a directory`), { code: 'ENOTDIR' });
281
+ } catch (e) {
282
+ if (e.code !== 'ENOENT') throw e;
283
+ return false;
284
+ }
285
+ }
286
+
287
+ // The levels below the nearest existing ancestor, outermost first, within a bounded walk.
288
+ function missingLevels(dir) {
276
289
  const missing = [];
277
290
  let d = dir;
278
- for (let i = 0; i < 64; i++) {
279
- try {
280
- if (fs.statSync(d).isDirectory()) break;
281
- throw Object.assign(new Error(`${d} is not a directory`), { code: 'ENOTDIR' });
282
- } catch (e) {
283
- if (e.code !== 'ENOENT') throw e;
284
- }
291
+ for (let i = 0; i < 64 && !isDirectory(d); i++) {
285
292
  missing.unshift(d);
286
293
  const parent = path.dirname(d);
287
294
  if (parent === d) break;
288
295
  d = parent;
289
296
  }
297
+ return missing;
298
+ }
299
+
300
+ function ensureDir(dir) {
301
+ const missing = missingLevels(dir);
290
302
  for (const m of missing) {
291
303
  try {
292
304
  fs.mkdirSync(m);
@@ -296,6 +308,9 @@ function ensureDir(dir) {
296
308
  }
297
309
  }
298
310
 
311
+ // Append a structured line to the audit log. Frozen contract:
312
+ // "timestamp\tkind\ttool\tdetail\n", byte-exact — any deviation here is a
313
+ // regression, not a style choice.
299
314
  export function audit(payload, kind, detail) {
300
315
  const tool = field(payload, '.tool_name');
301
316
  const log = auditLogPath();
@@ -304,6 +319,12 @@ export function audit(payload, kind, detail) {
304
319
  fs.appendFileSync(log, `${timestamp}\t${kind}\t${tool || 'unknown'}\t${detail}\n`);
305
320
  }
306
321
 
322
+ // Copilot CLI reads these fields at the top level and Claude Code under hookSpecificOutput. Each ignores the other's, so one output
323
+ // serves both and no hook has to guess its host.
324
+ function preToolOutput(decision, reason) {
325
+ return { permissionDecision: decision, permissionDecisionReason: reason, hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: decision, permissionDecisionReason: reason } };
326
+ }
327
+
307
328
  // Deny a PreToolUse tool call. Use this for block-* hooks. Emits the modern
308
329
  // hookSpecificOutput.permissionDecision schema, writes the DENY audit line,
309
330
  // then throws HookExit(0) — yes, exit 0: from the harness's point of view a
@@ -312,28 +333,18 @@ export function audit(payload, kind, detail) {
312
333
  // with runHook() at the hook's top level so the throw is caught correctly
313
334
  // and doesn't propagate as an uncaught exception.
314
335
  export function denyPretool(payload, reason) {
315
- console.log(JSON.stringify({
316
- hookSpecificOutput: {
317
- hookEventName: 'PreToolUse',
318
- permissionDecision: 'deny',
319
- permissionDecisionReason: reason,
320
- },
321
- }));
336
+ console.log(JSON.stringify(preToolOutput('deny', reason)));
337
+ // Exit 2 denies on Claude Code and Copilot CLI alike, whatever each makes of the JSON body. Claude Code reads the reason from stderr.
338
+ console.error(reason);
322
339
  audit(payload, 'DENY', reason);
323
- throw new HookExit(0);
340
+ throw new HookExit(2);
324
341
  }
325
342
 
326
343
  // Ask the user about a PreToolUse tool call instead of deciding it: the harness shows `reason` and
327
344
  // lets the user allow or deny. Same shape and flow as denyPretool, with permissionDecision 'ask' and an
328
345
  // ASK audit line (a failed audit write never changes the answer). Throws HookExit(0).
329
346
  export function askPretool(payload, reason) {
330
- console.log(JSON.stringify({
331
- hookSpecificOutput: {
332
- hookEventName: 'PreToolUse',
333
- permissionDecision: 'ask',
334
- permissionDecisionReason: reason,
335
- },
336
- }));
347
+ console.log(JSON.stringify(preToolOutput('ask', reason)));
337
348
  try { audit(payload, 'ASK', reason); } catch { /* the question has been asked; auditing is best effort */ }
338
349
  throw new HookExit(0);
339
350
  }
@@ -355,7 +366,7 @@ export function contextOutput(event, context) {
355
366
  //
356
367
  // somi::matches_any / somi::matches_any_nocase equivalents. Thin wrappers:
357
368
  // hooks own their actual pattern lists (as RegExp literals — see
358
- // scripts/somi-check.mjs's SECRET_PATTERNS for the established idiom); this
369
+ // block-secret-writes.mjs's SECRET_PATTERNS for the established idiom); this
359
370
  // lib only owns the "does this string match any of these patterns" shape —
360
371
  // it is deliberately not a pattern-list registry or a translation layer.
361
372
  //
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse on subagent starts: a SoMi agent runs on its tier's model, because a tier that depends on an agent remembering to pass it gets
3
+ // skipped. The tier is in the agent's name, so this needs no state, and it leaves every other agent alone. It rewrites and never denies,
4
+ // because a denial makes some hosts do the work inline. A tier with no model in this environment's config changes nothing. On Claude Code a SoMi
5
+ // agent also stays in the foreground: one in the background cannot ask for a permission, so a reviewer's diff command is denied and it reviews blind.
6
+
7
+ import { loadConfig } from '../../scripts/lib/config-files.mjs';
8
+ import { detectHost, resolveSpawn } from '../../scripts/lib/tiers.mjs';
9
+ import { tierForReviewer, tierForWorker } from '../../scripts/lib/workflows.mjs';
10
+ import { projectRoot, readPayload, runHook } from '../lib/common.mjs';
11
+
12
+ runHook(() => {
13
+ const payload = readPayload();
14
+ let args = payload.tool_input ?? payload.toolArgs ?? {};
15
+ if (typeof args === 'string') { try { args = JSON.parse(args); } catch { return; } }
16
+ const agent = args.subagent_type ?? args.agent_type;
17
+ const reviewerTier = tierForReviewer(agent);
18
+ const wanted = reviewerTier ?? tierForWorker(agent);
19
+ if (!wanted) return;
20
+ const root = projectRoot();
21
+ if (root === null) return;
22
+ let loaded;
23
+ try { loaded = loadConfig(root); } catch { return; }
24
+ // Who reviews is review policy, so a committed project config cannot lower it. Only the user's own config can.
25
+ const host = detectHost();
26
+ const { model } = resolveSpawn(reviewerTier ? loaded.global.config ?? {} : loaded.config, host, wanted);
27
+ const background = host === 'claude' && args.run_in_background !== false;
28
+ if ((!model || args.model === model) && !background) return;
29
+ const updated = { ...args, ...(model ? { model } : {}), ...(background ? { run_in_background: false } : {}) };
30
+ process.stdout.write(JSON.stringify({ modifiedArgs: updated, permissionDecision: 'allow', hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow', updatedInput: updated } }));
31
+ });
@@ -284,6 +284,20 @@ Bash-side twin of the Write/Edit secret guard — do not work around either sile
284
284
  }
285
285
  }
286
286
 
287
+ // SoMi's review record and check result are written only by the CLI. A tripwire, not a boundary: it catches the honest mistake.
288
+ const STATE_PATH = String.raw`[^ \t\n\r\f\v]*\.somi/state(/|\s|$)`;
289
+ const STATE_WRITE_PATTERNS = [
290
+ new RegExp(String.raw`(>|>>)\s*${STATE_PATH}`),
291
+ new RegExp(String.raw`(^|[\s|;&])tee\s+(-[a-zA-Z]+\s+)*${STATE_PATH}`),
292
+ new RegExp(String.raw`(^|[\s|;&])(sed\s+[^|;&]*-i|cp|mv|rm|truncate)\s[^|;&]*${STATE_PATH}`),
293
+ ];
294
+
295
+ function checkStateWrites(payload, c) {
296
+ if (STATE_WRITE_PATTERNS.some((p) => p.test(c))) {
297
+ denyPretool(payload, 'somi refused this command: only the somi CLI writes to the SoMi state folder. If a flow seems to need a hand edit, the CLI is wrong: say so to the human.');
298
+ }
299
+ }
300
+
287
301
  // Force-push without a verifiable target (block-dangerous-bash.sh:133-164). The
288
302
  // protected-branch patterns above only fire when the branch is named in the command —
289
303
  // but `git push -f`, `git push -f origin`, and `git push -f origin HEAD` push the
@@ -364,6 +378,7 @@ function main() {
364
378
  checkDangerous(payload, cmd);
365
379
  checkDangerous(payload, cmdStripped);
366
380
  checkSecretWrites(payload, cmdStripped);
381
+ checkStateWrites(payload, cmdStripped);
367
382
  checkBareForcePush(payload, cmdStripped);
368
383
  }
369
384
 
@@ -209,8 +209,8 @@ function main() {
209
209
  }
210
210
 
211
211
  denyPretool(payload, `somi refused this command: it would add a new dependency (\`${m[0]}\`).
212
- Adding a dep is a decision — record it in \`.somi/plans/<slug>/decisions.md\` (or surface it in
213
- the iteration summary for the human) and re-run with \`SOMI_ALLOW_DEP_INSTALL=1\` in the
212
+ Adding a dep is a decision — record it in the plan (or surface it in
213
+ your summary for the human) and re-run with \`SOMI_ALLOW_DEP_INSTALL=1\` in the
214
214
  environment for this session, or have the human run the install themselves. Projects can also
215
215
  allowlist package-name prefixes in \`.somi/config.json\` under \`dep_install.allow\`.
216
216
  Lockfile-respecting reinstalls (bare \`npm install\` / \`pip install -r requirements.txt\`-less,
@@ -32,7 +32,7 @@
32
32
  //
33
33
  // --- lockfile-gate precedence reconciliation ------------------------------------------------
34
34
  // Precedence: SOMI_ALLOW_LOCKFILES (env, session override, even "0") > .somi/config.json's
35
- // `lockfiles.allow_edit` (committed project policy) > default deny. scripts/somi-check.mjs's
35
+ // `lockfiles.allow_edit` (committed project policy) > default deny. the lockfile check's
36
36
  // lockfilesAllowed() already solved this exact precedence problem,
37
37
  // including the jq-text string-vs-boolean subtlety: bash's `somi::config` shells out to
38
38
  // `jq -r`, so a config author writing `"allow_edit": "true"` (a JSON STRING) produces the
@@ -41,7 +41,7 @@
41
41
  // reads (returns '' for null/undefined/false, else the string itself or JSON.stringify(cur) for
42
42
  // a non-string scalar), so `config('.lockfiles.allow_edit') === 'true'` below reproduces the
43
43
  // SAME text comparison bash performs, without re-implementing a config reader the way
44
- // somi-check.mjs (which predates common.mjs) had to. Env-side fall-through matches too: bash's
44
+ // older hooks had to. Env-side fall-through matches too: bash's
45
45
  // `${SOMI_ALLOW_LOCKFILES:-}` treats unset AND explicitly-empty (`SOMI_ALLOW_LOCKFILES=""`)
46
46
  // identically (falls through to the config check); the `env !== undefined && env !== ''` guard
47
47
  // below reproduces that, matching lockfilesAllowed()'s own env branch.
@@ -56,8 +56,8 @@
56
56
  // 2. A path is absolute if it starts with `/` or a drive letter (`C:/`); anything else is
57
57
  // joined to projectRoot() (also slash-converted). The test is a literal one, deliberately
58
58
  // not `path.isAbsolute()`, so the result does not depend on the platform running the hook.
59
- // 3. path.posix.normalize() then collapses `..`, `.` and `//`, so `.somi/plans/../somi-state/
60
- // loop/x` cannot hide from a glob. A drive-letter path is normalized as it stands: posix
59
+ // 3. path.posix.normalize() then collapses `..`, `.` and `//`, so a path that climbs back
60
+ // into a protected folder cannot hide from a glob. A drive-letter path is normalized as it stands: posix
61
61
  // resolve() would take it for a relative path and prefix the current directory.
62
62
  // 4. Climbing past a drive root (`a:/../.git/config`) leaves a relative result, which no `*/`-led
63
63
  // glob matches; a result that is neither `/`-led nor drive-led gets a leading `/`.
@@ -76,14 +76,8 @@ const PROTECTED_GLOBS = [
76
76
  // SOMI plugin install — never let an agent rewrite the ruleset under itself.
77
77
  '*/.claude/plugins/somi/*',
78
78
 
79
- // The sizing CLI's records (scripts/somi-tier.mjs): they gate the brief-only path, so only the
80
- // CLI writes them, never an agent's Write/Edit.
81
- '*/.somi/somi-state/tier/*',
82
-
83
- // The loop's state and the run budget's (scripts/somi-loop.mjs, scripts/lib/run-budget.mjs): the loop's
84
- // scripts write them from node, which no hook sees, so only an agent's Write/Edit is refused.
85
- '*/.somi/somi-state/loop/*',
86
- '*/.somi/somi-state/run/*',
79
+ // SoMi's review record and check result: only the CLI writes them. If a flow ever needs a hand edit, the CLI is wrong.
80
+ '*/.somi/state/*',
87
81
 
88
82
  // Vendored deps & build outputs.
89
83
  '*/node_modules/*',
@@ -120,7 +114,7 @@ function globToRegExp(glob, flags) {
120
114
  // The globs naming a directory the agent must not even replace with a file (`.git` is a worktree's pointer file).
121
115
  // A trailing-slash retest checks the path itself, not just paths under it; the vendored-output globs are left
122
116
  // out, since a file named `build` or `vendor` anywhere is ordinary.
123
- const OWN_PATH_GLOBS = new Set(['*/.git/*', '*/.claude/plugins/somi/*', '*/.somi/somi-state/tier/*', '*/.somi/somi-state/loop/*', '*/.somi/somi-state/run/*']);
117
+ const OWN_PATH_GLOBS = new Set(['*/.git/*', '*/.claude/plugins/somi/*', '*/.somi/state/*']);
124
118
  const CASE_FOLDED = /\/\.(git|somi|claude)\//;
125
119
 
126
120
  const PROTECTED_PATTERNS = PROTECTED_GLOBS.map((glob) => ({ glob, re: globToRegExp(glob, CASE_FOLDED.test(glob) ? 'i' : ''), own: OWN_PATH_GLOBS.has(glob) }));
@@ -147,8 +141,7 @@ const slashes = (p) => p.replace(/\\/g, '/');
147
141
 
148
142
  // Where to send the agent instead, for the paths that tooling writes through a CLI.
149
143
  function nextStep(glob) {
150
- if (glob.includes('/somi-state/tier/')) return 'Tier records are written by `node scripts/somi-tier.mjs`; change them through it.';
151
- if (glob.includes('/somi-state/')) return 'Loop and run state are written by the loop CLI (`node scripts/somi-loop.mjs`, or `somi-loop.mjs step`); change them through that.';
144
+ if (glob.includes('/.somi/state/')) return 'SoMi state is written only by the `somi` CLI and the SoMi tools; if a flow seems to need a hand edit, the CLI is wrong.';
152
145
  return '';
153
146
  }
154
147
 
@@ -162,7 +155,7 @@ function checkPath(payload, tool, target) {
162
155
 
163
156
  for (const { glob, re, own } of PROTECTED_PATTERNS) {
164
157
  // The trailing-slash form catches a write at a protected directory's own path (`.git` as a worktree's
165
- // pointer file, `.somi/somi-state/loop`), which the globs' `/*` would otherwise need a child for.
158
+ // pointer file, the state folder), which the globs' `/*` would otherwise need a child for.
166
159
  if (re.test(pathInput) || (own && re.test(`${pathInput}/`))) {
167
160
  const next = nextStep(glob);
168
161
  denyPretool(payload, `somi refused to ${tool} \`${pathInput}\`: this path matches a protected glob (\`${glob}\`).
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse on file writes: changing which model a tier uses, or the quality gate's limits, is the maintainer's call, because lowering
3
+ // either lowers what a change is held to. Asks and does not deny, and it reads like any other permission question. An edit cannot show
4
+ // whether a limit goes up or down, so every change to one asks.
5
+
6
+ import { askPretool, readPayload, runHook, writeTargets } from '../lib/common.mjs';
7
+
8
+ const CONFIG = /(^|\/)(\.somi|somi)\/config\.json$/i;
9
+
10
+ runHook(() => {
11
+ const payload = readPayload();
12
+ const touchesConfig = writeTargets(payload).paths.some((t) => CONFIG.test(String(t).replaceAll('\\', '/')));
13
+ if (!touchesConfig) return;
14
+ const change = JSON.stringify(payload.tool_input ?? payload.toolArgs ?? {});
15
+ if (/tiers|ceiling/.test(change)) askPretool(payload, 'This changes which models SoMi tiers use. Allow it?');
16
+ else if (/quality/.test(change)) askPretool(payload, 'This changes the limits SoMi\'s quality gate holds code to. Allow it?');
17
+ });
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse on file writes: a reviewer reads and reports, on either host, and shared agent files cannot say so because tool names differ
3
+ // per host. Nothing else is limited here. The main agent and workers write freely.
4
+
5
+ import { denyPretool, readPayload, runHook } from '../lib/common.mjs';
6
+
7
+ runHook(() => {
8
+ const payload = readPayload();
9
+ const subagent = payload.agent_id ?? payload.agentId;
10
+ if (subagent && /reviewer$/.test(String(payload.agent_type ?? payload.agentType ?? ''))) denyPretool(payload, 'SoMi: a reviewer reads and reports. It does not edit.');
11
+ });
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ // SessionStart hook: hands the model the rules digest, the CLI's path and the decision ledger at session start and after compaction, and warns when the sandbox is off. The
3
+ // digest is deliberately not injected on every turn, because that repeats its cost each turn and adds nothing new.
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { pluginRoot, projectRoot, readPayload, runHook } from '../lib/common.mjs';
8
+ import { sandboxSettings, settingsWarnings } from '../../scripts/lib/doctor.mjs';
9
+ import { stateIsTracked } from '../../scripts/lib/git-tree.mjs';
10
+ import { readLedger } from '../../scripts/lib/ledger.mjs';
11
+ import { planStatus } from '../../scripts/lib/plan.mjs';
12
+ import { listShards } from '../../scripts/lib/shards.mjs';
13
+ import { detectHost } from '../../scripts/lib/tiers.mjs';
14
+ import { updateNotice } from '../../scripts/lib/update-notice.mjs';
15
+
16
+ // Compaction drops rules and scope limits first. This hook fires on compaction too, so the ledger comes back every time.
17
+ function projectParts(project) {
18
+ if (!project) return [];
19
+ const parts = [];
20
+ try {
21
+ const ledger = process.env.SOMI_STATE_DIR || !stateIsTracked(project) ? readLedger(project) : '';
22
+ if (ledger) parts.push(`Decisions and limits for the open work:\n${ledger}`);
23
+ const plan = planStatus(project);
24
+ if (plan?.next) parts.push(`An open plan is in the project at .somi/plan.md: ${plan.done} of ${plan.total} milestones done. Tell the user if it is relevant to what they ask.`);
25
+ const held = listShards({ root: project }).filter((b) => b.state !== 'ok');
26
+ if (held.length > 0) parts.push(`Connected steps needing attention: ${held.map((b) => `${b.ref} (${b.state})`).join(', ')}. Run \`somi slot --list\` for the detail if the user asks.`);
27
+ } catch { /* a bad state file must not stop a session starting */ }
28
+ return parts;
29
+ }
30
+
31
+ runHook(() => {
32
+ const payload = readPayload();
33
+ const root = pluginRoot();
34
+ if (root === null) return;
35
+ const host = detectHost();
36
+ const parts = [fs.readFileSync(path.join(root, 'rules', 'digest.md'), 'utf8').trim()];
37
+ parts.push(`SoMi CLI: \`node "${path.join(root, 'scripts', 'somi.mjs')}"\`, written as \`somi\` in SoMi's commands.`);
38
+ const warnings = settingsWarnings(host, sandboxSettings({ host, root: projectRoot() }));
39
+ if (warnings.length > 0) parts.push(`WARNING: the OS sandbox, SoMi's security boundary, needs attention: ${warnings[0]}. Hooks are tripwires, not a boundary. Tell the user once, in one line, and do not repeat it. If they ask for the detail, run \`somi doctor\` and relay it.`);
40
+ parts.push(...projectParts(projectRoot()));
41
+ const notice = updateNotice();
42
+ if (notice) parts.push(notice);
43
+ // Claude Code names the active agent here. Copilot CLI does not, so there the model is told how to tell from its own instructions.
44
+ if (host === 'claude' && !/(^|:)somi(-main)?$/.test(payload?.agent_type ?? '')) parts.push('SoMi is not the active agent in this session, so plain prompts are not routed and tiers apply only under `/somi` and SoMi commands. Tell the user once, and mention that starting with `--agent somi:somi` routes every request, and that /somi-config can run it on the model they choose.');
45
+ if (host === 'copilot') parts.push('Unless your own instructions already tell you to call somi_route for work, SoMi is not the active agent here, so plain prompts are not routed and tiers apply only under `/somi` and SoMi commands. Then tell the user once that starting with `copilot --agent somi:somi`, or `/agent somi` in a session, routes every request.');
46
+ // Copilot CLI gives an MCP server no project root, so the tool takes it from the session.
47
+ if (host === 'copilot' && payload?.cwd) parts.push(`Pass project_dir "${payload.cwd}" on every SoMi tool call.`);
48
+ const context = parts.join('\n\n');
49
+ // Copilot CLI reads the top-level field and Claude Code the nested one. Each ignores the other's.
50
+ process.stdout.write(`${JSON.stringify({ additionalContext: context, hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: context } })}\n`);
51
+ });
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ // Stop, on Claude Code and Copilot CLI, which both run the plugin's hooks: before the agent ends a turn, the diff decides whether a
3
+ // review is due and whether the change meets the quality limits, so the model does not have to remember either. When the gate fails, or
4
+ // a signal fired and no review covers the change, the turn goes on once with the reasons: the quality failures first, so the review
5
+ // reads the code that is finished. It asks once per tree, so it never loops, and when it cannot read the repository it lets the turn end.
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { loadConfig } from '../../scripts/lib/config-files.mjs';
10
+ import { stateIsTracked } from '../../scripts/lib/git-tree.mjs';
11
+ import { somiCommand } from '../../scripts/lib/advisor.mjs';
12
+ import { qualityStep } from '../../scripts/lib/quality/run.mjs';
13
+ import { reviewPlan } from '../../scripts/lib/reviews.mjs';
14
+ import { statePaths, writeStateFile } from '../../scripts/lib/state.mjs';
15
+ import { detectHost } from '../../scripts/lib/tiers.mjs';
16
+ import { projectRoot, readPayload, runHook } from '../lib/common.mjs';
17
+
18
+ runHook(() => {
19
+ const payload = readPayload();
20
+ if (payload.stop_hook_active === true || payload.agent_id) return;
21
+ const root = projectRoot();
22
+ if (root === null) return;
23
+ let plan;
24
+ try {
25
+ if (!process.env.SOMI_STATE_DIR && stateIsTracked(root)) return;
26
+ let loaded = { config: {}, global: { config: {} }, project: { config: {} } };
27
+ try { loaded = loadConfig(root); } catch { /* built-in signals still apply */ }
28
+ plan = reviewPlan({ root, env: process.env, config: loaded.config, configLayers: [loaded.global.config ?? {}, loaded.project.config ?? {}], host: detectHost(), now: () => new Date().toISOString() });
29
+ } catch { return; }
30
+ const asked = path.join(statePaths(root).dir, 'review-asked.json');
31
+ try { if (JSON.parse(fs.readFileSync(asked, 'utf8')).tree === plan.tree) return; } catch { /* not asked about this tree yet */ }
32
+ const quality = qualityStep(root, { scope: 'pr', env: process.env });
33
+ const reasons = [
34
+ ...(quality.ok ? [] : [`SoMi: this change is over the quality limits:\n${quality.failures.join('\n')}\nRefactor until \`${somiCommand('quality --scope pr')}\` passes, with the tests still green. Do not add a somi-gate-allow exemption to get past it: that is the user's call. If a limit cannot be met, or the code over it is not code you wrote in this conversation, tell the user which and why instead.`]),
35
+ ...(plan.needed ? [`SoMi: this change needs a review before it is finished (${plan.signals.join(', ')}). Call somi_review, start the reviewers it names with their briefs, and record what they return. If the user said not to review, tell them it is due and stop.`] : []),
36
+ ];
37
+ try { writeStateFile(root, asked, `${JSON.stringify({ tree: plan.tree })}\n`); } catch { return; }
38
+ if (reasons.length === 0) return;
39
+ process.stdout.write(`${JSON.stringify({ decision: 'block', reason: reasons.join('\n\n') })}\n`);
40
+ });
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ // UserPromptSubmit: keeps the user's messages so SoMi's tools can read the user's own words, not only the agent's summary of them.
3
+ // It adds nothing to the conversation and never blocks a prompt. A committed state folder is not trusted, so nothing is written there.
4
+
5
+ import { stateIsTracked } from '../../scripts/lib/git-tree.mjs';
6
+ import { savePrompt } from '../../scripts/lib/prompt.mjs';
7
+ import { projectRoot, readPayload, runHook } from '../lib/common.mjs';
8
+
9
+ runHook(() => {
10
+ const payload = readPayload();
11
+ const root = projectRoot();
12
+ if (root === null) return;
13
+ try {
14
+ if (!process.env.SOMI_STATE_DIR && stateIsTracked(root)) return;
15
+ savePrompt(root, payload.prompt ?? payload.userPrompt ?? '', process.env, { session: payload.session_id ?? payload.sessionId });
16
+ } catch { /* a prompt must never fail because SoMi could not keep a copy */ }
17
+ });
@@ -0,0 +1 @@
1
+ Use when a review should judge structure. Check dependency direction, new public contracts, what would be hard to reverse, and whether the change fits the boundaries already there. Raise a finding only for a concrete cost.
@@ -0,0 +1 @@
1
+ Use when a review should judge testing. Ask what could break that no test would catch. Check that tests fail without the change, that they assert behaviour and not mocks, and that they run at the cheapest level that can catch the bug.
@@ -0,0 +1 @@
1
+ You build or fix user interface so that everyone can use it. Read the accessibility skill listed below before you write markup. Generate the change, then review it against that checklist as a separate second pass, and fix what the pass finds. Run an automated checker such as axe if the project has one or can run one. Passing it is necessary and does not prove the interface is accessible, so say what still needs a person to check.
@@ -0,0 +1 @@
1
+ You answer a question about this project. Read what you need, and answer directly with file and line references. Say what you verified and what you inferred. Change nothing.
@@ -0,0 +1 @@
1
+ You map this codebase or a proposed change's blast radius, from what you read and not from what files are named. For a map, give the modules, how they depend on each other, how to run and test it, and what is surprising. For a change, give what calls it, what contracts it crosses, what tests cover it, and what would break. Mark anything you inferred. Keep it short enough to be read, and change no code.
@@ -0,0 +1 @@
1
+ You build one small, clear change. Read the code you will touch before changing it, follow the conventions already there, and make the smallest change that meets the request. Add or update tests that fail without the change and pass with it, then run them. Do not refactor on the way past, and touch nothing the request does not need.
@@ -0,0 +1,6 @@
1
+ You fix a bug whose cause is not yet known. Do not trust a cause named in the report: treat it as a lead and test it.
2
+
3
+ 1. Reproduce it first, as a failing test where you can. If you cannot reproduce it, say so and stop.
4
+ 2. Narrow it by testing one guess at a time, and record what each result rules out.
5
+ 3. Fix the cause, not the symptom. Look for the same mistake in other copies of the code, such as a second path doing the same job.
6
+ 4. Keep the failing test as the regression guard, and run the suite.
@@ -0,0 +1 @@
1
+ You settle an expensive-to-reverse choice on this codebase. Read the code it touches. Give at most three real options, each with what it costs, how it fails, and what reversing it would take. Recommend one and say why. Name the assumptions that would change your answer. Change no code. Cover trust boundaries if the change crosses one.
@@ -0,0 +1 @@
1
+ You test a new product idea before anyone specifies it. Find what exists and what its users complain about, with sources you actually read, and mark anything you could not verify. Report who it is for, the problem in their words, what would make it fail, and the smallest thing worth building first. Say plainly if the evidence says not to build it. Change no code.
@@ -0,0 +1 @@
1
+ Production is hurting, so restore service first with the smallest safe step: a flag flip, a revert or a narrow patch. Guardrails still apply. Do not hunt for the root cause while it is down. Once it is mitigated, your report must include: what you changed and how to undo it, what you saw and when, what you do not know yet, and the follow-up that should find the real cause.
@@ -0,0 +1 @@
1
+ You change a data shape that is already in use. Assume old and new code run at once during a deploy, so split the change into steps that are each safe alone: expand, backfill, switch reads, contract. Every step must have a way back, and a backfill must be safe to rerun and to resume. Test against a copy with realistic data, including rows the new shape has trouble with. Never drop or rewrite data in the same step that starts using the new shape. State the rollback for each step in your report.
@@ -0,0 +1 @@
1
+ You make something measurably faster or smaller. Models are poor at guessing performance problems, so measure first: write a repeatable benchmark for the case that matters, record the baseline, and profile it to find where the time actually goes. Change one thing at a time and keep it only if the number moves. Report before and after, with the command that produces them. Behaviour must not change, so run the tests too. If you cannot measure it, say so and stop.
@@ -0,0 +1 @@
1
+ You plan work too big for one sitting. Read enough of the code to be concrete. Split it into milestones, each one feature that can be built and tested alone, in dependency order. Save the plan with somi_plan, or by piping it to `somi plan` where the tool is not available. Number each milestone as a line reading `Milestone N: what it delivers`, followed by one test or command that can fail and proves it. State decisions that later milestones must honour, and anything expensive to reverse as options with the cost of reversing each. Change no code.
@@ -0,0 +1 @@
1
+ You change structure and keep behaviour exactly. Start from green tests. Where the code you will change has no test pinning its behaviour, add one first, including the odd cases, because quirks are often depended on. Make the change in small steps with the tests green after each. Do not mix in feature work or fix bugs on the way: report any you find. If the change turns out to span many modules or need a migration, report `too-big` with the parts.
@@ -0,0 +1 @@
1
+ Review the current changes, or the diff or pull request named in the request, with fresh eyes. Run `git diff` for the changes yourself, and read what you need around them. Return your JSON findings as your instructions define. Change nothing.
@@ -0,0 +1 @@
1
+ Review the current changes, or the code named in the request, for security. Run `git diff` for the changes yourself, and trace untrusted input to each sink. Read the secure-coding skill listed below. Return your JSON findings as your instructions define. Change nothing.
@@ -0,0 +1 @@
1
+ You upgrade a dependency. Read the changelog and migration notes for every version you cross, from the project's own docs and not from memory, because a model's memory of an API is often an older version. Find how this project uses what changed, migrate those uses, and run the full tests. Update the lockfile with the project's tool, and do not add other dependencies. Report anything breaking that you could not cover with a test.
@@ -0,0 +1,16 @@
1
+ # Accessibility
2
+
3
+ Use when creating or changing user interface: pages, components, forms, dialogs, menus or charts. Models usually miss these unless told.
4
+
5
+ Build it, then check it against this list as a separate pass. Prefer native elements to re-implementing them.
6
+
7
+ - **Names:** every control has an accessible name from a visible label. Images have alt text, or empty alt when decorative. An icon button needs a name.
8
+ - **Structure:** one main landmark and a sensible heading order, with lists and tables marked as such.
9
+ - **Keyboard:** everything works by keyboard in a logical order, with a visible focus. No traps. Use a real `button` or `a`, not a clickable `div`.
10
+ - **Forms:** each input has a label. Errors are tied to their field with text and announced. Required state is exposed.
11
+ - **Dialogs and menus:** focus moves in, stays in, and returns on close. Escape closes. Roles and states match the behaviour, and a wrong ARIA role is worse than none.
12
+ - **Dynamic content:** status changes are announced through a live region. Loading state is exposed.
13
+ - **Colour and motion:** contrast of at least 4.5:1 for text and 3:1 for large text and controls. Colour is never the only signal. Respect reduced motion.
14
+ - **Zoom:** usable at 200% and on a narrow screen, with no horizontal scrolling for text.
15
+
16
+ Run an automated checker if you can. It catches a fraction of problems, so say what still needs a person with a screen reader.
@@ -0,0 +1,12 @@
1
+ # CI and infrastructure gotchas
2
+
3
+ Use when changing CI, containers, deployment manifests or infrastructure config.
4
+
5
+ Examples in your memory are often an older version, and copying a near match does harm. First read which version this project runs and that version's own docs, then copy nothing you have not checked against them.
6
+
7
+ - Add only what was asked for. An extra policy or resource you were not asked for is a regression.
8
+ - Pin third-party actions and images by digest or commit, because tags can be moved.
9
+ - Give CI tokens the least permission, per job. Never expose secrets to code from forks.
10
+ - A step that masks its exit status hides failure: check pipes and `|| true`.
11
+ - Validate with the tool's own dry run or schema check before you say it works.
12
+ - Caches must key on what changes the result, or they serve stale output.
@@ -0,0 +1,10 @@
1
+ # Performance method
2
+
3
+ Use when something must get faster or smaller, or when a review questions performance.
4
+
5
+ - Measure before changing anything. Guesses about hot spots are usually wrong, and models are especially weak here.
6
+ - Define the case and the number that matters: which input size, and latency, throughput or memory.
7
+ - Warm up, repeat, and report spread. A change within the noise is no change.
8
+ - Profile to find where time goes, then fix the largest contributor first.
9
+ - Look for the structural causes first: repeated work, queries in loops, missing indexes, copying large data, unbounded growth.
10
+ - Keep a benchmark or budget so the gain cannot quietly regress.
@@ -0,0 +1,18 @@
1
+ # Secure coding
2
+
3
+ Use when code handles input from outside the process, or touches authentication, authorization, secrets, files, or a sink such as SQL, shell, HTML or an HTTP request.
4
+
5
+ General reminders do little. Check each specific weakness that applies, and trace real input to the sink.
6
+
7
+ - **CWE-89, 78, 79, injection:** every sink is parameterized or escaped for its own context. Attribute, URL and script contexts escape differently from HTML text. Check values reaching the sink through a helper, not only direct ones.
8
+ - **CWE-22, path traversal:** resolve the real path, following links, and compare against the base with a trailing separator, because `/data-evil` starts with `/data`. Refuse `..`, absolute paths, backslashes and NUL. Check links already on disk, not just the given name.
9
+ - **CWE-601, open redirect:** allow only a path on your own origin. Refuse `//host`, `/\host`, control characters and `user@host` forms, and parse before you compare. Never test with a prefix match on the origin.
10
+ - **CWE-862, 639, missing authorization:** check ownership at the sink for every object id, including on lists, exports and background jobs. Being signed in is not being allowed.
11
+ - **CWE-384, 613, sessions and tokens:** store tokens hashed. Single-use tokens are spent atomically, a new one kills the old, and a password change ends other sessions. Answer identically whether an account exists or not.
12
+ - **CWE-208, comparing secrets:** compare in constant time and check lengths first, because some constant-time functions throw on a mismatch and that must not become a crash.
13
+ - **CWE-347, webhook signatures:** verify over the exact raw bytes, before parsing. Check the timestamp in both directions, accept rotated keys, and record a replay id only after verifying.
14
+ - **CWE-502, 1321, unsafe parsing:** never deserialize to code. Look up user-supplied keys with own-property checks, so `__proto__` and `constructor` are just missing names.
15
+ - **CWE-918, server-side request forgery:** an allowlist of hosts, resolved and checked after redirects, with internal ranges refused.
16
+ - **CWE-532, secrets in logs:** nothing secret in logs, errors or URLs.
17
+
18
+ If something is unclear, say so instead of guessing that it is safe.
@@ -0,0 +1,16 @@
1
+ # Testing checklist
2
+
3
+ Use when writing or judging tests for a change, especially one with edge cases that are easy to skip.
4
+
5
+ Before you call it done, check each that applies, and add a test where it matters:
6
+
7
+ - The test fails without the change. Run it that way once if it is cheap.
8
+ - Boundaries: zero, one, empty, the maximum, just past the maximum, and inclusive against exclusive ends.
9
+ - Bad input: wrong type, missing field, and the documented error for each.
10
+ - Repeats: doing it twice, retrying after a failure, and two at once if it can happen.
11
+ - All-or-nothing: after a failure midway, nothing is left half done.
12
+ - Time and zones: daylight saving changes, month ends, and expiry at the exact moment.
13
+ - Money and rounding: whole units, ties, and totals that must add up exactly.
14
+ - What must not change: other callers, other users' data, and existing output.
15
+
16
+ Assert behaviour, not how it is built. Do not mock what you do not own. Use the framework and style the project already uses. This list says what to cover, not how to write it.