brl-subagent 2.7.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/AGENT.md +3 -3
  2. package/README.md +18 -10
  3. package/package.json +6 -5
  4. package/src/agent-tools.ts +332 -0
  5. package/src/background-pipeline.ts +1025 -0
  6. package/src/boot-recovery.ts +313 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +26 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +69 -0
  11. package/src/event-bus.ts +10 -0
  12. package/src/git.ts +274 -5
  13. package/src/headstate.ts +471 -0
  14. package/src/history.ts +21 -3
  15. package/src/index.ts +127 -3943
  16. package/src/kill-escalation.ts +87 -7
  17. package/src/loader.ts +47 -1
  18. package/src/logging.ts +1 -1
  19. package/src/mode-prologue.ts +4 -10
  20. package/src/mode-runners.ts +1575 -0
  21. package/src/notify-completion.ts +180 -12
  22. package/src/params.ts +211 -37
  23. package/src/preflight.ts +123 -16
  24. package/src/prelude.ts +92 -7
  25. package/src/presets.ts +85 -18
  26. package/src/proc.ts +2 -3
  27. package/src/project-flags.ts +3 -3
  28. package/src/recovery-engine.ts +11 -1
  29. package/src/recovery-surface.ts +1 -2
  30. package/src/recovery.ts +155 -20
  31. package/src/reports.ts +1 -7
  32. package/src/run-registry.ts +22 -3
  33. package/src/runner.ts +80 -21
  34. package/src/runtime.ts +50 -0
  35. package/src/sanitize.ts +20 -2
  36. package/src/scheduler.ts +1 -2
  37. package/src/schema.ts +37 -7
  38. package/src/scratch-root.ts +909 -0
  39. package/src/scratch-spawn.ts +256 -0
  40. package/src/session-manager.ts +854 -200
  41. package/src/state.ts +130 -30
  42. package/src/templates.ts +42 -17
  43. package/src/terminal-notifier.ts +405 -0
  44. package/src/transcript.ts +1 -1
  45. package/src/tui-format.ts +177 -7
  46. package/src/tui.ts +115 -57
  47. package/src/types.ts +206 -5
  48. package/src/unit-params.ts +113 -0
  49. package/src/unit-run.ts +45 -16
  50. package/src/validate.ts +89 -11
  51. package/src/worktree-report.ts +142 -0
package/src/recovery.ts CHANGED
@@ -31,11 +31,12 @@
31
31
  * ownership cannot be verified.
32
32
  */
33
33
 
34
+ import type { Logger } from "./logging";
34
35
  import { listInflightRuns, type InflightRun } from "./run-registry";
35
36
  import { assertSafeAgentId } from "./sanitize";
36
37
  import { isProcAvailable, defaultRecoveryDeps } from "./proc";
37
- import { decideRecovery, reapPids, type RecoveryDeps, type RecoveryRecord } from "./recovery-engine";
38
- import type { Logger } from "./logging";
38
+ import { decideRecovery, classifyOwner, reapPids, type RecoveryDeps, type RecoveryRecord } from "./recovery-engine";
39
+ import { PROMPT_NEVER_ISSUED_MESSAGE, type SubagentRun } from "./types";
39
40
 
40
41
  // Re-export the pure engine and the production wiring so existing importers
41
42
  // (`index.ts`, the recovery/registry suites) keep their single entry point.
@@ -61,6 +62,14 @@ export interface BootScanSummary {
61
62
  skippedNoOwner: number;
62
63
  /** Registry entries skipped fail-closed because their id failed the write guard. */
63
64
  skippedUnsafeIds: number;
65
+ /**
66
+ * Issue #447: registry entries classified NEVER STARTED (`acceptedAt:
67
+ * null`) and settled `failed` instead of being offered as an interrupted,
68
+ * retryable run. Counted per FINALIZE attempt: an entry held back because its
69
+ * owner is still live (or unverifiable) is not counted, and a failed terminal
70
+ * write is warned — either way the entry stays out of the interrupted class.
71
+ */
72
+ neverStarted: number;
64
73
  }
65
74
 
66
75
  /** The all-zero summary (a skipped scan / an empty registry). */
@@ -75,6 +84,7 @@ export function emptyBootScanSummary(): BootScanSummary {
75
84
  skippedUnverifiable: 0,
76
85
  skippedNoOwner: 0,
77
86
  skippedUnsafeIds: 0,
87
+ neverStarted: 0,
78
88
  };
