@skathio/somi 4.0.0 → 4.1.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 (163) hide show
  1. package/.claude/settings.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.copilot-extension/extension.json +1 -1
  5. package/.copilot-extension/marketplace.json +1 -1
  6. package/README.md +11 -5
  7. package/VERSION +1 -1
  8. package/agents/somi-coder.md +4 -228
  9. package/agents/somi-designer.md +4 -160
  10. package/agents/somi-discovery-analyst.md +4 -276
  11. package/agents/somi-flow.md +47 -0
  12. package/agents/somi-general.md +36 -0
  13. package/agents/somi-planner.md +4 -341
  14. package/agents/somi-reviewer.md +4 -199
  15. package/agents/somi.md +81 -253
  16. package/commands/adopt.md +6 -84
  17. package/commands/architecture-review.md +11 -86
  18. package/commands/atlas.md +10 -25
  19. package/commands/code-loop.md +10 -221
  20. package/commands/code-parallel.md +10 -151
  21. package/commands/code.md +9 -157
  22. package/commands/debug.md +9 -131
  23. package/commands/design.md +9 -160
  24. package/commands/discover.md +9 -194
  25. package/commands/impact.md +9 -25
  26. package/commands/incident.md +9 -39
  27. package/commands/plan-loop.md +9 -181
  28. package/commands/plan.md +9 -244
  29. package/commands/pr.md +10 -25
  30. package/commands/refactor-design.md +11 -89
  31. package/commands/refactor.md +11 -50
  32. package/commands/release-readiness.md +11 -70
  33. package/commands/review-panel.md +10 -141
  34. package/commands/review.md +11 -181
  35. package/commands/security-review.md +11 -75
  36. package/commands/ship-loop.md +9 -260
  37. package/commands/ship.md +9 -115
  38. package/commands/somi-config.md +12 -124
  39. package/commands/test-strategy.md +11 -75
  40. package/commands/upgrade.md +9 -72
  41. package/hooks/hooks.json +1 -1
  42. package/hooks/lib/common.mjs +15 -13
  43. package/hooks/pre-tool/block-dangerous-bash.mjs +1 -1
  44. package/hooks/pre-tool/block-secret-writes.mjs +5 -7
  45. package/hooks/pre-tool/guard-cost-lowering.mjs +26 -11
  46. package/hooks/pre-tool/guard-protected-paths.mjs +54 -34
  47. package/hooks/session-start/ensure-default-config.mjs +34 -42
  48. package/package.json +1 -1
  49. package/scripts/lib/config-files.mjs +145 -0
  50. package/scripts/lib/cost-ceiling.mjs +29 -22
  51. package/scripts/lib/cost-defaults.mjs +2 -0
  52. package/scripts/lib/escalation-facts.mjs +146 -0
  53. package/scripts/lib/escalation.mjs +129 -0
  54. package/scripts/lib/findings-ledger.mjs +241 -0
  55. package/scripts/lib/install-text.mjs +97 -0
  56. package/scripts/lib/loop-caps.mjs +140 -0
  57. package/scripts/lib/loop-diff.mjs +12 -70
  58. package/scripts/lib/loop-engine.mjs +226 -0
  59. package/scripts/lib/loop-escalate.mjs +49 -0
  60. package/scripts/lib/loop-exit.mjs +47 -0
  61. package/scripts/lib/loop-notes-compact.mjs +72 -0
  62. package/scripts/lib/loop-notes.mjs +278 -0
  63. package/scripts/lib/loop-review.mjs +355 -12
  64. package/scripts/lib/loop-state.mjs +44 -0
  65. package/scripts/lib/loop-step-close.mjs +75 -0
  66. package/scripts/lib/loop-step-kit.mjs +179 -0
  67. package/scripts/lib/loop-step-review.mjs +140 -0
  68. package/scripts/lib/loop-step-tool.mjs +89 -0
  69. package/scripts/lib/loop-step.mjs +301 -0
  70. package/scripts/lib/mcp-project-root.mjs +18 -7
  71. package/scripts/lib/path-facts.mjs +187 -0
  72. package/scripts/lib/path-safety.mjs +171 -0
  73. package/scripts/lib/run-card.mjs +73 -0
  74. package/scripts/size-budget-overrides.json +5 -13
  75. package/scripts/somi-card.mjs +39 -0
  76. package/scripts/somi-check.mjs +4 -3
  77. package/scripts/somi-config.mjs +113 -50
  78. package/scripts/somi-findings.mjs +56 -271
  79. package/scripts/somi-loop.mjs +77 -446
  80. package/scripts/somi-mcp.mjs +27 -96
  81. package/scripts/validate.sh +92 -54
  82. package/skills/flow-adopt/SKILL.md +92 -0
  83. package/skills/flow-architecture-review/SKILL.md +94 -0
  84. package/skills/flow-atlas/SKILL.md +34 -0
  85. package/skills/flow-code/SKILL.md +167 -0
  86. package/skills/flow-code-loop/SKILL.md +263 -0
  87. package/skills/flow-code-parallel/SKILL.md +160 -0
  88. package/skills/flow-debug/SKILL.md +141 -0
  89. package/skills/flow-design/SKILL.md +170 -0
  90. package/skills/flow-discover/SKILL.md +204 -0
  91. package/skills/flow-impact/SKILL.md +35 -0
  92. package/skills/flow-incident/SKILL.md +49 -0
  93. package/skills/flow-plan/SKILL.md +254 -0
  94. package/skills/flow-plan-loop/SKILL.md +254 -0
  95. package/skills/flow-pr/SKILL.md +34 -0
  96. package/skills/flow-refactor/SKILL.md +58 -0
  97. package/skills/flow-refactor-design/SKILL.md +97 -0
  98. package/skills/flow-release-readiness/SKILL.md +82 -0
  99. package/skills/flow-review/SKILL.md +193 -0
  100. package/skills/flow-review-panel/SKILL.md +154 -0
  101. package/skills/flow-security-review/SKILL.md +83 -0
  102. package/skills/flow-ship/SKILL.md +125 -0
  103. package/skills/flow-ship-loop/SKILL.md +274 -0
  104. package/skills/flow-somi-config/SKILL.md +142 -0
  105. package/skills/flow-status/SKILL.md +43 -0
  106. package/skills/flow-test-strategy/SKILL.md +83 -0
  107. package/skills/flow-upgrade/SKILL.md +82 -0
  108. package/skills/role-coder/SKILL.md +247 -0
  109. package/skills/role-designer/SKILL.md +172 -0
  110. package/skills/role-discovery-analyst/SKILL.md +288 -0
  111. package/skills/role-planner/SKILL.md +353 -0
  112. package/skills/role-reviewer/SKILL.md +218 -0
  113. package/skills/somi-checkpoint/SKILL.md +95 -0
  114. package/skills/somi-dispatch/SKILL.md +14 -14
  115. package/skills/somi-routing/SKILL.md +6 -2
  116. package/tests/hooks/cases/block-secret-writes.json +6 -1
  117. package/tests/hooks/cases/guard-protected-paths.json +44 -2
  118. package/tests/hooks/run.sh +21 -0
  119. package/tests/scripts/checkpoint-gate.sh +2 -2
  120. package/tests/scripts/cost-defaults.sh +2 -0
  121. package/tests/scripts/cost-hardcap.sh +26 -17
  122. package/tests/scripts/dispatch-line-gate.sh +4 -4
  123. package/tests/scripts/dispatch-reference-gate.sh +14 -14
  124. package/tests/scripts/ensure-default-config.sh +4 -4
  125. package/tests/scripts/escalation.sh +409 -0
  126. package/tests/scripts/eval-runner.sh +8 -7
  127. package/tests/scripts/fact-sheet.sh +296 -0
  128. package/tests/scripts/global-config.sh +167 -0
  129. package/tests/scripts/goldens/somi-loop.json +2 -2
  130. package/tests/scripts/lib/dispatch-reference-gate.mjs +14 -5
  131. package/tests/scripts/lib/escalation-facts-tests.mjs +140 -0
  132. package/tests/scripts/lib/escalation-tests.mjs +154 -0
  133. package/tests/scripts/lib/findings-ledger-tests.mjs +118 -0
  134. package/tests/scripts/lib/loop-engine-tests.mjs +287 -0
  135. package/tests/scripts/lib/loop-escalate-tests.mjs +356 -0
  136. package/tests/scripts/lib/loop-flow-gate.mjs +173 -0
  137. package/tests/scripts/lib/loop-notes-tests.mjs +371 -0
  138. package/tests/scripts/lib/loop-step-cli-tests.mjs +141 -0
  139. package/tests/scripts/lib/loop-step-close-tests.mjs +351 -0
  140. package/tests/scripts/lib/loop-step-lenient-tests.mjs +114 -0
  141. package/tests/scripts/lib/loop-step-state-tests.mjs +127 -0
  142. package/tests/scripts/lib/loop-step-tests.mjs +499 -0
  143. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +55 -0
  144. package/tests/scripts/lib/path-facts-tests.mjs +198 -0
  145. package/tests/scripts/lib/path-safety-tests.mjs +201 -0
  146. package/tests/scripts/lib/run-suites.mjs +139 -0
  147. package/tests/scripts/lib/site-roadmap-gate.mjs +64 -0
  148. package/tests/scripts/lib/sizing-score-tests.mjs +210 -0
  149. package/tests/scripts/lib/sizing-set-tests.mjs +131 -0
  150. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +226 -0
  151. package/tests/scripts/lib/somi-mcp-tests.mjs +21 -1
  152. package/tests/scripts/loop-engine.sh +22 -0
  153. package/tests/scripts/loop-flow-gate.sh +11 -0
  154. package/tests/scripts/review-panel-seats.sh +4 -4
  155. package/tests/scripts/run-card.sh +57 -0
  156. package/tests/scripts/run-suites.sh +74 -0
  157. package/tests/scripts/run.sh +11 -0
  158. package/tests/scripts/site-roadmap-gate.sh +76 -0
  159. package/tests/scripts/size-tier.sh +3 -3
  160. package/tests/scripts/somi-agent-dispatch-contract.sh +23 -3
  161. package/tests/scripts/somi-config.sh +9 -4
  162. package/tests/scripts/somi-mcp.sh +1 -0
  163. package/tests/scripts/suite-plan.json +20 -0
