pi-crew 0.6.1 → 0.6.3

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 (102) hide show
  1. package/CHANGELOG.md +160 -0
  2. package/README.md +70 -33
  3. package/docs/issue-29-analysis.md +189 -0
  4. package/docs/superpowers/plans/2026-06-09-fallow-patterns-adoption.md +1268 -0
  5. package/package.json +2 -2
  6. package/src/config/config.ts +106 -15
  7. package/src/errors.ts +107 -0
  8. package/src/extension/async-notifier.ts +6 -2
  9. package/src/extension/crew-cleanup.ts +8 -5
  10. package/src/extension/management.ts +464 -109
  11. package/src/extension/register.ts +194 -34
  12. package/src/extension/registration/commands.ts +2 -2
  13. package/src/extension/registration/subagent-helpers.ts +2 -2
  14. package/src/extension/registration/subagent-tools.ts +1 -1
  15. package/src/extension/registration/team-tool.ts +1 -1
  16. package/src/extension/registration/viewers.ts +2 -2
  17. package/src/extension/team-tool/api.ts +3 -3
  18. package/src/extension/team-tool/cancel.ts +3 -3
  19. package/src/extension/team-tool/explain.ts +1 -1
  20. package/src/extension/team-tool/handle-schedule.ts +40 -0
  21. package/src/extension/team-tool/inspect.ts +3 -3
  22. package/src/extension/team-tool/lifecycle-actions.ts +4 -4
  23. package/src/extension/team-tool/respond.ts +2 -2
  24. package/src/extension/team-tool/run.ts +60 -11
  25. package/src/extension/team-tool/status.ts +1 -1
  26. package/src/extension/team-tool.ts +173 -46
  27. package/src/hooks/registry.ts +77 -13
  28. package/src/hooks/types.ts +9 -0
  29. package/src/plugins/plugin-define.ts +6 -0
  30. package/src/plugins/plugin-registry.ts +32 -0
  31. package/src/plugins/plugins/index.ts +3 -0
  32. package/src/plugins/plugins/nextjs.ts +19 -0
  33. package/src/plugins/plugins/vite.ts +14 -0
  34. package/src/plugins/plugins/vitest.ts +14 -0
  35. package/src/runtime/async-runner.ts +35 -7
  36. package/src/runtime/background-runner.ts +529 -144
  37. package/src/runtime/chain-parser.ts +5 -1
  38. package/src/runtime/chain-runner.ts +9 -3
  39. package/src/runtime/checkpoint.ts +262 -180
  40. package/src/runtime/child-pi.ts +164 -37
  41. package/src/runtime/crash-recovery.ts +25 -14
  42. package/src/runtime/crew-agent-records.ts +2 -0
  43. package/src/runtime/diagnostic-export.ts +1 -1
  44. package/src/runtime/dynamic-script-runner.ts +10 -7
  45. package/src/runtime/foreground-watchdog.ts +1 -1
  46. package/src/runtime/heartbeat-watcher.ts +19 -2
  47. package/src/runtime/intercom-bridge.ts +7 -0
  48. package/src/runtime/iteration-hooks.ts +1 -1
  49. package/src/runtime/manifest-cache.ts +4 -0
  50. package/src/runtime/orphan-worker-registry.ts +444 -0
  51. package/src/runtime/parent-guard.ts +70 -16
  52. package/src/runtime/pi-args.ts +437 -14
  53. package/src/runtime/pi-spawn.ts +1 -0
  54. package/src/runtime/post-checks.ts +1 -1
  55. package/src/runtime/retry-runner.ts +9 -3
  56. package/src/runtime/run-tracker.ts +38 -10
  57. package/src/runtime/sandbox.ts +17 -2
  58. package/src/runtime/scheduler.ts +25 -2
  59. package/src/runtime/skill-effectiveness.ts +105 -62
  60. package/src/runtime/skill-instructions.ts +110 -32
  61. package/src/runtime/stale-reconciler.ts +310 -69
  62. package/src/runtime/subagent-manager.ts +251 -57
  63. package/src/runtime/task-health.ts +76 -0
  64. package/src/runtime/task-id.ts +20 -0
  65. package/src/runtime/task-runner/live-executor.ts +1 -1
  66. package/src/runtime/task-runner/progress.ts +1 -1
  67. package/src/runtime/task-runner/state-helpers.ts +110 -6
  68. package/src/runtime/task-runner.ts +92 -70
  69. package/src/runtime/team-runner.ts +186 -20
  70. package/src/schema/team-tool-schema.ts +27 -9
  71. package/src/skills/discover-skills.ts +9 -3
  72. package/src/state/active-run-registry.ts +170 -38
  73. package/src/state/artifact-store.ts +25 -13
  74. package/src/state/atomic-write-v2.ts +86 -0
  75. package/src/state/atomic-write.ts +346 -55
  76. package/src/state/blob-store.ts +178 -10
  77. package/src/state/crew-init.ts +161 -28
  78. package/src/state/decision-ledger.ts +172 -111
  79. package/src/state/event-log-rotation.ts +82 -52
  80. package/src/state/event-log.ts +254 -70
  81. package/src/state/health-store.ts +71 -0
  82. package/src/state/locks.ts +102 -20
  83. package/src/state/mailbox.ts +45 -7
  84. package/src/state/observation-store.ts +4 -1
  85. package/src/state/run-graph.ts +141 -130
  86. package/src/state/run-metrics.ts +24 -8
  87. package/src/state/state-store.ts +330 -43
  88. package/src/ui/live-run-sidebar.ts +1 -1
  89. package/src/ui/loaders.ts +4 -0
  90. package/src/ui/overlays/agent-picker-overlay.ts +1 -1
  91. package/src/ui/overlays/mailbox-detail-overlay.ts +1 -1
  92. package/src/ui/run-action-dispatcher.ts +2 -2
  93. package/src/ui/run-snapshot-cache.ts +1 -1
  94. package/src/utils/env-filter.ts +66 -0
  95. package/src/utils/file-coalescer.ts +9 -1
  96. package/src/utils/paths.ts +80 -5
  97. package/src/utils/redaction.ts +6 -1
  98. package/src/utils/safe-paths.ts +281 -10
  99. package/src/worktree/cleanup.ts +112 -24
  100. package/src/worktree/worktree-manager.ts +128 -15
  101. package/test-bugs-all.mjs +10 -6
  102. package/test-integration-check.ts +4 -0
