@skathio/somi 3.1.0 → 4.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 (148) hide show
  1. package/.claude/settings.json +13 -0
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.copilot-extension/extension.json +1 -1
  5. package/.copilot-extension/marketplace.json +2 -2
  6. package/README.md +28 -23
  7. package/VERSION +1 -1
  8. package/agents/{architecture-reviewer.md → somi-architecture-reviewer.md} +10 -11
  9. package/agents/{atlas.md → somi-atlas.md} +3 -5
  10. package/agents/{coder.md → somi-coder.md} +29 -26
  11. package/agents/{designer.md → somi-designer.md} +9 -11
  12. package/agents/{discovery-analyst.md → somi-discovery-analyst.md} +7 -9
  13. package/agents/{impact.md → somi-impact.md} +6 -8
  14. package/agents/{incident.md → somi-incident.md} +2 -4
  15. package/agents/{plan-reviewer.md → somi-plan-reviewer.md} +9 -11
  16. package/agents/{planner.md → somi-planner.md} +19 -27
  17. package/agents/{pr.md → somi-pr.md} +2 -4
  18. package/agents/{refactor-designer.md → somi-refactor-designer.md} +14 -15
  19. package/agents/{refactorer.md → somi-refactorer.md} +14 -15
  20. package/agents/{reviewer.md → somi-reviewer.md} +8 -7
  21. package/agents/{sdlc-reviewer.md → somi-sdlc-reviewer.md} +8 -10
  22. package/agents/{security-reviewer.md → somi-security-reviewer.md} +8 -8
  23. package/agents/{test-strategist.md → somi-test-strategist.md} +4 -6
  24. package/agents/somi.md +27 -14
  25. package/commands/adopt.md +9 -10
  26. package/commands/architecture-review.md +4 -5
  27. package/commands/atlas.md +3 -4
  28. package/commands/code-loop.md +38 -14
  29. package/commands/code-parallel.md +4 -4
  30. package/commands/code.md +24 -15
  31. package/commands/debug.md +8 -9
  32. package/commands/design.md +14 -15
  33. package/commands/discover.md +11 -12
  34. package/commands/impact.md +2 -3
  35. package/commands/incident.md +3 -4
  36. package/commands/plan-loop.md +16 -12
  37. package/commands/plan.md +15 -16
  38. package/commands/pr.md +2 -3
  39. package/commands/refactor-design.md +10 -11
  40. package/commands/refactor.md +7 -8
  41. package/commands/release-readiness.md +6 -7
  42. package/commands/review-panel.md +24 -23
  43. package/commands/review.md +14 -14
  44. package/commands/security-review.md +8 -7
  45. package/commands/ship-loop.md +107 -28
  46. package/commands/ship.md +6 -6
  47. package/commands/somi-config.md +131 -0
  48. package/commands/test-strategy.md +3 -4
  49. package/commands/upgrade.md +4 -5
  50. package/examples/code-review-example.md +1 -1
  51. package/examples/discovery-example.md +1 -1
  52. package/examples/feature-plan-example.md +2 -2
  53. package/hooks/hooks.json +14 -1
  54. package/hooks/lib/common.mjs +64 -1
  55. package/hooks/post-tool/audit-log.mjs +3 -2
  56. package/hooks/pre-tool/block-secret-writes.mjs +12 -11
  57. package/hooks/pre-tool/guard-cost-lowering.mjs +177 -0
  58. package/hooks/pre-tool/guard-protected-paths.mjs +13 -3
  59. package/hooks/session-start/detect-repo-instructions.mjs +27 -2
  60. package/hooks/session-start/ensure-default-config.mjs +121 -0
  61. package/package.json +1 -1
  62. package/rules/00-priorities.md +1 -1
  63. package/rules/30-security-owasp.md +1 -1
  64. package/rules/50-collaboration.md +9 -6
  65. package/rules/CLAUDE.md +11 -10
  66. package/scripts/lib/agent-info.mjs +85 -0
  67. package/scripts/lib/agent-registry.mjs +92 -0
  68. package/scripts/lib/cost-ceiling.mjs +175 -171
  69. package/scripts/lib/cost-config-edit.mjs +102 -0
  70. package/scripts/lib/cost-config.mjs +64 -0
  71. package/scripts/lib/cost-defaults.mjs +51 -0
  72. package/scripts/lib/cost-lowering.mjs +89 -0
  73. package/scripts/lib/cost-model.mjs +37 -22
  74. package/scripts/lib/dispatch-resolver.mjs +68 -50
  75. package/scripts/lib/loop-diff.mjs +96 -0
  76. package/scripts/lib/loop-dispatch.mjs +19 -0
  77. package/scripts/lib/loop-review.mjs +52 -0
  78. package/scripts/lib/run-budget.mjs +28 -0
  79. package/scripts/lib/size-tier.mjs +184 -0
  80. package/scripts/lib/tier-record.mjs +82 -0
  81. package/scripts/size-budget-overrides.json +7 -15
  82. package/scripts/somi-config.mjs +358 -0
  83. package/scripts/somi-dispatch.mjs +1 -1
  84. package/scripts/somi-loop.mjs +71 -96
  85. package/scripts/somi-mcp.mjs +135 -14
  86. package/scripts/somi-tier.mjs +393 -0
  87. package/scripts/validate.sh +37 -215
  88. package/skills/api-design/SKILL.md +1 -1
  89. package/skills/clean-code/SKILL.md +1 -1
  90. package/skills/market-research/SKILL.md +2 -2
  91. package/skills/owasp-defense/SKILL.md +2 -2
  92. package/skills/plan-review/SKILL.md +5 -1
  93. package/skills/reasoning-craft/SKILL.md +1 -1
  94. package/skills/requirements-engineering/SKILL.md +3 -3
  95. package/skills/solid-principles/SKILL.md +1 -1
  96. package/skills/somi-dispatch/SKILL.md +116 -87
  97. package/skills/somi-routing/SKILL.md +88 -1
  98. package/skills/testing-playbook/SKILL.md +2 -2
  99. package/skills/threat-modeling/SKILL.md +3 -3
  100. package/templates/BRIEF.md.tmpl +2 -2
  101. package/templates/DESIGN.md.tmpl +1 -1
  102. package/templates/DOD.md.tmpl +2 -2
  103. package/templates/PHASE.md.tmpl +2 -2
  104. package/templates/RCA.md.tmpl +1 -1
  105. package/templates/REVIEW.md.tmpl +3 -2
  106. package/templates/SDD.md.tmpl +1 -1
  107. package/templates/SPEC.md.tmpl +1 -1
  108. package/templates/TDD.md.tmpl +1 -1
  109. package/tests/hooks/cases/block-secret-writes.json +130 -17
  110. package/tests/hooks/cases/detect-repo-instructions.json +22 -1
  111. package/tests/hooks/cases/guard-protected-paths.json +175 -25
  112. package/tests/scripts/agent-model-frontmatter.sh +38 -0
  113. package/tests/scripts/agent-names.sh +77 -0
  114. package/tests/scripts/check-frontmatter.sh +1 -1
  115. package/tests/scripts/checkpoint-gate.sh +44 -3
  116. package/tests/scripts/convergence-runner.sh +10 -6
  117. package/tests/scripts/cost-ceiling.sh +127 -215
  118. package/tests/scripts/cost-defaults.sh +128 -0
  119. package/tests/scripts/cost-hardcap.sh +329 -0
  120. package/tests/scripts/cost-lowering.sh +261 -0
  121. package/tests/scripts/cost-model.sh +18 -14
  122. package/tests/scripts/dispatch-guard.sh +7 -7
  123. package/tests/scripts/dispatch-line-gate.sh +61 -0
  124. package/tests/scripts/dispatch-reference-gate.sh +13 -13
  125. package/tests/scripts/ensure-default-config.sh +162 -0
  126. package/tests/scripts/eval-runner.sh +9 -9
  127. package/tests/scripts/evals-packaging.sh +127 -20
  128. package/tests/scripts/fixtures/size-tier-cases.json +87 -0
  129. package/tests/scripts/goldens/loop-state-done.json +1 -1
  130. package/tests/scripts/goldens/somi-loop.json +3 -3
  131. package/tests/scripts/lib/agent-registry-tests.mjs +95 -0
  132. package/tests/scripts/lib/brief-only-guard.mjs +27 -0
  133. package/tests/scripts/lib/checkpoint-gate.mjs +40 -3
  134. package/tests/scripts/lib/dispatch-reference-gate.mjs +5 -5
  135. package/tests/scripts/lib/retirement-gate.mjs +7 -2
  136. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +52 -0
  137. package/tests/scripts/lib/size-tier-drift.mjs +74 -0
  138. package/tests/scripts/lib/somi-mcp-config-tests.mjs +92 -0
  139. package/tests/scripts/lib/somi-mcp-tests.mjs +80 -25
  140. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +64 -0
  141. package/tests/scripts/retirement-gate.sh +19 -0
  142. package/tests/scripts/review-panel-seats.sh +2 -2
  143. package/tests/scripts/run.sh +95 -0
  144. package/tests/scripts/size-tier.sh +562 -0
  145. package/tests/scripts/somi-agent-dispatch-contract.sh +20 -11
  146. package/tests/scripts/somi-config.sh +281 -0
  147. package/tests/scripts/somi-dispatch.sh +194 -95
  148. package/tests/scripts/somi-mcp.sh +2 -0
