@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
@@ -30,16 +30,32 @@
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';
58
+ import { loadConfig } from './lib/config-files.mjs';
43
59
 
44
60
  const PROG = 'somi-loop';
45
61
 
@@ -77,11 +93,11 @@ function projectRoot() {
77
93
  return b;
78
94
  }
79
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.
80
98
  function readConfig(root) {
81
- const cfgPath = path.join(root, '.somi', 'config.json');
82
- if (!fs.existsSync(cfgPath)) return {};
83
99
  try {
84
- return JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
100
+ return loadConfig(root).config;
85
101
  } catch {
86
102
  return {};
87
103
  }
@@ -113,96 +129,6 @@ function nowIso() {
113
129
  return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
114
130
  }
115
131
 
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
132
  // --- mid-loop cap re-resolution --------------------------------------------
207
133
  // `init` resolves caps once (CLI flag > env var > .somi/config.json > default) and
208
134
  // freezes them into state -- deliberately, so the diff baseline and pass history stay
@@ -319,6 +245,9 @@ function main() {
319
245
  let BLOCKERS = '0';
320
246
  let MAJORS = '0';
321
247
  let STATUS = '';
248
+ let AGENT = '';
249
+ let HOST;
250
+ let ARG_MAX_MINUTES = '';
322
251
  let FORCE = false;
323
252
  let ARG_MAX_PASSES = '';
324
253
  let ARG_DIFF_CAP = '';
@@ -338,12 +267,15 @@ function main() {
338
267
  case '--blockers': BLOCKERS = rest[1]; rest = rest.slice(2); break;
339
268
  case '--majors': MAJORS = rest[1]; rest = rest.slice(2); break;
340
269
  case '--status': STATUS = rest[1]; rest = rest.slice(2); break;
270
+ case '--agent': AGENT = rest[1]; rest = rest.slice(2); break;
271
+ case '--host': HOST = rest[1]; rest = rest.slice(2); break;
272
+ case '--max-minutes': ARG_MAX_MINUTES = rest[1]; rest = rest.slice(2); break;
341
273
  case '--force': FORCE = true; rest = rest.slice(1); break;
342
274
  default: die(`unknown argument: ${a}`);
343
275
  }
344
276
  }
345
277
 
346
- if (!CMD) die('usage: somi-loop.mjs <init|resume|pass|check-diff|record-pass|finish|stats> --slug <slug> …');
278
+ 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
279
  if (!SLUG) die('--slug is required');
348
280
 
349
281
  function stateFile() {
@@ -365,7 +297,16 @@ function main() {
365
297
  fs.writeFileSync(SF, JSON.stringify(state));
366
298
  }
367
299
 
300
+ const RUN_ROOT = path.dirname(STATE_DIR);
368
301
  switch (CMD) {
302
+ case 'run-start': {
303
+ const raw = firstDefined(ARG_MAX_MINUTES, process.env.SOMI_SHIP_LOOP_MAX_MINUTES, configVal(readConfig(root), ['ship_loop', 'max_minutes']));
304
+ const max = raw === undefined ? null : validateCap(raw, 'max_minutes');
305
+ if (max === 0) die('max_minutes: 0 would disable the budget; leave it unset instead');
306
+ console.log(JSON.stringify(startRun(RUN_ROOT, SLUG, max, { force: FORCE })));
307
+ break;
308
+ }
309
+
369
310
  case 'init': {
370
311
  fs.mkdirSync(STATE_DIR, { recursive: true });
371
312
  if (fs.existsSync(SF) && !FORCE) {
@@ -380,6 +321,14 @@ function main() {
380
321
  }
381
322
  }
382
323
 
324
+ // A brief-only work item (a plan directory with no phases/) exists only for the sized, human-
325
+ // approved small tier of /ship-loop: refuse it without the tier record's approval stamp.
326
+ const planDir = path.join(root, '.somi', 'plans', SLUG);
327
+ if (LOOP === 'code' && fs.existsSync(planDir) && !fs.existsSync(path.join(planDir, 'phases'))) {
328
+ const v = verifyBriefOnly(root, SLUG);
329
+ if (!v.ok) die(`brief-only work item refused: ${v.reason}; use /plan or /ship-loop`);
330
+ }
331
+
383
332
  // Cap resolution: CLI > env > config > default (per loop type), through the
384
333
  // same CAP_ENV / CAP_CONFIG_SECTION / CAP_DEFAULT tables reresolveCap() uses,
385
334
  // and validated the same way -- a malformed value dies here rather than
@@ -420,8 +369,9 @@ function main() {
420
369
  pass: 0,
421
370
  history: [],
422
371
  };
372
+ if (LOOP === 'code') state.review_min = reviewMinFor(root, SLUG) ?? undefined; // undefined: not serialised
423
373
  saveState(state);
424
- console.log(JSON.stringify({ baseline_sha: state.baseline_sha, caps: state.caps, state_file: SF }));
374
+ console.log(JSON.stringify({ baseline_sha: state.baseline_sha, caps: state.caps, state_file: SF, ...(state.review_min ? { review_min: state.review_min } : {}) }));
425
375
  break;
426
376
  }
427
377
 
@@ -443,9 +393,11 @@ function main() {
443
393
  if (cur + 1 > max) {
444
394
  fail(2, `max-passes-exceeded: pass ${cur + 1} > cap ${max}`);
445
395
  }
396
+ const run = checkRun(RUN_ROOT, SLUG);
397
+ if (run?.over) fail(4, `time-budget-exceeded: ${run.elapsed_minutes} of ${run.max_minutes} minutes used by this run`);
446
398
  state.pass = cur + 1;
447
399
  saveState(state);
448
- console.log(JSON.stringify({ pass: state.pass, max_passes: max }));
400
+ console.log(JSON.stringify({ pass: state.pass, max_passes: max, ...(state.review_min ? { review_min: state.review_min } : {}) }));
449
401
  break;
450
402
  }
451
403
 
@@ -465,6 +417,28 @@ function main() {
465
417
  break;
466
418
  }
467
419
 
420
+ case 'review-scope': {
421
+ requireState();
422
+ const state = loadState();
423
+ const setting = firstDefined(process.env.SOMI_CODE_LOOP_REVIEW_SCOPE, configVal(readConfig(root), ['code_loop', 'review_scope']), 'delta');
424
+ if (!REVIEW_SCOPES.includes(setting)) die(`review scope must be one of ${REVIEW_SCOPES.join('|')}, got ${JSON.stringify(setting)}`);
425
+ console.log(JSON.stringify({ ...reviewScope(root, state, setting), ...(state.review_min ? { review_min: state.review_min } : {}) }));
426
+ break;
427
+ }
428
+
429
+ case 'record-dispatch': {
430
+ requireState();
431
+ if (!AGENT) die('record-dispatch requires --agent');
432
+ const state = loadState();
433
+ const installRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
434
+ const d = dispatchEntry({ root, installRoot, agent: AGENT, host: HOST, pass: state.pass });
435
+ if (!d.ok) fail(d.code, `${PROG}: ${d.message}`);
436
+ (state.dispatches ??= []).push(d.entry);
437
+ saveState(state);
438
+ console.log(JSON.stringify(d.entry));
439
+ break;
440
+ }
441
+
468
442
  case 'record-pass': {
469
443
  requireState();
470
444
  if (!VERDICT) die('record-pass requires --verdict');
@@ -476,6 +450,7 @@ function main() {
476
450
  blockers: Number(BLOCKERS),
477
451
  majors: Number(MAJORS),
478
452
  diff_lines: total,
453
+ tree: snapshotTree(root) ?? undefined, // the reviewed tree: the next pass's delta starts here
479
454
  at: nowIso(),
480
455
  };
481
456
  state.history.push(entry);
@@ -496,6 +471,7 @@ function main() {
496
471
  pass: state.pass,
497
472
  history: state.history.length,
498
473
  cap_overrides: state.cap_overrides || [],
474
+ ...(state.dispatches ? { dispatches: state.dispatches } : {}),
499
475
  }));
500
476
  break;
501
477
  }
@@ -2,7 +2,7 @@
2
2
  // somi-mcp.mjs — a zero-dependency stdio MCP server bundling scripts/lib/dispatch-resolver.mjs's
3
3
  // resolveDispatch() as the `somi_resolve` tool, plus a command-procedure text reader as the
4
4
  // `somi_command` tool, a skill-text reader as the `somi_skill` tool and an agent-instructions
5
- // reader as the `somi_agent` tool. Both Claude Code and
5
+ // reader as the `somi_agent` tool, and the read-only `somi_agent_info` lookup. Both Claude Code and
6
6
  // Copilot CLI launch a plugin's bundled MCP server with its root already expanded
7
7
  // (${CLAUDE_PLUGIN_ROOT} / ${PLUGIN_ROOT}), so a prompt calling these tools never needs to know
8
8
  // where SoMi is installed — unlike scripts/somi-dispatch.mjs, which a prompt can only shell out to
@@ -24,6 +24,7 @@
24
24
  // error with `id: null` — the server keeps running; one bad line must never kill in-flight calls.
25
25
 
26
26
  import { createInterface } from 'node:readline';
27
+ import { spawnSync } from 'node:child_process';
27
28
  import fs from 'node:fs';
28
29
  import path from 'node:path';
29
30
  import { fileURLToPath } from 'node:url';
@@ -35,6 +36,8 @@ import {
35
36
  EXIT_UNKNOWN_AGENT,
36
37
  } from './lib/dispatch-resolver.mjs';
37
38
  import { resolveProjectRoot } from './lib/mcp-project-root.mjs';
39
+ import { AGENT_INFO_TOOL, agentInfo } from './lib/agent-info.mjs';
40
+ import { SIGNAL_IDS } from './lib/size-tier.mjs';
38
41
 
39
42
  const PROG = 'somi-dispatch'; // shared identity with the CLI: this is the SAME resolver speaking.
40
43
 
@@ -113,23 +116,25 @@ const TOOLS = [
113
116
  {
114
117
  name: 'somi_resolve',
115
118
  description:
116
- "Resolve one agent's dispatch tier and model against the current session ceiling — the " +
119
+ "Resolve one agent's dispatch tier and model: its cost.agents override from .somi/config.json, " +
120
+ 'else the current session ceiling itself (a hard cap) — the ' +
117
121
  'MCP-native equivalent of `node scripts/somi-dispatch.mjs resolve`. Same validation, same ' +
118
- 'four-code failure family (64 usage / 65 unknown agent / 66 malformed cost: declaration / ' +
122
+ 'four-code failure family (64 usage / 65 unknown agent / 66 no default tier / ' +
119
123
  '67 project environment failure — including "no project root could be established": no ' +
120
124
  'CLAUDE_PROJECT_DIR, no usable MCP roots, and no project_dir given), reported in the tool ' +
121
125
  'result text on failure.',
122
126
  inputSchema: {
123
127
  type: 'object',
124
128
  properties: {
125
- agent: { type: 'string', description: 'agent name, e.g. "coder" (matches ^[a-z][a-z0-9-]*$)' },
129
+ agent: { type: 'string', description: 'agent name, e.g. "somi-coder" (matches ^[a-z][a-z0-9-]*$)' },
126
130
  host: { type: 'string', description: 'e.g. "claude-code" or "copilot"; defaults to "claude-code"' },
127
131
  ceiling: {
128
132
  type: 'string',
129
133
  description:
130
- 'one of low|medium|high. Sets and SAVES the session ceiling for every later dispatch ' +
131
- 'in this project, not just this call — omit it unless the user actually asked to ' +
132
- 'change the ceiling.',
134
+ 'one of low|medium|high. Used for this call and remembered as an explicitly set ' +
135
+ 'value, but cost.ceiling in .somi/config.json is read live and outranks it, so it ' +
136
+ 'does not last where the config sets one — omit it unless the user actually asked ' +
137
+ 'to change the ceiling.',
133
138
  },
134
139
  project_dir: {
135
140
  type: 'string',
@@ -143,6 +148,7 @@ const TOOLS = [
143
148
  required: ['agent'],
144
149
  },
145
150
  },
151
+ AGENT_INFO_TOOL,
146
152
  {
147
153
  name: 'somi_command',
148
154
  description:
@@ -178,17 +184,69 @@ const TOOLS = [
178
184
  name: 'somi_agent',
179
185
  description:
180
186
  "Read a SoMi agent's instructions (agents/<name>.md, frontmatter removed) from the install " +
181
- "root. For a host whose subagent tool cannot start a plugin agent by name (Copilot's task " +
182
- 'tool accepts only its built-in types): start a built-in general-purpose subagent with this ' +
183
- 'text as the start of its prompt, and the model somi_resolve returned.',
187
+ 'root, to inspect or quote them. Not a way to run the agent: start it as the agent_type ' +
188
+ 'somi_resolve returns, never as another agent given this text.',
184
189
  inputSchema: {
185
190
  type: 'object',
186
191
  properties: {
187
- name: { type: 'string', description: 'agent name, e.g. "reviewer" (matches ^[a-z][a-z0-9-]*$)' },
192
+ name: { type: 'string', description: 'agent name, e.g. "somi-reviewer" (matches ^[a-z][a-z0-9-]*$)' },
188
193
  },
189
194
  required: ['name'],
190
195
  },
191
196
  },
197
+ {
198
+ name: 'somi_config',
199
+ description:
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
+ '`node scripts/somi-config.mjs`, and return its one JSON line unchanged. Actions: show ' +
202
+ '(every agent\'s effective tier and warnings), get, set, unset, init (create the default file ' +
203
+ 'when absent). cost.ceiling and cost.agents.<name> take low|medium|high; ' +
204
+ 'cost.mapping.<host>.<tier> takes a model id or a comma-separated preference list (unset ' +
205
+ 'cost.mapping.<host> removes a host map). Any lowering or remap needs the user; ' +
206
+ 'the change is live, since the config is read on every dispatch. Failures report the CLI exit ' +
207
+ 'code: 64 usage (bad key, tier or name), 67 the project\'s config or .somi is unusable.',
208
+ inputSchema: {
209
+ type: 'object',
210
+ properties: {
211
+ action: { type: 'string', description: 'show, get, set, unset or init' },
212
+ key: { type: 'string', description: 'cost.ceiling, cost.agents.<name>, or cost.mapping.<host>[.<tier>] (get, set, unset)' },
213
+ value: { type: 'string', description: 'set: low, medium or high; for cost.mapping.<host>.<tier>, model-id[,model-id...]' },
214
+ project_dir: { type: 'string', description: 'absolute path of the project, as for somi_resolve' },
215
+ host: { type: 'string', description: 'show only: the host this session runs on (claude-code, copilot), as for somi_resolve; adds a warning when it has no model mapping' },
216
+ },
217
+ required: ['action'],
218
+ },
219
+ },
220
+ {
221
+ name: 'somi_tier',
222
+ description:
223
+ "Size a request: run `node scripts/somi-tier.mjs resolve` (no --record) on the signals you " +
224
+ 'extracted and return its one JSON line unchanged (tier, effective, source, floor, security_lens, reasons, ' +
225
+ 'basis). The rubric is the skill somi-routing, section Size tiers; this tool states no ' +
226
+ 'thresholds. The signal ids in `signals` are exact: use these names and no others. A name that ' +
227
+ 'is not one is ignored and listed back as `unrecognized` next to `expected`, and a missing ' +
228
+ 'signal is read as its worst case. Failures report the CLI exit code: 64 usage/input, 65 refused (a downward ' +
229
+ 'override below the security floor). It writes nothing: the tier record and the approval ' +
230
+ 'stamp need the CLI itself with --record and approve. SoMi is installed at ' + installRoot() +
231
+ ': run `node <that path>/scripts/somi-tier.mjs ...` from the project directory.',
232
+ inputSchema: {
233
+ type: 'object',
234
+ properties: {
235
+ signals: {
236
+ type: 'object',
237
+ description: 'One entry per rubric signal id, with exactly these names: { value, evidence }. What each means and how to extract it is in the skill somi-routing, section Size tiers.',
238
+ properties: Object.fromEntries(SIGNAL_IDS.map((id) => [id, {
239
+ type: 'object',
240
+ properties: { value: { description: 'true or false, or a whole number for a count signal; null when it cannot be determined' }, evidence: { type: 'string', description: 'files and lines you opened' } },
241
+ required: ['value', 'evidence'],
242
+ }])),
243
+ required: [...SIGNAL_IDS],
244
+ },
245
+ override: { type: 'string', description: 'small or full; only after a human reply' },
246
+ },
247
+ required: ['signals'],
248
+ },
249
+ },
192
250
  ];
193
251
 
194
252
  // --- tool implementations --------------------------------------------------------------------
@@ -232,6 +290,15 @@ async function callSomiResolve(args) {
232
290
  return textResult(JSON.stringify(outcome.result));
233
291
  }
234
292
 
293
+ // Read-only agent lookup; the logic lives in lib/agent-info.mjs, this only supplies the project root.
294
+ async function callSomiAgentInfo(args) {
295
+ const outcome = await agentInfo(args, {
296
+ resolveRoot: () => resolveProjectRoot({ projectDirArg: args?.project_dir, listRoots: () => listClientRoots() }),
297
+ installRoot: installRoot(),
298
+ });
299
+ return outcome.ok ? textResult(JSON.stringify(outcome.result)) : textResult(`somi-agent-info: ${outcome.message} (exit ${outcome.code})`, true);
300
+ }
301
+
235
302
  // One reader for every install-root text tool. The name is checked against AGENT_NAME_RE BEFORE
236
303
  // any path is built, so a traversal payload (`../x`, `a/b`) is a 64 and never reaches path.join.
237
304
  // JSON.stringify, not a template interpolation, for the invalid name: an object-shaped `name`
@@ -261,23 +328,77 @@ function callSomiSkill(args) {
261
328
  return r.error ?? textResult(r.content);
262
329
  }
263
330
 
264
- // The agent's instructions without its frontmatter: a host that cannot start a plugin agent by
265
- // type (Copilot's task tool) starts a built-in general-purpose subagent with this text instead, and
266
- // the frontmatter's `model:` would contradict the tier somi_resolve just selected.
331
+ // The agent's instructions without its frontmatter, for reading. Dispatch never uses this: an agent
332
+ // starts as its registered agent_type (see skills/somi-dispatch §5), so the text is never a payload.
267
333
  function callSomiAgent(args) {
268
334
  const r = readInstallText('somi-agent', 'agent', args?.name, (n) => ['agents', `${n}.md`]);
269
335
  return r.error ?? textResult(r.content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '').trimStart());
270
336
  }
271
337
 
338
+ // Runs the sizing CLI itself, so the result and the exit codes are the CLI's, byte for byte.
339
+ function callSomiTier(args) {
340
+ if (args.signals === null || typeof args.signals !== 'object' || Array.isArray(args.signals)) {
341
+ return textResult('somi-tier: signals must be an object (exit 64)', true);
342
+ }
343
+ const argv = [path.join(installRoot(), 'scripts', 'somi-tier.mjs'), 'resolve', '--signals', '-'];
344
+ if (args.override !== undefined) argv.push('--override', String(args.override));
345
+ const r = spawnSync(process.execPath, argv, { input: JSON.stringify(args.signals), encoding: 'utf8', timeout: 10000 });
346
+ if (r.status === 0) return textResult(r.stdout.trimEnd());
347
+ return textResult(`${(r.stderr || 'somi-tier: failed').trim()} (exit ${r.status ?? 'none'})`, true);
348
+ }
349
+
350
+ // Runs the config CLI itself (never a shell), so output and exit codes are the CLI's, byte for byte.
351
+ async function callSomiConfig(args) {
352
+ const text = (v) => v === undefined || typeof v === 'string';
353
+ if (typeof args.action !== 'string' || !['show', 'get', 'set', 'unset', 'init'].includes(args.action)) {
354
+ return textResult('somi-config: action must be one of show, get, set, unset, init (exit 64)', true);
355
+ }
356
+ if (args.host !== undefined && (args.action !== 'show' || typeof args.host !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(args.host))) {
357
+ return textResult('somi-config: host applies to show only and must be a lowercase host name (exit 64)', true);
358
+ }
359
+ if (!text(args.key) || !text(args.value) || [args.key, args.value].some((v) => v !== undefined && (v === '' || v.startsWith('-') || /[\u0000-\u001f\u007f]/.test(v)))) {
360
+ return textResult('somi-config: key and value must be non-empty strings without control characters that do not start with a dash (exit 64)', true);
361
+ }
362
+ // Writes need a root the HOST supplied: a model-supplied project_dir alone could point a write anywhere.
363
+ // The probe (no project_dir) succeeds, or fails as ambiguous, only when the host offered a root.
364
+ if (args.action !== 'show' && args.action !== 'get') {
365
+ const probe = await resolveProjectRoot({ projectDirArg: undefined, listRoots: () => listClientRoots() });
366
+ if (!probe.ok && !probe.message.startsWith('ambiguous')) {
367
+ return textResult('somi-config: no host project root; run the CLI yourself (node scripts/somi-config.mjs) to change the config (exit 67)', true);
368
+ }
369
+ }
370
+ const rootOutcome = await resolveProjectRoot({ projectDirArg: args.project_dir, listRoots: () => listClientRoots() });
371
+ if (!rootOutcome.ok) return textResult(`somi-config: ${rootOutcome.message} (exit ${rootOutcome.code})`, true);
372
+ const argv = [path.join(installRoot(), 'scripts', 'somi-config.mjs'), args.action];
373
+ if (args.key !== undefined) argv.push(args.key);
374
+ if (args.value !== undefined) argv.push(args.value);
375
+ if (args.host !== undefined) argv.push('--host', args.host);
376
+ // Lowering a tier or remapping a model needs the user. Where Claude Code runs the SoMi plugin's hooks
377
+ // (CLAUDE_PLUGIN_ROOT set) the cost-lowering PreToolUse hook asks; elsewhere nothing can ask, so the CLI
378
+ // refuses. Copilot CLI also sets CLAUDE_PLUGIN_ROOT, but names this tool `somi-somi_config`, which the
379
+ // hook's matcher does not catch (verified live on 1.0.103), so COPILOT_PLUGIN_ROOT means "refuse".
380
+ // A heuristic for "a hook can ask", failing closed on any host it does not recognise.
381
+ const pluginRoot = process.env.CLAUDE_PLUGIN_ROOT;
382
+ const hookCanAsk = pluginRoot && !pluginRoot.includes('${') && !process.env.COPILOT_PLUGIN_ROOT;
383
+ if ((args.action === 'set' || args.action === 'unset') && !hookCanAsk) argv.push('--refuse-lowering');
384
+ argv.push('--project-dir', fs.realpathSync(rootOutcome.root));
385
+ const r = spawnSync(process.execPath, argv, { encoding: 'utf8', timeout: 10000 });
386
+ if (r.status === 0) return textResult(r.stdout.trimEnd());
387
+ return textResult(`${(r.stderr || 'somi-config: failed').trim()} (exit ${r.status ?? 'none'})`, true);
388
+ }
389
+
272
390
  // Returns null for an unrecognized tool name — the caller turns that into a JSON-RPC error, since
273
391
  // an unknown TOOL is the protocol failing to find it at all, distinct from a known tool that ran
274
392
  // and failed (which reports isError:true in an otherwise-successful JSON-RPC response).
275
393
  async function callTool(name, args) {
276
394
  switch (name) {
277
395
  case 'somi_resolve': return await callSomiResolve(args || {});
396
+ case 'somi_agent_info': return await callSomiAgentInfo(args || {});
278
397
  case 'somi_command': return callSomiCommand(args || {});
279
398
  case 'somi_skill': return callSomiSkill(args || {});
280
399
  case 'somi_agent': return callSomiAgent(args || {});
400
+ case 'somi_tier': return callSomiTier(args || {});
401
+ case 'somi_config': return await callSomiConfig(args || {});
281
402
  default: return null;
282
403
  }
283
404
  }