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.
@@ -1,20 +1,23 @@
1
1
  // Purpose: Background execution: SDK sessions (`createAgentSession`), agent records, timeouts, steering, and settle paths.
2
2
  import { randomUUID } from 'crypto';
3
3
  import { basename, dirname, join, resolve } from 'path';
4
- import { writeFileSync, readFileSync, readdirSync, existsSync, rmSync, statSync, type Dirent } from 'fs';
4
+ import { writeFileSync, readFileSync, readdirSync, existsSync, rmSync, statSync, unlinkSync, type Dirent } from 'fs';
5
5
  import {
6
6
  EMPTY_USAGE,
7
7
  classifyError,
8
8
  classifyTerminalOutcome,
9
9
  isProviderError,
10
+ isTerminalAgentStatusValue,
10
11
  coherentFailureReason,
11
12
  SUBAGENT_ABORTED_MESSAGE,
12
13
  NO_ASSISTANT_OUTPUT_REASON,
14
+ CANCELLED_RETRY_MESSAGE,
13
15
  PROMPT_NEVER_ISSUED_MESSAGE,
14
16
  type BackgroundAgent,
15
17
  type AgentStatus,
16
18
  type GitMode,
17
19
  type RecoveryMode,
20
+ type RetryCause,
18
21
  type SubagentResult,
19
22
  type SubagentRun,
20
23
  type ThinkingLevel,
@@ -46,7 +49,7 @@ import {
46
49
  } from './git';
47
50
  import { clearHeadState, readHeadState, writeHeadState, HEAD_STATE_VERSION } from './headstate';
48
51
  import { effectiveBackgroundBudget } from './validate';
49
- import { currentProcessOwner, classifyOwner, defaultRecoveryDeps } from './recovery';
52
+ import { currentProcessOwner, classifyOwner, defaultRecoveryDeps, type AgentRecordFailureReason } from './recovery';
50
53
  import {
51
54
  persistRunRecord,
52
55
  listInflightRuns,
@@ -57,8 +60,11 @@ import {
57
60
  } from './run-registry';
58
61
  import { isTransportRetryable } from './transport-retry';
59
62
  import { ensureOwnerOnlyDir, repairOwnerOnlyFiles } from './store-permissions';
63
+ import { writeFileAtomicSync } from './atomic-write';
60
64
  import { buildEngineeringBarSection } from './engineering-bar';
61
65
  import { prepareRunScratch, markSettled } from './scratch-spawn';
66
+ import { readRequiredGuard, resolveGuardPath, verifyGuardLoaded } from './background-guard';
67
+ import { clearArmedRetry, isRetryCancelRequested } from './retry-armed';
62
68
 
63
69
  const log = createLogger('brl-subagent');
64
70
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
@@ -470,6 +476,51 @@ function sweepRetainedSessions(currentDir: string): void {
470
476
  }
471
477
  }
472
478
 
479
+ // ---------------------------------------------------------------------------
480
+ // Issue #554: temp residue from the atomic record writer.
481
+ //
482
+ // A SIGKILL cannot run `writeFileAtomicSync`'s cleanup, so `.tmp` siblings
483
+ // accumulate in the agent store (measured: 8 leftovers in 20 kills). The record
484
+ // scans filter `.json`, so they are invisible to every reader — which is exactly
485
+ // why they need their own bounded sweep instead of aging out silently.
486
+ //
487
+ // The 1-hour age floor is the safety property: a temp belonging to a LIVE
488
+ // writer must survive another process's boot, and a writer that is merely slow
489
+ // can hold one for seconds, not an hour. A fresh temp is NEVER removed.
490
+ // ---------------------------------------------------------------------------
491
+
492
+ /** Only temps older than this are sweepable — a live writer's temp is younger. */
493
+ export const AGENT_TEMP_MAX_AGE_MS = 60 * 60 * 1000;
494
+
495
+ /**
496
+ * Remove `*.tmp` residue in the agent store older than one hour. Returns the
497
+ * number removed. Never throws: the store may be missing or unwritable, and a
498
+ * boot must not fail on hygiene.
499
+ */
500
+ export function sweepAgentRecordTemps(): number {
501
+ let names: string[];
502
+ try {
503
+ names = readdirSync(STORAGE_DIR);
504
+ } catch {
505
+ return 0; // store absent/unreadable — nothing to bound
506
+ }
507
+ const now = Date.now();
508
+ let swept = 0;
509
+ for (const name of names) {
510
+ if (!name.endsWith('.tmp')) continue;
511
+ const file = join(STORAGE_DIR, name);
512
+ try {
513
+ if (now - statSync(file).mtimeMs <= AGENT_TEMP_MAX_AGE_MS) continue;
514
+ unlinkSync(file);
515
+ swept += 1;
516
+ } catch {
517
+ // vanished between the readdir and the stat/unlink, or the store is not
518
+ // writable — leave it for the next boot.
519
+ }
520
+ }
521
+ return swept;
522
+ }
523
+
473
524
  /**
474
525
  * Retain `dir` for the #401 resume preamble: brand it with the retention marker
475
526
  * (its mtime is the recency source) and enforce the caps.
@@ -530,11 +581,16 @@ function persistAgent(agent: BackgroundAgent): void {
530
581
  // persisted record field (D4).
531
582
  const { _sessionRef, _sessionFile, ...persistable } = agent;
532
583
  try {
584
+ // Issue #554: atomic (temp+rename) so a SIGKILL between the truncate and the
585
+ // write cannot leave a torn record. `mode` is applied on the temp and
586
+ // survives the rename (the inode changes; the record is still `0o600`).
533
587
  // F6 (issue #29): records contain task, error, result.messages (full
534
588
  // conversation) and finalOutput — write owner-only (0o600) so other local
535
589
  // users cannot read subagent tasks/output. mode applies on file CREATE;
536
- // pre-existing files keep their old mode (not retroactive).
537
- writeFileSync(filePath, JSON.stringify(persistable, null, 2), { encoding: 'utf-8', mode: 0o600 });
590
+ // pre-existing files keep their old mode (not retroactive) — and a
591
+ // read-only record no longer blocks the write: a writable DIRECTORY does
592
+ // (issue #554's accepted permission-contract change).
593
+ writeFileAtomicSync(filePath, JSON.stringify(persistable, null, 2));
538
594
  } catch (err) {
539
595
  // Log but never throw — persistence must not break execution
540
596
  log.error(`Failed to persist agent ${agent.id}`, { error: err instanceof Error ? err.message : String(err) });
@@ -562,6 +618,14 @@ function agentRecordPath(id: string): string | null {
562
618
  return join(STORAGE_DIR, `${id}.json`);
563
619
  }
564
620
 
621
+ /** The tri-state record read plus the #554 named failure kind. */
622
+ export interface AgentRecordRead {
623
+ record: BackgroundAgent | null;
624
+ exists: boolean;
625
+ /** `"corrupt"` when the bytes are not JSON; `"unreadable"` when stat/read failed. */
626
+ reason?: AgentRecordFailureReason;
627
+ }
628
+
565
629
  /**
566
630
  * Issue #546 (major 2): the disk-only, TRI-STATE read of one agent record.
567
631
  *
@@ -570,8 +634,14 @@ function agentRecordPath(id: string): string | null {
570
634
  * go stale (retire the marker), the second means we know nothing (keep it).
571
635
  * `exists` is the stat of the validated path, so a chmod-000 or corrupt file
572
636
  * reports `{ record: null, exists: true }`.
637
+ *
638
+ * Issue #554: the two failure kinds are NAMED on the result (`reason`) instead
639
+ * of being collapsed — `"corrupt"` (the file read but JSON.parse rejected it:
640
+ * repair the file) vs `"unreadable"` (stat/read failed: fix permissions or the
641
+ * filesystem). The flip's decisions are unchanged; only the boot ledger can now
642
+ * count the corrupt subset by name.
573
643
  */
574
- export function readAgentRecordFromDisk(id: string): { record: BackgroundAgent | null; exists: boolean } {
644
+ export function readAgentRecordFromDisk(id: string): AgentRecordRead {
575
645
  const filePath = agentRecordPath(id);
576
646
  if (!filePath) return { record: null, exists: false };
577
647
  try {
@@ -586,12 +656,23 @@ export function readAgentRecordFromDisk(id: string): { record: BackgroundAgent |
586
656
  log.warn(`Could not stat agent record ${id} — treating it as unreadable`, {
587
657
  error: err instanceof Error ? err.message : String(err),
588
658
  });
589
- return { record: null, exists: true };
659
+ return { record: null, exists: true, reason: 'unreadable' };
660
+ }
661
+ let text: string;
662
+ try {
663
+ text = readFileSync(filePath, 'utf-8');
664
+ } catch (err) {
665
+ log.warn(`Could not read agent record ${id} — treating it as unreadable`, {
666
+ error: err instanceof Error ? err.message : String(err),
667
+ });
668
+ return { record: null, exists: true, reason: 'unreadable' };
590
669
  }
591
670
  try {
592
- return { record: JSON.parse(readFileSync(filePath, 'utf-8')), exists: true };
671
+ return { record: JSON.parse(text), exists: true };
593
672
  } catch {
594
- return { record: null, exists: true };
673
+ // The bytes are there and they are not JSON (a torn write before #554, or a
674
+ // zero-byte file). Never repaired or retired here — the count names them.
675
+ return { record: null, exists: true, reason: 'corrupt' };
595
676
  }
596
677
  }
597
678
 
@@ -702,6 +783,9 @@ export const RETRY_IDENTITY_KEYS: ReadonlySet<string> = new Set([
702
783
  'attempt',
703
784
  'status',
704
785
  'startedAt',
786
+ // Issue #616: the retry cause. Read by the shallow scanner so a dispatch-scoped
787
+ // stop can scope itself to `transport` without a full record parse.
788
+ 'retryCause',
705
789
  ]);
706
790
 
707
791
  const AGENT_STATUSES: ReadonlySet<string> = new Set([
@@ -722,6 +806,12 @@ export interface RetryRecordIdentity {
722
806
  status: AgentStatus;
723
807
  /** Epoch milliseconds (agent records store ms; registry ISO is normalised). */
724
808
  startedAt: number;
809
+ /**
810
+ * Issue #616: why this attempt exists, when the record says. ABSENT means
811
+ * UNKNOWN — neither cause is assumed, and unknown is never the stop-scoped
812
+ * `transport`.
813
+ */
814
+ retryCause?: RetryCause;
725
815
  }
726
816
 
727
817
  export type AgentIdResolution =
@@ -739,6 +829,13 @@ export interface RetryLineage {
739
829
  latest: RetryRecordIdentity | null;
740
830
  /** Registry entries that name the id itself or a member of its family. */
741
831
  inflight: InflightRun[];
832
+ /**
833
+ * Issue #616 (Q7): whether the scan was TRUNCATED, which is what a caller
834
+ * needs to avoid printing a universal claim over a partial read. `capped` is
835
+ * the `RETRY_SCAN_CAP` cut; a record older than `windowDays` is the caller's
836
+ * own check (it knows the requested record's `startedAt`).
837
+ */
838
+ bounds: { capped: boolean; windowDays: number };
742
839
  }
743
840
 
744
841
  function isSafeAgentId(id: string): boolean {
@@ -757,7 +854,9 @@ function isSafeAgentId(id: string): boolean {
757
854
  export type AgentFlipOutcome = 'repaired' | 'retired' | false;
758
855
 
759
856
  export function isTerminalAgentStatus(status: AgentStatus): boolean {
760
- return status === 'completed' || status === 'failed' || status === 'stopped';
857
+ // Issue #616: the vocabulary lives in `types.ts` (one definition, two readers —
858
+ // this export and the stop contract's post-stop verification).
859
+ return isTerminalAgentStatusValue(status);
761
860
  }
762
861
 
763
862
  function isAgentStatus(value: unknown): value is AgentStatus {
@@ -1040,6 +1139,7 @@ function readAgentIdentity(file: string): RetryRecordIdentity | null {
1040
1139
 
1041
1140
  const dispatchId = fields.get('dispatchId');
1042
1141
  const resumeOf = fields.get('resumeOf');
1142
+ const retryCause = fields.get('retryCause');
1043
1143
  return {
1044
1144
  id,
1045
1145
  status,
@@ -1047,6 +1147,8 @@ function readAgentIdentity(file: string): RetryRecordIdentity | null {
1047
1147
  attempt,
1048
1148
  ...(typeof dispatchId === 'string' ? { dispatchId } : {}),
1049
1149
  ...(typeof resumeOf === 'string' ? { resumeOf } : {}),
1150
+ // Issue #616: an unrecognized cause is ABSENT (unknown), never coerced.
1151
+ ...(retryCause === 'transport' || retryCause === 'manual' ? { retryCause } : {}),
1050
1152
  };
1051
1153
  }
1052
1154
 
@@ -1054,14 +1156,18 @@ function readAgentIdentity(file: string): RetryRecordIdentity | null {
1054
1156
  * The bounded store read: stat every record (cheap), keep the ones inside the
1055
1157
  * mtime window, sort newest-first, cap at `RETRY_SCAN_CAP`, then read only the
1056
1158
  * surviving files' identity fields. Corrupt/unsafe records are skipped.
1159
+ *
1160
+ * `capped` reports whether the CAP cut anything (issue #616, Q7): a caller that
1161
+ * makes a universal claim over the answer must be able to say the scan was
1162
+ * truncated.
1057
1163
  */
1058
- function readRecentAgentIdentities(): RetryRecordIdentity[] {
1164
+ function readRecentAgentIdentities(): { records: RetryRecordIdentity[]; capped: boolean } {
1059
1165
  let files: string[];
1060
1166
  try {
1061
- if (!existsSync(STORAGE_DIR)) return [];
1167
+ if (!existsSync(STORAGE_DIR)) return { records: [], capped: false };
1062
1168
  files = readdirSync(STORAGE_DIR);
1063
1169
  } catch {
1064
- return [];
1170
+ return { records: [], capped: false };
1065
1171
  }
1066
1172
 
1067
1173
  const cutoff = Date.now() - RETRY_SCAN_WINDOW_MS;
@@ -1080,12 +1186,13 @@ function readRecentAgentIdentities(): RetryRecordIdentity[] {
1080
1186
  }
1081
1187
 
1082
1188
  recent.sort((a, b) => b.mtime - a.mtime);
1189
+ const capped = recent.length > RETRY_SCAN_CAP;
1083
1190
  const records: RetryRecordIdentity[] = [];
1084
1191
  for (const entry of recent.slice(0, RETRY_SCAN_CAP)) {
1085
1192
  const record = readAgentIdentity(entry.file);
1086
1193
  if (record) records.push(record);
1087
1194
  }
1088
- return records;
1195
+ return { records, capped };
1089
1196
  }
1090
1197
 
1091
1198
  function identityFromAgent(agent: BackgroundAgent): RetryRecordIdentity | null {
@@ -1098,6 +1205,7 @@ function identityFromAgent(agent: BackgroundAgent): RetryRecordIdentity | null {
1098
1205
  attempt: agent.attempt ?? 1,
1099
1206
  ...(agent.dispatchId ? { dispatchId: agent.dispatchId } : {}),
1100
1207
  ...(agent.resumeOf ? { resumeOf: agent.resumeOf } : {}),
1208
+ ...(agent.retryCause ? { retryCause: agent.retryCause } : {}),
1101
1209
  };
1102
1210
  }
1103
1211
 
@@ -1106,13 +1214,35 @@ function identityFromRegistry(run: InflightRun): RetryRecordIdentity | null {
1106
1214
  if (startedAt === null) return null;
1107
1215
  return {
1108
1216
  id: run.id,
1217
+ // The registry has no status field: an entry being present IS the claim that
1218
+ // the run is in flight. Review 624 (F4): that claim is the WEAKEST one in the
1219
+ // family and is only used when no persisted record exists — see the fold in
1220
+ // `findRetryLineage`.
1109
1221
  status: 'running',
1110
1222
  startedAt,
1111
1223
  attempt: run.attempt ?? 1,
1112
1224
  ...(run.dispatchId ? { dispatchId: run.dispatchId } : {}),
1225
+ ...(run.retryCause ? { retryCause: run.retryCause } : {}),
1113
1226
  };
1114
1227
  }
1115
1228
 
1229
+ /**
1230
+ * The persisted identity for `id`, read OUTSIDE the shallow scan window.
1231
+ *
1232
+ * Review 624 (F4): `readRecentAgentIdentities` is bounded (7-day mtime window,
1233
+ * 200-record cap), so a record can be absent from it while its registry entry
1234
+ * survives — the crash-residue shape. One targeted read per registry entry (a
1235
+ * handful at most, never a scan) makes "the persisted record wins" independent
1236
+ * of that window. A record whose embedded id disagrees with its file name is not
1237
+ * this run's record and is ignored.
1238
+ */
1239
+ function persistedIdentityFor(id: string): RetryRecordIdentity | null {
1240
+ const file = agentRecordPath(id);
1241
+ if (!file) return null;
1242
+ const persisted = readAgentIdentity(file);
1243
+ return persisted && persisted.id === id ? persisted : null;
1244
+ }
1245
+
1116
1246
  /**
1117
1247
  * Find the logical dispatch family for `id`.
1118
1248
  *
@@ -1122,20 +1252,34 @@ function identityFromRegistry(run: InflightRun): RetryRecordIdentity | null {
1122
1252
  * in so an in-flight retry is visible without a store record.
1123
1253
  */
1124
1254
  export function findRetryLineage(id: string, source?: BackgroundAgent | null): RetryLineage {
1125
- const empty: RetryLineage = { id, family: [], found: null, latest: null, inflight: [] };
1255
+ const empty: RetryLineage = {
1256
+ id,
1257
+ family: [],
1258
+ found: null,
1259
+ latest: null,
1260
+ inflight: [],
1261
+ bounds: { capped: false, windowDays: RETRY_SCAN_WINDOW_DAYS },
1262
+ };
1126
1263
  if (!isSafeAgentId(id)) return empty;
1127
1264
 
1265
+ const scan = readRecentAgentIdentities();
1128
1266
  const byId = new Map<string, RetryRecordIdentity>();
1129
- for (const record of readRecentAgentIdentities()) byId.set(record.id, record);
1267
+ for (const record of scan.records) byId.set(record.id, record);
1130
1268
 
1131
1269
  const sourceIdentity = source && source.id === id ? identityFromAgent(source) : null;
1132
1270
  if (sourceIdentity) byId.set(id, sourceIdentity);
1133
1271
 
1134
1272
  const registry = safeListInflightRuns();
1135
1273
  for (const run of registry) {
1136
- const identity = identityFromRegistry(run);
1137
- // A persisted record is authoritative over the registry's "running" view.
1138
- if (identity && !byId.has(identity.id)) byId.set(identity.id, identity);
1274
+ if (byId.has(run.id)) continue;
1275
+ // Review 624 (F4): a PERSISTED record is authoritative over the registry's
1276
+ // hardcoded `running` — even when the record fell outside the shallow scan
1277
+ // (its 7-day window or its 200-record cap). Without this, crash residue (a
1278
+ // registry entry outliving a terminal record) planned the terminal attempt as
1279
+ // live, `stopAgent` returned it unchanged, and the report printed
1280
+ // "Stopped agent …" for an attempt that was already dead.
1281
+ const identity = persistedIdentityFor(run.id) ?? identityFromRegistry(run);
1282
+ if (identity) byId.set(identity.id, identity);
1139
1283
  }
1140
1284
 
1141
1285
  const all = [...byId.values()];
@@ -1161,7 +1305,14 @@ export function findRetryLineage(id: string, source?: BackgroundAgent | null): R
1161
1305
  (run) => run.id === id || (familyDispatch !== undefined && run.dispatchId === familyDispatch),
1162
1306
  );
1163
1307
 
1164
- return { id, family, found, latest, inflight };
1308
+ return {
1309
+ id,
1310
+ family,
1311
+ found,
1312
+ latest,
1313
+ inflight,
1314
+ bounds: { capped: scan.capped, windowDays: RETRY_SCAN_WINDOW_DAYS },
1315
+ };
1165
1316
  }
1166
1317
 
1167
1318
  /**
@@ -1180,6 +1331,32 @@ export function markAgentInterrupted(id: string, interruptedAt: string): Backgro
1180
1331
  return agent;
1181
1332
  }
1182
1333
 
1334
+ /**
1335
+ * Issue #574: state the run's KIND on the record, so the status flip that
1336
+ * follows persists it. A deadline and a user stop are both `status:"stopped"`;
1337
+ * only the category tells the two frictions apart.
1338
+ *
1339
+ * WHY BEFORE THE FLIP AND NOT AFTER: `updateAgentStatus` persists the record
1340
+ * itself, so a stamp written afterwards is absent from the bytes an observer
1341
+ * reads at the flip — and never lands at all if the settle that would write it
1342
+ * never arrives (a real stop is exactly that case: `stopAgent` persists
1343
+ * `stopped` before any abort settles).
1344
+ *
1345
+ * The `agents.set` is load-bearing: `getAgent` is memory-first, so a record that
1346
+ * exists only on disk would be re-loaded WITHOUT this stamp between the call and
1347
+ * its persist. Re-inserting the stamped object makes the flip write what this
1348
+ * function just said.
1349
+ */
1350
+ function stampAgentKind(
1351
+ agent: BackgroundAgent,
1352
+ errorCategory: ErrorCategory,
1353
+ stopReason: string,
1354
+ ): void {
1355
+ agent.errorCategory = errorCategory;
1356
+ agent.stopReason = stopReason;
1357
+ agents.set(agent.id, agent);
1358
+ }
1359
+
1183
1360
  /**
1184
1361
  * Update agent status
1185
1362
  */
@@ -1426,6 +1603,11 @@ export async function stopAgent(id: string): Promise<BackgroundAgent | null> {
1426
1603
  return agent;
1427
1604
  }
1428
1605
 
1606
+ // Issue #574: the KIND comes before the flip that persists it — this is the
1607
+ // earliest observable point of a user stop (the abort settles later, if at
1608
+ // all).
1609
+ stampAgentKind(agent, 'aborted', 'aborted');
1610
+
1429
1611
  // Mark stopped BEFORE aborting so the spawnBackgroundSession .then handler
1430
1612
  // (which fires after the run settles) keeps the stopped state.
1431
1613
  updateAgentStatus(id, 'stopped');
@@ -1574,6 +1756,11 @@ export async function spawnBackgroundSession(
1574
1756
  dispatchId?: string;
1575
1757
  resumeOf?: string;
1576
1758
  attempt?: number;
1759
+ /** Issue #616: why this attempt exists — `transport` for the automatic
1760
+ * background retry, `manual` for a caller-driven `retryRunId` retry. Absent
1761
+ * on a first dispatch, and then it reads as UNKNOWN (never `transport`).
1762
+ * Recorded on the agent record, the run entry and the registry entry. */
1763
+ retryCause?: RetryCause;
1577
1764
  /** Option B U3 (D4): recovery posture at dispatch — snapshotted onto the
1578
1765
  * agent record + run entry so the boot notice reads the posture the run
1579
1766
  * was actually dispatched under. Absent reads as "offer". */
@@ -1602,26 +1789,23 @@ export async function spawnBackgroundSession(
1602
1789
 
1603
1790
  try {
1604
1791
  const id = generateUUID();
1605
- // Issue #511 (U2): the scratch seam for the BACKGROUND surface. This function
1606
- // is the single place a background agent record and run entry are created
1607
- // (single, fan-out and the transport retry all pass through it), so the run's
1608
- // directory is resolved and created HERE — before the SDK is asked for a
1609
- // session, and therefore before `session.prompt()` can start the child.
1792
+ // Issue #620: the conductor's required background guard is RESOLVED AND
1793
+ // CONTAINED here — before the SDK is imported, before the loader exists, and
1794
+ // therefore before any agent record or run entry can exist. The resolution
1795
+ // root is `ctx.cwd` (the CONDUCTOR's project), never `params.cwd` — the child's
1796
+ // directory is model-chosen, so a guard resolved against it would be a guard
1797
+ // the model chooses. A missing, escaping or malformed guard throws here and
1798
+ // the pipeline's existing catch renders it as an ordinary spawn failure.
1610
1799
  //
1611
- // A refusal is PRE-SPAWN and NAMED: it throws before any record exists, and
1612
- // both pipeline callers translate a throw from this function into their
1613
- // ordinary "Failed to spawn background agent: …" result — the same shape as
1614
- // every other spawn failure.
1615
- //
1616
- // NOTE, stated rather than implied: a background run is an IN-PROCESS SDK
1617
- // session, so there is no child environment to carry `BRL_SCRATCH` (the SDK
1618
- // composes the shell env from `process.env` at command time, which a per-run
1619
- // value cannot vary without race). The directory and the record's
1620
- // `scratchDir` are this surface's whole carrier.
1621
- const scratch = prepareRunScratch(id, { log });
1622
- if (!scratch.ok) {
1623
- throw new Error(`scratch root unavailable (${scratch.code}): ${scratch.message}`);
1624
- }
1800
+ // ORDER, stated because it is load-bearing twice: resolve → reload → verify →
1801
+ // scratch → createAgentSession. The scratch directory is created AFTER the
1802
+ // guard is verified (PR #627 review, F3), so a refused spawn — missing, broken
1803
+ // or handler-less guard — leaves NO `runs/<uuid>` directory behind, matching the
1804
+ // "no agent record, no run entry" promise both refusals make. Nothing between
1805
+ // the resolver and the verifier needs the directory: the loader and the session
1806
+ // manager are given `effectiveCwd`, not the scratch path.
1807
+ const guardName = readRequiredGuard(ctx.cwd);
1808
+ const guardPath = guardName === null ? null : resolveGuardPath(ctx.cwd, guardName);
1625
1809
  const effectiveCwd = params.cwd ?? ctx.cwd;
1626
1810
  // Dynamic import — static import fails under concurrent jiti loads
1627
1811
  const { getAgentDir, createAgentSession, SessionManager, SettingsManager, DefaultResourceLoader } = await import('@earendil-works/pi-coding-agent');
@@ -1715,6 +1899,12 @@ export async function spawnBackgroundSession(
1715
1899
  // deliberate security choice: background sessions have no trust prompt, so
1716
1900
  // nothing is imported from anywhere — the prompt is fully specified by the
1717
1901
  // caller. Users needing skills/extensions should use foreground delegation.
1902
+ //
1903
+ // Issue #620 is the ONE exception, and it is not a discovery path: the
1904
+ // conductor's project NAMED a guard in its own manifest, `resolveGuardPath`
1905
+ // turned that name into one absolute, contained, realpathed file, and no key
1906
+ // at all is added otherwise. F5: a relative entry would resolve against the
1907
+ // loader's cwd — the CHILD's — so the entry is absolute by construction.
1718
1908
  const loader = new DefaultResourceLoader({
1719
1909
  cwd: effectiveCwd,
1720
1910
  agentDir,
@@ -1722,8 +1912,44 @@ export async function spawnBackgroundSession(
1722
1912
  ...(sections.length ? { appendSystemPrompt: sections } : {}),
1723
1913
  noExtensions: true,
1724
1914
  noSkills: true,
1915
+ ...(guardPath === null ? {} : { additionalExtensionPaths: [guardPath] }),
1725
1916
  });
1726
1917
  await loader.reload();
1918
+ // Issue #620: loading is not registration (F9: `reload()` never throws). The
1919
+ // named guard is verified BEFORE createAgentSession, so an absent, errored or
1920
+ // handler-less guard refuses the spawn rather than producing a run that looks
1921
+ // guarded and is not. A refusal here throws before any agent record.
1922
+ if (guardPath !== null) {
1923
+ verifyGuardLoaded(loader, guardPath);
1924
+ log.info("Background guard verified", {
1925
+ agentId: id,
1926
+ guard: guardName,
1927
+ path: guardPath,
1928
+ handlers: ["tool_call", "before_agent_start"],
1929
+ });
1930
+ }
1931
+ // Issue #511 (U2): the scratch seam for the BACKGROUND surface, reached only
1932
+ // once the guard is verified (F3 of the PR #627 review: a refused spawn must not
1933
+ // leave an orphan run directory). This function is the single place a background
1934
+ // agent record and run entry are created (single, fan-out and the transport retry
1935
+ // all pass through it), so the run's directory is resolved and created HERE —
1936
+ // before the SDK is asked for a session, and therefore before `session.prompt()`
1937
+ // can start the child.
1938
+ //
1939
+ // A refusal is PRE-SPAWN and NAMED: it throws before any record exists, and
1940
+ // both pipeline callers translate a throw from this function into their
1941
+ // ordinary "Failed to spawn background agent: …" result — the same shape as
1942
+ // every other spawn failure.
1943
+ //
1944
+ // NOTE, stated rather than implied: a background run is an IN-PROCESS SDK
1945
+ // session, so there is no child environment to carry `BRL_SCRATCH` (the SDK
1946
+ // composes the shell env from `process.env` at command time, which a per-run
1947
+ // value cannot vary without race). The directory and the record's
1948
+ // `scratchDir` are this surface's whole carrier.
1949
+ const scratch = prepareRunScratch(id, { log });
1950
+ if (!scratch.ok) {
1951
+ throw new Error(`scratch root unavailable (${scratch.code}): ${scratch.message}`);
1952
+ }
1727
1953
  const resourceLoader: InstanceType<typeof DefaultResourceLoader> = loader;
1728
1954
 
1729
1955
  // Create the session — honor the resolved tool restrictions so the
@@ -1798,6 +2024,10 @@ export async function spawnBackgroundSession(
1798
2024
  dispatchId,
1799
2025
  resumeOf: params.resumeOf,
1800
2026
  attempt,
2027
+ // Issue #616: the retry's cause, persisted on the record so a
2028
+ // dispatch-scoped stop can scope itself to automatic transport retries and
2029
+ // never to a manual one. Absent on a first dispatch (⇒ unknown).
2030
+ retryCause: params.retryCause,
1801
2031
  owner,
1802
2032
  // Option B U3 (D4): per-run recovery posture snapshot. Additive — absent
1803
2033
  // reads as "offer" via `runRecoveryPosture`/the notice collector.
@@ -1832,6 +2062,7 @@ export async function spawnBackgroundSession(
1832
2062
  dispatchId,
1833
2063
  resumeOf: params.resumeOf,
1834
2064
  attempt,
2065
+ retryCause: params.retryCause,
1835
2066
  owner,
1836
2067
  recoveryPosture: params.recoveryPosture,
1837
2068
  // Issue #511 (U2): the run's scratch directory (`<root>/runs/<id>`, 0700),
@@ -2044,6 +2275,13 @@ export async function spawnBackgroundSession(
2044
2275
  entryWritten = true;
2045
2276
  // Issue #179 (D6): the explicit settle line — the log's job is to record the
2046
2277
  // CLASSIFIED OUTCOME, which cwd alone can never convey.
2278
+ // Issue #556: the row carries the LINEAGE too. Without it the only way to
2279
+ // group a retry with what it resumed was spawn adjacency in the log, which
2280
+ // reads wrong across concurrent runs — the durable records had the answer
2281
+ // and the log did not. `attempt` defaults to the documented 1 (a record
2282
+ // written before the field existed IS a first attempt); `resumeOf` is
2283
+ // OMITTED, never null: an absent key is what "this run resumed nothing"
2284
+ // looks like, and a null would read as a lookup that failed.
2047
2285
  log.info("Background run settled", {
2048
2286
  agentId: id,
2049
2287
  status,
@@ -2052,6 +2290,8 @@ export async function spawnBackgroundSession(
2052
2290
  tokensOut: usage.output,
2053
2291
  errorCategory,
2054
2292
  error: error ?? null,
2293
+ attempt: entry.attempt ?? 1,
2294
+ ...(entry.resumeOf !== undefined ? { resumeOf: entry.resumeOf } : {}),
2055
2295
  });
2056
2296
  return entry;
2057
2297
  };
@@ -2306,6 +2546,61 @@ export async function spawnBackgroundSession(
2306
2546
  `${PROMPT_NEVER_ISSUED_MESSAGE}: ` +
2307
2547
  sanitizeErrorMessage(err instanceof Error ? err.message : String(err), effectiveCwd);
2308
2548
 
2549
+ /**
2550
+ * Issue #616 (Q3): settle a retry whose cancel was found at the pre-prompt
2551
+ * gate. The prompt is NEVER issued, so no deadline is armed yet and there is
2552
+ * no live session to abort — the record, the run entry and the transcript are
2553
+ * the whole settlement, and the status is `stopped` (this is a stop, not a
2554
+ * failure).
2555
+ *
2556
+ * ORDER: record flip → run entry → transcript, each contained separately, so a
2557
+ * throw in one cannot suppress another and cannot escape as the spawn result.
2558
+ * The run-entry write retires the registry entry (its status is terminal) and
2559
+ * prunes the per-run session dir — safe here for the same reason `failPreStart`
2560
+ * documents: the prompt was provably never issued, so nothing can be writing
2561
+ * to that directory and no retry will be offered for this run.
2562
+ *
2563
+ * ACCEPTED RESIDUE (stated, not papered over): a crash between these writes
2564
+ * leaves either a terminal record with a `running` run entry or a `running`
2565
+ * record with a retired entry. Both are the ordinary #439/#546 residue class
2566
+ * and neither is repairable by the boot scan — the window is three synchronous
2567
+ * statements wide.
2568
+ */
2569
+ const settleCancelledRetry = (): void => {
2570
+ const reason = CANCELLED_RETRY_MESSAGE;
2571
+ try {
2572
+ // Issue #574: the KIND precedes the flip that persists it, exactly as
2573
+ // `stopAgent` does for a user stop.
2574
+ stampAgentKind(agent, 'aborted', 'aborted');
2575
+ updateAgentStatus(id, 'stopped', reason);
2576
+ } catch (err) {
2577
+ safeLog(() =>
2578
+ log.warn(`spawnBackgroundSession: cancelled-retry record flip failed for ${id}`, {
2579
+ error: thrownMessage(err),
2580
+ }),
2581
+ );
2582
+ }
2583
+ try {
2584
+ finalizeRunEntry('failed', reason, { stopReason: 'aborted', errorCategory: 'aborted' });
2585
+ } catch (err) {
2586
+ safeLog(() =>
2587
+ log.warn(`spawnBackgroundSession: cancelled-retry run entry failed for ${id}`, {
2588
+ error: thrownMessage(err),
2589
+ }),
2590
+ );
2591
+ }
2592
+ try {
2593
+ transcript.completeTranscript(id, 'stopped');
2594
+ } catch (err) {
2595
+ safeLog(() =>
2596
+ log.warn(`spawnBackgroundSession: cancelled-retry transcript note failed for ${id}`, {
2597
+ error: thrownMessage(err),
2598
+ }),
2599
+ );
2600
+ }
2601
+ agent._sessionRef = undefined; // outside every try — cannot throw, must always run
2602
+ };
2603
+
2309
2604
  // Start transcript for this agent. Issue #447 (S2): a throw here used to
2310
2605
  // leave a `running` run entry and a live registry entry that the next boot
2311
2606
  // offered as an interrupted, retryable run — clean it and rethrow.
@@ -2568,6 +2863,18 @@ export async function spawnBackgroundSession(
2568
2863
  gitInfo: { gitBranch?: string; gitDiff?: string },
2569
2864
  stopReason: string,
2570
2865
  ): void => {
2866
+ // Issue #574: FILL ONLY — never re-classify. `updateAgentStatus` already
2867
+ // persisted the kind at the flip; this shared helper runs for BOTH a user
2868
+ // stop and a deadline, and a deadline's kind is `timeout`, so an
2869
+ // unconditional stamp here would overwrite it and lose the friction. The
2870
+ // stamp is for a record that reached the abort settle with NO kind (a
2871
+ // status flipped by a path that did not classify) — and only that.
2872
+ if (!agent.errorCategory) {
2873
+ agent.errorCategory = 'aborted';
2874
+ agent.stopReason = 'aborted';
2875
+ agents.set(id, agent);
2876
+ persistAgent(agent);
2877
+ }
2571
2878
  // W4/M1: capture whatever the branch produced before discarding it — an
2572
2879
  // aborted background agent's partial work is still worth reviewing, and
2573
2880
  // must be RECORDED, not just captured-and-deleted.
@@ -2717,6 +3024,9 @@ export async function spawnBackgroundSession(
2717
3024
  setTimeout(() => {
2718
3025
  if (agent.completedAt) return; // already settled — nothing to abort
2719
3026
  const reason = `Timed out after ${budgetMs}ms`;
3027
+ // Issue #574: the deadline states its OWN kind before the flip persists
3028
+ // it — the snapshot below lands later and may not land at all.
3029
+ stampAgentKind(agent, 'timeout', 'aborted');
2720
3030
  let bookkeepingFailure: unknown;
2721
3031
  try {
2722
3032
  updateAgentStatus(id, 'stopped', reason);
@@ -2772,6 +3082,65 @@ export async function spawnBackgroundSession(
2772
3082
  }
2773
3083
  }, delayMs);
2774
3084
 
3085
+ // ---------------------------------------------------------------------
3086
+ // Issue #616 (Q3): THE ARMED-RETRY CANCEL GATE.
3087
+ //
3088
+ // The automatic transport retry is unaddressable between its id being minted
3089
+ // (above) and its agent record landing: nothing durable names it, so a
3090
+ // `stop_subagent` of the dispatch can only reach the dead attempt 1. The
3091
+ // arming site (`scheduleTransportRetry`) therefore records a durable INTENT
3092
+ // before the spawn, and a stop that finds it sets the cancel. This is where
3093
+ // that cancel is honoured — before the deadline is armed and before the
3094
+ // ACCEPTANCE write, so a cancelled retry never claims `acceptedAt` and never
3095
+ // reaches `session.prompt()`.
3096
+ //
3097
+ // The check reads the marker KEYED BY THE SOURCE RUN (`params.resumeOf`,
3098
+ // inherited through `newDispatchIdentity`), not by our own id — our id is the
3099
+ // thing the marker had to be written without.
3100
+ //
3101
+ // THE SLIVER, AFTER review 624 r2: TWO checks cover the whole gate -> prompt
3102
+ // path. A stop landing before the marker check is honoured by it; one landing
3103
+ // after it but before the prompt can only flip the RECORD (see the belt below)
3104
+ // and is caught by the status read. What remains between that read and the
3105
+ // `session.prompt()` call is ATOMIC UNTIL THE FIRST `await` (the rest of the
3106
+ // path is hundreds of lines but zero awaits, so a racing stop in this process
3107
+ // cannot interleave inside it); a stop landing after the prompt falls back on
3108
+ // the record and the live session.
3109
+ // ---------------------------------------------------------------------
3110
+ //
3111
+ // BOTH the check and the clear are gated on `retryCause === "transport"`: the
3112
+ // marker is armed by, and describes, the AUTOMATIC retry only. A caller-driven
3113
+ // retry of the same source lands on the same `resumeOf`/`attempt` pair, and it
3114
+ // must neither consume another retry's cancel nor clear its intent.
3115
+ const armedRetrySource =
3116
+ params.resumeOf && params.retryCause === 'transport' ? params.resumeOf : undefined;
3117
+ const markerCancelled = !!armedRetrySource && isRetryCancelRequested(armedRetrySource, attempt);
3118
+ // ---------------------------------------------------------------------
3119
+ // Review 624 r2 (B1, THE BELT): a stop that landed between this run's record
3120
+ // write (above) and this gate could only FLIP THE RECORD — `session.abort()`
3121
+ // is a no-op on a session with no active run (the SDK aborts `activeRun`
3122
+ // only), and this run has not prompted yet. The stretch in between is not
3123
+ // small: the spawn queue and, for gitMode 'branch', another run's repository
3124
+ // lock can hold it for minutes, and the age rule above deliberately never
3125
+ // reclaims a cancel, so it cannot cover this case. The record can, and needs
3126
+ // no marker: if our OWN agent is already terminal, the prompt must not be
3127
+ // issued.
3128
+ //
3129
+ // Together with the marker check this settles the whole post-record /
3130
+ // pre-prompt stretch: before the marker clear the cancel is honoured here,
3131
+ // after it the cancel reaches the record and is caught by this line.
3132
+ // ---------------------------------------------------------------------
3133
+ const stoppedBeforePrompt = isTerminalAgentStatus(agent.status);
3134
+ // Past this line the retry IS addressable by its own id — the agent record and
3135
+ // the registry entry are durable — so the intent marker has done its job and
3136
+ // must go. Otherwise a later stop would keep disclosing an "armed" retry that
3137
+ // is in fact a normal running record.
3138
+ if (armedRetrySource) clearArmedRetry(armedRetrySource, attempt);
3139
+ if (markerCancelled || stoppedBeforePrompt) {
3140
+ settleCancelledRetry();
3141
+ return agent;
3142
+ }
3143
+
2775
3144
  // Issue #453 (ADR 0023, decision 1): ONE owner. This function arms the run's
2776
3145
  // deadline on EVERY path — the explicit timeout when there is one, else the
2777
3146
  // 30 m default — and no caller arms a second one (`deadlineOwner` is gone with
@@ -2867,6 +3236,9 @@ export async function spawnBackgroundSession(
2867
3236
  // status (pre-set 'stopped' + completedAt + event + transcript), only
2868
3237
  // the transcript note is missing from this path.
2869
3238
  if (agent.status !== 'stopped') {
3239
+ // Issue #574: this branch calls the flip itself, so it states the kind
3240
+ // first — otherwise the record would be 'stopped' with no category.
3241
+ stampAgentKind(agent, 'aborted', 'aborted');
2870
3242
  updateAgentStatus(id, 'stopped');
2871
3243
  transcript.completeTranscript(id, 'stopped');
2872
3244
  }