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
@@ -0,0 +1,113 @@
1
+ // Purpose: The per-unit param merge (SubTask over global) and the unit display name, shared by chain/parallel/graph and the background fan-out.
2
+ /**
3
+ * brl-subagent — per-unit params (cycle S1, ADR 0027 D6)
4
+ *
5
+ * `mergeSubTaskParams` and `displayTaskName` used to be closures inside
6
+ * src/index.ts's default export. A closure cannot be imported, so the two
7
+ * consumers that needed the real thing kept substitutes: a hand-maintained
8
+ * replica in chain-parallel.test.ts and a SOURCE-TEXT ratchet in
9
+ * integration.test.ts. Extracted here for the reason params.ts was extracted
10
+ * (issue #59) — the tests drive the real function instead of a copy.
11
+ *
12
+ * The move is verbatim apart from the file's one captured binding:
13
+ * `state.config.maxThinkingLevel` is now the `maxThinkingLevel` parameter, so
14
+ * the merge reads no per-invocation state and stays a pure function of its
15
+ * arguments.
16
+ */
17
+
18
+ import {
19
+ resolveThinkingLevel,
20
+ type ApprovalMode,
21
+ type GitMode,
22
+ type Priority,
23
+ type ResolvedParams,
24
+ type SubTaskParams,
25
+ type SubagentToolOptions,
26
+ type ThinkingLevel,
27
+ } from "./types";
28
+
29
+ /** A merged unit: the fields every batch mode's spawn path reads. */
30
+ export type MergedSubTaskParams = {
31
+ task: string;
32
+ label: string | undefined;
33
+ model: string | undefined;
34
+ inheritSP: boolean;
35
+ customSP: string | undefined;
36
+ outputFile: string | undefined;
37
+ timeout: number | undefined;
38
+ effectiveCwd: string;
39
+ thinkingLevel: ThinkingLevel;
40
+ priority: Priority | undefined;
41
+ toolOptions: SubagentToolOptions | undefined;
42
+ resolvedGitMode: GitMode;
43
+ resolvedApprovalMode: ApprovalMode;
44
+ };
45
+
46
+ /**
47
+ * Merge global resolved params with a SubTaskParams.
48
+ * SubTask fields override global fields. Tools/excludeTools/noBuiltinTools
49
+ * are replaced entirely if set in the subTask, otherwise inherited from global.
50
+ */
51
+ export function mergeSubTaskParams(
52
+ globalParams: ResolvedParams & { resolvedGitMode: GitMode; resolvedApprovalMode: ApprovalMode },
53
+ subTask: SubTaskParams,
54
+ maxThinkingLevel: ThinkingLevel,
55
+ ): MergedSubTaskParams {
56
+ const mergedThinkingLevel = subTask.thinkingLevel
57
+ ? resolveThinkingLevel(
58
+ subTask.thinkingLevel as ThinkingLevel,
59
+ maxThinkingLevel,
60
+ )
61
+ : globalParams.thinkingLevel;
62
+
63
+ const mergedTools = subTask.tools ?? globalParams.toolOptions?.tools;
64
+ // Fix: edit depends on write in pi's tool system.
65
+ const resolvedTools = mergedTools && mergedTools.includes("edit") && !mergedTools.includes("write")
66
+ ? [...mergedTools, "write"]
67
+ : mergedTools;
68
+ const mergedExcludeTools = subTask.excludeTools ?? globalParams.toolOptions?.excludeTools;
69
+ const mergedNoBuiltinTools =
70
+ subTask.noBuiltinTools ?? globalParams.toolOptions?.noBuiltinTools;
71
+
72
+ const mergedToolOptions: SubagentToolOptions | undefined =
73
+ resolvedTools || mergedExcludeTools || mergedNoBuiltinTools
74
+ ? {
75
+ tools: resolvedTools,
76
+ excludeTools: mergedExcludeTools,
77
+ noBuiltinTools: mergedNoBuiltinTools,
78
+ }
79
+ : undefined;
80
+
81
+ return {
82
+ task: subTask.task || globalParams.task,
83
+ label: subTask.label ?? globalParams.label,
84
+ model: subTask.model,
85
+ inheritSP: subTask.inheritSystemPrompt ?? globalParams.inheritSP,
86
+ customSP: subTask.systemPrompt ?? globalParams.customSP,
87
+ outputFile: subTask.outputFile ?? globalParams.outputFile,
88
+ timeout: subTask.timeout ?? globalParams.timeout,
89
+ effectiveCwd: subTask.cwd ?? globalParams.effectiveCwd,
90
+ thinkingLevel: mergedThinkingLevel,
91
+ // Issue #114: per-unit priority — undefined when the step declares none
92
+ // (the caller then falls back to the call-level priority).
93
+ priority: subTask.priority && ["critical", "high", "normal", "low"].includes(subTask.priority)
94
+ ? (subTask.priority as Priority)
95
+ : undefined,
96
+ toolOptions: mergedToolOptions,
97
+ resolvedGitMode: globalParams.resolvedGitMode,
98
+ resolvedApprovalMode: globalParams.resolvedApprovalMode,
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Per-unit display name for validation prefixes: the label when present,
104
+ * else the task truncated to 60 chars. Shared by the foreground parallel
105
+ * pre-pass and the background fan-out pre-pass (issue #220) so a unit
106
+ * renders identically in either shape.
107
+ */
108
+ export function displayTaskName(merged: MergedSubTaskParams): string {
109
+ return (
110
+ merged.label ??
111
+ (merged.task.length > 60 ? `${merged.task.slice(0, 57)}...` : merged.task)
112
+ );
113
+ }
package/src/unit-run.ts CHANGED
@@ -16,26 +16,26 @@
16
16
  * block and the background/retry registration paths remain in index.ts.
17
17
  */
18
18
 
19
- import type {
20
- AgentToolResult,
21
- AgentToolUpdateCallback,
22
- } from "@earendil-works/pi-agent-core";
19
+ import type { Logger } from "./logging";
20
+ import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
23
21
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
24
-
25
- import type {
26
- SubagentResult,
27
- SubagentRun,
28
- SubagentToolOptions,
29
- Priority,
30
- RecoveryMode,
22
+ import {
23
+ getFinalOutput,
24
+ classifyError,
25
+ DEFAULT_RECOVERY,
26
+ type SubagentResult,
27
+ type SubagentRun,
28
+ type SubagentToolOptions,
29
+ type Priority,
30
+ type RecoveryMode,
31
31
  } from "./types";
32
- import { getFinalOutput, classifyError, DEFAULT_RECOVERY } from "./types";
33
32
  import { snapshotOriginalParams } from "./params";
34
33
  import { currentProcessOwner } from "./recovery";
35
34
  import { capOutput, stripAnsi, buildCrashResult } from "./sanitize";
35
+ import { prepareRunScratch } from "./scratch-spawn";
36
36
  import { finalizeRunRecord, pruneSessionRuns } from "./history";
37
- import type { Logger } from "./logging";
38
37
  import { SessionState } from "./state";
38
+ import { attachWorktreeState } from "./worktree-report";
39
39
 
40
40
  // ---------------------------------------------------------------------------
41
41
  // Structural source for a per-unit run entry
@@ -43,8 +43,9 @@ import { SessionState } from "./state";
43
43
 
44
44
  /**
45
45
  * The per-unit fields shared by chain/parallel/graph modes (`merged` from
46
- * mergeSubTaskParams). Kept structural so the call sites verify by shape —
47
- * mergeSubTaskParams itself is not imported (it lives in index.ts).
46
+ * mergeSubTaskParams, unit-params.ts). Kept structural so the call sites
47
+ * verify by shape — this module writes a run record and has no reason to
48
+ * depend on the merge itself.
48
49
  */
49
50
  export interface UnitRunSource {
50
51
  task: string;
@@ -112,6 +113,12 @@ export function createUnitRun(
112
113
  recoveryPosture: RecoveryMode = DEFAULT_RECOVERY,
113
114
  ): { runId: string; run: SubagentRun } {
114
115
  const runId = crypto.randomUUID();
116
+ // Issue #511 (U2): the unit's scratch directory is created HERE, at record
117
+ // creation, so the record can carry it. Best-effort: the spawn seam in
118
+ // `runner.ts` re-prepares (idempotently) and is the gate that refuses to
119
+ // start a child whose root could not be placed — this call only decides what
120
+ // the durable record says.
121
+ const scratch = prepareRunScratch(runId);
115
122
  const run: SubagentRun = {
116
123
  id: runId,
117
124
  task: source.task,
@@ -138,6 +145,13 @@ export function createUnitRun(
138
145
  // U3 (D4): snapshot the posture so the boot notice/offer reads what was
139
146
  // in force at dispatch.
140
147
  recoveryPosture,
148
+ // Issue #511 (U2): attach the unit's scratch directory to the record at
149
+ // creation, so a retry of this run (the retry preamble, U3) can name the
150
+ // bank path from the durable record. Best-effort HERE: the spawn seam in
151
+ // `runner.ts` is the gate that refuses to start a child without one, so a
152
+ // refusal here persists a record with no `scratchDir` and the runner reports
153
+ // the named code.
154
+ scratchDir: scratch.ok ? scratch.runDir : undefined,
141
155
  // The execution-shape fields (background/gitMode/approvalMode/force) are
142
156
  // deliberately omitted: a fan-out unit retries as a SINGLE run, so it must
143
157
  // not inherit the fan-out's background-ness. A retry that wants background
@@ -204,6 +218,11 @@ export function finalizeUnitRun(
204
218
  * node"); `logContext` carries the mode-specific context fields (chain passes
205
219
  * the step index, parallel passes the task index, graph passes the node id)
206
220
  * spread into the log call alongside runId/error.
221
+ *
222
+ * Issue #474: `resolvedCwd` is the UNIT's cwd, and the block for it is attached
223
+ * to the rethrown error BEFORE the rethrow — the mode's outer catch only knows
224
+ * the dispatch cwd, so without the attachment a unit crash in its own directory
225
+ * would report a sibling's tree. `buildCrashResult` prefers the attachment.
207
226
  */
208
227
  export function finalizeUnitRunCrash(
209
228
  state: SessionState,
@@ -215,6 +234,7 @@ export function finalizeUnitRunCrash(
215
234
  log: Logger,
216
235
  logContext?: Record<string, unknown>,
217
236
  ): never {
237
+ attachWorktreeState(err, resolvedCwd);
218
238
  const crash = buildCrashResult(modeLabel, err, resolvedCwd);
219
239
  state.finalizeLiveSubagent(run.id);
220
240
  const crashOutput = state.subagentSessions.get(run.id)?.liveOutput ?? "";
@@ -269,13 +289,21 @@ export function pruneHistoryIfNeeded(
269
289
  * `labelOverride` supplies the live entry's label when the caller wants one
270
290
  * that differs from `run.label` (e.g. chain's unlabeled-step fallback).
271
291
  * When omitted the live label defaults to `run.label`.
292
+ *
293
+ * `timeoutMs` is the run's MERGED timeout (param/preset/template) — never the
294
+ * raw caller param (issue #423). It becomes the live entry's absolute
295
+ * `deadlineAt`, anchored on the run's own start clock. Absent or non-positive
296
+ * means "no deadline": a foreground run has no default deadline.
272
297
  */
273
298
  export function registerLiveRun(
274
299
  state: SessionState,
275
300
  run: SubagentRun,
276
301
  ctx: ExtensionContext,
277
302
  labelOverride?: string,
303
+ timeoutMs?: number,
278
304
  ): void {
305
+ const startedAt = new Date(run.startedAt).getTime();
306
+ const deadlineAt = timeoutMs && timeoutMs > 0 ? startedAt + timeoutMs : undefined;
279
307
  state.registerLiveSubagent(run.id, {
280
308
  id: run.id,
281
309
  label: labelOverride ?? run.label,
@@ -283,7 +311,8 @@ export function registerLiveRun(
283
311
  model: run.model,
284
312
  thinkingLevel: run.thinkingLevel,
285
313
  priority: run.priority,
286
- startedAt: new Date(run.startedAt).getTime(),
314
+ startedAt,
315
+ ...(deadlineAt !== undefined ? { deadlineAt } : {}),
287
316
  ctx,
288
317
  });
289
318
  }
package/src/validate.ts CHANGED
@@ -7,8 +7,7 @@
7
7
  * LLM context), so it's consistent regardless of conductor state.
8
8
  */
9
9
 
10
- import type { ThinkingLevel, SubagentToolOptions } from './types';
11
- import { THINKING_LEVELS } from './types';
10
+ import { THINKING_LEVELS, type ThinkingLevel, type SubagentToolOptions } from './types';
12
11
  import { DISPATCH_LINE_FORM, JEV_UNAVAILABLE, parseDispatchLine } from './dispatch-line';
13
12
  import { isProcessChecksEnabled } from './project-flags';
14
13
 
@@ -38,12 +37,19 @@ export interface ValidateConfig {
38
37
  cwd?: string;
39
38
  /**
40
39
  * delegate_task's `noJev` param — the STATED bypass for the Jev-line check
41
- * (issue #412, ADR 0018). Non-empty by schema. It downgrades the rejection
42
- * to a warning that carries the reason, so the bypass is visible in the
43
- * result, never silent. It bypasses ONLY the line check: every capability
44
- * conflict still rejects (unlike `force`, which is capability-only).
40
+ * (issue #412, ADR 0018). It downgrades the rejection to a warning that
41
+ * carries the reason, so the bypass is visible in the result, never silent.
42
+ * It bypasses ONLY the line check: every capability conflict still rejects
43
+ * (unlike `force`, which is capability-only).
44
+ *
45
+ * Typed `unknown` on purpose (issue #419, ADR 0020): the schema DECLARES a
46
+ * non-empty string, but the harness validates with `coerce: true` and
47
+ * pi-schema's string rule stringifies booleans/numbers before the handler
48
+ * runs, so the value that arrives is not guaranteed to be the declared type
49
+ * (a direct caller can pass anything at all). `readNoJevReason` is the
50
+ * runtime guard, and it is the ONLY place this value may be read.
45
51
  */
46
- noJev?: string;
52
+ noJev?: unknown;
47
53
  }
48
54
 
49
55
  export interface ValidateResult {
@@ -305,6 +311,55 @@ export function diagnoseFailure(config: DiagnoseConfig): string[] {
305
311
  return suggestions;
306
312
  }
307
313
 
314
+ // ── The noJev bypass reason (issue #419, ADR 0020) ───────────────────
315
+
316
+ /**
317
+ * What the harness's coercion turns a non-string reason INTO: `compile(schema,
318
+ * { coerce: true })` stringifies booleans and numbers, so `noJev: true`
319
+ * reaches the handler as `"true"` — a value that passes `Type.String({
320
+ * minLength: 1 })` and is NOT a stated reason. Matching the coerced text is the
321
+ * only way to tell it apart from a real one at this seam.
322
+ */
323
+ const COERCED_PRIMITIVE_RE = /^(true|false|-?\d+(\.\d+)?)$/i;
324
+
325
+ /** The three outcomes of reading `noJev`: no bypass, a usable reason, or a refusal. */
326
+ type NoJevVerdict =
327
+ | { kind: 'absent' }
328
+ | { kind: 'reason'; reason: string }
329
+ | { kind: 'invalid'; problem: string };
330
+
331
+ /**
332
+ * Reads `noJev` defensively. The schema declares a non-empty string, but that
333
+ * is a DECLARATION, not a runtime guarantee: coercion stringifies primitives
334
+ * (above), and a direct caller can pass any value. So: never `.trim()` a
335
+ * non-string, and treat a coerced primitive (or an empty/whitespace reason) as
336
+ * an INVALID bypass rather than a usable one — a boolean must neither bypass
337
+ * the check nor crash it.
338
+ */
339
+ function readNoJevReason(value: unknown): NoJevVerdict {
340
+ // Omitted, or an optional `null` (pi-schema drops those during coercion):
341
+ // no bypass was stated, so the caller gets the plain missing-line error.
342
+ if (value === undefined || value === null) return { kind: 'absent' };
343
+ if (typeof value !== 'string') {
344
+ const shape = Array.isArray(value) ? 'array' : typeof value;
345
+ return { kind: 'invalid', problem: `expected a non-empty reason string, got ${shape}` };
346
+ }
347
+ const reason = value.trim();
348
+ if (reason === '') {
349
+ return { kind: 'invalid', problem: 'the reason is empty' };
350
+ }
351
+ if (COERCED_PRIMITIVE_RE.test(reason)) {
352
+ const coerced = /^(true|false)$/i.test(reason) ? 'boolean' : 'number';
353
+ return {
354
+ kind: 'invalid',
355
+ problem:
356
+ `\`${reason}\` is a coerced ${coerced}, not a stated reason — the tool-argument validator ` +
357
+ `stringifies booleans and numbers before the handler sees them`,
358
+ };
359
+ }
360
+ return { kind: 'reason', reason };
361
+ }
362
+
308
363
  // ── Main validation ──────────────────────────────────────────────────
309
364
 
310
365
  export function validatePreTask(config: ValidateConfig): ValidateResult {
@@ -327,15 +382,24 @@ export function validatePreTask(config: ValidateConfig): ValidateResult {
327
382
  // dispatch is never rejected for a missing line. The flag read is fail-open
328
383
  // (`src/project-flags.ts`). `noJev` — a stated reason — downgrades the
329
384
  // rejection to a WARNING that names the reason, so the bypass is surfaced
330
- // rather than silent (ADR 0007's pattern).
385
+ // rather than silent (ADR 0007's pattern). The reason itself is read through
386
+ // a runtime guard, never off the declared type (issue #419, ADR 0020): a
387
+ // boolean/number arrives here coercion-stringified, and it must be refused
388
+ // as the missing line, not accepted as a bypass.
331
389
  if (isProcessChecksEnabled(config.cwd)) {
332
390
  const verdict = parseDispatchLine(taskText);
333
391
  if (!verdict.ok) {
334
- if (config.noJev !== undefined && config.noJev.trim() !== '') {
392
+ const bypass = readNoJevReason(config.noJev);
393
+ if (bypass.kind === 'reason') {
335
394
  warnings.push(
336
- `noJev override: the Jev dispatch line was skipped — ${config.noJev} (${verdict.reason})`,
395
+ `noJev override: the Jev dispatch line was skipped — ${bypass.reason} (${verdict.reason})`,
337
396
  );
338
397
  } else {
398
+ if (bypass.kind === 'invalid') {
399
+ errors.push(
400
+ `invalid noJev: ${bypass.problem}. Pass the reason the line was skipped as a non-empty string (e.g. noJev: "classifier unreachable; maintainer approved"), or append the line.`,
401
+ );
402
+ }
339
403
  errors.push(
340
404
  `missing Jev dispatch line: ${verdict.reason}. ` +
341
405
  `Classify with the Jev classifier, format the answer with \`jev-check --line '<json>'\` (it prints the line verbatim), and append it to the task as: ${DISPATCH_LINE_FORM}. ` +
@@ -386,7 +450,7 @@ export function validatePreTask(config: ValidateConfig): ValidateResult {
386
450
  const gitPatterns = [/\b(commit|push|pull|merge|rebase|checkout|branch|pr|pull.request)\b/i];
387
451
  if (gitPatterns.some(p => p.test(taskText)) && config.gitMode === 'none') {
388
452
  warnings.push(
389
- `Task involves git operations but gitMode is 'none' — subagent cannot create commits or branches`,
453
+ `gitMode is 'none' — the harness will not create or capture a branch; the task must run its own git commands`,
390
454
  );
391
455
  }
392
456
 
@@ -456,3 +520,17 @@ export function normalizeTimeout(timeout: number | undefined): number | undefine
456
520
  if (timeout >= 2 ** 31 - 1) return undefined;
457
521
  return timeout;
458
522
  }
523
+
524
+ /**
525
+ * The EFFECTIVE budget of a BACKGROUND run: the normalized explicit `timeout`,
526
+ * or {@link DEFAULT_BACKGROUND_DEADLINE_MS} when there is none (issue #423).
527
+ *
528
+ * The single definition of "30 m default" for the background path — the W3
529
+ * timer, the persisted record's `timeoutMs` and every display of the budget
530
+ * derive from here, so a displayed deadline cannot drift from the armed timer.
531
+ * Not used by the foreground path: a foreground run has NO default deadline,
532
+ * so an absent timeout there means "no deadline", not 30 m.
533
+ */
534
+ export function effectiveBackgroundBudget(timeout: number | undefined): number {
535
+ return normalizeTimeout(timeout) ?? DEFAULT_BACKGROUND_DEADLINE_MS;
536
+ }
@@ -0,0 +1,142 @@
1
+ // Purpose: Formats the read-only worktree state a failed or stopped run may have left behind (issue #474).
2
+ /**
3
+ * brl-subagent — failure-path worktree state (issue #474)
4
+ *
5
+ * Rule 11 escalated `connection-drop` after three hits in one cycle: six of
6
+ * ~28 sweep dispatches ended without their unit, two leaving a **mutant applied**
7
+ * in a worktree. The mitigations (auto-retry, a progress bank, transcript
8
+ * retention) worked, but every death still cost the conductor a manual state
9
+ * audit — memory, not mechanism. Three dispatches measured the same gap: a
10
+ * settled failure reported the failure and nothing about the tree.
11
+ *
12
+ * This module is the FORMATTING half. `probeWorktree` (git.ts) does the reading,
13
+ * and the split is deliberate: execution stays where `architecture-rules`
14
+ * confines it, and this module never throws, never classifies a run and never
15
+ * decides whether the tree is safe — it reports. The decision stays with the
16
+ * conductor (rule-notes: a killed agent's worktree is hostile until read).
17
+ *
18
+ * It imports `./git` and `node:path` only. That is a hard constraint, not a
19
+ * preference: `sanitize.ts` imports THIS module for the one crash seam, so any
20
+ * edge back into `sanitize.ts` (or into a module that imports it) would close a
21
+ * runtime cycle.
22
+ */
23
+
24
+ import * as path from "node:path";
25
+
26
+ import { probeWorktree } from "./git";
27
+
28
+ /** The block's first line. One spelling, so a reader (and a test) can find it. */
29
+ const HEADING = "Worktree state (git, at failure):";
30
+
31
+ /**
32
+ * The caution line's job is to stop a conductor from reusing a tree it did not
33
+ * inspect. It carries no verdict — "may be" is the whole claim.
34
+ */
35
+ const CAUTION =
36
+ " — uncommitted work may be a partially applied edit or a mutant; inspect before reusing.";
37
+
38
+ /** The property a rethrown unit crash carries its own block on (`finalizeUnitRunCrash`). */
39
+ export interface WorktreeStateCarrier {
40
+ worktreeState?: string;
41
+ }
42
+
43
+ /** An unavailable report — the block's whole body when the probe could not look. */
44
+ function unavailable(reason: string): string {
45
+ return `${HEADING}\n state: unavailable (${reason})`;
46
+ }
47
+
48
+ /** `1 file` / `2 files` — a count that reads as English in the report line. */
49
+ function fileCount(n: number): string {
50
+ return `${n} file${n === 1 ? "" : "s"}`;
51
+ }
52
+
53
+ /** Render a successful probe as the block. */
54
+ function renderProbe(probe: Extract<ReturnType<typeof probeWorktree>, { kind: "ok" }>): string {
55
+ const branch = probe.detached
56
+ ? "(detached)"
57
+ : probe.unborn
58
+ ? `${probe.branch ?? "(unborn)"} (unborn)`
59
+ : (probe.branch ?? "(unknown)");
60
+ const lineCounts =
61
+ probe.insertions === undefined ? "" : ` (+${probe.insertions}/−${probe.deletions ?? 0})`;
62
+ const lines = [
63
+ HEADING,
64
+ ` branch: ${branch}`,
65
+ ` dirty: ${fileCount(probe.dirtyFiles)}${lineCounts}`,
66
+ ` staged: ${probe.stagedFiles}`,
67
+ ];
68
+ // Only an unclean tree earns the caution: a clean failure has nothing to warn
69
+ // about, and a warning on every failure is a warning nobody reads.
70
+ if (probe.dirtyFiles + probe.stagedFiles > 0) lines.push(CAUTION);
71
+ return lines.join("\n");
72
+ }
73
+
74
+ /**
75
+ * The worktree-state block for `cwd`. ALWAYS returns text (never throws, never
76
+ * returns ""), because its callers append it to a message they must still
77
+ * deliver:
78
+ *
79
+ * - no cwd → `state: unavailable (no cwd)`;
80
+ * - a RELATIVE cwd → `state: unavailable (no recorded cwd)`. A background
81
+ * record written before #474 stamped `cwd` may hold the relative value the
82
+ * caller passed; resolving it against the conductor's process cwd would
83
+ * report a tree nobody ran in, so it is refused rather than guessed;
84
+ * - not a repo → `state: unavailable (not a git repository)`;
85
+ * - any read failure → `state: unavailable (<git's own reason>)`.
86
+ *
87
+ * The outer catch is belt-and-braces: `probeWorktree` classifies its own
88
+ * failures, and this one makes "never throws" a property of the formatter even
89
+ * if a future edit breaks that.
90
+ */
91
+ export function describeWorktreeState(cwd: string | undefined): string {
92
+ if (cwd === undefined || cwd.length === 0) return unavailable("no cwd");
93
+ if (!path.isAbsolute(cwd)) return unavailable("no recorded cwd");
94
+ try {
95
+ const probe = probeWorktree(cwd);
96
+ if (probe.kind === "not-repo") return unavailable("not a git repository");
97
+ if (probe.kind === "unavailable") return unavailable(probe.reason);
98
+ return renderProbe(probe);
99
+ } catch (err) {
100
+ return unavailable(err instanceof Error ? err.message : String(err));
101
+ }
102
+ }
103
+
104
+ /**
105
+ * The block an error already carries, when a unit crash attached its OWN tree.
106
+ * A mode runner's outer catch only knows the dispatch cwd; `finalizeUnitRunCrash`
107
+ * attaches the crashing unit's block to the rethrown error so the mode-level
108
+ * crash reports the unit's worktree rather than a sibling's (issue #474).
109
+ */
110
+ export function attachedWorktreeState(err: unknown): string | undefined {
111
+ if (typeof err !== "object" || err === null) return undefined;
112
+ const carried = (err as WorktreeStateCarrier).worktreeState;
113
+ return typeof carried === "string" && carried.length > 0 ? carried : undefined;
114
+ }
115
+
116
+ /**
117
+ * Attach the block for `cwd` to a rethrown error, best-effort.
118
+ *
119
+ * A thrown NON-OBJECT (a bare string) cannot carry anything, so the mode catch
120
+ * falls back to the dispatch cwd — a stated limit, not a silent one: real
121
+ * runner crashes throw `Error` instances.
122
+ */
123
+ export function attachWorktreeState(err: unknown, cwd: string | undefined): void {
124
+ if (typeof err !== "object" || err === null) return;
125
+ (err as WorktreeStateCarrier).worktreeState = describeWorktreeState(cwd);
126
+ }
127
+
128
+ /**
129
+ * Append the worktree block to failure text, separated by a blank line.
130
+ *
131
+ * The block goes LAST (issue #474 v3): the crash envelope, the classified-failure
132
+ * message and its H1 warnings note are the reason, and a report of the residue
133
+ * belongs after the cause — never spliced into it.
134
+ *
135
+ * `err` is optional and only for the crash seam: when a unit crash carried its
136
+ * own block, that block wins over `cwd`, which the mode-level caller only knows
137
+ * as the dispatch cwd.
138
+ */
139
+ export function appendWorktreeState(text: string, cwd: string | undefined, err?: unknown): string {
140
+ const block = attachedWorktreeState(err) ?? describeWorktreeState(cwd);
141
+ return `${text}\n\n${block}`;
142
+ }