pi-better-harness 0.47.0 → 0.48.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 (61) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/node_modules/pi-better-background-tasks/README.md +9 -0
  3. package/node_modules/pi-better-background-tasks/package.json +1 -1
  4. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  5. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
  6. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  7. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
  8. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  9. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
  10. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  11. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
  12. package/node_modules/pi-better-background-tasks/runtime-client/src/daemon-owner.mjs +2 -1
  13. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/work-client.mjs +16 -2
  14. package/node_modules/pi-better-background-tasks/src/index.ts +1 -0
  15. package/node_modules/pi-better-background-tasks/src/observed-waits.ts +168 -12
  16. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/assignment-observation.mjs +18 -1
  17. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/discovery.ts +9 -0
  18. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/operations.ts +6 -4
  19. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/result-supervision.ts +128 -0
  20. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/schema.ts +19 -1
  21. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/store.ts +20 -0
  22. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/src/types.ts +6 -0
  23. package/node_modules/pi-better-background-tasks/src/shared-work-client.mjs +16 -2
  24. package/node_modules/pi-better-background-tasks/src/tools.ts +59 -36
  25. package/node_modules/pi-better-goal/package.json +1 -1
  26. package/node_modules/pi-better-goal/src/shared-assignment-observation.mjs +18 -1
  27. package/node_modules/pi-better-subagents/agent-catalog.mjs +24 -0
  28. package/node_modules/pi-better-subagents/agent-commands.ts +71 -4
  29. package/node_modules/pi-better-subagents/agent-inspection.ts +2 -1
  30. package/node_modules/pi-better-subagents/agents-catalog-tool.ts +8 -1
  31. package/node_modules/pi-better-subagents/catalog-host-admission.ts +69 -0
  32. package/node_modules/pi-better-subagents/catalog-overlay.ts +10 -0
  33. package/node_modules/pi-better-subagents/catalog-runtime.ts +10 -2
  34. package/node_modules/pi-better-subagents/catalog-store.ts +23 -0
  35. package/node_modules/pi-better-subagents/catalog-ui.ts +26 -10
  36. package/node_modules/pi-better-subagents/docs/agent-catalog-operations.md +38 -0
  37. package/node_modules/pi-better-subagents/index.ts +12 -7
  38. package/node_modules/pi-better-subagents/launch-abort.ts +21 -0
  39. package/node_modules/pi-better-subagents/package.json +1 -1
  40. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  41. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  42. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  43. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  44. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  45. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  46. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  47. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  48. package/node_modules/pi-better-subagents/runtime-client/src/daemon-owner.mjs +2 -1
  49. package/node_modules/pi-better-subagents/runtime-client/src/runtime/work-client.mjs +16 -2
  50. package/node_modules/pi-better-subagents/shared-catalog.ts +69 -0
  51. package/node_modules/pi-better-subagents/shared-operation-coordinator/assignment-observation.mjs +18 -1
  52. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/discovery.ts +9 -0
  53. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/operations.ts +6 -4
  54. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/result-supervision.ts +128 -0
  55. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/schema.ts +19 -1
  56. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/store.ts +20 -0
  57. package/node_modules/pi-better-subagents/shared-operation-coordinator/src/types.ts +6 -0
  58. package/node_modules/pi-better-subagents/shared-work-client.d.mts +4 -1
  59. package/node_modules/pi-better-subagents/shared-work-client.mjs +16 -2
  60. package/node_modules/pi-better-subagents/skill-picker.ts +6 -2
  61. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.48.0] - 2026-11-16
