@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
@@ -0,0 +1,73 @@
1
+ // quality/parse.mjs: the vendored tree-sitter runtime and grammars, checked against their manifest before use, and a parse with limits.
2
+ // The bytes that are hashed are the bytes that run: the runtime and each grammar are handed the verified buffer, not a path. A file
3
+ // that is too large, or that the parser cannot finish in time, comes back unanalyzed, and the gate counts that as a failure.
4
+
5
+ import crypto from 'node:crypto';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { fileURLToPath, pathToFileURL } from 'node:url';
9
+
10
+ const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'vendor', 'tree-sitter');
11
+ export const MAX_FILE_BYTES = 512 * 1024;
12
+ export const PARSE_TIMEOUT_MS = 5000;
13
+ const LANGUAGES = { '.js': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript', '.jsx': 'javascript', '.ts': 'typescript', '.mts': 'typescript', '.cts': 'typescript', '.tsx': 'tsx', '.css': 'css' };
14
+
15
+ /** The grammar a file is parsed with, or null when the gate does not cover its language yet. */
16
+ export const languageOf = (file) => LANGUAGES[path.extname(file).toLowerCase()] ?? null;
17
+
18
+ let manifest = null;
19
+ let runtime = null;
20
+ const grammars = new Map();
21
+
22
+ /** The bytes of a vendored file, after checking them against the manifest in the same folder. */
23
+ export function verifiedFile(name, dir = DIR) {
24
+ const list = dir === DIR ? (manifest ??= JSON.parse(fs.readFileSync(path.join(DIR, 'manifest.json'), 'utf8'))) : JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8'));
25
+ const entry = list.files?.[name];
26
+ if (!entry) throw new Error(`${name} is not in the vendored manifest`);
27
+ const bytes = fs.readFileSync(path.join(dir, name));
28
+ if (crypto.createHash('sha256').update(bytes).digest('hex') !== entry.sha256) throw new Error(`${name} does not match its manifest, so it is not loaded`);
29
+ return bytes;
30
+ }
31
+
32
+ async function load(language) {
33
+ if (!runtime) {
34
+ verifiedFile('web-tree-sitter.js');
35
+ const wasmBinary = verifiedFile('web-tree-sitter.wasm');
36
+ const mod = await import(pathToFileURL(path.join(DIR, 'web-tree-sitter.js')).href);
37
+ await mod.Parser.init({ wasmBinary });
38
+ runtime = mod;
39
+ }
40
+ if (!grammars.has(language)) grammars.set(language, await runtime.Language.load(verifiedFile(`tree-sitter-${language}.wasm`)));
41
+ const parser = new runtime.Parser();
42
+ parser.setLanguage(grammars.get(language));
43
+ return parser;
44
+ }
45
+
46
+ // Where the parser could not follow the code, as [first, last] lines. A grammar can lag a language's newest syntax, so an error far
47
+ // from a change does not stop the rest of the file being scored.
48
+ function errorRanges(tree) {
49
+ const out = [];
50
+ const visit = (n) => {
51
+ if (n.isError || n.isMissing) { out.push([n.startPosition.row + 1, n.endPosition.row + 1]); return; }
52
+ for (const c of n.children) if (c.hasError || c.isMissing) visit(c);
53
+ };
54
+ visit(tree.rootNode);
55
+ return out;
56
+ }
57
+
58
+ /**
59
+ * { tree, language, errors } for a supported file, { unanalyzed: reason } when it could not be parsed at all, or null for a language not
60
+ * covered. errors lists the lines the parser could not follow, which the gate does not score.
61
+ */
62
+ export async function parseSource(file, text) {
63
+ const language = languageOf(file);
64
+ if (!language) return null;
65
+ if (Buffer.byteLength(text) > MAX_FILE_BYTES) return { unanalyzed: `larger than ${MAX_FILE_BYTES} bytes` };
66
+ const parser = await load(language);
67
+ const deadline = Date.now() + PARSE_TIMEOUT_MS;
68
+ try {
69
+ const tree = parser.parse(text, null, { progressCallback: () => Date.now() > deadline });
70
+ if (!tree) return { unanalyzed: `not parsed within ${PARSE_TIMEOUT_MS} ms` };
71
+ return { tree, language, errors: tree.rootNode.hasError ? errorRanges(tree) : [] };
72
+ } finally { parser.delete(); }
73
+ }
@@ -0,0 +1,69 @@
1
+ // quality/repo.mjs: the whole codebase measured as it stands, for a cleanup or a refactor. Where a change scope asks whether a change made
2
+ // things worse, this asks where the debt is: every function and file over a limit, every copy in product code, every suppression with
3
+ // no reason, worst first. It is a report, not a gate on a change, so there is no before to compare with and no per-change limit.
4
+
5
+ import { fileAt, listFiles } from '../git-tree.mjs';
6
+ import { findClones, tokensOf } from './clones.mjs';
7
+ import { JS_FAMILY, METRICS, exemption, isTest, scoreComments, scoreCss, skipped, total, withTree } from './gate.mjs';
8
+ import { topLevelCognitive, unitsOf } from './metrics.mjs';
9
+ import { languageOf } from './parse.mjs';
10
+
11
+ const TOP = 20;
12
+
13
+ // The change scopes' comment and stylesheet checks, run on every line, since the whole file is what is being measured.
14
+ const EVERY_LINE = [[1, Number.MAX_SAFE_INTEGER]];
15
+
16
+ function unitFindings(ctx, { file, lines, unit }) {
17
+ ctx.scored.functions += 1;
18
+ ctx.functions.push({ file, line: unit.start, name: unit.name, cognitive: unit.cognitive });
19
+ for (const metric of METRICS.filter((m) => unit[m] > ctx.limits[unit.kind][m])) {
20
+ const allowed = exemption(ctx, lines, unit, metric);
21
+ if (allowed) ctx.exemptions.push({ rule: metric, file, line: unit.start, name: unit.name, ...allowed });
22
+ else ctx.violations.push({ rule: metric, file, line: unit.start, name: unit.name, kind: unit.kind, value: unit[metric], limit: ctx.limits[unit.kind][metric] });
23
+ }
24
+ }
25
+
26
+ // A function the parser could not follow is not scored, and with one in the file its total is not trusted either.
27
+ function codeFindings(ctx, { file, lines, parsed }) {
28
+ const test = isTest(file);
29
+ const units = unitsOf(parsed.tree, { file, isTest: test });
30
+ const readable = (u) => !parsed.errors.some(([a, b]) => a <= u.end && b >= u.start);
31
+ for (const unit of units.filter(readable)) unitFindings(ctx, { file, lines, unit });
32
+ const sum = total(units, topLevelCognitive(parsed.tree));
33
+ if (parsed.errors.length === 0 && sum > ctx.limits.file.cognitive) ctx.violations.push({ rule: 'file-cognitive', file, line: 1, value: sum, limit: ctx.limits.file.cognitive });
34
+ if (JS_FAMILY.has(parsed.language) && !test) ctx.cloneFiles.push({ file, tokens: tokensOf(parsed.tree), size: ctx.limits.clones.tokens });
35
+ }
36
+
37
+ function scoreParsed(ctx, { file, text, parsed }) {
38
+ if (parsed?.unanalyzed || parsed?.errors.length) ctx.unanalyzed.push({ file, reason: parsed.unanalyzed ?? `the parser could not follow ${parsed.errors.length} part(s)` });
39
+ if (!parsed?.tree) return;
40
+ ctx.scored.files += 1;
41
+ scoreComments(ctx, file, parsed.tree, EVERY_LINE);
42
+ if (parsed.language === 'css') scoreCss(ctx, file, parsed.tree, EVERY_LINE);
43
+ else codeFindings(ctx, { file, lines: text.split('\n'), parsed });
44
+ }
45
+
46
+ function summary(ctx) {
47
+ const byRule = {};
48
+ const byFile = {};
49
+ for (const v of ctx.violations) {
50
+ byRule[v.rule] = (byRule[v.rule] ?? 0) + 1;
51
+ byFile[v.file] = (byFile[v.file] ?? 0) + 1;
52
+ }
53
+ return {
54
+ by_rule: byRule,
55
+ most_complex: ctx.functions.sort((a, b) => b.cognitive - a.cognitive).slice(0, TOP),
56
+ most_findings: Object.entries(byFile).sort((a, b) => b[1] - a[1]).slice(0, TOP).map(([file, findings]) => ({ file, findings })),
57
+ };
58
+ }
59
+
60
+ /** The codebase at `rev`, measured against `limits`: { ok, violations, exemptions, unanalyzed, scored, summary }. */
61
+ export async function repoQuality(root, { rev, limits, now = new Date().toISOString() }) {
62
+ const ctx = { limits, now, mode: 'project', violations: [], exemptions: [], unanalyzed: [], functions: [], cloneFiles: [], scored: { files: 0, functions: 0 } };
63
+ for (const file of listFiles(root, rev).filter((f) => languageOf(f))) {
64
+ const text = fileAt(root, rev, file);
65
+ if (text !== null && !skipped(file, text)) await withTree(file, text, (parsed) => scoreParsed(ctx, { file, text, parsed }));
66
+ }
67
+ for (const c of findClones({ after: ctx.cloneFiles })) ctx.violations.push({ rule: 'clone', file: c.file, line: c.line, value: c.lines, limit: 0, other: c.other });
68
+ return { ok: ctx.violations.length === 0, violations: ctx.violations, exemptions: ctx.exemptions, unanalyzed: ctx.unanalyzed, scored: ctx.scored, summary: summary(ctx) };
69
+ }
@@ -0,0 +1,38 @@
1
+ // quality/run.mjs: the quality gate as a step the synchronous commands can take. somi check and somi pr call it, and it runs the same
2
+ // somi quality a person would, so all three agree. A gate that cannot run is not a pass: its failure is reported as a violation.
3
+
4
+ import path from 'node:path';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'somi.mjs');
9
+ export const QUALITY_TIMEOUT_MS = 120000;
10
+ const MAX_SHOWN = 20;
11
+
12
+ const describe = (v) => {
13
+ const where = `${v.file}:${v.line}${v.name ? ` ${v.name}` : ''}`;
14
+ if (v.rule === 'clone') return `clone ${where}: ${v.value} lines also at ${v.other.file}:${v.other.line}`;
15
+ return `${v.rule} ${where}: ${v.value} over ${v.limit}${v.before !== undefined ? `, was ${v.before}` : ''}`;
16
+ };
17
+
18
+ /** The gate's own report for one scope, or { error } when it could not run. */
19
+ export function runQuality(root, { scope, env = process.env }) {
20
+ const r = spawnSync(process.execPath, [CLI, 'quality', '--scope', scope], { cwd: root, env, encoding: 'utf8', timeout: QUALITY_TIMEOUT_MS, killSignal: 'SIGKILL', maxBuffer: 32 * 1024 * 1024 });
21
+ let result = null;
22
+ try { result = JSON.parse(r.stdout); } catch { /* reported below */ }
23
+ if (!result || (r.status !== 0 && r.status !== 1)) return { error: `the quality gate could not run: ${(r.stderr || r.error?.message || 'no output').trim().split('\n')[0].slice(0, 200)}` };
24
+ return result;
25
+ }
26
+
27
+ /** Each violation as one line naming the rule, the place and the numbers, at most MAX_SHOWN of them. */
28
+ export function describeAll(violations, scope) {
29
+ const lines = violations.map(describe);
30
+ return lines.length > MAX_SHOWN ? [...lines.slice(0, MAX_SHOWN), `and ${lines.length - MAX_SHOWN} more: somi_quality with scope ${scope} lists them`] : lines;
31
+ }
32
+
33
+ /** { ok, failures: [line], warnings: n } for one scope, where each failure names the rule, the place and the numbers. */
34
+ export function qualityStep(root, { scope, env = process.env }) {
35
+ const result = runQuality(root, { scope, env });
36
+ if (result.error) return { ok: false, failures: [result.error], warnings: 0 };
37
+ return { ok: result.ok, failures: describeAll(result.violations, scope), warnings: result.warnings.length };
38
+ }
@@ -0,0 +1,132 @@
1
+ // reviews.mjs: which review a change needs, what reviewers found, and whether it can leave. A review never blocks the conversation or
2
+ // a local commit. The one place it can stop anything is the outward step: SoMi will not write pull request text for a change that needed
3
+ // a review and has none, or that has an open blocking finding, unless the text says so at the top. Signals come from the real diff,
4
+ // and nothing in a project's config can lower them. The record is a tripwire like the rest of SoMi's hooks, not a security boundary.
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { readDiff, resolveRef, reviewDiffCommand, snapshotTree, workBase } from './git-tree.mjs';
9
+ import { ReviewInputError, decideAfterReview, isBlocking, parseReviews } from './policy.mjs';
10
+ import { computeSignals, RECORDED_ONLY, SECURITY_SIGNALS } from './signals.mjs';
11
+ import { StateError, appendStateFile, statePaths } from './state.mjs';
12
+ import { resolveSpawn } from './tiers.mjs';
13
+
14
+ const REVIEWER = 'somi-reviewer';
15
+ const SECURITY_REVIEWER = 'somi-security-reviewer';
16
+ const OBJECT_ID = /^[0-9a-f]{40,64}$/;
17
+ const REVIEWER_PROMPT = 'Fresh, read-only review. Run the diff command, read what you need, return only the JSON your instructions define.';
18
+ // Judging a diff is judgement work, so the code reviewer runs on medium and the security reviewer on high.
19
+ const TIERS = Object.freeze({ [REVIEWER]: 'medium', [SECURITY_REVIEWER]: 'high' });
20
+ const bare = (agent) => String(agent ?? '').split(':').pop();
21
+
22
+ // Who reviews is review policy, so only the user's own config chooses the model, and a committed project config has no say.
23
+ const seat = (ctx, agent, diff) => {
24
+ const { tier, model } = resolveSpawn(ctx.configLayers?.[0] ?? {}, ctx.host, TIERS[agent]);
25
+ return { agent: `somi:${agent}`, tier, ...(model ? { model } : {}), brief: `${REVIEWER_PROMPT}\n\nThe diff command:\n${diff}` };
26
+ };
27
+
28
+ const triggers = (signals) => [...signals.review.filter((s) => !RECORDED_ONLY.includes(s)), ...signals.security];
29
+
30
+ export function readReviews(root, env = process.env) {
31
+ let text;
32
+ try { text = fs.readFileSync(statePaths(root, env).reviews, 'utf8'); } catch (e) { if (e.code === 'ENOENT') return []; throw e; }
33
+ return text.split('\n').filter(Boolean).map((line) => {
34
+ try { return JSON.parse(line); } catch { throw new StateError('reviews.jsonl has a line that is not JSON; SoMi will not guess at it'); }
35
+ });
36
+ }
37
+
38
+ function baseOf(ctx, base) {
39
+ if (base === undefined || base === null) return workBase(ctx.root);
40
+ try { return resolveRef(ctx.root, base); } catch { throw new ReviewInputError(`cannot find the base ${JSON.stringify(String(base).slice(0, 80))}`); }
41
+ }
42
+
43
+ function signalsFor(ctx, from, to) {
44
+ return computeSignals(readDiff(ctx.root, from, to), ctx.configLayers ?? []);
45
+ }
46
+
47
+ // What this change needs, read from the diff. `always` and `security` come from a user asking, and only ever add a reviewer.
48
+ export function reviewPlan(ctx, { base, always = false, security = false } = {}) {
49
+ const from = baseOf(ctx, base);
50
+ const tree = snapshotTree(ctx.root);
51
+ const signals = signalsFor(ctx, from, tree);
52
+ const empty = signals.facts.files === 0;
53
+ const fired = triggers(signals);
54
+ const agents = [];
55
+ // One reviewer per change. When a security signal fired, the security reviewer also reads the change as the code reviewer would, so
56
+ // its attack paths and its defects come from one pass: a second reviewer on the same diff found little the first had not, at about
57
+ // twice the cost.
58
+ if (!empty && (signals.security.length > 0 || security)) agents.push(SECURITY_REVIEWER);
59
+ else if (!empty && (fired.length > 0 || always)) agents.push(REVIEWER);
60
+ // A clean review still vouches for a change until something new fires, so acting on its comments does not pay for it again. A user asking
61
+ // is the exception, and so is an open blocking finding, whose fix needs a look.
62
+ const covered = agents.length > 0 && !always && !security && coveringReview(ctx, tree, agents);
63
+ if (covered && (covered.findings ?? []).filter(isBlocking).length === 0) return { needed: false, covered: true, reviewers: [], required: agents, base: from, tree, signals: fired };
64
+ const diff = reviewDiffCommand(from, tree);
65
+ return { needed: agents.length > 0, reviewers: agents.map((a) => seat(ctx, a, diff)), required: agents, base: from, tree, signals: fired, diff };
66
+ }
67
+
68
+ // Hosts hand reviewers the absolute path of the working copy, and a report is not worth paying for twice over that.
69
+ const relativeFile = (root, file) => (typeof file === 'string' && path.isAbsolute(file) && path.relative(root, file) && !path.relative(root, file).startsWith('..') ? path.relative(root, file) : file);
70
+
71
+ function normalized(ctx, reviews) {
72
+ if (!Array.isArray(reviews)) throw new ReviewInputError('reviews must be an array');
73
+ return reviews.map((r) => (r !== null && typeof r === 'object' && !Array.isArray(r)
74
+ ? { ...r, agent: bare(r.agent), findings: Array.isArray(r.findings) ? r.findings.map((f) => (f !== null && typeof f === 'object' ? { ...f, file: relativeFile(ctx.root, f.file) } : f)) : r.findings }
75
+ : r));
76
+ }
77
+
78
+ const ADVICE = Object.freeze({
79
+ fix: 'These findings block this change from leaving. Fix them where the change was made: if a worker built it, start the same worker with its brief and these findings below it, and otherwise fix them here. Then call somi_review with no reviews, run the reviewers it names, and record what they return. If a finding has needs_verification, check it first: a reviewer asking to remove a check is not enough reason to remove it.',
80
+ fixHere: 'These findings block this change from leaving, and security signals fired on its diff. Fix them here, on this conversation\'s model, and not on a low worker, even if one built the change. Then call somi_review with no reviews, run the reviewers it names, and record what they return. If a finding has needs_verification, check it first: a reviewer asking to remove a check is not enough reason to remove it.',
81
+ ask: 'Tell the user: blocking findings remain after repeated review passes. Show them, and let the user choose between more fixing and stopping. SoMi will not write clean pull request text until a review clears them.',
82
+ close: 'Nothing here blocks the change. Pass the logged findings on to the user briefly, and do not act on them unless the user asks.',
83
+ });
84
+
85
+ export function recordReviews(ctx, { reviews, base, tree: reviewed, always = false, security = false }) {
86
+ const plan = reviewPlan(ctx, { base, always, security });
87
+ const tree = OBJECT_ID.test(String(reviewed)) ? reviewed : plan.tree;
88
+ const list = normalized(ctx, reviews);
89
+ const named = list.map((r) => r?.agent).filter((a) => Object.hasOwn(TIERS, a));
90
+ const dispatched = [...new Set([...plan.required, ...named])].map((agent) => ({ agent }));
91
+ const { findings, verdicts } = parseReviews(list, dispatched);
92
+ const earlier = readReviews(ctx.root, ctx.env).filter((r) => r.base === plan.base);
93
+ const pass = earlier.length + 1;
94
+ const previousBlocking = earlier.at(-1)?.blocking ?? [];
95
+ const decision = decideAfterReview({ findings, pass, previousBlocking });
96
+ const blocking = findings.filter(isBlocking);
97
+ const securityFired = plan.signals.some((s) => SECURITY_SIGNALS.includes(s));
98
+ const record = { v: 1, at: ctx.now(), base: plan.base, tree, pass, verdicts, findings, blocking: blocking.map((f) => f.fingerprint) };
99
+ appendStateFile(ctx.root, statePaths(ctx.root, ctx.env).reviews, `${JSON.stringify(record)}\n`, ctx.env);
100
+ const logged = findings.filter((f) => !isBlocking(f));
101
+ return {
102
+ verdict: decision.next === 'close' ? 'clear' : decision.next === 'fix' ? 'fix' : 'ask-user',
103
+ pass,
104
+ blocking,
105
+ logged,
106
+ advice: decision.next === 'fix' && securityFired ? ADVICE.fixHere : ADVICE[decision.next],
107
+ ...(decision.stop ? { stop: decision.stop } : {}),
108
+ };
109
+ }
110
+
111
+ // Whether a record still vouches for the tree now. A later change that fires no signal does not undo it. One that does needs its own look.
112
+ function covers(ctx, record, tree, needed) {
113
+ if (!OBJECT_ID.test(String(record.tree))) return false;
114
+ const agents = (record.verdicts ?? []).map((v) => bare(v.agent));
115
+ if (!needed.every((a) => agents.includes(a))) return false;
116
+ if (record.tree === tree) return true;
117
+ try { return triggers(signalsFor(ctx, record.tree, tree)).length === 0; } catch { return false; }
118
+ }
119
+
120
+ const coveringReview = (ctx, tree, needed) => [...readReviews(ctx.root, ctx.env)].reverse().find((r) => covers(ctx, r, tree, needed)) ?? null;
121
+
122
+ // The review gate. Findings are taken from the newest review that covers the tree, so a clean re-review clears an earlier blocker.
123
+ export function prGate(ctx, { base } = {}) {
124
+ const plan = reviewPlan(ctx, { base });
125
+ const covering = coveringReview(ctx, plan.tree, plan.required);
126
+ if (!plan.needed && !covering) return { ok: true, plan, review: null };
127
+ if (!covering) return { ok: false, reason: 'not-reviewed', signals: plan.signals, plan, review: null };
128
+ const blocking = (covering.findings ?? []).filter(isBlocking);
129
+ if (blocking.length > 0) return { ok: false, reason: 'open-blocking', blocking, plan, review: covering };
130
+ return { ok: true, plan, review: covering };
131
+ }
132
+
@@ -0,0 +1,108 @@
1
+ // routes.mjs: the deterministic half of routing. It classifies what the work is, never how big it will be, because model size forecasts
2
+ // were 2 to 8 times too high. A request in a clear form gets one route. Anything else goes to the coordinator to choose from a short
3
+ // table, which spends one turn and no extra agent. Rules alone are not enough: they scored 96% on the phrasings they were written
4
+ // beside and 41% on fresh ones, because people describe a problem without naming its kind. Pure, and scored in the benchmark.
5
+
6
+ // Checked first, in order: when one of these applies it decides, whatever else the request mentions.
7
+ const FIRST = [
8
+ ['status', /^\s*(status|what('s| is) (in flight|open|running))\b/i],
9
+ ['resume', /^\s*(continue|resume|pick up|carry on)\b/i],
10
+ ['config', /\bsomi\b.*\b(config|tiers?|model map)\b|\b(tier|model) map\b/i],
11
+ ['incident', /\b(outage|incident|sev[ -]?[012]\b|on fire)\b|\b(prod|production|site|service)\b.{0,30}\b(is |are )?(down|broken|failing|on fire)\b/i],
12
+ ['security-review', /\b(security|threat|vulnerabilit\w*|pentest|owasp)\b.{0,40}\b(review|audit|check|assess\w*|look)\b|\b(review|audit|check|assess)\b.{0,40}\b(security|vulnerabilit\w*|threats?)\b/i],
13
+ ['accessibility', /\b(accessib\w*|a11y|wcag|screen ?readers?|aria)\b/i],
14
+ ];
15
+
16
+ // A spec says what a feature returns, so "error" alone is not a symptom, and "keeps working exactly as it does" is a guard, not a refactor.
17
+ // A bug is reported by its symptom, often with a guess at the cause, so the guess and the symptom are what it is known by.
18
+ const DEBUG = new RegExp([
19
+ String.raw`\b(bug|broken|fails?|failing|failure|crash\w*|exception|regression|stack ?trace|doesn'?t work|not working|flaky|wrong (result|output|value|total)s?)\b|\bfix(es|ing)?\b`,
20
+ String.raw`\b(getting|seeing|see|saw|hitting|threw|keeps (throwing|showing|returning)) (an? |the |this |that )?([\w-]+ )?errors?\b|\berrors? (when|whenever|after|since|in (prod|production|the logs))\b`,
21
+ String.raw`\b(find|track down|work out) (the |its )?(real |root |actual )?causes?\b|\broot cause\b|\bsomeone (thinks|suspects|says|proposes|blames|believes)\b|\bis (at fault|to blame)\b`,
22
+ String.raw`\b(at random|now and then|every so often|from run to run|intermittent\w*|sporadic\w*)\b|\b(at|for) the wrong (hour|time|day|week|month|price|amount|total|place|person|user|customer)s?\b`,
23
+ String.raw`\b(comes?|came|goes|go|went) out (wrong|differently|different)\b|\bdisagree\w*\b|\b(charged|billed|sent|counted) twice\b|\b(lose|loses|losing) (\w+ )?(orders|data|records|rows|messages|events|money|items)\b`,
24
+ ].join('|'), 'i');
25
+ // A refactor is asked for by what is wrong with the shape, or by behaviour that must not move while the code does.
26
+ const REFACTOR = new RegExp([
27
+ String.raw`\b(refactor\w*|clean ?up|tidy|untangle|simplify|decouple|extract|dedupe|deduplicate|rename|restructur\w*)\b`,
28
+ String.raw`\b(nearly|almost) (the same|identical)\b|\bduplicat\w+\b|\b(has )?grown into\b|\bkeeps growing\b|\bhard to (change|read|follow|maintain|test)\b|\bnobody dares\b`,
29
+ String.raw`\bmove (the |its )?\w+( \w+)? into\b|\bsplit (it|this|them|the \w+) into\b|\b(stays?|remains?) exactly (the same|as)\b|\bevery (caller|answer|result)\b[^.]{0,60}\bexactly\b`,
30
+ ].join('|'), 'i');
31
+
32
+ // Work kinds. One match decides; several conflicting matches go to the coordinator.
33
+ const KINDS = [
34
+ ['review', /^\s*(please |can you |could you )?(review|audit|assess|critique)\b|\bcode review\b|\breview (this|the|my|pr|#)|\bis this (ok|okay|right|safe|correct)\b/i],
35
+ ['ship', /\b(ship it|ship this|cut a release|open (a |the )?(pr|pull request)|prepare (a |the )?(release|pr|pull request)|ready to merge|release notes)\b/i],
36
+ ['upgrade', /\b(upgrade|bump|update)\b.{0,40}\b(dependenc\w*|version|package|library|framework|sdk|to v?\d)\b|\bdependabot\b|\bupgrade\b/i],
37
+ ['migrate', /\b(migrat\w*|schema change|backfill|move .{1,40} from .{1,40} to)\b/i],
38
+ ['perf', /\b(too slow|slow|performance|latency|optimi[sz]e|speed up|memory (leak|usage)|profil(ing|er)|throughput|n\+1)\b|\bprofile (it|this|the (code|app|service|query))\b/i],
39
+ ['refactor', REFACTOR],
40
+ ['debug', DEBUG],
41
+ ['discover', /\b(new product|greenfield|product idea|idea for a|competitors?|market research)\b/i],
42
+ ['design', /\b(design|architecture|how should we|adr|trade-?offs?|rfc|which approach|options for)\b/i],
43
+ ['atlas', /\b(map (the|this)|codebase overview|onboard\w*|atlas|blast radius|impact of)\b/i],
44
+ ['plan', /\b(plan (for|this|out|the|first)|roadmap|break (this|it) down|milestones?|epic)\b/i],
45
+ ];
46
+
47
+ // "Support keeps seeing" names the support team, not a feature to support.
48
+ const NEW_WORK = /^\s*(please )?(add|implement|create|support(?!\s+(team|staff|keeps|says|reports|sees|saw|tells|told|noticed)\b)|allow|let|show|make|write|build|send|store|translate|change|enable)\b/i;
49
+ // A ticket that asks for new behaviour in any sentence is not a bug report, however it describes what the feature handles.
50
+ const ASKS_NEW = /(^|[.!?:]\s+)(please )?(add|implement|create|allow|build|write)\b/i;
51
+ // A long ticket lists its own milestones and decisions, so plan and design words in it are structure. By WHEN, it is still build.
52
+ const LONG_SKIPS = new Set(['plan', 'design', 'discover', 'atlas']);
53
+ const TICKET_KEY = /^\s*[A-Z][A-Z0-9]+-\d+\s*$/;
54
+ const ANSWER = /\?\s*$|^\s*(what|why|how|where|when|who|which|does|do|is|are|can|explain|show me|list)\b/i;
55
+ const TICKET_TYPES = Object.freeze({ bug: 'debug', defect: 'debug', incident: 'incident', epic: 'plan', spike: 'design', story: 'build', task: 'build', feature: 'build', improvement: 'build' });
56
+
57
+ export const ROUTE_NAMES = Object.freeze([...new Set([...FIRST, ...KINDS].map(([r]) => r)), 'answer', 'build']);
58
+
59
+ // What the coordinator reads when it has to choose. Short, because it is read on the session's model.
60
+ export const LONG_REQUEST = 600;
61
+ export const WHEN = Object.freeze({
62
+ build: 'a new or changed feature, or anything clear, even a long ticket of many steps: the worker splits it if it proves too big',
63
+ debug: 'something behaves wrongly, and the cause is not known',
64
+ refactor: 'change structure and keep behaviour',
65
+ upgrade: 'move a dependency or runtime to another version',
66
+ migrate: 'change the shape of data already in use',
67
+ perf: 'make something faster or smaller',
68
+ incident: 'production is hurting right now',
69
+ accessibility: 'make an interface usable by everyone',
70
+ plan: 'the maintainer asks to see a plan first, or the order of the work needs approving',
71
+ design: 'settle an expensive-to-reverse choice',
72
+ discover: 'test a new product idea',
73
+ atlas: 'map the code or a change\'s blast radius',
74
+ answer: 'a question, with nothing to change',
75
+ review: 'judge existing changes',
76
+ 'security-review': 'judge changes for security',
77
+ ship: 'prepare a release or pull request',
78
+ });
79
+
80
+
81
+ // "Add retries for the usual error" asks for new behaviour: there is no bug to reproduce.
82
+ function matchedKinds(text, opening, long) {
83
+ const newWork = NEW_WORK.test(text) || ASKS_NEW.test(opening);
84
+ return KINDS.filter(([route, re]) => !(long && LONG_SKIPS.has(route)) && re.test(opening) && !(route === 'debug' && newWork)).map(([route]) => route);
85
+ }
86
+
87
+ export function classify({ request = '', ticket, hint } = {}) {
88
+ if (typeof hint === 'string' && ROUTE_NAMES.includes(hint)) return { route: hint, via: 'hint' };
89
+ const type = String(ticket?.type ?? '').trim().toLowerCase();
90
+ if (Object.hasOwn(TICKET_TYPES, type)) return { route: TICKET_TYPES[type], via: 'ticket' };
91
+ const text = String(request);
92
+ // A long ticket contains words like "fails", "incident" and "milestone" without being about them, so only its opening line can decide.
93
+ // A ticket opens with what it is about: "Bug report", a symptom, or the shape that needs changing.
94
+ const long = text.length > LONG_REQUEST;
95
+ const opening = long ? text.split('\n').find((l) => l.trim() !== '').slice(0, 200) : text;
96
+ for (const [route, re] of FIRST) if (re.test(opening)) return { route, via: 'rule' };
97
+ const matched = matchedKinds(text, opening, long);
98
+ if (matched.length === 1) return { route: matched[0], via: 'rule' };
99
+ if (matched.length > 1) return { route: null, via: 'choose', choices: matched };
100
+ return long ? { route: null, via: 'choose', choices: Object.keys(WHEN) } : unmatched(text);
101
+ }
102
+
103
+ // A request opening with a question word is asking something, unless it clearly names work to do.
104
+ function unmatched(text) {
105
+ if (ANSWER.test(text)) return { route: 'answer', via: 'rule' };
106
+ if (NEW_WORK.test(text) || TICKET_KEY.test(text)) return { route: 'build', via: 'rule' };
107
+ return { route: null, via: 'choose', choices: Object.keys(WHEN) };
108
+ }
@@ -0,0 +1,34 @@
1
+ // setup.mjs: makes SoMi's agent the session's agent, on the model the user chose for its tier. The model sits on the agent the session runs as,
2
+ // so it holds for every follow-up and the conversation is not interrupted to change it. Model names differ per environment, so shared
3
+ // plugin files carry none: this writes a file in the user's own agent folder, from the user's own config, and changes nothing else.
4
+
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { TIERS, mainTier, resolveSpawn } from './tiers.mjs';
9
+ import { StateError, refuseLink } from './state.mjs';
10
+
11
+ const body = (pluginRoot) => fs.readFileSync(path.join(pluginRoot, 'agents', 'somi.md'), 'utf8').replace(/^---\n[\s\S]*?\n---\n/, '').trim();
12
+ const DESCRIPTION = 'SoMi as the session agent, on the model set for its tier. It holds the conversation, routes work and keeps the cost down.';
13
+
14
+ export function setupAgent({ host, config = {}, pluginRoot, env = process.env, home = os.homedir() }) {
15
+ const tier = mainTier(config);
16
+ const { model } = resolveSpawn(config, host, tier);
17
+ const example = { tiers: { main: 'low', [host]: { low: '<cheap model>', medium: '<everyday model>', high: '<strongest model>' } } };
18
+ if (!model) return { written: false, reason: `no model is set for tier ${tier} on ${host}`, set_in_config: example };
19
+ const dir = host === 'copilot' ? path.join(env.COPILOT_HOME || path.join(home, '.copilot'), 'agents') : path.join(env.CLAUDE_CONFIG_DIR || path.join(home, '.claude'), 'agents');
20
+ const file = path.join(dir, host === 'copilot' ? 'somi-main.agent.md' : 'somi-main.md');
21
+ fs.mkdirSync(dir, { recursive: true });
22
+ if (refuseLink(file) && !fs.readFileSync(file, 'utf8').includes(DESCRIPTION)) throw new StateError(`${file} exists and is not SoMi's; move it first`);
23
+ fs.writeFileSync(file, `---\nname: somi-main\ndescription: "${DESCRIPTION}"\nmodel: ${model}\n---\n\n${body(pluginRoot)}\n`);
24
+ const missing = TIERS.filter((t) => !resolveSpawn(config, host, t).enforced);
25
+ return {
26
+ written: true,
27
+ file,
28
+ tier,
29
+ model,
30
+ start: host === 'copilot' ? 'copilot --agent somi-main' : 'claude --agent somi-main',
31
+ ...(host === 'claude' ? { note: 'Passing --model as well overrides this. To make it the default in a project, set "agent": "somi-main" in .claude/settings.local.json.' } : {}),
32
+ ...(missing.length > 0 ? { warning: `no model is set for tier ${missing.join(', ')} on ${host}, so work at those tiers runs on this session's model` } : {}),
33
+ };
34
+ }
@@ -0,0 +1,166 @@
1
+ // shards.mjs: another plugin's skill, agent or tool slotted into a named workflow step. `somi slot` inspects the plugin and writes a
2
+ // binding to config, and the named step reads its bindings when it is reached. There is no typed contract, because a model consumes the output and
3
+ // tolerates drift a schema would reject. The check is about what is safe:
4
+ // - a read binding that changed keeps working and says so, because it has to survive that plugin updating;
5
+ // - a missing component is stale, and is skipped with a notice;
6
+ // - a write binding whose content changed asks first. Outward writes always ask, whatever the hash says.
7
+ // Shard output is data, never instructions, and the brief says so where it is used.
8
+
9
+ import { createHash } from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { globalConfigPath } from './config-files.mjs';
14
+
15
+ export const SHARD_STEPS = Object.freeze(['work-item.start', 'plan.approved', 'pr.open', 'review.done']);
16
+ const MODES = Object.freeze(['read', 'write']);
17
+ const KINDS = Object.freeze(['skill', 'agent', 'command', 'tool']);
18
+ const REF = /^([A-Za-z0-9._-]+):([A-Za-z0-9._-]+)$/;
19
+ export class ShardError extends Error {}
20
+
21
+ // Config is repository content, and these fields reach a worker's brief and session context, so only the exact shape is believed.
22
+ const isBinding = (b) => b !== null && typeof b === 'object' && SHARD_STEPS.includes(b.step) && typeof b.ref === 'string' && REF.test(b.ref) && MODES.includes(b.mode) && KINDS.includes(b.kind);
23
+ const asList = (v) => (Array.isArray(v) ? v : []);
24
+
25
+ const sha = (text) => createHash('sha256').update(text).digest('hex');
26
+
27
+ function pluginDirs(env, home) {
28
+ const out = [];
29
+ const extra = env.SOMI_PLUGIN_DIRS;
30
+ if (extra) out.push(...extra.split(path.delimiter).filter(Boolean));
31
+ for (const root of [path.join(home, '.claude', 'plugins'), path.join(home, '.copilot', 'installed-plugins')]) {
32
+ const walk = (dir, depth) => {
33
+ let entries;
34
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
35
+ if (entries.some((e) => e.name === '.claude-plugin' || e.name === '.copilot-extension' || e.name === 'plugin.json')) out.push(dir);
36
+ if (depth > 0) for (const e of entries) if (e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules') walk(path.join(dir, e.name), depth - 1);
37
+ };
38
+ walk(root, 5);
39
+ }
40
+ return out;
41
+ }
42
+
43
+ function pluginName(dir) {
44
+ for (const f of ['.claude-plugin/plugin.json', '.copilot-extension/extension.json', 'plugin.json']) {
45
+ try {
46
+ const j = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'));
47
+ if (typeof j.name === 'string') return { name: j.name, version: String(j.version ?? 'unknown') };
48
+ } catch { /* try the next manifest */ }
49
+ }
50
+ return { name: path.basename(dir), version: 'unknown' };
51
+ }
52
+
53
+ function findComponent(dir, component) {
54
+ const candidates = [
55
+ ['skill', `skills/${component}/SKILL.md`],
56
+ ['agent', `agents/${component}.md`],
57
+ ['agent', `agents/${component}.agent.md`],
58
+ ['command', `commands/${component}.md`],
59
+ ['tool', '.mcp.json'],
60
+ ['tool', 'mcp.json'],
61
+ ];
62
+ for (const [kind, rel] of candidates) {
63
+ const file = path.join(dir, rel);
64
+ if (!fs.existsSync(file)) continue;
65
+ const text = fs.readFileSync(file, 'utf8');
66
+ if (kind === 'tool' && !text.includes(`"${component}"`)) continue;
67
+ return { kind, file, text };
68
+ }
69
+ return null;
70
+ }
71
+
72
+ // The newest installed copy wins when a plugin is present more than once, as it is across cached versions.
73
+ function locate(ref, env, home) {
74
+ const m = REF.exec(ref);
75
+ if (!m) throw new ShardError('a shard is named plugin:component');
76
+ const hits = pluginDirs(env, home).map((dir) => ({ dir, ...pluginName(dir) })).filter((p) => p.name === m[1]);
77
+ if (hits.length === 0) return null;
78
+ const sorted = hits.sort((a, b) => b.version.localeCompare(a.version, undefined, { numeric: true }));
79
+ for (const plugin of sorted) {
80
+ const c = findComponent(plugin.dir, m[2]);
81
+ if (c) return { ...c, version: plugin.version };
82
+ }
83
+ return null;
84
+ }
85
+
86
+ const readJson = (file) => { if (file === null) return {}; try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { if (e.code === 'ENOENT') return {}; throw new ShardError(`${file} is not valid JSON`); } };
87
+ function writeJson(file, value) {
88
+ if (file === null) throw new ShardError('no global config file is set here; use --project');
89
+ fs.mkdirSync(path.dirname(file), { recursive: true });
90
+ if (fs.existsSync(file) && fs.lstatSync(file).isSymbolicLink()) throw new ShardError(`refusing to write through a link at ${file}`);
91
+ const tmp = `${file}.${process.pid}.tmp`;
92
+ fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`);
93
+ fs.renameSync(tmp, file);
94
+ }
95
+
96
+ const configFile = (root, env, project) => (project ? path.join(root, '.somi', 'config.json') : globalConfigPath(env));
97
+
98
+ export function slot({ root, step, ref, mode = 'read', project = false, env = process.env, home = os.homedir(), now }) {
99
+ if (!SHARD_STEPS.includes(step)) throw new ShardError(`a shard slots into one of: ${SHARD_STEPS.join(', ')}`);
100
+ if (!MODES.includes(mode)) throw new ShardError('a shard mode is read or write');
101
+ const found = locate(ref, env, home);
102
+ if (!found) throw new ShardError(`${ref} is not installed; install the plugin first, because SoMi never installs one for you`);
103
+ const file = configFile(root, env, project);
104
+ const config = readJson(file);
105
+ const binding = { step, ref, kind: found.kind, mode, version: found.version, sha256: sha(found.text), bound_at: now };
106
+ config.shards = [...asList(config.shards).filter((b) => !(b?.step === step && b?.ref === ref)), binding];
107
+ writeJson(file, config);
108
+ return { slotted: ref, step, kind: found.kind, mode, version: found.version, scope: project ? 'project' : 'global' };
109
+ }
110
+
111
+ export function unslot({ root, step, ref, project = false, env = process.env }) {
112
+ const file = configFile(root, env, project);
113
+ const config = readJson(file);
114
+ const before = asList(config.shards);
115
+ config.shards = before.filter((b) => !(b?.step === step && b?.ref === ref));
116
+ writeJson(file, config);
117
+ return { removed: before.length - config.shards.length };
118
+ }
119
+
120
+ // A committed project binding runs another plugin because someone edited a file, so it needs one confirmation per project and binding.
121
+ const confirmKey = (root, b) => sha(`${path.resolve(root)}|${b.step}|${b.ref}|${b.mode}|${b.kind}`);
122
+ // Confirming accepts the plugin as it is now: a project binding is allowed to run, and a changed one is pinned to its current content.
123
+ export function confirmProjectShards({ root, env = process.env, home = os.homedir() }) {
124
+ const projectFile = configFile(root, env, true);
125
+ const project = readJson(projectFile);
126
+ const file = configFile(root, env, false);
127
+ const global = readJson(file);
128
+ const refresh = (b) => {
129
+ if (!isBinding(b)) return b;
130
+ const found = locate(b.ref, env, home);
131
+ return found ? { ...b, kind: found.kind, version: found.version, sha256: sha(found.text) } : b;
132
+ };
133
+ const pinned = asList(project.shards).map(refresh);
134
+ if (pinned.length > 0 && JSON.stringify(pinned) !== JSON.stringify(project.shards)) writeJson(projectFile, { ...project, shards: pinned });
135
+ const keys = pinned.filter(isBinding).map((b) => confirmKey(root, b));
136
+ writeJson(file, { ...global, shards: asList(global.shards).map(refresh), shard_confirmations: [...new Set([...asList(global.shard_confirmations), ...keys])] });
137
+ return { confirmed: keys.length };
138
+ }
139
+
140
+ // Every binding with its current state: ok, changed, stale or unconfirmed.
141
+ export function listShards({ root, env = process.env, home = os.homedir() }) {
142
+ const global = readJson(configFile(root, env, false));
143
+ const project = readJson(configFile(root, env, true));
144
+ const confirmed = new Set(asList(global.shard_confirmations));
145
+ const inspect = (b, scope) => {
146
+ if (!isBinding(b)) return { step: SHARD_STEPS.includes(b?.step) ? b.step : 'unknown', ref: '(invalid binding)', mode: 'read', scope, state: 'invalid' };
147
+ if (scope === 'project' && !confirmed.has(confirmKey(root, b))) return { ...b, scope, state: 'unconfirmed' };
148
+ let found = null;
149
+ try { found = locate(b.ref, env, home); } catch { /* an unusable name counts as stale */ }
150
+ if (!found) return { ...b, scope, state: 'stale' };
151
+ return { ...b, scope, state: sha(found.text) === b.sha256 ? 'ok' : 'changed', current_version: found.version };
152
+ };
153
+ return [
154
+ ...asList(global.shards).map((b) => inspect(b, 'global')),
155
+ ...asList(project.shards).map((b) => inspect(b, 'project')),
156
+ ];
157
+ }
158
+
159
+ export function shardsFor({ root, step, env = process.env, home = os.homedir() }) {
160
+ const here = listShards({ root, env, home }).filter((b) => b.step === step);
161
+ return {
162
+ usable: here.filter((b) => b.state === 'ok' || (b.state === 'changed' && b.mode === 'read')),
163
+ held: here.filter((b) => b.state === 'changed' && b.mode === 'write'),
164
+ skipped: here.filter((b) => b.state === 'stale' || b.state === 'unconfirmed' || b.state === 'invalid'),
165
+ };
166
+ }