brl-subagent 2.9.1 → 2.9.3

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.
Files changed (46) hide show
  1. package/AGENT.md +3 -0
  2. package/CHANGELOG.md +366 -0
  3. package/README.md +11 -5
  4. package/package.json +14 -11
  5. package/src/agent-tools.ts +178 -19
  6. package/src/atomic-write.ts +101 -0
  7. package/src/background-guard.ts +295 -0
  8. package/src/background-pipeline.ts +21 -5
  9. package/src/boot-recovery.ts +16 -0
  10. package/src/brief.ts +228 -0
  11. package/src/delegate-handler.ts +51 -12
  12. package/src/dispatch-header.ts +226 -0
  13. package/src/history.ts +0 -6
  14. package/src/index.ts +27 -5
  15. package/src/kill-escalation.ts +32 -9
  16. package/src/mode-prologue.ts +3 -11
  17. package/src/mode-runners.ts +0 -3
  18. package/src/notify-completion.ts +81 -12
  19. package/src/params.ts +10 -2
  20. package/src/prelude.ts +1 -9
  21. package/src/proc.ts +73 -15
  22. package/src/project-flags.ts +42 -6
  23. package/src/recovery-engine.ts +16 -2
  24. package/src/recovery.ts +29 -0
  25. package/src/retry-armed.ts +383 -0
  26. package/src/run-registry.ts +121 -1
  27. package/src/runner.ts +308 -10
  28. package/src/schema.ts +0 -11
  29. package/src/session-manager.ts +490 -54
  30. package/src/state.ts +16 -1
  31. package/src/stop-lineage.ts +280 -0
  32. package/src/templates.ts +97 -1
  33. package/src/terminal-notifier.ts +70 -4
  34. package/src/types.ts +110 -0
  35. package/src/unit-run.ts +7 -2
  36. package/src/validate.ts +47 -86
  37. package/templates/analyze-data.md +1 -0
  38. package/templates/code-review.md +1 -0
  39. package/templates/debug-issue.md +1 -0
  40. package/templates/implement-feature.md +1 -0
  41. package/templates/prototype.md +1 -0
  42. package/templates/refactor.md +1 -0
  43. package/templates/security-audit.md +1 -0
  44. package/templates/write-docs.md +1 -0
  45. package/templates/write-tests.md +1 -0
  46. package/src/dispatch-line.ts +0 -144
package/src/state.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  CIRCUIT_DEGRADED_THINKING,
30
30
  type SubagentState,
31
31
  type SubagentRun,
32
+ type SubagentUsageGroup,
32
33
  type LiveSubagent,
33
34
  type ThinkingLevel,
34
35
  type ApprovalMode,
@@ -39,7 +40,7 @@ import {
39
40
  type ModeContext,
40
41
  } from "./types";
41
42
  import { cleanupRuns } from "./history";
42
- import { persistRunRecord, type InflightRunKind } from "./run-registry";
43
+ import { persistRunRecord, persistSettledRunRecord, type InflightRunKind } from "./run-registry";
43
44
 
44
45
  // ---------------------------------------------------------------------------
45
46
  // Live-monitor staleness sweep (issue #52 part 2)
@@ -334,6 +335,20 @@ export class SessionState {
334
335
  persistRunRecord(pi, run, kind);
335
336
  }
336
337
 
338
+ /**
339
+ * Issue #648 (Q6): the TERMINAL subagent write. `usageGroups` is REQUIRED —
340
+ * the run's spend rides on the same choke point as its record, so a future
341
+ * settle site that forgets to pass it is a type error, not a silent
342
+ * undercount in the footer. Aggregate/structural writes keep `persistRun`.
343
+ */
344
+ persistSettledRun(
345
+ pi: ExtensionAPI,
346
+ run: SubagentRun,
347
+ usageGroups: readonly SubagentUsageGroup[],
348
+ ): void {
349
+ persistSettledRunRecord(pi, run, usageGroups);
350
+ }
351
+
337
352
  // -------------------------------------------------------------------
338
353
  // F5/F9: Safe state restoration from session entries
339
354
  // -------------------------------------------------------------------
