pi-durable-subagents 1.5.1 → 1.6.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 +34 -0
- package/README.md +69 -14
- package/dist/agent/capabilities.js +5 -4
- package/dist/agent/child/live.js +2 -1
- package/dist/agent/exact/capture.js +3 -2
- package/dist/agent/main/snapshots.js +10 -9
- package/dist/agent/main.js +2 -1
- package/dist/cli/chaos/stack.js +53 -21
- package/dist/cli/control.js +4 -3
- package/dist/cli/doctor.js +3 -1
- package/dist/cli/drill/index.js +35 -17
- package/dist/cli/hold.js +221 -16
- package/dist/cli/restart.js +14 -2
- package/dist/cli/service.js +77 -2
- package/dist/cli/smoke.js +10 -6
- package/dist/compat/agents.js +46 -13
- package/dist/events/log.js +33 -11
- package/dist/kernel/cache.js +3 -2
- package/dist/kernel/fsx.js +203 -0
- package/dist/kernel/ids.js +11 -0
- package/dist/kernel/journal.js +42 -25
- package/dist/kernel/mailbox.js +7 -4
- package/dist/orchestrator/engine.js +49 -46
- package/dist/orchestrator/evaluator-client.js +11 -3
- package/dist/orchestrator/executor/command.js +21 -6
- package/dist/orchestrator/executor/effects/gate.js +291 -56
- package/dist/orchestrator/executor/effects/index.js +3 -4
- package/dist/orchestrator/executor/effects/output.js +9 -5
- package/dist/orchestrator/executor/effects/prepare.js +34 -32
- package/dist/orchestrator/executor/effects/worktree-path.js +102 -0
- package/dist/orchestrator/executor/ended.js +7 -3
- package/dist/orchestrator/executor/index.js +216 -62
- package/dist/orchestrator/executor/memory.js +15 -0
- package/dist/orchestrator/executor/session.js +4 -3
- package/dist/orchestrator/executor/sweep.js +34 -1
- package/dist/orchestrator/executor/worktree.js +1 -1
- package/dist/orchestrator/main.js +4 -2
- package/dist/orchestrator/reader-ledger.js +3 -2
- package/dist/orchestrator/settled.js +2 -1
- package/dist/orchestrator/snapshot.js +24 -19
- package/dist/orchestrator/stats.js +2 -1
- package/dist/orchestrator/store.js +3 -2
- package/dist/platform/cmdline.js +3 -0
- package/dist/platform/command.js +184 -20
- package/dist/platform/containment.js +204 -40
- package/dist/platform/job.js +1404 -0
- package/dist/platform/launch.js +157 -23
- package/dist/platform/lease.js +351 -32
- package/dist/platform/lock.js +464 -16
- package/dist/platform/proctable.js +31 -2
- package/dist/platform/windows.js +642 -0
- package/dist/requests.js +1 -1
- package/dist/ui/data.js +7 -6
- package/dist/ui/session.js +6 -5
- package/package.json +3 -3
|
@@ -1,13 +1,68 @@
|
|
|
1
|
-
// Private workflow records (P30, A5): gate-intent{call,id,exec},
|
|
1
|
+
// Private workflow records (P30, A5): gate-intent{call,id,exec,jobDir?},
|
|
2
2
|
// gate-tracked{id,process}; gate{id,exit,json?,error?,unknown?,aborted?}.
|
|
3
3
|
// DSA_RESULT and DSA_OUTPUT are immutable gate inputs; JSON output is read from stdout.
|
|
4
|
+
import { closeSync, openSync } from "node:fs";
|
|
5
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
4
6
|
import { join } from "node:path";
|
|
7
|
+
import { retryWinSharing } from "../../../kernel/fsx.js";
|
|
5
8
|
import { publishFile } from "../../../kernel/mailbox.js";
|
|
6
9
|
import { callDir } from "../../../paths.js";
|
|
7
10
|
import { validate } from "../../../agent/child/schema.js";
|
|
8
|
-
import { fenceAttentionResolved, recordFenceFailure, recordOnce } from "../sweep.js";
|
|
11
|
+
import { fenceAttentionResolved, gateJobProcesses, gateJobTracked, recordFenceFailure, recordOnce } from "../sweep.js";
|
|
9
12
|
import { entriesOf } from "../indexes.js";
|
|
10
|
-
|
|
13
|
+
import { JOB_HOST_LOG, prepareCancelled, prepareJob, readGroupEndSync, spawnInJob, startError, } from "../../../platform/job.js";
|
|
14
|
+
import { shellTarget } from "../../../platform/launch.js";
|
|
15
|
+
import { comspec, envValue, helperEnv, isWinStart, mergeEnv, normalizeEnv, sameCreation, systemRoot, winTagArg } from "../../../platform/windows.js";
|
|
16
|
+
const GATE_SPEC = "gate.json";
|
|
17
|
+
const GATE_WRAPPER = "wrapper.mjs";
|
|
18
|
+
const GATE_STDOUT = "stdout.log";
|
|
19
|
+
/** Windows gate wrapper: runs inside the per-gate Job Object (created suspended and assigned before its first
|
|
20
|
+
* instruction). Normalizes the case-insensitive Windows environment, executes the gate command through its ComSpec
|
|
21
|
+
* with stdout inherited and stdin/stderr attached to NUL, and exits with the normalized DWORD status. */
|
|
22
|
+
export const GATE_WRAPPER_SOURCE = `import { spawn } from "node:child_process";
|
|
23
|
+
import { readFileSync, unlinkSync } from "node:fs";
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
const dir = process.argv[2];
|
|
26
|
+
const SHARING = new Set(["EACCES", "EBUSY", "EPERM"]);
|
|
27
|
+
const WAIT = new Int32Array(new SharedArrayBuffer(4));
|
|
28
|
+
function retrySharing(fn, deadline) {
|
|
29
|
+
for (let attempt = 0; ; attempt++) {
|
|
30
|
+
try { return fn(); }
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (!SHARING.has(error && error.code) || attempt >= 25) throw error;
|
|
33
|
+
const left = deadline - Date.now();
|
|
34
|
+
if (left <= 0) throw error;
|
|
35
|
+
Atomics.wait(WAIT, 0, 0, Math.min(left, Math.min(100, 10 * (attempt + 1))));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
let spec;
|
|
40
|
+
try {
|
|
41
|
+
spec = JSON.parse(retrySharing(() => readFileSync(join(dir, "${GATE_SPEC}"), "utf8"), Date.now() + 2500));
|
|
42
|
+
try { unlinkSync(join(dir, "${GATE_SPEC}")); } catch { /* already gone */ }
|
|
43
|
+
} catch { process.exit(126); }
|
|
44
|
+
function dword(code) { return code >>> 0; }
|
|
45
|
+
function value(env, name) { const lower = name.toLowerCase(); let found; for (const key of Object.keys(env)) if (key.toLowerCase() === lower) found = env[key]; return found; }
|
|
46
|
+
function put(env, name, val) { const lower = name.toLowerCase(); for (const key of Object.keys(env)) if (key.toLowerCase() === lower) delete env[key]; env[name] = val; }
|
|
47
|
+
const shell = value(spec.env, "ComSpec") || value(process.env, "ComSpec") || (process.platform === "win32" ? "cmd.exe" : "/bin/sh");
|
|
48
|
+
const env = {};
|
|
49
|
+
for (const key of Object.keys(spec.env)) put(env, key, spec.env[key]);
|
|
50
|
+
put(env, "ComSpec", shell);
|
|
51
|
+
put(env, "PATHEXT", value(spec.env, "PATHEXT") || value(process.env, "PATHEXT") || ".COM;.EXE;.BAT;.CMD");
|
|
52
|
+
let child;
|
|
53
|
+
try {
|
|
54
|
+
child = spawn(spec.command, { cwd: spec.cwd, env, shell, stdio: ["ignore", "inherit", "ignore"], windowsHide: true });
|
|
55
|
+
} catch (error) {
|
|
56
|
+
process.exit(error && error.code === "ENOENT" ? 127 : 126);
|
|
57
|
+
}
|
|
58
|
+
child.once("error", error => { process.exit(error && error.code === "ENOENT" ? 127 : 126); });
|
|
59
|
+
child.once("exit", (code, signal) => { process.exit(code === null ? (signal ? 128 : 1) : dword(code)); });
|
|
60
|
+
`;
|
|
61
|
+
function tracked(journal, intent) {
|
|
62
|
+
const id = String(intent.id);
|
|
63
|
+
const recorded = journal.entries().filter(e => e.type === "gate-tracked" && e.id === id).map(e => e.process);
|
|
64
|
+
return gateJobTracked(intent.jobDir, id, recorded);
|
|
65
|
+
}
|
|
11
66
|
// Calls parked on an unfenced gate, woken when the sweep records the gate's outcome.
|
|
12
67
|
const parked = new Map();
|
|
13
68
|
/** P30, F1: A gate proven retired after a failed fence gets its unknown outcome once and its attention resolved. */
|
|
@@ -47,7 +102,7 @@ async function gateParked(journal, id, signal) {
|
|
|
47
102
|
async function fenceGate(journal, intent, containment) {
|
|
48
103
|
const id = String(intent.id);
|
|
49
104
|
try {
|
|
50
|
-
await containment.fence(id, tracked(journal,
|
|
105
|
+
await containment.fence(id, tracked(journal, intent));
|
|
51
106
|
return true;
|
|
52
107
|
}
|
|
53
108
|
catch (error) {
|
|
@@ -91,7 +146,7 @@ function apply(result, record) {
|
|
|
91
146
|
return { ...result, data: { ...data, gate: record.json } };
|
|
92
147
|
}
|
|
93
148
|
/** P30: Run a contained, journaled gate at most once and honor settlement aborts. */
|
|
94
|
-
export async function runGate(t, home, cwd, exec, result, signal, containment) {
|
|
149
|
+
export async function runGate(t, home, cwd, exec, result, signal, containment, options = {}) {
|
|
95
150
|
if (!t.spec.gate || signal.aborted)
|
|
96
151
|
return result;
|
|
97
152
|
const prior = t.journal.entries().filter(e => e.type === "gate-intent" && e.call === t.callId);
|
|
@@ -112,8 +167,11 @@ export async function runGate(t, home, cwd, exec, result, signal, containment) {
|
|
|
112
167
|
const gate = typeof t.spec.gate === "string" ? { command: t.spec.gate } : t.spec.gate;
|
|
113
168
|
if (gate.timeoutMs !== undefined && (!Number.isFinite(gate.timeoutMs) || gate.timeoutMs < 0))
|
|
114
169
|
throw new Error("Invalid gate timeout");
|
|
115
|
-
const
|
|
116
|
-
const
|
|
170
|
+
const n = prior.length + 1, win = (options.platform ?? process.platform) === "win32";
|
|
171
|
+
const id = `gate:${t.callId}#${n}`, dir = join(callDir(home, t.wid, t.key, t.gen), `gate-${n}`), jobDir = join(dir, "job");
|
|
172
|
+
// Persist the Windows Job Object handshake directory on `gate-intent` BEFORE spawning any host or gate process,
|
|
173
|
+
// so crash recovery and sweeps always bind the verified Job Object owner and wrapper identities before user code acts.
|
|
174
|
+
const intent = await t.journal.append("gate-intent", { call: t.callId, id, exec, ...(win ? { jobDir } : {}) });
|
|
117
175
|
for (const [name, bytes] of [["result.json", JSON.stringify(result)], ["output.txt", result.output]]) {
|
|
118
176
|
if (await publishFile(dir, name, bytes) === "conflict")
|
|
119
177
|
throw new Error(`Gate input conflict: ${dir}/${name}`);
|
|
@@ -128,55 +186,232 @@ export async function runGate(t, home, cwd, exec, result, signal, containment) {
|
|
|
128
186
|
let abort = () => { };
|
|
129
187
|
let fields = { id, exit: null };
|
|
130
188
|
let finishRead = Promise.resolve(), retired = false;
|
|
131
|
-
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
await
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
189
|
+
if (win) {
|
|
190
|
+
const stdoutPath = join(jobDir, GATE_STDOUT);
|
|
191
|
+
let prepared, spawned, killActiveOwner;
|
|
192
|
+
let abortLaunch = () => { }, stdoutReady = false;
|
|
193
|
+
try {
|
|
194
|
+
await mkdir(jobDir, { recursive: true });
|
|
195
|
+
await writeFile(stdoutPath, "");
|
|
196
|
+
const inherited = normalizeEnv(process.env);
|
|
197
|
+
const gateEnv = mergeEnv(inherited, {
|
|
198
|
+
ComSpec: envValue(inherited, "ComSpec") || (process.platform === "win32" ? comspec(inherited) : "/bin/sh"),
|
|
199
|
+
PATHEXT: envValue(inherited, "PATHEXT") || ".COM;.EXE;.BAT;.CMD",
|
|
200
|
+
DSA_RESULT: join(dir, "result.json"),
|
|
201
|
+
DSA_OUTPUT: join(dir, "output.txt"),
|
|
202
|
+
DSA_CALL: t.callId,
|
|
203
|
+
DSA_EXEC: id,
|
|
204
|
+
});
|
|
205
|
+
await writeFile(join(jobDir, GATE_SPEC), JSON.stringify({ command: gate.command, cwd, env: gateEnv }));
|
|
206
|
+
await writeFile(join(jobDir, GATE_WRAPPER), GATE_WRAPPER_SOURCE);
|
|
207
|
+
const launch = {
|
|
208
|
+
exe: process.execPath,
|
|
209
|
+
args: [join(jobDir, GATE_WRAPPER), jobDir, winTagArg("DSA_EXEC", id)],
|
|
210
|
+
cwd,
|
|
211
|
+
log: "",
|
|
212
|
+
env: helperEnv({ SystemRoot: systemRoot() }),
|
|
213
|
+
exec: id,
|
|
214
|
+
};
|
|
215
|
+
prepared = await prepareJob(jobDir, launch, {
|
|
216
|
+
signal,
|
|
217
|
+
...(options.job?.compiler ? { compiler: options.job.compiler } : {}),
|
|
218
|
+
...(options.job?.compileMs ? { compileMs: options.job.compileMs } : {}),
|
|
219
|
+
...(options.job?.publish ? { publish: options.job.publish } : {}),
|
|
220
|
+
});
|
|
221
|
+
if (signal.aborted) {
|
|
222
|
+
await prepared.release().catch(() => { });
|
|
223
|
+
fields.aborted = true;
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
abortLaunch = () => { try {
|
|
227
|
+
killActiveOwner?.();
|
|
228
|
+
}
|
|
229
|
+
catch { /* gone */ } };
|
|
230
|
+
signal.addEventListener("abort", abortLaunch, { once: true });
|
|
231
|
+
let stdoutFd, errFd;
|
|
232
|
+
try {
|
|
233
|
+
stdoutFd = openSync(stdoutPath, "a");
|
|
234
|
+
errFd = openSync(join(jobDir, JOB_HOST_LOG), "a");
|
|
235
|
+
spawned = await spawnInJob(jobDir, launch, {
|
|
236
|
+
prepared,
|
|
237
|
+
proceed: () => !signal.aborted,
|
|
238
|
+
stdio: options.job?.stdio ?? ["ignore", stdoutFd, errFd],
|
|
239
|
+
unref: false,
|
|
240
|
+
onOwnerSpawned: kill => {
|
|
241
|
+
killActiveOwner = kill;
|
|
242
|
+
if (signal.aborted) {
|
|
243
|
+
try {
|
|
244
|
+
kill();
|
|
245
|
+
}
|
|
246
|
+
catch { /* gone */ }
|
|
247
|
+
}
|
|
248
|
+
options.onJobOwnerSpawned?.();
|
|
249
|
+
},
|
|
250
|
+
...(options.job?.timeoutMs !== undefined ? { timeoutMs: options.job.timeoutMs } : {}),
|
|
251
|
+
...(options.job?.observeMs !== undefined ? { observeMs: options.job.observeMs } : {}),
|
|
252
|
+
...(options.job?.endMs !== undefined ? { endMs: options.job.endMs } : {}),
|
|
253
|
+
...(options.job?.observe ? { observe: options.job.observe } : {}),
|
|
254
|
+
...(options.job?.endHelper ? { endHelper: options.job.endHelper } : {}),
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
if (stdoutFd !== undefined)
|
|
259
|
+
closeSync(stdoutFd);
|
|
260
|
+
if (errFd !== undefined)
|
|
261
|
+
closeSync(errFd);
|
|
262
|
+
signal.removeEventListener("abort", abortLaunch);
|
|
263
|
+
}
|
|
264
|
+
if (!spawned) {
|
|
265
|
+
await prepared.release().catch(() => { });
|
|
266
|
+
fields.aborted = true;
|
|
267
|
+
}
|
|
268
|
+
else {
|
|
269
|
+
killActiveOwner = spawned.killOwner;
|
|
270
|
+
const remember = async (p) => {
|
|
271
|
+
if (!isWinStart(p.start) || known.some(k => k.pid === p.pid && sameCreation(k.start, p.start)))
|
|
272
|
+
return;
|
|
273
|
+
await t.journal.append("gate-tracked", { id, process: p });
|
|
274
|
+
known.push(p);
|
|
275
|
+
};
|
|
276
|
+
if (spawned.uncertain) {
|
|
277
|
+
for (const p of gateJobProcesses(jobDir, id))
|
|
278
|
+
await remember(p);
|
|
279
|
+
if (spawned.pid > 0 && isWinStart(spawned.start))
|
|
280
|
+
await remember({ pid: spawned.pid, start: spawned.start, ppid: process.pid, tag: id });
|
|
281
|
+
fields.error = spawned.uncertain;
|
|
282
|
+
}
|
|
283
|
+
else {
|
|
284
|
+
if (options.beforeRecordTracked)
|
|
285
|
+
await options.beforeRecordTracked();
|
|
286
|
+
for (const p of gateJobProcesses(jobDir, id))
|
|
287
|
+
await remember(p);
|
|
288
|
+
if (spawned.group && isWinStart(spawned.group.start))
|
|
289
|
+
await remember({ pid: spawned.group.pid, start: spawned.group.start, ppid: process.pid, tag: id });
|
|
290
|
+
if (spawned.pid > 0 && isWinStart(spawned.start))
|
|
291
|
+
await remember({ pid: spawned.pid, start: spawned.start, ppid: spawned.group?.pid ?? process.pid, tag: id });
|
|
292
|
+
let failScan = () => { };
|
|
293
|
+
const scanFailed = new Promise((_, reject) => { failScan = reject; });
|
|
294
|
+
scanTimer = setInterval(() => {
|
|
295
|
+
scanQueue = scanQueue.then(async () => {
|
|
296
|
+
const found = await containment.scan(new Map([[id, known]]));
|
|
297
|
+
for (const p of found.get(id) ?? [])
|
|
298
|
+
await remember(p);
|
|
299
|
+
});
|
|
300
|
+
void scanQueue.catch(failScan);
|
|
301
|
+
}, 1000);
|
|
302
|
+
const interrupted = new Promise(resolve => {
|
|
303
|
+
abort = () => resolve("aborted");
|
|
304
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
305
|
+
if (signal.aborted)
|
|
306
|
+
abort();
|
|
307
|
+
if (gate.timeoutMs !== undefined)
|
|
308
|
+
timer = setTimeout(() => resolve("timeout"), gate.timeoutMs);
|
|
309
|
+
});
|
|
310
|
+
const outcome = await Promise.race([spawned.exited.then(() => "exited"), interrupted, scanFailed]);
|
|
311
|
+
if (outcome === "aborted")
|
|
312
|
+
fields.aborted = true;
|
|
313
|
+
else if (outcome === "timeout")
|
|
314
|
+
fields.error = "Gate timeout";
|
|
315
|
+
else {
|
|
316
|
+
const groupEnd = readGroupEndSync(jobDir);
|
|
317
|
+
if (groupEnd) {
|
|
318
|
+
stdoutReady = true;
|
|
319
|
+
fields.exit = groupEnd.status;
|
|
320
|
+
}
|
|
321
|
+
else
|
|
322
|
+
fields.error = `Gate job host ended without recording exit status${await startError(jobDir)}`;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
if (signal.aborted || prepareCancelled(error))
|
|
330
|
+
fields.aborted = true;
|
|
331
|
+
else
|
|
332
|
+
fields.error = String(error);
|
|
333
|
+
}
|
|
334
|
+
finally {
|
|
335
|
+
clearTimeout(timer);
|
|
336
|
+
clearInterval(scanTimer);
|
|
337
|
+
signal.removeEventListener("abort", abortLaunch);
|
|
338
|
+
signal.removeEventListener("abort", abort);
|
|
339
|
+
if (spawned && (fields.aborted || fields.error || signal.aborted)) {
|
|
340
|
+
try {
|
|
341
|
+
killActiveOwner?.();
|
|
342
|
+
}
|
|
343
|
+
catch { /* gone */ }
|
|
344
|
+
let waitTimer;
|
|
345
|
+
try {
|
|
346
|
+
await Promise.race([spawned.exited, new Promise(resolve => { waitTimer = setTimeout(resolve, 2000); })]);
|
|
347
|
+
}
|
|
348
|
+
finally {
|
|
349
|
+
clearTimeout(waitTimer);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
await scanQueue.catch(() => { });
|
|
353
|
+
retired = await fenceGate(t.journal, intent, containment);
|
|
354
|
+
}
|
|
355
|
+
if (stdoutReady && retired && !signal.aborted && gate.output === "json") {
|
|
356
|
+
const readStdout = options.readStdout ?? ((path) => readFile(path, "utf8"));
|
|
357
|
+
finishRead = retryWinSharing(() => readStdout(stdoutPath), {
|
|
358
|
+
platform: options.platform ?? process.platform,
|
|
359
|
+
timeoutMs: 2_000,
|
|
360
|
+
maxAttempts: 20,
|
|
361
|
+
}).then(text => { stdout = text; });
|
|
362
|
+
}
|
|
173
363
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
364
|
+
else {
|
|
365
|
+
try {
|
|
366
|
+
const child = await containment.spawn({ ...shellTarget(gate.command, id), cwd, exec: id,
|
|
367
|
+
env: { DSA_RESULT: join(dir, "result.json"), DSA_OUTPUT: join(dir, "output.txt"), DSA_CALL: t.callId } });
|
|
368
|
+
child.stdin.end();
|
|
369
|
+
child.stderr.resume();
|
|
370
|
+
child.stdout.setEncoding("utf8");
|
|
371
|
+
finishRead = (async () => { for await (const chunk of child.stdout)
|
|
372
|
+
stdout += chunk.toString(); })();
|
|
373
|
+
void finishRead.catch(() => { });
|
|
374
|
+
const remember = async (p) => {
|
|
375
|
+
if (known.some(k => k.pid === p.pid && k.start === p.start))
|
|
376
|
+
return;
|
|
377
|
+
await t.journal.append("gate-tracked", { id, process: p });
|
|
378
|
+
known.push(p);
|
|
379
|
+
};
|
|
380
|
+
if (child.start)
|
|
381
|
+
await remember({ pid: child.pid, start: child.start, ppid: process.pid, tag: id });
|
|
382
|
+
let failScan = () => { };
|
|
383
|
+
const scanFailed = new Promise((_, reject) => { failScan = reject; });
|
|
384
|
+
scanTimer = setInterval(() => {
|
|
385
|
+
scanQueue = scanQueue.then(async () => { const found = await containment.scan(new Map([[id, known]])); for (const p of found.get(id) ?? [])
|
|
386
|
+
await remember(p); });
|
|
387
|
+
void scanQueue.catch(failScan);
|
|
388
|
+
}, 1000);
|
|
389
|
+
const interrupted = new Promise((resolve) => {
|
|
390
|
+
abort = () => resolve("aborted");
|
|
391
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
392
|
+
if (signal.aborted)
|
|
393
|
+
abort();
|
|
394
|
+
if (gate.timeoutMs !== undefined)
|
|
395
|
+
timer = setTimeout(() => resolve("timeout"), gate.timeoutMs);
|
|
396
|
+
});
|
|
397
|
+
const outcome = await Promise.race([child.exited, interrupted, scanFailed]);
|
|
398
|
+
if (outcome === "aborted")
|
|
399
|
+
fields.aborted = true;
|
|
400
|
+
else if (outcome === "timeout")
|
|
401
|
+
fields.error = "Gate timeout";
|
|
402
|
+
else
|
|
403
|
+
fields.exit = outcome.code;
|
|
404
|
+
}
|
|
405
|
+
catch (error) {
|
|
406
|
+
fields.error = String(error);
|
|
407
|
+
}
|
|
408
|
+
finally {
|
|
409
|
+
clearTimeout(timer);
|
|
410
|
+
clearInterval(scanTimer);
|
|
411
|
+
signal.removeEventListener("abort", abort);
|
|
412
|
+
await scanQueue.catch(() => { });
|
|
413
|
+
retired = await fenceGate(t.journal, intent, containment);
|
|
414
|
+
}
|
|
180
415
|
}
|
|
181
416
|
if (!retired) {
|
|
182
417
|
// F1, A2: descendants may still live; the outcome is left to the sweep (unknown) and the call waits for it.
|
|
@@ -186,7 +421,7 @@ export async function runGate(t, home, cwd, exec, result, signal, containment) {
|
|
|
186
421
|
await finishRead.catch(error => { outputError = String(error); });
|
|
187
422
|
if (signal.aborted)
|
|
188
423
|
fields = { id, exit: fields.exit, aborted: true };
|
|
189
|
-
else if (outputError)
|
|
424
|
+
else if (!fields.error && outputError)
|
|
190
425
|
fields.error = outputError;
|
|
191
426
|
else if (fields.exit === 0 && !fields.error && gate.output === "json") {
|
|
192
427
|
try {
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { serialContainment } from "../sweep.js";
|
|
2
|
-
import { cleanWorktree, prepareFork, prepareWorktree } from "./prepare.js";
|
|
2
|
+
import { cleanWorktree, prepareFork, prepareWorktree, worktreePath } from "./prepare.js";
|
|
3
3
|
import { recoverGates, runGate } from "./gate.js";
|
|
4
4
|
import { publishOutput } from "./output.js";
|
|
5
5
|
/** P19, P30, P32, P33, A5: Construct durable call effects under the orchestrator's single-writer authority. */
|
|
6
|
-
export default function createEffects(ledgers, containment = serialContainment()) {
|
|
6
|
+
export default function createEffects(ledgers, containment = serialContainment(), gateOptions) {
|
|
7
7
|
const queues = new Map();
|
|
8
8
|
function serial(key, operation) {
|
|
9
9
|
const result = (queues.get(key) ?? Promise.resolve()).then(operation);
|
|
@@ -23,8 +23,7 @@ export default function createEffects(ledgers, containment = serialContainment()
|
|
|
23
23
|
// A refused call did no work: no gate, no output (the executor does not call this for one either).
|
|
24
24
|
if (t.refusal !== undefined || ctl.signal.aborted || ["stopped", "timeout", "budget"].includes(result.status))
|
|
25
25
|
return result;
|
|
26
|
-
const
|
|
27
|
-
const gated = await runGate(t, ledgers.home, intent ? String(intent.path) : t.cwd, exec, result, ctl.signal, containment);
|
|
26
|
+
const gated = await runGate(t, ledgers.home, worktreePath(t.journal, t.callId) ?? t.cwd, exec, result, ctl.signal, containment, gateOptions);
|
|
28
27
|
if (ctl.signal.aborted)
|
|
29
28
|
return result;
|
|
30
29
|
return serial(`output:${t.journal.path}`, () => publishOutput(t, ledgers.home, gated));
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// Private workflow records (P19, A5): output-intent{call,path,hash,previous,absolute},
|
|
2
2
|
// output{call,path,hash,skipped?}. Intent fixes the artifact identity across crash windows.
|
|
3
|
-
import { readFile,
|
|
3
|
+
import { readFile, symlink, unlink } from "node:fs/promises";
|
|
4
4
|
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
5
5
|
import { createHash, randomUUID } from "node:crypto";
|
|
6
6
|
import { publishFile } from "../../../kernel/mailbox.js";
|
|
7
7
|
import { syncDirectory } from "../../../kernel/journal.js";
|
|
8
|
+
import { replacePath } from "../../../kernel/fsx.js";
|
|
8
9
|
import { artifactsDir } from "../../../paths.js";
|
|
9
10
|
import { attention } from "./prepare.js";
|
|
10
11
|
const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
@@ -22,18 +23,21 @@ async function replace(path, bytes) {
|
|
|
22
23
|
const temp = `.${randomUUID()}.tmp`, dir = dirname(path);
|
|
23
24
|
try {
|
|
24
25
|
await publishFile(dir, temp, bytes);
|
|
25
|
-
await
|
|
26
|
+
await replacePath(join(dir, temp), path);
|
|
26
27
|
await syncDirectory(dir);
|
|
27
28
|
}
|
|
28
29
|
finally {
|
|
29
30
|
await unlink(join(dir, temp)).catch(() => { });
|
|
30
31
|
}
|
|
31
32
|
}
|
|
32
|
-
async function latest(path) {
|
|
33
|
+
async function latest(path, bytes) {
|
|
34
|
+
// Publishing a regular copy on Windows also works for accounts without symlink privileges.
|
|
35
|
+
if (process.platform === "win32")
|
|
36
|
+
return replace(join(dirname(path), "latest"), bytes);
|
|
33
37
|
const dir = dirname(path), temp = join(dir, `.${randomUUID()}.link`);
|
|
34
38
|
try {
|
|
35
39
|
await symlink(basename(path), temp);
|
|
36
|
-
await
|
|
40
|
+
await replacePath(temp, join(dir, "latest"));
|
|
37
41
|
await syncDirectory(dir);
|
|
38
42
|
}
|
|
39
43
|
finally {
|
|
@@ -74,7 +78,7 @@ export async function publishOutput(t, home, result) {
|
|
|
74
78
|
else {
|
|
75
79
|
if (await publishFile(dirname(path), basename(path), result.output) === "conflict")
|
|
76
80
|
throw new Error(`Artifact conflict: ${path}`);
|
|
77
|
-
await latest(path);
|
|
81
|
+
await latest(path, result.output);
|
|
78
82
|
}
|
|
79
83
|
done ??= await t.journal.append("output", { call: t.callId, path, hash: digest });
|
|
80
84
|
}
|
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
import { execFile } from "node:child_process";
|
|
4
4
|
import { promisify } from "node:util";
|
|
5
5
|
import { readFile } from "node:fs/promises";
|
|
6
|
-
import {
|
|
7
|
-
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
6
|
+
import { basename, dirname, resolve } from "node:path";
|
|
8
7
|
import { randomUUID } from "node:crypto";
|
|
9
8
|
import { publishFile } from "../../../kernel/mailbox.js";
|
|
10
9
|
import { contentHash } from "../../../kernel/ids.js";
|
|
11
10
|
import { JT, isEntry } from "../../../types.js";
|
|
12
11
|
import { forkEntry } from "../../origin.js";
|
|
12
|
+
import { checkKey, inside, keyBranch, keyDir, sameWorktree } from "./worktree-path.js";
|
|
13
13
|
const exec = promisify(execFile);
|
|
14
14
|
const git = async (cwd, ...args) => (await exec("git", args, { cwd, timeout: 30000, maxBuffer: 4 * 1024 * 1024 })).stdout.trim();
|
|
15
15
|
const records = (t, type) => t.journal.entries().filter(e => e.type === type && e.call === t.callId);
|
|
@@ -19,25 +19,8 @@ export async function attention(t, kind, text) {
|
|
|
19
19
|
if (!t.journal.entries().some(e => isEntry(e, JT.attention) && e.item?.id === id))
|
|
20
20
|
await t.journal.append(JT.attention, { item: { id, rev: 1, kind: "unknown", text, wid: t.wid, call: t.callId } });
|
|
21
21
|
}
|
|
22
|
-
/** Git lists worktrees by real path (macOS: /var is /private/var); compare paths in that form. */
|
|
23
|
-
function canonical(path) {
|
|
24
|
-
let dir = path, rest = "";
|
|
25
|
-
for (;;) {
|
|
26
|
-
try {
|
|
27
|
-
return join(realpathSync(dir), rest);
|
|
28
|
-
}
|
|
29
|
-
catch {
|
|
30
|
-
const up = dirname(dir);
|
|
31
|
-
if (up === dir)
|
|
32
|
-
return path;
|
|
33
|
-
rest = join(basename(dir), rest);
|
|
34
|
-
dir = up;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
22
|
async function worktree(cwd, path) {
|
|
39
|
-
|
|
40
|
-
return (await worktrees(cwd)).find(w => w.worktree && canonical(w.worktree) === want);
|
|
23
|
+
return (await worktrees(cwd)).find(w => w.worktree && sameWorktree(w.worktree, path));
|
|
41
24
|
}
|
|
42
25
|
async function worktrees(cwd) {
|
|
43
26
|
const text = await git(cwd, "worktree", "list", "--porcelain", "-z");
|
|
@@ -77,30 +60,34 @@ function repairAdvice(path, branch, kept) {
|
|
|
77
60
|
: `${inspect}. The call failed and the path, its files and its branches were left untouched: restore the path on ${branch}, ` +
|
|
78
61
|
`or remove that worktree once its changes are preserved, and run the call again`;
|
|
79
62
|
}
|
|
80
|
-
/** P32: Commit creation intent and reconcile Git's worktree registry and branch identity.
|
|
63
|
+
/** P32: Commit creation intent and reconcile Git's worktree registry and branch identity. The returned cwd is always the
|
|
64
|
+
* intent's spelling (the same string on every replay), so the call, its gate, its cleanup and every message name one
|
|
65
|
+
* path; the registry is matched by the identity the file system gives a path (see `sameWorktree`). */
|
|
81
66
|
export async function prepareWorktree(t) {
|
|
82
67
|
if (t.spec.isolation !== "worktree")
|
|
83
68
|
return t.cwd;
|
|
69
|
+
const root = resolve(t.cwd, ".dsa", t.wid);
|
|
84
70
|
let intent = records(t, "wt-intent")[0];
|
|
85
71
|
if (!intent) {
|
|
86
|
-
|
|
87
|
-
//
|
|
88
|
-
//
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
if (t.key.split("/").some(part => !part || part === "." || part === ".."))
|
|
93
|
-
throw new Error("Invalid worktree key");
|
|
94
|
-
if (!path.startsWith(root + sep))
|
|
72
|
+
// The key is an opaque name inside the workflow's directory, and a key Win32 cannot spell (a colon, a reserved device
|
|
73
|
+
// name, a trailing dot) is encoded instead of resolved, so it cannot replace the root or land outside it. Existing
|
|
74
|
+
// literal keys keep their paths and branches; `:` keys kept the hashed branch namespace they already had.
|
|
75
|
+
checkKey(t.key);
|
|
76
|
+
const path = resolve(root, keyDir(t.key)), branch = keyBranch(t.wid, t.key);
|
|
77
|
+
if (!inside(root, path))
|
|
95
78
|
throw new Error("Invalid worktree key");
|
|
96
79
|
await git(t.cwd, "check-ref-format", "--branch", branch);
|
|
97
80
|
const base = await git(t.cwd, "rev-parse", "HEAD");
|
|
98
|
-
const earlier = t.journal.entries().some(e => e.type === "wt-intent" && e.
|
|
81
|
+
const earlier = t.journal.entries().some(e => e.type === "wt-intent" && e.branch === branch && sameWorktree(String(e.path), path));
|
|
99
82
|
if (!earlier && await branchHead(t.cwd, branch))
|
|
100
83
|
throw new Error(`Worktree branch already exists: ${branch}`);
|
|
101
84
|
intent = await t.journal.append("wt-intent", { call: t.callId, path, branch, base });
|
|
102
85
|
}
|
|
103
86
|
const { path, branch, base } = intent;
|
|
87
|
+
// A journal from before the key rules could hold a path outside the workflow (an absolute key replaced the root then):
|
|
88
|
+
// it must not reach Git, so nothing is created, inspected, moved or removed there.
|
|
89
|
+
if (!inside(root, path))
|
|
90
|
+
throw new Error("Invalid worktree key");
|
|
104
91
|
if (records(t, "wt-removed").length)
|
|
105
92
|
return path;
|
|
106
93
|
const tree = (await worktree(t.cwd, path)), head = await branchHead(t.cwd, branch);
|
|
@@ -125,12 +112,27 @@ export async function prepareWorktree(t) {
|
|
|
125
112
|
await t.journal.append("wt-created", { call: t.callId });
|
|
126
113
|
return path;
|
|
127
114
|
}
|
|
115
|
+
/** The path the journal recorded for a call's worktree (the `wt-intent` spelling, which the call returns and every message
|
|
116
|
+
* names), for the gate or a person asking where it ran; `undefined` when the call records no worktree. */
|
|
117
|
+
export function worktreePath(journal, call) {
|
|
118
|
+
const intent = journal.entries().find(e => e.type === "wt-intent" && e.call === call);
|
|
119
|
+
return intent ? String(intent.path) : undefined;
|
|
120
|
+
}
|
|
128
121
|
/** P32: Remove only a clean successful worktree, retaining its branch and failed work. */
|
|
129
122
|
export async function cleanWorktree(t) {
|
|
130
123
|
const intent = records(t, "wt-intent")[0];
|
|
131
124
|
if (!intent || records(t, "wt-removed").length || records(t, "wt-kept").length)
|
|
132
125
|
return;
|
|
133
|
-
const path = String(intent.path),
|
|
126
|
+
const path = String(intent.path), root = resolve(t.cwd, ".dsa", t.wid);
|
|
127
|
+
// A journal from before the key rules could hold a path outside the workflow: Git is never asked about it, nothing is
|
|
128
|
+
// created or removed there, and the keep is recorded with one note so the cleanup does not retry on every start.
|
|
129
|
+
if (!inside(root, path)) {
|
|
130
|
+
await attention(t, "worktree-conflict", `Worktree path outside its workflow: ${t.callId} (workflow ${t.wid}) records ` +
|
|
131
|
+
`${path}, which is not inside ${root}. Nothing was created, removed or moved, and this call's sealed result is unchanged`);
|
|
132
|
+
await t.journal.append("wt-kept", { call: t.callId });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const tree = (await worktree(t.cwd, path));
|
|
134
136
|
if (!tree) {
|
|
135
137
|
if (records(t, "wt-remove-intent").length)
|
|
136
138
|
await t.journal.append("wt-removed", { call: t.callId });
|