@skathio/somi 3.1.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/.claude/settings.json +13 -0
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.copilot-extension/extension.json +1 -1
  5. package/.copilot-extension/marketplace.json +2 -2
  6. package/README.md +28 -23
  7. package/VERSION +1 -1
  8. package/agents/{architecture-reviewer.md → somi-architecture-reviewer.md} +10 -11
  9. package/agents/{atlas.md → somi-atlas.md} +3 -5
  10. package/agents/{coder.md → somi-coder.md} +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 +131 -0
  48. package/commands/test-strategy.md +3 -4
  49. package/commands/upgrade.md +4 -5
  50. package/examples/code-review-example.md +1 -1
  51. package/examples/discovery-example.md +1 -1
  52. package/examples/feature-plan-example.md +2 -2
  53. package/hooks/hooks.json +14 -1
  54. package/hooks/lib/common.mjs +64 -1
  55. package/hooks/post-tool/audit-log.mjs +3 -2
  56. package/hooks/pre-tool/block-secret-writes.mjs +12 -11
  57. package/hooks/pre-tool/guard-cost-lowering.mjs +177 -0
  58. package/hooks/pre-tool/guard-protected-paths.mjs +13 -3
  59. package/hooks/session-start/detect-repo-instructions.mjs +27 -2
  60. package/hooks/session-start/ensure-default-config.mjs +121 -0
  61. package/package.json +1 -1
  62. package/rules/00-priorities.md +1 -1
  63. package/rules/30-security-owasp.md +1 -1
  64. package/rules/50-collaboration.md +9 -6
  65. package/rules/CLAUDE.md +11 -10
  66. package/scripts/lib/agent-info.mjs +85 -0
  67. package/scripts/lib/agent-registry.mjs +92 -0
  68. package/scripts/lib/cost-ceiling.mjs +175 -171
  69. package/scripts/lib/cost-config-edit.mjs +102 -0
  70. package/scripts/lib/cost-config.mjs +64 -0
  71. package/scripts/lib/cost-defaults.mjs +51 -0
  72. package/scripts/lib/cost-lowering.mjs +89 -0
  73. package/scripts/lib/cost-model.mjs +37 -22
  74. package/scripts/lib/dispatch-resolver.mjs +59 -50
  75. package/scripts/lib/loop-diff.mjs +96 -0
  76. package/scripts/lib/loop-dispatch.mjs +19 -0
  77. package/scripts/lib/loop-review.mjs +52 -0
  78. package/scripts/lib/run-budget.mjs +28 -0
  79. package/scripts/lib/size-tier.mjs +184 -0
  80. package/scripts/lib/tier-record.mjs +82 -0
  81. package/scripts/size-budget-overrides.json +7 -15
  82. package/scripts/somi-config.mjs +358 -0
  83. package/scripts/somi-dispatch.mjs +1 -1
  84. package/scripts/somi-loop.mjs +71 -96
  85. package/scripts/somi-mcp.mjs +135 -14
  86. package/scripts/somi-tier.mjs +393 -0
  87. package/scripts/validate.sh +37 -215
  88. package/skills/api-design/SKILL.md +1 -1
  89. package/skills/clean-code/SKILL.md +1 -1
  90. package/skills/market-research/SKILL.md +2 -2
  91. package/skills/owasp-defense/SKILL.md +2 -2
  92. package/skills/plan-review/SKILL.md +5 -1
  93. package/skills/reasoning-craft/SKILL.md +1 -1
  94. package/skills/requirements-engineering/SKILL.md +3 -3
  95. package/skills/solid-principles/SKILL.md +1 -1
  96. package/skills/somi-dispatch/SKILL.md +104 -109
  97. package/skills/somi-routing/SKILL.md +88 -1
  98. package/skills/testing-playbook/SKILL.md +2 -2
  99. package/skills/threat-modeling/SKILL.md +3 -3
  100. package/templates/BRIEF.md.tmpl +2 -2
  101. package/templates/DESIGN.md.tmpl +1 -1
  102. package/templates/DOD.md.tmpl +2 -2
  103. package/templates/PHASE.md.tmpl +2 -2
  104. package/templates/RCA.md.tmpl +1 -1
  105. package/templates/REVIEW.md.tmpl +3 -2
  106. package/templates/SDD.md.tmpl +1 -1
  107. package/templates/SPEC.md.tmpl +1 -1
  108. package/templates/TDD.md.tmpl +1 -1
  109. package/tests/hooks/cases/block-secret-writes.json +130 -17
  110. package/tests/hooks/cases/detect-repo-instructions.json +22 -1
  111. package/tests/hooks/cases/guard-protected-paths.json +175 -25
  112. package/tests/scripts/agent-model-frontmatter.sh +38 -0
  113. package/tests/scripts/agent-names.sh +77 -0
  114. package/tests/scripts/check-frontmatter.sh +1 -1
  115. package/tests/scripts/checkpoint-gate.sh +44 -3
  116. package/tests/scripts/convergence-runner.sh +10 -6
  117. package/tests/scripts/cost-ceiling.sh +127 -215
  118. package/tests/scripts/cost-defaults.sh +128 -0
  119. package/tests/scripts/cost-hardcap.sh +329 -0
  120. package/tests/scripts/cost-lowering.sh +261 -0
  121. package/tests/scripts/cost-model.sh +18 -14
  122. package/tests/scripts/dispatch-guard.sh +7 -7
  123. package/tests/scripts/dispatch-line-gate.sh +61 -0
  124. package/tests/scripts/dispatch-reference-gate.sh +13 -13
  125. package/tests/scripts/ensure-default-config.sh +162 -0
  126. package/tests/scripts/eval-runner.sh +9 -9
  127. package/tests/scripts/evals-packaging.sh +127 -20
  128. package/tests/scripts/fixtures/size-tier-cases.json +87 -0
  129. package/tests/scripts/goldens/loop-state-done.json +1 -1
  130. package/tests/scripts/goldens/somi-loop.json +3 -3
  131. package/tests/scripts/lib/agent-registry-tests.mjs +95 -0
  132. package/tests/scripts/lib/brief-only-guard.mjs +27 -0
  133. package/tests/scripts/lib/checkpoint-gate.mjs +40 -3
  134. package/tests/scripts/lib/dispatch-reference-gate.mjs +5 -5
  135. package/tests/scripts/lib/retirement-gate.mjs +7 -2
  136. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +52 -0
  137. package/tests/scripts/lib/size-tier-drift.mjs +74 -0
  138. package/tests/scripts/lib/somi-mcp-config-tests.mjs +92 -0
  139. package/tests/scripts/lib/somi-mcp-tests.mjs +66 -28
  140. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +64 -0
  141. package/tests/scripts/retirement-gate.sh +19 -0
  142. package/tests/scripts/review-panel-seats.sh +2 -2
  143. package/tests/scripts/run.sh +95 -0
  144. package/tests/scripts/size-tier.sh +562 -0
  145. package/tests/scripts/somi-agent-dispatch-contract.sh +20 -11
  146. package/tests/scripts/somi-config.sh +281 -0
  147. package/tests/scripts/somi-dispatch.sh +150 -98
  148. package/tests/scripts/somi-mcp.sh +2 -0