@@ -0,0 +1,280 @@
1
+ // Purpose: The dispatch-scoped stop plan and its report lines for `stop_subagent` (issue #616).
2
+ /**
3
+ * Issue #616 — `stop_subagent`'s dispatch contract, as data.
4
+ *
5
+ * The defect the report fixes was a MESSAGE defect with a scope bug underneath:
6
+ * `stop_subagent` stopped one id and printed "Stopped" for anything it found,
7
+ * including an already-terminal attempt 1 whose transport auto-retry was live
8
+ * under the same label (and, nine seconds before a manual kill, writing a
9
+ * merge-gating review record).
10
+ *
11
+ * The contract this module plans and reports:
12
+ *
13
+ * - the stop is DISPATCH-scoped: the requested id plus every attempt of the
14
+ * same `dispatchId` whose `retryCause` is `"transport"`. A manual retry is
15
+ * never stopped by a stop aimed at another attempt (it is named, not
16
+ * touched) — `retryCause` is a SCOPE FILTER, not an immunity: naming the
17
+ * manual retry's own id stops it;
18
+ * - an attempt whose cause is ABSENT is unknown, and unknown is never stopped
19
+ * by scope — it is disclosed;
20
+ * - an armed retry (see `retry-armed.ts`) is a pending intent, never silently
21
+ * "nothing running";
22
+ * - a TRUNCATED scan (7-day window / 200-record cap) may not carry a universal
23
+ * claim either.
24
+ *
25
+ * Everything here is PURE: no filesystem, no session mutation. The tool loops
26
+ * the live attempts and collects outcomes; this module decides what is in scope
27
+ * and what the sentences say. `src/__tests__/stop-subagent-lineage.test.ts` pins
28
+ * every line.
29
+ */
30
+
31
+ import type { ArmedRetry, CancelOutcome } from './retry-armed';
32
+ import type { RetryLineage, RetryRecordIdentity } from './session-manager';
33
+ import { isTerminalAgentStatusValue, type AgentStatus, type RetryCause } from './types';
34
+
35
+ /**
36
+ * Statuses that count as LIVE. F11: `AgentStatus` also carries `pending` and
37
+ * `steered`, which nothing writes today — they are included so a future writer
38
+ * cannot silently fall outside the stop's scope.
39
+ */
40
+ export const STOP_LIVE_STATUSES: ReadonlySet<AgentStatus> = new Set<AgentStatus>([
41
+ 'pending',
42
+ 'running',
43
+ 'steered',
44
+ ]);
45
+
46
+ export function isLiveStatus(status: AgentStatus): boolean {
47
+ return STOP_LIVE_STATUSES.has(status);
48
+ }
49
+
50
+ /** The dispatch-scoped answer: what to stop, what to leave, what to disclose. */
51
+ export interface StopPlan {
52
+ /** The requested (resolved) id. */
53
+ targetId: string;
54
+ /** The requested id's own record, when one exists. */
55
+ target: RetryRecordIdentity | null;
56
+ /** The dispatch key named by the report's universal line. */
57
+ dispatchId: string;
58
+ /** In-scope, live attempts AFTER the requested id — ordered attempt, start. */
59
+ live: RetryRecordIdentity[];
60
+ /** Live manual retries: named as residue, never stopped by scope. */
61
+ outOfScopeLive: RetryRecordIdentity[];
62
+ /** Live attempts whose cause could not be established: named, never stopped. */
63
+ unknownCauseLive: RetryRecordIdentity[];
64
+ /** Every known attempt that is already terminal (nothing to do for them). */
65
+ terminalFamily: RetryRecordIdentity[];
66
+ /** Armed retries found for any family member. */
67
+ armed: ArmedRetry[];
68
+ /** The store scan hit its record cap. */
69
+ capped: boolean;
70
+ /** The scan window, in whole days (the disclosure's number). */
71
+ windowDays: number;
72
+ /** The requested record predates the scan window. */
73
+ targetOutsideWindow: boolean;
74
+ }
75
+
76
+ /**
77
+ * Turn a lineage answer into a stop plan.
78
+ *
79
+ * SCOPE, stated once: the requested id is ALWAYS in scope (the caller named it,
80
+ * and that is how a manual retry is stopped after all); every OTHER attempt is in
81
+ * scope only when the record says `retryCause === "transport"`. Absent is
82
+ * unknown and unknown is never in scope — the discriminator exists precisely
83
+ * because a manual retry of a transport-failed attempt is indistinguishable from
84
+ * the automatic one by shape alone (issue #616 F6/F15).
85
+ */
86
+ export function planDispatchStop(input: {
87
+ targetId: string;
88
+ lineage: RetryLineage;
89
+ armed: ArmedRetry[];
90
+ nowMs: number;
91
+ }): StopPlan {
92
+ const { targetId, lineage, armed, nowMs } = input;
93
+ const target = lineage.found;
94
+ const dispatchId =
95
+ lineage.family.find((record) => record.dispatchId !== undefined)?.dispatchId ?? targetId;
96
+
97
+ const live: RetryRecordIdentity[] = [];
98
+ const outOfScopeLive: RetryRecordIdentity[] = [];
99
+ const unknownCauseLive: RetryRecordIdentity[] = [];
100
+ const terminalFamily: RetryRecordIdentity[] = [];
101
+
102
+ for (const record of lineage.family) {
103
+ if (!isLiveStatus(record.status)) {
104
+ terminalFamily.push(record);
105
+ continue;
106
+ }
107
+ if (record.id === targetId || record.retryCause === 'transport') {
108
+ live.push(record);
109
+ } else if (record.retryCause === 'manual') {
110
+ outOfScopeLive.push(record);
111
+ } else {
112
+ unknownCauseLive.push(record);
113
+ }
114
+ }
115
+
116
+ // `lineage.family` is already ordered by attempt, then start, then id — the
117
+ // stop order the contract asks for. Sorted again here so this module does not
118
+ // depend on the reader's ordering choice.
119
+ const byAttempt = (a: RetryRecordIdentity, b: RetryRecordIdentity): number =>
120
+ a.attempt - b.attempt || a.startedAt - b.startedAt || a.id.localeCompare(b.id);
121
+ live.sort(byAttempt);
122
+ outOfScopeLive.sort(byAttempt);
123
+ unknownCauseLive.sort(byAttempt);
124
+
125
+ return {
126
+ targetId,
127
+ target,
128
+ dispatchId,
129
+ live,
130
+ outOfScopeLive,
131
+ unknownCauseLive,
132
+ terminalFamily,
133
+ armed,
134
+ capped: lineage.bounds.capped,
135
+ windowDays: lineage.bounds.windowDays,
136
+ targetOutsideWindow:
137
+ target !== null && target.startedAt < nowMs - lineage.bounds.windowDays * 24 * 60 * 60 * 1000,
138
+ };
139
+ }
140
+
141
+ // ---------------------------------------------------------------------------
142
+ // The sentences
143
+ // ---------------------------------------------------------------------------
144
+
145
+ /** The cause token every line carries. Absent is UNKNOWN — never `transport`. */
146
+ export function causeLabel(cause: RetryCause | undefined): string {
147
+ if (cause === 'transport') return 'cause transport';
148
+ if (cause === 'manual') return 'cause manual';
149
+ return 'cause unknown';
150
+ }
151
+
152
+ /** One attempt's identity, as every line names it. */
153
+ export function describeAttempt(
154
+ id: string,
155
+ attempt: number,
156
+ cause: RetryCause | undefined,
157
+ ): string {
158
+ return `${id} (attempt ${attempt}, ${causeLabel(cause)})`;
159
+ }
160
+
161
+ /** A stop attempt and what the STORE says afterwards (not what the primitive returned). */
162
+ export interface StoppedAttempt {
163
+ record: RetryRecordIdentity;
164
+ description?: string;
165
+ /** The terminal status read back from the store, or `null` when none could be read. */
166
+ verifiedStatus: AgentStatus | null;
167
+ /** Why no terminal status could be proven (a human-readable state, e.g. "no record"). */
168
+ unverifiedState?: string;
169
+ }
170
+
171
+ export interface StopReportInput {
172
+ plan: StopPlan;
173
+ stopped: StoppedAttempt[];
174
+ /** One entry per marker in `plan.armed`, in the same order. */
175
+ cancels: Array<{ armed: ArmedRetry; outcome: CancelOutcome }>;
176
+ }
177
+
178
+ export interface StopReport {
179
+ text: string;
180
+ isError: boolean;
181
+ }
182
+
183
+ /**
184
+ * Assemble the report. The rules, each pinned by a test:
185
+ *
186
+ * - the word "Stopped" describes an attempt ONLY when the re-read record says
187
+ * it is terminal — the primitive's return value is not evidence;
188
+ * - an in-scope live attempt that does not reach a terminal status is an ERROR
189
+ * (the postcondition "nothing in scope is running" was not met);
190
+ * - a live attempt left alone BY SCOPE (manual) or BY UNKNOWNNESS is a residue
191
+ * line and NOT an error — the scoped stop itself succeeded;
192
+ * - no universal claim when a retry is armed, a cause is unknown, a live
193
+ * out-of-scope attempt remains, or the scan was truncated; each of those gets
194
+ * its own disclosure line instead.
195
+ */
196
+ export function formatStopReport(input: StopReportInput): StopReport {
197
+ const { plan, stopped, cancels } = input;
198
+ const lines: string[] = [];
199
+ let isError = false;
200
+
201
+ for (const cancel of cancels) {
202
+ const attempt = describeAttempt(cancel.armed.parentId, cancel.armed.attempt, 'transport');
203
+ if (cancel.outcome === 'cancelled') {
204
+ // NOT a universal claim: the cancel is an intent the spawn consumes.
205
+ lines.push(
206
+ `Cancelled transport retry for ${attempt} before it prompted — the dispatch is not claimed quiescent until it settles.`,
207
+ );
208
+ } else if (cancel.outcome === 'failed') {
209
+ lines.push(
210
+ `An armed transport retry for ${attempt} could not be cancelled (the marker write failed) — it may still prompt and run.`,
211
+ );
212
+ isError = true;
213
+ }
214
+ }
215
+
216
+ for (const outcome of stopped) {
217
+ const record = outcome.record;
218
+ if (outcome.verifiedStatus !== null && isTerminalStatus(outcome.verifiedStatus)) {
219
+ lines.push(
220
+ `Stopped agent ${record.id} (attempt ${record.attempt}, ${causeLabel(record.retryCause)}, ${outcome.description ?? 'no description'}).`,
221
+ );
222
+ } else {
223
+ const state = outcome.unverifiedState ?? 'not terminal';
224
+ lines.push(
225
+ `Attempt ${record.id} (attempt ${record.attempt}, ${causeLabel(record.retryCause)}) did not reach a terminal status (store says: ${state}) — it may still be running.`,
226
+ );
227
+ isError = true;
228
+ }
229
+ }
230
+
231
+ for (const record of plan.outOfScopeLive) {
232
+ lines.push(
233
+ `Left running: ${record.id} (attempt ${record.attempt}, ${causeLabel(record.retryCause)}) — a manual retry is not stopped by a stop aimed at another attempt; name it to stop it.`,
234
+ );
235
+ }
236
+
237
+ for (const record of plan.unknownCauseLive) {
238
+ lines.push(
239
+ `Left running: ${record.id} (attempt ${record.attempt}, ${causeLabel(record.retryCause)}) — the retry cause could not be established, so this dispatch-scoped stop leaves it alone.`,
240
+ );
241
+ }
242
+
243
+ if (stopped.length === 0 && cancels.length === 0 && plan.target) {
244
+ lines.push(
245
+ `Agent ${plan.target.id} is already ${plan.target.status} (attempt ${plan.target.attempt}, ${causeLabel(plan.target.retryCause)}) — nothing stopped.`,
246
+ );
247
+ }
248
+
249
+ if (plan.capped) {
250
+ lines.push(
251
+ 'Lineage not fully checked: the agent-store scan hit its record cap (only the newest records were read).',
252
+ );
253
+ }
254
+ if (plan.targetOutsideWindow) {
255
+ lines.push(
256
+ `Lineage not fully checked: ${plan.targetId} started more than ${plan.windowDays} days ago, outside the retry scan window.`,
257
+ );
258
+ }
259
+
260
+ // THE UNIVERSAL CLAIM. Every disqualifier is named above instead, so the
261
+ // conductor can tell "the dispatch is quiescent" from "the scan could not say".
262
+ const armedPending = cancels.length > 0;
263
+ const truncated = plan.capped || plan.targetOutsideWindow;
264
+ const unproven = stopped.some(
265
+ (outcome) => outcome.verifiedStatus === null || !isTerminalStatus(outcome.verifiedStatus),
266
+ );
267
+ // An out-of-scope LIVE attempt is disqualifying too, and deliberately: it is a
268
+ // member of the SAME dispatch, so "nothing of this dispatch is running" would
269
+ // be false — the sentence's scope is the dispatch, not the stop's scope.
270
+ const liveResidue = plan.outOfScopeLive.length > 0;
271
+ if (!armedPending && !liveResidue && plan.unknownCauseLive.length === 0 && !truncated && !unproven) {
272
+ lines.push(`Nothing of this dispatch (${plan.dispatchId}) is running.`);
273
+ }
274
+
275
+ return { text: lines.join('\n'), isError };
276
+ }
277
+
278
+ function isTerminalStatus(status: AgentStatus): boolean {
279
+ return isTerminalAgentStatusValue(status);
280
+ }
package/src/templates.ts CHANGED
@@ -29,6 +29,8 @@ import { TEMPLATE_PARAM_RE, THINKING_LEVELS, type TaskTemplate, type ThinkingLev
29
29
  import { applyFrontmatterMappers, loadMarkdownRecords, type FrontmatterFieldMapper, type FrontmatterMapContext } from "./loader";
30
30
  import { sanitizeFileName } from "./presets";
31
31
  import { pkgPath } from "./paths";
32
+ import { DISPATCH_KIND_LIST, dispatchFieldProblem, parseDispatchHeader, splitDispatchHeader, type DispatchKind } from "./dispatch-header";
33
+ import { isProcessChecksEnabled } from "./project-flags";
32
34
 
33
35
  // ---------------------------------------------------------------------------
34
36
  // Param extraction
@@ -69,6 +71,7 @@ export function extractParamNames(text: string): string[] {
69
71
  export function resolveTemplate(
70
72
  template: TaskTemplate,
71
73
  params: Record<string, string>,
74
+ context: TemplateRenderContext = {},
72
75
  ): { ok: true; value: TaskTemplate } | { ok: false; error: string } {
73
76
  // Collect all unique param names used in task and outputFile
74
77
  const namesInTask = extractParamNames(template.task);
@@ -92,15 +95,93 @@ export function resolveTemplate(
92
95
  });
93
96
  };
94
97
 
98
+ const rendered = renderDispatchBlock(template, params, replaceAll(template.task), context.cwd);
99
+ if (!rendered.ok) return { ok: false, error: rendered.error };
100
+
95
101
  const resolved: TaskTemplate = {
96
102
  ...template,
97
- task: replaceAll(template.task),
103
+ task: rendered.text,
98
104
  outputFile: template.outputFile ? replaceAll(template.outputFile) : undefined,
99
105
  };
100
106
 
101
107
  return { ok: true, value: resolved };
102
108
  }
