@skathio/somi 4.0.0 → 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.
@@ -1,6 +1,9 @@
1
1
  // cost-ceiling.mjs — the session cost ceiling: the tier every dispatch runs at unless an agent has
2
2
  // its own override in .somi/config.json.
3
3
  //
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
+ //
4
7
  // The ceiling is re-resolved on every call, nothing is frozen once. Precedence, highest first:
5
8
  // 1. a value given THIS call: an argument the caller parsed itself (a CLI flag) or SOMI_COST_CEILING
6
9
  // 2. `cost.ceiling` in .somi/config.json, read live on every call
@@ -30,6 +33,7 @@ import fs from 'node:fs';
30
33
  import path from 'node:path';
31
34
  import { resolveModel, VALID_COSTS } from './cost-model.mjs';
32
35
  import { validateCostConfig, quote } from './cost-config.mjs';
36
+ import { loadConfig, ConfigFileError, MAX_CONFIG_BYTES as CONFIG_LIMIT } from './config-files.mjs';
33
37
 
34
38
  export const CEILING_ENV = 'SOMI_COST_CEILING';
35
39
  export const DEFAULT_CEILING = 'medium';
@@ -45,13 +49,14 @@ function nowIso() {
45
49
  return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
46
50
  }
47
51
 
48
- // A committed config is untrusted input, read whole into memory and into the model's reach; a file
49
- // this large is not a config, so it is refused rather than parsed.
50
- export const MAX_CONFIG_BYTES = 64 * 1024;
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;
51
54
 
52
- // Opened with O_NOFOLLOW (a committed symlink -- say to /dev/zero -- is refused, never followed) and
53
- // O_NONBLOCK (a FIFO cannot hang the open), then checked on the open descriptor, not the path, so
54
- // there is no stat-then-read race. At most MAX_CONFIG_BYTES+1 bytes are ever read.
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.
55
60
  const OPEN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
56
61
 
