@skathio/somi 3.1.1 → 4.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 (153) 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 +34 -24
  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} +26 -23
  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} +16 -24
  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} +11 -12
  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 +25 -12
  25. package/commands/adopt.md +9 -10
  26. package/commands/architecture-review.md +4 -5
  27. package/commands/atlas.md +3 -3
  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 -2
  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 -2
  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 +138 -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 +71 -9
  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 +192 -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 +113 -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/config-files.mjs +145 -0
  69. package/scripts/lib/cost-ceiling.mjs +190 -179
  70. package/scripts/lib/cost-config-edit.mjs +102 -0
  71. package/scripts/lib/cost-config.mjs +64 -0
  72. package/scripts/lib/cost-defaults.mjs +51 -0
  73. package/scripts/lib/cost-lowering.mjs +89 -0
  74. package/scripts/lib/cost-model.mjs +37 -22
  75. package/scripts/lib/dispatch-resolver.mjs +59 -50
  76. package/scripts/lib/loop-diff.mjs +96 -0
  77. package/scripts/lib/loop-dispatch.mjs +19 -0
  78. package/scripts/lib/loop-review.mjs +52 -0
  79. package/scripts/lib/run-budget.mjs +28 -0
  80. package/scripts/lib/size-tier.mjs +184 -0
  81. package/scripts/lib/tier-record.mjs +82 -0
  82. package/scripts/size-budget-overrides.json +7 -15
  83. package/scripts/somi-check.mjs +4 -3
  84. package/scripts/somi-config.mjs +421 -0
  85. package/scripts/somi-dispatch.mjs +1 -1
  86. package/scripts/somi-loop.mjs +75 -99
  87. package/scripts/somi-mcp.mjs +135 -14
  88. package/scripts/somi-tier.mjs +393 -0
  89. package/scripts/validate.sh +57 -215
  90. package/skills/api-design/SKILL.md +1 -1
  91. package/skills/clean-code/SKILL.md +1 -1
  92. package/skills/market-research/SKILL.md +2 -2
  93. package/skills/owasp-defense/SKILL.md +2 -2
  94. package/skills/plan-review/SKILL.md +5 -1
  95. package/skills/reasoning-craft/SKILL.md +1 -1
  96. package/skills/requirements-engineering/SKILL.md +3 -3
  97. package/skills/solid-principles/SKILL.md +1 -1
  98. package/skills/somi-dispatch/SKILL.md +104 -109
  99. package/skills/somi-routing/SKILL.md +88 -1
  100. package/skills/testing-playbook/SKILL.md +2 -2
  101. package/skills/threat-modeling/SKILL.md +3 -3
  102. package/templates/BRIEF.md.tmpl +2 -2
  103. package/templates/DESIGN.md.tmpl +1 -1
  104. package/templates/DOD.md.tmpl +2 -2
  105. package/templates/PHASE.md.tmpl +2 -2
  106. package/templates/RCA.md.tmpl +1 -1
  107. package/templates/REVIEW.md.tmpl +3 -2
  108. package/templates/SDD.md.tmpl +1 -1
  109. package/templates/SPEC.md.tmpl +1 -1
  110. package/templates/TDD.md.tmpl +1 -1
  111. package/tests/hooks/cases/block-secret-writes.json +130 -17
  112. package/tests/hooks/cases/detect-repo-instructions.json +22 -1
  113. package/tests/hooks/cases/guard-protected-paths.json +175 -25
  114. package/tests/scripts/agent-model-frontmatter.sh +38 -0
  115. package/tests/scripts/agent-names.sh +77 -0
  116. package/tests/scripts/check-frontmatter.sh +1 -1
  117. package/tests/scripts/checkpoint-gate.sh +44 -3
  118. package/tests/scripts/convergence-runner.sh +10 -6
  119. package/tests/scripts/cost-ceiling.sh +127 -215
  120. package/tests/scripts/cost-defaults.sh +128 -0
  121. package/tests/scripts/cost-hardcap.sh +338 -0
  122. package/tests/scripts/cost-lowering.sh +261 -0
  123. package/tests/scripts/cost-model.sh +18 -14
  124. package/tests/scripts/dispatch-guard.sh +7 -7
  125. package/tests/scripts/dispatch-line-gate.sh +61 -0
  126. package/tests/scripts/dispatch-reference-gate.sh +13 -13
  127. package/tests/scripts/ensure-default-config.sh +162 -0
  128. package/tests/scripts/eval-runner.sh +9 -9
  129. package/tests/scripts/evals-packaging.sh +127 -20
  130. package/tests/scripts/fixtures/size-tier-cases.json +87 -0
  131. package/tests/scripts/global-config.sh +167 -0
  132. package/tests/scripts/goldens/loop-state-done.json +1 -1
  133. package/tests/scripts/goldens/somi-loop.json +3 -3
  134. package/tests/scripts/lib/agent-registry-tests.mjs +95 -0
  135. package/tests/scripts/lib/brief-only-guard.mjs +27 -0
  136. package/tests/scripts/lib/checkpoint-gate.mjs +40 -3
  137. package/tests/scripts/lib/dispatch-reference-gate.mjs +5 -5
  138. package/tests/scripts/lib/retirement-gate.mjs +7 -2
  139. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +52 -0
  140. package/tests/scripts/lib/site-roadmap-gate.mjs +64 -0
  141. package/tests/scripts/lib/size-tier-drift.mjs +74 -0
  142. package/tests/scripts/lib/somi-mcp-config-tests.mjs +92 -0
  143. package/tests/scripts/lib/somi-mcp-tests.mjs +66 -28
  144. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +64 -0
  145. package/tests/scripts/retirement-gate.sh +19 -0
  146. package/tests/scripts/review-panel-seats.sh +2 -2
  147. package/tests/scripts/run.sh +95 -0
  148. package/tests/scripts/site-roadmap-gate.sh +76 -0
  149. package/tests/scripts/size-tier.sh +562 -0
  150. package/tests/scripts/somi-agent-dispatch-contract.sh +20 -11
  151. package/tests/scripts/somi-config.sh +286 -0
  152. package/tests/scripts/somi-dispatch.sh +150 -98
  153. package/tests/scripts/somi-mcp.sh +2 -0