@@ -1,81 +1,32 @@
1
- // somi-loop.mjs — deterministic state engine for the bounded loops.
1
+ // somi-loop.mjs — command line of the deterministic state engine for the bounded loops: parses the arguments,
2
+ // calls the handler in lib/loop-engine.mjs and prints its result. No gate logic lives here.
2
3
  //
3
- // Zero-dependency: stdlib only (node:fs, node:path, node:child_process). No jq,
4
- // no bash. Behavior-preserving — exit codes and stdout JSON shapes are frozen
5
- // and reproduced exactly; see the bash original's header comment for the full
6
- // rationale (state survives session death, caps are SoMi's central safety
7
- // claim, etc).
4
+ // The gates live in lib/loop-engine.mjs, cap resolution (flag > env var > .somi/config.json > default) in
5
+ // lib/loop-caps.mjs, state in lib/loop-state.mjs, diff measurement in lib/loop-diff.mjs. Exit codes and stdout
6
+ // JSON shapes are frozen; callers branch on them: 0 ok, 2 max passes, 3 diff cap, 4 time budget, 5 circuit breaker
7
+ // (step after-review), 64 usage, 65 record-dispatch's resolver refused the agent, 70 internal error (step only).
8
8
  //
9
- // State: .somi/somi-state/loop/<slug>[.<iteration>].json under the project
10
- // root (project-local, gitignored by SoMi's conventions). Never committed.
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
- //
16
- // Cap precedence (matches the gate tables): CLI flag > env var > .somi/config.json
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.
27
- //
28
- // Exit codes (callers branch on these — do not repurpose):
29
- // 0 ok
30
- // 2 max-passes-exceeded (`pass` would exceed the cap)
31
- // 3 diff-cap-exceeded (`check-diff`: weighted lines over the cap;
32
- // out-of-scope lines count double)
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)
35
- //
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
9
+ // Subcommands (each prints one JSON object): run-start, init, resume, stats, pass, check-diff, review-scope,
10
+ // record-dispatch, record-pass, finish, and `step <open|after-code|after-review|close|status>`: the composite steps of
11
+ // lib/loop-step.mjs, arguments as `--flag value` (--findings and --fixed as JSON text, --reviewers comma-separated), the
12
+ // response on stdout as one JSON line, its `exit` as the exit code, nothing on stderr: the response carries every refusal
13
+ // (a bad flag included, exit 64), and an internal error (70) goes to <state dir>/step-errors.log, never to the stderr a model reads.
46
14
  //
