@skathio/somi 2.2.2 → 3.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 (128) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +8 -2
  3. package/.copilot-extension/extension.json +9 -8
  4. package/.copilot-extension/marketplace.json +2 -2
  5. package/README.md +45 -33
  6. package/VERSION +1 -1
  7. package/agents/architecture-reviewer.md +16 -0
  8. package/agents/atlas.md +102 -0
  9. package/agents/coder.md +66 -22
  10. package/agents/designer.md +20 -16
  11. package/agents/discovery-analyst.md +6 -5
  12. package/agents/impact.md +97 -0
  13. package/agents/incident.md +96 -0
  14. package/agents/plan-reviewer.md +70 -0
  15. package/agents/planner.md +77 -20
  16. package/agents/pr.md +101 -0
  17. package/agents/refactor-designer.md +82 -0
  18. package/agents/refactorer.md +30 -24
  19. package/agents/reviewer.md +28 -25
  20. package/agents/sdlc-reviewer.md +69 -0
  21. package/agents/security-reviewer.md +17 -0
  22. package/agents/somi.md +204 -153
  23. package/agents/test-strategist.md +16 -1
  24. package/commands/adopt.md +21 -7
  25. package/commands/architecture-review.md +8 -5
  26. package/commands/atlas.md +24 -72
  27. package/commands/code-loop.md +46 -15
  28. package/commands/code-parallel.md +6 -4
  29. package/commands/code.md +29 -21
  30. package/commands/debug.md +17 -11
  31. package/commands/design.md +48 -31
  32. package/commands/discover.md +26 -16
  33. package/commands/impact.md +16 -54
  34. package/commands/incident.md +22 -55
  35. package/commands/plan-loop.md +43 -17
  36. package/commands/plan.md +64 -26
  37. package/commands/pr.md +19 -66
  38. package/commands/refactor-design.md +98 -0
  39. package/commands/refactor.md +22 -23
  40. package/commands/release-readiness.md +16 -7
  41. package/commands/review-panel.md +31 -10
  42. package/commands/review.md +21 -14
  43. package/commands/security-review.md +12 -3
  44. package/commands/ship-loop.md +71 -54
  45. package/commands/ship.md +17 -13
  46. package/commands/test-strategy.md +6 -4
  47. package/commands/upgrade.md +10 -8
  48. package/examples/discovery-example.md +2 -2
  49. package/examples/sample-consumer/CLAUDE.md +41 -7
  50. package/examples/sample-consumer/README.md +36 -22
  51. package/hooks/lib/common.mjs +66 -20
  52. package/hooks/post-tool/audit-log.mjs +7 -11
  53. package/hooks/post-tool/lint-changed-files.mjs +8 -11
  54. package/hooks/pre-tool/block-dangerous-bash.mjs +32 -44
  55. package/hooks/pre-tool/block-secret-writes.mjs +6 -9
  56. package/hooks/pre-tool/gate-dep-install.mjs +18 -27
  57. package/hooks/pre-tool/guard-protected-paths.mjs +9 -11
  58. package/hooks/session-start/detect-repo-instructions.mjs +21 -23
  59. package/hooks/user-prompt-submit/inject-workflow-context.mjs +190 -42
  60. package/mcp.json +10 -0
  61. package/package.json +5 -2
  62. package/rules/CLAUDE.md +22 -19
  63. package/scripts/check-links.mjs +218 -0
  64. package/scripts/check-session-artefacts.mjs +149 -0
  65. package/scripts/check-size-budget.mjs +137 -0
  66. package/scripts/generate-digest.mjs +176 -0
  67. package/scripts/lib/cost-ceiling.mjs +317 -0
  68. package/scripts/lib/cost-model.mjs +95 -0
  69. package/scripts/lib/dispatch-resolver.mjs +225 -0
  70. package/scripts/lib/mcp-project-root.mjs +183 -0
  71. package/scripts/size-budget-overrides.json +74 -0
  72. package/scripts/somi-check.mjs +6 -13
  73. package/scripts/somi-dispatch.mjs +141 -0
  74. package/scripts/somi-findings.mjs +4 -5
  75. package/scripts/somi-loop.mjs +181 -13
  76. package/scripts/somi-mcp.mjs +357 -0
  77. package/scripts/validate.sh +691 -30
  78. package/skills/clean-code/SKILL.md +1 -1
  79. package/skills/plan-review/SKILL.md +79 -0
  80. package/skills/rules/SKILL.md +47 -0
  81. package/skills/sdlc-process/SKILL.md +74 -0
  82. package/skills/somi-dispatch/SKILL.md +220 -0
  83. package/skills/somi-routing/SKILL.md +31 -6
  84. package/skills/{test-strategy → testing-playbook}/SKILL.md +1 -1
  85. package/templates/ATLAS.md.tmpl +4 -4
  86. package/templates/BRIEF.md.tmpl +23 -22
  87. package/templates/DECISIONS.md.tmpl +1 -0
  88. package/templates/DESIGN.md.tmpl +5 -5
  89. package/templates/DIARY.md.tmpl +10 -5
  90. package/templates/DOD.md.tmpl +24 -0
  91. package/templates/PROGRESS.md.tmpl +3 -16
  92. package/templates/SOMI-README.md.tmpl +3 -3
  93. package/tests/hooks/cases/inject-workflow-context.json +120 -7
  94. package/tests/hooks/run.sh +20 -11
  95. package/tests/scripts/check-links.sh +105 -0
  96. package/tests/scripts/check-session-artefacts.sh +60 -0
  97. package/tests/scripts/check-size-budget.sh +71 -0
  98. package/tests/scripts/checkpoint-gate.sh +90 -0
  99. package/tests/scripts/convergence-runner.sh +1510 -0
  100. package/tests/scripts/cost-ceiling.sh +343 -0
  101. package/tests/scripts/cost-model.sh +192 -0
  102. package/tests/scripts/dispatch-guard.sh +108 -0
  103. package/tests/scripts/dispatch-reference-gate.sh +173 -0
  104. package/tests/scripts/eval-runner.sh +3691 -0
  105. package/tests/scripts/evals-packaging.sh +117 -0
  106. package/tests/scripts/fixtures/legacy-shard-no-schema.json +50 -0
  107. package/tests/scripts/generate-digest.sh +180 -0
  108. package/tests/scripts/goldens/loop-state-breach.json +1 -0
  109. package/tests/scripts/goldens/loop-state-done.json +1 -0
  110. package/tests/scripts/goldens/somi-loop.json +1 -1
  111. package/tests/scripts/lib/adr-shape.mjs +41 -0
  112. package/tests/scripts/lib/checkpoint-gate.mjs +54 -0
  113. package/tests/scripts/lib/digest-marker-coupling.mjs +52 -0
  114. package/tests/scripts/lib/dispatch-reference-gate.mjs +112 -0
  115. package/tests/scripts/lib/multipass-dependence.mjs +192 -0
  116. package/tests/scripts/lib/multipass-source-identity.mjs +243 -0
  117. package/tests/scripts/lib/reference-pair.mjs +61 -0
  118. package/tests/scripts/lib/retirement-gate.mjs +167 -0
  119. package/tests/scripts/lib/shell-embedded-js.mjs +47 -0
  120. package/tests/scripts/lib/somi-mcp-client.mjs +102 -0
  121. package/tests/scripts/lib/somi-mcp-tests.mjs +401 -0
  122. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +38 -0
  123. package/tests/scripts/retirement-gate.sh +287 -0
  124. package/tests/scripts/review-panel-seats.sh +32 -0
  125. package/tests/scripts/run.sh +184 -2
  126. package/tests/scripts/somi-agent-dispatch-contract.sh +195 -0
  127. package/tests/scripts/somi-dispatch.sh +366 -0
  128. package/tests/scripts/somi-mcp.sh +12 -0
