pi-crew 0.9.41 → 0.9.44

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 (170) hide show
  1. package/CHANGELOG.md +253 -0
  2. package/README.md +14 -0
  3. package/dist/build-meta.json +6450 -12419
  4. package/dist/index.mjs +57998 -68417
  5. package/dist/index.mjs.map +4 -4
  6. package/docs/migration/atomic-write-v2-migration.md +2 -0
  7. package/docs/superpowers/plans/2026-06-09-fallow-patterns-adoption.md +2 -0
  8. package/package.json +4 -2
  9. package/scripts/README.md +6 -0
  10. package/scripts/build-bundle.mjs +2 -1
  11. package/scripts/check-all-skills.ts +3 -3
  12. package/scripts/dev-runner.mjs +106 -0
  13. package/scripts/postinstall.mjs +6 -2
  14. package/scripts/verify-skill.ts +2 -2
  15. package/src/agents/agent-config.ts +1 -1
  16. package/src/config/config.ts +20 -1
  17. package/src/config/drift-detector.ts +97 -15
  18. package/src/config/resilient-parser.ts +4 -4
  19. package/src/config/types.ts +0 -2
  20. package/src/extension/crew-cleanup.ts +17 -3
  21. package/src/extension/crew-vibes/config.ts +1 -1
  22. package/src/extension/crew-vibes/font-detect.ts +16 -3
  23. package/src/extension/crew-vibes/index.ts +1 -1
  24. package/src/extension/cross-extension-rpc.ts +26 -9
  25. package/src/extension/management.ts +6 -5
  26. package/src/extension/register.ts +58 -1573
  27. package/src/extension/registration/command-registration.ts +57 -0
  28. package/src/extension/registration/commands.ts +7 -2
  29. package/src/extension/registration/context-builder.ts +131 -0
  30. package/src/extension/registration/crash-recovery-cache.ts +54 -0
  31. package/src/extension/registration/foreground-run-controller.ts +238 -0
  32. package/src/extension/registration/hook-registration.ts +119 -0
  33. package/src/extension/registration/lazy-configurers.ts +124 -0
  34. package/src/extension/registration/lifecycle-handlers.ts +731 -0
  35. package/src/extension/registration/observability.ts +33 -4
  36. package/src/extension/registration/registration-types.ts +149 -0
  37. package/src/extension/registration/runtime-cleanup.ts +230 -0
  38. package/src/extension/registration/subagent-manager-setup.ts +211 -0
  39. package/src/extension/registration/tool-registration.ts +50 -0
  40. package/src/extension/registration/wire-cross-extension.ts +37 -0
  41. package/src/extension/rpc-hmac.ts +21 -1
  42. package/src/extension/run-import.ts +3 -3
  43. package/src/extension/team-tool/auto-summarize.ts +4 -4
  44. package/src/extension/team-tool/cancel.ts +5 -5
  45. package/src/extension/team-tool/chain-executor.ts +5 -4
  46. package/src/extension/team-tool/context.ts +11 -1
  47. package/src/extension/team-tool/doctor.ts +2 -1
  48. package/src/extension/team-tool/goal-wrap.ts +2 -2
  49. package/src/extension/team-tool/goal.ts +1 -1
  50. package/src/extension/team-tool/handle-schedule.ts +25 -36
  51. package/src/extension/team-tool/orchestrate.ts +0 -1
  52. package/src/extension/team-tool/parallel-dispatch.ts +5 -0
  53. package/src/extension/team-tool/run.ts +220 -214
  54. package/src/extension/team-tool/workflow-manage.ts +1 -1
  55. package/src/extension/team-tool.ts +69 -16
  56. package/src/hooks/registry.ts +7 -2
  57. package/src/observability/correlation.ts +4 -3
  58. package/src/observability/event-bus.ts +10 -1
  59. package/src/observability/event-to-metric.ts +8 -7
  60. package/src/observability/exporters/adapter.ts +6 -9
  61. package/src/observability/exporters/otlp-exporter.ts +81 -0
  62. package/src/observability/metric-retention.ts +4 -0
  63. package/src/observability/metric-sink.ts +14 -4
  64. package/src/prompt/prompt-runtime.ts +15 -0
  65. package/src/runtime/adaptive-plan.ts +1 -1
  66. package/src/runtime/async-runner.ts +13 -4
  67. package/src/runtime/background-runner.ts +32 -23
  68. package/src/runtime/capability-inventory.ts +1 -1
  69. package/src/runtime/chain-runner.ts +5 -5
  70. package/src/runtime/checkpoint.ts +6 -16
  71. package/src/runtime/child-pi-constants.ts +42 -0
  72. package/src/runtime/child-pi-kill.ts +180 -0
  73. package/src/runtime/child-pi-spawn.ts +234 -0
  74. package/src/runtime/child-pi-steering.ts +128 -0
  75. package/src/runtime/child-pi-streams.ts +296 -0
  76. package/src/runtime/child-pi-transcript.ts +169 -0
  77. package/src/runtime/child-pi.ts +80 -822
  78. package/src/runtime/coalesce-tasks.ts +1 -1
  79. package/src/runtime/compact-stages/tail-capture-stage.ts +1 -1
  80. package/src/runtime/crash-recovery.ts +63 -47
  81. package/src/runtime/delivery-coordinator.ts +1 -1
  82. package/src/runtime/deterministic-ast.ts +2 -2
  83. package/src/runtime/diagnostic-export.ts +2 -1
  84. package/src/runtime/dwf-state-store.ts +5 -0
  85. package/src/runtime/dynamic-workflow-context.ts +78 -18
  86. package/src/runtime/dynamic-workflow-runner.ts +18 -2
  87. package/src/runtime/foreground-control.ts +3 -2
  88. package/src/runtime/goal-evaluator.ts +59 -27
  89. package/src/runtime/goal-loop-runner.ts +46 -13
  90. package/src/runtime/goal-state-store.ts +1 -1
  91. package/src/runtime/handoff-manager.ts +0 -2
  92. package/src/runtime/intercom-bridge.ts +0 -2
  93. package/src/runtime/live-agent-manager.ts +30 -5
  94. package/src/runtime/live-extension-bridge.ts +0 -2
  95. package/src/runtime/live-session-runtime.ts +65 -57
  96. package/src/runtime/manifest-cache.ts +59 -0
  97. package/src/runtime/mcp-proxy.ts +1 -1
  98. package/src/runtime/orphan-worker-registry.ts +3 -3
  99. package/src/runtime/output-validator.ts +1 -1
  100. package/src/runtime/path-overlap.ts +1 -1
  101. package/src/runtime/pi-args.ts +3 -3
  102. package/src/runtime/pi-json-output.ts +4 -3
  103. package/src/runtime/pi-spawn.ts +7 -1
  104. package/src/runtime/pipeline-runner.ts +1 -4
  105. package/src/runtime/post-checks.ts +0 -1
  106. package/src/runtime/retry-runner.ts +1 -1
  107. package/src/runtime/run-coalesced-task-group.ts +18 -23
  108. package/src/runtime/scheduler.ts +2 -0
  109. package/src/runtime/session-resources.ts +1 -1
  110. package/src/runtime/settings-store.ts +31 -1
  111. package/src/runtime/skill-effectiveness.ts +2 -2
  112. package/src/runtime/stale-reconciler.ts +23 -53
  113. package/src/runtime/subagent-manager.ts +19 -3
  114. package/src/runtime/task-output-context.ts +2 -1
  115. package/src/runtime/task-runner/prompt-builder.ts +3 -3
  116. package/src/runtime/task-runner/run-projection.ts +3 -1
  117. package/src/runtime/task-runner/state-helpers.ts +13 -1
  118. package/src/runtime/task-runner.ts +31 -6
  119. package/src/runtime/team-runner.ts +8 -2
  120. package/src/runtime/verification-gates.ts +54 -5
  121. package/src/schema/config-schema.ts +19 -1
  122. package/src/schema/team-tool-schema.ts +2 -0
  123. package/src/skills/discover-skills.ts +25 -15
  124. package/src/state/active-run-registry.ts +0 -1
  125. package/src/state/atomic-write.ts +37 -11
  126. package/src/state/blob-store.ts +3 -9
  127. package/src/state/contracts.ts +5 -1
  128. package/src/state/crew-init.ts +3 -2
  129. package/src/state/decision-ledger.ts +2 -2
  130. package/src/state/event-log-rotation.ts +1 -1
  131. package/src/state/event-log.ts +4 -3
  132. package/src/state/gitignore-manager.ts +2 -1
  133. package/src/state/health-store.ts +5 -2
  134. package/src/state/instinct-store.ts +11 -2
  135. package/src/state/locks.ts +132 -49
  136. package/src/state/mailbox.ts +3 -4
  137. package/src/state/observation-store.ts +1 -13
  138. package/src/state/run-cache.ts +12 -12
  139. package/src/state/run-graph.ts +2 -1
  140. package/src/state/run-metrics.ts +1 -1
  141. package/src/state/schedule.ts +7 -1
  142. package/src/state/state-store.ts +9 -3
  143. package/src/state/tiered-eval.ts +1 -1
  144. package/src/state/worker-atomic-writer.ts +1 -0
  145. package/src/ui/dynamic-border.ts +13 -3
  146. package/src/ui/live-conversation-overlay.ts +7 -27
  147. package/src/ui/live-duration.ts +2 -2
  148. package/src/ui/live-run-sidebar.ts +56 -32
  149. package/src/ui/mascot.ts +19 -13
  150. package/src/ui/powerbar-publisher.ts +244 -178
  151. package/src/ui/render-coalescer.ts +44 -3
  152. package/src/ui/render-diff.ts +2 -2
  153. package/src/ui/run-dashboard.ts +122 -21
  154. package/src/ui/run-event-bus.ts +66 -0
  155. package/src/ui/run-snapshot-cache.ts +84 -81
  156. package/src/ui/settings-overlay.ts +3 -3
  157. package/src/ui/status-colors.ts +24 -0
  158. package/src/ui/tool-progress-formatter.ts +1 -1
  159. package/src/ui/tool-render.ts +3 -3
  160. package/src/ui/transcript-cache.ts +5 -10
  161. package/src/ui/transcript-entries.ts +68 -72
  162. package/src/ui/transcript-viewer.ts +54 -14
  163. package/src/ui/widget/index.ts +26 -15
  164. package/src/ui/widget/widget-model.ts +18 -9
  165. package/src/ui/widget/widget-renderer.ts +2 -5
  166. package/src/utils/fingerprint.ts +1 -1
  167. package/src/utils/paths.ts +1 -1
  168. package/src/utils/project-detector.ts +1 -1
  169. package/src/worktree/worktree-manager.ts +47 -19
  170. package/src/state/atomic-write-v2.ts +0 -108