@@ -1,36 +1,42 @@
1
- // cost-ceiling.mjs — the session cost ceiling: a maximum `cost` tier a dispatch may cross without
2
- // explicit sign-off.
1
+ // cost-ceiling.mjs — the session cost ceiling: the tier every dispatch runs at unless an agent has
2
+ // its own override in .somi/config.json.
3
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.
4
+ // "The config" below is the effective one: the global file with the project's .somi/config.json
5
+ // merged over it (scripts/lib/config-files.mjs).
6
+ //
7
+ // The ceiling is re-resolved on every call, nothing is frozen once. Precedence, highest first:
8
+ // 1. a value given THIS call: an argument the caller parsed itself (a CLI flag) or SOMI_COST_CEILING
9
+ // 2. `cost.ceiling` in .somi/config.json, read live on every call
10
+ // 3. a ceiling persisted by an earlier call, but only one that call took from a CLI flag or the env
11
+ // var (a ceiling someone explicitly set), and only when the config sets none
12
+ // 4. DEFAULT_CEILING
13
+ // So a bare edit to .somi/config.json moves the ceiling on the very next dispatch. That reverses the
14
+ // older rule (and the loop-cap precedent in scripts/somi-loop.mjs) under which a config edit could
15
+ // not move a ceiling already in force. A persisted ceiling that was itself taken from the config,
16
+ // the default, or from before origins were recorded never outranks 2 or 4 -- it yields, so it can
17
+ // not pin a stale value after a config fix or a change of default.
18
+ //
19
+ // Only a CLI/env value is ever written to disk. Every value that reaches validateCeiling() is
20
+ // rejected outright if it isn't one of VALID_COSTS -- never coerced -- so a malformed value dies
21
+ // loudly instead of quietly disabling the ceiling.
11
22
  //
12
23
  // State is deliberately NOT keyed by slug (unlike loop state): the ceiling bounds an operator's
13
24
  // 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 —
