pi-better-background-tasks 0.14.3 → 0.15.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.
@@ -72,7 +72,7 @@ import {
72
72
  import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
73
73
  import type { SpawnTaskParams, WatchTaskParams } from "./runtime.js";
74
74
 
75
- export const OBSERVED_WAITS_SERVICE_VERSION = 1 as const;
75
+ export const OBSERVED_WAITS_SERVICE_VERSION = 2 as const;
76
76
  export const OBSERVED_WAITS_SERVICE_CHANNEL = "pi-better-background-tasks:observed-waits-service";
77
77
  export const OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL = "pi-better-background-tasks:observed-waits-service-request";
78
78
 
@@ -126,6 +126,27 @@ const HOST_INSTANCE_STATE = (() => {
126
126
  })();
127
127
  const LOCAL_DURABLE_ID = /^bgs_[0-9a-f]{20}$/;
128
128
  const DEFAULT_POLL_MS = 250;
129
+ /**
130
+ * A cached projection survives unchanged renders. Host notifications invalidate
131
+ * it immediately; this bound only recovers changes whose notification was lost
132
+ * or came from a process this host never observed. It is not a render cadence.
133
+ */
134
+ const DURABLE_PROJECTION_CACHE_MS = 5_000;
135
+
136
+ /** Observable work performed by {@link ObservedWaitHost.listDurableTasks}. */
137
+ export interface DurableProjectionMetrics {
138
+ listCalls: number;
139
+ queries: number;
140
+ rowsRead: number;
141
+ projectionsBuilt: number;
142
+ cacheHits: number;
143
+ }
144
+
145
+ /** The active parent scope whose durable projection changed. */
146
+ export interface DurableTaskChange {
147
+ readonly sessionId: string;
148
+ readonly workspace: string;
149
+ }
129
150
 
130
151
  /** A parent launch is always local; remote launches stay on the legacy task route. */
131
152
  export type DurableTaskKind = "process" | "watch";
@@ -164,6 +185,7 @@ export interface WaitView {
164
185
  readonly park: boolean;
165
186
  /** Cancellation epoch the caller must echo when claiming or cancelling. */
166
187
  readonly cancelEpoch: number;
188
+ readonly publishedClaimId?: string | null;
167
189
  readonly ownerKind: OwnerIdentity["kind"];
168
190
  readonly continuationNote: string;
169
191
  readonly taskIds: readonly string[];
@@ -449,6 +471,8 @@ export interface BackgroundOperationService {
449
471
  readonly serviceId: string;
450
472
  readonly available: true;
451
473
  /** True when a verified continuation adapter is registered. */
474
+ readonly assignmentContinuation: 1;
475
+ readonly outageReconciliation: 1;
452
476
  readonly continuationReady: boolean;
453
477
  ownsTask(run: WorkerRunScope, taskId: string): boolean;
454
478
  launchForWorker(run: WorkerRunScope, input: WorkerLaunchInput): Promise<DurableLaunch>;
@@ -469,6 +493,7 @@ export interface BackgroundOperationService {
469
493
  * epoch and evidence pins and invalidates the claim so nothing resumes again.
470
494
  */
471
495
  holdFailedResumeForWorker(run: WorkerRunScope, input: HoldResumedAttemptInput): HoldResumedAttemptView;
496
+ repairFailedResumeForWorker(run: WorkerRunScope, input: HoldResumedAttemptInput & { checkpointId: string; expectedCancelEpoch: number }): { phase: string; repaired: boolean };
472
497
  listWorkerWaits(run: WorkerRunScope, options?: { pendingOnly?: boolean }): readonly WaitView[];
473
498
  cancelWorkerWait(run: WorkerRunScope, input: { waitId: string; generation: number; reason: string }): WaitView;
474
499
  registerContinuationAdapter(adapter: ContinuationAdapter): void;
@@ -784,7 +809,7 @@ function evidenceFor(inspection: SupervisorInspection): WaitEvidenceView[] {
784
809
  operationId: "",
785
810
  terminalRevision: 0,
786
811
  kind: "log",
787
- ref: `${label}.log`,
812
+ ref: path,
788
813
  summary: `${label} retained (${size} bytes)`,
789
814
  detailLost: false,
790
815
  });
@@ -815,6 +840,8 @@ export class ObservedWaitHost {
815
840
  private store?: Store;
816
841
  private readonly supervisor: LocalSupervisor;
817
842
  private readonly directory: string;
843
+ private readonly storePath: string;
844
+ private readonly discoveryScope: string;
818
845
  private readonly pollMs: number;
819
846
  private readonly options: ObservedWaitHostOptions;
820
847
  private timer?: NodeJS.Timeout;
@@ -836,6 +863,20 @@ export class ObservedWaitHost {
836
863
  private readonly watchedRunningTasks = new Set<string>();
837
864
  /** Durable sidecars discovered in this supervisor directory. */
838
865
  private readonly discoveredTaskSidecars = new Set<string>();
866
+ private durableProjectionCache?: {
867
+ readonly originKey: string;
868
+ readonly key: string;
869
+ readonly at: number;
870
+ readonly list: DurableTaskProjection[];
871
+ readonly byTask: Map<string, DurableTaskProjection>;
872
+ };
873
+ private projectionMetrics: DurableProjectionMetrics = {
874
+ listCalls: 0,
875
+ queries: 0,
876
+ rowsRead: 0,
877
+ projectionsBuilt: 0,
878
+ cacheHits: 0,
879
+ };
839
880
  private continuation?: ContinuationAdapter;
840
881
  private continuationError?: string;
841
882
  private readonly launches = new Map<string, LaunchContext>();
@@ -843,19 +884,33 @@ export class ObservedWaitHost {
843
884
  private readonly waitOwners = new Map<string, OwnerIdentity>();
844
885
  private readonly stagedCheckpoints = new Map<string, { evidence: JsonRecord; toolCallId: string; checkpointRecorded: boolean }>();
845
886
  private readonly branchAnchors = new Map<string, string | null>();
846
- private readonly durableChangeListeners = new Set<() => void>();
887
+ private readonly durableChangeListeners = new Set<(change: DurableTaskChange) => void>();
847
888
  private readonly serviceId = `bg-observed-${randomUUID()}`;
848
889
  /** Opaque, validation-safe process-instance identity: pid + hashed start token. */
849
890
  private readonly hostStartDigest = startTokenDigest(currentProcessStartToken());
850
891
  private readonly hostId = `${process.pid}:${this.hostStartDigest}:${randomUUID()}`;
851
892
  private hostGeneration = ++HOST_INSTANCE_STATE.next;
893
+ private discoveryToken?: string;
894
+ private discoveryRole?: "holder" | "follower";
895
+ private reconcileInFlight?: Promise<void>;
896
+ private authorityPassCache?: Map<string, "live" | "dead" | "unknown">;
897
+ /** Running operations this follower is currently assigned to supervise. */
898
+ private readonly followerRunningTasks = new Set<string>();
899
+ private lastChangeRevision = -1;
900
+ private lastOwnedTerminalAt = 0;
852
901
 
853
902
  constructor(private readonly pi: ExtensionAPI, options: ObservedWaitHostOptions = {}) {
854
903
  this.options = options;
855
904
  this.directory = options.supervisorDirectory ?? defaultSupervisorDirectory();
905
+ this.storePath = options.storePath ?? defaultStorePath();
906
+ this.discoveryScope = createHash("sha256")
907
+ .update(`${resolve(this.storePath)}\0${resolve(this.directory)}`)
908
+ .digest("hex");
856
909
  this.supervisor = options.supervisor ?? createLocalSupervisor({ directory: this.directory });
857
910
  this.pollMs = options.pollMs ?? DEFAULT_POLL_MS;
858
911
  const base = {
912
+ assignmentContinuation: 1 as const,
913
+ outageReconciliation: 1 as const,
859
914
  version: OBSERVED_WAITS_SERVICE_VERSION,
860
915
  serviceId: this.serviceId,
861
916
  available: true as const,
@@ -873,6 +928,10 @@ export class ObservedWaitHost {
873
928
  publishResumeForWorker: (run: WorkerRunScope, input: PublishResumeViewInput) => this.publishResumeForWorker(run, input),
874
929
  releaseResumeForWorker: (run: WorkerRunScope, input: ReleaseResumeViewInput) => this.releaseResumeForWorker(run, input),
875
930
  holdFailedResumeForWorker: (run: WorkerRunScope, input: HoldResumedAttemptInput) => this.holdFailedResumeForWorker(run, input),
931
+ repairFailedResumeForWorker: (run, input) => {
932
+ this.ownedWait(this.workerOwner(run), input.waitId, input.generation);
933
+ return this.requireStore().repairFailedResume(input);
934
+ },
876
935
  listWorkerWaits: (run: WorkerRunScope, listOptions?: { pendingOnly?: boolean }) => this.listWorkerWaits(run, listOptions),
877
936
  cancelWorkerWait: (run: WorkerRunScope, input: { waitId: string; generation: number; reason: string }) => this.cancelWorkerWait(run, input),
878
937
  registerContinuationAdapter: (adapter: ContinuationAdapter) => this.registerContinuationAdapter(adapter),
@@ -908,7 +967,6 @@ export class ObservedWaitHost {
908
967
  // The same host instance can be activated for another session without a
909
968
  // reload. Re-evaluate pending deliveries against the new active origin.
910
969
  this.recoverAbandonedDeliveries();
911
- this.discoverObservedTasks();
912
970
  void this.reconcileNow();
913
971
  this.recoverTerminalNotifications();
914
972
  this.terminalRecoveryNeeded = false;
@@ -920,7 +978,7 @@ export class ObservedWaitHost {
920
978
  this.unavailableReason = undefined;
921
979
  try {
922
980
  this.store = openStore({
923
- path: this.options.storePath ?? defaultStorePath(),
981
+ path: this.storePath,
924
982
  ...(this.options.now ? { now: this.options.now } : {}),
925
983
  });
926
984
  } catch (error) {
@@ -936,7 +994,6 @@ export class ObservedWaitHost {
936
994
  this.announce();
937
995
  this.writeHostDebug();
938
996
  this.recoverAbandonedDeliveries();
939
- this.discoverObservedTasks();
940
997
  void this.reconcileNow();
941
998
  this.recoverTerminalNotifications();
942
999
  this.terminalRecoveryNeeded = false;
@@ -952,6 +1009,8 @@ export class ObservedWaitHost {
952
1009
  HOST_INSTANCE_STATE.closed.add(this.hostId);
953
1010
  if (this.timer) clearInterval(this.timer);
954
1011
  this.timer = undefined;
1012
+ this.releaseDiscoveryAuthority();
1013
+ this.releaseSupervisionAuthority();
955
1014
  try { this.store?.close(); } catch { /* already closed */ }
956
1015
  this.store = undefined;
957
1016
  this.launches.clear();
@@ -965,6 +1024,7 @@ export class ObservedWaitHost {
965
1024
  this.pendingTerminalCallbacks.clear();
966
1025
  this.watchedRunningTasks.clear();
967
1026
  this.discoveredTaskSidecars.clear();
1027
+ this.durableProjectionCache = undefined;
968
1028
  this.writeHostDebug();
969
1029
  this.announceUnavailable("the Background operation host closed");
970
1030
  }
@@ -995,6 +1055,7 @@ export class ObservedWaitHost {
995
1055
  if (!store) return;
996
1056
  let names: string[];
997
1057
  try { names = readdirSync(join(this.directory, "observed")); } catch { return; }
1058
+ let visibleOwner: OwnerIdentity | undefined;
998
1059
  for (const name of names) {
999
1060
  if (!name.endsWith(".json") || name === "host.json") continue;
1000
1061
  const taskId = name.slice(0, -5);
@@ -1002,6 +1063,7 @@ export class ObservedWaitHost {
1002
1063
  const operation = this.operationForTask(taskId);
1003
1064
  if (!operation) continue; // registration may land on the next tick
1004
1065
  this.discoveredTaskSidecars.add(taskId);
1066
+ if (this.activeOwnerRelation(operation.owner) === "match") visibleOwner = operation.owner;
1005
1067
  if (operation.terminalRevision > 0) {
1006
1068
  this.attemptTerminalCallback(
1007
1069
  operation,
@@ -1014,6 +1076,10 @@ export class ObservedWaitHost {
1014
1076
  this.watchedRunningTasks.add(taskId);
1015
1077
  }
1016
1078
  }
1079
+ // A task launched by another Pi process became visible in this host's
1080
+ // supervisor directory. The navigator must refresh without waiting for a
1081
+ // render to rediscover it, and its cached projections are now stale.
1082
+ if (visibleOwner) this.emitDurableTaskChange(visibleOwner);
1017
1083
  }
1018
1084
 
1019
1085
  /**
@@ -1058,15 +1124,48 @@ export class ObservedWaitHost {
1058
1124
 
1059
1125
  /** A deterministic, awaitable reconciliation pass for tests and session activation. */
1060
1126
  async reconcileNow(): Promise<void> {
1127
+ if (this.reconcileInFlight) return this.reconcileInFlight;
1128
+ const pass = this.reconcilePass();
1129
+ this.reconcileInFlight = pass;
1130
+ try {
1131
+ await pass;
1132
+ } finally {
1133
+ if (this.reconcileInFlight === pass) this.reconcileInFlight = undefined;
1134
+ }
1135
+ }
1136
+
1137
+ private async reconcilePass(): Promise<void> {
1061
1138
  if (!this.store || this.closed) return;
1062
- this.discoverObservedTasks();
1063
- const running = this.store.listOperations({ phase: "running" });
1139
+ this.authorityPassCache = new Map();
1140
+ try {
1141
+ const role = this.refreshDiscoveryAuthority();
1142
+ this.noteDiscoveryRole(role);
1143
+ if (role === "holder") {
1144
+ this.discoverObservedTasks();
1145
+ this.reconcileGlobalRunning();
1146
+ } else {
1147
+ this.reconcileFollowerRunning();
1148
+ this.reconcileOwnerChanges();
1149
+ }
1150
+ this.retryPendingTerminalCallbacks();
1151
+ await this.dispatchOutbox();
1152
+ } finally {
1153
+ this.authorityPassCache = undefined;
1154
+ }
1155
+ }
1156
+
1157
+ private reconcileGlobalRunning(): void {
1158
+ const store = this.store;
1159
+ if (!store) return;
1160
+ const running = store.listOperations({ phase: "running" });
1064
1161
  const runningIds = new Set(running.map((operation) => operation.taskId));
1162
+ let changedOwner: OwnerIdentity | undefined;
1065
1163
  for (const taskId of [...this.watchedRunningTasks]) {
1066
1164
  if (runningIds.has(taskId)) continue;
1067
1165
  this.watchedRunningTasks.delete(taskId);
1068
1166
  const operation = this.operationForTask(taskId);
1069
1167
  if (operation && operation.terminalRevision > 0) {
1168
+ if (this.activeOwnerRelation(operation.owner) === "match") changedOwner = operation.owner;
1070
1169
  // Another host may have recorded the terminal result without a live
1071
1170
  // owner context. This host watched the operation, so recover its callback
1072
1171
  // now that the active branch/identity can authorize the handoff.
@@ -1079,12 +1178,131 @@ export class ObservedWaitHost {
1079
1178
  );
1080
1179
  }
1081
1180
  }
1181
+ if (changedOwner) this.emitDurableTaskChange(changedOwner);
1082
1182
  for (const operation of running) {
1083
1183
  this.watchedRunningTasks.add(operation.taskId);
1084
1184
  this.reconcileOperation(operation);
1085
1185
  }
1086
- this.retryPendingTerminalCallbacks();
1087
- await this.dispatchOutbox();
1186
+ }
1187
+
1188
+ private reconcileFollowerRunning(): void {
1189
+ const store = this.store;
1190
+ if (!store) return;
1191
+ const running = store.listRunningSupervisedBy(this.hostId);
1192
+ const runningIds = new Set(running.map((operation) => operation.taskId));
1193
+ for (const taskId of [...this.followerRunningTasks]) {
1194
+ if (!runningIds.has(taskId)) this.followerRunningTasks.delete(taskId);
1195
+ }
1196
+ for (const operation of running) {
1197
+ this.followerRunningTasks.add(operation.taskId);
1198
+ this.reconcileOperation(operation);
1199
+ }
1200
+ }
1201
+
1202
+ /**
1203
+ * A follower does not scan foreign operations. It refreshes the exact active
1204
+ * owner's terminal records only when the shared change revision advances, so
1205
+ * callback recovery stays correct without multiplying the running-set scan.
1206
+ */
1207
+ private reconcileOwnerChanges(): void {
1208
+ const store = this.store;
1209
+ const ctx = this.activeContext;
1210
+ if (!store || !ctx) return;
1211
+ const sessionId = this.sessionIdIfAvailable(ctx);
1212
+ if (!sessionId) return;
1213
+ let revision: number;
1214
+ try {
1215
+ revision = store.getChangeRevision();
1216
+ } catch {
1217
+ return;
1218
+ }
1219
+ if (revision === this.lastChangeRevision) return;
1220
+ this.lastChangeRevision = revision;
1221
+ let operations: OperationRecord[];
1222
+ try {
1223
+ operations = store.listOperations({
1224
+ ownerScope: { kind: "parent-session", sessionId, workspace: ctx.cwd },
1225
+ phase: "terminal",
1226
+ });
1227
+ } catch {
1228
+ return;
1229
+ }
1230
+ let newest = this.lastOwnedTerminalAt;
1231
+ let visibleOwner: OwnerIdentity | undefined;
1232
+ for (const operation of operations) {
1233
+ newest = Math.max(newest, operation.terminalAt ?? operation.updatedAt);
1234
+ if (this.activeOwnerRelation(operation.owner) === "match") visibleOwner ??= operation.owner;
1235
+ this.attemptTerminalCallback(
1236
+ operation,
1237
+ this.statusOf(operation.operationId),
1238
+ operation.terminalOutcome ?? "failed",
1239
+ [],
1240
+ { pendingWithoutContext: true },
1241
+ );
1242
+ }
1243
+ if (newest > this.lastOwnedTerminalAt) {
1244
+ this.lastOwnedTerminalAt = newest;
1245
+ if (visibleOwner) this.emitDurableTaskChange(visibleOwner);
1246
+ }
1247
+ }
1248
+
1249
+ private noteDiscoveryRole(role: "holder" | "follower"): void {
1250
+ if (this.discoveryRole === role) return;
1251
+ this.discoveryRole = role;
1252
+ this.followerRunningTasks.clear();
1253
+ if (role === "holder") {
1254
+ this.watchedRunningTasks.clear();
1255
+ this.discoveredTaskSidecars.clear();
1256
+ }
1257
+ this.lastChangeRevision = -1;
1258
+ }
1259
+
1260
+ /**
1261
+ * Acquire or confirm the one shared discovery claim. Process identity and
1262
+ * explicit close evidence decide replacement; elapsed time is not a lease.
1263
+ */
1264
+ private refreshDiscoveryAuthority(): "holder" | "follower" {
1265
+ const store = this.store;
1266
+ if (!store) return "follower";
1267
+ let claim;
1268
+ try {
1269
+ claim = store.readDiscoveryClaim(this.discoveryScope);
1270
+ } catch {
1271
+ return "follower";
1272
+ }
1273
+ if (claim?.hostId === this.hostId) {
1274
+ this.discoveryToken = claim.token;
1275
+ return "holder";
1276
+ }
1277
+ if (claim) {
1278
+ const state = this.discoveryHolderState(claim.hostId);
1279
+ if (state === "live" || state === "unknown") {
1280
+ this.discoveryToken = undefined;
1281
+ return "follower";
1282
+ }
1283
+ }
1284
+ const token = `discovery_${randomUUID()}`;
1285
+ try {
1286
+ const claimed = store.tryClaimDiscovery({
1287
+ scope: this.discoveryScope,
1288
+ expected: claim ? { hostId: claim.hostId, token: claim.token } : null,
1289
+ hostId: this.hostId,
1290
+ token,
1291
+ });
1292
+ if (claimed) {
1293
+ this.discoveryToken = claimed.token;
1294
+ return "holder";
1295
+ }
1296
+ } catch {
1297
+ // A busy store or a lost race defers discovery to a later pass.
1298
+ }
1299
+ this.discoveryToken = undefined;
1300
+ return "follower";
1301
+ }
1302
+
1303
+ private discoveryHolderState(hostId: string): "live" | "dead" | "unknown" {
1304
+ if (hostId === this.hostId) return "live";
1305
+ return this.supervisionHolderState(hostId);
1088
1306
  }
1089
1307
 
1090
1308
  isDurableTask(taskId: string): boolean {
@@ -1141,7 +1359,7 @@ export class ObservedWaitHost {
1141
1359
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1142
1360
  });
1143
1361
  this.launches.set(taskId, launchContext);
1144
- this.emitDurableTaskChange();
1362
+ this.emitDurableTaskChange(owner);
1145
1363
  const launch: DurableLaunch = {
1146
1364
  id: taskId,
1147
1365
  operationId,
@@ -1261,10 +1479,27 @@ export class ObservedWaitHost {
1261
1479
  ): DurableTaskProjection[] {
1262
1480
  const store = this.store;
1263
1481
  if (!store || this.closed) return [];
1482
+ if (!origin.sessionId) return [];
1483
+ this.projectionMetrics.listCalls += 1;
1264
1484
  const now = this.options.now?.() ?? Date.now();
1485
+ const originKey = `${origin.cwd}\0${origin.sessionId}`;
1486
+ const cacheKey = `${originKey}\0${options.retentionMs ?? ""}\0${options.includeDismissed === true ? 1 : 0}`;
1487
+ const cached = this.durableProjectionCache;
1488
+ if (cached && cached.key === cacheKey && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
1489
+ this.projectionMetrics.cacheHits += 1;
1490
+ if (options.retentionMs === undefined) return cached.list;
1491
+ const live = cached.list.filter((projection) => !this.expiredProjection(projection, options, now));
1492
+ return live.length === cached.list.length ? cached.list : live;
1493
+ }
1265
1494
  const projections: DurableTaskProjection[] = [];
1266
- for (const operation of store.listOperations()) {
1495
+ const operations = store.listOperations({
1496
+ ownerScope: { kind: "parent-session", sessionId: origin.sessionId, workspace: origin.cwd },
1497
+ });
1498
+ this.projectionMetrics.queries += 1;
1499
+ this.projectionMetrics.rowsRead += operations.length;
1500
+ for (const operation of operations) {
1267
1501
  if (!this.belongsToParentOrigin(operation, origin)) continue;
1502
+ this.projectionMetrics.projectionsBuilt += 1;
1268
1503
  const projection = this.projectDurable(operation, now);
1269
1504
  if (!projection) continue;
1270
1505
  if (projection.dismissedAt !== undefined && options.includeDismissed !== true) continue;
@@ -1274,13 +1509,49 @@ export class ObservedWaitHost {
1274
1509
  }
1275
1510
  projections.push(projection);
1276
1511
  }
1277
- return projections.sort((a, b) => b.startedAt - a.startedAt);
1512
+ projections.sort((a, b) => b.startedAt - a.startedAt);
1513
+ this.durableProjectionCache = {
1514
+ originKey,
1515
+ key: cacheKey,
1516
+ at: now,
1517
+ list: projections,
1518
+ byTask: new Map(projections.map((projection) => [projection.id, projection])),
1519
+ };
1520
+ const live = projections.filter((projection) => !this.expiredProjection(projection, options, now));
1521
+ return live.length === projections.length ? projections : live;
1278
1522
  }
1279
1523
 
1280
1524
  readDurableTask(origin: BackgroundTaskCallbackOrigin, taskId: string): DurableTaskProjection | undefined {
1525
+ const now = this.options.now?.() ?? Date.now();
1526
+ const cached = this.durableProjectionCache;
1527
+ if (cached && cached.originKey === `${origin.cwd}\0${origin.sessionId ?? ""}`
1528
+ && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
1529
+ const projection = cached.byTask.get(taskId);
1530
+ if (projection) return projection;
1531
+ }
1281
1532
  const operation = this.operationForTask(taskId);
1282
1533
  if (!operation || !this.belongsToParentOrigin(operation, origin)) return undefined;
1283
- return this.projectDurable(operation, this.options.now?.() ?? Date.now());
1534
+ this.projectionMetrics.projectionsBuilt += 1;
1535
+ return this.projectDurable(operation, now);
1536
+ }
1537
+
1538
+ /** Accumulated projection work, for performance regression proof. */
1539
+ getDurableProjectionMetrics(): DurableProjectionMetrics {
1540
+ return { ...this.projectionMetrics };
1541
+ }
1542
+
1543
+ resetDurableProjectionMetrics(): void {
1544
+ this.projectionMetrics = { listCalls: 0, queries: 0, rowsRead: 0, projectionsBuilt: 0, cacheHits: 0 };
1545
+ }
1546
+
1547
+ private expiredProjection(
1548
+ projection: DurableTaskProjection,
1549
+ options: { retentionMs?: number },
1550
+ now: number,
1551
+ ): boolean {
1552
+ if (!projection.terminal || options.retentionMs === undefined) return false;
1553
+ const endedAt = projection.endedAt ?? now;
1554
+ return now - endedAt >= options.retentionMs;
1284
1555
  }
1285
1556
 
1286
1557
  /**
@@ -1321,6 +1592,7 @@ export class ObservedWaitHost {
1321
1592
  const operation = this.operationForTask(taskId);
1322
1593
  if (!operation || !this.belongsToParentOrigin(operation, origin)) return undefined;
1323
1594
  await this.stop(taskId, operation.owner);
1595
+ this.invalidateDurableProjection(operation.owner);
1324
1596
  return this.projectDurable(operation, this.options.now?.() ?? Date.now());
1325
1597
  }
1326
1598
 
@@ -1342,21 +1614,32 @@ export class ObservedWaitHost {
1342
1614
  context.dismissedAt = Date.now();
1343
1615
  this.launches.set(taskId, context);
1344
1616
  this.writeLaunchContext(taskId, context);
1345
- this.emitDurableTaskChange();
1617
+ this.emitDurableTaskChange(operation.owner);
1346
1618
  return true;
1347
1619
  }
1348
1620
 
1349
- onDurableTaskChange(listener: () => void): () => void {
1621
+ onDurableTaskChange(listener: (change: DurableTaskChange) => void): () => void {
1350
1622
  this.durableChangeListeners.add(listener);
1351
1623
  return () => { this.durableChangeListeners.delete(listener); };
1352
1624
  }
1353
1625
 
1354
- private emitDurableTaskChange(): void {
1626
+ private emitDurableTaskChange(owner: OwnerIdentity): void {
1627
+ // Navigators and Goal activity only show the active parent session. A
1628
+ // worker, another session, or another workspace must not evict its cache or
1629
+ // request a repaint.
1630
+ if (owner.kind !== "parent-session" || this.activeOwnerRelation(owner) !== "match") return;
1631
+ this.invalidateDurableProjection(owner);
1632
+ const change = { sessionId: owner.sessionId, workspace: owner.workspace };
1355
1633
  for (const listener of [...this.durableChangeListeners]) {
1356
- try { listener(); } catch { /* a projection listener cannot break supervision */ }
1634
+ try { listener(change); } catch { /* a projection listener cannot break supervision */ }
1357
1635
  }
1358
1636
  }
1359
1637
 
1638
+ private invalidateDurableProjection(owner?: OwnerIdentity): void {
1639
+ if (owner && (owner.kind !== "parent-session" || this.activeOwnerRelation(owner) !== "match")) return;
1640
+ this.durableProjectionCache = undefined;
1641
+ }
1642
+
1360
1643
  private belongsToParentOrigin(operation: OperationRecord, origin: BackgroundTaskCallbackOrigin): boolean {
1361
1644
  if (operation.owner.kind !== "parent-session") return false;
1362
1645
  if (operation.owner.workspace !== origin.cwd) return false;
@@ -1641,7 +1924,7 @@ export class ObservedWaitHost {
1641
1924
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1642
1925
  });
1643
1926
  this.launches.set(taskId, launchContext);
1644
- this.emitDurableTaskChange();
1927
+ this.emitDurableTaskChange(owner);
1645
1928
  return {
1646
1929
  id: taskId,
1647
1930
  operationId,
@@ -1966,6 +2249,7 @@ export class ObservedWaitHost {
1966
2249
  }
1967
2250
 
1968
2251
  private rpcRegisterRun(params: JsonRecord): JsonRecord {
2252
+ if (params.assignmentOutcomesVersion !== undefined && params.assignmentOutcomesVersion !== 1) throw new Error("Unsupported assignment outcome capability; this host supports version 1.");
1969
2253
  const runId = requireRpcString(params, "runId");
1970
2254
  const conversationId = requireRpcString(params, "conversationId");
1971
2255
  const workspace = requireRpcString(params, "workspace");
@@ -2002,7 +2286,7 @@ export class ObservedWaitHost {
2002
2286
  ...(typeof params.writerPid === "number" && params.writerPid > 0 ? { writerPid: params.writerPid } : {}),
2003
2287
  ...(typeof params.writerLeaseId === "string" ? { writerLeaseId: params.writerLeaseId } : {}),
2004
2288
  }));
2005
- return { runId, conversationId, workspace, attemptId, workerOperations: true };
2289
+ return { runId, conversationId, workspace, attemptId, workerOperations: true, assignmentOutcomesVersion: 1 };
2006
2290
  }
2007
2291
 
2008
2292
  private rpcReleaseRun(params: JsonRecord): JsonRecord {
@@ -2542,6 +2826,27 @@ export class ObservedWaitHost {
2542
2826
 
2543
2827
  private reconcileOperation(operation: OperationRecord): void {
2544
2828
  if (operation.terminalRevision > 0) return;
2829
+ const authority = this.supervisionAuthority(operation);
2830
+ if (authority === "foreign") return;
2831
+ let claimed = false;
2832
+ if (authority === "replace") {
2833
+ try {
2834
+ this.store?.recordSupervision({
2835
+ operationId: operation.operationId,
2836
+ owner: operation.owner,
2837
+ expectedHostId: operation.supervision?.hostId ?? null,
2838
+ supervision: this.supervision(),
2839
+ health: "active",
2840
+ });
2841
+ claimed = true;
2842
+ } catch (error) {
2843
+ // Another host can hold the write lock, or it can take over between the
2844
+ // snapshot and this write. Leave the observed record alone and let the
2845
+ // next reconciliation tick re-read it.
2846
+ if (rpcCode(error) === "store-busy" || rpcCode(error) === "supervision-conflict") return;
2847
+ throw error;
2848
+ }
2849
+ }
2545
2850
  const inspection = this.inspect(operation.taskId);
2546
2851
  if (!inspection) {
2547
2852
  const now = this.options.now?.() ?? Date.now();
@@ -2569,12 +2874,15 @@ export class ObservedWaitHost {
2569
2874
  return;
2570
2875
  }
2571
2876
  try {
2572
- this.store?.recordSupervision({
2573
- operationId: operation.operationId,
2574
- owner: operation.owner,
2575
- health: "unmonitored",
2576
- reason: "no durable supervisor record exists for this operation",
2577
- });
2877
+ if (claimed || operation.health !== "unmonitored" || operation.healthReason !== "no durable supervisor record exists for this operation") {
2878
+ this.store?.recordSupervision({
2879
+ operationId: operation.operationId,
2880
+ owner: operation.owner,
2881
+ expectedHostId: this.hostId,
2882
+ health: "unmonitored",
2883
+ reason: "no durable supervisor record exists for this operation",
2884
+ });
2885
+ }
2578
2886
  } catch { /* the owner may have been superseded; health is observational */ }
2579
2887
  return;
2580
2888
  }
@@ -2582,15 +2890,99 @@ export class ObservedWaitHost {
2582
2890
  this.recordTerminal(operation, inspection);
2583
2891
  return;
2584
2892
  }
2585
- if (operation.health !== "active" || operation.supervision?.hostId !== this.hostId) {
2893
+ if (!claimed && (operation.health !== "active" || operation.supervision?.hostId !== this.hostId)) {
2586
2894
  // Health is observational; write it only when the supervising host or the
2587
2895
  // reported health actually changed. A 250 ms tick must not churn SQLite.
2588
- this.store?.recordSupervision({
2589
- operationId: operation.operationId,
2590
- owner: operation.owner,
2591
- supervision: this.supervision(),
2592
- health: "active",
2593
- });
2896
+ try {
2897
+ this.store?.recordSupervision({
2898
+ operationId: operation.operationId,
2899
+ owner: operation.owner,
2900
+ expectedHostId: this.hostId,
2901
+ supervision: this.supervision(),
2902
+ health: "active",
2903
+ });
2904
+ } catch (error) {
2905
+ // Another host can hold the write lock or have taken over. Leave health
2906
+ // unchanged and let the next tick re-read the operation.
2907
+ if (rpcCode(error) !== "store-busy" && rpcCode(error) !== "supervision-conflict") throw error;
2908
+ }
2909
+ }
2910
+ }
2911
+
2912
+ /**
2913
+ * Whether this host may inspect the operation. The recorded `supervision`
2914
+ * identity is the cross-process authority marker: a live holder keeps it, and
2915
+ * only a closed or dead holder is replaced. Process identity is checked before
2916
+ * elapsed time, and an unprovable holder is never stolen from.
2917
+ */
2918
+ private supervisionAuthority(operation: OperationRecord): "self" | "foreign" | "replace" {
2919
+ const hostId = operation.supervision?.hostId;
2920
+ if (!hostId) return "replace";
2921
+ if (hostId === this.hostId) return "self";
2922
+ if (HOST_INSTANCE_STATE.closed.has(hostId)) return "replace";
2923
+ const cached = this.authorityPassCache?.get(hostId);
2924
+ const state = cached ?? this.supervisionHolderState(hostId);
2925
+ if (cached === undefined) this.authorityPassCache?.set(hostId, state);
2926
+ return state === "live" || state === "unknown" ? "foreign" : "replace";
2927
+ }
2928
+
2929
+ /** Process-identity check for a recorded holder, cached per pass by callers. */
2930
+ private supervisionHolderState(hostId: string): "live" | "dead" | "unknown" {
2931
+ const { pid, startTokenDigest: claimedDigest } = parseHostIdentity(hostId);
2932
+ if (!pid) return "unknown";
2933
+ if (pid === process.pid) {
2934
+ const generation = HOST_INSTANCE_STATE.generations.get(hostId);
2935
+ // Another instance in this process still owns its record. Creation order
2936
+ // alone is not death: a reload predecessor is marked closed above.
2937
+ return generation === undefined ? "dead" : "live";
2938
+ }
2939
+ if (!processExists(pid)) return "dead";
2940
+ if (!claimedDigest) return "unknown";
2941
+ const current = readProcessStartToken(pid);
2942
+ if (!current) return "unknown";
2943
+ return startTokenDigest(current) === claimedDigest ? "live" : "dead";
2944
+ }
2945
+
2946
+ /**
2947
+ * A graceful close releases only this host's running authority. A crash leaves
2948
+ * the same record for the next host to replace after process identity proves it
2949
+ * dead; a newer holder is never cleared by a late close.
2950
+ */
2951
+ private releaseSupervisionAuthority(): void {
2952
+ const store = this.store;
2953
+ if (!store) return;
2954
+ let running: OperationRecord[];
2955
+ try {
2956
+ running = store.listOperations({ phase: "running" });
2957
+ } catch {
2958
+ return;
2959
+ }
2960
+ for (const operation of running) {
2961
+ if (operation.supervision?.hostId !== this.hostId) continue;
2962
+ try {
2963
+ store.releaseSupervision({
2964
+ operationId: operation.operationId,
2965
+ owner: operation.owner,
2966
+ hostId: this.hostId,
2967
+ reason: "the supervising host closed; another host may take over",
2968
+ });
2969
+ } catch {
2970
+ // Closing must not fail on a busy or already replaced record.
2971
+ }
2972
+ }
2973
+ }
2974
+
2975
+ /** Release only this host's exact discovery claim; a successor keeps its own. */
2976
+ private releaseDiscoveryAuthority(): void {
2977
+ const store = this.store;
2978
+ const token = this.discoveryToken;
2979
+ this.discoveryToken = undefined;
2980
+ this.discoveryRole = undefined;
2981
+ if (!store || !token) return;
2982
+ try {
2983
+ store.releaseDiscoveryClaim({ scope: this.discoveryScope, hostId: this.hostId, token });
2984
+ } catch {
2985
+ // Closing must not fail on a busy or already replaced claim.
2594
2986
  }
2595
2987
  }
2596
2988
 
@@ -2652,11 +3044,15 @@ export class ObservedWaitHost {
2652
3044
  refs,
2653
3045
  { pendingWithoutContext: true },
2654
3046
  );
3047
+ // The local projection cache may still show this operation as running even
3048
+ // though another process committed its terminal revision. Invalidate and
3049
+ // notify so the navigator repaints on this reconcile pass.
3050
+ this.emitDurableTaskChange(recorded.operation.owner);
2655
3051
  return;
2656
3052
  }
2657
3053
  this.options.logger?.(`observed waits: ${operation.taskId} ${status} (revision ${recorded.operation.terminalRevision})`);
2658
3054
  this.attemptTerminalCallback(operation, status, outcome, refs, { pendingWithoutContext: true });
2659
- this.emitDurableTaskChange();
3055
+ this.emitDurableTaskChange(operation.owner);
2660
3056
  // The parent callback is independent from the worker's wait: a worker may be
2661
3057
  // parked, while the parent session still learns that the supervised task ended.
2662
3058
  void this.dispatchOutbox();
@@ -2837,7 +3233,8 @@ export class ObservedWaitHost {
2837
3233
  delete context.callbackDeferredReason;
2838
3234
  this.launches.set(taskId, context);
2839
3235
  this.writeLaunchContext(taskId, context);
2840
- this.emitDurableTaskChange();
3236
+ const operation = this.operationForTask(taskId);
3237
+ if (operation) this.emitDurableTaskChange(operation.owner);
2841
3238
  }
2842
3239
 
2843
3240
  private deferTerminalCallback(taskId: string, reason: string, retry = true, claimToken?: string): void {
@@ -2987,6 +3384,7 @@ export class ObservedWaitHost {
2987
3384
  let claimed: OutboxEventRecord[];
2988
3385
  try {
2989
3386
  claimed = store.claimOutbox({
3387
+ type: "dependency-ready",
2990
3388
  recipient: owner,
2991
3389
  claimToken,
2992
3390
  claimedBy: this.hostId,
@@ -3174,6 +3572,7 @@ export class ObservedWaitHost {
3174
3572
  settled: wait.settled,
3175
3573
  park: wait.park !== null,
3176
3574
  cancelEpoch: wait.cancelEpoch,
3575
+ publishedClaimId: store.listResumeClaims({ waitId: wait.waitId, generation: wait.generation, state: "published" })[0]?.claimId ?? null,
3177
3576
  ownerKind: wait.owner.kind,
3178
3577
  continuationNote: wait.continuationNote,
3179
3578
  taskIds: dependencies
@@ -3406,7 +3805,10 @@ export class ObservedWaitHost {
3406
3805
  // A tool call or activation for a different session/workspace must seed the
3407
3806
  // terminal callback journal once. Same-session calls keep the live context
3408
3807
  // current without rescanning historical terminal records.
3409
- if (!previous || previousKey !== nextKey) this.terminalRecoveryNeeded = true;
3808
+ if (!previous || previousKey !== nextKey) {
3809
+ this.terminalRecoveryNeeded = true;
3810
+ this.lastChangeRevision = -1;
3811
+ }
3410
3812
  this.writeHostDebug();
3411
3813
  }
3412
3814