@skathio/somi 4.1.1 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +8 -3
  3. package/.claude-plugin/plugin.json +9 -10
  4. package/.copilot-extension/extension.json +32 -40
  5. package/.copilot-extension/marketplace.json +8 -3
  6. package/README.md +88 -227
  7. package/VERSION +1 -1
  8. package/agents/somi-reviewer.md +21 -40
  9. package/agents/somi-security-reviewer.md +16 -90
  10. package/agents/somi-worker-high.md +11 -0
  11. package/agents/somi-worker-low.md +11 -0
  12. package/agents/somi-worker-medium.md +11 -0
  13. package/agents/somi.md +8 -75
  14. package/commands/somi-config.md +5 -14
  15. package/commands/somi-deliver.md +11 -0
  16. package/commands/somi-quality.md +10 -0
  17. package/commands/somi-review.md +10 -0
  18. package/commands/somi-status.md +11 -0
  19. package/commands/somi.md +10 -0
  20. package/hooks/hooks.json +29 -23
  21. package/hooks/lib/common.mjs +45 -34
  22. package/hooks/pre-tool/apply-tier.mjs +31 -0
  23. package/hooks/pre-tool/block-dangerous-bash.mjs +15 -0
  24. package/hooks/pre-tool/gate-dep-install.mjs +2 -2
  25. package/hooks/pre-tool/guard-protected-paths.mjs +9 -16
  26. package/hooks/pre-tool/guard-tier-config.mjs +17 -0
  27. package/hooks/pre-tool/reviewers-read-only.mjs +11 -0
  28. package/hooks/session-start/inject-digest.mjs +51 -0
  29. package/hooks/stop/review-due.mjs +44 -0
  30. package/hooks/user-prompt/capture-prompt.mjs +17 -0
  31. package/library/lenses/architecture.md +1 -0
  32. package/library/lenses/test-strategy.md +1 -0
  33. package/library/roles/accessibility.md +1 -0
  34. package/library/roles/answer.md +1 -0
  35. package/library/roles/atlas.md +1 -0
  36. package/library/roles/build.md +1 -0
  37. package/library/roles/debug.md +6 -0
  38. package/library/roles/design.md +1 -0
  39. package/library/roles/discover.md +1 -0
  40. package/library/roles/incident.md +1 -0
  41. package/library/roles/migrate.md +1 -0
  42. package/library/roles/perf.md +1 -0
  43. package/library/roles/plan.md +1 -0
  44. package/library/roles/refactor.md +1 -0
  45. package/library/roles/review.md +1 -0
  46. package/library/roles/security-review.md +1 -0
  47. package/library/roles/upgrade.md +1 -0
  48. package/library/skills/accessibility.md +16 -0
  49. package/library/skills/ci-infra-gotchas.md +12 -0
  50. package/library/skills/perf-method.md +10 -0
  51. package/library/skills/secure-coding.md +18 -0
  52. package/library/skills/testing-checklist.md +16 -0
  53. package/library/skills/threat-modeling.md +10 -0
  54. package/package.json +12 -17
  55. package/profiles/claude.json +21 -0
  56. package/profiles/copilot.json +5 -0
  57. package/rules/digest.md +40 -0
  58. package/scripts/check-links.mjs +65 -76
  59. package/scripts/lib/advisor.mjs +207 -0
  60. package/scripts/lib/check.mjs +167 -0
  61. package/scripts/lib/copilot-workflow.mjs +41 -0
  62. package/scripts/lib/doctor.mjs +91 -0
  63. package/scripts/lib/gates.mjs +69 -0
  64. package/scripts/lib/git-tree.mjs +201 -0
  65. package/scripts/lib/init.mjs +23 -0
  66. package/scripts/lib/ledger.mjs +38 -0
  67. package/scripts/lib/mcp-project-root.mjs +63 -67
  68. package/scripts/lib/migrate.mjs +73 -0
  69. package/scripts/lib/path-facts.mjs +2 -2
  70. package/scripts/lib/path-safety.mjs +6 -134
  71. package/scripts/lib/plan.mjs +69 -0
  72. package/scripts/lib/policy.mjs +103 -0
  73. package/scripts/lib/pr.mjs +28 -0
  74. package/scripts/lib/prompt.mjs +72 -0
  75. package/scripts/lib/quality/clones.mjs +76 -0
  76. package/scripts/lib/quality/css.mjs +43 -0
  77. package/scripts/lib/quality/gate.mjs +230 -0
  78. package/scripts/lib/quality/limits.mjs +97 -0
  79. package/scripts/lib/quality/metrics.mjs +159 -0
  80. package/scripts/lib/quality/parse.mjs +73 -0
  81. package/scripts/lib/quality/repo.mjs +69 -0
  82. package/scripts/lib/quality/run.mjs +58 -0
  83. package/scripts/lib/reviews.mjs +132 -0
  84. package/scripts/lib/routes.mjs +108 -0
  85. package/scripts/lib/setup.mjs +34 -0
  86. package/scripts/lib/shards.mjs +166 -0
  87. package/scripts/lib/signals.mjs +110 -0
  88. package/scripts/lib/state.mjs +42 -0
  89. package/scripts/lib/tiers.mjs +42 -0
  90. package/scripts/lib/update-notice.mjs +48 -0
  91. package/scripts/lib/views.mjs +62 -0
  92. package/scripts/lib/workflows.mjs +56 -0
  93. package/scripts/somi-mcp.mjs +182 -323
  94. package/scripts/somi.mjs +208 -0
  95. package/scripts/vendor/tree-sitter/LICENSE.vscode-tree-sitter-wasm +21 -0
  96. package/scripts/vendor/tree-sitter/LICENSE.web-tree-sitter +21 -0
  97. package/scripts/vendor/tree-sitter/cgmanifest.vscode-tree-sitter-wasm.json +16 -0
  98. package/scripts/vendor/tree-sitter/manifest.json +59 -0
  99. package/scripts/vendor/tree-sitter/package.json +3 -0
  100. package/scripts/vendor/tree-sitter/tree-sitter-css.wasm +0 -0
  101. package/scripts/vendor/tree-sitter/tree-sitter-javascript.wasm +0 -0
  102. package/scripts/vendor/tree-sitter/tree-sitter-tsx.wasm +0 -0
  103. package/scripts/vendor/tree-sitter/tree-sitter-typescript.wasm +0 -0
  104. package/scripts/vendor/tree-sitter/web-tree-sitter.js +4081 -0
  105. package/scripts/vendor/tree-sitter/web-tree-sitter.wasm +0 -0
  106. package/skills/somi-expertise/SKILL.md +6 -0
  107. package/workflows/deliver-stages.js +81 -0
  108. package/.claude/settings.json +0 -131
  109. package/agents/somi-architecture-reviewer.md +0 -101
  110. package/agents/somi-atlas.md +0 -100
  111. package/agents/somi-coder.md +0 -60
  112. package/agents/somi-designer.md +0 -36
  113. package/agents/somi-discovery-analyst.md +0 -57
  114. package/agents/somi-flow.md +0 -47
  115. package/agents/somi-general.md +0 -36
  116. package/agents/somi-impact.md +0 -95
  117. package/agents/somi-incident.md +0 -94
  118. package/agents/somi-plan-reviewer.md +0 -68
  119. package/agents/somi-planner.md +0 -57
  120. package/agents/somi-pr.md +0 -99
  121. package/agents/somi-refactor-designer.md +0 -81
  122. package/agents/somi-refactorer.md +0 -99
  123. package/agents/somi-sdlc-reviewer.md +0 -67
  124. package/agents/somi-test-strategist.md +0 -87
  125. package/commands/adopt.md +0 -14
  126. package/commands/architecture-review.md +0 -19
  127. package/commands/atlas.md +0 -19
  128. package/commands/code-loop.md +0 -19
  129. package/commands/code-parallel.md +0 -19
  130. package/commands/code.md +0 -19
  131. package/commands/debug.md +0 -19
  132. package/commands/design.md +0 -19
  133. package/commands/discover.md +0 -19
  134. package/commands/impact.md +0 -19
  135. package/commands/incident.md +0 -19
  136. package/commands/plan-loop.md +0 -19
  137. package/commands/plan.md +0 -19
  138. package/commands/pr.md +0 -19
  139. package/commands/refactor-design.md +0 -19
  140. package/commands/refactor.md +0 -19
  141. package/commands/release-readiness.md +0 -19
  142. package/commands/review-panel.md +0 -19
  143. package/commands/review.md +0 -19
  144. package/commands/security-review.md +0 -19
  145. package/commands/ship-loop.md +0 -19
  146. package/commands/ship.md +0 -19
  147. package/commands/test-strategy.md +0 -19
  148. package/commands/upgrade.md +0 -19
  149. package/examples/README.md +0 -19
  150. package/examples/code-review-example.md +0 -88
  151. package/examples/discovery-example.md +0 -200
  152. package/examples/feature-plan-example.md +0 -377
  153. package/examples/full-pipeline-example.md +0 -188
  154. package/examples/sample-consumer/.claude/settings.json +0 -29
  155. package/examples/sample-consumer/CLAUDE.md +0 -78
  156. package/examples/sample-consumer/README.md +0 -102
  157. package/hooks/post-tool/lint-changed-files.mjs +0 -209
  158. package/hooks/pre-tool/guard-cost-lowering.mjs +0 -192
  159. package/hooks/session-start/detect-repo-instructions.mjs +0 -287
  160. package/hooks/session-start/ensure-default-config.mjs +0 -113
  161. package/hooks/user-prompt-submit/inject-workflow-context.mjs +0 -580
  162. package/rules/00-priorities.md +0 -48
  163. package/rules/10-solid.md +0 -87
  164. package/rules/20-clean-code.md +0 -62
  165. package/rules/30-security-owasp.md +0 -83
  166. package/rules/40-engineering-practices.md +0 -65
  167. package/rules/50-collaboration.md +0 -114
  168. package/rules/99-overrides.md +0 -52
  169. package/rules/CLAUDE.md +0 -200
  170. package/scripts/check-session-artefacts.mjs +0 -149
  171. package/scripts/check-size-budget.mjs +0 -137
  172. package/scripts/generate-digest.mjs +0 -176
  173. package/scripts/lib/agent-info.mjs +0 -85
  174. package/scripts/lib/agent-registry.mjs +0 -92
  175. package/scripts/lib/cost-ceiling.mjs +0 -328
  176. package/scripts/lib/cost-config-edit.mjs +0 -102
  177. package/scripts/lib/cost-config.mjs +0 -64
  178. package/scripts/lib/cost-defaults.mjs +0 -53
  179. package/scripts/lib/cost-lowering.mjs +0 -89
  180. package/scripts/lib/cost-model.mjs +0 -110
  181. package/scripts/lib/dispatch-resolver.mjs +0 -243
  182. package/scripts/lib/escalation-facts.mjs +0 -146
  183. package/scripts/lib/escalation.mjs +0 -129
  184. package/scripts/lib/findings-ledger.mjs +0 -241
  185. package/scripts/lib/install-text.mjs +0 -97
  186. package/scripts/lib/loop-caps.mjs +0 -140
  187. package/scripts/lib/loop-diff.mjs +0 -38
  188. package/scripts/lib/loop-dispatch.mjs +0 -19
  189. package/scripts/lib/loop-engine.mjs +0 -227
  190. package/scripts/lib/loop-escalate.mjs +0 -49
  191. package/scripts/lib/loop-exit.mjs +0 -47
  192. package/scripts/lib/loop-notes-compact.mjs +0 -72
  193. package/scripts/lib/loop-notes.mjs +0 -282
  194. package/scripts/lib/loop-review.mjs +0 -395
  195. package/scripts/lib/loop-state.mjs +0 -44
  196. package/scripts/lib/loop-step-close.mjs +0 -75
  197. package/scripts/lib/loop-step-kit.mjs +0 -179
  198. package/scripts/lib/loop-step-review.mjs +0 -140
  199. package/scripts/lib/loop-step-tool.mjs +0 -89
  200. package/scripts/lib/loop-step.mjs +0 -303
  201. package/scripts/lib/run-budget.mjs +0 -28
  202. package/scripts/lib/run-card.mjs +0 -73
  203. package/scripts/lib/size-tier.mjs +0 -184
  204. package/scripts/lib/tier-record.mjs +0 -82
  205. package/scripts/size-budget-overrides.json +0 -58
  206. package/scripts/somi-card.mjs +0 -39
  207. package/scripts/somi-check.mjs +0 -237
  208. package/scripts/somi-config.mjs +0 -421
  209. package/scripts/somi-dispatch.mjs +0 -141
  210. package/scripts/somi-findings.mjs +0 -100
  211. package/scripts/somi-loop.mjs +0 -139
  212. package/scripts/somi-tier.mjs +0 -393
  213. package/scripts/validate.sh +0 -653
  214. package/skills/api-design/SKILL.md +0 -147
  215. package/skills/clean-code/SKILL.md +0 -142
  216. package/skills/flow-adopt/SKILL.md +0 -92
  217. package/skills/flow-architecture-review/SKILL.md +0 -94
  218. package/skills/flow-atlas/SKILL.md +0 -34
  219. package/skills/flow-code/SKILL.md +0 -167
  220. package/skills/flow-code-loop/SKILL.md +0 -263
  221. package/skills/flow-code-parallel/SKILL.md +0 -160
  222. package/skills/flow-debug/SKILL.md +0 -141
  223. package/skills/flow-design/SKILL.md +0 -170
  224. package/skills/flow-discover/SKILL.md +0 -204
  225. package/skills/flow-impact/SKILL.md +0 -35
  226. package/skills/flow-incident/SKILL.md +0 -49
  227. package/skills/flow-plan/SKILL.md +0 -254
  228. package/skills/flow-plan-loop/SKILL.md +0 -254
  229. package/skills/flow-pr/SKILL.md +0 -34
  230. package/skills/flow-refactor/SKILL.md +0 -58
  231. package/skills/flow-refactor-design/SKILL.md +0 -97
  232. package/skills/flow-release-readiness/SKILL.md +0 -82
  233. package/skills/flow-review/SKILL.md +0 -193
  234. package/skills/flow-review-panel/SKILL.md +0 -154
  235. package/skills/flow-security-review/SKILL.md +0 -83
  236. package/skills/flow-ship/SKILL.md +0 -125
  237. package/skills/flow-ship-loop/SKILL.md +0 -274
  238. package/skills/flow-somi-config/SKILL.md +0 -142
  239. package/skills/flow-status/SKILL.md +0 -43
  240. package/skills/flow-test-strategy/SKILL.md +0 -83
  241. package/skills/flow-upgrade/SKILL.md +0 -82
  242. package/skills/market-research/SKILL.md +0 -125
  243. package/skills/observability/SKILL.md +0 -133
  244. package/skills/owasp-defense/SKILL.md +0 -141
  245. package/skills/plan-review/SKILL.md +0 -83
  246. package/skills/reasoning-craft/SKILL.md +0 -213
  247. package/skills/requirements-engineering/SKILL.md +0 -137
  248. package/skills/role-coder/SKILL.md +0 -247
  249. package/skills/role-designer/SKILL.md +0 -172
  250. package/skills/role-discovery-analyst/SKILL.md +0 -288
  251. package/skills/role-planner/SKILL.md +0 -353
  252. package/skills/role-reviewer/SKILL.md +0 -218
  253. package/skills/rules/SKILL.md +0 -47
  254. package/skills/sdlc-process/SKILL.md +0 -74
  255. package/skills/solid-principles/SKILL.md +0 -143
  256. package/skills/somi-checkpoint/SKILL.md +0 -95
  257. package/skills/somi-dispatch/SKILL.md +0 -259
  258. package/skills/somi-routing/SKILL.md +0 -158
  259. package/skills/testing-playbook/SKILL.md +0 -133
  260. package/skills/threat-modeling/SKILL.md +0 -117
  261. package/templates/ADR.md.tmpl +0 -73
  262. package/templates/ATLAS.md.tmpl +0 -75
  263. package/templates/BRD.md.tmpl +0 -68
  264. package/templates/BRIEF.md.tmpl +0 -119
  265. package/templates/CONTEXT.md.tmpl +0 -74
  266. package/templates/DECISIONS.md.tmpl +0 -105
  267. package/templates/DESIGN.md.tmpl +0 -83
  268. package/templates/DIARY.md.tmpl +0 -70
  269. package/templates/DOD.md.tmpl +0 -90
  270. package/templates/FRD.md.tmpl +0 -64
  271. package/templates/PHASE.md.tmpl +0 -80
  272. package/templates/PROGRESS.md.tmpl +0 -63
  273. package/templates/RCA.md.tmpl +0 -53
  274. package/templates/RD-README.md.tmpl +0 -70
  275. package/templates/RESEARCH.md.tmpl +0 -96
  276. package/templates/REVIEW.md.tmpl +0 -82
  277. package/templates/SDD.md.tmpl +0 -82
  278. package/templates/SOMI-README.md.tmpl +0 -83
  279. package/templates/SPEC.md.tmpl +0 -123
  280. package/templates/SRS.md.tmpl +0 -85
  281. package/templates/TDD.md.tmpl +0 -77
  282. package/tests/hooks/cases/audit-log.json +0 -21
  283. package/tests/hooks/cases/block-dangerous-bash.json +0 -166
  284. package/tests/hooks/cases/block-secret-writes.json +0 -140
  285. package/tests/hooks/cases/detect-repo-instructions.json +0 -105
  286. package/tests/hooks/cases/gate-dep-install.json +0 -42
  287. package/tests/hooks/cases/guard-protected-paths.json +0 -222
  288. package/tests/hooks/cases/inject-workflow-context.json +0 -239
  289. package/tests/hooks/cases/lint-changed-files.json +0 -120
  290. package/tests/hooks/run.sh +0 -392
  291. package/tests/scripts/agent-model-frontmatter.sh +0 -38
  292. package/tests/scripts/agent-names.sh +0 -77
  293. package/tests/scripts/check-frontmatter.sh +0 -37
  294. package/tests/scripts/check-links.sh +0 -105
  295. package/tests/scripts/check-session-artefacts.sh +0 -60
  296. package/tests/scripts/check-size-budget.sh +0 -71
  297. package/tests/scripts/checkpoint-gate.sh +0 -131
  298. package/tests/scripts/convergence-runner.sh +0 -1514
  299. package/tests/scripts/cost-ceiling.sh +0 -255
  300. package/tests/scripts/cost-defaults.sh +0 -130
  301. package/tests/scripts/cost-hardcap.sh +0 -338
  302. package/tests/scripts/cost-lowering.sh +0 -261
  303. package/tests/scripts/cost-model.sh +0 -196
  304. package/tests/scripts/dispatch-guard.sh +0 -108
  305. package/tests/scripts/dispatch-line-gate.sh +0 -61
  306. package/tests/scripts/dispatch-reference-gate.sh +0 -173
  307. package/tests/scripts/ensure-default-config.sh +0 -162
  308. package/tests/scripts/escalation.sh +0 -409
  309. package/tests/scripts/eval-runner.sh +0 -3692
  310. package/tests/scripts/evals-packaging.sh +0 -224
  311. package/tests/scripts/fact-sheet.sh +0 -296
  312. package/tests/scripts/fixtures/legacy-shard-no-schema.json +0 -50
  313. package/tests/scripts/fixtures/mock-stdin-read-throw.cjs +0 -18
  314. package/tests/scripts/fixtures/size-tier-cases.json +0 -87
  315. package/tests/scripts/generate-digest.sh +0 -180
  316. package/tests/scripts/global-config.sh +0 -167
  317. package/tests/scripts/goldens/loop-state-breach.json +0 -1
  318. package/tests/scripts/goldens/loop-state-done.json +0 -1
  319. package/tests/scripts/goldens/somi-findings.json +0 -336
  320. package/tests/scripts/goldens/somi-loop.json +0 -168
  321. package/tests/scripts/lib/adr-shape.mjs +0 -41
  322. package/tests/scripts/lib/agent-registry-tests.mjs +0 -95
  323. package/tests/scripts/lib/brief-only-guard.mjs +0 -27
  324. package/tests/scripts/lib/checkpoint-gate.mjs +0 -91
  325. package/tests/scripts/lib/digest-marker-coupling.mjs +0 -52
  326. package/tests/scripts/lib/dispatch-reference-gate.mjs +0 -121
  327. package/tests/scripts/lib/escalation-facts-tests.mjs +0 -140
  328. package/tests/scripts/lib/escalation-tests.mjs +0 -154
  329. package/tests/scripts/lib/findings-ledger-tests.mjs +0 -118
  330. package/tests/scripts/lib/loop-engine-tests.mjs +0 -287
  331. package/tests/scripts/lib/loop-escalate-tests.mjs +0 -356
  332. package/tests/scripts/lib/loop-flow-gate.mjs +0 -173
  333. package/tests/scripts/lib/loop-notes-tests.mjs +0 -384
  334. package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -156
  335. package/tests/scripts/lib/loop-step-close-tests.mjs +0 -351
  336. package/tests/scripts/lib/loop-step-lenient-tests.mjs +0 -114
  337. package/tests/scripts/lib/loop-step-state-tests.mjs +0 -127
  338. package/tests/scripts/lib/loop-step-tests.mjs +0 -499
  339. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +0 -55
  340. package/tests/scripts/lib/multipass-dependence.mjs +0 -192
  341. package/tests/scripts/lib/multipass-source-identity.mjs +0 -243
  342. package/tests/scripts/lib/path-facts-tests.mjs +0 -198
  343. package/tests/scripts/lib/path-safety-tests.mjs +0 -201
  344. package/tests/scripts/lib/reference-pair.mjs +0 -61
  345. package/tests/scripts/lib/retirement-gate.mjs +0 -172
  346. package/tests/scripts/lib/run-suites.mjs +0 -139
  347. package/tests/scripts/lib/shell-embedded-js.mjs +0 -47
  348. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +0 -52
  349. package/tests/scripts/lib/site-roadmap-gate.mjs +0 -64
  350. package/tests/scripts/lib/size-tier-drift.mjs +0 -74
  351. package/tests/scripts/lib/sizing-score-tests.mjs +0 -210
  352. package/tests/scripts/lib/sizing-set-tests.mjs +0 -131
  353. package/tests/scripts/lib/somi-mcp-client.mjs +0 -102
  354. package/tests/scripts/lib/somi-mcp-config-tests.mjs +0 -92
  355. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +0 -226
  356. package/tests/scripts/lib/somi-mcp-tests.mjs +0 -491
  357. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +0 -64
  358. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +0 -38
  359. package/tests/scripts/loop-engine.sh +0 -22
  360. package/tests/scripts/loop-flow-gate.sh +0 -11
  361. package/tests/scripts/retirement-gate.sh +0 -306
  362. package/tests/scripts/review-panel-seats.sh +0 -32
  363. package/tests/scripts/run-card.sh +0 -57
  364. package/tests/scripts/run-suites.sh +0 -74
  365. package/tests/scripts/run.sh +0 -689
  366. package/tests/scripts/site-roadmap-gate.sh +0 -76
  367. package/tests/scripts/size-tier.sh +0 -562
  368. package/tests/scripts/somi-agent-dispatch-contract.sh +0 -224
  369. package/tests/scripts/somi-config.sh +0 -286
  370. package/tests/scripts/somi-dispatch.sh +0 -465
  371. package/tests/scripts/somi-mcp.sh +0 -15
  372. package/tests/scripts/suite-plan.json +0 -20
