@skathio/somi 4.1.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +8 -3
  3. package/.claude-plugin/plugin.json +9 -10
  4. package/.copilot-extension/extension.json +32 -40
  5. package/.copilot-extension/marketplace.json +8 -3
  6. package/README.md +83 -228
  7. package/VERSION +1 -1
  8. package/agents/somi-reviewer.md +21 -40
  9. package/agents/somi-security-reviewer.md +16 -90
  10. package/agents/somi-worker-high.md +11 -0
  11. package/agents/somi-worker-low.md +11 -0
  12. package/agents/somi-worker-medium.md +11 -0
  13. package/agents/somi.md +8 -75
  14. package/commands/somi-config.md +5 -14
  15. package/commands/somi-deliver.md +11 -0
  16. package/commands/somi-quality.md +10 -0
  17. package/commands/somi-review.md +10 -0
  18. package/commands/somi-status.md +11 -0
  19. package/commands/somi.md +10 -0
  20. package/hooks/hooks.json +28 -23
  21. package/hooks/lib/common.mjs +45 -34
  22. package/hooks/pre-tool/apply-tier.mjs +31 -0
  23. package/hooks/pre-tool/block-dangerous-bash.mjs +15 -0
  24. package/hooks/pre-tool/gate-dep-install.mjs +2 -2
  25. package/hooks/pre-tool/guard-protected-paths.mjs +9 -16
  26. package/hooks/pre-tool/guard-tier-config.mjs +17 -0
  27. package/hooks/pre-tool/reviewers-read-only.mjs +11 -0
  28. package/hooks/session-start/inject-digest.mjs +51 -0
  29. package/hooks/stop/review-due.mjs +40 -0
  30. package/hooks/user-prompt/capture-prompt.mjs +17 -0
  31. package/library/lenses/architecture.md +1 -0
  32. package/library/lenses/test-strategy.md +1 -0
  33. package/library/roles/accessibility.md +1 -0
  34. package/library/roles/answer.md +1 -0
  35. package/library/roles/atlas.md +1 -0
  36. package/library/roles/build.md +1 -0
  37. package/library/roles/debug.md +6 -0
  38. package/library/roles/design.md +1 -0
  39. package/library/roles/discover.md +1 -0
  40. package/library/roles/incident.md +1 -0
  41. package/library/roles/migrate.md +1 -0
  42. package/library/roles/perf.md +1 -0
  43. package/library/roles/plan.md +1 -0
  44. package/library/roles/refactor.md +1 -0
  45. package/library/roles/review.md +1 -0
  46. package/library/roles/security-review.md +1 -0
  47. package/library/roles/upgrade.md +1 -0
  48. package/library/skills/accessibility.md +16 -0
  49. package/library/skills/ci-infra-gotchas.md +12 -0
  50. package/library/skills/perf-method.md +10 -0
  51. package/library/skills/secure-coding.md +18 -0
  52. package/library/skills/testing-checklist.md +16 -0
  53. package/library/skills/threat-modeling.md +10 -0
  54. package/package.json +12 -17
  55. package/profiles/claude.json +21 -0
  56. package/profiles/copilot.json +5 -0
  57. package/rules/digest.md +40 -0
  58. package/scripts/check-links.mjs +65 -76
  59. package/scripts/lib/advisor.mjs +207 -0
  60. package/scripts/lib/check.mjs +165 -0
  61. package/scripts/lib/copilot-workflow.mjs +41 -0
  62. package/scripts/lib/doctor.mjs +91 -0
  63. package/scripts/lib/gates.mjs +69 -0
  64. package/scripts/lib/git-tree.mjs +201 -0
  65. package/scripts/lib/init.mjs +23 -0
  66. package/scripts/lib/ledger.mjs +38 -0
  67. package/scripts/lib/mcp-project-root.mjs +63 -67
  68. package/scripts/lib/migrate.mjs +73 -0
  69. package/scripts/lib/path-facts.mjs +2 -2
  70. package/scripts/lib/path-safety.mjs +6 -134
  71. package/scripts/lib/plan.mjs +69 -0
  72. package/scripts/lib/policy.mjs +103 -0
  73. package/scripts/lib/pr.mjs +28 -0
  74. package/scripts/lib/prompt.mjs +72 -0
  75. package/scripts/lib/quality/clones.mjs +76 -0
  76. package/scripts/lib/quality/css.mjs +43 -0
  77. package/scripts/lib/quality/gate.mjs +230 -0
  78. package/scripts/lib/quality/limits.mjs +73 -0
  79. package/scripts/lib/quality/metrics.mjs +159 -0
  80. package/scripts/lib/quality/parse.mjs +73 -0
  81. package/scripts/lib/quality/repo.mjs +69 -0
  82. package/scripts/lib/quality/run.mjs +38 -0
  83. package/scripts/lib/reviews.mjs +132 -0
  84. package/scripts/lib/routes.mjs +108 -0
  85. package/scripts/lib/setup.mjs +34 -0
  86. package/scripts/lib/shards.mjs +166 -0
  87. package/scripts/lib/signals.mjs +110 -0
  88. package/scripts/lib/state.mjs +42 -0
  89. package/scripts/lib/tiers.mjs +42 -0
  90. package/scripts/lib/update-notice.mjs +48 -0
  91. package/scripts/lib/views.mjs +62 -0
  92. package/scripts/lib/workflows.mjs +56 -0
  93. package/scripts/somi-mcp.mjs +181 -323
  94. package/scripts/somi.mjs +208 -0
  95. package/scripts/vendor/tree-sitter/LICENSE.vscode-tree-sitter-wasm +21 -0
  96. package/scripts/vendor/tree-sitter/LICENSE.web-tree-sitter +21 -0
  97. package/scripts/vendor/tree-sitter/cgmanifest.vscode-tree-sitter-wasm.json +16 -0
  98. package/scripts/vendor/tree-sitter/manifest.json +59 -0
  99. package/scripts/vendor/tree-sitter/package.json +3 -0
  100. package/scripts/vendor/tree-sitter/tree-sitter-css.wasm +0 -0
  101. package/scripts/vendor/tree-sitter/tree-sitter-javascript.wasm +0 -0
  102. package/scripts/vendor/tree-sitter/tree-sitter-tsx.wasm +0 -0
  103. package/scripts/vendor/tree-sitter/tree-sitter-typescript.wasm +0 -0
  104. package/scripts/vendor/tree-sitter/web-tree-sitter.js +4081 -0
  105. package/scripts/vendor/tree-sitter/web-tree-sitter.wasm +0 -0
  106. package/skills/somi-expertise/SKILL.md +6 -0
  107. package/workflows/deliver-stages.js +81 -0
  108. package/.claude/settings.json +0 -131
  109. package/agents/somi-architecture-reviewer.md +0 -101
  110. package/agents/somi-atlas.md +0 -100
  111. package/agents/somi-coder.md +0 -60
  112. package/agents/somi-designer.md +0 -36
  113. package/agents/somi-discovery-analyst.md +0 -57
  114. package/agents/somi-flow.md +0 -47
  115. package/agents/somi-general.md +0 -36
  116. package/agents/somi-impact.md +0 -95
  117. package/agents/somi-incident.md +0 -94
  118. package/agents/somi-plan-reviewer.md +0 -68
  119. package/agents/somi-planner.md +0 -57
  120. package/agents/somi-pr.md +0 -99
  121. package/agents/somi-refactor-designer.md +0 -81
  122. package/agents/somi-refactorer.md +0 -99
  123. package/agents/somi-sdlc-reviewer.md +0 -67
  124. package/agents/somi-test-strategist.md +0 -87
  125. package/commands/adopt.md +0 -14
  126. package/commands/architecture-review.md +0 -19
  127. package/commands/atlas.md +0 -19
  128. package/commands/code-loop.md +0 -19
  129. package/commands/code-parallel.md +0 -19
  130. package/commands/code.md +0 -19
  131. package/commands/debug.md +0 -19
  132. package/commands/design.md +0 -19
  133. package/commands/discover.md +0 -19
  134. package/commands/impact.md +0 -19
  135. package/commands/incident.md +0 -19
  136. package/commands/plan-loop.md +0 -19
  137. package/commands/plan.md +0 -19
  138. package/commands/pr.md +0 -19
  139. package/commands/refactor-design.md +0 -19
  140. package/commands/refactor.md +0 -19
  141. package/commands/release-readiness.md +0 -19
  142. package/commands/review-panel.md +0 -19
  143. package/commands/review.md +0 -19
  144. package/commands/security-review.md +0 -19
  145. package/commands/ship-loop.md +0 -19
  146. package/commands/ship.md +0 -19
  147. package/commands/test-strategy.md +0 -19
  148. package/commands/upgrade.md +0 -19
  149. package/examples/README.md +0 -19
  150. package/examples/code-review-example.md +0 -88
  151. package/examples/discovery-example.md +0 -200
  152. package/examples/feature-plan-example.md +0 -377
  153. package/examples/full-pipeline-example.md +0 -188
  154. package/examples/sample-consumer/.claude/settings.json +0 -29
  155. package/examples/sample-consumer/CLAUDE.md +0 -78
  156. package/examples/sample-consumer/README.md +0 -102
  157. package/hooks/post-tool/lint-changed-files.mjs +0 -209
  158. package/hooks/pre-tool/guard-cost-lowering.mjs +0 -192
  159. package/hooks/session-start/detect-repo-instructions.mjs +0 -287
  160. package/hooks/session-start/ensure-default-config.mjs +0 -113
  161. package/hooks/user-prompt-submit/inject-workflow-context.mjs +0 -580
  162. package/rules/00-priorities.md +0 -48
  163. package/rules/10-solid.md +0 -87
  164. package/rules/20-clean-code.md +0 -62
  165. package/rules/30-security-owasp.md +0 -83
  166. package/rules/40-engineering-practices.md +0 -65
  167. package/rules/50-collaboration.md +0 -114
  168. package/rules/99-overrides.md +0 -52
  169. package/rules/CLAUDE.md +0 -200
  170. package/scripts/check-session-artefacts.mjs +0 -149
  171. package/scripts/check-size-budget.mjs +0 -137
  172. package/scripts/generate-digest.mjs +0 -176
  173. package/scripts/lib/agent-info.mjs +0 -85
  174. package/scripts/lib/agent-registry.mjs +0 -92
  175. package/scripts/lib/cost-ceiling.mjs +0 -328
  176. package/scripts/lib/cost-config-edit.mjs +0 -102
  177. package/scripts/lib/cost-config.mjs +0 -64
  178. package/scripts/lib/cost-defaults.mjs +0 -53
  179. package/scripts/lib/cost-lowering.mjs +0 -89
  180. package/scripts/lib/cost-model.mjs +0 -110
  181. package/scripts/lib/dispatch-resolver.mjs +0 -243
  182. package/scripts/lib/escalation-facts.mjs +0 -146
  183. package/scripts/lib/escalation.mjs +0 -129
  184. package/scripts/lib/findings-ledger.mjs +0 -241
  185. package/scripts/lib/install-text.mjs +0 -97
  186. package/scripts/lib/loop-caps.mjs +0 -140
  187. package/scripts/lib/loop-diff.mjs +0 -38
  188. package/scripts/lib/loop-dispatch.mjs +0 -19
  189. package/scripts/lib/loop-engine.mjs +0 -226
  190. package/scripts/lib/loop-escalate.mjs +0 -49
  191. package/scripts/lib/loop-exit.mjs +0 -47
  192. package/scripts/lib/loop-notes-compact.mjs +0 -72
  193. package/scripts/lib/loop-notes.mjs +0 -278
  194. package/scripts/lib/loop-review.mjs +0 -395
  195. package/scripts/lib/loop-state.mjs +0 -44
  196. package/scripts/lib/loop-step-close.mjs +0 -75
  197. package/scripts/lib/loop-step-kit.mjs +0 -179
  198. package/scripts/lib/loop-step-review.mjs +0 -140
  199. package/scripts/lib/loop-step-tool.mjs +0 -89
  200. package/scripts/lib/loop-step.mjs +0 -301
  201. package/scripts/lib/run-budget.mjs +0 -28
  202. package/scripts/lib/run-card.mjs +0 -73
  203. package/scripts/lib/size-tier.mjs +0 -184
  204. package/scripts/lib/tier-record.mjs +0 -82
  205. package/scripts/size-budget-overrides.json +0 -58
  206. package/scripts/somi-card.mjs +0 -39
  207. package/scripts/somi-check.mjs +0 -237
  208. package/scripts/somi-config.mjs +0 -421
  209. package/scripts/somi-dispatch.mjs +0 -141
  210. package/scripts/somi-findings.mjs +0 -100
  211. package/scripts/somi-loop.mjs +0 -128
  212. package/scripts/somi-tier.mjs +0 -393
  213. package/scripts/validate.sh +0 -653
  214. package/skills/api-design/SKILL.md +0 -147
  215. package/skills/clean-code/SKILL.md +0 -142
  216. package/skills/flow-adopt/SKILL.md +0 -92
  217. package/skills/flow-architecture-review/SKILL.md +0 -94
  218. package/skills/flow-atlas/SKILL.md +0 -34
  219. package/skills/flow-code/SKILL.md +0 -167
  220. package/skills/flow-code-loop/SKILL.md +0 -263
  221. package/skills/flow-code-parallel/SKILL.md +0 -160
  222. package/skills/flow-debug/SKILL.md +0 -141
  223. package/skills/flow-design/SKILL.md +0 -170
  224. package/skills/flow-discover/SKILL.md +0 -204
  225. package/skills/flow-impact/SKILL.md +0 -35
  226. package/skills/flow-incident/SKILL.md +0 -49
  227. package/skills/flow-plan/SKILL.md +0 -254
  228. package/skills/flow-plan-loop/SKILL.md +0 -254
  229. package/skills/flow-pr/SKILL.md +0 -34
  230. package/skills/flow-refactor/SKILL.md +0 -58
  231. package/skills/flow-refactor-design/SKILL.md +0 -97
  232. package/skills/flow-release-readiness/SKILL.md +0 -82
  233. package/skills/flow-review/SKILL.md +0 -193
  234. package/skills/flow-review-panel/SKILL.md +0 -154
  235. package/skills/flow-security-review/SKILL.md +0 -83
  236. package/skills/flow-ship/SKILL.md +0 -125
  237. package/skills/flow-ship-loop/SKILL.md +0 -274
  238. package/skills/flow-somi-config/SKILL.md +0 -142
  239. package/skills/flow-status/SKILL.md +0 -43
  240. package/skills/flow-test-strategy/SKILL.md +0 -83
  241. package/skills/flow-upgrade/SKILL.md +0 -82
  242. package/skills/market-research/SKILL.md +0 -125
  243. package/skills/observability/SKILL.md +0 -133
  244. package/skills/owasp-defense/SKILL.md +0 -141
  245. package/skills/plan-review/SKILL.md +0 -83
  246. package/skills/reasoning-craft/SKILL.md +0 -213
  247. package/skills/requirements-engineering/SKILL.md +0 -137
  248. package/skills/role-coder/SKILL.md +0 -247
  249. package/skills/role-designer/SKILL.md +0 -172
  250. package/skills/role-discovery-analyst/SKILL.md +0 -288
  251. package/skills/role-planner/SKILL.md +0 -353
  252. package/skills/role-reviewer/SKILL.md +0 -218
  253. package/skills/rules/SKILL.md +0 -47
  254. package/skills/sdlc-process/SKILL.md +0 -74
  255. package/skills/solid-principles/SKILL.md +0 -143
  256. package/skills/somi-checkpoint/SKILL.md +0 -95
  257. package/skills/somi-dispatch/SKILL.md +0 -259
  258. package/skills/somi-routing/SKILL.md +0 -158
  259. package/skills/testing-playbook/SKILL.md +0 -133
  260. package/skills/threat-modeling/SKILL.md +0 -117
  261. package/templates/ADR.md.tmpl +0 -73
  262. package/templates/ATLAS.md.tmpl +0 -75
  263. package/templates/BRD.md.tmpl +0 -68
  264. package/templates/BRIEF.md.tmpl +0 -119
  265. package/templates/CONTEXT.md.tmpl +0 -74
  266. package/templates/DECISIONS.md.tmpl +0 -105
  267. package/templates/DESIGN.md.tmpl +0 -83
  268. package/templates/DIARY.md.tmpl +0 -70
  269. package/templates/DOD.md.tmpl +0 -90
  270. package/templates/FRD.md.tmpl +0 -64
  271. package/templates/PHASE.md.tmpl +0 -80
  272. package/templates/PROGRESS.md.tmpl +0 -63
  273. package/templates/RCA.md.tmpl +0 -53
  274. package/templates/RD-README.md.tmpl +0 -70
  275. package/templates/RESEARCH.md.tmpl +0 -96
  276. package/templates/REVIEW.md.tmpl +0 -82
  277. package/templates/SDD.md.tmpl +0 -82
  278. package/templates/SOMI-README.md.tmpl +0 -83
  279. package/templates/SPEC.md.tmpl +0 -123
  280. package/templates/SRS.md.tmpl +0 -85
  281. package/templates/TDD.md.tmpl +0 -77
  282. package/tests/hooks/cases/audit-log.json +0 -21
  283. package/tests/hooks/cases/block-dangerous-bash.json +0 -166
  284. package/tests/hooks/cases/block-secret-writes.json +0 -140
  285. package/tests/hooks/cases/detect-repo-instructions.json +0 -105
  286. package/tests/hooks/cases/gate-dep-install.json +0 -42
  287. package/tests/hooks/cases/guard-protected-paths.json +0 -222
  288. package/tests/hooks/cases/inject-workflow-context.json +0 -239
  289. package/tests/hooks/cases/lint-changed-files.json +0 -120
  290. package/tests/hooks/run.sh +0 -392
  291. package/tests/scripts/agent-model-frontmatter.sh +0 -38
  292. package/tests/scripts/agent-names.sh +0 -77
  293. package/tests/scripts/check-frontmatter.sh +0 -37
  294. package/tests/scripts/check-links.sh +0 -105
  295. package/tests/scripts/check-session-artefacts.sh +0 -60
  296. package/tests/scripts/check-size-budget.sh +0 -71
  297. package/tests/scripts/checkpoint-gate.sh +0 -131
  298. package/tests/scripts/convergence-runner.sh +0 -1514
  299. package/tests/scripts/cost-ceiling.sh +0 -255
  300. package/tests/scripts/cost-defaults.sh +0 -130
  301. package/tests/scripts/cost-hardcap.sh +0 -338
  302. package/tests/scripts/cost-lowering.sh +0 -261
  303. package/tests/scripts/cost-model.sh +0 -196
  304. package/tests/scripts/dispatch-guard.sh +0 -108
  305. package/tests/scripts/dispatch-line-gate.sh +0 -61
  306. package/tests/scripts/dispatch-reference-gate.sh +0 -173
  307. package/tests/scripts/ensure-default-config.sh +0 -162
  308. package/tests/scripts/escalation.sh +0 -409
  309. package/tests/scripts/eval-runner.sh +0 -3692
  310. package/tests/scripts/evals-packaging.sh +0 -224
  311. package/tests/scripts/fact-sheet.sh +0 -296
  312. package/tests/scripts/fixtures/legacy-shard-no-schema.json +0 -50
  313. package/tests/scripts/fixtures/mock-stdin-read-throw.cjs +0 -18
  314. package/tests/scripts/fixtures/size-tier-cases.json +0 -87
  315. package/tests/scripts/generate-digest.sh +0 -180
  316. package/tests/scripts/global-config.sh +0 -167
  317. package/tests/scripts/goldens/loop-state-breach.json +0 -1
  318. package/tests/scripts/goldens/loop-state-done.json +0 -1
  319. package/tests/scripts/goldens/somi-findings.json +0 -336
  320. package/tests/scripts/goldens/somi-loop.json +0 -168
  321. package/tests/scripts/lib/adr-shape.mjs +0 -41
  322. package/tests/scripts/lib/agent-registry-tests.mjs +0 -95
  323. package/tests/scripts/lib/brief-only-guard.mjs +0 -27
  324. package/tests/scripts/lib/checkpoint-gate.mjs +0 -91
  325. package/tests/scripts/lib/digest-marker-coupling.mjs +0 -52
  326. package/tests/scripts/lib/dispatch-reference-gate.mjs +0 -121
  327. package/tests/scripts/lib/escalation-facts-tests.mjs +0 -140
  328. package/tests/scripts/lib/escalation-tests.mjs +0 -154
  329. package/tests/scripts/lib/findings-ledger-tests.mjs +0 -118
  330. package/tests/scripts/lib/loop-engine-tests.mjs +0 -287
  331. package/tests/scripts/lib/loop-escalate-tests.mjs +0 -356
  332. package/tests/scripts/lib/loop-flow-gate.mjs +0 -173
  333. package/tests/scripts/lib/loop-notes-tests.mjs +0 -371
  334. package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -141
  335. package/tests/scripts/lib/loop-step-close-tests.mjs +0 -351
  336. package/tests/scripts/lib/loop-step-lenient-tests.mjs +0 -114
  337. package/tests/scripts/lib/loop-step-state-tests.mjs +0 -127
  338. package/tests/scripts/lib/loop-step-tests.mjs +0 -499
  339. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +0 -55
  340. package/tests/scripts/lib/multipass-dependence.mjs +0 -192
  341. package/tests/scripts/lib/multipass-source-identity.mjs +0 -243
  342. package/tests/scripts/lib/path-facts-tests.mjs +0 -198
  343. package/tests/scripts/lib/path-safety-tests.mjs +0 -201
  344. package/tests/scripts/lib/reference-pair.mjs +0 -61
  345. package/tests/scripts/lib/retirement-gate.mjs +0 -172
  346. package/tests/scripts/lib/run-suites.mjs +0 -139
  347. package/tests/scripts/lib/shell-embedded-js.mjs +0 -47
  348. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +0 -52
  349. package/tests/scripts/lib/site-roadmap-gate.mjs +0 -64
  350. package/tests/scripts/lib/size-tier-drift.mjs +0 -74
  351. package/tests/scripts/lib/sizing-score-tests.mjs +0 -210
  352. package/tests/scripts/lib/sizing-set-tests.mjs +0 -131
  353. package/tests/scripts/lib/somi-mcp-client.mjs +0 -102
  354. package/tests/scripts/lib/somi-mcp-config-tests.mjs +0 -92
  355. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +0 -226
  356. package/tests/scripts/lib/somi-mcp-tests.mjs +0 -491
  357. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +0 -64
  358. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +0 -38
  359. package/tests/scripts/loop-engine.sh +0 -22
  360. package/tests/scripts/loop-flow-gate.sh +0 -11
  361. package/tests/scripts/retirement-gate.sh +0 -306
  362. package/tests/scripts/review-panel-seats.sh +0 -32
  363. package/tests/scripts/run-card.sh +0 -57
  364. package/tests/scripts/run-suites.sh +0 -74
  365. package/tests/scripts/run.sh +0 -689
  366. package/tests/scripts/site-roadmap-gate.sh +0 -76
  367. package/tests/scripts/size-tier.sh +0 -562
  368. package/tests/scripts/somi-agent-dispatch-contract.sh +0 -224
  369. package/tests/scripts/somi-config.sh +0 -286
  370. package/tests/scripts/somi-dispatch.sh +0 -465
  371. package/tests/scripts/somi-mcp.sh +0 -15
  372. package/tests/scripts/suite-plan.json +0 -20
