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
@@ -1,29 +1,33 @@
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,
23
+ type SubagentUsageGroup,
20
24
  type ThinkingLevel,
21
25
  type SubagentToolOptions,
22
26
  type UsageStats,
23
27
  type ErrorCategory,
24
28
  type AssistantEvidence,
25
29
  } from './types';
26
- import { accumulateUsage } from './runner';
30
+ import { sumUsageGroups, usageGroupsFromSession } from './runner';
27
31
  import * as eventBus from './event-bus';
28
32
  import * as transcript from './transcript';
29
33
  import { createEvent } from './event-bus';
@@ -46,9 +50,10 @@ import {
46
50
  } from './git';
47
51
  import { clearHeadState, readHeadState, writeHeadState, HEAD_STATE_VERSION } from './headstate';
48
52
  import { effectiveBackgroundBudget } from './validate';
49
- import { currentProcessOwner, classifyOwner, defaultRecoveryDeps } from './recovery';
53
+ import { currentProcessOwner, classifyOwner, defaultRecoveryDeps, type AgentRecordFailureReason } from './recovery';
50
54
  import {
51
55
  persistRunRecord,
56
+ persistSettledRunRecord,
52
57
  listInflightRuns,
53
58
  clearInflightRun,
54
59
  markRecordFlipPending,
@@ -57,8 +62,11 @@ import {
57
62
  } from './run-registry';
58
63
  import { isTransportRetryable } from './transport-retry';
59
64
  import { ensureOwnerOnlyDir, repairOwnerOnlyFiles } from './store-permissions';
65
+ import { writeFileAtomicSync } from './atomic-write';
60
66
  import { buildEngineeringBarSection } from './engineering-bar';
61
67
  import { prepareRunScratch, markSettled } from './scratch-spawn';
68
+ import { readRequiredGuard, resolveGuardPath, verifyGuardLoaded } from './background-guard';
69
+ import { clearArmedRetry, isRetryCancelRequested } from './retry-armed';
62
70
 
63
71
  const log = createLogger('brl-subagent');
64
72
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
@@ -470,6 +478,51 @@ function sweepRetainedSessions(currentDir: string): void {
470
478
  }
471
479
  }
472
480
 
481
+ // ---------------------------------------------------------------------------
482
+ // Issue #554: temp residue from the atomic record writer.
483
+ //
484
+ // A SIGKILL cannot run `writeFileAtomicSync`'s cleanup, so `.tmp` siblings
485
+ // accumulate in the agent store (measured: 8 leftovers in 20 kills). The record
486
+ // scans filter `.json`, so they are invisible to every reader — which is exactly
487
+ // why they need their own bounded sweep instead of aging out silently.
488
+ //
489
+ // The 1-hour age floor is the safety property: a temp belonging to a LIVE
490
+ // writer must survive another process's boot, and a writer that is merely slow
491
+ // can hold one for seconds, not an hour. A fresh temp is NEVER removed.
492
+ // ---------------------------------------------------------------------------
493
+
494
+ /** Only temps older than this are sweepable — a live writer's temp is younger. */
495
+ export const AGENT_TEMP_MAX_AGE_MS = 60 * 60 * 1000;
496
+
497
+ /**
498
+ * Remove `*.tmp` residue in the agent store older than one hour. Returns the
499
+ * number removed. Never throws: the store may be missing or unwritable, and a
500
+ * boot must not fail on hygiene.
501
+ */
502
+ export function sweepAgentRecordTemps(): number {
503
+ let names: string[];
504
+ try {
505
+ names = readdirSync(STORAGE_DIR);
506
+ } catch {
507
+ return 0; // store absent/unreadable — nothing to bound
508
+ }
509
+ const now = Date.now();
510
+ let swept = 0;
511
+ for (const name of names) {
512
+ if (!name.endsWith('.tmp')) continue;
513
+ const file = join(STORAGE_DIR, name);
514
+ try {
515
+ if (now - statSync(file).mtimeMs <= AGENT_TEMP_MAX_AGE_MS) continue;
516
+ unlinkSync(file);
517
+ swept += 1;
518
+ } catch {
519
+ // vanished between the readdir and the stat/unlink, or the store is not
520
+ // writable — leave it for the next boot.
521
+ }
522
+ }
523
+ return swept;
524
+ }
525
+
473
526
  /**
474
527
  * Retain `dir` for the #401 resume preamble: brand it with the retention marker
475
528
  * (its mtime is the recency source) and enforce the caps.
@@ -530,11 +583,16 @@ function persistAgent(agent: BackgroundAgent): void {
530
583
  // persisted record field (D4).
531
584
  const { _sessionRef, _sessionFile, ...persistable } = agent;
532
585
  try {
586
+ // Issue #554: atomic (temp+rename) so a SIGKILL between the truncate and the
587
+ // write cannot leave a torn record. `mode` is applied on the temp and
588
+ // survives the rename (the inode changes; the record is still `0o600`).
533
589
  // F6 (issue #29): records contain task, error, result.messages (full
534
590
  // conversation) and finalOutput — write owner-only (0o600) so other local
535
591
  // 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 });
592
+ // pre-existing files keep their old mode (not retroactive) — and a
593
+ // read-only record no longer blocks the write: a writable DIRECTORY does
594
+ // (issue #554's accepted permission-contract change).
595
+ writeFileAtomicSync(filePath, JSON.stringify(persistable, null, 2));
538
596
  } catch (err) {
539
597
  // Log but never throw — persistence must not break execution
540
598
  log.error(`Failed to persist agent ${agent.id}`, { error: err instanceof Error ? err.message : String(err) });
@@ -562,6 +620,14 @@ function agentRecordPath(id: string): string | null {
562
620
  return join(STORAGE_DIR, `${id}.json`);
563
621
  }
564
622
 
623
+ /** The tri-state record read plus the #554 named failure kind. */
624
+ export interface AgentRecordRead {
625
+ record: BackgroundAgent | null;
626
+ exists: boolean;
627
+ /** `"corrupt"` when the bytes are not JSON; `"unreadable"` when stat/read failed. */
628
+ reason?: AgentRecordFailureReason;
629
+ }
630
+
565
631
  /**
566
632
  * Issue #546 (major 2): the disk-only, TRI-STATE read of one agent record.
567
633
  *
@@ -570,8 +636,14 @@ function agentRecordPath(id: string): string | null {
570
636
  * go stale (retire the marker), the second means we know nothing (keep it).
571
637
  * `exists` is the stat of the validated path, so a chmod-000 or corrupt file
572
638
  * reports `{ record: null, exists: true }`.
639
+ *
640
+ * Issue #554: the two failure kinds are NAMED on the result (`reason`) instead
641
+ * of being collapsed — `"corrupt"` (the file read but JSON.parse rejected it:
642
+ * repair the file) vs `"unreadable"` (stat/read failed: fix permissions or the
643
+ * filesystem). The flip's decisions are unchanged; only the boot ledger can now
644
+ * count the corrupt subset by name.
573
645
  */