25
+ // Callers pass `root` explicitly rather than this module sniffing CLAUDE_PROJECT_DIR itself --
15
26
  // keeps the module a pure library over explicit inputs, testable without env-var setup.
16
27
  //
17
- // Every raise is appended to `ceiling_overrides`, shaped {field, from, to, source, at} — the same
28
+ // Every raise is appended to `ceiling_overrides`, shaped {field, from, to, source, at} -- the same
18
29
  // shape somi-loop.mjs's `cap_overrides` uses, so an override record looks the same wherever it's
19
30
  // 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
31
 
28
32
  import fs from 'node:fs';
29
33
  import path from 'node:path';
30
34
  import { resolveModel, VALID_COSTS } from './cost-model.mjs';
35
+ import { validateCostConfig, quote } from './cost-config.mjs';
36
+ import { loadConfig, ConfigFileError, MAX_CONFIG_BYTES as CONFIG_LIMIT } from './config-files.mjs';
31
37
 
32
38
  export const CEILING_ENV = 'SOMI_COST_CEILING';
33
- export const DEFAULT_CEILING = 'high';
39
+ export const DEFAULT_CEILING = 'medium';
34
40
  export const ACTIONS = Object.freeze(['allow']);
35
41
 
36
42
  const ORDER = Object.freeze(Object.fromEntries(VALID_COSTS.map((c, i) => [c, i])));
@@ -43,26 +49,58 @@ function nowIso() {
43
49
  return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
44
50
  }
45
51
 
46
- function readConfig(root) {
47
- const file = path.join(root, '.somi', 'config.json');
48
- let raw;
52
+ // A file this large is neither a config nor a state file, so it is refused rather than parsed.
53
+ export const MAX_CONFIG_BYTES = CONFIG_LIMIT;
54
+
55
+ // The reader for SoMi's own state files (the persisted ceiling): opened with O_NOFOLLOW (a planted
56
+ // symlink -- say to /dev/zero -- is refused, never followed) and O_NONBLOCK (a FIFO cannot hang the
57
+ // open), then checked on the open descriptor, not the path, so there is no stat-then-read race. At
58
+ // most MAX_CONFIG_BYTES+1 bytes are ever read. Config files are read by config-files.mjs instead,
59
+ // which follows links (a junction or symlinked .somi, a linked config) under the same other checks.
60
+ const OPEN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
61
+
62
+ export function readTextFile(file) {
63
+ let fd;
49
64
  try {
50
- raw = fs.readFileSync(file, 'utf8');
65
+ fd = fs.openSync(file, OPEN_FLAGS);
51
66
  } catch (e) {
52
- if (e.code === 'ENOENT') return {}; // no config committed: nothing configured, defaults apply
67
+ if (e.code === 'ELOOP') throw new Error(`cost-ceiling: ${file} is a symlink; refusing to follow it`);
53
68
  throw e;
54
69
  }
55
70
  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}`);
71
+ if (!fs.fstatSync(fd).isFile()) throw new Error(`cost-ceiling: ${file} is not a regular file`);
72
+ const buf = Buffer.alloc(MAX_CONFIG_BYTES + 1);
73
+ let n = 0;
74
+ while (n < buf.length) {
75
+ const got = fs.readSync(fd, buf, n, buf.length - n, null);
76
+ if (got === 0) break;
77
+ n += got;
78
+ }
79
+ if (n > MAX_CONFIG_BYTES) throw new Error(`cost-ceiling: ${file} is over the ${MAX_CONFIG_BYTES}-byte limit`);
80
+ return buf.toString('utf8', 0, n);
81
+ } finally {
82
+ fs.closeSync(fd);
62
83
  }
63
84
  }
64
85
 
65
- const COST_CONFIG_KEYS = new Set(['ceiling', 'mapping']);
86
+ // The parser's own message quotes file text (untrusted, and it reaches the model), so only its error
87
+ // name and numeric position are reported.
88
+ function parseFailure(file, e) {
89
+ const pos = /position (\d+)/.exec(String(e.message))?.[1];
90
+ return new Error(`cost-ceiling: ${file} is not valid JSON (${JSON.stringify(e.name)}${pos ? ` at position ${pos}` : ''})`);
91
+ }
92
+
93
+ // The effective config. A file that fails to PARSE is not "unconfigured" -- silently returning {}
94
+ // would bootstrap DEFAULT_CEILING and PERSIST it, inverting a team's `low` policy until someone
95
+ // notices, and outliving the typo once fixed. Dies loudly, naming the file.
96
+ export function readConfig(root) {
97
+ try {
98
+ return loadConfig(root).config;
99
+ } catch (e) {
100
+ if (e instanceof ConfigFileError) throw new Error(`cost-ceiling: ${e.message}`);
101
+ throw e;
102
+ }
103
+ }
66
104
 
67
105
  // A `cost` that isn't an object, has an unrecognized key (a typo), or a `ceiling` misplaced at
68
106
  // the top level all die loudly here instead of silently resolving to "not configured".
@@ -70,47 +108,39 @@ const COST_CONFIG_KEYS = new Set(['ceiling', 'mapping']);
70
108
  // Exported: this is also the one config reader scripts/somi-dispatch.mjs uses to pull `mapping`
71
109
  // (its `ceiling` sibling), so a project's cost config is never parsed by two independent readers
72
110
  // that could drift on what counts as malformed.
111
+ // Each file's own cost block is validated first, so an error names the file it is in; then the merge.
73
112
  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)}`);
