brl-subagent 2.8.0 → 2.9.1

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 (48) hide show
  1. package/AGENT.md +17 -2
  2. package/README.md +3 -3
  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 +360 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +3 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +1 -1
  11. package/src/git.ts +220 -8
  12. package/src/headstate.ts +3 -3
  13. package/src/history.ts +21 -3
  14. package/src/index.ts +109 -4473
  15. package/src/loader.ts +1 -1
  16. package/src/logging.ts +67 -4
  17. package/src/mode-prologue.ts +4 -10
  18. package/src/mode-runners.ts +1575 -0
  19. package/src/notify-completion.ts +35 -8
  20. package/src/params.ts +14 -13
  21. package/src/preflight.ts +123 -16
  22. package/src/prelude.ts +14 -5
  23. package/src/presets.ts +3 -5
  24. package/src/proc.ts +2 -3
  25. package/src/recovery-engine.ts +1 -1
  26. package/src/recovery-surface.ts +1 -2
  27. package/src/recovery.ts +238 -10
  28. package/src/reports.ts +1 -7
  29. package/src/run-registry.ts +133 -10
  30. package/src/runner.ts +47 -18
  31. package/src/runtime.ts +50 -0
  32. package/src/sanitize.ts +20 -2
  33. package/src/scheduler.ts +1 -2
  34. package/src/schema.ts +4 -2
  35. package/src/scratch-root.ts +909 -0
  36. package/src/scratch-spawn.ts +256 -0
  37. package/src/session-manager.ts +587 -81
  38. package/src/state.ts +12 -14
  39. package/src/templates.ts +3 -5
  40. package/src/terminal-notifier.ts +405 -0
  41. package/src/transcript.ts +1 -1
  42. package/src/tui-format.ts +3 -1
  43. package/src/tui.ts +46 -36
  44. package/src/types.ts +29 -3
  45. package/src/unit-params.ts +113 -0
  46. package/src/unit-run.ts +35 -15
  47. package/src/validate.ts +28 -9
  48. package/src/worktree-report.ts +142 -0
@@ -18,17 +18,17 @@
18
18
  */
19
19
 
20
20
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
21
- import type {
22
- BackgroundAgent,
23
- BackgroundAgentIdentity,
24
- SubagentRun,
25
- CompletionNotifyMode,
26
- AgentStatus,
27
- } from "./types";
28
21
  import { truncateTail } from "./transcript-tail";
29
22
  import { formatRunDuration } from "./history";
30
23
  import { formatBudgetDuration } from "./tui-format";
31
- import { classifyTerminalOutcome } from "./types";
24
+ import {
25
+ classifyTerminalOutcome,
26
+ type BackgroundAgent,
27
+ type BackgroundAgentIdentity,
28
+ type SubagentRun,
29
+ type CompletionNotifyMode,
30
+ type AgentStatus,
31
+ } from "./types";
32
32
  import { resolveTerminalRunEntry } from "./state";
33
33
 
34
34
  /** Terminal statuses the completion message can carry. */
@@ -246,6 +246,33 @@ export function buildCompletionMessage(
246
246
  return { customType: "subagent-completion", content, display: true, details };
247
247
  }
248
248
 
249
+ /**
250
+ * Issue #474: insert the worktree-state block into a settled-failure wake, as
251
+ * its own part and BEFORE the closing directive.
252
+ *
253
+ * PURE — it takes the already-rendered block and never probes git: the builder's
254
+ * contract is "no side effects", and the probe is a subprocess. The caller
255
+ * renders the block (`describeWorktreeState`) and gates on the CLASSIFIED
256
+ * status.
257
+ *
258
+ * The directive is matched at the END (`endsWith`), never as the first
259
+ * occurrence: an agent's own tail can quote the directive text, and splitting
260
+ * there would drop everything after the quote. A shape that does not end with
261
+ * the directive keeps the block by appending it — a missing report is the one
262
+ * outcome this function must not produce.
263
+ */
264
+ export function withWorktreeState(
265
+ message: CompletionMessagePayload,
266
+ worktreeState: string,
267
+ ): CompletionMessagePayload {
268
+ if (!worktreeState) return message;
269
+ const suffix = `\n\n${COMPLETION_DIRECTIVE}`;
270
+ const content = message.content.endsWith(suffix)
271
+ ? `${message.content.slice(0, -suffix.length)}\n\n${worktreeState}${suffix}`
272
+ : `${message.content}\n\n${worktreeState}`;
273
+ return { ...message, content };
274
+ }
275
+
249
276
  /**
250
277
  * D1 + D2 matrix — the only knob-dependent logic. Delivery is always-on
251
278
  * (minimum `nextTurn`); the knob controls the WAKE (triggerTurn).
package/src/params.ts CHANGED
@@ -12,24 +12,25 @@
12
12
  * drive the REAL function (no more silent test drift).
13
13
  */
