pi-better-background-tasks 0.14.3 → 0.14.4

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.14.3",
3
+ "version": "0.14.4",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,6 +22,12 @@ import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.j
22
22
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta, BackgroundTaskStatus } from "./types.js";
23
23
 
24
24
  const TERMINAL_NAVIGATOR_RETENTION_MS = 30_000;
25
+ const DURABLE_ROW_CACHE_MS = 1_000;
26
+ let durableRowCache: {
27
+ tasks: readonly DurableTaskProjection[];
28
+ at: number;
29
+ rows: BackgroundWorkRow[];
30
+ } | undefined;
25
31
 
26
32
  export function createBackgroundTasksNavigator(runtime: Pick<BackgroundTaskRuntime, "stopTask"> = { stopTask }) {
27
33
  const owner = Symbol("background-tasks navigator factory");
@@ -88,7 +94,7 @@ const provider: BackgroundWorkProvider = {
88
94
  },
89
95
  listRows: (now) => [
90
96
  ...visibleMetas(now).map((meta) => rowFromMeta(meta, now)),
91
- ...visibleDurableTasks(now).map((task) => rowFromDurable(task, now)),
97
+ ...durableRows(visibleDurableTasks(now), now),
92
98
  ],
93
99
  detail: (id, now, options) => {
94
100
  const durable = durableTask(id);
@@ -123,12 +129,12 @@ const provider: BackgroundWorkProvider = {
123
129
  },
124
130
  onVisibleChanged: (notify) => {
125
131
  const offMeta = onMetaChanged(notify);
126
- const offDurable = getObservedWaitHost(piRef)?.onDurableTaskChange(() => {
127
- invalidateDurableProjection();
132
+ const offDurable = getObservedWaitHost(piRef)?.onDurableTaskChange((change) => {
133
+ const active = activeNavigatorOrigin;
134
+ if (!active || change.workspace !== active.cwd || change.sessionId !== active.sessionId) return;
128
135
  notify();
129
136
  });
130
137
  return () => {
131
- invalidateDurableProjection();
132
138
  offMeta();
133
139
  offDurable?.();
134
140
  };
@@ -139,30 +145,24 @@ function navigatorHost() {
139
145
  return piRef ? getObservedWaitHost(piRef) : undefined;
140
146
  }
141
147
 
142
- /**
143
- * One refresh asks for {@link provider.visibleCount} and then {@link provider.listRows},
144
- * and a detail view asks again. Rebuilding the projection re-reads every durable
145
- * record, so a single paint would pay for the same list up to three times. Hold
146
- * one result per paint window; a durable-change notification clears it.
147
- */
148
- const PROJECTION_MEMO_MS = 250;
149
- let projectionMemo: { at: number; tasks: DurableTaskProjection[] } | undefined;
150
-
151
- function invalidateDurableProjection(): void {
152
- projectionMemo = undefined;
153
- }
154
-
155
148
  function visibleDurableTasks(now = Date.now()): DurableTaskProjection[] {
156
149
  const active = activeNavigatorOrigin;
157
150
  const host = navigatorHost();
158
151
  if (!active || !host) return [];
159
- if (projectionMemo && now - projectionMemo.at < PROJECTION_MEMO_MS) {
160
- return projectionMemo.tasks.filter((task) => !isExpiredDurableRow(task, now));
161
- }
152
+ // ObservedWaitHost caches unchanged projections and invalidates them on every
153
+ // durable notification, so a host redraw no longer re-queries per panel.
162
154
  const listed = host.listDurableTasks(active, { retentionMs: TERMINAL_NAVIGATOR_RETENTION_MS });
163
- const tasks = listed.filter((task) => task.dismissedAt === undefined);
164
- projectionMemo = { at: now, tasks };
165
- return tasks.filter((task) => !isExpiredDurableRow(task, now));
155
+ return listed;
156
+ }
157
+
158
+ function durableRows(tasks: readonly DurableTaskProjection[], now: number): BackgroundWorkRow[] {
159
+ if (durableRowCache && durableRowCache.tasks === tasks
160
+ && now >= durableRowCache.at && now - durableRowCache.at < DURABLE_ROW_CACHE_MS) {
161
+ return durableRowCache.rows;
162
+ }
163
+ const rows = tasks.map((task) => rowFromDurable(task, now));
164
+ durableRowCache = { tasks, at: now, rows };
165
+ return rows;
166
166
  }
167
167
 
168
168
  function durableTask(id: string): DurableTaskProjection | undefined {
@@ -172,11 +172,6 @@ function durableTask(id: string): DurableTaskProjection | undefined {
172
172
  return host.readDurableTask(active, id);
173
173
  }
174
174
 
175
- function isExpiredDurableRow(task: DurableTaskProjection, now: number): boolean {
176
- if (!task.terminal || task.endedAt === undefined) return false;
177
- return now - task.endedAt >= TERMINAL_NAVIGATOR_RETENTION_MS;
178
- }
179
-
180
175
  function rowFromDurable(task: DurableTaskProjection, now: number): BackgroundWorkRow {
181
176
  const command = durableCommandLabel(task);
182
177
  const elapsed = formatDuration((task.endedAt ?? now) - task.startedAt);
@@ -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";
@@ -836,6 +857,20 @@ export class ObservedWaitHost {
836
857
  private readonly watchedRunningTasks = new Set<string>();
837
858
  /** Durable sidecars discovered in this supervisor directory. */
838
859
  private readonly discoveredTaskSidecars = new Set<string>();
860
+ private durableProjectionCache?: {
861
+ readonly originKey: string;
862
+ readonly key: string;
863
+ readonly at: number;
864
+ readonly list: DurableTaskProjection[];
865
+ readonly byTask: Map<string, DurableTaskProjection>;
866
+ };
867
+ private projectionMetrics: DurableProjectionMetrics = {
868
+ listCalls: 0,
869
+ queries: 0,
870
+ rowsRead: 0,
871
+ projectionsBuilt: 0,
872
+ cacheHits: 0,
873
+ };
839
874
  private continuation?: ContinuationAdapter;
840
875
  private continuationError?: string;
841
876
  private readonly launches = new Map<string, LaunchContext>();
@@ -843,7 +878,7 @@ export class ObservedWaitHost {
843
878
  private readonly waitOwners = new Map<string, OwnerIdentity>();
844
879
  private readonly stagedCheckpoints = new Map<string, { evidence: JsonRecord; toolCallId: string; checkpointRecorded: boolean }>();
845
880
  private readonly branchAnchors = new Map<string, string | null>();
846
- private readonly durableChangeListeners = new Set<() => void>();
881
+ private readonly durableChangeListeners = new Set<(change: DurableTaskChange) => void>();
847
882
  private readonly serviceId = `bg-observed-${randomUUID()}`;
848
883
  /** Opaque, validation-safe process-instance identity: pid + hashed start token. */
849
884
  private readonly hostStartDigest = startTokenDigest(currentProcessStartToken());
@@ -965,6 +1000,7 @@ export class ObservedWaitHost {
965
1000
  this.pendingTerminalCallbacks.clear();
966
1001
  this.watchedRunningTasks.clear();
967
1002
  this.discoveredTaskSidecars.clear();
1003
+ this.durableProjectionCache = undefined;
968
1004
  this.writeHostDebug();
969
1005
  this.announceUnavailable("the Background operation host closed");
970
1006
  }
@@ -995,6 +1031,7 @@ export class ObservedWaitHost {
995
1031
  if (!store) return;
996
1032
  let names: string[];
997
1033
  try { names = readdirSync(join(this.directory, "observed")); } catch { return; }
1034
+ let visibleOwner: OwnerIdentity | undefined;
998
1035
  for (const name of names) {
999
1036
  if (!name.endsWith(".json") || name === "host.json") continue;
1000
1037
  const taskId = name.slice(0, -5);
@@ -1002,6 +1039,7 @@ export class ObservedWaitHost {
1002
1039
  const operation = this.operationForTask(taskId);
1003
1040
  if (!operation) continue; // registration may land on the next tick
1004
1041
  this.discoveredTaskSidecars.add(taskId);
1042
+ if (this.activeOwnerRelation(operation.owner) === "match") visibleOwner = operation.owner;
1005
1043
  if (operation.terminalRevision > 0) {
1006
1044
  this.attemptTerminalCallback(
1007
1045
  operation,
@@ -1014,6 +1052,10 @@ export class ObservedWaitHost {
1014
1052
  this.watchedRunningTasks.add(taskId);
1015
1053
  }
1016
1054
  }
1055
+ // A task launched by another Pi process became visible in this host's
1056
+ // supervisor directory. The navigator must refresh without waiting for a
1057
+ // render to rediscover it, and its cached projections are now stale.
1058
+ if (visibleOwner) this.emitDurableTaskChange(visibleOwner);
1017
1059
  }
1018
1060
 
1019
1061
  /**
@@ -1062,11 +1104,13 @@ export class ObservedWaitHost {
1062
1104
  this.discoverObservedTasks();
1063
1105
  const running = this.store.listOperations({ phase: "running" });
1064
1106
  const runningIds = new Set(running.map((operation) => operation.taskId));
1107
+ let changedOwner: OwnerIdentity | undefined;
1065
1108
  for (const taskId of [...this.watchedRunningTasks]) {
1066
1109
  if (runningIds.has(taskId)) continue;
1067
1110
  this.watchedRunningTasks.delete(taskId);
1068
1111
  const operation = this.operationForTask(taskId);
1069
1112
  if (operation && operation.terminalRevision > 0) {
1113
+ if (this.activeOwnerRelation(operation.owner) === "match") changedOwner = operation.owner;
1070
1114
  // Another host may have recorded the terminal result without a live
1071
1115
  // owner context. This host watched the operation, so recover its callback
1072
1116
  // now that the active branch/identity can authorize the handoff.
@@ -1079,6 +1123,7 @@ export class ObservedWaitHost {
1079
1123
  );
1080
1124
  }
1081
1125
  }
1126
+ if (changedOwner) this.emitDurableTaskChange(changedOwner);
1082
1127
  for (const operation of running) {
1083
1128
  this.watchedRunningTasks.add(operation.taskId);
1084
1129
  this.reconcileOperation(operation);
@@ -1141,7 +1186,7 @@ export class ObservedWaitHost {
1141
1186
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1142
1187
  });
1143
1188
  this.launches.set(taskId, launchContext);
1144
- this.emitDurableTaskChange();
1189
+ this.emitDurableTaskChange(owner);
1145
1190
  const launch: DurableLaunch = {
1146
1191
  id: taskId,
1147
1192
  operationId,
@@ -1261,10 +1306,27 @@ export class ObservedWaitHost {
1261
1306
  ): DurableTaskProjection[] {
1262
1307
  const store = this.store;
1263
1308
  if (!store || this.closed) return [];
1309
+ if (!origin.sessionId) return [];
1310
+ this.projectionMetrics.listCalls += 1;
1264
1311
  const now = this.options.now?.() ?? Date.now();
1312
+ const originKey = `${origin.cwd}\0${origin.sessionId}`;
1313
+ const cacheKey = `${originKey}\0${options.retentionMs ?? ""}\0${options.includeDismissed === true ? 1 : 0}`;
1314
+ const cached = this.durableProjectionCache;
1315
+ if (cached && cached.key === cacheKey && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
1316
+ this.projectionMetrics.cacheHits += 1;
1317
+ if (options.retentionMs === undefined) return cached.list;
1318
+ const live = cached.list.filter((projection) => !this.expiredProjection(projection, options, now));
1319
+ return live.length === cached.list.length ? cached.list : live;
1320
+ }
1265
1321
  const projections: DurableTaskProjection[] = [];
1266
- for (const operation of store.listOperations()) {
1322
+ const operations = store.listOperations({
1323
+ ownerScope: { kind: "parent-session", sessionId: origin.sessionId, workspace: origin.cwd },
1324
+ });
1325
+ this.projectionMetrics.queries += 1;
1326
+ this.projectionMetrics.rowsRead += operations.length;
1327
+ for (const operation of operations) {
1267
1328
  if (!this.belongsToParentOrigin(operation, origin)) continue;
1329
+ this.projectionMetrics.projectionsBuilt += 1;
1268
1330
  const projection = this.projectDurable(operation, now);
1269
1331
  if (!projection) continue;
1270
1332
  if (projection.dismissedAt !== undefined && options.includeDismissed !== true) continue;
@@ -1274,13 +1336,49 @@ export class ObservedWaitHost {
1274
1336
  }
1275
1337
  projections.push(projection);
1276
1338
  }
1277
- return projections.sort((a, b) => b.startedAt - a.startedAt);
1339
+ projections.sort((a, b) => b.startedAt - a.startedAt);
1340
+ this.durableProjectionCache = {
1341
+ originKey,
1342
+ key: cacheKey,
1343
+ at: now,
1344
+ list: projections,
1345
+ byTask: new Map(projections.map((projection) => [projection.id, projection])),
1346
+ };
1347
+ const live = projections.filter((projection) => !this.expiredProjection(projection, options, now));
1348
+ return live.length === projections.length ? projections : live;
1278
1349
  }
1279
1350
 
1280
1351
  readDurableTask(origin: BackgroundTaskCallbackOrigin, taskId: string): DurableTaskProjection | undefined {
1352
+ const now = this.options.now?.() ?? Date.now();
1353
+ const cached = this.durableProjectionCache;
1354
+ if (cached && cached.originKey === `${origin.cwd}\0${origin.sessionId ?? ""}`
1355
+ && now >= cached.at && now - cached.at < DURABLE_PROJECTION_CACHE_MS) {
1356
+ const projection = cached.byTask.get(taskId);
1357
+ if (projection) return projection;
1358
+ }
1281
1359
  const operation = this.operationForTask(taskId);
1282
1360
  if (!operation || !this.belongsToParentOrigin(operation, origin)) return undefined;
1283
- return this.projectDurable(operation, this.options.now?.() ?? Date.now());
1361
+ this.projectionMetrics.projectionsBuilt += 1;
1362
+ return this.projectDurable(operation, now);
1363
+ }
1364
+
1365
+ /** Accumulated projection work, for performance regression proof. */
1366
+ getDurableProjectionMetrics(): DurableProjectionMetrics {
1367
+ return { ...this.projectionMetrics };
1368
+ }
1369
+
1370
+ resetDurableProjectionMetrics(): void {
1371
+ this.projectionMetrics = { listCalls: 0, queries: 0, rowsRead: 0, projectionsBuilt: 0, cacheHits: 0 };
1372
+ }
1373
+
1374
+ private expiredProjection(
1375
+ projection: DurableTaskProjection,
1376
+ options: { retentionMs?: number },
1377
+ now: number,
1378
+ ): boolean {
1379
+ if (!projection.terminal || options.retentionMs === undefined) return false;
1380
+ const endedAt = projection.endedAt ?? now;
1381
+ return now - endedAt >= options.retentionMs;
1284
1382
  }
1285
1383
 
1286
1384
  /**
@@ -1321,6 +1419,7 @@ export class ObservedWaitHost {
1321
1419
  const operation = this.operationForTask(taskId);
1322
1420
  if (!operation || !this.belongsToParentOrigin(operation, origin)) return undefined;
1323
1421
  await this.stop(taskId, operation.owner);
1422
+ this.invalidateDurableProjection(operation.owner);
1324
1423
  return this.projectDurable(operation, this.options.now?.() ?? Date.now());
1325
1424
  }
1326
1425
 
@@ -1342,21 +1441,32 @@ export class ObservedWaitHost {
1342
1441
  context.dismissedAt = Date.now();
1343
1442
  this.launches.set(taskId, context);
1344
1443
  this.writeLaunchContext(taskId, context);
1345
- this.emitDurableTaskChange();
1444
+ this.emitDurableTaskChange(operation.owner);
1346
1445
  return true;
1347
1446
  }
1348
1447
 
1349
- onDurableTaskChange(listener: () => void): () => void {
1448
+ onDurableTaskChange(listener: (change: DurableTaskChange) => void): () => void {
1350
1449
  this.durableChangeListeners.add(listener);
1351
1450
  return () => { this.durableChangeListeners.delete(listener); };
1352
1451
  }
1353
1452
 
1354
- private emitDurableTaskChange(): void {
1453
+ private emitDurableTaskChange(owner: OwnerIdentity): void {
1454
+ // Navigators and Goal activity only show the active parent session. A
1455
+ // worker, another session, or another workspace must not evict its cache or
1456
+ // request a repaint.
1457
+ if (owner.kind !== "parent-session" || this.activeOwnerRelation(owner) !== "match") return;
1458
+ this.invalidateDurableProjection(owner);
1459
+ const change = { sessionId: owner.sessionId, workspace: owner.workspace };
1355
1460
  for (const listener of [...this.durableChangeListeners]) {
1356
- try { listener(); } catch { /* a projection listener cannot break supervision */ }
1461
+ try { listener(change); } catch { /* a projection listener cannot break supervision */ }
1357
1462
  }
1358
1463
  }
1359
1464
 
1465
+ private invalidateDurableProjection(owner?: OwnerIdentity): void {
1466
+ if (owner && (owner.kind !== "parent-session" || this.activeOwnerRelation(owner) !== "match")) return;
1467
+ this.durableProjectionCache = undefined;
1468
+ }
1469
+
1360
1470
  private belongsToParentOrigin(operation: OperationRecord, origin: BackgroundTaskCallbackOrigin): boolean {
1361
1471
  if (operation.owner.kind !== "parent-session") return false;
1362
1472
  if (operation.owner.workspace !== origin.cwd) return false;
@@ -1641,7 +1751,7 @@ export class ObservedWaitHost {
1641
1751
  token, taskId, kind: input.kind, params: input.params, prepared, operationId,
1642
1752
  });
1643
1753
  this.launches.set(taskId, launchContext);
1644
- this.emitDurableTaskChange();
1754
+ this.emitDurableTaskChange(owner);
1645
1755
  return {
1646
1756
  id: taskId,
1647
1757
  operationId,
@@ -2585,12 +2695,18 @@ export class ObservedWaitHost {
2585
2695
  if (operation.health !== "active" || operation.supervision?.hostId !== this.hostId) {
2586
2696
  // Health is observational; write it only when the supervising host or the
2587
2697
  // 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
- });
2698
+ try {
2699
+ this.store?.recordSupervision({
2700
+ operationId: operation.operationId,
2701
+ owner: operation.owner,
2702
+ supervision: this.supervision(),
2703
+ health: "active",
2704
+ });
2705
+ } catch (error) {
2706
+ // Another host can hold the write lock. Leave health unchanged and let
2707
+ // the next reconciliation tick retry this observational update.
2708
+ if (rpcCode(error) !== "store-busy") throw error;
2709
+ }
2594
2710
  }
2595
2711
  }
2596
2712
 
@@ -2652,11 +2768,15 @@ export class ObservedWaitHost {
2652
2768
  refs,
2653
2769
  { pendingWithoutContext: true },
2654
2770
  );
2771
+ // The local projection cache may still show this operation as running even
2772
+ // though another process committed its terminal revision. Invalidate and
2773
+ // notify so the navigator repaints on this reconcile pass.
2774
+ this.emitDurableTaskChange(recorded.operation.owner);
2655
2775
  return;
2656
2776
  }
2657
2777
  this.options.logger?.(`observed waits: ${operation.taskId} ${status} (revision ${recorded.operation.terminalRevision})`);
2658
2778
  this.attemptTerminalCallback(operation, status, outcome, refs, { pendingWithoutContext: true });
2659
- this.emitDurableTaskChange();
2779
+ this.emitDurableTaskChange(operation.owner);
2660
2780
  // The parent callback is independent from the worker's wait: a worker may be
2661
2781
  // parked, while the parent session still learns that the supervised task ended.
2662
2782
  void this.dispatchOutbox();
@@ -2837,7 +2957,8 @@ export class ObservedWaitHost {
2837
2957
  delete context.callbackDeferredReason;
2838
2958
  this.launches.set(taskId, context);
2839
2959
  this.writeLaunchContext(taskId, context);
2840
- this.emitDurableTaskChange();
2960
+ const operation = this.operationForTask(taskId);
2961
+ if (operation) this.emitDurableTaskChange(operation.owner);
2841
2962
  }
2842
2963
 
2843
2964
  private deferTerminalCallback(taskId: string, reason: string, retry = true, claimToken?: string): void {
@@ -342,6 +342,11 @@ export function listOperations(
342
342
  ): OperationRecord[] {
343
343
  const clauses: string[] = [];
344
344
  const params: Array<string | number> = [];
345
+ if (filter.ownerScope) {
346
+ const owner = normalizeOwner("ownerScope", filter.ownerScope);
347
+ clauses.push("owner_kind = ? AND owner_session_id = ? AND owner_workspace = ?");
348
+ params.push(owner.kind, owner.sessionId, owner.workspace);
349
+ }
345
350
  if (filter.owner) {
346
351
  const owner = normalizeOwner("owner", filter.owner);
347
352
  clauses.push(
@@ -204,6 +204,8 @@ export interface RecordTerminalOutcomeResult {
204
204
  /** Filter for `listOperations`. */
205
205
  export interface OperationFilter {
206
206
  owner?: OwnerIdentity;
207
+ /** Session/workspace scope spanning all branches and goals. */
208
+ ownerScope?: Pick<OwnerIdentity, "kind" | "sessionId" | "workspace">;
207
209
  phase?: OperationPhase;
208
210
  taskId?: string;
209
211
  }