@skathio/somi 2.2.2 → 3.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 (128) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +8 -2
  3. package/.copilot-extension/extension.json +9 -8
  4. package/.copilot-extension/marketplace.json +2 -2
  5. package/README.md +45 -33
  6. package/VERSION +1 -1
  7. package/agents/architecture-reviewer.md +16 -0
  8. package/agents/atlas.md +102 -0
  9. package/agents/coder.md +66 -22
  10. package/agents/designer.md +20 -16
  11. package/agents/discovery-analyst.md +6 -5
  12. package/agents/impact.md +97 -0
  13. package/agents/incident.md +96 -0
  14. package/agents/plan-reviewer.md +70 -0
  15. package/agents/planner.md +77 -20
  16. package/agents/pr.md +101 -0
  17. package/agents/refactor-designer.md +82 -0
  18. package/agents/refactorer.md +30 -24
  19. package/agents/reviewer.md +28 -25
  20. package/agents/sdlc-reviewer.md +69 -0
  21. package/agents/security-reviewer.md +17 -0
  22. package/agents/somi.md +204 -153
  23. package/agents/test-strategist.md +16 -1
  24. package/commands/adopt.md +21 -7
  25. package/commands/architecture-review.md +8 -5
  26. package/commands/atlas.md +24 -72
  27. package/commands/code-loop.md +46 -15
  28. package/commands/code-parallel.md +6 -4
  29. package/commands/code.md +29 -21
  30. package/commands/debug.md +17 -11
  31. package/commands/design.md +48 -31
  32. package/commands/discover.md +26 -16
  33. package/commands/impact.md +16 -54
  34. package/commands/incident.md +22 -55
  35. package/commands/plan-loop.md +43 -17
  36. package/commands/plan.md +64 -26
  37. package/commands/pr.md +19 -66
  38. package/commands/refactor-design.md +98 -0
  39. package/commands/refactor.md +22 -23
  40. package/commands/release-readiness.md +16 -7
  41. package/commands/review-panel.md +31 -10
  42. package/commands/review.md +21 -14
  43. package/commands/security-review.md +12 -3
  44. package/commands/ship-loop.md +71 -54
  45. package/commands/ship.md +17 -13
  46. package/commands/test-strategy.md +6 -4
  47. package/commands/upgrade.md +10 -8
  48. package/examples/discovery-example.md +2 -2
  49. package/examples/sample-consumer/CLAUDE.md +41 -7
  50. package/examples/sample-consumer/README.md +36 -22
  51. package/hooks/lib/common.mjs +66 -20
  52. package/hooks/post-tool/audit-log.mjs +7 -11
  53. package/hooks/post-tool/lint-changed-files.mjs +8 -11
  54. package/hooks/pre-tool/block-dangerous-bash.mjs +32 -44
  55. package/hooks/pre-tool/block-secret-writes.mjs +6 -9
  56. package/hooks/pre-tool/gate-dep-install.mjs +18 -27
  57. package/hooks/pre-tool/guard-protected-paths.mjs +9 -11
  58. package/hooks/session-start/detect-repo-instructions.mjs +21 -23
  59. package/hooks/user-prompt-submit/inject-workflow-context.mjs +190 -42
  60. package/mcp.json +10 -0
  61. package/package.json +5 -2
  62. package/rules/CLAUDE.md +22 -19
  63. package/scripts/check-links.mjs +218 -0
  64. package/scripts/check-session-artefacts.mjs +149 -0
  65. package/scripts/check-size-budget.mjs +137 -0
  66. package/scripts/generate-digest.mjs +176 -0
  67. package/scripts/lib/cost-ceiling.mjs +317 -0
  68. package/scripts/lib/cost-model.mjs +95 -0
  69. package/scripts/lib/dispatch-resolver.mjs +225 -0
  70. package/scripts/lib/mcp-project-root.mjs +183 -0
  71. package/scripts/size-budget-overrides.json +74 -0
  72. package/scripts/somi-check.mjs +6 -13
  73. package/scripts/somi-dispatch.mjs +141 -0
  74. package/scripts/somi-findings.mjs +4 -5
  75. package/scripts/somi-loop.mjs +181 -13
  76. package/scripts/somi-mcp.mjs +357 -0
  77. package/scripts/validate.sh +691 -30
  78. package/skills/clean-code/SKILL.md +1 -1
  79. package/skills/plan-review/SKILL.md +79 -0
  80. package/skills/rules/SKILL.md +47 -0
  81. package/skills/sdlc-process/SKILL.md +74 -0
  82. package/skills/somi-dispatch/SKILL.md +220 -0
  83. package/skills/somi-routing/SKILL.md +31 -6
  84. package/skills/{test-strategy → testing-playbook}/SKILL.md +1 -1
  85. package/templates/ATLAS.md.tmpl +4 -4
  86. package/templates/BRIEF.md.tmpl +23 -22
  87. package/templates/DECISIONS.md.tmpl +1 -0
  88. package/templates/DESIGN.md.tmpl +5 -5
  89. package/templates/DIARY.md.tmpl +10 -5
  90. package/templates/DOD.md.tmpl +24 -0
  91. package/templates/PROGRESS.md.tmpl +3 -16
  92. package/templates/SOMI-README.md.tmpl +3 -3
  93. package/tests/hooks/cases/inject-workflow-context.json +120 -7
  94. package/tests/hooks/run.sh +20 -11
  95. package/tests/scripts/check-links.sh +105 -0
  96. package/tests/scripts/check-session-artefacts.sh +60 -0
  97. package/tests/scripts/check-size-budget.sh +71 -0
  98. package/tests/scripts/checkpoint-gate.sh +90 -0
  99. package/tests/scripts/convergence-runner.sh +1510 -0
  100. package/tests/scripts/cost-ceiling.sh +343 -0
  101. package/tests/scripts/cost-model.sh +192 -0
  102. package/tests/scripts/dispatch-guard.sh +108 -0
  103. package/tests/scripts/dispatch-reference-gate.sh +173 -0
  104. package/tests/scripts/eval-runner.sh +3691 -0
  105. package/tests/scripts/evals-packaging.sh +117 -0
  106. package/tests/scripts/fixtures/legacy-shard-no-schema.json +50 -0
  107. package/tests/scripts/generate-digest.sh +180 -0
  108. package/tests/scripts/goldens/loop-state-breach.json +1 -0
  109. package/tests/scripts/goldens/loop-state-done.json +1 -0
  110. package/tests/scripts/goldens/somi-loop.json +1 -1
  111. package/tests/scripts/lib/adr-shape.mjs +41 -0
  112. package/tests/scripts/lib/checkpoint-gate.mjs +54 -0
  113. package/tests/scripts/lib/digest-marker-coupling.mjs +52 -0
  114. package/tests/scripts/lib/dispatch-reference-gate.mjs +112 -0
  115. package/tests/scripts/lib/multipass-dependence.mjs +192 -0
  116. package/tests/scripts/lib/multipass-source-identity.mjs +243 -0
  117. package/tests/scripts/lib/reference-pair.mjs +61 -0
  118. package/tests/scripts/lib/retirement-gate.mjs +167 -0
  119. package/tests/scripts/lib/shell-embedded-js.mjs +47 -0
  120. package/tests/scripts/lib/somi-mcp-client.mjs +102 -0
  121. package/tests/scripts/lib/somi-mcp-tests.mjs +401 -0
  122. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +38 -0
  123. package/tests/scripts/retirement-gate.sh +287 -0
  124. package/tests/scripts/review-panel-seats.sh +32 -0
  125. package/tests/scripts/run.sh +184 -2
  126. package/tests/scripts/somi-agent-dispatch-contract.sh +195 -0
  127. package/tests/scripts/somi-dispatch.sh +366 -0
  128. package/tests/scripts/somi-mcp.sh +12 -0
