brl-subagent 2.7.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 +2 -2
- package/README.md +17 -9
- package/package.json +5 -5
- package/src/concurrency.ts +25 -2
- package/src/engineering-bar.ts +69 -0
- package/src/event-bus.ts +10 -0
- package/src/git.ts +58 -1
- package/src/headstate.ts +471 -0
- package/src/index.ts +787 -239
- package/src/kill-escalation.ts +87 -7
- package/src/loader.ts +46 -0
- package/src/notify-completion.ts +146 -5
- package/src/params.ts +198 -25
- package/src/prelude.ts +79 -3
- package/src/presets.ts +84 -15
- package/src/project-flags.ts +3 -3
- package/src/recovery-engine.ts +10 -0
- package/src/recovery.ts +155 -19
- package/src/run-registry.ts +20 -0
- package/src/runner.ts +34 -4
- package/src/schema.ts +37 -7
- package/src/session-manager.ts +782 -196
- package/src/state.ts +118 -16
- package/src/templates.ts +41 -14
- package/src/tui-format.ts +174 -6
- package/src/tui.ts +74 -26
- package/src/types.ts +177 -2
- package/src/unit-run.ts +10 -1
- package/src/validate.ts +87 -8
package/AGENT.md
CHANGED
|
@@ -78,8 +78,8 @@ delegation-heavy work.
|
|
|
78
78
|
|
|
79
79
|
## Deadlines and retries
|
|
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
|
|
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).
|
|
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.
|
|
83
83
|
|
|
84
84
|
## Mechanics pointer
|
|
85
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
|
+
**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 (`0o700` stores, `0o600` files; the directory mode is repaired on every write and is the confidentiality boundary), and a
|
|
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
|
|
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
|
|
|
@@ -110,9 +110,13 @@ All settings persist across sessions.
|
|
|
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
|
|
|
@@ -184,10 +188,14 @@ model: anthropic/claude-opus-4-6
|
|
|
184
188
|
tools:
|
|
185
189
|
- read
|
|
186
190
|
- bash
|
|
191
|
+
# optional — capture the run's findings to this path; needs the write tool
|
|
192
|
+
outputFile: findings.md
|
|
187
193
|
thinkingLevel: high
|
|
188
194
|
---
|
|
189
195
|
```
|
|
190
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
|
+
|
|
191
199
|
Custom presets override built-ins with the same name and survive `pi install` updates.
|
|
192
200
|
|
|
193
201
|
Refer to a preset via the `preset` parameter of `delegate_task` (see above). Parameters on `delegate_task` override preset values.
|
|
@@ -234,7 +242,7 @@ Supported frontmatter fields:
|
|
|
234
242
|
| `thinkingLevel` | string | `off` / `minimal` / `low` / `medium` / `high` / `xhigh` |
|
|
235
243
|
| `outputFile` | string | Output file path (may contain `${param}` slots) |
|
|
236
244
|
| `timeout` | number | Max milliseconds for the delegated run |
|
|
237
|
-
| `tools` | list | Tool allowlist |
|
|
245
|
+
| `tools` | list | Tool allowlist (empty = no tools) |
|
|
238
246
|
| `excludeTools` | list | Tools to exclude |
|
|
239
247
|
| `noBuiltinTools` | `"true"` / `"false"` | Disable all pi built-in tools |
|
|
240
248
|
| `inheritSystemPrompt` | `"true"` / `"false"` | Override system-prompt inheritance (default `true`) |
|
|
@@ -314,7 +322,7 @@ The approval-aware fallback is the safety property: background runs have no appr
|
|
|
314
322
|
|
|
315
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:
|
|
316
324
|
|
|
317
|
-
- **Per-agent timeout** —
|
|
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.
|
|
318
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.
|
|
319
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.
|
|
320
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.
|
|
@@ -324,7 +332,7 @@ The approval-aware fallback is the safety property: background runs have no appr
|
|
|
324
332
|
|
|
325
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.
|
|
326
334
|
|
|
327
|
-
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`.
|
|
328
336
|
|
|
329
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.
|
|
330
338
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brl-subagent",
|
|
3
|
-
"version": "2.
|
|
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"
|
|
@@ -40,10 +40,10 @@
|
|
|
40
40
|
"typebox": "*"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@earendil-works/pi-agent-core": "^1.
|
|
44
|
-
"@earendil-works/pi-ai": "^1.
|
|
45
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
46
|
-
"@earendil-works/pi-tui": "^1.
|
|
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",
|
|
47
47
|
"jiti": "^2.7.0",
|
|
48
48
|
"typebox": "1.3.27",
|
|
49
49
|
"typescript": "7.0.2",
|
package/src/concurrency.ts
CHANGED
|
@@ -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(
|
|
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,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) {
|