113
+ let files;
114
+ try {
115
+ files = loadConfig(root);
116
+ } catch (e) {
117
+ if (e instanceof ConfigFileError) throw new Error(`cost-ceiling: ${e.message}`);
118
+ throw e;
82
119
  }
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
- }
120
+ for (const f of [files.global, files.project]) {
121
+ if (!f.present) continue;
122
+ if (f.config.ceiling !== undefined) throw new Error(`cost-ceiling: "ceiling" in ${f.path} belongs under "cost.ceiling"`);
123
+ try { validateCostConfig(f.config.cost); } catch (e) { throw new Error(`${e.message} (in ${f.path})`); }
87
124
  }
88
- return cost;
125
+ return validateCostConfig(files.config.cost);
89
126
  }
90
127
 
91
128
  function validateCeiling(raw, label) {
92
129
  if (!VALID_COSTS.includes(raw)) {
93
- throw new Error(`cost-ceiling: ${label} expected one of ${VALID_COSTS.join('|')}, got "${raw}"`);
130
+ throw new Error(`cost-ceiling: ${label} expected one of ${VALID_COSTS.join('|')}, got ${quote(raw)}`);
94
131
  }
95
132
  return raw;
96
133
  }
97
134
 
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.
135
+ // What produced a persisted ceiling. Only `cli` and `env` are ever written now; `config` and `default`
136
+ // are what earlier versions wrote, and are accepted (never rewritten) so an old state file still
137
+ // loads. A state file with no origin at all (one written before origins were recorded) is legacy: it yields.
102
138
  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';
139
+ const EXPLICIT_ORIGINS = Object.freeze(['cli', 'env']);
110
140
 
111
141
  function validateOrigin(raw, label) {
112
142
  if (!VALID_ORIGINS.includes(raw)) {
113
- throw new Error(`cost-ceiling: ${label} expected one of ${VALID_ORIGINS.join('|')}, got "${raw}"`);
143
+ throw new Error(`cost-ceiling: ${label} expected one of ${VALID_ORIGINS.join('|')}, got ${quote(raw)}`);
114
144
  }
115
145
  return raw;
116
146
  }
@@ -118,130 +148,115 @@ function validateOrigin(raw, label) {
118
148
  function saveState(root, state) {
119
149
  const file = ceilingStatePath(root);
120
150
  fs.mkdirSync(path.dirname(file), { recursive: true });
121
- fs.writeFileSync(file, JSON.stringify(state));
151
+ // Written to a fresh exclusive temp file (O_NOFOLLOW) and renamed over the target: the rename
152
+ // replaces a symlink planted at ceiling.json instead of writing through it, and a reader never
153
+ // sees a half-written file.
154
+ const tmp = `${file}.${process.pid}.tmp`;
155
+ const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0);
156
+ try {
157
+ const fd = fs.openSync(tmp, flags, 0o666);
158
+ try { fs.writeSync(fd, JSON.stringify(state)); } finally { fs.closeSync(fd); }
159
+ fs.renameSync(tmp, file);
160
+ } catch (e) {
161
+ fs.rmSync(tmp, { force: true });
162
+ throw e;
163
+ }
122
164
  }