574
- export function readAgentRecordFromDisk(id: string): { record: BackgroundAgent | null; exists: boolean } {
646
+ export function readAgentRecordFromDisk(id: string): AgentRecordRead {
575
647
  const filePath = agentRecordPath(id);
576
648
  if (!filePath) return { record: null, exists: false };
577
649
  try {
@@ -586,12 +658,23 @@ export function readAgentRecordFromDisk(id: string): { record: BackgroundAgent |
586
658
  log.warn(`Could not stat agent record ${id} — treating it as unreadable`, {
587
659
  error: err instanceof Error ? err.message : String(err),
588
660
  });
589
- return { record: null, exists: true };
661
+ return { record: null, exists: true, reason: 'unreadable' };
590
662
  }
663
+ let text: string;
591
664
  try {
592
- return { record: JSON.parse(readFileSync(filePath, 'utf-8')), exists: true };
665
+ text = readFileSync(filePath, 'utf-8');
666
+ } catch (err) {
667
+ log.warn(`Could not read agent record ${id} — treating it as unreadable`, {
668
+ error: err instanceof Error ? err.message : String(err),
669
+ });
670
+ return { record: null, exists: true, reason: 'unreadable' };
671
+ }
672
+ try {
673
+ return { record: JSON.parse(text), exists: true };
593
674
  } catch {
594
- return { record: null, exists: true };
675
+ // The bytes are there and they are not JSON (a torn write before #554, or a
676
+ // zero-byte file). Never repaired or retired here — the count names them.
677
+ return { record: null, exists: true, reason: 'corrupt' };
595
678
  }
596
679
  }
597
680
 
@@ -702,6 +785,9 @@ export const RETRY_IDENTITY_KEYS: ReadonlySet<string> = new Set([
702
785
  'attempt',
703
786
  'status',
704
787
  'startedAt',
788
+ // Issue #616: the retry cause. Read by the shallow scanner so a dispatch-scoped
789
+ // stop can scope itself to `transport` without a full record parse.
790
+ 'retryCause',
705
791
  ]);
706
792
 
707
793
  const AGENT_STATUSES: ReadonlySet<string> = new Set([
@@ -722,6 +808,12 @@ export interface RetryRecordIdentity {
722
808
  status: AgentStatus;
723
809
  /** Epoch milliseconds (agent records store ms; registry ISO is normalised). */
724
810
  startedAt: number;
811
+ /**
812
+ * Issue #616: why this attempt exists, when the record says. ABSENT means
813
+ * UNKNOWN — neither cause is assumed, and unknown is never the stop-scoped
814
+ * `transport`.
815
+ */
816
+ retryCause?: RetryCause;
725
817
  }
726
818
 
727
819
  export type AgentIdResolution =
@@ -739,6 +831,13 @@ export interface RetryLineage {
739
831
  latest: RetryRecordIdentity | null;
740
832
  /** Registry entries that name the id itself or a member of its family. */
741
833
  inflight: InflightRun[];
834
+ /**
835
+ * Issue #616 (Q7): whether the scan was TRUNCATED, which is what a caller
836
+ * needs to avoid printing a universal claim over a partial read. `capped` is
837
+ * the `RETRY_SCAN_CAP` cut; a record older than `windowDays` is the caller's
838
+ * own check (it knows the requested record's `startedAt`).
839
+ */
840
+ bounds: { capped: boolean; windowDays: number };
742
841
  }
743
842
 
744
843
  function isSafeAgentId(id: string): boolean {
@@ -757,7 +856,9 @@ function isSafeAgentId(id: string): boolean {
757
856
  export type AgentFlipOutcome = 'repaired' | 'retired' | false;
758
857
 
759
858
  export function isTerminalAgentStatus(status: AgentStatus): boolean {
760
- return status === 'completed' || status === 'failed' || status === 'stopped';
859
+ // Issue #616: the vocabulary lives in `types.ts` (one definition, two readers —
860
+ // this export and the stop contract's post-stop verification).
861
+ return isTerminalAgentStatusValue(status);
761
862
  }
762
863
 
763
864
  function isAgentStatus(value: unknown): value is AgentStatus {
@@ -1040,6 +1141,7 @@ function readAgentIdentity(file: string): RetryRecordIdentity | null {
1040
1141
 
1041
1142
  const dispatchId = fields.get('dispatchId');
1042
1143
  const resumeOf = fields.get('resumeOf');
1144
+ const retryCause = fields.get('retryCause');
1043
1145
  return {
1044
1146
  id,
1045
1147
  status,
@@ -1047,6 +1149,8 @@ function readAgentIdentity(file: string): RetryRecordIdentity | null {
1047
1149
  attempt,
1048
1150
  ...(typeof dispatchId === 'string' ? { dispatchId } : {}),
1049
1151
  ...(typeof resumeOf === 'string' ? { resumeOf } : {}),
1152
+ // Issue #616: an unrecognized cause is ABSENT (unknown), never coerced.
1153
+ ...(retryCause === 'transport' || retryCause === 'manual' ? { retryCause } : {}),
1050
1154
  };
1051
1155
  }
1052
1156
 
@@ -1054,14 +1158,18 @@ function readAgentIdentity(file: string): RetryRecordIdentity | null {
1054
1158
  * The bounded store read: stat every record (cheap), keep the ones inside the
1055
1159
  * mtime window, sort newest-first, cap at `RETRY_SCAN_CAP`, then read only the
1056
1160
  * surviving files' identity fields. Corrupt/unsafe records are skipped.
1161
+ *
1162
+ * `capped` reports whether the CAP cut anything (issue #616, Q7): a caller that
1163
+ * makes a universal claim over the answer must be able to say the scan was
1164
+ * truncated.
1057
1165
  */
1058
- function readRecentAgentIdentities(): RetryRecordIdentity[] {
1166
+ function readRecentAgentIdentities(): { records: RetryRecordIdentity[]; capped: boolean } {
1059
1167
  let files: string[];
1060
1168
  try {
1061
- if (!existsSync(STORAGE_DIR)) return [];
1169
+ if (!existsSync(STORAGE_DIR)) return { records: [], capped: false };
1062
1170
  files = readdirSync(STORAGE_DIR);
1063
1171
  } catch {
1064
- return [];
1172
+ return { records: [], capped: false };
1065
1173
  }
1066
1174
 
1067
1175
  const cutoff = Date.now() - RETRY_SCAN_WINDOW_MS;
@@ -1080,12 +1188,13 @@ function readRecentAgentIdentities(): RetryRecordIdentity[] {
1080
1188
  }
1081
1189
 
1082
1190
  recent.sort((a, b) => b.mtime - a.mtime);
1191
+ const capped = recent.length > RETRY_SCAN_CAP;
1083
1192
  const records: RetryRecordIdentity[] = [];
1084
1193
  for (const entry of recent.slice(0, RETRY_SCAN_CAP)) {
1085
1194
  const record = readAgentIdentity(entry.file);
1086
1195
  if (record) records.push(record);
1087
1196
  }
1088
- return records;
1197
+ return { records, capped };
1089
1198
  }
1090
1199
 
1091
1200
  function identityFromAgent(agent: BackgroundAgent): RetryRecordIdentity | null {
@@ -1098,6 +1207,7 @@ function identityFromAgent(agent: BackgroundAgent): RetryRecordIdentity | null {
1098
1207
  attempt: agent.attempt ?? 1,
1099
1208
  ...(agent.dispatchId ? { dispatchId: agent.dispatchId } : {}),
1100
1209
  ...(agent.resumeOf ? { resumeOf: agent.resumeOf } : {}),
1210
+ ...(agent.retryCause ? { retryCause: agent.retryCause } : {}),
1101
1211
  };
1102
1212
  }
1103
1213
 
@@ -1106,13 +1216,35 @@ function identityFromRegistry(run: InflightRun): RetryRecordIdentity | null {
1106
1216
  if (startedAt === null) return null;
1107
1217
  return {
1108
1218
  id: run.id,
1219
+ // The registry has no status field: an entry being present IS the claim that
1220
+ // the run is in flight. Review 624 (F4): that claim is the WEAKEST one in the
1221
+ // family and is only used when no persisted record exists — see the fold in
1222
+ // `findRetryLineage`.
1109
1223
  status: 'running',
1110
1224
  startedAt,
1111
1225
  attempt: run.attempt ?? 1,
1112
1226
  ...(run.dispatchId ? { dispatchId: run.dispatchId } : {}),
1227
+ ...(run.retryCause ? { retryCause: run.retryCause } : {}),
1113
1228
  };
1114
1229
  }
1115
1230
 
1231
+ /**
1232
+ * The persisted identity for `id`, read OUTSIDE the shallow scan window.
1233
+ *
1234
+ * Review 624 (F4): `readRecentAgentIdentities` is bounded (7-day mtime window,
1235
+ * 200-record cap), so a record can be absent from it while its registry entry
1236
+ * survives — the crash-residue shape. One targeted read per registry entry (a
1237
+ * handful at most, never a scan) makes "the persisted record wins" independent
1238
+ * of that window. A record whose embedded id disagrees with its file name is not
1239
+ * this run's record and is ignored.
1240
+ */
1241
+ function persistedIdentityFor(id: string): RetryRecordIdentity | null {
1242
+ const file = agentRecordPath(id);
1243
+ if (!file) return null;
1244
+ const persisted = readAgentIdentity(file);
1245
+ return persisted && persisted.id === id ? persisted : null;
1246
+ }
1247
+
1116
1248
  /**
1117
1249
  * Find the logical dispatch family for `id`.
1118
1250
  *
@@ -1122,20 +1254,34 @@ function identityFromRegistry(run: InflightRun): RetryRecordIdentity | null {
1122
1254
  * in so an in-flight retry is visible without a store record.
1123
1255
  */
1124
1256
  export function findRetryLineage(id: string, source?: BackgroundAgent | null): RetryLineage {
1125
- const empty: RetryLineage = { id, family: [], found: null, latest: null, inflight: [] };
1257
+ const empty: RetryLineage = {
1258
+ id,
1259
+ family: [],
1260
+ found: null,
1261
+ latest: null,
1262
+ inflight: [],
1263
+ bounds: { capped: false, windowDays: RETRY_SCAN_WINDOW_DAYS },
1264
+ };
1126
1265
  if (!isSafeAgentId(id)) return empty;
1127
1266
 
1267
+ const scan = readRecentAgentIdentities();
1128
1268
  const byId = new Map<string, RetryRecordIdentity>();
1129
- for (const record of readRecentAgentIdentities()) byId.set(record.id, record);
1269
+ for (const record of scan.records) byId.set(record.id, record);
1130
1270
 
1131
1271
  const sourceIdentity = source && source.id === id ? identityFromAgent(source) : null;
1132
1272
  if (sourceIdentity) byId.set(id, sourceIdentity);
1133
1273
 
1134
1274
  const registry = safeListInflightRuns();
1135
1275
  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);
1276
+ if (byId.has(run.id)) continue;
1277
+ // Review 624 (F4): a PERSISTED record is authoritative over the registry's
1278
+ // hardcoded `running` — even when the record fell outside the shallow scan
1279
+ // (its 7-day window or its 200-record cap). Without this, crash residue (a
1280
+ // registry entry outliving a terminal record) planned the terminal attempt as
1281
+ // live, `stopAgent` returned it unchanged, and the report printed
1282
+ // "Stopped agent …" for an attempt that was already dead.
1283
+ const identity = persistedIdentityFor(run.id) ?? identityFromRegistry(run);
1284
+ if (identity) byId.set(identity.id, identity);
1139
1285
  }
1140
1286
 
1141
1287
  const all = [...byId.values()];
@@ -1161,7 +1307,14 @@ export function findRetryLineage(id: string, source?: BackgroundAgent | null): R
1161
1307
  (run) => run.id === id || (familyDispatch !== undefined && run.dispatchId === familyDispatch),
1162
1308
  );
1163
1309
 
1164
- return { id, family, found, latest, inflight };
1310
+ return {
1311
+ id,
1312
+ family,
1313
+ found,
1314
+ latest,
1315
+ inflight,
1316
+ bounds: { capped: scan.capped, windowDays: RETRY_SCAN_WINDOW_DAYS },
1317
+ };
1165
1318
  }
1166
1319
 
1167
1320
  /**
@@ -1180,6 +1333,32 @@ export function markAgentInterrupted(id: string, interruptedAt: string): Backgro
1180
1333
  return agent;
1181
1334
  }
1182
1335
 
1336
+ /**
1337
+ * Issue #574: state the run's KIND on the record, so the status flip that
1338
+ * follows persists it. A deadline and a user stop are both `status:"stopped"`;
1339
+ * only the category tells the two frictions apart.
1340
+ *
1341
+ * WHY BEFORE THE FLIP AND NOT AFTER: `updateAgentStatus` persists the record
1342
+ * itself, so a stamp written afterwards is absent from the bytes an observer
1343
+ * reads at the flip — and never lands at all if the settle that would write it
1344
+ * never arrives (a real stop is exactly that case: `stopAgent` persists
1345
+ * `stopped` before any abort settles).
1346
+ *
1347
+ * The `agents.set` is load-bearing: `getAgent` is memory-first, so a record that
1348
+ * exists only on disk would be re-loaded WITHOUT this stamp between the call and
1349
+ * its persist. Re-inserting the stamped object makes the flip write what this
1350
+ * function just said.
1351
+ */
1352
+ function stampAgentKind(
1353
+ agent: BackgroundAgent,
1354
+ errorCategory: ErrorCategory,
1355
+ stopReason: string,
1356
+ ): void {
1357
+ agent.errorCategory = errorCategory;
1358
+ agent.stopReason = stopReason;
1359
+ agents.set(agent.id, agent);
1360
+ }
1361
+
1183
1362
  /**
1184
1363
  * Update agent status
1185
1364
  */
@@ -1426,6 +1605,11 @@ export async function stopAgent(id: string): Promise<BackgroundAgent | null> {
1426
1605
  return agent;
1427
1606
  }
1428
1607
 
1608
+ // Issue #574: the KIND comes before the flip that persists it — this is the
1609
+ // earliest observable point of a user stop (the abort settles later, if at
1610
+ // all).
1611
+ stampAgentKind(agent, 'aborted', 'aborted');
1612
+
1429
1613
  // Mark stopped BEFORE aborting so the spawnBackgroundSession .then handler
1430
1614
  // (which fires after the run settles) keeps the stopped state.
1431
1615
  updateAgentStatus(id, 'stopped');
@@ -1574,6 +1758,11 @@ export async function spawnBackgroundSession(
1574
1758
  dispatchId?: string;
1575
1759
  resumeOf?: string;
1576
1760
  attempt?: number;
1761
+ /** Issue #616: why this attempt exists — `transport` for the automatic
1762
+ * background retry, `manual` for a caller-driven `retryRunId` retry. Absent
1763
+ * on a first dispatch, and then it reads as UNKNOWN (never `transport`).
1764
+ * Recorded on the agent record, the run entry and the registry entry. */
1765
+ retryCause?: RetryCause;
1577
1766
  /** Option B U3 (D4): recovery posture at dispatch — snapshotted onto the
1578
1767
  * agent record + run entry so the boot notice reads the posture the run
1579
1768
  * was actually dispatched under. Absent reads as "offer". */
@@ -1602,26 +1791,23 @@ export async function spawnBackgroundSession(
1602
1791
 
1603
1792
  try {
1604
1793
  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.
1794
+ // Issue #620: the conductor's required background guard is RESOLVED AND
1795
+ // CONTAINED here — before the SDK is imported, before the loader exists, and
1796
+ // therefore before any agent record or run entry can exist. The resolution
1797
+ // root is `ctx.cwd` (the CONDUCTOR's project), never `params.cwd` — the child's
1798
+ // directory is model-chosen, so a guard resolved against it would be a guard
1799
+ // the model chooses. A missing, escaping or malformed guard throws here and
1800
+ // the pipeline's existing catch renders it as an ordinary spawn failure.
1610
1801
  //
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
- }
1802
+ // ORDER, stated because it is load-bearing twice: resolve → reload → verify →
1803
+ // scratch → createAgentSession. The scratch directory is created AFTER the
1804
+ // guard is verified (PR #627 review, F3), so a refused spawn — missing, broken
1805
+ // or handler-less guard — leaves NO `runs/<uuid>` directory behind, matching the
1806
+ // "no agent record, no run entry" promise both refusals make. Nothing between
1807
+ // the resolver and the verifier needs the directory: the loader and the session
1808
+ // manager are given `effectiveCwd`, not the scratch path.
1809
+ const guardName = readRequiredGuard(ctx.cwd);
1810
+ const guardPath = guardName === null ? null : resolveGuardPath(ctx.cwd, guardName);
1625
1811
  const effectiveCwd = params.cwd ?? ctx.cwd;
1626
1812
  // Dynamic import — static import fails under concurrent jiti loads
1627
1813
  const { getAgentDir, createAgentSession, SessionManager, SettingsManager, DefaultResourceLoader } = await import('@earendil-works/pi-coding-agent');
@@ -1715,6 +1901,12 @@ export async function spawnBackgroundSession(
1715
1901
  // deliberate security choice: background sessions have no trust prompt, so
1716
1902
  // nothing is imported from anywhere — the prompt is fully specified by the
1717
1903
  // caller. Users needing skills/extensions should use foreground delegation.
1904
+ //
1905
+ // Issue #620 is the ONE exception, and it is not a discovery path: the
1906
+ // conductor's project NAMED a guard in its own manifest, `resolveGuardPath`
1907
+ // turned that name into one absolute, contained, realpathed file, and no key
1908
+ // at all is added otherwise. F5: a relative entry would resolve against the
1909
+ // loader's cwd — the CHILD's — so the entry is absolute by construction.
1718
1910
  const loader = new DefaultResourceLoader({
1719
1911
  cwd: effectiveCwd,
1720
1912
  agentDir,
@@ -1722,8 +1914,44 @@ export async function spawnBackgroundSession(
1722
1914
  ...(sections.length ? { appendSystemPrompt: sections } : {}),
1723
1915
  noExtensions: true,
1724
1916
  noSkills: true,
1917
+ ...(guardPath === null ? {} : { additionalExtensionPaths: [guardPath] }),
1725
1918
  });
1726
1919
  await loader.reload();
1920
+ // Issue #620: loading is not registration (F9: `reload()` never throws). The
1921
+ // named guard is verified BEFORE createAgentSession, so an absent, errored or
1922
+ // handler-less guard refuses the spawn rather than producing a run that looks
1923
+ // guarded and is not. A refusal here throws before any agent record.
1924
+ if (guardPath !== null) {
1925
+ verifyGuardLoaded(loader, guardPath);
1926
+ log.info("Background guard verified", {
1927
+ agentId: id,
1928
+ guard: guardName,
1929
+ path: guardPath,
1930
+ handlers: ["tool_call", "before_agent_start"],
1931
+ });
1932
+ }
1933
+ // Issue #511 (U2): the scratch seam for the BACKGROUND surface, reached only
1934
+ // once the guard is verified (F3 of the PR #627 review: a refused spawn must not
1935
+ // leave an orphan run directory). This function is the single place a background
1936
+ // agent record and run entry are created (single, fan-out and the transport retry
1937
+ // all pass through it), so the run's directory is resolved and created HERE —
1938
+ // before the SDK is asked for a session, and therefore before `session.prompt()`
1939
+ // can start the child.
1940
+ //
1941
+ // A refusal is PRE-SPAWN and NAMED: it throws before any record exists, and
1942
+ // both pipeline callers translate a throw from this function into their
1943
+ // ordinary "Failed to spawn background agent: …" result — the same shape as
1944
+ // every other spawn failure.
1945
+ //
1946
+ // NOTE, stated rather than implied: a background run is an IN-PROCESS SDK
1947
+ // session, so there is no child environment to carry `BRL_SCRATCH` (the SDK
1948
+ // composes the shell env from `process.env` at command time, which a per-run
1949
+ // value cannot vary without race). The directory and the record's
1950
+ // `scratchDir` are this surface's whole carrier.
1951
+ const scratch = prepareRunScratch(id, { log });
1952
+ if (!scratch.ok) {
1953
+ throw new Error(`scratch root unavailable (${scratch.code}): ${scratch.message}`);
1954
+ }
1727
1955
  const resourceLoader: InstanceType<typeof DefaultResourceLoader> = loader;
1728
1956
 
1729
1957
  // Create the session — honor the resolved tool restrictions so the
@@ -1798,6 +2026,10 @@ export async function spawnBackgroundSession(
1798
2026
  dispatchId,
1799
2027
  resumeOf: params.resumeOf,
1800
2028
  attempt,
2029
+ // Issue #616: the retry's cause, persisted on the record so a
2030
+ // dispatch-scoped stop can scope itself to automatic transport retries and
2031
+ // never to a manual one. Absent on a first dispatch (⇒ unknown).
2032
+ retryCause: params.retryCause,
1801
2033
  owner,
1802
2034
  // Option B U3 (D4): per-run recovery posture snapshot. Additive — absent
1803
2035
  // reads as "offer" via `runRecoveryPosture`/the notice collector.
@@ -1832,6 +2064,7 @@ export async function spawnBackgroundSession(
1832
2064
  dispatchId,
1833
2065
  resumeOf: params.resumeOf,
1834
2066
  attempt,
2067
+ retryCause: params.retryCause,
1835
2068
  owner,
1836
2069
  recoveryPosture: params.recoveryPosture,
1837
2070
  // Issue #511 (U2): the run's scratch directory (`<root>/runs/<id>`, 0700),
@@ -1876,9 +2109,32 @@ export async function spawnBackgroundSession(
1876
2109
  * deadline ever sets it (see the arm site). A settle→settle re-entry (the
1877
2110
  * catch-all after a throwing handler) therefore still writes nothing, which is
1878
2111
  * the single-terminal-entry contract the old `runFinalized` guard enforced.
2112
+ * CONSUMED by the amendment (issue #648 review r2): one snapshot, one amendment,
2113
+ * so a second terminal call cannot append the run's spend twice.
1879
2114
  */
1880
2115
  let snapshot: SubagentRun | undefined;
1881
2116
 
2117
+ /**
2118
+ * Issue #648 (Q4/C): the child session's own entries. The child's footer sums
2119
+ * assistant messages AND `toolResult` usage (the messages half, taken from
2120
+ * `session.messages`) plus `type: "usage"` entries and compaction/branch-summary
2121
+ * calls, so a run's recorded spend must fold the same sources to agree with what
2122
+ * the child would have reported. Defensive by contract: a session fixture without
2123
+ * a manager (most tests) is an empty source, never a throw.
2124
+ */
2125
+ const childEntries = (): ReadonlyArray<unknown> => {
2126
+ try {
2127
+ const entries = session.sessionManager?.getEntries?.();
2128
+ return Array.isArray(entries) ? entries : [];
2129
+ } catch {
2130
+ return [];
2131
+ }
2132
+ };
2133
+
2134
+ /** The groups the TERMINAL write (and its amendment) appends. Never the snapshot. */
2135
+ const terminalUsageGroups = (): SubagentUsageGroup[] =>
2136
+ usageGroupsFromSession(session.messages ?? [], childEntries(), run.model);
2137
+
1882
2138
  /**
1883
2139
  * This call's OWN classification. The retention/prune gate reads THIS — never
1884
2140
  * the snapshot's — because at the deadline a run looks like `timeout` (not
@@ -1916,6 +2172,14 @@ export async function spawnBackgroundSession(
1916
2172
  stopReason?: string;
1917
2173
  errorCategory?: ErrorCategory;
1918
2174
  prune?: boolean;
2175
+ /**
2176
+ * Issue #648 (Q2): this write is the DEADLINE's classification snapshot, not
2177
+ * a measurement. A still-running agent's usage is zero/partial, so the
2178
+ * snapshot appends NO footer entry — the payload lands on the amendment the
2179
+ * late settle writes. Set by the one call site that IS the deadline; every
2180
+ * other terminal write leaves it unset and appends its groups.
2181
+ */
2182
+ snapshot?: boolean;
1919
2183
  /**
1920
2184
  * Issue #546: do NOT retire the registry entry here — the caller owns the
1921
2185
  * retirement and performs it only once the record flip is durable. Only the
@@ -1977,7 +2241,8 @@ export async function spawnBackgroundSession(
1977
2241
  // second classification claim — mutant M7).
1978
2242
  if (entryWritten) {
1979
2243
  // No snapshot => this is a settle RE-ENTRY (the settle already wrote the
1980
- // record); nothing new to say. Only a deadline snapshot is amendable.
2244
+ // record, and any deadline snapshot has already been amended); nothing new
2245
+ // to say. Only an UNCONSUMED deadline snapshot is amendable.
1981
2246
  if (!snapshot) return undefined;
1982
2247
  const amended: SubagentRun = {
1983
2248
  ...snapshot,
@@ -1990,7 +2255,15 @@ export async function spawnBackgroundSession(
1990
2255
  outputSummary: finalOutput.slice(0, 200),
1991
2256
  fullOutput: finalOutput || undefined,
1992
2257
  };
1993
- persistRunRecord(pi, amended);
2258
+ persistSettledRunRecord(pi, amended, terminalUsageGroups());
2259
+ // Issue #648 review r2: the latch is CONSUMED by the write that used it.
2260
+ // Leaving the snapshot set let a LATER terminal call (the catch-all after a
2261
+ // settle-handler step threw — a read-only transcript, a throwing emit) amend
2262
+ // the same snapshot a SECOND time. Before #648 that duplicated a record;
2263
+ // with the run's spend riding on the write it duplicated MONEY — the footer
2264
+ // over-counted that run by its whole cost. Cleared only AFTER the append
2265
+ // resolved, so a throwing write still leaves the amendment retryable.
2266
+ snapshot = undefined;
1994
2267
  log.info("Background run amended after a late settle", {
1995
2268
  agentId: id,
1996
2269
  status: amended.status,
@@ -2037,13 +2310,22 @@ export async function spawnBackgroundSession(
2037
2310
  ? { ...(run.originalParams ?? {}), errorCategory }
2038
2311
  : run.originalParams,
2039
2312
  };
2040
- persistRunRecord(pi, entry, undefined, { deferRetire: terminal?.deferRetire });
2313
+ persistSettledRunRecord(pi, entry, terminal?.snapshot ? [] : terminalUsageGroups(), {
2314
+ deferRetire: terminal?.deferRetire,
2315
+ });
2041
2316
  // Issue #453: set only AFTER the append resolved. A throwing write therefore
2042
2317
  // leaves `entryWritten === false`, so a later settle still classifies the run
2043
2318
  // instead of amending a record that was never written (mutant M3).
2044
2319
  entryWritten = true;
2045
2320
  // Issue #179 (D6): the explicit settle line — the log's job is to record the
2046
2321
  // CLASSIFIED OUTCOME, which cwd alone can never convey.
2322
+ // Issue #556: the row carries the LINEAGE too. Without it the only way to
2323
+ // group a retry with what it resumed was spawn adjacency in the log, which
2324
+ // reads wrong across concurrent runs — the durable records had the answer
2325
+ // and the log did not. `attempt` defaults to the documented 1 (a record
2326
+ // written before the field existed IS a first attempt); `resumeOf` is
2327
+ // OMITTED, never null: an absent key is what "this run resumed nothing"
2328
+ // looks like, and a null would read as a lookup that failed.
2047
2329
  log.info("Background run settled", {
2048
2330
  agentId: id,
2049
2331
  status,
@@ -2052,6 +2334,8 @@ export async function spawnBackgroundSession(
2052
2334
  tokensOut: usage.output,
2053
2335
  errorCategory,
2054
2336
  error: error ?? null,
2337
+ attempt: entry.attempt ?? 1,
2338
+ ...(entry.resumeOf !== undefined ? { resumeOf: entry.resumeOf } : {}),
2055
2339
  });
2056
2340
  return entry;
2057
2341
  };
@@ -2306,6 +2590,61 @@ export async function spawnBackgroundSession(
2306
2590
  `${PROMPT_NEVER_ISSUED_MESSAGE}: ` +
2307
2591
  sanitizeErrorMessage(err instanceof Error ? err.message : String(err), effectiveCwd);
2308
2592
 
2593
+ /**
2594
+ * Issue #616 (Q3): settle a retry whose cancel was found at the pre-prompt
2595
+ * gate. The prompt is NEVER issued, so no deadline is armed yet and there is
2596
+ * no live session to abort — the record, the run entry and the transcript are
2597
+ * the whole settlement, and the status is `stopped` (this is a stop, not a
2598
+ * failure).
2599
+ *
2600
+ * ORDER: record flip → run entry → transcript, each contained separately, so a
2601
+ * throw in one cannot suppress another and cannot escape as the spawn result.
2602
+ * The run-entry write retires the registry entry (its status is terminal) and
2603
+ * prunes the per-run session dir — safe here for the same reason `failPreStart`
2604
+ * documents: the prompt was provably never issued, so nothing can be writing
2605
+ * to that directory and no retry will be offered for this run.
2606
+ *
2607
+ * ACCEPTED RESIDUE (stated, not papered over): a crash between these writes
2608
+ * leaves either a terminal record with a `running` run entry or a `running`
2609
+ * record with a retired entry. Both are the ordinary #439/#546 residue class
2610
+ * and neither is repairable by the boot scan — the window is three synchronous
2611
+ * statements wide.
2612
+ */
2613
+ const settleCancelledRetry = (): void => {
2614
+ const reason = CANCELLED_RETRY_MESSAGE;
2615
+ try {
2616
+ // Issue #574: the KIND precedes the flip that persists it, exactly as
2617
+ // `stopAgent` does for a user stop.
2618
+ stampAgentKind(agent, 'aborted', 'aborted');
2619
+ updateAgentStatus(id, 'stopped', reason);
2620
+ } catch (err) {
2621
+ safeLog(() =>
2622
+ log.warn(`spawnBackgroundSession: cancelled-retry record flip failed for ${id}`, {
2623
+ error: thrownMessage(err),
2624
+ }),
2625
+ );
2626
+ }
2627
+ try {
2628
+ finalizeRunEntry('failed', reason, { stopReason: 'aborted', errorCategory: 'aborted' });
2629
+ } catch (err) {
2630
+ safeLog(() =>
2631
+ log.warn(`spawnBackgroundSession: cancelled-retry run entry failed for ${id}`, {
2632
+ error: thrownMessage(err),
2633
+ }),
2634
+ );
2635
+ }
2636
+ try {
2637
+ transcript.completeTranscript(id, 'stopped');
2638
+ } catch (err) {
2639
+ safeLog(() =>
2640
+ log.warn(`spawnBackgroundSession: cancelled-retry transcript note failed for ${id}`, {
2641
+ error: thrownMessage(err),
2642
+ }),
2643
+ );
2644
+ }
2645
+ agent._sessionRef = undefined; // outside every try — cannot throw, must always run
2646
+ };
2647
+
2309
2648
  // Start transcript for this agent. Issue #447 (S2): a throw here used to
2310
2649
  // leave a `running` run entry and a live registry entry that the next boot
2311
2650
  // offered as an interrupted, retryable run — clean it and rethrow.
@@ -2338,22 +2677,41 @@ export async function spawnBackgroundSession(
2338
2677
 
2339
2678
  // Issue #122: the session's REAL usage lives on the assistant messages in
2340
2679
  // session.messages — each turn carries the same usage shape accumulateUsage
2341
- // folds (the runner's single source of truth for usage semantics: turns++,
2342
- // sum input/output/cache, cost.total, contextTokens from totalTokens). Fold
2343
- // the session's assistant turns into a fresh stats object and MERGE it onto
2344
- // the agent's result record — never replace: the git-diff branches may have
2345
- // already set exitCode/messages/stderr/gitBranch/gitDiff, and the aborted/
2346
- // failed branches previously OVERWROTE usage with the empty fallback. Runs
2347
- // on every terminal path right before the finalize; must never throw
2348
- // (best-effort, same discipline as markTerminalBestEffort).
2680
+ // folds (turns++, sum input/output/cache, cost.total, contextTokens from
2681
+ // totalTokens). Fold the session's assistant turns into a fresh stats object
2682
+ // and MERGE it onto the agent's result record — never replace: the git-diff
2683
+ // branches may have already set exitCode/messages/stderr/gitBranch/gitDiff,
2684
+ // and the aborted/failed branches previously OVERWROTE usage with the empty
2685
+ // fallback. Runs on every terminal path right before the finalize; must never
2686
+ // throw (best-effort, same discipline as markTerminalBestEffort).
2687
+ //
2688
+ // Issue #648 (Q4/C): the fold is the SAME four-source fold the footer receives
2689
+ // — assistant messages, `toolResult` usage, `usage` entries, compaction/branch-
2690
+ // summary usage — and the record's cost/tokens are DERIVED from those groups, so
2691
+ // the run record and the appended footer entries agree by construction rather
2692
+ // than by two copies of the arithmetic. `turns` and `contextTokens` stay MESSAGE
2693
+ // semantics and stay assistant-only: a usage entry is not a turn, a toolResult's
2694
+ // tool-side spend is not a turn either, and context size is the LAST turn's
2695
+ // total. Money is per-source; work volume is per-turn.
2349
2696
  const recordSessionUsage = (): void => {
2350
2697
  try {
2698
+ const messages = session.messages ?? [];
2699
+ const groups = usageGroupsFromSession(messages, childEntries(), run.model);
2700
+ const totals = sumUsageGroups(groups);
2351
2701
  const usage: UsageStats = { ...EMPTY_USAGE };
2352
- for (const msg of session.messages ?? []) {
2353
- if (msg.role === 'assistant') {
2354
- accumulateUsage(usage, msg.usage as Parameters<typeof accumulateUsage>[1]);
2355
- }
2702
+ for (const msg of messages) {
2703
+ if (msg.role !== 'assistant' || !msg.usage) continue;
2704
+ // Issue #179 (D3): a turn is an assistant message that CARRIES usage —
2705
+ // the same rule `accumulateUsage` applies, so "did nothing" stays 0.
2706
+ usage.turns++;
2707
+ const totalTokens = (msg.usage as { totalTokens?: number } | undefined)?.totalTokens;
2708
+ if (totalTokens) usage.contextTokens = totalTokens;
2356
2709
  }
2710
+ usage.input = totals.input;
2711
+ usage.output = totals.output;
2712
+ usage.cacheRead = totals.cacheRead;
2713
+ usage.cacheWrite = totals.cacheWrite;
2714
+ usage.cost = totals.cost;
2357
2715
  agent.result = {
2358
2716
  // Issue #122: seed the FULL required SubagentResult shape (messages /
2359
2717
  // exitCode / stderr) BEFORE the existing record is spread — the seed
@@ -2568,6 +2926,18 @@ export async function spawnBackgroundSession(
2568
2926
  gitInfo: { gitBranch?: string; gitDiff?: string },
2569
2927
  stopReason: string,
2570
2928
  ): void => {
2929
+ // Issue #574: FILL ONLY — never re-classify. `updateAgentStatus` already
2930
+ // persisted the kind at the flip; this shared helper runs for BOTH a user
2931
+ // stop and a deadline, and a deadline's kind is `timeout`, so an
2932
+ // unconditional stamp here would overwrite it and lose the friction. The
2933
+ // stamp is for a record that reached the abort settle with NO kind (a
2934
+ // status flipped by a path that did not classify) — and only that.
2935
+ if (!agent.errorCategory) {
2936
+ agent.errorCategory = 'aborted';
2937
+ agent.stopReason = 'aborted';
2938
+ agents.set(id, agent);
2939
+ persistAgent(agent);
2940
+ }
2571
2941
  // W4/M1: capture whatever the branch produced before discarding it — an
2572
2942
  // aborted background agent's partial work is still worth reviewing, and
2573
2943
  // must be RECORDED, not just captured-and-deleted.
@@ -2717,6 +3087,9 @@ export async function spawnBackgroundSession(
2717
3087
  setTimeout(() => {
2718
3088
  if (agent.completedAt) return; // already settled — nothing to abort
2719
3089
  const reason = `Timed out after ${budgetMs}ms`;
3090
+ // Issue #574: the deadline states its OWN kind before the flip persists
3091
+ // it — the snapshot below lands later and may not land at all.
3092
+ stampAgentKind(agent, 'timeout', 'aborted');
2720
3093
  let bookkeepingFailure: unknown;
2721
3094
  try {
2722
3095
  updateAgentStatus(id, 'stopped', reason);
@@ -2754,6 +3127,7 @@ export async function spawnBackgroundSession(
2754
3127
  stopReason: 'aborted',
2755
3128
  errorCategory: 'timeout',
2756
3129
  prune: false,
3130
+ snapshot: true,
2757
3131
  });
2758
3132
  } catch (err) {
2759
3133
  log.warn(`spawnBackgroundSession: deadline record write failed for ${id}`, {
@@ -2772,6 +3146,65 @@ export async function spawnBackgroundSession(
2772
3146
  }
2773
3147
  }, delayMs);
2774
3148
 
3149
+ // ---------------------------------------------------------------------
3150
+ // Issue #616 (Q3): THE ARMED-RETRY CANCEL GATE.
3151
+ //
3152
+ // The automatic transport retry is unaddressable between its id being minted
3153
+ // (above) and its agent record landing: nothing durable names it, so a
3154
+ // `stop_subagent` of the dispatch can only reach the dead attempt 1. The
3155
+ // arming site (`scheduleTransportRetry`) therefore records a durable INTENT
3156
+ // before the spawn, and a stop that finds it sets the cancel. This is where
3157
+ // that cancel is honoured — before the deadline is armed and before the
3158
+ // ACCEPTANCE write, so a cancelled retry never claims `acceptedAt` and never
3159
+ // reaches `session.prompt()`.
3160
+ //
3161
+ // The check reads the marker KEYED BY THE SOURCE RUN (`params.resumeOf`,
3162
+ // inherited through `newDispatchIdentity`), not by our own id — our id is the
3163
+ // thing the marker had to be written without.
3164
+ //
3165
+ // THE SLIVER, AFTER review 624 r2: TWO checks cover the whole gate -> prompt
3166
+ // path. A stop landing before the marker check is honoured by it; one landing
3167
+ // after it but before the prompt can only flip the RECORD (see the belt below)
3168
+ // and is caught by the status read. What remains between that read and the
3169
+ // `session.prompt()` call is ATOMIC UNTIL THE FIRST `await` (the rest of the
3170
+ // path is hundreds of lines but zero awaits, so a racing stop in this process
3171
+ // cannot interleave inside it); a stop landing after the prompt falls back on
3172
+ // the record and the live session.
3173
+ // ---------------------------------------------------------------------
3174
+ //
3175
+ // BOTH the check and the clear are gated on `retryCause === "transport"`: the
3176
+ // marker is armed by, and describes, the AUTOMATIC retry only. A caller-driven
3177
+ // retry of the same source lands on the same `resumeOf`/`attempt` pair, and it
3178
+ // must neither consume another retry's cancel nor clear its intent.
3179
+ const armedRetrySource =
3180
+ params.resumeOf && params.retryCause === 'transport' ? params.resumeOf : undefined;
3181
+ const markerCancelled = !!armedRetrySource && isRetryCancelRequested(armedRetrySource, attempt);
3182
+ // ---------------------------------------------------------------------
3183
+ // Review 624 r2 (B1, THE BELT): a stop that landed between this run's record
3184
+ // write (above) and this gate could only FLIP THE RECORD — `session.abort()`
3185
+ // is a no-op on a session with no active run (the SDK aborts `activeRun`
3186
+ // only), and this run has not prompted yet. The stretch in between is not
3187
+ // small: the spawn queue and, for gitMode 'branch', another run's repository
3188
+ // lock can hold it for minutes, and the age rule above deliberately never
3189
+ // reclaims a cancel, so it cannot cover this case. The record can, and needs
3190
+ // no marker: if our OWN agent is already terminal, the prompt must not be
3191
+ // issued.
3192
+ //
3193
+ // Together with the marker check this settles the whole post-record /
3194
+ // pre-prompt stretch: before the marker clear the cancel is honoured here,
3195
+ // after it the cancel reaches the record and is caught by this line.
3196
+ // ---------------------------------------------------------------------
3197
+ const stoppedBeforePrompt = isTerminalAgentStatus(agent.status);
3198
+ // Past this line the retry IS addressable by its own id — the agent record and
3199
+ // the registry entry are durable — so the intent marker has done its job and
3200
+ // must go. Otherwise a later stop would keep disclosing an "armed" retry that
3201
+ // is in fact a normal running record.
3202
+ if (armedRetrySource) clearArmedRetry(armedRetrySource, attempt);
3203
+ if (markerCancelled || stoppedBeforePrompt) {
3204
+ settleCancelledRetry();
3205
+ return agent;
3206
+ }
3207
+
2775
3208
  // Issue #453 (ADR 0023, decision 1): ONE owner. This function arms the run's
2776
3209
  // deadline on EVERY path — the explicit timeout when there is one, else the
2777
3210
  // 30 m default — and no caller arms a second one (`deadlineOwner` is gone with
@@ -2867,6 +3300,9 @@ export async function spawnBackgroundSession(
2867
3300
  // status (pre-set 'stopped' + completedAt + event + transcript), only
2868
3301
  // the transcript note is missing from this path.
2869
3302
  if (agent.status !== 'stopped') {
3303
+ // Issue #574: this branch calls the flip itself, so it states the kind
3304
+ // first — otherwise the record would be 'stopped' with no category.
3305
+ stampAgentKind(agent, 'aborted', 'aborted');
2870
3306
  updateAgentStatus(id, 'stopped');
2871
3307
  transcript.completeTranscript(id, 'stopped');
2872
3308
  }