4
+
5
+ ### Added
6
+
7
+ - Bundle shared Catalog management and durable Background result supervision from the unified runtime. (#751, #789)
8
+
9
+ ### Fixed
10
+
11
+ - Keep exact-ID reads responsive during large initial inventories and recover failed read workers with a bounded restart budget and a fresh observation epoch.
12
+ - Reuse unpublished parsing work after source changes, observe coordinator writes through a coherent read snapshot, and avoid scheduling another inventory solely because the current scan is slow.
13
+ - Bundle Server 0.4.0, Subagents 0.34.0, Background Tasks 0.17.0 and Goal 0.14.2.
14
+
3
15
  ## [0.47.0] - 2026-11-16
4
16
 
5
17
  ### Added
@@ -320,6 +320,15 @@ keeps observing after the worker or Pi process exits. Status and logs recover
320
320
  from durable evidence; an ambiguous launch becomes `lost` and is not relaunched.
321
321
  SSH tasks and older `bg_` identifiers use the existing runtime.
322
322
 
323
+ The canonical local server owns result supervision for newly admitted local
324
+ tasks. Closing every frontend leaves the independent runner running. The server
325
+ imports matching terminal evidence, advances already-authorized waits, and keeps
326
+ notifications for their recorded recipients. Hosted sessions use the same root
327
+ supervisor rather than starting another discovery loop. A live or unverified
328
+ legacy owner blocks handoff; missing permission authority or execution evidence
329
+ is reported without starting a replacement command. This transfer does not
330
+ authorize a continuation, consume evidence, or start a parent model turn.
331
+
323
332
  Stop and timeout evidence can contain `groupCleanup=unproven` when the command's
324
333
  leader exits before cleanup can be verified. Descendants may remain running;
325
334
  inspect that evidence before interpreting the result.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"4a441dc74b227cdaaeebe9bf93580d18c4773acd30a43df8376205888314877f"},"sha256":"d605829c1323baa03ec1908337950c965d97e7ded4dc24479fff7300be296367"}