@@ -1,6 +1,5 @@
1
1
  // somi-findings.mjs — the findings ledger: identity and lifecycle for review findings.
2
2
  //
3
- // Node port of scripts/somi-findings.sh (node-runtime-port, phase 1, iteration 1.2).
4
3
  // Zero-dependency: stdlib only (node:fs, node:path). No jq, no bash. Behavior-preserving
5
4
  // — exit codes and stdout JSON shapes are frozen and reproduced exactly; see the bash
6
5
  // original's header comment for the full rationale (finding identity/lifecycle, the
@@ -37,7 +36,7 @@ const PROG = 'somi-findings';
37
36
 
38
37
  // Thrown to unwind to the top-level handler, which sets process.exitCode and lets Node
39
38
  // exit naturally — avoids process.exit()'s risk of truncating buffered stdout/stderr
40
- // writes on a pipe. Same idiom as somi-loop.mjs (1.1, reviewer-blessed).
39
+ // writes on a pipe. Same idiom as somi-loop.mjs.
41
40
  class ExitSignal extends Error {
42
41
  constructor(code) {
43
42
  super(`exit ${code}`);
@@ -92,9 +91,9 @@ function rawStr(v) {
92
91
  // byte-wise `tr` would never produce (bash leaves İ's UTF-8 bytes alone; the following
93
92
  // `tr -cs 'a-z0-9' ' '` step then discards all of them as non-alphanumeric). So the
94
93
  // lowercasing below only maps `A`-`Z`, mirroring `tr '[:upper:]' '[:lower:]'` exactly.
95
- // Verified against all six of Phase 0.6's normalize_title edge-case goldens (empty,
94
+ // Verified against six normalize_title edge-case goldens (empty,
96
95
  // single-word, >8-word, leading/trailing whitespace, multi-space, punctuation) plus
97
- // adversarial Unicode probes (café, İstanbul) — see diary for the case-by-case trace.
96
+ // adversarial Unicode probes (café, İstanbul).
98
97
  function normalizeTitle(title) {
99
98
  const lowered = title.replace(/[A-Z]/g, (c) => c.toLowerCase());
100
99
  const squeezed = lowered.replace(/[^a-z0-9]+/g, ' ').trim();
@@ -120,7 +119,7 @@ function loadLedger(ledgerPath) {
120
119
  function saveLedger(ledgerPath, ledger) {
121
120
  // Mirror bash's `tmp="$(mktemp)"; jq ... "$LEDGER" > "$tmp" && mv "$tmp" "$LEDGER"`:
122
121
  // pretty 2-space + trailing newline (jq's default pretty-print, verified byte-identical
123
- // against JSON.stringify(ledger, null, 2) + '\n' — see diary), written to a temp file in
122
+ // against JSON.stringify(ledger, null, 2) + '\n'), written to a temp file in
124
123
  // the SAME directory as the target and renamed into place so the write is atomic and the
125
124
  // rename never crosses a filesystem boundary.
126
125
  const tmpPath = `${ledgerPath}.tmp`;
@@ -1,6 +1,5 @@
1
1
  // somi-loop.mjs — deterministic state engine for the bounded loops.
2
2
  //
3
- // Node port of scripts/somi-loop.sh (node-runtime-port, phase 1, iteration 1.1).
4
3
  // Zero-dependency: stdlib only (node:fs, node:path, node:child_process). No jq,
5
4
  // no bash. Behavior-preserving — exit codes and stdout JSON shapes are frozen
6
5
  // and reproduced exactly; see the bash original's header comment for the full
@@ -10,9 +9,21 @@
10
9
  // State: .somi/somi-state/loop/<slug>[.<iteration>].json under the project
11
10
  // root (project-local, gitignored by SoMi's conventions). Never committed.
12
11
  //
12
+ // Diff measurement covers tracked, staged AND untracked-but-not-ignored files.
13
+ // The untracked half is deliberate: `git diff` alone cannot see a file git has
14
+ // never been told about, so without it a new file costs nothing against the cap.
15
+ //
13
16
  // Cap precedence (matches the gate tables): CLI flag > env var > .somi/config.json
14
- // > default. Diff measurement EXCLUDES .somi/ and .claude/ — artifact churn
15
- // (progress/diary updates every pass) must not eat the code diff budget.
17
+ // > default. `init` resolves once from that chain and freezes the result into state.
18
+ // `pass`/`check-diff` re-resolve their own cap on every call (the documented
19
+ // remedy for a fired gate, "adjust the env var and re-run", used to be inert): absent
20
+ // an explicit CLI flag or env var THIS invocation, the cap already in force for the
21
+ // loop stands unchanged (a `.somi/config.json` edit made mid-loop cannot silently
22
+ // reopen an already-resolved gate); see reresolveCap() below. Every cap value, at
23
+ // `init` and on re-resolution alike, is validated as a non-negative integer before
24
+ // use and rejected otherwise — a malformed value must not silently disable a gate.
25
+ // Diff measurement EXCLUDES .somi/ and .claude/ — artifact churn (progress/diary
26
+ // updates every pass) must not eat the code diff budget.
16
27
  //
17
28
  // Exit codes (callers branch on these — do not repurpose):
18
29
  // 0 ok
@@ -102,18 +113,64 @@ function nowIso() {
102
113
  return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
103
114
  }
104
115
 
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
+
105
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.
106
160
  function computeDiff(root, baseline, iterationFiles) {
161
+ const pathspec = ['.', ':(exclude).somi', ':(exclude).claude'];
107
162
  let output = '';
108
163
  try {
109
164
  output = execFileSync(
110
165
  'git',
111
- ['-C', root, 'diff', '--numstat', baseline, '--', '.', ':(exclude).somi', ':(exclude).claude'],
166
+ ['-C', root, 'diff', '--numstat', baseline, '--', ...pathspec],
112
167
  { encoding: 'utf8' },
113
168
  );
114
169
  } catch (e) {
115
170
  output = e.stdout ? e.stdout.toString() : '';
116
171
  }
172
+ const untracked = untrackedNumstat(root, pathspec);
173
+ if (untracked !== '') output = output === '' ? untracked : `${output}\n${untracked}`;
117
174
  let total = 0;
118
175
  let weighted = 0;
119
176
  const outOfScope = [];
@@ -146,6 +203,103 @@ function computeDiff(root, baseline, iterationFiles) {
146
203
  return { total, weighted, outOfScope };
147
204
  }
148
205
 
206
+ // --- mid-loop cap re-resolution --------------------------------------------
207
+ // `init` resolves caps once (CLI flag > env var > .somi/config.json > default) and
208
+ // freezes them into state -- deliberately, so the diff baseline and pass history stay
209
+ // stable across a whole loop. But commands/code-loop.md's Guardrails document a
210
+ // remedy for a gate that's wrong for the work at hand: "the user adjusts the env var
211
+ // explicitly and re-runs -- the loop does not 'decide' to widen its own bounds." That
212
+ // remedy needs a path that re-reads the override on the SAME subcommand (`pass`,
213
+ // `check-diff`), without `init --force` (which discards `pass`/`history`).
214
+ //
215
+ // `pass` and `check-diff` call reresolveCap() below before their gate check.
216
+ // Precedence matches what's documented: CLI flag > env var > .somi/config.json >
217
+ // default -- an explicit CLI flag or env var THIS invocation is the only thing that
218
+ // can move the cap; absent one, the cap already in force for the loop stands (a
219
+ // `.somi/config.json` edit made while a loop is running must NOT silently reopen an
220
+ // already-resolved gate). A resolved value that differs from what's stored is
221
+ // persisted into `caps` immediately, with an entry appended to a `cap_overrides`
222
+ // audit trail (field, from, to, source, after_pass, at) -- the after-the-fact record
223
+ // the documented remedy needs, since the env var itself lives only in a shell that
224
+ // may since have exited. `cap_overrides` is created lazily, only on the first real
225
+ // override, so a loop that never overrides anything keeps exactly today's state
226
+ // shape (no golden-fixture regeneration forced by this fix). `baseline_sha`,
227
+ // `started`, `pass`, and `history` are never touched here.
228
+ //
229
+ // Every value that reaches `Number()` on this path is user input (a CLI flag, an env
230
+ // var, or a config value) and is validated before use: `Number()` on a malformed
231
+ // string (`"1,000"`, `"unlimited"`) yields NaN, which is false against BOTH gate
232
+ // comparisons (`cur + 1 > max`, `weighted > cap`) -- silently switching the gate off
233
+ // -- and `JSON.stringify` then persists that NaN as `null`, which the next bare call
234
+ // falls through past (via `firstDefined`) to re-arm at the default, with no
235
+ // `cap_overrides` entry recording the reversion. `validateCap()` rejects rather than
236
+ // coerces, so a malformed value dies loudly instead of disabling a gate.
237
+ const CAP_ENV = {
238
+ code: { max_passes: 'SOMI_CODE_LOOP_MAX_PASSES', diff_cap_lines: 'SOMI_CODE_LOOP_DIFF_CAP' },
239
+ plan: { max_passes: 'SOMI_PLAN_LOOP_MAX_PASSES' },
240
+ };
241
+ const CAP_FLAG = { max_passes: '--max-passes', diff_cap_lines: '--diff-cap' };
242
+ const CAP_CONFIG_SECTION = { code: 'code_loop', plan: 'plan_loop' };
243
+ const CAP_DEFAULT = { max_passes: 3, diff_cap_lines: 400 };
244
+
245
+ // Rejects a malformed cap value rather than letting `Number()` coerce it to NaN.
246
+ // `label` names the source in the error so `die()`'s message points at what to fix
247
+ // (a specific flag, env var, or the generic field name at `init`, where the value
248
+ // may have come from any of CLI/env/config).
249
+ function validateCap(raw, label) {
250
+ const n = Number(raw);
251
+ if (!Number.isInteger(n) || n < 0) {
252
+ die(`${label}: expected a non-negative integer, got "${raw}"`);
253
+ }
254
+ return n;
255
+ }
256
+
257
+ // Resolves one cap at `init`, reading the same CAP_ENV / CAP_CONFIG_SECTION /
258
+ // CAP_DEFAULT tables reresolveCap() uses, so the two paths cannot silently diverge
259
+ // on an env var name, a config key, or a default value.
260
+ function resolveInitCap(config, family, field, argVal) {
261
+ if (field === 'diff_cap_lines' && family === 'plan') return 0; // plan loops have no diff cap
262
+ const envVar = CAP_ENV[family][field];
263
+ const fromConfig = configVal(config, [CAP_CONFIG_SECTION[family], field]);
264
+ const picked = firstDefined(argVal, process.env[envVar], fromConfig, CAP_DEFAULT[field]);
265
+ return validateCap(picked, field);
266
+ }
267
+
268
+ function reresolveCap(state, field, argVal) {
269
+ const family = state.loop === 'plan' ? 'plan' : 'code';
270
+ if (field === 'diff_cap_lines' && family === 'plan') {
271
+ return { resolved: 0, override: null }; // plan loops have no diff cap (see `init`)
272
+ }
273
+ const envVar = CAP_ENV[family][field];
274
+ const stored = state.caps[field];
275
+ const explicit = firstDefined(argVal, process.env[envVar]);
276
+ const isCli = argVal !== undefined && argVal !== '';
277
+ const resolved = explicit === undefined
278
+ ? stored
279
+ : validateCap(explicit, isCli ? CAP_FLAG[field] : envVar);
280
+ let override = null;
281
+ if (explicit !== undefined && resolved !== stored) {
282
+ override = {
283
+ field,
284
+ from: stored,
285
+ to: resolved,
286
+ source: isCli ? 'cli' : 'env',
287
+ after_pass: state.pass,
288
+ at: nowIso(),
289
+ };
290
+ }
291
+ return { resolved, override };
292
+ }
293
+
294
+ // Mutates `state.caps[field]` and appends the audit entry. Caller still owns calling
295
+ // saveState() -- kept separate so `pass`/`check-diff` persist the override BEFORE
296
+ // their gate check can throw, not only on the success path.
297
+ function applyCapOverride(state, override) {
298
+ state.caps[override.field] = override.to;
299
+ if (!Array.isArray(state.cap_overrides)) state.cap_overrides = [];
300
+ state.cap_overrides.push(override);
301
+ }
302
+
149
303
  function main() {
150
304
  requireGit();
151
305
 
@@ -226,23 +380,24 @@ function main() {
226
380
  }
227
381
  }
228
382
 
229
- // Cap resolution: CLI > env > config > default (per loop type).
383
+ // Cap resolution: CLI > env > config > default (per loop type), through the
384
+ // same CAP_ENV / CAP_CONFIG_SECTION / CAP_DEFAULT tables reresolveCap() uses,
385
+ // and validated the same way -- a malformed value dies here rather than
386
+ // silently resolving to a fail-open NaN/null.
230
387
  const config = readConfig(root);
231
388
  let maxPasses;
232
389
  let diffCap;
233
390
  let sevFloor;
234
391
  if (LOOP === 'plan') {
235
- maxPasses = firstDefined(ARG_MAX_PASSES, process.env.SOMI_PLAN_LOOP_MAX_PASSES, configVal(config, ['plan_loop', 'max_passes']));
392
+ maxPasses = resolveInitCap(config, 'plan', 'max_passes', ARG_MAX_PASSES);
236
393
  sevFloor = firstDefined(ARG_SEVERITY, process.env.SOMI_PLAN_LOOP_SEVERITY_FLOOR, configVal(config, ['plan_loop', 'severity_floor']));
237
394
  diffCap = 0; // plan loops have no diff cap
238
395
  } else {
239
- maxPasses = firstDefined(ARG_MAX_PASSES, process.env.SOMI_CODE_LOOP_MAX_PASSES, configVal(config, ['code_loop', 'max_passes']));
396
+ maxPasses = resolveInitCap(config, 'code', 'max_passes', ARG_MAX_PASSES);
240
397
  sevFloor = firstDefined(ARG_SEVERITY, process.env.SOMI_CODE_LOOP_SEVERITY_FLOOR, configVal(config, ['code_loop', 'severity_floor']));
241
- diffCap = firstDefined(ARG_DIFF_CAP, process.env.SOMI_CODE_LOOP_DIFF_CAP, configVal(config, ['code_loop', 'diff_cap_lines']));
398
+ diffCap = resolveInitCap(config, 'code', 'diff_cap_lines', ARG_DIFF_CAP);
242
399
  }
243
- maxPasses = Number(firstDefined(maxPasses, 3));
244
400
  sevFloor = firstDefined(sevFloor, 'Major');
245
- diffCap = Number(firstDefined(diffCap, 400));
246
401
 
247
402
  let baseline;
248
403
  try {
@@ -279,7 +434,11 @@ function main() {
279
434
  case 'pass': {
280
435
  requireState();
281
436
  const state = loadState();
282
- const max = state.caps.max_passes;
437
+ const { resolved: max, override } = reresolveCap(state, 'max_passes', ARG_MAX_PASSES);
438
+ if (override) {
439
+ applyCapOverride(state, override);
440
+ saveState(state); // persist the raise even if the gate below still fails
441
+ }
283
442
  const cur = state.pass;
284
443
  if (cur + 1 > max) {
285
444
  fail(2, `max-passes-exceeded: pass ${cur + 1} > cap ${max}`);
@@ -293,8 +452,12 @@ function main() {
293
452
  case 'check-diff': {
294
453
  requireState();
295
454
  const state = loadState();
455
+ const { resolved: cap, override } = reresolveCap(state, 'diff_cap_lines', ARG_DIFF_CAP);
456
+ if (override) {
457
+ applyCapOverride(state, override);
458
+ saveState(state); // persist the raise even if the gate below still fails
459
+ }
296
460
  const { total, weighted, outOfScope } = computeDiff(root, state.baseline_sha, state.iteration_files);
297
- const cap = state.caps.diff_cap_lines;
298
461
  console.log(JSON.stringify({ diff_lines: total, weighted_lines: weighted, cap, out_of_scope: outOfScope }));
299
462
  if (cap > 0 && weighted > cap) {
300
463
  fail(3, `diff-cap-exceeded: weighted ${weighted} > cap ${cap} (out-of-scope counts double)`);
@@ -328,7 +491,12 @@ function main() {
328
491
  state.status = STATUS;
329
492
  state.finished = nowIso();
330
493
  saveState(state);
331
- console.log(JSON.stringify({ status: state.status, pass: state.pass, history: state.history.length }));
494
+ console.log(JSON.stringify({
495
+ status: state.status,
496
+ pass: state.pass,
497
+ history: state.history.length,
498
+ cap_overrides: state.cap_overrides || [],
499
+ }));
332
500
  break;
333
501
  }
334
502
 
@@ -0,0 +1,357 @@
1
+ #!/usr/bin/env node
2
+ // somi-mcp.mjs — a zero-dependency stdio MCP server bundling scripts/lib/dispatch-resolver.mjs's
3
+ // resolveDispatch() as the `somi_resolve` tool, plus a command-procedure text reader as the
4
+ // `somi_command` tool and a skill-text reader as the `somi_skill` tool. Both Claude Code and
5
+ // Copilot CLI launch a plugin's bundled MCP server with its root already expanded
6
+ // (${CLAUDE_PLUGIN_ROOT} / ${PLUGIN_ROOT}), so a prompt calling these tools never needs to know
7
+ // where SoMi is installed — unlike scripts/somi-dispatch.mjs, which a prompt can only shell out to
8
+ // via a path it has to already know. That CLI stays the other consumer of the identical
9
+ // resolveDispatch() — this file's test harness and the fallback for a host with a shell but no
10
+ // MCP. Neither surface re-derives the composition or validation order. `somi_skill` exists for the
11
+ // identical reason `somi_command` does: a skill reference that's a relative link into SoMi's own
12
+ // install directory can't be followed from a consuming project, so its text is served over the
13
+ // same stdio channel instead.
14
+ //
15
+ // Hand-rolled, on purpose (zero dependencies — no MCP SDK): newline-delimited JSON-RPC 2.0 over
16
+ // stdio, one JSON object per line either direction, matching the MCP stdio transport's own framing
17
+ // rule. Nothing but JSON-RPC ever reaches stdout; every diagnostic goes to stderr, so a stray
18
+ // future console.log can never corrupt the wire format.
19
+ //
20
+ // Methods handled: `initialize`, `notifications/initialized`, `tools/list`, `tools/call`, `ping`.
21
+ // Anything else is a JSON-RPC method-not-found when it arrived as a request (has an `id`); an
22
+ // unrecognized NOTIFICATION (no `id`) is logged to stderr and dropped. Malformed JSON gets a parse
23
+ // error with `id: null` — the server keeps running; one bad line must never kill in-flight calls.
24
+
25
+ import { createInterface } from 'node:readline';
26
+ import fs from 'node:fs';
27
+ import path from 'node:path';
28
+ import { fileURLToPath } from 'node:url';
29
+ import {
30
+ resolveDispatch,
31
+ validateDispatchArgs,
32
+ AGENT_NAME_RE,
33
+ EXIT_USAGE,
34
+ EXIT_UNKNOWN_AGENT,
35
+ } from './lib/dispatch-resolver.mjs';
36
+ import { resolveProjectRoot } from './lib/mcp-project-root.mjs';
37
+
38
+ const PROG = 'somi-dispatch'; // shared identity with the CLI: this is the SAME resolver speaking.
39
+
40
+ // A small allowlist, not an echo of whatever `protocolVersion` the client sent -- that would be a
41
+ // promise this server never checked it can keep. `LATEST_PROTOCOL_VERSION` is the fallback.
42
+ const SUPPORTED_PROTOCOL_VERSIONS = Object.freeze(['2024-11-05', '2025-06-18']);
43
+ const LATEST_PROTOCOL_VERSION = '2025-06-18';
44
+
45
+ function installRoot() {
46
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
47
+ }
48
+
49
+ function serverVersion() {
50
+ try {
51
+ const pkg = JSON.parse(fs.readFileSync(path.join(installRoot(), 'package.json'), 'utf8'));
52
+ return typeof pkg.version === 'string' ? pkg.version : 'unknown';
53
+ } catch {
54
+ return 'unknown';
55
+ }
56
+ }
57
+
58
+ function log(msg) {
59
+ process.stderr.write(`somi-mcp: ${msg}\n`);
60
+ }
61
+
62
+ // --- JSON-RPC framing ----------------------------------------------------------------------
63
+
64
+ let nextOutgoingId = 1;
65
+ const pendingOutgoing = new Map(); // id -> {resolve, reject}
66
+ let clientCapabilities = {};
67
+
68
+ function writeMessage(obj) {
69
+ process.stdout.write(`${JSON.stringify(obj)}\n`);
70
+ }
71
+
72
+ function respond(id, result) {
73
+ writeMessage({ jsonrpc: '2.0', id, result });
74
+ }
75
+
76
+ function respondError(id, code, message) {
77
+ writeMessage({ jsonrpc: '2.0', id, error: { code, message } });
78
+ }
79
+
80
+ // Sends a request FROM this server TO the client (e.g. `roots/list`) and returns a promise for
81
+ // its result. Timed out rather than left to hang forever — a client that never declared (or
82
+ // never actually implements) `roots` would otherwise stall somi_resolve indefinitely.
83
+ function requestFromClient(method, params, timeoutMs = 2000) {
84
+ const id = `srv-${nextOutgoingId++}`;
85
+ return new Promise((resolve, reject) => {
86
+ const timer = setTimeout(() => {
87
+ pendingOutgoing.delete(id);
88
+ reject(new Error(`timed out waiting for the client's response to ${method}`));
89
+ }, timeoutMs);
90
+ pendingOutgoing.set(id, {
91
+ resolve: (v) => { clearTimeout(timer); resolve(v); },
92
+ reject: (e) => { clearTimeout(timer); reject(e); },
93
+ });
94
+ writeMessage({ jsonrpc: '2.0', id, method, params });
95
+ });
96
+ }
97
+
98
+ // Returns the RAW `uri` strings from the client's roots/list answer, unfiltered and undecoded —
99
+ // mcp-project-root.mjs owns deciding what counts as a usable root, so that logic lives in one
100
+ // place. Returns undefined when the client never declared `roots` at initialize, so its host-root
101
+ // lookup contributes nothing rather than attempting a round trip that was never going to answer.
102
+ async function listClientRoots() {
103
+ if (!clientCapabilities || !clientCapabilities.roots) return undefined;
104
+ const result = await requestFromClient('roots/list', {});
105
+ const roots = Array.isArray(result?.roots) ? result.roots : [];
106
+ return roots.map((r) => (typeof r?.uri === 'string' ? r.uri : null)).filter((u) => u !== null);
107
+ }
108
+
109
+ // --- tool definitions ------------------------------------------------------------------------
110
+
111
+ const TOOLS = [
112
+ {
113
+ name: 'somi_resolve',
114
+ description:
115
+ "Resolve one agent's dispatch tier and model against the current session ceiling — the " +
116
+ 'MCP-native equivalent of `node scripts/somi-dispatch.mjs resolve`. Same validation, same ' +
117
+ 'four-code failure family (64 usage / 65 unknown agent / 66 malformed cost: declaration / ' +
118
+ '67 project environment failure — including "no project root could be established": no ' +
119
+ 'CLAUDE_PROJECT_DIR, no usable MCP roots, and no project_dir given), reported in the tool ' +
120
+ 'result text on failure.',
121
+ inputSchema: {
122
+ type: 'object',
123
+ properties: {
124
+ agent: { type: 'string', description: 'agent name, e.g. "coder" (matches ^[a-z][a-z0-9-]*$)' },
125
+ host: { type: 'string', description: 'e.g. "claude-code" or "copilot"; defaults to "claude-code"' },
126
+ ceiling: {
127
+ type: 'string',
128
+ description:
129
+ 'one of low|medium|high. Sets and SAVES the session ceiling for every later dispatch ' +
130
+ 'in this project, not just this call — omit it unless the user actually asked to ' +
131
+ 'change the ceiling.',
132
+ },
133
+ project_dir: {
134
+ type: 'string',
135
+ description:
136
+ 'absolute path to the CONSUMING project (where .somi/ lives). Only needed when ' +
137
+ 'CLAUDE_PROJECT_DIR is unset and the client offers no MCP roots. When the host DOES ' +
138
+ 'supply a root, this must be that root or a directory inside it — narrows it, never ' +
139
+ 'overrides it; an outside value is refused (64), nothing read or written.',
140
+ },
141
+ },
142
+ required: ['agent'],
143
+ },
144
+ },
145
+ {
146
+ name: 'somi_command',
147
+ description:
148
+ "Read a SoMi command's own procedure text (commands/<name>.md) from the install root, so " +
149
+ 'a front door running in a consuming project can follow it live without knowing where SoMi ' +
150
+ 'is installed.',
151
+ inputSchema: {
152
+ type: 'object',
153
+ properties: {
154
+ name: { type: 'string', description: 'command name, e.g. "plan" (matches ^[a-z][a-z0-9-]*$)' },
155
+ },
156
+ required: ['name'],
157
+ },
158
+ },
159
+ {
160
+ name: 'somi_skill',
161
+ description:
162
+ "Read a SoMi skill's own text (skills/<name>/SKILL.md) from the install root — the same " +
163
+ 'problem `somi_command` solves for commands/, applied to skills/: a reference to a skill from ' +
164
+ "a consuming project can't rely on a relative link into SoMi's own install directory, since " +
165
+ "that directory generally isn't the consuming project's own tree. Read the dispatch " +
166
+ 'procedure this way (`somi_skill({name: "somi-dispatch"})`) whenever the skill can\'t be ' +
167
+ 'loaded by name on the current host (e.g. no Skill tool, or a non-Claude-Code host).',
168
+ inputSchema: {
169
+ type: 'object',
170
+ properties: {
171
+ name: { type: 'string', description: 'skill name, e.g. "somi-dispatch" (matches ^[a-z][a-z0-9-]*$)' },
172
+ },
173
+ required: ['name'],
174
+ },
175
+ },
176
+ ];
177
+
178
+ // --- tool implementations --------------------------------------------------------------------
179
+
180
+ function textResult(text, isError = false) {
181
+ return isError ? { content: [{ type: 'text', text }], isError: true } : { content: [{ type: 'text', text }] };
182
+ }
183
+
184
+ async function callSomiResolve(args) {
185
+ // Validated BEFORE the project-root lookup below (can be a 2s roots/list round trip). Raw args
186
+ // pass through unmodified -- validateDispatchArgs distinguishes "not given" (undefined) from
187
+ // "given but the wrong shape" (an array, an object, ''); silently coercing a wrong-shaped value
188
+ // to '' here, as an earlier version did, is exactly what let a bad host/ceiling default silently.
189
+ const validated = validateDispatchArgs({ agent: args?.agent, host: args?.host, ceiling: args?.ceiling });
190
+ if (!validated.ok) {
191
+ return textResult(`${PROG}: ${validated.message} (exit ${validated.code})`, true);
192
+ }
193
+
194
+ // project_dir passes through RAW too -- resolveProjectRoot's own validateDir() turns "not a
195
+ // string" into a clean 64, rather than this function quietly treating it as "not given".
196
+ const rootOutcome = await resolveProjectRoot({
197
+ projectDirArg: args?.project_dir,
198
+ listRoots: () => listClientRoots(),
199
+ });
200
+ if (!rootOutcome.ok) {
201
+ return textResult(`${PROG}: ${rootOutcome.message} (exit ${rootOutcome.code})`, true);
202
+ }
203
+
204
+ // agent/host/ceiling are already validated above; resolveDispatch re-runs the same cheap check.
205
+ const outcome = resolveDispatch({
206
+ agent: args.agent,
207
+ host: args.host,
208
+ ceiling: args.ceiling,
209
+ projectRoot: rootOutcome.root,
210
+ installRoot: installRoot(),
211
+ });
212
+
213
+ if (!outcome.ok) {
214
+ return textResult(`${PROG}: ${outcome.message} (exit ${outcome.code})`, true);
215
+ }
216
+ return textResult(JSON.stringify(outcome.result));
217
+ }
218
+
219
+ function callSomiCommand(args) {
220
+ const name = args?.name;
221
+ // JSON.stringify, not a bare template-literal interpolation -- an object-shaped `name` (e.g.
222
+ // `{toString: null}`) throws INSIDE `${name}`, which would surface as an unrelated internal
223
+ // error (-32603) instead of this 64.
224
+ if (typeof name !== 'string' || !AGENT_NAME_RE.test(name)) {
225
+ return textResult(`somi-command: invalid name ${JSON.stringify(name)} (expected ${AGENT_NAME_RE}) (exit ${EXIT_USAGE})`, true);
226
+ }
227
+ const cmdPath = path.join(installRoot(), 'commands', `${name}.md`);
228
+ let content;
229
+ try {
230
+ content = fs.readFileSync(cmdPath, 'utf8');
231
+ } catch (e) {
232
+ if (e.code === 'ENOENT') {
233
+ return textResult(`somi-command: unknown command "${name}" (no ${cmdPath}) (exit ${EXIT_UNKNOWN_AGENT})`, true);
234
+ }
235
+ throw e;
236
+ }
237
+ return textResult(content);
238
+ }
239
+
240
+ // Mirrors callSomiCommand exactly -- same allowlist regex, checked BEFORE the path is ever built,
241
+ // so a traversal payload (`../x`) is rejected by AGENT_NAME_RE (no `/`, no `.`) and never reaches
242
+ // path.join at all; only the two path segments (commands/ vs skills/.../SKILL.md) differ.
243
+ function callSomiSkill(args) {
244
+ const name = args?.name;
245
+ if (typeof name !== 'string' || !AGENT_NAME_RE.test(name)) {
246
+ return textResult(`somi-skill: invalid name ${JSON.stringify(name)} (expected ${AGENT_NAME_RE}) (exit ${EXIT_USAGE})`, true);
247
+ }
248
+ const skillPath = path.join(installRoot(), 'skills', name, 'SKILL.md');
249
+ let content;
250
+ try {
251
+ content = fs.readFileSync(skillPath, 'utf8');
252
+ } catch (e) {
253
+ if (e.code === 'ENOENT') {
254
+ return textResult(`somi-skill: unknown skill "${name}" (no ${skillPath}) (exit ${EXIT_UNKNOWN_AGENT})`, true);
255
+ }
256
+ throw e;
257
+ }
258
+ return textResult(content);
259
+ }
260
+
261
+ // Returns null for an unrecognized tool name — the caller turns that into a JSON-RPC error, since
262
+ // an unknown TOOL is the protocol failing to find it at all, distinct from a known tool that ran
263
+ // and failed (which reports isError:true in an otherwise-successful JSON-RPC response).
264
+ async function callTool(name, args) {
265
+ switch (name) {
266
+ case 'somi_resolve': return await callSomiResolve(args || {});
267
+ case 'somi_command': return callSomiCommand(args || {});
268
+ case 'somi_skill': return callSomiSkill(args || {});
269
+ default: return null;
270
+ }
271
+ }
272
+
273
+ // --- JSON-RPC method dispatch -----------------------------------------------------------------
274
+
275
+ async function handleRequest(id, method, params) {
276
+ switch (method) {
277
+ case 'initialize': {
278
+ clientCapabilities = params?.capabilities && typeof params.capabilities === 'object' ? params.capabilities : {};
279
+ // A version this server actually supports, never an echo of the client's request.
280
+ const requested = params?.protocolVersion;
281
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;
282
+ respond(id, {
283
+ protocolVersion,
284
+ capabilities: { tools: {} },
285
+ serverInfo: { name: 'somi', version: serverVersion() },
286
+ });
287
+ return;
288
+ }
289
+ case 'ping':
290
+ respond(id, {});
291
+ return;
292
+ case 'tools/list':
293
+ respond(id, { tools: TOOLS });
294
+ return;
295
+ case 'tools/call': {
296
+ const toolName = params?.name;
297
+ const result = await callTool(toolName, params?.arguments);
298
+ if (result === null) {
299
+ respondError(id, -32602, `Unknown tool: ${toolName}`);
300
+ return;
301
+ }
302
+ respond(id, result);
303
+ return;
304
+ }
305
+ default:
306
+ respondError(id, -32601, `Method not found: ${method}`);
307
+ }
308
+ }
309
+
310
+ function handleNotification(method) {
311
+ if (method === 'notifications/initialized') return; // nothing to do; acknowledged implicitly
312
+ log(`ignoring unrecognized notification: ${method}`);
313
+ }
314
+
315
+ function handleMessage(msg) {
316
+ if (msg === null || typeof msg !== 'object' || Array.isArray(msg)) {
317
+ respondError(null, -32600, 'Invalid Request');
318
+ return;
319
+ }
320
+ // A response TO one of our own outgoing requests (e.g. roots/list) carries no `method` — route
321
+ // it to the pending promise instead of treating it as an inbound request.
322
+ if (msg.method === undefined) {
323
+ if (msg.result !== undefined || msg.error !== undefined) {
324
+ const pending = pendingOutgoing.get(msg.id);
325
+ if (pending) {
326
+ pendingOutgoing.delete(msg.id);
327
+ if (msg.error) pending.reject(new Error(msg.error.message));
328
+ else pending.resolve(msg.result);
329
+ }
330
+ return;
331
+ }
332
+ respondError(msg.id ?? null, -32600, 'Invalid Request');
333
+ return;
334
+ }
335
+ if (msg.id === undefined) {
336
+ handleNotification(msg.method);
337
+ return;
338
+ }
339
+ handleRequest(msg.id, msg.method, msg.params).catch((e) => {
340
+ log(`error handling ${msg.method}: ${e.stack || e}`);
341
+ respondError(msg.id, -32603, `Internal error: ${e.message}`);
342
+ });
343
+ }
344
+
345
+ const rl = createInterface({ input: process.stdin, terminal: false });
346
+ rl.on('line', (line) => {
347
+ if (!line.trim()) return;
348
+ let msg;
349
+ try {
350
+ msg = JSON.parse(line);
351
+ } catch (e) {
352
+ respondError(null, -32700, `Parse error: ${e.message}`);
353
+ return;
354
+ }
355
+ handleMessage(msg);
356
+ });
357
+ rl.on('close', () => process.exit(0));