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