@@ -0,0 +1,358 @@
1
+ #!/usr/bin/env node
2
+ // somi-config.mjs — show and change the cost settings in a project's .somi/config.json.
3
+ //
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
7
+ // get cost.ceiling | cost.agents.<name>
8
+ // set cost.ceiling <low|medium|high> | set cost.agents.<name> <low|medium|high>
9
+ // set cost.mapping.<host>.<tier> <model-id[,model-id...]> (a preference list, first offered wins)
10
+ // unset cost.agents.<name> | unset cost.mapping.<host>
11
+ // init create the default file when absent (the exact text the SessionStart
12
+ // hook writes); a no-op if anything exists at the path
13
+ // [--project-dir DIR] default: CLAUDE_PROJECT_DIR, else the current directory
14
+ // [--host NAME] (show) the host this session runs on; adds a warning when that host has
15
+ // no model mapping while any agent resolves to high (#36)
16
+ // [--refuse-lowering] (set, unset) exit 64 and write nothing if the change would lower any
17
+ // agent's effective tier (see scripts/lib/cost-lowering.mjs)
18
+ //
19
+ // Only those keys can be changed. Any cost.mapping change counts as needing the user (cost-lowering.mjs),
20
+ // so --refuse-lowering refuses it: which model a tier means cannot be ranked here. The config is read on every dispatch, so a set or unset takes effect
21
+ // on the very next resolve. Everything else in the file is preserved as parsed.
22
+ //
23
+ // A set or unset rewrites the whole file, so it refuses (67, nothing written) any file whose content
24
+ // would not survive a round trip through JSON.parse/JSON.stringify: a duplicate key, an integer beyond
25
+ // the safe range, or a number outside the double range, anywhere in the file; text whose rewrite would
26
+ // exceed the 64 KiB limit the reader enforces; or nesting too deep to serialise. Other formatting
27
+ // (indentation, key spacing, float spelling such as 1.0) is normalised to 2-space JSON. The temp file is
28
+ // created in .somi and fsynced; .somi's identity is re-checked just before the rename. A same-user
29
+ // process that swaps .somi in that last instant, or edits config.json between our read and rename, is
30
+ // not defended against (the edit would be lost). A replaced file keeps the original's permission bits.
31
+ //
32
+ // With the ceiling, `show` and the output of `set` report what the resolver would use: the
33
+ // SOMI_COST_CEILING variable, else cost.ceiling, else a ceiling persisted by an earlier --ceiling or
34
+ // env call, else the built-in default (`effective_ceiling`), and warn when the variable or a
35
+ // persisted value is why it differs from the config.
36
+ //
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).
43
+ //
44
+ // Exit codes (callers branch on these — do not repurpose):
45
+ // 0 ok
46
+ // 64 usage: bad arguments, a key that may not be set, a bad tier or agent name
47
+ // 67 the project's files: .somi or config.json unreadable, oversize, a link, not valid JSON, or an
48
+ // invalid cost block (nothing is written); also a failed write
49
+ // Nothing is printed to stdout on an error path. Zero-dependency: stdlib only.
50
+
51
+ import fs from 'node:fs';
52
+ import path from 'node:path';
53
+ import { readTextFile, loadState, decideDispatch, DEFAULT_CEILING, MAX_CONFIG_BYTES } from './lib/cost-ceiling.mjs';
54
+ import { quote } from './lib/cost-config.mjs';
55
+ import { VALID_COSTS, HOST_MODELS } from './lib/cost-model.mjs';
56
+ import { AGENT_DEFAULT_TIERS, serializeDefaultConfig } from './lib/cost-defaults.mjs';
57
+ import { EditError, applyEdit, parseKey, validateCostBlock, missingMappingTiers } from './lib/cost-config-edit.mjs';
58
+ import { lowers, REASONS } from './lib/cost-lowering.mjs';
59
+
60
+ 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>)`;
62
+ const HOST_RE = /^[a-z][a-z0-9-]{0,31}$/;
63
+ const EXIT_USAGE = 64;
64
+ const EXIT_PROJECT = 67;
65
+
66
+ const SEC_WARNING = 'somi-security-reviewer runs below high; pin it with: set cost.agents.somi-security-reviewer high';
67
+ const ENV_WARNING = 'SOMI_COST_CEILING is set in this environment and outranks cost.ceiling in the config';
68
+ 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';
69
+ const UNKNOWN_WARNING = 'that agent name is not a shipped agent; the entry is accepted but may never be used';
70
+ 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
+ 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';
72
+ const LOWERING_MESSAGE = 'this change lowers a tier and needs the user: ask them to run node scripts/somi-config.mjs themselves or edit .somi/config.json';
73
+ const WRITE_FLAGS = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0);
74
+
75
+ class ExitSignal extends Error {
76
+ constructor(code) { super(`exit ${code}`); this.code = code; }
77
+ }
78
+ const asciiEscape = (s) => s.replace(/[\u0000-\u001f\u007f-￿]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
79
+ const ascii = (x) => asciiEscape(JSON.stringify(x));
80
+ function fail(code, msg, tail = '') {
81
+ process.stderr.write(`${PROG}: ${asciiEscape(msg)}${tail}\n`);
82
+ throw new ExitSignal(code);
83
+ }
84
+ const usage = (msg) => fail(EXIT_USAGE, msg, `\n${USAGE}`);
85
+ const project = (msg) => fail(EXIT_PROJECT, msg);
86
+
87
+ function parseArgs(argv) {
88
+ const [cmd, ...rest] = argv;
89
+ const pos = [];
90
+ let dir;
91
+ let refuse = false;
92
+ let host;
93
+ for (let i = 0; i < rest.length; i++) {
94
+ if (rest[i] === '--refuse-lowering') refuse = true;
95
+ else if (rest[i] === '--host') {
96
+ if (host !== undefined) usage('--host given twice');
97
+ host = rest[++i];
98
+ if (host === undefined || !HOST_RE.test(host)) usage(`--host must match ${HOST_RE}`);
99
+ }
100
+ else if (rest[i] === '--project-dir') {
101
+ if (dir !== undefined) usage('--project-dir given twice');
102
+ dir = rest[++i];
103
+ if (dir === undefined || dir === '') usage('--project-dir requires a non-empty value');
104
+ } else if (rest[i].startsWith('--')) usage(`unknown argument: ${quote(rest[i])}`);
105
+ else pos.push(rest[i]);
106
+ }
107
+ const want = { show: 0, get: 1, set: 2, unset: 1, init: 0 };
108
+ if (!Object.hasOwn(want, cmd ?? '')) usage(cmd ? `unknown command: ${quote(cmd)}` : 'a command is required');
109
+ if (pos.length !== want[cmd]) usage(`${cmd} takes ${want[cmd]} argument(s)`);
110
+ if (refuse && cmd !== 'set' && cmd !== 'unset') usage('--refuse-lowering applies to set and unset only');
111
+ if (host !== undefined && cmd !== 'show') usage('--host applies to show only');
112
+ return { cmd, pos, dir, refuse, host };
113
+ }
114
+
115
+ function projectRoot(dir) {
116
+ let base = dir ?? process.env.CLAUDE_PROJECT_DIR ?? '';
117
+ if (base === '' || base.includes('${')) base = dir ?? process.cwd();
118
+ try {
119
+ if (!fs.statSync(base).isDirectory()) usage('the project directory is not a directory');
120
+ } catch (e) {
121
+ if (e instanceof ExitSignal) throw e;
122
+ usage('the project directory cannot be read');
123
+ }
124
+ return path.resolve(base);
125
+ }
126
+
127
+ const lstatOrNull = (p) => { try { return fs.lstatSync(p); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } };
128
+
129
+ // -> {somi, file, dirExists, fileExists}; refuses a .somi that is not a real directory.
130
+ function locate(root) {
131
+ const somi = path.join(root, '.somi');
132
+ const file = path.join(somi, 'config.json');
133
+ let d; let f = null;
134
+ try { d = lstatOrNull(somi); if (d && !d.isDirectory()) project('.somi is a link or not a directory; refusing'); if (d) f = lstatOrNull(file); } catch (e) {
135
+ if (e instanceof ExitSignal) throw e;
136
+ project('.somi cannot be inspected');
137
+ }
138
+ return { somi, file, dirExists: d !== null, fileExists: f !== null, dirStat: d };
139
+ }
140
+
141
+ // Why a rewrite of `text` (already parsed OK) would change its meaning, or null: a duplicate key or a
142
+ // number JSON.stringify cannot reproduce. A small scanner; structure is already known to be valid.
143
+ function roundTripHazard(text) {
144
+ const stack = [];
145
+ const n = text.length;
146
+ for (let i = 0; i < n;) {
147
+ const c = text[i];
148
+ const top = stack[stack.length - 1];
149
+ if (c === '"') {
150
+ let j = i + 1;
151
+ while (j < n && text[j] !== '"') j += text[j] === '\\' ? 2 : 1;
152
+ if (top?.obj && top.expectKey) {
153
+ const key = JSON.parse(text.slice(i, j + 1));
154
+ if (top.keys.has(key)) return 'a duplicate key';
155
+ top.keys.add(key);
156
+ top.expectKey = false;
157
+ }
158
+ i = j + 1;
159
+ } else if (c === '{') { stack.push({ obj: true, keys: new Set(), expectKey: true }); i++; }
160
+ else if (c === '[') { stack.push({ obj: false }); i++; }
161
+ else if (c === '}' || c === ']') { stack.pop(); i++; }
162
+ else if (c === ',') { if (top?.obj) top.expectKey = true; i++; }
163
+ else if (c === '-' || (c >= '0' && c <= '9')) {
164
+ const tok = /^-?\d+(\.\d+)?([eE][+-]?\d+)?/.exec(text.slice(i, i + 400))[0];
165
+ const v = Number(tok);
166
+ if (!Number.isFinite(v)) return 'a number outside the double range';
167
+ if (/^-?\d+$/.test(tok) && !Number.isSafeInteger(v)) return 'an integer beyond the safe range';
168
+ i += tok.length;
169
+ } else i++;
170
+ }
171
+ return null;
172
+ }
173
+
174
+ // -> 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.
176
+ function load(root, loc, forWrite = false) {
177
+ if (!loc.fileExists) return {};
178
+ let text; let cfg;
179
+ try { text = readTextFile(loc.file); } catch (e) { project(String(e.message).replace(/^cost-ceiling: /, '')); }
180
+ try { cfg = JSON.parse(text); } catch { project('config.json is not valid JSON'); }
181
+ if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) project('config.json is not a JSON object');
182
+ if (cfg.ceiling !== undefined) project('"ceiling" at the top level of config.json belongs under "cost.ceiling"');
183
+ checkCost(cfg.cost, project);
184
+ if (forWrite) {
185
+ const why = roundTripHazard(text);
186
+ if (why) project(`config.json holds ${why}, which a rewrite would change; edit it by hand`);
187
+ }
188
+ return cfg;
189
+ }
190
+
191
+ function checkCost(cost, onFail) {
192
+ try { validateCostBlock(cost); } catch (e) { onFail(String(e.message).replace(/^cost-ceiling: /, '')); }
193
+ }
194
+
195
+ // What the resolver would use for the ceiling, without writing state: SOMI_COST_CEILING, else the
196
+ // config, else a ceiling an earlier flag/env call persisted, else the default.
197
+ function ceilingInForce(root, cost) {
198
+ const env = process.env.SOMI_COST_CEILING;
199
+ if (env !== undefined && env !== '') {
200
+ if (!VALID_COSTS.includes(env)) usage(`SOMI_COST_CEILING must be one of ${VALID_COSTS.join('|')}, got ${quote(env)}`);
201
+ return { value: env, source: 'env' };
202
+ }
203
+ if (cost?.ceiling !== undefined) return { value: cost.ceiling, source: 'config' };
204
+ let state;
205
+ try { state = loadState(root); } catch (e) { project(String(e.message).replace(/^cost-ceiling: /, '')); }
206
+ if (state && ['cli', 'env'].includes(state.ceiling_origin)) return { value: state.ceiling, source: 'state' };
207
+ return { value: DEFAULT_CEILING, source: 'default' };
208
+ }
209
+
210
+ // The resolver's rule, via the library: the agent's override if present, else the ceiling.
211
+ function effective(name, cost, ceiling) {
212
+ const override = cost?.agents && Object.hasOwn(cost.agents, name) ? cost.agents[name] : undefined;
213
+ const declared = AGENT_DEFAULT_TIERS[name] ?? override ?? ceiling;
214
+ const d = decideDispatch(declared, ceiling, override);
215
+ return { tier: d.selected, source: d.tier_source };
216
+ }
217
+
218
+ function warningsFor(cost, force, extra = []) {
219
+ const w = [...extra];
220
+ for (const host of Object.keys(cost?.mapping ?? {}).sort()) {
221
+ const missing = missingMappingTiers(cost, host);
222
+ if (missing.length) w.push(`cost.mapping.${host} has no ${missing.join(', ')} entry yet, so a dispatch at that tier on ${host} fails until it is set`);
223
+ }
224
+ if (force.source === 'env' && cost?.ceiling !== undefined && cost.ceiling !== force.value) w.push(ENV_WARNING);
225
+ if (force.source === 'state') w.push(STATE_WARNING);
226
+ if (effective('somi-security-reviewer', cost, force.value).tier !== 'high') w.push(SEC_WARNING);
227
+ return w;
228
+ }
229
+
230
+ function show(root, loc, cfg, host) {
231
+ const cost = cfg.cost ?? {};
232
+ const force = ceilingInForce(root, cost);
233
+ const names = Object.keys(AGENT_DEFAULT_TIERS).sort();
234
+ const extras = Object.keys(cost.agents ?? {}).filter((n) => !(n in AGENT_DEFAULT_TIERS)).sort();
235
+ const agent = (name, unknown) => {
236
+ 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 } : {}) };
238
+ };
239
+ const agents = [...names.map((n) => agent(n, false)), ...extras.map((n) => agent(n, true))];
240
+ const extra = [];
241
+ const mapped = host !== undefined && (Object.hasOwn(HOST_MODELS, host) || (cost.mapping && Object.hasOwn(cost.mapping, host)));
242
+ const highs = agents.filter((a) => a.tier === 'high').length;
243
+ if (host !== undefined && !mapped && highs > 0) extra.push(unmappedWarning(host, highs));
244
+ return {
245
+ 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' },
248
+ effective_ceiling: force,
249
+ agents,
250
+ warnings: warningsFor(cost, force, extra),
251
+ };
252
+ }
253
+
254
+ // Key and tier errors are the caller's (64).
255
+ const edit = (fn) => { try { return fn(); } catch (e) { if (e instanceof EditError) return usage(e.message); throw e; } };
256
+
257
+ function ensureSomi(loc) {
258
+ if (!loc.dirExists) {
259
+ try { fs.mkdirSync(loc.somi, { mode: 0o700 }); } catch (e) {
260
+ if (e.code !== 'EEXIST' || !lstatOrNull(loc.somi)?.isDirectory()) project('.somi could not be created');
261
+ }
262
+ }
263
+ loc.dirStat = lstatOrNull(loc.somi);
264
+ if (!loc.dirStat?.isDirectory()) project('.somi is a link or not a directory; refusing');
265
+ }
266
+
267
+ // Writes `text` to a fresh temp file beside config.json (exclusive, no-follow), fsyncs it, re-checks that
268
+ // .somi is still the directory we inspected, and renames it over; with `noClobber` it hard-links instead,
269
+ // which fails rather than replace a file that appeared meanwhile. `mode`, when given (replacing an
270
+ // existing file), is that file's permission bits; a new file gets 0644 minus the umask.
271
+ function writeAtomic(loc, text, { noClobber = false, mode } = {}) {
272
+ const tmp = path.join(loc.somi, `config.json.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);
273
+ let fd;
274
+ try {
275
+ fd = fs.openSync(tmp, WRITE_FLAGS, 0o644);
276
+ const buf = Buffer.from(text);
277
+ for (let off = 0; off < buf.length;) off += fs.writeSync(fd, buf, off, buf.length - off);
278
+ if (mode !== undefined) fs.fchmodSync(fd, mode);
279
+ fs.fsyncSync(fd);
280
+ 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');
283
+ if (noClobber) fs.linkSync(tmp, loc.file); else fs.renameSync(tmp, loc.file);
284
+ return true;
285
+ } catch (e) {
286
+ if (e instanceof ExitSignal) throw e;
287
+ if (noClobber && e.code === 'EEXIST') return false;
288
+ return project('config.json could not be written');
289
+ } finally {
290
+ if (fd !== undefined) try { fs.closeSync(fd); } catch { /* closed */ }
291
+ try { fs.rmSync(tmp, { force: true }); } catch { /* best effort */ }
292
+ }
293
+ }
294
+
295
+ function main() {
296
+ const { cmd, pos, dir, refuse, host } = parseArgs(process.argv.slice(2));
297
+ const root = projectRoot(dir);
298
+ const loc = locate(root);
299
+ const rel = path.join('.somi', 'config.json');
300
+
301
+ if (cmd === 'init') {
302
+ if (loc.fileExists) return { path: rel, created: false };
303
+ ensureSomi(loc);
304
+ return { path: rel, created: writeAtomic(loc, serializeDefaultConfig(), { noClobber: true }) };
305
+ }
306
+
307
+ const k = cmd === 'show' ? null : edit(() => parseKey(pos[0]));
308
+ 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);
311
+
312
+ 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 };
315
+ if (k.kind === 'mapping') {
316
+ const hostMap = cfg.cost?.mapping?.[k.host];
317
+ const value = hostMap === undefined ? null : (k.tier === undefined ? hostMap : (hostMap[k.tier] ?? null));
318
+ return { key: pos[0], value, source: value === null ? 'none' : 'config' };
319
+ }
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' };
322
+ }
323
+
324
+ // set/unset. A set on an absent file starts from the default file, so the default pins exist.
325
+ 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)) };
329
+ checkCost(next.cost, (m) => usage(m)); // the whole resulting block; a failure here is the caller's input
330
+ if (refuse) {
331
+ const v = lowers(beforeCfg, next, root);
332
+ if (v.lowers) usage(v.reasons.every((r) => r === REASONS.mapping) ? MAPPING_MESSAGE : LOWERING_MESSAGE);
333
+ }
334
+ const value = cmd !== 'set' ? undefined : (k.kind === 'mapping' ? next.cost.mapping[k.host][k.tier] : pos[1]);
335
+ 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 });
348
+ }
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) };
350
+ }
351
+
352
+ try {
353
+ const out = main();
354
+ process.stdout.write(`${ascii(out)}\n`);
355
+ } catch (e) {
356
+ if (e instanceof ExitSignal) process.exitCode = e.code;
357
+ else throw e;
358
+ }
@@ -25,7 +25,7 @@
25
25
  // 0 ok