@@ -1,48 +1,45 @@
1
- import { type ChildProcess, type SpawnOptions, spawn } from "node:child_process";
1
+ import { spawn } from "node:child_process";
2
2
  import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
5
  import type { AgentConfig } from "../agents/agent-config.ts";
6
6
  import { DEFAULT_CHILD_PI } from "../config/defaults.ts";
7
7
  import { registerChildProcess, unregisterChildProcess } from "../extension/crew-cleanup.ts";
8
+ import { atomicWriteFile } from "../state/atomic-write.ts";
8
9
  import type { WorkerExitStatus } from "../state/types.ts";
9
- import { WINDOWS_ESSENTIAL_ENV_VARS } from "../utils/env-allowlist.ts";
10
- import { buildScopedAllowList, sanitizeEnvSecrets } from "../utils/env-filter.ts";
11
10
  import { logInternalError } from "../utils/internal-error.ts";
12
- import { redactJsonLine, redactSecretString } from "../utils/redaction.ts";
13
- import { resolveRealContainedPath } from "../utils/safe-paths.ts";
14
- import { applyCompactPipeline } from "./compact-pipeline.ts";
15
- import { TailCaptureStage, TruncationStage } from "./compact-stages/index.ts";
11
+ import { redactSecretString } from "../utils/redaction.ts";
12
+ import { FINAL_DRAIN_MS, HARD_KILL_MS, POST_EXIT_STDIO_GUARD_MS, RESPONSE_TIMEOUT_MS } from "./child-pi-constants.ts";
13
+ import { appendBoundedTail, clearHardKillTimer, killProcessTree, registerActiveChild, unregisterActiveChild } from "./child-pi-kill.ts";
14
+ import { assertOnlyControlEnvKeys, buildChildPiSpawnOptions, prepareSpawnContext } from "./child-pi-spawn.ts";
15
+ import { ChildPiSteeringController } from "./child-pi-steering.ts";
16
+ // Internal helpers for active-child bookkeeping (extracted to child-pi-kill.ts).
17
+ import { ChildPiLineObserver } from "./child-pi-streams.ts";
18
+
19
+ // ── Re-exports from child-pi-kill.ts (H-7 decomposition step 2) ──
20
+ // killProcessTree is internal (not previously exported) — keep that invariant.
21
+ export {
22
+ killProcessPid,
23
+ terminateActiveChildPiProcesses,
24
+ } from "./child-pi-kill.ts";
25
+ // ── Re-export from child-pi-spawn.ts (H-7 decomposition step 6) ──
26
+ // buildChildPiSpawnOptions was previously exported from child-pi.ts. Keep the
27
+ // public API surface stable by re-exporting from the new module.
28
+ export { buildChildPiSpawnOptions } from "./child-pi-spawn.ts";
29
+ // ── Re-export from child-pi-streams.ts (H-7 decomposition step 4) ──
30
+ export { ChildPiLineObserver } from "./child-pi-streams.ts";
31
+
16
32
  import { classifyProcessCrash } from "./crash-classification.ts";
17
- import { buildPiWorkerArgs, checkCrewDepth, cleanupTempDir } from "./pi-args.ts";
18
- import { extractText } from "./pi-json-output.ts";
19
- import { getPiSpawnCommand } from "./pi-spawn.ts";
33
+ import { checkCrewDepth, cleanupTempDir } from "./pi-args.ts";
34
+
20
35
  import { attachPostExitStdioGuard, trySignalChild } from "./post-exit-stdio-guard.ts";
21
36
 
22
- const POST_EXIT_STDIO_GUARD_MS = DEFAULT_CHILD_PI.postExitStdioGuardMs;
23
- const FINAL_DRAIN_MS = DEFAULT_CHILD_PI.finalDrainMs;
24
- const HARD_KILL_MS = DEFAULT_CHILD_PI.hardKillMs;
25
- const RESPONSE_TIMEOUT_MS = DEFAULT_CHILD_PI.responseTimeoutMs;
26
- const MAX_CAPTURE_BYTES = DEFAULT_CHILD_PI.maxCaptureBytes;
27
- const MAX_ASSISTANT_TEXT_CHARS = DEFAULT_CHILD_PI.maxAssistantTextChars;
28
- const MAX_TOOL_RESULT_CHARS = DEFAULT_CHILD_PI.maxToolResultChars;
29
- const MAX_TOOL_INPUT_CHARS = DEFAULT_CHILD_PI.maxToolInputChars;
30
- const MAX_COMPACT_CONTENT_CHARS = DEFAULT_CHILD_PI.maxCompactContentChars;
31
- const activeChildProcesses = new Map<number, ChildProcess>();
32
- const childHardKillTimers = new Map<number, NodeJS.Timeout>();
37
+ /** Maximum size (bytes) for the ChildPiLineObserver's line accumulation buffer.
38
+ * When exceeded, the buffer is force-flushed to prevent unbounded memory growth
39
+ * from chatty child processes that produce output without newlines.
40
+ * (Constant moved to child-pi-constants.ts.) */
33
41
 
34
42
  // Periodic cleanup of dead child process entries to prevent memory leaks.
