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
@@ -4,12 +4,29 @@ import * as path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import type { AgentConfig } from "../agents/agent-config.ts";
6
6
  import { getAgentSessionOptions } from "../agents/agent-config.ts";
7
+ import { userPiRoot } from "../utils/paths.ts";
7
8
 
8
9
  const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
9
10
  const PROMPT_RUNTIME_EXTENSION_PATH = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "prompt", "prompt-runtime.ts");
10
11
  const TASK_ARG_LIMIT = 8000;
11
12
  const DEFAULT_MAX_CREW_DEPTH = 2;
12
13
 
14
+ // Track every temp dir created in this process so we can clean them up
15
+ // even if the parent is killed before child-pi.ts cleanup runs.
16
+ // Prevents accumulation of /tmp/pi-crew-* dirs from crashed/killed tests.
17
+ const createdTempDirs = new Set<string>();
18
+
19
+ /**
20
+ * Resolve the temp-dir base path.
21
+ * Uses pi-crew's own user-root (`~/.pi/agent/pi-crew/tmp/`) so the temp
22
+ * files live alongside other pi-crew state and never pollute the shared
23
+ * /tmp directory. Uses `userPiRoot()` so the path stays consistent with
24
+ * the rest of pi-crew (respects PI_TEAMS_HOME / PI_CODING_AGENT_DIR).
25
+ */
26
+ function getPiTempBase(): string {
27
+ return path.join(userPiRoot(), "tmp");
28
+ }
29
+
13
30
  export interface BuildPiWorkerArgsInput {
14
31
  task: string;
15
32
  agent: AgentConfig;
@@ -51,7 +68,15 @@ export function resolveCrewMaxDepth(inputMaxDepth?: number, env: NodeJS.ProcessE
51
68
  const raw = env.PI_CREW_MAX_DEPTH ?? env.PI_TEAMS_MAX_DEPTH;
52
69
  const envDepth = raw !== undefined ? Number(raw) : NaN;
53
70
  if (Number.isInteger(envDepth) && envDepth >= 1 && envDepth <= 10) return envDepth;
71
+ if (Number.isInteger(envDepth) && envDepth > 10) {
72
+ console.warn(`PI_CREW_MAX_DEPTH=${envDepth} exceeds cap of 10, clamping to 10. Set 10 or lower to avoid this warning.`);
73
+ return 10;
74
+ }
54
75
  if (Number.isInteger(inputMaxDepth) && inputMaxDepth !== undefined && inputMaxDepth >= 1 && inputMaxDepth <= 10) return inputMaxDepth;
76
+ if (Number.isInteger(inputMaxDepth) && inputMaxDepth !== undefined && inputMaxDepth > 10) {
77
+ console.warn(`maxDepth=${inputMaxDepth} exceeds cap of 10, clamping to 10. Set 10 or lower to avoid this warning.`);
78
+ return 10;
79
+ }
55
80
  return DEFAULT_MAX_CREW_DEPTH;
56
81
  }
57
82
 
@@ -67,13 +92,139 @@ export function checkCrewDepth(inputMaxDepth?: number, env: NodeJS.ProcessEnv =
67
92
  * 2. lstatSync to verify it is not a symlink (TOCTOU safety)
68
93
  * 3. realpathSync to resolve the canonical path
69
94
  */
70
- function createSafeTempDir(base: string, prefix: string): string {
95
+ /**
96
+ * Create a temp dir with symlink-safety checks. Tracked in the
97
+ * `createdTempDirs` Set for global cleanup.
98
+ *
99
+ * Exported (rather than module-private) so unit tests can populate
100
+ * the tracking Set without going through the public build flow.
101
+ */
102
+ export function createSafeTempDir(base: string, prefix: string): string {
103
+ // FIX: Walk FULL ancestor chain for symlinks BEFORE creating any directories.
104
+ // An attacker could plant a symlink at any ancestor of base (e.g.,
105
+ // making /home/bom/.pi -> /tmp/attacker). Walk from root to base
106
+ // and verify no component is a symlink. Only THEN create base if needed.
107
+ const absoluteBase = path.resolve(base);
108
+ const parts = absoluteBase.split(path.sep);
109
+ let accumulated = "";
110
+ if (parts[0] === "") accumulated = "/"; // Unix root
111
+ for (let i = 1; i < parts.length; i++) {
112
+ if (parts[i] === "") continue;
113
+ accumulated = path.join(accumulated, parts[i]);
114
+ try {
115
+ const stat = fs.lstatSync(accumulated);
116
+ if (stat.isSymbolicLink()) {
117
+ // On macOS, /var → /private/var, /tmp → /private/tmp, /etc → /private/etc
118
+ // are system symlinks managed by the OS. Allow them.
119
+ const knownDarwinSymlinks = ["/var", "/tmp", "/etc", "/private/var", "/private/tmp", "/private/etc"];
120
+ if (process.platform === "darwin" && knownDarwinSymlinks.includes(accumulated)) continue;
121
+ throw new Error("Refusing to create temp dir: ancestor is a symlink: " + accumulated);
122
+ }
123
+ } catch (e) {
124
+ if (e instanceof Error && e.message.includes("symlink")) throw e;
125
+ // Component doesn't exist yet — OK, proceed
126
+ break;
127
+ }
128
+ }
129
+ // Verify base dir itself is not a symlink before realpathSync.
130
+ // Issue #1 fix: if baseDir itself is a symlink, realpathSync would
131
+ // resolve to an attacker-controlled location.
132
+ try {
133
+ const baseStat = fs.lstatSync(base);
134
+ if (baseStat.isSymbolicLink()) throw new Error("Refusing to create temp dir in symlinked base: " + base);
135
+ } catch (e) {
136
+ if (e instanceof Error && e.message.includes("symlink")) throw e;
137
+ // ENOENT: base doesn't exist yet — will be created below.
138
+ }
139
+ // Create base dir only AFTER all ancestor symlink checks pass.
71
140
  if (!fs.existsSync(base)) fs.mkdirSync(base, { recursive: true });
72
- // Verify base dir is not a symlink (TOCTOU safety)
73
- const baseStat = fs.lstatSync(base);
74
- if (baseStat.isSymbolicLink()) throw new Error("Refusing to create temp dir in symlinked base: " + base);
75
- // Resolve base to canonical path before joining
76
- const resolvedBase = fs.realpathSync(base);
141
+ // Issue #1 fix: re-validate the FULL ancestor chain immediately after
142
+ // mkdirSync to close the TOCTOU window between initial validation
143
+ // (lines 111-122) and directory creation. An attacker could have
144
+ // deleted a validated ancestor and recreated it as a symlink in that
145
+ // window.
146
+ for (let i = 1; i < parts.length; i++) {
147
+ if (parts[i] === "") continue;
148
+ accumulated = path.join(accumulated, parts[i]);
149
+ try {
150
+ const stat = fs.lstatSync(accumulated);
151
+ if (stat.isSymbolicLink()) {
152
+ const knownDarwinSymlinks = ["/var", "/tmp", "/etc", "/private/var", "/private/tmp", "/private/etc"];
153
+ if (process.platform === "darwin" && knownDarwinSymlinks.includes(accumulated)) continue;
154
+ throw new Error("Refusing to create temp dir: ancestor is a symlink (post-mkdir): " + accumulated);
155
+ }
156
+ } catch (e) {
157
+ if (e instanceof Error && e.message.includes("symlink")) throw e;
158
+ // Component doesn't exist — OK
159
+ break;
160
+ }
161
+ }
162
+ // Resolve base to canonical path before joining.
163
+ // Issue #1 fix: if the base dir is deleted between the post-mkdir
164
+ // validation loop (lines 135-146) and realpathSync, realpathSync throws
165
+ // ENOENT. Re-validate and retry to handle fast delete+recreate races.
166
+ let resolvedBase: string;
167
+ let retries = 3;
168
+ while (true) {
169
+ try {
170
+ resolvedBase = fs.realpathSync(base);
171
+ break;
172
+ } catch (e: unknown) {
173
+ if (--retries <= 0) throw e;
174
+ // ENOENT: re-validate ancestor chain and retry
175
+ const code = e instanceof Object && "code" in e ? (e as { code: string }).code : undefined;
176
+ if (code !== "ENOENT") throw e;
177
+ }
178
+ // Re-validate ancestor chain post-mkdir (same logic as lines 135-146)
179
+ const revalidateParts = absoluteBase.split(path.sep);
180
+ let revalidateAccumulated = "";
181
+ if (revalidateParts[0] === "") revalidateAccumulated = "/";
182
+ for (let i = 1; i < revalidateParts.length; i++) {
183
+ if (revalidateParts[i] === "") continue;
184
+ revalidateAccumulated = path.join(revalidateAccumulated, revalidateParts[i]);
185
+ try {
186
+ const stat = fs.lstatSync(revalidateAccumulated);
187
+ if (stat.isSymbolicLink()) {
188
+ const knownDarwinSymlinks = ["/var", "/tmp", "/etc", "/private/var", "/private/tmp", "/private/etc"];
189
+ if (process.platform === "darwin" && knownDarwinSymlinks.includes(revalidateAccumulated)) continue;
190
+ throw new Error("Refusing to create temp dir: ancestor is a symlink (post-mkdir): " + revalidateAccumulated);
191
+ }
192
+ } catch (e) {
193
+ if (e instanceof Error && e.message.includes("symlink")) throw e;
194
+ // Component doesn't exist — stop re-validating, retry realpathSync
195
+ break;
196
+ }
197
+ }
198
+ }
199
+ // Issue #2 fix: verify resolvedBase itself is not a symlink (TOCTOU
200
+ // between realpathSync and the ancestor walk). If a symlink was
201
+ // created at the base path after realpathSync returned, catch it.
202
+ let resolvedBaseStat: fs.Stats;
203
+ try {
204
+ resolvedBaseStat = fs.lstatSync(resolvedBase);
205
+ if (resolvedBaseStat.isSymbolicLink()) throw new Error("Refusing to create temp dir: resolved base is a symlink: " + resolvedBase);
206
+ } catch (e) {
207
+ if (e instanceof Error && e.message.includes("symlink")) throw e;
208
+ // resolvedBase doesn't exist yet — OK
209
+ }
210
+ // Verify resolved path has no symlink ancestors. realpathSync follows
211
+ // symlinks, so if any ancestor is a symlink the resolved path will be
212
+ // inside the attacker's target. Catch that by walking the resolved path.
213
+ const resolvedParts = resolvedBase.split(path.sep);
214
+ let resolvedAccumulated = "";
215
+ if (resolvedParts[0] === "") resolvedAccumulated = "/"; // Unix root
216
+ for (let i = 1; i < resolvedParts.length; i++) {
217
+ if (resolvedParts[i] === "") continue;
218
+ resolvedAccumulated = path.join(resolvedAccumulated, resolvedParts[i]);
219
+ try {
220
+ const stat = fs.lstatSync(resolvedAccumulated);
221
+ if (stat.isSymbolicLink()) throw new Error("Refusing to create temp dir: resolved path contains symlink ancestor: " + resolvedAccumulated);
222
+ } catch (e) {
223
+ if (e instanceof Error && e.message.includes("symlink")) throw e;
224
+ // Component doesn't exist — OK
225
+ break;
226
+ }
227
+ }
77
228
  const rawTempDir = fs.mkdtempSync(path.join(resolvedBase, prefix));
78
229
  try {
79
230
  const stat = fs.lstatSync(rawTempDir);
@@ -85,7 +236,10 @@ function createSafeTempDir(base: string, prefix: string): string {
85
236
  }
86
237
  throw e;
87
238
  }
88
- return fs.realpathSync(rawTempDir);
239
+ const resolved = fs.realpathSync(rawTempDir);
240
+ // Track for global cleanup on shutdown / crash
241
+ createdTempDirs.add(resolved);
242
+ return resolved;
89
243
  }
90
244
 
91
245
  export function buildPiWorkerArgs(input: BuildPiWorkerArgsInput): BuildPiWorkerArgsResult {
@@ -123,10 +277,9 @@ export function buildPiWorkerArgs(input: BuildPiWorkerArgsInput): BuildPiWorkerA
123
277
 
124
278
  let tempDir: string | undefined;
125
279
  if (input.agent.systemPrompt) {
126
- // On Windows, prefer a subdirectory within the user's profile over system temp
127
- const tmpBase = process.platform === "win32" && os.homedir()
128
- ? path.join(os.homedir(), ".pi-crew", "tmp")
129
- : os.tmpdir();
280
+ // Use pi's own config dir instead of /tmp so temp files live alongside
281
+ // other pi state and don't pollute the shared system temp dir.
282
+ const tmpBase = getPiTempBase();
130
283
  tempDir = createSafeTempDir(tmpBase, `pi-crew-${process.pid}-`);
131
284
  const promptPath = path.join(tempDir, `${input.agent.name.replace(/[^\w.-]/g, "_")}.md`);
132
285
  fs.writeFileSync(promptPath, input.agent.systemPrompt, { mode: 0o600 });
@@ -135,9 +288,7 @@ export function buildPiWorkerArgs(input: BuildPiWorkerArgsInput): BuildPiWorkerA
135
288
 
136
289
  if (input.task.length > TASK_ARG_LIMIT) {
137
290
  if (!tempDir) {
138
- const tmpBase = process.platform === "win32" && os.homedir()
139
- ? path.join(os.homedir(), ".pi-crew", "tmp")
140
- : os.tmpdir();
291
+ const tmpBase = getPiTempBase();
141
292
  tempDir = createSafeTempDir(tmpBase, `pi-crew-${process.pid}-`);
142
293
  }
143
294
  const taskPath = path.join(tempDir, "task.md");
@@ -171,8 +322,280 @@ export function buildPiWorkerArgs(input: BuildPiWorkerArgsInput): BuildPiWorkerA
171
322
  export function cleanupTempDir(tempDir: string | undefined): void {
172
323
  if (!tempDir) return;
173
324
  try {
325
+ // CRITICAL: never rmSync a symlink. fs.rmSync with recursive:true
326
+ // FOLLOWS symlinks — use lstatSync (does not follow) to verify.
327
+ let lstat: fs.Stats;
328
+ try {
329
+ lstat = fs.lstatSync(tempDir);
330
+ } catch {
331
+ // Dir doesn't exist or inaccessible — best effort
332
+ createdTempDirs.delete(tempDir);
333
+ return;
334
+ }
335
+ if (lstat.isSymbolicLink()) {
336
+ // Symlinks should not be in createdTempDirs (createSafeTempDir
337
+ // rejects symlinked base dirs), but guard anyway.
338
+ createdTempDirs.delete(tempDir);
339
+ return;
340
+ }
174
341
  fs.rmSync(tempDir, { recursive: true, force: true });
342
+ createdTempDirs.delete(tempDir);
175
343
  } catch {
176
344
  // Best effort.
177
345
  }
178
346
  }
347
+
348
+ /**
349
+ * Clean up ALL temp dirs created in this process. Called from
350
+ * crew-cleanup.ts on session_shutdown to prevent accumulation of
351
+ * /tmp/pi-crew-* dirs when individual cleanupTempDir calls are missed
352
+ * (e.g. parent process killed before child-pi.ts settles).
353
+ */
354
+ export function cleanupAllTrackedTempDirs(): { cleaned: number; failed: number } {
355
+ let cleaned = 0;
356
+ let failed = 0;
357
+ // Snapshot to avoid mutation during iteration
358
+ for (const dir of [...createdTempDirs]) {
359
+ try {
360
+ // CRITICAL: never rmSync a symlink. fs.rmSync with recursive:true
361
+ // FOLLOWS symlinks — use lstatSync to verify first.
362
+ let lstat: fs.Stats;
363
+ try {
364
+ lstat = fs.lstatSync(dir);
365
+ } catch {
366
+ // Dir gone or inaccessible — best effort cleanup
367
+ createdTempDirs.delete(dir);
368
+ failed++;
369
+ continue;
370
+ }
371
+ if (lstat.isSymbolicLink()) {
372
+ // Should never happen (createSafeTempDir rejects symlinked
373
+ // base), but guard anyway to prevent accidental target deletion.
374
+ createdTempDirs.delete(dir);
375
+ continue;
376
+ }
377
+ fs.rmSync(dir, { recursive: true, force: true });
378
+ createdTempDirs.delete(dir);
379
+ cleaned++;
380
+ } catch {
381
+ failed++;
382
+ }
383
+ }
384
+ return { cleaned, failed };
385
+ }
386
+
387
+ /**
388
+ * @internal Test-only: reset the in-memory `createdTempDirs` Set.
389
+ * Used by unit tests to ensure isolation between cases. Not exported
390
+ * via the public API surface.
391
+ */
392
+ export function __test_resetTrackedTempDirs(): void {
393
+ createdTempDirs.clear();
394
+ }
395
+
396
+ /**
397
+ * @internal Test-only: get a snapshot of currently tracked temp dirs.
398
+ */
399
+ export function __test_getTrackedTempDirs(): readonly string[] {
400
+ return [...createdTempDirs];
401
+ }
402
+
403
+ /**
404
+ * Purge stale entries from createdTempDirs — directories that no longer
405
+ * exist on disk. This handles the case where a process crashed before
406
+ * cleanupAllTrackedTempDirs ran, leaving orphaned entries in the Set.
407
+ * Called at startup as a belt-and-suspenders measure alongside the
408
+ * periodic cleanupOrphanTempDirs.
409
+ */
410
+ export function purgeStaleTrackedTempDirs(): { removed: number; remaining: number } {
411
+ let removed = 0;
412
+ for (const dir of [...createdTempDirs]) {
413
+ if (!fs.existsSync(dir)) {
414
+ createdTempDirs.delete(dir);
415
+ removed++;
416
+ }
417
+ }
418
+ return { removed, remaining: createdTempDirs.size };
419
+ }
420
+
421
+ // Run startup purge to prevent unbounded Set growth from crash loops.
422
+ purgeStaleTrackedTempDirs();
423
+
424
+ /** Max age (ms) for orphan temp dirs. Anything older is considered abandoned. */
425
+ const ORPHAN_TEMP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24h
426
+ /** Cap dirs removed per call to avoid main-thread stalls. */
427
+ const ORPHAN_TEMP_CLEAN_BATCH_SIZE = 50;
428
+
429
+ /**
430
+ * Remove orphan temp dirs in `~/.pi/agent/pi-crew/tmp/` older than the age
431
+ * threshold. This catches dirs left behind by parent processes that were
432
+ * SIGKILL'd (no graceful shutdown to call cleanupAllTrackedTempDirs).
433
+ *
434
+ * Called periodically by register.ts:tempReconcileTimer.
435
+ *
436
+ * @param now Current epoch ms (parameter for testability)
437
+ * @param baseDir Override base dir (for testing). Defaults to
438
+ * `<userPiRoot>/tmp/`.
439
+ */
440
+ export function cleanupOrphanTempDirs(
441
+ now: number = Date.now(),
442
+ baseDir: string = path.join(userPiRoot(), "tmp"),
443
+ ): { scanned: number; cleaned: number; failed: number } {
444
+ let scanned = 0;
445
+ let cleaned = 0;
446
+ let failed = 0;
447
+ try {
448
+ if (!fs.existsSync(baseDir)) return { scanned: 0, cleaned: 0, failed: 0 };
449
+ const entries = fs.readdirSync(baseDir, { withFileTypes: true });
450
+ // Only process pi-crew-* dirs to avoid touching unrelated files
451
+ const candidates = entries
452
+ .filter((e) => e.isDirectory() && e.name.startsWith("pi-crew-"))
453
+ .sort((a, b) => a.name.localeCompare(b.name))
454
+ .slice(0, ORPHAN_TEMP_CLEAN_BATCH_SIZE);
455
+ for (const entry of candidates) {
456
+ scanned++;
457
+ const dir = path.join(baseDir, entry.name);
458
+ // CRITICAL: never rmSync a symlink. fs.rmSync with recursive:true
459
+ // FOLLOWS symlinks — an attacker could plant a symlink to /etc and
460
+ // wipe the system. Use lstat (does not follow) and skip.
461
+ let lstat: fs.Stats;
462
+ try {
463
+ lstat = fs.lstatSync(dir);
464
+ } catch {
465
+ failed++;
466
+ continue;
467
+ }
468
+ if (lstat.isSymbolicLink()) continue;
469
+ // Skip dirs currently in use by this process. A long-running child
470
+ // pi (>24h) would otherwise have its prompt/task tmp dir deleted
471
+ // mid-execution, causing broken-pipe failures when the child
472
+ // reads the system prompt.
473
+ if (createdTempDirs.has(dir)) continue;
474
+ try {
475
+ // FIX: Perform lstatSync BEFORE statSync mtime check to close TOCTOU window.
476
+ // An attacker could plant a symlink between the early lstatSync (line 373) and statSync.
477
+ // If statSync follows the symlink, it reads the target's mtime, not the dir's.
478
+ // By checking lstatSync first, we skip the mtime check entirely for symlinks.
479
+ let preRmlstat: fs.Stats | undefined;
480
+ try {
481
+ preRmlstat = fs.lstatSync(dir);
482
+ } catch {
483
+ failed++;
484
+ continue;
485
+ }
486
+ if (!preRmlstat || preRmlstat.isSymbolicLink()) continue;
487
+ // Reuse preRmlstat (captured at line 408) — already verified non-symlink at line 415.
488
+ // Avoid calling lstatSync again to eliminate the TOCTOU window between
489
+ // preRmlstat lstatSync (line 408) and this mtime check.
490
+ // NOTE: This is a best-effort approximation. The mtime was captured at line 408,
491
+ // potentially seconds before the rmSync at line 420. If the directory was modified
492
+ // after line 408, the age check uses stale data. This could cause premature cleanup
493
+ // of dirs that were recently modified but appeared old based on cached mtime (±seconds jitter).
494
+ if (now - preRmlstat.mtimeMs > ORPHAN_TEMP_MAX_AGE_MS) {
495
+ fs.rmSync(dir, { recursive: true, force: true });
496
+ createdTempDirs.delete(dir);
497
+ cleaned++;
498
+ }
499
+ } catch {
500
+ failed++;
501
+ }
502
+ }
503
+ } catch {
504
+ /* skip if tmpdir unreadable */
505
+ }
506
+ return { scanned, cleaned, failed };
507
+ }
508
+
509
+ /**
510
+ * Clean up orphan `pi-crew-*` prompt/task temp dirs left in the system
511
+ * `/tmp/` directory. Before commit 8ba270d these were the primary location
512
+ * for temp dirs; users who upgraded may have thousands of orphans (the
513
+ * user's /tmp had 2498 of these). The existing
514
+ * `reconcileOrphanedTempWorkspaces` only cleans dirs containing
515
+ * `.crew/state/runs/` (the run-state dirs), so prompt/task orphans are
516
+ * never touched.
517
+ *
518
+ * Strategy: remove `pi-crew-*` dirs in /tmp that DO NOT contain
519
+ * `.crew/state/runs/` AND are older than the age threshold. The age
520
+ * threshold protects active processes that might still be writing.
521
+ *
522
+ * Bounded to ORPHAN_TEMP_CLEAN_BATCH_SIZE dirs per call.
523
+ *
524
+ * @param now Current epoch ms (parameter for testability)
525
+ * @param tmpDirOverride Override /tmp dir (for testing). Defaults to
526
+ * `os.tmpdir()`.
527
+ */
528
+ export function cleanupLegacyOrphanTempDirs(
529
+ now: number = Date.now(),
530
+ tmpDirOverride: string = os.tmpdir(),
531
+ ): { scanned: number; cleaned: number; failed: number } {
532
+ const tmpDir = tmpDirOverride;
533
+ let scanned = 0;
534
+ let cleaned = 0;
535
+ let failed = 0;
536
+ try {
537
+ if (!fs.existsSync(tmpDir)) return { scanned: 0, cleaned: 0, failed: 0 };
538
+ const entries = fs.readdirSync(tmpDir, { withFileTypes: true });
539
+ const candidates = entries
540
+ .filter((e) => e.isDirectory() && e.name.startsWith("pi-crew-"))
541
+ .sort((a, b) => a.name.localeCompare(b.name))
542
+ .slice(0, ORPHAN_TEMP_CLEAN_BATCH_SIZE);
543
+ for (const entry of candidates) {
544
+ scanned++;
545
+ const dir = path.join(tmpDir, entry.name);
546
+ // Symlink guard
547
+ let lstat: fs.Stats;
548
+ try {
549
+ lstat = fs.lstatSync(dir);
550
+ } catch {
551
+ failed++;
552
+ continue;
553
+ }
554
+ if (lstat.isSymbolicLink()) continue;
555
+ // Skip dirs containing active run state — those are handled by
556
+ // reconcileOrphanedTempWorkspaces which has run-state semantics.
557
+ const crewDir = path.join(dir, ".crew");
558
+ let crewDirLstat: fs.Stats | undefined;
559
+ try {
560
+ crewDirLstat = fs.lstatSync(crewDir);
561
+ } catch {
562
+ // doesn't exist
563
+ }
564
+ if (crewDirLstat && !crewDirLstat.isSymbolicLink()) continue;
565
+ // Skip dirs currently tracked by this process (defense in depth:
566
+ // with 8ba270d the Set should never contain /tmp/ paths, but
567
+ // future code or external callers might).
568
+ if (createdTempDirs.has(dir)) continue;
569
+ try {
570
+ // FIX: Perform lstatSync BEFORE statSync mtime check to close TOCTOU window.
571
+ // An attacker could plant a symlink between the early lstatSync (line 457) and statSync.
572
+ // If statSync follows the symlink, it reads the target's mtime, not the dir's.
573
+ // By checking lstatSync first, we skip the mtime check entirely for symlinks.
574
+ let preRmlstat: fs.Stats;
575
+ try {
576
+ preRmlstat = fs.lstatSync(dir);
577
+ } catch {
578
+ failed++;
579
+ continue;
580
+ }
581
+ if (preRmlstat.isSymbolicLink()) continue;
582
+ // Reuse preRmlstat (captured at line 494) — already verified non-symlink at line 501.
583
+ // Avoid calling lstatSync again to eliminate the TOCTOU window between
584
+ // preRmlstat lstatSync (line 494) and this mtime check.
585
+ // NOTE: This is a best-effort approximation. The mtime was captured at line 494,
586
+ // potentially seconds before the rmSync at line 505. If the directory was modified
587
+ // after line 494, the age check uses stale data. This could cause premature cleanup
588
+ // of dirs that were recently modified but appeared old based on cached mtime (±seconds jitter).
589
+ if (now - preRmlstat.mtimeMs > ORPHAN_TEMP_MAX_AGE_MS) {
590
+ fs.rmSync(dir, { recursive: true, force: true });
591
+ cleaned++;
592
+ }
593
+ } catch {
594
+ failed++;
595
+ }
596
+ }
597
+ } catch {
598
+ /* skip if tmpdir unreadable */
599
+ }
600
+ return { scanned, cleaned, failed };
601
+ }
@@ -161,6 +161,7 @@ function validateExplicitBin(explicit: string): string | undefined {
161
161
  }
162
162
  } catch (e) {
163
163
  if (e instanceof Error && e.message.includes("allowed prefixes")) throw e;
164
+ console.error("[pi-spawn] validateExplicitBin: unexpected realpathSync error:", e);
164
165
  return undefined;
165
166
  }
166
167
  return resolved;
@@ -94,7 +94,7 @@ export async function runPostCheck(config: PostCheckConfig, cwd: string): Promis
94
94
  timeout: timeoutMs,
95
95
  encoding: "utf-8",
96
96
  maxBuffer: 10 * 1024 * 1024, // 10 MB
97
- env: { ...sanitizeEnvSecrets(process.env, { allowList: ["PATH", "HOME", "USER", "USERPROFILE", "TEMP", "TMP", "TMPDIR", "LANG", "LC_ALL", "ComSpec", "SystemRoot", "PI_*"] }), PI_CREW_POST_CHECK: "1" },
97
+ env: { ...sanitizeEnvSecrets(process.env, { allowList: ["PATH", "HOME", "USER", "USERPROFILE", "TEMP", "TMP", "TMPDIR", "LANG", "LC_ALL", "ComSpec", "SystemRoot", "PI_CREW_*"] }), PI_CREW_POST_CHECK: "1" },
98
98
  });
99
99
 
100
100
  const durationMs = Date.now() - startTime;
@@ -72,10 +72,16 @@ export class RetryRunner {
72
72
  private _disposed = false;
73
73
  private _handoffs: HandoffSummary[] = [];
74
74
 
75
+ private taskRunner: TaskRunnerLike;
76
+ private handoffManager: HandoffManager;
77
+
75
78
  constructor(
76
- private taskRunner: TaskRunnerLike,
77
- private handoffManager: HandoffManager,
78
- ) {}
79
+ taskRunner: TaskRunnerLike,
80
+ handoffManager: HandoffManager,
81
+ ) {
82
+ this.taskRunner = taskRunner;
83
+ this.handoffManager = handoffManager;
84
+ }
79
85
 
80
86
  /**
81
87
  * Check if this runner has been disposed.
@@ -1,21 +1,31 @@
1
- import type { TeamRunManifest, TeamTaskState } from "../state/types.ts";
2
1
  import * as fs from "node:fs";
3
2
  import * as path from "node:path";
4
3
  import { loadRunManifestById } from "../state/state-store.ts";
4
+ import type { TeamRunManifest, TeamTaskState } from "../state/types.ts";
5
+ import { projectCrewRoot } from "../utils/paths.ts";
5
6
  import { isFinishedRunStatus } from "./process-status.ts";
6
7
 
7
8
  export interface ActiveRunPromise {
8
9
  promise: Promise<{ manifest: TeamRunManifest; tasks: TeamTaskState[] }>;
9
- resolve: (value: { manifest: TeamRunManifest; tasks: TeamTaskState[] }) => void;
10
+ resolve: (value: {
11
+ manifest: TeamRunManifest;
12
+ tasks: TeamTaskState[];
13
+ }) => void;
10
14
  reject: (reason: unknown) => void;
11
15
  }
12
16
 
13
17
  const activeRunPromises = new Map<string, ActiveRunPromise>();
14
18
 
15
19
  export function registerRunPromise(runId: string): ActiveRunPromise {
16
- let resolve!: (value: { manifest: TeamRunManifest; tasks: TeamTaskState[] }) => void;
20
+ let resolve!: (value: {
21
+ manifest: TeamRunManifest;
22
+ tasks: TeamTaskState[];
23
+ }) => void;
17
24
  let reject!: (reason: unknown) => void;
18
- const promise = new Promise<{ manifest: TeamRunManifest; tasks: TeamTaskState[] }>((res, rej) => {
25
+ const promise = new Promise<{
26
+ manifest: TeamRunManifest;
27
+ tasks: TeamTaskState[];
28
+ }>((res, rej) => {
19
29
  resolve = res;
20
30
  reject = rej;
21
31
  });
@@ -24,7 +34,10 @@ export function registerRunPromise(runId: string): ActiveRunPromise {
24
34
  return entry;
25
35
  }
26
36
 
27
- export function resolveRunPromise(runId: string, result: { manifest: TeamRunManifest; tasks: TeamTaskState[] }): void {
37
+ export function resolveRunPromise(
38
+ runId: string,
39
+ result: { manifest: TeamRunManifest; tasks: TeamTaskState[] },
40
+ ): void {
28
41
  const entry = activeRunPromises.get(runId);
29
42
  if (entry) {
30
43
  entry.resolve(result);
@@ -55,7 +68,7 @@ export async function waitForRun(
55
68
  const deadline = Date.now() + timeoutMs;
56
69
 
57
70
  // Fast path: already terminal on disk
58
- const loaded = loadRunManifestById(cwd, runId);
71
+ const loaded = loadRunManifestById(cwd, runId); // NOTE: no withRunLock - best-effort only; concurrent writes may cause inconsistency;
59
72
  if (loaded && isFinishedRunStatus(loaded.manifest.status)) {
60
73
  return loaded;
61
74
  }
@@ -65,7 +78,13 @@ export async function waitForRun(
65
78
  if (entry) {
66
79
  let timer: ReturnType<typeof setTimeout> | undefined;
67
80
  const timeoutPromise = new Promise<never>((_, reject) => {
68
- timer = setTimeout(() => reject(new Error(`waitForRun timed out after ${timeoutMs}ms`)), timeoutMs);
81
+ timer = setTimeout(
82
+ () =>
83
+ reject(
84
+ new Error(`waitForRun timed out after ${timeoutMs}ms`),
85
+ ),
86
+ timeoutMs,
87
+ );
69
88
  });
70
89
  try {
71
90
  return await Promise.race([entry.promise, timeoutPromise]);
@@ -78,15 +97,24 @@ export async function waitForRun(
78
97
  let attempt = 0;
79
98
  while (Date.now() < deadline) {
80
99
  if (attempt === 0) {
81
- // Early exit: if the run directory doesn't exist, don't waste time polling
82
- const runDir = path.join(cwd, ".crew", "state", "runs", runId);
100
+ // Early exit: if the run directory doesn't exist, don't waste time polling.
101
+ // Use projectCrewRoot() to honour the .pi/teams/ fallback for .pi-based
102
+ // projects (see issue #29). Without this, the hardcoded `.crew/state/runs/`
103
+ // path never resolves in projects that use the `.pi/` layout, the throw
104
+ // escapes via subagent-manager.ts:281, and pi crashes with uncaughtException.
105
+ const runDir = path.join(
106
+ projectCrewRoot(cwd),
107
+ "state",
108
+ "runs",
109
+ runId,
110
+ );
83
111
  if (!fs.existsSync(runDir)) {
84
112
  throw new Error(
85
113
  `Run ${runId} not found. No run directory at ${runDir}`,
86
114
  );
87
115
  }
88
116
  }
89
- const fresh = loadRunManifestById(cwd, runId);
117
+ const fresh = loadRunManifestById(cwd, runId); // NOTE: no withRunLock - best-effort only; concurrent writes may cause inconsistency;
90
118
  if (fresh && isFinishedRunStatus(fresh.manifest.status)) {
91
119
  return fresh;
92
120
  }
@@ -21,7 +21,13 @@ const FORBIDDEN_PATTERNS = [
21
21
  // Global escape vectors
22
22
  /\bglobalThis\b/, // globalThis reference
23
23
  /\bglobal\b/, // global reference (Node.js)
24
- /\bconstructor\b/, // Block constructor chain escape: [].constructor.constructor("return process")()
24
+ // Block constructor chain escape vectors:
25
+ // - `.constructor` followed by `(`, `.`, `;`, or end-of-line/string
26
+ // - `[constructor]` or `["constructor"]` bracket access on any value
27
+ // The bare `constructor` keyword in a class body is safe and allowed.
28
+ /\.constructor\s*\(/, // Block obj.constructor() chain calls
29
+ /\.constructor\s*(?:\.|$|;|,|\s)/, // Block obj.constructor at end, semicolon, comma, or whitespace
30
+ /\[\s*['"]?constructor['"]?\s*\]/, // Block ["constructor"] or ['constructor'] or [constructor]
25
31
  ] as const;
26
32
 
27
33
  Object.freeze(FORBIDDEN_PATTERNS);
@@ -80,7 +86,16 @@ export class WorkflowSandbox {
80
86
  const safeEnv = Object.freeze(sanitizeEnvSecrets(process.env, {
81
87
  allowList: [
82
88
  "NODE_ENV",
83
- "PI_CREW_*",
89
+ // Note: PI_CREW_* globs are not used here because isDangerousGlob
90
+ // flags them as potentially matching secret env vars (PI_CREW_token,
91
+ // PI_CREW_api_key, etc.). Instead, list the specific PI_CREW env vars
92
+ // that sandboxed code legitimately needs.
93
+ "PI_CREW_DEPTH",
94
+ "PI_CREW_INHERIT_PROJECT_CONTEXT",
95
+ "PI_CREW_INHERIT_SKILLS",
96
+ "PI_CREW_MOCK_LIVE_SESSION",
97
+ "PI_CREW_SKIP_HOME_CHECK",
98
+ "PI_CREW_WARM_POOL_SIZE",
84
99
  "PATH",
85
100
  "PATH_SEPARATOR",
86
101
  "USERPROFILE",