26
26
  // 64 usage error
27
27
  // 65 unknown agent
28
- // 66 malformed declaration
28
+ // 66 no tier source (the exempt `somi` agent, or an agent file with no default-tier-table entry)
29
29
  // 67 project environment/config failure
30
30
  // A guessed model is never printed on any error path — only the success path emits JSON.
31
31
 
@@ -30,16 +30,31 @@
30
30
  // 2 max-passes-exceeded (`pass` would exceed the cap)
31
31
  // 3 diff-cap-exceeded (`check-diff`: weighted lines over the cap;
32
32
  // out-of-scope lines count double)
33
- // 64 usage / environment error
33
+ // 4 time-budget-exceeded (`pass`: the /ship-loop run started by `run-start` on this slug is out of time)
34
+ // 64 usage / environment error (65: record-dispatch's resolver refused the agent)
34
35
  //
35
- // Subcommands: init | resume | pass | check-diff | record-pass | finish | stats
36
- // (see scripts/somi-loop.sh for the full per-subcommand doc — unchanged here).
36
+ // Subcommands (each prints one JSON object):
37
+ // run-start record a /ship-loop run's start and optional --max-minutes budget (kept on resume)
38
+ // init new loop state: baseline SHA, resolved caps, review_min from the sizing record
39
+ // resume | stats the stored state
40
+ // pass next pass, or exit 2 (cap) / 4 (time budget); repeats review_min
41
+ // check-diff weighted cumulative diff against the baseline, or exit 3
42
+ // review-scope what the generalist reviewer reads this pass: delta (from/to trees, files) or full
43
+ // record-dispatch append the resolver's answer for --agent [--host] to the state
44
+ // record-pass append the verdict and counts, with the reviewed tree
45
+ // finish terminal status, cap overrides, dispatches
37
46
  //
