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.
Files changed (55) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +69 -14
  3. package/dist/agent/capabilities.js +5 -4
  4. package/dist/agent/child/live.js +2 -1
  5. package/dist/agent/exact/capture.js +3 -2
  6. package/dist/agent/main/snapshots.js +10 -9
  7. package/dist/agent/main.js +2 -1
  8. package/dist/cli/chaos/stack.js +53 -21
  9. package/dist/cli/control.js +4 -3
  10. package/dist/cli/doctor.js +3 -1
  11. package/dist/cli/drill/index.js +35 -17
  12. package/dist/cli/hold.js +221 -16
  13. package/dist/cli/restart.js +14 -2
  14. package/dist/cli/service.js +77 -2
  15. package/dist/cli/smoke.js +10 -6
  16. package/dist/compat/agents.js +46 -13
  17. package/dist/events/log.js +33 -11
  18. package/dist/kernel/cache.js +3 -2
  19. package/dist/kernel/fsx.js +203 -0
  20. package/dist/kernel/ids.js +11 -0
  21. package/dist/kernel/journal.js +42 -25
  22. package/dist/kernel/mailbox.js +7 -4
  23. package/dist/orchestrator/engine.js +49 -46
  24. package/dist/orchestrator/evaluator-client.js +11 -3
  25. package/dist/orchestrator/executor/command.js +21 -6
  26. package/dist/orchestrator/executor/effects/gate.js +291 -56
  27. package/dist/orchestrator/executor/effects/index.js +3 -4
  28. package/dist/orchestrator/executor/effects/output.js +9 -5
  29. package/dist/orchestrator/executor/effects/prepare.js +34 -32
  30. package/dist/orchestrator/executor/effects/worktree-path.js +102 -0
  31. package/dist/orchestrator/executor/ended.js +7 -3
  32. package/dist/orchestrator/executor/index.js +216 -62
  33. package/dist/orchestrator/executor/memory.js +15 -0
  34. package/dist/orchestrator/executor/session.js +4 -3
  35. package/dist/orchestrator/executor/sweep.js +34 -1
  36. package/dist/orchestrator/executor/worktree.js +1 -1
  37. package/dist/orchestrator/main.js +4 -2
  38. package/dist/orchestrator/reader-ledger.js +3 -2
  39. package/dist/orchestrator/settled.js +2 -1
  40. package/dist/orchestrator/snapshot.js +24 -19
  41. package/dist/orchestrator/stats.js +2 -1
  42. package/dist/orchestrator/store.js +3 -2
  43. package/dist/platform/cmdline.js +3 -0
  44. package/dist/platform/command.js +184 -20
  45. package/dist/platform/containment.js +204 -40
  46. package/dist/platform/job.js +1404 -0
  47. package/dist/platform/launch.js +157 -23
  48. package/dist/platform/lease.js +351 -32
  49. package/dist/platform/lock.js +464 -16
  50. package/dist/platform/proctable.js +31 -2
  51. package/dist/platform/windows.js +642 -0
  52. package/dist/requests.js +1 -1
  53. package/dist/ui/data.js +7 -6
  54. package/dist/ui/session.js +6 -5
  55. package/package.json +3 -3
@@ -3,6 +3,7 @@ import { PassThrough } from "node:stream";
3
3
  import { setTimeout as delay } from "node:timers/promises";
4
4
  import { performance } from "node:perf_hooks";
5
5
  import { captureStart, ProcessTable } from "./proctable.js";
6
+ import { DWORD_MAX, isOwnedWinChild, isWinKillTimeout, isWinStart, KILL_BATCH_SIZE, killTree, normalizeWinTargets, sameCreation } from "./windows.js";
6
7
  // One table per orchestrator process, including evaluator and gate observers.
7
8
  const sharedTable = new ProcessTable();
8
9
  const identity = (p) => `${p.pid}:${p.start}`;
