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,69 @@
1
+ // Purpose: Builds the project's `<engineering-bar>` system-prompt section for every child spawn (issue #421).
2
+ /**
3
+ * Issue #421 — the engineering bar is injected, never selected.
4
+ *
5
+ * The bar lived in the repo-local `project-implementer`/`project-reviewer`
6
+ * presets, and four dispatches (#411, #412, #415, #419) ran on the shipped
7
+ * `dev-agent` preset, which has no bar text at all. A per-dispatch choice is not
8
+ * a mechanism. The bar is therefore read from ONE tracked file
9
+ * (`.pi/skills/worktree/references/engineering-bar.md`) and appended to the
10
+ * child's system prompt at both spawn seams — whatever preset the conductor
11
+ * picked.
12
+ *
13
+ * The gate is the umbrella `processChecks` flag (ADR 0019), read through
14
+ * `project-flags.ts` and nowhere else: in a user's project the bar is neither
15
+ * injected nor read. Fail-open by contract — a missing or broken manifest means
16
+ * no injection, never a failed spawn.
17
+ *
18
+ * Failure to READ the bar is the one non-fail-open case, and it is loud: a
19
+ * missing or empty reference file logs one warning and skips the section. It
20
+ * never throws into a spawn, and it never skips silently — a silently
21
+ * unenforced bar is exactly the drift this issue exists to end.
22
+ *
23
+ * The section is built HERE as a complete framed string (not interpolated by
24
+ * the callers) so `session-manager.ts`'s sections builder keeps interpolating
25
+ * only the two charset-bounded caller fields pinned by its neutralization
26
+ * ratchet. The bar's content needs no marker neutralization: its source is a
27
+ * tracked repository file, not LLM-controlled output.
28
+ */
29
+
30
+ import type { Logger } from "./logging";
31
+ import { readFileSync } from "node:fs";
32
+ import { join } from "node:path";
33
+ import { isProcessChecksEnabled } from "./project-flags";
34
+
35
+ /** The tracked reference, relative to the project root. */
36
+ export const ENGINEERING_BAR_PATH = ".pi/skills/worktree/references/engineering-bar.md";
37
+
38
+ /**
39
+ * The `<engineering-bar>` section for a child spawned at `cwd`, or `null` when
40
+ * the project has not opted in or the reference is missing/empty.
41
+ *
42
+ * `log` is caller-supplied (dependency inversion): each seam passes the logger
43
+ * it already owns, so the warning lands in the same sink as the rest of that
44
+ * spawn's diagnostics — and a test can assert the warning without a filesystem
45
+ * sink.
46
+ */
47
+ export function buildEngineeringBarSection(cwd: string | undefined, log: Logger): string | null {
48
+ // `!cwd` is type narrowing, not a second gate: `project-flags.ts` owns the
49
+ // flag's semantics, and it reads a missing cwd as disabled too.
50
+ if (!cwd || !isProcessChecksEnabled(cwd)) return null;
51
+
52
+ const file = join(cwd, ENGINEERING_BAR_PATH);
53
+ let body: string;
54
+ try {
55
+ body = readFileSync(file, "utf8").trim();
56
+ } catch (err) {
57
+ log.warn("engineering bar: reference file unreadable — section skipped", {
58
+ path: file,
59
+ error: (err as Error).message,
60
+ });
61
+ return null;
62
+ }
63
+ if (body === "") {
64
+ log.warn("engineering bar: reference file is empty — section skipped", { path: file });
65
+ return null;
66
+ }
67
+
68
+ return `\n<engineering-bar>\n${body}\n</engineering-bar>\n`;
69
+ }
package/src/event-bus.ts CHANGED
@@ -27,6 +27,16 @@ export function on(type: SubagentEventType, listener: SubagentEventListener): vo
27
27
  typeListeners.add(listener);
28
28
  }
29
29
 