47
15
  // Tested by tests/scripts/run.sh (wired into scripts/validate.sh / CI).
48
16
 
49
- import fs from 'node:fs';
50
17
  import path from 'node:path';
51
18
  import { execFileSync } from 'node:child_process';
52
19
  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
-
59
- const PROG = 'somi-loop';
60
-
61
- // Thrown to unwind to the top-level handler, which sets process.exitCode and
62
- // lets Node exit naturally — avoids process.exit()'s risk of truncating
63
- // buffered stdout/stderr writes on a pipe.
64
- class ExitSignal extends Error {
65
- constructor(code) {
66
- super(`exit ${code}`);
67
- this.code = code;
68
- }
69
- }
70
-
20
+ import { LoopExit, PROG, usageError } from './lib/loop-exit.mjs';
21
+ import { runStep } from './lib/loop-step.mjs';
22
+ import { base, clean, cut, stepLog } from './lib/loop-step-kit.mjs';
23
+ import { checkDiff, finish, init, pass, recordDispatch, recordPass, resume, reviewScope, runStart } from './lib/loop-engine.mjs';
24
+
25
+ // Unwinding with a LoopExit reaches the top-level handler, which writes its message to stderr and sets
26
+ // process.exitCode, letting Node exit naturally — avoids process.exit()'s risk of truncating buffered
27
+ // stdout/stderr writes on a pipe.
71
28
  function die(msg) {
72
- process.stderr.write(`${PROG}: ${msg}\n`);
73
- throw new ExitSignal(64);
74
- }
75
-
76
- function fail(code, msg) {
77
- process.stderr.write(`${msg}\n`);
78
- throw new ExitSignal(code);
29
+ throw usageError(msg);
79
30
  }