123
165
 
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) {
166
+ // Returns the persisted state, or undefined when there is none. A PRESENT but corrupt file is not
167
+ // silently treated as missing -- it throws, same "malformed dies loudly" discipline as a bad
168
+ // CLI/env value. Read with the same no-follow, regular-file, size-bounded helper as the config.
169
+ export function loadState(root) {
135
170
  const file = ceilingStatePath(root);
136
171
  let raw;
137
172
  try {
138
- raw = fs.readFileSync(file, 'utf8');
173
+ raw = readTextFile(file);
139
174
  } 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 };
175
+ if (e.code === 'ENOENT') return undefined;
176
+ throw e;
150
177
  }
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.
178
+ // An unparsable state file must still name the file in its error -- a bare JSON.parse throw would
179
+ // surface as an unattributed SyntaxError, leaving a caller no path to report which file is corrupt.
154
180
  let state;
155
181
  try {
156
182
  state = JSON.parse(raw);
157
183
  } catch (e) {
158
- throw new Error(`cost-ceiling: ${file} is not valid JSON: ${e.message}`);
184
+ throw parseFailure(file, e);
159
185
  }
160
186
  if (state === null || typeof state !== 'object' || Array.isArray(state)) {
161
187
  throw new Error(`cost-ceiling: ${file} is not a valid state object`);
162
188
  }
163
189
  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;
190
+ // Absent entirely is legacy (it yields), not corruption; present but wrong is rejected.
191
+ if (state.ceiling_origin !== undefined) validateOrigin(state.ceiling_origin, `ceiling_origin in ${file}`);
192
+ return state;
188
193
  }
189
194
 
190
195
  /**
191
196
  * 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).
197
+ * extracted THIS invocation (e.g. a parsed CLI flag) -- distinct from SOMI_COST_CEILING, read here.
198
+ * Precedence is in this file's header: explicit (arg, then env) > config > persisted CLI/env > default.
199
+ * `source` names where THIS call's effective ceiling came from: `cli`, `env`, `config`, `state` (a
200
+ * ceiling persisted by an earlier CLI/env call) or `default`. `ceiling_origin` is what produced the
201
+ * value: the same, except a `state` ceiling reports the `cli`/`env` that originally set it.
202
+ * A CLI/env value that differs from what is persisted is saved (with an override record); that is the
203
+ * only write this function makes, and `{persist: false}` skips it (a read-only lookup such as
204
+ * somi_agent_info reports the same answer without remembering anything).
208
205
  * @returns {{ceiling: string, overridden: boolean, source: string, ceiling_origin: string, override?: object}}
209
206
  */
210
- export function resolveCeiling(root, explicitArg) {
211
- const { state, bootstrapSource } = loadOrInitState(root);
207
+ export function resolveCeiling(root, explicitArg, { persist = true } = {}) {
208
+ const state = loadState(root);
209
+ const configured = readCostConfig(root).ceiling;
210
+ const isConfigured = !(configured === undefined || configured === null || configured === '');
212
211
  const isCli = explicitArg !== undefined && explicitArg !== '';
213
212
  const envVal = process.env[CEILING_ENV];
214
213
  const explicit = isCli ? explicitArg : (envVal === undefined || envVal === '' ? undefined : envVal);
214
+
215
215
  if (explicit === undefined) {
216
- return { ceiling: state.ceiling, overridden: false, source: bootstrapSource, ceiling_origin: reportedOrigin(root, state, bootstrapSource) };
216
+ if (isConfigured) {
217
+ const ceiling = validateCeiling(configured, 'cost.ceiling in .somi/config.json');
218
+ return { ceiling, overridden: false, source: 'config', ceiling_origin: 'config' };
219
+ }
220
+ if (state && EXPLICIT_ORIGINS.includes(state.ceiling_origin)) {
221
+ return { ceiling: state.ceiling, overridden: false, source: 'state', ceiling_origin: state.ceiling_origin };
222
+ }
223
+ return { ceiling: DEFAULT_CEILING, overridden: false, source: 'default', ceiling_origin: 'default' };
217
224
  }
225
+
226
+ // A config that sets a ceiling is validated even when a CLI/env value outranks it: a typo there
227
+ // should surface now, not on the later call that lacks the flag.
228
+ if (isConfigured) validateCeiling(configured, 'cost.ceiling in .somi/config.json');
218
229
  const source = isCli ? 'cli' : 'env';
219
230
  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) };
