pi-better-background-tasks 0.17.0 → 0.18.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 (32) hide show
  1. package/package.json +4 -2
  2. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  3. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  4. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  5. package/runtime-client/artifacts/darwin-x64.json +1 -1
  6. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  7. package/runtime-client/artifacts/linux-arm64.json +1 -1
  8. package/runtime-client/artifacts/linux-x64.gz +0 -0
  9. package/runtime-client/artifacts/linux-x64.json +1 -1
  10. package/src/failures.ts +4 -2
  11. package/src/index.ts +6 -31
  12. package/src/managed-authority.ts +28 -0
  13. package/src/managed-client.ts +60 -0
  14. package/src/managed-frontend.ts +131 -0
  15. package/src/navigator-provider.ts +14 -6
  16. package/src/observed-waits.ts +118 -36
  17. package/src/output.ts +12 -0
  18. package/src/registry.ts +18 -1
  19. package/src/runtime.ts +8 -2
  20. package/src/sandbox.ts +7 -0
  21. package/src/shared-callback-batcher.ts +4 -1
  22. package/src/shared-failure-observations.ts +3 -0
  23. package/src/shared-navigator.ts +23 -5
  24. package/src/shared-operation-coordinator/assignment-observation.mjs +30 -0
  25. package/src/shared-operation-coordinator/index.ts +2 -0
  26. package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  27. package/src/shared-operation-coordinator/src/background-requests.ts +79 -0
  28. package/src/shared-operation-coordinator/src/schema.ts +31 -0
  29. package/src/shared-operation-coordinator/src/store.ts +18 -0
  30. package/src/shared-operation-coordinator/src/subagent-launch.ts +119 -0
  31. package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
  32. package/src/tools.ts +21 -5
@@ -21,7 +21,7 @@
21
21
  */
22
22
 
23
23
  import { createHash, randomUUID } from "node:crypto";
24
- import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync, writeFileSync } from "node:fs";
24
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
25
25
  import { homedir } from "node:os";
26
26
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
27
27
 
