brl-subagent 2.6.0 → 2.8.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.
package/AGENT.md CHANGED
@@ -41,6 +41,7 @@ delegation-heavy work.
41
41
  - Delivery mode by status holds at knob `"all"`: `failed`/`stopped` → steering you to act; `completed` → follow-up. The `completionNotify` knob changes both the delivery mode and the wake: under `"failed"` a `completed` run is delivered as a passive `nextTurn` (no wake) while `failed`/`stopped` still steer; under `"off"` everything is a passive `nextTurn` and nothing wakes you. (The knob controls whether an idle conductor is triggered — see below.)
42
42
  - Knob dependency: polling is correct only when wakes are disabled (`completionNotify: "off"`). The wake is per-terminal-status and knob-scoped: under `"all"` a terminal run always wakes you; under `"failed"` only a `failed` or `stopped` run wakes you — a `completed` run stays a passive `nextTurn` (no wake); under `"off"` nothing wakes you. So repeated polling is wrong; a single status check as a stall check is legitimate, and a status check is needed only when the knob will not wake you for that outcome (`"off"`, or a `completed` run under `"failed"`).
43
43
  - One message per run — the extension deduplicates on the first terminal event for a run id, so don't expect multiple messages for a single run. A fan-out wakes you once per agent — still one message per run (each agent is its own run), never coalesced.
44
+ - **Transport failures auto-retry once.** A background run whose conductor-side transport dropped (`exit_error` with a connection/network signature — `Connection error.`, `ECONNRESET`, `socket hang up`, `fetch failed`, `ETIMEDOUT`, …) is re-dispatched **once** with its recorded task and params, recorded as `attempt: 2` (`resumeOf` the source). The retry's **system prompt** carries a short `<resume-context>` resume block — inspect `git status --short`, the recent history, the `/tmp/brl-<label>-bank.md` progress bank, and the previous attempt's retained session directory when it exists — so it continues from what survived a drop instead of redoing it. The settle path keeps that directory for exactly this class of failure (marked `.transport-retained`, bounded to 5 dirs / 50 MB / 14 days by a sweep at the same choke point), so the retry can read the conversation attempt 1 lost. The block is system-prompt-only (outside the `<task>` fence): routing, thinking, model and the capability pre-flight still see the recorded original task, which stays byte-identical to the original — the spawn result's `Task:` line therefore no longer shows the resume marker (`attempt`/`resumeOf` carry that lineage). The source run's completion message is suppressed and replaced by a warning toast, so the retry's own settle is the wake you get — do not re-dispatch it yourself. A second transport failure surfaces as an ordinary failure; non-transport failures, foreground runs, and fan-out units are never auto-retried (`retryRunId` stays your call for those).
44
45
  - Honest records: trust the message's `errorCategory`/abort source over your own guess. The provider/abort origin is authoritative on why the run stopped.
45
46
  - Steering is not an abort. Being steered to act on a terminal run is not terminating it. A real `stop` is an abort — and a stopped run still wakes you.
46
47
 
@@ -77,8 +78,8 @@ delegation-heavy work.
77
78
 
78
79
  ## Deadlines and retries
79
80
 
80
- - `timeout` (ms) is a **deadline, not a ceiling** — an explicit value is honored as given; 30 minutes is only the default for a background run that passes none (a foreground run is not capped). Background expiry aborts the session (the run ends `stopped`); foreground expiry kills the process. Because background is now the default under `auto`, remember the 30-minute deadline: pass an explicit `timeout` for anything expected to run longer.
81
- - `retryOnTimeout` applies to **foreground runs only**. A timed-out background run is not auto-retried: re-dispatch it with `retryRunId` if that is the right call. The same applies to an interrupted run — recovery is always an explicit `retryRunId` call, never automatic (auto mode is not yet accepted).
81
+ - `timeout` (ms) is a **deadline, not a ceiling** — an explicit value is honored as given; 30 minutes is only the default for a background run that passes none (a foreground run is not capped). Background expiry aborts the session (the agent ends `stopped`, the run record is `failed`/`timeout`); foreground expiry kills the process. Because background is now the default under `auto`, remember the 30-minute deadline: pass an explicit `timeout` for anything expected to run longer.
82
+ - `retryOnTimeout` applies to **foreground runs only**. A timed-out background run is not auto-retried on the deadline: re-dispatch it with `retryRunId` if that is the right call. The one automatic retry is the **transport-class** one above — a background run that died on a dropped connection is replayed once. The same applies to an interrupted run — recovery is always an explicit `retryRunId` call, never automatic (auto mode is not yet accepted). A run recorded before its prompt was ever issued is settled as **failed**, so the retry menu never lists it as interrupted.
82
83
 
83
84
  ## Mechanics pointer
