pi-better-background-tasks 0.15.4 → 0.17.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 (42) hide show
  1. package/README.md +22 -0
  2. package/package.json +5 -2
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -0
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -0
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -0
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -0
  11. package/runtime-client/scripts/private-runtime/format.mjs +90 -0
  12. package/runtime-client/src/daemon-owner.mjs +218 -0
  13. package/runtime-client/src/runtime/client.mjs +130 -0
  14. package/runtime-client/src/runtime/root.mjs +41 -0
  15. package/runtime-client/src/runtime/socket.mjs +9 -0
  16. package/runtime-client/src/runtime/status-cli.mjs +14 -0
  17. package/runtime-client/src/runtime/work-client.mjs +102 -0
  18. package/runtime-client/src/startup/artifact.mjs +76 -0
  19. package/runtime-client/src/startup/install.mjs +184 -0
  20. package/runtime-client/src/startup/managed-types.mjs +1 -0
  21. package/runtime-client/src/startup/runtime.mjs +120 -0
  22. package/src/goal-provider.ts +11 -7
  23. package/src/index.ts +4 -0
  24. package/src/observed-waits.ts +255 -37
  25. package/src/output.ts +16 -13
  26. package/src/registry.ts +15 -0
  27. package/src/shared-harness-settings.ts +4 -2
  28. package/src/shared-log-utils.ts +18 -7
  29. package/src/shared-navigator.ts +16 -4
  30. package/src/shared-operation-coordinator/assignment-observation.mjs +80 -3
  31. package/src/shared-operation-coordinator/index.ts +2 -0
  32. package/src/shared-operation-coordinator/src/discovery.ts +9 -0
  33. package/src/shared-operation-coordinator/src/errors.ts +2 -0
  34. package/src/shared-operation-coordinator/src/operations.ts +6 -4
  35. package/src/shared-operation-coordinator/src/result-supervision.ts +128 -0
  36. package/src/shared-operation-coordinator/src/schema.ts +39 -1
  37. package/src/shared-operation-coordinator/src/store.ts +55 -0
  38. package/src/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  39. package/src/shared-operation-coordinator/src/types.ts +6 -0
  40. package/src/shared-work-client.mjs +102 -0
  41. package/src/tools.ts +87 -59
  42. package/src/work-observation.ts +117 -0
@@ -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,
@@ -49,6 +50,7 @@ import {
49
50
  } from "./sandbox.js";
50
51
  import {
51
52
  openStore,
53
+ cancellationCredential,
52
54
  type AcknowledgeDisposition,
53
55
  type EvidenceKind,
54
56
  type OperationEvidenceRecord,
@@ -555,6 +557,8 @@ function rpcCode(error: unknown): string {
555
557
  }
556
558
 
557
559
  export interface ObservedWaitHostOptions {
560
+ /** Production adapters leave global discovery and terminal import to the server. */
561
+ serverOwnedResults?: boolean;
558
562
  /** SQLite path. Defaults under the Pi agent directory. */
559
563
  storePath?: string;
560
564
  /** Durable supervisor record directory. Defaults beside the task registry. */
@@ -657,6 +661,7 @@ interface LaunchContext {
657
661
  readonly cwd?: string;
658
662
  /** Launch-time sandbox provenance; never recomputed from the current profile. */
659
663
  readonly sandbox?: TaskSandboxProvenance;
664
+ readonly supervisionPolicy?: ForegroundSandboxPlan;
660
665
  /** Owner branch anchor captured at launch (undefined when unavailable). */
661
666
  readonly branchId?: string | null;
662
667
  callbackPendingAt?: number;
@@ -835,6 +840,20 @@ function mapEvidence(
835
840
  }));
836
841
  }
837
842
 