@@ -0,0 +1,444 @@
1
+ /**
2
+ * Orphan background-worker registry.
3
+ *
4
+ * Tracks PIDs of background-runner.ts processes spawned via async-runner.
5
+ * Workers are detached, setsid'd, and unref'd, so they outlive the spawning
6
+ * pi session. If the parent pi process is killed (SIGKILL, crash), workers
7
+ * become orphans and keep running forever.
8
+ *
9
+ * This registry provides:
10
+ * 1. `registerWorker` — called from async-runner.ts after successful spawn.
11
+ * 2. `unregisterWorker` — called when a worker exits (via async-marker
12
+ * or heartbeat watcher).
13
+ * 3. `cleanupOrphanWorkers` — called on session_start; kills workers whose
14
+ * registration is older than STALE_REGISTRATION_MS (default 1h) and
15
+ * removes dead PIDs from the registry.
16
+ *
17
+ * Persistence: file-based JSON in `<userPiRoot>/state/orphan-workers.json`.
18
+ * File is rewritten on every operation to drop dead PIDs.
19
+ *
20
+ * Thread-safety: All mutating operations (registerWorker, unregisterWorker,
21
+ * cleanupOrphanWorkers) are protected by file locking to prevent concurrent
22
+ * writes from causing lost updates.
23
+ */
24
+ import * as fs from "node:fs";
25
+ import * as path from "node:path";
26
+ import { execSync } from "node:child_process";
27
+ import { userPiRoot } from "../utils/paths.ts";
28
+ import { logInternalError } from "../utils/internal-error.ts";
29
+ import { withFileLockSync } from "../state/locks.ts";
30
+ import { isSymlinkSafePath } from "../state/atomic-write.ts";
31
+
32
+ const STALE_REGISTRATION_MS = 60 * 60 * 1000; // 1 hour
33
+ // Grace period before a fresh worker can be cleaned up when parent is dead.
34
+ // Workers registered more recently than this are kept (monitored) even if
35
+ // parent is dead, to avoid killing a legitimate worker from a session that
36
+ // died recently. Only stale workers (> GRACE_PERIOD_MS) are SIGKILLed.
37
+ const GRACE_PERIOD_MS = 5 * 60 * 1000; // 5 minutes
38
+
39
+ export interface OrphanWorkerEntry {
40
+ pid: number;
41
+ sessionId: string;
42
+ runId: string;
43
+ /** Parent PID (the pi process that spawned this worker). Used to verify
44
+ * the owning session is actually dead before killing the worker. */
45
+ parentPid: number;
46
+ /** Parent process start time in milliseconds since boot (from /proc/<pid>/stat).
47
+ * Used to detect PID reuse of the parent process. If the OS recycles the
48
+ * parent PID for a new process, the start time will differ and we won't
49
+ * incorrectly believe the parent is still alive. */
50
+ parentPidStartTime: number;
51
+ registeredAt: number; // epoch ms
52
+ /** Process start time in milliseconds since boot (from /proc/<pid>/stat).
53
+ * Used to detect PID reuse: if the OS recycles this PID for a new process,
54
+ * the start time will differ and we won't kill the wrong process. */
55
+ startTime: number;
56
+ }
57
+
58
+ /**
59
+ * Get process start time in milliseconds since boot.
60
+ * Uses platform-specific APIs for cross-platform PID reuse detection:
61
+ * - Linux: reads /proc/<pid>/stat (field 22, starttime)
62
+ * - macOS: sysctl KERN_PROC_PID to get kinfo_proc and extract p_starttime
63
+ * - Windows: GetProcessTimes API to get creation time
64
+ *
65
+ * Returns undefined if the process is gone or the platform API is unavailable.
66
+ */
67
+ function getProcessStartTime(pid: number): number | undefined {
68
+ try {
69
+ // First check if process exists
70
+ process.kill(pid, 0);
71
+ } catch {
72
+ return undefined;
73
+ }
74
+
75
+ const platform = process.platform;
76
+ if (platform === "linux") {
77
+ return getProcessStartTimeLinux(pid);
78
+ } else if (platform === "darwin") {
79
+ return getProcessStartTimeMacOS(pid);
80
+ } else if (platform === "win32") {
81
+ return getProcessStartTimeWindows(pid);
82
+ }
83
+ return undefined;
84
+ }
85
+
86
+ function getProcessStartTimeLinux(pid: number): number | undefined {
87
+ try {
88
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8");
89
+ // comm is wrapped in parentheses and may contain spaces/special chars.
90
+ // Find the last ')' which marks the end of comm.
91
+ const lastParen = stat.lastIndexOf(")");
92
+ if (lastParen === -1) return undefined;
93
+ // Fields after comm: state(1) ppid(2) pgrp(3) session(4) tty_nr(5)
94
+ // tpgid(6) flags(7) minflt(8) cminflt(9) majflt(10) cmajflt(11)
95
+ // utime(12) stime(13) cutime(14) cstime(15) priority(16) nice(17)
96
+ // num_threads(18) itrealvalue(19) starttime(20) vsize(21) rss(22)
97
+ // ...but we only need starttime which is field 22 (index 21 after comm)
98
+ const fieldsAfterComm = stat.slice(lastParen + 1).trim().split(/\s+/);
99
+ // starttime is at index 19 (the 20th field after comm)
100
+ const startTimeClockTicks = Number(fieldsAfterComm[19]);
101
+ if (!Number.isFinite(startTimeClockTicks)) return undefined;
102
+ // Convert clock ticks to milliseconds using CLK_TCK (usually 100)
103
+ // We use a conservative estimate; the absolute value matters less
104
+ // than the uniqueness per PID lifecycle.
105
+ return Math.floor(startTimeClockTicks * 100);
106
+ } catch {
107
+ return undefined;
108
+ }
109
+ }
110
+
111
+ function getProcessStartTimeMacOS(pid: number): number | undefined {
112
+ // Use sysctl to get process start time on macOS
113
+ // KERN_PROC_PID returns a kinfo_proc structure with p_starttime
114
+ try {
115
+ // Use ps to get process start time - format: Mon Day Time or Mon Day Year
116
+ // For cross-platform consistency, we use 'lstart' which gives full timestamp
117
+ const output = execSync(`ps -p ${pid} -o lstart=`, { encoding: "utf-8", timeout: 5000 }).trim();
118
+ if (!output) return undefined;
119
+ // Parse date string like "Mon Jan 15 10:30:45 2024"
120
+ const date = new Date(output);
121
+ if (Number.isNaN(date.getTime())) return undefined;
122
+ return date.getTime();
123
+ } catch {
124
+ return undefined;
125
+ }
126
+ }
127
+
128
+ function getProcessStartTimeWindows(pid: number): number | undefined {
129
+ // Use Windows API via JSDrive's winattr or native code
130
+ // For Node.js without native modules, use tasklist /v and parse output
131
+ try {
132
+ // /v verbose, /fo csv, /nh no header
133
+ const output = execSync(
134
+ `powershell -Command "Get-Process -Id ${pid} | Select-Object -ExpandProperty StartTime"`,
135
+ { encoding: "utf-8", timeout: 5000 },
136
+ ).trim();
137
+ if (!output) return undefined;
138
+ const date = new Date(output);
139
+ if (Number.isNaN(date.getTime())) return undefined;
140
+ return date.getTime();
141
+ } catch {
142
+ return undefined;
143
+ }
144
+ }
145
+
146
+
147
+ let REGISTRY_PATH = path.join(userPiRoot(), "state", "orphan-workers.json");
148
+
149
+ /** @internal Test-only: override the registry path. */
150
+ export function __test_setRegistryPath(p: string): void {
151
+ REGISTRY_PATH = p;
152
+ }
153
+
154
+ function getRegistryPath(): string {
155
+ return REGISTRY_PATH;
156
+ }
157
+
158
+ /** Issue 3 fix: Validate sessionId and runId to prevent path traversal attacks. */
159
+ function isValidId(id: string): boolean {
160
+ if (!id || typeof id !== "string") return false;
161
+ if (id.includes("..") || id.includes("/") || id.includes("\\") || id.includes("\0")) return false;
162
+ return true;
163
+ }
164
+
165
+ function readRegistry(): OrphanWorkerEntry[] {
166
+ const p = getRegistryPath();
167
+ try {
168
+ // Atomic read: if file doesn't exist, readFileSync throws ENOENT
169
+ // which we handle explicitly. This eliminates the TOCTOU window
170
+ // between existsSync and readFileSync.
171
+ const raw = fs.readFileSync(p, "utf-8");
172
+ const parsed = JSON.parse(raw);
173
+ if (!Array.isArray(parsed)) return [];
174
+ return parsed.filter(
175
+ (e): e is OrphanWorkerEntry =>
176
+ typeof e === "object" &&
177
+ e !== null &&
178
+ typeof e.pid === "number" &&
179
+ typeof e.sessionId === "string" &&
180
+ typeof e.runId === "string" &&
181
+ typeof e.registeredAt === "number" &&
182
+ typeof (e as OrphanWorkerEntry).parentPid === "number" &&
183
+ typeof (e as OrphanWorkerEntry).parentPidStartTime === "number" &&
184
+ typeof (e as OrphanWorkerEntry).startTime === "number",
185
+ );
186
+ } catch (error) {
187
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
188
+ return [];
189
+ }
190
+ // Silent failure is deliberate for robustness (registry read failures
191
+ // shouldn't crash the process), but log at warning level to aid troubleshooting.
192
+ console.warn(`[orphan-worker-registry] readRegistry failed: ${error}`);
193
+ return [];
194
+ }
195
+ }
196
+
197
+ function writeRegistry(entries: OrphanWorkerEntry[]): void {
198
+ const p = getRegistryPath();
199
+ const dir = path.dirname(p);
200
+ // Issue 2 fix: Defense-in-depth validation of IDs inside writeRegistry.
201
+ // Even if registerWorker is bypassed in the future, we still validate
202
+ // that sessionId/runId don't contain path traversal characters before
203
+ // writing to disk.
204
+ for (const entry of entries) {
205
+ if (!isValidId(entry.sessionId) || !isValidId(entry.runId)) {
206
+ logInternalError("orphan-worker-registry.write", new Error("Refusing to write: invalid sessionId or runId"), `sessionId=${entry.sessionId} runId=${entry.runId}`);
207
+ return;
208
+ }
209
+ }
210
+ // NOTE: No withFileLockSync here — all callers (registerWorker, unregisterWorker,
211
+ // cleanupOrphanWorkers) already hold the lock. Nesting withFileLockSync on the same
212
+ // path causes self-deadlock (the lock file is not reentrant).
213
+ // Guard against symlink attacks on the registry file.
214
+ // isSymlinkSafePath walks the ancestor chain to detect any symlinks,
215
+ // preventing attacks where an intermediate ancestor is a symlink.
216
+ if (!isSymlinkSafePath(p)) {
217
+ logInternalError("orphan-worker-registry.write", new Error("Refusing to write: target is a symlink or inside untrusted directory"), `path=${p}`);
218
+ return;
219
+ }
220
+ // Issue 2 fix: Check parent directory safety immediately before creating it.
221
+ if (!isSymlinkSafePath(dir)) {
222
+ logInternalError("orphan-worker-registry.write", new Error("Refusing to create: parent directory is a symlink or inside untrusted directory"), `dir=${dir}`);
223
+ return;
224
+ }
225
+ // Ensure parent directory exists to serialize directory
226
+ // creation with registry file writes and prevent TOCTOU races.
227
+ if (!fs.existsSync(dir)) {
228
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
229
+ }
230
+ try {
231
+ fs.writeFileSync(p, JSON.stringify(entries, null, 2), { mode: 0o600 });
232
+ } catch (error) {
233
+ logInternalError(
234
+ "orphan-worker-registry.write",
235
+ error,
236
+ `path=${p} entries=${entries.length}`,
237
+ );
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Add a worker PID to the registry. Idempotent (replaces existing entry
243
+ * for the same PID).
244
+ *
245
+ * @param parentPid The PID of the spawning pi process. Used later to
246
+ * verify the owning session is actually dead before killing the worker.
247
+ */
248
+ export function registerWorker(
249
+ pid: number,
250
+ sessionId: string,
251
+ runId: string,
252
+ parentPid: number,
253
+ options?: { registeredAt?: number },
254
+ ): void {
255
+ if (!Number.isFinite(pid) || pid <= 0) return;
256
+ // Issue 3 fix: Validate sessionId and runId to prevent path traversal attacks.
257
+ if (!isValidId(sessionId) || !isValidId(runId)) return;
258
+ const startTime = getProcessStartTime(pid) ?? 0;
259
+ const parentPidStartTime = Number.isFinite(parentPid) && parentPid > 0
260
+ ? (getProcessStartTime(parentPid) ?? 0)
261
+ : 0;
262
+ withFileLockSync(getRegistryPath(), () => {
263
+ const entries = readRegistry();
264
+ // Dedupe by PID
265
+ const filtered = entries.filter((e) => e.pid !== pid);
266
+ filtered.push({
267
+ pid,
268
+ sessionId,
269
+ runId,
270
+ parentPid: Number.isFinite(parentPid) ? parentPid : 0,
271
+ parentPidStartTime,
272
+ registeredAt: options?.registeredAt ?? Date.now(),
273
+ startTime,
274
+ });
275
+ writeRegistry(filtered);
276
+ });
277
+ }
278
+
279
+ /**
280
+ * Remove a worker PID from the registry. Called when the worker is known
281
+ * to have exited (e.g. via async-marker poll or heartbeat watcher).
282
+ */
283
+ export function unregisterWorker(pid: number): void {
284
+ if (!Number.isFinite(pid) || pid <= 0) return;
285
+ withFileLockSync(getRegistryPath(), () => {
286
+ const entries = readRegistry();
287
+ const filtered = entries.filter((e) => e.pid !== pid);
288
+ if (filtered.length !== entries.length) {
289
+ writeRegistry(filtered);
290
+ }
291
+ });
292
+ }
293
+
294
+ export interface CleanupOrphanWorkersResult {
295
+ scanned: number;
296
+ killed: number;
297
+ pruned: number; // dead PIDs removed from registry without killing
298
+ kept: number; // alive and fresh
299
+ }
300
+
301
+ /**
302
+ * Kill stale orphan background workers and prune dead PIDs from the registry.
303
+ *
304
+ * Strategy:
305
+ * - For each entry in the registry, check if the PID is still alive.
306
+ * - If alive AND registered > STALE_REGISTRATION_MS ago: SIGTERM the PID
307
+ * (it's an orphan from a long-dead session).
308
+ * - If alive AND fresh: keep (concurrent session).
309
+ * - If dead: prune from registry.
310
+ *
311
+ * @param currentSessionId If provided, workers from this session are
312
+ * ALWAYS kept regardless of age. This protects concurrent sessions.
313
+ * Pass undefined for unconditional cleanup (e.g. from `pi-crew cleanup`).
314
+ */
315
+ export function cleanupOrphanWorkers(
316
+ currentSessionId?: string,
317
+ ): CleanupOrphanWorkersResult {
318
+ let result: CleanupOrphanWorkersResult = { scanned: 0, killed: 0, pruned: 0, kept: 0 };
319
+ withFileLockSync(getRegistryPath(), () => {
320
+ const entries = readRegistry();
321
+ const now = Date.now();
322
+ const kept: OrphanWorkerEntry[] = [];
323
+ let killed = 0;
324
+ let pruned = 0;
325
+ for (const entry of entries) {
326
+ try {
327
+ process.kill(entry.pid, 0);
328
+ // PID is alive
329
+ const isMine = currentSessionId && entry.sessionId === currentSessionId;
330
+ if (isMine) {
331
+ // My session's worker — keep regardless of age
332
+ kept.push(entry);
333
+ continue;
334
+ }
335
+ // Verify parent is actually dead before killing worker.
336
+ // If parent is alive, this is a concurrent session's worker
337
+ // (or the same session that was misidentified). Keep it.
338
+ if (entry.parentPid > 0) {
339
+ // Verify parent hasn't been recycled before checking liveness.
340
+ // If the parent PID was reused by a different process, the start
341
+ // time will differ and we shouldn't trust the parentPid liveness check.
342
+ const currentParentStartTime = getProcessStartTime(entry.parentPid);
343
+ if (
344
+ currentParentStartTime !== undefined &&
345
+ entry.parentPidStartTime !== 0 &&
346
+ currentParentStartTime !== entry.parentPidStartTime
347
+ ) {
348
+ // Parent PID was recycled — this is a different process,
349
+ // treat as if parent is dead so we may clean up the worker.
350
+ } else {
351
+ try {
352
+ process.kill(entry.parentPid, 0);
353
+ // Parent is alive — concurrent session, keep worker
354
+ kept.push(entry);
355
+ continue;
356
+ } catch (err) {
357
+ // Parent is dead — proceed to verify it's actually our worker
358
+ // However, EPERM means the process exists but we lack permission
359
+ // to signal it. Treat as 'unknown' state and keep the entry.
360
+ if ((err as NodeJS.ErrnoException).code === "EPERM") {
361
+ kept.push(entry);
362
+ continue;
363
+ }
364
+ }
365
+ }
366
+ }
367
+ // Verify PID hasn't been recycled by checking start time matches.
368
+ // Capture startTime for re-verification before kill to close TOCTOU window.
369
+ // Between the kill(0) check and the actual SIGKILL below, the OS
370
+ // may have reused this PID for a new process. If the start time
371
+ // has changed, this is a different process and we must not kill it.
372
+ const currentStartTime = getProcessStartTime(entry.pid);
373
+ if (currentStartTime === undefined || entry.startTime === 0) {
374
+ // Can't verify startTime (macOS/Windows or stale entry) — trust registry
375
+ } else if (currentStartTime !== entry.startTime) {
376
+ // PID was recycled — different process now, prune without killing
377
+ pruned++;
378
+ continue;
379
+ }
380
+ // Re-verify start time immediately before SIGKILL to close the
381
+ // TOCTOU window.
382
+ //
383
+ // KNOWN RESIDUAL RACE: Even with this re-check, a microsecond-level
384
+ // window exists between the currentStartTime read (line 366) and the
385
+ // actual process.kill(entry.pid, "SIGKILL") call (line 400). The OS
386
+ // could theoretically recycle the PID and allocate it to a new process
387
+ // within that window. This is an inherent limitation of userspace PID
388
+ // verification against kernel PID allocation — the race cannot be fully
389
+ // eliminated without kernel-level process naming or a process descriptor
390
+ // that we do not have. As alternative mitigations, consider using
391
+ // process groups (killpg) for worker identification instead of raw PIDs,
392
+ // or kernel-level process descriptors if available on the platform.
393
+ // The consequence of killing a wrong process is severe (SIGKILL of an
394
+ // unrelated process), so this re-check is the best possible mitigation
395
+ // given the kernel's PID allocation semantics.
396
+ if (currentStartTime !== undefined && entry.startTime !== 0 && currentStartTime !== entry.startTime) {
397
+ // PID was recycled — different process now, prune without killing
398
+ pruned++;
399
+ continue;
400
+ }
401
+ if (now - entry.registeredAt > STALE_REGISTRATION_MS) {
402
+ // Stale orphan — SIGKILL because background-runner
403
+ // intentionally ignores SIGTERM (BUG #17 fix).
404
+ try {
405
+ process.kill(entry.pid, "SIGKILL");
406
+ killed++;
407
+ } catch {
408
+ // Race: died between check and kill
409
+ pruned++;
410
+ }
411
+ } else if (now - entry.registeredAt > GRACE_PERIOD_MS) {
412
+ // Fresh but outside grace period — parent dead and worker
413
+ // is not doing useful work (same session died > 5 min ago).
414
+ // SIGKILL to avoid wasting resources.
415
+ try {
416
+ process.kill(entry.pid, "SIGKILL");
417
+ killed++;
418
+ } catch {
419
+ pruned++;
420
+ }
421
+ } else {
422
+ // Fresh and within grace period — keep worker even though
423
+ // parent is dead. Could be a legitimate worker from a session
424
+ // that died recently and may still be doing useful work.
425
+ // Will be cleaned up on next cycle if still orphan.
426
+ kept.push(entry);
427
+ }
428
+ } catch {
429
+ // PID is dead — prune from registry
430
+ pruned++;
431
+ }
432
+ }
433
+ if (kept.length !== entries.length) {
434
+ writeRegistry(kept);
435
+ }
436
+ result = {
437
+ scanned: entries.length,
438
+ killed,
439
+ pruned,
440
+ kept: kept.length,
441
+ };
442
+ });
443
+ return result;
444
+ }
@@ -15,11 +15,48 @@
15
15
  * const parentPid = Number(process.env.PI_CREW_PARENT_PID);
16
16
  * if (parentPid > 0) startParentGuard(parentPid);
17
17
  * ```
18
+ *
19
+ * ## Trust model
20
+ *
21
+ * `PI_CREW_PARENT_PID` is propagated from the spawning team-runner to each
22
+ * child via the explicit env allow-list in `child-pi.ts`. The PID itself is
23
+ * NOT a secret — process identifiers are public knowledge on Unix-like
24
+ * systems (visible in `ps`, `/proc`, etc.) and carry no privilege.
25
+ *
26
+ * Residual risk: a malicious or compromised child can spoof
27
+ * `process.env.PI_CREW_PARENT_PID` before invoking `startParentGuard()`.
28
+ * This is acceptable because the parent-guard is a self-termination
29
+ * signal, NOT a security boundary:
30
+ * - It only causes the (already-compromised) child to exit earlier.
31
+ * - A truly malicious child can simply not call `startParentGuard()`.
32
+ * - Real protection against hostile children comes from the sandbox,
33
+ * env-filter allowlist, and redaction — all enforced before spawn.
34
+ *
35
+ * The guard exists for the benign case: a parent dies (user closes the
36
+ * terminal, pi crashes, machine loses power) and we want all detached
37
+ * workers to stop wasting CPU. It is NOT an anti-tampering mechanism.
18
38
  */
19
39
 
20
- const POLL_INTERVAL_MS = 3_000;
40
+ /**
41
+ * Poll interval for parent liveness checks (in milliseconds).
42
+ * Default: 500ms. A parent killed by SIGKILL is detected within one poll
43
+ * interval (max 500ms latency).
44
+ *
45
+ * For latency-sensitive workloads (e.g., preventing orphaned workers from
46
+ * running with a dead supervisor), you can tune this lower by setting the
47
+ * PI_CREW_PARENT_GUARD_INTERVAL_MS environment variable.
48
+ *
49
+ * WARNING: Values below 100ms significantly increase overhead for large
50
+ * numbers of parallel workers, since each poll issues a process.kill(pid, 0)
51
+ * syscall per worker. Only tune this if immediate detection is critical.
52
+ *
53
+ * FUTURE: An event-based SIGCHLD handler could supplement or replace this
54
+ * polling approach for near-instantaneous parent-death detection on Unix
55
+ * systems, avoiding the polling overhead entirely.
56
+ */
57
+ const POLL_INTERVAL_MS = Number(process.env.PI_CREW_PARENT_GUARD_INTERVAL_MS) || 500;
21
58
 
22
- let guardInterval: ReturnType<typeof setInterval> | undefined;
59
+ const guardIntervals = new Map<number, ReturnType<typeof setInterval>>();
23
60
 
24
61
  function isPidAlive(pid: number): boolean {
25
62
  try {
@@ -46,26 +83,43 @@ function selfTerminate(parentPid: number): never {
46
83
  * Start a lightweight poll that checks if the parent process is still alive.
47
84
  * If the parent dies, this worker exits immediately with code 124.
48
85
  *
49
- * The interval is `unref()`'d so it doesn't keep the event loop alive
50
- * on its own but if the worker has other work (LLM calls, tool execution),
51
- * the check continues running in the background.
86
+ * FIX: Removed unref() the guard interval MUST keep the event loop alive
87
+ * to prevent premature worker exit when the parent is still alive but the
88
+ * worker has no other pending work (LLM calls, timers, I/O). Without this,
89
+ * a worker in pure CPU wait could exit even though its parent is alive.
52
90
  */
53
91
  export function startParentGuard(parentPid: number): void {
54
92
  if (!parentPid || !Number.isFinite(parentPid) || parentPid <= 0) return;
55
93
 
56
- // Immediate check if parent is already dead, don't even start
57
- if (!isPidAlive(parentPid)) {
58
- selfTerminate(parentPid);
59
- }
94
+ // Clear any existing guard for this specific parentPid before setting a new one
95
+ const existing = guardIntervals.get(parentPid);
96
+ if (existing) clearInterval(existing);
97
+
98
+ // Add ±20% jitter to prevent synchronized polling across workers that
99
+ // start simultaneously (e.g., after pi restart). Without jitter, all
100
+ // workers would poll at exactly the same interval, creating load spikes.
101
+ const jitter = POLL_INTERVAL_MS * 0.2 * (Math.random() - 0.5) * 2;
102
+ const actualInterval = POLL_INTERVAL_MS + jitter;
60
103
 
61
- guardInterval = setInterval(() => {
104
+ const interval = setInterval(() => {
105
+ // Immediate check on every tick — detects parent death within one poll
106
+ // interval (max POLL_INTERVAL_MS latency, default 500ms).
62
107
  if (!isPidAlive(parentPid)) {
63
- if (guardInterval) clearInterval(guardInterval);
108
+ const guard = guardIntervals.get(parentPid);
109
+ if (guard) clearInterval(guard);
110
+ guardIntervals.delete(parentPid);
64
111
  selfTerminate(parentPid);
65
112
  }
66
- }, POLL_INTERVAL_MS);
113
+ }, actualInterval);
114
+
115
+ guardIntervals.set(parentPid, interval);
67
116
 
68
- guardInterval.unref();
117
+ // NOTE: Intentionally NOT calling guardInterval.unref() here.
118
+ // The watchdog timer must keep the event loop alive to ensure the worker
119
+ // doesn't exit while the parent is alive. If other work (child processes,
120
+ // timers, I/O) keeps the loop alive, that's fine — the guard runs as a
121
+ // side effect. If no other work exists, the guard is the only thing
122
+ // keeping the process alive, and that's by design.
69
123
  }
70
124
 
71
125
  /**
@@ -73,8 +127,8 @@ export function startParentGuard(parentPid: number): void {
73
127
  * and doesn't need to watch the parent anymore.
74
128
  */
75
129
  export function stopParentGuard(): void {
76
- if (guardInterval) {
77
- clearInterval(guardInterval);
78
- guardInterval = undefined;
130
+ for (const interval of guardIntervals.values()) {
131
+ clearInterval(interval);
79
132
  }
133
+ guardIntervals.clear();
80
134
  }