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.
- package/CHANGELOG.md +62 -0
- package/LICENSE +21 -0
- package/README.md +291 -3
- package/agents/claude.mjs +80 -0
- package/agents/codex.mjs +67 -0
- package/agents/common.mjs +200 -0
- package/agents/cursor.mjs +67 -0
- package/agents/gemini.mjs +63 -0
- package/agents/index.mjs +10 -0
- package/agents/opencode.mjs +65 -0
- package/agents/vscode.mjs +47 -0
- package/agents/windsurf.mjs +32 -0
- package/cli.mjs +536 -0
- package/hook/engine.mjs +286 -0
- package/hook/features/claims.mjs +265 -0
- package/hook/features/gates.mjs +134 -0
- package/hook/features/git.mjs +243 -0
- package/hook/features/log.mjs +70 -0
- package/hook/features/notes.mjs +88 -0
- package/hook/features/pause.mjs +340 -0
- package/hook/features/stopGuard.mjs +42 -0
- package/hook/features/workerId.mjs +55 -0
- package/hook/introsio-hook.mjs +95 -0
- package/hook/normalize.mjs +171 -0
- package/hook/respond.mjs +46 -0
- package/hook/state.mjs +136 -0
- package/lib/config.mjs +64 -0
- package/lib/git.mjs +120 -0
- package/lib/jsonFile.mjs +103 -0
- package/lib/lock.mjs +182 -0
- package/lib/managedBlock.mjs +19 -0
- package/lib/paths.mjs +59 -0
- package/lib/processTree.mjs +127 -0
- package/opencode/introsio.template.js +55 -0
- package/package.json +54 -6
- package/templates/execute.md +20 -0
- package/templates/pause.md +25 -0
- package/templates/resume.md +22 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
// Feature `pause`: /introsio-pause and /introsio-resume, made exact (docs/adr/0011-pause-and-resume.md).
|
|
2
|
+
//
|
|
3
|
+
// pause — before pauseTask runs, the working tree is snapshotted as a commit kept under
|
|
4
|
+
// refs/introsio/paused/<taskId> (never pushed, nothing on any branch changes) and the
|
|
5
|
+
// git position the agent reports is checked against the real one; after it succeeds
|
|
6
|
+
// the claim is dropped and ~/.introsio/pauses/<taskId>.json records where the code is.
|
|
7
|
+
// resume — whenever an Introsio answer carries a pause (getTaskById, claimTask's resumedPause),
|
|
8
|
+
// the repository is compared with it here, in code, and the agent gets a verdict:
|
|
9
|
+
// exact | drift | blocked, with the precise differences and the commands that fix them.
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { introsioDir, repoKey } from '../../lib/paths.mjs';
|
|
14
|
+
import { readJsonSafe, writeJson } from '../../lib/jsonFile.mjs';
|
|
15
|
+
import { sessionIsLive } from './workerId.mjs';
|
|
16
|
+
|
|
17
|
+
export const pauseRef = (taskId) => `refs/introsio/paused/${String(taskId).replace(/[^A-Za-z0-9._-]/g, '_')}`;
|
|
18
|
+
export const pausesDir = (env) => path.join(introsioDir(env), 'pauses');
|
|
19
|
+
const pauseFile = (taskId, env) => path.join(pausesDir(env), `${String(taskId).replace(/[^A-Za-z0-9._-]/g, '_')}.json`);
|
|
20
|
+
|
|
21
|
+
export const readLocalPause = (taskId, env) => readJsonSafe(pauseFile(taskId, env), null);
|
|
22
|
+
|
|
23
|
+
export function listLocalPauses(env) {
|
|
24
|
+
let names = [];
|
|
25
|
+
try { names = fs.readdirSync(pausesDir(env)).filter((name) => name.endsWith('.json') && !name.includes('.tmp')); } catch { return []; }
|
|
26
|
+
return names.map((name) => readJsonSafe(path.join(pausesDir(env), name), null)).filter(Boolean);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function removeLocalPause(taskId, env) {
|
|
30
|
+
try { fs.rmSync(pauseFile(taskId, env), { force: true }); } catch { /* best effort */ }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const short = (sha) => (sha ? String(sha).slice(0, 10) : '?');
|
|
34
|
+
const MAX_LISTED = 12;
|
|
35
|
+
const list = (items) => (items.length > MAX_LISTED ? [...items.slice(0, MAX_LISTED), `… and ${items.length - MAX_LISTED} more`] : items);
|
|
36
|
+
|
|
37
|
+
/** Where the repository stands right now, or null outside a repository. */
|
|
38
|
+
export function gitFacts(git) {
|
|
39
|
+
const root = git.root();
|
|
40
|
+
if (!root) return null;
|
|
41
|
+
const branch = git.branch();
|
|
42
|
+
return {
|
|
43
|
+
root,
|
|
44
|
+
branch: branch && branch !== 'HEAD' ? branch : null,
|
|
45
|
+
head: git.head(),
|
|
46
|
+
dirtyFiles: git.dirtyPaths(),
|
|
47
|
+
inProgressOp: git.inProgressOp(),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Before pauseTask: take the snapshot and check what the agent says about git.
|
|
53
|
+
* The snapshot is kept in the session until the pause succeeds (a refused pause
|
|
54
|
+
* leaves no ref behind). A wrong or missing git position is refused ONCE with
|
|
55
|
+
* the exact values to send — models guess commit ids — and goes through after.
|
|
56
|
+
*/
|
|
57
|
+
export function pauseDecision({ git, args = {}, session, now, budgetMs }) {
|
|
58
|
+
const taskId = String(args.taskId ?? '');
|
|
59
|
+
if (!taskId) return { type: 'none' };
|
|
60
|
+
const facts = gitFacts(git);
|
|
61
|
+
if (!facts) return { type: 'none' };
|
|
62
|
+
const snap = git.snapshot({ budgetMs });
|
|
63
|
+
session.pendingPause = session.pendingPause ?? {};
|
|
64
|
+
// The same tree as the snapshot already named (to the agent, or in what it sends): keep that commit,
|
|
65
|
+
// so the server's copy and the local ref name one snapshot (a new commit differs only by its time).
|
|
66
|
+
const named = [args.handoff?.git?.snapshot, session.pendingPause[taskId]?.snapshot].filter(Boolean);
|
|
67
|
+
for (const candidate of named) {
|
|
68
|
+
if (snap.tree && git.treeOf(candidate) === snap.tree) { snap.commit = git.resolve(candidate); break; }
|
|
69
|
+
}
|
|
70
|
+
session.pendingPause[taskId] = {
|
|
71
|
+
at: now, root: facts.root, branch: facts.branch, head: facts.head, dirtyFiles: facts.dirtyFiles.slice(0, 200),
|
|
72
|
+
inProgressOp: facts.inProgressOp, snapshot: snap.commit ?? null, tree: snap.tree ?? null, snapshotError: snap.error ?? null,
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const claim = session.claims?.[taskId];
|
|
76
|
+
const taskFiles = new Set([...(session.editedFiles ?? []), ...(claim?.files ?? [])]);
|
|
77
|
+
if (args.release === true) {
|
|
78
|
+
const unsaved = facts.dirtyFiles.filter((file) => taskFiles.size === 0 || taskFiles.has(file));
|
|
79
|
+
if (unsaved.length > 0) {
|
|
80
|
+
return {
|
|
81
|
+
type: 'deny',
|
|
82
|
+
message: `Introsio: release: true hands this task to any worker, but its work is not committed:\n${list(unsaved).map((file) => ` - ${file}`).join('\n')}\n` +
|
|
83
|
+
'Commit it on the task branch (and push it, in github mode) and record outcome.branch, then pause again — or pause without release so it waits for your resume.',
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const sent = args.handoff?.git ?? null;
|
|
89
|
+
const wrong = [];
|
|
90
|
+
if (!sent) wrong.push('handoff.git is missing');
|
|
91
|
+
else {
|
|
92
|
+
if ((sent.branch || null) !== facts.branch && !(sent.branch === 'HEAD' && !facts.branch)) wrong.push(`branch is "${facts.branch ?? '(detached HEAD)'}", not "${sent.branch ?? ''}"`);
|
|
93
|
+
if (facts.head && (!sent.head || !facts.head.startsWith(String(sent.head).toLowerCase()))) wrong.push(`HEAD is ${facts.head}, not ${sent.head ?? '(missing)'}`);
|
|
94
|
+
}
|
|
95
|
+
const key = `${taskId}:${facts.branch}:${facts.head}`;
|
|
96
|
+
if (wrong.length > 0 && session.pauseCorrected !== key) {
|
|
97
|
+
session.pauseCorrected = key;
|
|
98
|
+
const exact = {
|
|
99
|
+
...(facts.branch ? { branch: facts.branch } : {}),
|
|
100
|
+
...(facts.head ? { head: facts.head } : {}),
|
|
101
|
+
...(snap.commit ? { snapshot: snap.commit } : {}),
|
|
102
|
+
dirtyFiles: facts.dirtyFiles.slice(0, 200),
|
|
103
|
+
...(facts.dirtyFiles.length > 200 ? { truncated: true } : {}),
|
|
104
|
+
...(facts.inProgressOp ? { inProgressOp: facts.inProgressOp } : {}),
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
type: 'deny',
|
|
108
|
+
message: `Introsio: the pause would record the wrong git position (${wrong.join('; ')}). Call pauseTask again with handoff.git exactly:\n${JSON.stringify(exact)}`,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
return { type: 'none' };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** After a successful pauseTask: keep the snapshot under its ref and write the local record. */
|
|
115
|
+
export function recordPause({ git, session, args = {}, data = {}, now, env, gatePassed = null }) {
|
|
116
|
+
const taskId = String(args.taskId ?? data.task?.id ?? '');
|
|
117
|
+
if (!taskId) return null;
|
|
118
|
+
const pending = session.pendingPause?.[taskId] ?? null;
|
|
119
|
+
if (session.pendingPause) delete session.pendingPause[taskId];
|
|
120
|
+
const claim = session.claims?.[taskId];
|
|
121
|
+
let snapshotKept = false;
|
|
122
|
+
if (pending?.snapshot && git) snapshotKept = git.updateRef(pauseRef(taskId), pending.snapshot);
|
|
123
|
+
const record = {
|
|
124
|
+
taskId,
|
|
125
|
+
title: data.task?.title ?? claim?.title ?? taskId,
|
|
126
|
+
projectId: claim?.projectId ?? null,
|
|
127
|
+
workerId: args.workerId ?? claim?.workerId ?? session.workerId ?? null,
|
|
128
|
+
agent: session.agent ?? null,
|
|
129
|
+
sessionId: session.sessionId,
|
|
130
|
+
host: os.hostname(),
|
|
131
|
+
at: new Date(now).toISOString(),
|
|
132
|
+
// The server's own time stamp of this pause: what ties this record to it at resume (localMatchesPause).
|
|
133
|
+
pausedAt: typeof data.pausedAt === 'string' ? data.pausedAt : null,
|
|
134
|
+
release: args.release === true,
|
|
135
|
+
note: typeof args.handoff?.note === 'string' ? args.handoff.note.slice(0, 600) : null,
|
|
136
|
+
...(pending ? {
|
|
137
|
+
root: pending.root,
|
|
138
|
+
repoKey: repoKey(pending.root),
|
|
139
|
+
origin: git?.originUrl() ?? null,
|
|
140
|
+
branch: pending.branch,
|
|
141
|
+
head: pending.head,
|
|
142
|
+
dirtyFiles: pending.dirtyFiles,
|
|
143
|
+
inProgressOp: pending.inProgressOp,
|
|
144
|
+
snapshot: snapshotKept ? pending.snapshot : null,
|
|
145
|
+
tree: snapshotKept ? pending.tree : null,
|
|
146
|
+
ref: snapshotKept ? pauseRef(taskId) : null,
|
|
147
|
+
snapshotError: pending.snapshotError ?? (pending.snapshot && !snapshotKept ? 'could not write the snapshot ref' : null),
|
|
148
|
+
gatePassed,
|
|
149
|
+
} : {}),
|
|
150
|
+
};
|
|
151
|
+
writeJson(pauseFile(taskId, env), record);
|
|
152
|
+
session.paused = { ...(session.paused ?? {}), [taskId]: { at: now, title: record.title } };
|
|
153
|
+
return record;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** After a task is finished: its snapshot and local record have done their job. */
|
|
157
|
+
export function forgetPause({ git, taskId, env }) {
|
|
158
|
+
const local = readLocalPause(taskId, env);
|
|
159
|
+
if (local?.ref && git) git.deleteRef(local.ref);
|
|
160
|
+
else if (git) git.deleteRef(pauseRef(taskId));
|
|
161
|
+
removeLocalPause(taskId, env);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The task id an Introsio answer is about, and the pause it carries (if it carries one). */
|
|
165
|
+
export function pauseInAnswer(name, data) {
|
|
166
|
+
if (!data || typeof data !== 'object') return null;
|
|
167
|
+
if (name === 'getTaskById' && data.pause && data.id) return { taskId: String(data.id), pause: data.pause, resumed: false };
|
|
168
|
+
if (name === 'claimTask' && data.claimed === true && data.resumedPause && data.task?.id) {
|
|
169
|
+
return { taskId: String(data.task.id), pause: data.resumedPause, resumed: true, changed: data.taskChangedSincePause === true };
|
|
170
|
+
}
|
|
171
|
+
// The worker that paused a task may start it again with updateTask in_progress; the answer carries the pause.
|
|
172
|
+
if (name === 'updateTask' && data.resumedPause && data.task?.id) {
|
|
173
|
+
return { taskId: String(data.task.id), pause: data.resumedPause, resumed: true, changed: data.taskChangedSincePause === true };
|
|
174
|
+
}
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const sameSha = (a, b) => {
|
|
179
|
+
const x = String(a ?? '').toLowerCase();
|
|
180
|
+
const y = String(b ?? '').toLowerCase();
|
|
181
|
+
return x.length >= 7 && y.length >= 7 && (x.startsWith(y) || y.startsWith(x));
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Whether the local record on this computer belongs to the pause the server
|
|
186
|
+
* reports. A task can be resumed and paused again elsewhere while an old
|
|
187
|
+
* record stays here (it is removed only when this computer sees the task
|
|
188
|
+
* completed), and an old record must never replace the current pause's facts.
|
|
189
|
+
*/
|
|
190
|
+
export function localMatchesPause(local, pause = {}) {
|
|
191
|
+
if (!local) return false;
|
|
192
|
+
const serverAt = Date.parse(pause.at ?? '');
|
|
193
|
+
const localAt = Date.parse(local.pausedAt ?? '');
|
|
194
|
+
// Exact: the record kept the server's own time stamp of the pause.
|
|
195
|
+
if (Number.isFinite(serverAt) && Number.isFinite(localAt)) return serverAt === localAt;
|
|
196
|
+
// Older records: the snapshot commit is unique to one pause.
|
|
197
|
+
if (pause.git?.snapshot && local.snapshot) return sameSha(pause.git.snapshot, local.snapshot);
|
|
198
|
+
// No snapshot on either side: the same worker at the same commit.
|
|
199
|
+
if (pause.workerId && local.workerId && pause.workerId !== local.workerId) return false;
|
|
200
|
+
if (pause.git?.head && local.head) return sameSha(pause.git.head, local.head);
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* The resume check — every comparison between where the work was paused and
|
|
206
|
+
* the repository now, decided here and not by the model.
|
|
207
|
+
*
|
|
208
|
+
* @returns {{ verdict: 'exact'|'drift'|'blocked', lines: string[], restore: string|null }}
|
|
209
|
+
*/
|
|
210
|
+
export function resumeReport({ git, taskId, pause = {}, local: storedLocal = null, others = [], now = Date.now(), alive, taskChanged = false, gatePassedNow = null }) {
|
|
211
|
+
const blocked = [];
|
|
212
|
+
const drift = [];
|
|
213
|
+
const ok = [];
|
|
214
|
+
let restore = null;
|
|
215
|
+
// A record left by an earlier pause of this task says nothing about this one: ignore it (and its snapshot ref).
|
|
216
|
+
const local = localMatchesPause(storedLocal, pause) ? storedLocal : null;
|
|
217
|
+
if (storedLocal && !local) ok.push('an older pause record of this task on this computer was ignored (it belongs to an earlier pause)');
|
|
218
|
+
const pausedGit = { ...(pause.git ?? {}) };
|
|
219
|
+
// The local record is exact (it was read from git by the hook); the server's copy was typed by the agent.
|
|
220
|
+
for (const field of ['branch', 'head', 'snapshot', 'dirtyFiles']) if (local?.[field] !== undefined && local[field] !== null) pausedGit[field] = local[field];
|
|
221
|
+
const facts = git ? gitFacts(git) : null;
|
|
222
|
+
|
|
223
|
+
// 7. Another live session on this computer holds or is working this task.
|
|
224
|
+
const holder = others.find((other) => other.claims?.[taskId] && sessionIsLive(other, now, alive));
|
|
225
|
+
if (holder) blocked.push(`another ${holder.agent ?? 'agent'} session on this computer (workerId ${holder.workerId ?? '?'}) is working this task right now — resume there, or stop that session first.`);
|
|
226
|
+
|
|
227
|
+
if (!facts) {
|
|
228
|
+
if (pausedGit.branch || pausedGit.head) drift.push('this folder is not a git repository, but the task was paused in one — open the repository it was paused in.');
|
|
229
|
+
} else {
|
|
230
|
+
// 1. Same repository.
|
|
231
|
+
if (local?.repoKey && repoKey(facts.root) !== local.repoKey) {
|
|
232
|
+
const sameOrigin = local.origin && git.originUrl() === local.origin;
|
|
233
|
+
(sameOrigin ? drift : blocked).push(`the task was paused in ${local.root}, and this is ${facts.root}${sameOrigin ? ' (another clone of the same repository)' : ''}.`);
|
|
234
|
+
}
|
|
235
|
+
// 6. A git operation left half way.
|
|
236
|
+
if (facts.inProgressOp) blocked.push(`a git ${facts.inProgressOp} is in progress — finish or abort it (git ${facts.inProgressOp === 'bisect' ? 'bisect reset' : `${facts.inProgressOp} --abort`}) before resuming.`);
|
|
237
|
+
|
|
238
|
+
// 2. Branch.
|
|
239
|
+
if (pausedGit.branch && facts.branch !== pausedGit.branch) {
|
|
240
|
+
if (git.localBranchExists(pausedGit.branch)) drift.push(`you are on ${facts.branch ?? 'a detached HEAD'}; the work is on ${pausedGit.branch} → git switch ${pausedGit.branch}`);
|
|
241
|
+
else if (git.remoteBranchExists(pausedGit.branch)) drift.push(`branch ${pausedGit.branch} exists only on origin → git switch --track origin/${pausedGit.branch}`);
|
|
242
|
+
else blocked.push(`branch ${pausedGit.branch} no longer exists here or on origin (git fetch first if it was pushed elsewhere).`);
|
|
243
|
+
} else if (pausedGit.branch) ok.push(`branch ${pausedGit.branch}`);
|
|
244
|
+
|
|
245
|
+
// 3. HEAD.
|
|
246
|
+
if (pausedGit.head && facts.head && facts.branch === (pausedGit.branch ?? facts.branch)) {
|
|
247
|
+
if (!git.hasCommit(pausedGit.head)) drift.push(`commit ${short(pausedGit.head)} (HEAD when paused) is not in this repository → git fetch, or resume on the computer it was paused on${pause.host ? ` (${pause.host})` : ''}.`);
|
|
248
|
+
else if (facts.head === pausedGit.head || facts.head.startsWith(pausedGit.head)) ok.push(`HEAD ${short(facts.head)} unchanged`);
|
|
249
|
+
else if (git.isAncestor(pausedGit.head, facts.head)) {
|
|
250
|
+
const added = git.commits(`${pausedGit.head}..${facts.head}`);
|
|
251
|
+
drift.push(`${added.length} commit(s) were added since the pause — read them before continuing:\n${list(added.map((c) => ` ${c.sha} ${c.author}: ${c.subject}`)).join('\n')}`);
|
|
252
|
+
} else if (git.isAncestor(facts.head, pausedGit.head)) {
|
|
253
|
+
drift.push(`the branch moved back: HEAD is ${short(facts.head)}, behind ${short(pausedGit.head)} (reset?). The paused commit still exists: git reset --keep ${short(pausedGit.head)} if that was not intended.`);
|
|
254
|
+
} else {
|
|
255
|
+
drift.push(`history was rewritten since the pause (rebase or force push): ${short(pausedGit.head)} is no longer on this branch. Check git log before continuing.`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// 4. The working tree against the snapshot.
|
|
260
|
+
const snapshot = pausedGit.snapshot && git.hasCommit(pausedGit.snapshot) ? pausedGit.snapshot : (local?.ref ? git.resolve(local.ref) : null);
|
|
261
|
+
const pausedDirty = Array.isArray(pausedGit.dirtyFiles) ? pausedGit.dirtyFiles : [];
|
|
262
|
+
if (snapshot) {
|
|
263
|
+
const current = git.snapshot({ message: 'introsio resume check' });
|
|
264
|
+
if (current.error) drift.push(`the working tree could not be compared with the pause (${current.error}).`);
|
|
265
|
+
else if (current.tree === git.treeOf(snapshot)) ok.push(pausedDirty.length ? `working tree identical to the pause (${pausedDirty.length} unfinished file(s) in place)` : 'working tree identical to the pause');
|
|
266
|
+
else {
|
|
267
|
+
const changes = git.changedBetween(snapshot, current.commit) ?? [];
|
|
268
|
+
const missing = pausedDirty.filter((file) => changes.some((change) => change.path === file));
|
|
269
|
+
const lost = missing.length > 0 && changes.every((change) => pausedDirty.includes(change.path))
|
|
270
|
+
&& facts.head === pausedGit.head && facts.dirtyFiles.length === 0;
|
|
271
|
+
if (lost) {
|
|
272
|
+
restore = `git restore --source=${snapshot} --worktree -- ${missing.map((file) => JSON.stringify(file)).join(' ')}`;
|
|
273
|
+
drift.push(`the unfinished work is gone from the working tree (reset, stash or clean?): ${list(missing).join(', ')}.\n It is saved in the pause snapshot — after the user agrees: ${restore}`);
|
|
274
|
+
} else {
|
|
275
|
+
drift.push(`${changes.length} file(s) differ from the pause:\n${list(changes.map((change) => ` ${{ A: 'added', D: 'deleted', M: 'changed' }[change.status] ?? change.status} ${change.path}`)).join('\n')}\n` +
|
|
276
|
+
` Compare: git diff ${short(snapshot)} -- <file>. The paused state is saved in ${local?.ref ?? short(snapshot)}.`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
} else if (pausedDirty.length > 0) {
|
|
280
|
+
const here = new Set(facts.dirtyFiles);
|
|
281
|
+
const absent = pausedDirty.filter((file) => !here.has(file));
|
|
282
|
+
if (pause.portable === true) ok.push('the work was released (committed / pushed)');
|
|
283
|
+
else if (absent.length === pausedDirty.length) {
|
|
284
|
+
blocked.push(`the unfinished work (${list(pausedDirty).join(', ')}) is not here and there is no snapshot of it on this computer — it was paused${pause.host ? ` on ${pause.host}` : ' elsewhere'}. Resume there, or confirm with the user that it is lost and start the task over.`);
|
|
285
|
+
} else if (absent.length > 0) drift.push(`some unfinished files are not modified here: ${list(absent).join(', ')}.`);
|
|
286
|
+
else ok.push('the unfinished files are in place (no snapshot to compare contents)');
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// 10. Tests.
|
|
290
|
+
if (snapshot && ok.some((line) => line.startsWith('working tree identical'))) {
|
|
291
|
+
if (gatePassedNow === true) ok.push('the test gate passed on exactly this tree — no need to run it again');
|
|
292
|
+
else if (local?.gatePassed === true) ok.push('the test gate passed when it was paused');
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// 8 / 9. The task or its context changed while it was paused.
|
|
297
|
+
if (taskChanged) drift.push('the task itself was edited while it was paused (spec, subtasks or links) — re-read it before continuing.');
|
|
298
|
+
|
|
299
|
+
const verdict = blocked.length ? 'blocked' : drift.length ? 'drift' : 'exact';
|
|
300
|
+
const lines = [
|
|
301
|
+
...blocked.map((line) => `✗ ${line}`),
|
|
302
|
+
...drift.map((line) => `! ${line}`),
|
|
303
|
+
...ok.map((line) => `✓ ${line}`),
|
|
304
|
+
];
|
|
305
|
+
return { verdict, lines, restore };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const NEXT = {
|
|
309
|
+
exact: 'EXACT — the repository is where the work stopped. Take it back with claimTask { taskId, workerId, resume: true } and continue from the note and nextSteps.',
|
|
310
|
+
drift: 'DRIFT — show the user these differences and ask how to go on (restore the snapshot / continue as it is / leave it paused) BEFORE claiming. Leaving it paused changes nothing.',
|
|
311
|
+
blocked: 'BLOCKED — do not resume. Tell the user what is wrong; the pause stays as it is.',
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
export function formatReport(title, report, { resumed = false } = {}) {
|
|
315
|
+
const head = `Introsio resume check for "${title}": ${report.verdict.toUpperCase()}`;
|
|
316
|
+
const next = resumed
|
|
317
|
+
? (report.verdict === 'exact'
|
|
318
|
+
? 'You hold the task again. Continue from the note and nextSteps.'
|
|
319
|
+
: 'You already hold the task: settle these with the user before changing any code (updateTask statusState "pending" gives it back if you should not continue).')
|
|
320
|
+
: NEXT[report.verdict];
|
|
321
|
+
return [head, ...report.lines.map((line) => ` ${line}`), next].join('\n');
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** A task held by a session on this computer whose agent is no longer running: interrupted without a pause. */
|
|
325
|
+
export function interruptedNote({ taskId, claimWorkerId, others, now, alive }) {
|
|
326
|
+
if (!claimWorkerId) return null;
|
|
327
|
+
const dead = others.find((other) => (other.workerId === claimWorkerId || other.claims?.[taskId]?.workerId === claimWorkerId)
|
|
328
|
+
&& !sessionIsLive(other, now, alive));
|
|
329
|
+
if (!dead) return null;
|
|
330
|
+
const edited = (dead.editedFiles ?? []).slice(0, MAX_LISTED);
|
|
331
|
+
return `Introsio: this task was interrupted without a pause — worker "${claimWorkerId}" was a ${dead.agent ?? 'agent'} session on this computer that is no longer running` +
|
|
332
|
+
`${dead.cwd ? ` (in ${dead.cwd})` : ''}. To take it over at once, claim it with that same workerId: claimTask { taskId: "${taskId}", workerId: "${claimWorkerId}" }.` +
|
|
333
|
+
`${edited.length ? ` It had edited: ${edited.join(', ')} — check git status/diff for that work before continuing.` : ''}`;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export function pausedNote(session) {
|
|
337
|
+
const paused = Object.entries(session.paused ?? {});
|
|
338
|
+
if (!paused.length) return null;
|
|
339
|
+
return `Paused in this session: ${paused.map(([id, item]) => `"${item.title}" (${id})`).join(', ')} — /introsio-resume takes them back.`;
|
|
340
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Feature `stop-guard`: the agent may not finish while a task it claimed is still open in Introsio.
|
|
2
|
+
|
|
3
|
+
export function openClaims(session) {
|
|
4
|
+
return Object.values(session.claims ?? {});
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
const describe = (claim) => `- "${claim.title}" (taskId ${claim.taskId}${claim.workerId ? `, workerId ${claim.workerId}` : ''})`;
|
|
8
|
+
|
|
9
|
+
export function stopDecision(session, evt, now) {
|
|
10
|
+
const open = openClaims(session);
|
|
11
|
+
if (open.length === 0) {
|
|
12
|
+
session.lastBlock = null;
|
|
13
|
+
session.releasedKey = null;
|
|
14
|
+
return { type: 'none' };
|
|
15
|
+
}
|
|
16
|
+
const key = open.map((claim) => claim.taskId).sort().join(',');
|
|
17
|
+
// Already let go once with exactly these tasks open: don't start refusing again.
|
|
18
|
+
if (session.releasedKey === key) return { type: 'none' };
|
|
19
|
+
const retried = evt.stopHookActive || evt.loopCount > 0 || (session.lastBlock && now - session.lastBlock.at < 10 * 60_000);
|
|
20
|
+
if (retried && session.lastBlock?.key === key && session.lastBlock.count >= 1) {
|
|
21
|
+
// Reminded once and it stops again with the same tasks open: that is a decision (the
|
|
22
|
+
// user may keep the task for themselves). Let it stop, say so, and don't ask again.
|
|
23
|
+
session.lastBlock = null;
|
|
24
|
+
session.releasedKey = key;
|
|
25
|
+
return {
|
|
26
|
+
type: 'warn',
|
|
27
|
+
message: `Introsio: stopping with ${open.length} claimed task(s) still open:\n${open.map(describe).join('\n')}\nThey stay in progress until their lease expires; the next claimTask resumes them.`,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
session.lastBlock = { key, at: now, count: session.lastBlock?.key === key ? session.lastBlock.count + 1 : 1 };
|
|
31
|
+
return {
|
|
32
|
+
type: 'block',
|
|
33
|
+
message:
|
|
34
|
+
`Introsio: you still hold ${open.length} claimed task(s) that are not completed:\n${open.map(describe).join('\n')}\n` +
|
|
35
|
+
'Before you stop, settle each one — and follow what the user asked, not this reminder:\n' +
|
|
36
|
+
'- you are out of usage, context or time, or the user asked to pause: pause it with pauseTask (the /introsio-pause procedure: a note, nextSteps, the subtask and git) — it waits for /introsio-resume;\n' +
|
|
37
|
+
'- the user only wanted it claimed: release it with updateTask { taskId, workerId, statusState: "pending" } (it goes back to the queue) — do not do the work;\n' +
|
|
38
|
+
'- the work is done: completeTask { taskId, workerId, outcome: { summary: what you produced, verification: how you checked it, files } };\n' +
|
|
39
|
+
'- you cannot finish it: updateTask { taskId, workerId, statusState: "blocked" } and tell the user why;\n' +
|
|
40
|
+
'- the user wants to keep it claimed for themselves: just stop again — you will not be asked twice.',
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Feature `worker-id`: one workerId per session, never shared with another live session.
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import { isAlive } from '../../lib/processTree.mjs';
|
|
4
|
+
|
|
5
|
+
/** Without a known agent process, a session counts as live this long after its last hook. */
|
|
6
|
+
export const LIVE_WINDOW_MS = 10 * 60_000;
|
|
7
|
+
|
|
8
|
+
/** Whether another session is still running: its agent process is alive, or it was heard from recently. */
|
|
9
|
+
export function sessionIsLive(other, now, alive = isAlive) {
|
|
10
|
+
if (other.agentPid) return alive(other.agentPid);
|
|
11
|
+
return now - Number(other.lastSeenAt || 0) < LIVE_WINDOW_MS;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function makeWorkerId(agent, sessionId, host = os.hostname()) {
|
|
15
|
+
const clean = (value) => String(value ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
|
16
|
+
const id = [clean(agent) || 'agent', clean(host).slice(0, 20) || 'host', clean(sessionId).replace(/-/g, '').slice(0, 8) || 'session']
|
|
17
|
+
.join('-');
|
|
18
|
+
return id.slice(0, 64);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const STARTS_WORK = (name, args) => name === 'claimTask' || (name === 'updateTask' && args?.statusState === 'in_progress');
|
|
22
|
+
|
|
23
|
+
/** Before claimTask (or a start): refuse a workerId another live session is using, and a second claim without one. */
|
|
24
|
+
export function workerIdDecision(session, others, { name, args = {} }, now, alive = isAlive) {
|
|
25
|
+
if (!STARTS_WORK(name, args)) return { type: 'none' };
|
|
26
|
+
const requested = typeof args.workerId === 'string' ? args.workerId.trim() : '';
|
|
27
|
+
const held = Object.values(session.claims ?? {});
|
|
28
|
+
if (!requested) {
|
|
29
|
+
if (held.length > 0 && name === 'claimTask' && !args.taskId) {
|
|
30
|
+
const mine = session.workerId ?? held[0].workerId;
|
|
31
|
+
return {
|
|
32
|
+
type: 'deny',
|
|
33
|
+
message: `Introsio: pass a workerId. To continue "${held[0].title}", use "${mine}". If you are a separate parallel worker (e.g. a subagent), use your own, e.g. "${mine}-2" — without one the server cannot tell workers apart.`,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
return { type: 'none' };
|
|
37
|
+
}
|
|
38
|
+
const taken = others.find((other) => Object.values(other.claims ?? {}).some((claim) => (claim.workerId ?? other.workerId) === requested
|
|
39
|
+
&& (!claim.expiresAt || claim.expiresAt > now))
|
|
40
|
+
&& sessionIsLive(other, now, alive));
|
|
41
|
+
if (taken) {
|
|
42
|
+
const mine = session.workerId && session.workerId !== requested ? session.workerId : null;
|
|
43
|
+
return {
|
|
44
|
+
type: 'deny',
|
|
45
|
+
message: `Introsio: workerId "${requested}" is in use by another live ${taken.agent ?? 'agent'} session. Two sessions with one workerId look like one worker and can both work the same task. Use ${mine ? `your own workerId "${mine}"` : 'a workerId of your own'}.`,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
return { type: 'none' };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function workerIdNote(session) {
|
|
52
|
+
return session.workerId
|
|
53
|
+
? `Introsio: if you execute an Introsio project in this session, use workerId "${session.workerId}" on claimTask, updateTask, updateSubtask and completeTask.`
|
|
54
|
+
: null;
|
|
55
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Entry point every agent's hook config calls: node introsio-hook.mjs <agent> [<event>]
|
|
3
|
+
// Reads the hook payload on stdin, answers on stdout in that agent's format, and
|
|
4
|
+
// ALWAYS exits 0 — a broken hook must never trap the agent. Internal errors go to
|
|
5
|
+
// ~/.introsio/errors.log (shown by `int doctor`), never to stdout.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { normalize } from './normalize.mjs';
|
|
9
|
+
import { respond } from './respond.mjs';
|
|
10
|
+
import { handleEvent } from './engine.mjs';
|
|
11
|
+
import { introsioDir } from '../lib/paths.mjs';
|
|
12
|
+
import { killChildrenOnSignals } from '../lib/processTree.mjs';
|
|
13
|
+
|
|
14
|
+
const STDIN_IDLE_MS = 2000;
|
|
15
|
+
const STDIN_MAX_MS = 10_000;
|
|
16
|
+
const MAX_ERROR_LOG_BYTES = 1024 * 1024;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Reads the payload. Resolves as soon as the bytes so far parse as one JSON
|
|
20
|
+
* value, at EOF, or when input stops arriving — an agent that never closes
|
|
21
|
+
* stdin must not hang its own hook.
|
|
22
|
+
*/
|
|
23
|
+
function readPayload(stream = process.stdin) {
|
|
24
|
+
if (stream.isTTY) return Promise.resolve('');
|
|
25
|
+
return new Promise((resolve) => {
|
|
26
|
+
let text = '';
|
|
27
|
+
let done = false;
|
|
28
|
+
let idle = null;
|
|
29
|
+
const finish = () => {
|
|
30
|
+
if (done) return;
|
|
31
|
+
done = true;
|
|
32
|
+
clearTimeout(idle);
|
|
33
|
+
clearTimeout(hard);
|
|
34
|
+
stream.pause();
|
|
35
|
+
stream.removeAllListeners('data');
|
|
36
|
+
resolve(text);
|
|
37
|
+
};
|
|
38
|
+
const hard = setTimeout(finish, STDIN_MAX_MS);
|
|
39
|
+
stream.setEncoding('utf8');
|
|
40
|
+
stream.on('data', (chunk) => {
|
|
41
|
+
text += chunk;
|
|
42
|
+
clearTimeout(idle);
|
|
43
|
+
try {
|
|
44
|
+
JSON.parse(text);
|
|
45
|
+
finish();
|
|
46
|
+
return;
|
|
47
|
+
} catch { /* not complete yet */ }
|
|
48
|
+
idle = setTimeout(finish, STDIN_IDLE_MS);
|
|
49
|
+
});
|
|
50
|
+
stream.on('end', finish);
|
|
51
|
+
stream.on('error', finish);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function logError(agent, event, error) {
|
|
56
|
+
try {
|
|
57
|
+
const file = path.join(introsioDir(), 'errors.log');
|
|
58
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
59
|
+
try { if (fs.statSync(file).size > MAX_ERROR_LOG_BYTES) fs.renameSync(file, `${file}.1`); } catch { /* none yet */ }
|
|
60
|
+
fs.appendFileSync(file, `${new Date().toISOString()} ${agent} ${event}: ${String(error?.stack ?? error).split('\n').slice(0, 6).join(' | ')}\n`);
|
|
61
|
+
} catch { /* nowhere to report */ }
|
|
62
|
+
if (process.env.INTROSIO_HOOK_DEBUG) process.stderr.write(`int hook: ${error?.stack ?? error}\n`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function main() {
|
|
66
|
+
killChildrenOnSignals();
|
|
67
|
+
const [agent, eventArg] = process.argv.slice(2);
|
|
68
|
+
const text = await readPayload();
|
|
69
|
+
let payload;
|
|
70
|
+
try {
|
|
71
|
+
payload = text.trim() ? JSON.parse(text) : {};
|
|
72
|
+
} catch (error) {
|
|
73
|
+
logError(agent, eventArg, new Error(`unreadable payload (${text.length} bytes): ${error.message}`));
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
let evt = null;
|
|
77
|
+
try {
|
|
78
|
+
evt = normalize(agent, eventArg, payload);
|
|
79
|
+
if (!evt) return;
|
|
80
|
+
const answer = await handleEvent(evt);
|
|
81
|
+
const output = respond(agent, evt, answer);
|
|
82
|
+
if (output !== null && output !== undefined) process.stdout.write(`${JSON.stringify(output)}\n`);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
logError(agent, eventArg, error);
|
|
85
|
+
// Still answer in the shape the agent requires.
|
|
86
|
+
const output = respond(agent, evt ?? { event: null }, { type: 'none' });
|
|
87
|
+
if (output) process.stdout.write(`${JSON.stringify(output)}\n`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
main().finally(() => {
|
|
92
|
+
process.exitCode = 0;
|
|
93
|
+
// Never linger: an open handle must not keep the agent waiting.
|
|
94
|
+
setTimeout(() => process.exit(0), 50).unref();
|
|
95
|
+
});
|