843
+ /** Shared terminal publication contract for the host and fixed server cancel adapter. */
844
+ export function supervisorTerminalPublication(operation: OperationRecord, inspection: SupervisorInspection, refs = evidenceFor(inspection)) {
845
+ const status = inspection.status;
846
+ const outcome = terminalOutcome(status);
847
+ return {
848
+ operationId: operation.operationId,
849
+ eventId: `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`,
850
+ outcome, owner: operation.owner,
851
+ evidence: refs.map(ref => ({ kind: ref.kind, ref: ref.ref, ...(ref.summary ? { summary: ref.summary } : {}), detailLost: ref.detailLost })),
852
+ ...(outcome === "lost" ? { detailLost: true } : {}),
853
+ reason: inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
854
+ };
855
+ }
856
+
838
857
  export class ObservedWaitHost {
839
858
  readonly service: BackgroundOperationService;
840
859
  private store?: Store;
@@ -846,6 +865,7 @@ export class ObservedWaitHost {
846
865
  private readonly options: ObservedWaitHostOptions;
847
866
  private timer?: NodeJS.Timeout;
848
867
  private closed = false;
868
+ private activationAttempted = false;
849
869
  private unavailableReason?: string;
850
870
  private parentOrigin?: BackgroundTaskCallbackOrigin;
851
871
  private activeOrigin?: BackgroundTaskCallbackOrigin;
@@ -880,6 +900,8 @@ export class ObservedWaitHost {
880
900
  private continuation?: ContinuationAdapter;
881
901
  private continuationError?: string;
882
902
  private readonly launches = new Map<string, LaunchContext>();
903
+ private readonly localCancels = new Set<string>();
904
+ private readonly resultHandoffs = new Set<string>();
883
905
  private readonly rpcRuns = new Map<string, RpcRunBinding>();
884
906
  private readonly waitOwners = new Map<string, OwnerIdentity>();
885
907
  private readonly stagedCheckpoints = new Map<string, { evidence: JsonRecord; toolCallId: string; checkpointRecorded: boolean }>();
@@ -956,12 +978,16 @@ export class ObservedWaitHost {
956
978
  return this.store !== undefined && !this.closed;
957
979
  }
958
980
 
981
+ get usesServerResults(): boolean { return this.options.serverOwnedResults === true; }
982
+ get hasActivated(): boolean { return this.activationAttempted; }
983
+
959
984
  get reason(): string | undefined {
960
985
  return this.unavailableReason;
961
986
  }
962
987
 
963
988
  /** Open the durable store and begin bounded reconciliation. */
964
989
  start(ctx?: ExtensionContext): void {
990
+ this.activationAttempted = true;
965
991
  if (ctx) this.setActiveOrigin(ctx);
966
992
  if (this.store) {
967
993
  // The same host instance can be activated for another session without a
@@ -1147,7 +1173,16 @@ export class ObservedWaitHost {
1147
1173
  if (!this.store || this.closed) return;
1148
1174
  this.authorityPassCache = new Map();
1149
1175
  try {
1150
- const role = this.refreshDiscoveryAuthority();
1176
+ const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope);
1177
+ if (this.options.serverOwnedResults || discovery?.managed) {
1178
+ this.releaseDiscoveryAuthority();
1179
+ if (!this.options.serverOwnedResults) this.reconcileFollowerRunning();
1180
+ this.reconcileOwnerChanges();
1181
+ this.retryPendingTerminalCallbacks();
1182
+ await this.dispatchOutbox();
1183
+ return;
1184
+ }
1185
+ const role = this.refreshDiscoveryAuthority(discovery!.claim);
1151
1186
  this.noteDiscoveryRole(role);
1152
1187
  if (role === "holder") {
1153
1188
  this.discoverObservedTasks();
@@ -1270,15 +1305,9 @@ export class ObservedWaitHost {
1270
1305
  * Acquire or confirm the one shared discovery claim. Process identity and
1271
1306
  * explicit close evidence decide replacement; elapsed time is not a lease.
1272
1307
  */
1273
- private refreshDiscoveryAuthority(): "holder" | "follower" {
1308
+ private refreshDiscoveryAuthority(claim: ReturnType<Store["readDiscoveryClaim"]>): "holder" | "follower" {
1274
1309
  const store = this.store;
1275
1310
  if (!store) return "follower";
1276
- let claim;
1277
- try {
1278
- claim = store.readDiscoveryClaim(this.discoveryScope);
1279
- } catch {
1280
- return "follower";
1281
- }
1282
1311
  if (claim?.hostId === this.hostId) {
1283
1312
  this.discoveryToken = claim.token;
1284
1313
  return "holder";
@@ -1335,6 +1364,11 @@ export class ObservedWaitHost {
1335
1364
  }
1336
1365
  const owner = this.ownerFor(input.ctx);
1337
1366
  const prepared = this.prepareLaunch(input.kind, input.params, "bg_task_spawn", owner, undefined);
1367
+ if (this.options.serverOwnedResults) {
1368
+ this.assertResultAdmission(prepared.provenance);
1369
+ const client = await this.resultSupervisionClient();
1370
+ client.close();
1371
+ }
1338
1372
  const operationId = `op_${randomUUID()}`;
1339
1373
  const token = `launch_${randomUUID()}`;
1340
1374
  const taskId = supervisorTaskIdForToken(token);
@@ -1358,12 +1392,15 @@ export class ObservedWaitHost {
1358
1392
  ...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
1359
1393
  cwd: prepared.cwd,
1360
1394
  sandbox: prepared.provenance,
1395
+ supervisionPolicy: prepared.plan,
1361
1396
  branchId: owner.branchId ?? null,
1362
1397
  };
1363
1398
  // Persist supervision metadata outside the task execution record so a
1364
1399
  // replacement host can still notify the right parent and never re-route a
1365
1400
  // worker-owned operation to the parent's callback.
1366
1401
  this.writeLaunchContext(taskId, launchContext);
1402
+ this.launches.set(taskId, launchContext);
1403
+ if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
1367
1404
  const started = await this.startSupervisor({
1368
1405
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1369
1406
  });
@@ -1470,11 +1507,69 @@ export class ObservedWaitHost {
1470
1507
  return this.log(taskId, this.ownerFor(ctx), options);
1471
1508
  }
1472
1509
 
1473
- async stopForParent(ctx: ExtensionContext, taskId: string): Promise<StatusView> {
1510
+ async stopForParent(ctx: ExtensionContext, taskId: string, requestId?: string): Promise<StatusView> {
1474
1511
  this.noteParentContext(ctx);
1512
+ if (requestId) {
1513
+ try { return await this.stopThroughRuntime(ctx, taskId, requestId); }
1514
+ catch (error) {
1515
+ if (/not_accepted|accepted:|outcome_unknown/.test(String(error))) throw error;
1516
+ throw new Error(`not_accepted: ${String(error)}`);
1517
+ }
1518
+ }
1475
1519
  return this.stop(taskId, this.ownerFor(ctx));
1476
1520
  }
1477
1521
 
1522
+ /** Called from an actual admitted parent tool context, not a wire owner claim. */
1523
+ authorizeCancellationForParent(ctx: ExtensionContext, taskId: string, requestId: string): string {
1524
+ 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));
1526
+ const managed = this.requireStore().resultSupervision(operation.operationId);
1527
+ 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
+ const proof = cancellationCredential();
1529
+ const previous = this.requireStore().getTaskCancellation({ owner: operation.owner, idempotencyKey: requestId });
1530
+ if (previous && previous.operationId !== operation.operationId) throw new Error("not_accepted: request-conflict: cancellation key belongs to another task");
1531
+ this.requireStore().admitTaskCancellation({ credentialHash: proof.hash, directory: this.directory, request: previous ?? {
1532
+ owner: operation.owner, idempotencyKey: requestId, operationId: operation.operationId,
1533
+ expectedLaunchToken: operation.launchToken, expectedTerminalRevision: operation.terminalRevision,
1534
+ expectedHostId: operation.supervision?.hostId ?? "unavailable", reason: "explicit stop",
1535
+ } });
1536
+ return proof.credential;
1537
+ }
1538
+
1539
+ private async stopThroughRuntime(ctx: ExtensionContext, taskId: string, requestId: string): Promise<StatusView> {
1540
+ this.ownedOperation(taskId, this.ownerFor(ctx));
1541
+ const root = realpathSync(dirname(this.storePath));
1542
+ const registrationPath = join(root, "server-registration-v1.json");
1543
+ if (!existsSync(registrationPath)) {
1544
+ const installer = "../runtime-client/src/runtime/client.mjs";
1545
+ await (await import(installer)).ensureRuntime({ agentDir: root });
1546
+ }
1547
+ const registration = JSON.parse(readFileSync(registrationPath, "utf8"));
1548
+ if (registration.agentDir !== root || registration.version !== 1) throw new Error("not_accepted: invalid canonical runtime registration");
1549
+ const module = "./shared-work-client.mjs";
1550
+ const { WorkClient } = await import(module);
1551
+ const client = new WorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-cancellation-v1"]);
1552
+ let submitted = false;
1553
+ try {
1554
+ await client.ready;
1555
+ await client.request("runtime_cancellation_status");
1556
+ const credential = this.authorizeCancellationForParent(ctx, taskId, requestId);
1557
+ const previous = await client.request("runtime_query_cancellation", { credential });
1558
+ let receipt = previous;
1559
+ if (previous.state === "not_accepted") {
1560
+ submitted = true;
1561
+ receipt = await client.request("runtime_cancel_task", { credential });
1562
+ }
1563
+ 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);
1565
+ } catch (error) {
1566
+ const message = String(error);
1567
+ if (/not_accepted|accepted:|outcome_unknown/.test(message)) throw error;
1568
+ if (!submitted) throw new Error(`not_accepted: cancellation ${requestId}: ${message}`);
1569
+ throw new Error(`outcome_unknown: cancellation ${requestId}; reconnect and query the same request before retrying: ${message}`);
1570
+ } finally { client.close(); }
1571
+ }
1572
+
1478
1573
  // ---- read-only projections for list, navigator and Goal -----------------
1479
1574
 
1480
1575
  /**
@@ -1484,7 +1579,7 @@ export class ObservedWaitHost {
1484
1579
  */
1485
1580
  listDurableTasks(
1486
1581
  origin: BackgroundTaskCallbackOrigin,
1487
- options: { retentionMs?: number; includeDismissed?: boolean } = {},
1582
+ options: { retentionMs?: number; includeDismissed?: boolean; fresh?: boolean } = {},
1488
1583
  ): DurableTaskProjection[] {
1489
1584
  const store = this.store;
1490
1585
  if (!store || this.closed) return [];
@@ -1494,7 +1589,7 @@ export class ObservedWaitHost {
1494
1589
  const originKey = `${origin.cwd}\0${origin.sessionId}`;
1495
1590
  const cacheKey = `${originKey}\0${options.retentionMs ?? ""}\0${options.includeDismissed === true ? 1 : 0}`;
1496
1591
  const cached = this.durableProjectionCache;
1497
- if (cached && cached.key === cacheKey && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
1592
+ if (!options.fresh && cached && cached.key === cacheKey && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
1498
1593
  this.projectionMetrics.cacheHits += 1;
1499
1594
  if (options.retentionMs === undefined) return cached.list;
1500
1595
  const live = cached.list.filter((projection) => !this.expiredProjection(projection, options, now));
@@ -1794,14 +1889,19 @@ export class ObservedWaitHost {
1794
1889
  private async stop(taskId: string, owner: OwnerIdentity): Promise<StatusView> {
1795
1890
  const store = this.requireStore();
1796
1891
  const operation = this.ownedOperation(taskId, owner);
1797
- const result = await this.supervisor.stop(taskId);
1798
- const inspection = result?.inspection ?? this.supervisor.inspect(taskId);
1799
- this.reconcileInspection(operation, inspection);
1800
- const current = store.getOperation(operation.operationId) ?? operation;
1801
- if (current.terminalRevision === 0 && inspection?.terminal) {
1802
- this.recordTerminal(current, inspection);
1803
- }
1804
- return this.status(taskId, owner);
1892
+ if (store.taskCancellationManaged(operation.operationId)) throw new Error("not_accepted: cancellation admission transferred to server; use the registered stop tool with the original request_id");
1893
+ if (this.localCancels.has(taskId)) throw new Error("not_accepted: old cancellation is already in flight");
1894
+ this.localCancels.add(taskId);
1895
+ try {
1896
+ const result = await this.supervisor.stop(taskId, { token: operation.launchToken });
1897
+ const inspection = result?.inspection ?? this.supervisor.inspect(taskId);
1898
+ this.reconcileInspection(operation, inspection);
1899
+ const current = store.getOperation(operation.operationId) ?? operation;
1900
+ if (current.terminalRevision === 0 && inspection?.terminal) {
1901
+ this.recordTerminal(current, inspection);
1902
+ }
1903
+ return this.status(taskId, owner);
1904
+ } finally { this.localCancels.delete(taskId); }
1805
1905
  }
1806
1906
 
1807
1907
  formatStatus(view: StatusView): string {
@@ -1855,6 +1955,124 @@ export class ObservedWaitHost {
1855
1955
  return this.waitView(store.getWait({ waitId: result.wait.waitId }) ?? result.wait);
1856
1956
  }
1857
1957
 
1958
+ private async resultSupervisionClient(): Promise<any> {
1959
+ const root = realpathSync(dirname(this.storePath));
1960
+ const ports = (globalThis as any)[Symbol.for("pi-better-server:result-supervision-ports-v1")];
1961
+ const port = ports?.get(root);
1962
+ if (port) return { request: async (type: string) => {
1963
+ if (type !== "runtime_result_supervision") throw new Error("not_accepted: unsupported in-process supervision operation");
1964
+ return port.status();
1965
+ }, close() {} };
1966
+ // @ts-expect-error Generated standalone lightweight socket client.
1967
+ const { WorkClient } = await import("./shared-work-client.mjs");
1968
+ const connect = async () => {
1969
+ const registration = JSON.parse(readFileSync(join(root, "server-registration-v1.json"), "utf8"));
1970
+ if (registration.version !== 1 || registration.agentDir !== root) throw new Error("Invalid canonical runtime registration");
1971
+ const connection = new WorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-result-supervision-v1"]);
1972
+ try { await connection.ready; return connection; }
1973
+ catch (error) { connection.close(); throw error; }
1974
+ };
1975
+ let client;
1976
+ try { client = await connect(); }
1977
+ catch (error) {
1978
+ if (!["ENOENT", "ECONNREFUSED"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
1979
+ // The packaged canonical client owns artifact verification, owner checks and startup.
1980
+ // @ts-expect-error Generated by sync-runtime-client during package preparation.
1981
+ const { ensureRuntime } = await import("../runtime-client/src/runtime/client.mjs");
1982
+ await ensureRuntime({ agentDir: root, serverDir: process.env.PI_SERVER_DIR });
1983
+ client = await connect();
1984
+ }
1985
+ return client;
1986
+ }
1987
+
1988
+ async refreshManagedResults(): Promise<void> {
1989
+ if (!this.options.serverOwnedResults || !this.store || this.closed) return;
1990
+ const client = await this.resultSupervisionClient();
1991
+ try { await client.request("runtime_result_supervision"); }
1992
+ finally { client.close(); }
1993
+ }
1994
+
1995
+ /** A runner may finish between the server pass and this session's inspection. */
1996
+ async settledStatusForParent(ctx: ExtensionContext, taskId: string): Promise<StatusView> {
1997
+ const observed = this.statusForParent(ctx, taskId);
1998
+ if (!this.options.serverOwnedResults || observed.terminalRevision > 0 || ["running", "starting"].includes(observed.status)) return observed;
1999
+ await this.refreshManagedResults();
2000
+ const imported = this.statusForParent(ctx, taskId);
2001
+ if (imported.terminalRevision === 0) throw new Error("Terminal runner evidence is awaiting authoritative server import; supervision is unavailable.");
2002
+ return imported;
2003
+ }
2004
+
2005
+ private assertResultAdmission(captured: TaskSandboxProvenance, transferring: ReadonlySet<string> = new Set()): void {
2006
+ const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
2007
+ if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
2008
+ throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
2009
+ }
2010
+ if (captured.policySource !== "no-publisher" && !currentForegroundSandboxPolicy(this.pi)) {
2011
+ throw new Error("permission-unavailable: expected current Background permission source is unavailable");
2012
+ }
2013
+ for (const operation of this.requireStore().listOperations({ phase: "running" })) {
2014
+ if (!existsSync(this.sidecarPath(operation.taskId)) || this.requireStore().resultSupervision(operation.operationId)) continue;
2015
+ // A compatible peer may be between registration and its grant transaction.
2016
+ // It cannot start a runner until that grant commits and never discovers globally.
2017
+ if (operation.supervision?.resultAdapter === 1) continue;
2018
+ if (this.supervisionAuthority(operation) === "foreign") {
2019
+ throw new Error("permission-unavailable: a live or unknown legacy operation holder prevents scope handoff");
2020
+ }
2021
+ // A dead holder is not itself a grant. Fencing discovery for a different
2022
+ // task would strand this runner: the server only imports explicit grants.
2023
+ if (!transferring.has(operation.operationId)) {
2024
+ throw new Error("permission-unavailable: an untransferred legacy operation prevents scope handoff; explicitly supervise its wait first");
2025
+ }
2026
+ }
2027
+ }
2028
+
2029
+ private async handoffResults(operations: readonly OperationRecord[]): Promise<void> {
2030
+ const client = await this.resultSupervisionClient();
2031
+ try {
2032
+ const manager = await client.request("runtime_result_supervision");
2033
+ const discovery = this.requireStore().readDiscoveryClaim(this.discoveryScope);
2034
+ if (discovery && discovery.hostId !== this.hostId && this.discoveryHolderState(discovery.hostId) !== "dead") {
2035
+ throw new Error("permission-unavailable: live or unknown original discovery holder prevents scope handoff");
2036
+ }
2037
+ const transfers = [];
2038
+ const transferring = new Set(operations.map(operation => operation.operationId));
2039
+ for (const operation of operations) {
2040
+ if (this.requireStore().resultSupervision(operation.operationId)) continue;
2041
+ if (this.supervisionAuthority(operation) === "foreign" || this.localCancels.has(operation.taskId)) {
2042
+ throw new Error("permission-unavailable: original supervision owner is live, unknown or draining");
2043
+ }
2044
+ const context = this.launchContext(operation.taskId);
2045
+ if (!context?.sandbox || !context.supervisionPolicy || !operation.authorityRef) throw new Error("permission-unavailable: captured Background authority is unavailable");
2046
+ this.assertResultAdmission(context.sandbox, transferring);
2047
+ const current = currentForegroundSandboxPolicy(this.pi);
2048
+ if (context.sandbox.policySource !== "no-publisher" && !current) throw new Error("permission-unavailable: expected current Background permission source is unavailable");
2049
+ transfers.push({ operationId: operation.operationId,
2050
+ expectedHostId: operation.supervision?.hostId ?? "unavailable", directory: this.directory, hostId: manager.hostId, epoch: manager.epoch,
2051
+ capability: { adapter: "background-results-v1", captured: { provenance: context.sandbox, policy: context.supervisionPolicy }, current: current ?? { state: "legacy-unconfined", policySource: "no-publisher" } } });
2052
+ }
2053
+ // Validate the whole batch, then stop admission before the durable CAS.
2054
+ for (const transfer of transfers) this.resultHandoffs.add(transfer.operationId);
2055
+ try {
2056
+ this.requireStore().handoffResultScope({ scope: this.discoveryScope,
2057
+ expectedDiscovery: discovery ? { hostId: discovery.hostId, token: discovery.token } : null, grants: transfers });
2058
+ this.discoveryToken = undefined;
2059
+ this.discoveryRole = "follower";
2060
+ } catch (error) {
2061
+ // The transaction rolled back; only these uncommitted local fences may reopen.
2062
+ for (const transfer of transfers) this.resultHandoffs.delete(transfer.operationId);
2063
+ throw error;
2064
+ }
2065
+ await client.request("runtime_result_supervision");
2066
+ } finally { client.close(); }
2067
+ }
2068
+
2069
+ async superviseParentWait(ctx: ExtensionContext, taskIds: readonly string[], note: string): Promise<WaitView> {
2070
+ this.noteParentContext(ctx);
2071
+ const operations = this.operationsForTaskIds(this.ownerFor(ctx), taskIds);
2072
+ await this.handoffResults(operations);
2073
+ return this.waitForParent(ctx, taskIds, note);
2074
+ }
2075
+
1858
2076
  waitViewForParent(ctx: ExtensionContext, waitId: string, generation?: number): WaitView | undefined {
1859
2077
  const store = this.requireStore();
1860
2078
  const wait = store.getWait({ waitId, ...(generation ? { generation } : {}) });
@@ -1895,6 +2113,10 @@ export class ObservedWaitHost {
1895
2113
  const store = this.requireStore();
1896
2114
  if (input.params.ssh) throw new Error("Worker background launches are local-only; structured SSH is unavailable through this service.");
1897
2115
  const owner = this.workerOwner(run);
2116
+ if (this.options.serverOwnedResults) {
2117
+ const client = await this.resultSupervisionClient();
2118
+ client.close();
2119
+ }
1898
2120
  const prepared = this.prepareLaunch(
1899
2121
  input.kind,
1900
2122
  input.params,
@@ -1903,6 +2125,7 @@ export class ObservedWaitHost {
1903
2125
  input.policy,
1904
2126
  run.workspace,
1905
2127
  );
2128
+ if (this.options.serverOwnedResults) this.assertResultAdmission(prepared.provenance);
1906
2129
  const operationId = `op_${randomUUID()}`;
1907
2130
  const token = `launch_${randomUUID()}`;
1908
2131
  const taskId = supervisorTaskIdForToken(token);
@@ -1926,9 +2149,12 @@ export class ObservedWaitHost {
1926
2149
  ...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
1927
2150
  cwd: prepared.cwd,
1928
2151
  sandbox: prepared.provenance,
2152
+ supervisionPolicy: prepared.plan,
1929
2153
  branchId: owner.branchId ?? null,
1930
2154
  };
1931
2155
  this.writeLaunchContext(taskId, launchContext);
2156
+ this.launches.set(taskId, launchContext);
2157
+ if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
1932
2158
  const started = await this.startSupervisor({
1933
2159
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1934
2160
  });
@@ -2835,6 +3061,8 @@ export class ObservedWaitHost {
2835
3061
 
2836
3062
  private reconcileOperation(operation: OperationRecord): void {
2837
3063
  if (operation.terminalRevision > 0) return;
3064
+ if (this.resultHandoffs.has(operation.operationId) || (operation.resultManaged ?? !!this.store?.resultSupervision(operation.operationId))) return;
3065
+ if (this.options.serverOwnedResults) return;
2838
3066
  const authority = this.supervisionAuthority(operation);
2839
3067
  if (authority === "foreign") return;
2840
3068
  let claimed = false;
@@ -3000,29 +3228,15 @@ export class ObservedWaitHost {
3000
3228
  }
3001
3229
 
3002
3230
  private recordTerminal(operation: OperationRecord, inspection: SupervisorInspection): void {
3231
+ if (this.options.serverOwnedResults) return;
3232
+ if (this.resultHandoffs.has(operation.operationId) || this.store?.resultSupervision(operation.operationId)) return;
3003
3233
  const store = this.requireStore();
3004
3234
  const status = inspection.status;
3005
3235
  const outcome = terminalOutcome(status);
3006
- const eventId = `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`;
3007
3236
  const refs = evidenceFor(inspection);
3008
3237
  let recorded;
3009
3238
  try {
3010
- recorded = store.recordTerminalOutcome({
3011
- operationId: operation.operationId,
3012
- eventId,
3013
- outcome,
3014
- owner: operation.owner,
3015
- evidence: refs.map((ref) => ({
3016
- kind: ref.kind,
3017
- ref: ref.ref,
3018
- ...(ref.summary ? { summary: ref.summary } : {}),
3019
- detailLost: ref.detailLost,
3020
- })),
3021
- ...(outcome === "lost" ? { detailLost: true } : {}),
3022
- reason: inspection.result
3023
- ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}`
3024
- : "supervisor lost: no terminal evidence",
3025
- });
3239
+ recorded = store.recordTerminalOutcome(supervisorTerminalPublication(operation, inspection, refs));
3026
3240
  } catch (error) {
3027
3241
  // A timer and a tool call can observe the same terminal record. The store
3028
3242
  // keeps the first revision; a replay is never a second execution.
@@ -3863,6 +4077,7 @@ export class ObservedWaitHost {
3863
4077
  hostId: this.hostId,
3864
4078
  storeOpen: !!this.store,
3865
4079
  closed: this.closed,
4080
+ managementMode: this.options.serverOwnedResults ? "server-client" : "legacy",
3866
4081
  activeContext: !!ctx,
3867
4082
  activeSessionId: ctx ? this.sessionIdIfAvailable(ctx) ?? this.sessionId(ctx) : undefined,
3868
4083
  activeCwd: ctx ? ctx.cwd : undefined,
@@ -3912,6 +4127,8 @@ export class ObservedWaitHost {
3912
4127
  ...(typeof value.cwd === "string" ? { cwd: value.cwd } : {}),
3913
4128
  ...(value.sandbox && typeof value.sandbox === "object" && !Array.isArray(value.sandbox)
3914
4129
  ? { sandbox: value.sandbox as TaskSandboxProvenance } : {}),
4130
+ ...(value.supervisionPolicy && typeof value.supervisionPolicy === "object"
4131
+ ? { supervisionPolicy: value.supervisionPolicy } : {}),
3915
4132
  ...(typeof value.branchId === "string" || value.branchId === null ? { branchId: value.branchId } : {}),
3916
4133
  ...(typeof value.callbackPendingAt === "number" ? { callbackPendingAt: value.callbackPendingAt } : {}),
3917
4134
  ...(typeof value.callbackDeliveredAt === "number" ? { callbackDeliveredAt: value.callbackDeliveredAt }
@@ -4003,7 +4220,8 @@ export class ObservedWaitHost {
4003
4220
  }
4004
4221
 
4005
4222
  private supervision(): SupervisionIdentity {
4006
- return { hostId: this.hostId, runnerId: null, processStartToken: null };
4223
+ return { hostId: this.hostId, runnerId: null, processStartToken: null, resultScope: this.discoveryScope,
4224
+ ...(this.options.serverOwnedResults ? { resultAdapter: 1 as const } : {}) };
4007
4225
  }
4008
4226
 
4009
4227
  private parentAuthority(owner: OwnerIdentity, plan: ForegroundSandboxPlan): string {
package/src/output.ts CHANGED
@@ -133,7 +133,7 @@ function stringifyObserved(value: unknown): string {
133
133
 
134
134
  /** Cursor scope: pagination and revision cursors never cross session scopes. */
135
135
  function scopeKey(options: OutputOptions): string {
136
- return sessionScopeKey({ all: options.all, unavailable: options.sessionUnavailable, origin: options.origin });
136
+ return sessionScopeKey({ all: options.all, unavailable: options.sessionUnavailable, origin: options.origin, processId: process.pid });
137
137
  }
138
138
 
139
139
  function taskGaps(meta: BackgroundTaskMeta): EvidenceGap[] {
@@ -810,11 +810,11 @@ function compactRow(meta: BackgroundTaskMeta, incidents: number): string {
810
810
  const remote = meta.ssh ? ` ${oneLine(meta.ssh.target, 60)}${meta.remote?.session ? ` ${meta.remote.session}` : ""}` : "";
811
811
  const incident = incidents > 0 ? ` · ${incidents} incident${incidents === 1 ? "" : "s"}` : "";
812
812
  const label = meta.name ? ` ${oneLine(meta.name, 60)}` : "";
813
- return `${meta.id} ${meta.status} ${meta.kind} ${age}${incident}${remote}${label}`;
813
+ const waits = (meta as BackgroundTaskMeta & { waits?: unknown[] }).waits?.length;
814
+ return `${meta.id} ${meta.status} ${meta.kind} ${age}${incident}${remote}${label}${waits ? ` waits=${waits}` : ""}`;
814
815
  }
815
816
 
816
- export function formatList(options: OutputOptions = {}): string {
817
- const index = listTaskRecords();
817
+ export function formatList(options: OutputOptions = {}, index = listTaskRecords()): string {
818
818
  if (index.indexError) {
819
819
  return assembleBackgroundContent({
820
820
  surface: "list",
@@ -838,8 +838,8 @@ export function formatList(options: OutputOptions = {}): string {
838
838
  });
839
839
  }
840
840
  const wanted = options.statuses && options.statuses.length > 0 ? new Set(options.statuses) : undefined;
841
- let unreadable = 0;
842
- let unknown = 0;
841
+ let unreadable = index.page?.unreadable ?? 0;
842
+ let unknown = index.page?.unknown ?? 0;
843
843
  const allowed: BackgroundTaskMeta[] = [];
844
844
  for (const record of index.records) {
845
845
  if (!record.meta) {
@@ -848,7 +848,8 @@ export function formatList(options: OutputOptions = {}): string {
848
848
  }
849
849
  const ownership = classifyOwnership(record.meta, options);
850
850
  if (ownership === "allow") {
851
- if (!wanted || wanted.has(record.meta.status)) allowed.push(record.meta);
851
+ if (!wanted || wanted.has(record.meta.status) || wanted.has("running") && (record.meta as BackgroundTaskMeta & { durable?: boolean; active?: boolean }).durable
852
+ && (record.meta as BackgroundTaskMeta & { active?: boolean }).active) allowed.push(record.meta);
852
853
  } else if (ownership === "unknown") {
853
854
  unknown += 1;
854
855
  }
@@ -857,12 +858,13 @@ export function formatList(options: OutputOptions = {}): string {
857
858
  const statusesKey = [...(options.statuses ?? [])].sort().join(",");
858
859
  const resource = `list:${scope}:${statusesKey}`;
859
860
  const limit = Math.max(1, Math.min(Math.floor(options.limit ?? DEFAULT_LIST_ENTRIES), MAX_LIST_ENTRIES));
861
+ const total = index.page?.total ?? allowed.length;
860
862
  const states = new Map(allowed.map((meta) => [meta.id, failureStateFor(meta.id)] as const));
861
863
  const incidentsOf = (id: string) => actionableFailures(states.get(id)!).length;
862
864
  const revision = inspectStatusRevision({
863
865
  resource,
864
- contentRevision: revisionOf(allowed.map((meta) => [meta.id, meta.status, meta.endedAt ?? null])),
865
- failureRevision: revisionOf(allowed.map((meta) => [meta.id, failureRevision(states.get(meta.id)!)])),
866
+ contentRevision: index.page?.contentRevision ?? revisionOf(allowed.map((meta) => [meta.id, meta.status, meta.endedAt ?? null])),
867
+ failureRevision: revisionOf([index.page?.failureRevision, allowed.map((meta) => [meta.id, failureRevision(states.get(meta.id)!)])]),
866
868
  cursor: cursorKind(options.cursor) === "s" ? options.cursor : undefined,
867
869
  });
868
870
  const scopeLabel = options.all ? "all sessions" : "current session";
@@ -871,7 +873,7 @@ export function formatList(options: OutputOptions = {}): string {
871
873
  surface: "list",
872
874
  maxBytes: options.maxBytes,
873
875
  sections: {
874
- identity: `${allowed.length} background task${allowed.length === 1 ? "" : "s"} (${scopeLabel}) · unchanged`,
876
+ identity: `${total} background task${total === 1 ? "" : "s"} (${scopeLabel}) · unchanged`,
875
877
  decision: formatUnchangedEvidence(options.cursor),
876
878
  },
877
879
  statusCursor: revision.nextCursor,
@@ -884,7 +886,7 @@ export function formatList(options: OutputOptions = {}): string {
884
886
  const listFailure = (budget: number): string | undefined => {
885
887
  const newest = failing[0];
886
888
  if (!newest) return undefined;
887
- const count = `${withIncidents} task${withIncidents === 1 ? "" : "s"} with unresolved incidents; newest ${newest.id} has ${incidentsOf(newest.id)}. Full incidents: bg_task_status id=${newest.id}.`;
889
+ const count = `${withIncidents} task${withIncidents === 1 ? "" : "s"}${index.page ? " on this page" : ""} with unresolved incidents; newest ${newest.id} has ${incidentsOf(newest.id)}. Full incidents: bg_task_status id=${newest.id}.`;
888
890
  const top = formatFailureLines(states.get(newest.id)!)[0] ?? "";
889
891
  // The lead-in is a pointer, not the incident page: at most a short preview.
890
892
  const room = Math.min(LIST_LEAD_PREVIEW_BYTES, budget - utf8ByteLength(count) - 1);
@@ -908,9 +910,9 @@ export function formatList(options: OutputOptions = {}): string {
908
910
  sections: {
909
911
  identity: options.sessionUnavailable && !options.all
910
912
  ? "Current session identity is unavailable; task ownership cannot be verified."
911
- : allowed.length === 0
913
+ : total === 0
912
914
  ? `No background tasks found (${scopeLabel}).`
913
- : `${allowed.length} background task${allowed.length === 1 ? "" : "s"} (${scopeLabel}), newest first`,
915
+ : `${total} background task${total === 1 ? "" : "s"} (${scopeLabel}), newest first${allowed.some(meta => (meta as BackgroundTaskMeta & { durable?: boolean }).durable) ? "; durable background operations included" : ""}`,
914
916
  failure: withIncidents ? listFailure : undefined,
915
917
  diagnostics: notes.join("\n") || undefined,
916
918
  },
@@ -921,6 +923,7 @@ export function formatList(options: OutputOptions = {}): string {
921
923
  resource,
922
924
  limit,
923
925
  maxBytes: budget,
926
+ ...(index.page ? { indexed: { total, before: index.page.before } } : {}),
924
927
  keyOf: (meta) => ({ time: meta.startedAt, id: meta.id }),
925
928
  render: (meta) => compactRow(meta, incidentsOf(meta.id)),
926
929
  }),
package/src/registry.ts CHANGED
@@ -158,6 +158,7 @@ export function inspectMeta(id: string): MetaInspection {
158
158
  export interface TaskIndex {
159
159
  records: MetaInspection[];
160
160
  indexError?: string;
161
+ page?: { total: number; before: number; contentRevision: string; failureRevision: string; unreadable: number; unknown: number };
161
162
  }
162
163
 
163
164
  /** List every task directory, including unreadable metadata. */
@@ -231,6 +232,20 @@ export function listActiveMetasForOrigin(origin: BackgroundTaskCallbackOrigin):
231
232
  .sort((a, b) => b.startedAt - a.startedAt);
232
233
  }
233
234
 
235
+ /** Passive shared-runtime query: no backfill, cache repair, or completed-history scan. */
236
+ export function observeMetasForOrigin(origin: BackgroundTaskCallbackOrigin, activeOnly = true): BackgroundTaskMeta[] {
237
+ const directory = activeOnly ? originActiveIndexDir(origin) : originIndexDir(origin);
238
+ let ids: string[];
239
+ try { ids = readdirSync(directory).filter(id => id !== ".initialized"); }
240
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
241
+ return ids.map(id => {
242
+ const record = inspectMeta(id);
243
+ if (record.found && !record.meta) throw new Error(`Unverified background task ${id}: ${record.error}`);
244
+ return record.meta;
245
+ }).filter((meta): meta is BackgroundTaskMeta => !!meta && !!meta.callbackOrigin && belongsToOrigin(meta, origin)
246
+ && (!activeOnly || meta.status === "running")).sort((a, b) => b.startedAt - a.startedAt);
247
+ }
248
+
234
249
  function readMetaForSweep(id: string): BackgroundTaskMeta | undefined {
235
250
  const cached = metaCache.get(id);
236
251
  if (cached && isTerminalStatus(cached.status)) return cached;
@@ -34,10 +34,12 @@ function section(settings: Record<string, unknown>): Record<string, unknown> {
34
34
  }
35
35
 
36
36
  function acquire(path: string): () => void {
37
- for (let attempt = 0; attempt < 10; attempt++) {
37
+ // A live writer can be briefly descheduled; allow contention without stealing its lock.
38
+ const maxAttempts = 100;
39
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
38
40
  try { return lockfile.lockSync(path, { realpath: false }); }
39
41
  catch (error) {
40
- if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt === 9) throw error;
42
+ if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt === maxAttempts - 1) throw error;
41
43
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
42
44
  }
43
45
  }