brl-subagent 2.6.0 → 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
@@ -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
 
@@ -78,7 +79,7 @@ delegation-heavy work.
78
79
  ## Deadlines and retries
79
80
 
80
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.
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).
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).
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.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 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 1900+ test suite pinning every contract against the real pi SDK.
18
18
 
19
19
  ---
20
20
 
@@ -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,6 +122,18 @@ 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).
@@ -305,6 +317,7 @@ The approval-aware fallback is the safety property: background runs have no appr
305
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.
306
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.
307
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.
308
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).
309
322
 
310
323
  ### Background fan-out
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brl-subagent",
3
- "version": "2.6.0",
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",
@@ -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