38
47
  // Tested by tests/scripts/run.sh (wired into scripts/validate.sh / CI).
39
48
 
40
49
  import fs from 'node:fs';
41
50
  import path from 'node:path';
42
51
  import { execFileSync } from 'node:child_process';
52
+ import { fileURLToPath } from 'node:url';
53
+ import { verifyBriefOnly } from './lib/tier-record.mjs';
54
+ import { REVIEW_SCOPES, reviewMinFor, reviewScope, snapshotTree } from './lib/loop-review.mjs';
55
+ import { computeDiff } from './lib/loop-diff.mjs';
56
+ import { dispatchEntry } from './lib/loop-dispatch.mjs';
57
+ import { checkRun, startRun } from './lib/run-budget.mjs';
43
58
 
44
59
  const PROG = 'somi-loop';
45
60
 
@@ -113,96 +128,6 @@ function nowIso() {
113
128
  return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
114
129
  }
115
130
 
116
- // Untracked, non-ignored files as synthetic `--numstat` rows (all lines added).
117
- // `git diff` reads the index and the work tree, but a file git has never been
118
- // told about is in neither -- so a brand-new file counts ZERO until someone runs
119
- // `git add`. That made the cap under-measure by the entire size of every new
120
- // file an iteration introduced, silently, in the direction that lets work
121
- // through (measured 248 against a true 503 on one real iteration).
122
- // Enumerated separately and merged into the same stream rather than fixed with
123
- // `git add -N`, which would mutate the caller's index as a side effect of a
124
- // read-only query.
125
- function untrackedNumstat(root, pathspec) {
126
- let listed = '';
127
- try {
128
- listed = execFileSync(
129
- 'git',
130
- ['-C', root, 'ls-files', '--others', '--exclude-standard', '--', ...pathspec],
131
- { encoding: 'utf8' },
132
- );
133
- } catch (e) {
134
- listed = e.stdout ? e.stdout.toString() : '';
135
- }
136
- const rows = [];
137
- for (const file of listed.split('\n')) {
138
- if (file === '') continue;
139
- let buf;
140
- try {
141
- buf = fs.readFileSync(path.join(root, file));
142
- } catch {
143
- continue; // raced away between listing and reading
144
- }
145
- // git calls a blob binary on a NUL in the first 8000 bytes and reports `-`.
146
- if (buf.subarray(0, 8000).includes(0)) {
147
- rows.push(`-\t-\t${file}`);
148
- continue;
149
- }
150
- const text = buf.toString('utf8');
151
- const added = text === '' ? 0 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
152
- rows.push(`${added}\t0\t${file}`);
153
- }
154
- return rows.join('\n');
155
- }
156
-
157
- // Weighted cumulative diff vs baseline. Out-of-scope lines count double.
158
- // Covers tracked changes, staged changes, AND untracked files (see above) --
159
- // the whole working tree, which is what the cap is meant to bound.
160
- function computeDiff(root, baseline, iterationFiles) {
161
- const pathspec = ['.', ':(exclude).somi', ':(exclude).claude'];
162
- let output = '';
163
- try {
164
- output = execFileSync(
165
- 'git',
166
- ['-C', root, 'diff', '--numstat', baseline, '--', ...pathspec],
167
- { encoding: 'utf8' },
168
- );
169
- } catch (e) {
170
- output = e.stdout ? e.stdout.toString() : '';
171
- }
172
- const untracked = untrackedNumstat(root, pathspec);
173
- if (untracked !== '') output = output === '' ? untracked : `${output}\n${untracked}`;
174
- let total = 0;
175
- let weighted = 0;
176
- const outOfScope = [];
177
- for (const line of output.split('\n')) {
178
- if (line === '') continue;
179
- const parts = line.split('\t');
180
- let added = parts[0];
181
- let deleted = parts[1];
182
- const file = parts.slice(2).join('\t');
183
- if (!file) continue;
184
- added = added === '-' ? 0 : Number(added); // binary
185
- deleted = deleted === '-' ? 0 : Number(deleted);
186
- const lines = added + deleted;
187
- total += lines;
188
- let inScope = false;
189
- for (const entry of iterationFiles) {
190
- if (!entry) continue;
191
- if (file === entry || (entry.endsWith('/') && file.startsWith(entry))) {
192
- inScope = true;
193
- break;
194
- }
195
- }
196
- if (inScope) {
197
- weighted += lines;
198
- } else {
199
- weighted += 2 * lines;
200
- outOfScope.push(file);
201
- }
202
- }
203
- return { total, weighted, outOfScope };
204
- }
205
-
206
131
  // --- mid-loop cap re-resolution --------------------------------------------
