@skathio/somi 2.2.1 → 3.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 (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 +207 -209
  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 +224 -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 +690 -29
  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 +33 -8
  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 +354 -0
  128. package/tests/scripts/somi-mcp.sh +12 -0
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env node
2
+ // scripts/generate-digest.mjs — regenerate the always-on digest copies from their canonical source.
3
+ //
4
+ // WHY THIS EXISTS
5
+ // The always-on digest lives in three places: rules/CLAUDE.md (canonical), AGENTS.md, and
6
+ // .github/copilot-instructions.md. They were hand-synced, and they drifted — the Copilot copy was
7
+ // missing the `Reasoning craft` bullet entirely, which `npm test` could not see. Hand-syncing three
8
+ // copies is what caused the drift, so this script makes the canonical the only editable one.
9
+ //
10
+ // WHAT IT DOES
11
+ // Reads the bullets between `<!-- digest:start -->` / `<!-- digest:end -->` in the canonical
12
+ // file and writes them into each target's own "## Always-on digest" section, adjusting the relative
13
+ // link prefix per target's directory depth (see TARGETS below). `--check` exits non-zero on any diff
14
+ // instead of writing, for CI (wired into scripts/validate.sh).
15
+ //
16
+ // THE PREFIX ADJUSTMENT IS NOT THE WHOLE FIX
17
+ // A link-prefix substitution ALONE cannot reproduce the copies from a canonical with no links:
18
+ // there would be no prefix to substitute. The canonical is therefore written with full markdown
19
+ // links FIRST; only then does a per-file prefix adjustment become sufficient. Both halves are required — this script is the second half.
20
+ //
21
+ // MARKER PLACEMENT is pinned deliberately: the markers wrap ONLY the digest bullets, not the
22
+ // heading and not the framing paragraph. Two consumers depend on that. This generator inserts
23
+ // bullets under each target's own existing heading (neither target has a framing paragraph today,
24
+ // and adding one silently would be a content change nobody asked for). The UserPromptSubmit hook
25
+ // injects the same bullets into a consuming project's context, where a
26
+ // repeated heading is pure token cost. One marker pair serves both.
27
+ //
28
+ // CONSUMER-CONTEXT CAVEAT (the seam this script deliberately does NOT own): the hook strips these
29
+ // markdown links back to bare `(NN)` codes before injecting, because no repo-relative path resolves
30
+ // in a consuming project — SoMi's rules/ lives in the plugin install directory. That stripping is
31
+ // the hook's job, at the point of extraction. Loosening the canonical's citation style to suit
32
+ // a consumer this file is never injected into would fix the symptom in the wrong place.
33
+
34
+ import fs from 'node:fs';
35
+ import path from 'node:path';
36
+ import { fileURLToPath } from 'node:url';
37
+
38
+ const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
39
+ const CANONICAL = 'rules/CLAUDE.md';
40
+ const START = '<!-- digest:start -->';
41
+ const END = '<!-- digest:end -->';
42
+ const HEADING = '## Always-on digest';
43
+
44
+ // Each target's link prefix. The canonical sits at rules/CLAUDE.md and cites `./NN-*.md` —
45
+ // FILE-relative, and the only form that resolves from inside rules/. (`./rules/NN-*.md` would
46
+ // resolve to rules/rules/ — a dead link. That mistake shipped once here, and it passed review
47
+ // because the hook's citation stripper happened to require the `rules/` segment, so a broken
48
+ // canonical was the only thing that round-tripped. Both are fixed; this comment is the guard.)
49
+ // AGENTS.md is at the repo root, so it needs `./rules/`; .github/copilot-instructions.md is one
50
+ // level down, so it needs `../rules/`. Getting this wrong produces links that render but 404 — the
51
+ // exact silent failure the digest copies exist to prevent, so it is data here rather than a guess.
52
+ const TARGETS = [
53
+ { file: 'AGENTS.md', prefix: './rules/' },
54
+ { file: '.github/copilot-instructions.md', prefix: '../rules/' },
55
+ ];
56
+
57
+ function read(rel) {
58
+ return fs.readFileSync(path.join(REPO_ROOT, rel), 'utf8');
59
+ }
60
+
61
+ // The canonical bullets, verbatim, between the markers. Throws rather than silently emitting an
62
+ // empty digest — a generator that quietly writes nothing is worse than one that fails loudly.
63
+ function canonicalBullets() {
64
+ const src = read(CANONICAL);
65
+ const i = src.indexOf(START);
66
+ const j = src.indexOf(END);
67
+ if (i === -1 || j === -1 || j < i) {
68
+ throw new Error(`${CANONICAL}: missing or malformed ${START} / ${END} markers`);
69
+ }
70
+ const body = src.slice(i + START.length, j).trim();
71
+ if (body === '') throw new Error(`${CANONICAL}: digest block is empty`);
72
+ return body;
73
+ }
74
+
75
+ // Retarget the canonical's bare `./NN-*.md` to the prefix this target needs. Only the link TARGET
76
+ // is rewritten, never the label — so ``[`00`](./00-priorities.md)`` keeps its `00` label intact.
77
+ function retarget(bullets, prefix) {
78
+ // ANCHORED on the citation shape (`./NN-name.md`), not on any `](./`. An unanchored pattern
79
+ // rewrites every relative link in a bullet: a prose link like `[guide](./docs/ADOPTION.md)`
80
+ // became `./rules/docs/ADOPTION.md` — dead — while `--check` reported both copies in sync.
81
+ // The hook deliberately keeps prose links in bullets intact, so an
82
+ // unanchored rewrite here put the two halves of the seam in disagreement about what is legal.
83
+ return bullets.replace(/\]\(\.\/(\d{2}-[A-Za-z0-9-]+\.md)\)/g, `](${prefix}$1)`);
84
+ }
85
+
86
+ // Replace everything between the target's `## Always-on digest` heading and the next `## ` heading
87
+ // (or EOF) with the generated bullets.
88
+ //
89
+ // Anchoring is LINE-ANCHORED and FENCE-AWARE, and a second heading match is an error rather than a
90
+ // silent pick. A substring search got all three wrong, and each failure corrupted the file while
91
+ // `--check` still reported "in sync" — a generator built to eliminate silent drift must not be able
92
+ // to manufacture it:
93
+ // - prose merely MENTIONING "## Always-on digest" above the real heading hijacked the anchor,
94
+ // truncating that sentence mid-word and deleting the real section;
95
+ // - a `## ` line inside a fenced code block terminated the splice early, swallowing the opening
96
+ // fence and leaving it unbalanced;
97
+ // - two headings would silently take the first.
98
+ function splice(targetSrc, bullets) {
99
+ const lines = targetSrc.split('\n');
100
+ const headingRe = /^## Always-on digest[ \t]*$/;
101
+ const nextHeadingRe = /^## /;
102
+
103
+ // Fenced regions are invisible to both anchors. Tracked by toggling on ``` / ~~~ at line start.
104
+ const fenced = new Set();
105
+ let inFence = false;
106
+ lines.forEach((line, i) => {
107
+ if (/^\s*(```|~~~)/.test(line)) inFence = !inFence;
108
+ if (inFence) fenced.add(i);
109
+ });
110
+
111
+ const heads = lines.map((l, i) => (headingRe.test(l) && !fenced.has(i) ? i : -1)).filter((i) => i >= 0);
112
+ if (heads.length === 0) throw new Error(`missing "${HEADING}" heading`);
113
+ if (heads.length > 1) {
114
+ throw new Error(`"${HEADING}" appears ${heads.length} times (lines ${heads.map((i) => i + 1).join(', ')}) — ambiguous`);
115
+ }
116
+
117
+ const h = heads[0];
118
+ let end = lines.length;
119
+ for (let i = h + 1; i < lines.length; i++) {
120
+ if (nextHeadingRe.test(lines[i]) && !fenced.has(i)) { end = i; break; }
121
+ }
122
+ const tail = end === lines.length ? '' : `\n${lines.slice(end).join('\n')}`;
123
+ return `${lines.slice(0, h + 1).join('\n')}\n\n${bullets}\n${tail}`;
124
+ }
125
+
126
+ function main() {
127
+ const check = process.argv.includes('--check');
128
+
129
+ // A malformed canonical is a config error, not a crash. Without this the script exits on an
130
+ // unhandled exception with a stack trace — technically non-zero, so CI would still fail, but the
131
+ // operator sees a Node traceback instead of the one line that tells them what to fix. Found by
132
+ // mutating the end marker and reading what the script actually printed.
133
+ let bullets;
134
+ try {
135
+ bullets = canonicalBullets();
136
+ } catch (err) {
137
+ console.error(`generate-digest: ${err.message}`);
138
+ process.exitCode = 1;
139
+ return;
140
+ }
141
+
142
+ let drifted = 0;
143
+
144
+ for (const { file, prefix } of TARGETS) {
145
+ const current = read(file);
146
+ let next;
147
+ try {
148
+ next = splice(current, retarget(bullets, prefix));
149
+ } catch (err) {
150
+ console.error(`generate-digest: ${file}: ${err.message}`);
151
+ process.exitCode = 1;
152
+ return;
153
+ }
154
+ if (next === current) continue;
155
+ drifted++;
156
+ if (check) {
157
+ console.error(`generate-digest: DRIFT in ${file} — regenerate with \`node scripts/generate-digest.mjs\``);
158
+ } else {
159
+ fs.writeFileSync(path.join(REPO_ROOT, file), next);
160
+ console.log(`generate-digest: updated ${file}`);
161
+ }
162
+ }
163
+
164
+ if (check) {
165
+ if (drifted > 0) {
166
+ console.error(`generate-digest: ${drifted} file(s) out of sync with ${CANONICAL}`);
167
+ process.exitCode = 1;
168
+ } else {
169
+ console.log(`generate-digest: all ${TARGETS.length} copies match ${CANONICAL}`);
170
+ }
171
+ } else if (drifted === 0) {
172
+ console.log('generate-digest: already in sync, nothing to write');
173
+ }
174
+ }
175
+
176
+ main();
@@ -0,0 +1,317 @@
1
+ // cost-ceiling.mjs — the session cost ceiling: a maximum `cost` tier a dispatch may cross without
2
+ // explicit sign-off.
3
+ //
4
+ // Follows the loop-cap precedent (scripts/somi-loop.mjs's reresolveCap/applyCapOverride): the
5
+ // ceiling is re-resolved on every call, not frozen once. Absent an explicit value THIS call (an
6
+ // argument the caller parsed itself, or SOMI_COST_CEILING), the ceiling already recorded on disk
7
+ // stands unchanged — a bare `.somi/config.json` edit cannot silently move a ceiling already in
8
+ // force, because config is consulted only once, when no state file exists yet. Every value that
9
+ // reaches validateCeiling() is rejected outright if it isn't one of VALID_COSTS — never coerced —
10
+ // so a malformed value dies loudly instead of quietly disabling the ceiling.
11
+ //
12
+ // State is deliberately NOT keyed by slug (unlike loop state): the ceiling bounds an operator's
13
+ // spend for the whole session, not one slice of work, so one file covers every dispatch.
14
+ // Callers pass `root` explicitly rather than this module sniffing CLAUDE_PROJECT_DIR itself —
15
+ // keeps the module a pure library over explicit inputs, testable without env-var setup.
16
+ //
17
+ // Every raise is appended to `ceiling_overrides`, shaped {field, from, to, source, at} — the same
18
+ // shape somi-loop.mjs's `cap_overrides` uses, so an override record looks the same wherever it's
19
+ // read from. Created lazily, only on the first real override.
20
+ //
21
+ // The ceiling not moving on a bare config edit (above) means `ceiling_origin: "config"` can go
22
+ // stale: config can change to a DIFFERENT value after state already exists, without moving what's
23
+ // in force. `resolveCeiling` detects this and reports `"config-stale"` instead — never persisted,
24
+ // since nothing about the value in force actually changed, only the honesty of naming why. A state
25
+ // file written before `ceiling_origin` shipped (no hard failure -- reported as `"unknown"`) is the
26
+ // other non-canonical value `resolveCeiling` can return; see LEGACY_ORIGIN below.
27
+
28
+ import fs from 'node:fs';
29
+ import path from 'node:path';
30
+ import { resolveModel, VALID_COSTS } from './cost-model.mjs';
31
+
32
+ export const CEILING_ENV = 'SOMI_COST_CEILING';
33
+ export const DEFAULT_CEILING = 'high';
34
+ export const ACTIONS = Object.freeze(['allow']);
35
+
36
+ const ORDER = Object.freeze(Object.fromEntries(VALID_COSTS.map((c, i) => [c, i])));
37
+
38
+ export function ceilingStatePath(root) {
39
+ return path.join(root, '.somi', 'somi-state', 'ceiling.json');
40
+ }
41
+
42
+ function nowIso() {
43
+ return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
44
+ }
45
+
46
+ function readConfig(root) {
47
+ const file = path.join(root, '.somi', 'config.json');
48
+ let raw;
49
+ try {
50
+ raw = fs.readFileSync(file, 'utf8');
51
+ } catch (e) {
52
+ if (e.code === 'ENOENT') return {}; // no config committed: nothing configured, defaults apply
53
+ throw e;
54
+ }
55
+ try {
56
+ return JSON.parse(raw);
57
+ } catch (e) {
58
+ // A committed config that fails to PARSE is not "unconfigured" -- silently returning {} here
59
+ // would bootstrap DEFAULT_CEILING and PERSIST it, inverting a team's `low` policy until
60
+ // someone notices, and outliving the typo once fixed. Dies loudly instead, naming the file.
61
+ throw new Error(`cost-ceiling: ${file} is not valid JSON: ${e.message}`);
62
+ }
63
+ }
64
+
65
+ const COST_CONFIG_KEYS = new Set(['ceiling', 'mapping']);
66
+
67
+ // A `cost` that isn't an object, has an unrecognized key (a typo), or a `ceiling` misplaced at
68
+ // the top level all die loudly here instead of silently resolving to "not configured".
69
+ //
70
+ // Exported: this is also the one config reader scripts/somi-dispatch.mjs uses to pull `mapping`
71
+ // (its `ceiling` sibling), so a project's cost config is never parsed by two independent readers
72
+ // that could drift on what counts as malformed.
73
+ export function readCostConfig(root) {
74
+ const cfg = readConfig(root);
75
+ if (cfg.ceiling !== undefined) {
76
+ throw new Error('cost-ceiling: "ceiling" in .somi/config.json belongs under "cost.ceiling"');
77
+ }
78
+ const cost = cfg.cost;
79
+ if (cost === undefined || cost === null) return {};
80
+ if (typeof cost !== 'object' || Array.isArray(cost)) {
81
+ throw new Error(`cost-ceiling: cost in .somi/config.json expected an object, got ${JSON.stringify(cost)}`);
82
+ }
83
+ for (const key of Object.keys(cost)) {
84
+ if (!COST_CONFIG_KEYS.has(key)) {
85
+ throw new Error(`cost-ceiling: cost in .somi/config.json has an unrecognized key "${key}"`);
86
+ }
87
+ }
88
+ return cost;
89
+ }
90
+
91
+ function validateCeiling(raw, label) {
92
+ if (!VALID_COSTS.includes(raw)) {
93
+ throw new Error(`cost-ceiling: ${label} expected one of ${VALID_COSTS.join('|')}, got "${raw}"`);
94
+ }
95
+ return raw;
96
+ }
97
+
98
+ // What produced the ceiling value currently on disk -- distinct from `source` (below), which names
99
+ // what THIS call did. `ceiling_origin` survives every later bare call that just loads state, so an
100
+ // announcement can say WHY a persisted `low` is in force ("you set this via SOMI_COST_CEILING last
101
+ // session") instead of only "it's saved state" -- see resolveCeiling's own doc comment.
102
+ const VALID_ORIGINS = Object.freeze(['config', 'cli', 'env', 'default']);
103
+
104
+ // Reported (never persisted) origin for a state file written before `ceiling_origin` existed --
105
+ // this repo's own checked-in .somi/somi-state/ceiling.json is exactly that shape. There is no way
106
+ // to recover which of config/cli/env/default actually produced the value, so this is the honest
107
+ // answer rather than a guess. Distinct from a PRESENT-but-invalid value (a typo, a stale removed
108
+ // value), which still dies loudly in loadOrInitState below -- absence is legacy, corruption isn't.
109
+ const LEGACY_ORIGIN = 'unknown';
110
+
111
+ function validateOrigin(raw, label) {
112
+ if (!VALID_ORIGINS.includes(raw)) {
113
+ throw new Error(`cost-ceiling: ${label} expected one of ${VALID_ORIGINS.join('|')}, got "${raw}"`);
114
+ }
115
+ return raw;
116
+ }
117
+
118
+ function saveState(root, state) {
119
+ const file = ceilingStatePath(root);
120
+ fs.mkdirSync(path.dirname(file), { recursive: true });
121
+ fs.writeFileSync(file, JSON.stringify(state));
122
+ }
123
+
124
+ // Reads the state file if present. A missing file bootstraps fresh, from
125
+ // .somi/config.json's `cost.ceiling` (validated) or DEFAULT_CEILING. A PRESENT but corrupt file is
126
+ // not silently treated as missing — it throws, same "malformed dies loudly" discipline as a bad
127
+ // CLI/env value, rather than quietly re-arming at the default with the corruption unreported.
128
+ //
129
+ // Returns `{state, bootstrapSource}` — `bootstrapSource` is `'config'` or `'default'` when this
130
+ // call just bootstrapped a fresh state file, or `'state'` when an existing one was loaded. This is
131
+ // what lets resolveCeiling() report where a ceiling came from even on a call that overrides
132
+ // nothing — a dispatcher can then announce a `low` ceiling honestly, by its real source, not just
133
+ // by its bare value.
134
+ function loadOrInitState(root) {
135
+ const file = ceilingStatePath(root);
136
+ let raw;
137
+ try {
138
+ raw = fs.readFileSync(file, 'utf8');
139
+ } catch (e) {
140
+ if (e.code !== 'ENOENT') throw e;
141
+ const configured = readCostConfig(root).ceiling;
142
+ const isConfigured = !(configured === undefined || configured === null || configured === '');
143
+ const ceiling = isConfigured
144
+ ? validateCeiling(configured, 'cost.ceiling in .somi/config.json')
145
+ : DEFAULT_CEILING;
146
+ const bootstrapSource = isConfigured ? 'config' : 'default';
147
+ const state = { ceiling, ceiling_origin: bootstrapSource };
148
+ saveState(root, state);
149
+ return { state, bootstrapSource };
150
+ }
151
+ // An unparsable state file (bad JSON, not merely a wrong shape) must still name the file in its
152
+ // error -- a bare JSON.parse throw here would surface as an unattributed SyntaxError, leaving a
153
+ // caller (or a project-environment-failure classifier) no path to report which file is corrupt.
154
+ let state;
155
+ try {
156
+ state = JSON.parse(raw);
157
+ } catch (e) {
158
+ throw new Error(`cost-ceiling: ${file} is not valid JSON: ${e.message}`);
159
+ }
160
+ if (state === null || typeof state !== 'object' || Array.isArray(state)) {
161
+ throw new Error(`cost-ceiling: ${file} is not a valid state object`);
162
+ }
163
+ state.ceiling = validateCeiling(state.ceiling, `ceiling in ${file}`);
164
+ // Absent entirely (a state file written before this field shipped) is legacy, not corruption --
165
+ // report LEGACY_ORIGIN rather than hard-failing a file this repo itself ships checked in. Present
166
+ // but wrong (a typo, a stale removed value) is still rejected the same as any other malformed
167
+ // persisted value.
168
+ state.ceiling_origin = state.ceiling_origin === undefined
169
+ ? LEGACY_ORIGIN
170
+ : validateOrigin(state.ceiling_origin, `ceiling_origin in ${file}`);
171
+ return { state, bootstrapSource: 'state' };
172
+ }
173
+
174
+ // `ceiling_origin: "config"` is a claim -- "a committed project policy produced this value" --
175
+ // that a later, DIFFERENT `.somi/config.json` edit silently falsifies. By design (see this file's
176
+ // own header) an edit after state already exists does not move the ceiling already in force, so
177
+ // reporting the origin unchanged would keep asserting a policy that no longer matches what's
178
+ // committed. Detected only when the origin currently on disk still claims 'config' (once a cli/env
179
+ // override has moved it, the origin already reflects THAT, correctly) and only against a call that
180
+ // LOADED existing state rather than bootstrapping fresh this same call (a fresh bootstrap read
181
+ // config and set state from it in this same call, so it cannot yet be stale). Never persisted --
182
+ // this changes only what THIS call reports, not the state file itself.
183
+ function reportedOrigin(root, state, bootstrapSource) {
184
+ if (bootstrapSource !== 'state' || state.ceiling_origin !== 'config') return state.ceiling_origin;
185
+ const configured = readCostConfig(root).ceiling;
186
+ const unset = configured === undefined || configured === null || configured === '';
187
+ return (unset || configured !== state.ceiling) ? 'config-stale' : state.ceiling_origin;
188
+ }
189
+
190
+ /**
191
+ * Re-resolves the session ceiling for one dispatch. `explicitArg` is a value the caller already
192
+ * extracted THIS invocation (e.g. a parsed CLI flag) — distinct from SOMI_COST_CEILING, read here.
193
+ * Precedence for what can MOVE a ceiling already in force: explicitArg > env var; neither present
194
+ * means the ceiling on disk stands, full stop — `.somi/config.json` is never re-read after the
195
+ * state file first exists.
196
+ * `source` names where THIS call's effective ceiling came from — `cli` or `env` when explicitArg
197
+ * or SOMI_COST_CEILING was read this call (whether or not it actually moved the value), otherwise
198
+ * the ceiling's own origin: `config` or `default` on the call that bootstrapped it, `state` on
199
+ * every later call that just loads what a previous call already persisted.
200
+ * `ceiling_origin` is what actually produced the value now in force — `config`/`cli`/`env`/`default`
201
+ * — and, unlike `source`, it survives every later bare call. `source: "state"` alone only tells a
202
+ * caller a ceiling was already on disk; `ceiling_origin` is what lets an announcement say WHY (a
203
+ * committed team policy, or an explicit `cli`/`env` set in an earlier session) instead of only
204
+ * "it's saved state". Two further values it can report, neither ever persisted: `config-stale` —
205
+ * the value was bootstrapped from `.somi/config.json`, but that file's `cost.ceiling` has since
206
+ * changed to something else (or been removed) — and `unknown` — a state file written before this
207
+ * field existed (this repo's own committed state is exactly that shape).
208
+ * @returns {{ceiling: string, overridden: boolean, source: string, ceiling_origin: string, override?: object}}
209
+ */
210
+ export function resolveCeiling(root, explicitArg) {
211
+ const { state, bootstrapSource } = loadOrInitState(root);
212
+ const isCli = explicitArg !== undefined && explicitArg !== '';
213
+ const envVal = process.env[CEILING_ENV];
214
+ const explicit = isCli ? explicitArg : (envVal === undefined || envVal === '' ? undefined : envVal);
215
+ if (explicit === undefined) {
216
+ return { ceiling: state.ceiling, overridden: false, source: bootstrapSource, ceiling_origin: reportedOrigin(root, state, bootstrapSource) };
217
+ }
218
+ const source = isCli ? 'cli' : 'env';
219
+ const validated = validateCeiling(explicit, isCli ? '--ceiling' : CEILING_ENV);
220
+ if (validated === state.ceiling) {
221
+ return { ceiling: state.ceiling, overridden: false, source, ceiling_origin: reportedOrigin(root, state, bootstrapSource) };
222
+ }
223
+ const override = {
224
+ field: 'ceiling',
225
+ from: state.ceiling,
226
+ to: validated,
227
+ source,
228
+ at: nowIso(),
229
+ };
230
+ state.ceiling = validated;
231
+ // The value now in force was produced by THIS override, not by whatever bootstrapped the file --
232
+ // ceiling_origin tracks the origin of the CURRENT value, so it must move with it.
233
+ state.ceiling_origin = source;
234
+ if (!Array.isArray(state.ceiling_overrides)) state.ceiling_overrides = [];
235
+ state.ceiling_overrides.push(override);
236
+ saveState(root, state);
237
+ return { ceiling: state.ceiling, overridden: true, source, ceiling_origin: state.ceiling_origin, override };
238
+ }
239
+
240
+ // A declared `cost` is a CAPABILITY SET, not a single value -- every tier the unit can usefully
241
+ // run at (a frontmatter `cost: medium, high` split on comma). Accepts a bare string too, as a
242
+ // one-member set, so a single-tier unit's declaration needs no special-casing at the call site.
243
+ // Always returns a frozen array in ascending order -- the same shape validate.sh already enforces
244
+ // on a frontmatter declaration, re-checked here rather than trusted: this is a library over
245
+ // explicit inputs, and a malformed set must die loudly rather than be silently coerced into
246
+ // something valid -- the same discipline validateCeiling() above applies to the ceiling value.
247
+ function normalizeCostSet(costs, label) {
248
+ const arr = Array.isArray(costs) ? costs : [costs];
249
+ if (arr.length === 0) {
250
+ throw new Error(`cost-ceiling: ${label} must declare at least one cost value`);
251
+ }
252
+ let prevRank = -1;
253
+ for (const c of arr) {
254
+ if (!VALID_COSTS.includes(c)) {
255
+ throw new Error(`cost-ceiling: ${label} has an unrecognized value "${c}" (expected one of ${VALID_COSTS.join('|')})`);
256
+ }
257
+ const rank = ORDER[c];
258
+ if (rank <= prevRank) {
259
+ throw new Error(`cost-ceiling: ${label} must be strictly ascending with no duplicates, got "${arr.join(',')}"`);
260
+ }
261
+ prevRank = rank;
262
+ }
263
+ return Object.freeze([...arr]);
264
+ }
265
+
266
+ /**
267
+ * Selects the tier a dispatch declaring `costs` (its full capability set) runs at against
268
+ * `ceiling`. `costs` is a single cost string or an ascending, duplicate-free array/list of them.
269
+ * Always allows, and always runs at a tier the unit itself declared:
270
+ *
271
+ * - some declared member sits at or below the ceiling -> `selected` is the HIGHEST such member.
272
+ * The ceiling silently picks the richest permitted tier -- this is selection within declared
273
+ * capability, not a downgrade.
274
+ * - no declared member fits -> `selected` is the CHEAPEST declared member (`supported[0]`). A
275
+ * unit whose cheapest declared tier is already above the ceiling has no cheaper mode to fall
276
+ * back to -- it is intrinsically that expensive, so blocking it would not be a saving, only a
277
+ * stoppage. It runs at its own declared floor rather than not at all.
278
+ *
279
+ * `supported` always echoes exactly the normalized declared set -- there is no lookup table, no
280
+ * "nearest allowed tier" pulled from outside what the unit itself declared. The result is frozen so
281
+ * a caller can't rewrite it into something that would look like one.
282
+ */
283
+ export function decideDispatch(costs, ceiling) {
284
+ const supported = normalizeCostSet(costs, 'declared cost');
285
+ if (!VALID_COSTS.includes(ceiling)) {
286
+ throw new Error(`cost-ceiling: unrecognized ceiling "${ceiling}" (expected one of ${VALID_COSTS.join('|')})`);
287
+ }
288
+ // `ORDER[c] > ORDER[selected]` is redundant given `supported`'s strictly-ascending invariant
289
+ // (normalizeCostSet enforces it) -- each later `c` in the loop is already the higher one. Left
290
+ // in as a documented guard, not a bug: it makes "take the highest permitted member" true by
291
+ // construction even if that invariant were ever relaxed, rather than by iteration order alone.
292
+ let selected = null;
293
+ for (const c of supported) {
294
+ if (ORDER[c] <= ORDER[ceiling] && (selected === null || ORDER[c] > ORDER[selected])) {
295
+ selected = c;
296
+ }
297
+ }
298
+ // Nothing in `supported` fit the ceiling: fall back to the cheapest declared member rather than
299
+ // blocking. It is still a tier the unit itself declared, so the never-degrade rule holds.
300
+ if (selected === null) selected = supported[0];
301
+ return Object.freeze({ action: 'allow', selected, supported, ceiling });
302
+ }
303
+
304
+ /**
305
+ * The only sanctioned way to turn a decideDispatch() result into a model. `decideDispatch` always
306
+ * returns "allow" now, so this guard is unreachable by construction -- kept anyway as the
307
+ * structural closer for the never-degrade rule: nothing can hand this function a decision that
308
+ * wasn't produced by `decideDispatch`'s own selection and expect a model back.
309
+ */
310
+ export function modelForDispatch(decision, host, mapping) {
311
+ if (!decision || decision.action !== 'allow') {
312
+ throw new Error(
313
+ `cost-ceiling: modelForDispatch requires an "allow" decision (one of ${ACTIONS.join('|')}), got "${decision?.action}"`
314
+ );
315
+ }
316
+ return resolveModel(decision.selected, host, mapping);
317
+ }
@@ -0,0 +1,95 @@
1
+ // One shipped, user-overridable mapping instead of scattering model names across instruction
2
+ // files: a repricing or a new model is an edit here. A host absent from the mapping gets no
3
+ // override — the caller omits the model argument and that host's own default applies (today's
4
+ // behavior, unchanged). A cost value outside the enum, or a mapped host missing that tier, throws
5
+ // rather than silently routing to an unintended model.
6
+
7
+ export const VALID_COSTS = Object.freeze(['low', 'medium', 'high']);
8
+
9
+ // A mapped model can come from committed, cloned .somi/config.json -- untrusted input about to
10
+ // reach a prompt and possibly a host CLI -- so it must look like a model identifier, not just be
11
+ // a non-empty string.
12
+ const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:/@\[\]-]{0,127}$/;
13
+
14
+ // Hosts with a verified model identifier for each tier. Add an entry to opt a new host into
15
+ // explicit model selection; leave a host out to keep it on its own default.
16
+ //
17
+ // TODO(cost-model maintainer): add copilot-cli / vscode once a verified model identifier exists
18
+ // for each tier; until then they return null and fall back to their own default.
19
+ export const HOST_MODELS = Object.freeze({
20
+ 'claude-code': Object.freeze({ low: 'haiku', medium: 'sonnet', high: 'opus' }),
21
+ });
22
+
23
+ /**
24
+ * Resolves a declared cost tier to a concrete model for the given host.
25
+ * @returns {string|null} the mapped model, or null when the host is absent from the mapping
26
+ * (no override for that host — the caller omits the model argument and its own default applies).
27
+ */
28
+ export function resolveModel(cost, host, mapping = HOST_MODELS) {
29
+ if (!VALID_COSTS.includes(cost)) {
30
+ throw new Error(`cost-model: unrecognized cost "${cost}" (expected one of ${VALID_COSTS.join('|')})`);
31
+ }
32
+ if (!Object.hasOwn(mapping, host)) return null; // unmapped host: no override, its own default applies
33
+ const models = mapping[host];
34
+ const model = models[cost];
35
+ if (model === undefined) {
36
+ throw new Error(`cost-model: host "${host}" has no "${cost}" entry in its mapping`);
37
+ }
38
+ // A user-supplied mapping (.somi/config.json's cost.mapping) can name a tier with a non-string
39
+ // value (a number, an object, an empty string) -- that must die loudly here, at the one place
40
+ // every mapping (shipped or overridden) is read, rather than silently handing a caller something
41
+ // that prints into JSON as a "model" no host can actually run.
42
+ if (typeof model !== 'string' || model === '') {
43
+ throw new Error(`cost-model: host "${host}"'s "${cost}" entry must be a non-empty string, got ${JSON.stringify(model)}`);
44
+ }
45
+ if (!MODEL_ID_RE.test(model)) {
46
+ throw new Error(`cost-model: host "${host}"'s "${cost}" entry "${model}" is not a valid model identifier`);
47
+ }
48
+ return model;
49
+ }
50
+
51
+ // JSON.parse gives a "__proto__" key in parsed text a genuine OWN enumerable property (unlike
52
+ // object-literal syntax, which would set the prototype instead) — Object.keys/for-in sees it like
53
+ // any other key. A naive `{...defaults, ...override}` spread is safe against the accessor-setter
54
+ // gadget (spread uses DefineOwnProperty, not Set), but a config-sourced override is exactly the
55
+ // input a merge helper should not trust blindly, so disallowed keys are rejected outright rather
56
+ // than silently absorbed as an inert host entry.
57
+ const FORBIDDEN_HOST_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
58
+
59
+ /**
60
+ * Merges a user-supplied per-host override (e.g. `.somi/config.json`'s `cost.mapping`) on top of
61
+ * `defaults`, for use as resolveModel()'s third argument. A host present in `override` REPLACES
62
+ * that host's whole tier map — never merged tier-by-tier — so mapping a host to `{}` makes every
63
+ * tier for that host fail loudly via resolveModel() instead of silently falling back to the
64
+ * shipped default. Throws on a disallowed or non-object override rather than absorbing it.
65
+ */
66
+ export function mergeHostMapping(defaults, override) {
67
+ if (override === undefined || override === null) return defaults;
68
+ if (typeof override !== 'object' || Array.isArray(override)) {
69
+ throw new Error('cost-model: mapping override must be an object');
70
+ }
71
+ const merged = { ...defaults };
72
+ for (const host of Object.keys(override)) {
73
+ if (FORBIDDEN_HOST_KEYS.has(host)) {
74
+ throw new Error(`cost-model: mapping override has a disallowed host key "${host}"`);
75
+ }
76
+ const tiers = override[host];
77
+ if (typeof tiers !== 'object' || tiers === null || Array.isArray(tiers)) {
78
+ throw new Error(`cost-model: mapping override for host "${host}" must be an object of cost -> model`);
79
+ }
80
+ // A tier key outside VALID_COSTS is either a typo (this repo's own "low"/"medium"/"high") or a
81
+ // stale key from a renamed tier -- either way it would sit unused forever, unflagged, since
82
+ // resolveModel() only ever looks up the tier it actually selected. Reject the whole per-host
83
+ // object rather than silently keeping the junk key alongside the valid ones.
84
+ for (const tier of Object.keys(tiers)) {
85
+ if (!VALID_COSTS.includes(tier)) {
86
+ throw new Error(
87
+ `cost-model: mapping override for host "${host}" has an unrecognized tier key "${tier}" ` +
88
+ `(expected one of ${VALID_COSTS.join('|')})`,
89
+ );
90
+ }
91
+ }
92
+ merged[host] = tiers;
93
+ }
94
+ return merged;
95
+ }