brl-subagent 2.8.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 (47) hide show
  1. package/AGENT.md +1 -1
  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 +313 -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 +1 -1
  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 +2 -3
  28. package/src/reports.ts +1 -7
  29. package/src/run-registry.ts +2 -3
  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/scratch-root.ts +909 -0
  35. package/src/scratch-spawn.ts +256 -0
  36. package/src/session-manager.ts +75 -7
  37. package/src/state.ts +12 -14
  38. package/src/templates.ts +3 -5
  39. package/src/terminal-notifier.ts +405 -0
  40. package/src/transcript.ts +1 -1
  41. package/src/tui-format.ts +3 -1
  42. package/src/tui.ts +42 -32
  43. package/src/types.ts +29 -3
  44. package/src/unit-params.ts +113 -0
  45. package/src/unit-run.ts +35 -15
  46. package/src/validate.ts +2 -3
  47. package/src/worktree-report.ts +142 -0
@@ -27,9 +27,9 @@
27
27
  * tracked repository file, not LLM-controlled output.
28
28
  */
29
29
 
30
+ import type { Logger } from "./logging";
30
31
  import { readFileSync } from "node:fs";
31
32
  import { join } from "node:path";
32
- import type { Logger } from "./logging";
33
33
  import { isProcessChecksEnabled } from "./project-flags";
34
34
 
35
35
  /** The tracked reference, relative to the project root. */
package/src/git.ts CHANGED
@@ -1,22 +1,33 @@
1
- // Purpose: Branch-based git workflow for worktree runs: branch creation, diff capture, switch-back, cleanup.
1
+ // Purpose: Branch-based git workflow for worktree runs (branch, diff, switch-back, cleanup) plus the read-only worktree probe.
2
2
  /**
3
3
  * brl-subagent — Git Integration (P3)
4
4
  *
5
5
  * Branch-based git workflow for subagent isolation.
6
- * All git commands use execFileSync with a 10-second timeout.
6
+ * All git commands use execFileSync, with a 10-second default timeout.
7
+ *
8
+ * Issue #474 added `probeWorktree` — the READ-ONLY half: it reports what a
9
+ * settled-failure run may have left behind, and it must not write (the index
10
+ * refresh `git status` performs opportunistically is exactly the write the
11
+ * caller is trying to avoid). It is also the only entry point here that never
12
+ * throws: a probe failure is a classified value, so reporting can never change
13
+ * a run's failure classification.
7
14
  */
8
15
 
9
16
  import { execFileSync } from "node:child_process";
17
+ import * as fs from "node:fs";
18
+
19
+ /** Default bound for one git command (the long-standing 10 s). */
20
+ const GIT_TIMEOUT_MS = 10_000;
10
21
 
11
22
  // ---------------------------------------------------------------------------
12
23
  // Options for git commands
13
24
  // ---------------------------------------------------------------------------
14
25
 
