brl-subagent 2.5.2 → 2.7.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
@@ -16,16 +16,17 @@ delegation-heavy work.
16
16
 
17
17
  | Mode | What blocks | What wakes you | Batchable? |
18
18
  | --- | --- | --- | --- |
19
- | single, foreground | blocks until it returns | — (result comes back inline) | no |
20
- | single, background | returns immediately with an agent id | yes — a `subagent-completion` message on terminal state | no |
19
+ | single, background (**default** at effective `auto`) | returns immediately with an agent id | yes — a `subagent-completion` message on terminal state | no |
20
+ | single, foreground (default at `writes`/`always`, or `background: false`) | blocks until it returns | — (result comes back inline) | no |
21
21
  | chain | blocks until the chain finishes or fails | — | yes (foreground) |
22
- | parallel (`tasks`), foreground | blocks until every task finishes | — | yes (foreground) |
23
- | parallel, background (fan-out) | returns immediately with one agent id per task | yes — a `subagent-completion` message per agent, on each agent's terminal state | yes |
22
+ | parallel (`tasks`), background fan-out (**default** at effective `auto`) | returns immediately with one agent id per task | yes — a `subagent-completion` message per agent, on each agent's terminal state | yes |
23
+ | parallel (`tasks`), foreground (default at `writes`/`always`, or `background: false`) | blocks until every task finishes | — | yes (foreground) |
24
24
  | graph | blocks; runs in waves via `dependsOn` | — | yes (foreground) |
25
25
 
26
+ - **`background` is a conditional default (issue #361).** With `background` omitted, a single task or a `tasks` fan-out runs in the **background** when the *effective* approval mode is `auto` (per-call param, else the configured default), and stays **foreground** when it is `writes` or `always`. Chain and graph always stay foreground. Explicit `true`/`false` is honoured exactly.
26
27
  - Foreground single blocks: you wait for the result inline.
27
28
  - Background single returns immediately with an agent id; a completion message wakes you (see below).
28
- - Chain, parallel, and graph are batch — one call, many subtasks. Chain and graph are foreground; `tasks` + `background: true` fans out: every task starts as its own background agent, the call returns with one id per task in task order, and you are woken once per agent as each finishes.
29
+ - Chain, parallel, and graph are batch — one call, many subtasks. Chain and graph are foreground; `tasks` fans out by default under `auto` (and always with `background: true`): every task starts as its own background agent, the call returns with one id per task in task order, and you are woken once per agent as each finishes.
29
30
  - Fan-out validates the whole batch before spawning anything: any invalid task (cwd, `outputFile`, or a pre-task check) rejects the entire batch before a single spawn starts, and the error names the task (`Task N ("label")`).
30
31
  - Fan-out rejects `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). It also rejects `approvalMode: "always"` up front, and the session cost limit is checked as per-task estimate × N.
31
32
  - Spawn failure mid-loop stops further spawns and reports the failed task plus the ids already started; abort mid-loop stops further spawns and reports the ids already started. Either way those agents are detached and still wake you.
@@ -40,16 +41,17 @@ delegation-heavy work.
40
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.)
41
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"`).
42
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).
43
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.
44
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.
45
47
 
46
48
  ## Delegation judgment
47
49
 
48
- - Foreground vs background: if your next step needs the result inline, run foreground. If the user can keep working or is AFK, run background and act on the wake. Pre-declared independent work while the user is away → `tasks` + `background: true` (fan-out); act on each wake.
50
+ - Foreground vs background: the default is background under effective `auto`, foreground otherwise. Pass `background: false` for a quick probe whose answer the next step needs inline (it keeps the call blocking, so no wake round-trip). Pass `background: true` to force a background run where the default blocks. If the user can keep working or is AFK, act on the wake. Pre-declared independent work while the user is away → `tasks` (fan-out is the default) and act on each wake.
49
51
  - Batch vs sequential: if the work is pre-declared, use chain/parallel/graph. If you're steering incrementally with the user, issue sequential calls.
50
52
  - Retry taxonomy: `retryRunId` is a retry — it re-runs with the recorded task and params. A re-dispatch (a fresh call with the same task text) is not a retry. Never re-issue an identical spec after a termination without confirming the cause with the user.
