pi-better-background-tasks 0.16.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 (40) hide show
  1. package/README.md +9 -0
  2. package/package.json +4 -2
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -1
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -1
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -1
  11. package/runtime-client/src/daemon-owner.mjs +2 -1
  12. package/runtime-client/src/runtime/work-client.mjs +16 -2
  13. package/src/failures.ts +4 -2
  14. package/src/index.ts +6 -30
  15. package/src/managed-authority.ts +28 -0
  16. package/src/managed-client.ts +60 -0
  17. package/src/managed-frontend.ts +131 -0
  18. package/src/navigator-provider.ts +14 -6
  19. package/src/observed-waits.ts +286 -48
  20. package/src/output.ts +12 -0
  21. package/src/registry.ts +18 -1
  22. package/src/runtime.ts +8 -2
  23. package/src/sandbox.ts +7 -0
  24. package/src/shared-callback-batcher.ts +4 -1
  25. package/src/shared-failure-observations.ts +3 -0
  26. package/src/shared-navigator.ts +23 -5
  27. package/src/shared-operation-coordinator/assignment-observation.mjs +48 -1
  28. package/src/shared-operation-coordinator/index.ts +2 -0
  29. package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  30. package/src/shared-operation-coordinator/src/background-requests.ts +79 -0
  31. package/src/shared-operation-coordinator/src/discovery.ts +9 -0
  32. package/src/shared-operation-coordinator/src/operations.ts +6 -4
  33. package/src/shared-operation-coordinator/src/result-supervision.ts +128 -0
  34. package/src/shared-operation-coordinator/src/schema.ts +50 -1
  35. package/src/shared-operation-coordinator/src/store.ts +38 -0
  36. package/src/shared-operation-coordinator/src/subagent-launch.ts +119 -0
  37. package/src/shared-operation-coordinator/src/types.ts +6 -0
  38. package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
  39. package/src/shared-work-client.mjs +16 -2
  40. package/src/tools.ts +76 -37
@@ -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
 