@@ -1,210 +0,0 @@
1
- #!/usr/bin/env node
2
- // Tests of the sizing scorer (tests/evals/lib/sizing-score.mjs). Risk: a bar that passes a run it should fail (a weak
3
- // share, an unguarded floor case, a tie read as a winner), or two runs on different labels compared as one. Tables run
4
- // over records built from the committed set; the entry point runs as a child process for its exit codes. Each guard is
5
- // then broken on a scratch copy of the module and the same suite must turn red. Run by
6
- // tests/scripts/eval-gate-bench-driver.sh. Hermetic: no model, no network, no randomness.
7
-
8
- import { spawnSync } from 'node:child_process';
9
- import fs from 'node:fs';
10
- import os from 'node:os';
11
- import path from 'node:path';
12
- import { isDeepStrictEqual } from 'node:util';
13
- import { pathToFileURL } from 'node:url';
14
- import { REPO_ROOT, TIERS, isFloorCase, labelHash, loadSet, scenarioId } from '../../evals/lib/sizing-set.mjs';
15
-
16
- const LIB = path.join(REPO_ROOT, 'tests', 'evals', 'lib');
17
- const set = loadSet();
18
- const SHA = 'a'.repeat(40);
19
- const clone = (v) => JSON.parse(JSON.stringify(v));
20
- // A record in which every entry matches its label on all five draws, with `over` replacing some entries' draws.
21
- const rec = (over = {}, extra = {}) => ({ label_sha256: labelHash(set), plugin_sha: SHA, arm: 'somi', entries: Object.fromEntries(set.entries.map((e) => [e.id, over[e.id] ?? Array(5).fill(e.label)])), ...extra });
22
- const draws = (n, tier, rest = null) => [...Array(n).fill(tier), ...Array(5 - n).fill(rest)];
23
- // The cases the tests lean on come from the set itself, so a relabelled or extended set does not silently void them.
24
- const floors = set.entries.filter(isFloorCase);
25
- const [O1, O2] = set.entries.filter((e) => !isFloorCase(e));
26
- const F1 = floors[0]; const F2 = floors[1]; const F3 = floors.at(-1);
27
- const otherThan = (...tiers) => TIERS.filter((t) => !tiers.includes(t));
28
- const [X1] = otherThan(O1.label); const [Y1] = otherThan(O1.label, X1);
29
- const offDraws = (e, n) => [...Array(n).fill(otherThan(e.label)[0]), ...Array(5 - n).fill(e.label)];
30
- const rowsFor = (n) => set.entries.flatMap((e) => Array.from({ length: n }, () => ({ scenario: scenarioId(e), arm: 'somi', phase: 'sizing', tier: e.label })));
31
- const META = { plugin_sha: SHA, arm: 'somi' };
32
-
33
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sizing-score-'));
34
- process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));
35
-
36
- // A scratch copy of the scorer (and the modules it imports, with the data directories linked) with `from` replaced by `to`.
37
- let scratchN = 0;
38
- function scratch(from, to) {
39
- const dir = path.join(tmp, `scratch${scratchN++}`, 'tests', 'evals');
40
- fs.mkdirSync(path.join(dir, 'lib'), { recursive: true });
41
- for (const f of ['sizing-set.mjs', 'bench-schema.mjs', 'manifest.mjs']) fs.copyFileSync(path.join(LIB, f), path.join(dir, 'lib', f));
42
- for (const d of ['ab', 'ab-micro', 'fixtures', 'sizing-set']) fs.symlinkSync(path.join(REPO_ROOT, 'tests', 'evals', d), path.join(dir, d));
43
- const original = fs.readFileSync(path.join(LIB, 'sizing-score.mjs'), 'utf8');
44
- fs.writeFileSync(path.join(dir, 'lib', 'sizing-score.mjs'), original.replace(from, to));
45
- return { file: path.join(dir, 'lib', 'sizing-score.mjs'), applies: original.includes(from) };
46
- }
47
-
48
- async function suite(modPath, say) {
49
- let pass = 0; let fail = 0;
50
- const check = (name, got, want) => {
51
- if (isDeepStrictEqual(got, want)) { pass++; say(` ok ${name}`); } else { fail++; say(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
52
- };
53
- const M = await import(pathToFileURL(modPath).href);
54
- const refused = (fn) => { try { fn(); return 'no throw'; } catch (e) { return e instanceof M.Refusal ? e.message : `wrong error: ${e.message}`; } };
55
- const refusedWith = (fn, re) => re.test(refused(fn));
56
- const score = (r, o) => M.scoreResult(set, r, o);
57
- const entry = (r, id, o) => score(r, o).entries.find((x) => x.id === id);
58
-
59
- say('== sizing score: building a record ==');
60
- const built = M.buildResult(set, rowsFor(5), META);
61
- check('turns sizing rows into a record bound to the set', [built.label_sha256, built.plugin_sha, built.arm, Object.keys(built.entries).length, built.entries[O1.id]], [labelHash(set), SHA, 'somi', set.entries.length, Array(5).fill(O1.label)]);
62
- check('keeps the draw order and reads a tier outside the three as null', M.buildResult(set, rowsFor(1).map((r, i) => (i === 0 ? { ...r, tier: 'unknown' } : r)), META).entries[O1.id], [null]);
63
- check('reads a missing tier as null', M.buildResult(set, rowsFor(1).map((r, i) => (i === 0 ? { ...r, tier: undefined } : r)), META).entries[O1.id], [null]);
64
- check('refuses a row outside the sizing phase', refusedWith(() => M.buildResult(set, rowsFor(1).map((r, i) => (i === 0 ? { ...r, phase: 'experiment' } : r)), META), /not sizing/), true);
65
- check('refuses a scenario that is not in the set', refusedWith(() => M.buildResult(set, [...rowsFor(1), { scenario: 'S4-Z9', arm: 'somi', phase: 'sizing', tier: 'small' }], META), /not in the set/), true);
66
- check('refuses a row of the other arm', refusedWith(() => M.buildResult(set, rowsFor(1).map((r, i) => (i === 0 ? { ...r, arm: 'bare' } : r)), META), /arm "bare"/), true);
67
- check('refuses entries with different draw counts', refusedWith(() => M.buildResult(set, [...rowsFor(2), rowsFor(1)[0]], META), /same number of draws/), true);
68
- check('refuses an entry with no draw', refusedWith(() => M.buildResult(set, rowsFor(2).slice(2), META), /same number of draws/), true);
69
- check('refuses an empty list of rows', refusedWith(() => M.buildResult(set, [], META), /at least one/), true);
70
- const withOutcome = (outcome) => rowsFor(1).map((r, i) => (i === 0 ? { ...r, outcome } : r));
71
- check('refuses a draw that ended paused or over budget, so it has to be drawn again', ['paused', 'over-budget'].map((o) => refusedWith(() => M.buildResult(set, withOutcome(o), META), new RegExp(`ended ${o}`))), [true, true]);
72
- const withEnd = (outcome, reason) => rowsFor(1).map((r, i) => (i === 0 ? { ...r, outcome, reason } : r));
73
- check("takes a scored draw and the probe's own invalid draw as answers", [['scored'], ['invalid', 'probe']].map((a) => M.buildResult(set, withEnd(...a), META).entries[O1.id]), [[O1.label], [O1.label]]);
74
- check('refuses a draw that ended invalid for any reason but probe: a harness event, not an answer', ['timeout', 'output-cap', 'leak: token', 'unpinned-model', undefined].map((why) => refusedWith(() => M.buildResult(set, withEnd('invalid', why), META), /ended invalid/)), Array(5).fill(true));
75
- const timedOut = (tier, tierSource) => rowsFor(1).map((r, i) => (i === 0 ? { ...r, outcome: 'invalid', reason: 'timeout', tier, tierSource } : r));
76
- check('takes a timed-out draw whose tier is full from the record file as an answer', M.buildResult(set, timedOut('full', 'file'), META).entries[O1.id], ['full']);
77
- check('counts only the timed-out full draws it took, and never a scored draw that carries a timeout reason', [M.buildRecord(set, timedOut('full', 'file'), META).taken, M.buildRecord(set, rowsFor(1), META).taken, M.buildRecord(set, rowsFor(1).map((r, i) => (i === 0 ? { ...r, outcome: 'scored', reason: 'timeout', tier: 'full', tierSource: 'file' } : r)), META).taken], [1, 0, 0]);
78
- check('refuses a timeout on any other tier or tier source', [['small', 'file'], ['trivial', 'file'], ['unknown', 'file'], ['full', 'stream'], ['full', 'none'], ['full', undefined]].map((a) => refusedWith(() => M.buildResult(set, timedOut(...a), META), /ended invalid \("timeout"\)/)), Array(6).fill(true));
79
- check('refuses a full/file draw that ended invalid for a reason but timeout', ['output-cap', 'leak: token', 'unpinned-model', undefined].map((why) => refusedWith(() => M.buildResult(set, timedOut('full', 'file').map((r, i) => (i === 0 ? { ...r, reason: why } : r)), META), /ended invalid/)), Array(4).fill(true));
80
- check('refuses a bad plugin sha', refusedWith(() => M.buildResult(set, rowsFor(1), { plugin_sha: 'main', arm: 'somi' }), /plugin_sha/), true);
81
-
82
- say('== sizing score: the bar per entry ==');
83
- check('passes when every entry matches 5 of 5', score(rec()).bar_met, true);
84
- check('modal tier, share and need are reported', (({ modal, share, need, pass }) => ({ modal, share, need, pass }))(entry(rec({ [O1.id]: draws(4, O1.label, X1) }), O1.id)), { modal: O1.label, share: 0.8, need: 4, pass: true });
85
- check('fails an ordinary entry at 3 of 5', entry(rec({ [O1.id]: draws(3, O1.label, X1) }), O1.id).pass, false);
86
- check('passes an ordinary entry at 4 of 5', entry(rec({ [O1.id]: draws(4, O1.label, X1) }), O1.id).pass, true);
87
- check('fails a floor case at 4 of 5', entry(rec({ [F1.id]: draws(4, F1.label, otherThan(F1.label)[0]) }), F1.id).pass, false);
88
- check('passes a floor case at 5 of 5', entry(rec(), F1.id).pass, true);
89
- check('a floor case at 4 of 5 fails the whole bar', score(rec({ [F3.id]: draws(4, F3.label, otherThan(F3.label)[0]) })).bar_met, false);
90
- check('fails a 2/2/1 tie, which has no modal tier', (({ modal, pass }) => ({ modal, pass }))(entry(rec({ [O1.id]: [O1.label, O1.label, X1, X1, Y1] }), O1.id)), { modal: null, pass: false });
91
- check('fails a modal tier that is not the label even at 5 of 5', entry(rec({ [O1.id]: Array(5).fill(X1) }), O1.id).pass, false);
92
- check('counts a null tier as a miss', [entry(rec({ [O1.id]: draws(4, O1.label) }), O1.id).pass, entry(rec({ [O1.id]: draws(3, O1.label) }), O1.id).pass], [true, false]);
93
- check('counts a null tier as an off-label draw', score(rec({ [O1.id]: draws(4, O1.label) })).pooled.off, 1);
94
- check('fails a floor case with one null draw', entry(rec({ [F2.id]: draws(4, F2.label) }), F2.id).pass, false);
95
- check('scales the share to the draw count (10 draws need 8)', [8, 7].map((n) => entry(rec({ [O1.id]: [...Array(n).fill(O1.label), ...Array(10 - n).fill(X1)], ...Object.fromEntries(set.entries.filter((e) => e.id !== O1.id).map((e) => [e.id, Array(10).fill(e.label)])) }), O1.id).pass), [true, false]);
96
-
97
- say('== sizing score: the pooled reading ==');
98
- // Off-label draws spread over the ordinary entries, five to an entry (the set size sets the allowance: one draw in ten).
99
- const ordinary = set.entries.filter((e) => !isFloorCase(e));
100
- const spread = (n, per = 5) => Object.fromEntries(ordinary.map((e, i) => [e.id, offDraws(e, Math.max(0, Math.min(per, n - i * per)))]));
101
- const allowed = Math.floor((set.entries.length * 5) / 10);
102
- const atLimit = rec(spread(allowed)); const overLimit = rec(spread(allowed + 1));
103
- const failing = Math.ceil((allowed - 1) / 5);
104
- check(`accepts ${allowed} of ${set.entries.length * 5} off-label draws`, [score(atLimit, { mode: 'pooled' }).pooled.off, score(atLimit, { mode: 'pooled' }).bar_met], [allowed, true]);
105
- check('the same draws miss the per-task bar and both numbers are reported', [score(atLimit).bar_met, score(atLimit).per_task.passing, score(atLimit).pooled.allowed], [false, set.entries.length - failing, allowed]);
106
- check(`rejects ${allowed + 1} of ${set.entries.length * 5} off-label draws`, [score(overLimit, { mode: 'pooled' }).pooled.off, score(overLimit, { mode: 'pooled' }).bar_met], [allowed + 1, false]);
107
- // 3 draws an entry is a total that is not a multiple of ten: the allowance rounds down, so one draw over is rejected.
108
- const few = (n) => Object.fromEntries(ordinary.map((e, i) => { const k = Math.max(0, Math.min(3, n - i * 3)); return [e.id, [...Array(k).fill(otherThan(e.label)[0]), ...Array(3 - k).fill(e.label)]]; }));
109
- const rec3 = (over) => rec(Object.fromEntries(set.entries.map((e) => [e.id, over[e.id] ?? Array(3).fill(e.label)])));
110
- const allowed3 = Math.floor((set.entries.length * 3) / 10);
111
- check(`rounds the allowance down: ${allowed3} of ${set.entries.length * 3} accepted, ${allowed3 + 1} rejected`, [allowed3, allowed3 + 1].map((n) => score(rec3(few(n)), { mode: 'pooled' }).bar_met), [true, false]);
112
- check('still fails a floor case at 4 of 5', score(rec({ [F1.id]: draws(4, F1.label, otherThan(F1.label)[0]) }), { mode: 'pooled' }).bar_met, false);
113
- check('refuses an unknown mode', refusedWith(() => score(rec(), { mode: 'loose' }), /unknown mode/), true);
114
-
115
- say('== sizing score: the label-hash binding and malformed records ==');
116
- check('refuses a record whose hash is not the committed set', refusedWith(() => score(rec({}, { label_sha256: 'b'.repeat(64) })), /different label set/), true);
117
- const altered = clone(set); altered.entries[0].label = otherThan(altered.entries[0].label)[0];
118
- check('refuses a record scored against a re-labelled set', refusedWith(() => M.scoreResult(altered, rec()), /different label set/), true);
119
- check('refuses a record without a hash', refusedWith(() => score(rec({}, { label_sha256: undefined })), /label_sha256/), true);
120
- check('refuses a record with an unknown arm', refusedWith(() => score(rec({}, { arm: 'x' })), /plugin_sha or arm/), true);
121
- check('refuses a record that is not an object', refusedWith(() => score([]), /not a result record/), true);
122
- check('refuses a record missing an entry', refusedWith(() => { const r = rec(); delete r.entries[O1.id]; score(r); }, /exactly the set's entries/), true);
123
- check('refuses a record with an extra entry', refusedWith(() => { const r = rec(); r.entries.Z9 = ['small']; score(r); }, /exactly the set's entries/), true);
124
- check('refuses a draw outside the three tiers', refusedWith(() => score(rec({ [O1.id]: ['medium', ...Array(4).fill(O1.label)] })), /list of tiers or null/), true);
125
- check('refuses an entry with no draws', refusedWith(() => score(rec({ [O1.id]: [] })), /list of tiers or null/), true);
126
- check('refuses entries with different draw counts', refusedWith(() => score(rec({ [O1.id]: Array(4).fill(O1.label) })), /different draw counts/), true);
127
- const base = rec(); const cand = rec({ [O1.id]: draws(3, O1.label, X1) });
128
- const side = M.compareResults(set, base, cand);
129
- check('compares two records of the same set side by side', [side.baseline.bar_met, side.candidate.bar_met, side.candidate.entries.find((x) => x.id === O1.id).pass], [true, false, false]);
130
- check('refuses a candidate with a different label hash than the baseline', refusedWith(() => M.compareResults(set, base, rec({}, { label_sha256: 'b'.repeat(64) })), /different label sets/), true);
131
- check('refuses two records that agree with each other but not with the set', refusedWith(() => M.compareResults(set, rec({}, { label_sha256: 'b'.repeat(64) }), rec({}, { label_sha256: 'b'.repeat(64) })), /different label set/), true);
132
-
133
- say('== sizing score: the entry point ==');
134
- const cli = (...argv) => spawnSync('node', [path.join(path.dirname(modPath), 'sizing-score.mjs'), ...argv], { encoding: 'utf8' });
135
- const work = fs.mkdtempSync(path.join(tmp, 'c-'));
136
- const put = (name, v) => { const f = path.join(work, name); fs.writeFileSync(f, typeof v === 'string' ? v : JSON.stringify(v)); return f; };
137
- const met = put('met.json', rec()); const missed = put('missed.json', cand); const wrong = put('wrong.json', rec({}, { label_sha256: 'b'.repeat(64) }));
138
- const ran = (...a) => { const r = cli(...a); return [r.status, r.stdout.split('\n')[0].slice(0, 22)]; };
139
- check('exits 0 and says met when the bar is met', ran('--score', met), [0, 'sizing bar met (per-ta']);
140
- check('exits 3 and names the entry when the bar is missed', [cli('--score', missed).status, cli('--score', missed).stdout.includes(`missed (per-task): disagrees on ${O1.id};`)], [3, true]);
141
- check('exits 2 on a refusal, not 3 and not 64 or 65', [cli('--score', wrong).status, /different label set/.test(cli('--score', wrong).stderr)], [2, true]);
142
- check('exits 2 on a record that is not JSON', cli('--score', put('junk.json', 'nope')).status, 2);
143
- check('exits 2 on a usage error', [cli().status, cli('--score').status, cli('--bogus').status], [2, 2, 2]);
144
- check('--pooled reads the same record by the pooled bar', [cli('--score', put('at-limit.json', atLimit), '--pooled').status, cli('--score', put('at-limit2.json', atLimit)).status], [0, 3]);
145
- check('--compare exits 0 on comparable records even when the candidate missed', [cli('--compare', met, missed).status, /^baseline: sizing bar met[^\n]*\ncandidate: sizing bar missed/.test(cli('--compare', met, missed).stdout)], [0, true]);
146
- check('--compare exits 2 when the label hashes differ', cli('--compare', met, wrong).status, 2);
147
- const rowsFile = put('rows.jsonl', rowsFor(1).map((r) => JSON.stringify({ status: 'halted', row: null, ...r })).concat(rowsFor(5).map((r) => JSON.stringify({ status: 'done', row: r }))).join('\n'));
148
- const out = cli('--build', rowsFile, '--plugin-sha', SHA);
149
- check('--build prints a record that scores as met, ignoring halted draws', [out.status, out.status === 0 && M.scoreResult(set, JSON.parse(out.stdout)).bar_met], [0, true]);
150
- const err = (r) => [r.status, /^sizing-score: refused: /.test(r.stderr), /^sizing-score: error: /.test(r.stderr)];
151
- check('a refusal is reported as refused, exit 2', err(cli('--score', wrong)), [2, true, false]);
152
- const bug = scratch('const needOf = (draws) => Math.ceil((draws * 4) / 5);', "const needOf = () => { throw new TypeError('boom'); };");
153
- const bugRun = spawnSync('node', [bug.file, '--score', met], { encoding: 'utf8' });
154
- check('any other exception is an error, exit 1, never a refusal', [bug.applies, ...err(bugRun), /boom/.test(bugRun.stderr)], [true, 1, false, true, true]);
155
- const badSet = put('bad-set.json', '{"entries": []}');
156
- check('a set that fails validation is a refusal, exit 2', [...err(cli('--score', met, '--set', badSet)), /sizing set invalid/.test(cli('--score', met, '--set', badSet).stderr)], [2, true, false, true]);
157
- check('a set file that is missing is a refusal, exit 2', err(cli('--score', met, '--set', path.join(work, 'nope.json'))).slice(0, 2), [2, true]);
158
- const badRows = put('bad-rows.jsonl', `${JSON.stringify({ status: 'done', row: rowsFor(1)[0] })}\n\n{"status": "done", row\n`);
159
- const badRun = cli('--build', badRows, '--plugin-sha', SHA);
160
- check('--build names the line whose JSON does not parse', [badRun.status, /line 3 is not JSON/.test(badRun.stderr)], [2, true]);
161
- check('--build refuses an empty rows file', [cli('--build', put('empty.jsonl', ''), '--plugin-sha', SHA).status, /at least one/.test(cli('--build', put('empty.jsonl', ''), '--plugin-sha', SHA).stderr)], [2, true]);
162
- check('--build refuses a finished draw whose entry reason is not probe, and takes one that is', [['timeout', 2], ['probe', 0]].map(([why, code]) => cli('--build', put(`why-${why}.jsonl`, rowsFor(1).map((r) => JSON.stringify({ status: 'done', reason: why, row: { ...r, outcome: 'invalid' } })).join('\n')), '--plugin-sha', SHA).status === code), [true, true]);
163
- const timeoutFile = (tier) => put(`timeout-${tier}.jsonl`, rowsFor(5).map((r, i) => JSON.stringify({ status: 'done', reason: i === 0 ? 'timeout' : 'probe', row: i === 0 ? { ...r, outcome: 'invalid', tier, tierSource: 'file' } : r })).join('\n'));
164
- const tFull = cli('--build', timeoutFile('full'), '--plugin-sha', SHA); const tSmall = cli('--build', timeoutFile('small'), '--plugin-sha', SHA);
165
- const tRows = rowsFor(5).map((r, i) => (i === 0 ? { ...r, outcome: 'invalid', reason: 'timeout', tier: 'full', tierSource: 'file' } : { ...r, outcome: 'invalid', reason: 'probe' }));
166
- check('--build takes a timed-out full draw, says so on stderr and prints exactly the record (stdout is one JSON document)', [tFull.status, tFull.stderr, tFull.status === 0 && isDeepStrictEqual(JSON.parse(tFull.stdout), M.buildResult(set, tRows, META))],
167
- [0, 'sizing-score: timed-out full draws taken as answers (tier from the record file): 1\n', true]);
168
- check('--build refuses a timed-out small draw, exit 2', [tSmall.status, /ended invalid/.test(tSmall.stderr)], [2, true]);
169
- check('--build says nothing on stderr when it took no timeout', [out.status, out.stderr], [0, '']);
170
- check('--build refuses a file that is missing', cli('--build', path.join(work, 'nope.jsonl'), '--plugin-sha', SHA).status, 2);
171
- check('a flag that needs a value and has none is a usage refusal, even last or before another flag', [
172
- cli('--score', met, '--set'), cli('--build', rowsFile, '--plugin-sha'), cli('--build', rowsFile, '--plugin-sha', SHA, '--arm'), cli('--score', met, '--set', '--pooled'),
173
- ].map((r) => [...err(r).slice(0, 2), /needs a value/.test(r.stderr)]), Array(4).fill([2, true, true]));
174
- const pausedFile = put('paused.jsonl', rowsFor(5).map((r, i) => JSON.stringify({ status: 'done', row: i === 0 ? { ...r, outcome: 'paused' } : r })).join('\n'));
175
- const pausedRun = cli('--build', pausedFile, '--plugin-sha', SHA);
176
- check('--build refuses a draw that ended paused rather than scoring it', [pausedRun.status, /ended paused/.test(pausedRun.stderr)], [2, true]);
177
- return { pass, fail };
178
- }
179
-
180
- const say = (s) => console.log(s);
181
- const real = await suite(path.join(LIB, 'sizing-score.mjs'), say);
182
-
183
- // ---- mutations: each guard broken on a scratch copy of the module; the suite must fail on it ------------------------
184
- say('== sizing score: mutations ==');
185
- const MUTATIONS = [
186
- ['the share threshold weakened to 3 of 5', 'Math.ceil((draws * 4) / 5)', 'Math.ceil((draws * 3) / 5)'],
187
- ['the floor rule dropped', 'const need = floor ? draws.length : needOf(draws.length);', 'const need = needOf(draws.length);'],
188
- ['the label-hash check dropped', 'if (rec.label_sha256 !== labelHash(set))', 'if (false)'],
189
- // A tie can only change the reported modal tier, never `pass` (a tied top count is below the need); the suite pins the modal.
190
- ['the empty-rows guard dropped', 'counts.length !== 1 || counts[0] === 0', 'counts.length !== 1'],
191
- ['the pooled allowance rounded up', 'Math.floor(total / 10)', 'Math.ceil(total / 10)'],
192
- ['an invalid draw taken as an answer', "(r.outcome === 'invalid' && r.reason !== 'probe' && !isTakenTimeout(r))", 'false'],
193
- ['a timeout taken whatever its tier', "r.tier === 'full' && r.tierSource === 'file'", "r.tierSource === 'file'"],
194
- ['a timeout taken whatever its reason', "r.reason === 'timeout' && r.tier === 'full'", "r.tier === 'full'"],
195
- ['a timeout counted whatever its outcome', "r.outcome === 'invalid' && r.reason === 'timeout'", "r.reason === 'timeout'"],
196
- ['a timeout taken whatever its tier source', "r.tier === 'full' && r.tierSource === 'file'", "r.tier === 'full'"],
197
- ['ties resolved to the first tier', 'if (top.length !== 1) return { tier: null, count };', 'if (top.length === 0) return { tier: null, count };'],
198
- ];
199
- let mutFail = 0;
200
- for (const [name, from, to] of MUTATIONS) {
201
- const m = scratch(from, to);
202
- const r = m.applies ? await suite(m.file, () => {}) : { fail: 0 };
203
- const red = m.applies && r.fail > 0;
204
- if (!red) mutFail++;
205
- say(red ? ` ok mutation turns the suite red: ${name} (${r.fail} failing)` : ` FAIL mutation ${m.applies ? 'left the suite green' : 'did not apply'}: ${name}`);
206
- }
207
-
208
- const failed = real.fail + mutFail;
209
- say(` ${real.pass} passed, ${failed} failed`);
210
- process.exit(failed === 0 ? 0 : 1);
@@ -1,131 +0,0 @@
1
- #!/usr/bin/env node
2
- // Tests of the labelled sizing set (tests/evals/lib/sizing-set.mjs). Risk: a set that validates when it should not, or a
3
- // hash that does not move when a label, a request or a fixture does, would let two runs on different labels be compared.
4
- // Red cases run against a scratch repository tree; the committed set is checked against the real one. Run by
5
- // tests/scripts/eval-gate-bench-driver.sh. Hermetic: no model, no network.
6
-
7
- import fs from 'node:fs';
8
- import os from 'node:os';
9
- import path from 'node:path';
10
- import { isDeepStrictEqual } from 'node:util';
11
- import { REPO_ROOT, SET_FILE, TIERS, labelHash, loadSet, scenarioId, setMaterial, sizingScenarios, stageFixture, validateSet } from '../../evals/lib/sizing-set.mjs';
12
-
13
- let pass = 0; let fail = 0;
14
- const check = (name, got, want) => {
15
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
16
- };
17
- const clone = (v) => JSON.parse(JSON.stringify(v));
18
-
19
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sizing-set-'));
20
- process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));
21
- // A scratch tree: one corpus task, two fixtures, and the things a fixture name must not resolve to.
22
- for (const d of ['tests/evals/ab-micro/M1-x', 'tests/evals/fixtures/fx', 'tests/evals/fixtures/fy', 'tests/evals/fixtures/_candidates', 'tests/evals/fixtures/_target', 'tests/evals/ab/D-empty']) fs.mkdirSync(path.join(tmp, d), { recursive: true });
23
- fs.writeFileSync(path.join(tmp, 'tests/evals/ab-micro/M1-x/task.json'), '{}');
24
- fs.writeFileSync(path.join(tmp, 'tests/evals/fixtures/afile'), 'x');
25
- fs.symlinkSync('fx', path.join(tmp, 'tests/evals/fixtures/lnk'));
26
-
27
- const corpus = { id: 'M1', label: 'small', task: 'ab-micro/M1-x', reason: 'one file' };
28
- const authored = { id: 'A1', label: 'trivial', fixture: 'fx', request: 'Fix the typo in src/a.mjs.', reason: 'one file' };
29
- const floor = { id: 'A2', label: 'full', sensitive: true, fixture: 'fy', request: 'Rotate the key.', reason: 'floor' };
30
- const base = { schema_version: 1, entries: [corpus, authored, floor] };
31
- const problems = (mut) => { const s = clone(base); mut(s); return validateSet(s, { root: tmp }); };
32
-
33
- console.log('== sizing set: validator ==');
34
- check('accepts a valid set of both kinds and a floor case', validateSet(base, { root: tmp }), []);
35
- const REDS = [
36
- ['a missing label', (s) => { delete s.entries[0].label; }, /no label/],
37
- ['an unknown tier', (s) => { s.entries[0].label = 'medium'; }, /unknown tier/],
38
- ['a sensitive entry labelled below full', (s) => { s.entries[2].label = 'small'; }, /security floor/],
39
- ['a duplicate id', (s) => { s.entries[1].id = 'M1'; }, /duplicate id M1/],
40
- ['a corpus task that does not exist', (s) => { s.entries[0].task = 'ab-micro/M9-none'; }, /does not exist/],
41
- ['a corpus task directory with no task.json', (s) => { s.entries[0].task = 'ab/D-empty'; }, /does not exist/],
42
- ['a corpus task outside the two corpora', (s) => { s.entries[0].task = 'fixtures/fx'; }, /needs a task/],
43
- ['a corpus entry that carries a fixture', (s) => { s.entries[0].fixture = 'fx'; }, /carries a fixture/],
44
- ['a corpus entry that carries a request', (s) => { s.entries[0].request = 'x'; }, /carries a fixture or a request/],
45
- ['an authored entry with no request', (s) => { delete s.entries[1].request; }, /needs request text/],
46
- ['an authored entry with a blank request', (s) => { s.entries[1].request = ' '; }, /needs request text/],
47
- ['an authored entry with no fixture', (s) => { delete s.entries[1].fixture; }, /needs a fixture/],
48
- ['a fixture that does not exist', (s) => { s.entries[1].fixture = 'nope'; }, /fixture does not exist/],
49
- ['a fixture that is a file', (s) => { s.entries[1].fixture = 'afile'; }, /not a directory/],
50
- ['a fixture that is a symlink', (s) => { s.entries[1].fixture = 'lnk'; }, /symlink/],
51
- ['a fixture holding ..', (s) => { s.entries[1].fixture = '..'; }, /plain directory name/],
52
- ['a fixture path that climbs', (s) => { s.entries[1].fixture = '../fixtures/fx'; }, /plain directory name/],
53
- ['a fixture that is not directly under fixtures', (s) => { s.entries[1].fixture = 'fx/sub'; }, /plain directory name/],
54
- ['a fixture that is absolute', (s) => { s.entries[1].fixture = path.join(tmp, 'tests/evals/fixtures/fx'); }, /plain directory name/],
55
- ['the candidates directory', (s) => { s.entries[1].fixture = '_candidates'; }, /underscore directories/],
56
- ['the target directory', (s) => { s.entries[1].fixture = '_target'; }, /underscore directories/],
57
- ['an unknown key', (s) => { s.entries[1].notes = 'x'; }, /unknown key/],
58
- ['a control character in a request', (s) => { s.entries[1].request = 'a\u202eb'; }, /needs request text/],
59
- ['a wrong schema version', (s) => { s.schema_version = 2; }, /schema_version/],
60
- ['no entries', (s) => { s.entries = []; }, /non-empty/],
61
- ];
62
- for (const [name, mut, want] of REDS) { const p = problems(mut); check(`rejects ${name}`, p.length > 0 && p.some((x) => want.test(x)), true); }
63
- check('rejects a set that is not an object', validateSet([], { root: tmp }).length, 1);
64
-
65
- console.log('== sizing set: label hash ==');
66
- const h0 = labelHash(base);
67
- check('is 64 hex characters', /^[0-9a-f]{64}$/.test(h0), true);
68
- const reordered = { entries: [floor, corpus, authored].map((e) => Object.fromEntries(Object.entries(e).reverse())), schema_version: 1 };
69
- check('is stable across key order and entry order', labelHash(reordered), h0);
70
- const changed = (mut) => { const s = clone(base); mut(s); return labelHash(s) !== h0; };
71
- check('is stable when only a reason changes', changed((s) => { s.entries[1].reason = 'other words'; }), false);
72
- const MOVES = [
73
- ['an id', (s) => { s.entries[1].id = 'A9'; }],
74
- ['a label', (s) => { s.entries[0].label = 'full'; }],
75
- ['a request text', (s) => { s.entries[1].request += ' '; }],
76
- ['a fixture name', (s) => { s.entries[1].fixture = 'fy'; }],
77
- ['a corpus task', (s) => { s.entries[0].task = 'ab/D-empty'; }],
78
- ['the sensitive flag', (s) => { s.entries[2].sensitive = false; }],
79
- ['an added entry', (s) => { s.entries.push({ ...authored, id: 'A3' }); }],
80
- ];
81
- for (const [name, mut] of MOVES) check(`moves when ${name} changes`, changed(mut), true);
82
- check('does not confuse a request with a fixture name', labelHash({ entries: [{ id: 'X', label: 'full', fixture: 'ab', request: 'cd' }] }) !== labelHash({ entries: [{ id: 'X', label: 'full', fixture: 'a', request: 'bcd' }] }), true);
83
-
84
- console.log('== sizing set: the committed set ==');
85
- const set = loadSet();
86
- check('loads and validates against the repository', validateSet(set), []);
87
- check('is the file the library points at', path.relative(REPO_ROOT, SET_FILE), path.join('tests', 'evals', 'sizing-set', 'set.json'));
88
- check('holds the planned entries', set.entries.map((e) => e.id), ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'T1', 'H1', 'H2', 'H4', 'A1', 'A2', 'A3', 'A4']);
89
- check('uses all three tiers', TIERS.filter((t) => set.entries.some((e) => e.label === t)), [...TIERS]);
90
- check('has floor cases, all labelled full', set.entries.filter((e) => e.sensitive).map((e) => `${e.id}:${e.label}`), ['H4:full', 'A3:full', 'A4:full']);
91
- check('derives the scenario ids already in use', ['M01', 'T1'].map((id) => scenarioId(set.entries.find((e) => e.id === id))), ['S4-M01', 'S4-T1']);
92
- // A reason or request that cites a path its fixture does not hold is a wrong label, so every cited path must exist: in the
93
- // authored entry's fixture, or for a corpus entry in the repository (tests/...) or in its task's fixture (src/...).
94
- const EV = path.join(REPO_ROOT, 'tests', 'evals');
95
- const missing = [];
96
- for (const e of set.entries) {
97
- const bases = e.fixture ? [path.join(EV, 'fixtures', e.fixture)] : [REPO_ROOT, path.join(EV, e.task, 'fixture')];
98
- for (const cited of `${e.request ?? ''} ${e.reason}`.match(/(?<![\w/.-])(?:src|tests|docs)\/[\w./-]*\w/g) ?? []) {
99
- if (!bases.some((b) => fs.existsSync(path.join(b, cited)))) missing.push(`${e.id}: ${cited}`);
100
- }
101
- }
102
- check('every entry cites only paths its tree holds', missing, []);
103
- check('loadSet refuses a set that fails validation', (() => { const f = path.join(tmp, 'bad.json'); fs.writeFileSync(f, '{"schema_version":1,"entries":[{"id":"Z"}]}'); try { loadSet(f); return 'no throw'; } catch (e) { return /no label/.test(e.message); } })(), true);
104
- check('loadSet refuses a file that is not JSON', (() => { const f = path.join(tmp, 'junk.json'); fs.writeFileSync(f, 'nope'); try { loadSet(f); return 'no throw'; } catch (e) { return /unreadable/.test(e.message); } })(), true);
105
-
106
- console.log('== sizing set: probe scenarios and fixture staging ==');
107
- const scen = sizingScenarios(set);
108
- check('has one probe scenario per entry, in set order', Object.keys(scen), set.entries.map(scenarioId));
109
- check('runs a corpus entry in its task', scen['S4-M03'], { kind: 'task', corpus: 'tests/evals/ab-micro', task: 'M03-rank-aggregation', probe: true });
110
- const a3 = set.entries.find((e) => e.id === 'A3');
111
- check('runs an authored entry as its request in a copy of its fixture', scen['S4-A3'], { kind: 'set', dir: 'tests/evals/fixtures/task02-code', request: a3.request, probe: true });
112
- const fixtureDir = path.join(REPO_ROOT, scen['S4-A3'].dir);
113
- const staged = path.join(tmp, 'staged');
114
- stageFixture(fixtureDir, staged);
115
- check('stages the fixture files and leaves the plan tree out', [fs.existsSync(path.join(staged, 'src/auth/token.mjs')), fs.existsSync(path.join(staged, '_somi')), fs.existsSync(path.join(staged, '.somi'))], [true, false, false]);
116
- check('keeps the plan tree as .somi when asked', (() => { stageFixture(fixtureDir, `${staged}-plans`, { keepPlans: true }); return [fs.existsSync(`${staged}-plans/.somi/plans`), fs.existsSync(`${staged}-plans/_somi`)]; })(), [true, false]);
117
- // A scratch fixture: a file, a plan tree, and a link to a file outside it that staging must never read through.
118
- const fx = path.join(tmp, 'tests/evals/fixtures/fx');
119
- fs.mkdirSync(path.join(fx, '_somi/plans'), { recursive: true });
120
- fs.writeFileSync(path.join(fx, 'a.txt'), 'a'); fs.writeFileSync(path.join(fx, '_somi/plans/p.md'), 'p');
121
- const h1 = setMaterial(fx, 'req');
122
- check('binds a fixture and a request in a stable hash that moves with either', [/^[0-9a-f]{64}$/.test(h1), setMaterial(fx, 'req') === h1, setMaterial(fx, 'req2') !== h1, (fs.writeFileSync(path.join(fx, 'a.txt'), 'b'), setMaterial(fx, 'req') !== h1)], [true, true, true, true]);
123
- fs.writeFileSync(path.join(tmp, 'outside.txt'), 'SECRET');
124
- fs.symlinkSync(path.join(tmp, 'outside.txt'), path.join(fx, 'inner'));
125
- const out = path.join(tmp, 'out-link');
126
- const thrown = (() => { try { stageFixture(fx, out); return 'no throw'; } catch (e) { return e.message; } })();
127
- check('refuses a fixture with an inner link: nothing is staged, so nothing is read through it', [/could not be read/.test(thrown), fs.existsSync(out)], [true, false]);
128
- check('has no material for a fixture with an inner link or one that is missing', [setMaterial(fx, 'req'), setMaterial(path.join(tmp, 'nope'), 'req')], [null, null]);
129
-
130
- console.log(` ${pass} passed, ${fail} failed`);
131
- process.exit(fail === 0 ? 0 : 1);
@@ -1,102 +0,0 @@
1
- // somi-mcp-client.mjs — a minimal MCP CLIENT used only to test scripts/somi-mcp.mjs over real
2
- // stdio: spawns the server, speaks newline-delimited JSON-RPC 2.0 in both directions (request /
3
- // response correlation, plus answering a SERVER-initiated request such as `roots/list`, the same
4
- // as a real MCP client would), and records every line for scenarios to inspect directly.
5
-
6
- import { spawn } from 'node:child_process';
7
- import { createInterface } from 'node:readline';
8
-
9
- export class McpClient {
10
- constructor(serverPath, { env } = {}) {
11
- this.child = spawn(process.execPath, [serverPath], {
12
- env: { ...process.env, ...env },
13
- stdio: ['pipe', 'pipe', 'pipe'],
14
- });
15
- this.nextId = 1;
16
- this.pending = new Map(); // id -> {resolve, reject}
17
- this.messages = []; // every parsed line the server sent, in arrival order
18
- this.rawLines = []; // every raw line, parsed or not (parse-error scenarios read this)
19
- this.stderr = '';
20
- this.rootsHandler = null; // async () => string[] -- set by a scenario to answer roots/list
21
- this.child.stderr.on('data', (d) => { this.stderr += d.toString(); });
22
- this.rl = createInterface({ input: this.child.stdout, terminal: false });
23
- this.rl.on('line', (line) => this._onLine(line));
24
- }
25
-
26
- _onLine(rawLine) {
27
- if (!rawLine.trim()) return;
28
- this.rawLines.push(rawLine);
29
- let msg;
30
- try {
31
- msg = JSON.parse(rawLine);
32
- } catch {
33
- return;
34
- }
35
- this.messages.push(msg);
36
- if (msg.method === undefined && (msg.result !== undefined || msg.error !== undefined)) {
37
- const p = this.pending.get(msg.id);
38
- if (p) {
39
- this.pending.delete(msg.id);
40
- if (msg.error) p.reject(new Error(msg.error.message));
41
- else p.resolve(msg.result);
42
- }
43
- return;
44
- }
45
- if (msg.method === 'roots/list') {
46
- Promise.resolve(this.rootsHandler ? this.rootsHandler() : [])
47
- .then((roots) => {
48
- // A scenario's rootsHandler returns either a bare path (wrapped as a file:// URI here,
49
- // the common case) or a ready-made root object (e.g. {uri: 'not-a-file-uri'} or a
50
- // pre-encoded file:// URI) when it needs to control the URI itself -- non-file schemes,
51
- // percent-encoding, or more than one root.
52
- this._write({
53
- jsonrpc: '2.0',
54
- id: msg.id,
55
- result: { roots: roots.map((r) => (typeof r === 'string' ? { uri: `file://${r}` } : r)) },
56
- });
57
- });
58
- }
59
- }
60
-
61
- _write(obj) {
62
- this.child.stdin.write(`${JSON.stringify(obj)}\n`);
63
- }
64
-
65
- writeRaw(text) {
66
- this.child.stdin.write(text.endsWith('\n') ? text : `${text}\n`);
67
- }
68
-
69
- request(method, params) {
70
- const id = this.nextId++;
71
- return new Promise((resolve, reject) => {
72
- this.pending.set(id, { resolve, reject });
73
- this._write({ jsonrpc: '2.0', id, method, params });
74
- });
75
- }
76
-
77
- notify(method, params) {
78
- this._write({ jsonrpc: '2.0', method, params });
79
- }
80
-
81
- async waitFor(predicate, timeoutMs = 3000) {
82
- const start = Date.now();
83
- for (;;) {
84
- const hit = this.messages.find(predicate);
85
- if (hit) return hit;
86
- if (Date.now() - start > timeoutMs) throw new Error('timeout waiting for a matching message');
87
- await new Promise((r) => setTimeout(r, 20));
88
- }
89
- }
90
-
91
- async initialize(capabilities = {}) {
92
- const result = await this.request('initialize', { protocolVersion: '2024-11-05', capabilities });
93
- this.notify('notifications/initialized');
94
- return result;
95
- }
96
-
97
- close() {
98
- try { this.child.stdin.end(); } catch { /* already closed */ }
99
- this.rl.close();
100
- this.child.kill();
101
- }
102
- }
@@ -1,92 +0,0 @@
1
- #!/usr/bin/env node
2
- // Drives scripts/somi-mcp.mjs over real stdio JSON-RPC for the somi_config tool: parity with the config
3
- // CLI for every action, the host-root requirement for writes, argument rejection, and a broken config.
4
- // Invoked from tests/scripts/somi-config.sh. CLAUDE_PROJECT_DIR is always set explicitly, so a run inside
5
- // a Claude Code shell cannot change what a case means.
6
-
7
- import { execFileSync } from 'node:child_process';
8
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, symlinkSync } from 'node:fs';
9
- import { tmpdir } from 'node:os';
10
- import path from 'node:path';
11
- import { fileURLToPath } from 'node:url';
12
- import { McpClient } from './somi-mcp-client.mjs';
13
-
14
- const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
15
- const SERVER = path.join(ROOT, 'scripts', 'somi-mcp.mjs');
16
- const CFG_CLI = path.join(ROOT, 'scripts', 'somi-config.mjs');
17
- let pass = 0; let fail = 0;
18
- const check = (name, got, want) => {
19
- if (JSON.stringify(got) === JSON.stringify(want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
20
- };
21
- const tmpRoot = mkdtempSync(path.join(tmpdir(), 'somi-mcp-config-'));
22
- const fresh = () => { const d = path.join(tmpRoot, `p${Math.random().toString(36).slice(2)}`); mkdirSync(d, { recursive: true }); return d; };
23
- const projWith = (body) => { const d = fresh(); mkdirSync(path.join(d, '.somi')); writeFileSync(path.join(d, '.somi', 'config.json'), body); return d; };
24
- async function withClient(root, fn, extraEnv = {}) {
25
- const client = new McpClient(SERVER, { env: { CLAUDE_PROJECT_DIR: root, ...extraEnv } });
26
- try { await client.initialize(); return await fn(client); } finally { client.close(); }
27
- }
28
- const call = (client, args) => client.request('tools/call', { name: 'somi_config', arguments: args });
29
- const text = (r) => r?.content?.[0]?.text ?? '';
30
- const exits = (r, code) => [r.isError, text(r).endsWith(`(exit ${code})`)];
31
-
32
- console.log('== somi_config over MCP ==');
33
-
34
- const viaMcp = fresh(); const viaCli = fresh();
35
- await withClient(viaMcp, async (client) => {
36
- const steps = [['init'], ['show'], ['get', 'cost.ceiling'], ['set', 'cost.ceiling', 'low'], ['set', 'cost.agents.somi-designer', 'medium'], ['get', 'cost.agents.somi-designer'], ['unset', 'cost.agents.somi-designer'], ['show'], ['set', 'cost.bogus', 'low'], ['set', 'cost.ceiling', 'turbo']];
37
- for (const [action, ...kv] of steps) {
38
- let want; let code = 0;
39
- try { want = execFileSync(process.execPath, [CFG_CLI, action, ...kv, '--project-dir', viaCli], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, SOMI_COST_CEILING: '' } }).trimEnd(); } catch (e) { code = e.status; }
40
- const r = await call(client, { action, key: kv[0], value: kv[1], project_dir: viaMcp });
41
- check(`${[action, ...kv].join(' ')}: ${code === 0 ? 'same JSON as the CLI' : `error with exit ${code}`}`, code === 0 ? [r.isError, text(r)] : exits(r, code), code === 0 ? [undefined, want] : [true, true]);
42
- }
43
- check('both projects hold the same bytes after the same steps', readFileSync(path.join(viaMcp, '.somi', 'config.json'), 'utf8'), readFileSync(path.join(viaCli, '.somi', 'config.json'), 'utf8'));
44
- for (const args of [{ action: 'drop' }, { action: 'get', key: '--project-dir' }, { action: 'set', key: 'cost.ceiling', value: 5 }, { action: 'get', key: 'cost.ceiling\u0000x' }, { action: 'set', key: 'cost.ceiling', value: 'low\nx' }]) {
45
- check(`rejects ${JSON.stringify(args)} with 64`, exits(await call(client, { ...args, project_dir: viaMcp }), 64), [true, true]);
46
- }
47
- }, { CLAUDE_PLUGIN_ROOT: ROOT });
48
- const bad = projWith('{ not json');
49
- await withClient(bad, async (client) => {
50
- const r = await call(client, { action: 'set', key: 'cost.ceiling', value: 'low', project_dir: bad });
51
- check('an unparsable config: exit 67, file untouched', [...exits(r, 67), readFileSync(path.join(bad, '.somi', 'config.json'), 'utf8')], [true, true, '{ not json']);
52
- });
53
- // No host root: reads work from project_dir, writes are refused and nothing is created.
54
- const lone = fresh();
55
- await withClient('', async (client) => {
56
- for (const args of [{ action: 'set', key: 'cost.ceiling', value: 'low' }, { action: 'unset', key: 'cost.agents.somi-coder' }, { action: 'init' }]) {
57
- const r = await call(client, { ...args, project_dir: lone });
58
- check(`without a host root ${args.action} is refused (67)`, [...exits(r, 67), /no host project root/.test(text(r)), existsSync(path.join(lone, '.somi'))], [true, true, true, false]);
59
- }
60
- const r = await call(client, { action: 'show', project_dir: lone });
61
- check('without a host root show still works from project_dir', [r.isError, JSON.parse(text(r)).exists], [undefined, false]);
62
- const hp = fresh(); mkdirSync(path.join(hp, '.somi')); writeFileSync(path.join(hp, '.somi', 'config.json'), '{"cost":{"ceiling":"high"}}\n');
63
- const h = await call(client, { action: 'show', project_dir: hp, host: 'copilot' });
64
- check('show with host copilot passes --host through: the unmapped warning appears', [h.isError, JSON.parse(text(h)).warnings.some((w) => w.startsWith('copilot has no model mapping'))], [undefined, true]);
65
- const hs = await call(client, { action: 'set', key: 'cost.ceiling', value: 'high', project_dir: lone, host: 'copilot' });
66
- check('host on a non-show action is refused (64) before anything runs', exits(hs, 64), [true, true]);
67
- });
68
- // With a host root the CLI receives the real path of the root.
69
- const hostReal = fresh(); const alias = path.join(fresh(), 'alias'); symlinkSync(hostReal, alias);
70
- await withClient(alias, async (client) => {
71
- const r = await call(client, { action: 'init', project_dir: alias });
72
- check('a host root reached through a symlink is passed to the CLI by real path and works', [r.isError, existsSync(path.join(realpathSync(hostReal), '.somi', 'config.json'))], [undefined, true]);
73
- });
74
-
75
- // Lowering needs the user. With no CLAUDE_PLUGIN_ROOT (a heuristic for "no hook can ask") the tool refuses
76
- // a lowering; with it set the hook asks instead, so the tool does not refuse.
77
- for (const [label, env, lowersOk] of [['without CLAUDE_PLUGIN_ROOT', { CLAUDE_PLUGIN_ROOT: '' }, false], ['with CLAUDE_PLUGIN_ROOT set', { CLAUDE_PLUGIN_ROOT: ROOT, COPILOT_PLUGIN_ROOT: '' }, true], ['under Copilot CLI (COPILOT_PLUGIN_ROOT set too: its tool name escapes the hook matcher)', { CLAUDE_PLUGIN_ROOT: ROOT, COPILOT_PLUGIN_ROOT: ROOT }, false]]) {
78
- const p = fresh();
79
- await withClient(p, async (client) => {
80
- await call(client, { action: 'init', project_dir: p });
81
- const lower = await call(client, { action: 'set', key: 'cost.agents.somi-coder', value: 'low', project_dir: p });
82
- const onDisk = JSON.parse(readFileSync(path.join(p, '.somi', 'config.json'), 'utf8')).cost.agents;
83
- const raise = await call(client, { action: 'set', key: 'cost.agents.somi-coder', value: 'high', project_dir: p });
84
- const unsetPin = await call(client, { action: 'unset', key: 'cost.agents.somi-designer', project_dir: p });
85
- check(`${label}: a lowering set ${lowersOk ? 'goes through (the hook asks)' : 'is refused with 64 and the fixed message'}`, lowersOk ? [lower.isError, onDisk['somi-coder']] : [...exits(lower, 64), /this change lowers a tier and needs the user/.test(text(lower))], lowersOk ? [undefined, 'low'] : [true, true, true]);
86
- check(`${label}: a raise is not refused`, raise.isError, undefined);
87
- check(`${label}: an unset of a pin at the ceiling or above ${lowersOk ? 'goes through' : 'is judged by the same rule'}`, lowersOk ? unsetPin.isError : [unsetPin.isError, /lowers a tier/.test(text(unsetPin))], lowersOk ? undefined : [true, true]);
88
- }, env);
89
- }
90
-
91
- console.log(`somi_config MCP tests: ${pass} ok, ${fail} failed`);
92
- process.exit(fail === 0 ? 0 : 1);