35
- // If a child process never emits exit/close (zombie), the entry would leak.
36
- setInterval(() => {
37
- for (const [pid, child] of activeChildProcesses) {
38
- try {
39
- process.kill(pid, 0); // Throws ESRCH if dead
40
- } catch {
41
- activeChildProcesses.delete(pid);
42
- }
43
- }
44
- }, 60_000).unref();
45
-
46
43
  /**
47
44
  * SEC-1: Extract a redacted stderr/stdout excerpt for embedding in lifecycle
48
45
  * events and error messages. The in-memory stdout/stderr accumulators receive
@@ -62,126 +59,12 @@ export function redactStderrExcerpt(stderr: string, maxChars: number): string {
62
59
  return redactSecretString(stderr.slice(-maxChars));
63
60
  }
64
61
 
65
- function appendBoundedTail(current: string, chunk: string, maxBytes = MAX_CAPTURE_BYTES): string {
66
- // Sprint 5: refactored onto TailCaptureStage (P0-A stage-chain). The marker
67
- // embeds the cap size in KiB so the caller sees how much was dropped. Stage
68
- // construction per call is cheap (4 fields) and avoids caching concerns.
69
- return new TailCaptureStage({
70
- maxBytes,
71
- marker: `[pi-crew captured output truncated to last ${Math.round(maxBytes / 1024)} KiB]`,
72
- }).apply(current + chunk);
73
- }
74
-
75
- function clearHardKillTimer(pid: number | undefined): void {
76
- if (!pid) return;
77
- const timer = childHardKillTimers.get(pid);
78
- if (!timer) return;
79
- clearTimeout(timer);
80
- childHardKillTimers.delete(pid);
81
- }
82
-
83
62
  /**
84
63
  * B6: spawn taskkill and attach an 'error' listener. spawn() emits ENOENT/EACCES
85
64
  * asynchronously via the 'error' event (not as a throw), so an unlistened spawn
86
65
  * can crash the parent as an uncaught exception. taskkill is a standard Windows
87
66
  * binary so this is defensive, but the listener keeps failures bounded.
88
67
  */
89
- function spawnTaskkillSafe(pid: number): void {
90
- const taskkillChild = spawn("taskkill", ["/pid", String(pid), "/t", "/f"], {
91
- stdio: "ignore",
92
- windowsHide: true,
93
- });
94
- taskkillChild.on("error", (err) => {
95
- logInternalError("child-pi.taskkill-spawn-error", err instanceof Error ? err : new Error(String(err)), `pid=${pid}`);
96
- });
97
- }
98
-
99
- export function killProcessPid(pid: number): void {
100
- if (!Number.isInteger(pid) || pid <= 0) return;
101
- try {
102
- if (process.platform === "win32") {
103
- // 3.8: Windows path uses taskkill /T /F (force kill the entire tree).
104
- // taskkill itself can silently fail (PID gone, permission denied, etc.)
105
- // so verify after 2s and log a warning if the process is still alive.
106
- spawnTaskkillSafe(pid);
107
- const verifyTimer = setTimeout(() => {
108
- try {
109
- process.kill(pid, 0); // throws ESRCH when dead
110
- // Still alive — log and retry once.
111
- logInternalError(
112
- "child-pi.taskkill-stuck",
113
- new Error(`process ${pid} still alive 2s after taskkill /T /F; retrying`),
114
- `pid=${pid}`,
115
- "error",
116
- );
117
- try {
118
- spawnTaskkillSafe(pid);
119
- } catch {
120
- /* best-effort */
121
- }
122
- } catch {
123
- // ESRCH or EPERM — process is gone. OK.
124
- }
125
- }, 2000);
126
- verifyTimer.unref();
127
- return;
128
- }
129
- try {
130
- process.kill(-pid, "SIGTERM");
131
- } catch (error) {
132
- logInternalError("child-pi.sigterm", error, `pid=${pid}`);
133
- try {
134
- process.kill(pid, "SIGTERM");
135
- } catch (fallbackError) {
136
- logInternalError("child-pi.sigterm-absolute", fallbackError, `pid=${pid}`);
137
- }
138
- }
139
- clearHardKillTimer(pid);
140
- const hardKillTimer = setTimeout(() => {
141
- try {
142
- process.kill(-pid, "SIGKILL");
143
- } catch (error) {
144
- logInternalError("child-pi.sigkill", error, `pid=${pid}`);
145
- try {
146
- process.kill(pid, "SIGKILL");
147
- } catch (fallbackError) {
148
- logInternalError("child-pi.sigkill-absolute", fallbackError, `pid=${pid}`);
149
- }
150
- }
151
- childHardKillTimers.delete(pid);
152
- }, HARD_KILL_MS);
153
- hardKillTimer.unref();
154
- childHardKillTimers.set(pid, hardKillTimer);
155
- } catch (error) {
156
- logInternalError("child-pi.kill-process-pid", error, `pid=${pid}`);
157
- }
158
- }
159
-
160
- function killProcessTree(pid: number | undefined, child?: ChildProcess): void {
161
- // Phase-0 diagnostic (HB-003a): capture who invoked killProcessTree so the
162
- // exit-null race has a provenance trail. .stack is best-effort (may be undefined
163
- // under deep async), so we take a snapshot lazily.
164
- try {
165
- const callerStack = new Error("killProcessTree caller").stack ?? "(no stack)";
166
- logInternalError(
167
- "child-pi.kill-process-tree-invoked",
168
- new Error(`pid=${pid} called from:\n${callerStack.split("\n").slice(0, 8).join("\n")}`),
169
- `pid=${pid}`,
170
- );
171
- } catch {
172
- /* diagnostic best-effort */
173
- }
174
- if (!pid || !Number.isInteger(pid) || pid <= 0) return;
175
- if (child && child.exitCode !== null) return;
176
- killProcessPid(pid);
177
- child?.once("exit", () => clearHardKillTimer(pid));
178
- }
179
-
180
- export function terminateActiveChildPiProcesses(): number {
181
- const entries = [...activeChildProcesses.entries()];
182
- for (const [pid, child] of entries) killProcessTree(pid, child);
183
- return entries.length;
184
- }
185
68
 
186
69
  /** Structured lifecycle event emitted by child-pi for critical transitions. */
