introsio 0.0.0-stage → 0.3.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,171 @@
1
+ // Turns each agent's hook payload into one shape the engine understands:
2
+ // { agent, event, sessionId, cwd, source, stopHookActive, loopCount, transcriptPath, tool, result }
3
+ // event: session-start | before-tool | after-tool | stop | compact
4
+ // tool: { kind: introsio | shell | edit | other, raw, name, args, command, files }
5
+
6
+ /** Every Introsio MCP tool whose name alone identifies it, even under another server name. */
7
+ export const DISTINCTIVE_TOOLS = new Set([
8
+ 'claimTask', 'pauseTask', 'completeTask', 'undoTaskCompletion', 'updateSubtask', 'getReadySubtasks', 'getReadyTasks',
9
+ 'getExecutionWaves', 'getProjectPlan', 'createProjectPlan', 'getProjectState', 'updateProjectState',
10
+ 'getProjectContext', 'updateProjectContext', 'editProjectContextItems', 'recordProjectDecision',
11
+ 'exportProjectBlueprint', 'importProjectBlueprint', 'getTaskDependencies', 'addTaskDependency', 'removeTaskDependency',
12
+ ]);
13
+
14
+ const EVENT_MAP = {
15
+ // SubagentStop is deliberately absent: a subagent must not be held to its parent's claims.
16
+ claude: { SessionStart: 'session-start', PreToolUse: 'before-tool', PostToolUse: 'after-tool', Stop: 'stop', PreCompact: 'compact' },
17
+ codex: { SessionStart: 'session-start', PreToolUse: 'before-tool', PostToolUse: 'after-tool', Stop: 'stop', PreCompact: 'compact', PostCompact: 'session-start' },
18
+ gemini: { SessionStart: 'session-start', BeforeTool: 'before-tool', AfterTool: 'after-tool', AfterAgent: 'stop', PreCompress: 'compact' },
19
+ cursor: {
20
+ beforeMCPExecution: 'before-tool', afterMCPExecution: 'after-tool', beforeShellExecution: 'before-tool',
21
+ afterShellExecution: 'after-tool', afterFileEdit: 'after-tool', stop: 'stop',
22
+ },
23
+ opencode: { 'tool.execute.before': 'before-tool', 'tool.execute.after': 'after-tool', 'session.idle': 'stop', 'session.compacted': 'session-start', 'session.created': 'session-start' },
24
+ };
25
+
26
+ export const AGENTS_WITH_HOOKS = Object.keys(EVENT_MAP);
27
+
28
+ const SHELL_TOOLS = /^(bash|shell|exec_command|local_shell|run_shell_command|run_terminal_cmd|terminal)$/i;
29
+ const EDIT_TOOLS = /^(edit|write|multiedit|notebookedit|apply_patch|write_file|replace|patch|str_replace_editor|create_file|edit_file)$/i;
30
+
31
+ /** The bare tool name of an MCP tool: mcp__introsio__claimTask, mcp_introsio_claimTask, introsio_claimTask → claimTask. */
32
+ export function bareToolName(raw) {
33
+ return String(raw ?? '').split(/__|[_.:/]/).filter(Boolean).pop() ?? '';
34
+ }
35
+
36
+ export function isIntrosioTool(raw, agent) {
37
+ const name = bareToolName(raw);
38
+ if (!name) return false;
39
+ if (/introsio/i.test(String(raw)) && String(raw) !== name) return true;
40
+ if (DISTINCTIVE_TOOLS.has(name)) return true;
41
+ // Cursor passes the bare name; updateTask / getTasks etc. are only counted when the server is Introsio.
42
+ return agent === 'cursor' && /introsio/i.test(String(raw));
43
+ }
44
+
45
+ function parseMaybeJson(value) {
46
+ if (typeof value !== 'string') return value;
47
+ const text = value.trim();
48
+ if (!text || !'{['.includes(text[0])) return value;
49
+ try {
50
+ return JSON.parse(text);
51
+ } catch {
52
+ return value;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * The data an Introsio tool answered with. Agents hand the MCP result over in
58
+ * different wrappers (content blocks, { content }, a JSON string, the parsed
59
+ * object); the server always sends one text block of JSON.
60
+ */
61
+ export function parseToolResult(response) {
62
+ let value = parseMaybeJson(response);
63
+ let isError = false;
64
+ for (let depth = 0; depth < 4 && value && typeof value === 'object'; depth += 1) {
65
+ if (value.isError === true) isError = true;
66
+ const blocks = Array.isArray(value) ? value : Array.isArray(value.content) ? value.content : null;
67
+ if (blocks) {
68
+ // MCP content blocks ({ type: 'text', text }) or Gemini parts ({ text }).
69
+ const text = blocks.filter((block) => block && (block.type === 'text' || block.type === undefined) && typeof block.text === 'string').map((block) => block.text).join('');
70
+ value = parseMaybeJson(text);
71
+ continue;
72
+ }
73
+ if (value.llmContent !== undefined && !('success' in value)) {
74
+ // Gemini CLI: { llmContent, returnDisplay, error }.
75
+ if (value.error) isError = true;
76
+ value = parseMaybeJson(value.llmContent);
77
+ continue;
78
+ }
79
+ if (typeof value.result === 'string' || (value.result && typeof value.result === 'object' && !('success' in value))) {
80
+ value = parseMaybeJson(value.result);
81
+ continue;
82
+ }
83
+ if (typeof value.output === 'string' && !('success' in value) && !('claimed' in value)) {
84
+ value = parseMaybeJson(value.output);
85
+ continue;
86
+ }
87
+ break;
88
+ }
89
+ const data = value && typeof value === 'object' && !Array.isArray(value) ? value : null;
90
+ const ok = !isError && !!data && data.success !== false && !(typeof data.error === 'string' && data.success !== true && !('claimed' in data));
91
+ return { ok, data, isError };
92
+ }
93
+
94
+ /** Files named by an apply_patch body ("*** Update File: path"). */
95
+ export function patchFiles(patch) {
96
+ const files = [];
97
+ for (const match of String(patch ?? '').matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)) files.push(match[1].trim());
98
+ for (const match of String(patch ?? '').matchAll(/^\*\*\* Move to: (.+)$/gm)) files.push(match[1].trim());
99
+ return files;
100
+ }
101
+
102
+ function shellCommandOf(input) {
103
+ const command = input?.command ?? input?.cmd ?? input?.script;
104
+ if (Array.isArray(command)) {
105
+ // ["bash", "-lc", "git push"] → the script; otherwise the joined argv.
106
+ const flagIndex = command.findIndex((part) => part === '-c' || part === '-lc');
107
+ return flagIndex >= 0 ? String(command[flagIndex + 1] ?? '') : command.join(' ');
108
+ }
109
+ return typeof command === 'string' ? command : '';
110
+ }
111
+
112
+ function editFilesOf(input) {
113
+ if (!input || typeof input !== 'object') return [];
114
+ const direct = input.file_path ?? input.filePath ?? input.path ?? input.notebook_path ?? input.absolute_path;
115
+ if (typeof direct === 'string') return [direct];
116
+ const patch = input.patch ?? input.input ?? (typeof input.command === 'string' ? input.command : null);
117
+ if (typeof patch === 'string') return patchFiles(patch);
118
+ if (Array.isArray(input.edits)) return input.edits.map((edit) => edit?.file_path ?? edit?.filePath).filter(Boolean);
119
+ return [];
120
+ }
121
+
122
+ export function classifyTool(raw, input, agent) {
123
+ const args = parseMaybeJson(input);
124
+ const objectArgs = args && typeof args === 'object' && !Array.isArray(args) ? args : {};
125
+ if (isIntrosioTool(raw, agent)) return { kind: 'introsio', raw, name: bareToolName(raw), args: objectArgs };
126
+ if (SHELL_TOOLS.test(String(raw))) return { kind: 'shell', raw, command: shellCommandOf(objectArgs) || (typeof args === 'string' ? args : '') };
127
+ if (EDIT_TOOLS.test(String(raw))) return { kind: 'edit', raw, files: editFilesOf(typeof args === 'string' ? { patch: args } : objectArgs) };
128
+ return { kind: 'other', raw };
129
+ }
130
+
131
+ /** One agent payload → the engine's event, or null for an event this kit ignores. */
132
+ export function normalize(agent, hookEvent, payload) {
133
+ const map = EVENT_MAP[agent];
134
+ const eventName = hookEvent || payload?.hook_event_name || payload?.hookEventName;
135
+ const event = map?.[eventName];
136
+ if (!event) return null;
137
+ const p = payload ?? {};
138
+ const base = {
139
+ agent,
140
+ hookEvent: eventName,
141
+ event,
142
+ // Without an id, the agent process is the session — never one shared "unknown" for everybody.
143
+ sessionId: String(p.session_id ?? p.sessionId ?? p.conversation_id ?? p.sessionID ?? `${agent}-pid-${process.ppid}`),
144
+ cwd: p.cwd ?? (Array.isArray(p.workspace_roots) ? p.workspace_roots[0] : null) ?? process.cwd(),
145
+ transcriptPath: p.transcript_path ?? p.transcriptPath ?? null,
146
+ source: eventName === 'PostCompact' || eventName === 'session.compacted' ? 'compact' : (p.source ?? p.trigger ?? null),
147
+ stopHookActive: p.stop_hook_active === true || p.stopHookActive === true,
148
+ loopCount: Number(p.loop_count ?? 0) || 0,
149
+ };
150
+ if (event !== 'before-tool' && event !== 'after-tool') return base;
151
+
152
+ if (agent === 'cursor') {
153
+ if (eventName === 'beforeShellExecution' || eventName === 'afterShellExecution') {
154
+ return { ...base, tool: { kind: 'shell', raw: 'shell', command: String(p.command ?? '') }, result: null };
155
+ }
156
+ if (eventName === 'afterFileEdit') return { ...base, tool: { kind: 'edit', raw: 'edit', files: p.file_path ? [p.file_path] : [] }, result: null };
157
+ const raw = p.tool_name ?? '';
158
+ const serverHint = /introsio/i.test(String(p.url ?? p.command ?? '')) ? `introsio_${raw}` : raw;
159
+ const tool = classifyTool(serverHint, p.tool_input, agent);
160
+ return { ...base, tool, result: event === 'after-tool' ? parseToolResult(p.result_json ?? p.tool_output ?? p.result) : null };
161
+ }
162
+
163
+ const name = String(p.tool_name ?? p.toolName ?? p.tool ?? '');
164
+ // Gemini names MCP tools by bare name unless they clash; its payload says which server a tool belongs to.
165
+ const server = p.mcp_server ?? p.mcp_context?.server_name ?? p.mcp_context?.serverName ?? p.server_name ?? null;
166
+ const raw = server && !name.toLowerCase().includes(String(server).toLowerCase()) ? `${server}__${name}` : name;
167
+ const tool = classifyTool(raw, p.tool_input ?? p.toolInput ?? p.args ?? p.arguments, agent);
168
+ const response = p.tool_response ?? p.tool_output ?? p.toolResponse ?? p.output ?? p.result;
169
+ const durationMs = Number(p.duration_ms);
170
+ return { ...base, tool, result: event === 'after-tool' ? parseToolResult(response) : null, ...(Number.isFinite(durationMs) ? { durationMs } : {}) };
171
+ }
@@ -0,0 +1,46 @@
1
+ // The engine's answer in each agent's own hook output format. `null` = print nothing.
2
+
3
+ /** Nothing a hook says may flood the agent's context. */
4
+ export const MAX_MESSAGE_CHARS = 6000;
5
+
6
+ export function capMessage(message) {
7
+ const text = String(message ?? '');
8
+ return text.length > MAX_MESSAGE_CHARS ? `${text.slice(0, MAX_MESSAGE_CHARS - 40)}\n…(cut — ${text.length} chars in all)` : text;
9
+ }
10
+ // { type: 'none' | 'deny' | 'context' | 'block' | 'warn', message }
11
+
12
+ export function respond(agent, evt, answer) {
13
+ if (!answer || answer.type === 'none' || !answer.message) {
14
+ // Codex expects JSON on stdout whenever a hook exits 0; Cursor's before-hooks too.
15
+ if (agent === 'codex') return {};
16
+ return agent === 'cursor' && evt?.event === 'before-tool' ? {} : null;
17
+ }
18
+ const { type } = answer;
19
+ const message = capMessage(answer.message);
20
+ switch (agent) {
21
+ case 'claude':
22
+ case 'codex':
23
+ if (type === 'deny') {
24
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: message } };
25
+ }
26
+ if (type === 'block') return { decision: 'block', reason: message };
27
+ if (type === 'warn') return agent === 'claude' ? { systemMessage: message } : {};
28
+ if (type === 'context') {
29
+ const hookEventName = evt.hookEvent === 'PostCompact' ? 'SessionStart' : evt.hookEvent;
30
+ return { hookSpecificOutput: { hookEventName, additionalContext: message } };
31
+ }
32
+ return null;
33
+ case 'gemini':
34
+ if (type === 'deny' || type === 'block') return { decision: 'deny', reason: message };
35
+ if (type === 'warn') return { systemMessage: message };
36
+ if (type === 'context') return { hookSpecificOutput: { hookEventName: evt.hookEvent, additionalContext: message } };
37
+ return null;
38
+ case 'cursor':
39
+ if (type === 'deny') return { permission: 'deny', user_message: message, agent_message: message };
40
+ if (type === 'block') return { followup_message: message };
41
+ // Cursor's after-hooks cannot add to the agent's context; the note is kept in the log only.
42
+ return evt?.event === 'before-tool' ? {} : null;
43
+ default:
44
+ return answer;
45
+ }
46
+ }
package/hook/state.mjs ADDED
@@ -0,0 +1,136 @@
1
+ // Per-session state: one small JSON file per agent session under ~/.introsio/sessions,
2
+ // so parallel sessions never write the same file.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { sessionsDir } from '../lib/paths.mjs';
6
+ import { readJsonSafe, writeJson } from '../lib/jsonFile.mjs';
7
+ import { acquireLock, SAVE_WAIT_MS } from '../lib/lock.mjs';
8
+
9
+ export const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
10
+
11
+ const safeName = (sessionId) => String(sessionId || 'unknown').replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120);
12
+
13
+ export function emptySession(sessionId, agent, now) {
14
+ return {
15
+ sessionId: String(sessionId || 'unknown'),
16
+ agent,
17
+ workerId: null,
18
+ cwd: null,
19
+ startedAt: now,
20
+ lastSeenAt: now,
21
+ claims: {},
22
+ contextRevision: {},
23
+ contextRead: {},
24
+ lastCompletion: null,
25
+ lastBlock: null,
26
+ pending: {},
27
+ warnedFiles: [],
28
+ editedFiles: [],
29
+ agentPid: null,
30
+ notes: [],
31
+ contextLost: false,
32
+ sawIntrosioResult: false,
33
+ };
34
+ }
35
+
36
+ export function loadSession(sessionId, agent, now, env) {
37
+ const stored = readJsonSafe(path.join(sessionsDir(env), `${safeName(sessionId)}.json`), null);
38
+ return stored ? { ...emptySession(sessionId, agent, now), ...stored } : emptySession(sessionId, agent, now);
39
+ }
40
+
41
+ export function sessionFile(sessionId, env) {
42
+ return path.join(sessionsDir(env), `${safeName(sessionId)}.json`);
43
+ }
44
+
45
+ export function sessionExists(sessionId, env) {
46
+ return fs.existsSync(sessionFile(sessionId, env));
47
+ }
48
+
49
+ export function saveSession(session, env) {
50
+ writeJson(path.join(sessionsDir(env), `${safeName(session.sessionId)}.json`), session);
51
+ }
52
+
53
+ const KEYED = ['claims', 'paused', 'pending', 'pendingPause', 'contextRevision', 'contextRead', 'rereadDenied', 'resumeChecked'];
54
+ const LISTS = ['editedFiles', 'warnedFiles'];
55
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
56
+ const isMap = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
57
+
58
+ /**
59
+ * When the session lock could not be taken in time, other hooks of the same
60
+ * session may have written meanwhile: apply only what THIS hook changed (since
61
+ * `start`, the session as it was loaded) on top of what is on disk now, instead
62
+ * of overwriting their claims with a stale copy.
63
+ */
64
+ export function mergeSessionChanges(start, ours, disk) {
65
+ if (!disk) return ours;
66
+ const merged = { ...disk };
67
+ for (const [key, value] of Object.entries(ours)) {
68
+ if (KEYED.includes(key) && isMap(value)) {
69
+ const before = isMap(start[key]) ? start[key] : {};
70
+ const next = { ...(isMap(disk[key]) ? disk[key] : {}) };
71
+ for (const id of Object.keys(before)) if (!(id in value)) delete next[id];
72
+ for (const [id, item] of Object.entries(value)) if (!(id in before) || !same(before[id], item)) next[id] = item;
73
+ merged[key] = next;
74
+ } else if (LISTS.includes(key) && Array.isArray(value)) {
75
+ const before = new Set(Array.isArray(start[key]) ? start[key] : []);
76
+ const added = value.filter((item) => !before.has(item));
77
+ merged[key] = [...new Set([...(Array.isArray(disk[key]) ? disk[key] : []), ...added])];
78
+ } else if (!same(start[key], value)) {
79
+ merged[key] = value;
80
+ }
81
+ }
82
+ for (const key of Object.keys(start)) if (!(key in ours)) delete merged[key];
83
+ return merged;
84
+ }
85
+
86
+ /**
87
+ * Saves a session this hook worked on without the lock: takes the lock once
88
+ * more for the short read-merge-write (so two such hooks cannot race each
89
+ * other), and merges its own changes into whatever another hook saved meanwhile.
90
+ */
91
+ export async function saveSessionUnlocked(start, session, env) {
92
+ const file = sessionFile(session.sessionId, env);
93
+ const release = await acquireLock(file, { waitMs: SAVE_WAIT_MS });
94
+ try {
95
+ saveSession(mergeSessionChanges(start, session, readJsonSafe(file, null)), env);
96
+ } finally {
97
+ release();
98
+ }
99
+ }
100
+
101
+ /** Every other session seen in the last day (for worker-id collisions and `int claims`). */
102
+ export function loadOtherSessions(sessionId, now, env) {
103
+ const dir = sessionsDir(env);
104
+ let names = [];
105
+ try {
106
+ names = fs.readdirSync(dir).filter((name) => name.endsWith('.json') && !name.includes('.tmp'));
107
+ } catch {
108
+ return [];
109
+ }
110
+ const own = `${safeName(sessionId)}.json`;
111
+ const out = [];
112
+ for (const name of names) {
113
+ if (name === own) continue;
114
+ const session = readJsonSafe(path.join(dir, name), null);
115
+ if (!session) continue;
116
+ if (now - Number(session.lastSeenAt || 0) > SESSION_TTL_MS) {
117
+ try { fs.unlinkSync(path.join(dir, name)); } catch { /* another hook pruned it */ }
118
+ continue;
119
+ }
120
+ out.push(session);
121
+ }
122
+ return out;
123
+ }
124
+
125
+ export function clearSessions(env) {
126
+ const dir = sessionsDir(env);
127
+ let removed = 0;
128
+ try {
129
+ for (const name of fs.readdirSync(dir)) {
130
+ if (!name.endsWith('.json')) continue;
131
+ fs.unlinkSync(path.join(dir, name));
132
+ removed += 1;
133
+ }
134
+ } catch { /* nothing to clear */ }
135
+ return removed;
136
+ }
package/lib/config.mjs ADDED
@@ -0,0 +1,64 @@
1
+ // ~/.introsio/config.json — which features are on, and each repository's settings.
2
+ import { configPath, repoKey } from './paths.mjs';
3
+ import { readJson, readJsonSafe, writeJson } from './jsonFile.mjs';
4
+
5
+ /** Every hook feature, on by default. `int disable <name>` turns one off. */
6
+ export const FEATURES = {
7
+ 'stop-guard': 'Keep the agent from finishing while a task it claimed is still open in Introsio',
8
+ 'test-gate': "Run the repo's check command before a task can be completed (needs `int gate set`)",
9
+ 'shipped-gate': 'Before completing: work committed (local mode) or committed + pushed + branch recorded (github mode)',
10
+ 'push-guard': 'Block pushes to the default branch, force pushes, and every push in local mode',
11
+ secrets: 'Block commits / pushes that add API keys, private keys or .env files',
12
+ scope: "Warn when the agent edits files the claimed task doesn't mention",
13
+ 'worker-id': 'One workerId per session; refuse a claim with another live session\'s workerId',
14
+ 'compact-recovery': 'Restore the claimed task, workerId and progress after the context is compacted',
15
+ lease: 'Remind the agent to report progress before its claim expires',
16
+ reread: 'Skip re-reading context / schedule the agent already has',
17
+ log: 'Record every Introsio call in ~/.introsio/log.jsonl (see `int stats`)',
18
+ pause: 'Snapshot the working tree when a task is paused, and check the repository against the pause before it is resumed',
19
+ };
20
+
21
+ export const MODES = ['github', 'local', 'off'];
22
+ export const DEFAULT_GATE_TIMEOUT_SEC = 300;
23
+
24
+ /**
25
+ * Hooks read the config leniently (a broken file means defaults — never a stuck
26
+ * agent). The CLI reads it strictly (`strict: true` throws on a broken file), so
27
+ * a command never overwrites settings it could not read.
28
+ */
29
+ export function loadConfig(env, { strict = false } = {}) {
30
+ const config = strict ? readJson(configPath(env), {}) : readJsonSafe(configPath(env), {});
31
+ return {
32
+ features: { ...(config.features ?? {}) },
33
+ repos: { ...(config.repos ?? {}) },
34
+ mcpUrl: config.mcpUrl ?? null,
35
+ };
36
+ }
37
+
38
+ export function saveConfig(config, env) {
39
+ writeJson(configPath(env), config);
40
+ }
41
+
42
+ export function featureOn(config, name) {
43
+ return config.features?.[name] !== false;
44
+ }
45
+
46
+ /** The settings of the repository at `root` (any spelling of its path), defaults filled in. */
47
+ export function repoSettings(config, root) {
48
+ const stored = (root && (config.repos?.[repoKey(root)] ?? config.repos?.[root])) || {};
49
+ return {
50
+ mode: MODES.includes(stored.mode) ? stored.mode : null,
51
+ gate: typeof stored.gate === 'string' && stored.gate.trim() ? stored.gate.trim() : null,
52
+ gateTimeoutSec: Number(stored.gateTimeoutSec) > 0 ? Number(stored.gateTimeoutSec) : DEFAULT_GATE_TIMEOUT_SEC,
53
+ };
54
+ }
55
+
56
+ export function updateRepo(config, root, patch) {
57
+ const key = repoKey(root);
58
+ const next = { ...(config.repos[key] ?? config.repos[root] ?? {}), ...patch };
59
+ for (const [name, value] of Object.entries(next)) if (value === null || value === undefined) delete next[name];
60
+ if (key !== root) delete config.repos[root];
61
+ config.repos[key] = next;
62
+ if (Object.keys(next).length === 0) delete config.repos[key];
63
+ return config;
64
+ }
package/lib/git.mjs ADDED
@@ -0,0 +1,120 @@
1
+ // Thin git runner. Every call is synchronous, short, and never throws — a hook
2
+ // must answer quickly and a missing repository simply means "no git checks".
3
+ import crypto from 'node:crypto';
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
+
9
+ // The snapshot commit's identity: the user's own may be unset, and it must never look like their work.
10
+ const SNAPSHOT_IDENTITY = {
11
+ GIT_AUTHOR_NAME: 'Introsio pause', GIT_AUTHOR_EMAIL: 'pause@introsio.invalid',
12
+ GIT_COMMITTER_NAME: 'Introsio pause', GIT_COMMITTER_EMAIL: 'pause@introsio.invalid',
13
+ };
14
+
15
+ export function createGit(cwd) {
16
+ const run = (args, { maxBuffer = 16 * 1024 * 1024, env = null, timeout = 15000 } = {}) => {
17
+ const result = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer, timeout, ...(env ? { env: { ...process.env, ...env } } : {}) });
18
+ return { ok: result.status === 0, out: (result.stdout ?? '').trimEnd(), err: (result.stderr ?? '').trim(), timedOut: result.error?.code === 'ETIMEDOUT' };
19
+ };
20
+ const value = (args) => {
21
+ const result = run(args);
22
+ return result.ok ? result.out : null;
23
+ };
24
+ const api = {
25
+ cwd,
26
+ run,
27
+ root: () => value(['rev-parse', '--show-toplevel']),
28
+ gitDir: () => value(['rev-parse', '--absolute-git-dir']),
29
+ head: () => value(['rev-parse', '--verify', '--quiet', 'HEAD']),
30
+ shortHead: () => value(['rev-parse', '--short', 'HEAD']),
31
+ branch: () => value(['rev-parse', '--abbrev-ref', 'HEAD']),
32
+ /** Porcelain status lines, ignoring the kit's own folder. */
33
+ dirty: () => (value(['status', '--porcelain']) ?? '').split('\n').filter((line) => line.trim() && !line.includes('.introsio/')),
34
+ /** The paths `dirty()` names (the new name of a rename). */
35
+ dirtyPaths: () => api.dirty().map((line) => line.slice(3).split(' -> ').pop().replace(/^"|"$/g, '')).filter(Boolean),
36
+ upstream: () => value(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']),
37
+ /** Where a bare `git push` sends the current branch ("origin/main"), honouring push.default. */
38
+ pushTarget: () => value(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{push}']),
39
+ aheadOfUpstream: () => {
40
+ const count = value(['rev-list', '--count', '@{u}..HEAD']);
41
+ return count === null ? null : Number(count);
42
+ },
43
+ defaultBranch: () => {
44
+ const ref = value(['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD']);
45
+ if (ref) return ref.replace(/^refs\/remotes\/origin\//, '');
46
+ for (const name of ['main', 'master']) if (value(['rev-parse', '--verify', '--quiet', `refs/heads/${name}`])) return name;
47
+ return null;
48
+ },
49
+ /** A diff, or null when it cannot be read whole (callers must not treat that as "no changes"). */
50
+ diff: (args) => {
51
+ const result = run(['diff', '--no-color', '--no-ext-diff', ...args], { maxBuffer: 128 * 1024 * 1024 });
52
+ return result.ok ? result.out : null;
53
+ },
54
+ originUrl: () => value(['remote', 'get-url', 'origin']),
55
+ /** The commit id a ref or name points at, or null. */
56
+ resolve: (name) => value(['rev-parse', '--verify', '--quiet', `${name}^{commit}`]),
57
+ treeOf: (commit) => value(['rev-parse', '--verify', '--quiet', `${commit}^{tree}`]),
58
+ hasCommit: (sha) => run(['cat-file', '-e', `${sha}^{commit}`]).ok,
59
+ isAncestor: (ancestor, descendant) => run(['merge-base', '--is-ancestor', ancestor, descendant]).ok,
60
+ localBranchExists: (name) => run(['rev-parse', '--verify', '--quiet', `refs/heads/${name}`]).ok,
61
+ remoteBranchExists: (name) => run(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${name}`]).ok,
62
+ /** Commits in `range` as { sha, author, subject }, newest first (at most `max`). */
63
+ commits: (range, max = 20) => (value(['log', `-n${max}`, '--format=%h%x09%an%x09%s', range]) ?? '')
64
+ .split('\n').filter(Boolean).map((line) => {
65
+ const [sha, author, ...subject] = line.split('\t');
66
+ return { sha, author, subject: subject.join('\t') };
67
+ }),
68
+ /** `git diff --name-status` between two trees/commits as { status, path }. */
69
+ changedBetween: (a, b) => {
70
+ const out = value(['diff', '--name-status', '--no-renames', a, b]);
71
+ if (out === null) return null;
72
+ return out.split('\n').filter(Boolean).map((line) => {
73
+ const [status, ...rest] = line.split('\t');
74
+ return { status: status[0], path: rest.join('\t') };
75
+ });
76
+ },
77
+ updateRef: (ref, sha) => run(['update-ref', ref, sha]).ok,
78
+ deleteRef: (ref) => run(['update-ref', '-d', ref]).ok,
79
+ /** A git operation left half way (merge, rebase …), or null. */
80
+ inProgressOp: () => {
81
+ const dir = api.gitDir();
82
+ if (!dir) return null;
83
+ const has = (name) => fs.existsSync(path.join(dir, name));
84
+ if (has('rebase-merge') || has('rebase-apply')) return 'rebase';
85
+ if (has('MERGE_HEAD')) return 'merge';
86
+ if (has('CHERRY_PICK_HEAD')) return 'cherry-pick';
87
+ if (has('REVERT_HEAD')) return 'revert';
88
+ if (has('BISECT_LOG')) return 'bisect';
89
+ return null;
90
+ },
91
+ /**
92
+ * The whole working tree as a commit, without touching it, the index or any
93
+ * branch: tracked changes and untracked files (.gitignore respected), staged
94
+ * or not. Built in a throwaway index seeded from the real one, so only
95
+ * changed files are hashed. Returns { commit, tree } or { error }.
96
+ */
97
+ snapshot: ({ budgetMs = 15000, message = 'introsio pause snapshot' } = {}) => {
98
+ const dir = api.gitDir();
99
+ if (!dir) return { error: 'not a git repository' };
100
+ const started = Date.now();
101
+ const left = () => Math.max(1000, budgetMs - (Date.now() - started));
102
+ const tmpIndex = path.join(os.tmpdir(), `introsio-index-${process.pid}-${crypto.randomBytes(4).toString('hex')}`);
103
+ try {
104
+ try { fs.copyFileSync(path.join(dir, 'index'), tmpIndex); } catch { /* a fresh repository has no index yet */ }
105
+ const env = { GIT_INDEX_FILE: tmpIndex, ...SNAPSHOT_IDENTITY };
106
+ const added = run(['add', '-A', '--', ':/'], { env, timeout: left() });
107
+ if (!added.ok) return { error: added.timedOut ? `took longer than ${Math.round(budgetMs / 1000)} s` : (added.err || 'git add failed').slice(0, 200) };
108
+ const tree = run(['write-tree'], { env, timeout: left() });
109
+ if (!tree.ok) return { error: (tree.err || 'git write-tree failed').slice(0, 200) };
110
+ const head = api.head();
111
+ const commit = run(['commit-tree', tree.out, ...(head ? ['-p', head] : []), '-m', message], { env, timeout: left() });
112
+ if (!commit.ok) return { error: (commit.err || 'git commit-tree failed').slice(0, 200) };
113
+ return { commit: commit.out, tree: tree.out };
114
+ } finally {
115
+ try { fs.rmSync(tmpIndex, { force: true }); } catch { /* best effort */ }
116
+ }
117
+ },
118
+ };
119
+ return api;
120
+ }
@@ -0,0 +1,103 @@
1
+ // Small, careful file helpers: atomic writes, tolerant reads, JSON with comments stripped.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ export function readText(file) {
6
+ try {
7
+ return fs.readFileSync(file, 'utf8');
8
+ } catch {
9
+ return null;
10
+ }
11
+ }
12
+
13
+ /** Strips // and /* *\/ comments and trailing commas outside strings (VS Code / OpenCode configs allow them). */
14
+ export function stripJsonComments(text) {
15
+ let out = '';
16
+ let inString = false;
17
+ for (let i = 0; i < text.length; i += 1) {
18
+ const ch = text[i];
19
+ const next = text[i + 1];
20
+ if (inString) {
21
+ out += ch;
22
+ if (ch === '\\') { out += next ?? ''; i += 1; } else if (ch === '"') inString = false;
23
+ continue;
24
+ }
25
+ if (ch === '"') { inString = true; out += ch; continue; }
26
+ if (ch === '/' && next === '/') { while (i < text.length && text[i] !== '\n') i += 1; out += '\n'; continue; }
27
+ if (ch === '/' && next === '*') { i += 2; while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i += 1; i += 1; continue; }
28
+ out += ch;
29
+ }
30
+ return out.replace(/,(\s*[}\]])/g, '$1');
31
+ }
32
+
33
+ /**
34
+ * Reads a JSON file. Missing or empty → `fallback`. Unparseable → throws, so an
35
+ * installer never overwrites a file it could not understand.
36
+ */
37
+ export function readJson(file, fallback = {}) {
38
+ const text = readText(file);
39
+ if (text === null || !text.trim()) return structuredClone(fallback);
40
+ try {
41
+ return JSON.parse(text);
42
+ } catch {
43
+ try {
44
+ return JSON.parse(stripJsonComments(text));
45
+ } catch {
46
+ const error = new Error(`${file} is not valid JSON — fix or move it, then run again. Nothing was changed.`);
47
+ error.code = 'BAD_JSON';
48
+ throw error;
49
+ }
50
+ }
51
+ }
52
+
53
+ /** Same as readJson but never throws (hook-side state: a broken file just reads as empty). */
54
+ export function readJsonSafe(file, fallback = {}) {
55
+ try {
56
+ return readJson(file, fallback);
57
+ } catch {
58
+ return structuredClone(fallback);
59
+ }
60
+ }
61
+
62
+ // On Windows, replacing a file another process has open (a hook reading the same
63
+ // session, `int claims`, an antivirus scan) fails for a moment with EPERM / EACCES /
64
+ // EBUSY. That is transient: retry for a short while instead of losing the write.
65
+ const RENAME_RETRY_MS = 2_000;
66
+ const TRANSIENT = new Set(['EPERM', 'EACCES', 'EBUSY']);
67
+ const pause = (ms) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); };
68
+
69
+ function renameWithRetry(from, to) {
70
+ const deadline = Date.now() + RENAME_RETRY_MS;
71
+ let delay = 5;
72
+ for (;;) {
73
+ try {
74
+ fs.renameSync(from, to);
75
+ return;
76
+ } catch (error) {
77
+ if (process.platform !== 'win32' || !TRANSIENT.has(error.code) || Date.now() > deadline) throw error;
78
+ pause(delay + Math.floor(Math.random() * delay));
79
+ delay = Math.min(delay * 2, 100);
80
+ }
81
+ }
82
+ }
83
+
84
+ export function writeAtomic(file, text) {
85
+ fs.mkdirSync(path.dirname(file), { recursive: true });
86
+ const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
87
+ fs.writeFileSync(tmp, text);
88
+ try {
89
+ renameWithRetry(tmp, file);
90
+ } catch (error) {
91
+ try { fs.rmSync(tmp, { force: true }); } catch { /* best effort */ }
92
+ throw error;
93
+ }
94
+ }
95
+
96
+ export function writeJson(file, value) {
97
+ writeAtomic(file, `${JSON.stringify(value, null, 2)}\n`);
98
+ }
99
+
100
+ export function appendLine(file, line) {
101
+ fs.mkdirSync(path.dirname(file), { recursive: true });
102
+ fs.appendFileSync(file, `${line}\n`);
103
+ }