@skathio/somi 5.0.0 → 5.0.2

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.
@@ -13,7 +13,7 @@
13
13
  "url": "https://github.com/skathio/somi.git"
14
14
  },
15
15
  "description": "A workflow plugin for coding agents: say what you want or pass a ticket, and it picks the right workflow and keeps the cost down, while your agent stays in charge.",
16
- "version": "5.0.0",
16
+ "version": "5.0.2",
17
17
  "tags": [
18
18
  "workflow",
19
19
  "agents",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "somi",
3
- "version": "5.0.0",
3
+ "version": "5.0.2",
4
4
  "displayName": "SoMi",
5
5
  "description": "A workflow plugin for coding agents: say what you want or pass a ticket, and it picks the right workflow and keeps the cost down, while your agent stays in charge.",
6
6
  "keywords": [
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "somi",
3
3
  "displayName": "SoMi",
4
- "version": "5.0.0",
4
+ "version": "5.0.2",
5
5
  "description": "A workflow plugin for coding agents: say what you want or pass a ticket, and it picks the right workflow and keeps the cost down, while your agent stays in charge.",
6
6
  "keywords": [
7
7
  "workflow",
@@ -11,7 +11,7 @@
11
11
  "name": "somi",
12
12
  "source": "github:skathio/somi",
13
13
  "description": "A workflow plugin for coding agents: say what you want or pass a ticket, and it picks the right workflow and keeps the cost down, while your agent stays in charge.",
14
- "version": "5.0.0",
14
+ "version": "5.0.2",
15
15
  "tags": [
16
16
  "workflow",
17
17
  "agents",
package/README.md CHANGED
@@ -96,6 +96,12 @@ Ask `/somi-config` to change one, or set your own under `quality` in the same gl
96
96
 
97
97
  A project's `.somi/config.json` can only make a limit stricter: a looser value there is ignored, and the gate says so. SoMi asks before an agent changes a limit.
98
98
 
99
+ The gate may run for 300 seconds before it counts as failed. For a large change, set `quality.timeout_seconds`, up to 1800, in your own file, or in the project's, which may only lengthen it:
100
+
101
+ ```json
102
+ { "quality": { "timeout_seconds": 900 } }
103
+ ```
104
+
99
105
  For a cleanup or a refactor, `/somi-quality repo` reports on the whole codebase as it stands: every function and file over a limit, every copy in product code and every suppression with no reason. It lists the most complex functions and the files with the most findings first. Give it its own limits under `quality.repo`.
100
106
 
101
107
  You do not need to run it yourself. When a turn that changed code ends, on Claude Code and Copilot CLI alike, SoMi runs the gate and sends anything over a limit back to the agent to fix, before any review. The agent never adds an exemption to get past it: that is yours to decide. No pull request text is written while the branch fails it, and `/somi-deliver` checks each build and steps the build up a tier with the findings.
package/VERSION CHANGED
@@ -1 +1 @@
1
- 5.0.0
1
+ 5.0.2
package/hooks/hooks.json CHANGED
@@ -83,7 +83,8 @@
83
83
  "hooks": [
84
84
  {
85
85
  "type": "command",
86
- "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/stop/review-due.mjs\""
86
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/stop/review-due.mjs\"",
87
+ "timeout": 1860
87
88
  }
88
89
  ]
89
90
  }
@@ -3,11 +3,12 @@
3
3
  // review is due and whether the change meets the quality limits, so the model does not have to remember either. When the gate fails, or
4
4
  // a signal fired and no review covers the change, the turn goes on once with the reasons: the quality failures first, so the review
5
5
  // reads the code that is finished. It asks once per tree, so it never loops, and when it cannot read the repository it lets the turn end.
6
+ // A turn that changed nothing, such as a question, ends at once: the gate reads the whole branch, and on a large one that takes a while.
6
7
 
7
8
  import fs from 'node:fs';
8
9
  import path from 'node:path';
9
10
  import { loadConfig } from '../../scripts/lib/config-files.mjs';
10
- import { stateIsTracked } from '../../scripts/lib/git-tree.mjs';
11
+ import { snapshotTree, stateIsTracked } from '../../scripts/lib/git-tree.mjs';
11
12
  import { somiCommand } from '../../scripts/lib/advisor.mjs';
12
13
  import { qualityStep } from '../../scripts/lib/quality/run.mjs';
13
14
  import { reviewPlan } from '../../scripts/lib/reviews.mjs';
@@ -20,21 +21,30 @@ runHook(() => {
20
21
  if (payload.stop_hook_active === true || payload.agent_id) return;
21
22
  const root = projectRoot();
22
23
  if (root === null) return;
24
+ const asked = path.join(statePaths(root).dir, 'review-asked.json');
25
+ const read = (file) => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } };
23
26
  let plan;
24
27
  try {
25
28
  if (!process.env.SOMI_STATE_DIR && stateIsTracked(root)) return;
29
+ const tree = snapshotTree(root);
30
+ const turn = read(statePaths(root).turn);
31
+ if (turn?.tree === tree && turn.session === (payload.session_id ?? payload.sessionId ?? null)) return;
32
+ if (read(asked)?.tree === tree) return;
26
33
  let loaded = { config: {}, global: { config: {} }, project: { config: {} } };
27
34
  try { loaded = loadConfig(root); } catch { /* built-in signals still apply */ }
28
35
  plan = reviewPlan({ root, env: process.env, config: loaded.config, configLayers: [loaded.global.config ?? {}, loaded.project.config ?? {}], host: detectHost(), now: () => new Date().toISOString() });
29
36
  } catch { return; }
30
- const asked = path.join(statePaths(root).dir, 'review-asked.json');
31
- try { if (JSON.parse(fs.readFileSync(asked, 'utf8')).tree === plan.tree) return; } catch { /* not asked about this tree yet */ }
37
+ // The tree is marked before the gate runs, so a host that stops the hook part way does not start the same gate again every turn.
38
+ try { writeStateFile(root, asked, `${JSON.stringify({ tree: plan.tree })}\n`); } catch { return; }
32
39
  const quality = qualityStep(root, { scope: 'pr', env: process.env });
40
+ // A gate that could not run is not a pass, and there is nothing in the code to fix for it, so the user hears why.
41
+ const qualityReason = quality.error
42
+ ? `SoMi: the quality gate could not check this change: ${quality.error}. That is not a pass. Tell the user, and do not change code for it.`
43
+ : `SoMi: this change is over the quality limits:\n${quality.failures.join('\n')}\nRefactor until \`${somiCommand('quality --scope pr')}\` passes, with the tests still green. Do not add a somi-gate-allow exemption to get past it: that is the user's call. If a limit cannot be met, or the code over it is not code you wrote in this conversation, tell the user which and why instead.`;
33
44
  const reasons = [
34
- ...(quality.ok ? [] : [`SoMi: this change is over the quality limits:\n${quality.failures.join('\n')}\nRefactor until \`${somiCommand('quality --scope pr')}\` passes, with the tests still green. Do not add a somi-gate-allow exemption to get past it: that is the user's call. If a limit cannot be met, or the code over it is not code you wrote in this conversation, tell the user which and why instead.`]),
45
+ ...(quality.ok ? [] : [qualityReason]),
35
46
  ...(plan.needed ? [`SoMi: this change needs a review before it is finished (${plan.signals.join(', ')}). Call somi_review, start the reviewers it names with their briefs, and record what they return. If the user said not to review, tell them it is due and stop.`] : []),
36
47
  ];
37
- try { writeStateFile(root, asked, `${JSON.stringify({ tree: plan.tree })}\n`); } catch { return; }
38
48
  if (reasons.length === 0) return;
39
49
  process.stdout.write(`${JSON.stringify({ decision: 'block', reason: reasons.join('\n\n') })}\n`);
40
50
  });
@@ -1,17 +1,23 @@
1
1
  #!/usr/bin/env node
2
- // UserPromptSubmit: keeps the user's messages so SoMi's tools can read the user's own words, not only the agent's summary of them.
3
- // It adds nothing to the conversation and never blocks a prompt. A committed state folder is not trusted, so nothing is written there.
2
+ // UserPromptSubmit: keeps the user's messages so SoMi's tools can read the user's own words, not only the agent's summary of them, and
3
+ // the tree as the turn starts, so the Stop hook can tell a turn that changed nothing. It adds nothing to the conversation and never
4
+ // blocks a prompt. A committed state folder is not trusted, so nothing is written there.
4
5
 
5
- import { stateIsTracked } from '../../scripts/lib/git-tree.mjs';
6
- import { savePrompt } from '../../scripts/lib/prompt.mjs';
6
+ import { snapshotTree, stateIsTracked } from '../../scripts/lib/git-tree.mjs';
7
+ import { isHostNotice, savePrompt } from '../../scripts/lib/prompt.mjs';
8
+ import { statePaths, writeStateFile } from '../../scripts/lib/state.mjs';
7
9
  import { projectRoot, readPayload, runHook } from '../lib/common.mjs';
8
10
 
9
11
  runHook(() => {
10
12
  const payload = readPayload();
11
13
  const root = projectRoot();
12
14
  if (root === null) return;
15
+ const text = payload.prompt ?? payload.userPrompt ?? '';
16
+ const session = payload.session_id ?? payload.sessionId ?? null;
13
17
  try {
14
18
  if (!process.env.SOMI_STATE_DIR && stateIsTracked(root)) return;
15
- savePrompt(root, payload.prompt ?? payload.userPrompt ?? '', process.env, { session: payload.session_id ?? payload.sessionId });
19
+ savePrompt(root, text, process.env, { session });
20
+ // A host notice, such as a background task finishing, carries on the turn before it, so what that task changed still counts.
21
+ if (typeof text === 'string' && !isHostNotice(text)) writeStateFile(root, statePaths(root).turn, `${JSON.stringify({ session, tree: snapshotTree(root) })}\n`);
16
22
  } catch { /* a prompt must never fail because SoMi could not keep a copy */ }
17
23
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skathio/somi",
3
- "version": "5.0.0",
3
+ "version": "5.0.2",
4
4
  "scripts": {
5
5
  "test": "node --test --test-reporter=spec tests/*.test.mjs",
6
6
  "test:coverage": "node -e \"require('fs').mkdirSync('coverage',{recursive:true})\" && node --test --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info tests/*.test.mjs",
@@ -18,7 +18,7 @@ import { TIERS, mainTier, resolveSpawn } from './tiers.mjs';
18
18
  import { WORKFLOWS, expertiseIndex, libraryPath, roleBrief, workerAgent } from './workflows.mjs';
19
19
  import { copilotName } from './copilot-workflow.mjs';
20
20
  import { globalConfigPath } from './config-files.mjs';
21
- import { SCOPES, resolveLimits } from './quality/limits.mjs';
21
+ import { QUALITY_TIMEOUT, SCOPES, resolveLimits, resolveTimeout } from './quality/limits.mjs';
22
22
 
23
23
  const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'somi.mjs');
24
24
  export const somiCommand = (args) => `node ${JSON.stringify(CLI)} ${args}`;
@@ -116,7 +116,7 @@ const LARGE = (request) => String(request ?? '').length > LONG_REQUEST;
116
116
  // for the reviews, so reading the work again here spends the conversation's tier on what a cheaper stage has done.
117
117
  // A project's config is cloned input and may only tighten a limit, so a change the user wants goes in their own file.
118
118
  // Everything here is done from the chat: the agent runs SoMi's own commands by their full path, because no somi command is on the PATH.
119
- const QUALITY_CONFIG = 'Relay this briefly. To change a quality limit, write it under quality in the file named by global_config, or under quality.commit or quality.pr for one scope, never in the project\'s .somi/config.json, where only a tighter value counts. Before you write a value looser than the current limit, ask the user and wait for a yes.';
119
+ const QUALITY_CONFIG = `Relay this briefly. To change a quality limit, write it under quality in the file named by global_config, or under quality.commit or quality.pr for one scope, never in the project's .somi/config.json, where only a tighter value counts. Before you write a value looser than the current limit, ask the user and wait for a yes. quality_timeout_seconds is how long the gate may run before it counts as failed: to change it, write quality.timeout_seconds there, a whole number from ${QUALITY_TIMEOUT.min} to ${QUALITY_TIMEOUT.max}.`;
120
120
  const SETUP = (host) => `To check SoMi's setup, run \`${somiCommand('doctor')}\` and relay what it finds. After tiers.main changes, run \`${somiCommand('setup')}\`. To connect another plugin to a step, run \`${somiCommand('slot <step> <plugin:component>')}\` with the step and component the user names, and \`${somiCommand('slot --list')}\` to show what is connected.${host === 'claude' ? '' : ` To turn on the staged workflow, /somi-deliver, in this project, run \`${somiCommand('init --host copilot')}\` once the user says yes.`}`;
121
121
  const STAGED_ADVICE = (host) => `The user typed /somi-deliver to run this work in stages. Start the workflow below by its name with its args unchanged${host === 'claude' ? ', using the Workflow tool: it is a saved workflow, so no script and no authoring guide are needed' : ', as Copilot runs workflows in experimental mode'}. Tell the user it is running and end your turn. When it returns, do not read or check the work again, because the workflow ran the checks: record its reviews with somi_review, passing tree as review_tree, and tell the user its summary and status in a few lines. If you cannot start it, say why, and call somi_route again with the same request and without staged for the steps.`;
122
122
  const SUGGEST_STAGED = 'This looks like large work. Tell the user once that typing /somi-deliver with it runs it in stages, each on its tier, and that only they can start that. Then follow steps.';
@@ -133,7 +133,7 @@ function chooseRoute({ request, ticket, hint }) {
133
133
  function configAnswer(ctx) {
134
134
  const scoped = SCOPES.map((scope) => [scope, resolveLimits({ global: ctx.configLayers?.[0], project: ctx.configLayers?.[1], scope })]);
135
135
  const ignored = [...new Map(scoped.flatMap(([, r]) => r.ignored).map((x) => [`${x.where}:${x.key}`, x])).values()];
136
- return { route: 'config', main: mainTier(ctx.config), tiers: Object.fromEntries(TIERS.map((t) => [t, resolveSpawn(ctx.config, ctx.host, t)])), host: ctx.host, quality: Object.fromEntries(scoped.map(([scope, r]) => [scope, r.limits])), ...(ignored.length ? { quality_ignored: ignored } : {}), global_config: globalConfigPath(ctx.env), advice: `${QUALITY_CONFIG} ${SETUP(ctx.host)}` };
136
+ return { route: 'config', main: mainTier(ctx.config), tiers: Object.fromEntries(TIERS.map((t) => [t, resolveSpawn(ctx.config, ctx.host, t)])), host: ctx.host, quality: Object.fromEntries(scoped.map(([scope, r]) => [scope, r.limits])), quality_timeout_seconds: resolveTimeout({ global: ctx.configLayers?.[0], project: ctx.configLayers?.[1] }).seconds, ...(ignored.length ? { quality_ignored: ignored } : {}), global_config: globalConfigPath(ctx.env), advice: `${QUALITY_CONFIG} ${SETUP(ctx.host)}` };
137
137
  }
138
138
 
139
139
  // Routes that answer at once, with no work to place: asking which route fits, status, config, the pull request and the reviews.
@@ -141,13 +141,15 @@ export function runCheck({ root, env = process.env, full = false, from = null, s
141
141
  ];
142
142
  const quality = qualityStep(root, { scope, env });
143
143
  gates.push(gate('quality', quality.failures));
144
+ // The gate has its own time limit, so a slow one on a large change does not use up the tests' budget.
145
+ const testsFrom = Date.now();
144
146
 
145
147
  if (full) {
146
148
  const command = plan.full_cmd ?? (hasNpmTest(root) ? 'npm test' : null);
147
149
  gates.push(command ? runShell(root, 'full-suite', command, undefined) : gate('full-suite', []));
148
150
  } else {
149
151
  const budget = plan.budget_s * 1000;
150
- const left = () => Math.max(1, budget - (Date.now() - started));
152
+ const left = () => Math.max(1, budget - (Date.now() - testsFrom));
151
153
  if (plan.fast_cmd) gates.push(runShell(root, 'fast', plan.fast_cmd, left()));
152
154
  const selected = selectTests(files, plan, (f) => fs.existsSync(path.join(root, f)));
153
155
  if (selected.unmapped && plan.full_cmd) gates.push(runShell(root, 'tests', plan.full_cmd, left()));
@@ -194,6 +194,45 @@ export function fileAt(root, rev, file) {
194
194
  try { return git(root, ['cat-file', '-p', `${rev}:${file}`]); } catch { return null; }
195
195
  }
196
196
 
197
+ const BATCH = 200;
198
+
199
+ /** Many files' text at a commit or tree, read by one git process per batch: a Map from file to text, without the files not there. */
200
+ export function filesAt(root, rev, files) {
201
+ if (!OBJECT_ID.test(rev)) throw new Error('a recorded revision is not an object id');
202
+ const texts = new Map();
203
+ for (let i = 0; i < files.length; i += BATCH) {
204
+ for (const [file, text] of readBatch(root, rev, files.slice(i, i + BATCH))) if (text !== null) texts.set(file, text);
205
+ }
206
+ return texts;
207
+ }
208
+
209
+ // [file, text or null] for each file, in order. The batch protocol is one name per line, so a name with a newline in it is read on its
210
+ // own, and so is every file of a batch too large to buffer.
211
+ function readBatch(root, rev, files) {
212
+ const named = files.filter((f) => !f.includes('\n'));
213
+ let out = null;
214
+ try { out = git(root, ['cat-file', '--batch'], { encoding: null, stdio: ['pipe', 'pipe', 'pipe'], input: named.map((f) => `${rev}:${f}\n`).join('') }); } catch { /* read one by one */ }
215
+ const read = out ? parseBatch(out, named) : new Map();
216
+ return files.map((f) => [f, out && !f.includes('\n') ? read.get(f) ?? null : fileAt(root, rev, f)]);
217
+ }
218
+
219
+ // Each answer is "<id> <type> <size>" and the content, or one line saying the name is missing.
220
+ function parseBatch(out, names) {
221
+ const read = new Map();
222
+ let at = 0;
223
+ for (const name of names) {
224
+ const end = out.indexOf(10, at);
225
+ if (end < 0) break;
226
+ const header = /^[0-9a-f]+ (\w+) (\d+)$/.exec(out.toString('utf8', at, end));
227
+ at = end + 1;
228
+ if (!header) continue;
229
+ const size = Number(header[2]);
230
+ if (header[1] === 'blob') read.set(name, out.toString('utf8', at, at + size));
231
+ at += size + 1;
232
+ }
233
+ return read;
234
+ }
235
+
197
236
  // This string reaches an agent as a command, and its ids come from a state file, so anything but an object id is refused.
198
237
  export function reviewDiffCommand(from, to) {
199
238
  if (!OBJECT_ID.test(String(from)) || !OBJECT_ID.test(String(to))) throw new Error('a recorded revision is not an object id');
@@ -6,7 +6,7 @@
6
6
 
7
7
  import crypto from 'node:crypto';
8
8
  import { TEST_FILE } from '../signals.mjs';
9
- import { addedRanges, fileAt } from '../git-tree.mjs';
9
+ import { addedRanges, filesAt } from '../git-tree.mjs';
10
10
  import { findClones, tokensOf } from './clones.mjs';
11
11
  import { cssRules } from './css.mjs';
12
12
  import { unitsOf, topLevelCognitive } from './metrics.mjs';
@@ -131,7 +131,7 @@ export async function withTree(file, text, read) {
131
131
 
132
132
  const NO_VERSION = Object.freeze({ units: [], keys: [], total: 0, tokens: null });
133
133
  async function previousVersion(ctx, file, status, test) {
134
- const text = status.startsWith('A') ? null : fileAt(ctx.root, ctx.from, file);
134
+ const text = status.startsWith('A') ? null : ctx.before.get(file) ?? null;
135
135
  if (text === null || skipped(file, text)) return NO_VERSION;
136
136
  const lines = text.split('\n');
137
137
  return withTree(file, text, (parsed) => {
@@ -168,7 +168,7 @@ async function scoreCode(ctx, { file, status, added, lines, tree, language, erro
168
168
  async function scoreFile(ctx, file, { status, added }) {
169
169
  if (!languageOf(file)) return;
170
170
  if (status.startsWith('D')) return recordDeleted(ctx, file, status);
171
- const text = fileAt(ctx.root, ctx.to, file);
171
+ const text = ctx.after.get(file) ?? null;
172
172
  if (text === null || skipped(file, text)) return;
173
173
  const lines = text.split('\n');
174
174
  const parsed = await parseSource(file, text);
@@ -206,9 +206,8 @@ async function cachedTokens(cache, file, text) {
206
206
  async function restOfRepo(ctx, touched) {
207
207
  const rest = [];
208
208
  const candidates = ctx.repoFiles.filter((f) => JS_FAMILY.has(languageOf(f)) && !touched.has(f) && !isTest(f) && !SKIPPED.test(f) && !MINIFIED.test(f));
209
- for (const file of candidates.slice(0, MAX_REPO_FILES)) {
210
- const text = fileAt(ctx.root, ctx.to, file);
211
- if (text === null || skipped(file, text)) continue;
209
+ for (const [file, text] of filesAt(ctx.root, ctx.to, candidates.slice(0, MAX_REPO_FILES))) {
210
+ if (skipped(file, text)) continue;
212
211
  const tokens = await cachedTokens(ctx.cache, file, text);
213
212
  if (tokens) rest.push({ file, tokens, size: ctx.limits.clones.tokens });
214
213
  }
@@ -222,9 +221,14 @@ async function restOfRepo(ctx, touched) {
222
221
  export async function qualityGate(root, { from, to, limits, now = new Date().toISOString(), mode = 'project', repoFiles = [], cache = null }) {
223
222
  const ctx = { root, from, to, limits, now, mode, repoFiles, cache, violations: [], warnings: [], exemptions: [], unanalyzed: [], scored: { files: 0, functions: 0 }, cloneAfter: [], cloneBefore: [], totals: [], moves: { before: [], after: [] } };
224
223
  const changed = addedRanges(root, from, to);
224
+ // The changed code is read up front, a batch at a time. One git process per file was most of the gate's time on a large branch.
225
+ const code = [...changed].filter(([file]) => languageOf(file));
226
+ ctx.before = filesAt(root, from, code.filter(([, c]) => !c.status.startsWith('A')).map(([file]) => file));
227
+ ctx.after = filesAt(root, to, code.filter(([, c]) => !c.status.startsWith('D')).map(([file]) => file));
225
228
  for (const [file, change] of changed) await scoreFile(ctx, file, change);
226
229
  scoreMoves(ctx);
227
- const rest = await restOfRepo(ctx, new Set(changed.keys()));
230
+ // A copy is only reported in code the change holds, so with none of that the rest of the repository is not read.
231
+ const rest = ctx.cloneAfter.length > 0 ? await restOfRepo(ctx, new Set(changed.keys())) : [];
228
232
  for (const c of findClones({ after: ctx.cloneAfter, before: ctx.cloneBefore, rest })) flag(ctx, { rule: 'clone', file: c.file, line: c.line, value: c.lines, limit: 0, other: c.other });
229
233
  return { ok: ctx.violations.length === 0, violations: ctx.violations, warnings: ctx.warnings, exemptions: ctx.exemptions, scored: ctx.scored, unanalyzed: ctx.unanalyzed };
230
234
  }
@@ -25,6 +25,13 @@ export const DEFAULT_LIMITS = Object.freeze({
25
25
  suppressions: Object.freeze({ added: 0 }),
26
26
  });
27
27
 
28
+ // How long the gate may run before it counts as failed, in seconds. A large change on a slow machine needs longer than the default, so
29
+ // either file may set quality.timeout_seconds: the user's own either way, and a project's, which knows its own size, only to lengthen it.
30
+ // A gate that runs out of time is not a pass, so a cloned project cannot make the gate pass by shortening it, and may not make it fail
31
+ // every change that way either. The end-of-turn hook's own time, in
32
+ // hooks/hooks.json, is set above the maximum, so the host never cuts the gate off first.
33
+ export const QUALITY_TIMEOUT = Object.freeze({ default: 300, min: 10, max: 1800 });
34
+
28
35
  const SCOPE_DEFAULTS = Object.freeze({ commit: {}, pr: { file: { added_cognitive: 100 } }, repo: {} });
29
36
 
30
37
  /** The default limits at one scope, as a fresh object. */
@@ -52,7 +59,7 @@ function apply(limits, ignored, { where, prefix, group, key, value }) {
52
59
 
53
60
  function applyLayer(limits, ignored, { where, prefix, layer }) {
54
61
  for (const [group, values] of Object.entries(layer ?? {})) {
55
- if (prefix === 'quality' && SCOPES.includes(group)) continue;
62
+ if (prefix === 'quality' && (SCOPES.includes(group) || group === 'timeout_seconds')) continue;
56
63
  if (!DEFAULT_LIMITS[group]) { ignored.push({ where, key: `${prefix}.${group}`, reason: NOT_A_LIMIT }); continue; }
57
64
  for (const [key, value] of Object.entries(values ?? {})) apply(limits, ignored, { where, prefix, group, key, value });
58
65
  }
@@ -69,5 +76,22 @@ export function resolveLimits({ global = {}, project = {}, scope = 'pr' } = {})
69
76
  applyLayer(limits, ignored, { where, prefix: 'quality', layer: file?.quality });
70
77
  applyLayer(limits, ignored, { where, prefix: `quality.${scope}`, layer: file?.quality?.[scope] });
71
78
  }
72
- return { limits, ignored };
79
+ return { limits, ignored: [...ignored, ...resolveTimeout({ global, project }).ignored] };
80
+ }
81
+
82
+ const TIMEOUT_KEY = 'quality.timeout_seconds';
83
+ const timeoutValid = (v) => Number.isInteger(v) && v >= QUALITY_TIMEOUT.min && v <= QUALITY_TIMEOUT.max;
84
+
85
+ /** { seconds, ignored }: the default, then the global file's quality.timeout_seconds, then the project's if it is longer. */
86
+ export function resolveTimeout({ global = {}, project = {} } = {}) {
87
+ let seconds = QUALITY_TIMEOUT.default;
88
+ const ignored = [];
89
+ for (const [where, file] of [['global', global], ['project', project]]) {
90
+ const value = file?.quality?.timeout_seconds;
91
+ if (value === undefined) continue;
92
+ if (!timeoutValid(value)) ignored.push({ where, key: TIMEOUT_KEY, reason: `not a whole number of seconds from ${QUALITY_TIMEOUT.min} to ${QUALITY_TIMEOUT.max}` });
93
+ else if (where === 'project' && value < seconds) ignored.push({ where, key: TIMEOUT_KEY, reason: `a project may only lengthen the time, and ${value} is shorter than ${seconds}` });
94
+ else seconds = value;
95
+ }
96
+ return { seconds, ignored };
73
97
  }
@@ -4,20 +4,40 @@
4
4
  import path from 'node:path';
5
5
  import { spawnSync } from 'node:child_process';
6
6
  import { fileURLToPath } from 'node:url';
7
+ import { loadConfig } from '../config-files.mjs';
8
+ import { QUALITY_TIMEOUT, resolveTimeout } from './limits.mjs';
7
9
 
8
10
  const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'somi.mjs');
9
- export const QUALITY_TIMEOUT_MS = 120000;
10
11
  const MAX_SHOWN = 20;
11
12
 
13
+ /** The seconds the gate may run in this project, from the user's and the project's config. An unreadable config keeps the default. */
14
+ export function qualityTimeout(root, env = process.env) {
15
+ try {
16
+ const loaded = loadConfig(root, env);
17
+ return resolveTimeout({ global: loaded.global.config ?? {}, project: loaded.project.config ?? {} }).seconds;
18
+ } catch {
19
+ return QUALITY_TIMEOUT.default;
20
+ }
21
+ }
22
+
23
+ const timedOut = (seconds) => `the quality gate did not finish within ${seconds} s. To give it longer, set quality.timeout_seconds in your own config, up to ${QUALITY_TIMEOUT.max}; /somi-config can do it`;
24
+
12
25
  const describe = (v) => {
13
26
  const where = `${v.file}:${v.line}${v.name ? ` ${v.name}` : ''}`;
14
27
  if (v.rule === 'clone') return `clone ${where}: ${v.value} lines also at ${v.other.file}:${v.other.line}`;
15
28
  return `${v.rule} ${where}: ${v.value} over ${v.limit}${v.before !== undefined ? `, was ${v.before}` : ''}`;
16
29
  };
17
30
 
18
- /** The gate's own report for one scope, or { error } when it could not run. */
31
+ /** The gate's own report for one scope, or { error } when it could not run, with timed_out when it ran out of time. */
19
32
  export function runQuality(root, { scope, env = process.env }) {
20
- const r = spawnSync(process.execPath, [CLI, 'quality', '--scope', scope], { cwd: root, env, encoding: 'utf8', timeout: QUALITY_TIMEOUT_MS, killSignal: 'SIGKILL', maxBuffer: 32 * 1024 * 1024 });
33
+ const seconds = qualityTimeout(root, env);
34
+ const r = spawnSync(process.execPath, [CLI, 'quality', '--scope', scope], { cwd: root, env, encoding: 'utf8', timeout: seconds * 1000, killSignal: 'SIGKILL', maxBuffer: 32 * 1024 * 1024 });
35
+ return gateOutcome(r, seconds);
36
+ }
37
+
38
+ /** What one run of the gate's process means: its report, or { error } and, when it ran out of time, timed_out. */
39
+ export function gateOutcome(r, seconds) {
40
+ if (r.error?.code === 'ETIMEDOUT') return { error: timedOut(seconds), timed_out: true };
21
41
  let result = null;
22
42
  try { result = JSON.parse(r.stdout); } catch { /* reported below */ }
23
43
  if (!result || (r.status !== 0 && r.status !== 1)) return { error: `the quality gate could not run: ${(r.stderr || r.error?.message || 'no output').trim().split('\n')[0].slice(0, 200)}` };
@@ -30,9 +50,9 @@ export function describeAll(violations, scope) {
30
50
  return lines.length > MAX_SHOWN ? [...lines.slice(0, MAX_SHOWN), `and ${lines.length - MAX_SHOWN} more: somi_quality with scope ${scope} lists them`] : lines;
31
51
  }
32
52
 
33
- /** { ok, failures: [line], warnings: n } for one scope, where each failure names the rule, the place and the numbers. */
53
+ /** { ok, failures: [line], warnings: n } for one scope, where each failure names the rule, the place and the numbers, or { error }. */
34
54
  export function qualityStep(root, { scope, env = process.env }) {
35
55
  const result = runQuality(root, { scope, env });
36
- if (result.error) return { ok: false, failures: [result.error], warnings: 0 };
56
+ if (result.error) return { ok: false, failures: [result.error], warnings: 0, error: result.error };
37
57
  return { ok: result.ok, failures: describeAll(result.violations, scope), warnings: result.warnings.length };
38
58
  }
@@ -8,7 +8,7 @@ export class StateError extends Error {}
8
8
 
9
9
  export function statePaths(root, env = process.env) {
10
10
  const dir = env.SOMI_STATE_DIR ? path.resolve(env.SOMI_STATE_DIR) : path.join(root, '.somi', 'state');
11
- return { dir, reviews: path.join(dir, 'reviews.jsonl'), check: path.join(dir, 'check.json') };
11
+ return { dir, reviews: path.join(dir, 'reviews.jsonl'), check: path.join(dir, 'check.json'), turn: path.join(dir, 'turn.json') };
12
12
  }
13
13
 
14
14
  export function refuseLink(p) {
@@ -185,6 +185,7 @@ function qualityTool(ctx, a) {
185
185
  const scope = a.scope ?? 'pr';
186
186
  if (!SCOPES.includes(scope)) return textResult(`scope is one of ${SCOPES.join(', ')}.`, true);
187
187
  const r = runQuality(ctx.root, { scope, env: ctx.env });
188
+ if (r.timed_out) return textResult({ ok: false, scope, error: r.error, advice: 'Tell the user the gate ran out of time on this change, and that a longer quality.timeout_seconds in their own config gives it more. It is not a pass. Do not change code for it.' }, true);
188
189
  if (r.error) return textResult(r.error, true);
189
190
  const worst = CHANGE_SCOPES.includes(scope) ? {} : { most_complex: r.summary.most_complex.slice(0, 5), most_findings: r.summary.most_findings.slice(0, 5) };
190
191
  const ignored = r.ignored_config ? { ignored_config: r.ignored_config } : {};