brl-subagent 2.9.1 → 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 +3 -0
- 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 +16 -0
- package/src/brief.ts +228 -0
- package/src/delegate-handler.ts +39 -6
- package/src/dispatch-header.ts +230 -0
- package/src/index.ts +26 -0
- 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 +29 -0
- package/src/retry-armed.ts +383 -0
- package/src/run-registry.ts +26 -1
- package/src/session-manager.ts +410 -38
- package/src/stop-lineage.ts +280 -0
- package/src/templates.ts +97 -1
- package/src/terminal-notifier.ts +69 -3
- package/src/types.ts +94 -0
- package/src/validate.ts +57 -0
- 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/delegate-handler.ts
CHANGED
|
@@ -295,7 +295,7 @@ function warnUnknownParams(
|
|
|
295
295
|
function applyTemplate(
|
|
296
296
|
params: DelegateTaskParams,
|
|
297
297
|
templates: readonly TaskTemplate[],
|
|
298
|
-
deps: Pick<NormalizeDeps, "pi" | "log">,
|
|
298
|
+
deps: Pick<NormalizeDeps, "pi" | "log" | "ctx">,
|
|
299
299
|
): Outcome<void> {
|
|
300
300
|
const { pi, log } = deps;
|
|
301
301
|
if (!params.template) return { ok: true, value: undefined };
|
|
@@ -318,7 +318,11 @@ function applyTemplate(
|
|
|
318
318
|
};
|
|
319
319
|
}
|
|
320
320
|
|
|
321
|
-
|
|
321
|
+
// Issue #606 (§3a): the renderer needs the DISPATCH cwd, because a template
|
|
322
|
+
// with no `dispatch:` field is refused only where the project opted in.
|
|
323
|
+
const resolved = resolveTemplate(templateEntry, params.params ?? {}, {
|
|
324
|
+
cwd: templateDispatchCwd(params, deps.ctx),
|
|
325
|
+
});
|
|
322
326
|
if (!resolved.ok) {
|
|
323
327
|
return {
|
|
324
328
|
ok: false,
|
|
@@ -376,6 +380,18 @@ function applyTemplate(
|
|
|
376
380
|
return { ok: true, value: undefined };
|
|
377
381
|
}
|
|
378
382
|
|
|
383
|
+
/**
|
|
384
|
+
* The cwd a rendered dispatch will run in, as far as THIS seam can know it:
|
|
385
|
+
* the call's own `cwd` resolved against the harness cwd, else the harness cwd.
|
|
386
|
+
* The later resolver may refine it (a worktree branch, a per-step cwd), so this
|
|
387
|
+
* is the project the CONDUCTOR named — and the read is fail-open, which is what
|
|
388
|
+
* keeps a template rendering untouched in a project that never opted in.
|
|
389
|
+
*/
|
|
390
|
+
function templateDispatchCwd(params: DelegateTaskParams, ctx: ExtensionContext): string {
|
|
391
|
+
const declared = typeof params.cwd === "string" ? params.cwd : "";
|
|
392
|
+
return declared === "" ? ctx.cwd : path.resolve(ctx.cwd, declared);
|
|
393
|
+
}
|
|
394
|
+
|
|
379
395
|
/**
|
|
380
396
|
* Seam A — resolve the dispatch inputs: unknown-param warning, template
|
|
381
397
|
* resolution, retry restore (issue #430).
|
|
@@ -402,7 +418,7 @@ function normalizeInput(
|
|
|
402
418
|
// A1: the two pre-resolution notices (unknown keys, ignored task) and the
|
|
403
419
|
// template application itself.
|
|
404
420
|
warnUnknownParams(params, { pi, log });
|
|
405
|
-
const templated = applyTemplate(params, state.config.templates, { pi, log });
|
|
421
|
+
const templated = applyTemplate(params, state.config.templates, { pi, log, ctx });
|
|
406
422
|
if (!templated.ok) return templated;
|
|
407
423
|
|
|
408
424
|
// Handle retryRunId — MUST run after template resolution and before the
|
|
@@ -881,7 +897,19 @@ function routeDispatch(
|
|
|
881
897
|
if (useBackground) {
|
|
882
898
|
return {
|
|
883
899
|
kind: "returned",
|
|
884
|
-
|
|
900
|
+
// Issue #616: a background spawn reached from `delegate_task` is a
|
|
901
|
+
// CALLER-driven retry when a `retryRunId` resolved — `"manual"`, never
|
|
902
|
+
// `"transport"`. Only `scheduleTransportRetry` may claim the automatic
|
|
903
|
+
// cause, because only it IS the automatic retry.
|
|
904
|
+
result: runners.spawnBackgroundRun(
|
|
905
|
+
pi,
|
|
906
|
+
ctx,
|
|
907
|
+
params,
|
|
908
|
+
singleTask,
|
|
909
|
+
retrySourceRun,
|
|
910
|
+
undefined,
|
|
911
|
+
retrySourceRun ? "manual" : undefined,
|
|
912
|
+
),
|
|
885
913
|
};
|
|
886
914
|
}
|
|
887
915
|
|
|
@@ -1524,7 +1552,11 @@ function registerForegroundRun(
|
|
|
1524
1552
|
// Option B U1: durability identity — a retry inherits the original
|
|
1525
1553
|
// dispatchId and records resumeOf/attempt; a fresh marker keys the
|
|
1526
1554
|
// child process for boot-time orphan discovery.
|
|
1527
|
-
|
|
1555
|
+
// Issue #616: a foreground retry is always CALLER-driven (`retryRunId` or
|
|
1556
|
+
// `retryOnTimeout`), so its cause is `manual` — there is no automatic
|
|
1557
|
+
// foreground retry. Recorded for completeness; a foreground run has no agent
|
|
1558
|
+
// record, so the dispatch-scoped stop never reaches it (stated non-goal).
|
|
1559
|
+
const identity = newDispatchIdentity(retrySourceRun, retrySourceRun ? "manual" : undefined);
|
|
1528
1560
|
// Issue #511 (U2): create this run's scratch directory at record creation so
|
|
1529
1561
|
// the record can name it (the retry preamble, U3, reads `scratchDir`). The
|
|
1530
1562
|
// spawn seam in `runner.ts` re-prepares idempotently and is the gate that
|
|
@@ -1545,6 +1577,7 @@ function registerForegroundRun(
|
|
|
1545
1577
|
dispatchId: identity.dispatchId,
|
|
1546
1578
|
resumeOf: identity.resumeOf,
|
|
1547
1579
|
attempt: identity.attempt,
|
|
1580
|
+
retryCause: identity.retryCause,
|
|
1548
1581
|
owner: currentProcessOwner(),
|
|
1549
1582
|
childMarker: crypto.randomUUID(),
|
|
1550
1583
|
// U3 (D4): the session recovery posture at dispatch.
|
|
@@ -2154,7 +2187,7 @@ export function createDelegateHandler(
|
|
|
2154
2187
|
`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.`,
|
|
2155
2188
|
buildTemplateGuideline(templateSummary),
|
|
2156
2189
|
"To retry a failed subagent, pass its run ID as retryRunId. The retry restores the recorded params - including background, gitMode, approvalMode, force - with explicit values on this call winning. Multi-step runs degrade to a single task. See the retryRunId description for the full field list.",
|
|
2157
|
-
"Set retryOnTimeout: true to automatically retry a FOREGROUND subagent that times out. Only retries once — the second timeout is treated as a final failure. A background run is not retried on its deadline, but it IS retried once automatically when it dies on a transport-class error (a
|
|
2190
|
+
"Set retryOnTimeout: true to automatically retry a FOREGROUND subagent that times out. Only retries once — the second timeout is treated as a final failure. A background run is not retried on its deadline, but it IS retried once automatically when it dies on a transport-class error (a transport death at any point before the run settles, not only before it starts work), recorded as attempt 2 and announced with a warning toast — do not re-dispatch it yourself. A second transport death is NOT retried again: that settle is an ordinary failure, and its completion notice says to change the shape (run it in the conductor, override the model, or split the brief). Any other background failure needs an explicit retryRunId.",
|
|
2158
2191
|
"Background is the CONDITIONAL default for delegate_task. With background omitted, a single task or a tasks fan-out runs in the BACKGROUND when the effective approvalMode is 'auto' (call param, else config): the tool returns an agent ID immediately, and with tasks it fans out — every task starts as its own background agent, one ID per task in task order, and the conductor is woken once per agent as each finishes. It stays FOREGROUND when the effective approvalMode is 'writes' or 'always' (a background run has no approval dialog, so a gate that needs the user must keep blocking), and for chain and graph (they block by definition; an explicit background: true with chain/graph is rejected). Pass background: false for a quick probe whose answer the next step needs inline; pass background: true to force a background run where the default would block. Background runs wake the conductor with a structured completion message when they finish — do not poll: polling is only correct when completion notifications are disabled (completionNotify \"off\"); one status check as a stall check is legitimate. A background run defaults to a 30-minute deadline when no timeout is given.",
|
|
2159
2192
|
"",
|
|
2160
2193
|
"## Conductor Guardrails",
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// Purpose: The mandatory dispatch header (issue #606): split it from the task body and parse it.
|
|
2
|
+
/**
|
|
3
|
+
* The dispatch header — one definition, two consumers (issue #606, Unit 1).
|
|
4
|
+
*
|
|
5
|
+
* Every dispatch task must open with a block:
|
|
6
|
+
*
|
|
7
|
+
* dispatch: impl | review | probe | docs
|
|
8
|
+
* brief: <slug> (required when dispatch: impl)
|
|
9
|
+
* brief: none — <reason> (the stated escape; reason non-empty)
|
|
10
|
+
*
|
|
11
|
+
* Two consumers, never two parsers:
|
|
12
|
+
* - `parseDispatchHeader` — the validator's gate (src/validate.ts). It reads
|
|
13
|
+
* the leading BLOCK only, so a task that merely quotes `dispatch: impl` in
|
|
14
|
+
* its prose (inline or fenced) stays valid (T3).
|
|
15
|
+
* - `splitDispatchHeader` — the router's seam (src/params.ts keeps the header
|
|
16
|
+
* out of `classifyTask`). A header would otherwise re-route a dispatch:
|
|
17
|
+
* `dispatch: review` matches the code-reviewer rule before the body's own
|
|
18
|
+
* "write tests" ever reaches the test-engineer rule (spec §3b).
|
|
19
|
+
*
|
|
20
|
+
* BOUNDARY, stated once so CRLF/BOM/blank-separator cases have one answer:
|
|
21
|
+
* the block starts at the first non-blank line and consumes consecutive lines
|
|
22
|
+
* matching `^(dispatch|brief|jev):`, ending at the first line that does not
|
|
23
|
+
* match (a blank line ends it too). The task is `\r?\n`-split and a leading BOM
|
|
24
|
+
* is stripped before the first line is read. A title (`# Task`) before the block
|
|
25
|
+
* ends it — that is a refusal, not a tolerance, because a silent tolerance would
|
|
26
|
+
* let a quoted example at the top of a task become the declaration.
|
|
27
|
+
*
|
|
28
|
+
* The Jev line may still appear ANYWHERE (src/dispatch-line.ts scans every line
|
|
29
|
+
* and takes the first valid one), which is why `jev:` is a block-continuation
|
|
30
|
+
* line here but does not have to be inside the block.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/** The four dispatch kinds. `impl` is the gated class: it needs a brief. */
|
|
34
|
+
export const DISPATCH_KINDS = ["impl", "review", "probe", "docs"] as const;
|
|
35
|
+
export type DispatchKind = (typeof DISPATCH_KINDS)[number];
|
|
36
|
+
|
|
37
|
+
/** The kinds as one comma-separated list, quoted verbatim in every refusal. */
|
|
38
|
+
export const DISPATCH_KIND_LIST = DISPATCH_KINDS.join(", ");
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The three accepted forms, quoted VERBATIM in every refusal so the conductor
|
|
42
|
+
* never has to guess. Kept as one constant: a second copy is a second truth.
|
|
43
|
+
*/
|
|
44
|
+
export const DISPATCH_HEADER_FORMS = [
|
|
45
|
+
"dispatch: impl | review | probe | docs",
|
|
46
|
+
"brief: <slug> (required when dispatch: impl)",
|
|
47
|
+
"brief: none — <reason> (the stated escape; reason non-empty)",
|
|
48
|
+
].join("\n");
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A brief slug: one path component, lowercase alphanumeric plus interior
|
|
52
|
+
* hyphens, 1-64 characters. `none` is reserved for the escape and is therefore
|
|
53
|
+
* rejected as a slug. Separators, dots and traversal are all refused by this
|
|
54
|
+
* pattern — never join a slug that has not matched it.
|
|
55
|
+
*/
|
|
56
|
+
export const BRIEF_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
57
|
+
|
|
58
|
+
/** The reserved escape token (`brief: none — <reason>`). */
|
|
59
|
+
export const BRIEF_ESCAPE_TOKEN = "none";
|
|
60
|
+
|
|
61
|
+
/** A line that belongs to the leading block. Anchored: an indented copy does not. */
|
|
62
|
+
const BLOCK_LINE_RE = /^(dispatch|brief|jev):/;
|
|
63
|
+
|
|
64
|
+
const DISPATCH_PREFIX = "dispatch:";
|
|
65
|
+
const BRIEF_PREFIX = "brief:";
|
|
66
|
+
const EM_DASH = "—";
|
|
67
|
+
|
|
68
|
+
/** The token is reserved only when it STANDS ALONE — `none-extra` is a legal slug. */
|
|
69
|
+
const ESCAPE_PREFIX_RE = new RegExp(`^${BRIEF_ESCAPE_TOKEN}(?:\\s|$)`);
|
|
70
|
+
const ESCAPE_VALUE_RE = new RegExp(`^${BRIEF_ESCAPE_TOKEN}\\s*${EM_DASH}\\s*(.*)$`);
|
|
71
|
+
|
|
72
|
+
export interface DispatchHeaderSplit {
|
|
73
|
+
/** The consumed block, `\n`-joined (empty when the task does not open with one). */
|
|
74
|
+
header: string;
|
|
75
|
+
/** Everything after the block. */
|
|
76
|
+
body: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A brief reference: a signed brief's slug, or the stated escape and its reason. */
|
|
80
|
+
export type BriefDeclaration =
|
|
81
|
+
| { kind: "slug"; slug: string }
|
|
82
|
+
| { kind: "none"; reason: string };
|
|
83
|
+
|
|
84
|
+
export type DispatchHeaderVerdict =
|
|
85
|
+
| { ok: true; kind: DispatchKind; brief: BriefDeclaration | undefined }
|
|
86
|
+
| { ok: false; reason: string };
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Split a task into its leading dispatch block and the body that follows.
|
|
90
|
+
*
|
|
91
|
+
* Pure and total: any string maps to a pair, and `header + "\n" + body`
|
|
92
|
+
* reconstructs the task apart from the leading blank lines the block start
|
|
93
|
+
* consumes. Never throws — the validator and the router both call it on
|
|
94
|
+
* conductor-supplied text.
|
|
95
|
+
*/
|
|
96
|
+
export function splitDispatchHeader(task: string): DispatchHeaderSplit {
|
|
97
|
+
const text = String(task ?? "").replace(/^\uFEFF/, "");
|
|
98
|
+
const lines = text.split(/\r?\n/);
|
|
99
|
+
|
|
100
|
+
let start = 0;
|
|
101
|
+
while (start < lines.length && lines[start].trim() === "") start++;
|
|
102
|
+
|
|
103
|
+
let end = start;
|
|
104
|
+
while (end < lines.length && BLOCK_LINE_RE.test(lines[end])) end++;
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
header: lines.slice(start, end).join("\n"),
|
|
108
|
+
body: lines.slice(end).join("\n"),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** One refusal shape: the finding first, then the three accepted forms verbatim. */
|
|
113
|
+
function refuse(detail: string): DispatchHeaderVerdict {
|
|
114
|
+
return { ok: false, reason: `${detail} The accepted dispatch block is:\n${DISPATCH_HEADER_FORMS}` };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The block's value for one prefix (`undefined` when the line carries none). */
|
|
118
|
+
function lineValue(line: string, prefix: string): string {
|
|
119
|
+
return line.slice(prefix.length).trim();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Parse one `brief:` value into its declaration, or the reason it is not one. */
|
|
123
|
+
function parseBriefValue(value: string): BriefDeclaration | { error: string } {
|
|
124
|
+
if (value === "") {
|
|
125
|
+
return { error: "the brief line needs a value — a slug, or the stated escape." };
|
|
126
|
+
}
|
|
127
|
+
// The escape is `none — <reason>` with an EM DASH. The bare token is judged
|
|
128
|
+
// here so `brief: none` cannot slide through as a slug.
|
|
129
|
+
if (ESCAPE_PREFIX_RE.test(value)) {
|
|
130
|
+
const match = ESCAPE_VALUE_RE.exec(value);
|
|
131
|
+
if (match === null) {
|
|
132
|
+
return {
|
|
133
|
+
error: `the brief escape is \`brief: ${BRIEF_ESCAPE_TOKEN} ${EM_DASH} <reason>\` — the em dash and the reason are both required.`,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
const reason = match[1].trim();
|
|
137
|
+
if (reason === "") {
|
|
138
|
+
return { error: "the brief escape's reason is empty — say why no brief was agreed." };
|
|
139
|
+
}
|
|
140
|
+
return { kind: "none", reason };
|
|
141
|
+
}
|
|
142
|
+
if (value === BRIEF_ESCAPE_TOKEN || !BRIEF_SLUG_PATTERN.test(value)) {
|
|
143
|
+
return {
|
|
144
|
+
error:
|
|
145
|
+
`invalid brief slug "${value}": a slug matches ${BRIEF_SLUG_PATTERN.source}, ` +
|
|
146
|
+
`is a single path component (no "/", no ".", no ".."), and "${BRIEF_ESCAPE_TOKEN}" is reserved for the escape.`,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
return { kind: "slug", slug: value };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Parse the leading dispatch block. Refusals quote the three accepted forms
|
|
154
|
+
* verbatim (§3); success returns the kind and, when one was declared, the brief.
|
|
155
|
+
*
|
|
156
|
+
* A task that does NOT open with a block is refused, and the reason says which:
|
|
157
|
+
* a stray `dispatch:` line later in the text gets "the block must be the first
|
|
158
|
+
* content" (P12), because that is the mistake an author actually makes.
|
|
159
|
+
*/
|
|
160
|
+
export function parseDispatchHeader(task: string): DispatchHeaderVerdict {
|
|
161
|
+
const { header, body } = splitDispatchHeader(task);
|
|
162
|
+
const blockLines = header === "" ? [] : header.split("\n");
|
|
163
|
+
|
|
164
|
+
const dispatchLines = blockLines.filter((line) => line.startsWith(DISPATCH_PREFIX));
|
|
165
|
+
if (dispatchLines.length === 0) {
|
|
166
|
+
const strayDeclaration = body.split(/\r?\n/).some((line) => line.startsWith(DISPATCH_PREFIX));
|
|
167
|
+
return refuse(
|
|
168
|
+
strayDeclaration
|
|
169
|
+
? "missing dispatch header: the block must be the first content — the task's first non-blank line " +
|
|
170
|
+
"is not one of `dispatch:`/`brief:`/`jev:`, so a later declaration is outside the block. " +
|
|
171
|
+
"Move the block to the top of the task."
|
|
172
|
+
: "missing dispatch header: the task's first non-blank line must declare the kind.",
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
if (dispatchLines.length > 1) {
|
|
176
|
+
return refuse("more than one `dispatch:` line in the leading block — declare the kind exactly once.");
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const dispatchRest = lineValue(dispatchLines[0], DISPATCH_PREFIX);
|
|
180
|
+
if (dispatchRest === "") {
|
|
181
|
+
return refuse("the dispatch line has no kind — name exactly one.");
|
|
182
|
+
}
|
|
183
|
+
// The one-token rule: no trailing comment, no extra words. `dispatch: impl #
|
|
184
|
+
// note` is ambiguous, and an ambiguous declaration is not a declaration.
|
|
185
|
+
if (/\s/.test(dispatchRest)) {
|
|
186
|
+
return refuse(
|
|
187
|
+
`the dispatch line takes exactly one token — no trailing comment or extra words after "${dispatchRest.split(/\s+/)[0]}".`,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
if (!(DISPATCH_KINDS as readonly string[]).includes(dispatchRest)) {
|
|
191
|
+
return refuse(`unknown dispatch kind "${dispatchRest}" — must be one of: ${DISPATCH_KIND_LIST}.`);
|
|
192
|
+
}
|
|
193
|
+
const kind = dispatchRest as DispatchKind;
|
|
194
|
+
|
|
195
|
+
const briefLines = blockLines.filter((line) => line.startsWith(BRIEF_PREFIX));
|
|
196
|
+
if (briefLines.length > 1) {
|
|
197
|
+
return refuse("more than one `brief:` line in the leading block — declare the brief exactly once.");
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
let brief: BriefDeclaration | undefined;
|
|
201
|
+
if (briefLines.length === 1) {
|
|
202
|
+
const parsed = parseBriefValue(lineValue(briefLines[0], BRIEF_PREFIX));
|
|
203
|
+
if ("error" in parsed) return refuse(parsed.error);
|
|
204
|
+
brief = parsed;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (kind === "impl" && brief === undefined) {
|
|
208
|
+
return refuse(
|
|
209
|
+
"`dispatch: impl` requires a brief — add `brief: <slug>` (the file is briefs/<slug>.md) " +
|
|
210
|
+
`or \`brief: ${BRIEF_ESCAPE_TOKEN} ${EM_DASH} <reason>\` for the stated escape.`,
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return { ok: true, kind, brief };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* The frontmatter `dispatch:` field's problem, or `undefined` when it is absent
|
|
219
|
+
* or one of the four kinds. Shared by the template's load-time validation and
|
|
220
|
+
* its render-time check: an unknown or misspelled value must be an error naming
|
|
221
|
+
* the field and the allowed set, never a silently ignored key (spec §3a).
|
|
222
|
+
*/
|
|
223
|
+
export function dispatchFieldProblem(value: unknown): string | undefined {
|
|
224
|
+
if (value === undefined) return undefined;
|
|
225
|
+
if (typeof value !== "string" || !(DISPATCH_KINDS as readonly string[]).includes(value)) {
|
|
226
|
+
const shown = typeof value === "string" ? `"${value}"` : JSON.stringify(value);
|
|
227
|
+
return `invalid "dispatch" value ${shown} — must be one of: ${DISPATCH_KIND_LIST}.`;
|
|
228
|
+
}
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -42,6 +42,7 @@ import { loadBuiltinPresets, loadCustomPresets, getAllPresets, writePresetFile }
|
|
|
42
42
|
import { cleanupTempDirs, reapActiveChildren } from "./runner";
|
|
43
43
|
import { clearProgressLinger, repaintStatus, stopProgressTicker } from "./concurrency";
|
|
44
44
|
import { setLogCwd } from "./logging";
|
|
45
|
+
import { createGuardStartNotice } from "./background-guard";
|
|
45
46
|
import { createTerminalNotifier } from "./terminal-notifier";
|
|
46
47
|
|
|
47
48
|
// ---------------------------------------------------------------------------
|
|
@@ -162,6 +163,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
162
163
|
resetRecoveryNotice,
|
|
163
164
|
} = createBootRecovery(rt);
|
|
164
165
|
|
|
166
|
+
// Issue #620 (Q14): the cheap half of "required". A project that names a
|
|
167
|
+
// background guard must hear about a guard that never loaded — the silence is
|
|
168
|
+
// what let #620 hide — but exactly once per process, and not at all when the
|
|
169
|
+
// project did not opt in. The latch is per invocation (D5), like every other
|
|
170
|
+
// once-per-boot flag here.
|
|
171
|
+
const guardStartNotice = createGuardStartNotice();
|
|
172
|
+
|
|
165
173
|
// -------------------------------------------------------------------
|
|
166
174
|
// Config change callback
|
|
167
175
|
// -------------------------------------------------------------------
|
|
@@ -239,6 +247,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
239
247
|
// Issue #179 (D6): createLogger ran at module load with no cwd — point
|
|
240
248
|
// the shared file sink at this session's cwd now that it exists.
|
|
241
249
|
setLogCwd(ctx.cwd);
|
|
250
|
+
// Issue #620 (Q14): one warning per process when this project names a
|
|
251
|
+
// background guard that is not loaded. Silent for an absent key and for
|
|
252
|
+
// "none" — a project that did not opt in never sees our machinery.
|
|
253
|
+
{
|
|
254
|
+
const warning = guardStartNotice(ctx.cwd);
|
|
255
|
+
if (warning !== null) log.warn(warning);
|
|
256
|
+
}
|
|
242
257
|
// Load built-in presets
|
|
243
258
|
const presetsDir = pkgPath("presets");
|
|
244
259
|
state.builtinPresets = loadBuiltinPresets(presetsDir, log);
|
|
@@ -287,6 +302,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
287
302
|
// records interrupted BEFORE anything else touches their worktrees.
|
|
288
303
|
await performBootRecovery();
|
|
289
304
|
|
|
305
|
+
// Issue #616 / review 624 (B1): reclaim the armed-retry markers a conductor
|
|
306
|
+
// left behind when it died between an arm write and the retry's spawn. No
|
|
307
|
+
// run-shaped reader enumerates `armed/` (that is what keeps an intent from
|
|
308
|
+
// rendering as a run row), so nothing else would ever notice them, and a
|
|
309
|
+
// stale marker makes every later stop of its dispatch cancel a phantom.
|
|
310
|
+
{
|
|
311
|
+
const { sweepStaleArmedRetries } = await import("./retry-armed");
|
|
312
|
+
const swept = sweepStaleArmedRetries();
|
|
313
|
+
if (swept.reclaimed > 0) log.info("Reclaimed stale armed-retry markers", swept);
|
|
314
|
+
}
|
|
315
|
+
|
|
290
316
|
// Issue #466 (ADR 0026 D2/D5): reconcile the durable head-state records —
|
|
291
317
|
// the ONE step allowed to move git at boot, and only for a record whose
|
|
292
318
|
// owner it has proved dead.
|
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
|
|