pi-better-background-tasks 0.14.2 → 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.2",
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",
package/src/batch.ts CHANGED
@@ -3,7 +3,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  import { readTaskIntent } from "./failures.js";
4
4
  import { validateCommandSpec } from "./process.js";
5
5
  import { resolveSshCommand } from "./shared-ssh-core/index.js";
6
- import { spawnTask, type ActiveSessionProvider, type SpawnTaskParams, type TaskRuntimeDependencies } from "./runtime.js";
6
+ import { spawnTask, type ActiveSessionProvider, type BackgroundTaskRuntime, type SpawnTaskParams, type TaskRuntimeDependencies } from "./runtime.js";
7
7
  import type { BackgroundTaskCallbackOrigin } from "./types.js";
8
8
 
9
9
  export interface SpawnBatchParams {
@@ -31,7 +31,10 @@ export function spawnTaskBatch(
31
31
  callbackOrigin?: BackgroundTaskCallbackOrigin,
32
32
  getActiveSession?: ActiveSessionProvider,
33
33
  dependencies: TaskRuntimeDependencies = {},
34
+ runtime: Pick<BackgroundTaskRuntime, "spawnTask"> = { spawnTask },
34
35
  ): SpawnBatchResult {
36
+ // Jobs launch through the owning factory's runtime, never the default singleton.
37
+ const spawnOne = runtime.spawnTask;
35
38
  if (!Array.isArray(params.jobs) || params.jobs.length < 1 || params.jobs.length > 100) {
36
39
  throw new Error("jobs must contain between 1 and 100 background tasks.");
37
40
  }
@@ -72,7 +75,7 @@ export function spawnTaskBatch(
72
75
  };
73
76
  for (const [index, job] of jobs.entries()) {
74
77
  try {
75
- const meta = spawnTask(pi, { ...job, batchId: result.batchId, batchName: result.batchName }, defaultCwd, callbackOrigin, getActiveSession, dependencies);
78
+ const meta = spawnOne(pi, { ...job, batchId: result.batchId, batchName: result.batchName }, defaultCwd, callbackOrigin, getActiveSession, dependencies);
76
79
  result.launched.push({ job: index + 1, id: meta.id, ...(meta.name !== undefined ? { name: meta.name } : {}) });
77
80
  } catch (error) {
78
81
  result.failed.push({ job: index + 1, ...(job.name !== undefined ? { name: job.name } : {}), error: errorMessage(error) });
package/src/failures.ts CHANGED
@@ -103,18 +103,19 @@ export function recoverDeclaredOperation(meta: BackgroundTaskMeta, at = Date.now
103
103
  }
104
104
  }
105
105
 
106
+ export function createFailureAttention() {
106
107
  const attentionTimers = new Map<string, ReturnType<typeof setTimeout>>();
107
108
  let attentionSuspended = false;
108
109
  /** Session shutdown: stop this instance's attention timers; the next session_start reschedules (#324). */
109
- export function suspendFailureAttention(): void {
110
+ function suspendFailureAttention(): void {
110
111
  attentionSuspended = true;
111
112
  for (const timer of attentionTimers.values()) clearTimeout(timer);
112
113
  attentionTimers.clear();
113
114
  }
114
- export function resumeFailureAttention(): void {
115
+ function resumeFailureAttention(): void {
115
116
  attentionSuspended = false;
116
117
  }
117
- export function stopFailureAttention(id: string): void {
118
+ function stopFailureAttention(id: string): void {
118
119
  const timer = attentionTimers.get(id);
119
120
  if (timer) clearTimeout(timer);
120
121
  attentionTimers.delete(id);
@@ -125,7 +126,7 @@ export function stopFailureAttention(id: string): void {
125
126
  * identity is per incident set; the inspect target is the real task id.
126
127
  * Only the pending incidents are rows; earlier deliveries are counted, never repeated (#315).
127
128
  */
128
- export function failureAttentionFields(meta: BackgroundTaskMeta, state: FailureState, pending: { key: string; incidents: string[] }) {
129
+ function failureAttentionFields(meta: BackgroundTaskMeta, state: FailureState, pending: { key: string; incidents: string[] }) {
129
130
  const rows = pendingAttentionRows(state, pending.incidents);
130
131
  const note = pendingAttentionNote(state, pending.incidents);
131
132
  const due = pending.incidents.length;
@@ -144,7 +145,7 @@ export function failureAttentionFields(meta: BackgroundTaskMeta, state: FailureS
144
145
  }
145
146
 
146
147
  /** Running incidents get one grace wake. Terminal incidents ride the completion callback. */
147
- export function scheduleFailureAttention(pi: ExtensionAPI, id: string, getActiveSession?: ActiveSessionProvider): void {
148
+ function scheduleFailureAttention(pi: ExtensionAPI, id: string, getActiveSession?: ActiveSessionProvider): void {
148
149
  stopFailureAttention(id);
149
150
  if (attentionSuspended) return;
150
151
  const meta = readMeta(id);
@@ -167,6 +168,7 @@ export function scheduleFailureAttention(pi: ExtensionAPI, id: string, getActive
167
168
  return current.status !== "running" || failureAttentionHandled(now, pending.incidents);
168
169
  },
169
170
  getSuppressionReason: () => {
171
+ if (attentionSuspended) throw new Error("Failure attention instance is suspended; defer notification");
170
172
  const current = readMeta(id);
171
173
  if (!current) throw new Error("Task metadata is unavailable; defer failure notification");
172
174
  if (current.status !== "running" || current.callback === false || current.stopRequestedAt) return "task is no longer running";
@@ -179,7 +181,7 @@ export function scheduleFailureAttention(pi: ExtensionAPI, id: string, getActive
179
181
  onDelivered: (at) => { markFailureAttentionDelivered(failurePath(id), pending, at); },
180
182
  });
181
183
  void Promise.resolve(delivery).then((sent) => {
182
- if (!sent && (!readMeta(id) || readMeta(id)?.status === "running")) {
184
+ if (!sent && !attentionSuspended && (!readMeta(id) || readMeta(id)?.status === "running")) {
183
185
  const timer = setTimeout(() => scheduleFailureAttention(pi, id, getActiveSession), 1_000);
184
186
  timer.unref();
185
187
  attentionTimers.set(id, timer);
@@ -197,6 +199,12 @@ export function scheduleFailureAttention(pi: ExtensionAPI, id: string, getActive
197
199
  }
198
200
  }
199
201
 
202
+ return { suspendFailureAttention, resumeFailureAttention, stopFailureAttention, scheduleFailureAttention, failureAttentionFields };
203
+ }
204
+ /** Shared by the compatibility exports here and the legacy background runtime. */
205
+ export const defaultAttention = createFailureAttention();
206
+ export const { suspendFailureAttention, resumeFailureAttention, stopFailureAttention, scheduleFailureAttention, failureAttentionFields } = defaultAttention;
207
+
200
208
  export function terminalFailureAttention(id: string) {
201
209
  return pendingFailureAttention(readFailureState(failurePath(id)), Date.now(), { terminal: true });
202
210
  }
package/src/index.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { disposeBackgroundWorkNavigator } from "./shared-navigator.ts";
3
2
  import { initializeNavigatorPanels } from "./shared-navigator-panels.ts";
4
3
  import { registerBackgroundTasksGoalProvider } from "./goal-provider.js";
5
- import { clearBackgroundTasksNavigatorSession, ensureBackgroundTasksNavigator, ensureBackgroundTasksNavigatorProvider } from "./navigator-provider.js";
6
- import { resumeScheduledWork, suspendScheduledWork } from "./runtime.js";
4
+ import { createBackgroundTasksNavigator } from "./navigator-provider.js";
5
+ import { createBackgroundTaskRuntime } from "./runtime.js";
7
6
  import { createObservedWaitHost } from "./observed-waits.js";
8
7
  import { getCallbackBatcher } from "./shared-callback-batcher.js";
9
8
  import { observeForegroundSandboxPolicy } from "./sandbox.js";
@@ -11,6 +10,10 @@ import { registerTools } from "./tools.js";
11
10
  import { deliverBackgroundTasksPrompt } from "./prompt.js";
12
11
 
13
12
  export default function backgroundTasksExtension(pi: ExtensionAPI): void {
13
+ // Each cached factory invocation owns its runtime, failure timers, navigator
14
+ // projection, and durable host. Nothing here is shared module state (#460).
15
+ const runtime = createBackgroundTaskRuntime();
16
+ const navigator = createBackgroundTasksNavigator(runtime);
14
17
  // Created before registerTools so the tools can resolve it lazily; the durable
15
18
  // store opens on session activation and closes on switch/unload.
16
19
  const observedWaits = createObservedWaitHost(pi, {
@@ -41,29 +44,27 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
41
44
  // would then carry a snapshot, so sections published after it never arrive.
42
45
  pi.on("before_agent_start", (event) => deliverBackgroundTasksPrompt(event));
43
46
  registerBackgroundTasksGoalProvider(pi);
44
- ensureBackgroundTasksNavigatorProvider(pi);
47
+ navigator.ensureBackgroundTasksNavigatorProvider(pi);
45
48
  // Subscribed at load so a sandbox extension that publishes later is heard, and
46
49
  // asked for a snapshot in case one published before this extension existed.
47
50
  observeForegroundSandboxPolicy(pi);
48
51
  // Registered before registerTools(pi), so this runs before running tasks are resumed.
49
52
  pi.on("session_start", async (_event, ctx) => {
50
- resumeScheduledWork();
53
+ runtime.resumeScheduledWork();
51
54
  registerBackgroundTasksGoalProvider(pi);
52
- ensureBackgroundTasksNavigator(ctx);
55
+ navigator.ensureBackgroundTasksNavigator(ctx);
53
56
  });
54
57
  pi.on("session_before_switch", async () => {
55
58
  observedWaits.close();
56
- clearBackgroundTasksNavigatorSession();
57
- disposeBackgroundWorkNavigator();
59
+ navigator.clearBackgroundTasksNavigatorSession();
58
60
  });
59
61
  pi.on("session_shutdown", async (_event, ctx) => {
60
62
  // /reload, session replacement, and quit load a fresh instance; stop this one's timers (#324).
61
63
  observedWaits.close();
62
- suspendScheduledWork();
63
- clearBackgroundTasksNavigatorSession();
64
- disposeBackgroundWorkNavigator(ctx);
64
+ runtime.suspendScheduledWork();
65
+ navigator.clearBackgroundTasksNavigatorSession();
65
66
  });
66
- registerTools(pi);
67
+ registerTools(pi, runtime, navigator.refreshBackgroundTasksNavigator);
67
68
  // Registered after registerTools so the callback batcher has its session
68
69
  // context before a reconciled delivery can enqueue a parent notification.
69
70
  pi.on("session_start", async (_event, ctx) => {
@@ -75,4 +76,4 @@ export default function backgroundTasksExtension(pi: ExtensionAPI): void {
75
76
  pi.on("session_tree", async (_event, ctx) => {
76
77
  observedWaits.noteParentContext(ctx);
77
78
  });
78
- }
79
+ }
@@ -1,6 +1,8 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import {
3
3
  DEFAULT_LOG_TAIL_ROWS as NAVIGATOR_DETAIL_ROWS,
4
+ disposeBackgroundWorkNavigator,
5
+ isNavigatorUiAvailable,
4
6
  ensureBackgroundWorkNavigator,
5
7
  refreshBackgroundWorkNavigator,
6
8
  registerBackgroundWorkProvider,
@@ -15,16 +17,31 @@ import { failurePath, failureView } from "./failures.js";
15
17
  import { readLog } from "./logs.js";
16
18
  import { listMetasForOrigin, onMetaChanged, readMeta, writeMeta } from "./registry.js";
17
19
  import { getObservedWaitHost, type DurableTaskProjection } from "./observed-waits.js";
18
- import { stopTask } from "./runtime.js";
20
+ import { stopTask, type BackgroundTaskRuntime } from "./runtime.js";
19
21
  import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.js";
20
22
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta, BackgroundTaskStatus } from "./types.js";
21
23
 
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;
31
+
32
+ export function createBackgroundTasksNavigator(runtime: Pick<BackgroundTaskRuntime, "stopTask"> = { stopTask }) {
33
+ const owner = Symbol("background-tasks navigator factory");
22
34
  let unregister: (() => void) | undefined;
35
+ let navigatorContext: ExtensionContext | undefined;
23
36
  let piRef: ExtensionAPI | undefined;
24
37
  let activeNavigatorOrigin: BackgroundTaskCallbackOrigin | undefined;
25
- const TERMINAL_NAVIGATOR_RETENTION_MS = 30_000;
26
-
27
- export function ensureBackgroundTasksNavigatorProvider(pi: ExtensionAPI): void {
38
+ function ensureBackgroundTasksNavigatorProvider(pi: ExtensionAPI): void {
39
+ // Provider registration is deferred until an actual TUI session owns it, so a
40
+ // headless child sharing the cached module cannot replace the parent's provider.
41
+ if (!navigatorContext) {
42
+ piRef = pi;
43
+ return;
44
+ }
28
45
  // A reloaded or replaced extension instance gets a fresh host. Re-register so
29
46
  // the provider's durable-change subscription targets that host, not the one
30
47
  // captured by the previous instance.
@@ -37,22 +54,33 @@ export function ensureBackgroundTasksNavigatorProvider(pi: ExtensionAPI): void {
37
54
  unregister = registerBackgroundWorkProvider(provider);
38
55
  }
39
56
 
40
- export function ensureBackgroundTasksNavigator(ctx: ExtensionContext): void {
57
+ function ensureBackgroundTasksNavigator(ctx: ExtensionContext): void {
58
+ if (!isNavigatorUiAvailable(ctx)) return;
59
+ navigatorContext = ctx;
60
+ if (piRef) ensureBackgroundTasksNavigatorProvider(piRef);
41
61
  activeNavigatorOrigin = getNavigatorOrigin(ctx);
42
62
  ensureBackgroundWorkNavigator(ctx, {
43
63
  createDefaultEditor: (tui, theme, keybindings) => new CustomEditor(tui as never, theme as never, keybindings as never),
44
64
  isOpenTrigger: (data) => matchesKey(data, Key.left),
45
65
  matchKey: (data, keyId) => matchesKey(data, keyId as Parameters<typeof matchesKey>[1]),
46
66
  truncate: truncateToWidth,
47
- });
67
+ }, owner);
48
68
  }
49
69
 
50
- export function clearBackgroundTasksNavigatorSession(): void {
70
+ function clearBackgroundTasksNavigatorSession(): void {
51
71
  activeNavigatorOrigin = undefined;
72
+ unregister?.();
73
+ unregister = undefined;
74
+ if (navigatorContext) disposeBackgroundWorkNavigator(navigatorContext, owner);
75
+ navigatorContext = undefined;
52
76
  }
53
77
 
54
- export function refreshBackgroundTasksNavigator(ctx?: ExtensionContext): void {
55
- refreshBackgroundWorkNavigator(ctx);
78
+ function refreshBackgroundTasksNavigator(ctx?: ExtensionContext): void {
79
+ // This factory owns no navigator until a TUI session installs it; a refresh from
80
+ // a non-TUI tool context then repaints the stored owner context (main #332).
81
+ const ownerCtx = navigatorContext;
82
+ if (!ownerCtx) return;
83
+ refreshBackgroundWorkNavigator(ctx && isNavigatorUiAvailable(ctx) ? ctx : ownerCtx);
56
84
  }
57
85
 
58
86
  const provider: BackgroundWorkProvider = {
@@ -66,7 +94,7 @@ const provider: BackgroundWorkProvider = {
66
94
  },
67
95
  listRows: (now) => [
68
96
  ...visibleMetas(now).map((meta) => rowFromMeta(meta, now)),
69
- ...visibleDurableTasks(now).map((task) => rowFromDurable(task, now)),
97
+ ...durableRows(visibleDurableTasks(now), now),
70
98
  ],
71
99
  detail: (id, now, options) => {
72
100
  const durable = durableTask(id);
@@ -92,7 +120,7 @@ const provider: BackgroundWorkProvider = {
92
120
  const meta = readMeta(id);
93
121
  if (!meta) return { action: "missing", providerId: "background-tasks", id };
94
122
  if (meta.status === "running") {
95
- void stopTask(piRef as ExtensionAPI, id);
123
+ void runtime.stopTask(piRef as ExtensionAPI, id);
96
124
  return { action: "stopped", providerId: "background-tasks", id, status: "stopping" };
97
125
  }
98
126
  meta.dismissedAt = Date.now();
@@ -101,12 +129,12 @@ const provider: BackgroundWorkProvider = {
101
129
  },
102
130
  onVisibleChanged: (notify) => {
103
131
  const offMeta = onMetaChanged(notify);
104
- const offDurable = getObservedWaitHost(piRef)?.onDurableTaskChange(() => {
105
- invalidateDurableProjection();
132
+ const offDurable = getObservedWaitHost(piRef)?.onDurableTaskChange((change) => {
133
+ const active = activeNavigatorOrigin;
134
+ if (!active || change.workspace !== active.cwd || change.sessionId !== active.sessionId) return;
106
135
  notify();
107
136
  });
108
137
  return () => {
109
- invalidateDurableProjection();
110
138
  offMeta();
111
139
  offDurable?.();
112
140
  };
@@ -117,30 +145,24 @@ function navigatorHost() {
117
145
  return piRef ? getObservedWaitHost(piRef) : undefined;
118
146
  }
119
147
 
120
- /**
121
- * One refresh asks for {@link provider.visibleCount} and then {@link provider.listRows},
122
- * and a detail view asks again. Rebuilding the projection re-reads every durable
123
- * record, so a single paint would pay for the same list up to three times. Hold
124
- * one result per paint window; a durable-change notification clears it.
125
- */
126
- const PROJECTION_MEMO_MS = 250;
127
- let projectionMemo: { at: number; tasks: DurableTaskProjection[] } | undefined;
128
-
129
- function invalidateDurableProjection(): void {
130
- projectionMemo = undefined;
131
- }
132
-
133
148
  function visibleDurableTasks(now = Date.now()): DurableTaskProjection[] {
134
149
  const active = activeNavigatorOrigin;
135
150
  const host = navigatorHost();
136
151
  if (!active || !host) return [];
137
- if (projectionMemo && now - projectionMemo.at < PROJECTION_MEMO_MS) {
138
- return projectionMemo.tasks.filter((task) => !isExpiredDurableRow(task, now));
139
- }
152
+ // ObservedWaitHost caches unchanged projections and invalidates them on every
153
+ // durable notification, so a host redraw no longer re-queries per panel.
140
154
  const listed = host.listDurableTasks(active, { retentionMs: TERMINAL_NAVIGATOR_RETENTION_MS });
141
- const tasks = listed.filter((task) => task.dismissedAt === undefined);
142
- projectionMemo = { at: now, tasks };
143
- 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;
144
166
  }
145
167
 
146
168
  function durableTask(id: string): DurableTaskProjection | undefined {
@@ -150,11 +172,6 @@ function durableTask(id: string): DurableTaskProjection | undefined {
150
172
  return host.readDurableTask(active, id);
151
173
  }
152
174
 
153
- function isExpiredDurableRow(task: DurableTaskProjection, now: number): boolean {
154
- if (!task.terminal || task.endedAt === undefined) return false;
155
- return now - task.endedAt >= TERMINAL_NAVIGATOR_RETENTION_MS;
156
- }
157
-
158
175
  function rowFromDurable(task: DurableTaskProjection, now: number): BackgroundWorkRow {
159
176
  const command = durableCommandLabel(task);
160
177
  const elapsed = formatDuration((task.endedAt ?? now) - task.startedAt);
@@ -288,6 +305,11 @@ function belongsToActiveNavigatorSession(meta: BackgroundTaskMeta): boolean {
288
305
  return meta.cwd === active.cwd;
289
306
  }
290
307
 
308
+ return { ensureBackgroundTasksNavigatorProvider, ensureBackgroundTasksNavigator, clearBackgroundTasksNavigatorSession, refreshBackgroundTasksNavigator };
309
+ }
310
+ const defaultNavigator = createBackgroundTasksNavigator();
311
+ export const { ensureBackgroundTasksNavigatorProvider, ensureBackgroundTasksNavigator, clearBackgroundTasksNavigatorSession, refreshBackgroundTasksNavigator } = defaultNavigator;
312
+
291
313
  function isExpiredTerminalNavigatorRow(meta: BackgroundTaskMeta, now: number): boolean {
292
314
  if (meta.status === "running") return false;
293
315
  const endedAt = meta.endedAt;
@@ -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 {