207
132
  // `init` resolves caps once (CLI flag > env var > .somi/config.json > default) and
208
133
  // freezes them into state -- deliberately, so the diff baseline and pass history stay
@@ -319,6 +244,9 @@ function main() {
319
244
  let BLOCKERS = '0';
320
245
  let MAJORS = '0';
321
246
  let STATUS = '';
247
+ let AGENT = '';
248
+ let HOST;
249
+ let ARG_MAX_MINUTES = '';
322
250
  let FORCE = false;
323
251
  let ARG_MAX_PASSES = '';
324
252
  let ARG_DIFF_CAP = '';
@@ -338,12 +266,15 @@ function main() {
338
266
  case '--blockers': BLOCKERS = rest[1]; rest = rest.slice(2); break;
339
267
  case '--majors': MAJORS = rest[1]; rest = rest.slice(2); break;
340
268
  case '--status': STATUS = rest[1]; rest = rest.slice(2); break;
269
+ case '--agent': AGENT = rest[1]; rest = rest.slice(2); break;
270
+ case '--host': HOST = rest[1]; rest = rest.slice(2); break;
271
+ case '--max-minutes': ARG_MAX_MINUTES = rest[1]; rest = rest.slice(2); break;
341
272
  case '--force': FORCE = true; rest = rest.slice(1); break;
342
273
  default: die(`unknown argument: ${a}`);
343
274
  }
344
275
  }