103
109
 
110
+ /**
111
+ * The render context: the dispatch cwd, so the render-time process checks use
112
+ * the project's OWN manifest. Absent means "no dispatch cwd known", which reads
113
+ * as fail-open exactly like an un-opted-in project (issue #415's contract).
114
+ */
115
+ export interface TemplateRenderContext {
116
+ cwd?: string;
117
+ }
118
+
119
+ /** The one place the frontmatter kind becomes a header line (spec §3a). */
120
+ function renderDispatchBlock(
121
+ template: TaskTemplate,
122
+ params: Record<string, string>,
123
+ body: string,
124
+ cwd: string | undefined,
125
+ ): { ok: true; text: string } | { ok: false; error: string } {
126
+ const problem = dispatchFieldProblem(template.dispatch);
127
+ if (problem !== undefined) return { ok: false, error: `Template "${template.name}": ${problem}` };
128
+
129
+ if (template.dispatch === undefined) {
130
+ // FAIL-OPEN: a project that has not opted in renders exactly as it did
131
+ // before #606 — the render-time refusal may not leak past the boundary.
132
+ if (!isProcessChecksEnabled(cwd)) return { ok: true, text: body };
133
+ return {
134
+ ok: false,
135
+ error:
136
+ `Template "${template.name}" has no "dispatch" field. Add \`dispatch: <kind>\` to its frontmatter ` +
137
+ `(one of: ${DISPATCH_KIND_LIST}) so the rendered dispatch carries a header — this project opted into processChecks.`,
138
+ };
139
+ }
140
+
141
+ // No second declaration: a body that already opens with one is authoritative,
142
+ // and a frontmatter kind that contradicts it would be a silent disagreement
143
+ // about what the dispatch IS (the kind is what the brief rules key on).
144
+ const declared = splitDispatchHeader(body).header
145
+ .split("\n")
146
+ .find((line) => line.startsWith("dispatch:"));
147
+ if (declared !== undefined) {
148
+ const bodyKind = declared.slice("dispatch:".length).trim();
149
+ if (bodyKind !== template.dispatch) {
150
+ return {
151
+ ok: false,
152
+ error:
153
+ `Template "${template.name}" declares dispatch: ${template.dispatch} but its body opens with ` +
154
+ `\`dispatch: ${bodyKind}\`. Declare the kind in one place.`,
155
+ };
156
+ }
157
+ return { ok: true, text: body };
158
+ }
159
+
160
+ const lines = [`dispatch: ${template.dispatch}`];
161
+ if (template.dispatch === "impl") {
162
+ const brief = (params.brief ?? "").trim();
163
+ if (brief === "") {
164
+ return {
165
+ ok: false,
166
+ error:
167
+ `Template "${template.name}" declares dispatch: impl but no "brief" param was supplied. ` +
168
+ `Pass brief: "<slug>" (the brief lives at briefs/<slug>.md), or ` +
169
+ `brief: "none — <reason>" for the stated escape.`,
170
+ };
171
+ }
172
+ lines.push(`brief: ${brief}`);
173
+ }
174
+
175
+ const composed = `${lines.join("\n")}\n${body}`;
176
+ // One validator for the composed block: a bad brief param and a body whose
177
+ // first line joins the block are the same class of error, caught here.
178
+ const verdict = parseDispatchHeader(composed);
179
+ if (!verdict.ok) {
180
+ return { ok: false, error: `Template "${template.name}" rendered an invalid dispatch block: ${verdict.reason}` };
181
+ }
182
+ return { ok: true, text: composed };
183
+ }
184
+
104
185
  // ---------------------------------------------------------------------------