231
+ const persisted = state && EXPLICIT_ORIGINS.includes(state.ceiling_origin) ? state : undefined;
232
+ // Nothing to do only when the stored value already matches AND no differing config is being raised
233
+ // over (then the effective ceiling changes and the raise is recorded below).
234
+ const configDiffers = isConfigured && configured !== validated;
235
+ if (persisted && persisted.ceiling === validated && persisted.ceiling_origin === source && !configDiffers) {
236
+ return { ceiling: validated, overridden: false, source, ceiling_origin: source };
237
+ }
238
+ const next = state ?? {};
239
+ // The override record's `from` is the ceiling that was in force before this call.
240
+ const from = isConfigured ? configured : (persisted ? persisted.ceiling : DEFAULT_CEILING);
241
+ next.ceiling = validated;
242
+ next.ceiling_origin = source;
243
+ if (from === validated) {
244
+ if (persist) saveState(root, next);
245
+ return { ceiling: validated, overridden: false, source, ceiling_origin: source };
222
246
  }
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 };
247
+ const override = { field: 'ceiling', from, to: validated, source, at: nowIso() };
248
+ if (!Array.isArray(next.ceiling_overrides)) next.ceiling_overrides = [];
249
+ // A repeat of the identical raise (same flag every call, config unchanged) is not a new event.
250
+ const last = next.ceiling_overrides[next.ceiling_overrides.length - 1];
251
+ if (!(last && last.from === from && last.to === validated && last.source === source)) next.ceiling_overrides.push(override);
252
+ if (persist) saveState(root, next);
253
+ return { ceiling: validated, overridden: true, source, ceiling_origin: source, override };
238
254
  }
239
255
 
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
256
+ // The `costs` argument is a tier set in ascending order; the resolver passes the agent's single
257
+ // default tier. Accepts a bare string too, as a one-member set, so a single-tier caller needs no
258
+ // special-casing. Always returns a frozen array in ascending order, re-checked here rather than
259
+ // trusted: this is a library over
245
260
  // explicit inputs, and a malformed set must die loudly rather than be silently coerced into
246
261
  // something valid -- the same discipline validateCeiling() above applies to the ceiling value.
247
262
  function normalizeCostSet(costs, label) {
@@ -264,48 +279,44 @@ function normalizeCostSet(costs, label) {
264
279
  }
265
280
 
266
281
  /**
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:
282
+ * Selects the tier a dispatch runs at. The ceiling is a HARD cap with one escape hatch:
270
283
  *
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.
284
+ * - `override` given (the agent's `cost.agents.<name>` from config) -> `selected` is the override,
285
+ * even above the ceiling. `tier_source` is `"override"`.
286
+ * - no override -> `selected` is the CEILING tier itself, whatever the unit's default tier is (not that
287
+ * default, not a min() of the two). `tier_source` is `"ceiling"`.
278
288
  *
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.
289
+ * `costs` (the unit's default tier set, a string or an ascending duplicate-free array) is
290
+ * read only to report: `supported` echoes it, and `degraded` is true when `selected` ranks below
291
+ * its highest member. It never changes `selected`: declaring a tier never lowers or raises the run.
292
+ *
293
+ * Pure and deterministic; the result is frozen so a caller can't rewrite the selection.
282
294
  */
283
- export function decideDispatch(costs, ceiling) {
284
- const supported = normalizeCostSet(costs, 'declared cost');
295
+ export function decideDispatch(costs, ceiling, override) {
296
+ const supported = normalizeCostSet(costs, 'default tier');
285
297
  if (!VALID_COSTS.includes(ceiling)) {
286
298
  throw new Error(`cost-ceiling: unrecognized ceiling "${ceiling}" (expected one of ${VALID_COSTS.join('|')})`);
287
299
  }
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
- }
300
+ if (override !== undefined && !VALID_COSTS.includes(override)) {
301
+ throw new Error(`cost-ceiling: unrecognized override "${override}" (expected one of ${VALID_COSTS.join('|')})`);
297
302
  }
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 });
303
+ const selected = override === undefined ? ceiling : override;
304
+ const degraded = ORDER[selected] < ORDER[supported[supported.length - 1]];
305
+ return Object.freeze({
306
+ action: 'allow',
307
+ selected,
308
+ supported,
309
+ ceiling,
310
+ degraded,
311
+ tier_source: override === undefined ? 'ceiling' : 'override',
312
+ });
302
313
  }