@@ -10,10 +11,23 @@ const identity = (p) => `${p.pid}:${p.start}`;
10
11
  export class Containment {
11
12
  table;
12
13
  launched = new Map();
13
- constructor(table = sharedTable) { this.table = table; }
14
+ platform;
15
+ readStart;
16
+ fenceTimeoutMs;
17
+ killWin;
18
+ killUnix;
19
+ constructor(table = sharedTable, options = {}) {
20
+ this.table = table;
21
+ this.platform = options.platform ?? process.platform;
22
+ this.readStart = options.captureStart ?? captureStart;
23
+ this.fenceTimeoutMs = options.fenceTimeoutMs;
24
+ this.killWin = options.killWindows ?? killTree;
25
+ this.killUnix = options.killPosix;
26
+ }
14
27
  /** C1, C3: Inject the execution tag and capture the direct child's start token. */
15
28
  async spawn(spec) {
16
- const child = spawn(spec.command, spec.args, { cwd: spec.cwd,
29
+ const child = spawn(spec.command, spec.args, { cwd: spec.cwd, shell: spec.shell,
30
+ ...(spec.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
17
31
  env: { ...process.env, ...spec.env, DSA_EXEC: spec.exec }, stdio: "pipe" });
18
32
  // Buffer output immediately: Node drains child pipes on exit, even while
19
33
  // identity capture is pending and the caller has not received the streams.
@@ -28,9 +42,20 @@ export class Containment {
28
42
  try {
29
43
  await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
30
44
  const pid = child.pid;
31
- const captured = await captureStart(pid);
32
- // Empty tokens represent children that retired before identity capture.
33
- const start = child.exitCode !== null || child.signalCode !== null ? "" : captured;
45
+ let captured = await this.readStart(pid);
46
+ if (!captured && child.exitCode === null && child.signalCode === null) {
47
+ // The child may have just exited in the kernel before libuv delivered `'exit'`; wait briefly, then re-read once.
48
+ await Promise.race([exited.then(() => undefined, () => undefined), delay(100)]);
49
+ if (child.exitCode === null && child.signalCode === null)
50
+ captured = await this.readStart(pid);
51
+ }
52
+ // Empty tokens represent children that retired before identity capture; a still-live child without a valid start
53
+ // token fails closed instead of running untracked.
54
+ const retired = child.exitCode !== null || child.signalCode !== null;
55
+ const start = retired ? "" : captured;
56
+ if (!retired && (!start || (this.platform === "win32" && !isWinStart(start)))) {
57
+ throw new Error(`C3: process ${pid} has no verifiable start identity`);
58
+ }
34
59
  const known = this.launched.get(spec.exec) ?? [];
35
60
  if (start)
36
61
  known.push({ pid, ppid: process.pid, start, tag: spec.exec });
@@ -40,13 +65,16 @@ export class Containment {
40
65
  catch (error) {
41
66
  stdout.destroy();
42
67
  stderr.destroy();
43
- child.kill("SIGKILL");
68
+ // Direct libuv handle termination (`uv_process_kill`), never bare-PID `taskkill /T` without verified `start`.
69
+ if (child.exitCode === null && child.signalCode === null)
70
+ child.kill("SIGKILL");
44
71
  await exited.catch(() => { });
45
72
  throw error;
46
73
  }
47
74
  }
48
75
  /** P22: Find tagged processes and the live descendants of known identities. */
49
76
  async scan(known, options = {}) {
77
+ const windows = this.platform === "win32";
50
78
  const execs = new Set([...known.keys(), ...this.launched.keys()]);
51
79
  const all = await this.table.list(execs, options);
52
80
  for (const p of all)
@@ -69,72 +97,212 @@ export class Containment {
69
97
  else
70
98
  children.set(p.ppid, [p]);
71
99
  }
100
+ const validChild = (parent, child) => {
101
+ if (child.pid === parent.pid || child.ppid !== parent.pid || !parent.start || !child.start)
102
+ return false;
103
+ if (windows)
104
+ return isOwnedWinChild(parent, child);
105
+ if (this.platform === "linux" && /^\d+$/.test(parent.start) && /^\d+$/.test(child.start)) {
106
+ return BigInt(child.start) >= BigInt(parent.start);
107
+ }
108
+ return true;
109
+ };
72
110
  for (const exec of execs) {
73
111
  // Historical identities cannot select an absent/reused pid. Avoid allocating a string/Set entry for each one.
74
- const ids = new Map();
75
- for (const group of [known.get(exec) ?? [], this.launched.get(exec) ?? []])
76
- for (const p of group)
77
- if (p.start !== "" && liveStarts.get(p.pid) === p.start)
78
- ids.set(p.pid, p.start);
112
+ const matchedPids = new Set();
113
+ for (const group of [known.get(exec) ?? [], this.launched.get(exec) ?? []]) {
114
+ for (const p of group) {
115
+ if (!p.start || (windows && !isWinStart(p.start)))
116
+ continue;
117
+ const liveStart = liveStarts.get(p.pid);
118
+ if (liveStart !== undefined && (windows ? sameCreation(liveStart, p.start) : liveStart === p.start))
119
+ matchedPids.add(p.pid);
120
+ }
121
+ }
79
122
  const own = tagged.get(exec);
80
123
  // Nothing tagged and no live identity selects nothing (most execs of a sweep are history).
81
- if (!ids.size && !own) {
124
+ if (!matchedPids.size && !own) {
82
125
  result.set(exec, []);
83
126
  continue;
84
127
  }
85
- // The tagged and the known live processes in table order, then every live descendant (breadth first).
128
+ // The tagged and the known live processes in table order, then every proven-owned live descendant (breadth first).
86
129
  const selected = new Map();
87
130
  for (const p of all)
88
- if (p.tag === exec || ids.get(p.pid) === p.start)
131
+ if (p.tag === exec || matchedPids.has(p.pid))
89
132
  selected.set(p.pid, p);
90
133
  const queue = [...selected.keys()];
91
- for (let i = 0; i < queue.length; i++)
92
- for (const c of children.get(queue[i]) ?? [])
93
- if (!selected.has(c.pid)) {
134
+ for (let i = 0; i < queue.length; i++) {
135
+ const parent = selected.get(queue[i]);
136
+ if (!parent.start || (windows && !isWinStart(parent.start)))
137
+ continue;
138
+ for (const c of children.get(parent.pid) ?? []) {
139
+ if (!selected.has(c.pid) && validChild(parent, c)) {
94
140
  selected.set(c.pid, c);
95
141
  queue.push(c.pid);
96
142
  }
143
+ }
144
+ }
97
145
  result.set(exec, [...selected.values()]);
98
146
  }
99
147
  return result;
100
148
  }
101
149
  /** P22, P23: Kill tagged and tracked identities until a rescan proves retirement. */
102
150
  async fence(exec, tracked, opts = {}) {
103
- const timeout = opts.timeoutMs ?? 5000;
151
+ const windows = this.platform === "win32";
152
+ // PowerShell/CIM scans and handle-verified termination are ~0.5 s on Windows: the Unix 5 s deadline is too
153
+ // tight under load (several workflows, parallel test files).
154
+ const timeout = opts.timeoutMs ?? this.fenceTimeoutMs ?? (windows ? 15_000 : 5000);
104
155
  if (!Number.isFinite(timeout) || timeout < 0)
105
156
  throw new Error("Invalid fence timeout");
106
- const deadline = performance.now() + timeout;
157
+ const started = performance.now(), deadline = started + timeout;
107
158
  let recordingMs = 500;
108
- const known = new Map(tracked.filter(p => p.start !== "").map(p => [identity(p), p]));
159
+ const hasIdentity = (p) => Number.isInteger(p.pid) && p.pid > 0 && (windows ? p.pid <= DWORD_MAX && isWinStart(p.start) : p.start !== "");
160
+ const known = new Map(tracked.filter(hasIdentity).map(p => [identity(p), p]));
161
+ let unverifiedPid;
162
+ // F1 diagnostics: a fence that runs out of budget says what it observed -- numbers only, bounded, no process
163
+ // detail -- so a stall on a loaded runner is attributable: a scan that never answered (0 scans completed), targets
164
+ // that kept appearing after kills, or identities that stayed unconfirmed and were never signalled.
165
+ let scans = 0, slowestScan = 0, seen = 0, kills = 0, skipped = 0;
166
+ const timedOut = (phase) => new Error(`Fence timeout: ${exec} after ${Math.round(performance.now() - started)} ms of ${timeout} ms ` +
167
+ `(${scans} scan(s) completed, slowest ${Math.round(slowestScan)} ms, ${seen} process(es) at the last scan, ` +
168
+ `${kills} kill(s), ${skipped} skipped for an unconfirmed identity; waiting on the ${phase}${unverifiedPid === undefined ? "" : `, unverified identity for pid ${unverifiedPid}`})`);
109
169
  for (;;) {
110
170
  const remaining = deadline - performance.now();
111
171
  let timer;
172
+ const scanStarted = performance.now();
173
+ const pending = this.scan(new Map([[exec, [...known.values()]]]), { fresh: true });
112
174
  const live = await Promise.race([
113
- this.scan(new Map([[exec, [...known.values()]]]), { fresh: true }),
114
- new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`Fence timeout: ${exec}`)), Math.max(0, remaining)); }),
175
+ pending.then(live => { scans++; slowestScan = Math.max(slowestScan, performance.now() - scanStarted); return live; }),
176
+ new Promise((_, reject) => { timer = setTimeout(() => reject(timedOut("scan")), Math.max(0, remaining)); }),
115
177
  ]).finally(() => clearTimeout(timer));
116
178
  const targets = live.get(exec) ?? [];
179
+ seen = targets.length;
117
180
  if (!targets.length) {
118
181
  this.launched.delete(exec);
119
182
  return;
120
183
  }
184
+ for (const p of targets) {
185
+ if (hasIdentity(p))
186
+ known.set(identity(p), p);
187
+ else if (windows) {
188
+ unverifiedPid = p.pid;
189
+ skipped++;
190
+ }
191
+ }
121
192
  if (performance.now() >= deadline)
122
- throw new Error(`Fence timeout: ${exec}`);
193
+ throw timedOut("kill round");
194
+ if (windows) {
195
+ // Fail closed: never touch a target whose `(pid, start)` identity is missing or malformed.
196
+ const verifiedProcs = targets.filter(hasIdentity);
197
+ const killTargets = verifiedProcs.length
198
+ ? normalizeWinTargets(verifiedProcs.map(p => ({ pid: p.pid, start: p.start })))
199
+ : [];
200
+ if (killTargets.length) {
201
+ if (opts.beforeKill && recordingMs > 0) {
202
+ const remainingForDiag = deadline - performance.now();
203
+ if (remainingForDiag <= 0)
204
+ throw timedOut("beforeKill diagnostics");
205
+ const diagBudget = Math.min(recordingMs, remainingForDiag);
206
+ const capsAtDeadline = remainingForDiag <= recordingMs;
207
+ const recordingStarted = performance.now(), controller = new AbortController();
208
+ let diagTimer, deadlineHit = false;
209
+ try {
210
+ const pendingDiag = Promise.resolve().then(() => opts.beforeKill(verifiedProcs, controller.signal)).catch(() => { });
211
+ await Promise.race([
212
+ pendingDiag,
213
+ new Promise(resolve => {
214
+ diagTimer = setTimeout(() => {
215
+ if (capsAtDeadline)
216
+ deadlineHit = true;
217
+ controller.abort();
218
+ resolve();
219
+ }, diagBudget);
220
+ }),
221
+ ]);
222
+ }
223
+ finally {
224
+ clearTimeout(diagTimer);
225
+ controller.abort();
226
+ recordingMs = Math.max(0, recordingMs - (performance.now() - recordingStarted));
227
+ }
228
+ if (deadlineHit || performance.now() >= deadline)
229
+ throw timedOut("beforeKill diagnostics");
230
+ }
231
+ // Handle-verified termination checks GetProcessTimes on the open kernel handle right before TerminateProcess,
232
+ // so exit/PID reuse during scan or beforeKill cannot touch an unrelated process. Bound each batch to the
233
+ // remaining fence deadline and abort in-flight and later batches once the budget expires.
234
+ for (let i = 0; i < killTargets.length; i += KILL_BATCH_SIZE) {
235
+ const remainingForKill = deadline - performance.now();
236
+ if (remainingForKill <= 0)
237
+ throw timedOut(i === 0 ? "kill round" : "kill");
238
+ const batch = killTargets.slice(i, i + KILL_BATCH_SIZE);
239
+ kills += batch.length;
240
+ const controller = new AbortController();
241
+ let killTimer, deadlineErr;
242
+ try {
243
+ const pendingKill = Promise.resolve().then(() => this.killWin(batch, { timeout: Math.max(1, Math.ceil(remainingForKill)), signal: controller.signal }));
244
+ const timeoutKill = new Promise((_, reject) => {
245
+ killTimer = setTimeout(() => {
246
+ deadlineErr = timedOut("kill");
247
+ reject(deadlineErr);
248
+ controller.abort(deadlineErr);
249
+ }, remainingForKill);
250
+ });
251
+ void pendingKill.catch(() => { });
252
+ void timeoutKill.catch(() => { });
253
+ await Promise.race([pendingKill, timeoutKill]);
254
+ }
255
+ catch (error) {
256
+ if (error === deadlineErr)
257
+ throw error;
258
+ if (deadlineErr || isWinKillTimeout(error))
259
+ throw deadlineErr ?? timedOut("kill");
260
+ throw error;
261
+ }
262
+ finally {
263
+ clearTimeout(killTimer);
264
+ controller.abort();
265
+ }
266
+ }
267
+ const rem = deadline - performance.now();
268
+ if (rem <= 0)
269
+ throw timedOut("scan");
270
+ const pause = Math.min(20, Math.floor(rem / 4));
271
+ if (pause > 0)
272
+ await delay(pause);
273
+ }
274
+ else {
275
+ const rem = deadline - performance.now();
276
+ if (rem <= 0)
277
+ throw timedOut("scan");
278
+ await delay(Math.min(20, rem));
279
+ if (performance.now() >= deadline)
280
+ throw timedOut("scan");
281
+ }
282
+ continue;
283
+ }
284
+ const signalUnix = (pid) => {
285
+ kills++;
286
+ try {
287
+ if (this.killUnix)
288
+ this.killUnix(pid);
289
+ else
290
+ process.kill(pid, "SIGKILL");
291
+ }
292
+ catch (error) {
293
+ if (error.code !== "ESRCH")
294
+ throw error;
295
+ }
296
+ };
123
297
  const killing = [];
124
298
  for (const p of targets) {
125
- known.set(identity(p), p);
126
299
  // C3: the pid may have exited and been reused since the scan; kill only if it still has the scanned start.
127
- if (p.start !== "" && await captureStart(p.pid) !== p.start)
300
+ if (p.start !== "" && await this.readStart(p.pid) !== p.start) {
301
+ skipped++;
128
302
  continue;
129
- if (!opts.beforeKill) {
130
- try {
131
- process.kill(p.pid, "SIGKILL");
132
- }
133
- catch (error) {
134
- if (error.code !== "ESRCH")
135
- throw error;
136
- }
137
303
  }
304
+ if (!opts.beforeKill)
305
+ signalUnix(p.pid);
138
306
  else
139
307
  killing.push(p);
140
308
  }
@@ -156,15 +324,11 @@ export class Containment {
156
324
  }
157
325
  for (const p of killing) {
158
326
  // Diagnostic I/O was asynchronous: revalidate identity again before signalling.
159
- if (opts.beforeKill && p.start !== "" && await captureStart(p.pid) !== p.start)
327
+ if (opts.beforeKill && p.start !== "" && await this.readStart(p.pid) !== p.start) {
328
+ skipped++;
160
329
  continue;
161
- try {
162
- process.kill(p.pid, "SIGKILL");
163
- }
164
- catch (error) {
165
- if (error.code !== "ESRCH")
166
- throw error;
167
330
  }
331
+ signalUnix(p.pid);
168
332
  }
169
333
  await delay(Math.min(20, Math.max(0, deadline - performance.now())));
170
334
  }