@@ -0,0 +1,72 @@
1
+ // prompt.mjs: the user's messages, word for word, as a hook saw them arrive. The agent's own summary of a request can lose the words
2
+ // that mark it as sensitive, or the detail a worker needs, so routing and briefs read these too. A worker or a workflow stage starts
3
+ // with none of the conversation, so the earlier messages of the same session go with it: a decision stated once at the start still
4
+ // holds when the fourth message is built. Everything lives under the state folder and never leaves the machine.
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { statePaths, writeStateFile } from './state.mjs';
9
+
10
+ export const MAX_PROMPT_BYTES = 65536;
11
+ export const MAX_HISTORY_BYTES = 65536;
12
+ export const MAX_HISTORY = 24;
13
+ const file = (root, env) => path.join(statePaths(root, env).dir, 'prompt.txt');
14
+ const historyFile = (root, env) => path.join(statePaths(root, env).dir, 'prompts.json');
15
+ const clip = (text, bytes) => Buffer.from(text).subarray(0, bytes).toString();
16
+ const quote = (text) => String(text).trim().split('\n').map((l) => `> ${l}`).join('\n');
17
+
18
+ // A host delivers some of its own notices as a new user turn, such as a background task finishing. Those are not the user's words.
19
+ export const isHostNotice = (text) => /^\s*<(task-notification|system-reminder)>/.test(text);
20
+
21
+ export function savePrompt(root, text, env = process.env, { session } = {}) {
22
+ if (typeof text !== 'string' || text.trim() === '' || isHostNotice(text)) return false;
23
+ const kept = clip(text, MAX_PROMPT_BYTES);
24
+ writeStateFile(root, file(root, env), kept, env);
25
+ // With no session id there is no telling one conversation from the next, so nothing is carried over.
26
+ const id = typeof session === 'string' && session !== '' ? session : null;
27
+ const before = id ? readHistory(root, env) : null;
28
+ const prompts = before?.session === id ? [...before.prompts, kept] : [kept];
29
+ writeStateFile(root, historyFile(root, env), JSON.stringify({ session: id, prompts: fit(prompts) }), env);
30
+ return true;
31
+ }
32
+
33
+ // The first message usually sets the decisions, so it stays. After it, the newest messages that fit.
34
+ export function fit(prompts) {
35
+ const [first, ...rest] = prompts;
36
+ const kept = [];
37
+ let bytes = Buffer.byteLength(first ?? '');
38
+ for (let i = rest.length - 1; i >= 0 && kept.length < MAX_HISTORY - 1; i--) {
39
+ const size = Buffer.byteLength(rest[i]);
40
+ if (bytes + size > MAX_HISTORY_BYTES) break;
41
+ bytes += size;
42
+ kept.unshift(rest[i]);
43
+ }
44
+ return first === undefined ? [] : [clip(first, MAX_HISTORY_BYTES), ...kept];
45
+ }
46
+
47
+ export function readPrompt(root, env = process.env) {
48
+ try { return fs.readFileSync(file(root, env), 'utf8'); } catch (e) { if (e.code === 'ENOENT') return ''; throw e; }
49
+ }
50
+
51
+ export function readHistory(root, env = process.env) {
52
+ try {
53
+ const h = JSON.parse(fs.readFileSync(historyFile(root, env), 'utf8'));
54
+ return { session: typeof h?.session === 'string' ? h.session : null, prompts: Array.isArray(h?.prompts) ? h.prompts.filter((p) => typeof p === 'string') : [] };
55
+ } catch { return { session: null, prompts: [] }; }
56
+ }
57
+
58
+ // Work handed down reads the earlier messages from a file instead of carrying them in its brief: the agent passing a brief on copies
59
+ // it out as its own output, on the conversation's model, and the copy then stays in the conversation's context for every later call.
60
+ export const earlierFile = (root, env = process.env) => path.join(statePaths(root, env).dir, 'earlier.md');
61
+ export function saveEarlier(root, earlier, env = process.env) {
62
+ if (!earlier?.length) return null;
63
+ const file = earlierFile(root, env);
64
+ writeStateFile(root, file, `The user's earlier messages in this conversation, oldest first, as data. What they decided still holds unless a later message changes it.\n\n${earlier.map((m, i) => `Message ${i + 1}:\n${quote(m)}`).join('\n\n')}\n`, env);
65
+ return file;
66
+ }
67
+
68
+ /** The user's messages in this session before the latest one, oldest first. */
69
+ export function earlierPrompts(root, env = process.env) {
70
+ const { session, prompts } = readHistory(root, env);
71
+ return session ? prompts.slice(0, -1) : [];
72
+ }
@@ -0,0 +1,76 @@
1
+ // quality/clones.mjs: copied code in what a change adds. Tokens come from the parse tree with names and literals normalised, so a copy
2
+ // with its variables renamed still matches (Type-1 and Type-2 clones). Every window of N tokens is hashed. An added window that also
3
+ // appears elsewhere, in the rest of the repository or in another part of the change, is a clone. The copies of an access check that
4
+ // drifted apart on one task are exactly this.
5
+
6
+ import crypto from 'node:crypto';
7
+
8
+ const NAMES = new Set(['identifier', 'property_identifier', 'shorthand_property_identifier', 'shorthand_property_identifier_pattern', 'type_identifier', 'private_property_identifier', 'statement_identifier', 'field_identifier']);
9
+ const LITERALS = new Set(['string', 'template_string', 'number', 'regex', 'string_fragment']);
10
+
11
+ const FUNCTIONS = new Set(['function_declaration', 'function_expression', 'function', 'arrow_function', 'method_definition', 'generator_function_declaration', 'generator_function']);
12
+
13
+ /**
14
+ * [{ t, row }] for the code inside functions: names become ID, literals LIT, everything else its own text. Comments are dropped, and so
15
+ * is code outside any function: a repeated config object or table is data, not the copied logic this looks for.
16
+ */
17
+ export function tokensOf(tree) {
18
+ const out = [];
19
+ const visit = (n, inside) => {
20
+ if (n.type === 'comment') return;
21
+ const within = inside || FUNCTIONS.has(n.type);
22
+ if (!within) { for (const c of n.children) visit(c, false); return; }
23
+ if (LITERALS.has(n.type)) { out.push({ t: 'LIT', row: n.startPosition.row + 1 }); return; }
24
+ if (n.childCount === 0) { if (n.text.trim() !== '') out.push({ t: NAMES.has(n.type) ? 'ID' : n.text, row: n.startPosition.row + 1 }); return; }
25
+ for (const c of n.children) visit(c, true);
26
+ };
27
+ visit(tree.rootNode, false);
28
+ return out;
29
+ }
30
+
31
+ const hash = (tokens) => crypto.createHash('sha1').update(tokens.map((x) => x.t).join('\u0001')).digest('hex');
32
+
33
+ /** Every window of `size` tokens: [{ hash, first, last }] with first and last rows. */
34
+ export function windows(tokens, size) {
35
+ const out = [];
36
+ for (let i = 0; i + size <= tokens.length; i++) out.push({ hash: hash(tokens.slice(i, i + size)), first: tokens[i].row, last: tokens[i + size - 1].row, at: i });
37
+ return out;
38
+ }
39
+
40
+ function index(files) {
41
+ const m = new Map();
42
+ for (const f of files) for (const w of windows(f.tokens, f.size)) m.set(w.hash, [...(m.get(w.hash) ?? []), { file: f.file, w }]);
43
+ return m;
44
+ }
45
+
46
+ // The runs of consecutive new-copy windows in one file, each with one other place the fragment occurs.
47
+ function copiedRuns(f, isNew, places) {
48
+ const runs = [];
49
+ let run = null;
50
+ for (const w of windows(f.tokens, f.size)) {
51
+ if (!isNew(w.hash)) { if (run) runs.push(run); run = null; continue; }
52
+ if (run && w.at === run.end + 1) { run.end = w.at; run.last = w.last; continue; }
53
+ if (run) runs.push(run);
54
+ const other = places(w.hash).find((c) => c.file !== f.file || Math.abs(c.w.at - w.at) >= f.size);
55
+ run = other ? { file: f.file, line: w.first, last: w.last, end: w.at, other: { file: other.file, line: other.w.first } } : null;
56
+ }
57
+ if (run) runs.push(run);
58
+ return runs;
59
+ }
60
+
61
+ /**
62
+ * Copies a change made. A fragment is a new copy when it occurs more often after the change than before it, which does not depend on
63
+ * how git pairs the changed lines. after and before are the touched files in each version, rest the files the change did not touch;
64
+ * each is [{ file, tokens, size }]. Returns one finding per run of copied windows: { file, line, lines, other: { file, line } }.
65
+ */
66
+ export function findClones({ after, before = [], rest = [] }) {
67
+ const old = index([...before, ...rest]);
68
+ const now = index([...after, ...rest]);
69
+ const count = (m, h) => m.get(h)?.length ?? 0;
70
+ const isNew = (h) => count(now, h) >= 2 && count(now, h) > count(old, h);
71
+ const findings = after.flatMap((f) => copiedRuns(f, isNew, (h) => now.get(h)));
72
+ // Two copies that are both in the change would each be reported against the other: keep the later one.
73
+ const mirrors = (x, y) => y.file === x.other.file && y.line === x.other.line && y.other.file === x.file && y.other.line === x.line;
74
+ const later = (x, y) => x.file > y.file || (x.file === y.file && x.line > y.line);
75
+ return findings.filter((x) => !findings.some((y) => y !== x && mirrors(x, y) && later(y, x))).map(({ file, line, last, other }) => ({ file, line, lines: last - line + 1, other }));
76
+ }
@@ -0,0 +1,43 @@
1
+ // quality/css.mjs: stylesheet rules the gate checks. All of them are convention, not measured outcomes: nesting depth, how many
2
+ // compound selectors a selector chains, ID selectors (which win every specificity fight) and !important.
3
+
4
+ const COMBINATORS = new Set(['descendant_selector', 'child_selector', 'sibling_selector', 'adjacent_sibling_selector']);
5
+
6
+ function compound(selector) {
7
+ let n = 1;
8
+ const visit = (s) => { if (COMBINATORS.has(s.type)) n += 1; for (const c of s.namedChildren) visit(c); };
9
+ visit(selector);
10
+ return n;
11
+ }
12
+
13
+ function count(node, type) {
14
+ let n = node.type === type ? 1 : 0;
15
+ for (const c of node.namedChildren) n += count(c, type);
16
+ return n;
17
+ }
18
+
19
+ /** [{ line, nesting, compound, ids, important }] for every rule set, with its first line. */
20
+ export function cssRules(tree) {
21
+ const out = [];
22
+ const visit = (node, depth) => {
23
+ if (node.type === 'rule_set') {
24
+ const selectors = node.namedChildren.find((c) => c.type === 'selectors');
25
+ const list = selectors ? selectors.namedChildren : [];
26
+ const block = node.namedChildren.find((c) => c.type === 'block');
27
+ const own = block ? block.namedChildren.filter((c) => c.type !== 'rule_set') : [];
28
+ out.push({
29
+ line: node.startPosition.row + 1,
30
+ end: node.endPosition.row + 1,
31
+ nesting: depth + 1,
32
+ compound: Math.max(0, ...list.map(compound)),
33
+ ids: list.reduce((s, sel) => s + count(sel, 'id_selector'), 0),
34
+ important: own.reduce((s, d) => s + count(d, 'important'), 0),
35
+ });
36
+ if (block) for (const c of block.namedChildren) visit(c, depth + 1);
37
+ return;
38
+ }
39
+ for (const c of node.namedChildren) visit(c, depth);
40
+ };
41
+ visit(tree.rootNode, 0);
42
+ return out;
43
+ }
@@ -0,0 +1,230 @@
1
+ // quality/gate.mjs: whether a change meets the quality limits. It scores only what the change touches, against the version before it,
2
+ // so an old codebase is not failed on day one: a change may not take a function or a file over a limit, and a file may not gain more
3
+ // complexity in one change than its per-change limit, which is what stops a function being split apart just to pass. A function that
4
+ // was already over and got worse is reported as a warning. Copied code, stylesheet rules and newly added suppressions are checked in
5
+ // what the change added. A change the parser cannot follow fails, because a change that cannot be measured must not pass as clean.
6
+
7
+ import crypto from 'node:crypto';
8
+ import { TEST_FILE } from '../signals.mjs';
9
+ import { addedRanges, fileAt } from '../git-tree.mjs';
10
+ import { findClones, tokensOf } from './clones.mjs';
11
+ import { cssRules } from './css.mjs';
12
+ import { unitsOf, topLevelCognitive } from './metrics.mjs';
13
+ import { languageOf, parseSource } from './parse.mjs';
14
+
15
+ // Code that is not the product: dependencies, build output, test data, and docs, examples and playgrounds, which are written to be
16
+ // read once.
17
+ const SKIPPED = /(^|\/)(node_modules|vendor|dist|build|coverage|\.next|\.somi|fixtures?|__fixtures__|testdata|test-data|docs?|examples?|demos?|playgrounds?)\//;
18
+ const MINIFIED = /\.min\.(js|css)$/;
19
+ const GENERATED = /@generated\b|Code generated .* DO NOT EDIT/;
20
+ const SUPPRESSION = /eslint-disable|@ts-ignore|@ts-expect-error|@ts-nocheck|NOSONAR|#\s*noqa|\/\/\s*nolint|@SuppressWarnings|#\s*type:\s*ignore|istanbul ignore|c8 ignore|stylelint-disable/;
21
+ // A suppression that says why, the way ESLint's -- description or text after @ts-expect-error does, is a decision rather than a
22
+ // shortcut. Outside a benchmark it passes.
23
+ const REASONED = /eslint-disable[^\n]*\s--\s+\S.{8,}|@ts-(expect-error|ignore)\s*:?\s+\S.{8,}|stylelint-disable[^\n]*\s--\s+\S.{8,}/;
24
+ const ALLOW = /somi-gate-allow\s+([a-z_-]+)\s+reason="([^"]{20,})"\s+expires=(\d{4}-\d{2}-\d{2})/;
25
+ export const MAX_EXEMPTION_DAYS = 90;
26
+ export const METRICS = ['cognitive', 'depth', 'lines', 'params'];
27
+ export const JS_FAMILY = new Set(['javascript', 'typescript', 'tsx']);
28
+ const MAX_REPO_FILES = 3000;
29
+
30
+ const touches = (unit, ranges) => ranges.some(([a, b]) => a <= unit.end && b >= unit.start);
31
+ export const isTest = (file) => TEST_FILE.test(file);
32
+ export const skipped = (file, text) => SKIPPED.test(file) || MINIFIED.test(file) || GENERATED.test(text.split('\n').slice(0, 5).join('\n'));
33
+ export const total = (units, top) => units.reduce((s, u) => s + u.cognitive, 0) + top;
34
+
35
+ // An exemption sits on the line just above the function. It needs a reason of 20 characters or more and an expiry no more than 90 days
36
+ // out. In benchmark mode none counts: an agent writing its own exemption is a violation.
37
+ export function exemption(ctx, lines, unit, rule) {
38
+ const m = ALLOW.exec(lines[unit.start - 2] ?? '');
39
+ if (!m || (m[1] !== rule && m[1] !== 'all') || ctx.mode === 'benchmark') return null;
40
+ const expires = Date.parse(`${m[3]}T00:00:00Z`);
41
+ const today = Date.parse(ctx.now);
42
+ if (!(expires >= today) || expires - today > MAX_EXEMPTION_DAYS * 86400000) return null;
43
+ return { reason: m[2], expires: m[3] };
44
+ }
45
+
46
+ function pairUnits(before, after) {
47
+ const pool = new Map();
48
+ for (const u of before) { const k = `${u.kind}:${u.name}`; pool.set(k, [...(pool.get(k) ?? []), u]); }
49
+ return after.map((u) => ({ after: u, before: pool.get(`${u.kind}:${u.name}`)?.shift() ?? null }));
50
+ }
51
+
52
+ const inAdded = (added, line) => added.some(([a, b]) => line >= a && line <= b);
53
+ const flag = (ctx, v) => ctx.violations.push(v);
54
+
55
+ // Comments the change added: a new suppression is a violation, and in a benchmark so is an exemption the agent wrote. Only comments
56
+ // count, so a string that mentions eslint-disable is not one.
57
+ function scoreComment(ctx, file, line, text) {
58
+ if (SUPPRESSION.test(text) && (ctx.mode === 'benchmark' || !REASONED.test(text))) flag(ctx, { rule: 'suppression', file, line, value: 1, limit: ctx.limits.suppressions.added });
59
+ if (ctx.mode === 'benchmark' && /somi-gate-allow/.test(text)) flag(ctx, { rule: 'exemption', file, line, value: 1, limit: 0 });
60
+ }
61
+
62
+ // A directive opens its comment: // eslint-disable-next-line, /* @ts-nocheck */. A comment that only mentions one is prose.
63
+ const DIRECTIVE = /^(\/\/|\/\*+|#)\s*(eslint-disable|@ts-ignore|@ts-expect-error|@ts-nocheck|NOSONAR|nolint|stylelint-disable|istanbul ignore|c8 ignore|somi-gate-allow)/;
64
+
65
+ export function scoreComments(ctx, file, tree, added) {
66
+ const visit = (n) => {
67
+ if (n.type === 'comment') { if (inAdded(added, n.startPosition.row + 1) && DIRECTIVE.test(n.text)) scoreComment(ctx, file, n.startPosition.row + 1, n.text); return; }
68
+ for (const c of n.children) visit(c);
69
+ };
70
+ visit(tree.rootNode);
71
+ }
72
+
73
+ // With no tree to read comments from, every added line is checked instead.
74
+ function scoreLines(ctx, file, lines, added) {
75
+ for (const [i, line] of lines.entries()) if (inAdded(added, i + 1)) scoreComment(ctx, file, i + 1, line);
76
+ }
77
+
78
+ export function scoreCss(ctx, file, tree, added) {
79
+ for (const r of cssRules(tree).filter((x) => added.some(([a, b]) => a <= x.end && b >= x.line))) {
80
+ for (const rule of ['nesting', 'compound', 'ids', 'important']) {
81
+ if (r[rule] > ctx.limits.css[rule]) flag(ctx, { rule: `css-${rule}`, file, line: r.line, value: r[rule], limit: ctx.limits.css[rule] });
82
+ }
83
+ }
84
+ }
85
+
86
+ // One touched function. A change that takes it over a limit is a violation, whether it is new or was within the limit before. One that
87
+ // was already over and got worse is a warning: well-kept projects add a branch to a complex function every week, and SonarQube does
88
+ // not count that as a new issue either. The file's per-change limit still caps how much any change may add.
89
+ function scoreUnit(ctx, { file, lines, after, before }) {
90
+ ctx.scored.functions += 1;
91
+ for (const metric of METRICS) {
92
+ const limit = ctx.limits[after.kind][metric];
93
+ if (after[metric] <= limit || (before && after[metric] <= before[metric])) continue;
94
+ if (before && before[metric] > limit) { ctx.warnings.push({ rule: metric, file, line: after.start, name: after.name, value: after[metric], limit, before: before[metric] }); continue; }
95
+ const allowed = exemption(ctx, lines, after, metric);
96
+ if (allowed) ctx.exemptions.push({ rule: metric, file, line: after.start, name: after.name, ...allowed });
97
+ else flag(ctx, { rule: metric, file, line: after.start, name: after.name, kind: after.kind, value: after[metric], limit, ...(before ? { before: before[metric] } : {}) });
98
+ }
99
+ }
100
+
101
+ // A change may not take a file over its limit, nor add more than the per-change limit at once, however its functions are cut up. What
102
+ // it moved in from another file it touched is not added, so splitting a file into modules is not refused for its size.
103
+ function scoreTotals(ctx, { file, now, was, moved }) {
104
+ if (now > ctx.limits.file.cognitive && was <= ctx.limits.file.cognitive) flag(ctx, { rule: 'file-cognitive', file, line: 1, value: now, limit: ctx.limits.file.cognitive, before: was });
105
+ const added = now - was - moved;
106
+ if (added > ctx.limits.file.added_cognitive) flag(ctx, { rule: 'file-added-cognitive', file, line: 1, value: added, limit: ctx.limits.file.added_cognitive, ...(moved > 0 ? { moved } : {}) });
107
+ }
108
+
109
+ // A function's text, trimmed line by line, so the same function moved elsewhere, or indented differently, has the same key.
110
+ const keyOf = (lines, u) => lines.slice(u.start - 1, u.end).map((l) => l.trim()).join('\n');
111
+ const countOf = (keys) => keys.reduce((m, k) => m.set(k, (m.get(k) ?? 0) + 1), new Map());
112
+
113
+ // A function is moved, not added, when its file did not have it, the files the change touched did, and it occurs no more often after
114
+ // the change than before. A copy occurs more often, and a function changed on the way has a new key, so both still count in full.
115
+ function scoreMoves(ctx) {
116
+ const before = countOf(ctx.moves.before);
117
+ const after = countOf(ctx.moves.after);
118
+ const moved = (key) => (before.get(key) ?? 0) >= after.get(key);
119
+ for (const { units, own, ...totals } of ctx.totals) {
120
+ const credit = units.filter((u) => !own.has(u.key) && moved(u.key)).reduce((s, u) => s + u.cognitive, 0);
121
+ scoreTotals(ctx, { ...totals, moved: credit });
122
+ }
123
+ }
124
+
125
+ // A tree lives in the parser's WebAssembly memory, which the garbage collector does not free, so each one is deleted as soon as what
126
+ // the gate needs has been taken from it. Without that a large repository fills the memory and the runtime aborts.
127
+ export async function withTree(file, text, read) {
128
+ const parsed = await parseSource(file, text);
129
+ try { return read(parsed); } finally { parsed?.tree?.delete(); }
130
+ }
131
+
132
+ const NO_VERSION = Object.freeze({ units: [], keys: [], total: 0, tokens: null });
133
+ async function previousVersion(ctx, file, status, test) {
134
+ const text = status.startsWith('A') ? null : fileAt(ctx.root, ctx.from, file);
135
+ if (text === null || skipped(file, text)) return NO_VERSION;
136
+ const lines = text.split('\n');
137
+ return withTree(file, text, (parsed) => {
138
+ if (!parsed?.tree) return NO_VERSION;
139
+ const units = unitsOf(parsed.tree, { file, isTest: test });
140
+ return { units, keys: units.map((u) => keyOf(lines, u)), total: total(units, topLevelCognitive(parsed.tree)), tokens: JS_FAMILY.has(parsed.language) && !test ? tokensOf(parsed.tree) : null };
141
+ });
142
+ }
143
+
144
+ // A deleted file scores nothing, but what it held may have moved to another file the change touched.
145
+ async function recordDeleted(ctx, file, status) {
146
+ ctx.moves.before.push(...(await previousVersion(ctx, file, status, isTest(file))).keys);
147
+ }
148
+
149
+ async function scoreCode(ctx, { file, status, added, lines, tree, language, errors }) {
150
+ const test = isTest(file);
151
+ const units = unitsOf(tree, { file, isTest: test });
152
+ const old = await previousVersion(ctx, file, status, test);
153
+ // A function the parser could not follow is not scored, and with any such function the file's total is not trusted either.
154
+ const readable = (u) => !errors.some(([a, b]) => a <= u.end && b >= u.start);
155
+ for (const pair of pairUnits(old.units, units)) if (touches(pair.after, added) && readable(pair.after)) scoreUnit(ctx, { file, lines, ...pair });
156
+ const keyed = units.map((u) => ({ key: keyOf(lines, u), cognitive: u.cognitive }));
157
+ ctx.moves.before.push(...old.keys);
158
+ ctx.moves.after.push(...keyed.map((u) => u.key));
159
+ if (errors.length === 0) ctx.totals.push({ file, now: total(units, topLevelCognitive(tree)), was: old.total, units: keyed, own: new Set(old.keys) });
160
+ // Copies are looked for in product code. Copied setup between tests is mostly benign (Kapser and Godfrey), and it was most of the
161
+ // false alarms on known-good projects.
162
+ if (!JS_FAMILY.has(language) || test) return;
163
+ const size = ctx.limits.clones.tokens;
164
+ ctx.cloneAfter.push({ file, tokens: tokensOf(tree), size });
165
+ if (old.tokens) ctx.cloneBefore.push({ file, tokens: old.tokens, size });
166
+ }
167
+
168
+ async function scoreFile(ctx, file, { status, added }) {
169
+ if (!languageOf(file)) return;
170
+ if (status.startsWith('D')) return recordDeleted(ctx, file, status);
171
+ const text = fileAt(ctx.root, ctx.to, file);
172
+ if (text === null || skipped(file, text)) return;
173
+ const lines = text.split('\n');
174
+ const parsed = await parseSource(file, text);
175
+ if (parsed?.tree) scoreComments(ctx, file, parsed.tree, added); else scoreLines(ctx, file, lines, added);
176
+ try { await scoreParsed(ctx, { file, status, added, lines, parsed }); } finally { parsed?.tree?.delete(); }
177
+ }
178
+
179
+ async function scoreParsed(ctx, { file, status, added, lines, parsed }) {
180
+ // A change the parser cannot follow cannot be measured, so it must not pass as clean. An error elsewhere in the file only stops the
181
+ // functions it sits in from being scored.
182
+ const unreadable = parsed?.unanalyzed ?? (parsed.errors.some(([a, b]) => added.some(([x, y]) => a <= y && b >= x)) ? 'the parser could not follow the changed lines' : null);
183
+ // In a project this is a warning: a grammar can lag valid new syntax, and failing correct code on that would teach people to ignore
184
+ // the gate. In a benchmark it fails, so an agent cannot pass by writing what the gate cannot read.
185
+ if (unreadable) {
186
+ ctx.unanalyzed.push({ file, reason: unreadable });
187
+ const finding = { rule: 'unanalyzed', file, line: 1, value: 1, limit: 0, reason: unreadable };
188
+ if (ctx.mode === 'benchmark') flag(ctx, finding); else ctx.warnings.push(finding);
189
+ return;
190
+ }
191
+ ctx.scored.files += 1;
192
+ if (parsed.language === 'css') scoreCss(ctx, file, parsed.tree, added);
193
+ else await scoreCode(ctx, { file, status, added, lines, ...parsed });
194
+ }
195
+
196
+ async function cachedTokens(cache, file, text) {
197
+ const key = cache ? `${file}\0${crypto.createHash('sha1').update(text).digest('hex')}` : null;
198
+ if (key && cache.has(key)) return cache.get(key);
199
+ const tokens = await withTree(file, text, (parsed) => (parsed?.tree ? tokensOf(parsed.tree) : null));
200
+ if (key) cache.set(key, tokens);
201
+ return tokens;
202
+ }
203
+
204
+ // The rest of the repository is what a copy is compared against. Test files are left out of it: copied setup in tests is often benign.
205
+ // A caller scoring many changes in one repository can pass a cache, so files it has read once are not parsed again.
206
+ async function restOfRepo(ctx, touched) {
207
+ const rest = [];
208
+ const candidates = ctx.repoFiles.filter((f) => JS_FAMILY.has(languageOf(f)) && !touched.has(f) && !isTest(f) && !SKIPPED.test(f) && !MINIFIED.test(f));
209
+ for (const file of candidates.slice(0, MAX_REPO_FILES)) {
210
+ const text = fileAt(ctx.root, ctx.to, file);
211
+ if (text === null || skipped(file, text)) continue;
212
+ const tokens = await cachedTokens(ctx.cache, file, text);
213
+ if (tokens) rest.push({ file, tokens, size: ctx.limits.clones.tokens });
214
+ }
215
+ return rest;
216
+ }
217
+
218
+ /**
219
+ * The gate's verdict on the change from `from` to `to`: { ok, violations, warnings, exemptions, scored, unanalyzed }. Each violation is
220
+ * { rule, file, line, name?, value, limit, before? }.
221
+ */
222
+ export async function qualityGate(root, { from, to, limits, now = new Date().toISOString(), mode = 'project', repoFiles = [], cache = null }) {
223
+ const ctx = { root, from, to, limits, now, mode, repoFiles, cache, violations: [], warnings: [], exemptions: [], unanalyzed: [], scored: { files: 0, functions: 0 }, cloneAfter: [], cloneBefore: [], totals: [], moves: { before: [], after: [] } };
224
+ const changed = addedRanges(root, from, to);
225
+ for (const [file, change] of changed) await scoreFile(ctx, file, change);
226
+ scoreMoves(ctx);
227
+ const rest = await restOfRepo(ctx, new Set(changed.keys()));
228
+ for (const c of findClones({ after: ctx.cloneAfter, before: ctx.cloneBefore, rest })) flag(ctx, { rule: 'clone', file: c.file, line: c.line, value: c.lines, limit: 0, other: c.other });
229
+ return { ok: ctx.violations.length === 0, violations: ctx.violations, warnings: ctx.warnings, exemptions: ctx.exemptions, scored: ctx.scored, unanalyzed: ctx.unanalyzed };
230
+ }
@@ -0,0 +1,97 @@
1
+ // quality/limits.mjs: the gate's thresholds, calibrated on 12 well-kept JavaScript and TypeScript projects (benchmarks/quality/). The
2
+ // function limits are the common SonarSource and ESLint ones, which a few percent of those projects' functions exceed. Tests may run
3
+ // longer, and a copy has to be SonarQube's 100 tokens, about ten lines, because shorter repeated patterns were most of the false alarms.
4
+ //
5
+ // The gate runs at two scopes. A commit is a small step, checked before it is made against the last commit. A pull request is the whole
6
+ // branch since it left the shared history. A function over a limit is over it at either scope, so every limit is shared except how much
7
+ // one change may add to a file: 25 in a commit, which is what the calibration measured, and 100 in a pull request, so a branch can add a
8
+ // new module. Either scope can override any limit under quality.commit or quality.pr.
9
+ //
10
+ // The user's global config may set any limit, and SoMi asks before an agent changes one. A project's config is cloned input, so it may
11
+ // only tighten: a looser value there is ignored and reported. A benchmark scores a whole draw as a pull request with the defaults alone,
12
+ // so its results stay comparable.
13
+
14
+ // commit and pr gate a change. repo is a report on the whole codebase as it stands, for cleanups and refactors.
15
+ export const CHANGE_SCOPES = Object.freeze(['commit', 'pr']);
16
+ export const SCOPES = Object.freeze([...CHANGE_SCOPES, 'repo']);
17
+
18
+ export const DEFAULT_LIMITS = Object.freeze({
19
+ function: Object.freeze({ cognitive: 15, depth: 4, lines: 60, params: 4 }),
20
+ component: Object.freeze({ cognitive: 15, depth: 4, lines: 150, params: 4 }),
21
+ test: Object.freeze({ cognitive: 8, depth: 3, lines: 150, params: 4 }),
22
+ file: Object.freeze({ cognitive: 100, added_cognitive: 25 }),
23
+ clones: Object.freeze({ tokens: 100 }),
24
+ css: Object.freeze({ nesting: 3, compound: 3, ids: 0, important: 0 }),
25
+ suppressions: Object.freeze({ added: 0 }),
26
+ });
27
+
28
+ // How long the gate may run before it counts as failed, in seconds. A large change on a slow machine needs longer than the default, so
29
+ // either file may set quality.timeout_seconds: the user's own either way, and a project's, which knows its own size, only to lengthen it.
30
+ // A gate that runs out of time is not a pass, so a cloned project cannot make the gate pass by shortening it, and may not make it fail
31
+ // every change that way either. The end-of-turn hook's own time, in
32
+ // hooks/hooks.json, is set above the maximum, so the host never cuts the gate off first.
33
+ export const QUALITY_TIMEOUT = Object.freeze({ default: 300, min: 10, max: 1800 });
34
+
35
+ const SCOPE_DEFAULTS = Object.freeze({ commit: {}, pr: { file: { added_cognitive: 100 } }, repo: {} });
36
+
37
+ /** The default limits at one scope, as a fresh object. */
38
+ export function limitsFor(scope = 'pr') {
39
+ if (!SCOPES.includes(scope)) throw new Error(`the quality scope is ${SCOPES.join(', ')}, not ${scope}`);
40
+ const limits = Object.fromEntries(Object.entries(DEFAULT_LIMITS).map(([group, values]) => [group, { ...values }]));
41
+ for (const [group, values] of Object.entries(SCOPE_DEFAULTS[scope])) Object.assign(limits[group], values);
42
+ return limits;
43
+ }
44
+
45
+ const valid = (v) => Number.isInteger(v) && v >= 0 && v <= 100000;
46
+ const NOT_A_LIMIT = 'not a quality limit';
47
+ const NOT_A_NUMBER = 'not a whole number from 0 to 100000';
48
+
49
+ // One value from one file. The user's own file may set it either way. A project's may only lower it, since lower is stricter for
50
+ // every limit here.
51
+ function apply(limits, ignored, { where, prefix, group, key, value }) {
52
+ const name = `${prefix}.${group}.${key}`;
53
+ if (!(key in DEFAULT_LIMITS[group])) return ignored.push({ where, key: name, reason: NOT_A_LIMIT });
54
+ if (!valid(value)) return ignored.push({ where, key: name, reason: NOT_A_NUMBER });
55
+ if (where === 'project' && value > limits[group][key]) return ignored.push({ where, key: name, reason: `a project may only tighten a limit, and ${value} is looser than ${limits[group][key]}` });
56
+ limits[group][key] = value;
57
+ return null;
58
+ }
59
+
60
+ function applyLayer(limits, ignored, { where, prefix, layer }) {
61
+ for (const [group, values] of Object.entries(layer ?? {})) {
62
+ if (prefix === 'quality' && (SCOPES.includes(group) || group === 'timeout_seconds')) continue;
63
+ if (!DEFAULT_LIMITS[group]) { ignored.push({ where, key: `${prefix}.${group}`, reason: NOT_A_LIMIT }); continue; }
64
+ for (const [key, value] of Object.entries(values ?? {})) apply(limits, ignored, { where, prefix, group, key, value });
65
+ }
66
+ }
67
+
68
+ /**
69
+ * { limits, ignored } at one scope: the scope's defaults, then the global file's shared quality and its quality.<scope>, then the
70
+ * project file's, in that order.
71
+ */
72
+ export function resolveLimits({ global = {}, project = {}, scope = 'pr' } = {}) {
73
+ const limits = limitsFor(scope);
74
+ const ignored = [];
75
+ for (const [where, file] of [['global', global], ['project', project]]) {
76
+ applyLayer(limits, ignored, { where, prefix: 'quality', layer: file?.quality });
77
+ applyLayer(limits, ignored, { where, prefix: `quality.${scope}`, layer: file?.quality?.[scope] });
78
+ }
79
+ return { limits, ignored: [...ignored, ...resolveTimeout({ global, project }).ignored] };
80
+ }
81
+
82
+ const TIMEOUT_KEY = 'quality.timeout_seconds';
83
+ const timeoutValid = (v) => Number.isInteger(v) && v >= QUALITY_TIMEOUT.min && v <= QUALITY_TIMEOUT.max;
84
+
85
+ /** { seconds, ignored }: the default, then the global file's quality.timeout_seconds, then the project's if it is longer. */
86
+ export function resolveTimeout({ global = {}, project = {} } = {}) {
87
+ let seconds = QUALITY_TIMEOUT.default;
88
+ const ignored = [];
89
+ for (const [where, file] of [['global', global], ['project', project]]) {
90
+ const value = file?.quality?.timeout_seconds;
91
+ if (value === undefined) continue;
92
+ if (!timeoutValid(value)) ignored.push({ where, key: TIMEOUT_KEY, reason: `not a whole number of seconds from ${QUALITY_TIMEOUT.min} to ${QUALITY_TIMEOUT.max}` });
93
+ else if (where === 'project' && value < seconds) ignored.push({ where, key: TIMEOUT_KEY, reason: `a project may only lengthen the time, and ${value} is shorter than ${seconds}` });
94
+ else seconds = value;
95
+ }
96
+ return { seconds, ignored };
97
+ }