105
186
  // Template validation
106
187
  // ---------------------------------------------------------------------------
@@ -170,6 +251,14 @@ export function validateTemplate(meta: Record<string, unknown>, fileName: string
170
251
  errors.push(`Template "${meta.name}" (${fileName}): preset must be a string.`);
171
252
  }
172
253
 
254
+ // Issue #606 (§3a): `dispatch:` is an ENUM. validateTemplate ignored unknown
255
+ // fields before this, so a typo (`dispatch: reveiw`) would have disabled the
256
+ // gate with no warning — the exact failure a silently-ignored key produces.
257
+ const dispatchProblem = dispatchFieldProblem(meta.dispatch);
258
+ if (dispatchProblem !== undefined) {
259
+ errors.push(`Template "${meta.name}" (${fileName}): ${dispatchProblem}`);
260
+ }
261
+
173
262
  return errors;
174
263
  }
175
264
 
@@ -208,6 +297,12 @@ const TEMPLATE_FIELD_MAPPERS = {
208
297
  noBuiltinTools: (meta) => (meta.noBuiltinTools === "true" ? true : undefined),
209
298
  inheritSystemPrompt: (meta) =>
210
299
  (meta.inheritSystemPrompt === "false" ? false : undefined),
300
+ // An already-validated enum value; anything else stays `undefined` so a
301
+ // stale file cannot present itself as a typed kind.
302
+ dispatch: (meta) =>
303
+ typeof meta.dispatch === "string" && dispatchFieldProblem(meta.dispatch) === undefined
304
+ ? (meta.dispatch as DispatchKind)
305
+ : undefined,
211
306
  } satisfies TemplateFieldMappers;