@@ -0,0 +1,261 @@
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
@@ -112,32 +112,22 @@ check "a mapping with only valid tier keys is unaffected by the new check" \
112
112
 
113
113
 
114
114
  # --- scripts/validate.sh's own derivation idiom stays capture-then-check, not a bare eval --------
115
- # validate.sh builds its cost/model environment from this resolver via a shell idiom: assign the
115
+ # validate.sh once built its cost/model environment from this resolver via a shell idiom: assign the
116
116
  # node call's stdout to a plain variable with an explicit `|| { ...; exit 1; }`, THEN eval the
117
117
  # variable -- never `eval "$(node -e ...)"` directly. A PARTIAL failure (one tier's resolveModel
118
118
  # call throws after earlier tiers already printed) exits node non-zero, but a bare eval hides that
119
119
  # status from `set -e`: the failing substitution is only an argument being built for eval, not the
120
120
  # exit status of a simple command, so the earlier assignments land silently and the surrounding
121
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 checks read
123
- # the REAL `scripts/validate.sh` and are the only coverage that file's own form actually has
124
- # (literal revert, or the script-form bypass below); the behavioral reproduction that follows runs
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
125
  # a hardcoded COPY of the idiom -- it never opens `validate.sh` -- and only pins that the
126
126
  # capture-then-check shell idiom itself, in the abstract, still exits 1 and reports its diagnostic
