@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
@@ -0,0 +1,241 @@
1
+ // findings-ledger.mjs -- the findings ledger: identity, the ledger file and every handler (record, resolve,
2
+ // reopen, open, get). Each returns `{lines, code, message}`. Nothing here
3
+ // reads the process environment, stdin or argv, and nothing prints: the caller (somi-findings.mjs today, a tool
4
+ // later) hands in the project root and already-parsed arguments, and gets back the lines to print, an exit code
5
+ // and the stderr text. The stdin read and the JSON parse stay at the CLI, the trust boundary of the shell path.
6
+ //
7
+ // Ledger: .somi/reviews/<slug>/findings.json under the root. Locus matching: same file + same symbol
8
+ // (case-insensitive) + same normalized title (lowercased, non-alphanumerics collapsed, first 8 words); line
9
+ // numbers are deliberately NOT part of the locus, lines drift between passes. Exit codes: 0 ok, 5 consecutive
10
+ // recurrence detected, 64 bad input.
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { randomBytes } from 'node:crypto';
15
+ import { EXIT_CIRCUIT_BREAKER } from './loop-exit.mjs';
16
+
17
+ export const PROG = 'somi-findings';
18
+
19
+ export function ledgerPaths(root, slug) {
20
+ const dir = path.join(root, '.somi', 'reviews', slug);
21
+ return { dir, file: path.join(dir, 'findings.json') };
22
+ }
23
+
24
+ function nowDateUtc() {
25
+ // `date -u +%Y-%m-%d` — bare date, no time component (findings' seen[].date).
26
+ return new Date().toISOString().slice(0, 10);
27
+ }
28
+
29
+ // Mirrors jq's `//` alternative operator at the JSON-value level: substitutes the
30
+ // fallback only when the left side is `null`/missing or `false` — NOT for other
31
+ // falsy values like `""` or `0`, which jq treats as present. Used wherever the bash
32
+ // script keeps a raw JSON value (locus/severity/confidence on a newly created finding).
33
+ function orElse(v, fallback) {
34
+ return v === null || v === undefined || v === false ? fallback : v;
35
+ }
36
+
37
+ // Mirrors `jq -r '<expr> // empty'` captured into a bash variable: same null/false
38
+ // substitution as orElse, then stringified (bash captures everything as text) — used
39
+ // wherever the bash script tests `[[ -n "$var" ]]` or concatenates into the locus key.
40
+ function rawStr(v) {
41
+ const x = orElse(v, '');
42
+ return x === '' ? '' : String(x);
43
+ }
44
+
45
+ // normalize_title() — bash pipeline: `tr '[:upper:]' '[:lower:]'` (byte-wise, ASCII-only —
46
+ // it only maps the 26 ASCII uppercase bytes; any multi-byte UTF-8 sequence passes through
47
+ // untouched) -> `tr -cs 'a-z0-9' ' '` (every maximal run of non-alphanumerics — including a
48
+ // leading or trailing run — collapses to ONE space; this is what then eats those untouched
49
+ // UTF-8 bytes) -> awk takes fields 1-8 (awk's default field-splitting ignores leading/
50
+ // trailing whitespace and splits on whitespace runs). By the time the tr step is done,
51
+ // the only characters left in the string are lowercase alphanumerics and single-space
52
+ // separators (with at most one leading and one trailing space) — so the awk step's only
53
+ // remaining job is to drop that leading/trailing space and truncate to 8 fields, which
54
+ // is exactly what trim + split + slice does below — PROVIDED the lowercasing step is also
55
+ // byte-wise ASCII-only. JS's `String.prototype.toLowerCase()` is Unicode-aware (e.g. U+0130
56
+ // İ -> "i" + combining dot above), which can *introduce* a fresh ASCII letter that bash's
57
+ // byte-wise `tr` would never produce (bash leaves İ's UTF-8 bytes alone; the following
58
+ // `tr -cs 'a-z0-9' ' '` step then discards all of them as non-alphanumeric). So the
59
+ // lowercasing below only maps `A`-`Z`, mirroring `tr '[:upper:]' '[:lower:]'` exactly.
60
+ // Verified against six normalize_title edge-case goldens (empty,
61
+ // single-word, >8-word, leading/trailing whitespace, multi-space, punctuation) plus
62
+ // adversarial Unicode probes (café, İstanbul).
63
+ export function normalizeTitle(title) {
64
+ const lowered = title.replace(/[A-Z]/g, (c) => c.toLowerCase());
65
+ const squeezed = lowered.replace(/[^a-z0-9]+/g, ' ').trim();
66
+ if (squeezed === '') return '';
67
+ return squeezed.split(/\s+/).slice(0, 8).join(' ');
68
+ }
69
+
70
+ // The locus a finding is matched on. ASCII-only lowercase of the symbol, same reasoning as normalizeTitle: bash uses
71
+ // byte-wise `tr '[:upper:]' '[:lower:]'`.
72
+ export function locusKey(f) {
73
+ return `${rawStr(f.file)}|${rawStr(f.symbol).replace(/[A-Z]/g, (c) => c.toLowerCase())}|${normalizeTitle(rawStr(f.title))}`;
74
+ }
75
+
76
+ function ensureLedger(ledgerDir, ledgerPath) {
77
+ fs.mkdirSync(ledgerDir, { recursive: true });
78
+ if (!fs.existsSync(ledgerPath)) {
79
+ // Byte-for-byte the bash seed: `printf '{"next_id": 1, "findings": []}\n' > "$LEDGER"` —
80
+ // a literal, NOT jq output (note the space after each colon but no other jq-pretty
81
+ // formatting). Immediately superseded by the jq-pretty form on the first record/resolve/
82
+ // reopen that touches this ledger; only matters at rest if `open`/`get` is called first.
83
+ try { fs.writeFileSync(ledgerPath, '{"next_id": 1, "findings": []}\n', { flag: 'wx' }); } catch (e) { if (e.code !== 'EEXIST') throw e; } // exclusive: nothing is created through a link at the name; a first touch that lost a race is fine
84
+ }
85
+ }
86
+
87
+ function loadLedger(ledgerPath) {
88
+ return JSON.parse(fs.readFileSync(ledgerPath, 'utf8'));
89
+ }
90
+
91
+ // A killed write leaves its random temp file behind. Once a save has landed, a regular file of that shape untouched for an
92
+ // hour (no live writer holds one that long) is removed; a link, a younger file and any other name are left alone.
93
+ const STALE_TMP_MS = 60 * 60 * 1000;
94
+ function sweepTmp(dir) {
95
+ try {
96
+ for (const f of fs.readdirSync(dir)) {
97
+ const st = /^findings\.json\.[0-9a-f]{12}\.tmp$/.test(f) ? fs.lstatSync(path.join(dir, f)) : null;
98
+ if (st?.isFile() && Date.now() - st.mtimeMs > STALE_TMP_MS) fs.rmSync(path.join(dir, f), { force: true });
99
+ }
100
+ } catch { /* housekeeping only: the save has already landed */ }
101
+ }
102
+
103
+ function saveLedger(ledgerPath, ledger) {
104
+ // Mirror bash's `tmp="$(mktemp)"; jq ... "$LEDGER" > "$tmp" && mv "$tmp" "$LEDGER"`:
105
+ // pretty 2-space + trailing newline (jq's default pretty-print, verified byte-identical
106
+ // against JSON.stringify(ledger, null, 2) + '\n'), written to a temp file in
107
+ // the SAME directory as the target and renamed into place so the write is atomic and the
108
+ // rename never crosses a filesystem boundary.
109
+ // The temp name is random and created exclusively ('wx'), so a link planted at a guessable name is never followed.
110
+ const tmpPath = `${ledgerPath}.${randomBytes(6).toString('hex')}.tmp`;
111
+ try {
112
+ fs.writeFileSync(tmpPath, JSON.stringify(ledger, null, 2) + '\n', { flag: 'wx' });
113
+ fs.renameSync(tmpPath, ledgerPath);
114
+ sweepTmp(path.dirname(ledgerPath));
115
+ } catch (e) {
116
+ fs.rmSync(tmpPath, { force: true });
117
+ throw e;
118
+ }
119
+ }
120
+
121
+ // A finding is recordable when it names a file and a title.
122
+ function firstUnrecordable(input) {
123
+ return input.findIndex((f) => !rawStr(f?.file) || !rawStr(f?.title));
124
+ }
125
+
126
+ // Upserts each finding of `input` (an already-parsed array) into the ledger: a new locus becomes F-<n>, a known
127
+ // OPEN locus gets a sighting appended. `lines` is one JSON line per finding; `code` is 5 if ANY finding recurred
128
+ // in consecutive passes (judged after all are processed). Every element is validated before the ledger is
129
+ // touched: a malformed one returns 64 and writes nothing, not even the empty ledger. `dedupe` (a step that may be
130
+ // replayed) skips a sighting the same review, run and pass already holds on a known locus; so two findings of one
131
+ // locus in one batch leave a single sighting.
132
+ export function recordFindings({ root, slug, review, run, pass, input, now = nowDateUtc, dedupe = false }) {
133
+ const bad = firstUnrecordable(input);
134
+ if (bad !== -1) return { lines: [], code: 64, message: `${PROG}: finding ${bad} needs at least {file, title}` };
135
+
136
+ const { dir, file } = ledgerPaths(root, slug);
137
+ ensureLedger(dir, file);
138
+ const ledger = loadLedger(file);
139
+ const date = now();
140
+ const lines = [];
141
+ let breaker = false;
142
+
143
+ for (const f of input.map((x) => x ?? {})) {
144
+ const key = locusKey(f);
145
+ const sighting = { review, run, pass, date };
146
+
147
+ // Known open locus: recurrence is classified BEFORE the sighting is appended.
148
+ const existing = ledger.findings.find((x) => x.key === key && x.status === 'open');
149
+ if (existing) {
150
+ const recurringConsecutive = existing.seen.some((s) => s.run === run && s.pass === pass - 1);
151
+ const recurringCross = existing.seen.some((s) => s.run !== run);
152
+ const raised = canonSeverity(f.severity); // a re-sighting at a stronger severity raises it (and says so on the sighting), never lowers it
153
+ if (SEVERITIES.includes(raised) && SEVERITIES.indexOf(raised) < SEVERITIES.indexOf(existing.severity)) existing.severity = sighting.severity = raised;
154
+ if (!(dedupe && existing.seen.some((s) => s.review === review && s.run === run && s.pass === pass))) existing.seen.push(sighting); // dedupe: a replayed call adds no second sighting
155
+ if (recurringConsecutive) breaker = true;
156
+ lines.push(JSON.stringify({ id: existing.id, state: 'known', recurring_consecutive: recurringConsecutive, recurring_cross_run: recurringCross }));
157
+ } else {
158
+ const id = `F-${ledger.next_id}`;
159
+ ledger.next_id += 1;
160
+ ledger.findings.push({
161
+ id,
162
+ key,
163
+ locus: { file: f.file, symbol: orElse(f.symbol, '') },
164
+ title: f.title,
165
+ severity: canonSeverity(orElse(f.severity, 'Minor')),
166
+ confidence: orElse(f.confidence, 'Medium'),
167
+ status: 'open',
168
+ introduced_by: review,
169
+ resolved_by: null,
170
+ seen: [sighting],
171
+ });
172
+ lines.push(JSON.stringify({ id, state: 'new', recurring_consecutive: false, recurring_cross_run: false }));
173
+ }
174
+ }
175
+
176
+ // An empty batch changes nothing: leave the file as it is, seed literal included.
177
+ if (input.length > 0) saveLedger(file, ledger);
178
+ return { lines, code: breaker ? EXIT_CIRCUIT_BREAKER : 0, message: '' };
179
+ }
180
+
181
+ export const SEVERITIES = ['Blocker', 'Major', 'Minor', 'Nit']; // strongest first
182
+ // A stored severity is read as one of the four names, else Unrated; an Unrated one counts as at the floor (it fails closed).
183
+ export const readSeverity = (s) => (SEVERITIES.includes(s) ? s : 'Unrated');
184
+ export const atOrAbove = (severity, floor) => !SEVERITIES.includes(severity) || SEVERITIES.indexOf(severity) <= SEVERITIES.indexOf(floor);
185
+ export const CONFIDENCES = ['High', 'Medium', 'Low'];
186
+ export const canonName = (names, v) => names.find((n) => typeof v === 'string' && n.toLowerCase() === v.toLowerCase()) ?? v; // blocker -> Blocker
187
+ const canonSeverity = (v) => canonName(SEVERITIES, v);
188
+ const STATUSES = ['fixed', 'accepted', 'wontfix'];
189
+ const refuse = (msg) => ({ lines: [], code: 64, message: `${PROG}: ${msg}` });
190
+ const ok = (lines = []) => ({ lines, code: 0, message: '' });
191
+
192
+ // Seeds the ledger on first touch and returns its path. Every lifecycle handler does this before it validates its
193
+ // arguments, so a refused call still leaves the seed behind, as the bash original did.
194
+ function touchLedger(root, slug) {
195
+ const { dir, file } = ledgerPaths(root, slug);
196
+ ensureLedger(dir, file);
197
+ return file;
198
+ }
199
+
200
+ // An unknown id is not an error: nothing is changed and nothing is printed.
201
+ export function resolveFinding({ root, slug, id, status, by }) {
202
+ const file = touchLedger(root, slug);
203
+ if (!id || !status) return refuse('resolve requires --id and --status');
204
+ if (!STATUSES.includes(status)) return refuse('--status must be fixed|accepted|wontfix');
205
+ const ledger = loadLedger(file);
206
+ const found = ledger.findings.find((x) => x.id === id);
207
+ if (!found) return ok();
208
+ found.status = status;
209
+ found.resolved_by = by;
210
+ saveLedger(file, ledger);
211
+ return ok([JSON.stringify({ id: found.id, status: found.status, resolved_by: found.resolved_by })]);
212
+ }
213
+
214
+ export function reopenFinding({ root, slug, id, by }) {
215
+ const file = touchLedger(root, slug);
216
+ if (!id) return refuse('reopen requires --id');
217
+ const ledger = loadLedger(file);
218
+ const found = ledger.findings.find((x) => x.id === id);
219
+ if (!found) return ok();
220
+ found.status = 'open';
221
+ found.resolved_by = null;
222
+ found.reopened_by = by;
223
+ saveLedger(file, ledger);
224
+ return ok([JSON.stringify({ id: found.id, status: found.status })]);
225
+ }
226
+
227
+ // The open findings only, trimmed to the fields a reader needs, as one pretty-printed JSON array.
228
+ export function openFindings({ root, slug }) {
229
+ const ledger = loadLedger(touchLedger(root, slug));
230
+ const open = ledger.findings
231
+ .filter((x) => x.status === 'open')
232
+ .map((x) => ({ id: x.id, locus: x.locus, title: x.title, severity: x.severity, confidence: x.confidence, introduced_by: x.introduced_by }));
233
+ return ok([JSON.stringify(open, null, 2)]);
234
+ }
235
+
236
+ export function getFinding({ root, slug, id }) {
237
+ const file = touchLedger(root, slug);
238
+ if (!id) return refuse('get requires --id');
239
+ const found = loadLedger(file).findings.find((x) => x.id === id);
240
+ return ok(found ? [JSON.stringify(found, null, 2)] : []);
241
+ }
@@ -0,0 +1,97 @@
1
+ // install-text.mjs — the install-root text tools: somi_command, somi_skill and somi_agent, each
2
+ // serving one file that ships in SoMi's own install directory (commands/<name>.md,
3
+ // skills/<name>/SKILL.md, agents/<name>.md). A consuming project can't follow a relative link into
4
+ // that directory, so the text is served over the MCP channel instead.
5
+ //
6
+ // Pure apart from the one file read: the caller supplies the install root and turns {ok, ...} into
7
+ // its own surface (the MCP server's textResult and the `<prog>: <message> (exit N)` failure line).
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { AGENT_NAME_RE, EXIT_USAGE, EXIT_UNKNOWN_AGENT } from './dispatch-resolver.mjs';
12
+
13
+ export const INSTALL_TEXT_TOOLS = [
14
+ {
15
+ name: 'somi_command',
16
+ description:
17
+ "Read a SoMi command's own procedure text (commands/<name>.md) from the install root, so " +
18
+ 'a front door running in a consuming project can follow it live without knowing where SoMi ' +
19
+ 'is installed.',
20
+ inputSchema: {
21
+ type: 'object',
22
+ properties: {
23
+ name: { type: 'string', description: 'command name, e.g. "plan" (matches ^[a-z][a-z0-9-]*$)' },
24
+ },
25
+ required: ['name'],
26
+ },
27
+ },
28
+ {
29
+ name: 'somi_skill',
30
+ description:
31
+ "Read a SoMi skill's own text (skills/<name>/SKILL.md) from the install root — the same " +
32
+ 'problem `somi_command` solves for commands/, applied to skills/: a reference to a skill from ' +
33
+ "a consuming project can't rely on a relative link into SoMi's own install directory, since " +
34
+ "that directory generally isn't the consuming project's own tree. Read the dispatch " +
35
+ 'procedure this way (`somi_skill({name: "somi-dispatch"})`) whenever the skill can\'t be ' +
36
+ 'loaded by name on the current host (e.g. no Skill tool, or a non-Claude-Code host).',
37
+ inputSchema: {
38
+ type: 'object',
39
+ properties: {
40
+ name: { type: 'string', description: 'skill name, e.g. "somi-dispatch" (matches ^[a-z][a-z0-9-]*$)' },
41
+ },
42
+ required: ['name'],
43
+ },
44
+ },
45
+ {
46
+ name: 'somi_agent',
47
+ description:
48
+ "Read a SoMi agent's instructions (agents/<name>.md, frontmatter removed) from the install " +
49
+ 'root, to inspect or quote them. Not a way to run the agent: start it as the agent_type ' +
50
+ 'somi_resolve returns, never as another agent given this text.',
51
+ inputSchema: {
52
+ type: 'object',
53
+ properties: {
54
+ name: { type: 'string', description: 'agent name, e.g. "somi-reviewer" (matches ^[a-z][a-z0-9-]*$)' },
55
+ },
56
+ required: ['name'],
57
+ },
58
+ },
59
+ ];
60
+
61
+ const NAME_MAX = 64; // the slug bound; the echo of a refused name is cut as well
62
+ const fail = (code, message) => ({ ok: false, code, message });
63
+
64
+ // The agent's instructions without its frontmatter, for reading. Dispatch never uses this: an agent
65
+ // starts as its registered agent_type (see skills/somi-dispatch §5), so the text is never a payload.
66
+ const stripFrontmatter = (text) => text.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '').trimStart();
67
+
68
+ const SOURCES = {
69
+ command: { relPath: (n) => ['commands', `${n}.md`], shape: (t) => t },
70
+ skill: { relPath: (n) => ['skills', n, 'SKILL.md'], shape: (t) => t },
71
+ agent: { relPath: (n) => ['agents', `${n}.md`], shape: stripFrontmatter },
72
+ };
73
+
74
+ // One reader for every install-root text tool. The name is checked against AGENT_NAME_RE BEFORE
75
+ // any path is built, so a traversal payload (`../x`, `a/b`) is a 64 and never reaches path.join.
76
+ // JSON.stringify, not a template interpolation, for the invalid name: an object-shaped `name`
77
+ // (e.g. `{toString: null}`) throws inside `${name}` and would surface as an unrelated -32603.
78
+ /**
79
+ * @param {'command' | 'skill' | 'agent'} kind
80
+ * @param {{name?: unknown}} args
81
+ * @param {{installRoot: string}} env
82
+ * @returns {{ok: true, text: string} | {ok: false, code: number, message: string}}
83
+ */
84
+ export function installText(kind, args, { installRoot }) {
85
+ const name = args?.name;
86
+ if (typeof name !== 'string' || name.length > NAME_MAX || !AGENT_NAME_RE.test(name)) {
87
+ return fail(EXIT_USAGE, `invalid name ${JSON.stringify(name)?.slice(0, 60)} (expected ${AGENT_NAME_RE}, at most ${NAME_MAX} characters)`);
88
+ }
89
+ const { relPath, shape } = SOURCES[kind];
90
+ const filePath = path.join(installRoot, ...relPath(name));
91
+ try {
92
+ return { ok: true, text: shape(fs.readFileSync(filePath, 'utf8')) };
93
+ } catch (e) {
94
+ if (e.code === 'ENOENT') return fail(EXIT_UNKNOWN_AGENT, `unknown ${kind} "${name}" (no ${filePath})`);
95
+ throw e;
96
+ }
97
+ }
@@ -0,0 +1,140 @@
1
+ // loop-caps.mjs -- cap resolution for the loop engine, lifted out of somi-loop.mjs unchanged apart from its
2
+ // inputs: the environment arrives as a parameter and this file never reads process.env, so an in-process
3
+ // caller (the MCP tool) resolves against the env it was handed and a test can prove the isolation.
4
+ //
5
+ // --- mid-loop cap re-resolution --------------------------------------------
6
+ // `init` resolves caps once (CLI flag > env var > .somi/config.json > default) and
7
+ // freezes them into state -- deliberately, so the diff baseline and pass history stay
8
+ // stable across a whole loop. But commands/code-loop.md's Guardrails document a
9
+ // remedy for a gate that's wrong for the work at hand: "the user adjusts the env var
10
+ // explicitly and re-runs -- the loop does not 'decide' to widen its own bounds." That
11
+ // remedy needs a path that re-reads the override on the SAME subcommand (`pass`,
12
+ // `check-diff`), without `init --force` (which discards `pass`/`history`).
13
+ //
14
+ // `pass` and `check-diff` (lib/loop-engine.mjs) call reresolveCap() before their gate check.
15
+ // Precedence matches what's documented: CLI flag > env var > .somi/config.json >
16
+ // default -- an explicit CLI flag or env var THIS invocation is the only thing that
17
+ // can move the cap; absent one, the cap already in force for the loop stands (a
18
+ // `.somi/config.json` edit made while a loop is running must NOT silently reopen an
19
+ // already-resolved gate). A resolved value that differs from what's stored is
20
+ // persisted into `caps` immediately, with an entry appended to a `cap_overrides`
21
+ // audit trail (field, from, to, source, after_pass, at) -- the after-the-fact record
22
+ // the documented remedy needs, since the env var itself lives only in a shell that
23
+ // may since have exited. `cap_overrides` is created lazily, only on the first real
24
+ // override, so a loop that never overrides anything keeps exactly today's state
25
+ // shape (no golden-fixture regeneration forced by this fix). `baseline_sha`,
26
+ // `started`, `pass`, and `history` are never touched here.
27
+ //
28
+ // Every value that reaches `Number()` on this path is user input (a CLI flag, an env
29
+ // var, or a config value) and is validated before use: `Number()` on a malformed
30
+ // string (`"1,000"`, `"unlimited"`) yields NaN, which is false against BOTH gate
31
+ // comparisons (`cur + 1 > max`, `weighted > cap`) -- silently switching the gate off
32
+ // -- and `JSON.stringify` then persists that NaN as `null`, which the next bare call
33
+ // falls through past (via `firstDefined`) to re-arm at the default, with no
34
+ // `cap_overrides` entry recording the reversion. `validateCap()` rejects rather than
35
+ // coerces, so a malformed value dies loudly instead of disabling a gate.
36
+
37
+ import { usageError } from './loop-exit.mjs';
38
+
39
+ export function configVal(config, keys) {
40
+ let cur = config;
41
+ for (const k of keys) {
42
+ if (cur === undefined || cur === null) return undefined;
43
+ cur = cur[k];
44
+ }
45
+ return cur === null ? undefined : cur;
46
+ }
47
+
48
+ // Mirrors bash's `${a:-${b:-$c}}` — first arg that is neither unset nor an
49
+ // empty string wins (a numeric 0 counts as "set", matching bash treating the
50
+ // non-empty string "0" as set).
51
+ export function firstDefined(...vals) {
52
+ for (const v of vals) {
53
+ if (v === undefined || v === null) continue;
54
+ if (typeof v === 'string' && v === '') continue;
55
+ return v;
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ const CAP_ENV = {
61
+ code: { max_passes: 'SOMI_CODE_LOOP_MAX_PASSES', diff_cap_lines: 'SOMI_CODE_LOOP_DIFF_CAP' },
62
+ plan: { max_passes: 'SOMI_PLAN_LOOP_MAX_PASSES' },
63
+ };
64
+ const CAP_FLAG = { max_passes: '--max-passes', diff_cap_lines: '--diff-cap' };
65
+ const CAP_CONFIG_SECTION = { code: 'code_loop', plan: 'plan_loop' };
66
+ const CAP_DEFAULT = { max_passes: 3, diff_cap_lines: 400 };
67
+
68
+ // Rejects a malformed cap value rather than letting `Number()` coerce it to NaN.
69
+ // `label` names the source in the error so the error points at what to fix
70
+ // (a specific flag, env var, or the generic field name at `init`, where the value
71
+ // may have come from any of CLI/env/config).
72
+ export function validateCap(raw, label) {
73
+ const n = Number(raw);
74
+ if (!Number.isInteger(n) || n < 0) {
75
+ throw usageError(`${label}: expected a non-negative integer, got "${raw}"`);
76
+ }
77
+ return n;
78
+ }
79
+
80
+ // Resolves one cap at `init`, reading the same CAP_ENV / CAP_CONFIG_SECTION /
81
+ // CAP_DEFAULT tables reresolveCap() uses, so the two paths cannot silently diverge
82
+ // on an env var name, a config key, or a default value.
83
+ export function resolveInitCap(env, config, family, field, argVal) {
84
+ if (field === 'diff_cap_lines' && family === 'plan') return 0; // plan loops have no diff cap
85
+ const envVar = CAP_ENV[family][field];
86
+ const fromConfig = configVal(config, [CAP_CONFIG_SECTION[family], field]);
87
+ const picked = firstDefined(argVal, env[envVar], fromConfig, CAP_DEFAULT[field]);
88
+ return validateCap(picked, field);
89
+ }
90
+
91
+ // `at` is the timestamp an override entry records, supplied by the caller so this file keeps no clock.
92
+ export function reresolveCap(env, state, field, argVal, at) {
93
+ const family = state.loop === 'plan' ? 'plan' : 'code';
94
+ if (field === 'diff_cap_lines' && family === 'plan') {
95
+ return { resolved: 0, override: null }; // plan loops have no diff cap (see `init`)
96
+ }
97
+ const envVar = CAP_ENV[family][field];
98
+ const stored = state.caps[field];
99
+ const explicit = firstDefined(argVal, env[envVar]);
100
+ const isCli = argVal !== undefined && argVal !== '';
101
+ const resolved = explicit === undefined
102
+ ? stored
103
+ : validateCap(explicit, isCli ? CAP_FLAG[field] : envVar);
104
+ let override = null;
105
+ if (explicit !== undefined && resolved !== stored) {
106
+ override = {
107
+ field,
108
+ from: stored,
109
+ to: resolved,
110
+ source: isCli ? 'cli' : 'env',
111
+ after_pass: state.pass,
112
+ at,
113
+ };
114
+ }
115
+ return { resolved, override };
116
+ }
117
+
118
+ // Mutates `state.caps[field]` and appends the audit entry. Caller still owns calling
119
+ // saveState() -- kept separate so `pass`/`check-diff` persist the override BEFORE
120
+ // their gate check can throw, not only on the success path.
121
+ export function applyCapOverride(state, override) {
122
+ state.caps[override.field] = override.to;
123
+ if (!Array.isArray(state.cap_overrides)) state.cap_overrides = [];
124
+ state.cap_overrides.push(override);
125
+ }
126
+
127
+ // Cap arguments that arrive from a tool may only tighten the cap in force: above it is refused with 64, equal is no
128
+ // change, below returns the override entry (source `tool`) for the caller to apply. A diff cap of 0 is the gate off,
129
+ // so any positive value tightens it and 0 against a live cap is an attempt to raise it. `argVal` was shape-checked
130
+ // by the caller; undefined means no argument.
131
+ export function tightenCap(state, field, argVal, at, label = field) {
132
+ if (argVal === undefined) return null;
133
+ const stored = state.caps[field];
134
+ const limit = (v) => (field === 'diff_cap_lines' && v === 0 ? Infinity : v);
135
+ if (limit(argVal) > limit(stored)) {
136
+ throw usageError(`${label}: ${argVal} is above the cap in force (${stored}); arguments only tighten, raise it with the CLI flag or env var`);
137
+ }
138
+ if (argVal === stored) return null;
139
+ return { field, from: stored, to: argVal, source: 'tool', after_pass: state.pass, at };
140
+ }
@@ -1,80 +1,22 @@
1
1
  // loop-diff.mjs -- the code loop's diff measurement: the weighted cumulative diff of the working tree against the
2
- // loop's baseline, untracked files included. Moved out of scripts/somi-loop.mjs unchanged.
2
+ // loop's baseline, untracked files included.
3
3
 
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
- import { execFileSync } from 'node:child_process';
7
-
8
- // Untracked, non-ignored files as synthetic `--numstat` rows (all lines added).
9
- // `git diff` reads the index and the work tree, but a file git has never been
10
- // told about is in neither -- so a brand-new file counts ZERO until someone runs
11
- // `git add`. That made the cap under-measure by the entire size of every new
12
- // file an iteration introduced, silently, in the direction that lets work
13
- // through (measured 248 against a true 503 on one real iteration).
14
- // Enumerated separately and merged into the same stream rather than fixed with
15
- // `git add -N`, which would mutate the caller's index as a side effect of a
16
- // read-only query.
17
- export function untrackedNumstat(root, pathspec) {
18
- let listed = '';
19
- try {
20
- listed = execFileSync(
21
- 'git',
22
- ['-C', root, 'ls-files', '--others', '--exclude-standard', '--', ...pathspec],
23
- { encoding: 'utf8' },
24
- );
25
- } catch (e) {
26
- listed = e.stdout ? e.stdout.toString() : '';
27
- }
28
- const rows = [];
29
- for (const file of listed.split('\n')) {
30
- if (file === '') continue;
31
- let buf;
32
- try {
33
- buf = fs.readFileSync(path.join(root, file));
34
- } catch {
35
- continue; // raced away between listing and reading
36
- }
37
- // git calls a blob binary on a NUL in the first 8000 bytes and reports `-`.
38
- if (buf.subarray(0, 8000).includes(0)) {
39
- rows.push(`-\t-\t${file}`);
40
- continue;
41
- }
42
- const text = buf.toString('utf8');
43
- const added = text === '' ? 0 : text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
44
- rows.push(`${added}\t0\t${file}`);
45
- }
46
- return rows.join('\n');
47
- }
4
+ import { measuredTree, treeRows } from './loop-review.mjs';
48
5
 
49
6
  // Weighted cumulative diff vs baseline. Out-of-scope lines count double.
50
- // Covers tracked changes, staged changes, AND untracked files (see above) --
51
- // the whole working tree, which is what the cap is meant to bound.
7
+ // Measured between the baseline and a snapshot tree of the whole working tree (tracked, staged and untracked
8
+ // files; .somi and .claude excluded), the same tree the review scope diffs, so the cap and the reviewer see one
9
+ // file set. A brand-new file is in the snapshot though git has never been told about it, and names are read
10
+ // NUL-separated, so no file is skipped for how it is spelled. When the tree cannot be measured this throws a
11
+ // refusal (exit 64) instead of returning a smaller diff. `iterationFiles` entries and the reported file names are
12
+ // relative to `root` (the project directory), not to the repository's top level. `rows` are the per-file rows as git
13
+ // reports them ({file, added, deleted, status}), for the escalation.
52
14
  export function computeDiff(root, baseline, iterationFiles) {
53
- const pathspec = ['.', ':(exclude).somi', ':(exclude).claude'];
54
- let output = '';
55
- try {
56
- output = execFileSync(
57
- 'git',
58
- ['-C', root, 'diff', '--numstat', baseline, '--', ...pathspec],
59
- { encoding: 'utf8' },
60
- );
61
- } catch (e) {
62
- output = e.stdout ? e.stdout.toString() : '';
63
- }
64
- const untracked = untrackedNumstat(root, pathspec);
65
- if (untracked !== '') output = output === '' ? untracked : `${output}\n${untracked}`;
15
+ const rows = treeRows(root, baseline, measuredTree(root));
66
16
  let total = 0;
67
17
  let weighted = 0;
68
18
  const outOfScope = [];
69
- for (const line of output.split('\n')) {
70
- if (line === '') continue;
71
- const parts = line.split('\t');
72
- let added = parts[0];
73
- let deleted = parts[1];
74
- const file = parts.slice(2).join('\t');
75
- if (!file) continue;
76
- added = added === '-' ? 0 : Number(added); // binary
77
- deleted = deleted === '-' ? 0 : Number(deleted);
19
+ for (const { added, deleted, file } of rows) {
78
20
  const lines = added + deleted;
79
21
  total += lines;
80
22
  let inScope = false;
@@ -92,5 +34,5 @@ export function computeDiff(root, baseline, iterationFiles) {
92
34
  outOfScope.push(file);
93
35
  }
94
36
  }
95
- return { total, weighted, outOfScope };
37
+ return { total, weighted, outOfScope, rows };
96
38
  }