79
89
  }
80
90
 
@@ -211,10 +221,66 @@ export async function runBootScan(options: BootScanOptions): Promise<BootScanSum
211
221
  export interface PersistedAgentLike {
212
222
  status: string;
213
223
  interruptedAt?: string;
224
+ /**
225
+ * Issue #447: the acceptance marker, when the record carries one. Only the
226
+ * registry entry and the run entry write it today; this read keeps a record
227
+ * that DOES carry it authoritative (the entry is the fallback, not the
228
+ * override) — see `acceptanceState`.
229
+ */
230
+ acceptedAt?: string | null;
214
231
  owner?: RecoveryRecord["owner"];
215
232
  childMarker?: string;
216
233
  }
217
234
 
235
+ /**
236
+ * Issue #447: the tri-state read of the acceptance marker. `undefined` is the
237
+ * LEGACY/untracked state, and it must stay distinguishable from `null` (never
238
+ * started) — which is why this is an explicit `!== undefined` probe and never
239
+ * `??` (`null ?? agent` would silently reclassify every never-started entry as
240
+ * accepted and bring the false positive straight back).
241
+ */
242
+ function acceptanceState(
243
+ entry: InflightRun,
244
+ agent: PersistedAgentLike | null,
245
+ ): string | null | undefined {
246
+ if (entry.acceptedAt !== undefined) return entry.acceptedAt;
247
+ return agent?.acceptedAt;
248
+ }
249
+
250
+ /**
251
+ * The terminal `failed` record written for a dispatch that never reached the
252
+ * prompt: the durable summary the entry already holds, stamped with the honest
253
+ * reason. Projected here (next to the classification that decides it) so the
254
+ * caller only has to persist what it is handed. Deliberately does NOT carry
255
+ * `interruptedAt` — a never-started run is not an interrupted run, and the
256
+ * recovery surface keys on that mark alone.
257
+ */
258
+ export function neverStartedRunRecord(
259
+ entry: InflightRun,
260
+ finishedAt: string,
261
+ reason: string = PROMPT_NEVER_ISSUED_MESSAGE,
262
+ ): SubagentRun {
263
+ return {
264
+ id: entry.id,
265
+ task: entry.task ?? "",
266
+ ...(entry.label !== undefined ? { label: entry.label } : {}),
267
+ ...(entry.dispatchId !== undefined ? { dispatchId: entry.dispatchId } : {}),
268
+ ...(entry.attempt !== undefined ? { attempt: entry.attempt } : {}),
269
+ status: "failed",
270
+ model: entry.model ?? "unknown",
271
+ thinkingLevel: entry.thinkingLevel ?? "unknown",
272
+ startedAt: entry.startedAt,
273
+ finishedAt,
274
+ errorCategory: "unknown",
275
+ errorMessage: reason,
276
+ ...(entry.recoveryPosture !== undefined ? { recoveryPosture: entry.recoveryPosture } : {}),
277
+ ...(entry.originalParams !== undefined ? { originalParams: entry.originalParams } : {}),
278
+ // The marker stays `null` on the terminal record: this run never accepted
279
+ // the prompt, and the record must not claim otherwise after the fact.
280
+ acceptedAt: null,
281
+ };
282
+ }
283
+
218
284
  export interface RegistryScanOptions {
219
285
  deps: RecoveryDeps;
220
286
  /**
@@ -222,6 +288,13 @@ export interface RegistryScanOptions {
222
288
  * background). Returns `false` when the durable write did not land.
223
289
  */
224
290
  mark(record: RecoveryRecord, interruptedAt: string): boolean | void;
291
+ /**
292
+ * Issue #447: persist the terminal record of a dispatch that never reached
293
+ * the prompt (`acceptedAt: null`). Absent ⇒ the entry is left untouched —
294
+ * it is still never offered as interrupted, so the fail-closed direction is
295
+ * "no write", never "offer a retry".
296
+ */
297
+ finalizeNeverStarted?(run: SubagentRun, reason: string): boolean | void;
225
298
  /**
226
299
  * Read ONE background run's agent record by id (never the whole store).
227
300
  * Returns null when the record is absent; absent defaults to an in-flight
@@ -269,31 +342,89 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
269
342
  }
270
343
 
271
344
  const records: RecoveryRecord[] = [];
345
+ // Issue #447: `acceptedAt: null` = tracked but the prompt was never issued.
346
+ // Such an entry is NOT a recovery candidate: nothing was started, so there
347
+ // is nothing to reap, nothing to interrupt, and nothing to retry. It is
348
+ // finalized `failed` below instead of being handed to the decision engine.
349
+ const neverStarted: InflightRun[] = [];
272
350
  for (const entry of addressable) {
273
- if (entry.kind === "background") {
274
- const agent = options.readAgentRecord?.(entry.id) ?? null;
275
- if (agent && agent.status !== "running") continue;
276
- records.push({
351
+ const isBackground = entry.kind === "background";
352
+ // Only a background entry has an agent record to enrich from (and to drop
353
+ // a stale entry by); the read is that ONE file, never the whole store.
354
+ const agent = isBackground ? (options.readAgentRecord?.(entry.id) ?? null) : null;
355
+ if (agent && agent.status !== "running") continue;
356
+ // Issue #447: ONE tri-state read for both kinds, so the `null` rule cannot
357
+ // drift between the background and run branches.
358
+ if (acceptanceState(entry, agent) === null) {
359
+ neverStarted.push(entry);
360
+ continue;
361
+ }
362
+ records.push({
363
+ id: entry.id,
364
+ kind: isBackground ? "agent" : "run",
365
+ status: "running",
366
+ interruptedAt: agent?.interruptedAt ?? entry.interruptedAt,
367
+ owner: agent?.owner ?? entry.owner,
368
+ childMarker: agent?.childMarker ?? entry.childMarker,
369
+ source: entry,
370
+ });
371
+ }
372
+
373
+ const now = options.now?.() ?? new Date();
374
+ /** Entries this scan actually SETTLED (see `BootScanSummary.neverStarted`). */
375
+ let settledNeverStarted = 0;
376
+ for (const entry of neverStarted) {
377
+ if (!options.finalizeNeverStarted) {
378
+ options.log?.debug("Recovery: left a never-started dispatch untouched (no finalizer wired)", {
277
379
  id: entry.id,
278
- kind: "agent",
279
- status: "running",
280
- interruptedAt: agent?.interruptedAt ?? entry.interruptedAt,
281
- owner: agent?.owner ?? entry.owner,
282
- childMarker: agent?.childMarker ?? entry.childMarker,
283
- source: entry,
380
+ kind: entry.kind,
284
381
  });
285
- } else {
286
- records.push({
382
+ continue;
383
+ }
384
+ // A never-started entry is acted on ONLY when its owner is provably dead,
385
+ // the same ownership rule the decision engine applies before it marks
386
+ // anything. A LIVE owner may still be inside its own pre-start window (the
387
+ // git-branch lock, a slow transcript start) and will write its acceptance
388
+ // marker momentarily — finalizing it here would stamp a false `failed`
389
+ // terminal record the run's real terminal entry could not outrank (the
390
+ // store keeps the earlier entry, and readers prefer the LAST one). No owner or
391
+ // an unverifiable one ⇒ no write, exactly as for the mark path.
392
+ const owner = entry.owner;
393
+ const ownerDead =
394
+ !!owner &&
395
+ Number.isInteger(owner.pid) &&
396
+ owner.pid > 0 &&
397
+ classifyOwner(owner, options.deps) === "dead";
398
+ if (!ownerDead) {
399
+ options.log?.debug("Recovery: left a never-started dispatch with a live/unverified owner", {
287
400
  id: entry.id,
288
- kind: "run",
289
- status: "running",
290
- interruptedAt: entry.interruptedAt,
291
- owner: entry.owner,
292
- childMarker: entry.childMarker,
293
- source: entry,
401
+ kind: entry.kind,
402
+ });
403
+ continue;
404
+ }
405
+ settledNeverStarted++;
406
+ try {
407
+ options.finalizeNeverStarted(
408
+ neverStartedRunRecord(entry, now.toISOString()),
409
+ PROMPT_NEVER_ISSUED_MESSAGE,
410
+ );
411
+ options.log?.info("Recovery: finalized a never-started dispatch as failed", {
412
+ id: entry.id,
413
+ kind: entry.kind,
414
+ });
415
+ } catch (err) {
416
+ // Best-effort, exactly like the mark path: a failed finalize must not
417
+ // abort the scan for the OTHER candidates. The registry entry is cleared
418
+ // before the append lands (`persistRunRecord`), so the residue is gone
419
+ // even when the terminal entry cannot be written.
420
+ options.log?.warn("Recovery: never-started finalize failed", {
421
+ id: entry.id,
422
+ kind: entry.kind,
423
+ error: (err as Error).message,
294
424
  });
295
425
  }
296
426
  }
427
+
297
428
  const summary = await runBootScan({
298
429
  records,
299
430
  deps: options.deps,
@@ -302,6 +433,7 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
302
433
  log: options.log,
303
434
  });
304
435
  summary.skippedUnsafeIds = unsafeIds.length;
436
+ summary.neverStarted = settledNeverStarted;
305
437
  return summary;
306
438
  }
307
439
 
@@ -314,6 +446,8 @@ export interface ProductionRecoveryOptions {
314
446
  deps?: RecoveryDeps;
315
447
  /** Persist the D3 mark for this record; `false` = the durable write failed. */
316
448
  mark(record: RecoveryRecord, interruptedAt: string): boolean | void;
449
+ /** Issue #447: persist the terminal record of a never-started dispatch. */
450
+ finalizeNeverStarted?(run: SubagentRun, reason: string): boolean | void;
317
451
  readAgentRecord?(id: string): PersistedAgentLike | null;
318
452
  now?: () => Date;
319
453
  log?: Pick<Logger, "debug" | "info" | "warn">;
@@ -336,6 +470,7 @@ export async function recoverProduction(options: ProductionRecoveryOptions): Pro
336
470
  return recoverInflightRuns({
337
471
  deps: options.deps ?? defaultRecoveryDeps(),
338
472
  mark: options.mark,
473
+ finalizeNeverStarted: options.finalizeNeverStarted,
339
474
  readAgentRecord: options.readAgentRecord,
340
475
  now: options.now,
341
476
  log: options.log,
package/src/reports.ts CHANGED
@@ -6,13 +6,7 @@
6
6
  * and what secrets may have been accessed.
7
7
  */
8
8
 
9
- import type {
10
- SubagentRun,
11
- FileAccessReport,
12
- SecretsExposureEntry,
13
- SecretsExposureReport,
14
- ComplianceSummary,
15
- } from "./types";
9
+ import type { SubagentRun, FileAccessReport, SecretsExposureEntry, SecretsExposureReport, ComplianceSummary } from "./types";
16
10
  import { computeSLAMetrics } from "./metrics";
17
11
 
18
12
  // ---------------------------------------------------------------------------
@@ -29,11 +29,10 @@
29
29
  * agent store's F6 discipline.
30
30
  */
31
31
 
32
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
32
33
  import * as fs from "node:fs";
33
34
  import * as path from "node:path";
34
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
35
- import type { ProcessOwner, RecoveryMode, SubagentRun } from "./types";
36
- import { CUSTOM_ENTRY_TYPES, RECOVERY_MODES } from "./types";
35
+ import { CUSTOM_ENTRY_TYPES, RECOVERY_MODES, type ProcessOwner, type RecoveryMode, type SubagentRun } from "./types";
37
36
  import { assertSafeAgentId } from "./sanitize";
38
37
  import { ensureOwnerOnlyDir } from "./store-permissions";
39
38
 
@@ -64,6 +63,13 @@ export interface InflightRun {
64
63
  // run record, so a post-crash retry restores the same 17-field shape a
65
64
  // same-session retry does (including `force`; decision 2026-10-11).
66
65
  originalParams?: SubagentRun["originalParams"];
66
+ /**
67
+ * Issue #447: the acceptance marker, mirrored from the run record.
68
+ * `null` = tracked but never accepted (never reached `session.prompt()`),
69
+ * ISO string = accepted, absent = legacy entry written before the field.
70
+ * The boot scan classifies on this tri-state (`recoverInflightRuns`).
71
+ */
72
+ acceptedAt?: string | null;
67
73
  startedAt: string;
68
74
  cwd: string;
69
75
  interruptedAt?: string;
@@ -83,6 +89,7 @@ export interface InflightRunInput {
83
89
  model?: string;
84
90
  thinkingLevel?: string;
85
91
  originalParams?: SubagentRun["originalParams"];
92
+ acceptedAt?: string | null;
86
93
  startedAt: string;
87
94
  cwd?: string;
88
95
  }
@@ -161,6 +168,14 @@ function normalizeEnrichment(value: InflightRun, raw: Record<string, unknown>):
161
168
  } else {
162
169
  delete entry.originalParams;
163
170
  }
171
+ // Issue #447: keep the tri-state intact and treat anything else as LEGACY
172
+ // (absent) rather than inventing a fourth state. A mistyped marker must
173
+ // never downgrade a real run into the never-started class.
174
+ if (raw.acceptedAt === null || typeof raw.acceptedAt === "string") {
175
+ entry.acceptedAt = raw.acceptedAt;
176
+ } else {
177
+ delete entry.acceptedAt;
178
+ }
164
179
  return entry;
165
180
  }
166
181
 
@@ -205,6 +220,9 @@ function mergeInput(base: InflightRun, input: InflightRunInput): InflightRun {
205
220
  if (input.model !== undefined) next.model = input.model;
206
221
  if (input.thinkingLevel !== undefined) next.thinkingLevel = input.thinkingLevel;
207
222
  if (input.originalParams !== undefined) next.originalParams = input.originalParams;
223
+ // Issue #447: `null` MUST copy (it is the never-started sentinel); only
224
+ // `undefined` is skipped, so a refresh without the marker cannot erase it.
225
+ if (input.acceptedAt !== undefined) next.acceptedAt = input.acceptedAt;
208
226
  return next;
209
227
  }
210
228
 
@@ -309,6 +327,7 @@ function toRegistryInput(run: SubagentRun, kind: InflightRunKind): InflightRunIn
309
327
  model: run.model,
310
328
  thinkingLevel: run.thinkingLevel,
311
329
  originalParams: run.originalParams,
330
+ acceptedAt: run.acceptedAt,
312
331
  startedAt: run.startedAt,
313
332
  cwd: process.cwd(),
314
333
  };
package/src/runner.ts CHANGED
@@ -10,19 +10,13 @@
10
10
  * - Temp file management
11
11
  */
12
12
 
13
- import { spawn } from "node:child_process";
14
- import type { ChildProcess } from "node:child_process";
13
+ import type { TranscriptMessage, TranscriptContentBlock, TranscriptToolCallBlock } from "./transcript-tail";
14
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
15
+ import { spawn, type ChildProcess } from "node:child_process";
15
16
  import * as fs from "node:fs";
16
17
  import * as path from "node:path";
17
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
18
18
  import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
19
19
  import { wrapTask } from "./prompt";
20
- import type {
21
- SubagentResult,
22
- SubagentToolOptions,
23
- UsageStats,
24
- ThinkingLevel,
25
- } from "./types";
26
20
  import {
27
21
  EMPTY_USAGE,
28
22
  SIGKILL_GRACE_MS,
@@ -33,6 +27,10 @@ import {
33
27
  classifyError,
34
28
  SUBAGENT_ABORTED_MESSAGE,
35
29
  SUBAGENT_SIGNAL_KILLED_MESSAGE,
30
+ type SubagentResult,
31
+ type SubagentToolOptions,
32
+ type UsageStats,
33
+ type ThinkingLevel,
36
34
  } from "./types";
37
35
  import {
38
36
  escalateKill,
@@ -45,14 +43,20 @@ import {
45
43
  } from "./kill-escalation";
46
44
  import { findByMarker, pidAlive, pidHasMarker, pidGone, groupHasMembers, killProcessGroup } from "./proc";
47
45
  import { getSafeEnv, DEPTH_ENV_KEY, CHILD_MARKER_ENV_KEY, sanitizeErrorMessage } from "./sanitize";
48
- import type { Logger } from "./logging";
49
- import type { Intercom } from "./messaging";
50
- import { extractMessages, formatPendingMessages } from "./messaging";
51
- import type {
52
- TranscriptMessage,
53
- TranscriptContentBlock,
54
- TranscriptToolCallBlock,
55
- } from "./transcript-tail";
46
+ import { createLogger, type Logger } from "./logging";
47
+ import { buildEngineeringBarSection } from "./engineering-bar";
48
+ import { SCRATCH_ENV_KEY, prepareRunScratch } from "./scratch-spawn";
49
+ import { extractMessages, formatPendingMessages, type Intercom } from "./messaging";
50
+
51
+ /**
52
+ * The logger for diagnostics a CALLER did not instrument. `runSubagent`'s `log`
53
+ * is optional (its sweep/shutdown callers pass one; the foreground dispatch in
54
+ * `index.ts` passes one too), but the engineering bar's read failure (#421)
55
+ * must never be silent — so the bar's warning falls back to this sink instead of
56
+ * being dropped when `log` is absent.
57
+ */
58
+ const fallbackLog = createLogger("runner");
59
+
56
60
  // ---------------------------------------------------------------------------
57
61
  // In-flight child registry (Option B U1)
58
62
  // ---------------------------------------------------------------------------
@@ -478,7 +482,17 @@ export function buildSubagentArgs(
478
482
  "--thinking",
479
483
  thinkingLevel,
480
484
  ];
481
- if (toolOptions?.noBuiltinTools) {
485
+ // Issue #442: an EXPLICITLY empty allowlist means "no child tools", which is
486
+ // neither of the two states pi already expresses. Omitted keeps pi's
487
+ // defaults (no restriction flag at all), and `--no-builtin-tools` keeps
488
+ // extension and custom tools. `tools !== undefined` is therefore the
489
+ // emptiness test, not `.length > 0`: `[]` must reach pi's blanket
490
+ // `--no-tools`, and it must win over `noBuiltinTools` so an empty allowlist
491
+ // can never widen into "built-ins off, extension tools on". `--exclude-tools`
492
+ // stays additive below — it only disables, so it cannot re-enable a tool.
493
+ if (toolOptions?.tools !== undefined && toolOptions.tools.length === 0) {
494
+ args.push("--no-tools");
495
+ } else if (toolOptions?.noBuiltinTools) {
482
496
  args.push("--no-builtin-tools");
483
497
  } else if (toolOptions?.tools && toolOptions.tools.length > 0) {
484
498
  args.push("--tools", toolOptions.tools.join(","));
@@ -1062,7 +1076,39 @@ export async function runSubagent(
1062
1076
  intercom?: Intercom,
1063
1077
  subagentId?: string,
1064
1078
  childMarker?: string,
1079
+ /**
1080
+ * Issue #511 (U2): this run's id — the record id the caller already persisted
1081
+ * (`run.id`), and the name of its scratch directory (`<root>/runs/<id>`).
1082
+ *
1083
+ * Supplied by every DISPATCH call site (single, chain, parallel, graph — and
1084
+ * the timeout retry re-enters this function with the same id). It is optional
1085
+ * only so the non-dispatch callers and the unit tests need not own a scratch
1086
+ * root: absent means "no scratch directory for this spawn", which is a hole
1087
+ * `scratch-spawn.test.ts` closes by asserting each dispatch site passes one.
1088
+ */
1089
+ runId?: string,
1065
1090
  ): Promise<SubagentResult> {
1091
+ // Issue #511 (U2): resolve the scratch root, create this run's directory and
1092
+ // admit `BRL_SCRATCH` into the child's environment — HERE, at the one
1093
+ // foreground spawn seam every caller shares, BEFORE any side effect of the
1094
+ // spawn (no temp system-prompt file, no process). A refusal is named and
1095
+ // pre-spawn: the caller's ordinary failure path reports it and no child
1096
+ // starts.
1097
+ const scratch = runId === undefined ? undefined : prepareRunScratch(runId, { log });
1098
+ if (scratch !== undefined && !scratch.ok) {
1099
+ return {
1100
+ messages: [],
1101
+ usage: { ...EMPTY_USAGE },
1102
+ exitCode: 1,
1103
+ stderr: scratch.message,
1104
+ errorMessage: `scratch root unavailable (${scratch.code}): ${scratch.message}`,
1105
+ // An environment refusal is not a provider or tool failure; "crash" is
1106
+ // the closed taxonomy's bucket for "the child never got to run" (the
1107
+ // named code in the message is the actionable half).
1108
+ errorCategory: "crash",
1109
+ };
1110
+ }
1111
+
1066
1112
  // E10: Inject pending intercom messages into the task prompt
1067
1113
  if (intercom && subagentId && intercom.hasMessages(subagentId)) {
1068
1114
  const pending = intercom.receiveAndClear(subagentId);
@@ -1078,11 +1124,19 @@ ${msgBlock}`;
1078
1124
 
1079
1125
  const args = buildSubagentArgs(model, thinkingLevel, toolOptions);
1080
1126
 
1127
+ // Issue #421: the project's engineering bar rides the same
1128
+ // --append-system-prompt channel as the caller's prompt, appended last.
1129
+ // Injected HERE (the foreground chokepoint all callers share) rather than
1130
+ // in each caller, so no preset selection can drop it; gated by the project
1131
+ // flag (ADR 0019), and `engineering-bar.ts` owns the read + its warning.
1132
+ const barSection = buildEngineeringBarSection(cwd, log ?? fallbackLog);
1133
+ const childSystemPrompt = barSection ? `${systemPrompt}${barSection}` : systemPrompt;
1134
+
1081
1135
  let tmpDir: string | null = null;
1082
1136
  let tmpFilePath: string | null = null;
1083
1137
 
1084
- if (systemPrompt.trim()) {
1085
- const tmp = await writeToTempFile(cwd, "system", systemPrompt);
1138
+ if (childSystemPrompt.trim()) {
1139
+ const tmp = await writeToTempFile(cwd, "system", childSystemPrompt);
1086
1140
  tmpDir = tmp.dir;
1087
1141
  tmpFilePath = tmp.filePath;
1088
1142
  args.push("--append-system-prompt", tmpFilePath);
@@ -1105,7 +1159,7 @@ ${msgBlock}`;
1105
1159
  thinkingLevel,
1106
1160
  cwd,
1107
1161
  taskPreview: task.slice(0, 80),
1108
- hasSystemPrompt: systemPrompt.trim().length > 0,
1162
+ hasSystemPrompt: childSystemPrompt.trim().length > 0,
1109
1163
  timeout,
1110
1164
  });
1111
1165
 
@@ -1118,6 +1172,11 @@ ${msgBlock}`;
1118
1172
  // Option B U1: stamp the per-run marker so boot recovery can discover
1119
1173
  // this child by scanning /proc/*/environ after a conductor crash.
1120
1174
  if (childMarker) envOverrides[CHILD_MARKER_ENV_KEY] = childMarker;
1175
+ // Issue #511 (U2): the run's scratch directory, as an OVERRIDE (applied
1176
+ // last by `getSafeEnv`) and never as an allowlisted key: a `BRL_SCRATCH`
1177
+ // inherited from the parent process must be replaced, and a grandchild
1178
+ // must resolve its own run rather than inherit this one.
1179
+ if (scratch) envOverrides[SCRATCH_ENV_KEY] = scratch.runDir;
1121
1180
  const hasEnvOverrides = Object.keys(envOverrides).length > 0;
1122
1181
  const proc = spawn(invocation.command, invocation.args, {
1123
1182
  cwd,
package/src/runtime.ts ADDED
@@ -0,0 +1,50 @@
1
+ // Purpose: The per-invocation runtime context (pi, log, state) the composition root builds once and hands to the mode runners.
2
+ /**
3
+ * brl-subagent — the runtime context (cycle S2, ADR 0027 D1/D3)
4
+ *
5
+ * ADR 0027 D1 splits the composition root from the code it composes. The mode
6
+ * runners (S2) are the first consumers that need the three long-lived bindings
7
+ * `src/index.ts`'s `default` export used to own as closures: `pi` (the extension
8
+ * API), `log` (the session logger) and `state` (the session-bound store).
9
+ *
10
+ * `RuntimeContext` names those three, and `createRuntime` builds them with the
11
+ * exact order and arguments `index.ts` used inline — `createLogger` first
12
+ * because `createSessionState` takes the logger. D1 is why this is a value, not
13
+ * a module-level singleton: one context per `initExtension` invocation, so two
14
+ * loaded sessions in one process share no state.
15
+ *
16
+ * Deliberately NOT part of the context (D3): `sessionCtx`,
17
+ * `recoveryNoticeDelivered` and the other `default`-export closures. The runners
18
+ * never read them (recon at 46b427e: zero references across the moved range);
19
+ * adding one here without a consumer would be a binding the split does not
20
+ * need. ADR 0027 F1: if a runner ever needs a fourth field, the split is wrong —
21
+ * report it rather than widening this interface.
22
+ */
23
+
24
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
25
+ import { createLogger, type Logger } from "./logging";
26
+ import { createSessionState, type SessionState } from "./state";
27
+
28
+ /**
29
+ * The three bindings the mode runners read, captured once per extension
30
+ * invocation. `readonly` because the split's contract is "handed in, never
31
+ * rebound": `createRuntime` produces it, `createModeRunners` destructures it,
32
+ * and nothing downstream reassigns a field (a rebind would be a second owner).
33
+ */
34
+ export interface RuntimeContext {
35
+ readonly pi: ExtensionAPI;
36
+ readonly log: Logger;
37
+ readonly state: SessionState;
38
+ }
39
+
40
+ /**
41
+ * Build the runtime context for one extension invocation — the same two calls
42
+ * `index.ts` made inline (log → state, in that order). The only reason this is a
43
+ * function rather than three lines at the call site: the S2 boundary test drives
44
+ * two contexts and asserts they are independent (ADR 0027 D1).
45
+ */
46
+ export function createRuntime(pi: ExtensionAPI): RuntimeContext {
47
+ const log = createLogger("brl-subagent");
48
+ const state = createSessionState(log);
49
+ return { pi, log, state };
50
+ }
package/src/sanitize.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  import * as path from "node:path";
10
10
  import * as fs from "node:fs";
11
11
  import { EMPTY_USAGE, DEFAULT_OUTPUT_CAP_BYTES } from "./types";
12
+ import { appendWorktreeState } from "./worktree-report";
12
13
 
13
14
  // ---------------------------------------------------------------------------
14
15
  // F1: Input sanitization
@@ -152,6 +153,14 @@ export function assertSafeAgentId(id: string): void {
152
153
  const SAFE_ENV_KEYS = new Set([
153
154
  "PATH",
154
155
  "HOME",
156
+ // Issue #511 (U2): the Windows halves of the same question. The shipped
157
+ // scratch root is `%LOCALAPPDATA%\brl-subagent` there, and `USERPROFILE` is
158
+ // what a nested child needs to find its own home at all — `HOME` alone leaves
159
+ // a Windows grandchild with no root to resolve. Symmetric with `HOME`, and
160
+ // deliberately NOT a place for `BRL_SCRATCH`: that value is per-run, so it is
161
+ // overridden at the spawn seam and stripped from anything inherited.
162
+ "USERPROFILE",
163
+ "LOCALAPPDATA",
155
164
  "USER",
156
165
  "LANG",
157
166
  "LC_ALL",
@@ -316,7 +325,7 @@ function neutralizePathPrefix(text: string, prefix: string, replacement: string)
316
325
  * 4. Caps length at 2000 chars with an ellipsis marker.
317
326
  *
318
327
  * Remaining-absolute-path policy: paths OUTSIDE the project root and its
319
- * parent are left as-is (e.g. `/etc/passwd`, `/usr/bin/node`, `/tmp/x.log`).
328
+ * parent are left as-is (e.g. `/etc/passwd`, `/usr/bin/node`, `/var/log/x.log`).
320
329
  * Issue #30 is specifically about CWD/home disclosure; system paths carry no
321
330
  * personal structure and keeping them preserves debugging value. Messages
322
331
  * that are short and clean (no ANSI, no cwd/parent prefixes) pass through
@@ -357,6 +366,13 @@ export function sanitizeErrorMessage(msg: string, cwd?: string): string {
357
366
  * serializes `content` into the LLM context, while the raw text persists to
358
367
  * the session file for post-mortems (issue #68 framing: extraction is DRY,
359
368
  * not a stderr-content change).
369
+ *
370
+ * Issue #474: this is the ONE crash seam (single, chain, graph and the per-unit
371
+ * finalizer all build their envelope here), so the worktree-state block is
372
+ * appended here rather than at seven call sites. `err` may carry the crashing
373
+ * UNIT's own block (`finalizeUnitRunCrash` attaches it) and that wins over
374
+ * `cwd`, which a mode-level caller only knows as the dispatch cwd. The block is
375
+ * appended, never spliced: the cause reads first, the residue after.
360
376
  */
361
377
  export function buildCrashResult(mode: string, err: unknown, cwd: string): {
362
378
  content: Array<{ type: "text"; text: string }>;
@@ -374,7 +390,9 @@ export function buildCrashResult(mode: string, err: unknown, cwd: string): {
374
390
  cwd,
375
391
  );
376
392
  return {
377
- content: [{ type: "text", text: `${mode} crashed: ${errorMessage}` }],
393
+ content: [
394
+ { type: "text", text: appendWorktreeState(`${mode} crashed: ${errorMessage}`, cwd, err) },
395
+ ],
378
396
  details: {
379
397
  messages: [],
380
398
  usage: { ...EMPTY_USAGE },
package/src/scheduler.ts CHANGED
@@ -6,8 +6,7 @@
6
6
  * and graph validation for P10 dependency graph mode.
7
7
  */
8
8
 
9
- import type { GraphTask } from "./types";
10
- import { MAX_GRAPH_TASKS } from "./types";
9
+ import { MAX_GRAPH_TASKS, type GraphTask } from "./types";
11
10
 
12
11
  // ---------------------------------------------------------------------------
13
12
  // Cycle detection — three-color DFS