@@ -256,6 +256,7 @@ export interface ParentNotification {
256
256
  * `notifyParent` is not delivery.
257
257
  */
258
258
  export interface ParentDelivery {
259
+ readonly receiptId?: string;
259
260
  delivered(): void;
260
261
  defer(reason: string): void;
261
262
  }
@@ -557,6 +558,14 @@ function rpcCode(error: unknown): string {
557
558
  }
558
559
 
559
560
  export interface ObservedWaitHostOptions {
561
+ /** Fixed server admission guard, checked immediately before external dispatch. */
562
+ assertAdmission?: () => void;
563
+ /** Fixed native adapter alone may authorize an explicit cross-owner stop. */
564
+ authorizeParentCancellation?: (input: { requester: OwnerIdentity; operation: OperationRecord; requestId: string }) => { requestId: string; reason: string };
565
+ prepareWorkerPolicy?: (run: WorkerRunScope) => (() => void);
566
+ beforeParentOperation?: (operation: { operationId: string; taskId: string; token: string }) => void;
567
+ /** Runtime-owned coordinator handle. The caller retains its lifetime lease. */
568
+ sharedStore?: Store;
560
569
  /** Production adapters leave global discovery and terminal import to the server. */
561
570
  serverOwnedResults?: boolean;
562
571
  /** SQLite path. Defaults under the Pi agent directory. */
@@ -646,6 +655,8 @@ export function createObservedWaitHost(pi: ExtensionAPI, options: ObservedWaitHo
646
655
  return host;
647
656
  }
648
657
 
658
+ export function registerObservedWaitClient(pi: ExtensionAPI, host: ObservedWaitHost): void { hosts.set(pi as object, host); }
659
+
649
660
  export function getObservedWaitHost(pi: unknown): ObservedWaitHost | undefined {
650
661
  return pi && typeof pi === "object" ? hosts.get(pi as object) : undefined;
651
662
  }
@@ -918,7 +929,26 @@ export class ObservedWaitHost {
918
929
  private authorityPassCache?: Map<string, "live" | "dead" | "unknown">;
919
930
  /** Running operations this follower is currently assigned to supervise. */
920
931
  private readonly followerRunningTasks = new Set<string>();
921
- private lastChangeRevision = -1;
932
+ private readonly unscopedCallbackRecovery = { revision: -1, branch: "", delivery: undefined as string | undefined, claims: undefined as string | undefined };
933
+ private readonly callbackRecoveryScopes = new Map<string, { revision: number; delivery?: string; claims?: string; branch: string }>();
934
+ private recoveryScopeState() {
935
+ if (!this.activeOrigin) return this.unscopedCallbackRecovery;
936
+ const key = JSON.stringify([this.activeOrigin?.cwd, this.activeOrigin?.sessionId]);
937
+ let state = this.callbackRecoveryScopes.get(key);
938
+ if (!state) {
939
+ if (this.callbackRecoveryScopes.size >= 128) this.callbackRecoveryScopes.delete(this.callbackRecoveryScopes.keys().next().value!);
940
+ state = { revision: -1, branch: "" }; this.callbackRecoveryScopes.set(key, state);
941
+ }
942
+ return state;
943
+ }
944
+ private get lastChangeRevision() { return this.recoveryScopeState().revision; }
945
+ private set lastChangeRevision(value: number) { this.recoveryScopeState().revision = value; }
946
+ private get pendingCallbackCursor() { return this.recoveryScopeState().delivery; }
947
+ private set pendingCallbackCursor(value: string | undefined) { this.recoveryScopeState().delivery = value; }
948
+ private get pendingClaimCursor() { return this.recoveryScopeState().claims; }
949
+ private set pendingClaimCursor(value: string | undefined) { this.recoveryScopeState().claims = value; }
950
+ private get activeBranchSignature() { return this.recoveryScopeState().branch; }
951
+ private set activeBranchSignature(value: string) { this.recoveryScopeState().branch = value; }
922
952
  private lastOwnedTerminalAt = 0;
923
953
 
924
954
  constructor(private readonly pi: ExtensionAPI, options: ObservedWaitHostOptions = {}) {
@@ -1003,7 +1033,7 @@ export class ObservedWaitHost {
1003
1033
  this.closed = false;
1004
1034
  this.unavailableReason = undefined;
1005
1035
  try {
1006
- this.store = openStore({
1036
+ this.store = this.options.sharedStore ?? openStore({
1007
1037
  path: this.storePath,
1008
1038
  ...(this.options.now ? { now: this.options.now } : {}),
1009
1039
  });
@@ -1037,7 +1067,7 @@ export class ObservedWaitHost {
1037
1067
  this.timer = undefined;
1038
1068
  this.releaseDiscoveryAuthority();
1039
1069
  this.releaseSupervisionAuthority();
1040
- try { this.store?.close(); } catch { /* already closed */ }
1070
+ try { if (!this.options.sharedStore) this.store?.close(); } catch { /* already closed */ }
1041
1071
  this.store = undefined;
1042
1072
  this.launches.clear();
1043
1073
  this.rpcRuns.clear();
@@ -1048,6 +1078,7 @@ export class ObservedWaitHost {
1048
1078
  this.activeContext = undefined;
1049
1079
  this.terminalRecoveryNeeded = false;
1050
1080
  this.pendingTerminalCallbacks.clear();
1081
+ this.callbackRecoveryScopes.clear();
1051
1082
  this.watchedRunningTasks.clear();
1052
1083
  this.discoveredTaskSidecars.clear();
1053
1084
  this.durableProjectionCache = undefined;
@@ -1069,13 +1100,14 @@ export class ObservedWaitHost {
1069
1100
  }
1070
1101
  }
1071
1102
 
1072
- private activeParentTerminalOperations(): OperationRecord[] {
1103
+ private activeParentTerminalOperations(claims = false): OperationRecord[] {
1073
1104
  const origin = this.activeOrigin;
1074
1105
  if (!this.store || !origin?.sessionId) return [];
1075
- return this.store.listOperations({
1076
- phase: "terminal",
1077
- ownerScope: { kind: "parent-session", sessionId: origin.sessionId, workspace: origin.cwd },
1078
- });
1106
+ const page = this.store.listPendingParentCallbacks({ sessionId: origin.sessionId, workspace: origin.cwd },
1107
+ { after: claims ? this.pendingClaimCursor : this.pendingCallbackCursor, limit: 256 });
1108
+ const next = page.length === 256 ? page.at(-1)!.operationId : undefined;
1109
+ if (claims) this.pendingClaimCursor = next; else this.pendingCallbackCursor = next;
1110
+ return page;
1079
1111
  }
1080
1112
 
1081
1113
  /**
@@ -1122,9 +1154,18 @@ export class ObservedWaitHost {
1122
1154
  * pending set is seeded once at activation and by each terminal attempt; it is
1123
1155
  * not a scan of the historical terminal table on every 250 ms tick.
1124
1156
  */
1157
+ hasPendingParentCallbackRecovery(): boolean { return this.lastChangeRevision < 0 || this.pendingCallbackCursor !== undefined || this.pendingClaimCursor !== undefined; }
1158
+
1159
+ private rememberPendingCallback(taskId: string): void {
1160
+ if (!this.pendingTerminalCallbacks.has(taskId) && this.pendingTerminalCallbacks.size >= 256)
1161
+ this.pendingTerminalCallbacks.delete(this.pendingTerminalCallbacks.values().next().value!);
1162
+ this.pendingTerminalCallbacks.add(taskId);
1163
+ }
1164
+
1125
1165
  private retryPendingTerminalCallbacks(): void {
1126
1166
  if (!this.store || this.pendingTerminalCallbacks.size === 0) return;
1127
- for (const taskId of [...this.pendingTerminalCallbacks]) {
1167
+ for (const taskId of [...this.pendingTerminalCallbacks].slice(0, 64)) {
1168
+ this.pendingTerminalCallbacks.delete(taskId); this.rememberPendingCallback(taskId);
1128
1169
  const operation = this.operationForTask(taskId);
1129
1170
  if (!operation || operation.terminalRevision === 0) {
1130
1171
  this.pendingTerminalCallbacks.delete(taskId);
@@ -1260,14 +1301,11 @@ export class ObservedWaitHost {
1260
1301
  } catch {
1261
1302
  return;
1262
1303
  }
1263
- if (revision === this.lastChangeRevision) return;
1304
+ if (revision === this.lastChangeRevision && !this.pendingCallbackCursor) return;
1264
1305
  this.lastChangeRevision = revision;
1265
1306
  let operations: OperationRecord[];
1266
1307
  try {
1267
- operations = store.listOperations({
1268
- ownerScope: { kind: "parent-session", sessionId, workspace: ctx.cwd },
1269
- phase: "terminal",
1270
- });
1308
+ operations = this.activeParentTerminalOperations();
1271
1309
  } catch {
1272
1310
  return;
1273
1311
  }
@@ -1372,6 +1410,8 @@ export class ObservedWaitHost {
1372
1410
  const operationId = `op_${randomUUID()}`;
1373
1411
  const token = `launch_${randomUUID()}`;
1374
1412
  const taskId = supervisorTaskIdForToken(token);
1413
+ this.options.assertAdmission?.();
1414
+ this.options.beforeParentOperation?.({ operationId, taskId, token });
1375
1415
  store.registerOperation({
1376
1416
  operationId,
1377
1417
  taskId,
@@ -1522,7 +1562,11 @@ export class ObservedWaitHost {
1522
1562
  /** Called from an actual admitted parent tool context, not a wire owner claim. */
1523
1563
  authorizeCancellationForParent(ctx: ExtensionContext, taskId: string, requestId: string): string {
1524
1564
  if (this.localCancels.has(taskId)) throw new Error("not_accepted: old cancellation admission is still draining");
1525
- const operation = this.ownedOperation(taskId, this.ownerFor(ctx));
1565
+ const requester = this.ownerFor(ctx), operation = this.operationForTask(taskId);
1566
+ if (!operation) throw new Error(`Unknown task ${taskId}`);
1567
+ const admission = this.options.authorizeParentCancellation?.({ requester, operation, requestId });
1568
+ if (!ownerMatchesOperation(operation, requester) && !admission) throw new Error(`Task ${taskId} belongs to another execution owner.`);
1569
+ requestId = admission?.requestId ?? requestId;
1526
1570
  const managed = this.requireStore().resultSupervision(operation.operationId);
1527
1571
  if (this.supervisionAuthority(operation) === "foreign" && !(managed?.launchToken === operation.launchToken && managed.hostId === operation.supervision?.hostId)) throw new Error("permission-unavailable: live legacy or unknown supervisor prevents cancellation handoff");
1528
1572
  const proof = cancellationCredential();
@@ -1531,13 +1575,12 @@ export class ObservedWaitHost {
1531
1575
  this.requireStore().admitTaskCancellation({ credentialHash: proof.hash, directory: this.directory, request: previous ?? {
1532
1576
  owner: operation.owner, idempotencyKey: requestId, operationId: operation.operationId,
1533
1577
  expectedLaunchToken: operation.launchToken, expectedTerminalRevision: operation.terminalRevision,
1534
- expectedHostId: operation.supervision?.hostId ?? "unavailable", reason: "explicit stop",
1578
+ expectedHostId: operation.supervision?.hostId ?? "unavailable", reason: admission?.reason ?? "explicit stop",
1535
1579
  } });
1536
1580
  return proof.credential;
1537
1581
  }
1538
1582
 
1539
1583
  private async stopThroughRuntime(ctx: ExtensionContext, taskId: string, requestId: string): Promise<StatusView> {
1540
- this.ownedOperation(taskId, this.ownerFor(ctx));
1541
1584
  const root = realpathSync(dirname(this.storePath));
1542
1585
  const registrationPath = join(root, "server-registration-v1.json");
1543
1586
  if (!existsSync(registrationPath)) {
@@ -1561,7 +1604,12 @@ export class ObservedWaitHost {
1561
1604
  receipt = await client.request("runtime_cancel_task", { credential });
1562
1605
  }
1563
1606
  if (receipt.state === "outcome_unknown" || !receipt.result) throw new Error(`${receipt.state}: cancellation ${requestId}; query the same request before retrying`);
1564
- return this.statusForParent(ctx, taskId);
1607
+ // The credential above authorizes this exact recorded owner/token. Keep
1608
+ // the requester context intact even when its explicit all:true grant won.
1609
+ const operation = this.requireStore().getOperation(receipt.operationId);
1610
+ if (!operation || operation.taskId !== taskId || operation.launchToken !== receipt.expectedLaunchToken
1611
+ || !sameOwner(operation.owner, receipt.owner)) throw new Error('outcome_unknown: cancellation target identity changed');
1612
+ return this.statusForOperation(operation, this.ownerFor(ctx));
1565
1613
  } catch (error) {
1566
1614
  const message = String(error);
1567
1615
  if (/not_accepted|accepted:|outcome_unknown/.test(message)) throw error;
@@ -1809,8 +1857,11 @@ export class ObservedWaitHost {
1809
1857
  }
1810
1858
 
1811
1859
  private status(taskId: string, owner: OwnerIdentity): StatusView {
1812
- const store = this.requireStore();
1813
- const operation = this.ownedOperation(taskId, owner);
1860
+ return this.statusForOperation(this.ownedOperation(taskId, owner), owner);
1861
+ }
1862
+
1863
+ private statusForOperation(operation: OperationRecord, owner: OwnerIdentity): StatusView {
1864
+ const store = this.requireStore(), taskId = operation.taskId;
1814
1865
  const inspection = this.inspect(taskId);
1815
1866
  this.reconcileInspection(operation, inspection);
1816
1867
  const current = store.getOperation(operation.operationId) ?? operation;
@@ -2117,6 +2168,7 @@ export class ObservedWaitHost {
2117
2168
  const client = await this.resultSupervisionClient();
2118
2169
  client.close();
2119
2170
  }
2171
+ const assertWorkerPolicy = this.options.prepareWorkerPolicy?.(run);
2120
2172
  const prepared = this.prepareLaunch(
2121
2173
  input.kind,
2122
2174
  input.params,
@@ -2156,7 +2208,7 @@ export class ObservedWaitHost {
2156
2208
  this.launches.set(taskId, launchContext);
2157
2209
  if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
2158
2210
  const started = await this.startSupervisor({
2159
- token, taskId, kind: input.kind, params: input.params, prepared, operationId,
2211
+ token, taskId, kind: input.kind, params: input.params, prepared, operationId, assertDispatch: assertWorkerPolicy,
2160
2212
  });
2161
2213
  this.launches.set(taskId, launchContext);
2162
2214
  this.emitDurableTaskChange(owner);
@@ -2987,6 +3039,7 @@ export class ObservedWaitHost {
2987
3039
  params: Record<string, unknown>;
2988
3040
  prepared: ReturnType<ObservedWaitHost["prepareLaunch"]>;
2989
3041
  operationId: string;
3042
+ assertDispatch?: () => void;
2990
3043
  }): Promise<{ started: boolean; claimed: boolean }> {
2991
3044
  const { token, taskId, kind, params, prepared, operationId } = input;
2992
3045
  const profilePath = join(supervisorPaths(this.directory, taskId).dir, "sandbox.sb");
@@ -3014,6 +3067,15 @@ export class ObservedWaitHost {
3014
3067
  ...(typeof params.max_log_bytes === "number" ? { maxLogBytes: params.max_log_bytes } : {}),
3015
3068
  ...(kind === "watch" ? this.watchOptions(params) : this.processTimeout(params)),
3016
3069
  };
3070
+ try { this.options.assertAdmission?.(); input.assertDispatch?.(); }
3071
+ catch (error) {
3072
+ const operation = this.requireStore().getOperation(operationId);
3073
+ if (operation && operation.terminalRevision === 0) this.requireStore().recordTerminalOutcome({
3074
+ operationId, eventId: `admission_refused_${randomUUID()}`, owner: operation.owner,
3075
+ outcome: "failed", evidence: [], reason: `External dispatch refused before spawn: ${String(error)}`,
3076
+ });
3077
+ throw error;
3078
+ }
3017
3079
  const started = await this.supervisor.start(options);
3018
3080
  return { started: started.started, claimed: started.claimed };
3019
3081
  }
@@ -3307,13 +3369,14 @@ export class ObservedWaitHost {
3307
3369
  if (!this.options.notifyParent) return;
3308
3370
  if (operation.owner.kind !== "parent-session") return;
3309
3371
  if (!context) return;
3310
- if (context.callback === false) return;
3372
+ if (context.callback === false) { this.store?.setParentCallbackPending(operation.taskId, false); return; }
3311
3373
  // Never write any journal field while a newer or unprovable other host owns
3312
3374
  // the claim. In particular, a stale host's reconcile must not rewrite its
3313
3375
  // cached claim token over the current shared one.
3314
3376
  const claim = this.claimState(context.callbackClaimedBy);
3315
3377
  if (claim === "live" || claim === "unknown") return;
3316
3378
  if (context.callbackDeliveredAt !== undefined) {
3379
+ this.store?.setParentCallbackPending(operation.taskId, false);
3317
3380
  this.pendingTerminalCallbacks.delete(operation.taskId);
3318
3381
  skip("already delivered");
3319
3382
  return;
@@ -3353,7 +3416,7 @@ export class ObservedWaitHost {
3353
3416
  // A terminal result can become eligible later: the live session may have
3354
3417
  // been settling when the record was produced, or the owner may navigate
3355
3418
  // back to an eligible descendant branch. Keep retrying only this id.
3356
- this.pendingTerminalCallbacks.add(operation.taskId);
3419
+ this.rememberPendingCallback(operation.taskId);
3357
3420
  const origin = context.parentOrigin ?? { cwd: operation.owner.workspace, sessionId: operation.owner.sessionId };
3358
3421
  const branchId = context.branchId ?? operation.owner.branchId;
3359
3422
  if (!this.isParentOriginActive(origin, branchId)) {
@@ -3373,6 +3436,7 @@ export class ObservedWaitHost {
3373
3436
  const claimToken = context.callbackClaimToken;
3374
3437
  let settled = false;
3375
3438
  const delivery: ParentDelivery = {
3439
+ receiptId: `background-terminal:${operation.operationId}`,
3376
3440
  delivered: () => {
3377
3441
  if (settled) return;
3378
3442
  settled = true;
@@ -3429,13 +3493,13 @@ export class ObservedWaitHost {
3429
3493
  if (!context || context.callbackDeliveredAt !== undefined) return;
3430
3494
  const claim = this.claimState(context.callbackClaimedBy);
3431
3495
  if (claim === "live" || claim === "unknown") {
3432
- this.pendingTerminalCallbacks.add(taskId);
3496
+ this.rememberPendingCallback(taskId);
3433
3497
  return; // preserve the current owner's claim without any write
3434
3498
  }
3435
3499
  context.callbackPendingAt ??= Date.now();
3436
3500
  this.launches.set(taskId, context);
3437
3501
  this.writeLaunchContext(taskId, context);
3438
- this.pendingTerminalCallbacks.add(taskId);
3502
+ this.rememberPendingCallback(taskId);
3439
3503
  }
3440
3504
 
3441
3505
  private completeTerminalCallback(taskId: string, claimToken?: string): void {
@@ -3465,7 +3529,7 @@ export class ObservedWaitHost {
3465
3529
  if (!context || context.callbackDeliveredAt !== undefined) return;
3466
3530
  // A stale suppression must not clear the claim of a newer attempt.
3467
3531
  if (claimToken !== undefined && context.callbackClaimToken !== claimToken) return;
3468
- this.pendingTerminalCallbacks.add(taskId);
3532
+ this.rememberPendingCallback(taskId);
3469
3533
  context.callbackDeferredReason = oneLine(reason, 200);
3470
3534
  context.callbackAttemptedAt = Date.now();
3471
3535
  context.callbackSkipReason = `deferred: ${oneLine(reason, 160)}`;
@@ -3568,7 +3632,7 @@ export class ObservedWaitHost {
3568
3632
  });
3569
3633
  } catch { /* another host already recovered it */ }
3570
3634
  }
3571
- for (const operation of this.activeParentTerminalOperations()) {
3635
+ for (const operation of this.activeParentTerminalOperations(true)) {
3572
3636
  const context = this.currentLaunchContext(operation.taskId);
3573
3637
  if (!context?.callbackClaimedBy || context.callbackClaimedBy === this.hostId) continue;
3574
3638
  if (this.claimState(context.callbackClaimedBy) !== "dead") continue;
@@ -3691,6 +3755,7 @@ export class ObservedWaitHost {
3691
3755
  }
3692
3756
  let settled = false;
3693
3757
  const delivery: ParentDelivery = {
3758
+ receiptId: event.eventId,
3694
3759
  delivered: () => {
3695
3760
  if (settled) return;
3696
3761
  settled = true;
@@ -3998,8 +4063,9 @@ export class ObservedWaitHost {
3998
4063
  * on every session_tree/branch navigation. Branch changes must be visible to
3999
4064
  * a queued callback *before* the batcher decides whether to deliver it.
4000
4065
  */
4001
- noteParentContext(ctx: ExtensionContext): void {
4002
- this.setActiveOrigin(ctx);
4066
+ noteParentContext(ctx: ExtensionContext, options: {recover?: boolean} = {}): void {
4067
+ this.setActiveOrigin(ctx, options.recover !== false);
4068
+ if(options.recover === false)return;
4003
4069
  if (!this.store) return;
4004
4070
  this.recoverAbandonedDeliveries();
4005
4071
  if (this.terminalRecoveryNeeded) {
@@ -4011,7 +4077,7 @@ export class ObservedWaitHost {
4011
4077
  this.writeHostDebug();
4012
4078
  }
4013
4079
 
4014
- private setActiveOrigin(ctx: ExtensionContext): void {
4080
+ private setActiveOrigin(ctx: ExtensionContext, debug = true): void {
4015
4081
  const previous = this.activeContext;
4016
4082
  const previousKey = previous ? this.contextKey(previous) : undefined;
4017
4083
  const nextSessionId = this.sessionIdIfAvailable(ctx);
@@ -4027,11 +4093,16 @@ export class ObservedWaitHost {
4027
4093
  // A tool call or activation for a different session/workspace must seed the
4028
4094
  // terminal callback journal once. Same-session calls keep the live context
4029
4095
  // current without rescanning historical terminal records.
4030
- if (!previous || previousKey !== nextKey) {
4031
- this.terminalRecoveryNeeded = true;
4096
+ const branchSignature = JSON.stringify(branchIdsOf(ctx));
4097
+ const branchChanged = branchSignature !== this.activeBranchSignature;
4098
+ if (!previous || previousKey !== nextKey || branchChanged) this.terminalRecoveryNeeded = true;
4099
+ if (branchChanged) {
4032
4100
  this.lastChangeRevision = -1;
4101
+ this.pendingCallbackCursor = undefined;
4102
+ this.pendingClaimCursor = undefined;
4033
4103
  }
4034
- this.writeHostDebug();
4104
+ this.activeBranchSignature = branchSignature;
4105
+ if(debug)this.writeHostDebug();
4035
4106
  }
4036
4107
 
4037
4108
  private contextKey(ctx: ExtensionContext): string | undefined {
@@ -4104,10 +4175,21 @@ export class ObservedWaitHost {
4104
4175
 
4105
4176
  private writeLaunchContext(taskId: string, context: LaunchContext): void {
4106
4177
  try {
4178
+ const operation = this.operationForTask(taskId);
4179
+ const parent = operation?.owner.kind === "parent-session";
4180
+ const outboxDelivered = operation && Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision);
4181
+ const pending = context.callback !== false && context.callbackDeliveredAt === undefined && !outboxDelivered;
4182
+ // Publish the obligation before the sidecar: a crash may leave a pending
4183
+ // candidate, but cannot hide an accepted callback. Retire only after the
4184
+ // delivered/disabled sidecar is durable, so replay can prove suppression.
4185
+ if (parent && pending) this.store?.setParentCallbackPending(taskId, true);
4107
4186
  const path = this.sidecarPath(taskId);
4108
4187
  mkdirSync(dirname(path), { recursive: true });
4109
- writeFileSync(path, JSON.stringify(context), { mode: 0o600 });
4110
- } catch { /* notification metadata is best-effort; durable state is in SQLite */ }
4188
+ const staged = `${path}.${randomUUID()}.tmp`;
4189
+ try { writeFileSync(staged, JSON.stringify(context), { mode: 0o600, flag: "wx" }); renameSync(staged, path); }
4190
+ finally { rmSync(staged, { force: true }); }
4191
+ if (parent && !pending) this.store?.setParentCallbackPending(taskId, false);
4192
+ } catch { /* retain an obligation if the exact sidecar cannot be persisted */ }
4111
4193
  }
4112
4194
 
4113
4195
  private readLaunchContext(taskId: string): LaunchContext | undefined {
package/src/output.ts CHANGED
@@ -621,6 +621,18 @@ function redactedVerbose(meta: BackgroundTaskMeta, options: OutputOptions): unkn
621
621
  * whole document fits it is returned as plain JSON; otherwise it is paged
622
622
  * with a caller cursor like any other retained evidence.
623
623
  */
624
+ /** Bounded raw metadata for canonical supervisor tasks. These records contain no
625
+ * environment values and do not invent legacy process ownership fields. */
626
+ export function formatDurableStatusMetadata(meta: { id: string; [key: string]: unknown }, options: OutputOptions): string {
627
+ const json = JSON.stringify(meta, null, 2);
628
+ if (!options.cursor && utf8ByteLength(json) <= backgroundBudget("rawPage", options.maxBytes)) return json;
629
+ return assembleBackgroundContent({
630
+ surface: "rawPage", maxBytes: options.maxBytes,
631
+ sections: { identity: `Background task ${meta.id} metadata (environment values omitted).` },
632
+ verbatim: budget => pageVerbatimText(json, { cursor: options.cursor, maxBytes: budget, resource: `verbose:${scopeKey(options)}:${meta.id}` }),
633
+ });
634
+ }
635
+
624
636
  function formatVerbose(meta: BackgroundTaskMeta, options: OutputOptions): string {
625
637
  const json = JSON.stringify(redactedVerbose(meta, options), null, 2);
626
638
  const resource = `verbose:${scopeKey(options)}:${meta.id}`;
package/src/registry.ts CHANGED
@@ -12,12 +12,13 @@ const metaCache = new Map<string, BackgroundTaskMeta>();
12
12
  const indexIdsCache = new Map<string, { ids: Set<string>; signature: string }>();
13
13
  const initializedIndexes = new Set<string>();
14
14
  const metaChangedListeners = new Set<() => void>();
15
- const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, indexRevisionChecks: 0 };
15
+ const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, terminalMetadataFileReads: 0, indexRevisionChecks: 0 };
16
16
 
17
17
  export interface RegistryIoMetrics {
18
18
  fullDirectoryReads: number;
19
19
  indexDirectoryReads: number;
20
20
  metadataFileReads: number;
21
+ terminalMetadataFileReads: number;
21
22
  indexRevisionChecks: number;
22
23
  }
23
24
 
@@ -29,6 +30,7 @@ export function resetRegistryIoMetrics(): void {
29
30
  registryIo.fullDirectoryReads = 0;
30
31
  registryIo.indexDirectoryReads = 0;
31
32
  registryIo.metadataFileReads = 0;
33
+ registryIo.terminalMetadataFileReads = 0;
32
34
  registryIo.indexRevisionChecks = 0;
33
35
  }
34
36
 
@@ -129,6 +131,7 @@ export function inspectMeta(id: string): MetaInspection {
129
131
  const raw = readFileSync(path, "utf8");
130
132
  try {
131
133
  const meta = JSON.parse(raw) as BackgroundTaskMeta;
134
+ if(isTerminalStatus(meta.status))registryIo.terminalMetadataFileReads++;
132
135
  const invalid = metaShapeProblem(meta, id);
133
136
  if (invalid) {
134
137
  metaCache.delete(id);
@@ -223,6 +226,18 @@ export function listMetasForOrigin(origin: BackgroundTaskCallbackOrigin): Backgr
223
226
  .sort((a, b) => b.startedAt - a.startedAt);
224
227
  }
225
228
 
229
+ /** Durable pending callbacks are independent of the Navigator's terminal retention. */
230
+ export function listPendingCallbackMetasForOrigin(origin: BackgroundTaskCallbackOrigin): BackgroundTaskMeta[] {
231
+ const directory=join(baseDir(),'by-origin-callback',originKey(origin));
232
+ if(!initializedIndexes.has(directory)){
233
+ try {readFileSync(join(directory,'.initialized'));}
234
+ catch {for(const meta of listMetasForOrigin(origin))if(pendingCallback(meta))writeIndexEntry(directory,meta.id);mkdirSync(directory,{recursive:true});writeFileSync(join(directory,'.initialized'),'1');}
235
+ initializedIndexes.add(directory);
236
+ }
237
+ return readIndexIds(directory).map(readOwnedMeta).filter((meta):meta is BackgroundTaskMeta=>!!meta&&belongsToOrigin(meta,origin)&&pendingCallback(meta));
238
+ }
239
+ function pendingCallback(meta:BackgroundTaskMeta):boolean {return isTerminalStatus(meta.status)&&meta.status!=='cancelled'&&meta.callback!==false&&!meta.callbackSentAt&&!meta.callbackSuppressedAt;}
240
+
226
241
  export function listActiveMetasForOrigin(origin: BackgroundTaskCallbackOrigin): BackgroundTaskMeta[] {
227
242
  const directory = originActiveIndexDir(origin);
228
243
  ensureOriginActiveIndex(origin, directory);
@@ -288,6 +303,8 @@ function indexMeta(meta: BackgroundTaskMeta): void {
288
303
  try {
289
304
  const directory = originIndexDir(originOf(meta));
290
305
  writeIndexEntry(directory, meta.id);
306
+ const callbackDirectory=join(baseDir(),'by-origin-callback',originKey(originOf(meta)));
307
+ if(pendingCallback(meta))writeIndexEntry(callbackDirectory,meta.id);else removeIndexEntry(callbackDirectory,meta.id);
291
308
  const activeDirectory = originActiveIndexDir(originOf(meta));
292
309
  if (meta.status === "running") writeIndexEntry(activeDirectory, meta.id);
293
310
  else removeIndexEntry(activeDirectory, meta.id);
package/src/runtime.ts CHANGED
@@ -110,7 +110,7 @@ export type FirstCheckWaitEnd = "timeout" | "aborted" | "suspended";
110
110
  export type FirstCheckOutcome = FirstWatchCheck | { pending: FirstCheckWaitEnd; waitedMs: number } | undefined;
111
111
 
112
112
  /** Each cached extension factory owns its scheduling and suspension state. */
113
- export function createBackgroundTaskRuntime(attention = createFailureAttention()) {
113
+ export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion?: (origin: BackgroundTaskCallbackOrigin | undefined, event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => void, admission?: { assert(): void; prepared?(id: string): void }) {
114
114
  const { resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention } = attention;
115
115
  const watcherTimers = new Map<string, ReturnType<typeof setTimeout>>();
116
116
  const remoteSessionTimers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -298,6 +298,7 @@ function spawnTask(
298
298
  getActiveSession?: ActiveSessionProvider,
299
299
  dependencies: TaskRuntimeDependencies = {},
300
300
  ): BackgroundTaskMeta {
301
+ admission?.assert();
301
302
  // Resolved before any task directory, log, or metadata exists so a blocked
302
303
  // launch leaves nothing behind. Structured SSH must also honor launch restrictions.
303
304
  const intent = readTaskIntent(params);
@@ -314,6 +315,7 @@ function spawnTask(
314
315
  assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
315
316
  const commandLimits = backgroundExecutionLimits(sandboxPlan);
316
317
  const id = nextTaskId();
318
+ admission?.prepared?.(id);
317
319
  const logPath = logPathFor(id);
318
320
  ensureTaskDir(id);
319
321
  const remoteTask = params.ssh
@@ -611,6 +613,7 @@ function startWatchTask(
611
613
  getActiveSession?: ActiveSessionProvider,
612
614
  dependencies: TaskRuntimeDependencies = {},
613
615
  ): BackgroundTaskMeta {
616
+ admission?.assert();
614
617
  for (const [name, condition] of [["success_when", params.success_when], ["failure_when", params.failure_when]] as const) {
615
618
  const error = condition && validateCondition(condition);
616
619
  if (error) throw new Error(`${name}: ${error}`);
@@ -625,6 +628,7 @@ function startWatchTask(
625
628
  assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
626
629
  const commandLimits = backgroundExecutionLimits(sandboxPlan);
627
630
  const id = nextTaskId();
631
+ admission?.prepared?.(id);
628
632
  const now = Date.now();
629
633
  const timeoutSeconds = resolveWatchTimeoutSeconds(params.timeout_seconds);
630
634
  const remoteTask = params.ssh
@@ -1363,7 +1367,9 @@ async function notifyTerminal(
1363
1367
  const pending = terminalFailureAttention(latest.id);
1364
1368
  const label = latest.name ? `${latest.name} (${latest.id})` : latest.id;
1365
1369
  const facts = formatCallbackFacts(latest);
1366
- getCallbackBatcher(pi).enqueue({
1370
+ const enqueue = (event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => deliverCompletion ? deliverCompletion(latest.callbackOrigin, event) : getCallbackBatcher(pi).enqueue(event);
1371
+ enqueue({
1372
+ receiptId: `background-legacy:${latest.id}:${latest.endedAt ?? latest.startedAt}`,
1367
1373
  source: "background-task",
1368
1374
  id: latest.id,
1369
1375
  label,
package/src/sandbox.ts CHANGED
@@ -901,3 +901,10 @@ function blocked(plan: ForegroundSandboxPlan & { confined: true }, detail: strin
901
901
  detail,
902
902
  );
903
903
  }
904
+
905
+ /** Fixed server adapter clears only its own scope mirror before publishing another captured grant. */
906
+ export function clearForegroundSandboxPolicy(pi: unknown): void {
907
+ observeForegroundSandboxPolicy(pi);
908
+ const events=eventBusOf(pi), mirror=events && mirrors.get(events);
909
+ if(mirror){mirror.policy=undefined;mirror.error=undefined;mirror.processAccess="off";mirror.mainConfined=false;}
910
+ }
@@ -158,6 +158,8 @@ export interface CallbackBatchEvent {
158
158
  }
159
159
 
160
160
  export interface UrgentCallbackEvent {
161
+ /** Durable recipient transcript identity for handoff/receipt crash recovery. */
162
+ receiptId?: string;
161
163
  source: CallbackSource;
162
164
  /** Notification identity (dedupe/receipts). */
163
165
  id: string;
@@ -743,7 +745,8 @@ export function createCallbackBatcher(
743
745
  urgentInFlight.add(key);
744
746
  try {
745
747
  const handoff = host.sendMessage(
746
- { customType: event.customType, content: formatUrgentCallback(event, { maxBytes }), display: true },
748
+ { customType: event.customType, content: formatUrgentCallback(event, { maxBytes }), display: true,
749
+ ...(event.receiptId ? { details: { urgentEventId: event.receiptId } } : {}) },
747
750
  { deliverAs: "followUp", triggerTurn: true },
748
751
  );
749
752
  if (isPromiseLike(handoff)) {
@@ -1072,6 +1072,9 @@ export function readFailureState(path: string): FailureState {
1072
1072
  for (const record of remaining ?? []) state = reduceFailure(state, record.event, record.observedAt);
1073
1073
  return remaining?.length ? storageProblem(state, "Failure evidence could not be persisted") : state;
1074
1074
  }
1075
+ /** Read-only projection: never retries or appends process-local pending writes. */
1076
+ export function readFailureStateReadOnly(path: string): FailureState { return readStoredState(path); }
1077
+
1075
1078
  function readStoredState(path: string): FailureState {
1076
1079
  let source: string;
1077
1080
  try { source = readFileSync(path, "utf8"); }
@@ -64,6 +64,7 @@ export type BackgroundWorkProvider = {
64
64
  showSection?(rows: BackgroundWorkRow[], now: number): boolean;
65
65
  parentRow?(now: number): BackgroundWorkRow | null;
66
66
  listRows(now: number): BackgroundWorkRow[];
67
+ prepareDetail?(id: string, options?: {logTailLines?: number}): void;
67
68
  detail(id: string, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null;
68
69
  armCloseLabel(row: BackgroundWorkRow): string;
69
70
  close(id: string): BackgroundWorkCloseOutcome;
@@ -728,6 +729,11 @@ function singleLine(value: unknown): string {
728
729
  return String(value ?? "").replace(/[\r\n\t]+/g, " ").replace(/ {2,}/g, " ").trim();
729
730
  }
730
731
 
732
+ function prepareDetail(navigatorId: string, options?: {logTailLines?: number}): void {
733
+ const {providerId,id}=splitRowKey(navigatorId);
734
+ try {state().providers.get(providerId)?.prepareDetail?.(id,options);}catch {/* observation failure retains cached detail */}
735
+ }
736
+
731
737
  function detailFor(navigatorId: string, now = Date.now(), options?: { logTailLines?: number }): BackgroundWorkDetail | null {
732
738
  const { providerId, id } = splitRowKey(navigatorId);
733
739
  const provider = state().providers.get(providerId);
@@ -989,10 +995,12 @@ function createOverlayComponent(
989
995
  const overlayState: OverlayState = { rows: initialRows, selected: 0 };
990
996
  let logTailRows: number = DEFAULT_LOG_TAIL_ROWS;
991
997
  const expandedSections = new Set<string>();
998
+ const initializedSections = new Set<string>();
992
999
  let detailId: string = initialDetailId;
993
1000
  const initialRow = initialRows.find((row) => row.navigatorId === detailId);
1001
+ prepareDetail(detailId,{logTailLines:logTailRows});
994
1002
  let detail: BackgroundWorkDetail | null = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? (initialRow ? fallbackDetail(initialRow) : null);
995
- applyDefaultExpandedSections(detail, expandedSections);
1003
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
996
1004
  {
997
1005
  const idx = overlayState.rows.findIndex((row) => row.navigatorId === detailId);
998
1006
  if (idx >= 0) overlayState.selected = idx;
@@ -1028,6 +1036,7 @@ function createOverlayComponent(
1028
1036
  const detailScheduler = createRenderScheduler(() => {
1029
1037
  if (closed) return;
1030
1038
  detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1039
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1031
1040
  requestRender();
1032
1041
  startDetailTimer();
1033
1042
  });
@@ -1079,8 +1088,10 @@ function createOverlayComponent(
1079
1088
  clearCloseArm();
1080
1089
  detailId = row.navigatorId;
1081
1090
  expandedSections.clear();
1091
+ initializedSections.clear();
1092
+ prepareDetail(detailId,{logTailLines:logTailRows});
1082
1093
  detail = detailFor(row.navigatorId, Date.now(), { logTailLines: logTailRows }) ?? fallbackDetail(row);
1083
- applyDefaultExpandedSections(detail, expandedSections);
1094
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1084
1095
  startDetailTimer();
1085
1096
  requestRender();
1086
1097
  }
@@ -1251,12 +1262,15 @@ function createOverlayComponent(
1251
1262
  const key = data === "m" || data === "M" ? "m" : "ctrl+s";
1252
1263
  if (!row || !provider?.handleDetailInput?.(row.id, key)) return;
1253
1264
  detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1265
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1254
1266
  refreshMainListWidget();
1255
1267
  requestRender();
1256
1268
  }
1257
1269
  else if (data === "l" || data === "L") {
1258
1270
  logTailRows = cycleLogTailRows(logTailRows);
1271
+ prepareDetail(detailId,{logTailLines:logTailRows});
1259
1272
  if (detailId) detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1273
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1260
1274
  requestRender();
1261
1275
  }
1262
1276
  else if (deps.matchKey(data, "escape")) {
@@ -1266,9 +1280,9 @@ function createOverlayComponent(
1266
1280
  /** Observation arrival updates this row without resetting selection or folded sections. */
1267
1281
  refreshDetail() {
1268
1282
  if (closed) return;
1269
- const wasLoading = detail?.status === "rebuilding";
1283
+ prepareDetail(detailId,{logTailLines:logTailRows});
1270
1284
  detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1271
- if (wasLoading) applyDefaultExpandedSections(detail, expandedSections);
1285
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1272
1286
  startDetailTimer();
1273
1287
  requestRender();
1274
1288
  },
@@ -1502,8 +1516,12 @@ function firstToggleableSectionId(detail: BackgroundWorkDetail | null | undefine
1502
1516
  return detail && isFoldableEvidence(detail) ? EVIDENCE_SECTION_ID : undefined;
1503
1517
  }
1504
1518
 
1505
- function applyDefaultExpandedSections(detail: BackgroundWorkDetail | null, expandedSections: Set<string>): void {
1519
+ function applyDefaultExpandedSections(detail: BackgroundWorkDetail | null, expandedSections: Set<string>, initializedSections: Set<string>): void {
1506
1520
  for (const section of detail?.foldedSections ?? []) {
1521
+ if (initializedSections.has(section.id)) continue;
1522
+ // Details can arrive after a running row's fallback. Initialize each section
1523
+ // on first arrival, then preserve the user's choice across observations.
1524
+ initializedSections.add(section.id);
1507
1525
  if (section.expandedByDefault) expandedSections.add(section.id);
1508
1526
  }
1509
1527
  }