51
53
  - When to delegate: when the task needs an isolated context, a deep investigation, parallel research, or a long-running analysis.
52
- - Approval: `approvalMode: "always"` is rejected in background — there is no dialog. Use `auto` (default) or `writes`; `writes` auto-approves in background.
54
+ - Approval: `approvalMode: "always"` is rejected in background — there is no dialog. Use `auto` (default) or `writes`; `writes` auto-approves in background. This is why the background default is approval-aware: an omitted `background` stays foreground under `writes`/`always`, so the gate is never silently bypassed by a default.
53
55
 
54
56
  ### Claim verification
55
57
 
@@ -62,8 +64,9 @@ delegation-heavy work.
62
64
 
63
65
  - Batch chain with `{previous}`: `chain: [{ task: "…" }, { task: "Use {previous} …" }]` — each step gets the prior step's output.
64
66
  - Graph with `dependsOn`: subtasks declare edges; the scheduler runs them in waves.
65
- - Background + act on wake: spawn a background run, then act when the completion message arrives. Never poll between spawn and wake.
66
- - Background fan-out: `tasks: [...], background: true` — one background agent per task, one id per task in task order, one wake per agent.
67
+ - Background + act on wake: spawn a background run (the default under `auto`), then act when the completion message arrives. Never poll between spawn and wake.
68
+ - Background fan-out: `tasks: [...]` — one background agent per task, one id per task in task order, one wake per agent.
69
+ - Inline probe: `background: false` — blocks and returns the result in the same turn when the next step needs it immediately.
67
70
  - retryRunId: pass a failed or **interrupted** run's id to re-run it with its recorded task and params; explicit parameters override the originals. A run interrupted before durable task capture (a pre-enrichment registry entry) has no recorded task — pass `task` explicitly for those.
68
71
 
69
72
  ## Interrupted runs and recovery
@@ -75,8 +78,8 @@ delegation-heavy work.
75
78
 
76
79
  ## Deadlines and retries
77
80
 
78
- - `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. Background expiry aborts the session (the run ends `stopped`); foreground expiry kills the process.
79
- - `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 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.
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).
80
83
 
81
84
  ## Mechanics pointer
82
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.5.2 · **Author:** Azmeen Afandi / [Beeroo Labs](https://beeroolabs.com) · **License:** MIT
5
+ **Version:** 2.7.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 1500+ 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 1900+ test suite pinning every contract against the real pi SDK.
18
18
 
19
19
  ---
20
20
 
@@ -92,7 +92,7 @@ All settings persist across sessions.
92
92
  | `outputFile` | string | — | Path for the subagent to write full findings. Returns only a summary. |
93
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). |
94
94
  | `cwd` | string | — | Working directory. Defaults to conductor's cwd. |
