introsio 0.1.0 → 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 +48 -1
- package/LICENSE +1 -1
- package/README.md +111 -16
- package/agents/claude.mjs +15 -8
- package/agents/codex.mjs +6 -5
- package/agents/common.mjs +55 -5
- package/agents/cursor.mjs +10 -5
- package/agents/gemini.mjs +9 -5
- package/agents/opencode.mjs +5 -4
- package/agents/vscode.mjs +9 -7
- package/agents/windsurf.mjs +1 -1
- package/cli.mjs +95 -11
- package/hook/engine.mjs +76 -3
- package/hook/features/claims.mjs +35 -2
- package/hook/features/git.mjs +43 -3
- package/hook/features/notes.mjs +2 -0
- package/hook/features/pause.mjs +340 -0
- package/hook/features/stopGuard.mjs +2 -1
- package/hook/normalize.mjs +1 -1
- package/hook/state.mjs +49 -0
- package/lib/config.mjs +1 -0
- package/lib/git.mjs +83 -5
- package/lib/jsonFile.mjs +29 -2
- package/lib/lock.mjs +144 -13
- package/lib/paths.mjs +2 -2
- package/package.json +4 -5
- package/templates/execute.md +9 -3
- 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
|
+
}
|
|
@@ -33,7 +33,8 @@ export function stopDecision(session, evt, now) {
|
|
|
33
33
|
message:
|
|
34
34
|
`Introsio: you still hold ${open.length} claimed task(s) that are not completed:\n${open.map(describe).join('\n')}\n` +
|
|
35
35
|
'Before you stop, settle each one — and follow what the user asked, not this reminder:\n' +
|
|
36
|
-
'-
|
|
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' +
|
|
37
38
|
'- the work is done: completeTask { taskId, workerId, outcome: { summary: what you produced, verification: how you checked it, files } };\n' +
|
|
38
39
|
'- you cannot finish it: updateTask { taskId, workerId, statusState: "blocked" } and tell the user why;\n' +
|
|
39
40
|
'- the user wants to keep it claimed for themselves: just stop again — you will not be asked twice.',
|
package/hook/normalize.mjs
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
/** Every Introsio MCP tool whose name alone identifies it, even under another server name. */
|
|
7
7
|
export const DISTINCTIVE_TOOLS = new Set([
|
|
8
|
-
'claimTask', 'completeTask', 'undoTaskCompletion', 'updateSubtask', 'getReadySubtasks', 'getReadyTasks',
|
|
8
|
+
'claimTask', 'pauseTask', 'completeTask', 'undoTaskCompletion', 'updateSubtask', 'getReadySubtasks', 'getReadyTasks',
|
|
9
9
|
'getExecutionWaves', 'getProjectPlan', 'createProjectPlan', 'getProjectState', 'updateProjectState',
|
|
10
10
|
'getProjectContext', 'updateProjectContext', 'editProjectContextItems', 'recordProjectDecision',
|
|
11
11
|
'exportProjectBlueprint', 'importProjectBlueprint', 'getTaskDependencies', 'addTaskDependency', 'removeTaskDependency',
|
package/hook/state.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import fs from 'node:fs';
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { sessionsDir } from '../lib/paths.mjs';
|
|
6
6
|
import { readJsonSafe, writeJson } from '../lib/jsonFile.mjs';
|
|
7
|
+
import { acquireLock, SAVE_WAIT_MS } from '../lib/lock.mjs';
|
|
7
8
|
|
|
8
9
|
export const SESSION_TTL_MS = 24 * 60 * 60 * 1000;
|
|
9
10
|
|
|
@@ -49,6 +50,54 @@ export function saveSession(session, env) {
|
|
|
49
50
|
writeJson(path.join(sessionsDir(env), `${safeName(session.sessionId)}.json`), session);
|
|
50
51
|
}
|
|
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
|
+
|
|
52
101
|
/** Every other session seen in the last day (for worker-id collisions and `int claims`). */
|
|
53
102
|
export function loadOtherSessions(sessionId, now, env) {
|
|
54
103
|
const dir = sessionsDir(env);
|
package/lib/config.mjs
CHANGED
|
@@ -15,6 +15,7 @@ export const FEATURES = {
|
|
|
15
15
|
lease: 'Remind the agent to report progress before its claim expires',
|
|
16
16
|
reread: 'Skip re-reading context / schedule the agent already has',
|
|
17
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',
|
|
18
19
|
};
|
|
19
20
|
|
|
20
21
|
export const MODES = ['github', 'local', 'off'];
|
package/lib/git.mjs
CHANGED
|
@@ -1,25 +1,38 @@
|
|
|
1
1
|
// Thin git runner. Every call is synchronous, short, and never throws — a hook
|
|
2
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';
|
|
3
7
|
import { spawnSync } from 'node:child_process';
|
|
4
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
|
+
|
|
5
15
|
export function createGit(cwd) {
|
|
6
|
-
const run = (args, { maxBuffer = 16 * 1024 * 1024 } = {}) => {
|
|
7
|
-
const result = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer, timeout:
|
|
8
|
-
return { ok: result.status === 0, out: (result.stdout ?? '').trimEnd(), err: (result.stderr ?? '').trim() };
|
|
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' };
|
|
9
19
|
};
|
|
10
20
|
const value = (args) => {
|
|
11
21
|
const result = run(args);
|
|
12
22
|
return result.ok ? result.out : null;
|
|
13
23
|
};
|
|
14
|
-
|
|
24
|
+
const api = {
|
|
15
25
|
cwd,
|
|
16
26
|
run,
|
|
17
27
|
root: () => value(['rev-parse', '--show-toplevel']),
|
|
18
|
-
|
|
28
|
+
gitDir: () => value(['rev-parse', '--absolute-git-dir']),
|
|
29
|
+
head: () => value(['rev-parse', '--verify', '--quiet', 'HEAD']),
|
|
19
30
|
shortHead: () => value(['rev-parse', '--short', 'HEAD']),
|
|
20
31
|
branch: () => value(['rev-parse', '--abbrev-ref', 'HEAD']),
|
|
21
32
|
/** Porcelain status lines, ignoring the kit's own folder. */
|
|
22
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),
|
|
23
36
|
upstream: () => value(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']),
|
|
24
37
|
/** Where a bare `git push` sends the current branch ("origin/main"), honouring push.default. */
|
|
25
38
|
pushTarget: () => value(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{push}']),
|
|
@@ -38,5 +51,70 @@ export function createGit(cwd) {
|
|
|
38
51
|
const result = run(['diff', '--no-color', '--no-ext-diff', ...args], { maxBuffer: 128 * 1024 * 1024 });
|
|
39
52
|
return result.ok ? result.out : null;
|
|
40
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
|
+
},
|
|
41
118
|
};
|
|
119
|
+
return api;
|
|
42
120
|
}
|
package/lib/jsonFile.mjs
CHANGED
|
@@ -59,11 +59,38 @@ export function readJsonSafe(file, fallback = {}) {
|
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
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
|
+
|
|
62
84
|
export function writeAtomic(file, text) {
|
|
63
85
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
64
|
-
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
86
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
65
87
|
fs.writeFileSync(tmp, text);
|
|
66
|
-
|
|
88
|
+
try {
|
|
89
|
+
renameWithRetry(tmp, file);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
try { fs.rmSync(tmp, { force: true }); } catch { /* best effort */ }
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
67
94
|
}
|
|
68
95
|
|
|
69
96
|
export function writeJson(file, value) {
|