@skathio/somi 5.0.1 → 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.1",
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.1",
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.1",
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.1",
14
+ "version": "5.0.2",
15
15
  "tags": [
16
16
  "workflow",
17
17
  "agents",
package/VERSION CHANGED
@@ -1 +1 @@
1
- 5.0.1
1
+ 5.0.2
@@ -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,15 +21,21 @@ 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 });
33
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.
34
41
  const qualityReason = quality.error
@@ -38,7 +45,6 @@ runHook(() => {
38
45
  ...(quality.ok ? [] : [qualityReason]),
39
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.`] : []),
40
47
  ];
41
- try { writeStateFile(root, asked, `${JSON.stringify({ tree: plan.tree })}\n`); } catch { return; }
42
48
  if (reasons.length === 0) return;
43
49
  process.stdout.write(`${JSON.stringify({ decision: 'block', reason: reasons.join('\n\n') })}\n`);
44
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.1",
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",
@@ -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
  }
@@ -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) {