30
+ /**
31
+ * TEST-ONLY (issue #437): the listener identities currently registered for a
32
+ * type, in registration order. Read-only snapshot — the lifecycle suite uses it
33
+ * to assert that a shut-down runtime removed exactly its own listeners and that
34
+ * repeated clean generations do not accumulate.
35
+ */
36
+ export function __listenerIdentities(type: SubagentEventType): SubagentEventListener[] {
37
+ return [...(listeners.get(type) ?? [])];
38
+ }
39
+
30
40
  /**
31
41
  * Unsubscribe a listener from a specific event type.
32
42
  *
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
@@ -101,16 +112,79 @@ export function hasUncommittedChanges(cwd: string): boolean {
101
112
  return output.trim().length > 0;
102
113
  }
103
114
 
115
+ /**
116
+ * Mint a work-branch name.
117
+ *
118
+ * Issue #466 (ADR 0026 D1): the name is generated by the CALLER, not inside
119
+ * `createWorkBranch`, because the durable head-state record must name the branch
120
+ * it is about and is written BEFORE the branch exists (the write-ahead property
121
+ * that makes a crash inside `createWorkBranch` recoverable). This function is
122
+ * the only producer of the `brl-subagent-` prefix in the source tree.
123
+ */
124
+ export function newWorkBranchName(): string {
125
+ return "brl-subagent-" + crypto.randomUUID().slice(0, 8);
126
+ }
127
+
128
+ /**
129
+ * The branch HEAD points at, and whether it has a commit yet.
130
+ *
131
+ * `branch` is undefined for a detached HEAD. `unborn` is true when HEAD is a
132
+ * symbolic ref to a branch that does not exist (a branch deleted while it was
133
+ * checked out): `git checkout <some-branch>` still works there, but
134
+ * `git status --porcelain` reports every tracked file as changed, so callers
135
+ * that gate on a clean tree must know the difference.
136
+ */
137
+ export interface HeadBranch {
138
+ branch: string | undefined;
139
+ unborn: boolean;
140
+ }
141
+
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 {
150
+ let branch: string | undefined;
151
+ try {
152
+ branch = execFileSync("git", ["symbolic-ref", "--short", "-q", "HEAD"], gitOpts(cwd, timeoutMs)).trim() || undefined;
153
+ } catch {
154
+ // Detached (or not a repo): no symbolic ref to read.
155
+ branch = undefined;
156
+ }
157
+ let unborn = false;
158
+ try {
159
+ execFileSync("git", ["rev-parse", "--verify", "-q", "HEAD"], gitOpts(cwd, timeoutMs));
160
+ } catch {
161
+ unborn = true;
162
+ }
163
+ return { branch, unborn };
164
+ }
165
+
166
+ /** The repository's work branches (`brl-subagent-*`), short names. */
167
+ export function listWorkBranches(cwd: string): string[] {
168
+ const output = execFileSync("git", ["branch", "--list", "brl-subagent-*", "--format=%(refname:short)"], gitOpts(cwd));
169
+ return output
170
+ .split("\n")
171
+ .map((line) => line.trim())
172
+ .filter((line) => line.length > 0);
173
+ }
174
+
104
175
  /**
105
176
  * Create a work branch from the given base branch.
106
177
  * Returns { ok: true, branch } on success, { ok: false, error } on failure.
178
+ *
179
+ * Issue #466: `branch` is a parameter (defaulted for existing callers) so a
180
+ * caller can record the name in the durable head state BEFORE this runs.
107
181
  */
108
182
  export function createWorkBranch(
109
183
  cwd: string,
110
184
  baseBranch: string,
185
+ branch: string = newWorkBranchName(),
111
186
  ): { ok: true; branch: string } | { ok: false; error: string } {
112
187
  try {
113
- const branch = "brl-subagent-" + crypto.randomUUID().slice(0, 8);
114
188
  execFileSync("git", ["checkout", "-b", branch, baseBranch], gitOpts(cwd));
115
189
  return { ok: true, branch };
116
190
  } catch (err) {
@@ -268,3 +342,198 @@ export function captureWorkingDiff(cwd: string): string | undefined {
268
342
  return undefined;
269
343
  }
270
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
+ }