@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
@@ -1,261 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Guard for "this change lowers a tier and needs the user": the pure rules (scripts/lib/cost-lowering.mjs), the
3
- # PreToolUse hook (hooks/pre-tool/guard-cost-lowering.mjs) that asks on the somi_config MCP tool and on
4
- # Write/Edit/MultiEdit of .somi/config.json, and the CLI's --refuse-lowering. The rules and the fail-closed
5
- # behaviour are also proven red on mutated copies.
6
- set -uo pipefail
7
-
8
- ROOT_REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
9
- HOOK="$ROOT_REPO/hooks/pre-tool/guard-cost-lowering.mjs"
10
- CLI="$ROOT_REPO/scripts/somi-config.mjs"
11
-
12
- pass=0; fail=0
13
- ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }
14
- bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
15
- check() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (want '$3', got '$2')"; fi; }
16
-
17
- echo "== cost lowering =="
18
-
19
- TMP="$(mktemp -d)"
20
- trap 'chmod -R u+rwx "$TMP" 2>/dev/null; rm -rf "$TMP"' EXIT
21
-
22
- # --- the pure rules ----------------------------------------------------------------------------------
23
- # $1 = lib dir; stdin = JS using L (cost-lowering), D (defaults) and `res(before, after)` -> "true|false:reasonCount"
24
- rules() {
25
- node --input-type=module -e "
26
- const L = await import('$1/cost-lowering.mjs'); const D = await import('$1/cost-defaults.mjs');
27
- const d = () => D.buildDefaultConfig(); const mod = (f) => { const c = d(); f(c.cost); return c; };
28
- const r = (b, a) => { const v = L.lowers(b, a); return v.lowers + ':' + v.reasons.length; };
29
- const out = [];
30
- const t = (n, got, want) => out.push((got === want ? 'ok' : 'FAIL') + '\t' + n + (got === want ? '' : ' (want ' + want + ', got ' + got + ')'));
31
- t('a no-op never lowers', r(d(), d()), 'false:0');
32
- t('init from an absent file (defaults) does not lower', r({}, d()), 'false:0');
33
- t('raising the ceiling does not lower', r(d(), mod((c) => { c.ceiling = 'high'; })), 'false:0');
34
- t('raising an agent does not lower', r(d(), mod((c) => { c.agents['somi-coder'] = 'high'; })), 'false:0');
35
- t('adding a model mapping needs the user (remap)', L.lowers(d(), mod((c) => { c.mapping = { copilot: { low: 'a', medium: 'b', high: 'c' } }; })).reasons.join('|'), L.REASONS.mapping);
36
- t('changing one mapped model needs the user', L.lowers(mod((c) => { c.mapping = { h: { low: 'a', medium: 'b', high: 'c' } }; }), mod((c) => { c.mapping = { h: { low: 'a', medium: 'b', high: 'cheap' } }; })).reasons.join('|'), L.REASONS.mapping);
37
- t('reordering a preference list needs the user', r(mod((c) => { c.mapping = { h: { low: 'a', medium: 'b', high: ['x', 'y'] } }; }), mod((c) => { c.mapping = { h: { low: 'a', medium: 'b', high: ['y', 'x'] } }; })), 'true:1');
38
- t('an identical mapping is a no-op', r(mod((c) => { c.mapping = { h: { low: 'a', medium: 'b', high: 'c' } }; }), mod((c) => { c.mapping = { h: { low: 'a', medium: 'b', high: 'c' } }; })), 'false:0');
39
- t('pinning security-reviewer to high does not lower', r({ cost: { ceiling: 'low' } }, { cost: { ceiling: 'low', agents: { 'somi-security-reviewer': 'high' } } }), 'false:0');
40
- t('lowering the ceiling lowers (unpinned agents drop)', L.lowers({ cost: { ceiling: 'high' } }, { cost: { ceiling: 'medium' } }).reasons.includes(L.REASONS.ceiling), true);
41
- t('lowering an agent lowers', L.lowers(d(), mod((c) => { c.agents['somi-coder'] = 'low'; })).reasons.join('|'), L.REASONS.agent);
42
- t('security-reviewer pinned low is flagged', L.lowers(d(), mod((c) => { c.agents['somi-security-reviewer'] = 'low'; })).reasons.includes(L.REASONS.security), true);
43
- t('an explicit low security-reviewer pin is flagged even when unchanged from before', L.lowers(mod((c) => { c.agents['somi-security-reviewer'] = 'low'; }), mod((c) => { c.agents['somi-security-reviewer'] = 'low'; c.agents['somi-coder'] = 'high'; })).reasons.includes(L.REASONS.security), true);
44
- t('security-reviewer left to a medium ceiling is flagged on any real change', L.lowers({ cost: { ceiling: 'medium' } }, { cost: { ceiling: 'medium', agents: { 'somi-coder': 'high' } } }).reasons.includes(L.REASONS.security), true);
45
- t('removing a pin above the ceiling lowers, with its own reason', L.lowers({ cost: { ceiling: 'low', agents: { 'somi-designer': 'high', 'somi-security-reviewer': 'high' } } }, { cost: { ceiling: 'low', agents: { 'somi-security-reviewer': 'high' } } }).reasons.join('|'), L.REASONS.pin);
46
- t('removing a pin at or below the ceiling does not lower', r({ cost: { ceiling: 'medium', agents: { 'somi-coder': 'low', 'somi-security-reviewer': 'high' } } }, { cost: { ceiling: 'medium', agents: { 'somi-coder': 'medium', 'somi-security-reviewer': 'high' } } }), 'false:0');
47
- t('an unparsable after lowers', r(d(), null), 'true:1');
48
- t('a non-object after lowers', r(d(), [1]), 'true:1');
49
- t('an invalid cost block in after lowers', r(d(), { cost: { agents: { 'somi-coder': 'turbo' } } }), 'true:1');
50
- t('an unknown cost key in after lowers', r(d(), { cost: { cieling: 'low' } }), 'true:1');
51
- t('a tolerant before: a bad value in before does not throw', r({ cost: { ceiling: 'turbo', agents: 5 } }, d()), 'false:0');
52
- t('an agent outside the default table is compared too', L.lowers({ cost: { agents: { mine: 'high' } } }, { cost: { agents: { mine: 'low' } } }).lowers, true);
53
- t('deleting cost.ceiling lowers whatever state exists later (the worst case is judged)', L.lowers({ cost: { ceiling: 'medium', agents: { 'somi-security-reviewer': 'high' } } }, { cost: { agents: { 'somi-security-reviewer': 'high' } } }).reasons.join('|'), L.REASONS.ceiling);
54
- t('deleting a ceiling that was already low does not lower', r({ cost: { ceiling: 'low', agents: { 'somi-security-reviewer': 'high' } } }, { cost: { agents: { 'somi-security-reviewer': 'high' } } }), 'false:0');
55
- t('replacing the ceiling with a higher one does not lower', r({ cost: { ceiling: 'medium', agents: { 'somi-security-reviewer': 'high' } } }, { cost: { ceiling: 'high', agents: { 'somi-security-reviewer': 'high' } } }), 'false:0');
56
- t('unpinning a medium pin in a config without a ceiling lowers (worst case)', L.lowers({ cost: { agents: { 'somi-coder': 'medium', 'somi-security-reviewer': 'high' } } }, { cost: { agents: { 'somi-security-reviewer': 'high' } } }).reasons.join('|'), L.REASONS.pin);
57
- t('reasons are fixed strings only', JSON.stringify(Object.values(L.REASONS).every((x) => typeof x === 'string')), 'true');
58
- console.log(out.join('\n'));" 2>&1
59
- }
60
- tally() { while IFS=$'\t' read -r s n; do case "$s" in ok) ok "$n" ;; FAIL) bad "$n" ;; *) bad "unexpected output: $s $n" ;; esac; done; }
61
- rules "$ROOT_REPO/scripts/lib" | tally
62
-
63
- # --- the hook -----------------------------------------------------------------------------------------------
64
- export SOMI_AUDIT_LOG="$TMP/audit.log"
65
- proj() { local p; p="$(mktemp -d -p "$TMP")"; mkdir "$p/.somi"; node "$CLI" init --project-dir "$p" > /dev/null; echo "$p"; }
66
- # $1 = hook file, $2 = project root, $3 = payload JSON -> prints "ask" / "silent" / "BAD:<rc>"
67
- verdict() {
68
- local out rc=0
69
- out="$(printf '%s' "$3" | CLAUDE_PROJECT_DIR="$2" node "$1" 2> "$TMP/herr")" || rc=$?
70
- [ "$rc" -eq 0 ] || { echo "BAD:$rc"; return; }
71
- [ -s "$TMP/herr" ] && { echo "BAD:stderr"; return; }
72
- if [ -z "$out" ]; then echo silent; elif printf '%s' "$out" | node -e "const o=JSON.parse(require('fs').readFileSync(0,'utf8')).hookSpecificOutput; process.exit(o.permissionDecision==='ask'&&o.hookEventName==='PreToolUse'?0:1)"; then echo ask; else echo "BAD:shape"; fi
73
- }
74
- reason_of() { printf '%s' "$2" | CLAUDE_PROJECT_DIR="$1" node "$HOOK" | node -e "process.stdout.write(JSON.parse(require('fs').readFileSync(0,'utf8')).hookSpecificOutput.permissionDecisionReason)"; }
75
- mcp() { node -e "console.log(JSON.stringify({tool_name:process.argv[1],tool_input:{action:process.argv[2],key:process.argv[3],value:process.argv[4]}}))" "$1" "$2" "${3:-}" "${4:-}"; }
76
- T=mcp__plugin_somi_somi__somi_config
77
-
78
- P="$(proj)"
79
- check "MCP set that lowers security-reviewer: ask" "$(verdict "$HOOK" "$P" "$(mcp $T set cost.agents.somi-security-reviewer low)")" "ask"
80
- check "MCP set that lowers the ceiling: ask" "$(verdict "$HOOK" "$P" "$(mcp $T set cost.ceiling low)")" "ask"
81
- check "MCP set that lowers one agent: ask" "$(verdict "$HOOK" "$P" "$(mcp $T set cost.agents.somi-coder low)")" "ask"
82
- check "MCP unset of a pin above the ceiling (after the ceiling was lowered by hand): ask" "$(P2="$(proj)"; node "$CLI" set cost.ceiling low --project-dir "$P2" > /dev/null; verdict "$HOOK" "$P2" "$(mcp $T unset cost.agents.somi-designer)")" "ask"
83
- check "MCP set of a model mapping: ask (a remap cannot be ranked)" "$(verdict "$HOOK" "$P" "$(mcp $T set cost.mapping.copilot.high big-a)")" "ask"
84
- case "$(reason_of "$P" "$(mcp $T set cost.mapping.copilot.high big-a)")" in *"(a tier would be mapped to a different model)"*) ok "... and the reason names the remap" ;; *) bad "... and the reason names the remap" ;; esac
85
- cp_json() { node -e 'const [t, k, v] = process.argv.slice(1); console.log(JSON.stringify({tool_name: t, tool_input: k === "-" ? v : {[k]: v, file_text: "{}"}}))' "$@"; }
86
- check "Copilot Write (tool_input.path) to .somi/config.json: ask" "$(verdict "$HOOK" "$P" "$(cp_json Write path "$P/.somi/config.json")")" "ask"
87
- check "Copilot apply_patch touching .somi/config.json: ask" "$(verdict "$HOOK" "$P" "$(cp_json Edit - "$(printf '*** Begin Patch\n*** Update File: .somi/config.json\n@@\n-a\n+b\n*** End Patch\n')")")" "ask"
88
- check "Copilot apply_patch touching the persisted ceiling: ask" "$(verdict "$HOOK" "$P" "$(cp_json Edit - "$(printf '*** Begin Patch\n*** Add File: .somi/somi-state/ceiling.json\n+{}\n*** End Patch\n')")")" "ask"
89
- check "Copilot apply_patch on an ordinary file: silent" "$(verdict "$HOOK" "$P" "$(cp_json Edit - "$(printf '*** Begin Patch\n*** Update File: calc.py\n@@\n-a\n+b\n*** End Patch\n')")")" "silent"
90
- check "MCP raise: silent" "$(verdict "$HOOK" "$P" "$(mcp $T set cost.agents.somi-coder high)")" "silent"
91
- check "MCP no-op: silent" "$(verdict "$HOOK" "$P" "$(mcp $T set cost.agents.somi-coder medium)")" "silent"
92
- check "MCP show / get / init: silent" "$(verdict "$HOOK" "$P" "$(mcp $T show)")|$(verdict "$HOOK" "$P" "$(mcp $T get cost.ceiling)")|$(verdict "$HOOK" "$P" "$(mcp $T init)")" "silent|silent|silent"
93
- check "MCP call with a bad key (the tool rejects it itself): silent" "$(verdict "$HOOK" "$P" "$(mcp $T set cost.bogus low)")" "silent"
94
- check "the bare tool name somi_config is handled too" "$(verdict "$HOOK" "$P" "$(mcp somi_config set cost.ceiling low)")" "ask"
95
- check "an unrelated MCP tool: silent" "$(verdict "$HOOK" "$P" "$(mcp mcp__x__other_tool set cost.ceiling low)")" "silent"
96
- check "an unrelated tool (Bash): silent" "$(verdict "$HOOK" "$P" '{"tool_name":"Bash","tool_input":{"command":"ls"}}')" "silent"
97
- check "the reason is plain text built from fixed strings and names no config content" "$(reason_of "$P" "$(mcp $T set cost.agents.somi-security-reviewer low)")" "SoMi: this change lowers a cost setting (security-reviewer would run below high; an agent tier would be lowered). Confirm only if you intend it."
98
- P2="$(mktemp -d -p "$TMP")"
99
- check "MCP set over an absent config (starts from defaults): raise is silent, lowering asks" "$(verdict "$HOOK" "$P2" "$(mcp $T set cost.ceiling high)")|$(verdict "$HOOK" "$P2" "$(mcp $T set cost.ceiling low)")" "silent|ask"
100
- P2="$(mktemp -d -p "$TMP")"; mkdir "$P2/.somi"; printf '{ not json' > "$P2/.somi/config.json"
101
- check "MCP set when the current config is unparsable (cannot evaluate): ask" "$(verdict "$HOOK" "$P2" "$(mcp $T set cost.ceiling high)")" "ask"
102
-
103
- # Write / Edit / MultiEdit of the config file
104
- wr() { node -e "console.log(JSON.stringify({tool_name:'Write',tool_input:{file_path:process.argv[1],content:process.argv[2]}}))" "$1" "$2"; }
105
- ed() { node -e "console.log(JSON.stringify({tool_name:process.argv[1],tool_input:JSON.parse(process.argv[2])}))" "$1" "$2"; }
106
- CFG="$P/.somi/config.json"
107
- LOWCONTENT='{"cost":{"ceiling":"low"}}'
108
- check "Write of lowering content to the config: ask" "$(verdict "$HOOK" "$P" "$(wr "$CFG" "$LOWCONTENT")")" "ask"
109
- check "Write of the same content back: silent" "$(verdict "$HOOK" "$P" "$(wr "$CFG" "$(cat "$CFG")")")" "silent"
110
- check "Write of raising content: silent" "$(verdict "$HOOK" "$P" "$(wr "$CFG" "$(node -e "const c=JSON.parse(require('fs').readFileSync('$CFG','utf8')); c.cost.ceiling='high'; console.log(JSON.stringify(c))")")")" "silent"
111
- check "Write of unparsable content: ask" "$(verdict "$HOOK" "$P" "$(wr "$CFG" '{ nope')")" "ask"
112
- check "Write of a relative path: resolved against the project root" "$(verdict "$HOOK" "$P" "$(wr '.somi/config.json' "$LOWCONTENT")")" "ask"
113
- check "Write of .somi/../.somi/config.json: the same file, ask" "$(verdict "$HOOK" "$P" "$(wr "$P/.somi/../.somi/config.json" "$LOWCONTENT")")" "ask"
114
- check "Write of another file: silent" "$(verdict "$HOOK" "$P" "$(wr "$P/other.json" "$LOWCONTENT")")|$(verdict "$HOOK" "$P" "$(wr "$P/.somi/other.json" "$LOWCONTENT")")" "silent|silent"
115
- check "Edit that lowers (the ceiling string): ask" "$(verdict "$HOOK" "$P" "$(ed Edit "$(node -e "console.log(JSON.stringify({file_path:'$CFG',old_string:'\"ceiling\": \"medium\"',new_string:'\"ceiling\": \"low\"'}))")")")" "ask"
116
- check "Edit that raises: silent" "$(verdict "$HOOK" "$P" "$(ed Edit "$(node -e "console.log(JSON.stringify({file_path:'$CFG',old_string:'\"somi-coder\": \"medium\"',new_string:'\"somi-coder\": \"high\"'}))")")")" "silent"
117
- check "Edit whose old_string is absent (cannot apply): ask" "$(verdict "$HOOK" "$P" "$(ed Edit "$(node -e "console.log(JSON.stringify({file_path:'$CFG',old_string:'NOT-THERE',new_string:'x'}))")")")" "ask"
118
- check "Edit with a non-unique old_string and no replace_all (the tool would fail): ask" "$(verdict "$HOOK" "$P" "$(ed Edit "$(node -e "console.log(JSON.stringify({file_path:'$CFG',old_string:'\"high\"',new_string:'\"low\"'}))")")")" "ask"
119
- check "Edit with replace_all that lowers every high pin: ask" "$(verdict "$HOOK" "$P" "$(ed Edit "$(node -e "console.log(JSON.stringify({file_path:'$CFG',old_string:'\"high\"',new_string:'\"low\"',replace_all:true}))")")")" "ask"
120
- check "Edit of another file: silent" "$(verdict "$HOOK" "$P" "$(ed Edit "$(node -e "console.log(JSON.stringify({file_path:'$P/README.md',old_string:'a',new_string:'b'}))")")")" "silent"
121
- check "MultiEdit that lowers in its second edit: ask" "$(verdict "$HOOK" "$P" "$(ed MultiEdit "$(node -e "console.log(JSON.stringify({file_path:'$CFG',edits:[{old_string:'\"somi-coder\": \"medium\"',new_string:'\"somi-coder\": \"high\"'},{old_string:'\"ceiling\": \"medium\"',new_string:'\"ceiling\": \"low\"'}]}))")")")" "ask"
122
- check "a Write with no file_path or a non-string one: silent (not a config write)" "$(verdict "$HOOK" "$P" '{"tool_name":"Write","tool_input":{"content":"x"}}')|$(verdict "$HOOK" "$P" '{"tool_name":"Write","tool_input":{"file_path":5,"content":"x"}}')" "silent|silent"
123
- check "empty stdin: silent, exit 0" "$(verdict "$HOOK" "$P" '')" "silent"
124
- # A symlinked .somi: the path still resolves to the project's config and is evaluated
125
- OUT="$(mktemp -d -p "$TMP")"; node "$CLI" init --project-dir "$OUT" > /dev/null
126
- PL="$(mktemp -d -p "$TMP")"; ln -s "$OUT/.somi" "$PL/.somi"
127
- check "Write through a symlinked .somi that resolves to the config: ask (fail closed)" "$(verdict "$HOOK" "$PL" "$(wr "$PL/.somi/config.json" "$LOWCONTENT")")" "ask"
128
- echo x > "$TMP/notadir"
129
- check "audit write failure does not change the answer (unwritable log)" "$(SOMI_AUDIT_LOG="$TMP/notadir/x.log" verdict "$HOOK" "$P" "$(mcp $T set cost.ceiling low)")" "ask"
130
-
131
- # --- CLI --refuse-lowering ----------------------------------------------------------------------------------
132
- cfg() { local p=$1; shift; node "$CLI" "$@" --project-dir "$p" > "$TMP/out" 2> "$TMP/err"; echo $?; }
133
- P="$(proj)"; cp "$P/.somi/config.json" "$TMP/before"
134
- check "--refuse-lowering on a lowering set: exit 64, fixed message, nothing written" "$(cfg "$P" set cost.agents.somi-coder low --refuse-lowering)|$(grep -c 'this change lowers a tier and needs the user: ask them to run node scripts/somi-config.mjs themselves or edit .somi/config.json' "$TMP/err" | tr -d ' ')|$(cmp -s "$P/.somi/config.json" "$TMP/before" && echo same)|$(wc -c < "$TMP/out" | tr -d ' ')" "64|1|same|0"
135
- check "--refuse-lowering on a security-reviewer pin below high: 64" "$(cfg "$P" set cost.agents.somi-security-reviewer medium --refuse-lowering)" "64"
136
- check "--refuse-lowering on a raise succeeds" "$(cfg "$P" set cost.agents.somi-coder high --refuse-lowering)" "0"
137
- check "--refuse-lowering on a no-op succeeds" "$(cfg "$P" set cost.agents.somi-coder high --refuse-lowering)" "0"
138
- check "--refuse-lowering on an unset of a pin above the ceiling: 64" "$(cfg "$P" unset cost.agents.somi-designer --refuse-lowering)|$(cfg "$P" set cost.ceiling low)" "64|0"
139
- check "without the flag a lowering is allowed (the CLI is the user's own tool)" "$(cfg "$P" set cost.agents.somi-coder low)" "0"
140
- check "--refuse-lowering with show is a usage error" "$(cfg "$P" show --refuse-lowering)" "64"
141
-
142
- # --- deleting the ceiling is a lowering whatever state exists, now or later ------------------------------------
143
- persist_low() { CLAUDE_PROJECT_DIR="$1" env -u SOMI_COST_CEILING node "$ROOT_REPO/scripts/somi-dispatch.mjs" resolve --agent somi-coder --ceiling low > /dev/null; }
144
- NOCEIL="$(node --input-type=module -e "const D = await import('$ROOT_REPO/scripts/lib/cost-defaults.mjs'); const c = D.buildDefaultConfig(); delete c.cost.ceiling; process.stdout.write(JSON.stringify(c))")"
145
- P="$(proj)"
146
- check "Write that deletes cost.ceiling (no persisted ceiling yet): ask" "$(verdict "$HOOK" "$P" "$(wr "$P/.somi/config.json" "$NOCEIL")")" "ask"
147
- P2="$(proj)"; persist_low "$P2"
148
- check "... and with a persisted low ceiling: ask" "$(verdict "$HOOK" "$P2" "$(wr "$P2/.somi/config.json" "$NOCEIL")")" "ask"
149
- check "a Write that replaces the ceiling with a higher one: silent" "$(verdict "$HOOK" "$P" "$(wr "$P/.somi/config.json" "$(node -e "const c=JSON.parse(require('fs').readFileSync('$P/.somi/config.json','utf8')); c.cost.ceiling='high'; process.stdout.write(JSON.stringify(c))")")")" "silent"
150
- # The reorder: delete the ceiling, unpin, and only then plant a persisted ceiling.
151
- P="$(proj)"; printf '%s' "$NOCEIL" > "$P/.somi/config.json"; cp "$P/.somi/config.json" "$TMP/before.state"
152
- check "reorder, step 2 (ceiling already deleted): unsetting a medium pin via MCP asks" "$(verdict "$HOOK" "$P" "$(mcp $T unset cost.agents.somi-coder)")" "ask"
153
- check "reorder, step 2: --refuse-lowering exits 64 and writes nothing" "$(cfg "$P" unset cost.agents.somi-coder --refuse-lowering)|$(cmp -s "$P/.somi/config.json" "$TMP/before.state" && echo same)" "64|same"
154
- persist_low "$P"
155
- check "reorder, step 3 (state planted afterwards): the same unset still asks, and is still refused" "$(verdict "$HOOK" "$P" "$(mcp $T unset cost.agents.somi-coder)")|$(cfg "$P" unset cost.agents.somi-coder --refuse-lowering)" "ask|64"
156
- P2="$(proj)"
157
- check "a plain (non-lowering) set on a config that has its ceiling stays silent" "$(verdict "$HOOK" "$P2" "$(mcp $T set cost.agents.somi-coder high)")" "silent"
158
-
159
- # --- the persisted ceiling file and somi_resolve are guarded too ------------------------------------------------------
160
- P="$(proj)"; mkdir -p "$P/.somi/somi-state"
161
- ST="$P/.somi/somi-state/ceiling.json"
162
- check "Write to the persisted ceiling file: ask" "$(verdict "$HOOK" "$P" "$(wr "$ST" '{"ceiling":"low","ceiling_origin":"cli"}')")" "ask"
163
- check "Edit and MultiEdit of it: ask" "$(verdict "$HOOK" "$P" "$(ed Edit "$(node -e "console.log(JSON.stringify({file_path:'$ST',old_string:'a',new_string:'b'}))")")")|$(verdict "$HOOK" "$P" "$(ed MultiEdit "$(node -e "console.log(JSON.stringify({file_path:'$ST',edits:[{old_string:'a',new_string:'b'}]}))")")")" "ask|ask"
164
- check "case variant and relative path: ask" "$(verdict "$HOOK" "$P" "$(wr "$P/.SOMI/Somi-State/Ceiling.JSON" '{}')")|$(verdict "$HOOK" "$P" "$(wr '.somi/somi-state/ceiling.json' '{}')")" "ask|ask"
165
- P3="$(mktemp -d -p "$TMP")"; ALST="$TMP/alias-state"; ln -s "$P3" "$ALST"
166
- check "absent .somi/somi-state reached through an alias of the root: ask" "$(verdict "$HOOK" "$P3" "$(wr "$ALST/.somi/somi-state/ceiling.json" '{}')")" "ask"
167
- check "other files in somi-state: silent" "$(verdict "$HOOK" "$P" "$(wr "$P/.somi/somi-state/other.json" '{}')")" "silent"
168
- rs() { node -e "console.log(JSON.stringify({tool_name:process.argv[1],tool_input:process.argv[2]===''?{agent:'somi-coder'}:{agent:'somi-coder',ceiling:process.argv[2],...(process.argv[3]?{project_dir:process.argv[3]}:{})}}))" "$1" "${2:-}" "${3:-}"; }
169
- R=mcp__plugin_somi_somi__somi_resolve
170
- P="$(proj)"
171
- check "somi_resolve with a ceiling below the current one (config medium): ask" "$(verdict "$HOOK" "$P" "$(rs $R low)")" "ask"
172
- check "a ceiling at or above it, an invalid one, or none: silent" "$(verdict "$HOOK" "$P" "$(rs $R medium)")|$(verdict "$HOOK" "$P" "$(rs $R high)")|$(verdict "$HOOK" "$P" "$(rs $R turbo)")|$(verdict "$HOOK" "$P" "$(rs $R '')")" "silent|silent|silent|silent"
173
- check "the bare name somi_resolve is handled too" "$(verdict "$HOOK" "$P" "$(rs somi_resolve low)")" "ask"
174
- P2="$(proj)"; printf '{}' > "$P2/.somi/config.json"; persist_low "$P2"
175
- check "with no config ceiling and a persisted low one, ceiling low is not a lowering: silent" "$(verdict "$HOOK" "$P2" "$(rs $R low)")" "silent"
176
- P2="$(proj)"; printf '{}' > "$P2/.somi/config.json"
177
- check "with no config ceiling and none persisted (default medium), ceiling low asks" "$(verdict "$HOOK" "$P2" "$(rs $R low)")" "ask"
178
- check "somi_resolve naming a project_dir outside the root: ask" "$(verdict "$HOOK" "$P" "$(rs $R high "$(proj)")")" "ask"
179
- printf '%s' '{ nope' > "$P/.somi/config.json"
180
- check "somi_resolve with a ceiling when the config cannot be read: ask (fail closed)" "$(verdict "$HOOK" "$P" "$(rs $R high)")" "ask"
181
-
182
- # --- which paths are the config -----------------------------------------------------------------------------------
183
- P="$(proj)"; rm "$P/.somi/config.json"
184
- check "Write to an absent config (the file does not exist yet) with a lowering content: ask" "$(verdict "$HOOK" "$P" "$(wr "$P/.somi/config.json" "$LOWCONTENT")")" "ask"
185
- check "case variants of the path: ask" "$(verdict "$HOOK" "$P" "$(wr "$P/.SOMI/Config.json" "$LOWCONTENT")")|$(verdict "$HOOK" "$P" "$(wr "$P/.somi/CONFIG.JSON" "$LOWCONTENT")")" "ask|ask"
186
- P3="$(proj)"; rm -rf "$P3/.somi"
187
- check "absent .somi: a Write of .somi/config.json is still the config" "$(verdict "$HOOK" "$P3" "$(wr "$P3/.somi/config.json" "$LOWCONTENT")")" "ask"
188
- ALIAS="$TMP/alias-root"; ln -s "$P" "$ALIAS"
189
- check "the project root reached through a symlink alias, config absent: ask" "$(verdict "$HOOK" "$P" "$(wr "$ALIAS/.somi/config.json" "$LOWCONTENT")")" "ask"
190
- P4="$(proj)"; ALIAS4="$TMP/alias-root4"; ln -s "$P4" "$ALIAS4"
191
- check "the project root reached through a symlink alias, config present: ask" "$(verdict "$HOOK" "$P4" "$(wr "$ALIAS4/.somi/config.json" "$LOWCONTENT")")" "ask"
192
- P5="$(mktemp -d -p "$TMP")"; rm -rf "$P5/x"; ALIAS5="$TMP/alias-root5"; ln -s "$P5" "$ALIAS5"
193
- check "alias and absent .somi: ask" "$(verdict "$HOOK" "$P5" "$(wr "$ALIAS5/.somi/config.json" "$LOWCONTENT")")" "ask"
194
- OUT2="$(mktemp -d -p "$TMP")"; mkdir "$OUT2/.somi"; PL2="$(mktemp -d -p "$TMP")"; ln -s "$OUT2/.somi" "$PL2/.somi"
195
- check "symlinked .somi with an absent config file: ask" "$(verdict "$HOOK" "$PL2" "$(wr "$PL2/.somi/config.json" "$LOWCONTENT")")" "ask"
196
- check "a config.json elsewhere and a file in .somi with another name: silent" "$(verdict "$HOOK" "$P4" "$(wr "$P4/sub/config.json" "$LOWCONTENT")")|$(verdict "$HOOK" "$P4" "$(wr "$P4/.somi/config.json.bak" "$LOWCONTENT")")" "silent|silent"
197
- P6="$(proj)"; ln -s "$P6/.somi/config.json" "$P6/link.json"
198
- check "a symlink elsewhere that points at the config: ask" "$(verdict "$HOOK" "$P6" "$(wr "$P6/link.json" "$LOWCONTENT")")" "ask"
199
-
200
- # --- project_dir narrowing --------------------------------------------------------------------------------------------
201
- P="$(proj)"; mkdir "$P/sub"; node "$CLI" set cost.ceiling high --project-dir "$P" > /dev/null; node "$CLI" init --project-dir "$P/sub" > /dev/null
202
- node "$CLI" set cost.ceiling high --project-dir "$P/sub" > /dev/null
203
- pd() { node -e "console.log(JSON.stringify({tool_name:process.argv[1],tool_input:{action:'set',key:'cost.ceiling',value:'medium',project_dir:process.argv[2]}}))" "$T" "$1"; }
204
- OTHER="$(proj)"
205
- check "project_dir outside the project root: ask (cannot evaluate)" "$(verdict "$HOOK" "$P" "$(pd "$OTHER")")" "ask"
206
- check "a relative project_dir: ask" "$(verdict "$HOOK" "$P" "$(pd sub)")" "ask"
207
- check "project_dir inside the root is evaluated: lowering THAT directory's ceiling asks" "$(verdict "$HOOK" "$P" "$(pd "$P/sub")")" "ask"
208
- node "$CLI" set cost.ceiling low --project-dir "$P" > /dev/null
209
- check "... and it is that directory's config that counts (the root's is lower, the sub's is high)" "$(verdict "$HOOK" "$P" "$(pd "$P/sub")")" "ask"
210
- check "project_dir equal to the root: a raise is silent" "$(verdict "$HOOK" "$P" "$(node -e "console.log(JSON.stringify({tool_name:process.argv[1],tool_input:{action:'set',key:'cost.ceiling',value:'high',project_dir:process.argv[2]}}))" "$T" "$P")")" "silent"
211
- node "$CLI" set cost.ceiling low --project-dir "$P/sub" > /dev/null
212
- check "project_dir inside the root whose own ceiling is low: setting medium is a raise there, silent" "$(verdict "$HOOK" "$P" "$(pd "$P/sub")")" "silent"
213
-
214
- # --- wording ------------------------------------------------------------------------------------------------------------
215
- P="$(proj)"; printf '%s' '{"cost":{"ceiling":"medium"}}' > "$P/.somi/config.json"
216
- check "a raise that only trips the security-reviewer rule gets its own wording (it does not claim a lowering)" "$(reason_of "$P" "$(mcp $T set cost.agents.somi-coder high)")" "SoMi: after this change security-reviewer would run below high (it is not pinned to high). Confirm only if you intend that."
217
- check "the vendored hooks list names the hook" "$(grep -c guard-cost-lowering "$ROOT_REPO/.claude/settings.json" | tr -d ' ')" "1"
218
-
219
- # --- red proofs on a mutated copy of the plugin tree --------------------------------------------------------
220
- tree() { # $1 = name -> $TMP/$1 holding hooks/ and scripts/ copies
221
- local d="$TMP/$1"; mkdir -p "$d"; cp -r "$ROOT_REPO/hooks" "$ROOT_REPO/scripts" "$d/"
222
- }
223
- mutate() { M_FILE="$TMP/$1/$2" M_FROM="$3" M_TO="$4" node -e "const f=process.env.M_FILE,fs=require('fs'),s=fs.readFileSync(f,'utf8');if(!s.includes(process.env.M_FROM))process.exit(3);fs.writeFileSync(f,s.replace(process.env.M_FROM,()=>process.env.M_TO))" || bad "mutant $1 did not apply"; }
224
- tree no-security; mutate no-security scripts/lib/cost-lowering.mjs "reasons.add(REASONS.security);" ""
225
- r="$(rules "$TMP/no-security/scripts/lib" | grep -c '^FAIL')"
226
- if [ "$r" -gt 0 ]; then ok "red proof: without the security-reviewer rule the rule table fails ($r)"; else bad "red proof: security rule mutant survived"; fi
227
- tree no-ceiling; mutate no-ceiling scripts/lib/cost-lowering.mjs "if (rank(a.ceiling) < rank(b.ceiling) || (ceilingGone && rank(b.ceiling) > rank('low'))) reasons.add(REASONS.ceiling);" ""
228
- r="$(rules "$TMP/no-ceiling/scripts/lib" | grep -c '^FAIL')"
229
- if [ "$r" -gt 0 ]; then ok "red proof: without the ceiling rule the rule table fails ($r)"; else bad "red proof: ceiling rule mutant survived"; fi
230
- tree open; mutate open hooks/pre-tool/guard-cost-lowering.mjs "askPretool(payload, UNEVALUABLE);" "return;"
231
- P="$(proj)"
232
- check "red proof: a hook that fails open stays silent on an edit that cannot apply" "$(verdict "$TMP/open/hooks/pre-tool/guard-cost-lowering.mjs" "$P" "$(ed Edit "$(node -e "console.log(JSON.stringify({file_path:'$P/.somi/config.json',old_string:'NOT-THERE',new_string:'x'}))")")")" "silent"
233
- tree nolower; mutate nolower hooks/pre-tool/guard-cost-lowering.mjs "if (verdict.lowers) askPretool(" "if (false) askPretool("
234
- check "red proof: without the lowers check nothing is asked" "$(verdict "$TMP/nolower/hooks/pre-tool/guard-cost-lowering.mjs" "$P" "$(mcp $T set cost.ceiling low)")" "silent"
235
-
236
- tree noworst; mutate noworst scripts/lib/cost-lowering.mjs " || (ceilingGone && rank(b.ceiling) > rank('low'))" ""
237
- P="$(proj)"
238
- check "red proof: without the worst-case rule deleting cost.ceiling goes unnoticed" "$(verdict "$TMP/noworst/hooks/pre-tool/guard-cost-lowering.mjs" "$P" "$(wr "$P/.somi/config.json" "$NOCEIL")")" "silent"
239
- tree nounpin; mutate nounpin scripts/lib/cost-lowering.mjs "const aTier = removedPin && noCeiling ? worst(name) : a.tier(name);" "const aTier = a.tier(name);"
240
- P="$(proj)"; printf '%s' "$NOCEIL" > "$P/.somi/config.json"
241
- check "red proof: without the unpin worst case the reorder's second step goes unnoticed (hook and CLI)" "$(verdict "$TMP/nounpin/hooks/pre-tool/guard-cost-lowering.mjs" "$P" "$(mcp $T unset cost.agents.somi-coder)")|$(node "$TMP/nounpin/scripts/somi-config.mjs" unset cost.agents.somi-coder --refuse-lowering --project-dir "$P" > /dev/null 2>&1; echo $?)" "silent|0"
242
- tree nostatewr; mutate nostatewr hooks/pre-tool/guard-cost-lowering.mjs "askPretool(payload, STATE_WRITE);" "void 0;"
243
- P="$(proj)"; mkdir -p "$P/.somi/somi-state"
244
- check "red proof: without the state-file rule a Write that plants a ceiling is not asked about" "$(verdict "$TMP/nostatewr/hooks/pre-tool/guard-cost-lowering.mjs" "$P" "$(wr "$P/.somi/somi-state/ceiling.json" '{"ceiling":"low","ceiling_origin":"cli"}')")" "silent"
245
- tree noresolve; mutate noresolve hooks/pre-tool/guard-cost-lowering.mjs "if (VALID_COSTS.indexOf(input.ceiling) < VALID_COSTS.indexOf(effective)) askPretool(payload, RESOLVE_LOWER);" ""
246
- check "red proof: without the somi_resolve rule a lower ceiling is not asked about" "$(verdict "$TMP/noresolve/hooks/pre-tool/guard-cost-lowering.mjs" "$P" "$(rs $R low)")" "silent"
247
- tree stringpath; mutate stringpath hooks/pre-tool/guard-cost-lowering.mjs "const lexical = path.resolve(root, target);" "const lexical = path.resolve(root, target); return lexical === path.join(root, '.somi', 'config.json');"
248
- P="$(proj)"; rm "$P/.somi/config.json"; ALIASX="$TMP/alias-x"; ln -s "$P" "$ALIASX"
249
- check "red proof: with a plain string comparison an aliased path, a case variant slip through" "$(verdict "$TMP/stringpath/hooks/pre-tool/guard-cost-lowering.mjs" "$P" "$(wr "$ALIASX/.somi/config.json" "$LOWCONTENT")")|$(verdict "$TMP/stringpath/hooks/pre-tool/guard-cost-lowering.mjs" "$P" "$(wr "$P/.SOMI/Config.json" "$LOWCONTENT")")" "silent|silent"
250
- tree nooutside; mutate nooutside hooks/pre-tool/guard-cost-lowering.mjs "askPretool(payload, OUTSIDE);" "return;"
251
- P="$(proj)"; OTHER="$(proj)"
252
- check "red proof: without the project_dir check an outside directory is not asked about" "$(verdict "$TMP/nooutside/hooks/pre-tool/guard-cost-lowering.mjs" "$P" "$(pd "$OTHER")")" "silent"
253
-
254
- # An audit log path under /proc used to make fs.mkdirSync({recursive}) spin forever, which hung every hook that
255
- # writes an audit line. The hook must now finish (with an error or not) well inside the timeout.
256
- P="$(proj)"
257
- printf '%s' '{"tool_name":"Bash","tool_input":{"command":"rm -rf /"}}' | CLAUDE_PROJECT_DIR="$P" SOMI_AUDIT_LOG=/proc/nope/x.log timeout 20 node "$ROOT_REPO/hooks/pre-tool/block-dangerous-bash.mjs" >/dev/null 2>&1; rc=$?
258
- if [ "$rc" -ne 124 ]; then ok "an audit log path that cannot be created fails fast instead of hanging the hook (exit $rc)"; else bad "a hook hung on an audit log path under /proc"; fi
259
-
260
- echo "cost lowering tests: $pass ok, $fail failed"
261
- [ "$fail" -eq 0 ] || exit 1
@@ -1,196 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Unit guard for scripts/lib/cost-model.mjs: the cost -> model resolver.
3
- #
4
- # Exercises the three required behaviors: a known (cost, host) pair resolves to its mapped model,
5
- # an unmapped host falls back to no override (its own default) without erroring, and an
6
- # unrecognized cost value — or a mapped host missing that tier — throws rather than silently
7
- # defaulting.
8
- set -uo pipefail
9
-
10
- ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
11
- LIB="$ROOT/scripts/lib/cost-model.mjs"
12
-
13
- pass=0; fail=0
14
- ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }
15
- bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
16
- check() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (want '$3', got '$2')"; fi; }
17
-
18
- # Runs a snippet with the resolver imported as `M`. A function so no case can forget the import
19
- # path and silently test nothing.
20
- run() { node --input-type=module -e "const M = await import('$LIB'); $1"; }
21
- expect_exit() { # $1 = name, $2 = expected exit code, $3 = snippet run via run()
22
- local name="$1" want="$2" snippet="$3" got=0
23
- run "$snippet" >/dev/null 2>&1 || got=$?
24
- if [ "$got" = "$want" ]; then ok "$name"; else bad "$name (expected exit $want, got $got)"; fi
25
- }
26
-
27
- echo "== cost model resolver =="
28
-
29
- # --- a known (cost, host) pair resolves to its mapped model ----------------------
30
- check "low/claude-code resolves to haiku" \
31
- "$(run 'process.stdout.write(M.resolveModel("low", "claude-code"))')" "haiku"
32
- check "medium/claude-code resolves to sonnet" \
33
- "$(run 'process.stdout.write(M.resolveModel("medium", "claude-code"))')" "sonnet"
34
- check "high/claude-code resolves to opus" \
35
- "$(run 'process.stdout.write(M.resolveModel("high", "claude-code"))')" "opus"
36
- expect_exit "a known pair resolves without throwing" 0 \
37
- 'M.resolveModel("medium", "claude-code")'
38
-
39
- # --- an unmapped host falls back to its own default, without erroring ------------
40
- check "unmapped host returns null (no override), not a guessed model" \
41
- "$(run 'process.stdout.write(String(M.resolveModel("medium", "some-future-host")))')" "null"
42
- expect_exit "an unmapped host does not error" 0 \
43
- 'M.resolveModel("medium", "some-future-host")'
44
- check "a prototype-chain host name is treated as unmapped, not inherited" \
45
- "$(run 'process.stdout.write(String(M.resolveModel("medium", "constructor")))')" "null"
46
-
47
- # --- a mapped model value must look like a model identifier, not just any non-empty string ------
48
- # Built from harmless shell metacharacters -- never a destructive command.
49
- HOSTILE_MODEL='opus; echo pwned; `id`; $(id)'
50
- expect_exit "a hostile mapped model value is rejected, not resolved" 1 \
51
- "M.resolveModel(\"high\", \"hostile-host\", { \"hostile-host\": { \"high\": \"$HOSTILE_MODEL\" } })"
52
- hostile_out="$(run "process.stdout.write(M.resolveModel(\"high\", \"hostile-host\", { \"hostile-host\": { \"high\": \"$HOSTILE_MODEL\" } }))" 2>/dev/null)"
53
- check "the hostile model value produces no stdout before dying" "$hostile_out" ""
54
- check "the thrown error names the bad value, not a generic message" \
55
- "$(run "try { M.resolveModel(\"high\", \"hostile-host\", { \"hostile-host\": { \"high\": \"$HOSTILE_MODEL\" } }); } catch (e) { process.stdout.write(String(e.message.includes('is not a valid model identifier'))); }")" \
56
- "true"
57
- check "every shipped HOST_MODELS value passes the model-identifier pattern" \
58
- "$(run 'let bad = 0; for (const host of Object.keys(M.HOST_MODELS)) { for (const c of M.VALID_COSTS) { try { M.resolveModel(c, host); } catch { bad++; } } } process.stdout.write(String(bad))')" \
59
- "0"
60
-
61
- # --- an unrecognized cost value fails loudly, never silently ---------------------
62
- expect_exit "an invalid cost value throws (uncaught, not swallowed)" 1 \
63
- 'M.resolveModel("critical", "claude-code")'
64
- check "the thrown error names the bad value, not a generic message" \
65
- "$(run 'try { M.resolveModel("critical", "claude-code"); } catch (e) { process.stdout.write(e.message); }')" \
66
- 'cost-model: unrecognized cost "critical" (expected one of low|medium|high)'
67
-
68
- # --- a mapped host missing that specific tier is malformed data, not a silent default --
69
- expect_exit "a mapped host missing the requested tier throws, not undefined" 1 \
70
- 'M.resolveModel("high", "partial-host", { "partial-host": { "medium": "x" } })'
71
- check "the thrown error for a missing tier names the host and tier, not a generic message" \
72
- "$(run 'try { M.resolveModel("high", "partial-host", { "partial-host": { "medium": "x" } }); } catch (e) { process.stdout.write(e.message); }')" \
73
- 'cost-model: host "partial-host" has no "high" entry in its mapping'
74
-
75
- # --- mergeHostMapping: the config-driven-override seam resolveModel's third arg composes with ---
76
- check "a new host from the override is merged in" \
77
- "$(run 'process.stdout.write(M.resolveModel("low", "extra-host", M.mergeHostMapping(M.HOST_MODELS, { "extra-host": { "low": "x" } })))')" \
78
- "x"
79
- check "an override for an existing host replaces its whole tier map, not merged tier-by-tier" \
80
- "$(run 'const merged = M.mergeHostMapping(M.HOST_MODELS, { "claude-code": { "low": "y" } }); process.stdout.write(String(merged["claude-code"].medium))')" \
81
- "undefined"
82
- check "an unmapped host stays unmapped when the override does not name it" \
83
- "$(run 'const merged = M.mergeHostMapping(M.HOST_MODELS, { "extra-host": { "low": "x" } }); process.stdout.write(String(merged["some-other-host"]))')" \
84
- "undefined"
85
- check "no override at all returns the defaults unchanged" \
86
- "$(run 'process.stdout.write(String(M.mergeHostMapping(M.HOST_MODELS, undefined) === M.HOST_MODELS))')" \
87
- "true"
88
- expect_exit "a __proto__ key in a JSON.parse'd override is rejected, not silently absorbed" 1 \
89
- 'M.mergeHostMapping(M.HOST_MODELS, JSON.parse(`{"__proto__": {"low": "x"}}`))'
90
- check "rejecting a __proto__ key does not pollute Object.prototype" \
91
- "$(run 'try { M.mergeHostMapping(M.HOST_MODELS, JSON.parse(`{"__proto__": {"low": "x"}}`)); } catch {} process.stdout.write(String(({}).low))')" \
92
- "undefined"
93
- expect_exit "a non-object override is rejected" 1 \
94
- 'M.mergeHostMapping(M.HOST_MODELS, "not-an-object")'
95
- expect_exit "a non-object per-host value in the override is rejected, not passed through" 1 \
96
- 'M.mergeHostMapping(M.HOST_MODELS, { "h": "sonnet" })'
97
- expect_exit "a null per-host value in the override is rejected, not a bare TypeError later" 1 \
98
- 'M.mergeHostMapping(M.HOST_MODELS, { "h": null })'
99
-
100
- # --- mergeHostMapping rejects a tier key outside low|medium|high -- a typo'd tier would otherwise
101
- # sit unused forever, unflagged, since resolveModel() only ever looks up the tier actually selected.
102
- expect_exit "a tier key outside low|medium|high is rejected" 1 \
103
- 'M.mergeHostMapping(M.HOST_MODELS, { "some-host": { "lo": "x" } })'
104
- check "the rejected tier key error names the bad key, the host, and the valid set" \
105
- "$(run 'try { M.mergeHostMapping(M.HOST_MODELS, { "some-host": { "lo": "x" } }); } catch (e) { process.stdout.write(e.message); }')" \
106
- 'cost-model: mapping override for host "some-host" has an unrecognized tier key "lo" (expected one of low|medium|high)'
107
- expect_exit "a valid tier key alongside an invalid one still rejects the whole per-host override" 1 \
108
- 'M.mergeHostMapping(M.HOST_MODELS, { "h": { "low": "x", "typo": "y" } })'
109
- check "a mapping with only valid tier keys is unaffected by the new check" \
110
- "$(run 'process.stdout.write(M.resolveModel("low", "h", M.mergeHostMapping(M.HOST_MODELS, { "h": { "low": "x" } })))')" \
111
- "x"
112
-
113
-
114
- # --- scripts/validate.sh's own derivation idiom stays capture-then-check, not a bare eval --------
115
- # validate.sh once built its cost/model environment from this resolver via a shell idiom: assign the
116
- # node call's stdout to a plain variable with an explicit `|| { ...; exit 1; }`, THEN eval the
117
- # variable -- never `eval "$(node -e ...)"` directly. A PARTIAL failure (one tier's resolveModel
118
- # call throws after earlier tiers already printed) exits node non-zero, but a bare eval hides that
119
- # status from `set -e`: the failing substitution is only an argument being built for eval, not the
120
- # exit status of a simple command, so the earlier assignments land silently and the surrounding
121
- # checks report PASSED with the missing tier never having been derived. Two independent instruments
122
- # below, covering two different things -- neither substitutes for the other: the shape check reads
123
- # the REAL `scripts/validate.sh` and is the only coverage that file's own form actually has
124
- # (it must never gain a bare eval/source of a node derivation, nor the script-form bypass below); the behavioral reproduction that follows runs
125
- # a hardcoded COPY of the idiom -- it never opens `validate.sh` -- and only pins that the
126
- # capture-then-check shell idiom itself, in the abstract, still exits 1 and reports its diagnostic
127
- # under a genuinely partial derivation failure. A rewrite of `validate.sh` that changes its form
128
- # without losing this property would pass the shape checks (correctly) but is not exercised by the
129
- # behavioral block at all.
130
- VALIDATE="$ROOT/scripts/validate.sh"
131
- if grep -vE '^[[:space:]]*#' "$VALIDATE" | grep -qE 'eval[[:space:]]+"\$\(node|source[[:space:]]+<\(node'; then
132
- bad "validate.sh evaluates or sources a node derivation directly (bare eval \"\$(node ...)\" or source <(node ...)) -- set -e cannot see a partial failure through either form"
133
- else
134
- ok "validate.sh does not eval or source a node derivation directly (outside comments) -- the capture-then-check form is intact"
135
- fi
136
-
137
- # The previous literal `eval "$(node -e` match missed a script-form bypass: a longer derivation
138
- # naturally moves from `node -e '...'` to a file, and `eval "$(node scripts/lib/some-file.mjs)"`
139
- # loses the same capture-then-check property without containing `-e` anywhere. Prove the widened
140
- # check actually catches that form, on a scratch copy -- never the real file.
141
- scratch_validate="$(mktemp)"
142
- cp -a "$VALIDATE" "$scratch_validate"
143
- printf '\neval "$(node scripts/lib/derive-dispatch.mjs)"\n' >> "$scratch_validate"
144
- if grep -vE '^[[:space:]]*#' "$scratch_validate" | grep -qE 'eval[[:space:]]+"\$\(node|source[[:space:]]+<\(node'; then
145
- ok "the widened shape check catches a bare eval of a node SCRIPT FILE (not just -e), on a scratch copy"
146
- else
147
- bad "the widened shape check misses a bare eval of a node script file -- a literal '-e' match is too narrow"
148
- fi
149
- rm -f "$scratch_validate"
150
-
151
- # A derivation that prints two assignments and then throws is what a real partial failure looks
152
- # like (e.g. a tier added to VALID_COSTS but missing from a host's mapping, mid-forEach). Run
153
- # validate.sh's exact idiom against it under the same `set -euo pipefail` validate.sh runs under.
154
- partial_derivation() { node -e 'console.log("a=1"); console.log("b=2"); throw new Error("boom");'; }
155
- guarded_out="$(
156
- exec 2>&1
157
- set -euo pipefail
158
- cost_env="$(partial_derivation)" || { echo "cost-model derivation failed; cannot validate cost tiers" >&2; exit 1; }
159
- eval "$cost_env"
160
- echo "REACHED-PAST-THE-GUARD"
161
- )"
162
- guarded_rc=$?
163
- if [ "$guarded_rc" -eq 1 ]; then
164
- ok "the capture-then-check idiom exits 1 on a partial derivation failure"
165
- else
166
- bad "the capture-then-check idiom did not exit 1 on a partial derivation failure (rc=$guarded_rc, out: $guarded_out)"
167
- fi
168
- case "$guarded_out" in
169
- *"cost-model derivation failed; cannot validate cost tiers"*)
170
- ok "the capture-then-check idiom's diagnostic reaches output" ;;
171
- *)
172
- bad "the capture-then-check idiom's diagnostic did not reach output (got: $guarded_out)" ;;
173
- esac
174
- case "$guarded_out" in
175
- *"REACHED-PAST-THE-GUARD"*)
176
- bad "execution continued past a partial derivation failure -- the guard did not stop it" ;;
177
- *)
178
- ok "execution did not continue past a partial derivation failure" ;;
179
- esac
180
-
181
- # --- ordered preference lists (#35) ---------------------------------------------------------------
182
- M2='{h:{low:["m-a","m-b"],medium:"m-c",high:["m-d"]}}'
183
- check "a list resolves to its candidates in order" "$(run "process.stdout.write(JSON.stringify(M.resolveModelCandidates('low','h',$M2)))")" '["m-a","m-b"]'
184
- check "resolveModel on a list returns the first candidate" "$(run "process.stdout.write(M.resolveModel('low','h',$M2))")" "m-a"
185
- check "a plain string is a one-candidate list" "$(run "process.stdout.write(JSON.stringify(M.resolveModelCandidates('medium','h',$M2)))")" '["m-c"]'
186
- check "a one-element list behaves like the string" "$(run "process.stdout.write(M.resolveModel('high','h',$M2))")" "m-d"
187
- check "an unmapped host still gives null candidates" "$(run "process.stdout.write(String(M.resolveModelCandidates('low','nope',$M2)))")" "null"
188
- expect_exit "an empty list throws" 1 "M.resolveModelCandidates('low','h',{h:{low:[]}})"
189
- expect_exit "a list longer than the cap throws" 1 "M.resolveModelCandidates('low','h',{h:{low:Array.from({length:M.MAX_MODEL_CANDIDATES+1},(_, i)=>'m'+i)}})"
190
- expect_exit "a duplicate in the list throws" 1 "M.resolveModelCandidates('low','h',{h:{low:['m-a','m-a']}})"
191
- expect_exit "a non-string in the list throws" 1 "M.resolveModelCandidates('low','h',{h:{low:['m-a',5]}})"
192
- expect_exit "an invalid id in the list throws" 1 "M.resolveModelCandidates('low','h',{h:{low:['m-a','bad id']}})"
193
- expect_exit "a nested list throws" 1 "M.resolveModelCandidates('low','h',{h:{low:[['m-a']]}})"
194
-
195
- echo "cost model tests: $pass ok, $fail failed"
196
- [ "$fail" -eq 0 ] || exit 1
@@ -1,108 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Regression test for scripts/validate.sh's dispatch guard: resolveModel() called
3
- # against a decision's `ceiling` field instead of its `selected` field is a caller that ignores
4
- # per-agent overrides: it would run a unit at the session ceiling, not the tier decideDispatch
5
- # picked. That guard was hand-verified RED once, by eye, and its automated test then dropped to fit a diff cap -- exactly
6
- # the failure this repo has already hit repeatedly (see
7
- # tests/scripts/retirement-gate.sh's own header): a guard proven only by memory of once failing.
8
- #
9
- # Runs the REAL block, extracted verbatim from a throwaway COPY of scripts/validate.sh (never the
10
- # real file, per this repo's cp -a scratch-copy convention) between two markers that are the
11
- # block's own structure (`dispatch_guard_failed=0` .. its second closing `fi`) -- not a second,
12
- # hand-typed copy of the grep pattern that could silently go stale.
13
- #
14
- # Residual, stated honestly: this proves the block's own logic still catches a violation, not that
15
- # scripts/validate.sh hasn't disabled the whole block wholesale (e.g. wrapped in `if false`).
16
- set -uo pipefail
17
-
18
- ROOT_REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
19
- VALIDATE="$ROOT_REPO/scripts/validate.sh"
20
-
21
- pass=0; fail=0
22
- ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }
23
- bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
24
- assert_rc() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (expected exit $3, got $2)"; fi; }
25
- assert_has() { if grep -qF "$2" "$3"; then ok "$1"; else bad "$1 (got: $(cat "$3"))"; fi; }
26
-
27
- echo "== dispatch guard (scripts/validate.sh) =="
28
-
29
- TMP="$(mktemp -d)"
30
- trap 'rm -rf "$TMP"' EXIT
31
-
32
- SCRATCH_VALIDATE="$TMP/validate.sh"
33
- cp -a "$VALIDATE" "$SCRATCH_VALIDATE"
34
-
35
- BLOCK="$(awk '
36
- /^dispatch_guard_failed=0$/ { capture=1 }
37
- capture { print; if ($0 == "fi") { n++; if (n == 2) exit } }
38
- ' "$SCRATCH_VALIDATE")"
39
-
40
- if [ -z "$BLOCK" ]; then
41
- bad "could not extract the guard block from scripts/validate.sh -- its markers may have moved"
42
- echo "dispatch guard tests: $pass ok, $fail failed"
43
- exit 1
44
- fi
45
-
46
- # Falling through with no violation ends on a false `[ ... -ne 0 ]` test (harmless mid-script under
47
- # validate.sh's own flow, which just continues) -- an isolated `bash -c` would otherwise report
48
- # THAT test's own status as its exit code. Appending `exit 0` makes "no violation" unambiguous.
49
- SNIPPET="$BLOCK"$'\nexit 0'
50
-
51
- run_guard() { ( cd "$1" && bash -c "$SNIPPET" ) >"$2" 2>"$3"; } # $1=root $2=stdout-file $3=stderr-file
52
-
53
- # --- RED: a planted violation in a swept file must fail the guard, naming file and line -----------
54
- RED="$TMP/red"; mkdir -p "$RED/agents"
55
- cat > "$RED/agents/example.md" <<'EOF'
56
- ---
57
- name: example
58
- cost: high
59
- ---
60
- Deliberately unsanctioned: resolveModel(decision.ceiling, host).
61
- EOF
62
- red_out="$TMP/red.out"; red_err="$TMP/red.err"
63
- run_guard "$RED" "$red_out" "$red_err"; rc=$?
64
- assert_rc "a planted resolveModel(x.ceiling) call makes the guard exit non-zero" "$rc" 1
65
- assert_has "the guard's report names the violating file and line" \
66
- 'agents/example.md:5:Deliberately unsanctioned: resolveModel(decision.ceiling, host).' "$red_out"
67
- assert_has "the guard's diagnostic explains the violation" 'UNSANCTIONED DISPATCH' "$red_err"
68
-
69
- # --- RED2: the planted violation at the REAL live call site's own path (scripts/somi-dispatch.mjs,
70
- # outside scripts/lib/) must also fail -- the agents/ fixture above can't detect `scripts` dropped
71
- # from the swept roots, or the scripts/lib/ exemption widened to all of scripts/.
72
- RED2="$TMP/red2"; mkdir -p "$RED2/scripts"
73
- cat > "$RED2/scripts/somi-dispatch.mjs" <<'EOF'
74
- // Deliberately unsanctioned, planted at the one live call site's own path (outside scripts/lib/).
75
- resolveModel(decision.ceiling, host);
76
- EOF
77
- red2_out="$TMP/red2.out"; red2_err="$TMP/red2.err"
78
- run_guard "$RED2" "$red2_out" "$red2_err"; rc=$?
79
- assert_rc "a planted violation at scripts/somi-dispatch.mjs (outside scripts/lib/) fails the guard" \
80
- "$rc" 1
81
- assert_has "the guard's report names scripts/somi-dispatch.mjs and its line" \
82
- 'scripts/somi-dispatch.mjs:2:resolveModel(decision.ceiling, host);' "$red2_out"
83
-
84
- # --- CLEAN: no unsanctioned call anywhere in the swept roots must pass -----------------------------
85
- CLEAN="$TMP/clean"; mkdir -p "$CLEAN/agents"
86
- cat > "$CLEAN/agents/example.md" <<'EOF'
87
- ---
88
- name: example
89
- cost: high
90
- ---
91
- Sanctioned: modelForDispatch(decideDispatch(declaredCost, ceiling), host).
92
- EOF
93
- clean_out="$TMP/clean.out"; clean_err="$TMP/clean.err"
94
- run_guard "$CLEAN" "$clean_out" "$clean_err"; rc=$?
95
- assert_rc "a clean tree (no unsanctioned call) passes the guard" "$rc" 0
96
-
97
- # --- EXEMPT: the identical call inside scripts/lib/ is the sanctioned internal, not flagged --------
98
- EXEMPT="$TMP/exempt"; mkdir -p "$EXEMPT/scripts/lib"
99
- cat > "$EXEMPT/scripts/lib/cost-ceiling.mjs" <<'EOF'
100
- // modelForDispatch()'s own sanctioned internal -- this file is the one exemption, by path.
101
- resolveModel(decision.ceiling, host);
102
- EOF
103
- exempt_out="$TMP/exempt.out"; exempt_err="$TMP/exempt.err"
104
- run_guard "$EXEMPT" "$exempt_out" "$exempt_err"; rc=$?
105
- assert_rc "the identical call inside scripts/lib/ is exempt and does not fail the guard" "$rc" 0
106
-
107
- echo "dispatch guard tests: $pass ok, $fail failed"
108
- [ "$fail" -eq 0 ] || exit 1