127
127
  # under a genuinely partial derivation failure. A rewrite of `validate.sh` that changes its form
128
128
  # without losing this property would pass the shape checks (correctly) but is not exercised by the
129
129
  # behavioral block at all.
130
130
  VALIDATE="$ROOT/scripts/validate.sh"
131
- if grep -qF 'cost_env="$(node -e' "$VALIDATE"; then
132
- ok "validate.sh still captures the cost-model derivation into a plain variable before checking it"
133
- else
134
- bad "validate.sh no longer captures the cost-model derivation into cost_env -- the guard may have been reverted"
135
- fi
136
- if grep -qF 'cost-model derivation failed; cannot validate cost tiers' "$VALIDATE"; then
137
- ok "validate.sh still has an explicit failure diagnostic for the derivation"
138
- else
139
- bad "validate.sh's derivation-failure diagnostic is gone"
140
- fi
141
131
  if grep -vE '^[[:space:]]*#' "$VALIDATE" | grep -qE 'eval[[:space:]]+"\$\(node|source[[:space:]]+<\(node'; then
142
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"
143
133
  else
@@ -188,5 +178,19 @@ case "$guarded_out" in
188
178
  ok "execution did not continue past a partial derivation failure" ;;
189
179
  esac
190
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
+
191
195
  echo "cost model tests: $pass ok, $fail failed"
