introsio 0.0.0-stage → 0.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.
@@ -0,0 +1,10 @@
1
+ import claude from './claude.mjs';
2
+ import codex from './codex.mjs';
3
+ import gemini from './gemini.mjs';
4
+ import cursor from './cursor.mjs';
5
+ import opencode from './opencode.mjs';
6
+ import vscode from './vscode.mjs';
7
+ import windsurf from './windsurf.mjs';
8
+
9
+ export const AGENTS = [claude, codex, gemini, cursor, opencode, vscode, windsurf];
10
+ export const agentById = (id) => AGENTS.find((agent) => agent.id === id);
@@ -0,0 +1,64 @@
1
+ // OpenCode: MCP in opencode.json, /introsio-execute in commands/, and a plugin (OpenCode has no shell hooks).
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { join, editJson, markdownCommand, existsDir, existsFile, hasCli, SERVER_NAME, COMMAND_NAME } from './common.mjs';
5
+ import { readJsonSafe, readText } from '../lib/jsonFile.mjs';
6
+ import { xdgConfigHome } from '../lib/paths.mjs';
7
+
8
+ const paths = (ctx) => {
9
+ const base = ctx.scope === 'project' ? join(ctx.root, '.opencode') : join(xdgConfigHome(ctx.env), 'opencode');
10
+ return {
11
+ config: ctx.scope === 'project' ? join(ctx.root, 'opencode.json') : join(base, 'opencode.json'),
12
+ command: join(base, 'commands', `${COMMAND_NAME}.md`),
13
+ plugin: join(base, 'plugins', 'introsio.js'),
14
+ };
15
+ };
16
+
17
+ function pluginSource(ctx, pluginFile) {
18
+ const template = readText(join(ctx.kitSource, 'opencode', 'introsio.template.js'));
19
+ const target = (file) => {
20
+ const absolute = join(ctx.kitInstallDir, 'hook', file);
21
+ if (ctx.scope !== 'project') return pathToFileURL(absolute).href;
22
+ const relative = path.relative(path.dirname(pluginFile), absolute).split(path.sep).join('/');
23
+ return relative.startsWith('.') ? relative : `./${relative}`;
24
+ };
25
+ return template.replace('__ENGINE__', target('engine.mjs')).replace('__NORMALIZE__', target('normalize.mjs'));
26
+ }
27
+
28
+ export default {
29
+ id: 'opencode',
30
+ label: 'OpenCode',
31
+ hooks: 'blocking (plugin)',
32
+ detect: (ctx) => existsDir(join(xdgConfigHome(ctx.env), 'opencode')) || hasCli('opencode', ctx.env),
33
+ install(ctx, writer) {
34
+ const p = paths(ctx);
35
+ const report = { connect: null, command: p.command, hooks: 'blocking (plugin)', next: [] };
36
+ const config = editJson(writer, p.config, (value) => {
37
+ value.$schema = value.$schema ?? 'https://opencode.ai/config.json';
38
+ value.mcp = value.mcp ?? {};
39
+ const next = { type: 'remote', url: ctx.url, enabled: true };
40
+ if (JSON.stringify(value.mcp[SERVER_NAME]) === JSON.stringify(next)) return false;
41
+ value.mcp[SERVER_NAME] = next;
42
+ return true;
43
+ });
44
+ report.connect = config.error ?? (config.manual ? `manual — add "mcp": { "${SERVER_NAME}": { "type": "remote", "url": "${ctx.url}" } } to ${p.config}` : config.changed ? 'added' : 'already connected');
45
+ report.next.push(`Sign in: opencode mcp auth ${SERVER_NAME}. Then in OpenCode: /${COMMAND_NAME} <project>`);
46
+ writer.writeText(p.command, markdownCommand(ctx));
47
+ writer.writeText(p.plugin, pluginSource(ctx, p.plugin));
48
+ return report;
49
+ },
50
+ uninstall(ctx, writer) {
51
+ const p = paths(ctx);
52
+ editJson(writer, p.config, (value) => (value.mcp?.[SERVER_NAME] ? (delete value.mcp[SERVER_NAME], true) : false));
53
+ writer.remove(p.command);
54
+ writer.remove(p.plugin);
55
+ },
56
+ status(ctx) {
57
+ const p = paths(ctx);
58
+ return {
59
+ connect: readJsonSafe(p.config, {}).mcp?.[SERVER_NAME] ? 'yes' : 'no',
60
+ command: existsFile(p.command),
61
+ hooks: existsFile(p.plugin) === 'yes' ? 'blocking (plugin)' : 'not installed',
62
+ };
63
+ },
64
+ };
@@ -0,0 +1,45 @@
1
+ // VS Code (GitHub Copilot agent mode): MCP in the user mcp.json and a /introsio-execute prompt file. No hooks.
2
+ import { join, editJson, executeText, existsDir, existsFile, SERVER_NAME, COMMAND_NAME, DESCRIPTION } from './common.mjs';
3
+ import { readJsonSafe } from '../lib/jsonFile.mjs';
4
+
5
+ function userDir(ctx) {
6
+ const platform = ctx.platform ?? process.platform;
7
+ if (platform === 'darwin') return join(ctx.home, 'Library', 'Application Support', 'Code', 'User');
8
+ if (platform === 'win32') return join(ctx.env.APPDATA && !ctx.env.INTROSIO_TEST_HOME ? ctx.env.APPDATA : join(ctx.home, 'AppData', 'Roaming'), 'Code', 'User');
9
+ return join(ctx.home, '.config', 'Code', 'User');
10
+ }
11
+
12
+ const paths = (ctx) => (ctx.scope === 'project'
13
+ ? { mcp: join(ctx.root, '.vscode', 'mcp.json'), command: join(ctx.root, '.github', 'prompts', `${COMMAND_NAME}.prompt.md`) }
14
+ : { mcp: join(userDir(ctx), 'mcp.json'), command: join(userDir(ctx), 'prompts', `${COMMAND_NAME}.prompt.md`) });
15
+
16
+ export default {
17
+ id: 'vscode',
18
+ label: 'VS Code (Copilot)',
19
+ hooks: 'none — the server still resumes abandoned claims',
20
+ detect: (ctx) => existsDir(userDir(ctx)),
21
+ install(ctx, writer) {
22
+ const p = paths(ctx);
23
+ const report = { connect: null, command: p.command, hooks: 'none', next: [] };
24
+ const mcp = editJson(writer, p.mcp, (config) => {
25
+ config.servers = config.servers ?? {};
26
+ const next = { type: 'http', url: ctx.url };
27
+ if (JSON.stringify(config.servers[SERVER_NAME]) === JSON.stringify(next)) return false;
28
+ config.servers[SERVER_NAME] = next;
29
+ return true;
30
+ });
31
+ report.connect = mcp.error ?? (mcp.manual ? `manual — add "${SERVER_NAME}": { "type": "http", "url": "${ctx.url}" } under "servers" in ${p.mcp}` : mcp.changed ? 'added' : 'already connected');
32
+ report.next.push('In VS Code: open mcp.json and click Start above "introsio" to sign in. Then in Copilot Chat (Agent mode): /introsio-execute <project>');
33
+ writer.writeText(p.command, `---\nmode: agent\ndescription: ${DESCRIPTION}\n---\n\n${executeText(ctx, '${input:project:Project name or id}')}\n`);
34
+ return report;
35
+ },
36
+ uninstall(ctx, writer) {
37
+ const p = paths(ctx);
38
+ editJson(writer, p.mcp, (config) => (config.servers?.[SERVER_NAME] ? (delete config.servers[SERVER_NAME], true) : false));
39
+ writer.remove(p.command);
40
+ },
41
+ status(ctx) {
42
+ const p = paths(ctx);
43
+ return { connect: readJsonSafe(p.mcp, {}).servers?.[SERVER_NAME] ? 'yes' : 'no', command: existsFile(p.command), hooks: 'none' };
44
+ },
45
+ };
@@ -0,0 +1,32 @@
1
+ // Windsurf: MCP in mcp_config.json. No global commands or hooks — setup prints the procedure to paste as a rule.
2
+ import { join, editJson, existsDir, SERVER_NAME } from './common.mjs';
3
+ import { readJsonSafe } from '../lib/jsonFile.mjs';
4
+
5
+ const configFile = (ctx) => join(ctx.home, '.codeium', 'windsurf', 'mcp_config.json');
6
+
7
+ export default {
8
+ id: 'windsurf',
9
+ label: 'Windsurf',
10
+ hooks: 'none — the server still resumes abandoned claims',
11
+ userOnly: true,
12
+ detect: (ctx) => existsDir(join(ctx.home, '.codeium', 'windsurf')),
13
+ install(ctx, writer) {
14
+ const file = configFile(ctx);
15
+ const report = { connect: null, command: null, hooks: 'none', next: [] };
16
+ const mcp = editJson(writer, file, (config) => {
17
+ config.mcpServers = config.mcpServers ?? {};
18
+ if (config.mcpServers[SERVER_NAME]?.serverUrl === ctx.url) return false;
19
+ config.mcpServers[SERVER_NAME] = { serverUrl: ctx.url };
20
+ return true;
21
+ });
22
+ report.connect = mcp.error ?? (mcp.manual ? `manual — add "${SERVER_NAME}": { "serverUrl": "${ctx.url}" } to ${file}` : mcp.changed ? 'added' : 'already connected');
23
+ report.next.push('In Windsurf: Cascade → MCP servers → refresh, sign in to introsio. For the execute procedure run `int print-execute` and save it as a Windsurf rule or workflow.');
24
+ return report;
25
+ },
26
+ uninstall(ctx, writer) {
27
+ editJson(writer, configFile(ctx), (config) => (config.mcpServers?.[SERVER_NAME] ? (delete config.mcpServers[SERVER_NAME], true) : false));
28
+ },
29
+ status(ctx) {
30
+ return { connect: readJsonSafe(configFile(ctx), {}).mcpServers?.[SERVER_NAME] ? 'yes' : 'no', command: 'n/a', hooks: 'none' };
31
+ },
32
+ };
package/cli.mjs ADDED
@@ -0,0 +1,452 @@
1
+ #!/usr/bin/env node
2
+ // int — the Introsio agent kit: connect coding agents to Introsio, run projects with
3
+ // /introsio-execute, and manage the hooks that keep Introsio updated.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { spawnSync } from 'node:child_process';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { AGENTS, agentById } from './agents/index.mjs';
10
+ import { Writer, nodePathOf } from './agents/common.mjs';
11
+ import { FEATURES, MODES, loadConfig, saveConfig, repoSettings, updateRepo, featureOn } from './lib/config.mjs';
12
+ import { MAX_GATE_TIMEOUT_SEC } from './hook/features/gates.mjs';
13
+ import { createGit } from './lib/git.mjs';
14
+ import { homeDir, introsioDir, kitDir, logPath, configPath } from './lib/paths.mjs';
15
+ import { readText } from './lib/jsonFile.mjs';
16
+ import { loadOtherSessions, clearSessions } from './hook/state.mjs';
17
+ import { summarize } from './hook/features/log.mjs';
18
+ import { runGateCommand } from './hook/features/gates.mjs';
19
+
20
+ const KIT_SOURCE = path.dirname(fileURLToPath(import.meta.url));
21
+ const DEFAULT_URL = 'https://api.introsio.app/mcp?toolset=developer';
22
+ const KIT_DIRS = ['hook', 'lib'];
23
+ const VERSION = JSON.parse(readText(path.join(KIT_SOURCE, 'package.json')) ?? '{"version":"0"}').version;
24
+
25
+ process.stdout.on('error', (error) => {
26
+ if (error.code === 'EPIPE') process.exit(0);
27
+ });
28
+ const out = (line = '') => process.stdout.write(`${line}\n`);
29
+ const fail = (message) => {
30
+ process.stderr.write(`introsio: ${message}\n`);
31
+ process.exitCode = 1;
32
+ };
33
+
34
+ function parseArgs(argv) {
35
+ const positional = [];
36
+ const flags = {};
37
+ for (let i = 0; i < argv.length; i += 1) {
38
+ const arg = argv[i];
39
+ if (arg.startsWith('--')) {
40
+ const [key, inline] = arg.slice(2).split('=', 2);
41
+ if (inline !== undefined) flags[key] = inline;
42
+ else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) flags[key] = argv[(i += 1)];
43
+ else flags[key] = true;
44
+ } else positional.push(arg);
45
+ }
46
+ return { positional, flags };
47
+ }
48
+
49
+ function context(flags, env = process.env) {
50
+ const scope = flags.project ? 'project' : 'user';
51
+ const root = scope === 'project' ? path.resolve(flags.project === true ? '.' : flags.project) : null;
52
+ const config = loadConfig(env, { strict: true });
53
+ const kitInstallDir = scope === 'project' ? path.join(root, '.introsio', 'kit') : kitDir(env);
54
+ return {
55
+ env,
56
+ home: homeDir(env),
57
+ scope,
58
+ root,
59
+ platform: process.platform,
60
+ url: typeof flags.url === 'string' ? flags.url : (config.mcpUrl ?? DEFAULT_URL),
61
+ kitSource: KIT_SOURCE,
62
+ kitInstallDir,
63
+ hookScript: path.join(kitInstallDir, 'hook', 'introsio-hook.mjs'),
64
+ nodePath: process.execPath,
65
+ executeTemplate: readText(path.join(KIT_SOURCE, 'templates', 'execute.md')),
66
+ };
67
+ }
68
+
69
+ function selectedAgents(ctx, flags) {
70
+ if (typeof flags.agents === 'string') {
71
+ const ids = flags.agents.split(',').map((id) => id.trim()).filter(Boolean);
72
+ const unknown = ids.filter((id) => !agentById(id));
73
+ if (unknown.length) throw new Error(`unknown agent(s): ${unknown.join(', ')} — choose from ${AGENTS.map((a) => a.id).join(', ')}`);
74
+ return ids.map(agentById);
75
+ }
76
+ return AGENTS.filter((agent) => agent.detect(ctx));
77
+ }
78
+
79
+ /** Copies the hook engine to where the agents' configs point, so they never depend on this checkout. */
80
+ function installKit(ctx, writer) {
81
+ const copy = (from, to) => {
82
+ for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
83
+ const source = path.join(from, entry.name);
84
+ const target = path.join(to, entry.name);
85
+ if (entry.isDirectory()) copy(source, target);
86
+ else if (/\.(mjs|js|json)$/.test(entry.name)) writer.writeText(target, fs.readFileSync(source, 'utf8'));
87
+ }
88
+ };
89
+ for (const dir of KIT_DIRS) copy(path.join(KIT_SOURCE, dir), path.join(ctx.kitInstallDir, dir));
90
+ writer.writeText(path.join(ctx.kitInstallDir, 'package.json'), `${JSON.stringify({ type: 'module', private: true, introsio: VERSION }, null, 2)}\n`);
91
+ }
92
+
93
+ function suggestGate(dir) {
94
+ const pkg = (() => { try { return JSON.parse(readText(path.join(dir, 'package.json')) ?? ''); } catch { return null; } })();
95
+ if (pkg?.scripts?.test && !/no test specified/.test(pkg.scripts.test)) return 'npm test';
96
+ if (fs.existsSync(path.join(dir, 'Makefile')) && /^test:/m.test(readText(path.join(dir, 'Makefile')) ?? '')) return 'make test';
97
+ if (fs.existsSync(path.join(dir, 'Cargo.toml'))) return 'cargo test';
98
+ if (fs.existsSync(path.join(dir, 'go.mod'))) return 'go test ./...';
99
+ if (fs.existsSync(path.join(dir, 'pyproject.toml')) || fs.existsSync(path.join(dir, 'pytest.ini'))) return 'pytest -q';
100
+ return null;
101
+ }
102
+
103
+ function setup(flags) {
104
+ const ctx = context(flags);
105
+ if (flags.print) {
106
+ const agent = agentById(String(flags.print));
107
+ if (!agent?.print) return fail(`nothing to print for ${flags.print}`);
108
+ out(JSON.stringify(agent.print(ctx), null, 2));
109
+ return;
110
+ }
111
+ const agents = selectedAgents(ctx, flags).filter((agent) => !(ctx.scope === 'project' && agent.userOnly));
112
+ if (agents.length === 0) {
113
+ out('No coding agents found. Name them: int setup --agents claude,codex,gemini,cursor,opencode,vscode,windsurf');
114
+ process.exitCode = 1;
115
+ return;
116
+ }
117
+ const writer = new Writer({ dryRun: !!flags['dry-run'] });
118
+ installKit(ctx, writer);
119
+ out(`${flags['dry-run'] ? 'Would install' : 'Installing'} Introsio for ${agents.map((a) => a.label).join(', ')} (${ctx.scope === 'project' ? `project ${ctx.root}` : 'every project — global'})`);
120
+ out(`MCP server: ${ctx.url}`);
121
+ out('');
122
+ const next = [];
123
+ for (const agent of agents) {
124
+ try {
125
+ const report = agent.install(ctx, writer);
126
+ out(`● ${agent.label}`);
127
+ out(` connect: ${report.connect}`);
128
+ if (report.command) out(` command: /introsio-execute → ${report.command}`);
129
+ out(` hooks: ${report.hooks}`);
130
+ for (const line of report.next) next.push(`${agent.label}: ${line}`);
131
+ } catch (error) {
132
+ out(`● ${agent.label}: failed — ${error.message}`);
133
+ }
134
+ }
135
+ if (!flags['dry-run'] && typeof flags.url === 'string') {
136
+ const config = loadConfig(undefined, { strict: true });
137
+ config.mcpUrl = flags.url;
138
+ saveConfig(config);
139
+ }
140
+ out('');
141
+ out('Next:');
142
+ for (const line of next) out(` - ${line}`);
143
+ const git = createGit(process.cwd());
144
+ const root = git.root();
145
+ if (root && !repoSettings(loadConfig(undefined, { strict: true }), root).gate) {
146
+ const suggestion = suggestGate(root);
147
+ if (suggestion) out(` - Test gate for this repo (tasks complete only when it passes): int gate set "${suggestion}"`);
148
+ }
149
+ out(' - Check everything: int doctor');
150
+ if (flags['dry-run']) {
151
+ out('');
152
+ out('Dry run — files that would change:');
153
+ for (const action of writer.actions) out(` ${action}`);
154
+ }
155
+ }
156
+
157
+ function uninstall(flags) {
158
+ const ctx = context(flags);
159
+ const agents = typeof flags.agents === 'string' ? selectedAgents(ctx, flags) : AGENTS;
160
+ const writer = new Writer({ dryRun: !!flags['dry-run'] });
161
+ for (const agent of agents) {
162
+ if (ctx.scope === 'project' && agent.userOnly) continue;
163
+ try { agent.uninstall(ctx, writer); } catch (error) { out(`${agent.label}: ${error.message}`); }
164
+ }
165
+ if (typeof flags.agents !== 'string') writer.remove(ctx.kitInstallDir);
166
+ out(writer.actions.length ? `Removed Introsio from:\n${writer.actions.map((a) => ` ${a}`).join('\n')}` : 'Nothing to remove.');
167
+ out('Your settings and log in ~/.introsio stay; delete that folder to remove them too.');
168
+ }
169
+
170
+ function repoRoot(flags) {
171
+ const root = createGit(path.resolve(typeof flags.repo === 'string' ? flags.repo : '.')).root();
172
+ if (!root) throw new Error('not inside a git repository (use --repo <dir>)');
173
+ return path.resolve(root);
174
+ }
175
+
176
+ function status(flags) {
177
+ const ctx = context(flags);
178
+ out(`int ${VERSION} — hook engine ${fs.existsSync(ctx.hookScript) ? `installed at ${ctx.kitInstallDir}` : 'NOT installed (run int setup)'}`);
179
+ out('');
180
+ for (const agent of AGENTS) {
181
+ if (!agent.detect(ctx)) continue;
182
+ const s = agent.status(ctx);
183
+ out(`● ${agent.label.padEnd(18)} connect: ${s.connect.padEnd(4)} /introsio-execute: ${String(s.command).padEnd(4)} hooks: ${s.hooks}`);
184
+ }
185
+ const config = loadConfig(undefined, { strict: true });
186
+ out('');
187
+ out(`Features: ${Object.keys(FEATURES).map((name) => `${name}${featureOn(config, name) ? '' : ' (off)'}`).join(', ')}`);
188
+ const root = createGit(process.cwd()).root();
189
+ if (root) {
190
+ const settings = repoSettings(config, root);
191
+ out(`This repo (${root}): mode ${settings.mode ?? 'auto (github if the project is linked to GitHub, else local)'} · test gate ${settings.gate ? `"${settings.gate}" (${settings.gateTimeoutSec}s)` : 'off'}`);
192
+ }
193
+ if (String(process.env.INTROSIO_HOOKS ?? '').toLowerCase() === 'off') out('INTROSIO_HOOKS=off is set in this shell — hooks do nothing here.');
194
+ }
195
+
196
+ function mode(positional, flags) {
197
+ const value = positional[1];
198
+ const root = repoRoot(flags);
199
+ const config = loadConfig(undefined, { strict: true });
200
+ if (!value) {
201
+ out(`${root}: ${repoSettings(config, root).mode ?? 'auto'}`);
202
+ return;
203
+ }
204
+ if (value !== 'auto' && !MODES.includes(value)) return fail(`mode must be one of: ${MODES.join(', ')}, auto`);
205
+ saveConfig(updateRepo(config, root, { mode: value === 'auto' ? null : value }));
206
+ const explain = {
207
+ github: 'tasks complete only when the work is committed, pushed on its own branch and outcome.branch is recorded; pushes to the default branch and force pushes are blocked',
208
+ local: 'the code stays on this computer: tasks complete once the work is committed, and every git push is blocked',
209
+ off: 'no git checks before completing; push guard off',
210
+ auto: 'github when the Introsio project is linked to a GitHub repository, else local',
211
+ };
212
+ out(`${root}: mode ${value} — ${explain[value]}`);
213
+ }
214
+
215
+ async function gate(positional, flags) {
216
+ const action = positional[1];
217
+ const root = repoRoot(flags);
218
+ const config = loadConfig(undefined, { strict: true });
219
+ const settings = repoSettings(config, root);
220
+ if (action === 'set') {
221
+ const command = positional.slice(2).join(' ').trim();
222
+ if (!command) return fail('usage: int gate set "<command>" [--timeout <seconds>]');
223
+ const timeout = flags.timeout ? Number(flags.timeout) : null;
224
+ if (timeout !== null && !(timeout > 0)) return fail('--timeout must be a number of seconds');
225
+ if (timeout !== null && timeout > MAX_GATE_TIMEOUT_SEC) {
226
+ return fail(`--timeout can be at most ${MAX_GATE_TIMEOUT_SEC}s: agents stop a hook after 900s, and a gate cut off by the agent would let the completion through unchecked.`);
227
+ }
228
+ saveConfig(updateRepo(config, root, { gate: command, ...(timeout ? { gateTimeoutSec: timeout } : {}) }));
229
+ out(`${root}: claimed Introsio tasks complete only after "${command}" passes (${timeout ?? settings.gateTimeoutSec}s limit). Try it: int gate run`);
230
+ } else if (action === 'off') {
231
+ saveConfig(updateRepo(config, root, { gate: null, gateTimeoutSec: null }));
232
+ out(`${root}: test gate off`);
233
+ } else if (action === 'run') {
234
+ if (!settings.gate) return fail('no gate set — int gate set "<command>"');
235
+ out(`Running "${settings.gate}" in ${root} …`);
236
+ const result = await runGateCommand(settings.gate, root, settings.gateTimeoutSec);
237
+ out(result.output);
238
+ out(result.ok ? `✓ passed in ${Math.round(result.ms / 1000)}s` : result.timedOut ? `✗ timed out after ${settings.gateTimeoutSec}s` : `✗ failed (exit ${result.code})`);
239
+ if (!result.ok) process.exitCode = 1;
240
+ } else {
241
+ out(settings.gate ? `${root}: "${settings.gate}" (${settings.gateTimeoutSec}s)` : `${root}: no test gate — int gate set "<command>"`);
242
+ }
243
+ }
244
+
245
+ function features(positional) {
246
+ const [action, name] = positional;
247
+ const config = loadConfig(undefined, { strict: true });
248
+ if (action === 'enable' || action === 'disable') {
249
+ if (!FEATURES[name]) return fail(`unknown feature "${name}" — one of: ${Object.keys(FEATURES).join(', ')}`);
250
+ config.features[name] = action === 'enable';
251
+ saveConfig(config);
252
+ out(`${name}: ${action === 'enable' ? 'on' : 'off'}`);
253
+ return;
254
+ }
255
+ for (const [feature, description] of Object.entries(FEATURES)) out(`${featureOn(config, feature) ? '✓' : '·'} ${feature.padEnd(17)} ${description}`);
256
+ }
257
+
258
+ function claims(positional) {
259
+ if (positional[1] === 'clear') {
260
+ out(`Cleared ${clearSessions()} session record(s) on this computer. Nothing changed in Introsio — a claim there ends when it is completed or its lease expires.`);
261
+ return;
262
+ }
263
+ const now = Date.now();
264
+ const sessions = loadOtherSessions('', now).filter((session) => Object.keys(session.claims ?? {}).length);
265
+ if (sessions.length === 0) {
266
+ out('No open claims tracked on this computer.');
267
+ return;
268
+ }
269
+ for (const session of sessions) {
270
+ out(`${session.agent} session ${session.sessionId} (workerId ${session.workerId ?? '?'}, ${session.cwd ?? ''})`);
271
+ for (const claim of Object.values(session.claims)) {
272
+ const lease = claim.expiresAt ? (claim.expiresAt > now ? `lease ${Math.round((claim.expiresAt - now) / 60000)} min left` : 'lease expired') : '';
273
+ out(` - "${claim.title}" taskId ${claim.taskId} ${lease}`);
274
+ }
275
+ }
276
+ }
277
+
278
+ function parseSince(value) {
279
+ const match = String(value ?? '').match(/^(\d+)([hdw])$/);
280
+ if (!match) return null;
281
+ return Date.now() - Number(match[1]) * { h: 3_600_000, d: 86_400_000, w: 604_800_000 }[match[2]];
282
+ }
283
+
284
+ function stats(flags) {
285
+ const since = flags.since ? parseSince(flags.since) : null;
286
+ if (flags.since && since === null) return fail('--since takes e.g. 12h, 7d, 2w');
287
+ const rows = [`${logPath()}.1`, logPath()]
288
+ .flatMap((file) => (readText(file) ?? '').split('\n'))
289
+ .filter(Boolean)
290
+ .map((line) => { try { return JSON.parse(line); } catch { return null; } })
291
+ .filter(Boolean)
292
+ .filter((row) => (since === null || Date.parse(row.at) >= since) && (!flags.project || row.projectId === flags.project));
293
+ const summary = summarize(rows);
294
+ if (flags.json) {
295
+ out(JSON.stringify(summary, null, 2));
296
+ return;
297
+ }
298
+ if (rows.length === 0) {
299
+ out('No Introsio calls logged yet.');
300
+ return;
301
+ }
302
+ out(`${summary.calls} Introsio calls, ${summary.refused} refused (${Math.round((summary.refused / summary.calls) * 100)}%)`);
303
+ out('');
304
+ out('By tool:');
305
+ for (const tool of summary.tools) out(` ${tool.tool.padEnd(24)} ${String(tool.calls).padStart(5)} calls ${String(tool.refused).padStart(4)} refused ${tool.avgMs === null ? '' : `${tool.avgMs} ms avg`}`);
306
+ if (summary.topErrors.length) {
307
+ out('');
308
+ out('Most common refusals:');
309
+ for (const { error, count } of summary.topErrors) out(` ${String(count).padStart(4)}× ${error}`);
310
+ }
311
+ if (summary.retryLoops.length) {
312
+ out('');
313
+ out('Retry loops (same call refused 3+ times in a row):');
314
+ for (const loop of summary.retryLoops) out(` ${loop.tool} on ${loop.taskId}: ${loop.error ?? ''}`);
315
+ }
316
+ out('');
317
+ out('Tasks (most refusals first):');
318
+ for (const task of summary.tasks.slice(0, 15)) out(` ${task.taskId} ${task.completed ? 'done' : 'open'} ${task.calls} calls ${task.refused} refused ${task.minutes} min`);
319
+ }
320
+
321
+ /** Every hook command string in a parsed config. */
322
+ function hookCommandsIn(value, found = []) {
323
+ if (typeof value === 'string') {
324
+ if (value.includes('introsio-hook.mjs')) found.push(value);
325
+ } else if (value && typeof value === 'object') {
326
+ for (const item of Object.values(value)) hookCommandsIn(item, found);
327
+ }
328
+ return found;
329
+ }
330
+
331
+ function doctor(flags) {
332
+ let problems = 0;
333
+ const check = (ok, label, hint) => {
334
+ out(`${ok ? '✓' : '✗'} ${label}${ok || !hint ? '' : ` — ${hint}`}`);
335
+ if (!ok) problems += 1;
336
+ };
337
+ const major = Number(process.versions.node.split('.')[0]);
338
+ check(major >= 18, `Node ${process.versions.node}`, 'Node 18 or newer is required for the hooks');
339
+ let ctx;
340
+ try {
341
+ ctx = context(flags);
342
+ check(true, `settings ${configPath()}`);
343
+ } catch (error) {
344
+ check(false, `settings ${configPath()}`, `${error.message}`);
345
+ out('\n1 problem — fix the settings file first.');
346
+ process.exitCode = 1;
347
+ return;
348
+ }
349
+ check(fs.existsSync(ctx.hookScript), `hook engine at ${ctx.kitInstallDir}`, 'run int setup');
350
+ const installed = (() => { try { return JSON.parse(readText(path.join(ctx.kitInstallDir, 'package.json'))).introsio; } catch { return null; } })();
351
+ if (installed) check(installed === VERSION, `hook engine version ${installed}`, `this int is ${VERSION} — run int setup to update the installed hooks`);
352
+
353
+ const hookFiles = ctx.scope === 'project'
354
+ ? []
355
+ : [path.join(ctx.home, '.claude', 'settings.json'), path.join(ctx.home, '.codex', 'hooks.json'), path.join(ctx.home, '.gemini', 'settings.json'), path.join(ctx.home, '.cursor', 'hooks.json')];
356
+ const nodes = new Set();
357
+ for (const file of hookFiles) {
358
+ const text = readText(file);
359
+ if (!text) continue;
360
+ try { for (const command of hookCommandsIn(JSON.parse(text))) nodes.add(nodePathOf(command)); } catch { /* reported by the agent check */ }
361
+ }
362
+ nodes.delete('');
363
+ for (const node of nodes) {
364
+ check(fs.existsSync(node), `hooks run with ${node}`, 'that Node binary is gone (nvm / Homebrew upgrade?) — run int setup again to point the hooks at the current one');
365
+ }
366
+
367
+ for (const agent of AGENTS) {
368
+ if (!agent.detect(ctx)) continue;
369
+ const s = agent.status(ctx);
370
+ check(s.connect !== 'no', `${agent.label}: MCP server`, 'run int setup');
371
+ if (agent.hooks.startsWith('blocking')) check(s.hooks.startsWith('blocking'), `${agent.label}: hooks`, 'run int setup');
372
+ }
373
+ if (fs.existsSync(ctx.hookScript)) {
374
+ // Fire the installed hook, with the Node the hooks use, in a scratch state folder: a claim, then a stop — it must refuse the stop.
375
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'introsio-doctor-'));
376
+ const env = { ...process.env, INTROSIO_HOME: scratch, INTROSIO_HOOKS: '' };
377
+ const node = [...nodes].find((candidate) => fs.existsSync(candidate)) ?? process.execPath;
378
+ const fire = (event, payload) => spawnSync(node, [ctx.hookScript, 'claude', event], { input: JSON.stringify(payload), encoding: 'utf8', env, timeout: 20000 });
379
+ const started = Date.now();
380
+ fire('PostToolUse', {
381
+ session_id: 'doctor', cwd: scratch, tool_name: 'mcp__introsio__claimTask', tool_input: { projectId: 'p' },
382
+ tool_response: [{ type: 'text', text: JSON.stringify({ claimed: true, workerId: 'doctor', task: { id: 't1', title: 'Doctor check' } }) }],
383
+ });
384
+ const stop = fire('Stop', { session_id: 'doctor', cwd: scratch, stop_hook_active: false });
385
+ const ms = Date.now() - started;
386
+ let blocked = false;
387
+ try { blocked = JSON.parse(stop.stdout).decision === 'block'; } catch { /* no output */ }
388
+ check(blocked, `hook fires and refuses a stop with an open claim (2 calls in ${ms} ms)`, `unexpected output: ${stop.stdout || stop.stderr}`);
389
+ fs.rmSync(scratch, { recursive: true, force: true });
390
+ }
391
+ const errors = (readText(path.join(introsioDir(), 'errors.log')) ?? '').trim().split('\n').filter(Boolean);
392
+ const recent = errors.filter((line) => Date.now() - Date.parse(line.slice(0, 24)) < 7 * 86_400_000);
393
+ check(recent.length === 0, 'no hook errors in the last 7 days', `${recent.length} — latest: ${recent.at(-1)?.slice(0, 240)} (full log: ${path.join(introsioDir(), 'errors.log')})`);
394
+ out(problems ? `\n${problems} problem(s).` : '\nAll good.');
395
+ if (problems) process.exitCode = 1;
396
+ }
397
+
398
+ function help() {
399
+ out(`int ${VERSION} — the Introsio agent kit: connect coding agents to Introsio and keep it updated while they execute
400
+
401
+ int setup [--agents claude,codex,gemini,cursor,opencode,vscode,windsurf] [--project <repo>] [--url <mcp url>] [--dry-run]
402
+ int uninstall [--agents …] [--project <repo>]
403
+ int status what is installed, per agent and for this repo
404
+ int doctor check the install and fire a test hook
405
+
406
+ int mode github|local|off|auto this repo: push + branch required / commit only, no push / no checks
407
+ int gate set "<cmd>" [--timeout <sec>] | gate off | gate run | gate
408
+ int features | enable <name> | disable <name>
409
+ int claims | claims clear tasks your agents hold on this computer
410
+ int stats [--since 7d] [--project <id>] [--json]
411
+ int print-execute the /introsio-execute procedure, to paste where an agent has no commands
412
+
413
+ Inside an agent: /introsio-execute <project> One session without hooks: INTROSIO_HOOKS=off`);
414
+ }
415
+
416
+ async function main() {
417
+ const { positional, flags } = parseArgs(process.argv.slice(2));
418
+ const command = positional[0] ?? 'help';
419
+ try {
420
+ return await run(command, positional, flags);
421
+ } catch (error) {
422
+ return fail(error.message);
423
+ }
424
+ }
425
+
426
+ async function run(command, positional, flags) {
427
+ {
428
+ switch (command) {
429
+ case 'setup': case 'install': return setup(flags);
430
+ case 'uninstall': case 'remove': return uninstall(flags);
431
+ case 'status': return status(flags);
432
+ case 'doctor': return doctor(flags);
433
+ case 'mode': return mode(positional, flags);
434
+ case 'gate': return gate(positional, flags);
435
+ case 'features': return features([]);
436
+ case 'enable': case 'disable': return features(positional);
437
+ case 'claims': return claims(positional);
438
+ case 'stats': return stats(flags);
439
+ case 'print-execute': return out(context(flags).executeTemplate.replaceAll('$ARGUMENTS', 'the project the user names'));
440
+ case 'hook': {
441
+ // `int hook <agent> <event>` — the same entry as introsio-hook.mjs, for package-manager installs.
442
+ process.argv = [process.argv[0], path.join(KIT_SOURCE, 'hook', 'introsio-hook.mjs'), ...positional.slice(1)];
443
+ await import('./hook/introsio-hook.mjs');
444
+ return undefined;
445
+ }
446
+ case 'version': case '--version': return out(VERSION);
447
+ default: return help();
448
+ }
449
+ }
450
+ }
451
+
452
+ main();