80
31
 
81
32
  function requireGit() {
@@ -92,404 +43,84 @@ function projectRoot() {
92
43
  return b;
93
44
  }
94
45
 
95
- function readConfig(root) {
96
- const cfgPath = path.join(root, '.somi', 'config.json');
97
- if (!fs.existsSync(cfgPath)) return {};
98
- try {
99
- return JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
100
- } catch {
101
- return {};
102
- }
46
+ // A handler's result: its one JSON object on stdout, its message on stderr, its code as the exit code.
47
+ function deliver(result, space) {
48
+ if (result.out !== undefined) console.log(JSON.stringify(result.out, null, space));
49
+ if (result.message) process.stderr.write(`${result.message}\n`);
50
+ process.exitCode = result.code;
103
51
  }
104
52
 
105
- function configVal(config, keys) {
106
- let cur = config;
107
- for (const k of keys) {
108
- if (cur === undefined || cur === null) return undefined;
109
- cur = cur[k];
110
- }
111
- return cur === null ? undefined : cur;
112
- }
113
-
114
- // Mirrors bash's `${a:-${b:-$c}}` — first arg that is neither unset nor an
115
- // empty string wins (a numeric 0 counts as "set", matching bash treating the
116
- // non-empty string "0" as set).
117
- function firstDefined(...vals) {
118
- for (const v of vals) {
119
- if (v === undefined || v === null) continue;
120
- if (typeof v === 'string' && v === '') continue;
121
- return v;
122
- }
123
- return undefined;
124
- }
125
-
126
- function nowIso() {
127
- // `date -u +%Y-%m-%dT%H:%M:%SZ` — no milliseconds.
128
- return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
129
- }
130
-
131
- // --- mid-loop cap re-resolution --------------------------------------------
132
- // `init` resolves caps once (CLI flag > env var > .somi/config.json > default) and
133
- // freezes them into state -- deliberately, so the diff baseline and pass history stay
134
- // stable across a whole loop. But commands/code-loop.md's Guardrails document a
135
- // remedy for a gate that's wrong for the work at hand: "the user adjusts the env var
136
- // explicitly and re-runs -- the loop does not 'decide' to widen its own bounds." That
137
- // remedy needs a path that re-reads the override on the SAME subcommand (`pass`,
138
- // `check-diff`), without `init --force` (which discards `pass`/`history`).
139
- //
140
- // `pass` and `check-diff` call reresolveCap() below before their gate check.
141
- // Precedence matches what's documented: CLI flag > env var > .somi/config.json >
142
- // default -- an explicit CLI flag or env var THIS invocation is the only thing that
143
- // can move the cap; absent one, the cap already in force for the loop stands (a
144
- // `.somi/config.json` edit made while a loop is running must NOT silently reopen an
145
- // already-resolved gate). A resolved value that differs from what's stored is
146
- // persisted into `caps` immediately, with an entry appended to a `cap_overrides`
147
- // audit trail (field, from, to, source, after_pass, at) -- the after-the-fact record
148
- // the documented remedy needs, since the env var itself lives only in a shell that
149
- // may since have exited. `cap_overrides` is created lazily, only on the first real
150
- // override, so a loop that never overrides anything keeps exactly today's state
151
- // shape (no golden-fixture regeneration forced by this fix). `baseline_sha`,
152
- // `started`, `pass`, and `history` are never touched here.
153
- //
154
- // Every value that reaches `Number()` on this path is user input (a CLI flag, an env
155
- // var, or a config value) and is validated before use: `Number()` on a malformed
156
- // string (`"1,000"`, `"unlimited"`) yields NaN, which is false against BOTH gate
157
- // comparisons (`cur + 1 > max`, `weighted > cap`) -- silently switching the gate off
158
- // -- and `JSON.stringify` then persists that NaN as `null`, which the next bare call
159
- // falls through past (via `firstDefined`) to re-arm at the default, with no
160
- // `cap_overrides` entry recording the reversion. `validateCap()` rejects rather than
161
- // coerces, so a malformed value dies loudly instead of disabling a gate.
162
- const CAP_ENV = {
163
- code: { max_passes: 'SOMI_CODE_LOOP_MAX_PASSES', diff_cap_lines: 'SOMI_CODE_LOOP_DIFF_CAP' },
164
- plan: { max_passes: 'SOMI_PLAN_LOOP_MAX_PASSES' },
53
+ // subcommand -> handler, and the JSON indent where it is not the compact default (`stats` is read by people).
54
+ const COMMANDS = {
55
+ 'run-start': { handler: runStart }, init: { handler: init }, resume: { handler: resume }, stats: { handler: resume, space: 2 },
56
+ pass: { handler: pass }, 'check-diff': { handler: checkDiff }, 'review-scope': { handler: reviewScope },
57
+ 'record-dispatch': { handler: recordDispatch }, 'record-pass': { handler: recordPass }, finish: { handler: finish },
165
58
  };
166
- const CAP_FLAG = { max_passes: '--max-passes', diff_cap_lines: '--diff-cap' };
167
- const CAP_CONFIG_SECTION = { code: 'code_loop', plan: 'plan_loop' };
168
- const CAP_DEFAULT = { max_passes: 3, diff_cap_lines: 400 };
169
-
170
- // Rejects a malformed cap value rather than letting `Number()` coerce it to NaN.
171
- // `label` names the source in the error so `die()`'s message points at what to fix
172
- // (a specific flag, env var, or the generic field name at `init`, where the value
173
- // may have come from any of CLI/env/config).
174
- function validateCap(raw, label) {
175
- const n = Number(raw);
176
- if (!Number.isInteger(n) || n < 0) {
177
- die(`${label}: expected a non-negative integer, got "${raw}"`);
59
+ const STEP_FLAGS = ['slug', 'loop', 'iteration', 'files', 'host', 'max-passes', 'diff-cap', 'agent', 'review-mode', 'review-scope', 'reviewers', 'verdict', 'blockers', 'majors', 'findings', 'review', 'fixed', 'status'];
60
+ // The step's arguments from `--flag value` pairs, as runStep takes them. A flag it does not know, a repeated one or one without a value is a usage error (echoed cut and cleaned).
61
+ function stepArgs(argv) {
62
+ const args = { step: argv[0] };
63
+ for (let i = 1; i < argv.length; i += 2) {
64
+ const key = argv[i].replace(/^--/, '');
65
+ if (!argv[i].startsWith('--') || !STEP_FLAGS.includes(key) || argv[i + 1] === undefined) die(`unknown argument or missing value: ${cut(argv[i], 40)}`);
66
+ if (Object.hasOwn(args, key.replaceAll('-', '_'))) die(`repeated argument: ${cut(argv[i], 40)}`);
67
+ args[key.replaceAll('-', '_')] = argv[i + 1];
178
68
  }
179
- return n;
69
+ for (const k of ['findings', 'fixed']) if (args[k] !== undefined) { try { args[k] = JSON.parse(args[k]); } catch { die(`--${k} expects JSON text`); } }
70
+ if (args.reviewers !== undefined) args.reviewers = args.reviewers.split(',');
71
+ return args;
180
72
  }
181
73
 
182
- // Resolves one cap at `init`, reading the same CAP_ENV / CAP_CONFIG_SECTION /
183
- // CAP_DEFAULT tables reresolveCap() uses, so the two paths cannot silently diverge
184
- // on an env var name, a config key, or a default value.
185
- function resolveInitCap(config, family, field, argVal) {
186
- if (field === 'diff_cap_lines' && family === 'plan') return 0; // plan loops have no diff cap
187
- const envVar = CAP_ENV[family][field];
188
- const fromConfig = configVal(config, [CAP_CONFIG_SECTION[family], field]);
189
- const picked = firstDefined(argVal, process.env[envVar], fromConfig, CAP_DEFAULT[field]);
190
- return validateCap(picked, field);
191
- }
74
+ const FLAGS = {
75
+ '--slug': 'slug', '--loop': 'loop', '--iteration': 'iteration', '--files': 'files', '--max-passes': 'maxPasses',
76
+ '--diff-cap': 'diffCap', '--severity-floor': 'severity', '--verdict': 'verdict', '--blockers': 'blockers',
77
+ '--majors': 'majors', '--status': 'status', '--agent': 'agent', '--host': 'host', '--max-minutes': 'maxMinutes',
78
+ };
192
79
 
193
- function reresolveCap(state, field, argVal) {
194
- const family = state.loop === 'plan' ? 'plan' : 'code';
195
- if (field === 'diff_cap_lines' && family === 'plan') {
196
- return { resolved: 0, override: null }; // plan loops have no diff cap (see `init`)
197
- }
198
- const envVar = CAP_ENV[family][field];
199
- const stored = state.caps[field];
200
- const explicit = firstDefined(argVal, process.env[envVar]);
201
- const isCli = argVal !== undefined && argVal !== '';
202
- const resolved = explicit === undefined
203
- ? stored
204
- : validateCap(explicit, isCli ? CAP_FLAG[field] : envVar);
205
- let override = null;
206
- if (explicit !== undefined && resolved !== stored) {
207
- override = {
208
- field,
209
- from: stored,
210
- to: resolved,
211
- source: isCli ? 'cli' : 'env',
212
- after_pass: state.pass,
213
- at: nowIso(),
214
- };
80
+ function step(argv) {
81
+ const root = projectRoot();
82
+ const explicit = Boolean(process.env.SOMI_LOOP_STATE_DIR);
83
+ const stateDir = process.env.SOMI_LOOP_STATE_DIR || path.join(root, '.somi', 'somi-state', 'loop');
84
+ const installRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
85
+ let resp;
86
+ try {
87
+ resp = runStep({ root, env: process.env, stateDir, installRoot, via: 'cli', log: stepLog(root, stateDir, explicit) }, stepArgs(argv));
88
+ } catch (e) { // a flag the parser refuses answers like any other refusal of a step: the response on stdout
89
+ if (!(e instanceof LoopExit)) throw e;
90
+ resp = base(clean(argv[0] ?? '', 20) || null, { ok: false, exit: e.code, error: clean(e.message.replace(`${PROG}: `, ''), 300) });
215
91
  }
216
- return { resolved, override };
217
- }
218
-
219
- // Mutates `state.caps[field]` and appends the audit entry. Caller still owns calling
220
- // saveState() -- kept separate so `pass`/`check-diff` persist the override BEFORE
221
- // their gate check can throw, not only on the success path.
222
- function applyCapOverride(state, override) {
223
- state.caps[override.field] = override.to;
224
- if (!Array.isArray(state.cap_overrides)) state.cap_overrides = [];
225
- state.cap_overrides.push(override);
92
+ deliver({ out: resp, code: resp.exit }, undefined);
226
93
  }
227
94
 
228
95
  function main() {
229
96
  requireGit();
230
97
 
231
- const root = projectRoot();
232
- const STATE_DIR = process.env.SOMI_LOOP_STATE_DIR || path.join(root, '.somi', 'somi-state', 'loop');
233
-
234
- // --- argument parsing (shared) ---------------------------------------------
235
- const argv = process.argv.slice(2);
236
- const CMD = argv[0] || '';
237
- let rest = argv.slice(1);
238
-
239
- let SLUG = '';
240
- let LOOP = 'code';
241
- let ITERATION = '';
242
- let FILES = '';
243
- let VERDICT = '';
244
- let BLOCKERS = '0';
245
- let MAJORS = '0';
246
- let STATUS = '';
247
- let AGENT = '';
248
- let HOST;
249
- let ARG_MAX_MINUTES = '';
250
- let FORCE = false;
251
- let ARG_MAX_PASSES = '';
252
- let ARG_DIFF_CAP = '';
253
- let ARG_SEVERITY = '';
254
-
255
- while (rest.length > 0) {
256
- const a = rest[0];
257
- switch (a) {
258
- case '--slug': SLUG = rest[1]; rest = rest.slice(2); break;
259
- case '--loop': LOOP = rest[1]; rest = rest.slice(2); break;
260
- case '--iteration': ITERATION = rest[1]; rest = rest.slice(2); break;
261
- case '--files': FILES = rest[1]; rest = rest.slice(2); break;
262
- case '--max-passes': ARG_MAX_PASSES = rest[1]; rest = rest.slice(2); break;
263
- case '--diff-cap': ARG_DIFF_CAP = rest[1]; rest = rest.slice(2); break;
264
- case '--severity-floor': ARG_SEVERITY = rest[1]; rest = rest.slice(2); break;
265
- case '--verdict': VERDICT = rest[1]; rest = rest.slice(2); break;
266
- case '--blockers': BLOCKERS = rest[1]; rest = rest.slice(2); break;
267
- case '--majors': MAJORS = rest[1]; rest = rest.slice(2); break;
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;
272
- case '--force': FORCE = true; rest = rest.slice(1); break;
273
- default: die(`unknown argument: ${a}`);
274
- }
275
- }
276
-
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> …');
278
- if (!SLUG) die('--slug is required');
279
-
280
- function stateFile() {
281
- let name = SLUG;
282
- if (ITERATION) name = `${SLUG}.${ITERATION}`;
283
- return path.join(STATE_DIR, `${name}.json`);
98
+ const cmd = process.argv[2] || '';
99
+ if (cmd === 'step') return step(process.argv.slice(3));
100
+ const args = { slug: '', loop: 'code', iteration: '', files: '', verdict: '', blockers: '0', majors: '0', status: '', agent: '', host: undefined, maxMinutes: '', force: false, maxPasses: '', diffCap: '', severity: '' };
101
+ for (let rest = process.argv.slice(3); rest.length > 0;) {
102
+ if (rest[0] === '--force') { args.force = true; rest = rest.slice(1); continue; }
103
+ if (!Object.hasOwn(FLAGS, rest[0])) die(`unknown argument: ${cut(rest[0], 40)}`);
104
+ args[FLAGS[rest[0]]] = rest[1];
105
+ rest = rest.slice(2);
284
106
  }
285
- const SF = stateFile();
286
-
287
- function requireState() {
288
- if (!fs.existsSync(SF)) die(`no loop state at ${SF} — run init first`);
289
- }
290
-
291
- function loadState() {
292
- return JSON.parse(fs.readFileSync(SF, 'utf8'));
293
- }
294
-
295
- function saveState(state) {
296
- fs.writeFileSync(SF, JSON.stringify(state));
297
- }
298
-
299
- const RUN_ROOT = path.dirname(STATE_DIR);
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
107
 
309
- case 'init': {
310
- fs.mkdirSync(STATE_DIR, { recursive: true });
311
- if (fs.existsSync(SF) && !FORCE) {
312
- let status;
313
- try {
314
- status = JSON.parse(fs.readFileSync(SF, 'utf8')).status;
315
- } catch {
316
- status = undefined;
317
- }
318
- if (status === 'running') {
319
- die(`loop state already running at ${SF} — use 'resume' to continue it, or 'init --force' to discard`);
320
- }
321
- }
108
+ if (!cmd) die('usage: somi-loop.mjs <run-start|init|resume|pass|check-diff|review-scope|record-dispatch|record-pass|finish|stats> --slug <slug> …, or step <name> …');
109
+ if (!args.slug) die('--slug is required');
110
+ if (!Object.hasOwn(COMMANDS, cmd)) die(`unknown subcommand: ${cut(cmd, 40)}`);
322
111
 
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
-
331
- // Cap resolution: CLI > env > config > default (per loop type), through the
332
- // same CAP_ENV / CAP_CONFIG_SECTION / CAP_DEFAULT tables reresolveCap() uses,
333
- // and validated the same way -- a malformed value dies here rather than
334
- // silently resolving to a fail-open NaN/null.
335
- const config = readConfig(root);
336
- let maxPasses;
337
- let diffCap;
338
- let sevFloor;
339
- if (LOOP === 'plan') {
340
- maxPasses = resolveInitCap(config, 'plan', 'max_passes', ARG_MAX_PASSES);
341
- sevFloor = firstDefined(ARG_SEVERITY, process.env.SOMI_PLAN_LOOP_SEVERITY_FLOOR, configVal(config, ['plan_loop', 'severity_floor']));
342
- diffCap = 0; // plan loops have no diff cap
343
- } else {
344
- maxPasses = resolveInitCap(config, 'code', 'max_passes', ARG_MAX_PASSES);
345
- sevFloor = firstDefined(ARG_SEVERITY, process.env.SOMI_CODE_LOOP_SEVERITY_FLOOR, configVal(config, ['code_loop', 'severity_floor']));
346
- diffCap = resolveInitCap(config, 'code', 'diff_cap_lines', ARG_DIFF_CAP);
347
- }
348
- sevFloor = firstDefined(sevFloor, 'Major');
349
-
350
- let baseline;
351
- try {
352
- baseline = execFileSync('git', ['-C', root, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
353
- } catch {
354
- die('cannot resolve HEAD');
355
- }
356
-
357
- const filesJson = FILES.split(' ').filter((s) => s.length > 0);
358
-
359
- const state = {
360
- slug: SLUG,
361
- loop: LOOP,
362
- iteration: ITERATION,
363
- baseline_sha: baseline,
364
- started: nowIso(),
365
- status: 'running',
366
- caps: { max_passes: maxPasses, diff_cap_lines: diffCap, severity_floor: sevFloor },
367
- iteration_files: filesJson,
368
- pass: 0,
369
- history: [],
370
- };
371
- if (LOOP === 'code') state.review_min = reviewMinFor(root, SLUG) ?? undefined; // undefined: not serialised
372
- saveState(state);
373
- console.log(JSON.stringify({ baseline_sha: state.baseline_sha, caps: state.caps, state_file: SF, ...(state.review_min ? { review_min: state.review_min } : {}) }));
374
- break;
375
- }
376
-
377
- case 'resume': {
378
- requireState();
379
- console.log(JSON.stringify(loadState()));
380
- break;
381
- }
382
-
383
- case 'pass': {
384
- requireState();
385
- const state = loadState();
386
- const { resolved: max, override } = reresolveCap(state, 'max_passes', ARG_MAX_PASSES);
387
- if (override) {
388
- applyCapOverride(state, override);
389
- saveState(state); // persist the raise even if the gate below still fails
390
- }
391
- const cur = state.pass;
392
- if (cur + 1 > max) {
393
- fail(2, `max-passes-exceeded: pass ${cur + 1} > cap ${max}`);
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`);
397
- state.pass = cur + 1;
398
- saveState(state);
399
- console.log(JSON.stringify({ pass: state.pass, max_passes: max, ...(state.review_min ? { review_min: state.review_min } : {}) }));
400
- break;
401
- }
402
-
403
- case 'check-diff': {
404
- requireState();
405
- const state = loadState();
406
- const { resolved: cap, override } = reresolveCap(state, 'diff_cap_lines', ARG_DIFF_CAP);
407
- if (override) {
408
- applyCapOverride(state, override);
409
- saveState(state); // persist the raise even if the gate below still fails
410
- }
411
- const { total, weighted, outOfScope } = computeDiff(root, state.baseline_sha, state.iteration_files);
412
- console.log(JSON.stringify({ diff_lines: total, weighted_lines: weighted, cap, out_of_scope: outOfScope }));
413
- if (cap > 0 && weighted > cap) {
414
- fail(3, `diff-cap-exceeded: weighted ${weighted} > cap ${cap} (out-of-scope counts double)`);
415
- }
416
- break;
417
- }
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
-
441
- case 'record-pass': {
442
- requireState();
443
- if (!VERDICT) die('record-pass requires --verdict');
444
- const state = loadState();
445
- const { total } = computeDiff(root, state.baseline_sha, state.iteration_files);
446
- const entry = {
447
- pass: state.pass,
448
- verdict: VERDICT,
449
- blockers: Number(BLOCKERS),
450
- majors: Number(MAJORS),
451
- diff_lines: total,
452
- tree: snapshotTree(root) ?? undefined, // the reviewed tree: the next pass's delta starts here
453
- at: nowIso(),
454
- };
455
- state.history.push(entry);
456
- saveState(state);
457
- console.log(JSON.stringify(state.history[state.history.length - 1]));
458
- break;
459
- }
460
-
461
- case 'finish': {
462
- requireState();
463
- if (!STATUS) die('finish requires --status');
464
- const state = loadState();
465
- state.status = STATUS;
466
- state.finished = nowIso();
467
- saveState(state);
468
- console.log(JSON.stringify({
469
- status: state.status,
470
- pass: state.pass,
471
- history: state.history.length,
472
- cap_overrides: state.cap_overrides || [],
473
- ...(state.dispatches ? { dispatches: state.dispatches } : {}),
474
- }));
475
- break;
476
- }
477
-
478
- case 'stats': {
479
- requireState();
480
- console.log(JSON.stringify(loadState(), null, 2));
481
- break;
482
- }
483
-
484
- default:
485
- die(`unknown subcommand: ${CMD}`);
486
- }
112
+ const root = projectRoot();
113
+ const stateDir = process.env.SOMI_LOOP_STATE_DIR || path.join(root, '.somi', 'somi-state', 'loop');
114
+ const installRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
115
+ const { handler, space } = COMMANDS[cmd];
116
+ deliver(handler({ root, env: process.env, stateDir, installRoot }, args), space);
487
117
  }
488
118
 
489
119
  try {
490
120
  main();
491
121
  } catch (e) {
492
- if (e instanceof ExitSignal) {
122
+ if (e instanceof LoopExit) {
123
+ process.stderr.write(`${e.message}\n`);
493
124
  process.exitCode = e.code;
494
125
  } else {
495
126
  throw e;