192
196
  [ "$fail" -eq 0 ] || exit 1
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env bash
2
- # Regression test for scripts/validate.sh's never-degrade dispatch guard: resolveModel() called
3
- # against a decision's `ceiling` field instead of its `selected` field would silently run a unit at
4
- # whatever the session merely PERMITS, not the tier decideDispatch picked. That guard was
5
- # hand-verified RED once, by eye, and its automated test then dropped to fit a diff cap -- exactly
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
6
  # the failure this repo has already hit repeatedly (see
7
7
  # tests/scripts/retirement-gate.sh's own header): a guard proven only by memory of once failing.
8
8
  #
@@ -24,7 +24,7 @@ bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
24
24
  assert_rc() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (expected exit $3, got $2)"; fi; }
25
25
  assert_has() { if grep -qF "$2" "$3"; then ok "$1"; else bad "$1 (got: $(cat "$3"))"; fi; }
26
26
 
27
- echo "== never-degrade dispatch guard (scripts/validate.sh) =="
27
+ echo "== dispatch guard (scripts/validate.sh) =="
28
28
 
29
29
  TMP="$(mktemp -d)"
30
30
  trap 'rm -rf "$TMP"' EXIT
@@ -39,7 +39,7 @@ BLOCK="$(awk '
39
39
 
40
40
  if [ -z "$BLOCK" ]; then
41
41
  bad "could not extract the guard block from scripts/validate.sh -- its markers may have moved"
42
- echo "never-degrade dispatch guard tests: $pass ok, $fail failed"
42
+ echo "dispatch guard tests: $pass ok, $fail failed"
43
43
  exit 1
44
44
  fi
45
45
 
@@ -104,5 +104,5 @@ exempt_out="$TMP/exempt.out"; exempt_err="$TMP/exempt.err"
104
104
  run_guard "$EXEMPT" "$exempt_out" "$exempt_err"; rc=$?
105
105
  assert_rc "the identical call inside scripts/lib/ is exempt and does not fail the guard" "$rc" 0
106
106
 