@@ -42,6 +42,7 @@ import {
42
42
  backgroundExecutionLimits,
43
43
  confineCommandSpec,
44
44
  resolveForegroundSandboxPlan,
45
+ currentForegroundSandboxPolicy,
45
46
  resolveWorkerSandboxPlan,
46
47
  sandboxProvenance,
47
48
  type ForegroundSandboxPlan,
@@ -255,6 +256,7 @@ export interface ParentNotification {
255
256
  * `notifyParent` is not delivery.
256
257
  */
257
258
  export interface ParentDelivery {
259
+ readonly receiptId?: string;
258
260
  delivered(): void;
259
261
  defer(reason: string): void;
260
262
  }
@@ -556,6 +558,16 @@ function rpcCode(error: unknown): string {
556
558
  }
557
559
 
558
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;
569
+ /** Production adapters leave global discovery and terminal import to the server. */
570
+ serverOwnedResults?: boolean;
559
571
  /** SQLite path. Defaults under the Pi agent directory. */
560
572
  storePath?: string;
561
573
  /** Durable supervisor record directory. Defaults beside the task registry. */
@@ -643,6 +655,8 @@ export function createObservedWaitHost(pi: ExtensionAPI, options: ObservedWaitHo
643
655
  return host;
644
656
  }
645
657
 
658
+ export function registerObservedWaitClient(pi: ExtensionAPI, host: ObservedWaitHost): void { hosts.set(pi as object, host); }
659
+
646
660
  export function getObservedWaitHost(pi: unknown): ObservedWaitHost | undefined {
647
661
  return pi && typeof pi === "object" ? hosts.get(pi as object) : undefined;
648
662
  }
@@ -658,6 +672,7 @@ interface LaunchContext {
658
672
  readonly cwd?: string;
659
673
  /** Launch-time sandbox provenance; never recomputed from the current profile. */
660
674
  readonly sandbox?: TaskSandboxProvenance;
675
+ readonly supervisionPolicy?: ForegroundSandboxPlan;
661
676
  /** Owner branch anchor captured at launch (undefined when unavailable). */
662
677
  readonly branchId?: string | null;
663
678
  callbackPendingAt?: number;
@@ -861,6 +876,7 @@ export class ObservedWaitHost {
861
876
  private readonly options: ObservedWaitHostOptions;
862
877
  private timer?: NodeJS.Timeout;
863
878
  private closed = false;
879
+ private activationAttempted = false;
864
880
  private unavailableReason?: string;
865
881
  private parentOrigin?: BackgroundTaskCallbackOrigin;
866
882
  private activeOrigin?: BackgroundTaskCallbackOrigin;
@@ -896,6 +912,7 @@ export class ObservedWaitHost {
896
912
  private continuationError?: string;
897
913
  private readonly launches = new Map<string, LaunchContext>();
898
914
  private readonly localCancels = new Set<string>();
915
+ private readonly resultHandoffs = new Set<string>();
899
916
  private readonly rpcRuns = new Map<string, RpcRunBinding>();
900
917
  private readonly waitOwners = new Map<string, OwnerIdentity>();
901
918
  private readonly stagedCheckpoints = new Map<string, { evidence: JsonRecord; toolCallId: string; checkpointRecorded: boolean }>();
@@ -912,7 +929,26 @@ export class ObservedWaitHost {
912
929
  private authorityPassCache?: Map<string, "live" | "dead" | "unknown">;
913
930
  /** Running operations this follower is currently assigned to supervise. */
914
931
  private readonly followerRunningTasks = new Set<string>();
915
- 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; }
916
952
  private lastOwnedTerminalAt = 0;
917
953
 
918
954
  constructor(private readonly pi: ExtensionAPI, options: ObservedWaitHostOptions = {}) {
@@ -972,12 +1008,16 @@ export class ObservedWaitHost {
972
1008
  return this.store !== undefined && !this.closed;
973
1009
  }
974
1010
 
1011
+ get usesServerResults(): boolean { return this.options.serverOwnedResults === true; }
1012
+ get hasActivated(): boolean { return this.activationAttempted; }
1013
+
975
1014
  get reason(): string | undefined {
976
1015
  return this.unavailableReason;
977
1016
  }
978
1017
 
979
1018
  /** Open the durable store and begin bounded reconciliation. */
980
1019
  start(ctx?: ExtensionContext): void {
1020
+ this.activationAttempted = true;
981
1021
  if (ctx) this.setActiveOrigin(ctx);
982
1022
  if (this.store) {
983
1023
  // The same host instance can be activated for another session without a
@@ -993,7 +1033,7 @@ export class ObservedWaitHost {
993
1033
  this.closed = false;
994
1034
  this.unavailableReason = undefined;
995
1035
  try {
996
- this.store = openStore({
1036
+ this.store = this.options.sharedStore ?? openStore({
997
1037
  path: this.storePath,
998
1038
  ...(this.options.now ? { now: this.options.now } : {}),
999
1039
  });
@@ -1027,7 +1067,7 @@ export class ObservedWaitHost {
1027
1067
  this.timer = undefined;
1028
1068
  this.releaseDiscoveryAuthority();
1029
1069
  this.releaseSupervisionAuthority();
1030
- try { this.store?.close(); } catch { /* already closed */ }
1070
+ try { if (!this.options.sharedStore) this.store?.close(); } catch { /* already closed */ }
1031
1071
  this.store = undefined;
1032
1072
  this.launches.clear();
1033
1073
  this.rpcRuns.clear();
@@ -1038,6 +1078,7 @@ export class ObservedWaitHost {
1038
1078
  this.activeContext = undefined;
1039
1079
  this.terminalRecoveryNeeded = false;
1040
1080
  this.pendingTerminalCallbacks.clear();
1081
+ this.callbackRecoveryScopes.clear();
1041
1082
  this.watchedRunningTasks.clear();
1042
1083
  this.discoveredTaskSidecars.clear();
1043
1084
  this.durableProjectionCache = undefined;
@@ -1059,13 +1100,14 @@ export class ObservedWaitHost {
1059
1100
  }
1060
1101
  }
1061
1102
 
1062
- private activeParentTerminalOperations(): OperationRecord[] {
1103
+ private activeParentTerminalOperations(claims = false): OperationRecord[] {
1063
1104
  const origin = this.activeOrigin;
1064
1105
  if (!this.store || !origin?.sessionId) return [];
1065
- return this.store.listOperations({
1066
- phase: "terminal",
1067
- ownerScope: { kind: "parent-session", sessionId: origin.sessionId, workspace: origin.cwd },
1068
- });
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;
1069
1111
  }
1070
1112
 
1071
1113
  /**
@@ -1112,9 +1154,18 @@ export class ObservedWaitHost {
1112
1154
  * pending set is seeded once at activation and by each terminal attempt; it is
1113
1155
  * not a scan of the historical terminal table on every 250 ms tick.
1114
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
+
1115
1165
  private retryPendingTerminalCallbacks(): void {
1116
1166
  if (!this.store || this.pendingTerminalCallbacks.size === 0) return;
1117
- for (const taskId of [...this.pendingTerminalCallbacks]) {
1167
+ for (const taskId of [...this.pendingTerminalCallbacks].slice(0, 64)) {
1168
+ this.pendingTerminalCallbacks.delete(taskId); this.rememberPendingCallback(taskId);
1118
1169
  const operation = this.operationForTask(taskId);
1119
1170
  if (!operation || operation.terminalRevision === 0) {
1120
1171
  this.pendingTerminalCallbacks.delete(taskId);
@@ -1163,7 +1214,16 @@ export class ObservedWaitHost {
1163
1214
  if (!this.store || this.closed) return;
1164
1215
  this.authorityPassCache = new Map();
1165
1216
  try {
1166
- const role = this.refreshDiscoveryAuthority();
1217
+ const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope);
1218
+ if (this.options.serverOwnedResults || discovery?.managed) {
1219
+ this.releaseDiscoveryAuthority();
1220
+ if (!this.options.serverOwnedResults) this.reconcileFollowerRunning();
1221
+ this.reconcileOwnerChanges();
1222
+ this.retryPendingTerminalCallbacks();
1223
+ await this.dispatchOutbox();
1224
+ return;
1225
+ }
1226
+ const role = this.refreshDiscoveryAuthority(discovery!.claim);
1167
1227
  this.noteDiscoveryRole(role);
1168
1228
  if (role === "holder") {
1169
1229
  this.discoverObservedTasks();
@@ -1241,14 +1301,11 @@ export class ObservedWaitHost {
1241
1301
  } catch {
1242
1302
  return;
1243
1303
  }
1244
- if (revision === this.lastChangeRevision) return;
1304
+ if (revision === this.lastChangeRevision && !this.pendingCallbackCursor) return;
1245
1305
  this.lastChangeRevision = revision;
1246
1306
  let operations: OperationRecord[];
1247
1307
  try {
1248
- operations = store.listOperations({
1249
- ownerScope: { kind: "parent-session", sessionId, workspace: ctx.cwd },
1250
- phase: "terminal",
1251
- });
1308
+ operations = this.activeParentTerminalOperations();
1252
1309
  } catch {
1253
1310
  return;
1254
1311
  }
@@ -1286,15 +1343,9 @@ export class ObservedWaitHost {
1286
1343
  * Acquire or confirm the one shared discovery claim. Process identity and
1287
1344
  * explicit close evidence decide replacement; elapsed time is not a lease.
1288
1345
  */
1289
- private refreshDiscoveryAuthority(): "holder" | "follower" {
1346
+ private refreshDiscoveryAuthority(claim: ReturnType<Store["readDiscoveryClaim"]>): "holder" | "follower" {
1290
1347
  const store = this.store;
1291
1348
  if (!store) return "follower";
1292
- let claim;
1293
- try {
1294
- claim = store.readDiscoveryClaim(this.discoveryScope);
1295
- } catch {
1296
- return "follower";
1297
- }
1298
1349
  if (claim?.hostId === this.hostId) {
1299
1350
  this.discoveryToken = claim.token;
1300
1351
  return "holder";
@@ -1351,9 +1402,16 @@ export class ObservedWaitHost {
1351
1402
  }
1352
1403
  const owner = this.ownerFor(input.ctx);
1353
1404
  const prepared = this.prepareLaunch(input.kind, input.params, "bg_task_spawn", owner, undefined);
1405
+ if (this.options.serverOwnedResults) {
1406
+ this.assertResultAdmission(prepared.provenance);
1407
+ const client = await this.resultSupervisionClient();
1408
+ client.close();
1409
+ }
1354
1410
  const operationId = `op_${randomUUID()}`;
1355
1411
  const token = `launch_${randomUUID()}`;
1356
1412
  const taskId = supervisorTaskIdForToken(token);
1413
+ this.options.assertAdmission?.();
1414
+ this.options.beforeParentOperation?.({ operationId, taskId, token });
1357
1415
  store.registerOperation({
1358
1416
  operationId,
1359
1417
  taskId,
@@ -1374,12 +1432,15 @@ export class ObservedWaitHost {
1374
1432
  ...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
1375
1433
  cwd: prepared.cwd,
1376
1434
  sandbox: prepared.provenance,
1435
+ supervisionPolicy: prepared.plan,
1377
1436
  branchId: owner.branchId ?? null,
1378
1437
  };
1379
1438
  // Persist supervision metadata outside the task execution record so a
1380
1439
  // replacement host can still notify the right parent and never re-route a
1381
1440
  // worker-owned operation to the parent's callback.
1382
1441
  this.writeLaunchContext(taskId, launchContext);
1442
+ this.launches.set(taskId, launchContext);
1443
+ if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
1383
1444
  const started = await this.startSupervisor({
1384
1445
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1385
1446
  });
@@ -1501,21 +1562,25 @@ export class ObservedWaitHost {
1501
1562
  /** Called from an actual admitted parent tool context, not a wire owner claim. */
1502
1563
  authorizeCancellationForParent(ctx: ExtensionContext, taskId: string, requestId: string): string {
1503
1564
  if (this.localCancels.has(taskId)) throw new Error("not_accepted: old cancellation admission is still draining");
1504
- const operation = this.ownedOperation(taskId, this.ownerFor(ctx));
1505
- if (this.supervisionAuthority(operation) === "foreign") throw new Error("permission-unavailable: live legacy or unknown supervisor prevents cancellation handoff");
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;
1570
+ const managed = this.requireStore().resultSupervision(operation.operationId);
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");
1506
1572
  const proof = cancellationCredential();
1507
1573
  const previous = this.requireStore().getTaskCancellation({ owner: operation.owner, idempotencyKey: requestId });
1508
1574
  if (previous && previous.operationId !== operation.operationId) throw new Error("not_accepted: request-conflict: cancellation key belongs to another task");
1509
1575
  this.requireStore().admitTaskCancellation({ credentialHash: proof.hash, directory: this.directory, request: previous ?? {
1510
1576
  owner: operation.owner, idempotencyKey: requestId, operationId: operation.operationId,
1511
1577
  expectedLaunchToken: operation.launchToken, expectedTerminalRevision: operation.terminalRevision,
1512
- expectedHostId: operation.supervision?.hostId ?? "unavailable", reason: "explicit stop",
1578
+ expectedHostId: operation.supervision?.hostId ?? "unavailable", reason: admission?.reason ?? "explicit stop",
1513
1579
  } });
1514
1580
  return proof.credential;
1515
1581
  }
1516
1582
 
1517
1583
  private async stopThroughRuntime(ctx: ExtensionContext, taskId: string, requestId: string): Promise<StatusView> {
1518
- this.ownedOperation(taskId, this.ownerFor(ctx));
1519
1584
  const root = realpathSync(dirname(this.storePath));
1520
1585
  const registrationPath = join(root, "server-registration-v1.json");
1521
1586
  if (!existsSync(registrationPath)) {
@@ -1539,7 +1604,12 @@ export class ObservedWaitHost {
1539
1604
  receipt = await client.request("runtime_cancel_task", { credential });
1540
1605
  }
1541
1606
  if (receipt.state === "outcome_unknown" || !receipt.result) throw new Error(`${receipt.state}: cancellation ${requestId}; query the same request before retrying`);
1542
- 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));
1543
1613
  } catch (error) {
1544
1614
  const message = String(error);
1545
1615
  if (/not_accepted|accepted:|outcome_unknown/.test(message)) throw error;
@@ -1557,7 +1627,7 @@ export class ObservedWaitHost {
1557
1627
  */
1558
1628
  listDurableTasks(
1559
1629
  origin: BackgroundTaskCallbackOrigin,
1560
- options: { retentionMs?: number; includeDismissed?: boolean } = {},
1630
+ options: { retentionMs?: number; includeDismissed?: boolean; fresh?: boolean } = {},
1561
1631
  ): DurableTaskProjection[] {
1562
1632
  const store = this.store;
1563
1633
  if (!store || this.closed) return [];
@@ -1567,7 +1637,7 @@ export class ObservedWaitHost {
1567
1637
  const originKey = `${origin.cwd}\0${origin.sessionId}`;
1568
1638
  const cacheKey = `${originKey}\0${options.retentionMs ?? ""}\0${options.includeDismissed === true ? 1 : 0}`;
1569
1639
  const cached = this.durableProjectionCache;
1570
- if (cached && cached.key === cacheKey && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
1640
+ if (!options.fresh && cached && cached.key === cacheKey && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
1571
1641
  this.projectionMetrics.cacheHits += 1;
1572
1642
  if (options.retentionMs === undefined) return cached.list;
1573
1643
  const live = cached.list.filter((projection) => !this.expiredProjection(projection, options, now));
@@ -1787,8 +1857,11 @@ export class ObservedWaitHost {
1787
1857
  }
1788
1858
 
1789
1859
  private status(taskId: string, owner: OwnerIdentity): StatusView {
1790
- const store = this.requireStore();
1791
- 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;
1792
1865
  const inspection = this.inspect(taskId);
1793
1866
  this.reconcileInspection(operation, inspection);
1794
1867
  const current = store.getOperation(operation.operationId) ?? operation;
@@ -1933,6 +2006,124 @@ export class ObservedWaitHost {
1933
2006
  return this.waitView(store.getWait({ waitId: result.wait.waitId }) ?? result.wait);
1934
2007
  }
1935
2008
 
2009
+ private async resultSupervisionClient(): Promise<any> {
2010
+ const root = realpathSync(dirname(this.storePath));
2011
+ const ports = (globalThis as any)[Symbol.for("pi-better-server:result-supervision-ports-v1")];
2012
+ const port = ports?.get(root);
2013
+ if (port) return { request: async (type: string) => {
2014
+ if (type !== "runtime_result_supervision") throw new Error("not_accepted: unsupported in-process supervision operation");
2015
+ return port.status();
2016
+ }, close() {} };
2017
+ // @ts-expect-error Generated standalone lightweight socket client.
2018
+ const { WorkClient } = await import("./shared-work-client.mjs");
2019
+ const connect = async () => {
2020
+ const registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8"));
2021
+ if (registration.version !== 1 || registration.agentDir !== root) throw new Error("Invalid canonical runtime registration");
2022
+ const connection = new WorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-result-supervision-v1"]);
2023
+ try { await connection.ready; return connection; }
2024
+ catch (error) { connection.close(); throw error; }
2025
+ };
2026
+ let client;
2027
+ try { client = await connect(); }
2028
+ catch (error) {
2029
+ if (!["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
2030
+ // The packaged canonical client owns artifact verification, owner checks and startup.
2031
+ // @ts-expect-error Generated by sync-runtime-client during package preparation.
2032
+ const { ensureRuntime } = await import("../runtime-client/src/runtime/client.mjs");
2033
+ await ensureRuntime({ agentDir: root, serverDir: process.env.PI_SERVER_DIR });
2034
+ client = await connect();
2035
+ }
2036
+ return client;
2037
+ }
2038
+
2039
+ async refreshManagedResults(): Promise<void> {
2040
+ if (!this.options.serverOwnedResults || !this.store || this.closed) return;
2041
+ const client = await this.resultSupervisionClient();
2042
+ try { await client.request("runtime_result_supervision"); }
2043
+ finally { client.close(); }
2044
+ }
2045
+
2046
+ /** A runner may finish between the server pass and this session's inspection. */
2047
+ async settledStatusForParent(ctx: ExtensionContext, taskId: string): Promise<StatusView> {
2048
+ const observed = this.statusForParent(ctx, taskId);
2049
+ if (!this.options.serverOwnedResults || observed.terminalRevision > 0 || ["running", "starting"].includes(observed.status)) return observed;
2050
+ await this.refreshManagedResults();
2051
+ const imported = this.statusForParent(ctx, taskId);
2052
+ if (imported.terminalRevision === 0) throw new Error("Terminal runner evidence is awaiting authoritative server import; supervision is unavailable.");
2053
+ return imported;
2054
+ }
2055
+
2056
+ private assertResultAdmission(captured: TaskSandboxProvenance, transferring: ReadonlySet<string> = new Set()): void {
2057
+ const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
2058
+ if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
2059
+ throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
2060
+ }
2061
+ if (captured.policySource !== "no-publisher" && !currentForegroundSandboxPolicy(this.pi)) {
2062
+ throw new Error("permission-unavailable: expected current Background permission source is unavailable");
2063
+ }
2064
+ for (const operation of this.requireStore().listOperations({ phase: "running" })) {
2065
+ if (!existsSync(this.sidecarPath(operation.taskId)) || this.requireStore().resultSupervision(operation.operationId)) continue;
2066
+ // A compatible peer may be between registration and its grant transaction.
2067
+ // It cannot start a runner until that grant commits and never discovers globally.
2068
+ if (operation.supervision?.resultAdapter === 1) continue;
2069
+ if (this.supervisionAuthority(operation) === "foreign") {
2070
+ throw new Error("permission-unavailable: a live or unknown legacy operation holder prevents scope handoff");
2071
+ }
2072
+ // A dead holder is not itself a grant. Fencing discovery for a different
2073
+ // task would strand this runner: the server only imports explicit grants.
2074
+ if (!transferring.has(operation.operationId)) {
2075
+ throw new Error("permission-unavailable: an untransferred legacy operation prevents scope handoff; explicitly supervise its wait first");
2076
+ }
2077
+ }
2078
+ }
2079
+
2080
+ private async handoffResults(operations: readonly OperationRecord[]): Promise<void> {
2081
+ const client = await this.resultSupervisionClient();
2082
+ try {
2083
+ const manager = await client.request("runtime_result_supervision");
2084
+ const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
2085
+ if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
2086
+ throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
2087
+ }
2088
+ const transfers = [];
2089
+ const transferring = new Set(operations.map(operation => operation.operationId));
2090
+ for (const operation of operations) {
2091
+ if (this.requireStore().resultSupervision(operation.operationId)) continue;
2092
+ if (this.supervisionAuthority(operation) === "foreign" || this.localCancels.has(operation.taskId)) {
2093
+ throw new Error("permission-unavailable: original supervision owner is live, unknown or draining");
2094
+ }
2095
+ const context = this.launchContext(operation.taskId);
2096
+ if (!context?.sandbox || !context.supervisionPolicy || !operation.authorityRef) throw new Error("permission-unavailable: captured Background authority is unavailable");
2097
+ this.assertResultAdmission(context.sandbox, transferring);
2098
+ const current = currentForegroundSandboxPolicy(this.pi);
2099
+ if (context.sandbox.policySource !== "no-publisher" && !current) throw new Error("permission-unavailable: expected current Background permission source is unavailable");
2100
+ transfers.push({ operationId: operation.operationId,
2101
+ expectedHostId: operation.supervision?.hostId ?? "unavailable", directory: this.directory, hostId: manager.hostId, epoch: manager.epoch,
2102
+ capability: { adapter: "background-results-v1", captured: { provenance: context.sandbox, policy: context.supervisionPolicy }, current: current ?? { state: "legacy-unconfined", policySource: "no-publisher" } } });
2103
+ }
2104
+ // Validate the whole batch, then stop admission before the durable CAS.
2105
+ for (const transfer of transfers) this.resultHandoffs.add(transfer.operationId);
2106
+ try {
2107
+ this.requireStore().handoffResultScope({ scope: this.discoveryScope,
2108
+ expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
2109
+ this.discoveryToken = undefined;
2110
+ this.discoveryRole = "follower";
2111
+ } catch (error) {
2112
+ // The transaction rolled back; only these uncommitted local fences may reopen.
2113
+ for (const transfer of transfers) this.resultHandoffs.delete(transfer.operationId);
2114
+ throw error;
2115
+ }
2116
+ await client.request("runtime_result_supervision");
2117
+ } finally { client.close(); }
2118
+ }
2119
+
2120
+ async superviseParentWait(ctx: ExtensionContext, taskIds: readonly string[], note: string): Promise<WaitView> {
2121
+ this.noteParentContext(ctx);
2122
+ const operations = this.operationsForTaskIds(this.ownerFor(ctx), taskIds);
2123
+ await this.handoffResults(operations);
2124
+ return this.waitForParent(ctx, taskIds, note);
2125
+ }
2126
+
1936
2127
  waitViewForParent(ctx: ExtensionContext, waitId: string, generation?: number): WaitView | undefined {
1937
2128
  const store = this.requireStore();
1938
2129
  const wait = store.getWait({ waitId, ...(generation ? { generation } : {}) });
@@ -1973,6 +2164,11 @@ export class ObservedWaitHost {
1973
2164
  const store = this.requireStore();
1974
2165
  if (input.params.ssh) throw new Error("Worker background launches are local-only; structured SSH is unavailable through this service.");
1975
2166
  const owner = this.workerOwner(run);
2167
+ if (this.options.serverOwnedResults) {
2168
+ const client = await this.resultSupervisionClient();
2169
+ client.close();
2170
+ }
2171
+ const assertWorkerPolicy = this.options.prepareWorkerPolicy?.(run);
1976
2172
  const prepared = this.prepareLaunch(
1977
2173
  input.kind,
1978
2174
  input.params,
@@ -1981,6 +2177,7 @@ export class ObservedWaitHost {
1981
2177
  input.policy,
1982
2178
  run.workspace,
1983
2179
  );
2180
+ if (this.options.serverOwnedResults) this.assertResultAdmission(prepared.provenance);
1984
2181
  const operationId = `op_${randomUUID()}`;
1985
2182
  const token = `launch_${randomUUID()}`;
1986
2183
  const taskId = supervisorTaskIdForToken(token);
@@ -2004,11 +2201,14 @@ export class ObservedWaitHost {
2004
2201
  ...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
2005
2202
  cwd: prepared.cwd,
2006
2203
  sandbox: prepared.provenance,
2204
+ supervisionPolicy: prepared.plan,
2007
2205
  branchId: owner.branchId ?? null,
2008
2206
  };
2009
2207
  this.writeLaunchContext(taskId, launchContext);
2208
+ this.launches.set(taskId, launchContext);
2209
+ if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
2010
2210
  const started = await this.startSupervisor({
2011
- token, taskId, kind: input.kind, params: input.params, prepared, operationId,
2211
+ token, taskId, kind: input.kind, params: input.params, prepared, operationId, assertDispatch: assertWorkerPolicy,
2012
2212
  });
2013
2213
  this.launches.set(taskId, launchContext);
2014
2214
  this.emitDurableTaskChange(owner);
@@ -2839,6 +3039,7 @@ export class ObservedWaitHost {
2839
3039
  params: Record<string, unknown>;
2840
3040
  prepared: ReturnType<ObservedWaitHost["prepareLaunch"]>;
2841
3041
  operationId: string;
3042
+ assertDispatch?: () => void;
2842
3043
  }): Promise<{ started: boolean; claimed: boolean }> {
2843
3044
  const { token, taskId, kind, params, prepared, operationId } = input;
2844
3045
  const profilePath = join(supervisorPaths(this.directory, taskId).dir, "sandbox.sb");
@@ -2866,6 +3067,15 @@ export class ObservedWaitHost {
2866
3067
  ...(typeof params.max_log_bytes === "number" ? { maxLogBytes: params.max_log_bytes } : {}),
2867
3068
  ...(kind === "watch" ? this.watchOptions(params) : this.processTimeout(params)),
2868
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
+ }
2869
3079
  const started = await this.supervisor.start(options);
2870
3080
  return { started: started.started, claimed: started.claimed };
2871
3081
  }
@@ -2913,6 +3123,8 @@ export class ObservedWaitHost {
2913
3123
 
2914
3124
  private reconcileOperation(operation: OperationRecord): void {
2915
3125
  if (operation.terminalRevision > 0) return;
3126
+ if (this.resultHandoffs.has(operation.operationId) || (operation.resultManaged ?? !!this.store?.resultSupervision(operation.operationId))) return;
3127
+ if (this.options.serverOwnedResults) return;
2916
3128
  const authority = this.supervisionAuthority(operation);
2917
3129
  if (authority === "foreign") return;
2918
3130
  let claimed = false;
@@ -3078,6 +3290,8 @@ export class ObservedWaitHost {
3078
3290
  }
3079
3291
 
3080
3292
  private recordTerminal(operation: OperationRecord, inspection: SupervisorInspection): void {
3293
+ if (this.options.serverOwnedResults) return;
3294
+ if (this.resultHandoffs.has(operation.operationId) || this.store?.resultSupervision(operation.operationId)) return;
3081
3295
  const store = this.requireStore();
3082
3296
  const status = inspection.status;
3083
3297
  const outcome = terminalOutcome(status);
@@ -3155,13 +3369,14 @@ export class ObservedWaitHost {
3155
3369
  if (!this.options.notifyParent) return;
3156
3370
  if (operation.owner.kind !== "parent-session") return;
3157
3371
  if (!context) return;
3158
- if (context.callback === false) return;
3372
+ if (context.callback === false) { this.store?.setParentCallbackPending(operation.taskId, false); return; }
3159
3373
  // Never write any journal field while a newer or unprovable other host owns
3160
3374
  // the claim. In particular, a stale host's reconcile must not rewrite its
3161
3375
  // cached claim token over the current shared one.
3162
3376
  const claim = this.claimState(context.callbackClaimedBy);
3163
3377
  if (claim === "live" || claim === "unknown") return;
3164
3378
  if (context.callbackDeliveredAt !== undefined) {
3379
+ this.store?.setParentCallbackPending(operation.taskId, false);
3165
3380
  this.pendingTerminalCallbacks.delete(operation.taskId);
3166
3381
  skip("already delivered");
3167
3382
  return;
@@ -3201,7 +3416,7 @@ export class ObservedWaitHost {
3201
3416
  // A terminal result can become eligible later: the live session may have
3202
3417
  // been settling when the record was produced, or the owner may navigate
3203
3418
  // back to an eligible descendant branch. Keep retrying only this id.
3204
- this.pendingTerminalCallbacks.add(operation.taskId);
3419
+ this.rememberPendingCallback(operation.taskId);
3205
3420
  const origin = context.parentOrigin ?? { cwd: operation.owner.workspace, sessionId: operation.owner.sessionId };
3206
3421
  const branchId = context.branchId ?? operation.owner.branchId;
3207
3422
  if (!this.isParentOriginActive(origin, branchId)) {
@@ -3221,6 +3436,7 @@ export class ObservedWaitHost {
3221
3436
  const claimToken = context.callbackClaimToken;
3222
3437
  let settled = false;
3223
3438
  const delivery: ParentDelivery = {
3439
+ receiptId: `background-terminal:${operation.operationId}`,
3224
3440
  delivered: () => {
3225
3441
  if (settled) return;
3226
3442
  settled = true;
@@ -3277,13 +3493,13 @@ export class ObservedWaitHost {
3277
3493
  if (!context || context.callbackDeliveredAt !== undefined) return;
3278
3494
  const claim = this.claimState(context.callbackClaimedBy);
3279
3495
  if (claim === "live" || claim === "unknown") {
3280
- this.pendingTerminalCallbacks.add(taskId);
3496
+ this.rememberPendingCallback(taskId);
3281
3497
  return; // preserve the current owner's claim without any write
3282
3498
  }
3283
3499
  context.callbackPendingAt ??= Date.now();
3284
3500
  this.launches.set(taskId, context);
3285
3501
  this.writeLaunchContext(taskId, context);
3286
- this.pendingTerminalCallbacks.add(taskId);
3502
+ this.rememberPendingCallback(taskId);
3287
3503
  }
3288
3504
 
3289
3505
  private completeTerminalCallback(taskId: string, claimToken?: string): void {
@@ -3313,7 +3529,7 @@ export class ObservedWaitHost {
3313
3529
  if (!context || context.callbackDeliveredAt !== undefined) return;
3314
3530
  // A stale suppression must not clear the claim of a newer attempt.
3315
3531
  if (claimToken !== undefined && context.callbackClaimToken !== claimToken) return;
3316
- this.pendingTerminalCallbacks.add(taskId);
3532
+ this.rememberPendingCallback(taskId);
3317
3533
  context.callbackDeferredReason = oneLine(reason, 200);
3318
3534
  context.callbackAttemptedAt = Date.now();
3319
3535
  context.callbackSkipReason = `deferred: ${oneLine(reason, 160)}`;
@@ -3416,7 +3632,7 @@ export class ObservedWaitHost {
3416
3632
  });
3417
3633
  } catch { /* another host already recovered it */ }
3418
3634
  }
3419
- for (const operation of this.activeParentTerminalOperations()) {
3635
+ for (const operation of this.activeParentTerminalOperations(true)) {
3420
3636
  const context = this.currentLaunchContext(operation.taskId);
3421
3637
  if (!context?.callbackClaimedBy || context.callbackClaimedBy === this.hostId) continue;
3422
3638
  if (this.claimState(context.callbackClaimedBy) !== "dead") continue;
@@ -3539,6 +3755,7 @@ export class ObservedWaitHost {
3539
3755
  }
3540
3756
  let settled = false;
3541
3757
  const delivery: ParentDelivery = {
3758
+ receiptId: event.eventId,
3542
3759
  delivered: () => {
3543
3760
  if (settled) return;
3544
3761
  settled = true;
@@ -3846,8 +4063,9 @@ export class ObservedWaitHost {
3846
4063
  * on every session_tree/branch navigation. Branch changes must be visible to
3847
4064
  * a queued callback *before* the batcher decides whether to deliver it.
3848
4065
  */
3849
- noteParentContext(ctx: ExtensionContext): void {
3850
- this.setActiveOrigin(ctx);
4066
+ noteParentContext(ctx: ExtensionContext, options: {recover?: boolean} = {}): void {
4067
+ this.setActiveOrigin(ctx, options.recover !== false);
4068
+ if(options.recover === false)return;
3851
4069
  if (!this.store) return;
3852
4070
  this.recoverAbandonedDeliveries();
3853
4071
  if (this.terminalRecoveryNeeded) {
@@ -3859,7 +4077,7 @@ export class ObservedWaitHost {
3859
4077
  this.writeHostDebug();
3860
4078
  }
3861
4079
 
3862
- private setActiveOrigin(ctx: ExtensionContext): void {
4080
+ private setActiveOrigin(ctx: ExtensionContext, debug = true): void {
3863
4081
  const previous = this.activeContext;
3864
4082
  const previousKey = previous ? this.contextKey(previous) : undefined;
3865
4083
  const nextSessionId = this.sessionIdIfAvailable(ctx);
@@ -3875,11 +4093,16 @@ export class ObservedWaitHost {
3875
4093
  // A tool call or activation for a different session/workspace must seed the
3876
4094
  // terminal callback journal once. Same-session calls keep the live context
3877
4095
  // current without rescanning historical terminal records.
3878
- if (!previous || previousKey !== nextKey) {
3879
- 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) {
3880
4100
  this.lastChangeRevision = -1;
4101
+ this.pendingCallbackCursor = undefined;
4102
+ this.pendingClaimCursor = undefined;
3881
4103
  }
3882
- this.writeHostDebug();
4104
+ this.activeBranchSignature = branchSignature;
4105
+ if(debug)this.writeHostDebug();
3883
4106
  }
3884
4107
 
3885
4108
  private contextKey(ctx: ExtensionContext): string | undefined {
@@ -3925,6 +4148,7 @@ export class ObservedWaitHost {
3925
4148
  hostId: this.hostId,
3926
4149
  storeOpen: !!this.store,
3927
4150
  closed: this.closed,
4151
+ managementMode: this.options.serverOwnedResults ? "server-client" : "legacy",
3928
4152
  activeContext: !!ctx,
3929
4153
  activeSessionId: ctx ? this.sessionIdIfAvailable(ctx) ?? this.sessionId(ctx) : undefined,
3930
4154
  activeCwd: ctx ? ctx.cwd : undefined,
@@ -3951,10 +4175,21 @@ export class ObservedWaitHost {
3951
4175
 
3952
4176
  private writeLaunchContext(taskId: string, context: LaunchContext): void {
3953
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);
3954
4186
  const path = this.sidecarPath(taskId);
3955
4187
  mkdirSync(dirname(path), { recursive: true });
3956
- writeFileSync(path, JSON.stringify(context), { mode: 0o600 });
3957
- } 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 */ }
3958
4193
  }
3959
4194
 
3960
4195
  private readLaunchContext(taskId: string): LaunchContext | undefined {
@@ -3974,6 +4209,8 @@ export class ObservedWaitHost {
3974
4209
  ...(typeof value.cwd === "string" ? { cwd: value.cwd } : {}),
3975
4210
  ...(value.sandbox && typeof value.sandbox === "object" && !Array.isArray(value.sandbox)
3976
4211
  ? { sandbox: value.sandbox as TaskSandboxProvenance } : {}),
4212
+ ...(value.supervisionPolicy && typeof value.supervisionPolicy === "object"
4213
+ ? { supervisionPolicy: value.supervisionPolicy } : {}),
3977
4214
  ...(typeof value.branchId === "string" || value.branchId === null ? { branchId: value.branchId } : {}),
3978
4215
  ...(typeof value.callbackPendingAt === "number" ? { callbackPendingAt: value.callbackPendingAt } : {}),
3979
4216
  ...(typeof value.callbackDeliveredAt === "number" ? { callbackDeliveredAt: value.callbackDeliveredAt }
@@ -4065,7 +4302,8 @@ export class ObservedWaitHost {
4065
4302
  }
4066
4303
 
4067
4304
  private supervision(): SupervisionIdentity {
4068
- return { hostId: this.hostId, runnerId: null, processStartToken: null };
4305
+ return { hostId: this.hostId, runnerId: null, processStartToken: null, resultScope: this.discoveryScope,
4306
+ ...(this.options.serverOwnedResults ? { resultAdapter: 1 as const } : {}) };
4069
4307
  }
4070
4308
 
4071
4309
  private parentAuthority(owner: OwnerIdentity, plan: ForegroundSandboxPlan): string {