187
70
  export interface ChildPiLifecycleEvent {
@@ -287,570 +170,16 @@ export interface ChildPiRunResult {
287
170
  }
288
171
 
289
172
  // Base allowlist of non-provider env vars always passed to child workers.
290
- // Provider API keys are injected dynamically via buildScopedAllowList() only
291
- // when a model is assigned to the task (per-task key scoping).
292
- const BASE_ALLOWLIST: string[] = [
293
- "PATH",
294
- "HOME",
295
- "USER",
296
- "SHELL",
297
- "TERM",
298
- "LANG",
299
- "LC_ALL",
300
- "LC_COLLATE",
301
- "LC_CTYPE",
302
- "LC_MESSAGES",
303
- "LC_MONETARY",
304
- "LC_NUMERIC",
305
- "LC_TIME",
306
- "XDG_CONFIG_HOME",
307
- "XDG_DATA_HOME",
308
- "XDG_CACHE_HOME",
309
- "XDG_RUNTIME_DIR",
310
- // Windows essentials — see WINDOWS_ESSENTIAL_ENV_VARS (src/utils/env-allowlist.ts).
311
- ...WINDOWS_ESSENTIAL_ENV_VARS,
312
- "NVM_BIN",
313
- "NVM_DIR",
314
- "NVM_INC",
315
- "NODE_DISABLE_COLORS",
316
- "NODE_EXTRA_CA_CERTS",
317
- "NPM_CONFIG_REGISTRY",
318
- "NPM_CONFIG_USERCONFIG",
319
- "NPM_CONFIG_GLOBALCONFIG",
320
- "PI_CREW_DEPTH",
321
- "PI_CREW_MAX_DEPTH",
322
- "PI_CREW_INHERIT_PROJECT_CONTEXT",
323
- "PI_CREW_INHERIT_SKILLS",
324
- "PI_CREW_KIND",
325
- "PI_CREW_PARENT_PID",
326
- "PI_TEAMS_DEPTH",
327
- "PI_TEAMS_MAX_DEPTH",
328
- "PI_TEAMS_INHERIT_PROJECT_CONTEXT",
329
- "PI_TEAMS_INHERIT_SKILLS",
330
- "PI_TEAMS_PI_BIN",
331
- "PI_TEAMS_MOCK_CHILD_PI",
332
- "PI_CREW_ALLOW_MOCK",
333
- "PI_CREW_MAX_OUTPUT",
334
- "PI_CREW_STEERING_FILE",
335
- ];
336
-
337
- export function buildChildPiSpawnOptions(cwd: string, env: NodeJS.ProcessEnv, model?: string): SpawnOptions {
338
- // SECURITY FIX (Issue #1): Validate cwd before passing to spawn.
339
- // If cwd comes from an untrusted source (user input, workspace config), a malicious cwd
340
- // could cause the child process to operate in an attacker-controlled directory,
341
- // enabling path traversal attacks, unintended file access, or exposure of sensitive paths.
342
- // Use realpathSync to resolve any symlinks and verify the path exists and is a directory.
343
- let validatedCwd: string;
344
- try {
345
- validatedCwd = fs.realpathSync(cwd);
346
- const stats = fs.statSync(validatedCwd);
347
- if (!stats.isDirectory()) {
348
- throw new Error(`cwd is not a directory: ${cwd}`);
349
- }
350
- } catch (error) {
351
- // If cwd doesn't exist (ENOENT) and isn't a security concern, fall back
352
- // to the lexical path. The child process will create the directory if
353
- // needed. Throwing would break tests/callers that pass not-yet-existing
354
- // paths and isn't a security issue for the env-filtering behavior this
355
- // function is primarily about.
356
- if ((error as NodeJS.ErrnoException).code === "ENOENT" && error instanceof Error && error.message.includes("ENOENT")) {
357
- validatedCwd = path.resolve(cwd);
358
- } else {
359
- throw new Error(`Invalid cwd: ${cwd} — ${error instanceof Error ? error.message : String(error)}`);
360
- }
361
- }
362
-
363
- // Filter out env vars whose keys match secret patterns to avoid leaking credentials to child processes.
364
- // IMPORTANT: preserve model provider API keys — they are needed by the child Pi to call the LLM.
365
- // Also preserve essential non-secret vars (PATH, HOME, USER, etc.) so the child process can function.
366
- // Bug #12 fix: essential env vars (PATH, HOME, etc.) are always preserved so child can find npm/node.
367
- //
368
- // PER-TASK KEY SCOPING: when a model is provided, only the env keys for that
369
- // provider are injected (via buildScopedAllowList). When no model is given,
370
- // only BASE_ALLOWLIST system vars pass through — no provider keys leak.
371
- const allowList = model ? buildScopedAllowList(BASE_ALLOWLIST, [model]) : BASE_ALLOWLIST;
372
- const filteredEnv = sanitizeEnvSecrets(env, { allowList });
373
- // FIX: Removed delete workarounds — with explicit allowlist, these vars
374
- // are no longer auto-leaked. The wildcard approach was fragile.
375
-
376
- // SECURITY FIX (Issue #1): Validate NODE_PATH to ensure it only contains standard
377
- // system locations or legitimate user paths (NVM). NODE_PATH can reveal user
378
- // environment information and could theoretically be exploited if it contains
379
- // untrusted entries. Only allow paths under standard system directories
380
- // (/opt, /lib, /usr) or NVM paths under /home/<user>/.nvm/... which are legitimate
381
- // for Node.js module loading in user environments.
382
- if (filteredEnv.NODE_PATH) {
383
- const validPrefixes = ["/opt/", "/lib/", "/usr/local/", "/usr/", "/home/"];
384
- const validPaths = filteredEnv.NODE_PATH.split(":").filter((p) => {
385
- return validPrefixes.some((prefix) => p.startsWith(prefix));
386
- });
387
- if (validPaths.length > 0) {
388
- filteredEnv.NODE_PATH = validPaths.join(":");
389
- } else {
390
- // No standard paths found — remove NODE_PATH entirely to avoid
391
- // passing user-specific paths that could reveal environment info.
392
- delete filteredEnv.NODE_PATH;
393
- }
394
- }
395
-
396
- return {
397
- cwd: validatedCwd,
398
- env: { ...filteredEnv, PI_CREW_PARENT_PID: String(process.pid) },
399
- stdio: ["ignore", "pipe", "pipe"], // stdin=ignore: child doesn't wait for input; task comes via CLI args
400
- detached: process.platform !== "win32",
401
- setsid: true,
402
- // NOTE: setsid creates a new session; the child process becomes the session leader
403
- // and its parent becomes that session leader (still the team-runner in the same
404
- // process group). PI_CREW_PARENT_PID is set before spawn using process.pid (team-runner).
405
- // The parent-guard in the child checks direct parent liveness via process.kill(pid, 0) —
406
- // it does NOT follow the lineage beyond the direct parent. If the team-runner's parent
407
- // (the original pi session) dies, the team-runner becomes an orphan but the child still
408
- // sees its direct parent (team-runner) as alive. This is correct for the parent-guard model.
409
- windowsHide: true,
410
- } as SpawnOptions;
411
- }
412
-
413
- function appendTranscript(input: ChildPiRunInput, line: string): void {
414
- if (!input.transcriptPath) return;
415
- // SECURITY FIX (Issue #1): Validate transcriptPath against artifactsRoot to prevent
416
- // arbitrary file writes and symlink traversal attacks. An attacker who can influence
417
- // the task graph could set transcriptPath to /etc/passwd or similar, and mkdirSync
418
- // with recursive:true would create parent directories. Additionally, appendFileSync
419
- // follows symlinks, potentially writing to sensitive files.
420
- let safePath: string;
421
- try {
422
- const artifactsRoot = input.artifactsRoot ?? input.cwd;
423
- safePath = resolveRealContainedPath(artifactsRoot, input.transcriptPath);
424
- } catch (error) {
425
- logInternalError("child-pi.transcript-path-rejected", error as Error, `transcriptPath=${input.transcriptPath}`);
426
- return;
427
- }
428
- // Use O_NOFOLLOW | O_CREAT | O_APPEND to safely open the transcript file.
429
- // O_NOFOLLOW prevents symlink attacks (refuses to follow symlinks).
430
- // O_CREAT creates the file if it doesn't exist.
431
- // O_APPEND atomically positions at end for each write (no seek race).
432
- // O_EXCL was previously used but prevented appending to existing files,
433
- // causing EBADF on subsequent writes.
434
- // NOTE: Parent directory must already exist (caller's responsibility).
435
- // We skip mkdirSync here for security — adding it would create parent
436
- // directories during validation, contradicting the original design where
437
- // resolveRealContainedPath validates a pre-existing path.
438
- // Async optimization: use fire-and-forget async write to avoid blocking the event loop.
439
- // The caller does not need to await this — transcript writes are best-effort telemetry.
440
- // OPT-06 follow-up: lines are buffered in a module-scoped Map and flushed
441
- // periodically (50ms debounce) or on lifecycle boundaries (ChildPiLineObserver.flush,
442
- // runChildPi settle). Without that drain, callers that immediately read the
443
- // transcript file post-flush (e.g. integration tests at phase3-runtime:50 and
444
- // phase4-runtime:37/:68/:103) would see ENOENT or empty content because the
445
- // async file handle had not yet been opened / flushed.
446
- trackTranscriptWrite(safePath, line);
447
- }
448
-
449
- /** Async version of appendTranscript — fire-and-forget for non-blocking writes. */
450
- // ── Transcript batch buffer (OPT-PHASE3) ────────────────────────────────
451
- // Instead of open/write/close per line (3 syscalls × N), accumulate lines
452
- // in a module-scoped buffer and flush them in one open/write/close per path
453
- // every TRANSCRIPT_FLUSH_MS. Lifecycle boundaries (observer.flush, settle)
454
- // force-flush the buffer before returning so transcript reads are complete.
455
- //
456
- // Ordering: lines are appended to the per-path array in call order. The flush
457
- // writes the joined array, preserving intra-batch ordering. Inter-batch
458
- // ordering is not guaranteed but transcript is append-only telemetry.
459
- //
460
- // Security: O_NOFOLLOW | O_CREAT | O_APPEND flags preserved on every flush.
461
- const transcriptBatches = new Map<string, string[]>();
462
- let transcriptFlushTimer: ReturnType<typeof setTimeout> | undefined;
463
- const TRANSCRIPT_FLUSH_MS = 50;
464
-
465
- function scheduleTranscriptFlush(): void {
466
- if (transcriptFlushTimer) return;
467
- transcriptFlushTimer = setTimeout(() => {
468
- transcriptFlushTimer = undefined;
469
- void flushTranscriptBatches();
470
- }, TRANSCRIPT_FLUSH_MS);
471
- transcriptFlushTimer.unref?.();
472
- }
473
-
474
- async function flushTranscriptBatches(): Promise<void> {
475
- const entries = [...transcriptBatches.entries()];
476
- transcriptBatches.clear();
477
- await Promise.allSettled(
478
- entries.map(async ([safePath, lines]) => {
479
- if (lines.length === 0) return;
480
- const content = lines.join("");
481
- try {
482
- const fd = await fs.promises.open(
483
- safePath,
484
- fs.constants.O_WRONLY | fs.constants.O_NOFOLLOW | fs.constants.O_CREAT | fs.constants.O_APPEND,
485
- 0o600,
486
- );
487
- try {
488
- await fd.write(content, undefined, "utf-8");
489
- } finally {
490
- await fd.close();
491
- }
492
- } catch (error) {
493
- logInternalError("child-pi.transcript-write-failed", error as Error, `path=${safePath}`);
494
- }
495
- }),
496
- );
497
- }
498
-
499
- function trackTranscriptWrite(safePath: string, line: string): void {
500
- const content = `${redactJsonLine(line)}\n`;
501
- let batch = transcriptBatches.get(safePath);
502
- if (!batch) {
503
- batch = [];
504
- transcriptBatches.set(safePath, batch);
505
- }
506
- batch.push(content);
507
- scheduleTranscriptFlush();
508
- }
509
-
510
- /**
511
- * Drain the transcript batch buffer and await any remaining in-flight writes.
512
- * Called by lifecycle boundaries (ChildPiLineObserver.flush, runChildPi settle)
513
- * so that transcript files are complete before callers read them.
514
- *
515
- * Uses a while loop to re-check the buffer after each flush — new lines may
516
- * arrive during the async I/O window (trackTranscriptWrite → scheduleTranscriptFlush).
517
- *
518
- * Exported so external callers (e.g. integration tests that construct a
519
- * ChildPiLineObserver directly) can drain explicitly if they need to read
520
- * the transcript file outside of the observer's lifecycle.
521
- */
522
- export async function flushPendingTranscriptWrites(): Promise<void> {
523
- // Force-flush the buffer synchronously (clear timer, write immediately).
524
- if (transcriptFlushTimer) {
525
- clearTimeout(transcriptFlushTimer);
526
- transcriptFlushTimer = undefined;
527
- }
528
- // Re-check loop: new lines may be appended to transcriptBatches during
529
- // the async flushTranscriptBatches I/O. Loop until the buffer is empty.
530
- while (transcriptBatches.size > 0) {
531
- await flushTranscriptBatches();
532
- }
533
- }
534
-
535
- /**
536
- * Reset the module-scoped transcript batch state. Exported for test isolation
537
- * only — production code should never call this.
538
- */
539
- export function resetTranscriptBatchState(): void {
540
- if (transcriptFlushTimer) {
541
- clearTimeout(transcriptFlushTimer);
542
- transcriptFlushTimer = undefined;
543
- }
544
- transcriptBatches.clear();
545
- }
546
-
547
- export function compactString(value: string, maxChars = MAX_COMPACT_CONTENT_CHARS, opts: { preserveImportant?: boolean } = {}): string {
548
- if (value.length <= maxChars) return value;
549
- // L4: head + tail instead of head-only. Keeps closing markdown structure
550
- // (code fences, headings, list tails) instead of dropping them — the old
551
- // head-only slice left unclosed ``` fences that downstream parsers and
552
- // output-validator.ts flagged as "output may be truncated". Head gets 75%
553
- // (opening structure + bulk of content); tail gets 25% (closing structure).
554
- // P0-A: compose the value through the stage-chain compression pipeline.
555
- // The default pipeline is just [TruncationStage] (single-stage, equivalent
556
- // to the pre-P0-A implementation) so plain text with no ANSI / no blank
557
- // runs / no consecutive duplicates produces bit-identical output (L4
558
- // regression safety). Callers that want noise stripping can opt into
559
- // additional stages via the pipeline — but compactString's caller surface
560
- // keeps the simple `(value, maxChars, opts)` signature.
561
- // P0-B: the TruncationStage scans the middle slice for important diagnostic
562
- // lines (error, file:line, HTTP 4xx/5xx, compiler codes) and preserves them
563
- // within a 15% slack budget. The `preserveImportant` opt propagates here.
564
- const result = applyCompactPipeline(value, [
565
- new TruncationStage(maxChars, {
566
- preserveImportant: opts.preserveImportant,
567
- }),
568
- ]);
569
- return result.text;
570
- }
571
-
572
- export function compactValue(value: unknown): unknown {
573
- if (typeof value === "string") return compactString(value);
574
- if (Array.isArray(value)) {
575
- // BUG-4: silent .slice(0, 20) lost items 21-50 with no marker.
576
- // Append a truncation marker when entries are dropped so downstream
577
- // consumers know data was elided (consistent with compactString style).
578
- if (value.length > 20) {
579
- return [...value.slice(0, 20).map(compactValue), `[pi-crew truncated ${value.length - 20} entries]`];
580
- }
581
- return value.map(compactValue);
582
- }
583
- const record = asRecord(value);
584
- if (!record) return value;
585
- const entries = Object.entries(record);
586
- const compacted: Record<string, unknown> = {};
587
- for (const [key, entry] of entries.slice(0, 20)) compacted[key] = compactValue(entry);
588
- // BUG-4: mark elided object keys so consumers know data was dropped.
589
- if (entries.length > 20) compacted["[truncated]"] = `${entries.length - 20} entries`;
590
- return compacted;
591
- }
592
-
593
- function compactContentPart(part: unknown): unknown | undefined {
594
- const record = asRecord(part);
595
- if (!record) return undefined;
596
- if (record.type === "text")
597
- return {
598
- type: "text",
599
- text:
600
- typeof record.text === "string"
601
- ? compactString(record.text, MAX_ASSISTANT_TEXT_CHARS, {
602
- preserveImportant: false,
603
- })
604
- : "",
605
- };
606
- if (record.type === "toolCall")
607
- return {
608
- type: "toolCall",
609
- name: record.name,
610
- input: compactValue(typeof record.input === "string" ? compactString(record.input, MAX_TOOL_INPUT_CHARS) : record.input),
611
- };
612
- if (record.type === "toolResult")
613
- return {
614
- type: "toolResult",
615
- name: record.name,
616
- content: compactValue(
617
- typeof record.content === "string" ? compactString(record.content, MAX_TOOL_RESULT_CHARS) : record.content,
618
- ),
619
- };
620
- return undefined;
621
- }
622
-
623
- function compactChildPiEvent(event: unknown): unknown | undefined {
624
- const record = asRecord(event);
625
- if (!record) return undefined;
626
- if (record.type === "message_update") return undefined;
627
- if (record.type === "tool_execution_start" || record.type === "tool_execution_end") {
628
- return {
629
- type: record.type,
630
- toolName: record.toolName,
631
- args: record.args,
632
- };
633
- }
634
- if (record.type === "tool_result_end" || record.type === "message_end" || record.type === "message") {
635
- const message = asRecord(record.message);
636
- if (message?.role === "user" || message?.role === "system") return undefined;
637
- const content = Array.isArray(message?.content)
638
- ? message.content.map(compactContentPart).filter((part) => part !== undefined)
639
- : undefined;
640
- return {
641
- type: record.type,
642
- ...(typeof record.text === "string" ? { text: record.text } : {}),
643
- ...(message
644
- ? {
645
- message: {
646
- role: message.role,
647
- ...(content ? { content } : {}),
648
- usage: message.usage,
649
- model: message.model,
650
- errorMessage: message.errorMessage,
651
- stopReason: message.stopReason,
652
- },
653
- }
654
- : {}),
655
- usage: record.usage,
656
- model: record.model,
657
- provider: record.provider,
658
- stopReason: record.stopReason,
659
- };
660
- }
661
- return record.type ? { type: record.type } : undefined;
662
- }
663
-
664
- function displayTextFromCompactEvent(event: unknown): string | undefined {
665
- const record = asRecord(event);
666
- if (!record) return undefined;
667
- if (record.type === "tool_execution_start") {
668
- return typeof record.toolName === "string" ? `tool: ${record.toolName}` : "tool started";
669
- }
670
- if (record.type !== "message" && record.type !== "message_end") return undefined;
671
- const message = asRecord(record.message);
672
- if (message?.role !== undefined && message.role !== "assistant") return undefined;
673
- const content = Array.isArray(message?.content) ? message.content : [];
674
- const text = content
675
- .flatMap((part) => {
676
- const item = asRecord(part);
677
- return item?.type === "text" && typeof item.text === "string" ? [item.text] : [];
678
- })
679
- .join("\n")
680
- .trim();
681
- return text || (typeof record.text === "string" ? record.text : undefined);
682
- }
683
-
684
- function nonJsonLineResult(line: string): {
685
- persistedLine: string;
686
- event?: unknown;
687
- displayLine?: string;
688
- json: boolean;
689
- } {
690
- return { json: false, persistedLine: line, displayLine: line };
691
- }
692
-
693
- function compactChildPiLine(
694
- line: string,
695
- preParsed?: unknown,
696
- ): {
697
- persistedLine: string;
698
- event?: unknown;
699
- displayLine?: string;
700
- json: boolean;
701
- } {
702
- // OPT-PHASE2: when the caller (emitLine) already parsed the line, pass the
703
- // result via preParsed to avoid a redundant JSON.parse. Standalone callers
704
- // without a preParsed fall back to their own parse+catch (DRY: single
705
- // compact+return path for both branches).
706
- let parsed: unknown;
707
- if (preParsed !== undefined) {
708
- parsed = preParsed;
709
- } else {
710
- try {
711
- parsed = JSON.parse(line);
712
- } catch {
713
- return nonJsonLineResult(line);
714
- }
715
- }
716
- const compact = compactChildPiEvent(parsed);
717
- return {
718
- json: true,
719
- event: compact,
720
- persistedLine: compact ? JSON.stringify(compact) : "",
721
- displayLine: displayTextFromCompactEvent(compact),
722
- };
723
- }
724
-
725
- export class ChildPiLineObserver {
726
- private buffer = "";
727
- private readonly input: ChildPiRunInput;
728
- /** F9: bounded ring buffer for RAW assistant-text fragments. Consumers
729
- * (getRawFinalText) only read the last element, but the legacy implementation
730
- * accumulated every fragment unconditionally, which let a verbose/long-running
731
- * worker grow this array linearly with output. We retain the last 2 entries:
732
- * the consumer needs the last; we keep the second-to-last only as a defensive
733
- * fence against a race where a final event arrives just after the consumer
734
- * read (the previous "last" is still the most-recent pre-final text in that
735
- * window). 2 is well below any plausible consumer's "tail-only" need while
736
- * bounding memory. */
737
- private static readonly MAX_RAW_TEXT_EVENTS = 2;
738
- private readonly rawTextEvents: string[] = [];
739
- /** F9: bounded ring buffer for intermediate findings. The downstream digest
740
- * (getIntermediateFindings) slices the last 20, but the array previously grew
741
- * to 1000s of entries. We keep MAX_INTERMEDIATE_DIGEST_LINES + headroom so
742
- * the public API behaviour is preserved (still returns "last 20 lines"). */
743
- private static readonly MAX_INTERMEDIATE_FINDINGS = 32;
744
- private readonly intermediateFindings: string[] = [];
745
-
746
- constructor(input: ChildPiRunInput) {
747
- this.input = input;
748
- }
749
-
750
- observe(text: string): void {
751
- this.buffer += text;
752
- const lines = this.buffer.split(/\r?\n/);
753
- this.buffer = lines.pop() ?? "";
754
- for (const line of lines) this.emitLine(line);
755
- }
756
-
757
- flush(): Promise<void> {
758
- if (this.buffer) {
759
- const line = this.buffer;
760
- this.buffer = "";
761
- this.emitLine(line);
762
- }
763
- // OPT-06 follow-up: appendTranscript is fire-and-forget async, so the file
764
- // may not exist on disk by the time this returns. Drain the module-scoped
765
- // transcript batch buffer before resolving so callers that immediately read the
766
- // transcript file (e.g. integration tests at phase4-runtime:37/:68/:103
767
- // after `await observer.flush()`) see the full content.
768
- return flushPendingTranscriptWrites();
769
- }
770
-
771
- /** Last non-empty RAW assistant text (mirrors {@link parsePiJsonOutput}'s
772
- * finalText semantics but uncapped). Undefined when no assistant text was
773
- * seen by this observer. {@link extractText} already drops empty fragments,
774
- * so the last entry is the final assistant utterance. */
775
- getRawFinalText(): string | undefined {
776
- return this.rawTextEvents.length > 0 ? this.rawTextEvents[this.rawTextEvents.length - 1] : undefined;
777
- }
778
-
779
- /** #7 hardening: returns a bounded digest of intermediate findings accumulated
780
- * during the run. This is NOT the final answer — it is a best-effort capture
781
- * of the last assistant text or tool-result display lines before budget
782
- * exhaustion. Only populated when getRawFinalText() would return undefined.
783
- * @param maxChars - maximum total characters to return (default 500). */
784
- getIntermediateFindings(maxChars = 500): string {
785
- const MAX_INTERMEDIATE_DIGEST_LINES = 20;
786
- if (this.intermediateFindings.length === 0) return "";
787
- // Take the last N lines and join, then cap.
788
- const lines = this.intermediateFindings.slice(-MAX_INTERMEDIATE_DIGEST_LINES);
789
- const joined = lines.join("\n");
790
- if (joined.length <= maxChars) return joined;
791
- // Return the tail within the budget.
792
- return joined.slice(-maxChars);
793
- }
794
-
795
- private emitLine(line: string): void {
796
- if (!line.trim()) return;
797
- // OPT-PHASE2: parse the line EXACTLY ONCE. The parsed value feeds both
798
- // (a) raw assistant-text extraction for the authoritative result and
799
- // (b) compaction for the telemetry transcript — previously each path
800
- // called JSON.parse independently (2 parses/line). When the line is not
801
- // valid JSON, parsed stays undefined and compactChildPiLine runs its own
802
- // catch path to produce the json:false fallback.
803
- let parsed: unknown;
804
- try {
805
- parsed = JSON.parse(line);
806
- } catch {
807
- parsed = undefined;
808
- }
809
- if (parsed !== undefined) {
810
- const rawTexts = extractText(parsed);
811
- if (rawTexts.length > 0) {
812
- // F9: trim from the front if the push would exceed the cap. Slice's
813
- // second arg excludes the index, so this drops the oldest entries
814
- // while keeping the freshly pushed tail.
815
- this.rawTextEvents.push(...rawTexts);
816
- const rawOverflow = this.rawTextEvents.length - ChildPiLineObserver.MAX_RAW_TEXT_EVENTS;
817
- if (rawOverflow > 0) this.rawTextEvents.splice(0, rawOverflow);
818
- // Also capture raw assistant text as intermediate findings — the last raw
819
- // text may be a partial answer before the worker ran out of budget.
820
- const last = rawTexts[rawTexts.length - 1];
821
- if (last.trim().length > 0) {
822
- this.intermediateFindings.push(last.trim());
823
- const findingsOverflow = this.intermediateFindings.length - ChildPiLineObserver.MAX_INTERMEDIATE_FINDINGS;
824
- if (findingsOverflow > 0) this.intermediateFindings.splice(0, findingsOverflow);
825
- }
826
- }
827
- }
828
- // OPT-PHASE2: construct the non-JSON fallback directly when parsing failed,
829
- // so a broken line triggers exactly ONE (failed) parse instead of two.
830
- const compact = parsed !== undefined ? compactChildPiLine(line, parsed) : nonJsonLineResult(line);
831
- if (compact.event !== undefined) {
832
- try {
833
- this.input.onJsonEvent?.(compact.event);
834
- } catch (error) {
835
- logInternalError("child-pi.on-json-event", error, `line=${compact.persistedLine ?? compact.displayLine ?? ""}`);
836
- }
837
- }
838
- if (compact.persistedLine) appendTranscript(this.input, compact.persistedLine);
839
- if (compact.displayLine?.trim()) {
840
- try {
841
- this.input.onStdoutLine?.(compact.displayLine);
842
- } catch (error) {
843
- logInternalError("child-pi.on-stdout-line", error, `line=${compact.displayLine}`);
844
- }
845
- // #7 hardening: capture display lines (tool results, stdout) as intermediate
846
- // findings. This ensures we capture tool output even when no assistant text
847
- // is emitted (budget exhausted on tool calls).
848
- this.intermediateFindings.push(compact.displayLine!.trim());
849
- const findingsOverflow = this.intermediateFindings.length - ChildPiLineObserver.MAX_INTERMEDIATE_FINDINGS;
850
- if (findingsOverflow > 0) this.intermediateFindings.splice(0, findingsOverflow);
851
- }
852
- }
853
- }
173
+ // ── Transcript batching + compaction (H-7 decomposition step 1) ────────
174
+ // Extracted to ./child-pi-transcript.ts. Re-exported here to preserve the
175
+ // existing public API surface.
176
+ export {
177
+ appendTranscript,
178
+ compactString,
179
+ compactValue,
180
+ flushPendingTranscriptWrites,
181
+ resetTranscriptBatchState,
182
+ } from "./child-pi-transcript.ts";
854
183
 
855
184
  /** Mock-only path — real code path reuses a single observer.
856
185
  * OPT-06 follow-up: returns a Promise so callers can await the transcript
@@ -869,7 +198,7 @@ function asRecord(value: unknown): Record<string, unknown> | undefined {
869
198
 
870
199
  function isFinalAssistantEvent(event: unknown): boolean {
871
200
  const obj = asRecord(event);
872
- if (!obj || obj.type !== "message_end") return false;
201
+ if (obj?.type !== "message_end") return false;
873
202
  const message = asRecord(obj.message);
874
203
  const role = message?.role;
875
204
  if (role !== undefined && role !== "assistant") return false;
@@ -1002,7 +331,7 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1002
331
  }
1003
332
  count += 1;
1004
333
  try {
1005
- fs.writeFileSync(counterFile, String(count));
334
+ atomicWriteFile(counterFile, String(count));
1006
335
  } catch (error) {
1007
336
  logInternalError("child-pi.mock-counter-write", error as Error, `file=${counterFile}`);
1008
337
  }
@@ -1035,64 +364,25 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1035
364
  }
1036
365
  return { exitCode: 1, stdout: "", stderr: `[MOCK] failure: ${mock}` };
1037
366
  }
1038
- const built = buildPiWorkerArgs({
1039
- task: effectiveTask,
1040
- agent: input.agent,
1041
- model: input.model,
1042
- sessionEnabled: true,
1043
- maxDepth: input.maxDepth,
1044
- skillPaths: input.skillPaths,
1045
- role: input.role,
1046
- });
1047
- // Pass steering file path to child for real-time steer injection
1048
- if (input.steeringFile) built.env.PI_CREW_STEERING_FILE = input.steeringFile;
1049
- // B5: if the parent already aborted before we spawn, do not start the child
1050
- // at all. Spawning a doomed process wastes resources, and the abort listener
1051
- // registered below will not re-fire for an already-aborted signal (so the
1052
- // child would only be killed later by the response-timeout path). Return a
1053
- // cancelled-style result immediately.
1054
- if (input.signal?.aborted) {
1055
- return {
1056
- exitCode: null,
1057
- stdout: "",
1058
- stderr: "",
1059
- error: "Aborted before spawn (parent AbortSignal already aborted)",
1060
- aborted: true,
1061
- };
1062
- }
1063
- const spawnSpec = getPiSpawnCommand(built.args);
367
+ // H-7 step 6: spawn/env/args preparation extracted to child-pi-spawn.ts.
368
+ // prepareSpawnContext builds the worker args, attaches the steering file env,
369
+ // and handles the pre-spawn abort check (returns an immediate-abort result
370
+ // if the parent signal has already fired).
371
+ const spawnPrep = prepareSpawnContext(input, effectiveTask);
372
+ if (spawnPrep.kind === "aborted") return spawnPrep.result;
373
+ const { spawnSpec, mergedEnv, tempDir, builtEnv } = spawnPrep.ctx;
1064
374
  try {
1065
375
  return await new Promise<ChildPiRunResult>((resolve) => {
1066
- // SECURITY (Issue #3): built.env contains only PI_CREW_* execution-control vars (NOT secrets).
1067
- // It is safe to spread built.env after process.env because sanitizeEnvSecrets will filter
1068
- // any secret values before the env reaches spawn(). However, if built.env ever gains
1069
- // secret content without corresponding allowlist filtering, secrets would leak to children.
1070
- // This comment serves as a warning: built.env must never contain secret values.
1071
- //
1072
- // Runtime assertion: verify all built.env keys are execution-control vars (PI_CREW_* or PI_TEAMS_*).
1073
- // This is a canary for future regressions — if someone accidentally adds a secret key to
1074
- // built.env, the assertion will throw before the secret reaches the child process.
1075
- for (const key of Object.keys(built.env)) {
1076
- if (!key.startsWith("PI_CREW_") && !key.startsWith("PI_TEAMS_")) {
1077
- throw new Error(
1078
- `SECURITY: built.env contains unexpected key "${key}"; expected only PI_CREW_* or PI_TEAMS_* execution-control vars`,
1079
- );
1080
- }
1081
- }
1082
- const child = spawn(
1083
- spawnSpec.command,
1084
- spawnSpec.args,
1085
- buildChildPiSpawnOptions(
1086
- input.cwd,
1087
- {
1088
- ...process.env,
1089
- ...built.env,
1090
- },
1091
- input.model,
1092
- ),
1093
- );
376
+ // Runtime canary: verify built.env doesn't accidentally contain
377
+ // secret keys. We assert on builtEnv (not mergedEnv) because mergedEnv
378
+ // contains ALL process.env keys (PATH, HOME, SHELL, etc.) which is
379
+ // expected; those are filtered by the allowlist in buildChildPiSpawnOptions
380
+ // before reaching the child. The canary guards against accidental
381
+ // additions to built.env leaking secrets to children.
382
+ assertOnlyControlEnvKeys(builtEnv);
383
+ const child = spawn(spawnSpec.command, spawnSpec.args, buildChildPiSpawnOptions(input.cwd, mergedEnv, input.model));
1094
384
  if (child.pid) {
1095
- activeChildProcesses.set(child.pid, child);
385
+ registerActiveChild(child.pid, child);
1096
386
  input.onSpawn?.(child.pid);
1097
387
  input.onLifecycleEvent?.({
1098
388
  type: "spawned",
@@ -1151,7 +441,7 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1151
441
  let abortRequested = input.signal?.aborted === true;
1152
442
  let hardKilled = false;
1153
443
  const cleanupErrors: string[] = [];
1154
- let turnCount = 0;
444
+ const steeringController = new ChildPiSteeringController(input.maxTurns, input.graceTurns);
1155
445
  // Track in-flight operations for proper rejection on unexpected exit
1156
446
  interface PendingOperation {
1157
447
  id: string;
@@ -1182,14 +472,12 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1182
472
  pendingOperations.clear();
1183
473
  };
1184
474
 
1185
- let softLimitReached = false;
1186
475
  const steerInjectionFailed = false;
1187
- const maxTurns = input.maxTurns;
1188
- // FIX (Issue #1): Bound graceTurns to prevent the hard abort condition from
1189
- // never triggering when an arbitrarily large value is passed.
1190
- let graceTurns = input.graceTurns;
1191
- if (graceTurns !== undefined && graceTurns > 1000) graceTurns = 1000;
1192
476
  let abortDueToParentSignal = false;
477
+ // CP-1: track whether the turn-limit hard-abort has been initiated. Once
478
+ // true, we must NOT restart the no-response timer — the child is already
479
+ // being killed via killProcessTree (SIGTERM → SIGKILL after 3s), and
480
+ // restarting the timer would delay detection of a SIGTERM-ignoring child.
1193
481
  // Round 27 (BUG 4): extract to a named handler so settle() can remove it.
1194
482
  // The previous anonymous listener was never removed → on runs with >10
1195
483
  // tasks sharing one AbortSignal (background-runner), Node emitted
@@ -1280,54 +568,21 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1280
568
  const lineObserver = new ChildPiLineObserver({
1281
569
  ...input,
1282
570
  onStdoutLine: (line) => {
1283
- restartNoResponseTimer();
571
+ if (!steeringController.isHardAbortInitiated()) restartNoResponseTimer();
1284
572
  stdout = appendBoundedTail(stdout, `${line}\n`);
1285
573
  input.onStdoutLine?.(line);
1286
574
  },
1287
575
  onJsonEvent: (event) => {
1288
- restartNoResponseTimer();
576
+ if (!steeringController.isHardAbortInitiated()) restartNoResponseTimer();
1289
577
  const eventOpId = startOperation("json_event");
1290
578
  try {
1291
579
  // Turn-count-based steering: soft limit steer + hard abort after graceTurns
1292
580
  if (event && typeof event === "object" && !Array.isArray(event)) {
1293
581
  const obj = event as Record<string, unknown>;
1294
582
  if (obj.type === "turn_end") {
1295
- turnCount += 1;
1296
- if (maxTurns !== undefined && !softLimitReached && turnCount >= maxTurns) {
1297
- softLimitReached = true;
1298
- // C8: deliver the "wrap up" advisory by appending to the steering JSONL
1299
- // file the child polls (PI_CREW_STEERING_FILE). The child is spawned with
1300
- // stdio:["ignore",...], so child.stdin is null and the old stdin branch was
1301
- // dead code that only spammed logs on every soft-limit hit. Advisory only —
1302
- // the hard-abort below at maxTurns + graceTurns is the real enforcement, so
1303
- // a failed write must NOT kill the worker.
1304
- if (input.steeringFile) {
1305
- try {
1306
- fs.appendFileSync(
1307
- input.steeringFile,
1308
- JSON.stringify({
1309
- type: "steer",
1310
- message:
1311
- "You have reached your turn limit. Wrap up immediately — provide your final answer now.",
1312
- }) + "\n",
1313
- "utf-8",
1314
- );
1315
- } catch (err) {
1316
- logInternalError(
1317
- "child-pi.steer-write-failed",
1318
- err instanceof Error ? err : new Error(String(err)),
1319
- `pid=${child.pid}`,
1320
- );
1321
- }
1322
- }
1323
- } else if (maxTurns !== undefined && softLimitReached && turnCount >= maxTurns + (graceTurns ?? 5)) {
1324
- // Hard abort — terminate after grace turns
1325
- try {
1326
- child.kill(process.platform === "win32" ? undefined : "SIGTERM");
1327
- } catch {
1328
- /* best-effort */
1329
- }
1330
- }
583
+ // H-7 step 5: steering state machine extracted to ChildPiSteeringController.
584
+ const action = steeringController.onTurnEnd(child.pid, child, input.steeringFile);
585
+ if (action.kind === "hardAbort") killProcessTree(action.pid, action.child);
1331
586
  }
