brl-subagent 2.7.0 → 2.9.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.
Files changed (51) hide show
  1. package/AGENT.md +3 -3
  2. package/README.md +18 -10
  3. package/package.json +6 -5
  4. package/src/agent-tools.ts +332 -0
  5. package/src/background-pipeline.ts +1025 -0
  6. package/src/boot-recovery.ts +313 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +26 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +69 -0
  11. package/src/event-bus.ts +10 -0
  12. package/src/git.ts +274 -5
  13. package/src/headstate.ts +471 -0
  14. package/src/history.ts +21 -3
  15. package/src/index.ts +127 -3943
  16. package/src/kill-escalation.ts +87 -7
  17. package/src/loader.ts +47 -1
  18. package/src/logging.ts +1 -1
  19. package/src/mode-prologue.ts +4 -10
  20. package/src/mode-runners.ts +1575 -0
  21. package/src/notify-completion.ts +180 -12
  22. package/src/params.ts +211 -37
  23. package/src/preflight.ts +123 -16
  24. package/src/prelude.ts +92 -7
  25. package/src/presets.ts +85 -18
  26. package/src/proc.ts +2 -3
  27. package/src/project-flags.ts +3 -3
  28. package/src/recovery-engine.ts +11 -1
  29. package/src/recovery-surface.ts +1 -2
  30. package/src/recovery.ts +155 -20
  31. package/src/reports.ts +1 -7
  32. package/src/run-registry.ts +22 -3
  33. package/src/runner.ts +80 -21
  34. package/src/runtime.ts +50 -0
  35. package/src/sanitize.ts +20 -2
  36. package/src/scheduler.ts +1 -2
  37. package/src/schema.ts +37 -7
  38. package/src/scratch-root.ts +909 -0
  39. package/src/scratch-spawn.ts +256 -0
  40. package/src/session-manager.ts +854 -200
  41. package/src/state.ts +130 -30
  42. package/src/templates.ts +42 -17
  43. package/src/terminal-notifier.ts +405 -0
  44. package/src/transcript.ts +1 -1
  45. package/src/tui-format.ts +177 -7
  46. package/src/tui.ts +115 -57
  47. package/src/types.ts +206 -5
  48. package/src/unit-params.ts +113 -0
  49. package/src/unit-run.ts +45 -16
  50. package/src/validate.ts +89 -11
  51. package/src/worktree-report.ts +142 -0
@@ -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
@@ -25,9 +25,9 @@
25
25
  * which is how PROJECT > USER precedence is enforced.
26
26
  */
27
27
 
28
+ import type { Logger } from "./logging";
28
29
  import * as fs from "node:fs";
29
30
  import * as path from "node:path";
30
- import type { Logger } from "./logging";
31
31
 
32
32
  // ---------------------------------------------------------------------------
33
33
  // Frontmatter parsing
@@ -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
  // ---------------------------------------------------------------------------
package/src/logging.ts CHANGED
@@ -14,9 +14,9 @@
14
14
  * session starts and all loggers share <cwd>/.pi/subagent-logs/brl-subagent.log.
15
15
  */
16
16
 
17
+ import type { LogLevel } from "./types";
17
18
  import * as fs from "node:fs";
18
19
  import * as path from "node:path";
19
- import type { LogLevel } from "./types";
20
20
 
21
21
  // ---------------------------------------------------------------------------
22
22
  // Configuration
@@ -37,20 +37,14 @@
37
37
  * same point in the sequence.
38
38
  */
39
39
 
40
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
41
- import type { ToolResult } from "./types";
42
- import type { SessionState } from "./state";
43
40
  import type { Logger } from "./logging";
41
+ import type { SessionState } from "./state";
42
+ import type { ToolResult } from "./types";
43
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
44
44
  import { resolveSubagentParams, type ResolveInputParams } from "./params";
45
45
  import { getCurrentDepth } from "./sanitize";
46
46
  import { preflightCheck } from "./preflight";
47
- import {
48
- depthLimitRejection,
49
- gateSessionCost,
50
- rejection,
51
- runPreTaskValidation,
52
- validateDelegationTargets,
53
- } from "./prelude";
47
+ import { depthLimitRejection, gateSessionCost, rejection, runPreTaskValidation, validateDelegationTargets } from "./prelude";
54
48
 
55
49
  /** The params object the shared resolver consumes (`ResolveInputParams`,
56
50
  * params.ts) — the same type the background and single paths pass. */