@@ -0,0 +1,343 @@
1
+ #!/usr/bin/env bash
2
+ # Unit guard for scripts/lib/cost-ceiling.mjs: the session cost ceiling.
3
+ #
4
+ # Exercises: re-resolution per dispatch across separate process invocations (state lives on disk,
5
+ # not in memory), a bare .somi/config.json edit cannot move a ceiling already recorded,
6
+ # capability-set selection (allow picks the highest permitted declared member; when none fits, allow
7
+ # at the cheapest declared member instead of blocking, never a tier outside the declared set), and a
8
+ # malformed ceiling or declared set — from config, an env var, or an explicit argument — dying loudly
9
+ # instead of silently disabling the ceiling.
10
+ set -uo pipefail
11
+
12
+ ROOT_REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
13
+ LIB="$ROOT_REPO/scripts/lib/cost-ceiling.mjs"
14
+
15
+ pass=0; fail=0
16
+ ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }
17
+ bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }
18
+ check() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (want '$3', got '$2')"; fi; }
19
+
20
+ # Runs a snippet with the module imported as `C` and `ROOT` bound to a throwaway directory.
21
+ run() { node --input-type=module -e "const C = await import('$LIB'); const ROOT = '$1'; $2"; }
22
+ expect_exit() { # $1 = name, $2 = expected exit code, $3 = root, $4 = snippet
23
+ local name="$1" want="$2" root="$3" snippet="$4" got=0
24
+ run "$root" "$snippet" >/dev/null 2>&1 || got=$?
25
+ if [ "$got" = "$want" ]; then ok "$name"; else bad "$name (expected exit $want, got $got)"; fi
26
+ }
27
+
28
+ echo "== cost ceiling =="
29
+
30
+ TMP="$(mktemp -d)"
31
+ trap 'rm -rf "$TMP"' EXIT
32
+
33
+ # --- bootstrap: no config, no env, no arg -> DEFAULT_CEILING, no overrides array yet -------------
34
+ A="$TMP/a"; mkdir -p "$A/.somi"
35
+ check "first resolve with nothing set bootstraps to the default" \
36
+ "$(run "$A" 'const r = C.resolveCeiling(ROOT, undefined); process.stdout.write(r.ceiling + "," + r.overridden)')" \
37
+ "high,false"
38
+ check "bootstrap writes state with no ceiling_overrides key (lazy creation)" \
39
+ "$(run "$A" 'const fs = await import("node:fs"); const s = JSON.parse(fs.readFileSync(C.ceilingStatePath(ROOT), "utf8")); process.stdout.write(String("ceiling_overrides" in s))')" \
40
+ "false"
41
+
42
+ # --- bootstrap reads .somi/config.json's cost.ceiling exactly once ------------------------------
43
+ B="$TMP/b"; mkdir -p "$B/.somi"
44
+ printf '{"cost": {"ceiling": "low"}}\n' > "$B/.somi/config.json"
45
+ check "bootstrap honours config's cost.ceiling" \
46
+ "$(run "$B" 'process.stdout.write(C.resolveCeiling(ROOT, undefined).ceiling)')" \
47
+ "low"
48
+
49
+ # The loop-cap precedent's central guard, mirrored: a bare config edit AFTER state exists must
50
+ # not move a ceiling already in force.
51
+ printf '{"cost": {"ceiling": "high"}}\n' > "$B/.somi/config.json"
52
+ check "a bare config edit after bootstrap does not move the ceiling already in force" \
53
+ "$(run "$B" 'const r = C.resolveCeiling(ROOT, undefined); process.stdout.write(r.ceiling + "," + r.overridden)')" \
54
+ "low,false"
55
+
56
+ # --- an explicit env var THIS call raises the ceiling and is recorded ---------------------------
57
+ out="$(SOMI_COST_CEILING=high node --input-type=module -e "const C = await import('$LIB'); const r = C.resolveCeiling('$B', undefined); process.stdout.write(r.ceiling+','+r.overridden+','+r.override.field+','+r.override.from+','+r.override.to+','+r.override.source)")"
58
+ check "env override moves the ceiling and reports it" "$out" "high,true,ceiling,low,high,env"
59
+ check "the override was persisted to disk, in a ceiling_overrides array" \
60
+ "$(run "$B" 'const fs = await import("node:fs"); const s = JSON.parse(fs.readFileSync(C.ceilingStatePath(ROOT), "utf8")); process.stdout.write(s.ceiling_overrides.length + "," + s.ceiling_overrides[0].source)')" \
61
+ "1,env"
62
+
63
+ # --- re-resolution: a later bare call keeps the raised ceiling, records no new entry -------------
64
+ check "a later bare call keeps the raised ceiling in force" \
65
+ "$(run "$B" 'const r = C.resolveCeiling(ROOT, undefined); process.stdout.write(r.ceiling + "," + r.overridden)')" \
66
+ "high,false"
67
+ check "no duplicate override entry was recorded for the bare call" \
68
+ "$(run "$B" 'const fs = await import("node:fs"); const s = JSON.parse(fs.readFileSync(C.ceilingStatePath(ROOT), "utf8")); process.stdout.write(String(s.ceiling_overrides.length))')" \
69
+ "1"
70
+
71
+ # --- an explicit argument beats an env var set in the SAME call ---------------------------------
72
+ out="$(SOMI_COST_CEILING=low node --input-type=module -e "const C = await import('$LIB'); const r = C.resolveCeiling('$B', 'medium'); process.stdout.write(r.ceiling+','+r.override.source+','+r.override.from)")"
73
+ check "explicit argument wins over env var, and is recorded with source cli" "$out" "medium,cli,high"
74
+
75
+ # --- resolveCeiling reports WHERE this call's ceiling came from -- this is what lets a dispatcher
76
+ # announce a `low` ceiling honestly, by its real source, not just its bare value. Additive field,
77
+ # checked independently of `ceiling`/`overridden` above so a caller that never reads it stays
78
+ # unaffected. ---------------------------------------------------------------------------------
79
+ DEF="$TMP/source-default"; mkdir -p "$DEF/.somi"
80
+ check "bootstrap with no config, no env, no arg: source is 'default'" \
81
+ "$(run "$DEF" 'process.stdout.write(C.resolveCeiling(ROOT, undefined).source)')" \
82
+ "default"
83
+
84
+ CFGSRC="$TMP/source-config"; mkdir -p "$CFGSRC/.somi"
85
+ printf '{"cost": {"ceiling": "low"}}\n' > "$CFGSRC/.somi/config.json"
86
+ check "bootstrap from .somi/config.json's cost.ceiling: source is 'config'" \
87
+ "$(run "$CFGSRC" 'process.stdout.write(C.resolveCeiling(ROOT, undefined).source)')" \
88
+ "config"
89
+ check "a later bare call against the same state: source is 'state', not 'config' again" \
90
+ "$(run "$CFGSRC" 'process.stdout.write(C.resolveCeiling(ROOT, undefined).source)')" \
91
+ "state"
92
+ check "an explicit CLI argument: source is 'cli' even when it matches the value already on disk" \
93
+ "$(run "$CFGSRC" 'process.stdout.write(C.resolveCeiling(ROOT, "low").source)')" \
94
+ "cli"
95
+ out="$(SOMI_COST_CEILING=low node --input-type=module -e "const C = await import('$LIB'); process.stdout.write(C.resolveCeiling('$CFGSRC', undefined).source)")"
96
+ check "an explicit env var: source is 'env'" "$out" "env"
97
+
98
+ # --- ceiling_origin: what actually produced the value now in force, distinct from `source` (what
99
+ # THIS call did). This is the field that makes "source: state" actionable -- see cost-ceiling.mjs's
100
+ # own doc comment. --------------------------------------------------------------------------------
101
+ ORIG_DEF="$TMP/origin-default"; mkdir -p "$ORIG_DEF/.somi"
102
+ check "bootstrap with nothing set: ceiling_origin is 'default', matching source on this first call" \
103
+ "$(run "$ORIG_DEF" 'const r = C.resolveCeiling(ROOT, undefined); process.stdout.write(r.source + "," + r.ceiling_origin)')" \
104
+ "default,default"
105
+
106
+ ORIG_CFG="$TMP/origin-config"; mkdir -p "$ORIG_CFG/.somi"
107
+ printf '{"cost": {"ceiling": "low"}}\n' > "$ORIG_CFG/.somi/config.json"
108
+ check "bootstrap from config: ceiling_origin is 'config', matching source on this first call" \
109
+ "$(run "$ORIG_CFG" 'const r = C.resolveCeiling(ROOT, undefined); process.stdout.write(r.source + "," + r.ceiling_origin)')" \
110
+ "config,config"
111
+ # The crux of the feature: a LATER bare call reports source "state" (nothing moved this call), but
112
+ # ceiling_origin still says "config" -- "saved state" alone would not explain why the user is at
113
+ # `low`; the origin does.
114
+ check "a later bare call: source is 'state', but ceiling_origin still says 'config' -- actionable" \
115
+ "$(run "$ORIG_CFG" 'const r = C.resolveCeiling(ROOT, undefined); process.stdout.write(r.source + "," + r.ceiling_origin)')" \
116
+ "state,config"
117
+
118
+ # An override updates ceiling_origin to track the value NOW in force, and a later bare call carries
119
+ # that origin forward too -- proving the disclosure survives across process invocations, not just
120
+ # within the one call that made the override.
121
+ ORIG_OVR="$TMP/origin-override"; mkdir -p "$ORIG_OVR/.somi"
122
+ out="$(SOMI_COST_CEILING=low node --input-type=module -e "const C = await import('$LIB'); const r = C.resolveCeiling('$ORIG_OVR', undefined); process.stdout.write(r.source + ',' + r.ceiling_origin)")"
123
+ check "an env override this call: source and ceiling_origin both report 'env'" "$out" "env,env"
124
+ check "a bare call after that override: source is 'state', ceiling_origin still says 'env'" \
125
+ "$(run "$ORIG_OVR" 'const r = C.resolveCeiling(ROOT, undefined); process.stdout.write(r.source + "," + r.ceiling_origin)')" \
126
+ "state,env"
127
+
128
+ # A CLI argument that matches the value already on disk records no override (per the existing
129
+ # no-duplicate-entry behavior above) -- ceiling_origin must therefore be left exactly as it was,
130
+ # not overwritten to "cli" for a value that didn't actually move.
131
+ ORIG_NOOP="$TMP/origin-noop"; mkdir -p "$ORIG_NOOP/.somi"
132
+ printf '{"cost": {"ceiling": "medium"}}\n' > "$ORIG_NOOP/.somi/config.json"
133
+ run "$ORIG_NOOP" 'C.resolveCeiling(ROOT, undefined)' >/dev/null # bootstrap from config first
134
+ check "a --ceiling matching the value already on disk: ceiling_origin is untouched (still 'config')" \
135
+ "$(run "$ORIG_NOOP" 'const r = C.resolveCeiling(ROOT, "medium"); process.stdout.write(r.overridden + "," + r.source + "," + r.ceiling_origin)')" \
136
+ "false,cli,config"
137
+
138
+ # M3: a state file written BEFORE ceiling_origin existed (this repo's own committed
139
+ # .somi/somi-state/ceiling.json is exactly this shape: {"ceiling":"high"}, no origin key at all) has
140
+ # no way to have set it -- absence is legacy, not corruption, and must not hard-fail. Reported as the
141
+ # distinct value 'unknown' rather than a guess. Contrast with ORIG_BADVAL below: PRESENT but wrong
142
+ # is still rejected.
143
+ ORIG_LEGACY="$TMP/origin-legacy"; mkdir -p "$ORIG_LEGACY/.somi/somi-state"
144
+ printf '{"ceiling": "high"}' > "$ORIG_LEGACY/.somi/somi-state/ceiling.json"
145
+ check "a state file predating ceiling_origin does not hard-fail; reports 'unknown'" \
146
+ "$(run "$ORIG_LEGACY" 'const r = C.resolveCeiling(ROOT, undefined); process.stdout.write(r.ceiling + "," + r.ceiling_origin)')" \
147
+ "high,unknown"
148
+
149
+ # M2: `ceiling_origin: "config"` goes stale when .somi/config.json's cost.ceiling changes to a
150
+ # DIFFERENT value after state already exists -- a bare edit still cannot MOVE the ceiling already in
151
+ # force (proven above), but continuing to report "config" would keep claiming a committed policy
152
+ # that no longer matches what's committed. Reported as "config-stale", never persisted.
153
+ ORIG_STALE="$TMP/origin-stale"; mkdir -p "$ORIG_STALE/.somi"
154
+ printf '{"cost": {"ceiling": "low"}}\n' > "$ORIG_STALE/.somi/config.json"
155
+ run "$ORIG_STALE" 'C.resolveCeiling(ROOT, undefined)' >/dev/null # bootstrap from config: low, origin config
156
+ printf '{"cost": {"ceiling": "high"}}\n' > "$ORIG_STALE/.somi/config.json" # config now says something else
157
+ check "config changed after bootstrap: ceiling stays put, ceiling_origin reports 'config-stale'" \
158
+ "$(run "$ORIG_STALE" 'const r = C.resolveCeiling(ROOT, undefined); process.stdout.write(r.ceiling + "," + r.overridden + "," + r.ceiling_origin)')" \
159
+ "low,false,config-stale"
160
+ check "config-stale is never written back to the state file itself" \
161
+ "$(run "$ORIG_STALE" 'const fs = await import("node:fs"); const s = JSON.parse(fs.readFileSync(C.ceilingStatePath(ROOT), "utf8")); process.stdout.write(s.ceiling_origin)')" \
162
+ "config"
163
+
164
+ ORIG_REMOVED="$TMP/origin-removed"; mkdir -p "$ORIG_REMOVED/.somi"
165
+ printf '{"cost": {"ceiling": "medium"}}\n' > "$ORIG_REMOVED/.somi/config.json"
166
+ run "$ORIG_REMOVED" 'C.resolveCeiling(ROOT, undefined)' >/dev/null # bootstrap from config
167
+ printf '{}\n' > "$ORIG_REMOVED/.somi/config.json" # the policy is removed entirely, not just changed
168
+ check "config.json's cost.ceiling removed entirely after bootstrap: still reported 'config-stale'" \
169
+ "$(run "$ORIG_REMOVED" 'process.stdout.write(C.resolveCeiling(ROOT, undefined).ceiling_origin)')" \
170
+ "config-stale"
171
+
172
+ ORIG_UNCHANGED="$TMP/origin-unchanged"; mkdir -p "$ORIG_UNCHANGED/.somi"
173
+ printf '{"cost": {"ceiling": "low"}}\n' > "$ORIG_UNCHANGED/.somi/config.json"
174
+ run "$ORIG_UNCHANGED" 'C.resolveCeiling(ROOT, undefined)' >/dev/null # bootstrap
175
+ check "config.json unchanged after bootstrap: ceiling_origin stays plain 'config', not stale" \
176
+ "$(run "$ORIG_UNCHANGED" 'process.stdout.write(C.resolveCeiling(ROOT, undefined).ceiling_origin)')" \
177
+ "config"
178
+
179
+ # A ceiling_origin of 'cli'/'env'/'default' never gets the staleness check applied, even against a
180
+ # config.json that would otherwise look stale by value -- staleness is only ever about a 'config'
181
+ # claim specifically.
182
+ ORIG_NOTCONFIG="$TMP/origin-not-config"; mkdir -p "$ORIG_NOTCONFIG/.somi"
183
+ out="$(SOMI_COST_CEILING=low node --input-type=module -e "const C = await import('$LIB'); const r = C.resolveCeiling('$ORIG_NOTCONFIG', undefined); process.stdout.write(r.ceiling_origin)")"
184
+ check "bootstrap via env override: ceiling_origin is 'env', unaffected by the config-staleness check" "$out" "env"
185
+
186
+ # M3 + M2 do not interact: a legacy (no ceiling_origin) state file is never treated as possibly stale.
187
+ ORIG_LEGACY_CFG="$TMP/origin-legacy-cfg"; mkdir -p "$ORIG_LEGACY_CFG/.somi/somi-state"
188
+ mkdir -p "$ORIG_LEGACY_CFG/.somi"
189
+ printf '{"ceiling": "high"}' > "$ORIG_LEGACY_CFG/.somi/somi-state/ceiling.json"
190
+ printf '{"cost": {"ceiling": "low"}}\n' > "$ORIG_LEGACY_CFG/.somi/config.json"
191
+ check "a legacy state file with a differing config.json still reports 'unknown', not 'config-stale'" \
192
+ "$(run "$ORIG_LEGACY_CFG" 'process.stdout.write(C.resolveCeiling(ROOT, undefined).ceiling_origin)')" \
193
+ "unknown"
194
+
195
+ ORIG_BADVAL="$TMP/origin-badval"; mkdir -p "$ORIG_BADVAL/.somi/somi-state"
196
+ printf '{"ceiling": "low", "ceiling_origin": "bogus"}' > "$ORIG_BADVAL/.somi/somi-state/ceiling.json"
197
+ expect_exit "a present state file with an invalid (not merely absent) ceiling_origin value dies loudly" 1 \
198
+ "$ORIG_BADVAL" 'C.resolveCeiling(ROOT, undefined)'
199
+
200
+ # --- an UNPARSABLE state file (bad JSON, not just a wrong shape) dies loudly and names the file --
201
+ STATE_BROKEN="$TMP/state-broken"; mkdir -p "$STATE_BROKEN/.somi/somi-state"
202
+ printf '{"ceiling": "low"\n' > "$STATE_BROKEN/.somi/somi-state/ceiling.json" # missing closing brace
203
+ expect_exit "an unparsable state file dies loudly rather than a bare uncaught SyntaxError" 1 \
204
+ "$STATE_BROKEN" 'C.resolveCeiling(ROOT, undefined)'
205
+ check "the unparsable-state error names the ceiling.json file path, not a bare JSON position" \
206
+ "$(run "$STATE_BROKEN" 'try { C.resolveCeiling(ROOT, undefined); } catch (e) { process.stdout.write(String(e.message.includes("ceiling.json"))); }')" \
207
+ "true"
208
+
209
+ # --- malformed values die loudly, never silently defang the ceiling -----------------------------
210
+ expect_exit "a malformed explicit argument is rejected (uncaught, not swallowed)" 1 \
211
+ "$B" 'C.resolveCeiling(ROOT, "unlimited")'
212
+ expect_exit "a malformed env var is rejected" 1 \
213
+ "$B" 'process.env.SOMI_COST_CEILING = "unlimited"; C.resolveCeiling(ROOT, undefined)'
214
+ check "a rejected malformed value leaves the on-disk ceiling and override count untouched" \
215
+ "$(run "$B" 'const fs = await import("node:fs"); const s = JSON.parse(fs.readFileSync(C.ceilingStatePath(ROOT), "utf8")); process.stdout.write(s.ceiling + "," + s.ceiling_overrides.length)')" \
216
+ "medium,2"
217
+
218
+ CFG="$TMP/c"; mkdir -p "$CFG/.somi"
219
+ printf '{"cost": {"ceiling": "unlimited"}}\n' > "$CFG/.somi/config.json"
220
+ expect_exit "a malformed config-sourced ceiling dies loudly at bootstrap" 1 \
221
+ "$CFG" 'C.resolveCeiling(ROOT, undefined)'
222
+ check "a failed bootstrap leaves no state file behind" \
223
+ "$(run "$CFG" 'const fs = await import("node:fs"); process.stdout.write(String(fs.existsSync(C.ceilingStatePath(ROOT))))')" \
224
+ "false"
225
+
226
+ # --- a wrong-shaped `cost` container fails closed, not open to the loosest ceiling --------------
227
+ SHAPE1="$TMP/shape1"; mkdir -p "$SHAPE1/.somi"; printf '{"cost": "low"}' > "$SHAPE1/.somi/config.json"
228
+ expect_exit "a cost key that is a string, not an object, dies loudly rather than defaulting" 1 \
229
+ "$SHAPE1" 'C.resolveCeiling(ROOT, undefined)'
230
+ SHAPE2="$TMP/shape2"; mkdir -p "$SHAPE2/.somi"; printf '{"cost": {"celing": "low"}}' > "$SHAPE2/.somi/config.json"
231
+ expect_exit "a typo'd key inside cost dies loudly rather than falling back to the default" 1 \
232
+ "$SHAPE2" 'C.resolveCeiling(ROOT, undefined)'
233
+ SHAPE3="$TMP/shape3"; mkdir -p "$SHAPE3/.somi"; printf '{"ceiling": "low"}' > "$SHAPE3/.somi/config.json"
234
+ expect_exit "a ceiling key at the top level (outside cost) dies loudly, not silently ignored" 1 \
235
+ "$SHAPE3" 'C.resolveCeiling(ROOT, undefined)'
236
+
237
+ # --- an UNPARSABLE config.json (bad JSON, not just a wrong shape) dies loudly too, never {} ------
238
+ BROKEN="$TMP/broken"; mkdir -p "$BROKEN/.somi"
239
+ printf '{"cost": {"ceiling": "low"}\n' > "$BROKEN/.somi/config.json" # missing closing brace
240
+ expect_exit "an unparsable config.json dies loudly rather than silently resolving to {}" 1 \
241
+ "$BROKEN" 'C.resolveCeiling(ROOT, undefined)'
242
+ broken_out="$(run "$BROKEN" 'C.resolveCeiling(ROOT, undefined); process.stdout.write("SHOULD-NOT-PRINT")' 2>/dev/null)"
243
+ check "an unparsable config.json produces no stdout before dying" "$broken_out" ""
244
+ check "the unparsable-config error names the config file path" \
245
+ "$(run "$BROKEN" 'try { C.resolveCeiling(ROOT, undefined); } catch (e) { process.stdout.write(String(e.message.includes("config.json"))); }')" \
246
+ "true"
247
+ check "an unparsable config leaves no state file behind" \
248
+ "$(run "$BROKEN" 'const fs = await import("node:fs"); process.stdout.write(String(fs.existsSync(C.ceilingStatePath(ROOT))))')" \
249
+ "false"
250
+
251
+ # --- a present state file with a semantically corrupt ceiling dies loudly, not silently ---------
252
+ CORRUPT="$TMP/corrupt"; mkdir -p "$CORRUPT/.somi/somi-state"
253
+ printf '{}' > "$CORRUPT/.somi/somi-state/ceiling.json"
254
+ expect_exit "a present state file missing its ceiling key dies loudly" 1 \
255
+ "$CORRUPT" 'C.resolveCeiling(ROOT, undefined)'
256
+ check "the thrown message names the state file, not a flag or env var" \
257
+ "$(run "$CORRUPT" 'try { C.resolveCeiling(ROOT, undefined); } catch (e) { process.stdout.write(String(e.message.includes("ceiling.json"))); }')" \
258
+ "true"
259
+
260
+ # --- decideDispatch: a declared cost is a CAPABILITY SET; the ceiling selects the highest member
261
+ # it permits, and always allows -- when no member fits, it selects the cheapest declared member
262
+ # instead of blocking. A bare string is a one-member set (back-compat, not a special case). ------
263
+
264
+ # One-member set (bare string) -- behaves exactly like a single declared tier.
265
+ check "one-member set within ceiling: allow, selected echoes the sole member" \
266
+ "$(run "$B" 'const d = C.decideDispatch("low", "high"); process.stdout.write(d.action + "," + d.selected + "," + d.supported.join("|"))')" \
267
+ "allow,low,low"
268
+
269
+ # The canonical case: a unit declaring only `high` has no cheaper mode. Under a ceiling that
270
+ # permits none of its members, it still runs, at that one declared tier -- blocking it would not be
271
+ # a saving, only a stoppage.
272
+ check "single-high declaration under a medium ceiling: still allow, at high (its only declared tier)" \
273
+ "$(run "$B" 'const d = C.decideDispatch("high", "medium"); process.stdout.write(d.action + "," + d.selected + "," + d.supported.join("|"))')" \
274
+ "allow,high,high"
275
+
276
+ # Two-member set -- selection across three ceilings: below both, between them, above both.
277
+ # The "no member fits" case is the general form the single-high case generalizes: `selected` falls
278
+ # to the cheapest declared member (supported[0]), not the unit's only member.
279
+ check "two-member set [medium,high], ceiling low: no member fits -> allow at cheapest (medium)" \
280
+ "$(run "$B" 'const d = C.decideDispatch(["medium","high"], "low"); process.stdout.write(d.action + "," + d.selected + "," + d.supported.join("|"))')" \
281
+ "allow,medium,medium|high"
282
+ check "two-member set [medium,high], ceiling medium: selects medium (highest permitted), silently" \
283
+ "$(run "$B" 'const d = C.decideDispatch(["medium","high"], "medium"); process.stdout.write(d.action + "," + d.selected)')" \
284
+ "allow,medium"
285
+ check "two-member set [medium,high], ceiling high: selects high (highest permitted)" \
286
+ "$(run "$B" 'const d = C.decideDispatch(["medium","high"], "high"); process.stdout.write(d.action + "," + d.selected)')" \
287
+ "allow,high"
288
+
289
+ # Three-member set -- selection at each of the three ceilings, proving the richest permitted
290
+ # member is always the one chosen, never a lower one left on the table.
291
+ check "three-member set [low,medium,high], ceiling low: selects low" \
292
+ "$(run "$B" 'const d = C.decideDispatch(["low","medium","high"], "low"); process.stdout.write(d.action + "," + d.selected)')" \
293
+ "allow,low"
294
+ check "three-member set [low,medium,high], ceiling medium: selects medium, not low" \
295
+ "$(run "$B" 'const d = C.decideDispatch(["low","medium","high"], "medium"); process.stdout.write(d.action + "," + d.selected)')" \
296
+ "allow,medium"
297
+ check "three-member set [low,medium,high], ceiling high: selects high, not a lower member" \
298
+ "$(run "$B" 'const d = C.decideDispatch(["low","medium","high"], "high"); process.stdout.write(d.action + "," + d.selected)')" \
299
+ "allow,high"
300
+
301
+ # No code path ever yields a tier absent from the declared set, and every outcome is "allow": sweep
302
+ # every set against every ceiling.
303
+ check "action is always allow, and selected is always a member of the declared set, across every set x ceiling" \
304
+ "$(run "$B" 'const sets=[["low"],["medium"],["high"],["low","medium"],["medium","high"],["low","high"],["low","medium","high"]]; const ceilings=["low","medium","high"]; let bad=0; for (const s of sets) for (const c of ceilings) { const d=C.decideDispatch(s,c); if (d.action!=="allow") bad++; if (!s.includes(d.selected)) bad++; } process.stdout.write(String(bad))')" \
305
+ "0"
306
+
307
+ check "the decision object is frozen -- a caller cannot rewrite the selection after the fact" \
308
+ "$(run "$B" 'const d = C.decideDispatch(["low","high"], "high"); try { d.selected = "low"; } catch {} process.stdout.write(d.selected)')" \
309
+ "high"
310
+ check "the supported array itself is frozen too, not just the decision object wrapping it" \
311
+ "$(run "$B" 'const d = C.decideDispatch(["low","high"], "high"); const before = d.supported.length; try { d.supported.push("medium"); } catch {} process.stdout.write(String(d.supported.length === before))')" \
312
+ "true"
313
+ check "the allow shape carries exactly action, selected, supported, ceiling" \
314
+ "$(run "$B" 'process.stdout.write(Object.keys(C.decideDispatch(["low","high"], "high")).sort().join("|"))')" \
315
+ "action|ceiling|selected|supported"
316
+ expect_exit "an unrecognized cost value throws rather than silently allowing" 1 \
317
+ "$B" 'C.decideDispatch("critical", "high")'
318
+ expect_exit "an unrecognized ceiling value throws rather than silently allowing" 1 \
319
+ "$B" 'C.decideDispatch("low", "critical")'
320
+ expect_exit "an unordered declared set (high before medium) throws rather than being silently sorted" 1 \
321
+ "$B" 'C.decideDispatch(["high","medium"], "high")'
322
+ expect_exit "a duplicate in the declared set throws" 1 \
323
+ "$B" 'C.decideDispatch(["medium","medium"], "high")'
324
+ expect_exit "an empty declared set throws rather than resolving to no-capability-silently" 1 \
325
+ "$B" 'C.decideDispatch([], "high")'
326
+
327
+ # --- modelForDispatch: the sanctioned composition, structurally unable to degrade ---------------
328
+ check "modelForDispatch resolves the model for the SELECTED tier, not just any declared member" \
329
+ "$(run "$B" 'process.stdout.write(C.modelForDispatch(C.decideDispatch(["low","medium"],"medium"), "claude-code"))')" \
330
+ "sonnet"
331
+ check "modelForDispatch on a one-member set resolves that member's model" \
332
+ "$(run "$B" 'process.stdout.write(C.modelForDispatch(C.decideDispatch("low","high"), "claude-code"))')" \
333
+ "haiku"
334
+ # decideDispatch itself can no longer produce anything but "allow" -- the guard is unreachable by
335
+ # construction now, but it is still exercised directly against a hand-built non-allow shape, so the
336
+ # never-degrade backstop stays proven rather than merely unreachable-and-untested.
337
+ expect_exit "modelForDispatch refuses a decision shaped as anything but allow" 1 \
338
+ "$B" 'C.modelForDispatch({ action: "refuse", supported: ["high"], ceiling: "low" }, "claude-code")'
339
+ expect_exit "modelForDispatch refuses a missing decision" 1 \
340
+ "$B" 'C.modelForDispatch(undefined, "claude-code")'
341
+
342
+ echo "cost ceiling tests: $pass ok, $fail failed"
343
+ [ "$fail" -eq 0 ] || exit 1
@@ -0,0 +1,192 @@
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 builds 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 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
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 -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
+ if grep -vE '^[[:space:]]*#' "$VALIDATE" | grep -qE 'eval[[:space:]]+"\$\(node|source[[:space:]]+<\(node'; then
142
+ 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
+ else
144
+ ok "validate.sh does not eval or source a node derivation directly (outside comments) -- the capture-then-check form is intact"
145
+ fi
146
+
147
+ # The previous literal `eval "$(node -e` match missed a script-form bypass: a longer derivation
148
+ # naturally moves from `node -e '...'` to a file, and `eval "$(node scripts/lib/some-file.mjs)"`
149
+ # loses the same capture-then-check property without containing `-e` anywhere. Prove the widened
150
+ # check actually catches that form, on a scratch copy -- never the real file.
151
+ scratch_validate="$(mktemp)"
152
+ cp -a "$VALIDATE" "$scratch_validate"
153
+ printf '\neval "$(node scripts/lib/derive-dispatch.mjs)"\n' >> "$scratch_validate"
154
+ if grep -vE '^[[:space:]]*#' "$scratch_validate" | grep -qE 'eval[[:space:]]+"\$\(node|source[[:space:]]+<\(node'; then
155
+ ok "the widened shape check catches a bare eval of a node SCRIPT FILE (not just -e), on a scratch copy"
156
+ else
157
+ bad "the widened shape check misses a bare eval of a node script file -- a literal '-e' match is too narrow"
158
+ fi
159
+ rm -f "$scratch_validate"
160
+
161
+ # A derivation that prints two assignments and then throws is what a real partial failure looks
162
+ # like (e.g. a tier added to VALID_COSTS but missing from a host's mapping, mid-forEach). Run
163
+ # validate.sh's exact idiom against it under the same `set -euo pipefail` validate.sh runs under.
164
+ partial_derivation() { node -e 'console.log("a=1"); console.log("b=2"); throw new Error("boom");'; }
165
+ guarded_out="$(
166
+ exec 2>&1
167
+ set -euo pipefail
168
+ cost_env="$(partial_derivation)" || { echo "cost-model derivation failed; cannot validate cost tiers" >&2; exit 1; }
169
+ eval "$cost_env"
170
+ echo "REACHED-PAST-THE-GUARD"
171
+ )"
172
+ guarded_rc=$?
173
+ if [ "$guarded_rc" -eq 1 ]; then
174
+ ok "the capture-then-check idiom exits 1 on a partial derivation failure"
175
+ else
176
+ bad "the capture-then-check idiom did not exit 1 on a partial derivation failure (rc=$guarded_rc, out: $guarded_out)"
177
+ fi
178
+ case "$guarded_out" in
179
+ *"cost-model derivation failed; cannot validate cost tiers"*)
180
+ ok "the capture-then-check idiom's diagnostic reaches output" ;;
181
+ *)
182
+ bad "the capture-then-check idiom's diagnostic did not reach output (got: $guarded_out)" ;;
183
+ esac
184
+ case "$guarded_out" in
185
+ *"REACHED-PAST-THE-GUARD"*)
186
+ bad "execution continued past a partial derivation failure -- the guard did not stop it" ;;
187
+ *)
188
+ ok "execution did not continue past a partial derivation failure" ;;
189
+ esac
190
+
191
+ echo "cost model tests: $pass ok, $fail failed"
192
+ [ "$fail" -eq 0 ] || exit 1