14
14
 
15
+ import type { Logger } from "./logging";
16
+ import type { SessionState } from "./state";
15
17
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
16
-
17
- import type {
18
- ThinkingLevel,
19
- SubagentPreset,
20
- GitMode,
21
- ApprovalMode,
22
- SubagentToolOptions,
23
- ResolvedParams,
24
- SnapshotParams,
25
- DelegateTaskParams,
18
+ import {
19
+ approvalBlocksBackground,
20
+ declaredThinkingLevel,
21
+ resolveThinkingLevel,
22
+ type ThinkingLevel,
23
+ type SubagentPreset,
24
+ type GitMode,
25
+ type ApprovalMode,
26
+ type SubagentToolOptions,
27
+ type ResolvedParams,
28
+ type SnapshotParams,
29
+ type DelegateTaskParams,
26
30
  } from "./types";
27
- import { approvalBlocksBackground, declaredThinkingLevel, resolveThinkingLevel } from "./types";
28
31
  import { getAllPresets, getPreset } from "./presets";
29
32
  import { classifyTask } from "./router";
30
33
  import { normalizeTimeout } from "./validate";
31
- import type { SessionState } from "./state";
32
- import type { Logger } from "./logging";
33
34
 
34
35
  // ---------------------------------------------------------------------------
35
36
  // delegate_task known keys (issue #99)
package/src/preflight.ts CHANGED
@@ -1,16 +1,34 @@
1
- // Purpose: Pre-spawn environment checks: pi binary, temp-dir writability, cwd readability.
1
+ // Purpose: Pre-spawn environment checks: pi binary, scratch-root writability, cwd readability.
2
2
  /**
3
3
  * brl-subagent — Pre-flight Checks (R3)
4
4
  *
5
5
  * Validates the execution environment before spawning a subagent.
6
- * Checks: pi binary availability, temp directory writability,
7
- * and project cwd readability.
6
+ * Checks: pi binary availability, **shipped scratch-root** writability (issue
7
+ * #511, U4 — the last probe of a system-temp path), and project cwd
8
+ * readability.
9
+ *
10
+ * THE THIRD CHECK IS AN EARLY WARNING, NOT THE AUTHORITY. It resolves the same
11
+ * root the spawn uses and proves a file can be created where the root lives or
12
+ * would be created; `prepareRunScratch` then re-resolves, re-validates the chain
13
+ * and creates `<root>/runs/<id>` at 0700 on every spawn. This check exists so a
14
+ * human learns before the dispatch does — never as the only place a bad root is
15
+ * caught.
16
+ *
17
+ * LIMITS, stated rather than implied: the probe CREATES nothing durable — a
18
+ * missing root stays missing (the spawn creates it), so a probe that passes on
19
+ * a writable ancestor says "the root can be created here", not "the root is
20
+ * sound"; a process killed between the write and the unlink leaves one 0600
21
+ * `.brl-preflight-probe-<pid>-<n>` file in the root or its nearest existing
22
+ * ancestor, recognisable and inert (nothing reads it, and no validation looks
23
+ * at it); and no system-temp
24
+ * path is probed, used as a fallback, or advised in a message any more
25
+ * (`src/__tests__/no-temp-paths` is the guard).
8
26
  */
9
27
 
10
28
  import * as fs from "node:fs";
11
- import * as os from "node:os";
12
29
  import * as path from "node:path";
13
30
  import { getPiInvocation } from "./runner";
31
+ import { FILE_MODE, resolveRoot, type RootOptions } from "./scratch-root";
14
32
 
15
33
  // ---------------------------------------------------------------------------
16
34
  // Types
@@ -18,6 +36,16 @@ import { getPiInvocation } from "./runner";
18
36
 
19
37
  export type PreflightResult = { ok: true } | { ok: false; error: string };
20
38
 
39
+ /** What a caller may inject. Production passes nothing. */
40
+ export interface PreflightOptions {
41
+ /**
42
+ * Root-resolution inputs (U1's seam), injected by tests only — `home` is the
43
+ * one that moves the layout. Production lets `resolveRoot` read the real
44
+ * environment.
45
+ */
46
+ root?: RootOptions;
47
+ }
48
+
21
49
  // ---------------------------------------------------------------------------
22
50
  // Checks
23
51
  // ---------------------------------------------------------------------------
@@ -117,24 +145,103 @@ function checkCwdReadable(cwd: string): PreflightResult {
117
145
  return { ok: true };
118
146
  }
119
147
 
148
+ /** The probe's one name, so a leftover from a killed process is recognisable as ours. */
149
+ const PROBE_PREFIX = ".brl-preflight-probe";
150
+
151
+ /**
152
+ * A per-process sequence, appended to the probe's name.
153
+ *
154
+ * The pid alone is not enough: `preflightCheck` runs BEFORE the concurrency slot
155
+ * is taken, so two overlapping dispatches in one process can probe at the same
156
+ * moment — and both would then write and unlink the SAME path, letting one
157
+ * call's unlink make the other report "not writable" for a directory that is
158
+ * perfectly writable. A distinct name per call removes the race without a lock.
159
+ */
160
+ let probeSequence = 0;
161
+
162
+ /**
163
+ * The probe's filename for THIS call: prefix, pid and a per-call sequence.
164
+ * Exported so a test can pin the part that matters — two calls must not share a
165
+ * name, because a pid-only name is exactly the race above.
166
+ */
167
+ export function nextProbeName(): string {
168
+ probeSequence += 1;
169
+ return `${PROBE_PREFIX}-${process.pid}-${probeSequence}`;
170
+ }
171
+
172
+ /**
173
+ * The nearest ancestor of `target` that exists — the directory a root that is
174
+ * not there yet would be CREATED in, and therefore the one that must be
175
+ * writable.
176
+ *
177
+ * `access` rather than `existsSync`: a directory we may not even look at is not
178
+ * a directory we can create in, and treating it as "missing" would walk past it
179
+ * and blame the wrong path. `dirname` is separator-agnostic and terminates at
180
+ * the filesystem root, which is returned as-is when nothing above exists.
181
+ */
182
+ function nearestExistingAncestor(target: string): string {
183
+ let current = target;
184
+ for (;;) {
185
+ try {
186
+ fs.accessSync(current, fs.constants.F_OK);
187
+ return current;
188
+ } catch {
189
+ const parent = path.dirname(current);
190
+ if (parent === current) return current;
191
+ current = parent;
192
+ }
193
+ }
194
+ }
195
+
120
196
  /**
121
- * Verify the system temp directory is writable by creating and
122
- * removing a small temporary file.
197
+ * Verify the shipped scratch root is writable, by creating and removing a
198
+ * 0600 probe file (issue #511, U4 — the replacement for the `os.tmpdir()`
199
+ * probe).
200
+ *
201
+ * WHERE it lands: inside the root when the root exists, otherwise in its
202
+ * nearest existing ancestor, because that is where the root would be created.
203
+ * A missing root is NOT a failure — the spawn creates it at 0700.
204
+ *
205
+ * WHERE the root comes from: `resolveRoot` (U1) with this module's injected
206
+ * inputs. PRODUCTION passes none, so the resolver reads the real environment;
207
+ * TESTS inject `{ home }`, the one input that moves the layout, which is why no
208
+ * test here reads or writes the developer's real cache root. There is
209
+ * deliberately NO module-level test redirect (the pattern `scratch-spawn.ts`
210
+ * uses): a global setup file that imported this module would load it BEFORE a
211
+ * suite registers `vi.mock("../runner")`, leaving this module bound to the real
212
+ * runner and silently defeating every suite whose preflight is supposed to see a
213
+ * mocked binary. The injected seam has no such ordering hazard.
214
+ *
215
+ * A refusal names the RESOLVED root, not the probe directory alone, so the line
216
+ * a human reads is the path the spawn would use. There is no "set TMPDIR"
217
+ * advice here: that advice belonged to the temp-dir probe this replaces, and the
218
+ * root is not configurable by an environment variable.
123
219
  */
124
- function checkTempWritable(): PreflightResult {
125
- const tmpDir = os.tmpdir();
126
- const testFile = path.join(tmpDir, `.brl-subagent-pcheck-${process.pid}`);
220
+ function checkScratchRootWritable(options: PreflightOptions): PreflightResult {
221
+ const resolved = resolveRoot(options.root);
222
+ if (!resolved.ok) {
223
+ // A resolver refusal (no home, a root that is a symlink, a foreign owner, a
224
+ // writable ancestor, a mode that is not 0700) IS a preflight failure, and
225
+ // the resolver's code travels with it: one taxonomy, no re-wording.
226
+ return {
227
+ ok: false,
228
+ error: `Scratch root could not be resolved (${resolved.code}): ${resolved.message}`,
229
+ };
230
+ }
231
+
232
+ const probeDir = nearestExistingAncestor(resolved.root);
233
+ const probeFile = path.join(probeDir, nextProbeName());
127
234
 
128
235
  try {
129
- fs.writeFileSync(testFile, "ok", { encoding: "utf-8", mode: 0o600 });
130
- fs.unlinkSync(testFile);
236
+ fs.writeFileSync(probeFile, "ok", { encoding: "utf-8", mode: FILE_MODE });
237
+ fs.unlinkSync(probeFile);
131
238
  return { ok: true };
132
239
  } catch (err) {
133
240
  const message = err instanceof Error ? err.message : String(err);
134
241
  return {
135
242
  ok: false,
136
- error: `System temp directory (${tmpDir}) is not writable: ${message}. ` +
137
- "Set TMPDIR or TEMP to a writable directory.",
243
+ error: `Scratch root (${resolved.root}) is not writable: ${message}. ` +
244
+ `brl-subagent banks each run's progress under this root, so ${probeDir} must be writable by you.`,
138
245
  };
139
246
  }
140
247
  }
@@ -152,15 +259,15 @@ function checkTempWritable(): PreflightResult {
152
259
  * Call this BEFORE acquiring a concurrency slot to avoid wasting
153
260
  * resources on a doomed spawn.
154
261
  */
155
- export function preflightCheck(cwd: string): PreflightResult {
262
+ export function preflightCheck(cwd: string, options: PreflightOptions = {}): PreflightResult {
156
263
  const piResult = checkPiBinary();
157
264
  if (!piResult.ok) return piResult;
158
265
 
159
266
  const cwdResult = checkCwdReadable(cwd);
160
267
  if (!cwdResult.ok) return cwdResult;
161
268
 
162
- const tempResult = checkTempWritable();
163
- if (!tempResult.ok) return tempResult;
269
+ const scratchResult = checkScratchRootWritable(options);
270
+ if (!scratchResult.ok) return scratchResult;
164
271
 
165
272
  return { ok: true };
166
273
  }
package/src/prelude.ts CHANGED
@@ -45,11 +45,20 @@
45
45
  * extra log fields.
46
46
  */
47
47
 
48
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
49
- import type { ApprovalMode, GitMode, SubagentPreset, SubagentToolOptions, ThinkingLevel, ToolResult } from "./types";
50
- import { approvalBlocksBackground, isThinkingLevel, THINKING_LEVELS } from "./types";
51
- import type { SessionState } from "./state";
52
48
  import type { Logger } from "./logging";
49
+ import type { SessionState } from "./state";
50
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
51
+ import {
52
+ approvalBlocksBackground,
53
+ isThinkingLevel,
54
+ THINKING_LEVELS,
55
+ type ApprovalMode,
56
+ type GitMode,
57
+ type SubagentPreset,
58
+ type SubagentToolOptions,
59
+ type ThinkingLevel,
60
+ type ToolResult,
61
+ } from "./types";
53
62
  import { validateCwd, validateOutputFile } from "./sanitize";
54
63
  import { validatePreTask, type ValidateConfig } from "./validate";
55
64
  import { modelIsAvailable, parseModelString } from "./model-availability";
@@ -308,7 +317,7 @@ export function runPreTaskValidation(input: {
308
317
 
309
318
  /**
310
319
  * A merged per-unit source, structurally (mergeSubTaskParams lives in
311
- * index.ts and is passed in by the handler). These are the fields the
320
+ * unit-params.ts and is passed in by the handler). These are the fields the
312
321
  * pre-pass reads; the handler's own type is preserved through the generic
313
322
  * `M` so it can build its mode-specific unit records from the result.
314
323
  */
package/src/presets.ts CHANGED
@@ -7,13 +7,11 @@
7
7
  * Custom presets are stored in session state.
8
8
  */
9
9
 
10
+ import type { Logger } from "./logging";
10
11
  import * as fs from "node:fs";
11
12
  import * as path from "node:path";
12
- import type { SubagentPreset, ThinkingLevel } from "./types";
13
- import { THINKING_LEVELS } from "./types";
14
- import type { Logger } from "./logging";
15
- import { applyFrontmatterMappers, loadMarkdownRecords } from "./loader";
16
- import type { FrontmatterFieldMapper, FrontmatterMapContext } from "./loader";
13
+ import { THINKING_LEVELS, type SubagentPreset, type ThinkingLevel } from "./types";
14
+ import { applyFrontmatterMappers, loadMarkdownRecords, type FrontmatterFieldMapper, type FrontmatterMapContext } from "./loader";
17
15
 
18
16
  // `parseFrontmatter` moved to loader.ts when the four loader copies collapsed
19
17
  // into one walk (issue #380). Re-exported so the existing import sites keep
package/src/proc.ts CHANGED
@@ -18,12 +18,11 @@
18
18
  * that platform guard without mocking `node:fs` module-wide.
19
19
  */
20
20
 
21
+ import type { RecoveryDeps } from "./recovery-engine";
21
22
  import * as fs from "node:fs";
22
23
  import * as path from "node:path";
23
- import type { ProcessOwner } from "./types";
24
- import { SIGKILL_GRACE_MS, SIGKILL_POLL_MS } from "./types";
24
+ import { SIGKILL_GRACE_MS, SIGKILL_POLL_MS, type ProcessOwner } from "./types";
25
25
  import { CHILD_MARKER_ENV_KEY } from "./sanitize";
26
- import type { RecoveryDeps } from "./recovery-engine";
27
26
  import { supportsProcessGroupKill } from "./kill-escalation";
28
27
 
29
28
  const PROC_ROOT = "/proc";
@@ -23,10 +23,10 @@
23
23
  * every pid, wait one grace window, SIGKILL any survivor.
24
24
  */
25
25
 
26
+ import type { Logger } from "./logging";
26
27
  import type { ProcessOwner, SubagentRun } from "./types";
27
28
  import { resolveTerminalRunEntry } from "./state";
28
29
  import { escalateKill, processTarget, type SignalGuard, type SignalPhase } from "./kill-escalation";
29
- import type { Logger } from "./logging";
30
30
 
31
31
  // ---------------------------------------------------------------------------
32
32
  // Dependency injection surface
@@ -28,8 +28,7 @@
28
28
  */
29
29
 
30
30
  import { listInflightRuns, type InflightRun, type InflightRunKind } from "./run-registry";
31
- import type { SubagentRun } from "./types";
32
- import { isInterruptedRun, runRecoveryPosture, type RecoveryMode } from "./types";
31
+ import { isInterruptedRun, runRecoveryPosture, type RecoveryMode, type SubagentRun } from "./types";
33
32
  import { resolveTerminalRunEntry } from "./state";
34
33
  import { sortNewestFirst } from "./history";
35
34
  import { claimTerminalNotice, type DeliveryResolution } from "./notify-completion";