brl-subagent 2.9.0 → 2.9.2
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 +19 -1
- package/README.md +11 -5
- package/package.json +7 -6
- package/src/agent-tools.ts +178 -19
- package/src/atomic-write.ts +101 -0
- package/src/background-guard.ts +295 -0
- package/src/background-pipeline.ts +19 -1
- package/src/boot-recovery.ts +66 -3
- package/src/brief.ts +228 -0
- package/src/delegate-handler.ts +41 -8
- package/src/dispatch-header.ts +230 -0
- package/src/index.ts +26 -0
- package/src/logging.ts +66 -3
- package/src/notify-completion.ts +81 -12
- package/src/params.ts +9 -1
- package/src/project-flags.ts +39 -2
- package/src/recovery-engine.ts +16 -2
- package/src/recovery.ts +265 -7
- package/src/retry-armed.ts +383 -0
- package/src/run-registry.ts +157 -8
- package/src/schema.ts +4 -2
- package/src/session-manager.ts +913 -103
- package/src/stop-lineage.ts +280 -0
- package/src/templates.ts +97 -1
- package/src/terminal-notifier.ts +69 -3
- package/src/tui.ts +4 -4
- package/src/types.ts +94 -0
- package/src/validate.ts +83 -6
- package/templates/analyze-data.md +1 -0
- package/templates/code-review.md +1 -0
- package/templates/debug-issue.md +1 -0
- package/templates/implement-feature.md +1 -0
- package/templates/prototype.md +1 -0
- package/templates/refactor.md +1 -0
- package/templates/security-audit.md +1 -0
- package/templates/write-docs.md +1 -0
- package/templates/write-tests.md +1 -0
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/notify-completion.ts
CHANGED
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
type AgentStatus,
|
|
31
31
|
} from "./types";
|
|
32
32
|
import { resolveTerminalRunEntry } from "./state";
|
|
33
|
+
import { isTransportFailure } from "./transport-retry";
|
|
33
34
|
|
|
34
35
|
/** Terminal statuses the completion message can carry. */
|
|
35
36
|
export type CompletionStatus = "completed" | "failed" | "stopped";
|
|
@@ -246,6 +247,30 @@ export function buildCompletionMessage(
|
|
|
246
247
|
return { customType: "subagent-completion", content, display: true, details };
|
|
247
248
|
}
|
|
248
249
|
|
|
250
|
+
/**
|
|
251
|
+
* Insert a paragraph into a completion message as its own part and BEFORE the
|
|
252
|
+
* closing directive. The ONE insert rule for every paragraph a settle adds
|
|
253
|
+
* (issue #556 made it shared: the worktree-state block and the repeat-transport
|
|
254
|
+
* advisory land the same way).
|
|
255
|
+
*
|
|
256
|
+
* The directive is matched at the END (`endsWith`), never as the first
|
|
257
|
+
* occurrence: an agent's own tail can quote the directive text, and splitting
|
|
258
|
+
* there would drop everything after the quote. A shape that does not end with
|
|
259
|
+
* the directive keeps the paragraph by appending it — a missing report is the
|
|
260
|
+
* one outcome this function must not produce.
|
|
261
|
+
*/
|
|
262
|
+
export function appendCompletionParagraph(
|
|
263
|
+
message: CompletionMessagePayload,
|
|
264
|
+
paragraph: string,
|
|
265
|
+
): CompletionMessagePayload {
|
|
266
|
+
if (!paragraph) return message;
|
|
267
|
+
const suffix = `\n\n${COMPLETION_DIRECTIVE}`;
|
|
268
|
+
const content = message.content.endsWith(suffix)
|
|
269
|
+
? `${message.content.slice(0, -suffix.length)}\n\n${paragraph}${suffix}`
|
|
270
|
+
: `${message.content}\n\n${paragraph}`;
|
|
271
|
+
return { ...message, content };
|
|
272
|
+
}
|
|
273
|
+
|
|
249
274
|
/**
|
|
250
275
|
* Issue #474: insert the worktree-state block into a settled-failure wake, as
|
|
251
276
|
* its own part and BEFORE the closing directive.
|
|
@@ -254,23 +279,12 @@ export function buildCompletionMessage(
|
|
|
254
279
|
* contract is "no side effects", and the probe is a subprocess. The caller
|
|
255
280
|
* renders the block (`describeWorktreeState`) and gates on the CLASSIFIED
|
|
256
281
|
* status.
|
|
257
|
-
*
|
|
258
|
-
* The directive is matched at the END (`endsWith`), never as the first
|
|
259
|
-
* occurrence: an agent's own tail can quote the directive text, and splitting
|
|
260
|
-
* there would drop everything after the quote. A shape that does not end with
|
|
261
|
-
* the directive keeps the block by appending it — a missing report is the one
|
|
262
|
-
* outcome this function must not produce.
|
|
263
282
|
*/
|
|
264
283
|
export function withWorktreeState(
|
|
265
284
|
message: CompletionMessagePayload,
|
|
266
285
|
worktreeState: string,
|
|
267
286
|
): CompletionMessagePayload {
|
|
268
|
-
|
|
269
|
-
const suffix = `\n\n${COMPLETION_DIRECTIVE}`;
|
|
270
|
-
const content = message.content.endsWith(suffix)
|
|
271
|
-
? `${message.content.slice(0, -suffix.length)}\n\n${worktreeState}${suffix}`
|
|
272
|
-
: `${message.content}\n\n${worktreeState}`;
|
|
273
|
-
return { ...message, content };
|
|
287
|
+
return appendCompletionParagraph(message, worktreeState);
|
|
274
288
|
}
|
|
275
289
|
|
|
276
290
|
/**
|
|
@@ -395,6 +409,61 @@ export function buildMonitoringDegradedAdvisory(
|
|
|
395
409
|
);
|
|
396
410
|
}
|
|
397
411
|
|
|
412
|
+
// ---------------------------------------------------------------------------
|
|
413
|
+
// Repeat transport death advisory (issue #556)
|
|
414
|
+
//
|
|
415
|
+
// The rule that should change the conductor's behaviour after a SECOND transport
|
|
416
|
+
// death on the same label — "two transport deaths on one label: change the
|
|
417
|
+
// shape" (`references/autonomous-run.md`) — lived only in prose the conductor
|
|
418
|
+
// had to remember. The completion notice is the moment it matters, so the notice
|
|
419
|
+
// carries it — but ONLY when the lineage is PROVEN from the durable records:
|
|
420
|
+
// this attempt is a transport failure, it is at least the second, and the record
|
|
421
|
+
// it resumed (`resumeOf`) is a transport failure too. A builder that inferred a
|
|
422
|
+
// lineage it cannot read would tell a conductor to abandon a run that died for
|
|
423
|
+
// an unrelated reason, which is worse than saying nothing.
|
|
424
|
+
// ---------------------------------------------------------------------------
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* PURE builder — no pi SDK, no side effects, never throws. Returns `""` for
|
|
428
|
+
* every unproven case (first attempt, non-transport failure, missing or
|
|
429
|
+
* non-transport source record), so a caller can append it unconditionally and a
|
|
430
|
+
* source record it cannot resolve costs nothing.
|
|
431
|
+
*
|
|
432
|
+
* The attempt numbers named in the prose are the SOURCE's recorded `attempt`
|
|
433
|
+
* and this attempt — never a hard-coded "attempt 1". The guard proves exactly
|
|
434
|
+
* two transport deaths: this attempt, and the record it resumed (`resumeOf`).
|
|
435
|
+
* Naming the source attempt is what keeps the sentence true when a manual
|
|
436
|
+
* `retryRunId` mints attempt 3 whose `resumeOf` points at attempt 2 (attempt 1
|
|
437
|
+
* may have failed for an unrelated reason). `source.attempt` is optional on a
|
|
438
|
+
* record, so the fallback is `attempt - 1` — the ordinary auto-retry lineage,
|
|
439
|
+
* which reproduces the same numbers as the source whenever the source carries
|
|
440
|
+
* one.
|
|
441
|
+
*
|
|
442
|
+
* `label` is omitted from the prose when absent, exactly as in the monitoring
|
|
443
|
+
* advisory above.
|
|
444
|
+
*/
|
|
445
|
+
export function buildRepeatTransportAdvisory(
|
|
446
|
+
run: Pick<
|
|
447
|
+
SubagentRun,
|
|
448
|
+
"attempt" | "status" | "errorCategory" | "errorMessage" | "originalParams" | "resumeOf"
|
|
449
|
+
>,
|
|
450
|
+
source:
|
|
451
|
+
| Pick<SubagentRun, "attempt" | "status" | "errorCategory" | "errorMessage" | "originalParams">
|
|
452
|
+
| undefined,
|
|
453
|
+
label?: string,
|
|
454
|
+
): string {
|
|
455
|
+
if (!isTransportFailure(run)) return "";
|
|
456
|
+
const attempt = run.attempt ?? 1;
|
|
457
|
+
if (attempt < 2) return "";
|
|
458
|
+
if (!source || !isTransportFailure(source)) return "";
|
|
459
|
+
const sourceAttempt = source.attempt ?? attempt - 1;
|
|
460
|
+
const name = label ? ` on "${label}"` : "";
|
|
461
|
+
return (
|
|
462
|
+
`Two transport deaths${name}: attempts ${sourceAttempt} and ${attempt} both died on a transport failure and this dispatch is not retried again. ` +
|
|
463
|
+
"Change the shape — run it in the conductor, override the model, or split the brief — per `references/autonomous-run.md`."
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
|
|
398
467
|
/**
|
|
399
468
|
* Emit the advisory on both channels, each in its own try: a throwing
|
|
400
469
|
* `sendMessage` must not swallow the footer line, and a missing UI must not
|
package/src/params.ts
CHANGED
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
} from "./types";
|
|
31
31
|
import { getAllPresets, getPreset } from "./presets";
|
|
32
32
|
import { classifyTask } from "./router";
|
|
33
|
+
import { splitDispatchHeader } from "./dispatch-header";
|
|
33
34
|
import { normalizeTimeout } from "./validate";
|
|
34
35
|
|
|
35
36
|
// ---------------------------------------------------------------------------
|
|
@@ -495,7 +496,14 @@ export function resolveDispatchPreset(
|
|
|
495
496
|
params.noBuiltinTools !== undefined;
|
|
496
497
|
if (params.template || hasExplicitToolPreference) return { autoRouted: false };
|
|
497
498
|
const matched = classifyTask(
|
|
498
|
-
|
|
499
|
+
// Issue #606 (§3b): classify the BODY, never the header. `classifyTask`
|
|
500
|
+
// matches keywords over the whole string, first rule wins, so a mandatory
|
|
501
|
+
// `dispatch: review` line would re-route a task whose body said "write
|
|
502
|
+
// tests" — a dispatch line must not be a routing decision. The header is
|
|
503
|
+
// stripped here (the caller), not in the classifier: the classifier's
|
|
504
|
+
// contract is "classify the text you are given", and T10/P9 pin both
|
|
505
|
+
// halves — the body-only preset, and that the whole task would differ.
|
|
506
|
+
splitDispatchHeader(params.task ?? "").body,
|
|
499
507
|
getAllPresets(state.builtinPresets, state.customPresets),
|
|
500
508
|
);
|
|
501
509
|
if (!matched) return { autoRouted: false };
|
package/src/project-flags.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Purpose: The single reader for the project-local `brl-subagent` umbrella flags (issue #415).
|
|
2
2
|
/**
|
|
3
|
-
* The umbrella project-local
|
|
3
|
+
* The umbrella project-local flags: `{"brl-subagent": {"processChecks": true}}` and
|
|
4
|
+
* `{"brl-subagent": {"backgroundGuard": "worktree-guard"}}`.
|
|
4
5
|
*
|
|
5
6
|
* `processChecks` gates OUR process mechanisms — the Jev dispatch-line check
|
|
6
7
|
* (#407/#412), rule 2's durable-shape auto-switch (#412), and the
|
|
@@ -21,6 +22,12 @@
|
|
|
21
22
|
* The manifest read is the project's OWN `package.json` — tracked, so it exists
|
|
22
23
|
* in every worktree (worktrees share the repo's manifest), unlike a gitignored
|
|
23
24
|
* marker under `.pi/`.
|
|
25
|
+
*
|
|
26
|
+
* `backgroundGuard` (#620, ADR 0029) joined the same section and therefore the
|
|
27
|
+
* same reader: a second manifest reader is exactly what the ratchet below
|
|
28
|
+
* forbids, and the guard opt-in belongs beside the process checks it completes.
|
|
29
|
+
* It is a NAME, not a path — resolution and containment live in
|
|
30
|
+
* `background-guard.ts`, so the manifest can never carry a traversable path.
|
|
24
31
|
*/
|
|
25
32
|
|
|
26
33
|
import { readFileSync } from "node:fs";
|
|
@@ -31,7 +38,7 @@ import { join } from "node:path";
|
|
|
31
38
|
* A third field is a new mechanism, and a new mechanism needs its own ADR and
|
|
32
39
|
* its own line in this whitelist (the ratchet enforces both directions).
|
|
33
40
|
*/
|
|
34
|
-
export const PROCESS_CHECK_KEYS = ["processChecks"] as const;
|
|
41
|
+
export const PROCESS_CHECK_KEYS = ["processChecks", "backgroundGuard"] as const;
|
|
35
42
|
|
|
36
43
|
/**
|
|
37
44
|
* Whether the project at `cwd` opted into our process checks. Fail-open in
|
|
@@ -50,6 +57,36 @@ export function readProcessChecks(cwd: string | undefined): boolean {
|
|
|
50
57
|
}
|
|
51
58
|
}
|
|
52
59
|
|
|
60
|
+
/**
|
|
61
|
+
* The NAME of the guard this project requires a background delegation to carry
|
|
62
|
+
* (#620), or `null` when the project names none. The string is trimmed and is
|
|
63
|
+
* returned verbatim — including the sentinel `"none"`, which the caller folds
|
|
64
|
+
* to "off" — because the sentinel's meaning is the resolver's, not the
|
|
65
|
+
* reader's (one reader, one job).
|
|
66
|
+
*
|
|
67
|
+
* Fail-open like `readProcessChecks`: no cwd, no manifest, unreadable manifest,
|
|
68
|
+
* malformed JSON, a non-object section, or a non-string/blank field all read as
|
|
69
|
+
* `null` — a project's packaging mistake must never reject a dispatch.
|
|
70
|
+
*
|
|
71
|
+
* A name is NOT a path: `background-guard.ts` validates it as one component and
|
|
72
|
+
* resolves it under the project root, so this reader has no traversal surface
|
|
73
|
+
* to get wrong.
|
|
74
|
+
*/
|
|
75
|
+
export function readBackgroundGuard(cwd: string | undefined): string | null {
|
|
76
|
+
if (cwd === undefined || cwd === "") return null;
|
|
77
|
+
try {
|
|
78
|
+
const manifest = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8")) as {
|
|
79
|
+
"brl-subagent"?: { backgroundGuard?: unknown };
|
|
80
|
+
};
|
|
81
|
+
const named = manifest?.["brl-subagent"]?.backgroundGuard;
|
|
82
|
+
if (typeof named !== "string") return null;
|
|
83
|
+
const trimmed = named.trim();
|
|
84
|
+
return trimmed === "" ? null : trimmed;
|
|
85
|
+
} catch {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
53
90
|
/**
|
|
54
91
|
* The validation seam's name for the same read (`validatePreTask` asks "is the
|
|
55
92
|
* check enabled for this project?"). One implementation: this is an alias, not
|
package/src/recovery-engine.ts
CHANGED
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
26
|
import type { Logger } from "./logging";
|
|
27
|
-
import type { ProcessOwner, SubagentRun } from "./types";
|
|
27
|
+
import type { ProcessOwner, RetryCause, SubagentRun } from "./types";
|
|
28
28
|
import { resolveTerminalRunEntry } from "./state";
|
|
29
29
|
import { escalateKill, processTarget, type SignalGuard, type SignalPhase } from "./kill-escalation";
|
|
30
30
|
|
|
@@ -150,16 +150,30 @@ export interface RecoveryOutcome {
|
|
|
150
150
|
* original's dispatchId and records `resumeOf`/`attempt`; a fresh dispatch
|
|
151
151
|
* mints a new dispatchId with attempt 1. These are RECORD fields, not
|
|
152
152
|
* delegate_task params (D4).
|
|
153
|
+
*
|
|
154
|
+
* Issue #616: `retryCause` states WHY the attempt exists, and only the MINT SITE
|
|
155
|
+
* knows it — the automatic transport retry passes `"transport"`, a
|
|
156
|
+
* caller-driven `retryRunId` retry passes `"manual"`. It is deliberately NOT
|
|
157
|
+
* derived here (from the source's failure class, say): a manual retry of a
|
|
158
|
+
* transport-failed attempt would then be indistinguishable from the automatic
|
|
159
|
+
* one, which is exactly the over-stop the narrowing exists to prevent. A fresh
|
|
160
|
+
* dispatch carries no cause at all (absent ⇒ unknown ⇒ never auto-stopped).
|
|
153
161
|
*/
|
|
154
|
-
export function newDispatchIdentity(
|
|
162
|
+
export function newDispatchIdentity(
|
|
163
|
+
source: SubagentRun | undefined,
|
|
164
|
+
retryCause?: RetryCause,
|
|
165
|
+
): {
|
|
155
166
|
dispatchId: string;
|
|
156
167
|
resumeOf?: string;
|
|
157
168
|
attempt: number;
|
|
169
|
+
retryCause?: RetryCause;
|
|
158
170
|
} {
|
|
159
171
|
return {
|
|
160
172
|
dispatchId: source?.dispatchId ?? crypto.randomUUID(),
|
|
161
173
|
resumeOf: source?.id,
|
|
162
174
|
attempt: source ? (source.attempt ?? 1) + 1 : 1,
|
|
175
|
+
// A cause without a source would describe a retry that has no origin.
|
|
176
|
+
...(source && retryCause ? { retryCause } : {}),
|
|
163
177
|
};
|
|
164
178
|
}
|
|
165
179
|
|