1332
587
  }
1333
588
  completeOperation(eventOpId);
@@ -1481,7 +736,7 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1481
736
  input.signal?.removeEventListener("abort", abort);
1482
737
  input.signal?.removeEventListener("abort", onParentAbort);
1483
738
  try {
1484
- cleanupTempDir(built.tempDir);
739
+ cleanupTempDir(tempDir);
1485
740
  } catch (error) {
1486
741
  cleanupErrors.push(error instanceof Error ? error.message : String(error));
1487
742
  }
@@ -1528,7 +783,7 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1528
783
  input.signal?.removeEventListener("abort", abort);
1529
784
  input.signal?.removeEventListener("abort", onParentAbort);
1530
785
  try {
1531
- cleanupTempDir(built.tempDir);
786
+ cleanupTempDir(tempDir);
1532
787
  } catch (error) {
1533
788
  cleanupErrors.push(error instanceof Error ? error.message : String(error));
1534
789
  }
@@ -1607,7 +862,7 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1607
862
  }
1608
863
  };
1609
864
  child.stdout?.on("data", (chunk: Buffer) => {
1610
- restartNoResponseTimer();
865
+ if (!steeringController.isHardAbortInitiated()) restartNoResponseTimer();
1611
866
  const text = chunk.toString("utf-8");
1612
867
  backpressureBytes += text.length;
1613
868
  try {
@@ -1626,7 +881,7 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1626
881
  }
1627
882
  });