1
+ {"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"d8babdaa88ccdf11463b69738823e4175a88cb25e1f6b51bd1cde1dc5ebbd6b3"},"sha256":"40cbb55c9f6bcba62ac2fde5d00521d44c627177baede403fdfa9ee53ccec6ce"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"217c2fe0b4c39621f2d231c2ee13e675514f5800d3d0f88edd1d640982df1cf8"},"sha256":"cafcd27fc435dd8a94b75154af1e509c0fb649c79423e090755c014c6609296b"}
1
+ {"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"0c892582dfd3e78b9f5fc25821dfd6b7c233f7f8b6d31677196dc3aaeda0a909"},"sha256":"61e469f213ae5ef7e379897f03f069b4a8c668a3a338f7fee7cafffeb7c648f3"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"ad01e2a4639e88f1919d9aa628d6d5760ab0b8bd34d563f6adf7c81c106e90f6"},"sha256":"0b5c8649a160f17eae208389848f09655d8e77fdf00c606241598c76fb956acd"}
1
+ {"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"d71fc0b69c23b6808726d5a971c3ddd1da00985dfb655c79190b83c3997fcb1f"},"sha256":"057130e7109c592068e375f31a5f39297163326bb88f6461d59ae4e7742d7a80"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"3327fd5e74b18926f945db86bb1bc82f6a5f52eaef9ce091cfe45b7537df871c","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.3.0","contentId":"1e311f8fd34ed8dbea8660e1383e128e4f2916b18949cd1288ab5e0682b6a85a"},"sha256":"258a050dfbb9089e3876d2ffcafa85f85e40c9396e041145e43a6d90d2cdf8ab"}
1
+ {"build":{"format":1,"sourceDigest":"f1a415e52552342511151e078257a3d81660989f30a684a263fb8f6252ac9e63","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"c63ff3a60c411a06ad881d6ae81fbe88402cc1ff3a3447bf54765b090b2c77bb","protocolVersion":1,"serverVersion":"0.4.0","contentId":"5e132e98f011fb0eee44a2184ef8d17787a7ac0f1b792b676b08582d248ba19f"},"sha256":"a007cde2962d0b0eb4fe378a3e9d08fd2f20ada6fce2c96b76f849cb6dd62c96"}
@@ -29,8 +29,9 @@ export function processMatchesStart(pid, start) {
29
29
  try {
30
30
  const observed = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
31
31
  encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000,
32
+ env: { ...process.env, LC_ALL: "C" },
32
33
  }).trim();
33
- return observed.length > 0 && observed === start.trim();
34
+ return observed.length > 0 && observed.replace(/\s+/g, " ") === start.trim().replace(/\s+/g, " ");
34
35
  }
35
36
  catch {
36
37
  return false;
@@ -1,4 +1,5 @@
1
1
  import { connect } from "node:net";
2
+ import { performance } from "node:perf_hooks";
2
3
 
3
4
  /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
4
5
  export class WorkClient {
@@ -6,6 +7,7 @@ export class WorkClient {
6
7
  snapshot;
7
8
  pending = new Map();
8
9
  listeners = new Set();
10
+ catalogListeners = new Set();
9
11
  sequence = 0;
10
12
  scope;
11
13
  buffer = "";
@@ -23,6 +25,7 @@ export class WorkClient {
23
25
  try {
24
26
  const message = JSON.parse(line);
25
27
  if (message.type === "event") {
28
+ if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
26
29
  if (message.event.type === "resync_required") { this.degrade(message.event.reason); void this.resync().catch(error => this.degrade(String(error))); }
27
30
  else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
28
31
  } else {
@@ -50,6 +53,7 @@ export class WorkClient {
50
53
  });
51
54
  }
52
55
  onChange(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
56
+ onCatalog(listener) { this.catalogListeners.add(listener); return () => this.catalogListeners.delete(listener); }
53
57
  notify() { for (const listener of this.listeners) listener(this.snapshot); }
54
58
  degrade(reason) {
55
59
  this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
@@ -77,12 +81,22 @@ export class WorkClient {
77
81
  const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
78
82
  this.accept(snapshot); return snapshot;
79
83
  }
80
- async get(scope) { await this.ready; return this.request("runtime_get_snapshot", { scope }); }
84
+ async get(scope) {
85
+ await this.ready;
86
+ const until = performance.now() + 3500;
87
+ for (let attempt = 0; ; attempt++) {
88
+ const value = await this.request("runtime_get_snapshot", { scope });
89
+ if (!scope?.id || value.status !== "rebuilding" || value.rows.length || performance.now() >= until) return value;
90
+ // A newly written ID may join an inventory without holding the shared RPC queue.
91
+ await new Promise(resolve => setTimeout(resolve, Math.min(250, 50 * 2 ** attempt, until - performance.now())));
92
+ }
93
+ }
81
94
  fail(error) {
82
95
  if (this.closed) return;
83
96
  this.closed = true;
84
97
  for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
85
98
  this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
99
+ for (const listener of this.catalogListeners) listener({ status: "revoked" });
86
100
  }
87
- close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); }
101
+ close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); this.catalogListeners.clear(); }
88
102
  }
@@ -18,6 +18,7 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
18
18
  // Created before registerTools so the tools can resolve it lazily; the durable
19
19
  // store opens on session activation and closes on switch/unload.
20
20
  const observedWaits = createObservedWaitHost(pi, {
21
+ serverOwnedResults: true,
21
22
  notifyParent: (notification, delivery) => {
22
23
  getCallbackBatcher(pi).enqueue({
23
24
  source: "background-task",
@@ -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,
@@ -556,6 +557,8 @@ function rpcCode(error: unknown): string {
556
557
  }
557
558
 
558
559
  export interface ObservedWaitHostOptions {
560
+ /** Production adapters leave global discovery and terminal import to the server. */
561
+ serverOwnedResults?: boolean;
559
562
  /** SQLite path. Defaults under the Pi agent directory. */
560
563
  storePath?: string;
561
564
  /** Durable supervisor record directory. Defaults beside the task registry. */
@@ -658,6 +661,7 @@ interface LaunchContext {
658
661
  readonly cwd?: string;
659
662
  /** Launch-time sandbox provenance; never recomputed from the current profile. */
660
663
  readonly sandbox?: TaskSandboxProvenance;
664
+ readonly supervisionPolicy?: ForegroundSandboxPlan;
661
665
  /** Owner branch anchor captured at launch (undefined when unavailable). */
662
666
  readonly branchId?: string | null;
663
667
  callbackPendingAt?: number;
@@ -861,6 +865,7 @@ export class ObservedWaitHost {
861
865
  private readonly options: ObservedWaitHostOptions;
862
866
  private timer?: NodeJS.Timeout;
863
867
  private closed = false;
868
+ private activationAttempted = false;
864
869
  private unavailableReason?: string;
865
870
  private parentOrigin?: BackgroundTaskCallbackOrigin;
866
871
  private activeOrigin?: BackgroundTaskCallbackOrigin;
@@ -896,6 +901,7 @@ export class ObservedWaitHost {
896
901
  private continuationError?: string;
897
902
  private readonly launches = new Map<string, LaunchContext>();
898
903
  private readonly localCancels = new Set<string>();
904
+ private readonly resultHandoffs = new Set<string>();
899
905
  private readonly rpcRuns = new Map<string, RpcRunBinding>();
900
906
  private readonly waitOwners = new Map<string, OwnerIdentity>();
901
907
  private readonly stagedCheckpoints = new Map<string, { evidence: JsonRecord; toolCallId: string; checkpointRecorded: boolean }>();
@@ -972,12 +978,16 @@ export class ObservedWaitHost {
972
978
  return this.store !== undefined && !this.closed;
973
979
  }
974
980
 
981
+ get usesServerResults(): boolean { return this.options.serverOwnedResults === true; }
982
+ get hasActivated(): boolean { return this.activationAttempted; }
983
+
975
984
  get reason(): string | undefined {
976
985
  return this.unavailableReason;
977
986
  }
978
987
 
979
988
  /** Open the durable store and begin bounded reconciliation. */
980
989
  start(ctx?: ExtensionContext): void {
990
+ this.activationAttempted = true;
981
991
  if (ctx) this.setActiveOrigin(ctx);
982
992
  if (this.store) {
983
993
  // The same host instance can be activated for another session without a
@@ -1163,7 +1173,16 @@ export class ObservedWaitHost {
1163
1173
  if (!this.store || this.closed) return;
1164
1174
  this.authorityPassCache = new Map();
1165
1175
  try {
1166
- 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);
1167
1186
  this.noteDiscoveryRole(role);
1168
1187
  if (role === "holder") {
1169
1188
  this.discoverObservedTasks();
@@ -1286,15 +1305,9 @@ export class ObservedWaitHost {
1286
1305
  * Acquire or confirm the one shared discovery claim. Process identity and
1287
1306
  * explicit close evidence decide replacement; elapsed time is not a lease.
1288
1307
  */
1289
- private refreshDiscoveryAuthority(): "holder" | "follower" {
1308
+ private refreshDiscoveryAuthority(claim: ReturnType<Store["readDiscoveryClaim"]>): "holder" | "follower" {
1290
1309
  const store = this.store;
1291
1310
  if (!store) return "follower";
1292
- let claim;
1293
- try {
1294
- claim = store.readDiscoveryClaim(this.discoveryScope);
1295
- } catch {
1296
- return "follower";
1297
- }
1298
1311
  if (claim?.hostId === this.hostId) {
1299
1312
  this.discoveryToken = claim.token;
1300
1313
  return "holder";
@@ -1351,6 +1364,11 @@ export class ObservedWaitHost {
1351
1364
  }
1352
1365
  const owner = this.ownerFor(input.ctx);
1353
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
+ }
1354
1372
  const operationId = `op_${randomUUID()}`;
1355
1373
  const token = `launch_${randomUUID()}`;
1356
1374
  const taskId = supervisorTaskIdForToken(token);
@@ -1374,12 +1392,15 @@ export class ObservedWaitHost {
1374
1392
  ...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
1375
1393
  cwd: prepared.cwd,
1376
1394
  sandbox: prepared.provenance,
1395
+ supervisionPolicy: prepared.plan,
1377
1396
  branchId: owner.branchId ?? null,
1378
1397
  };
1379
1398
  // Persist supervision metadata outside the task execution record so a
1380
1399
  // replacement host can still notify the right parent and never re-route a
1381
1400
  // worker-owned operation to the parent's callback.
1382
1401
  this.writeLaunchContext(taskId, launchContext);
1402
+ this.launches.set(taskId, launchContext);
1403
+ if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
1383
1404
  const started = await this.startSupervisor({
1384
1405
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1385
1406
  });
@@ -1502,7 +1523,8 @@ export class ObservedWaitHost {
1502
1523
  authorizeCancellationForParent(ctx: ExtensionContext, taskId: string, requestId: string): string {
1503
1524
  if (this.localCancels.has(taskId)) throw new Error("not_accepted: old cancellation admission is still draining");
1504
1525
  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");
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");
1506
1528
  const proof = cancellationCredential();
1507
1529
  const previous = this.requireStore().getTaskCancellation({ owner: operation.owner, idempotencyKey: requestId });
1508
1530
  if (previous && previous.operationId !== operation.operationId) throw new Error("not_accepted: request-conflict: cancellation key belongs to another task");
@@ -1557,7 +1579,7 @@ export class ObservedWaitHost {
1557
1579
  */
1558
1580
  listDurableTasks(
1559
1581
  origin: BackgroundTaskCallbackOrigin,
1560
- options: { retentionMs?: number; includeDismissed?: boolean } = {},
1582
+ options: { retentionMs?: number; includeDismissed?: boolean; fresh?: boolean } = {},
1561
1583
  ): DurableTaskProjection[] {
1562
1584
  const store = this.store;
1563
1585
  if (!store || this.closed) return [];
@@ -1567,7 +1589,7 @@ export class ObservedWaitHost {
1567
1589
  const originKey = `${origin.cwd}\0${origin.sessionId}`;
1568
1590
  const cacheKey = `${originKey}\0${options.retentionMs ?? ""}\0${options.includeDismissed === true ? 1 : 0}`;
1569
1591
  const cached = this.durableProjectionCache;
1570
- 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) {
1571
1593
  this.projectionMetrics.cacheHits += 1;
1572
1594
  if (options.retentionMs === undefined) return cached.list;
1573
1595
  const live = cached.list.filter((projection) => !this.expiredProjection(projection, options, now));
@@ -1933,6 +1955,124 @@ export class ObservedWaitHost {
1933
1955
  return this.waitView(store.getWait({ waitId: result.wait.waitId }) ?? result.wait);
1934
1956
  }
1935
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
+
1936
2076
  waitViewForParent(ctx: ExtensionContext, waitId: string, generation?: number): WaitView | undefined {
1937
2077
  const store = this.requireStore();
1938
2078
  const wait = store.getWait({ waitId, ...(generation ? { generation } : {}) });
@@ -1973,6 +2113,10 @@ export class ObservedWaitHost {
1973
2113
  const store = this.requireStore();
1974
2114
  if (input.params.ssh) throw new Error("Worker background launches are local-only; structured SSH is unavailable through this service.");
1975
2115
  const owner = this.workerOwner(run);
2116
+ if (this.options.serverOwnedResults) {
2117
+ const client = await this.resultSupervisionClient();
2118
+ client.close();
2119
+ }
1976
2120
  const prepared = this.prepareLaunch(
1977
2121
  input.kind,
1978
2122
  input.params,
@@ -1981,6 +2125,7 @@ export class ObservedWaitHost {
1981
2125
  input.policy,
1982
2126
  run.workspace,
1983
2127
  );
2128
+ if (this.options.serverOwnedResults) this.assertResultAdmission(prepared.provenance);
1984
2129
  const operationId = `op_${randomUUID()}`;
1985
2130
  const token = `launch_${randomUUID()}`;
1986
2131
  const taskId = supervisorTaskIdForToken(token);
@@ -2004,9 +2149,12 @@ export class ObservedWaitHost {
2004
2149
  ...(prepared.spec.argv ? { argv: [...prepared.spec.argv] } : {}),
2005
2150
  cwd: prepared.cwd,
2006
2151
  sandbox: prepared.provenance,
2152
+ supervisionPolicy: prepared.plan,
2007
2153
  branchId: owner.branchId ?? null,
2008
2154
  };
2009
2155
  this.writeLaunchContext(taskId, launchContext);
2156
+ this.launches.set(taskId, launchContext);
2157
+ if (this.options.serverOwnedResults) await this.handoffResults([store.getOperation(operationId)!]);
2010
2158
  const started = await this.startSupervisor({
2011
2159
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
2012
2160
  });
@@ -2913,6 +3061,8 @@ export class ObservedWaitHost {
2913
3061
 
2914
3062
  private reconcileOperation(operation: OperationRecord): void {
2915
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;
2916
3066
  const authority = this.supervisionAuthority(operation);
2917
3067
  if (authority === "foreign") return;
2918
3068
  let claimed = false;
@@ -3078,6 +3228,8 @@ export class ObservedWaitHost {
3078
3228
  }
3079
3229
 
3080
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;
3081
3233
  const store = this.requireStore();
3082
3234
  const status = inspection.status;
3083
3235
  const outcome = terminalOutcome(status);
@@ -3925,6 +4077,7 @@ export class ObservedWaitHost {
3925
4077
  hostId: this.hostId,
3926
4078
  storeOpen: !!this.store,
3927
4079
  closed: this.closed,
4080
+ managementMode: this.options.serverOwnedResults ? "server-client" : "legacy",
3928
4081
  activeContext: !!ctx,
3929
4082
  activeSessionId: ctx ? this.sessionIdIfAvailable(ctx) ?? this.sessionId(ctx) : undefined,
3930
4083
  activeCwd: ctx ? ctx.cwd : undefined,
@@ -3974,6 +4127,8 @@ export class ObservedWaitHost {
3974
4127
  ...(typeof value.cwd === "string" ? { cwd: value.cwd } : {}),
3975
4128
  ...(value.sandbox && typeof value.sandbox === "object" && !Array.isArray(value.sandbox)
3976
4129
  ? { sandbox: value.sandbox as TaskSandboxProvenance } : {}),
4130
+ ...(value.supervisionPolicy && typeof value.supervisionPolicy === "object"
4131
+ ? { supervisionPolicy: value.supervisionPolicy } : {}),
3977
4132
  ...(typeof value.branchId === "string" || value.branchId === null ? { branchId: value.branchId } : {}),
3978
4133
  ...(typeof value.callbackPendingAt === "number" ? { callbackPendingAt: value.callbackPendingAt } : {}),
3979
4134
  ...(typeof value.callbackDeliveredAt === "number" ? { callbackDeliveredAt: value.callbackDeliveredAt }
@@ -4065,7 +4220,8 @@ export class ObservedWaitHost {
4065
4220
  }
4066
4221
 
4067
4222
  private supervision(): SupervisionIdentity {
4068
- 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 } : {}) };
4069
4225
  }
4070
4226
 
4071
4227
  private parentAuthority(owner: OwnerIdentity, plan: ForegroundSandboxPlan): string {
@@ -47,6 +47,7 @@ export function readAssignmentWaits(path, owner, connection) {
47
47
  export function createAssignmentReader(path) {
48
48
  let db;
49
49
  let identity;
50
+ let snapshot = false;
50
51
  const statements = new Map();
51
52
  return {
52
53
  revision() {
@@ -54,6 +55,7 @@ export function createAssignmentReader(path) {
54
55
  const stat = statSync(path, { bigint: true });
55
56
  const next = `${stat.dev}:${stat.ino}`;
56
57
  if (identity !== next) {
58
+ if (snapshot) throw new Error("Coordinator identity changed during observation");
57
59
  db?.close();
58
60
  db = undefined;
59
61
  statements.clear();
@@ -63,6 +65,21 @@ export function createAssignmentReader(path) {
63
65
  db ??= new DatabaseSync(path, { readOnly: true });
64
66
  return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
65
67
  },
68
+ beginSnapshot() {
69
+ this.revision();
70
+ if (snapshot) throw new Error("Coordinator snapshot already open");
71
+ db.exec("BEGIN");
72
+ snapshot = true;
73
+ const release = () => {
74
+ if (!snapshot) return;
75
+ try { db.exec("ROLLBACK"); } finally { snapshot = false; }
76
+ };
77
+ try {
78
+ // Pin the WAL read view before recording its revision; other writers keep advancing.
79
+ db.prepare("SELECT count(*) FROM sqlite_schema").get();
80
+ return { revision: this.revision(), release };
81
+ } catch (error) { release(); throw error; }
82
+ },
66
83
  read(owner) {
67
84
  try {
68
85
  this.revision();
@@ -98,6 +115,6 @@ export function createAssignmentReader(path) {
98
115
  return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
99
116
  } catch { return undefined; }
100
117
  },
101
- close() { db?.close(); db = undefined; statements.clear(); identity = undefined; },
118
+ close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
102
119
  };
103
120
  }
@@ -48,6 +48,14 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
48
48
  return readClaim(ctx, requireId("scope", scope));
49
49
  }
50
50
 
51
+ /** Read scope transfer and its discovery claim from one SQLite snapshot. */
52
+ export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null } {
53
+ scope = requireId("scope", scope);
54
+ const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed
55
+ FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope)!;
56
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row) };
57
+ }
58
+
51
59
  export function tryClaimDiscovery(
52
60
  ctx: StoreContext,
53
61
  input: TryClaimDiscoveryInput,
@@ -62,6 +70,7 @@ export function tryClaimDiscovery(
62
70
  const expectedToken = input.expected === null ? null : requireId("expected.token", input.expected.token);
63
71
 
64
72
  return ctx.transaction(() => {
73
+ if (getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", "result-scope-v1:" + scope)) return null;
65
74
  const current = readClaim(ctx, scope);
66
75
  if (input.expected === null) {
67
76
  if (current) return null;
@@ -63,6 +63,8 @@ function normalizeSupervision(value: unknown): SupervisionIdentity | null {
63
63
  const supervision = value as Partial<SupervisionIdentity>;
64
64
  return {
65
65
  hostId: requireId("supervision.hostId", supervision.hostId),
66
+ ...(supervision.resultScope === undefined ? {} : { resultScope: requireId("supervision.resultScope", supervision.resultScope) }),
67
+ ...(supervision.resultAdapter === 1 ? { resultAdapter: 1 as const } : {}),
66
68
  runnerId: supervision.runnerId === undefined || supervision.runnerId === null
67
69
  ? null
68
70
  : requireId("supervision.runnerId", supervision.runnerId),
@@ -433,8 +435,8 @@ export function listOperations(
433
435
  params.push(requireId("taskId", filter.taskId));
434
436
  }
435
437
  const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
436
- return getRows(ctx, `SELECT * FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
437
- .map(mapOperation);
438
+ return getRows(ctx, `SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
439
+ .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
438
440
  }
439
441
 
440
442
  /** Running operations assigned to one supervising host, using the phase/host index. */
@@ -444,9 +446,9 @@ export function listRunningSupervisedBy(
444
446
  ): OperationRecord[] {
445
447
  return getRows(
446
448
  ctx,
447
- "SELECT * FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id",
449
+ "SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id",
448
450
  requireId("hostId", hostId),
449
- ).map(mapOperation);
451
+ ).map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
450
452
  }
451
453
 
452
454
  function listOutboxForRevision(