107
- echo "never-degrade dispatch guard tests: $pass ok, $fail failed"
107
+ echo "dispatch guard tests: $pass ok, $fail failed"
108
108
  [ "$fail" -eq 0 ] || exit 1
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env bash
2
+ # Gate for the one dispatch line (#38) and native dispatch: the canonical "pass its `model`, start it as
3
+ # its `agent_type`, and put the cost line ..." phrase lives once, between markers in
4
+ # skills/somi-dispatch/SKILL.md, and every copy in commands/*.md and agents/somi.md must match it
5
+ # (whitespace and blockquote markers aside); every command that names the cost line names it through
6
+ # that phrase; the three agents that trim at `low` carry the same requested-tier disclosure; and no
7
+ # dispatch text calls somi_agent to stand in for an agent. Proven red on mutated copies.
8
+ set -uo pipefail
9
+
10
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
11
+ pass=0; fail=0
12
+ ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }
13
+ bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
14
+ echo "== dispatch line gate =="
15
+
16
+ gate() { # $1 = tree root; prints one line per problem
17
+ node --input-type=module - "$1" <<'EOF'
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ const root = process.argv[2];
21
+ const norm = (s) => s.replace(/\n\s*>\s?/g, '\n').replace(/\s+/g, ' ');
22
+ const read = (p) => fs.readFileSync(path.join(root, p), 'utf8');
23
+ const problems = [];
24
+ const skill = read('skills/somi-dispatch/SKILL.md');
25
+ const m = /<!-- dispatch-line:start -->\n([\s\S]*?)\n<!-- dispatch-line:end -->/.exec(skill);
26
+ if (!m) { console.log('skills/somi-dispatch/SKILL.md: no dispatch-line markers'); process.exit(0); }
27
+ const canon = norm(m[1]).trim();
28
+ const COST = 'requested cost: <tier> (not enforced: no mapped model)';
29
+ const files = [...fs.readdirSync(path.join(root, 'commands')).filter((f) => f.endsWith('.md')).map((f) => `commands/${f}`), 'agents/somi.md'];
30
+ for (const f of files) {
31
+ const t = norm(read(f));
32
+ const costLines = t.split(COST).length - 1;
33
+ const canonLines = t.split(canon).length - 1;
34
+ if (costLines !== canonLines) problems.push(`${f}: ${costLines} cost line(s) but ${canonLines} canonical dispatch phrase(s); copy the phrase from the skill's dispatch-line markers`);
35
+ if (/somi_agent\(/.test(t)) problems.push(`${f}: calls somi_agent(...) -- an agent starts as its agent_type, never as text handed to another agent`);
36
+ }
37
+ if (/somi_agent\(/.test(norm(skill))) problems.push('skills/somi-dispatch/SKILL.md: calls somi_agent(...)');
38
+ const DISCLOSE = 'If the briefing said `requested cost: low` (not `dispatched at cost: low`), word it as: "Ran at `low` (requested, not enforced: the host chose the model)."';
39
+ for (const a of ['somi-coder', 'somi-planner', 'somi-refactorer']) {
40
+ if (!norm(read(`agents/${a}.md`)).includes(DISCLOSE)) problems.push(`agents/${a}.md: missing the requested-low disclosure sentence`);
41
+ }
42
+ process.stdout.write(problems.map((p) => `${p}\n`).join(''));
43
+ EOF
44
+ }
45
+
46
+ out="$(gate "$ROOT")"
47
+ if [ -z "$out" ]; then ok "the shipped tree: one dispatch phrase, copied exactly; disclosure in all three; no somi_agent stand-in"; else bad "the shipped tree:"; printf '%s\n' "$out" | sed 's/^/ /'; fi
48
+
49
+ TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
50
+ red() { # $1 = label, $2 = mutation run inside a copy
51
+ rm -rf "$TMP/r"; mkdir -p "$TMP/r"; cp -R "$ROOT/commands" "$ROOT/agents" "$ROOT/skills" "$TMP/r/"
52
+ (cd "$TMP/r" && eval "$2")
53
+ if [ -n "$(gate "$TMP/r")" ]; then ok "red proof: $1"; else bad "red proof: $1 (not caught)"; fi
54
+ }
55
+ red "a command whose copy drifted (agent_type dropped)" "sed -i 's/, start it as its \`agent_type\`,/,/' commands/plan.md"
56
+ red "the canonical phrase edited in the skill only" "sed -i 's/start it as its \`agent_type\`, and put/start it as its \`agent_type\` and put/' skills/somi-dispatch/SKILL.md"
57
+ red "a command that hands agent text to somi_agent" "printf 'call somi_agent({name: \"somi-coder\"}) and start a general-purpose agent\n' >> commands/code.md"
58
+ red "a missing requested-low disclosure" "sed -i 's/requested, not enforced: the host chose the model/requested/' agents/somi-planner.md"
59
+
60
+ echo "dispatch-line-gate tests: $pass ok, $fail failed"
61
+ [ "$fail" -eq 0 ]
@@ -28,25 +28,25 @@ import os from "node:os";
28
28
 
29
29
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "dispatch-gate-unit-"));
30
30
  fs.mkdirSync(path.join(tmp, "agents"));