1628
883
  child.stderr?.on("data", (chunk: Buffer) => {
1629
- restartNoResponseTimer();
884
+ if (!steeringController.isHardAbortInitiated()) restartNoResponseTimer();
1630
885
  stderr = appendBoundedTail(stderr, chunk.toString("utf-8"));
1631
886
  });
1632
887
  child.on("error", (error) => {
@@ -1671,7 +926,7 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1671
926
  });
1672
927
  child.on("exit", (code, signal) => {
1673
928
  if (child.pid) {
1674
- activeChildProcesses.delete(child.pid);
929
+ unregisterActiveChild(child.pid);
1675
930
  clearHardKillTimer(child.pid);
1676
931
  // Unregister from cleanup handler
1677
932
  unregisterChildProcess(child.pid);
@@ -1732,7 +987,7 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1732
987
  });
1733
988
  child.on("close", (exitCode) => {
1734
989
  if (child.pid) {
1735
- activeChildProcesses.delete(child.pid);
990
+ unregisterActiveChild(child.pid);
1736
991
  clearHardKillTimer(child.pid);
1737
992
  // Unregister from cleanup handler
1738
993
  unregisterChildProcess(child.pid);
@@ -1768,7 +1023,10 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1768
1023
  );
1769
1024
  }
1770
1025
  const finalExitCode = forcedFinalDrain && !timeoutError ? 0 : exitCode;
1771
- const wasGraceAborted = softLimitReached && turnCount >= (maxTurns ?? 0) + (graceTurns ?? 5);
1026
+ const wasGraceAborted =
1027
+ steeringController.isSoftLimitReached() &&
1028
+ steeringController.getTurnCount() >=
1029
+ (steeringController.getMaxTurns() ?? 0) + (steeringController.getGraceTurns() ?? 5);
1772
1030
  const wasParentAborted = abortDueToParentSignal && !wasGraceAborted;
1773
1031
  // steerInjectionFailed is now always false (Phase-1 fix: steer backpressure
1774
1032
  // is logged, not fatal). The steerError branch is retained for safety in
@@ -1793,7 +1051,7 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1793
1051
  ...(timeoutError ? { error: timeoutError.error } : {}),
1794
1052
  ...(steerError ? { error: steerError } : {}),
1795
1053
  aborted: wasGraceAborted || wasParentAborted,
1796
- steered: softLimitReached && !wasGraceAborted,
1054
+ steered: steeringController.isSoftLimitReached() && !wasGraceAborted,
1797
1055
  exitStatus: {
1798
1056
  exitCode: finalExitCode,
1799
1057
  cancelled: abortRequested,
@@ -1809,8 +1067,8 @@ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResu
1809
1067
  } finally {
1810
1068
  // cleanupTempDir is already called inside settle(), but guard against
1811
1069
  // the case where settle() was never reached (spawn throws synchronously).
1812
- if (built.tempDir && fs.existsSync(built.tempDir)) {
1813
- cleanupTempDir(built.tempDir);
1070
+ if (tempDir && fs.existsSync(tempDir)) {
1071
+ cleanupTempDir(tempDir);
1814
1072
  }
1815
1073
  }
1816
1074
  }