84
85
 
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > Multi-agent orchestration for [pi](https://github.com/earendil-works/pi) — chain, parallel, and dependency-graph delegation to isolated subagents with per-step model routing, preset-driven tool scoping, thinking-level control, and background execution with live monitoring, real abort, and per-agent timeouts.
4
4
 
5
- **Version:** 2.6.0 · **Author:** Azmeen Afandi / [Beeroo Labs](https://beeroolabs.com) · **License:** MIT
5
+ **Version:** 2.8.0 · **Author:** Azmeen Afandi / [Beeroo Labs](https://beeroolabs.com) · **License:** MIT
6
6
 
7
7
  ---
8
8
 
@@ -14,7 +14,7 @@
14
14
  - **True background execution** — live monitor, real abort (`stop_subagent`), per-agent timeouts, and a 30-minute default deadline for runs that don't set one. Nothing orphans; nothing leaks.
15
15
  - **Preset-driven tool scoping** — every subagent runs with exactly the tools its job needs, restricted by preset or per-call `tools`/`excludeTools`, with auto-route that picks the right preset when you don't.
16
16
  - **Templates with slots** — saved, file-backed task templates with `${param}` placeholders for workflows you run again and again.
17
- - **Safety by default** — task-fence injection protection, sanitized error paths, owner-only persistence, and a 1700+ test suite pinning every contract against the real pi SDK.
17
+ - **Safety by default** — task-fence injection protection, sanitized error paths, owner-only persistence (`0o700` stores, `0o600` files; the directory mode is repaired on every write and is the confidentiality boundary), and a 2400+ test suite pinning every contract against the real pi SDK.
18
18
 
19
19
  ---
20
20
 
@@ -88,13 +88,13 @@ All settings persist across sessions.
88
88
  | `params` | object | — | Values for `${param}` slots in the template. All slots must be filled; missing ones error. |
89
89
  | `systemPrompt` | string | — | Extra instructions or a different persona for the subagent. |
90
90
  | `inheritSystemPrompt` | boolean | `true` | Whether to inherit the main agent's system prompt. Set `false` to save tokens. |
91
- | `thinkingLevel` | string | — | `off` / `minimal` / `low` / `medium` / `high` / `xhigh`. Capped at user's configured max. |
91
+ | `thinkingLevel` | string | — | `off` / `minimal` / `low` / `medium` / `high` / `xhigh`. Capped at user's configured max. Matched **exactly** (case and whitespace matter): an unknown value is rejected before anything launches — including pi's own `max`, which is not a delegated level. `""` or an omitted field uses the configured max. |
92
92
  | `outputFile` | string | — | Path for the subagent to write full findings. Returns only a summary. |
93
- | `timeout` | number | — | Max milliseconds. Foreground: exceeded → SIGTERM (5s grace) → SIGKILL. Background: the session is aborted and the run ends `stopped` with the timeout reason. A background run with no explicit `timeout` gets the 30-minute default deadline — an explicit timeout is honored as given (a default, not a ceiling). A raw value `≥ 2^31-1` normalizes to no timeout (for a background run, the 30-minute default then applies). |
93
+ | `timeout` | number | — | Max milliseconds. Foreground: exceeded → SIGTERM (5s grace) → SIGKILL. Background: the session is aborted, the agent ends `stopped`, and the run record is finalized `failed` with `errorCategory: "timeout"`; a settle that arrives later amends that record's cost/tokens/output instead of rewriting its classification. One owner arms it — `spawnBackgroundSession`, before the prompt, with the budget anchored at the run record's creation. A background run with no explicit `timeout` gets the 30-minute default deadline — an explicit timeout is honored as given (a default, not a ceiling). A raw value `≥ 2^31-1` normalizes to no timeout (for a background run, the 30-minute default then applies). |
94
94
  | `cwd` | string | — | Working directory. Defaults to conductor's cwd. |
95
95
  | `background` | boolean | conditional | Spawn as an independent background session; returns an ID immediately. **Omitted**, a single task or a `tasks` fan-out runs in the background when the *effective* `approvalMode` is `auto` (call param, else config), and stays foreground under `writes`/`always` or for `chain`/`graph` — see [Background execution](#background-execution). With `tasks` it fans out (one background agent per task, one ID per task), and the conductor is woken once per agent as each finishes. Pass `false` for a quick probe whose answer the next step needs inline. |
96
96
  | `priority` | string | — | Concurrency priority: `critical` / `high` / `normal` / `low`. Defaults to `normal`; higher-priority delegations queue ahead. `tasks[]` / `graph[]` steps can set `priority` per unit (see below). |
97
- | `tools` | array | — | Explicit tool allowlist for the subagent. |
97
+ | `tools` | array | — | Explicit tool allowlist for the subagent. **An empty array (`tools: []`) requests zero child tools** — it maps to pi's `--no-tools`, which also wins over `noBuiltinTools`. Omit the field to keep pi's defaults. |
98
98
  | `excludeTools` | array | — | Tool names to disable for the subagent. |
99
99
  | `noBuiltinTools` | boolean | — | Disable all pi built-in tools for the subagent. |
100
100
 
@@ -106,13 +106,17 @@ All settings persist across sessions.
106
106
  | `approvalMode` | string | — | `auto` / `writes` / `always`. Default is user config (`/brl-subagent approval`). `always` is rejected for background runs. |
107
107
  | `force` | boolean | `false` | Dispatch anyway past a capability pre-flight block; the block is downgraded to a warning. |
108
108
  | `retryRunId` | string | — | Re-run a previously failed or interrupted run with its recorded task and params. |
109
- | `retryOnTimeout` | boolean | `false` | Retry once if a **foreground** subagent times out. The second timeout is a final failure. Background runs are not auto-retried — re-dispatch with `retryRunId`. |
109
+ | `retryOnTimeout` | boolean | `false` | Retry once if a **foreground** subagent times out. The second timeout is a final failure. A **background** run is not retried on its deadline, but it *is* re-dispatched once automatically when it dies on a transport-class error — see [Transport auto-retry](#transport-auto-retry). Any other background failure is re-dispatched with `retryRunId`. |
110
110
 
111
111
  **Capability pre-flight:** before spawning, the extension checks that the resolved toolset can actually do the task — a run/execute/test/compile/benchmark task with no `bash`, or an exploration task (search/grep/find/list/locate/glob) with none of `find`/`ls`/`grep`/`bash`. Such a dispatch is **rejected** by default; `force: true` downgrades the rejection to a **warning**. `force` never suppresses an `outputFile`-without-write conflict — that stays a hard error. Warnings are surfaced in the returned result in every mode.
112
112
 
113
+ **An empty tool list means no tools (`tools: []`):** `tools: []` is an explicit *restriction*, not an absent value. A foreground child is spawned with pi's `--no-tools`, so all built-in, extension, custom and MCP tools are inactive for that run, and it wins over `noBuiltinTools` (`[]` can never widen into "built-ins off, extension tools on"). A background run passes the same empty list to the SDK session, so it starts with zero active tools. When the resolved tool allowlist is omitted, Pi's normal selection applies unless `noBuiltinTools` or `excludeTools` restrict it; a preset may still supply an allowlist. Before this fix, a resolved empty allowlist alone incorrectly fell back to that selection in foreground runs. `[]` combined with `excludeTools` still has no tools; `excludeTools` can only disable.
114
+
115
+ This is a **tool-access setting, not a security sandbox.** In the foreground, configured extensions and MCP servers still load and connect at child startup, because users deliberately rely on that startup (and on extension *hooks* such as permission gates) — `[]` denies the model their tools, it does not prevent the code from running, and it is no defence against an extension that reactivates tools on purpose. Background runs are unchanged: they never load extensions or skills (`noExtensions`/`noSkills`) and start no MCP servers at all, with or without `tools`. A dispatch that needs zero capabilities therefore still costs the child its extension initialisation time; if an `outputFile` is requested alongside `tools: []`, the dispatch is rejected before launch, because no write tool exists to write that file.
116
+
113
117
  **Retries (`retryRunId`):** a retry rebuilds the parameter object from a fixed set of fields, falling back to the original run's recorded values, with explicit values on the retry call winning: `task`, `label`, `model`, `preset`, `systemPrompt`, `inheritSystemPrompt`, `thinkingLevel`, `priority`, `outputFile`, `timeout`, `cwd`, `tools`, `excludeTools`, `noBuiltinTools`, plus the four **execution-shape** fields `background`, `gitMode`, `approvalMode` and `force`.
114
118
 
115
- **Interrupted runs:** a run whose conductor died mid-run is marked interrupted (it keeps its persisted session file) and is surfaced as **Interrupted** in `/brl-subagent history` and in `/brl-subagent retry` — including after a crash + fresh boot, when it is reconstructed from the durable per-run registry (plus the background agent record). Recover one with `retryRunId: <run-id>`, or abandon it from the retry menu — abandon finalizes it as stopped, prunes its session file, and sends no completion wake. A **foreground** run's task is not persisted, so its crashed row shows no task and a retry needs the task supplied explicitly; a background run keeps its task in its agent record. The recovery posture (`/brl-subagent recovery`, default `offer`) controls whether a boot announces interrupted runs with one turn-boundary notice; `off` silences it. Recovery is never automatic — there is no `auto` mode.
119
+ **Interrupted runs:** a run whose conductor died mid-run is marked interrupted (it keeps its persisted session file) and is surfaced as **Interrupted** in `/brl-subagent history` and in `/brl-subagent retry` — including after a crash + fresh boot, when it is reconstructed from the durable per-run registry (plus the background agent record). Recover one with `retryRunId: <run-id>`, or abandon it from the retry menu — abandon finalizes it as stopped, prunes its session file, and sends no completion wake. A **foreground** run's task is not persisted, so its crashed row shows no task and a retry needs the task supplied explicitly; a background run keeps its task in its agent record. The recovery posture (`/brl-subagent recovery`, default `offer`) controls whether a boot announces interrupted runs with one turn-boundary notice; `off` silences it. Recovery is never automatic — there is no `auto` mode. A dispatch that died **before its prompt was issued** is not an interrupted run: it is finalized failed and never offered for retry.
116
120
 
117
121
  **The execution-shape fields are restored, so a retry keeps the original's shape:** retrying a background run re-runs it in the background (with its completion wake), a `gitMode: 'branch'` retry keeps its work branch, an `approvalMode`-constrained retry keeps that gating, and a retry that was capability-blocked keeps its `force`. Passing any of them explicitly on the retry call overrides the recorded value. One qualification on `gitMode`: when neither the record nor the call carries one, the **configured** default still applies — so a user with a global `gitMode: 'branch'` gets a work branch on every retry, and one with the default `'none'` gets none. Do not assume "no work branch" without checking the effective `gitMode`.
118
122
 
@@ -122,6 +126,18 @@ All settings persist across sessions.
122
126
 
123
127
  **`template` is asymmetric:** the original run's template is **not** restored, but a `template` you supply explicitly on the retry call **does** take effect (it is resolved before the retry merge, issue #175) — its body wins over the recorded `task`.
124
128
 
129
+ #### Transport auto-retry
130
+
131
+ A **background** run that settles `failed` with `errorCategory: 'exit_error'` and a transport signature in its message (`connection error`, `econnreset`, `econnrefused`, `socket hang up`, `fetch failed`, `network error`, `etimedout`, `enotfound`, `eai_again` — case-insensitive) is **re-dispatched once**, mechanically, with the parameters the run recorded. This is the class that dropped four background dispatches in the 2026-10 cycle before any file work; a replay is cheap and the cause is external.
132
+
133
+ The retry is a normal dispatch of the existing `retryRunId` shape: the recorded task, model, thinking level, tools, `cwd`, `timeout` and preset are restored, the record continues the logical dispatch (`resumeOf` the source run, `attempt: 2`), and every gate (session cost, approval, capability pre-flight) runs again. The source run's completion message is **suppressed** — replaced by a warning toast (`Transport failure — auto-retrying once (attempt 2/2)`), so the retry's own terminal settle is the wake. If the retry also fails, that failure is surfaced as an ordinary one: **one retry per logical dispatch, never a chain**.
134
+
135
+ A drop costs the child its context, not its files, so the retry is a **resume**: its **system prompt** carries a bounded `<resume-context>` block (outside the `<task>` fence) naming the previous attempt's id, the fact that the directory may already hold uncommitted edits, `git status --short` / `git log --oneline -8`, the `/tmp/brl-<label>-bank.md` progress bank (`<label>` is the source run's label, sanitized for a filename), and — when the settle path retained it — the previous attempt's session directory as an **absolute** path, with the instruction to read the newest `.jsonl` inside. It closes with "continue from what exists; do NOT redo committed, written, or banked work". The block rides the **system prompt** only — never inside the `<task>` fence — and the recorded task stays byte-identical to the original: that is what resolution, auto-routing, thinking level and the H1 capability checks see, and it is kept on the retry's own record so a further retry cannot stack preambles. Manual `retryRunId` dispatches do not get a resume block.
136
+
137
+ Out of scope by construction: non-transport failures, foreground runs (a synchronous failure is already visible, and `retryOnTimeout` covers the timeout case), fan-out units (their records carry no `originalParams`), and chain/graph. Recovery from an interrupted run stays an explicit `retryRunId` call.
138
+
139
+ **Retained sessions are bounded.** The only reason to keep a failed run's session directory is the auto-retry's reader, so the settle path retains **exactly** the auto-retry class (attempt 1, background, `exit_error` + a transport signature) and prunes everything else as before. A retained directory is marked `.transport-retained`; a sweep at the same settle-time choke point walks **marked directories only** and prunes the oldest while the set exceeds 5 directories, 50 MB, or 14 days (recency is the marker's mtime). The directory being retained by the current settle is exempt — one oversized run may overshoot for one settle and the next settle reclaims it. A session smaller than 2 KB (start-entry-only) is not retained, and a marker write that fails falls back to pruning: retention is an optimization, boundedness is the invariant. Interrupted runs keep their directories unmarked by design and are never swept. Retention applies to background runs; there is no manual-retry pointer for an attempt-2 session.
140
+
125
141
  ## Multi-step modes (chain, tasks, graph)
126
142
 
127
143
  Beyond a single `task`, `delegate_task` accepts three multi-step shapes: `chain` (sequential steps, `{previous}` references the prior step's output), `tasks` (parallel, independent), and `graph` (dependency-ordered, `{<nodeId>}` references another node's output — the referenced node's own `id`, which must be a word-character id: letters, digits, and underscore. `{step-1}` and `{node.a}` are not matched and are left as literal text).
@@ -172,10 +188,14 @@ model: anthropic/claude-opus-4-6
172
188
  tools:
173
189
  - read
174
190
  - bash
191
+ # optional — capture the run's findings to this path; needs the write tool
192
+ outputFile: findings.md
175
193
  thinkingLevel: high
176
194
  ---
177
195
  ```
178
196
 
197
+ A preset `outputFile` is validated at dispatch exactly like the `outputFile` parameter — it requires the `write` tool, so a preset that excludes `write` is a hard conflict. `timeout` is deliberately **not** a preset field: the deadline belongs to the call/template tier, not the persona (ADR 0022 §6).
198
+
179
199
  Custom presets override built-ins with the same name and survive `pi install` updates.
180
200
 
181
201
  Refer to a preset via the `preset` parameter of `delegate_task` (see above). Parameters on `delegate_task` override preset values.
@@ -222,7 +242,7 @@ Supported frontmatter fields:
222
242
  | `thinkingLevel` | string | `off` / `minimal` / `low` / `medium` / `high` / `xhigh` |
223
243
  | `outputFile` | string | Output file path (may contain `${param}` slots) |
224
244
  | `timeout` | number | Max milliseconds for the delegated run |
225
- | `tools` | list | Tool allowlist |
245
+ | `tools` | list | Tool allowlist (empty = no tools) |
226
246
  | `excludeTools` | list | Tools to exclude |
227
247
  | `noBuiltinTools` | `"true"` / `"false"` | Disable all pi built-in tools |
228
248
  | `inheritSystemPrompt` | `"true"` / `"false"` | Override system-prompt inheritance (default `true`) |
@@ -302,16 +322,17 @@ The approval-aware fallback is the safety property: background runs have no appr
302
322
 
303
323
  **Background safety controls (issue #28):** background agents honor the same safety controls as foreground runs — no more unattended sessions that bypass approval, git isolation, deadlines, or cost:
304
324
 
305
- - **Per-agent timeout** — the deadline is armed immediately after the prompt is issued, so in-prompt preflight (auth, model resolution) counts toward it. A background run with no explicit `timeout` gets a 30-minute default deadline (the issue #28 orphan protection); an explicit timeout is honored as given — 30 minutes is the default, not a ceiling. On expiry the session is aborted and the agent ends with status `stopped` and the timeout reason. Timeout values are normalized (`0`/negative/`NaN`/`Infinity`/`≥ 2^31` → no timeout, which for a background run means the 30-minute default) and a double-fire guard prevents the timer from acting on an already-settled agent.
325
+ - **Per-agent timeout** — exactly one deadline is armed per run, by the session that owns it, before the prompt is issued; the budget is anchored at the run record's creation, so the setup and the in-prompt preflight (auth, model resolution) both count toward it. A background run with no explicit `timeout` gets a 30-minute default deadline (the issue #28 orphan protection); an explicit timeout is honored as given — 30 minutes is the default, not a ceiling. On expiry the session is aborted, the agent ends with status `stopped` and the timeout reason, and the run record becomes `failed` / `timeout` — written at the deadline and amended (never re-classified) if the prompt settles later. The abort is cooperative: a prompt that ignores it keeps running, and that run keeps its session directory and its branch lock (and has no registry entry). Timeout values are normalized (`0`/negative/`NaN`/`Infinity`/`≥ 2^31` → no timeout, which for a background run means the 30-minute default) and a double-fire guard prevents the timer from acting on an already-settled agent.
306
326
  - **Session cost limit (R5)** — the cost check runs before the background spawn, so a session at its limit cannot bypass it by delegating to background. For a background fan-out the whole batch is checked up front as per-task estimate × N.
307
327
  - **Approval mode** — `approvalMode: 'always'` is rejected for background agents (there is no interactive dialog to approve a diff while running unattended); `'writes'` silently auto-approves with a warning logged. For a fan-out, `'always'` rejects the whole batch before any spawn and `'writes'` warns once for the batch.
328
+ - **Transport auto-retry** — a run that dies on a dropped connection is replayed once with its recorded params (see [Transport auto-retry](#transport-auto-retry)), carrying a `<resume-context>` block on the system-prompt side that names the surviving files and the progress bank; the source notice is replaced by a toast so a lost connection doesn't read as a lost run. A second failure surfaces normally.
308
329
  - **gitMode branch isolation** — with `gitMode: 'branch'` a work branch is created before the run, the agent's changes are committed at teardown so the diff is real, the diff is captured and surfaced via `get_subagent_result`, and the branch is then switched away from and deleted. This requires a clean working tree — a dirty tree is refused loudly rather than risking the base branch. `gitMode: 'branch'` is rejected for background fan-out — see [Background fan-out](#background-fan-out).
309
330
 
310
331
  ### Background fan-out
311
332
 
312
333
  `background: true` with `tasks: [...]` fans out: every task starts as its own background agent, the call returns immediately with **one ID per task** in task order, and the conductor is woken with **one completion message per agent** as each finishes — no coalescing, no batch wake. `chain` and `graph` cannot be combined with `background: true` (rejected loudly): sequential dependencies and dependency waves do not survive fan-out.
313
334
 
314
- Fan-out validates the entire batch before spawning anything. Any invalid task — `cwd`, `outputFile`, or a pre-task check — rejects the whole batch before a single spawn starts, and the error names the task (`Task N ("label")`). Per-task overrides are honoured: `model`, `thinkingLevel`, `tools` / `excludeTools` / `noBuiltinTools`, `systemPrompt` / `inheritSystemPrompt`, `outputFile`, `timeout`, `cwd`, `priority`, `label`.
335
+ Fan-out validates the entire batch before spawning anything. Any invalid task — `cwd`, `outputFile`, an unsupported `thinkingLevel`, or a pre-task check — rejects the whole batch before a single spawn starts, and the error names the task (`Task N ("label")`). Per-task overrides are honoured: `model`, `thinkingLevel`, `tools` / `excludeTools` / `noBuiltinTools`, `systemPrompt` / `inheritSystemPrompt`, `outputFile`, `timeout`, `cwd`, `priority`, `label`.
315
336
 
316
337
  Three checks reject the fan-out up front, before any spawn: `approvalMode: 'always'`; `gitMode: 'branch'` for the batch (the git lock is awaited inside the first spawn and held until that agent settles, so branch-mode spawns targeting the same repository would serialize and block the call — the rule is blanket because the lock is keyed by the resolved repository root, so any two units of the same repo contend); and the session cost limit, checked as per-task estimate × N.
317
338
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brl-subagent",
3
- "version": "2.6.0",
3
+ "version": "2.8.0",
4
4
  "description": "Subagent delegation for pi — blocking or background runs, chain/parallel/graph modes, presets and task templates, live monitor, and dispatch capability guards.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -24,6 +24,9 @@
24
24
  "./src/index.ts"
25
25
  ]
26
26
  },
27
+ "brl-subagent": {
28
+ "processChecks": true
29
+ },
27
30
  "scripts": {
28
31
  "typecheck": "tsc --noEmit",
29
32
  "docs:arch": "node scripts/docs-arch.mjs --write",
@@ -37,10 +40,10 @@
37
40
  "typebox": "*"
38
41
  },
39
42
  "devDependencies": {
40
- "@earendil-works/pi-agent-core": "^1.4.0",
41
- "@earendil-works/pi-ai": "^1.4.0",
42
- "@earendil-works/pi-coding-agent": "^1.4.0",
43
- "@earendil-works/pi-tui": "^1.4.0",
43
+ "@earendil-works/pi-agent-core": "^1.5.0",
44
+ "@earendil-works/pi-ai": "^1.5.0",
45
+ "@earendil-works/pi-coding-agent": "^1.5.0",
46
+ "@earendil-works/pi-tui": "^1.5.0",
44
47
  "jiti": "^2.7.0",
45
48
  "typebox": "1.3.27",
46
49
  "typescript": "7.0.2",
@@ -13,7 +13,8 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
13
13
  import type { Priority } from "./types";
14
14
  import { PRIORITY_ORDER } from "./types";
15
15
  import type { SessionState } from "./state";
16
- import { LIVE_SPINNER_FRAME_MS, formatProgressStatus } from "./tui-format";
16
+ import { LIVE_SPINNER_FRAME_MS, computeProgressTimes, formatProgressStatus } from "./tui-format";
17
+ import type { LiveBudgetInput } from "./tui-format";
17
18
 
18
19
  // ---------------------------------------------------------------------------
19
20
  // Slot management
@@ -121,9 +122,31 @@ const STATUS_RESET_DELAY_MS = 3000;
121
122
 
122
123
  /** Repaint the footer from the current counters (issue #354). */
123
124
  function renderProgressStatus(state: SessionState, ctx: ExtensionContext): void {
125
+ const now = Date.now();
126
+ // Issue #423: the footer's clocks come from the LIVE map, with settled ids
127
+ // excluded — a finalized row must not keep a deadline on screen. The input
128
+ // is built explicitly (the formatter no longer reads the whole state) so the
129
+ // counter slice and the clock slice stay separable.
130
+ const live: LiveBudgetInput[] = [];
131
+ for (const [id, session] of state.subagentSessions) {
132
+ if (state.isLiveEntryFinalized(id)) continue;
133
+ live.push(session);
134
+ }
124
135
  ctx.ui.setStatus(
125
136
  "brl-subagent",
126
- formatProgressStatus(state, Date.now(), ctx.ui.theme),
137
+ formatProgressStatus(
138
+ {
139
+ activeSubagents: state.activeSubagents,
140
+ completedSubagents: state.completedSubagents,
141
+ failedSubagents: state.failedSubagents,
142
+ unseenSubagents: state.unseenSubagents,
143
+ modeContext: state.modeContext,
144
+ activeSinceMs: state.activeSinceMs,
145
+ times: computeProgressTimes(live, now),
146
+ },
147
+ now,
148
+ ctx.ui.theme,
149
+ ),
127
150
  );
128
151
  }
129
152
 
@@ -0,0 +1,144 @@
1
+ // Purpose: Parse and validate the Rule 22 dispatch line (the project-local opt-in lives in project-flags.ts).
2
+ /**
3
+ * The Jev dispatch line — parse side (issue #412, absorbing #407).
4
+ *
5
+ * A dispatch task carries one classifier line:
6
+ *
7
+ * jev: medium (0.84) · C2 · worktree y
8
+ *
9
+ * `.pi/skills/worktree/jev-check.mjs` already PARSES that line for the audit
10
+ * (`--log`, `--ledger`) and FORMATS it (`--line`). This module is the
11
+ * dispatch-time half: the pre-flight needs the verdict before a spawn, and
12
+ * `.pi/` is not shipped (it is dev process tooling), so the extension cannot
13
+ * import the script. A second implementation is a second source of truth —
14
+ * which is why `dispatch-line.test.ts` shells the real script and requires
15
+ * accept/reject agreement on a vector set, and why the two patterns below are
16
+ * kept byte-comparable with the script's (`DISPATCH_LINE_PATTERN`,
17
+ * `BARE_DISPATCH_LINE_PATTERN`, `GAP_MARKERS`). Change one, change both.
18
+ *
19
+ * The check is OPT-IN per project, through the umbrella flag in
20
+ * `src/project-flags.ts`: the project's manifest carries the `processChecks`
21
+ * field (issue #415, ADR 0019). Absent (every user's project) → no check,
22
+ * ever: this is our process, not a product requirement. This module owns the
23
+ * PARSER only; the manifest read lives in `project-flags.ts` (the
24
+ * single-reader ratchet).
25
+ */
26
+
27
+ /**
28
+ * The exact form a dispatch task must carry — quoted verbatim in every
29
+ * rejection so the conductor never has to guess. Kept identical to
30
+ * `REQUIRED_DISPATCH_FORM` in `jev-check.mjs`.
31
+ */
32
+ export const DISPATCH_LINE_FORM = "jev: <level> (<0.xx>) · C<1|2|3> · worktree <y|n>";
33
+
34
+ /**
35
+ * The sanctioned escape when the classifier did not run (SKILL.md: "record
36
+ * `jev: unavailable` and proceed — never block a dispatch on the classifier").
37
+ * It is a RECORDED gap, not a silent one, and it is accepted by both this
38
+ * parser and the script's audit.
39
+ */
40
+ export const JEV_UNAVAILABLE = "jev: unavailable";
41
+
42
+ const LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"] as const;
43
+ const RISKS = ["C1", "C2", "C3"] as const;
44
+
45
+ /**
46
+ * The line as it appears inside a dispatch task. Mirrors `jev-check.mjs`'s
47
+ * `DISPATCH_LINE_PATTERN`: the confidence group is OPTIONAL so a bare level
48
+ * can be reported as such (the skip's exact form) instead of a generic
49
+ * "invalid". The worktree token is a word because the script's normalizer
50
+ * accepts y|yes|true / n|no|false.
51
+ */
52
+ const DISPATCH_LINE_PATTERN =
53
+ /jev:\s*([A-Za-z]+)\s*(?:\(\s*([0-9.]+)\s*\))?\s*·\s*(C\d)\s*·\s*worktree\s*([A-Za-z]+)/i;
54
+
55
+ /** A line that at least TRIED to be a dispatch line — tells "bare level" from "missing". */
56
+ const BARE_DISPATCH_LINE_PATTERN = /jev:\s*(?:off|minimal|low|medium|high|xhigh)\b/i;
57
+
58
+ /**
59
+ * Explicit "the classifier did not run" markers. Mirrors `GAP_MARKERS` in
60
+ * `jev-check.mjs`, anchored to the `jev:` prefix so prose that merely contains
61
+ * the word "unavailable" cannot pass as a classification.
62
+ */
63
+ const GAP_MARKER_PATTERN = /^jev:\s*(?:unavailable|not classified|n\/a|ritual gap)\b/i;
64
+
65
+ export type DispatchLineVerdict =
66
+ | { ok: true; line: string }
67
+ | { ok: false; reason: string };
68
+
69
+ /** Keep a refusal reason to one readable line (mirrors the script's `clip`). */
70
+ function clip(text: string, limit = 110): string {
71
+ const flat = text.replace(/\s+/g, " ").trim();
72
+ return flat.length > limit ? `${flat.slice(0, limit - 1)}…` : flat;
73
+ }
74
+
75
+ function normalizeWorktree(value: string): "y" | "n" | undefined {
76
+ const normalized = value.trim().toLowerCase();
77
+ if (normalized === "y" || normalized === "yes" || normalized === "true") return "y";
78
+ if (normalized === "n" || normalized === "no" || normalized === "false") return "n";
79
+ return undefined;
80
+ }
81
+
82
+ /**
83
+ * Parse a dispatch task for the Rule 22 line. Any line may satisfy it (the
84
+ * script audits per line and accepts the first valid one), and the returned
85
+ * `line` is the matched canonical text — not the whole raw line, which may
86
+ * carry a recorded reason after it.
87
+ *
88
+ * The reason strings mirror the script's, because the same wording is what
89
+ * closes the loop for the conductor: a bare level names the confidence as the
90
+ * missing piece, and a missing line names the exact form.
91
+ */
92
+ export function parseDispatchLine(task: string): DispatchLineVerdict {
93
+ const attempts: string[] = [];
94
+ for (const raw of String(task).split(/\r?\n/)) {
95
+ if (!/jev:/i.test(raw)) continue;
96
+ const line = raw.trim();
97
+ if (GAP_MARKER_PATTERN.test(line)) return { ok: true, line };
98
+
99
+ const match = DISPATCH_LINE_PATTERN.exec(line);
100
+ if (match === null) {
101
+ attempts.push(
102
+ BARE_DISPATCH_LINE_PATTERN.test(line)
103
+ ? `bare level without its classifier confidence — ${clip(line)}`
104
+ : `unparseable dispatch line — ${clip(line)}`,
105
+ );
106
+ continue;
107
+ }
108
+
109
+ const [, levelText, confidenceText, riskText, worktreeText] = match;
110
+ // The regex accepts a confidence-less line on purpose: naming the
111
+ // missing confidence is what makes the rejection actionable.
112
+ if (confidenceText === undefined) {
113
+ attempts.push(`bare level without its classifier confidence — ${clip(line)}`);
114
+ continue;
115
+ }
116
+
117
+ const level = levelText.toLowerCase();
118
+ if (!(LEVELS as readonly string[]).includes(level)) {
119
+ attempts.push(`unknown thinking level "${levelText}" — ${clip(line)}`);
120
+ continue;
121
+ }
122
+ const risk = riskText.toUpperCase();
123
+ if (!(RISKS as readonly string[]).includes(risk)) {
124
+ attempts.push(`unknown risk class "${riskText}" — ${clip(line)}`);
125
+ continue;
126
+ }
127
+ const confidence = Number(confidenceText);
128
+ if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) {
129
+ attempts.push(`confidence out of range "${confidenceText}" — ${clip(line)}`);
130
+ continue;
131
+ }
132
+ const worktree = normalizeWorktree(worktreeText);
133
+ if (worktree === undefined) {
134
+ attempts.push(`invalid workspace answer "${worktreeText}" — ${clip(line)}`);
135
+ continue;
136
+ }
137
+ return { ok: true, line: match[0] };
138
+ }
139
+
140
+ if (attempts.length === 0) {
141
+ return { ok: false, reason: `missing Jev dispatch line (${DISPATCH_LINE_FORM})` };
142
+ }
143
+ return { ok: false, reason: attempts[0] };
144
+ }
@@ -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 { readFileSync } from "node:fs";
31
+ import { join } from "node:path";
32
+ import type { Logger } from "./logging";
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
@@ -101,16 +101,73 @@ export function hasUncommittedChanges(cwd: string): boolean {
101
101
  return output.trim().length > 0;
102
102
  }
103
103
 
104
+ /**
105
+ * Mint a work-branch name.
106
+ *
107
+ * Issue #466 (ADR 0026 D1): the name is generated by the CALLER, not inside
108
+ * `createWorkBranch`, because the durable head-state record must name the branch
109
+ * it is about and is written BEFORE the branch exists (the write-ahead property
110
+ * that makes a crash inside `createWorkBranch` recoverable). This function is
111
+ * the only producer of the `brl-subagent-` prefix in the source tree.
112
+ */
113
+ export function newWorkBranchName(): string {
114
+ return "brl-subagent-" + crypto.randomUUID().slice(0, 8);
115
+ }
116
+
117
+ /**
118
+ * The branch HEAD points at, and whether it has a commit yet.
119
+ *
120
+ * `branch` is undefined for a detached HEAD. `unborn` is true when HEAD is a
121
+ * symbolic ref to a branch that does not exist (a branch deleted while it was
122
+ * checked out): `git checkout <some-branch>` still works there, but
123
+ * `git status --porcelain` reports every tracked file as changed, so callers
124
+ * that gate on a clean tree must know the difference.
125
+ */
126
+ export interface HeadBranch {
127
+ branch: string | undefined;
128
+ unborn: boolean;
129
+ }
130
+
131
+ /** Read the current HEAD branch tolerate-ably (detached and unborn included). */
132
+ export function getHeadBranch(cwd: string): HeadBranch {
133
+ let branch: string | undefined;
134
+ try {
135
+ branch = execFileSync("git", ["symbolic-ref", "--short", "-q", "HEAD"], gitOpts(cwd)).trim() || undefined;
136
+ } catch {
137
+ // Detached (or not a repo): no symbolic ref to read.
138
+ branch = undefined;
139
+ }
140
+ let unborn = false;
141
+ try {
142
+ execFileSync("git", ["rev-parse", "--verify", "-q", "HEAD"], gitOpts(cwd));
143
+ } catch {
144
+ unborn = true;
145
+ }
146
+ return { branch, unborn };
147
+ }
148
+
149
+ /** The repository's work branches (`brl-subagent-*`), short names. */
150
+ export function listWorkBranches(cwd: string): string[] {
151
+ const output = execFileSync("git", ["branch", "--list", "brl-subagent-*", "--format=%(refname:short)"], gitOpts(cwd));
152
+ return output
153
+ .split("\n")
154
+ .map((line) => line.trim())
155
+ .filter((line) => line.length > 0);
156
+ }
157
+
104
158
  /**
105
159
  * Create a work branch from the given base branch.
106
160
  * Returns { ok: true, branch } on success, { ok: false, error } on failure.
161
+ *
162
+ * Issue #466: `branch` is a parameter (defaulted for existing callers) so a
163
+ * caller can record the name in the durable head state BEFORE this runs.
107
164
  */
108
165
  export function createWorkBranch(
109
166
  cwd: string,
110
167
  baseBranch: string,
168
+ branch: string = newWorkBranchName(),
111
169
  ): { ok: true; branch: string } | { ok: false; error: string } {
112
170
  try {
113
- const branch = "brl-subagent-" + crypto.randomUUID().slice(0, 8);
114
171
  execFileSync("git", ["checkout", "-b", branch, baseBranch], gitOpts(cwd));
115
172
  return { ok: true, branch };
116
173
  } catch (err) {