212
307
 
213
308
  // ---------------------------------------------------------------------------
@@ -409,6 +504,7 @@ export function buildTemplateFrontmatter(template: TaskTemplate): string {
409
504
  lines.push("tools:");
410
505
  for (const t of template.tools) lines.push(` - ${t}`);
411
506
  }
507
+ if (template.dispatch) lines.push(`dispatch: ${template.dispatch}`);
412
508
  if (template.excludeTools?.length) {
413
509
  lines.push("excludeTools:");
414
510
  for (const t of template.excludeTools) lines.push(` - ${t}`);
@@ -44,14 +44,16 @@
44
44
  */
45
45
 
46
46
  import type { RuntimeContext } from "./runtime";
47
- import type { DelegateTaskParams, SubagentEvent, SubagentEventListener, SubagentRun, ToolResult } from "./types";
47
+ import type { DelegateTaskParams, RetryCause, SubagentEvent, SubagentEventListener, SubagentRun, ToolResult } from "./types";
48
48
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
49
49
  import * as fs from "node:fs";
50
50
  import { isAbsolute, join } from "node:path";
51
51
  import * as eventBus from "./event-bus";
52
52
  import { resolveRetryParams } from "./history";
53
53
  import {
54
+ appendCompletionParagraph,
54
55
  buildCompletionMessage,
56
+ buildRepeatTransportAdvisory,
55
57
  claimTerminalNotice,
56
58
  resolveDelivery,
57
59
  resolveRunEntry,
@@ -59,6 +61,7 @@ import {
59
61
  withWorktreeState,
60
62
  } from "./notify-completion";
61
63
  import { bankPath, resolveRoot, RUNS_DIR, type RootOptions } from "./scratch-root";
64
+ import { armRetry, clearArmedRetry } from "./retry-armed";
62
65
  import { isTransportRetryable, TRANSPORT_RETRY_TOAST } from "./transport-retry";
63
66
  import { describeWorktreeState } from "./worktree-report";
64
67
 
@@ -81,10 +84,11 @@ interface TerminalNotifierDeps {
81
84
  spawnBackgroundRun: (
82
85
  pi: ExtensionAPI,
83
86
  ctx: ExtensionContext,
84
- params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
87
+ params: DelegateTaskParams | ReturnType<typeof resolveRetryParams>,
85
88
  singleTask: string,
86
89
  retrySourceRun?: SubagentRun,
87
90
  attemptContext?: string,
91
+ retryCause?: RetryCause,
88
92
  ) => Promise<ToolResult<undefined>>;
89
93
  }
90
94
 
@@ -309,6 +313,26 @@ export function createTerminalNotifier(rt: RuntimeContext, deps: TerminalNotifie
309
313
  run: SubagentRun,
310
314
  ): Promise<boolean> {
311
315
  const sourceAttempt = run.attempt ?? 1;
316
+ // Issue #616 (Q3): the retry is UNADDRESSABLE until its own agent record
317
+ // lands, so a durable INTENT is written BEFORE the spawn — keyed by the
318
+ // source run, the only id that exists yet. A `stop_subagent` that reaches
319
+ // the dispatch inside that window sets the cancel, and the spawn honours it
320
+ // at its pre-prompt gate instead of prompting.
321
+ //
322
+ // Best-effort: a marker that cannot be written leaves the pre-#616 window
323
+ // (the retry starts unannounced) — strictly better than dropping a retry the
324
+ // transport predicate just decided to run.
325
+ const armed = armRetry({
326
+ parentId: run.id,
327
+ attempt: sourceAttempt + 1,
328
+ armedAt: new Date().toISOString(),
329
+ });
330
+ if (!armed) {
331
+ log.warn("Transport auto-retry could not arm its pre-spawn marker — the retry is unaddressable until it has a record", {
332
+ sourceId: run.id,
333
+ attempt: sourceAttempt + 1,
334
+ });
335
+ }
312
336
  try {
313
337
  const retryParams = resolveRetryParams({}, run);
314
338
  // Issue #404: point at the retained session ONLY when it is really
@@ -330,6 +354,9 @@ export function createTerminalNotifier(rt: RuntimeContext, deps: TerminalNotifie
330
354
  retryParams.task!,
331
355
  run,
332
356
  buildRetryResumePreamble(run, sourceAttempt + 1, retainedSessionDir),
357
+ // Issue #616: the mint site states the cause — this IS the automatic
358
+ // transport retry, and nothing else may claim it.
359
+ "transport",
333
360
  );
334
361
  if (result.isError) {
335
362
  log.warn("Transport auto-retry spawn rejected — surfacing the original failure", {
@@ -346,6 +373,12 @@ export function createTerminalNotifier(rt: RuntimeContext, deps: TerminalNotifie
346
373
  error: (err as Error).message,
347
374
  });
348
375
  return false;
376
+ } finally {
377
+ // Issue #616: the intent's window ends with the spawn — either the gate
378
+ // already cleared it (the retry is durable), or the spawn failed before
379
+ // reaching the gate (nothing will prompt, and a stale marker would make a
380
+ // later stop disclose an "armed" retry that cannot exist).
381
+ clearArmedRetry(run.id, sourceAttempt + 1);
349
382
  }
350
383
  log.info("Background run settled — transport auto-retry scheduled", {
351
384
  sourceId: run.id,
@@ -355,6 +388,29 @@ export function createTerminalNotifier(rt: RuntimeContext, deps: TerminalNotifie
355
388
  return true;
356
389
  }
357
390
 
391
+ /**
392
+ * Issue #556: the paragraph a SECOND transport death carries, resolved from the
393
+ * durable records — the settled run and the record it resumed (`resumeOf`).
394
+ *
395
+ * EMPTY for every case this cannot prove. The lookup is inside the try, so a
396
+ * missing run record, an unknown `resumeOf`, or a throwing registry read costs
397
+ * the paragraph and NOTHING else: the ordinary notice is delivered untouched
398
+ * (the same fail-open rule `scheduleTransportRetry` follows). A toast is
399
+ * deliberately absent — the retry toast already fired when attempt 2 was armed,
400
+ * and a second one would report the same lineage twice.
401
+ */
402
+ function repeatTransportAdvisory(run: SubagentRun | undefined): string {
403
+ if (!run?.resumeOf) return "";
404
+ try {
405
+ const ctx = getSession();
406
+ if (!ctx) return "";
407
+ const source = resolveRunEntry(state.getLogicalRunEntries(ctx), run.resumeOf);
408
+ return buildRepeatTransportAdvisory(run, source, run.label);
409
+ } catch {
410
+ return "";
411
+ }
412
+ }
413
+
358
414
  async function deliverCompletionAlert(event: SubagentEvent): Promise<void> {
359
415
  const id = event.agentId;
360
416
  if (!claimTerminalNotice(id)) return;
@@ -375,6 +431,16 @@ export function createTerminalNotifier(rt: RuntimeContext, deps: TerminalNotifie
375
431
  if (retried) return;
376
432
  }
377
433
  const message = buildCompletionMessage(agent, run);
434
+ // Issue #556: the line between "this class of death is retried" and "a
435
+ // second death is not made to matter" is the change-shape rule, and the
436
+ // completion notice is where the conductor reads it. Appended as its own
437
+ // part (before the closing directive), and warned once on the log so the
438
+ // event is machine-readable too.
439
+ const advisory = repeatTransportAdvisory(run);
440
+ if (advisory) {
441
+ log.warn(advisory, { agentId: id, resumeOf: run?.resumeOf, attempt: run?.attempt });
442
+ }
443
+ const advisedMessage = appendCompletionParagraph(message, advisory);
378
444
  // Issue #474: a settle that is not a success reports the worktree it may
379
445
  // have left. The CLASSIFIED status gates it (not `agent.status`), so the
380
446
  // #179 completed→failed downgrade carries the block too, and a genuinely
@@ -384,9 +450,9 @@ export function createTerminalNotifier(rt: RuntimeContext, deps: TerminalNotifie
384
450
  // against this process's cwd).
385
451
  const settledMessage =
386
452
  message.details.status === "completed"
387
- ? message
453
+ ? advisedMessage
388
454
  : withWorktreeState(
389
- message,
455
+ advisedMessage,
390
456
  describeWorktreeState(agent.cwd ?? run?.originalParams?.cwd),
391
457
  );
392
458
  // Issue #179 (D2): resolve delivery from the CLASSIFIED notification