95
- | `background` | boolean | `false` | Spawn as an independent background session; returns an ID immediately. 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. See [Background execution](#background-execution). |
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
97
  | `tools` | array | — | Explicit tool allowlist for the subagent. |
98
98
  | `excludeTools` | array | — | Tool names to disable for the subagent. |
@@ -106,7 +106,7 @@ 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
 
@@ -122,11 +122,23 @@ All settings persist across sessions.
122
122
 
123
123
  **`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
124
 
125
+ #### Transport auto-retry
126
+
127
+ 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.
128
+
129
+ 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**.
130
+
131
+ 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.
132
+
133
+ 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.
134
+
135
+ **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.
136
+
125
137
  ## Multi-step modes (chain, tasks, graph)
126
138
 
127
139
  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).
128
140
 
129
- `background: true` fans out the `tasks` shape into one background agent per task (one ID per task, one completion wake per agent); `chain` and `graph` reject it.
141
+ `background: true` fans out the `tasks` shape into one background agent per task (one ID per task, one completion wake per agent); `chain` and `graph` reject it. Under an effective `approvalMode` of `auto` that fan-out is the **default** (see [Background execution](#background-execution)); pass `background: false` to run the batch foreground.
130
142
 
131
143
  Every execution knob can be set per step: `model`, `thinkingLevel`, `tools`, `excludeTools`, `noBuiltinTools`, `systemPrompt`, `inheritSystemPrompt`, `outputFile`, `timeout`, `cwd`. Unset fields inherit from the global parameters (and their preset defaults).
132
144
 
@@ -283,7 +295,18 @@ The built-in `code-review` template's slot is `${target}` (its companion `securi
283
295
 
284
296
  ## Background execution
285
297
 
286
- Set `background: true` to spawn the subagent as an independent session that returns an ID immediately and keeps running. Its progress is tracked via `getAgent` and the live monitor while the main session continues. Steering via `steerAgent` delivers the message into the agent's live session — it is queued while the agent runs and delivered after the current tool call finishes, before the next model call. Repeat steers work, and a delivery failure surfaces as a real tool error rather than a recorded-but-undelivered steer.
298
+ The tool can spawn the subagent as an independent session that returns an ID immediately and keeps running (`background: true`). Its progress is tracked via `getAgent` and the live monitor while the main session continues. Steering via `steerAgent` delivers the message into the agent's live session — it is queued while the agent runs and delivered after the current tool call finishes, before the next model call. Repeat steers work, and a delivery failure surfaces as a real tool error rather than a recorded-but-undelivered steer.
299
+
300
+ **Background is the conditional default (issue #361).** When `background` is omitted, dispatch resolves it once from the *effective* approval mode (per-call param, else the configured default — the mode the child will actually run with):
301
+
302
+ | Call shape | Default |
303
+ | --- | --- |
304
+ | single task or `tasks` fan-out, effective `approvalMode: 'auto'` | **background** |
305
+ | `chain` / `graph` | foreground (an explicit `background: true` is still rejected) |
306
+ | effective `approvalMode` `'writes'` or `'always'` | foreground |
307
+ | explicit `true` / `false` | honoured exactly |
308
+
309
+ The approval-aware fallback is the safety property: background runs have no approval dialog, so a mode that gates on the user cannot be reached by a default. Pass `background: false` for a quick probe whose answer the next step needs inline, and `background: true` to force a background run where the default blocks. The effective value is recorded on the run, so a retry restores what the run actually was.
287
310
 
288
311
  **System prompt semantics:** background sessions are spawned with the same built prompt as foreground subagents (base prompt when `inheritSystemPrompt: true`, custom prompt, preset guidance, and subagent instructions). Like pi's own `--append-system-prompt`, supplying this prompt **replaces** any discovered `.pi/APPEND_SYSTEM.md` / global `APPEND_SYSTEM.md` content — this matches foreground subagent behavior exactly. With `inheritSystemPrompt: true` (the default) your conductor session's instructions — including its own appended content — are inherited through the base prompt.
289
312
 
@@ -294,6 +317,7 @@ Set `background: true` to spawn the subagent as an independent session that retu
294
317
  - **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.
295
318
  - **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.
296
319
  - **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.
320
+ - **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.
297
321
  - **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).
298
322
 
299
323
  ### Background fan-out
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brl-subagent",
3
- "version": "2.5.2",
3
+ "version": "2.7.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.3.0",
41
- "@earendil-works/pi-ai": "^1.3.0",
42
- "@earendil-works/pi-coding-agent": "^1.3.0",
43
- "@earendil-works/pi-tui": "^1.3.0",
43
+ "@earendil-works/pi-agent-core": "^1.4.0",
44
+ "@earendil-works/pi-ai": "^1.4.0",
45
+ "@earendil-works/pi-coding-agent": "^1.4.0",
46
+ "@earendil-works/pi-tui": "^1.4.0",
44
47
  "jiti": "^2.7.0",
45
48
  "typebox": "1.3.27",
46
49
  "typescript": "7.0.2",
@@ -13,6 +13,7 @@ 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
17
 
17
18
  // ---------------------------------------------------------------------------
18
19
  // Slot management
@@ -52,7 +53,7 @@ export async function acquireSlot(
52
53
 
53
54
  if (maxParallel === 0 || state.activeSubagents < maxParallel) {
54
55
  state.activeSubagents++;
55
- updateProgressStatus(state, ctx);
56
+ repaintStatus(state, ctx);
56
57
  return true;
57
58
  }
58
59
 
@@ -60,7 +61,7 @@ export async function acquireSlot(
60
61
  const entry = {
61
62
  run: () => {
62
63
  state.activeSubagents++;
63
- updateProgressStatus(state, ctx);
64
+ repaintStatus(state, ctx);
64
65
  resolve(true);
65
66
  },
66
67
  signal,
@@ -103,7 +104,7 @@ export function releaseSlot(state: SessionState, success: boolean, ctx: Extensio
103
104
  state.failedSubagents++;
104
105
  }
105
106
 
106
- updateProgressStatus(state, ctx);
107
+ repaintStatus(state, ctx);
107
108
 
108
109
  // Dequeue next waiting task
109
110
  const next = state.pendingQueue.shift();
@@ -118,7 +119,148 @@ export function releaseSlot(state: SessionState, success: boolean, ctx: Extensio
118
119
 
119
120
  const STATUS_RESET_DELAY_MS = 3000;
120
121
 
122
+ /** Repaint the footer from the current counters (issue #354). */
123
+ function renderProgressStatus(state: SessionState, ctx: ExtensionContext): void {
124
+ ctx.ui.setStatus(
125
+ "brl-subagent",
126
+ formatProgressStatus(state, Date.now(), ctx.ui.theme),
127
+ );
128
+ }
129
+
130
+ /**
131
+ * Keep the elapsed anchor in step with the active count: it is the start of
132
+ * the run that opened the current burst of activity, so it survives the settle
133
+ * of a later sibling and clears when the last run stops.
134
+ */
135
+ function syncActiveSince(state: SessionState, now: number): void {
136
+ if (state.activeSubagents > 0) {
137
+ if (state.activeSinceMs === undefined) state.activeSinceMs = now;
138
+ } else {
139
+ state.activeSinceMs = undefined;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * One ticker per session (issue #354): started by the first active run,
145
+ * stopped when the last one settles. Idempotent, so every counter update can
146
+ * call it — and it never coexists with the 2 s background poller, which ticks
147
+ * on its own interval in src/index.ts.
148
+ */
149
+ function syncProgressTicker(state: SessionState, ctx: ExtensionContext): void {
150
+ if (state.activeSubagents === 0) {
151
+ stopProgressTicker(state);
152
+ return;
153
+ }
154
+ if (state.statusTicker === undefined) {
155
+ state.statusTicker = setInterval(
156
+ () => repaintStatus(state, ctx),
157
+ LIVE_SPINNER_FRAME_MS,
158
+ );
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Stop the footer ticker (idempotent) and drop the elapsed anchor. Exported so
164
+ * session shutdown/dispose can guarantee no timer outlives the session.
165
+ */
166
+ export function stopProgressTicker(state: SessionState): void {
167
+ if (state.statusTicker !== undefined) {
168
+ clearInterval(state.statusTicker);
169
+ state.statusTicker = undefined;
170
+ }
171
+ state.activeSinceMs = undefined;
172
+ }
173
+
174
+ /**
175
+ * Drop the linger timer (idempotent). Exported so session shutdown can
176
+ * guarantee no timer outlives the session.
177
+ */
178
+ export function clearProgressLinger(state: SessionState): void {
179
+ if (state.statusResetTimer !== undefined) {
180
+ clearTimeout(state.statusResetTimer);
181
+ state.statusResetTimer = undefined;
182
+ }
183
+ }
184
+
185
+ /**
186
+ * One linger timer per burst of settled runs (issue #354, F2).
187
+ *
188
+ * When every run has settled the footer lingers on the static summary line for
189
+ * {@link STATUS_RESET_DELAY_MS} before the counters reset and the idle config
190
+ * line returns. The timer is EDGE-triggered: it arms once, on the transition
191
+ * into `active === 0` with something settled, and repeated renders of the same
192
+ * linger line leave it alone — so N renders can never stack N timers, and no
193
+ * render allocates a closure. Cleared when a new run becomes active (the
194
+ * linger window is over), when it fires, and on session shutdown.
195
+ *
196
+ * The window is measured from the end of the burst, not from the last render:
197
+ * a sibling settling inside it updates the line but does not extend it.
198
+ */
199
+ export function syncProgressLinger(state: SessionState, ctx: ExtensionContext): void {
200
+ const settled = state.completedSubagents + state.failedSubagents;
201
+
202
+ // A live run, or nothing settled to linger over: no armed timer may survive.
203
+ if (state.activeSubagents > 0 || settled === 0) {
204
+ clearProgressLinger(state);
205
+ return;
206
+ }
207
+
208
+ if (state.statusResetTimer !== undefined) return; // already armed — edge held
209
+
210
+ state.statusResetTimer = setTimeout(() => {
211
+ state.statusResetTimer = undefined;
212
+ state.completedSubagents = 0;
213
+ state.failedSubagents = 0;
214
+ state.unseenSubagents = 0;
215
+ repaintStatus(state, ctx);
216
+ }, STATUS_RESET_DELAY_MS);
217
+ }
218
+
219
+ /**
220
+ * The ONE production entry point for painting the footer status (issue #356).
221
+ *
222
+ * Every lifecycle edge calls this and nothing else:
223
+ * - dispatch — `acquireSlot` (slot taken or queued run started) and the
224
+ * background spawn's counter bump in `src/index.ts`;
225
+ * - settle — `releaseSlot`, the background poller's terminal branches, the
226
+ * deadline/crash paths;
227
+ * - dequeue — `releaseSlot` hands the slot to the next queued run, which
228
+ * repaints through `acquireSlot`;
229
+ * - config change — `applyConfig`, `resetState`, and the boot paint;
230
+ * - poller tick — the 2 s background poll and the live spinner interval,
231
+ * which both fire this function;
232
+ * - linger fire — the 3 s reset in `syncProgressLinger`.
233
+ *
234
+ * Contract: synchronous, reads the CURRENT counters/config from `state`, and
235
+ * picks the active line or the idle config line itself. There is no queued
236
+ * microtask or coalescing — a repaint is visible by the time the call returns,
237
+ * so callers may paint before a notification or an `onUpdate` and keep the
238
+ * established ordering.
239
+ *
240
+ * Idempotent: calling it twice with no state change repaints the same line (at
241
+ * the same clock instant) and cannot stack timers — the spinner ticker and
242
+ * linger timer are edge-triggered in their sync helpers. There is no explicit
243
+ * reentrancy guard; a nested paint terminates because the production render is
244
+ * non-reentrant and the timers are edge-triggered.
245
+ *
246
+ * `updateProgressStatus` below is the implementation. It is exported only for
247
+ * its unit tests; production sources (including `src/index.ts` and `src/tui.ts`)
248
+ * must call THIS function, while tests opt in to the implementation directly.
249
+ * `status-chokepoint.test.ts` asserts the production-source boundary.
250
+ */
251
+ export function repaintStatus(state: SessionState, ctx: ExtensionContext): void {
252
+ updateProgressStatus(state, ctx);
253
+ }
254
+
255
+ /**
256
+ * @internal Paint implementation — call {@link repaintStatus}, never this.
257
+ * The tag is convention-only; `status-chokepoint.test.ts`'s source scan is the
258
+ * enforcement.
259
+ */
121
260
  export function updateProgressStatus(state: SessionState, ctx: ExtensionContext): void {
261
+ syncActiveSince(state, Date.now());
262
+ syncProgressLinger(state, ctx);
263
+
122
264
  const total = state.activeSubagents + state.completedSubagents + state.failedSubagents;
123
265
 
124
266
  if (total === 0) {
@@ -126,50 +268,20 @@ export function updateProgressStatus(state: SessionState, ctx: ExtensionContext)
126
268
  return;
127
269
  }
128
270
 
129
- const parts: string[] = [];
130
- // Issue #133: prepend the multi-unit mode breakdown when a graph/chain
131
- // dispatch is in flight — e.g. "brl: graph wave 1/2 · node 2/3, 2 running".
132
- // The mode's finally clears modeContext, so the plain shape returns once
133
- // no mode is active.
134
- if (state.modeContext) {
135
- const mc = state.modeContext;
136
- parts.push(
137
- mc.kind === "graph"
138
- ? `graph wave ${mc.wave}/${mc.totalWaves} · node ${mc.node}/${mc.totalNodes}`
139
- : `chain step ${mc.step}/${mc.totalSteps}`,
140
- );
141
- }
142
- if (state.activeSubagents > 0) parts.push(`${state.activeSubagents} running`);
143
- if (state.completedSubagents > 0) {
144
- if (state.unseenSubagents > 0) {
145
- parts.push(`${state.completedSubagents} done (${state.unseenSubagents} unseen)`);
146
- } else {
147
- parts.push(`${state.completedSubagents} done`);
148
- }
149
- }
150
- if (state.failedSubagents > 0) parts.push(`${state.failedSubagents} failed`);
151
-
152
- const statusText = `brl: ${parts.join(", ")}`;
153
- ctx.ui.setStatus("brl-subagent", ctx.ui.theme.fg("accent", statusText));
154
-
155
- // When all subagents finish, reset counters after a brief delay
156
- if (state.activeSubagents === 0 && total > 0) {
157
- const snapshotTotal = total;
158
- setTimeout(() => {
159
- if (
160
- state.activeSubagents === 0 &&
161
- state.completedSubagents + state.failedSubagents === snapshotTotal
162
- ) {
163
- state.completedSubagents = 0;
164
- state.failedSubagents = 0;
165
- state.unseenSubagents = 0;
166
- updateStatus(state, ctx);
167
- }
168
- }, STATUS_RESET_DELAY_MS);
169
- }
271
+ renderProgressStatus(state, ctx);
272
+ syncProgressTicker(state, ctx);
170
273
  }
171
274
 
275
+ /**
276
+ * @internal The idle config line — also part of the one-entry paint contract.
277
+ * Produced by {@link updateProgressStatus} when no run is active; production
278
+ * callers must reach it through {@link repaintStatus}. The tag is
279
+ * convention-only; `status-chokepoint.test.ts`'s source scan is the enforcement.
280
+ */
172
281
  export function updateStatus(state: SessionState, ctx: ExtensionContext): void {
282
+ // The idle config line: no run is active, so the spinner has no job.
283
+ stopProgressTicker(state);
284
+
173
285
  if (state.config.model) {
174
286
  ctx.ui.setStatus(
175
287
  "brl-subagent",
@@ -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
+ }
package/src/history.ts CHANGED
@@ -147,6 +147,12 @@ export function finalizeRunRecord(
147
147
  * `retryOnTimeout` is deliberately explicit-only: it arms a deadline for THIS
148
148
  * call, so it is never inherited. `template`, `chain`, `tasks`, `graph` and
149
149
  * `params` are not carried — a retried multi-step run degrades to a single task.
150
+ *
151
+ * `task` falls back to `originalParams.task` BEFORE `run.task` (issue #401/#411):
152
+ * the resume preamble now rides the system-prompt side, so a retry's record has
153
+ * a clean `task`; the fallback is a defensive invariant that also resolves a
154
+ * legacy pre-#411 record whose `task` still carries the preamble. Fresh records
155
+ * carry no `originalParams.task` and resolve from `run.task` exactly as before.
150
156
  */
151
157
  export function resolveRetryParams(
152
158
  params: {
@@ -173,12 +179,17 @@ export function resolveRetryParams(
173
179
  gitMode?: string;
174
180
  approvalMode?: string;
175
181
  force?: boolean;
182
+ /** The call-level Jev-line bypass (issue #412) — kept so an explicit
183
+ * noJev on a retry call still reaches the validation seam; it is never
184
+ * inherited from the original (a bypass is per dispatch, and the
185
+ * original's line already rides the recorded task). */
186
+ noJev?: string;
176
187
  },
177
188
  run: SubagentRun,
178
189
  ): typeof params {
179
190
  const orig = run.originalParams;
180
191
  return {
181
- task: params.task || run.task,
192
+ task: params.task || orig?.task || run.task,
182
193
  label: params.label ?? run.label,
183
194
  model: params.model ?? orig?.model,
184
195
  preset: params.preset ?? orig?.preset,
@@ -197,6 +208,7 @@ export function resolveRetryParams(
197
208
  gitMode: params.gitMode ?? orig?.gitMode,
198
209
  approvalMode: params.approvalMode ?? orig?.approvalMode,
199
210
  force: params.force ?? orig?.force,
211
+ noJev: params.noJev,
200
212
  };
201
213
  }
202
214