brl-subagent 2.9.0 → 2.9.1
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 +16 -1
- package/README.md +2 -2
- package/package.json +5 -5
- package/src/boot-recovery.ts +50 -3
- package/src/delegate-handler.ts +2 -2
- package/src/logging.ts +66 -3
- package/src/recovery.ts +236 -7
- package/src/run-registry.ts +131 -7
- package/src/schema.ts +4 -2
- package/src/session-manager.ts +512 -74
- package/src/tui.ts +4 -4
- package/src/validate.ts +26 -6
package/AGENT.md
CHANGED
|
@@ -78,7 +78,22 @@ 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 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.
|
|
81
|
+
- `timeout` (ms) is a **deadline, not a ceiling** — an explicit positive 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. The exceptions to "honored as given": a raw value `≥ 2³¹−1` ms **or a nonpositive value** normalizes to no timeout (a background run then gets the 30m default, a foreground run has none), and the opt-in `processChecks` high/xhigh **foreground** switch may drop an explicit timeout.
|
|
82
|
+
|
|
83
|
+
**Reference priors (2026-11-18 snapshot).** The table uses minutes; the `timeout` parameter itself is milliseconds. Reference workload: this repo, 2026-11-04T14:37Z → 2026-11-18T13:45Z; 217 settled background runs; the model cohorts are descriptive (each includes whatever tasks that model ran); the completed-only stats are the cap basis. Your mileage will vary: use your own run history when you have it; the 2h fallback is for an unknown shape, not a guarantee; a slow/local model needs more — pass a larger explicit timeout (a valid positive value is honored unless the opt-in high/xhigh foreground switch drops it; the only removals are that switch and the normalization of raw ≥2³¹−1/nonpositive values: a background run then gets the 30m default, a foreground run has none). The reference cap is not a runtime ceiling.
|
|
84
|
+
|
|
85
|
+
| model cohort (descriptive) | n (done/failed) | completed p50 | p90 | p99 | max | reference cap |
|
|
86
|
+
|---|---|---|---|---|---|---|
|
|
87
|
+
| deepseek-flash (implementation + probes + 24 failures: 23 transport + 1 abort) | 106 (82/24) | 9.1m | 19.8m | 26.9m | 28.4m | 60m |
|
|
88
|
+
| muse-spark / muse-ember (review) | 70 (60/10) | 4.8m | 8.2m | 16.0m | 16.3m | 20–30m |
|
|
89
|
+
| gpt-6.1-terra (critique) | 39 (37/2) | 1.6m | 6.1m | 10.0m | 10.6m | 30m |
|
|
90
|
+
| qwen3.8-max (critique; n=2) | 2 (2/0) | 29.7m | — | — | 35.1m | 60m (caveat) |
|
|
91
|
+
| all background | 217 (181/36) | 5.2m | 15.7m | 26.9m | 35.1m | 2h fallback |
|
|
92
|
+
|
|
93
|
+
- The cap is a **reference ceiling above the observed tail** for that model cohort's completed work, not a runtime ceiling or a target. A run that hits it is aborted (background) or killed (foreground); pass a larger explicit timeout if you know the task/model needs it (a valid positive value is honored unless the opt-in high/xhigh foreground switch drops it; raw ≥2³¹−1/nonpositive values normalize to no timeout, background then 30m, foreground none).
|
|
94
|
+
- The 30-minute **background** default applies when no valid timeout remains after normalization; a **foreground** run has no default. It is a default, not an enforced floor.
|
|
95
|
+
- Quick probes are not a separate validated cohort; the 4-run sample is descriptive only. Use the 30-minute **background** default for a **background** probe unless your own history supports a shorter cap; a **foreground/inline** probe (`background: false`) has no default — pass an explicit `timeout` if it needs a cap. The opt-in high/xhigh foreground switch may drop an explicit timeout.
|
|
96
|
+
- The qwen row is n=2 — a caveat, not a rule; the 60m cap covers it, and the 2h fallback is for an unknown shape.
|
|
82
97
|
- `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
98
|
|
|
84
99
|
## Mechanics pointer
|
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.9.
|
|
5
|
+
**Version:** 2.9.1 · **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 3100+ test suite pinning every contract against the real pi SDK.
|
|
18
18
|
|
|
19
19
|
---
|
|
20
20
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brl-subagent",
|
|
3
|
-
"version": "2.9.
|
|
3
|
+
"version": "2.9.1",
|
|
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"
|
|
@@ -41,10 +41,10 @@
|
|
|
41
41
|
"typebox": "*"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@earendil-works/pi-agent-core": "^1.
|
|
45
|
-
"@earendil-works/pi-ai": "^1.
|
|
46
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
47
|
-
"@earendil-works/pi-tui": "^1.
|
|
44
|
+
"@earendil-works/pi-agent-core": "^1.6.0",
|
|
45
|
+
"@earendil-works/pi-ai": "^1.6.0",
|
|
46
|
+
"@earendil-works/pi-coding-agent": "^1.6.0",
|
|
47
|
+
"@earendil-works/pi-tui": "^1.6.0",
|
|
48
48
|
"jiti": "^2.7.0",
|
|
49
49
|
"typebox": "1.3.27",
|
|
50
50
|
"typescript": "7.0.2",
|
package/src/boot-recovery.ts
CHANGED
|
@@ -109,21 +109,40 @@ export function createBootRecovery(rt: RuntimeContext): BootRecovery {
|
|
|
109
109
|
// pid-only liveness cannot rule out pid reuse, so nothing is killed or
|
|
110
110
|
// marked unverified.
|
|
111
111
|
async function performBootRecovery(): Promise<void> {
|
|
112
|
+
// Issue #546 (major 6): the whole session-manager wiring — the record-flip
|
|
113
|
+
// applier included — is built at the EXISTING lazy import site and in its own
|
|
114
|
+
// containment. A failure there leaves `wiring` undefined: the scan still runs
|
|
115
|
+
// over the run registry, and `applyRecordFlip`/`readFreshAgentRecord` are not
|
|
116
|
+
// passed at all, so the scan takes its no-applier branch (the pre-#546
|
|
117
|
+
// behaviour: markers untouched). No half-wired repair is possible.
|
|
118
|
+
//
|
|
119
|
+
// The import must stay DYNAMIC: a static named import of a lifecycle mutator
|
|
120
|
+
// violates the reader-API rule in architecture-rules.test.ts (the allow-list
|
|
121
|
+
// is `getAgent`/`listAgents`; a dynamic `import()` edge carries no names
|
|
122
|
+
// there), and it would load session-manager on every extension start.
|
|
123
|
+
let sm: typeof import("./session-manager") | undefined;
|
|
124
|
+
try {
|
|
125
|
+
sm = await import("./session-manager");
|
|
126
|
+
} catch (err) {
|
|
127
|
+
log.warn("Boot recovery: session-manager unavailable — running the registry-only scan", {
|
|
128
|
+
error: (err as Error).message,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const wiring = sm;
|
|
112
132
|
try {
|
|
113
|
-
const { getAgent, markAgentInterrupted } = await import("./session-manager");
|
|
114
133
|
// `recoverProduction` owns the /proc platform guard (nothing is marked or
|
|
115
134
|
// killed without start-token verification) — see src/recovery.ts.
|
|
116
135
|
const summary = await recoverProduction({
|
|
117
136
|
log,
|
|
118
137
|
// Read THAT ONE agent record by id — never the whole store.
|
|
119
|
-
readAgentRecord: (id) => getAgent(id),
|
|
138
|
+
readAgentRecord: wiring ? (id) => wiring.getAgent(id) : undefined,
|
|
120
139
|
mark(record, interruptedAt) {
|
|
121
140
|
// Registry entry = the durable mark for every kind. Issue #304: its
|
|
122
141
|
// boolean is the durable-write result — do NOT drop it, or the boot
|
|
123
142
|
// summary would claim a mark that never landed. The scan counts a
|
|
124
143
|
// `false` as `markFailures` and warns with the id.
|
|
125
144
|
const durable = markInterrupted(record.id, interruptedAt);
|
|
126
|
-
if (record.kind === "agent") markAgentInterrupted(record.id, interruptedAt);
|
|
145
|
+
if (record.kind === "agent") wiring?.markAgentInterrupted(record.id, interruptedAt);
|
|
127
146
|
return durable;
|
|
128
147
|
},
|
|
129
148
|
// Issue #447: a dispatch whose acceptance marker is still `null` never
|
|
@@ -133,6 +152,24 @@ export function createBootRecovery(rt: RuntimeContext): BootRecovery {
|
|
|
133
152
|
finalizeNeverStarted: (run) => {
|
|
134
153
|
state.persistRun(pi, run);
|
|
135
154
|
},
|
|
155
|
+
...(wiring
|
|
156
|
+
? {
|
|
157
|
+
// Issue #546 (major 3): the pre-flip read is DISK-ONLY — `getAgent`
|
|
158
|
+
// is memory-first and a stale map would re-stamp a settled record.
|
|
159
|
+
readFreshAgentRecord: (id: string) => wiring.readAgentRecordFromDisk(id),
|
|
160
|
+
// Issue #546: the terminal write whose process died before the
|
|
161
|
+
// agent record was flipped. The two writes belong together — the
|
|
162
|
+
// registry entry IS the marker, so it may be retired only once
|
|
163
|
+
// the flip is durable. The outcome is passed through, and a
|
|
164
|
+
// settlement that did not land (record write OR unlink, major 4)
|
|
165
|
+
// keeps the entry for the next boot.
|
|
166
|
+
applyRecordFlip: (verdict) => {
|
|
167
|
+
const outcome = wiring.flipAgentRecord(verdict.id, verdict.status, verdict.error);
|
|
168
|
+
if (outcome === false) return false;
|
|
169
|
+
return clearInflightRun(verdict.id) ? outcome : false;
|
|
170
|
+
},
|
|
171
|
+
}
|
|
172
|
+
: {}),
|
|
136
173
|
});
|
|
137
174
|
// Report the scan whenever it did anything durable OR attempted a mark
|
|
138
175
|
// that failed — a failure-only boot must not be silent (issue #304).
|
|
@@ -141,6 +178,16 @@ export function createBootRecovery(rt: RuntimeContext): BootRecovery {
|
|
|
141
178
|
}
|
|
142
179
|
// Issue #447: never-started dispatches are finalized, not marked — a
|
|
143
180
|
// separate line so the two outcomes cannot be read as one another.
|
|
181
|
+
// Issue #546: record flips a dead process left pending. A separate line
|
|
182
|
+
// from both the interrupted marks and the never-started finalizes — this
|
|
183
|
+
// outcome rewrites the AGENT RECORD, which neither of those does.
|
|
184
|
+
if (summary.flipRepaired > 0 || summary.flipRetired > 0 || summary.flipFailures > 0) {
|
|
185
|
+
log.warn("Boot recovery settled pending record flips", {
|
|
186
|
+
repaired: summary.flipRepaired,
|
|
187
|
+
retired: summary.flipRetired,
|
|
188
|
+
failures: summary.flipFailures,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
144
191
|
if (summary.neverStarted > 0) {
|
|
145
192
|
log.info("Boot recovery finalized never-started dispatches", {
|
|
146
193
|
count: summary.neverStarted,
|
package/src/delegate-handler.ts
CHANGED
|
@@ -2148,7 +2148,7 @@ export function createDelegateHandler(
|
|
|
2148
2148
|
"You can customize per-call via inheritSystemPrompt and systemPrompt: set inheritSystemPrompt: false to save context, provide a systemPrompt for custom instructions, or use both to add instructions on top of inheritance.",
|
|
2149
2149
|
"Set thinkingLevel per call to match task complexity. The level is capped at the user's configured maximum. Map tasks to levels using this heuristic: off = file listing, grep, simple read. minimal = file diff, syntax check, find-and-replace. low = refactoring, test generation, documentation. medium = default — code review, debugging, moderate analysis. high = security audit, architecture review, complex debugging. xhigh = multi-step causal reasoning, research, novel problem solving. Default to 'off' or 'minimal' for trivial tasks — do not waste the user's budget.",
|
|
2150
2150
|
"Use outputFile to have the subagent write full findings to disk and return only a structured summary — saves context tokens for large investigations.",
|
|
2151
|
-
"Set timeout (in ms) to limit how long a subagent can run. Useful for tasks that might hang or get stuck. Background runs default to a 30-minute deadline when no timeout is given;
|
|
2151
|
+
"Set timeout (in ms) to limit how long a subagent can run. Useful for tasks that might hang or get stuck. Background runs default to a 30-minute deadline when no timeout is given; a foreground run has no default. An explicit positive timeout is honored as given — except a raw value ≥ 2³¹−1 ms or a nonpositive value (both normalize to no timeout; for a background run the 30-minute default then applies, a foreground run has none) and the opt-in high-thinking foreground switch that may drop it. 30 minutes is a background default, not a ceiling.",
|
|
2152
2152
|
"Set cwd to override the subagent's working directory. Defaults to the current project directory.",
|
|
2153
2153
|
"Set label to give the subagent a human-readable name (e.g., 'security-audit' or 'docs-review'). Labels appear in the status bar and tool call display.",
|
|
2154
2154
|
`Use preset to apply a delegation configuration (built-in or custom via /brl-subagent preset). Preset values are defaults — explicit parameters override them. IMPORTANT: some presets restrict tools — e.g. outputFile requires the subagent's write tool, which security-auditor and code-reviewer exclude. Built-in presets: ${presetRestrictionSummary}. Custom presets are NOT listed here — inspect them via /brl-subagent preset before combining with outputFile or tool-dependent work. When combining a preset with outputFile or tool-dependent work, verify the preset allows the required tools.`,
|
|
@@ -2164,7 +2164,7 @@ export function createDelegateHandler(
|
|
|
2164
2164
|
"2. **Thinking level**: Match thinking level to task complexity: off/minimal for trivial tasks (file listing, grep), low for refactoring/docs, medium for code review/debugging, high for security audits/complex debugging, xhigh for multi-step reasoning/novel problems.",
|
|
2165
2165
|
"3. **Git mode**: Use gitMode='branch' for tasks that create commits or PRs. Use gitMode='none' for read-only tasks.",
|
|
2166
2166
|
"4. **Tools**: Verify the subagent has the tools it needs. If the task writes files, ensure write and edit are not excluded. If the task runs commands, ensure bash is not excluded.",
|
|
2167
|
-
"5.
|
|
2167
|
+
"**5. Timeout:** A deadline is a cap, not a schedule: over-allocating is cheap, under-allocating is expensive. The `timeout` parameter is milliseconds; think in minutes. The 30-minute **background** default applies only when no valid timeout remains after normalization — it is a default, not an enforced floor; a **foreground** run has no default deadline. An explicit **positive** value is honored as given, except a raw value ≥ 2³¹−1 ms **or a nonpositive value** (both normalize to no timeout; a background run then gets the 30m default, a foreground run has none) and the opt-in high-thinking foreground switch that may drop it. When in doubt **pass `timeout: 7200000`** — 2 hours (7,200,000 ms); for slow/local models or long tasks, pass more. Reference-workload priors: `AGENT.md` §Deadlines and retries.",
|
|
2168
2168
|
"",
|
|
2169
2169
|
"These guardrails prevent common misconfigurations. The extension also validates configuration before spawning (H1): tool warnings are surfaced in the returned result, but two mismatches are HARD errors that reject the delegation — outputFile with the write tool excluded, and a capability-critical task/toolset mismatch (a run/execute/test/compile/benchmark task without bash, or an exploration task with none of find/ls/grep/bash; pass force: true to override the capability class). Getting it right the first time is faster and more efficient.",
|
|
2170
2170
|
"",
|
package/src/logging.ts
CHANGED
|
@@ -129,6 +129,61 @@ function resolveLogDir(): string | undefined {
|
|
|
129
129
|
return logCwd ? path.join(logCwd, ".pi", "subagent-logs") : undefined;
|
|
130
130
|
}
|
|
131
131
|
|
|
132
|
+
// ---------------------------------------------------------------------------
|
|
133
|
+
// Serialisation (issue #545)
|
|
134
|
+
// ---------------------------------------------------------------------------
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* #545: `data` is caller-supplied and `JSON.stringify` throws on a cycle and on a
|
|
138
|
+
* `BigInt`. A cycle collapses to `[Circular]`, a `BigInt` to its decimal literal
|
|
139
|
+
* (`10n`, and `-0n` to `"0n"`). Ancestors are tracked rather than every value ever
|
|
140
|
+
* seen, so `{a: x, b: x}` — a shared reference, not a cycle — keeps both copies.
|
|
141
|
+
* The replacer only sees values JSON reaches: a falsy root `data` (`0n`, `-0n`,
|
|
142
|
+
* `""`) is dropped by `log()`'s truthiness check before serialisation.
|
|
143
|
+
*/
|
|
144
|
+
function circularSafeReplacer(): (this: unknown, key: string, value: unknown) => unknown {
|
|
145
|
+
const ancestors: unknown[] = [];
|
|
146
|
+
return function (this: unknown, _key: string, value: unknown): unknown {
|
|
147
|
+
if (typeof value === "bigint") return `${value}n`;
|
|
148
|
+
if (typeof value !== "object" || value === null) return value;
|
|
149
|
+
while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) ancestors.pop();
|
|
150
|
+
if (ancestors.includes(value)) return "[Circular]";
|
|
151
|
+
ancestors.push(value);
|
|
152
|
+
return value;
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** #545: why a payload failed to serialise — guarded, because the caught value can
|
|
157
|
+
* be a Proxy whose `.message` access throws too. */
|
|
158
|
+
function faultReason(err: unknown): string {
|
|
159
|
+
try {
|
|
160
|
+
const message = (err as { message?: unknown }).message;
|
|
161
|
+
return typeof message === "string" && message !== "" ? message : "unknown fault";
|
|
162
|
+
} catch {
|
|
163
|
+
return "unknown fault";
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** #545: the entry line, defensively. The replacer covers a cycle and a `BigInt`;
|
|
168
|
+
* the catch covers what it cannot — a throwing `toJSON`, getter or Proxy trap.
|
|
169
|
+
* `data` becomes an object marker, `{"[unserializable]": reason}`: an object keeps
|
|
170
|
+
* every consumer that reads `data.<field>` alive (`missing → undefined`), where a
|
|
171
|
+
* string would crash one. The line is serialised and reaches the conditional
|
|
172
|
+
* file-write attempt below; whether a file exists still depends on a configured
|
|
173
|
+
* cwd and on the sink, which keeps swallowing its own faults. */
|
|
174
|
+
function serializeEntry(entry: Record<string, unknown>): string {
|
|
175
|
+
try {
|
|
176
|
+
return JSON.stringify(entry, circularSafeReplacer());
|
|
177
|
+
} catch (err) {
|
|
178
|
+
return JSON.stringify({
|
|
179
|
+
...entry,
|
|
180
|
+
prefix: typeof entry.prefix === "string" ? entry.prefix : "[unprintable prefix]",
|
|
181
|
+
message: typeof entry.message === "string" ? entry.message : "[unprintable message]",
|
|
182
|
+
data: { "[unserializable]": faultReason(err) },
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
132
187
|
/**
|
|
133
188
|
* Create a logger for a specific module.
|
|
134
189
|
* Logs are written to `<cwd>/.pi/subagent-logs/brl-subagent.log` relative to the
|
|
@@ -150,13 +205,21 @@ export function createLogger(prefix: string, cwd?: string): Logger {
|
|
|
150
205
|
...(data ? { data } : {}),
|
|
151
206
|
};
|
|
152
207
|
|
|
153
|
-
const line =
|
|
208
|
+
const line = serializeEntry(entry);
|
|
154
209
|
|
|
155
210
|
// Console mirror — opt-in (issue #265). Off by default so a logger call
|
|
156
211
|
// can never corrupt the pi TUI renderer; BRL_LOG_CONSOLE opts back in.
|
|
157
212
|
if (consoleOutput) {
|
|
158
|
-
|
|
159
|
-
|
|
213
|
+
try {
|
|
214
|
+
// Selection is inside the try on purpose — a replaced console can
|
|
215
|
+
// throw on the property access itself, not only on the call.
|
|
216
|
+
const consoleMethod = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
|
|
217
|
+
consoleMethod(`[${prefix}] ${level.toUpperCase()}: ${message}`);
|
|
218
|
+
} catch {
|
|
219
|
+
// Issue #543: the mirror fault does not prevent the file-write attempt
|
|
220
|
+
// when a cwd is configured; persistence remains conditional on the file
|
|
221
|
+
// sink, and `log.*` returns normally.
|
|
222
|
+
}
|
|
160
223
|
}
|
|
161
224
|
|
|
162
225
|
// File output — resolved on each call because the cwd may be set after
|
package/src/recovery.ts
CHANGED
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
*/
|
|
33
33
|
|
|
34
34
|
import type { Logger } from "./logging";
|
|
35
|
-
import { listInflightRuns, type InflightRun } from "./run-registry";
|
|
35
|
+
import { listInflightRuns, type InflightRun, type RecordFlipStatus } from "./run-registry";
|
|
36
36
|
import { assertSafeAgentId } from "./sanitize";
|
|
37
37
|
import { isProcAvailable, defaultRecoveryDeps } from "./proc";
|
|
38
38
|
import { decideRecovery, classifyOwner, reapPids, type RecoveryDeps, type RecoveryRecord } from "./recovery-engine";
|
|
@@ -70,6 +70,21 @@ export interface BootScanSummary {
|
|
|
70
70
|
* write is warned — either way the entry stays out of the interrupted class.
|
|
71
71
|
*/
|
|
72
72
|
neverStarted: number;
|
|
73
|
+
/**
|
|
74
|
+
* Issue #546: entries carrying a `recordFlipPending` marker whose agent record
|
|
75
|
+
* was still `running` with a provably dead owner — the flip was APPLIED and the
|
|
76
|
+
* entry retired, so a `running` record that no boot scan could otherwise see is
|
|
77
|
+
* terminal after this boot.
|
|
78
|
+
*/
|
|
79
|
+
flipRepaired: number;
|
|
80
|
+
/**
|
|
81
|
+
* Issue #546: markers whose record was ALREADY terminal (or absent) — the flip
|
|
82
|
+
* landed and only the retirement was lost. The entry is retired; nothing is
|
|
83
|
+
* rewritten and no terminal event is re-emitted.
|
|
84
|
+
*/
|
|
85
|
+
flipRetired: number;
|
|
86
|
+
/** Issue #546: flips decided but whose durable write did NOT land (#304 rule). */
|
|
87
|
+
flipFailures: number;
|
|
73
88
|
}
|
|
74
89
|
|
|
75
90
|
/** The all-zero summary (a skipped scan / an empty registry). */
|
|
@@ -85,6 +100,9 @@ export function emptyBootScanSummary(): BootScanSummary {
|
|
|
85
100
|
skippedNoOwner: 0,
|
|
86
101
|
skippedUnsafeIds: 0,
|
|
87
102
|
neverStarted: 0,
|
|
103
|
+
flipRepaired: 0,
|
|
104
|
+
flipRetired: 0,
|
|
105
|
+
flipFailures: 0,
|
|
88
106
|
};
|
|
89
107
|
}
|
|
90
108
|
|
|
@@ -281,6 +299,39 @@ export function neverStartedRunRecord(
|
|
|
281
299
|
};
|
|
282
300
|
}
|
|
283
301
|
|
|
302
|
+
/** What the boot verdict hands the caller: which record to flip, to what. */
|
|
303
|
+
export interface RecordFlipVerdict {
|
|
304
|
+
id: string;
|
|
305
|
+
status: RecordFlipStatus;
|
|
306
|
+
error?: string;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Issue #546 (major 4): what the applier's unit of work did. `'repaired'` = the
|
|
311
|
+
* record was rewritten and the store says terminal; `'retired'` = no rewrite was
|
|
312
|
+
* needed (the record was already terminal or absent) and only the entry was
|
|
313
|
+
* retired; `false` = NOT settled (unreadable record, a failed record write, or a
|
|
314
|
+
* failed unlink) — the scan keeps the marker and counts `flipFailures`.
|
|
315
|
+
*
|
|
316
|
+
* The applier reports the outcome instead of the scan inferring it from its own
|
|
317
|
+
* earlier decision: under the two-boot race the second boot's applier sees a
|
|
318
|
+
* terminal record and retires, and the ledger must say `retired` (not a second
|
|
319
|
+
* repair) without the scan having to re-read anything.
|
|
320
|
+
*/
|
|
321
|
+
export type RecordFlipOutcome = "repaired" | "retired" | false;
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Issue #546 (major 2/3): the disk-only, TRI-STATE read of one agent record,
|
|
325
|
+
* taken immediately before the flip verdict. `exists: false` is CONFIRMED
|
|
326
|
+
* ABSENCE (nothing durable can go stale ⇒ the marker may retire); `exists: true`
|
|
327
|
+
* with `record: null` is PRESENT-BUT-UNREADABLE/CORRUPT (we know nothing ⇒ hold,
|
|
328
|
+
* keep the marker); a record is the state the decision is made on.
|
|
329
|
+
*/
|
|
330
|
+
export interface FreshAgentRecord {
|
|
331
|
+
record: PersistedAgentLike | null;
|
|
332
|
+
exists: boolean;
|
|
333
|
+
}
|
|
334
|
+
|
|
284
335
|
export interface RegistryScanOptions {
|
|
285
336
|
deps: RecoveryDeps;
|
|
286
337
|
/**
|
|
@@ -301,6 +352,24 @@ export interface RegistryScanOptions {
|
|
|
301
352
|
* entry so a registry without an agent file is still marked, not skipped.
|
|
302
353
|
*/
|
|
303
354
|
readAgentRecord?(id: string): PersistedAgentLike | null;
|
|
355
|
+
/**
|
|
356
|
+
* Issue #546: apply a persisted `recordFlipPending` marker to that run's agent
|
|
357
|
+
* record AND retire the registry entry (the two writes belong together: the
|
|
358
|
+
* entry is the marker, so it may die only with the flip). Returns the outcome
|
|
359
|
+
* the ledger counts; `false` (a failed record write OR a failed unlink) keeps
|
|
360
|
+
* the entry, so the marker survives to the next boot. Idempotent by contract:
|
|
361
|
+
* an already-terminal record is not rewritten and emits no event.
|
|
362
|
+
* Absent ⇒ the marker is left untouched (no write, no retirement).
|
|
363
|
+
*/
|
|
364
|
+
applyRecordFlip?(verdict: RecordFlipVerdict): RecordFlipOutcome;
|
|
365
|
+
/**
|
|
366
|
+
* Issue #546 (major 3): a DISK read of the one agent record, taken just before
|
|
367
|
+
* the verdict — never the scanner's earlier snapshot, which is memory-first
|
|
368
|
+
* (`getAgent`) and may be stale. Wired together with `applyRecordFlip`; when
|
|
369
|
+
* either is absent the marker branch holds (fail-closed): a marker is never
|
|
370
|
+
* retired on a state we did not just read.
|
|
371
|
+
*/
|
|
372
|
+
readFreshAgentRecord?(id: string): FreshAgentRecord;
|
|
304
373
|
now?: () => Date;
|
|
305
374
|
log?: Pick<Logger, "debug" | "info" | "warn">;
|
|
306
375
|
}
|
|
@@ -318,6 +387,53 @@ export interface RegistryScanOptions {
|
|
|
318
387
|
* invisible here — consistent with the maintained `no-owner` policy (don't act
|
|
319
388
|
* on what we cannot verify).
|
|
320
389
|
*/
|
|
390
|
+
/**
|
|
391
|
+
* Issue #447 / #546: the one ownership rule both pre-verdict paths share — a
|
|
392
|
+
* record may be acted on ONLY when its owner is provably dead. A live owner may
|
|
393
|
+
* still be inside its own pre-start window (the git-branch lock, a slow
|
|
394
|
+
* transcript start, the microseconds between the marker write and its flip) and
|
|
395
|
+
* is about to finish the job itself; an owner we cannot verify is never acted on
|
|
396
|
+
* (`classifyOwner` returns "unverifiable" without /proc).
|
|
397
|
+
*/
|
|
398
|
+
function ownerProvablyDead(owner: RecoveryRecord["owner"], deps: RecoveryDeps): boolean {
|
|
399
|
+
if (!owner || !Number.isInteger(owner.pid) || owner.pid <= 0) return false;
|
|
400
|
+
return classifyOwner(owner, deps) === "dead";
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Issue #546: the verdict for an entry that carries a `recordFlipPending`
|
|
405
|
+
* marker. Three outcomes plus one hold:
|
|
406
|
+
*
|
|
407
|
+
* - record already terminal, or CONFIRMED ABSENT → the flip landed (or nothing
|
|
408
|
+
* durable exists) and only the retirement was lost: retire only
|
|
409
|
+
* (`flipRetired`);
|
|
410
|
+
* - record still `running` and the owner provably dead → apply the flip and
|
|
411
|
+
* retire (`flipRepaired`);
|
|
412
|
+
* - record present but UNREADABLE/corrupt → HOLD: we cannot tell whether a
|
|
413
|
+
* `running` record is still there, so the marker must survive (major 2);
|
|
414
|
+
* - record still `running` but the owner live/unverifiable → HOLD, write
|
|
415
|
+
* nothing, and skip ordinary recovery for this entry (`continue`).
|
|
416
|
+
*
|
|
417
|
+
* `fresh` is a DISK read taken by the caller immediately before this call
|
|
418
|
+
* (major 3), not the scanner's snapshot.
|
|
419
|
+
*/
|
|
420
|
+
function recordFlipDecision(
|
|
421
|
+
entry: InflightRun,
|
|
422
|
+
fresh: FreshAgentRecord,
|
|
423
|
+
deps: RecoveryDeps,
|
|
424
|
+
): "repaired" | "retired" | "held" | "unreadable" {
|
|
425
|
+
// Major 2: absence and unreadability are OPPOSITE verdicts. A confirmed
|
|
426
|
+
// absence may retire the marker (nothing durable can go stale); a file that
|
|
427
|
+
// exists but cannot be parsed keeps it (we know nothing, and retiring would
|
|
428
|
+
// strand a possibly still-`running` record). `unreadable` is its own verdict
|
|
429
|
+
// so the ledger can count it as a failed settlement instead of a silent hold.
|
|
430
|
+
if (!fresh.exists) return "retired";
|
|
431
|
+
if (!fresh.record) return "unreadable";
|
|
432
|
+
if (fresh.record.status !== "running") return "retired";
|
|
433
|
+
const owner = fresh.record.owner ?? entry.owner;
|
|
434
|
+
return ownerProvablyDead(owner, deps) ? "repaired" : "held";
|
|
435
|
+
}
|
|
436
|
+
|
|
321
437
|
export async function recoverInflightRuns(options: RegistryScanOptions): Promise<BootScanSummary> {
|
|
322
438
|
// Issue #304 read/write asymmetry, fail-closed: `listInflightRuns` accepts
|
|
323
439
|
// any string id, but every write (and `markInterrupted`) resolves through
|
|
@@ -347,11 +463,120 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
|
|
|
347
463
|
// is nothing to reap, nothing to interrupt, and nothing to retry. It is
|
|
348
464
|
// finalized `failed` below instead of being handed to the decision engine.
|
|
349
465
|
const neverStarted: InflightRun[] = [];
|
|
466
|
+
// Issue #546: the counters for the marker verdict (a marker is not a
|
|
467
|
+
// candidate; it is a repair).
|
|
468
|
+
let flipRepaired = 0;
|
|
469
|
+
let flipRetired = 0;
|
|
470
|
+
let flipFailures = 0;
|
|
350
471
|
for (const entry of addressable) {
|
|
351
472
|
const isBackground = entry.kind === "background";
|
|
352
473
|
// Only a background entry has an agent record to enrich from (and to drop
|
|
353
474
|
// a stale entry by); the read is that ONE file, never the whole store.
|
|
354
475
|
const agent = isBackground ? (options.readAgentRecord?.(entry.id) ?? null) : null;
|
|
476
|
+
// Issue #546: a marker means the terminal run-entry write was ATTEMPTED and
|
|
477
|
+
// the agent-record flip was not seen through. Settle it BEFORE the
|
|
478
|
+
// terminal-record drop below — that drop's whole job is to swallow a stale
|
|
479
|
+
// entry, and swallowing a marker would leave exactly the zombie row this
|
|
480
|
+
// issue is about. A marker is not gated by `recovery` (a repair is not an
|
|
481
|
+
// offer) and not by `acceptedAt` (the marker already names the terminal
|
|
482
|
+
// status, which supersedes the never-started class).
|
|
483
|
+
if (entry.recordFlipPending) {
|
|
484
|
+
if (!options.applyRecordFlip || !options.readFreshAgentRecord) {
|
|
485
|
+
// HOLD — and skip ordinary recovery for this entry. A half-wired
|
|
486
|
+
// applier cannot settle the marker, but falling through is worse than
|
|
487
|
+
// doing nothing: the never-started finalizer would retire a marker
|
|
488
|
+
// over a record that is still `running`, and the interrupted mark
|
|
489
|
+
// would stamp a dispatch whose terminal run entry is already
|
|
490
|
+
// written (r2 major 2). Entry and marker stay byte-identical for
|
|
491
|
+
// the next fully wired boot.
|
|
492
|
+
options.log?.debug("Recovery: held a record-flip marker (applier or fresh-record reader not wired)", {
|
|
493
|
+
id: entry.id,
|
|
494
|
+
kind: entry.kind,
|
|
495
|
+
});
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
{
|
|
499
|
+
// Issue #546 (major 3): the pre-flip read is taken HERE, after the
|
|
500
|
+
// candidate loop and immediately before the verdict — so a boot that
|
|
501
|
+
// begins after another finished sees the terminal record and retires
|
|
502
|
+
// without rewriting. Two boots that BOTH read here before either
|
|
503
|
+
// writes are the stated limit (see the spec's narrowed guarantee).
|
|
504
|
+
const fresh = options.readFreshAgentRecord(entry.id);
|
|
505
|
+
const decision = recordFlipDecision(entry, fresh, options.deps);
|
|
506
|
+
if (decision === "unreadable") {
|
|
507
|
+
// Major 2: the record exists but cannot be parsed, so we cannot
|
|
508
|
+
// tell whether it is still `running`. The marker is KEPT and the
|
|
509
|
+
// settlement is counted failed (never silently dropped).
|
|
510
|
+
flipFailures++;
|
|
511
|
+
options.log?.warn("Recovery: could not read the agent record for a record-flip marker — the marker is kept", {
|
|
512
|
+
id: entry.id,
|
|
513
|
+
kind: entry.kind,
|
|
514
|
+
});
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (decision === "held") {
|
|
518
|
+
// NOT a candidate either: the owner may be about to land this flip
|
|
519
|
+
// itself, and the "don't act on what we cannot verify" policy applies
|
|
520
|
+
// (neverStarted's no-owner rule). A marker is never offered as an
|
|
521
|
+
// interrupted run — that would offer a retry for a run that already
|
|
522
|
+
// wrote its terminal entry.
|
|
523
|
+
options.log?.debug("Recovery: held a record-flip marker whose owner is live or unverifiable", {
|
|
524
|
+
id: entry.id,
|
|
525
|
+
kind: entry.kind,
|
|
526
|
+
});
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
{
|
|
530
|
+
// The APPLIER's outcome is the ledger, not the decision taken above:
|
|
531
|
+
// under the two-boot race the second applier can find the record
|
|
532
|
+
// already terminal and retire — that is a `retired`, not a second
|
|
533
|
+
// `repaired`.
|
|
534
|
+
let outcome: RecordFlipOutcome = false;
|
|
535
|
+
try {
|
|
536
|
+
outcome = options.applyRecordFlip({
|
|
537
|
+
id: entry.id,
|
|
538
|
+
status: entry.recordFlipPending.status,
|
|
539
|
+
...(entry.recordFlipPending.error !== undefined
|
|
540
|
+
? { error: entry.recordFlipPending.error }
|
|
541
|
+
: {}),
|
|
542
|
+
});
|
|
543
|
+
} catch (err) {
|
|
544
|
+
// Best-effort, exactly like the mark and never-started paths: a
|
|
545
|
+
// failed repair must not abort the scan for the other candidates.
|
|
546
|
+
options.log?.warn("Recovery: record-flip repair threw", {
|
|
547
|
+
id: entry.id,
|
|
548
|
+
error: (err as Error).message,
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
if (outcome === false) {
|
|
552
|
+
flipFailures++;
|
|
553
|
+
options.log?.warn("Recovery: record-flip settlement did not land — the marker is kept", {
|
|
554
|
+
id: entry.id,
|
|
555
|
+
kind: entry.kind,
|
|
556
|
+
status: entry.recordFlipPending.status,
|
|
557
|
+
decision,
|
|
558
|
+
});
|
|
559
|
+
} else if (outcome === "repaired") {
|
|
560
|
+
flipRepaired++;
|
|
561
|
+
options.log?.info("Recovery: repaired a record whose terminal flip was lost", {
|
|
562
|
+
id: entry.id,
|
|
563
|
+
kind: entry.kind,
|
|
564
|
+
status: entry.recordFlipPending.status,
|
|
565
|
+
});
|
|
566
|
+
} else {
|
|
567
|
+
flipRetired++;
|
|
568
|
+
options.log?.debug("Recovery: retired a record-flip marker whose flip had landed", {
|
|
569
|
+
id: entry.id,
|
|
570
|
+
kind: entry.kind,
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
// A landed settlement retires the entry (the applier does it) and a
|
|
574
|
+
// kept marker must not be re-read as an ordinary candidate — either
|
|
575
|
+
// way this entry's scan is over.
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
355
580
|
if (agent && agent.status !== "running") continue;
|
|
356
581
|
// Issue #447: ONE tri-state read for both kinds, so the `null` rule cannot
|
|
357
582
|
// drift between the background and run branches.
|
|
@@ -389,12 +614,7 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
|
|
|
389
614
|
// terminal record the run's real terminal entry could not outrank (the
|
|
390
615
|
// store keeps the earlier entry, and readers prefer the LAST one). No owner or
|
|
391
616
|
// an unverifiable one ⇒ no write, exactly as for the mark path.
|
|
392
|
-
const
|
|
393
|
-
const ownerDead =
|
|
394
|
-
!!owner &&
|
|
395
|
-
Number.isInteger(owner.pid) &&
|
|
396
|
-
owner.pid > 0 &&
|
|
397
|
-
classifyOwner(owner, options.deps) === "dead";
|
|
617
|
+
const ownerDead = ownerProvablyDead(entry.owner, options.deps);
|
|
398
618
|
if (!ownerDead) {
|
|
399
619
|
options.log?.debug("Recovery: left a never-started dispatch with a live/unverified owner", {
|
|
400
620
|
id: entry.id,
|
|
@@ -434,6 +654,9 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
|
|
|
434
654
|
});
|
|
435
655
|
summary.skippedUnsafeIds = unsafeIds.length;
|
|
436
656
|
summary.neverStarted = settledNeverStarted;
|
|
657
|
+
summary.flipRepaired = flipRepaired;
|
|
658
|
+
summary.flipRetired = flipRetired;
|
|
659
|
+
summary.flipFailures = flipFailures;
|
|
437
660
|
return summary;
|
|
438
661
|
}
|
|
439
662
|
|
|
@@ -449,6 +672,10 @@ export interface ProductionRecoveryOptions {
|
|
|
449
672
|
/** Issue #447: persist the terminal record of a never-started dispatch. */
|
|
450
673
|
finalizeNeverStarted?(run: SubagentRun, reason: string): boolean | void;
|
|
451
674
|
readAgentRecord?(id: string): PersistedAgentLike | null;
|
|
675
|
+
/** Issue #546: apply a persisted record-flip marker (flip + retire). */
|
|
676
|
+
applyRecordFlip?(verdict: RecordFlipVerdict): RecordFlipOutcome;
|
|
677
|
+
/** Issue #546: the disk read the flip verdict is made on. */
|
|
678
|
+
readFreshAgentRecord?(id: string): FreshAgentRecord;
|
|
452
679
|
now?: () => Date;
|
|
453
680
|
log?: Pick<Logger, "debug" | "info" | "warn">;
|
|
454
681
|
}
|
|
@@ -472,6 +699,8 @@ export async function recoverProduction(options: ProductionRecoveryOptions): Pro
|
|
|
472
699
|
mark: options.mark,
|
|
473
700
|
finalizeNeverStarted: options.finalizeNeverStarted,
|
|
474
701
|
readAgentRecord: options.readAgentRecord,
|
|
702
|
+
applyRecordFlip: options.applyRecordFlip,
|
|
703
|
+
readFreshAgentRecord: options.readFreshAgentRecord,
|
|
475
704
|
now: options.now,
|
|
476
705
|
log: options.log,
|
|
477
706
|
});
|