31
- for (const n of ["coder", "reviewer", "architecture-reviewer"]) {
31
+ for (const n of ["somi-coder", "somi-reviewer", "somi-architecture-reviewer"]) {
32
32
  fs.writeFileSync(path.join(tmp, "agents", n + ".md"), "---\nname: " + n + "\n---\n");
33
33
  }
34
34
  fs.writeFileSync(path.join(tmp, "agents", "somi.md"), "---\nname: somi\n---\n");
35
35
  const names = agentNamesFrom(path.join(tmp, "agents"));
36
36
 
37
37
  const cases = [
38
- ["Brief the `coder` agent via the Task tool with:", "coder"],
39
- ["Task coder ( = /code <slug> )", "coder"],
40
- ["Task the [`reviewer`](../agents/reviewer.md) on a fresh context", "reviewer"],
41
- ["Task [`architecture-reviewer`](../agents/architecture-reviewer.md) (and more)", "architecture-reviewer"],
42
- ["Brief [`agents/coder.md`](../agents/coder.md) via the Task tool with:", "coder"],
38
+ ["Brief the `somi-coder` agent via the Task tool with:", "somi-coder"],
39
+ ["Task somi-coder ( = /code <slug> )", "somi-coder"],
40
+ ["Task the [`somi-reviewer`](../agents/somi-reviewer.md) on a fresh context", "somi-reviewer"],
41
+ ["Task [`somi-architecture-reviewer`](../agents/somi-architecture-reviewer.md) (and more)", "somi-architecture-reviewer"],
42
+ ["Brief [`agents/somi-coder.md`](../agents/somi-coder.md) via the Task tool with:", "somi-coder"],
43
43
  // The newer call-site verbs, and case-insensitivity on all of them.
44
- ["Start the `coder` agent via the Task tool with:", "coder"],
45
- ["Spawn the `reviewer` agent for a fresh-context pass", "reviewer"],
46
- ["Dispatch the `coder` agent with the current findings", "coder"],
47
- ["Run the `reviewer` agent on the same diff", "reviewer"],
48
- ["run the `coder` agent (lowercase verb)", "coder"],
49
- ["brief the `reviewer` agent (lowercase verb)", "reviewer"],
44
+ ["Start the `somi-coder` agent via the Task tool with:", "somi-coder"],
45
+ ["Spawn the `somi-reviewer` agent for a fresh-context pass", "somi-reviewer"],
46
+ ["Dispatch the `somi-coder` agent with the current findings", "somi-coder"],
47
+ ["Run the `somi-reviewer` agent on the same diff", "somi-reviewer"],
48
+ ["run the `somi-coder` agent (lowercase verb)", "somi-coder"],
49
+ ["brief the `somi-reviewer` agent (lowercase verb)", "somi-reviewer"],
50
50
  // A router Tasking another COMMAND, never an agent -- must NOT match.
51
51
  ["Task /code-loop \"<slug> phase <N>, iteration <M>\"", null],
52
52
  // Coincidental English-word / cross-reference prose -- must NOT match (no real call-site shape).
@@ -76,7 +76,7 @@ const refCases = [
76
76
  ["full rules: the `somi-dispatch` skill (`somi_skill`, or `somi:somi-dispatch` on Claude Code) only, nothing else", false],
77
77
  // The real shape every rewritten command reference line now uses -- true because it names
78
78
  // `somi_resolve` literally, not because it mentions the skill by name.
79
- ["Before this `Task`, call `somi_resolve` for `coder` (with `project_dir`), pass its model, and put `dispatched at cost: <tier>` in the briefing; full rules: the `somi-dispatch` skill (`somi_skill`, or `somi:somi-dispatch` on Claude Code).", true],
79
+ ["Before this `Task`, call `somi_resolve` for `somi-coder` (with `project_dir`), pass its model, and put the cost line in the briefing (`dispatched at cost: <tier>` only when `enforced` is true, else `requested cost: <tier> (not enforced: no mapped model)`); full rules: the `somi-dispatch` skill (`somi_skill`, or `somi:somi-dispatch` on Claude Code).", true],
80
80
  // The older full-path markdown-link shape still satisfies it too.
81
81
  ["started per [`skills/somi-dispatch`](../skills/somi-dispatch/SKILL.md)", true],
82
82
  ["no dispatch reference here at all", false],