15
- function gitOpts(cwd: string) {
26
+ function gitOpts(cwd: string, timeoutMs: number = GIT_TIMEOUT_MS) {
16
27
  return {
17
28
  cwd,
18
29
  encoding: "utf-8" as const,
19
- timeout: 10_000,
30
+ timeout: timeoutMs,
20
31
  // Capture child stderr instead of inheriting it: expected git failures
21
32
  // (e.g. deleting a checked-out branch) are caught and returned as
22
33
  // {ok:false, error}; execFileSync still puts the captured stderr in the
@@ -128,18 +139,24 @@ export interface HeadBranch {
128
139
  unborn: boolean;
129
140
  }
130
141
 
131
- /** Read the current HEAD branch tolerate-ably (detached and unborn included). */
132
- export function getHeadBranch(cwd: string): HeadBranch {
142
+ /** Read the current HEAD branch tolerate-ably (detached and unborn included).
143
+ *
144
+ * `timeoutMs` exists for the #474 probe, which must keep its own short bound:
145
+ * the detached/unborn semantics belong here (a second copy of "a failed
146
+ * symbolic-ref read means detached" is exactly the drift this helper
147
+ * prevents), but the probe's budget is not the 10 s the lifecycle calls use.
148
+ */
149
+ export function getHeadBranch(cwd: string, timeoutMs: number = GIT_TIMEOUT_MS): HeadBranch {
133
150
  let branch: string | undefined;
134
151
  try {
135
- branch = execFileSync("git", ["symbolic-ref", "--short", "-q", "HEAD"], gitOpts(cwd)).trim() || undefined;
152
+ branch = execFileSync("git", ["symbolic-ref", "--short", "-q", "HEAD"], gitOpts(cwd, timeoutMs)).trim() || undefined;
136
153
  } catch {
137
154
  // Detached (or not a repo): no symbolic ref to read.
138
155
  branch = undefined;
139
156
  }
140
157
  let unborn = false;
141
158
  try {
142
- execFileSync("git", ["rev-parse", "--verify", "-q", "HEAD"], gitOpts(cwd));
159
+ execFileSync("git", ["rev-parse", "--verify", "-q", "HEAD"], gitOpts(cwd, timeoutMs));
143
160
  } catch {
144
161
  unborn = true;
145
162
  }
@@ -325,3 +342,198 @@ export function captureWorkingDiff(cwd: string): string | undefined {
325
342
  return undefined;
326
343
  }
327
344
  }
345
+
346
+ // ---------------------------------------------------------------------------
347
+ // Read-only worktree probe (issue #474)
348
+ // ---------------------------------------------------------------------------
349
+
350
+ /**
351
+ * One git command inside the probe. The probe makes FIVE short reads —
352
+ * `rev-parse`, `status`, the two inside `getHeadBranch` (`symbolic-ref` +
353
+ * `rev-parse --verify`), and `diff --shortstat` — so its worst case is
354
+ * 5 × this bound (~15 s) on a host where every one hangs, and milliseconds
355
+ * when git is healthy. The bound is per command on purpose: the branch reads
356
+ * are shared with `getHeadBranch` (their detached/unborn semantics are not
357
+ * re-implemented here), and the failure path may wait, but not forever.
358
+ */
359
+ const PROBE_TIMEOUT_MS = 3_000;
360
+
361
+ /**
362
+ * Every probe read is a READ, and `git status` / `git diff` are only read-only
363
+ * by intent: without `GIT_OPTIONAL_LOCKS=0` git refreshes `.git/index` as an
364
+ * optional side effect, so the "read" moves a file in the tree it is reporting
365
+ * (measured: identical bytes, changed mtime — the index-safe test pins both).
366
+ * `LC_ALL=C` pins `--shortstat` to the parseable English wording.
367
+ */
368
+ function probeOpts(cwd: string) {
369
+ return {
370
+ cwd,
371
+ encoding: "utf-8" as const,
372
+ timeout: PROBE_TIMEOUT_MS,
373
+ stdio: ["ignore", "pipe", "pipe"] as ["ignore", "pipe", "pipe"],
374
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" },
375
+ };
376
+ }
377
+
378
+ /** What the probe found, or why it could not look (issue #474). */
379
+ export type WorktreeProbe =
380
+ | {
381
+ kind: "ok";
382
+ /** The checked-out branch; undefined when HEAD is detached. */
383
+ branch: string | undefined;
384
+ detached: boolean;
385
+ /** HEAD is a symbolic ref to a branch with no commit yet. */
386
+ unborn: boolean;
387
+ /** Entries with worktree changes, plus untracked files. */
388
+ dirtyFiles: number;
389
+ /** Entries with index changes (never the `??` untracked rows). */
390
+ stagedFiles: number;
391
+ /** Tracked unstaged line counts; absent when `git diff` reported none (or failed). */
392
+ insertions?: number;
393
+ deletions?: number;
394
+ }
395
+ /** The cwd is not inside a git repository (or is a bare repo). */
396
+ | { kind: "not-repo" }
397
+ /** The repository could not be read; `reason` is git's own diagnosis. */
398
+ | { kind: "unavailable"; reason: string };
399
+
400
+ /** Longest reason reported — the block rides a tool result, not a log file. */
401
+ const MAX_PROBE_REASON_LENGTH = 160;
402
+
403
+ /**
404
+ * The first line git printed, as the reason. git's stderr is the diagnosable
405
+ * half AND the safe half: the wrapper message `execFileSync` builds names the
406
+ * command line, and for a vanished cwd it names the absolute path (F7 — the
407
+ * failure path must never echo the cwd raw). Measured: an `ENOENT`/`ETIMEDOUT`
408
+ * spawn carries an EMPTY stderr, so those classify below instead.
409
+ *
410
+ * A deleted cwd and a missing git both surface as `ENOENT` (node reports the
411
+ * failed spawn, not which half failed), so the cwd is probed to tell them
412
+ * apart — the two need different fixes and the report is the reader's only
413
+ * evidence.
414
+ */
415
+ function probeFailureReason(cwd: string, err: unknown): string {
416
+ const stderr = (err as { stderr?: unknown } | null)?.stderr;
417
+ const text = typeof stderr === "string" ? stderr : stderr ? String(stderr) : "";
418
+ const line = text
419
+ .split("\n")
420
+ .map((part) => part.trim())
421
+ .find((part) => part.length > 0);
422
+ if (line) {
423
+ return line.length > MAX_PROBE_REASON_LENGTH ? `${line.slice(0, MAX_PROBE_REASON_LENGTH)}…` : line;
424
+ }
425
+ const code = (err as { code?: unknown } | null)?.code;
426
+ if (code === "ETIMEDOUT") return "git timed out";
427
+ if (code === "ENOENT") return fs.existsSync(cwd) ? "git is not installed" : "cwd does not exist";
428
+ if (typeof code === "string") return `git failed (${code})`;
429
+ return "git failed";
430
+ }
431
+
432
+ /**
433
+ * Classify a failed `rev-parse --is-inside-work-tree`: git's own "not a git
434
+ * repository" is the ONE expected failure (it is the answer, not an error),
435
+ * and everything else — a deleted cwd, a missing git, a timeout — is
436
+ * unavailable with a reason. `getRepoRoot`'s catch-all is deliberately NOT
437
+ * reused: it returns undefined for both cases, which would report a hung git
438
+ * as "not a git repository".
439
+ */
440
+ function classifyProbeFailure(cwd: string, err: unknown): WorktreeProbe {
441
+ const reason = probeFailureReason(cwd, err);
442
+ if (/not a git repository/i.test(reason)) return { kind: "not-repo" };
443
+ return { kind: "unavailable", reason };
444
+ }
445
+
446
+ /**
447
+ * Count `git status --porcelain -z` rows, split into worktree-dirty and staged.
448
+ *
449
+ * `-z` means NUL-separated records and never-quoted paths, and it changes the
450
+ * rename shape: `R <new>\0<old>` — the destination row followed by a BARE
451
+ * source path. Counting NUL fields would read one `git mv` as two dirty files,
452
+ * so the source field is skipped (and only renames/copies emit one).
453
+ */
454
+ function countStatusEntries(porcelain: string): { dirty: number; staged: number } {
455
+ let dirty = 0;
456
+ let staged = 0;
457
+ let skipNext = false;
458
+ for (const field of porcelain.split("\0")) {
459
+ if (field.length === 0) continue;
460
+ if (skipNext) {
461
+ skipNext = false;
462
+ continue;
463
+ }
464
+ const x = field[0];
465
+ const y = field[1];
466
+ if (x === undefined || y === undefined) continue;
467
+ if (x === "?") {
468
+ dirty++; // untracked file (or, with -uall, every file in an untracked dir)
469
+ continue;
470
+ }
471
+ if (x === "R" || x === "C") skipNext = true;
472
+ if (y !== " ") dirty++;
473
+ if (x !== " ") staged++;
474
+ }
475
+ return { dirty, staged };
476
+ }
477
+
478
+ /** ` 3 files changed, 10 insertions(+), 2 deletions(-)` → line counts, or undefined. */
479
+ function parseShortstat(output: string): { insertions: number; deletions: number } | undefined {
480
+ if (!/\d+ files? changed/.test(output)) return undefined;
481
+ const insertions = /(\d+) insertions?\(\+\)/.exec(output);
482
+ const deletions = /(\d+) deletions?\(-\)/.exec(output);
483
+ return {
484
+ insertions: insertions ? Number(insertions[1]) : 0,
485
+ deletions: deletions ? Number(deletions[1]) : 0,
486
+ };
487
+ }
488
+
489
+ /**
490
+ * Report the state of the worktree at `cwd` — branch, dirty/staged counts,
491
+ * unstaged line counts — for the failure report (issue #474). NEVER THROWS:
492
+ * every failure is a classified value.
493
+ *
494
+ * This is a BEST-EFFORT read of a moving tree, not an atomic snapshot: the
495
+ * status and the diff are two commands, so a write between them can make the
496
+ * counts disagree with each other. It is deliberately not made consistent —
497
+ * the reader is a conductor deciding whether to look before reusing the tree,
498
+ * and a torn count is still evidence, while a lock (or a second retry) on the
499
+ * failure path is not.
500
+ */
501
+ export function probeWorktree(cwd: string): WorktreeProbe {
502
+ let inside: string;
503
+ try {
504
+ inside = execFileSync("git", ["rev-parse", "--is-inside-work-tree"], probeOpts(cwd)).trim();
505
+ } catch (err) {
506
+ return classifyProbeFailure(cwd, err);
507
+ }
508
+ // A bare repository exits 0 with "false" — there is no worktree to report.
509
+ if (inside !== "true") return { kind: "not-repo" };
510
+
511
+ let porcelain: string;
512
+ try {
513
+ porcelain = execFileSync("git", ["status", "--porcelain", "-z", "-uall"], probeOpts(cwd));
514
+ } catch (err) {
515
+ return { kind: "unavailable", reason: probeFailureReason(cwd, err) };
516
+ }
517
+ const { dirty, staged } = countStatusEntries(porcelain);
518
+ // Undefined branch + not unborn = detached HEAD (getHeadBranch owns that reading).
519
+ const head = getHeadBranch(cwd, PROBE_TIMEOUT_MS);
520
+
521
+ // The line counts are the optional half: losing them costs a detail, never
522
+ // the report, so a failed `diff` degrades the block instead of emptying it.
523
+ let lineCounts: { insertions: number; deletions: number } | undefined;
524
+ try {
525
+ lineCounts = parseShortstat(execFileSync("git", ["diff", "--shortstat"], probeOpts(cwd)));
526
+ } catch {
527
+ lineCounts = undefined;
528
+ }
529
+
530
+ return {
531
+ kind: "ok",
532
+ branch: head.branch,
533
+ detached: head.branch === undefined && !head.unborn,
534
+ unborn: head.unborn,
535
+ dirtyFiles: dirty,
536
+ stagedFiles: staged,
537
+ ...(lineCounts ?? {}),
538
+ };
539
+ }
package/src/headstate.ts CHANGED
@@ -32,13 +32,13 @@
32
32
  * restores the recorded base and keeps the branch.
33
33
  */
34
34
 
35
+ import type { HeadState } from "./git";
36
+ import type { OwnerState } from "./recovery-engine";
37
+ import type { ProcessOwner } from "./types";
35
38
  import { createHash } from "node:crypto";
36
39
  import { existsSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
37
40
  import { basename, join, resolve } from "node:path";
38
- import type { HeadState } from "./git";
39
- import type { OwnerState } from "./recovery-engine";
40
41
  import { ensureOwnerOnlyDir } from "./store-permissions";
41
- import type { ProcessOwner } from "./types";
42
42
 
43
43
  /** On-disk record version. A record with any other value is `skip-record`. */
44
44
  export const HEAD_STATE_VERSION = 1;
package/src/history.ts CHANGED
@@ -6,11 +6,22 @@
6
6
  * and duration formatting.
7
7
  */
8
8
 
9
- import type { SubagentRun, SubagentResult } from "./types";
10
- import { isSubagentError, getFinalOutput, isSubagentRunShape, classifyError, coherentFailureReason, CUSTOM_ENTRY_TYPES, MAX_RUN_HISTORY_ENTRIES, DEFAULT_OUTPUT_CAP_BYTES } from "./types";
9
+ import type { ExtensionContext, SessionManager } from "@earendil-works/pi-coding-agent";
10
+ import {
11
+ isSubagentError,
12
+ getFinalOutput,
13
+ isSubagentRunShape,
14
+ classifyError,
15
+ coherentFailureReason,
16
+ CUSTOM_ENTRY_TYPES,
17
+ MAX_RUN_HISTORY_ENTRIES,
18
+ DEFAULT_OUTPUT_CAP_BYTES,
19
+ type SubagentRun,
20
+ type SubagentResult,
21
+ } from "./types";
11
22
  import { isOutputTruncated } from "./sanitize";
23
+ import { markSettled } from "./scratch-spawn";
12
24
  import { transcriptDisplayPath } from "./transcript-path";
13
- import type { ExtensionContext, SessionManager } from "@earendil-works/pi-coding-agent";
14
25
 
15
26
  // ---------------------------------------------------------------------------
16
27
  // Run pruning — R2: Disk usage policy
@@ -129,6 +140,13 @@ export function finalizeRunRecord(
129
140
  : result.stopReason;
130
141
  run.outputSummary = finalOutput.slice(0, 200);
131
142
  run.fullOutput = finalOutput || undefined;
143
+ // Issue #511 (U2): settling includes the scratch directory's `.done` marker,
144
+ // and this is the ONE function every foreground terminal path calls — the
145
+ // success, failure, crash and pre-start-rejection arms all land here — so the
146
+ // marker cannot be forgotten by a future caller. Best-effort by contract:
147
+ // `markSettled` logs a failure and never throws, and it is a no-op for a run
148
+ // with no scratch directory to mark.
149
+ markSettled(run);
132
150
  }
133
151
 
134
152
  // ---------------------------------------------------------------------------