@skathio/somi 5.0.1 → 5.0.3

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.
Binary file
@@ -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.3",
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.3",
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.3",
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.3",
15
15
  "tags": [
16
16
  "workflow",
17
17
  "agents",
package/README.md CHANGED
@@ -57,18 +57,20 @@ Start with SoMi as the session's agent and just talk to it:
57
57
  claude --agent somi:somi # or: copilot --agent somi:somi
58
58
  ```
59
59
 
60
+ To start that way with the model your config sets for the conversation's tier, `somi launch claude` or `somi launch copilot` starts the host with `--agent somi:somi` and that model, and Copilot in experimental mode for `/somi-deliver`. Anything after it goes to the host. Ask `/somi-config` for the full command, and wrap it in an alias or function of your own, on Linux, macOS or Windows.
61
+
60
62
  Everything is done from the chat. Ask for a change, a bug fix, a refactor, a plan, a design, a review, an upgrade or the pull request text in plain words, or paste a ticket, and SoMi's agent picks the workflow. Outside SoMi's agent, plain prompts are not routed, and SoMi says so at session start. In a Copilot session already running, `/agent somi` switches to it. Six commands do the rest:
61
63
 
62
64
  | Command | What it does |
63
65
  |---|---|
64
66
  | `/somi <anything>` | Routes anything, the way the agent does with plain words. Use it from another agent. |
65
- | `/somi-deliver <work or ticket>` | Runs large work as SoMi's staged workflow. Only you can start it. On Copilot, ask `/somi-config` to register it once, and turn on `/experimental`. |
67
+ | `/somi-deliver <work or ticket>` | Runs large work as SoMi's staged workflow. Only you can start it. On Copilot, it needs `/experimental`; SoMi registers it at session start, so a session already open gets it after `/clear`. |
66
68
  | `/somi-review` | Reviews the current changes, whether or not the diff calls for it. |
67
69
  | `/somi-quality [commit \| repo]` | Checks the code against the quality limits: the branch, one commit, or the whole codebase. |
68
70
  | `/somi-status` | Shows the open plan, decisions and findings. |
69
71
  | `/somi-config` | Shows and changes the models each tier uses and the quality limits, and checks the setup. |
70
72
 
71
- On Claude Code they also answer to `/somi:somi-review` and so on. On Copilot, SoMi's commands are listed as skills.
73
+ On Claude Code they also answer to `/somi:somi-review` and so on. On Copilot, SoMi's commands are listed as skills, by their plain names only: type `/somi-deliver`, not `/somi:somi-deliver`.
72
74
 
73
75
  ## Set your tiers
74
76
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 5.0.1
1
+ 5.0.3
@@ -5,8 +5,10 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { pluginRoot, projectRoot, readPayload, runHook } from '../lib/common.mjs';
8
+ import { globalConfigPath, readConfigFile } from '../../scripts/lib/config-files.mjs';
8
9
  import { sandboxSettings, settingsWarnings } from '../../scripts/lib/doctor.mjs';
9
10
  import { stateIsTracked } from '../../scripts/lib/git-tree.mjs';
11
+ import { copilotWorkflowsOn, installCopilotExtension, isInside } from '../../scripts/lib/init.mjs';
10
12
  import { readLedger } from '../../scripts/lib/ledger.mjs';
11
13
  import { planStatus } from '../../scripts/lib/plan.mjs';
12
14
  import { listShards } from '../../scripts/lib/shards.mjs';
@@ -28,6 +30,19 @@ function projectParts(project) {
28
30
  return parts;
29
31
  }
30
32
 
33
+ // Copilot loads a workflow only from an extension, so the user's copy is written here, where a missing step would otherwise surface
34
+ // as /somi-deliver failing. It is said only when it was written, because a session that started before then does not have it yet.
35
+ // A copy inside the project, such as a vendored one, serves only that project, so it does not become every project's.
36
+ function copilotWorkflows(root, project) {
37
+ if (isInside(project, root)) return [];
38
+ try {
39
+ const file = globalConfigPath();
40
+ if (!copilotWorkflowsOn(file ? readConfigFile(file) : null)) return [];
41
+ const { written } = installCopilotExtension({ pluginRoot: root });
42
+ return written ? ['SoMi just registered its staged workflow, /somi-deliver, with Copilot CLI for every project. It loads from the next session or after /clear. Mention it only if the user asks for /somi-deliver.'] : [];
43
+ } catch { return []; }
44
+ }
45
+
31
46
  runHook(() => {
32
47
  const payload = readPayload();
33
48
  const root = pluginRoot();
@@ -38,6 +53,7 @@ runHook(() => {
38
53
  const warnings = settingsWarnings(host, sandboxSettings({ host, root: projectRoot() }));
39
54
  if (warnings.length > 0) parts.push(`WARNING: the OS sandbox, SoMi's security boundary, needs attention: ${warnings[0]}. Hooks are tripwires, not a boundary. Tell the user once, in one line, and do not repeat it. If they ask for the detail, run \`somi doctor\` and relay it.`);
40
55
  parts.push(...projectParts(projectRoot()));
56
+ if (host === 'copilot') parts.push(...copilotWorkflows(root, projectRoot()));
41
57
  const notice = updateNotice();
42
58
  if (notice) parts.push(notice);
43
59
  // Claude Code names the active agent here. Copilot CLI does not, so there the model is told how to tell from its own instructions.
@@ -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.3",
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",
@@ -117,8 +117,8 @@ const LARGE = (request) => String(request ?? '').length > LONG_REQUEST;
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
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
- 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
- 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.`;
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. To start sessions with SoMi's agent on its tier's model, \`${somiCommand('launch claude')}\` or \`${somiCommand('launch copilot')}\` does it, with anything after it passed to the host: give the user that command for an alias of their own.${host === 'claude' ? '' : ' SoMi registers the staged workflow, /somi-deliver, with Copilot for every project at session start, so there is nothing to run for it: a session that started before that gets it after /clear, and Copilot runs it only in experimental mode.'}`;
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. If Copilot says no workflow is registered by that name, this session started before SoMi registered it: tell the user that /clear or a new session loads it, and that /experimental must be on'}. 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.';
123
123
 
124
124
  // With no rule to go on and the whole table to choose from, a request is new work. Asking the model to pick costs a turn and lets it
@@ -6,6 +6,7 @@ import fs from 'node:fs';
6
6
  import os from 'node:os';
7
7
  import path from 'node:path';
8
8
  import { spawnSync } from 'node:child_process';
9
+ import { copilotExtensionFile, copilotWorkflowsOn, projectExtensionWarnings } from './init.mjs';
9
10
  import { resolveSpawn } from './tiers.mjs';
10
11
 
11
12
  const WSL_REMEDY = 'Native Windows has no OS sandbox for agents. Run the agent inside WSL2 and run this again there.';
@@ -64,6 +65,14 @@ export function duplicateHookWarnings(root) {
64
65
  return fs.existsSync(file) ? [`${file} was written by an earlier somi init, and Copilot CLI now runs the plugin's own hooks, so every SoMi hook runs twice; delete that file`] : [];
65
66
  }
66
67
 
68
+ // The session-start hook writes the user's copy, so none there means the hooks did not run or the global config turned it off. Only the
69
+ // global config says it is off, as only it can turn it off.
70
+ export function copilotWorkflowWarnings(host, root, { config = {}, home = os.homedir(), env = process.env } = {}) {
71
+ if (host !== 'copilot' || !copilotWorkflowsOn(config)) return [];
72
+ const missing = fs.existsSync(copilotExtensionFile(env, home)) ? [] : [`${copilotExtensionFile(env, home)} is missing, so /somi-deliver has no workflow to run; start a new session, or run \`somi init --host copilot\``];
73
+ return [...missing, ...projectExtensionWarnings(root)];
74
+ }
75
+
67
76
  // A plugin's hooks can fail to load without any error. The audit hook runs on every tool call, so a log with nothing recent means none of them ran.
68
77
  export function hookWarnings(root, { now = Date.now(), env = process.env } = {}) {
69
78
  const log = env.SOMI_AUDIT_LOG || path.join(root, '.somi', 'audit.log');
@@ -71,7 +80,7 @@ export function hookWarnings(root, { now = Date.now(), env = process.env } = {})
71
80
  return ['no hook has logged a tool call here in the last hour, so the tripwire hooks may not be running on this host; run this from inside an agent session, and check that the SoMi plugin is enabled'];
72
81
  }
73
82
 
74
- export function runDoctor({ root, host, config = {}, platform = process.platform, env = process.env, home = os.homedir(), exec = defaultExec, removeFile = fs.rmSync, pid = process.pid }) {
83
+ export function runDoctor({ root, host, config = {}, globalConfig = {}, platform = process.platform, env = process.env, home = os.homedir(), exec = defaultExec, removeFile = fs.rmSync, pid = process.pid }) {
75
84
  if (platform === 'win32') return { ok: false, verdict: 'FAIL', host, remedy: WSL_REMEDY, probes: [], warnings: [] };
76
85
  const probePath = path.join(home, `.somi-sandbox-probe-${pid}`);
77
86
  const touch = exec('touch', [probePath]);
@@ -85,7 +94,7 @@ export function runDoctor({ root, host, config = {}, platform = process.platform
85
94
  const ok = probes.every((p) => p.blocked);
86
95
  return {
87
96
  ok, verdict: ok ? 'PASS' : 'FAIL', host, probes,
88
- warnings: [...settingsWarnings(host, sandboxSettings({ host, root, home, env })), ...tierWarnings(config, host), ...autoWarnings(host, { home, env }), ...hookWarnings(root, { env }), ...duplicateHookWarnings(root)],
97
+ warnings: [...settingsWarnings(host, sandboxSettings({ host, root, home, env })), ...tierWarnings(config, host), ...autoWarnings(host, { home, env }), ...hookWarnings(root, { env }), ...duplicateHookWarnings(root), ...copilotWorkflowWarnings(host, root, { config: globalConfig, home, env })],
89
98
  remedy: ok ? undefined : 'Enable the sandbox: `somi doctor --profile` prints the settings to merge into the host\'s own. Then check again from inside an agent session, because a command typed at a `!` prompt usually bypasses the sandbox.',
90
99
  };
91
100
  }
@@ -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');
@@ -1,23 +1,72 @@
1
- // init.mjs: writes the extension that registers SoMi's staged workflows with Copilot CLI, which loads a workflow only from an extension.
2
- // Copilot CLI runs the plugin's own hooks, so nothing else is written, and the Claude Code plugin install needs none of this.
1
+ // init.mjs: registers SoMi's staged workflows with Copilot CLI, which loads a workflow only from an extension. Copilot also reads
2
+ // extensions from the user's own folder, so one file there serves every project, and the session-start hook keeps it pointing at the
3
+ // installed plugin. Nothing is written into a project, and the Claude Code plugin install needs none of this.
3
4
 
4
5
  import fs from 'node:fs';
6
+ import os from 'node:os';
5
7
  import path from 'node:path';
6
8
  import { pathToFileURL } from 'node:url';
7
9
 
8
- // Copilot loads a workflow only from an extension. This one is a few lines that load SoMi's own module from the plugin.
10
+ const MARK = '// Written by SoMi:';
11
+ // An earlier somi init wrote this into the project. With the user's copy as well, both register the same workflow names.
12
+ const PROJECT_MARK = '// Written by somi init:';
13
+
14
+ const isLink = (p) => { try { return fs.lstatSync(p).isSymbolicLink(); } catch { return false; } };
15
+
16
+ export const copilotExtensionFile = (env = process.env, home = os.homedir()) => path.join(env.COPILOT_HOME || path.join(home, '.copilot'), 'extensions', 'somi', 'extension.mjs');
17
+
18
+ // A few lines that load SoMi's own module from the plugin. When the plugin is gone, it joins with nothing rather than failing to load.
9
19
  export function copilotExtension(pluginRoot) {
10
20
  const lib = pathToFileURL(path.join(pluginRoot, 'scripts', 'lib', 'copilot-workflow.mjs')).href;
11
- return `// Written by somi init: registers SoMi's staged workflows with Copilot CLI. Remove this folder to turn them off.\nimport { defineWorkflow, joinSession } from '@github/copilot-sdk/extension';\n\nconst { registerCopilotWorkflows } = await import(${JSON.stringify(lib)});\nawait registerCopilotWorkflows({ defineWorkflow, joinSession });\n`;
21
+ return `${MARK} registers SoMi's staged workflows with Copilot CLI for every project. SoMi rewrites it at session start while the plugin is
22
+ // installed. To turn it off, set "copilot": { "workflows": false } in SoMi's global config and delete this folder.
23
+ import fs from 'node:fs';
24
+ import { defineWorkflow, joinSession } from '@github/copilot-sdk/extension';
25
+
26
+ const lib = new URL(${JSON.stringify(lib)});
27
+ if (fs.existsSync(lib)) {
28
+ const { registerCopilotWorkflows } = await import(lib.href);
29
+ await registerCopilotWorkflows({ defineWorkflow, joinSession });
30
+ } else {
31
+ await joinSession({});
32
+ }
33
+ `;
34
+ }
35
+
36
+ /** Writes the user's copy, or brings it up to date. A file SoMi did not write is left alone, and a link is never written through. */
37
+ export function installCopilotExtension({ pluginRoot, env = process.env, home = os.homedir() }) {
38
+ const file = copilotExtensionFile(env, home);
39
+ const text = copilotExtension(pluginRoot);
40
+ try {
41
+ if (isLink(path.dirname(file)) || isLink(file)) return { written: false, file, reason: 'it is a link, and SoMi does not write through one' };
42
+ if (fs.existsSync(file)) {
43
+ const current = fs.readFileSync(file, 'utf8');
44
+ if (current === text) return { written: false, current: true, file };
45
+ if (!current.startsWith(MARK)) return { written: false, file, reason: 'a different extension.mjs is already there; SoMi leaves it alone' };
46
+ }
47
+ // A session starting at the same moment reads the old file or the new one, never half of one.
48
+ fs.mkdirSync(path.dirname(file), { recursive: true });
49
+ const temp = `${file}.${process.pid}.tmp`;
50
+ fs.writeFileSync(temp, text);
51
+ fs.renameSync(temp, file);
52
+ return { written: true, file };
53
+ } catch (e) {
54
+ return { written: false, file, reason: e.message };
55
+ }
12
56
  }
13
57
 
14
- export function writeCopilotExtension(root, pluginRoot) {
15
- return writeOnce(path.join(root, '.github', 'extensions', 'somi', 'extension.mjs'), copilotExtension(pluginRoot), 'extension.mjs');
58
+ /** Whether p is dir or inside it. A folder whose name starts with two dots is inside. */
59
+ export function isInside(dir, p) {
60
+ const rel = path.relative(dir, p);
61
+ return !(rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel));
16
62
  }
17
63
 
18
- function writeOnce(file, text, label) {
19
- if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') !== text) return { written: false, file, reason: `a different ${label} is already there; remove it first` };
20
- fs.mkdirSync(path.dirname(file), { recursive: true });
21
- fs.writeFileSync(file, text);
22
- return { written: true, file };
64
+ /** The global config can turn the user's copy off. A project's cannot, because the file serves every project. */
65
+ export const copilotWorkflowsOn = (globalConfig) => globalConfig?.copilot?.workflows !== false;
66
+
67
+ export function projectExtensionWarnings(root) {
68
+ const file = path.join(root, '.github', 'extensions', 'somi', 'extension.mjs');
69
+ let text = '';
70
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
71
+ return text.startsWith(PROJECT_MARK) ? [`${file} was written by an earlier somi init, and SoMi now registers its workflows once for every project, so they are registered twice here; delete that folder`] : [];
23
72
  }
@@ -0,0 +1,65 @@
1
+ // launch.mjs: starts Claude Code or Copilot CLI with SoMi's agent, on the model the user's global config sets for the conversation's
2
+ // tier. Only the global config counts here: a project's is cloned input, and it should not pick the model a session starts on.
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { mainTier, resolveSpawn } from './tiers.mjs';
7
+
8
+ export const LAUNCH_HOSTS = Object.freeze(['claude', 'copilot']);
9
+ const AGENT = 'somi:somi';
10
+
11
+ const passed = (extra, flag) => extra.some((a) => a === flag || a.startsWith(`${flag}=`));
12
+
13
+ /** The command and arguments to run. What the user passes comes last, and a flag they pass themselves is not added. */
14
+ export function launchPlan({ host, config = {}, extra = [] }) {
15
+ const tier = mainTier(config);
16
+ const { model } = resolveSpawn(config, host, tier);
17
+ const args = [
18
+ ...(passed(extra, '--agent') ? [] : ['--agent', AGENT]),
19
+ ...(model && !passed(extra, '--model') ? ['--model', model] : []),
20
+ // /somi-deliver runs as a Copilot workflow, which needs experimental mode.
21
+ ...(host === 'copilot' && !passed(extra, '--experimental') && !passed(extra, '--no-experimental') ? ['--experimental'] : []),
22
+ ...extra,
23
+ ];
24
+ const warnings = model ? [] : [`no model is set for tier ${tier} on ${host}, so ${host} starts on its own default; set tiers.${host}.${tier} in SoMi's global config`];
25
+ return { command: host, args, tier, model, warnings };
26
+ }
27
+
28
+ // Windows: an npm install puts each host on the PATH as a .cmd shim, which only cmd.exe can start, so the line is quoted for cmd.exe
29
+ // and for the C runtime that splits it again, the way cross-spawn does it. A native .exe starts directly, as it does everywhere else.
30
+ const META = /([()\][%!^"`<>&|;, *?])/g;
31
+ const escapeCommand = (file) => file.replace(META, '^$1');
32
+ function escapeArgument(arg, shim) {
33
+ const quoted = `"${String(arg).replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, '$1$1')}"`.replace(META, '^$1');
34
+ // A batch file that forwards %* hands its arguments to cmd.exe once more, so they are escaped for that pass too.
35
+ return shim ? quoted.replace(META, '^$1') : quoted;
36
+ }
37
+
38
+ const isFile = (f) => { try { return fs.statSync(f).isFile(); } catch { return false; } };
39
+ const readText = (f) => fs.readFileSync(f, 'utf8');
40
+
41
+ // Every package manager's shim (npm, pnpm, Yarn, nvm-windows, volta) forwards %*, wherever it is installed, so the file's own text
42
+ // decides. One that cannot be read is escaped twice: too many carets only garble an argument, too few let cmd.exe run part of it.
43
+ function forwardsArguments(file, read) {
44
+ try { return read(file).includes('%*'); } catch { return true; }
45
+ }
46
+
47
+ /** Where Windows finds a command: each PATH folder in turn, trying each PATHEXT extension. */
48
+ export function findOnWindowsPath(name, env, exists = isFile) {
49
+ const exts = (env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
50
+ for (const dir of (env.PATH ?? env.Path ?? '').split(';').filter(Boolean)) {
51
+ for (const ext of exts) if (exists(path.win32.join(dir, `${name}${ext}`))) return path.win32.join(dir, `${name}${ext}`);
52
+ }
53
+ return null;
54
+ }
55
+
56
+ /** How to spawn the command without a shell on POSIX, and on Windows whether it is an .exe or a .cmd shim. Null when it is not found. */
57
+ export function spawnPlan(command, args, { platform = process.platform, env = process.env, exists = isFile, read = readText } = {}) {
58
+ if (platform !== 'win32') return { file: command, args, options: {} };
59
+ const found = findOnWindowsPath(command, env, exists);
60
+ if (!found) return null;
61
+ if (!/\.(cmd|bat)$/i.test(found)) return { file: found, args, options: {} };
62
+ const shim = forwardsArguments(found, read);
63
+ const line = [escapeCommand(found), ...args.map((a) => escapeArgument(a, shim))].join(' ');
64
+ return { file: env.ComSpec || env.COMSPEC || 'cmd.exe', args: ['/d', '/s', '/c', `"${line}"`], options: { windowsVerbatimArguments: true } };
65
+ }
@@ -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) {
package/scripts/somi.mjs CHANGED
@@ -12,20 +12,24 @@
12
12
  // somi status | migrate
13
13
  // somi setup [--host claude|copilot] makes SoMi the session agent, on the model set for its tier
14
14
  // somi doctor [--host claude|copilot] [--profile]
15
- // somi init --host copilot registers the staged workflow with Copilot CLI
15
+ // somi init --host copilot registers the staged workflow with Copilot CLI, once for every project
16
+ // somi launch claude|copilot [args...] starts the host with SoMi's agent, on the model set for its tier
16
17
  //
17
18
  // Exit codes: 0 done, 1 a check, the doctor or the pull request gate failed, 64 the request was refused.
18
19
 
20
+ import { spawn } from 'node:child_process';
19
21
  import fs from 'node:fs';
22
+ import os from 'node:os';
20
23
  import path from 'node:path';
21
24
  import { parseArgs } from 'node:util';
22
25
  import { fileURLToPath } from 'node:url';
23
26
  import { advise } from './lib/advisor.mjs';
24
27
  import { runCheck } from './lib/check.mjs';
25
- import { ConfigFileError, loadConfig } from './lib/config-files.mjs';
28
+ import { ConfigFileError, globalConfigPath, loadConfig, readConfigFile } from './lib/config-files.mjs';
26
29
  import { duplicateHookWarnings, runDoctor } from './lib/doctor.mjs';
27
30
  import { commitBase, listFiles, repoRoot, resolveRef, snapshotTree, stateIsTracked, workBase } from './lib/git-tree.mjs';
28
- import { writeCopilotExtension } from './lib/init.mjs';
31
+ import { installCopilotExtension, projectExtensionWarnings } from './lib/init.mjs';
32
+ import { LAUNCH_HOSTS, launchPlan, spawnPlan } from './lib/launch.mjs';
29
33
  import { addToLedger, readLedger } from './lib/ledger.mjs';
30
34
  import { migrate } from './lib/migrate.mjs';
31
35
  import { lastCheck, migratedFindings, pullRequest } from './lib/pr.mjs';
@@ -125,9 +129,9 @@ function doctor(args) {
125
129
  }
126
130
  let root = process.cwd();
127
131
  try { root = repoRoot(root); } catch { /* not in a repository */ }
128
- let config = {};
129
- try { config = loadConfig(root).config ?? {}; } catch { /* reported elsewhere */ }
130
- const report = runDoctor({ root, host, config });
132
+ let loaded = null;
133
+ try { loaded = loadConfig(root); } catch { /* reported elsewhere */ }
134
+ const report = runDoctor({ root, host, config: loaded?.config ?? {}, globalConfig: loaded?.global.config ?? {} });
131
135
  print(report);
132
136
  return report.ok ? 0 : 1;
133
137
  }
@@ -142,13 +146,40 @@ function slotCommand(ctx, args) {
142
146
  return 0;
143
147
  }
144
148
 
149
+ // The session-start hook does this on its own, so init is for a session that started before the plugin was installed.
145
150
  function initCommand(ctx, args) {
146
151
  const { values } = parseArgs({ args, options: { host: { type: 'string' } } });
147
152
  if (values.host !== 'copilot') throw new StateError('init takes --host copilot; the Claude Code plugin needs no setup');
148
- const extension = writeCopilotExtension(ctx.root, PLUGIN_ROOT);
149
- const [duplicate] = duplicateHookWarnings(ctx.root);
150
- print({ extension, workflows: 'Copilot runs workflows in experimental mode: start it with --experimental, or turn it on with /experimental.', ...(duplicate ? { warning: duplicate } : {}) });
151
- return extension.written ? 0 : 1;
153
+ const extension = installCopilotExtension({ pluginRoot: PLUGIN_ROOT, env: ctx.env });
154
+ const warnings = [...duplicateHookWarnings(ctx.root), ...projectExtensionWarnings(ctx.root)];
155
+ print({ extension, workflows: 'Copilot loads it at the next session start or after /clear, and runs workflows in experimental mode: start with --experimental, or turn it on with /experimental.', ...(warnings.length ? { warnings } : {}) });
156
+ return extension.written || extension.current ? 0 : 1;
157
+ }
158
+
159
+ function globalConfig() {
160
+ const file = globalConfigPath();
161
+ try { return (file && readConfigFile(file)) ?? {}; } catch (e) {
162
+ if (!(e instanceof ConfigFileError)) throw e;
163
+ process.stderr.write('somi: ignoring an unreadable global config; the built-in tiers apply\n');
164
+ return {};
165
+ }
166
+ }
167
+
168
+ // The host owns the terminal while it runs. Ctrl-C reaches it from the terminal directly, so this process only waits for it.
169
+ function launch(args) {
170
+ const [host, ...extra] = args;
171
+ if (!LAUNCH_HOSTS.includes(host)) throw new StateError(`launch takes ${LAUNCH_HOSTS.join(' or ')}, then any arguments for it`);
172
+ const plan = launchPlan({ host, config: globalConfig(), extra });
173
+ for (const w of plan.warnings) process.stderr.write(`somi: ${w}\n`);
174
+ const run = spawnPlan(plan.command, plan.args);
175
+ if (!run) throw new StateError(`${host} is not on the PATH`);
176
+ for (const sig of ['SIGINT', 'SIGQUIT']) process.on(sig, () => {});
177
+ return new Promise((resolve, reject) => {
178
+ const child = spawn(run.file, run.args, { stdio: 'inherit', ...run.options });
179
+ for (const sig of ['SIGTERM', 'SIGHUP']) process.on(sig, () => child.kill(sig));
180
+ child.on('error', (e) => reject(e.code === 'ENOENT' ? new StateError(`${host} is not on the PATH`) : e));
181
+ child.on('exit', (code, signal) => resolve(code ?? 128 + (os.constants.signals[signal] ?? 0)));
182
+ });
152
183
  }
153
184
 
154
185
  const printed = (value, ok = true) => { print(value); return ok ? 0 : 1; };
@@ -190,8 +221,9 @@ const COMMANDS = {
190
221
  function main(argv) {
191
222
  const [command, ...args] = argv;
192
223
  if (command === 'doctor') return doctor(args);
224
+ if (command === 'launch') return launch(args);
193
225
  const run = Object.hasOwn(COMMANDS, command ?? '') ? COMMANDS[command] : null;
194
- if (!run) throw new StateError('somi takes route, review, check, quality, status, pr, plan, setup, slot, ledger, migrate, doctor or init');
226
+ if (!run) throw new StateError('somi takes route, review, check, quality, status, pr, plan, setup, slot, ledger, migrate, doctor, init or launch');
195
227
  return run(makeContext(), args);
196
228
  }
197
229