brl-subagent 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -329,6 +329,17 @@ export function processTarget(
329
329
  : pidTarget(pid, kill, pidAlive, guard);
330
330
  }
331
331
 
332
+ /**
333
+ * #455: the default post-SIGKILL confirmation window. SIGKILL delivery is
334
+ * ASYNCHRONOUS — sampling death in the same pass that signalled reads `R`
335
+ * (signal pending) or `Z` (awaiting reap) and calls a dying process a survivor.
336
+ * 100 ms is a bounded confirmation window, not a wait for a kill to work.
337
+ */
338
+ const DEFAULT_DRAIN_MS = 100;
339
+
340
+ /** #455: drain poll interval when the caller set no `pollMs`. */
341
+ const DEFAULT_DRAIN_POLL_MS = 10;
342
+
332
343
  export interface EscalationOptions {
333
344
  /** Grace window between SIGTERM and SIGKILL (ms). */
334
345
  graceMs: number;
@@ -337,11 +348,51 @@ export interface EscalationOptions {
337
348
  /**
338
349
  * Poll interval for the early-exit wait (B4). When > 0 the helper returns as
339
350
  * soon as every target verifies dead, bounded by `graceMs`; when omitted the
340
- * helper waits the full `graceMs` once.
351
+ * helper waits the full `graceMs` once. Also used as the #455 drain interval.
341
352
  */
342
353
  pollMs?: number;
343
354
  /** Injectable clock for the deadline (defaults to Date.now). */
344
355
  now?(): number;
356
+ /**
357
+ * #455: bounded post-SIGKILL confirmation window (ms) — how long the helper
358
+ * re-samples `verifyDeath()` for the targets it just force-killed before it
359
+ * classifies survivors. Defaults to {@link DEFAULT_DRAIN_MS}; `0` (any
360
+ * non-positive value) disables it and restores the legacy single-sample
361
+ * classification (the documented escape). Ignored when no `forceKill` was issued: a target that died during
362
+ * the grace window has no signal in flight to confirm.
363
+ */
364
+ drainMs?: number;
365
+ }
366
+
367
+ /**
368
+ * #455 phase B: re-sample `verifyDeath()` for the targets that were force-killed
369
+ * until every one confirms dead or the drain deadline passes. SIGKILL delivery
370
+ * and reaping are asynchronous, so the classification below must not be decided
371
+ * by the sample taken in the same instant as the signal.
372
+ *
373
+ * Bounded by `now() + drainMs` (never "poll until dead") and cheap when nothing
374
+ * is in flight: zero force-killed targets ⇒ no sleep, no clock read.
375
+ */
376
+ async function drainForceKilled(
377
+ forceKilled: EscalationTarget[],
378
+ options: EscalationOptions,
379
+ ): Promise<void> {
380
+ const drainMs = options.drainMs ?? DEFAULT_DRAIN_MS;
381
+ if (forceKilled.length === 0 || drainMs <= 0) return;
382
+ const pollMs = options.pollMs && options.pollMs > 0 ? options.pollMs : DEFAULT_DRAIN_POLL_MS;
383
+ const now = options.now ?? Date.now;
384
+ const deadline = now() + drainMs;
385
+ // TWO bounds, deliberately. The clock bound is the contract ("100 ms"); the
386
+ // iteration bound is what keeps a sleep that does not actually advance time
387
+ // (a no-op injected sleep) from turning the drain into a hot spin — measured
388
+ // at 61k samples inside one 100 ms window before this bound existed.
389
+ const maxPolls = Math.max(1, Math.ceil(drainMs / pollMs));
390
+ for (let poll = 0; poll < maxPolls; poll++) {
391
+ if (forceKilled.every((target) => target.verifyDeath())) return;
392
+ const remaining = deadline - now();
393
+ if (remaining <= 0) return;
394
+ await options.sleep(Math.min(pollMs, remaining));
395
+ }
345
396
  }
346
397
 
347
398
  /**
@@ -361,6 +412,15 @@ export interface EscalationOptions {
361
412
  * whose final group signal was REFUSED while its group still had live members is
362
413
  * appended to the survivors (`refusedForceKillGroup`), so a refined guard
363
414
  * decision can never report a clean result over a live group we targeted.
415
+ *
416
+ * #455: the SIGKILL pass is three phases — (A) dispatch `forceKill` to every
417
+ * target still verifying alive, (B) a BOUNDED post-SIGKILL drain of
418
+ * `verifyDeath` for exactly those targets, (C) classify survivors. Phases A and
419
+ * C were one pass before, which decided the survivor list from a sample taken
420
+ * in the same instant as the signal: SIGKILL is asynchronous, so a dying process
421
+ * (state `R`, or `Z` awaiting reap) read as a survivor every time. The refused
422
+ * group rule and the unconditional final group SIGKILL stay AFTER phase C — a
423
+ * refusal is a decision, not a timing window.
364
424
  */
365
425
  export async function escalateKill(
366
426
  targets: EscalationTarget[],
@@ -379,7 +439,13 @@ export async function escalateKill(
379
439
  if (pollMs > 0) {
380
440
  const now = options.now ?? Date.now;
381
441
  const deadline = now() + options.graceMs;
382
- while (now() < deadline && !targets.every((target) => target.verifyDeath())) {
442
+ // #455 review: the SAME two-bound rule as the drain below — a sleep that
443
+ // does not advance an injected clock must not turn this into a hot spin.
444
+ // With a real clock the iteration cap is exactly the number of polls the
445
+ // window can hold, so it never truncates a legitimate wait.
446
+ const maxPolls = Math.max(1, Math.ceil(options.graceMs / pollMs));
447
+ for (let poll = 0; poll < maxPolls; poll++) {
448
+ if (now() >= deadline || targets.every((target) => target.verifyDeath())) break;
383
449
  const remaining = Math.max(deadline - now(), 1);
384
450
  await options.sleep(Math.min(pollMs, remaining));
385
451
  }
@@ -388,19 +454,33 @@ export async function escalateKill(
388
454
  }
389
455
  }
390
456
 
391
- const survivors: EscalationTarget[] = [];
457
+ // Phase A — force-kill pass. Only force-kill the DIRECT process while it is
458
+ // still alive; a group whose leader already exited is ended by the
459
+ // unconditional group SIGKILL below.
460
+ const forceKilled: EscalationTarget[] = [];
392
461
  for (const target of targets) {
393
462
  if (target.verifyDeath()) continue;
394
- // Only force-kill the DIRECT process while it is still alive; a group whose
395
- // leader already exited is ended by the unconditional group SIGKILL below.
396
463
  if (target.verifyProcessAlive?.() ?? true) {
397
464
  try {
398
465
  target.forceKill();
466
+ forceKilled.push(target);
399
467
  } catch {
400
- // Exited between the liveness check and the signal.
468
+ // Exited between the liveness check and the signal: nothing in flight.
401
469
  }
402
470
  }
403
- if (!target.verifyDeath() && (target.verifyProcessAlive?.() ?? true)) survivors.push(target);
471
+ }
472
+
473
+ // Phase B — bounded drain (#455): let the SIGKILLs that were just dispatched
474
+ // land and be reaped before anything is classified as a survivor.
475
+ await drainForceKilled(forceKilled, options);
476
+
477
+ // Phase C — classify. A survivor is a target that is still not dead AND still
478
+ // process-alive, exactly as before — only now the sample is not taken in the
479
+ // same instant as the signal.
480
+ const survivors: EscalationTarget[] = [];
481
+ for (const target of targets) {
482
+ if (target.verifyDeath()) continue;
483
+ if (target.verifyProcessAlive?.() ?? true) survivors.push(target);
404
484
  }
405
485
 
406
486
  // D5 (option b): the final GROUP SIGKILL is UNCONDITIONAL. `verifyDeath` is
package/src/loader.ts CHANGED
@@ -84,6 +84,52 @@ export function parseFrontmatter(content: string): { meta: Record<string, unknow
84
84
  return { meta, body: match[2].trim() };
85
85
  }
86
86
 
87
+ // ---------------------------------------------------------------------------
88
+ // Field-mapper tables
89
+ // ---------------------------------------------------------------------------
90
+
91
+ /**
92
+ * The non-frontmatter inputs a field mapper may read: the resolved name (which
93
+ * comes from the file/validator, not always from `meta`) and the markdown body.
94
+ * Shared by both tiers' tables — presets read `name`/`body`, templates too.
95
+ */
96
+ export interface FrontmatterMapContext {
97
+ name: string;
98
+ body: string;
99
+ }
100
+
101
+ /**
102
+ * One row of a tier's field-mapper table: frontmatter plus context in, ONE
103
+ * record field out. `R` is the field's declared type, so a table declared as
104
+ * `{[K in keyof T]: FrontmatterFieldMapper<T[K]>}` makes a mapper that returns
105
+ * the wrong type a compile error at the row, not a silent cast at the assembly.
106
+ */
107
+ export type FrontmatterFieldMapper<R> = (
108
+ meta: Record<string, unknown>,
109
+ ctx: FrontmatterMapContext,
110
+ ) => R;
111
+
112
+ /**
113
+ * Build a record from a field-mapper table and one parsed frontmatter pair.
114
+ * Single-source for both tiers (`presetFromFrontmatter`, `templateFromFrontmatter`),
115
+ * which had byte-identical assemblies.
116
+ *
117
+ * The `as unknown as R` bridge is the compensating cast: `Object.fromEntries`
118
+ * hands back `{ [k: string]: unknown }`, and the record types are interfaces
119
+ * (no implicit index signature), so no narrower assertion compiles. Its safety
120
+ * is the table it is handed: `satisfies { [K in keyof T]: … }` pins the key set
121
+ * to exactly the record's fields, and the per-key return type pins each value.
122
+ */
123
+ export function applyFrontmatterMappers<R>(
124
+ mappers: Record<string, FrontmatterFieldMapper<unknown>>,
125
+ meta: Record<string, unknown>,
126
+ ctx: FrontmatterMapContext,
127
+ ): R {
128
+ return Object.fromEntries(
129
+ Object.entries(mappers).map(([field, mapper]) => [field, mapper(meta, ctx)]),
130
+ ) as unknown as R;
131
+ }
132
+
87
133
  // ---------------------------------------------------------------------------
88
134
  // Tier loading
89
135
  // ---------------------------------------------------------------------------
@@ -17,15 +17,17 @@
17
17
  * controls the WAKE (D2). D1: failed/stopped → "steer", completed → "followUp".
18
18
  */
19
19
 
20
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
20
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
21
21
  import type {
22
22
  BackgroundAgent,
23
+ BackgroundAgentIdentity,
23
24
  SubagentRun,
24
25
  CompletionNotifyMode,
25
26
  AgentStatus,
26
27
  } from "./types";
27
28
  import { truncateTail } from "./transcript-tail";
28
29
  import { formatRunDuration } from "./history";
30
+ import { formatBudgetDuration } from "./tui-format";
29
31
  import { classifyTerminalOutcome } from "./types";
30
32
  import { resolveTerminalRunEntry } from "./state";
31
33
 
@@ -59,7 +61,11 @@ export interface DeliveryResolution {
59
61
  triggerTurn: boolean;
60
62
  }
61
63
 
62
- /** Default dedupe cap: the set is simply cleared when it exceeds this. */
64
+ /**
65
+ * Default dedupe cap. The set stays bounded by evicting its oldest entry when it
66
+ * exceeds this — never the whole set (issue #440: a clear-all forgot the id it had
67
+ * just claimed, so that id could be delivered twice).
68
+ */
63
69
  const DEDUPE_CAP = 200;
64
70
 
65
71
  /**
@@ -114,6 +120,49 @@ function buildSummaryLine(
114
120
  return line;
115
121
  }
116
122
 
123
+ /**
124
+ * The ONE timeout predicate (issue #423): a run hit its deadline when the
125
+ * classified category says so or the agent's error is the deadline stamp. The
126
+ * wake, the result renderer and the budget line all read it, so the two
127
+ * exhaustion surfaces cannot disagree.
128
+ */
129
+ export function isTimeoutEvidence(agent: BackgroundAgent, run?: SubagentRun): boolean {
130
+ const category = run?.errorCategory ?? run?.originalParams?.errorCategory;
131
+ return category === "timeout" || /^Timed out/.test(agent.error ?? "");
132
+ }
133
+
134
+ /**
135
+ * One line stating a run's budget (issue #423). PURE. Returns undefined when the
136
+ * record carries no budget — an old record written before `timeoutMs` existed
137
+ * has nothing to state, so no line is better than an invented 30 m.
138
+ *
139
+ * Shapes:
140
+ * - timeout: `Budget: 30m (exhausted)`
141
+ * - otherwise `Budget: 30m — 4m 12s used, 25m 48s left`
142
+ *
143
+ * `status` guards the exhausted form: a run classified `completed` never claims
144
+ * to have exhausted its budget (the evidence predicate alone would otherwise be
145
+ * enough to downgrade a late-but-successful settle). `run` is optional because
146
+ * the result path (`get_subagent_result`) has only the agent record; both read
147
+ * the SAME predicate.
148
+ */
149
+ export function formatBudgetLine(
150
+ agent: BackgroundAgent,
151
+ status: CompletionStatus | undefined,
152
+ run: SubagentRun | undefined,
153
+ now: number = Date.now(),
154
+ ): string | undefined {
155
+ if (agent.timeoutMs === undefined) return undefined;
156
+ const budget = formatBudgetDuration(agent.timeoutMs);
157
+ if (status !== "completed" && isTimeoutEvidence(agent, run)) {
158
+ return `Budget: ${budget} (exhausted)`;
159
+ }
160
+ const endMs = agent.completedAt ?? now;
161
+ const usedMs = Math.max(0, endMs - agent.startedAt);
162
+ const remainingMs = Math.max(0, agent.startedAt + agent.timeoutMs - endMs);
163
+ return `Budget: ${budget} — ${formatBudgetDuration(usedMs)} used, ${formatBudgetDuration(remainingMs)} left`;
164
+ }
165
+
117
166
  /**
118
167
  * PURE builder — no pi SDK, no side effects, never throws. Returns the
119
168
  * sendMessage payload shape per D3.
@@ -169,6 +218,13 @@ export function buildCompletionMessage(
169
218
  : stored;
170
219
  const tail = truncateTail(body, 15);
171
220
  const parts = [summary];
221
+ // Issue #423: the budget rides its own part, and ONLY on a failed/stopped
222
+ // wake — a completed run's message is unchanged (the human reads the budget
223
+ // when something went wrong, not on every success).
224
+ if (status !== "completed") {
225
+ const budgetLine = formatBudgetLine(agent, status, run);
226
+ if (budgetLine) parts.push(budgetLine);
227
+ }
172
228
  if (headline) parts.push(headline);
173
229
  if (tail) parts.push(tail);
174
230
  parts.push(COMPLETION_DIRECTIVE);
@@ -209,13 +265,20 @@ export function resolveDelivery(
209
265
 
210
266
  /**
211
267
  * Dedupe guard — first terminal event per id wins. Returns true when the event
212
- * should be delivered, false when it is a duplicate. Capped simply (W1): the
213
- * set is cleared when it exceeds the cap.
268
+ * should be delivered, false when it is a duplicate. Retention is bounded (W1):
269
+ * once the set exceeds the cap its OLDEST entry is evicted (a `Set` iterates in
270
+ * insertion order, so that is exact). The id just claimed is the newest entry, so
271
+ * its own call evicts an EARLIER id — not the set, and not that claim. A clear-all
272
+ * forgot the claim entirely, so the very next duplicate was delivered twice (#440).
214
273
  */
215
274
  export function markTerminalSeen(seen: Set<string>, id: string, cap = DEDUPE_CAP): boolean {
275
+ cap = Math.max(cap, 1); // a cap below 1 evicts the claim just made — retention must keep it
216
276
  if (seen.has(id)) return false;
217
277
  seen.add(id);
218
- if (seen.size > cap) seen.clear();
278
+ if (seen.size > cap) {
279
+ const oldest = seen.values().next().value;
280
+ if (oldest !== undefined) seen.delete(oldest);
281
+ }
219
282
  return true;
220
283
  }
221
284
 
@@ -254,3 +317,81 @@ export function sendCompletionNotification(
254
317
  ): void {
255
318
  pi.sendMessage(message, { deliverAs: delivery.deliverAs, triggerTurn: delivery.triggerTurn });
256
319
  }
320
+
321
+ // ---------------------------------------------------------------------------
322
+ // Started-but-degraded monitoring advisory (issue #439)
323
+ //
324
+ // A background spawn whose tail faulted is a STARTED run whose monitoring is
325
+ // degraded — never a failed spawn. The conductor learns that from the spawn
326
+ // result's paragraph; the user learns it from this advisory. The advisory is
327
+ // deliberately NOT a terminal notice and never takes the terminal claim: the
328
+ // run is live, and its genuine completion notice must still be delivered later
329
+ // (the resolved contract on the issue). A run that emits the advisory and then
330
+ // never delivers a terminal notice (no listener at settle time) degrades to
331
+ // "advisory only" — a stated limitation, not a silent one.
332
+ // ---------------------------------------------------------------------------
333
+
334
+ /** The advisory's custom message type. NOT a terminal notice type. */
335
+ export const MONITORING_DEGRADED_CUSTOM_TYPE = "subagent-monitoring-degraded";
336
+
337
+ /** The user-facing half of the advisory (the footer/toast line). */
338
+ export const MONITORING_DEGRADED_TOAST = "Background agent started — monitoring degraded";
339
+
340
+ /**
341
+ * The conductor-facing paragraph a STARTED-but-degraded spawn result carries.
342
+ * Built from the identity record only — never from a property read on the live
343
+ * agent (see the boundary statement in `startBackgroundAgent`). EMPTY when the
344
+ * tail attached fully: callers append it unconditionally.
345
+ */
346
+ export function buildMonitoringDegradedParagraph(
347
+ unit: Pick<BackgroundAgentIdentity, "id" | "label">,
348
+ tailFailures: string[],
349
+ ): string {
350
+ if (tailFailures.length === 0) return "";
351
+ const name = unit.label ? `"${unit.label}" ` : "";
352
+ return (
353
+ `\n\nMonitoring degraded: ${name}started, but its live monitoring could not be attached (${tailFailures.join("; ")}). ` +
354
+ `Do not re-dispatch — the run is live; retrieve with get_subagent_result({ agent_id: "${unit.id}" }).`
355
+ );
356
+ }
357
+
358
+ /** The advisory's message body — the same facts, phrased for the user's screen. */
359
+ export function buildMonitoringDegradedAdvisory(
360
+ unit: Pick<BackgroundAgentIdentity, "id" | "label">,
361
+ tailFailures: string[],
362
+ ): string {
363
+ if (tailFailures.length === 0) return "";
364
+ const name = unit.label ? ` "${unit.label}"` : "";
365
+ return (
366
+ `Background agent${name} started, but its monitoring is degraded (${tailFailures.join("; ")}). ` +
367
+ `The run is live — do not re-dispatch it; retrieve with get_subagent_result({ agent_id: "${unit.id}" }).`
368
+ );
369
+ }
370
+
371
+ /**
372
+ * Emit the advisory on both channels, each in its own try: a throwing
373
+ * `sendMessage` must not swallow the footer line, and a missing UI must not
374
+ * swallow the message. Best-effort by design — this is the report of a
375
+ * degraded path and cannot itself fail the spawn.
376
+ */
377
+ export function sendMonitoringDegradedAdvisory(
378
+ pi: ExtensionAPI,
379
+ ctx: Pick<ExtensionContext, "ui">,
380
+ identity: BackgroundAgentIdentity,
381
+ tailFailures: string[],
382
+ ): void {
383
+ try {
384
+ pi.sendMessage(
385
+ {
386
+ customType: MONITORING_DEGRADED_CUSTOM_TYPE,
387
+ content: buildMonitoringDegradedAdvisory(identity, tailFailures),
388
+ display: true,
389
+ details: { agentId: identity.id, tailFailures },
390
+ },
391
+ { deliverAs: "followUp" },
392
+ );
393
+ } catch { /* best-effort */ }
394
+ try {
395
+ ctx.ui.notify(MONITORING_DEGRADED_TOAST, "warning");
396
+ } catch { /* best-effort */ }
397
+ }