57
62
  export function readTextFile(file) {
@@ -85,23 +90,16 @@ function parseFailure(file, e) {
85
90
  return new Error(`cost-ceiling: ${file} is not valid JSON (${JSON.stringify(e.name)}${pos ? ` at position ${pos}` : ''})`);
86
91
  }
87
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.
88
96
  export function readConfig(root) {
89
- const file = path.join(root, '.somi', 'config.json');
90
- let raw;
91
97
  try {
92
- raw = readTextFile(file);
98
+ return loadConfig(root).config;
93
99
  } catch (e) {
94
- if (e.code === 'ENOENT') return {}; // no config committed: nothing configured, defaults apply
100
+ if (e instanceof ConfigFileError) throw new Error(`cost-ceiling: ${e.message}`);
95
101
  throw e;
96
102
  }
97
- try {
98
- return JSON.parse(raw);
99
- } catch (e) {
100
- // A committed config that fails to PARSE is not "unconfigured" -- silently returning {} here
101
- // would bootstrap DEFAULT_CEILING and PERSIST it, inverting a team's `low` policy until
102
- // someone notices, and outliving the typo once fixed. Dies loudly, naming the file.
103
- throw parseFailure(file, e);
104
- }
105
103
  }
106
104
 
107
105
  // A `cost` that isn't an object, has an unrecognized key (a typo), or a `ceiling` misplaced at
@@ -110,12 +108,21 @@ export function readConfig(root) {
110
108
  // Exported: this is also the one config reader scripts/somi-dispatch.mjs uses to pull `mapping`
111
109
  // (its `ceiling` sibling), so a project's cost config is never parsed by two independent readers
112
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.
113
112
  export function readCostConfig(root) {
114
- const cfg = readConfig(root);
115
- if (cfg.ceiling !== undefined) {
116
- throw new Error('cost-ceiling: "ceiling" in .somi/config.json belongs under "cost.ceiling"');
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;
119
+ }
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})`); }
117
124
  }
118
- return validateCostConfig(cfg.cost);
125
+ return validateCostConfig(files.config.cost);
119
126
  }
120
127
 
121
128
  function validateCeiling(raw, label) {
@@ -29,6 +29,7 @@
29
29
  import fs from 'node:fs';
30
30
  import path from 'node:path';
31
31
  import { execFileSync } from 'node:child_process';
32
+ import { loadConfig } from './lib/config-files.mjs';
32
33
 
33
34
  const PROG = 'somi-check';
34
35
 
@@ -84,11 +85,11 @@ const LOCKFILES = [
84
85
  'poetry.lock', 'uv.lock', 'composer.lock', 'go.sum',
85
86
  ];
86
87
 
88
+ // The effective config (global, with the project's .somi/config.json over it); an unreadable or
89
+ // invalid file reads as unconfigured, so the documented defaults apply.
87
90
  function readConfig(root) {
88
- const cfgPath = path.join(root, '.somi', 'config.json');
89
- if (!fs.existsSync(cfgPath)) return {};
90
91
  try {
91
- return JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
92
+ return loadConfig(root).config;
92
93
  } catch {
93
94
  return {};
94
95
  }
@@ -1,15 +1,20 @@
1
1
  #!/usr/bin/env node
2
- // somi-config.mjs — show and change the cost settings in a project's .somi/config.json.
2
+ // somi-config.mjs — show and change the cost settings in SoMi's config: the global file every project
3
+ // and session reads, and a project's .somi/config.json merged over it (scripts/lib/config-files.mjs).
3
4
  //
4
- // show one JSON line: where the file is, the ceiling, and every agent's
5
- // effective tier (the resolver's own rule: the agent's cost.agents entry,
6
- // else the ceiling), plus fixed warnings
5
+ // show one JSON line: both files, the ceiling, and every agent's effective
6
+ // tier (the resolver's own rule: the agent's cost.agents entry, else the
7
+ // ceiling) in the merged config, each with the file it came from, plus
8
+ // fixed warnings
7
9
  // get cost.ceiling | cost.agents.<name>
8
10
  // set cost.ceiling <low|medium|high> | set cost.agents.<name> <low|medium|high>
9
11
  // set cost.mapping.<host>.<tier> <model-id[,model-id...]> (a preference list, first offered wins)
10
12
  // unset cost.agents.<name> | unset cost.mapping.<host>
11
13
  // init create the default file when absent (the exact text the SessionStart
12
- // hook writes); a no-op if anything exists at the path
14
+ // hook writes); a no-op if anything exists at the path, and for the
15
+ // project file also when a global config exists (it holds the defaults)
16
+ // [--global] (set, unset, init) change the global file instead of the project's.
17
+ // For the user to run: the somi_config MCP tool never passes it
13
18
  // [--project-dir DIR] default: CLAUDE_PROJECT_DIR, else the current directory
14
19
  // [--host NAME] (show) the host this session runs on; adds a warning when that host has
15
20
  // no model mapping while any agent resolves to high (#36)
@@ -34,12 +39,15 @@
34
39
  // env call, else the built-in default (`effective_ceiling`), and warn when the variable or a
35
40
  // persisted value is why it differs from the config.
36
41
  //
37
- // Safety: the committed config is untrusted. It is read with the same bounded (64 KiB), no-follow,
38
- // regular-file reader the resolver uses, and the whole `cost` block is validated by the shared
39
- // validator before and after an edit. A write goes to a fresh temp file in the same .somi directory
40
- // (O_EXCL, no-follow) and is renamed over config.json, so a reader never sees half a file and nothing
41
- // is written through a link. A symlinked .somi or config.json is refused. Output is pure ASCII and no
42
- // message echoes text from the file (values are quoted and bounded).
42
+ // Safety: the committed config is untrusted. show and get read it as the resolver does (bounded to
43
+ // 64 KiB, regular files only, links followed so a junction or symlinked .somi works), and the whole
44
+ // `cost` block is validated by the shared validator before and after an edit. A project write goes to
45
+ // a fresh temp file in the same .somi directory (O_EXCL, no-follow) and is renamed over config.json, so
46
+ // a reader never sees half a file and nothing is written through a link: a symlinked .somi or
47
+ // config.json is refused for set, unset and init. The global file is the user's own: a write to it
48
+ // follows a link to the real file (a dotfiles setup keeps its link) and creates missing parent
49
+ // directories. A lowering is judged on the merged config, before and after. Output is pure ASCII and
50
+ // no message echoes text from a file (values are quoted and bounded).
43
51
  //
44
52
  // Exit codes (callers branch on these — do not repurpose):
45
53
  // 0 ok
@@ -51,6 +59,7 @@
51
59
  import fs from 'node:fs';
52
60
  import path from 'node:path';
53
61
  import { readTextFile, loadState, decideDispatch, DEFAULT_CEILING, MAX_CONFIG_BYTES } from './lib/cost-ceiling.mjs';
62
+ import { ConfigFileError, globalConfigPath, loadConfig, mergeConfig, readConfigText } from './lib/config-files.mjs';
54
63
  import { quote } from './lib/cost-config.mjs';
55
64
  import { VALID_COSTS, HOST_MODELS } from './lib/cost-model.mjs';
56
65
  import { AGENT_DEFAULT_TIERS, serializeDefaultConfig } from './lib/cost-defaults.mjs';
@@ -58,7 +67,7 @@ import { EditError, applyEdit, parseKey, validateCostBlock, missingMappingTiers
58
67
  import { lowers, REASONS } from './lib/cost-lowering.mjs';
59
68
 
60
69
  const PROG = 'somi-config';
61
- const USAGE = `usage: ${PROG}.mjs show [--host NAME] | get <key> | set <key> <value> | unset <key> | init [--project-dir DIR] [--refuse-lowering] (keys: cost.ceiling, cost.agents.<name>, cost.mapping.<host>.<tier> = model-id[,model-id...]; unset cost.agents.<name> or cost.mapping.<host>)`;
70
+ const USAGE = `usage: ${PROG}.mjs show [--host NAME] | get <key> | set <key> <value> | unset <key> | init [--project-dir DIR] [--global] [--refuse-lowering] (keys: cost.ceiling, cost.agents.<name>, cost.mapping.<host>.<tier> = model-id[,model-id...]; unset cost.agents.<name> or cost.mapping.<host>)`;
62
71
  const HOST_RE = /^[a-z][a-z0-9-]{0,31}$/;
63
72
  const EXIT_USAGE = 64;
64
73
  const EXIT_PROJECT = 67;
@@ -66,6 +75,7 @@ const EXIT_PROJECT = 67;
66
75
  const SEC_WARNING = 'somi-security-reviewer runs below high; pin it with: set cost.agents.somi-security-reviewer high';
67
76
  const ENV_WARNING = 'SOMI_COST_CEILING is set in this environment and outranks cost.ceiling in the config';
68
77
  const STATE_WARNING = 'a ceiling set earlier by a flag or SOMI_COST_CEILING is in force because cost.ceiling is not set in the config';
78
+ const GLOBAL_ONLY_WARNING = 'that value is set in your global config, not this project, so nothing changed here; change it with --global (run the CLI yourself)';
69
79
  const UNKNOWN_WARNING = 'that agent name is not a shipped agent; the entry is accepted but may never be used';
70
80
  const unmappedWarning = (host, n) => `${host} has no model mapping, so ${n} high-tier agent(s) run on whatever model the host picks; set cost.mapping.${host} with low, medium and high (docs/USAGE.md, "Pinning models per tier on Copilot")`;
71
81
  const MAPPING_MESSAGE = 'this change remaps a tier to a different model and needs the user: ask them to run node scripts/somi-config.mjs themselves or edit .somi/config.json';
@@ -89,9 +99,11 @@ function parseArgs(argv) {
89
99
  const pos = [];
90
100
  let dir;
91
101
  let refuse = false;
102
+ let global = false;
92
103
  let host;
93
104
  for (let i = 0; i < rest.length; i++) {
94
105
  if (rest[i] === '--refuse-lowering') refuse = true;
106
+ else if (rest[i] === '--global') global = true;
95
107
  else if (rest[i] === '--host') {
96
108
  if (host !== undefined) usage('--host given twice');
97
109
  host = rest[++i];
@@ -109,7 +121,8 @@ function parseArgs(argv) {
109
121
  if (pos.length !== want[cmd]) usage(`${cmd} takes ${want[cmd]} argument(s)`);
110
122
  if (refuse && cmd !== 'set' && cmd !== 'unset') usage('--refuse-lowering applies to set and unset only');
111
123
  if (host !== undefined && cmd !== 'show') usage('--host applies to show only');
112
- return { cmd, pos, dir, refuse, host };
124
+ if (global && !['set', 'unset', 'init'].includes(cmd)) usage('--global applies to set, unset and init');
125
+ return { cmd, pos, dir, refuse, host, global };
113
126
  }
114
127
 
115
128
  function projectRoot(dir) {
@@ -126,7 +139,8 @@ function projectRoot(dir) {
126
139
 
127
140
  const lstatOrNull = (p) => { try { return fs.lstatSync(p); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } };
128
141
 
129
- // -> {somi, file, dirExists, fileExists}; refuses a .somi that is not a real directory.
142
+ // -> {somi, file, dirExists, fileExists}; refuses a .somi that is not a real directory. Writes only:
143
+ // show and get read through links.
130
144
  function locate(root) {
131
145
  const somi = path.join(root, '.somi');
132
146
  const file = path.join(somi, 'config.json');
@@ -171,12 +185,33 @@ function roundTripHazard(text) {
171
185
  return null;
172
186
  }
173
187
 
188
+ // The global file to write: its real path when it exists (a link is followed to it), and the stat of
189
+ // the directory it sits in, which writeAtomic re-checks. Parent directories are created when missing.
190
+ function locateGlobal() {
191
+ const g = globalConfigPath();
192
+ if (g === null) usage('there is no global config file: SOMI_GLOBAL_CONFIG is set to an empty value');
193
+ let file = g;
194
+ try { file = fs.realpathSync(g); } catch (e) { if (e.code !== 'ENOENT') project('the global config cannot be resolved'); }
195
+ const somi = path.dirname(file);
196
+ const fileExists = fs.existsSync(file);
197
+ return { somi, file, dirExists: fs.existsSync(somi), fileExists, global: true, shown: g };
198
+ }
199
+
200
+ // The merged config and both files, for reading; any problem with either file is 67.
201
+ function loadAll(root) {
202
+ try { return loadConfig(root); } catch (e) {
203
+ if (e instanceof ConfigFileError) return project(e.message);
204
+ throw e;
205
+ }
206
+ }
207
+
174
208
  // -> the parsed config object ({} when absent), with its whole cost block validated. With
175
- // `forWrite`, also refuses a file a rewrite could not reproduce faithfully.
209
+ // `forWrite`, also refuses a file a rewrite could not reproduce faithfully. A project file is read
210
+ // without following a link (it is about to be replaced); the global file through one.
176
211
  function load(root, loc, forWrite = false) {
177
212
  if (!loc.fileExists) return {};
178
213
  let text; let cfg;
179
- try { text = readTextFile(loc.file); } catch (e) { project(String(e.message).replace(/^cost-ceiling: /, '')); }
214
+ try { text = loc.global ? readConfigText(loc.file) : readTextFile(loc.file); } catch (e) { project(String(e.message).replace(/^cost-ceiling: /, '')); }
180
215
  try { cfg = JSON.parse(text); } catch { project('config.json is not valid JSON'); }
181
216
  if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) project('config.json is not a JSON object');
182
217
  if (cfg.ceiling !== undefined) project('"ceiling" at the top level of config.json belongs under "cost.ceiling"');
@@ -227,14 +262,19 @@ function warningsFor(cost, force, extra = []) {
227
262
  return w;
228
263
  }
229
264
 
230
- function show(root, loc, cfg, host) {
265
+ // Which file a merged cost value came from: the project file when it sets it, else the global one.
266
+ const fromFile = (files, get) => (get(files.project.config) !== undefined ? 'project' : 'global');
267
+
268
+ function show(root, files, host) {
269
+ const cfg = files.config;
231
270
  const cost = cfg.cost ?? {};
232
271
  const force = ceilingInForce(root, cost);
233
272
  const names = Object.keys(AGENT_DEFAULT_TIERS).sort();
234
273
  const extras = Object.keys(cost.agents ?? {}).filter((n) => !(n in AGENT_DEFAULT_TIERS)).sort();
235
274
  const agent = (name, unknown) => {
236
275
  const e = effective(name, cost, force.value);
237
- return { name, tier: e.tier, source: e.source, default: unknown ? null : AGENT_DEFAULT_TIERS[name], ...(unknown ? { unknown: true } : {}) };
276
+ const from = e.source === 'override' ? { from: fromFile(files, (c) => c.cost?.agents?.[name]) } : {};
277
+ return { name, tier: e.tier, source: e.source, ...from, default: unknown ? null : AGENT_DEFAULT_TIERS[name], ...(unknown ? { unknown: true } : {}) };
238
278
  };
239
279
  const agents = [...names.map((n) => agent(n, false)), ...extras.map((n) => agent(n, true))];
240
280
  const extra = [];
@@ -243,8 +283,9 @@ function show(root, loc, cfg, host) {
243
283
  if (host !== undefined && !mapped && highs > 0) extra.push(unmappedWarning(host, highs));
244
284
  return {
245
285
  path: path.join('.somi', 'config.json'),
246
- exists: loc.fileExists,
247
- ceiling: cost.ceiling === undefined ? { value: DEFAULT_CEILING, source: 'default' } : { value: cost.ceiling, source: 'config' },
286
+ exists: files.project.present,
287
+ global: { path: files.global.path, exists: files.global.present },
288
+ ceiling: cost.ceiling === undefined ? { value: DEFAULT_CEILING, source: 'default' } : { value: cost.ceiling, source: 'config', from: fromFile(files, (c) => c.cost?.ceiling) },
248
289
  effective_ceiling: force,
249
290
  agents,
250
291
  warnings: warningsFor(cost, force, extra),
@@ -255,6 +296,11 @@ function show(root, loc, cfg, host) {
255
296
  const edit = (fn) => { try { return fn(); } catch (e) { if (e instanceof EditError) return usage(e.message); throw e; } };
256
297
 
257
298
  function ensureSomi(loc) {
299
+ if (loc.global) {
300
+ try { fs.mkdirSync(loc.somi, { recursive: true, mode: 0o700 }); loc.dirStat = fs.statSync(loc.somi); } catch { project('the global config directory could not be created'); }
301
+ if (!loc.dirStat.isDirectory()) project('the global config directory is not a directory');
302
+ return;
303
+ }
258
304
  if (!loc.dirExists) {
259
305
  try { fs.mkdirSync(loc.somi, { mode: 0o700 }); } catch (e) {
260
306
  if (e.code !== 'EEXIST' || !lstatOrNull(loc.somi)?.isDirectory()) project('.somi could not be created');
@@ -278,8 +324,8 @@ function writeAtomic(loc, text, { noClobber = false, mode } = {}) {
278
324
  if (mode !== undefined) fs.fchmodSync(fd, mode);
279
325
  fs.fsyncSync(fd);
280
326
  fs.closeSync(fd); fd = undefined;
281
- const now = lstatOrNull(loc.somi);
282
- if (!now || !now.isDirectory() || now.dev !== loc.dirStat.dev || now.ino !== loc.dirStat.ino) project('.somi changed while writing; nothing was replaced');
327
+ const now = loc.global ? fs.statSync(loc.somi, { throwIfNoEntry: false }) : lstatOrNull(loc.somi);
328
+ if (!now || !now.isDirectory() || now.dev !== loc.dirStat.dev || now.ino !== loc.dirStat.ino) project(`${loc.global ? 'the global config directory' : '.somi'} changed while writing; nothing was replaced`);
283
329
  if (noClobber) fs.linkSync(tmp, loc.file); else fs.renameSync(tmp, loc.file);
284
330
  return true;
285
331
  } catch (e) {
@@ -293,60 +339,77 @@ function writeAtomic(loc, text, { noClobber = false, mode } = {}) {
293
339
  }
294
340
 
295
341
  function main() {
296
- const { cmd, pos, dir, refuse, host } = parseArgs(process.argv.slice(2));
342
+ const { cmd, pos, dir, refuse, host, global } = parseArgs(process.argv.slice(2));
297
343
  const root = projectRoot(dir);
298
- const loc = locate(root);
299
- const rel = path.join('.somi', 'config.json');
344
+ const writes = cmd === 'set' || cmd === 'unset' || cmd === 'init';
345
+ // Only a write inspects the target's links; show and get read through them.
346
+ const loc = !writes ? null : (global ? locateGlobal() : locate(root));
347
+ const rel = global ? loc.shown : path.join('.somi', 'config.json');
300
348
 
301
349
  if (cmd === 'init') {
302
350
  if (loc.fileExists) return { path: rel, created: false };
351
+ const g = global ? null : globalConfigPath();
352
+ if (g !== null && fs.lstatSync(g, { throwIfNoEntry: false })) return { path: rel, created: false, reason: 'a global config exists and holds the defaults' };
303
353
  ensureSomi(loc);
304
354
  return { path: rel, created: writeAtomic(loc, serializeDefaultConfig(), { noClobber: true }) };
305
355
  }
306
356
 
357
+ const files = loadAll(root);
307
358
  const k = cmd === 'show' ? null : edit(() => parseKey(pos[0]));
308
359
  if (cmd === 'unset' && !(k.kind === 'agent' || (k.kind === 'mapping' && k.tier === undefined))) usage('only cost.agents.<name> and cost.mapping.<host> can be unset');
309
- const cfg = load(root, loc, cmd === 'set' || cmd === 'unset');
310
- if (cmd === 'show') return show(root, loc, cfg, host);
360
+ if (files.config.ceiling !== undefined) project('"ceiling" at the top level of config.json belongs under "cost.ceiling"');
361
+ checkCost(files.config.cost, project);
362
+ if (cmd === 'show') return show(root, files, host);
311
363
 
312
364
  if (cmd === 'get') {
313
- const force = ceilingInForce(root, cfg.cost);
314
- if (k.kind === 'ceiling') return { key: pos[0], value: cfg.cost?.ceiling ?? DEFAULT_CEILING, source: cfg.cost?.ceiling === undefined ? 'default' : 'config', effective_ceiling: force };
365
+ const merged = files.config.cost;
366
+ const force = ceilingInForce(root, merged);
367
+ if (k.kind === 'ceiling') return { key: pos[0], value: merged?.ceiling ?? DEFAULT_CEILING, source: merged?.ceiling === undefined ? 'default' : 'config', effective_ceiling: force };
315
368
  if (k.kind === 'mapping') {
316
- const hostMap = cfg.cost?.mapping?.[k.host];
369
+ const hostMap = merged?.mapping?.[k.host];
317
370
  const value = hostMap === undefined ? null : (k.tier === undefined ? hostMap : (hostMap[k.tier] ?? null));
318
371
  return { key: pos[0], value, source: value === null ? 'none' : 'config' };
319
372
  }
320
- const has = cfg.cost?.agents && Object.hasOwn(cfg.cost.agents, k.name);
321
- return { key: pos[0], value: has ? cfg.cost.agents[k.name] : null, source: has ? 'override' : 'none' };
373
+ const has = merged?.agents && Object.hasOwn(merged.agents, k.name);
374
+ return { key: pos[0], value: has ? merged.agents[k.name] : null, source: has ? 'override' : 'none' };
322
375
  }
323
376
 
324
- // set/unset. A set on an absent file starts from the default file, so the default pins exist.
377
+ // set/unset edit one file. A set on an absent file starts from the default file, so the default
378
+ // pins exist -- except a project file over a global config, which starts empty: the global file
379
+ // holds the defaults, and copies of them in the project would mask later global changes.
380
+ const cfg = load(root, loc, true);
325
381
  const absent = !loc.fileExists;
326
- const beforeCfg = { cost: JSON.parse(JSON.stringify(cfg.cost ?? null)) };
327
- const { next, changed } = edit(() => applyEdit(absent ? null : cfg, { action: cmd, key: pos[0], value: pos[1] }));
328
- if (!changed) return { path: rel, key: pos[0], changed: false, warnings: warningsFor(cfg.cost, ceilingInForce(root, cfg.cost)) };
382
+ const start = absent && !global && files.global.present ? {} : (absent ? null : cfg);
383
+ // What the resolver sees, before and after: a project edit is judged merged over the global file;
384
+ // a global edit on its own, since it applies to projects whose files differ.
385
+ const view = (c) => (global ? c : mergeConfig(files.global.config, c ?? {}));
386
+ const beforeCfg = view(absent ? {} : cfg);
387
+ const { next, changed } = edit(() => applyEdit(start, { action: cmd, key: pos[0], value: pos[1] }));
388
+ if (!changed) {
389
+ // Nothing to unset in the project, but the same unset would change the global file: say where it lives.
390
+ const inGlobalOnly = !global && cmd === 'unset' && edit(() => applyEdit(files.global.config, { action: cmd, key: pos[0] })).changed;
391
+ return { path: rel, key: pos[0], changed: false, warnings: warningsFor(beforeCfg.cost, ceilingInForce(root, beforeCfg.cost), inGlobalOnly ? [GLOBAL_ONLY_WARNING] : []) };
392
+ }
329
393
  checkCost(next.cost, (m) => usage(m)); // the whole resulting block; a failure here is the caller's input
394
+ const after = view(next);
330
395
  if (refuse) {
331
- const v = lowers(beforeCfg, next, root);
396
+ const v = lowers(beforeCfg, after, root);
332
397
  if (v.lowers) usage(v.reasons.every((r) => r === REASONS.mapping) ? MAPPING_MESSAGE : LOWERING_MESSAGE);
333
398
  }
334
399
  const value = cmd !== 'set' ? undefined : (k.kind === 'mapping' ? next.cost.mapping[k.host][k.tier] : pos[1]);
335
400
  const extra = k.kind === 'agent' && cmd === 'set' && !(k.name in AGENT_DEFAULT_TIERS) && k.name !== 'somi' ? [UNKNOWN_WARNING] : [];
336
- if (changed) {
337
- let text;
338
- try {
339
- text = `${JSON.stringify(next, null, 2)}\n`;
340
- if (JSON.stringify(JSON.parse(text)) !== JSON.stringify(next)) project('config.json could not be rewritten faithfully; nothing was written');
341
- } catch (e) {
342
- if (e instanceof ExitSignal) throw e;
343
- project('config.json is too deeply nested to rewrite');
344
- }
345
- if (Buffer.byteLength(text) > MAX_CONFIG_BYTES) project('the edited config.json would exceed the size limit; nothing was written');
346
- ensureSomi(loc);
347
- writeAtomic(loc, text, { mode: loc.fileExists ? (fs.lstatSync(loc.file).mode & 0o777) : undefined });
401
+ let text;
402
+ try {
403
+ text = `${JSON.stringify(next, null, 2)}\n`;
404
+ if (JSON.stringify(JSON.parse(text)) !== JSON.stringify(next)) project('config.json could not be rewritten faithfully; nothing was written');
405
+ } catch (e) {
406
+ if (e instanceof ExitSignal) throw e;
407
+ project('config.json is too deeply nested to rewrite');
348
408
  }
349
- return { path: rel, key: pos[0], ...(cmd === 'set' ? { value } : {}), changed, effective_ceiling: ceilingInForce(root, next.cost), warnings: warningsFor(next.cost, ceilingInForce(root, next.cost), extra) };
409
+ if (Buffer.byteLength(text) > MAX_CONFIG_BYTES) project('the edited config.json would exceed the size limit; nothing was written');
410
+ ensureSomi(loc);
411
+ writeAtomic(loc, text, { mode: loc.fileExists ? (fs.statSync(loc.file).mode & 0o777) : undefined });
412
+ return { path: rel, key: pos[0], ...(cmd === 'set' ? { value } : {}), changed, effective_ceiling: ceilingInForce(root, after.cost), warnings: warningsFor(after.cost, ceilingInForce(root, after.cost), extra) };
350
413
  }
351
414
 
352
415
  try {
@@ -55,6 +55,7 @@ import { REVIEW_SCOPES, reviewMinFor, reviewScope, snapshotTree } from './lib/lo
55
55
  import { computeDiff } from './lib/loop-diff.mjs';
56
56
  import { dispatchEntry } from './lib/loop-dispatch.mjs';
57
57
  import { checkRun, startRun } from './lib/run-budget.mjs';
58
+ import { loadConfig } from './lib/config-files.mjs';
58
59
 
59
60
  const PROG = 'somi-loop';
60
61
 
@@ -92,11 +93,11 @@ function projectRoot() {
92
93
  return b;
93
94
  }
94
95
 
96
+ // The effective config (global, with the project's .somi/config.json over it); an unreadable or
97
+ // invalid file reads as unconfigured, so the documented defaults apply.
95
98
  function readConfig(root) {
96
- const cfgPath = path.join(root, '.somi', 'config.json');
97
- if (!fs.existsSync(cfgPath)) return {};
98
99
  try {
99
- return JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
100
+ return loadConfig(root).config;
100
101
  } catch {
101
102
  return {};
102
103
  }
@@ -197,7 +197,7 @@ const TOOLS = [
197
197
  {
198
198
  name: 'somi_config',
199
199
  description:
200
- 'Show or change the cost settings in the project\'s .somi/config.json by running ' +
200
+ 'Show the cost settings (the user\'s global config with the project\'s .somi/config.json merged over it) or change the project file, by running ' +
201
201
  '`node scripts/somi-config.mjs`, and return its one JSON line unchanged. Actions: show ' +
202
202
  '(every agent\'s effective tier and warnings), get, set, unset, init (create the default file ' +
203
203
  'when absent). cost.ceiling and cost.agents.<name> take low|medium|high; ' +
@@ -7,6 +7,10 @@
7
7
  # stub so the hashira-ops CI coverage-report action has a file to parse (no unit test suite).
8
8
  set -euo pipefail
9
9
 
10
+ # Hermetic: no suite may read the developer's own global SoMi config (scripts/lib/config-files.mjs).
11
+ # An empty value means "no global config"; suites that test the global file set their own.
12
+ export SOMI_GLOBAL_CONFIG=""
13
+
10
14
  # JSON validity via Node's own parser (no jq). Fails loudly on the first invalid file.
11
15
  json_valid() { node -e 'JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))' "$1"; }
12
16
 
@@ -73,6 +77,9 @@ bash tests/scripts/cost-model.sh
73
77
  echo "==> Cost ceiling tests..."
74
78
  bash tests/scripts/cost-ceiling.sh
75
79
 
80
+ echo "==> Global config, merge and reads through links..."
81
+ bash tests/scripts/global-config.sh
82
+
76
83
  echo "==> Dispatch resolver tests..."
77
84
  bash tests/scripts/somi-dispatch.sh
78
85
  bash tests/scripts/size-tier.sh
@@ -577,6 +584,19 @@ if ! node scripts/check-links.mjs; then
577
584
  exit 1
578
585
  fi
579
586
 
587
+ echo "==> Validating the overview page's roadmap covers every release..."
588
+ # site/src/content/roadmap.json must account for every CHANGELOG release, so a release cannot be
589
+ # dispatched (publish.yml's version job runs this script) with the page still describing the one
590
+ # before. site/ is not in the npm package, hence the skip.
591
+ if [ -d site ]; then
592
+ if ! node tests/scripts/lib/site-roadmap-gate.mjs; then
593
+ exit 1
594
+ fi
595
+ else
596
+ echo " (skipped: site/ not packaged)"
597
+ fi
598
+ bash tests/scripts/site-roadmap-gate.sh
599
+
580
600
  echo "==> Validating no session-artefact references in shipped code and prose..."
581
601
  # Comments in hooks/ and scripts/, and every line of agents/, commands/, skills/, must not point at
582
602
  # the gitignored .somi/ planning folder (finding ids, decision tags, iteration/phase numbers) --
@@ -27,7 +27,7 @@ verdict() {
27
27
 
28
28
  mutant() { # $1 = name, $2 = sed expression deleting one check; builds $TMP/$1 from the real lib
29
29
  mkdir -p "$TMP/$1"
30
- cp "$LIB_SRC/cost-ceiling.mjs" "$LIB_SRC/cost-model.mjs" "$LIB_SRC/cost-config.mjs" "$TMP/$1/"
30
+ cp "$LIB_SRC/cost-ceiling.mjs" "$LIB_SRC/cost-model.mjs" "$LIB_SRC/cost-config.mjs" "$LIB_SRC/config-files.mjs" "$TMP/$1/"
31
31
  sed -i "$2" "$TMP/$1/cost-config.mjs"
32
32
  cmp -s "$LIB_SRC/cost-config.mjs" "$TMP/$1/cost-config.mjs" && { bad "mutant $1 did not change the file"; return 1; }
33
33
  return 0
@@ -88,7 +88,7 @@ eq() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1 (want '$3', got '$2')"; fi
88
88
 
89
89
  # Red proofs: each mutant breaks exactly one rule in a COPY of the lib; the real case must then fail.
90
90
  mutant_sel() { # $1 = name, $2 = replacement for the selection expression
91
- mkdir -p "$TMP/$1"; cp "$LIB_SRC/cost-ceiling.mjs" "$LIB_SRC/cost-model.mjs" "$LIB_SRC/cost-config.mjs" "$TMP/$1/"
91
+ mkdir -p "$TMP/$1"; cp "$LIB_SRC/cost-ceiling.mjs" "$LIB_SRC/cost-model.mjs" "$LIB_SRC/cost-config.mjs" "$LIB_SRC/config-files.mjs" "$TMP/$1/"
92
92
  sed -i "s/const selected = override === undefined ? ceiling : override;/const selected = $2;/" "$TMP/$1/cost-ceiling.mjs"
93
93
  cmp -s "$LIB_SRC/cost-ceiling.mjs" "$TMP/$1/cost-ceiling.mjs" && bad "mutant $1 did not change the file"
94
94
  }
@@ -174,15 +174,15 @@ P="$(proj)"; big 60000 > "$P/.somi/config.json"; rc=0
174
174
  cli "$P" --agent somi-coder >/dev/null 2>&1 || rc=$?
175
175
  eq "a config.json under the cap (60000 bytes) is still read" "$rc" "0"
176
176
  # Red proof: raise the cap in a copy and the oversize file is accepted.
177
- mkdir -p "$TMP/nocap"; cp "$LIB_SRC"/cost-*.mjs "$TMP/nocap/"
178
- sed -i 's/64 \* 1024/64 * 1024 * 1024/' "$TMP/nocap/cost-ceiling.mjs"
177
+ mkdir -p "$TMP/nocap"; cp "$LIB_SRC"/cost-*.mjs "$LIB_SRC/config-files.mjs" "$TMP/nocap/"
178
+ sed -i 's/64 \* 1024/64 * 1024 * 1024/' "$TMP/nocap/config-files.mjs"
179
179
  P="$(proj)"; big 70000 > "$P/.somi/config.json"
180
180
  eq "red proof (size cap): without the cap the 70000-byte file is read" \
181
181
  "$(node --input-type=module -e "
182
182
  const C = await import('$TMP/nocap/cost-ceiling.mjs');
183
183
  try { C.readCostConfig('$P'); console.log('ok'); } catch (e) { console.log('reject'); }")" "ok"
184
184
 
185
- # ---- the read is fd-based: boundary sizes, symlinks refused, non-regular files refused ----------
185
+ # ---- the read is fd-based: boundary sizes, links followed, non-regular files refused ------------
186
186
  exact() { local pre='{"cost":{"ceiling":"low"},"pad":"' suf='"}'; printf '%s' "$pre"; head -c "$(( $1 - ${#pre} - ${#suf} ))" /dev/zero | tr '\0' 'x'; printf '%s' "$suf"; }
187
187
  P="$(proj)"; exact 65536 > "$P/.somi/config.json"; rc=0
188
188
  cli "$P" --agent somi-coder >/dev/null 2>&1 || rc=$?
@@ -191,13 +191,21 @@ P="$(proj)"; exact 65537 > "$P/.somi/config.json"; rc=0
191
191
  cli "$P" --agent somi-coder >/dev/null 2>&1 || rc=$?
192
192
  eq "a config.json of 65537 bytes is rejected with 67" "$rc" "67"
193
193
 
194
+ # Config reads follow links (a junction or symlinked .somi, a linked config file); what a link could
195
+ # abuse -- a device or FIFO that never ends, an endless read -- is refused on the open descriptor.
194
196
  P="$(proj)"; ln -s /dev/zero "$P/.somi/config.json"; rc=0
195
197
  timeout 10 env CLAUDE_PROJECT_DIR="$P" env -u SOMI_COST_CEILING node "$CLI" resolve --agent somi-coder >"$TMP/sym.out" 2>"$TMP/sym.err" || rc=$?
196
198
  eq "a config.json symlink to /dev/zero is rejected quickly with 67 (no timeout)" "$rc" "67"
197
- eq "... and the message says it refuses a symlink" "$(grep -c 'symlink' "$TMP/sym.err")" "1"
199
+ eq "... and the message says it is not a regular file" "$(grep -c 'not a regular file' "$TMP/sym.err")" "1"
200
+ P="$(proj)"; rm -f "$P/.somi/config.json"; mkfifo "$P/.somi/config.json"; rc=0
201
+ timeout 10 env CLAUDE_PROJECT_DIR="$P" env -u SOMI_COST_CEILING node "$CLI" resolve --agent somi-coder >/dev/null 2>"$TMP/fifo.err" || rc=$?
202
+ eq "a config.json that is a FIFO is rejected quickly with 67 (the open does not block)" "$rc" "67"
198
203
  P="$(proj '{"cost":{"ceiling":"low"}}')"; mv "$P/.somi/config.json" "$P/real.json"; ln -s ../real.json "$P/.somi/config.json"; rc=0
199
- cli "$P" --agent somi-coder >/dev/null 2>&1 || rc=$?
200
- eq "a symlink to an ordinary valid config is refused too" "$rc" "67"
204
+ out="$(cli "$P" --agent somi-coder 2>/dev/null)" || rc=$?
205
+ eq "a symlink to an ordinary valid config is read" "$rc|$(printf '%s' "$out" | grep -o '"tier":"[a-z]*"')" '0|"tier":"low"'
206
+ P="$(mktemp -d -p "$TMP")"; SHARED="$(mktemp -d -p "$TMP")"; printf '{"cost":{"ceiling":"low"}}' > "$SHARED/config.json"; ln -s "$SHARED" "$P/.somi"; rc=0
207
+ out="$(cli "$P" --agent somi-coder 2>/dev/null)" || rc=$?
208
+ eq "a .somi that is a link to another directory (a junction on Windows) is read through" "$rc|$(printf '%s' "$out" | grep -o '"tier":"[a-z]*"')" '0|"tier":"low"'
201
209
  P="$(proj)"; mkdir "$P/.somi/config.json"; rc=0
202
210
  cli "$P" --agent somi-coder >"$TMP/dir.out" 2>"$TMP/dir.err" || rc=$?
203
211
  eq "a config.json that is a directory is rejected with 67" "$rc" "67"
@@ -207,14 +215,15 @@ verdict_file() { # $1 = lib dir, $2 = project root -> ok | reject: msg
207
215
  const C = await import('$1/cost-ceiling.mjs');
208
216
  try { C.readCostConfig('$2'); console.log('ok'); } catch (e) { console.log('reject: ' + e.message); }"
209
217
  }
210
- mkdir -p "$TMP/nofollow" "$TMP/nofile"
211
- cp "$LIB_SRC"/cost-*.mjs "$TMP/nofollow/"; cp "$LIB_SRC"/cost-*.mjs "$TMP/nofile/"
212
- sed -i 's/(fs.constants.O_NOFOLLOW ?? 0)/0/' "$TMP/nofollow/cost-ceiling.mjs"
213
- sed -i 's/!fs.fstatSync(fd).isFile()/false/' "$TMP/nofile/cost-ceiling.mjs"
214
- cmp -s "$LIB_SRC/cost-ceiling.mjs" "$TMP/nofollow/cost-ceiling.mjs" && bad "mutant nofollow did not change the file"
215
- cmp -s "$LIB_SRC/cost-ceiling.mjs" "$TMP/nofile/cost-ceiling.mjs" && bad "mutant nofile did not change the file"
216
- P="$(proj '{"cost":{"ceiling":"low"}}')"; mv "$P/.somi/config.json" "$P/real.json"; ln -s ../real.json "$P/.somi/config.json"
217
- eq "red proof (O_NOFOLLOW): without it the symlinked config is followed and accepted" "$(verdict_file "$TMP/nofollow" "$P")" "ok"
218
+ mkdir -p "$TMP/nofile" "$TMP/blocking"
219
+ cp "$LIB_SRC"/cost-*.mjs "$LIB_SRC/config-files.mjs" "$TMP/nofile/"; cp "$LIB_SRC"/cost-*.mjs "$LIB_SRC/config-files.mjs" "$TMP/blocking/"
220
+ sed -i 's/!fs.fstatSync(fd).isFile()/false/' "$TMP/nofile/config-files.mjs"
221
+ sed -i 's/fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0)/fs.constants.O_RDONLY/' "$TMP/blocking/config-files.mjs"
222
+ cmp -s "$LIB_SRC/config-files.mjs" "$TMP/nofile/config-files.mjs" && bad "mutant nofile did not change the file"
223
+ cmp -s "$LIB_SRC/config-files.mjs" "$TMP/blocking/config-files.mjs" && bad "mutant blocking did not change the file"
224
+ P="$(proj)"; rm -f "$P/.somi/config.json"; mkfifo "$P/.somi/config.json"; rc=0
225
+ timeout 5 node --input-type=module -e "const C = await import('$TMP/blocking/cost-ceiling.mjs'); try { C.readCostConfig('$P'); } catch {}" >/dev/null 2>&1 || rc=$?
226
+ eq "red proof (O_NONBLOCK): without it a FIFO config hangs the read (timeout)" "$rc" "124"
218
227
  P="$(proj)"; mkdir "$P/.somi/config.json"
219
228
  case "$(verdict_file "$LIB_SRC" "$P")" in *"not a regular file"*) ok "a directory config is rejected by the regular-file check" ;; *) bad "a directory config is rejected by the regular-file check" ;; esac
220
229
  case "$(verdict_file "$TMP/nofile" "$P")" in *"not a regular file"*) bad "red proof (isFile): the regular-file message persists without the check" ;; *) ok "red proof (isFile): without the check the regular-file rejection is gone" ;; esac
@@ -239,7 +248,7 @@ pj() { # $1 = config body or '', $2 = state body or ''
239
248
  echo "$r"
240
249
  }
241
250
  mut_prec() { # $1 = name, $2 = sed expression
242
- mkdir -p "$TMP/$1"; cp "$LIB_SRC"/cost-*.mjs "$TMP/$1/"; sed -i "$2" "$TMP/$1/cost-ceiling.mjs"
251
+ mkdir -p "$TMP/$1"; cp "$LIB_SRC"/cost-*.mjs "$LIB_SRC/config-files.mjs" "$TMP/$1/"; sed -i "$2" "$TMP/$1/cost-ceiling.mjs"
243
252
  cmp -s "$LIB_SRC/cost-ceiling.mjs" "$TMP/$1/cost-ceiling.mjs" && bad "mutant $1 did not change the file"
244
253
  }
245
254
  mut_prec config-ignored 's/^ if (isConfigured) {$/ if (false) {/'