303
314
 
304
315
  /**
305
316
  * The only sanctioned way to turn a decideDispatch() result into a model. `decideDispatch` always
306
317
  * 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.
318
+ * structural closer: nothing can hand this function a decision that wasn't produced by
319
+ * `decideDispatch`'s own selection and expect a model back.
309
320
  */
310
321
  export function modelForDispatch(decision, host, mapping) {
311
322
  if (!decision || decision.action !== 'allow') {
@@ -0,0 +1,102 @@
1
+ // cost-config-edit.mjs — the pure edit step shared by scripts/somi-config.mjs, the cost-lowering
2
+ // PreToolUse hook and the tests: parse a key, check a tier, and apply set/unset/init to an
3
+ // already-parsed config. No I/O. Only cost.ceiling and cost.agents.<name> can be edited.
4
+
5
+ import { validateCostConfig, quote } from './cost-config.mjs';
6
+ import { VALID_COSTS, MODEL_ID_RE, MAX_MODEL_CANDIDATES, mergeHostMapping, resolveModelCandidates } from './cost-model.mjs';
7
+ import { buildDefaultConfig } from './cost-defaults.mjs';
8
+
9
+ // A caller mistake (bad key, tier or name), as opposed to a problem with the project's files.
10
+ export class EditError extends Error {}
11
+
12
+ const KEY_RE = /^cost\.(ceiling|agents\.([a-z][a-z0-9-]*)|mapping\.([a-z][a-z0-9-]{0,31})(?:\.(low|medium|high))?)$/;
13
+
14
+ /**
15
+ * -> {kind:'ceiling'} | {kind:'agent', name} | {kind:'mapping', host, tier?}; throws EditError for any
16
+ * other key. `cost.mapping.<host>.<tier>` is set; `cost.mapping.<host>` (the whole host map) is unset.
17
+ */
18
+ export function parseKey(key) {
19
+ const m = KEY_RE.exec(key);
20
+ if (!m) throw new EditError(`only cost.ceiling, cost.agents.<name> and cost.mapping.<host>[.<tier>] can be used, not ${quote(key)}`);
21
+ if (m[1] === 'ceiling') return { kind: 'ceiling' };
22
+ if (m[2] !== undefined) return { kind: 'agent', name: m[2] };
23
+ return { kind: 'mapping', host: m[3], tier: m[4] };
24
+ }
25
+
26
+ /** A model value: one id, or a comma-separated preference list (#35) -> a string or an array. */
27
+ export function parseModels(v) {
28
+ const list = typeof v === 'string' ? v.split(',').map((x) => x.trim()) : [];
29
+ if (list.length === 0 || list.length > MAX_MODEL_CANDIDATES || list.some((x) => !MODEL_ID_RE.test(x)) || new Set(list).size !== list.length) {
30
+ throw new EditError(`the value must be a model id or up to ${MAX_MODEL_CANDIDATES} distinct comma-separated ids, got ${quote(v)}`);
31
+ }
32
+ return list.length === 1 ? list[0] : list;
33
+ }
34
+
35
+ /** The tiers a named host's map still lacks (a host in cost.mapping replaces its whole tier map). */
36
+ export function missingMappingTiers(cost, host) {
37
+ const tiers = cost?.mapping?.[host];
38
+ return tiers ? VALID_COSTS.filter((t) => !Object.hasOwn(tiers, t)) : [];
39
+ }
40
+
41
+ export function parseTier(v) {
42
+ if (!VALID_COSTS.includes(v)) throw new EditError(`the tier must be one of ${VALID_COSTS.join('|')}, got ${quote(v)}`);
43
+ return v;
44
+ }
45
+
46
+ /** Throws unless the whole cost block is legal (keys, agent names, tiers, ceiling value). */
47
+ export function validateCostBlock(cost) {
48
+ validateCostConfig(cost);
49
+ if (cost && cost.mapping !== undefined) {
50
+ const merged = mergeHostMapping({}, cost.mapping);
51
+ for (const host of Object.keys(merged)) for (const tier of Object.keys(merged[host])) resolveModelCandidates(tier, host, merged);
52
+ }
53
+ if (cost && cost.ceiling !== undefined && !VALID_COSTS.includes(cost.ceiling)) {
54
+ throw new Error(`cost-ceiling: cost.ceiling expected one of ${VALID_COSTS.join('|')}, got ${quote(cost.ceiling)}`);
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Applies one edit to `cfg` (a parsed config object, or null for an absent file) IN PLACE where it
60
+ * can, and returns {next, changed}. `action` is set|unset|init. A set or init on an absent file
61
+ * starts from the default config; an unset of an absent file or entry changes nothing. The result is
62
+ * not validated here: callers run validateCostBlock(next.cost) so each can report it its own way.
63
+ */
64
+ export function applyEdit(cfg, { action, key, value }) {
65
+ const absent = cfg === null || cfg === undefined;
66
+ if (action === 'init') return absent ? { next: buildDefaultConfig(), changed: true } : { next: cfg, changed: false };
67
+ const k = parseKey(key);
68
+ if (action === 'unset') {
69
+ if (k.kind === 'mapping' && k.tier === undefined) {
70
+ if (absent || !(cfg.cost?.mapping && Object.hasOwn(cfg.cost.mapping, k.host))) return { next: cfg ?? {}, changed: false };
71
+ delete cfg.cost.mapping[k.host];
72
+ if (Object.keys(cfg.cost.mapping).length === 0) delete cfg.cost.mapping;
73
+ return { next: cfg, changed: true };
74
+ }
75
+ if (k.kind !== 'agent') throw new EditError('only cost.agents.<name> and cost.mapping.<host> can be unset');
76
+ if (absent || !(cfg.cost?.agents && Object.hasOwn(cfg.cost.agents, k.name))) return { next: cfg ?? {}, changed: false };
77
+ delete cfg.cost.agents[k.name];
78
+ return { next: cfg, changed: true };
79
+ }
80
+ if (action !== 'set') throw new EditError('the action must be set, unset or init');
81
+ if (k.kind === 'mapping') {
82
+ if (k.tier === undefined) throw new EditError('set one tier at a time: cost.mapping.<host>.<low|medium|high>');
83
+ const models = parseModels(value);
84
+ const base = absent ? buildDefaultConfig() : cfg;
85
+ const before = JSON.stringify(base.cost ?? null);
86
+ if (base.cost === undefined || base.cost === null) base.cost = {};
87
+ if (base.cost.mapping === undefined) base.cost.mapping = {};
88
+ if (base.cost.mapping[k.host] === undefined) base.cost.mapping[k.host] = {};
89
+ base.cost.mapping[k.host][k.tier] = models;
90
+ return { next: base, changed: absent || JSON.stringify(base.cost) !== before };
91
+ }
92
+ const tier = parseTier(value);
93
+ const next = absent ? buildDefaultConfig() : cfg;
94
+ const before = JSON.stringify(next.cost ?? null);
95
+ if (next.cost === undefined || next.cost === null) next.cost = {};
96
+ if (k.kind === 'ceiling') next.cost.ceiling = tier;
97
+ else {
98
+ if (next.cost.agents === undefined) next.cost.agents = {};
99
+ next.cost.agents[k.name] = tier;
100
+ }
101
+ return { next, changed: absent || JSON.stringify(next.cost) !== before };
102
+ }