345
276
 
346
- if (!CMD) die('usage: somi-loop.mjs <init|resume|pass|check-diff|record-pass|finish|stats> --slug <slug> …');
277
+ if (!CMD) die('usage: somi-loop.mjs <run-start|init|resume|pass|check-diff|review-scope|record-dispatch|record-pass|finish|stats> --slug <slug> …');
347
278
  if (!SLUG) die('--slug is required');
348
279
 
349
280
  function stateFile() {
@@ -365,7 +296,16 @@ function main() {
365
296
  fs.writeFileSync(SF, JSON.stringify(state));
366
297
  }
367
298
 
299
+ const RUN_ROOT = path.dirname(STATE_DIR);
368
300
  switch (CMD) {
301
+ case 'run-start': {
302
+ const raw = firstDefined(ARG_MAX_MINUTES, process.env.SOMI_SHIP_LOOP_MAX_MINUTES, configVal(readConfig(root), ['ship_loop', 'max_minutes']));
303
+ const max = raw === undefined ? null : validateCap(raw, 'max_minutes');
304
+ if (max === 0) die('max_minutes: 0 would disable the budget; leave it unset instead');
305
+ console.log(JSON.stringify(startRun(RUN_ROOT, SLUG, max, { force: FORCE })));
306
+ break;
307
+ }
308
+
369
309
  case 'init': {
370
310
  fs.mkdirSync(STATE_DIR, { recursive: true });
371
311
  if (fs.existsSync(SF) && !FORCE) {
@@ -380,6 +320,14 @@ function main() {
380
320
  }
381
321
  }
382
322
 
323
+ // A brief-only work item (a plan directory with no phases/) exists only for the sized, human-
324
+ // approved small tier of /ship-loop: refuse it without the tier record's approval stamp.
325
+ const planDir = path.join(root, '.somi', 'plans', SLUG);
326
+ if (LOOP === 'code' && fs.existsSync(planDir) && !fs.existsSync(path.join(planDir, 'phases'))) {
327
+ const v = verifyBriefOnly(root, SLUG);
328
+ if (!v.ok) die(`brief-only work item refused: ${v.reason}; use /plan or /ship-loop`);
329
+ }
330
+
383
331
  // Cap resolution: CLI > env > config > default (per loop type), through the
384
332
  // same CAP_ENV / CAP_CONFIG_SECTION / CAP_DEFAULT tables reresolveCap() uses,
385
333
  // and validated the same way -- a malformed value dies here rather than
@@ -420,8 +368,9 @@ function main() {
420
368
  pass: 0,
421
369
  history: [],
422
370
  };
371
+ if (LOOP === 'code') state.review_min = reviewMinFor(root, SLUG) ?? undefined; // undefined: not serialised
423
372
  saveState(state);
424
- console.log(JSON.stringify({ baseline_sha: state.baseline_sha, caps: state.caps, state_file: SF }));
373
+ console.log(JSON.stringify({ baseline_sha: state.baseline_sha, caps: state.caps, state_file: SF, ...(state.review_min ? { review_min: state.review_min } : {}) }));
425
374
  break;
426
375
  }
427
376
 
@@ -443,9 +392,11 @@ function main() {
443
392
  if (cur + 1 > max) {
444
393
  fail(2, `max-passes-exceeded: pass ${cur + 1} > cap ${max}`);
445
394
  }
395
+ const run = checkRun(RUN_ROOT, SLUG);
396
+ if (run?.over) fail(4, `time-budget-exceeded: ${run.elapsed_minutes} of ${run.max_minutes} minutes used by this run`);
446
397
  state.pass = cur + 1;
447
398
  saveState(state);
448
- console.log(JSON.stringify({ pass: state.pass, max_passes: max }));
399
+ console.log(JSON.stringify({ pass: state.pass, max_passes: max, ...(state.review_min ? { review_min: state.review_min } : {}) }));
449
400
  break;
450
401
  }
451
402
 
@@ -465,6 +416,28 @@ function main() {
465
416
  break;
466
417
  }
467
418
 
419
+ case 'review-scope': {
420
+ requireState();
421
+ const state = loadState();
422
+ const setting = firstDefined(process.env.SOMI_CODE_LOOP_REVIEW_SCOPE, configVal(readConfig(root), ['code_loop', 'review_scope']), 'delta');
423
+ if (!REVIEW_SCOPES.includes(setting)) die(`review scope must be one of ${REVIEW_SCOPES.join('|')}, got ${JSON.stringify(setting)}`);
424
+ console.log(JSON.stringify({ ...reviewScope(root, state, setting), ...(state.review_min ? { review_min: state.review_min } : {}) }));
425
+ break;
426
+ }
427
+
428
+ case 'record-dispatch': {
429
+ requireState();
430
+ if (!AGENT) die('record-dispatch requires --agent');
431
+ const state = loadState();
432
+ const installRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
433
+ const d = dispatchEntry({ root, installRoot, agent: AGENT, host: HOST, pass: state.pass });
434
+ if (!d.ok) fail(d.code, `${PROG}: ${d.message}`);
435
+ (state.dispatches ??= []).push(d.entry);
436
+ saveState(state);
437
+ console.log(JSON.stringify(d.entry));
438
+ break;
439
+ }
440
+
468
441
  case 'record-pass': {
469
442
  requireState();
470
443
  if (!VERDICT) die('record-pass requires --verdict');
@@ -476,6 +449,7 @@ function main() {
476
449
  blockers: Number(BLOCKERS),
477
450
  majors: Number(MAJORS),
478
451
  diff_lines: total,
452
+ tree: snapshotTree(root) ?? undefined, // the reviewed tree: the next pass's delta starts here
479
453
  at: nowIso(),
480
454
  };
481
455
  state.history.push(entry);
@@ -496,6 +470,7 @@ function main() {
496
470
  pass: state.pass,
497
471
  history: state.history.length,
498
472
  cap_overrides: state.cap_overrides || [],
473
+ ...(state.dispatches ? { dispatches: state.dispatches } : {}),
499
474
  }));
500
475
  break;
501
476
  }