pi-better-background-tasks 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +4 -3
  2. package/package.json +4 -2
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -1
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -1
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -1
  11. package/runtime-client/src/runtime/client.mjs +30 -3
  12. package/runtime-client/src/runtime/work-client.mjs +150 -7
  13. package/src/adapter-contract.ts +1 -1
  14. package/src/failures.ts +4 -2
  15. package/src/goal-provider.ts +31 -16
  16. package/src/index.ts +9 -37
  17. package/src/managed-authority.ts +30 -0
  18. package/src/managed-client.ts +73 -0
  19. package/src/managed-frontend.ts +176 -0
  20. package/src/navigator-provider.ts +28 -10
  21. package/src/observed-wait-client.ts +10 -0
  22. package/src/observed-waits.ts +268 -62
  23. package/src/output.ts +12 -0
  24. package/src/process-identity.ts +18 -2
  25. package/src/process.ts +3 -3
  26. package/src/registry.ts +71 -6
  27. package/src/runtime.ts +26 -10
  28. package/src/sandbox.ts +21 -11
  29. package/src/shared-callback-batcher.ts +15 -3
  30. package/src/shared-failure-observations.ts +3 -0
  31. package/src/shared-navigator-panels.ts +26 -4
  32. package/src/shared-navigator.ts +220 -19
  33. package/src/shared-operation-coordinator/assignment-observation.mjs +71 -33
  34. package/src/shared-operation-coordinator/index.ts +2 -0
  35. package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  36. package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  37. package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  38. package/src/shared-operation-coordinator/src/background-requests.ts +90 -0
  39. package/src/shared-operation-coordinator/src/discovery.ts +5 -3
  40. package/src/shared-operation-coordinator/src/operations.ts +50 -2
  41. package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
  42. package/src/shared-operation-coordinator/src/rows.ts +2 -0
  43. package/src/shared-operation-coordinator/src/schema.ts +71 -24
  44. package/src/shared-operation-coordinator/src/store.ts +50 -6
  45. package/src/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  46. package/src/shared-operation-coordinator/src/types.ts +5 -1
  47. package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
  48. package/src/shared-sandbox-core.ts +1 -1
  49. package/src/shared-work-client.mjs +150 -7
  50. package/src/supervisor/generated/process-identity.mjs +20 -2
  51. package/src/supervisor/generated/process.mjs +3 -3
  52. package/src/task-diagnostics.ts +1 -1
  53. package/src/tools.ts +60 -41
  54. package/src/types.ts +3 -1
  55. package/src/work-observation.ts +46 -19
package/src/output.ts CHANGED
@@ -621,6 +621,18 @@ function redactedVerbose(meta: BackgroundTaskMeta, options: OutputOptions): unkn
621
621
  * whole document fits it is returned as plain JSON; otherwise it is paged
622
622
  * with a caller cursor like any other retained evidence.
623
623
  */
624
+ /** Bounded raw metadata for canonical supervisor tasks. These records contain no
625
+ * environment values and do not invent legacy process ownership fields. */
626
+ export function formatDurableStatusMetadata(meta: { id: string; [key: string]: unknown }, options: OutputOptions): string {
627
+ const json = JSON.stringify(meta, null, 2);
628
+ if (!options.cursor && utf8ByteLength(json) <= backgroundBudget("rawPage", options.maxBytes)) return json;
629
+ return assembleBackgroundContent({
630
+ surface: "rawPage", maxBytes: options.maxBytes,
631
+ sections: { identity: `Background task ${meta.id} metadata (environment values omitted).` },
632
+ verbatim: budget => pageVerbatimText(json, { cursor: options.cursor, maxBytes: budget, resource: `verbose:${scopeKey(options)}:${meta.id}` }),
633
+ });
634
+ }
635
+
624
636
  function formatVerbose(meta: BackgroundTaskMeta, options: OutputOptions): string {
625
637
  const json = JSON.stringify(redactedVerbose(meta, options), null, 2);
626
638
  const resource = `verbose:${scopeKey(options)}:${meta.id}`;
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import { execFileSync } from "node:child_process";
2
3
 
3
4
  /**
@@ -29,10 +30,11 @@ interface TokenMemoEntry {
29
30
 
30
31
  const tokenMemo = new Map<number, TokenMemoEntry>();
31
32
 
32
- function readTokenUncached(pid: number): string | undefined {
33
+ function readTokenUncached(pid: number, admission = false): string | undefined {
33
34
  if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32") return undefined;
34
35
  try {
35
- const output = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
36
+ const output = execFileSync(admission ? "/bin/ps" : "ps", ["-o", "lstart=", "-p", String(pid)], {
37
+ env: admission ? { LC_ALL: "C", TZ: "UTC0", PATH: "/usr/bin:/bin" } : process.env,
36
38
  encoding: "utf8",
37
39
  stdio: ["ignore", "pipe", "ignore"],
38
40
  timeout: 2_000,
@@ -43,6 +45,20 @@ function readTokenUncached(pid: number): string | undefined {
43
45
  }
44
46
  }
45
47
 
48
+ // Admission crosses process environments; stored task tokens retain their original format.
49
+ export function readAdmissionStartToken(pid: number): string | undefined {
50
+ if (process.platform !== "linux") return readTokenUncached(pid, true);
51
+ if (!Number.isInteger(pid) || pid <= 0) return undefined;
52
+ try {
53
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
54
+ // Fields after the parenthesized command start at field 3. Start time is field 22.
55
+ const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
56
+ return start && /^\d+$/.test(start) ? start : undefined;
57
+ } catch {
58
+ return undefined;
59
+ }
60
+ }
61
+
46
62
  function remember(pid: number, token: string | undefined, now: number): void {
47
63
  if (tokenMemo.size >= TOKEN_MEMO_MAX_ENTRIES) {
48
64
  // Drop expired entries first; only evict live ones if that was not enough.
package/src/process.ts CHANGED
@@ -66,8 +66,8 @@ export function validateCommandSpec(spec: CommandSpec): void {
66
66
  /** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
67
67
  export function toMsysPath(path: string): string {
68
68
  const forward = path.replace(/\\/g, "/");
69
- const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
70
- return drive ? `/${drive[1].toLowerCase()}${drive[2]}` : forward;
69
+ const [, drive, rest] = /^([A-Za-z]):(\/.+)$/.exec(forward) ?? [];
70
+ return drive && rest ? `/${drive.toLowerCase()}${rest}` : forward;
71
71
  }
72
72
 
73
73
  /** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
@@ -155,7 +155,7 @@ export function parseStepGateFailure(logText: string, id: string): StepGateFailu
155
155
  const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
156
156
  if (!line.startsWith(marker) || !line.endsWith(" ---")) continue;
157
157
  const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
158
- if (!match) continue;
158
+ if (!match || match[3] === undefined) continue;
159
159
  const stepExitCode = Number(match[1]);
160
160
  const shellExitCode = Number(match[2]);
161
161
  if (!Number.isInteger(stepExitCode) || stepExitCode === 0) continue;
package/src/registry.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta } from "./types.js";
@@ -11,13 +11,14 @@ const metaCache = new Map<string, BackgroundTaskMeta>();
11
11
  // cross-process index changes before any cached IDs are reused.
12
12
  const indexIdsCache = new Map<string, { ids: Set<string>; signature: string }>();
13
13
  const initializedIndexes = new Set<string>();
14
- const metaChangedListeners = new Set<() => void>();
15
- const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, indexRevisionChecks: 0 };
14
+ const metaChangedListeners = new Set<(meta?: BackgroundTaskMeta) => void>();
15
+ const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, terminalMetadataFileReads: 0, indexRevisionChecks: 0 };
16
16
 
17
17
  export interface RegistryIoMetrics {
18
18
  fullDirectoryReads: number;
19
19
  indexDirectoryReads: number;
20
20
  metadataFileReads: number;
21
+ terminalMetadataFileReads: number;
21
22
  indexRevisionChecks: number;
22
23
  }
23
24
 
@@ -29,6 +30,7 @@ export function resetRegistryIoMetrics(): void {
29
30
  registryIo.fullDirectoryReads = 0;
30
31
  registryIo.indexDirectoryReads = 0;
31
32
  registryIo.metadataFileReads = 0;
33
+ registryIo.terminalMetadataFileReads = 0;
32
34
  registryIo.indexRevisionChecks = 0;
33
35
  }
34
36
 
@@ -82,11 +84,11 @@ export function writeMeta(meta: BackgroundTaskMeta): void {
82
84
  metaCache.set(meta.id, meta);
83
85
  indexMeta(meta);
84
86
  for (const listener of metaChangedListeners) {
85
- try { listener(); } catch { /* best effort */ }
87
+ try { listener(meta); } catch { /* best effort */ }
86
88
  }
87
89
  }
88
90
 
89
- export function onMetaChanged(listener: () => void): () => void {
91
+ export function onMetaChanged(listener: (meta?: BackgroundTaskMeta) => void): () => void {
90
92
  metaChangedListeners.add(listener);
91
93
  return () => metaChangedListeners.delete(listener);
92
94
  }
@@ -129,6 +131,7 @@ export function inspectMeta(id: string): MetaInspection {
129
131
  const raw = readFileSync(path, "utf8");
130
132
  try {
131
133
  const meta = JSON.parse(raw) as BackgroundTaskMeta;
134
+ if(isTerminalStatus(meta.status))registryIo.terminalMetadataFileReads++;
132
135
  const invalid = metaShapeProblem(meta, id);
133
136
  if (invalid) {
134
137
  metaCache.delete(id);
@@ -187,8 +190,9 @@ export function removeMeta(meta: BackgroundTaskMeta): boolean {
187
190
  metaCache.delete(meta.id);
188
191
  removeIndexEntry(originIndexDir(originOf(meta)), meta.id);
189
192
  removeIndexEntry(originActiveIndexDir(originOf(meta)), meta.id);
193
+ removeIndexEntry(recentPath(originOf(meta)), meta.id);
190
194
  for (const listener of metaChangedListeners) {
191
- try { listener(); } catch { /* best effort */ }
195
+ try { listener(meta); } catch { /* best effort */ }
192
196
  }
193
197
  return true;
194
198
  } catch {
@@ -223,6 +227,18 @@ export function listMetasForOrigin(origin: BackgroundTaskCallbackOrigin): Backgr
223
227
  .sort((a, b) => b.startedAt - a.startedAt);
224
228
  }
225
229
 
230
+ /** Durable pending callbacks are independent of the Navigator's terminal retention. */
231
+ export function listPendingCallbackMetasForOrigin(origin: BackgroundTaskCallbackOrigin): BackgroundTaskMeta[] {
232
+ const directory=join(baseDir(),'by-origin-callback',originKey(origin));
233
+ if(!initializedIndexes.has(directory)){
234
+ try {readFileSync(join(directory,'.initialized'));}
235
+ catch {for(const meta of listMetasForOrigin(origin))if(pendingCallback(meta))writeIndexEntry(directory,meta.id);mkdirSync(directory,{recursive:true});writeFileSync(join(directory,'.initialized'),'1');}
236
+ initializedIndexes.add(directory);
237
+ }
238
+ return readIndexIds(directory).map(readOwnedMeta).filter((meta):meta is BackgroundTaskMeta=>!!meta&&belongsToOrigin(meta,origin)&&pendingCallback(meta));
239
+ }
240
+ function pendingCallback(meta:BackgroundTaskMeta):boolean {return isTerminalStatus(meta.status)&&meta.status!=='cancelled'&&meta.callback!==false&&!meta.callbackSentAt&&!meta.callbackSuppressedAt;}
241
+
226
242
  export function listActiveMetasForOrigin(origin: BackgroundTaskCallbackOrigin): BackgroundTaskMeta[] {
227
243
  const directory = originActiveIndexDir(origin);
228
244
  ensureOriginActiveIndex(origin, directory);
@@ -236,6 +252,7 @@ export function listActiveMetasForOrigin(origin: BackgroundTaskCallbackOrigin):
236
252
  export function observeMetasForOrigin(origin: BackgroundTaskCallbackOrigin, activeOnly = true): BackgroundTaskMeta[] {
237
253
  const directory = activeOnly ? originActiveIndexDir(origin) : originIndexDir(origin);
238
254
  let ids: string[];
255
+ registryIo.indexDirectoryReads++;
239
256
  try { ids = readdirSync(directory).filter(id => id !== ".initialized"); }
240
257
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
241
258
  return ids.map(id => {
@@ -246,6 +263,42 @@ export function observeMetasForOrigin(origin: BackgroundTaskCallbackOrigin, acti
246
263
  && (!activeOnly || meta.status === "running")).sort((a, b) => b.startedAt - a.startedAt);
247
264
  }
248
265
 
266
+ const RECENT_LIMIT = 256;
267
+ const RECENT_MS = 30000;
268
+ function recentPath(origin: BackgroundTaskCallbackOrigin): string {
269
+ return join(baseDir(), "by-origin-recent", originKey(origin));
270
+ }
271
+ function recentEntries(origin: BackgroundTaskCallbackOrigin): Array<{ id: string; observedAt: number }> {
272
+ const directory = recentPath(origin);
273
+ try {
274
+ registryIo.indexDirectoryReads++;
275
+ const entries = readdirSync(directory).filter(id => !id.startsWith(".")).flatMap(id => {
276
+ try { registryIo.indexRevisionChecks++; return [{ id, observedAt: statSync(join(directory, id)).mtimeMs }]; }
277
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
278
+ }).sort((a, b) => b.observedAt - a.observedAt || b.id.localeCompare(a.id));
279
+ return entries.filter(entry => Date.now() - entry.observedAt < RECENT_MS).slice(0, RECENT_LIMIT);
280
+ } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
281
+ }
282
+
283
+ export function recentMetaDeadline(origin: BackgroundTaskCallbackOrigin): number[] {
284
+ return recentEntries(origin).map(entry => entry.observedAt + RECENT_MS);
285
+ }
286
+
287
+ /** Exact cooperative source identity; no metadata or historical enumeration. */
288
+ export function observationRevisionForOrigin(origin: BackgroundTaskCallbackOrigin): string {
289
+ return [originActiveIndexDir(origin), recentPath(origin)].map(indexDirectorySignature).join(";");
290
+ }
291
+
292
+ /** Bounded cooperative writes, including results written before the first reader. */
293
+ export function observeRecentMetasForOrigin(origin: BackgroundTaskCallbackOrigin): BackgroundTaskMeta[] {
294
+ return recentEntries(origin).map(entry => {
295
+ const record = inspectMeta(entry.id);
296
+ if (record.found && !record.meta) throw new Error(`Unverified background task ${entry.id}: ${record.error}`);
297
+ return record.meta;
298
+ }).filter((meta): meta is BackgroundTaskMeta =>
299
+ !!meta && belongsToOrigin(meta, origin) && meta.dismissedAt === undefined);
300
+ }
301
+
249
302
  function readMetaForSweep(id: string): BackgroundTaskMeta | undefined {
250
303
  const cached = metaCache.get(id);
251
304
  if (cached && isTerminalStatus(cached.status)) return cached;
@@ -288,9 +341,21 @@ function indexMeta(meta: BackgroundTaskMeta): void {
288
341
  try {
289
342
  const directory = originIndexDir(originOf(meta));
290
343
  writeIndexEntry(directory, meta.id);
344
+ const callbackDirectory=join(baseDir(),'by-origin-callback',originKey(originOf(meta)));
345
+ if(pendingCallback(meta))writeIndexEntry(callbackDirectory,meta.id);else removeIndexEntry(callbackDirectory,meta.id);
291
346
  const activeDirectory = originActiveIndexDir(originOf(meta));
292
347
  if (meta.status === "running") writeIndexEntry(activeDirectory, meta.id);
293
348
  else removeIndexEntry(activeDirectory, meta.id);
349
+ const origin = originOf(meta), recentDirectory = recentPath(origin);
350
+ mkdirSync(recentDirectory, { recursive: true });
351
+ // Independent pointers preserve concurrent writers; prune only this bounded
352
+ // recent-write accelerator, never the authoritative metadata or history.
353
+ const candidates = readdirSync(recentDirectory).filter(id => !id.startsWith("."));
354
+ const retained = new Set(recentEntries(origin).filter(entry => entry.id !== meta.id).slice(0, RECENT_LIMIT - 1).map(entry => entry.id));
355
+ for (const id of candidates) if (id !== meta.id && !retained.has(id)) removeIndexEntry(recentDirectory, id);
356
+ const temporary = join(recentDirectory, `.${meta.id}.${process.pid}.next`);
357
+ writeFileSync(temporary, "");
358
+ renameSync(temporary, join(recentDirectory, meta.id));
294
359
  } catch {
295
360
  // Indexes are accelerators; meta.json remains authoritative.
296
361
  }
package/src/runtime.ts CHANGED
@@ -27,7 +27,7 @@ import type {
27
27
  TerminalResult,
28
28
  } from "./types.js";
29
29
  import { observeTaskStallAttention } from "./stall-attention.js";
30
- import { isTerminalStatus } from "./types.js";
30
+ import { FIRST_WATCH_CHECK_WAIT_MS, isTerminalStatus } from "./types.js";
31
31
 
32
32
  export type ActiveSessionProvider = () => BackgroundTaskCallbackOrigin | undefined;
33
33
 
@@ -98,7 +98,7 @@ export const DEFAULT_WATCH_TIMEOUT_SECONDS = 15 * 60;
98
98
  /** Consecutive blind checks (exit 0, stderr, no condition matched) before a watch is flagged (#359). */
99
99
  export const DEFAULT_BLIND_CHECKS = 3;
100
100
  /** How long bg_task_watch waits for the first check before returning (#359). */
101
- export const FIRST_WATCH_CHECK_WAIT_MS = 15_000;
101
+ export { FIRST_WATCH_CHECK_WAIT_MS } from "./types.js";
102
102
  /** How to fix a false alarm: some tools write progress or warnings to stderr on success. */
103
103
  export const BLIND_CHECK_HINT = "If the stderr is expected (progress or warnings), redirect it (2>/dev/null) or set blind_checks:0.";
104
104
  /**
@@ -110,7 +110,8 @@ export type FirstCheckWaitEnd = "timeout" | "aborted" | "suspended";
110
110
  export type FirstCheckOutcome = FirstWatchCheck | { pending: FirstCheckWaitEnd; waitedMs: number } | undefined;
111
111
 
112
112
  /** Each cached extension factory owns its scheduling and suspension state. */
113
- export function createBackgroundTaskRuntime(attention = createFailureAttention()) {
113
+ export function createBackgroundTaskRuntime(attention = createFailureAttention(), deliverCompletion?: (origin: BackgroundTaskCallbackOrigin | undefined, event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => void, admission?: { assert(): void; prepared?(id: string): void },
114
+ sourceWork: (kind: string, id: string, work: () => unknown, dueAt?: number) => unknown = (_kind, _id, work) => work()) {
114
115
  const { resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention } = attention;
115
116
  const watcherTimers = new Map<string, ReturnType<typeof setTimeout>>();
116
117
  const remoteSessionTimers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -298,6 +299,7 @@ function spawnTask(
298
299
  getActiveSession?: ActiveSessionProvider,
299
300
  dependencies: TaskRuntimeDependencies = {},
300
301
  ): BackgroundTaskMeta {
302
+ admission?.assert();
301
303
  // Resolved before any task directory, log, or metadata exists so a blocked
302
304
  // launch leaves nothing behind. Structured SSH must also honor launch restrictions.
303
305
  const intent = readTaskIntent(params);
@@ -314,6 +316,7 @@ function spawnTask(
314
316
  assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
315
317
  const commandLimits = backgroundExecutionLimits(sandboxPlan);
316
318
  const id = nextTaskId();
319
+ admission?.prepared?.(id);
317
320
  const logPath = logPathFor(id);
318
321
  ensureTaskDir(id);
319
322
  const remoteTask = params.ssh
@@ -515,7 +518,8 @@ function scheduleRemoteSessionPoll(
515
518
  ): void {
516
519
  clearRemoteSessionTimer(id);
517
520
  if (scheduledWorkSuspended) return;
518
- const timer = setTimeout(() => void pollRemoteSession(pi, id, getActiveSession), delayMs);
521
+ const dueAt = Date.now() + delayMs;
522
+ const timer = setTimeout(() => void sourceWork("remote-poll", id, () => scheduledWorkSuspended ? undefined : pollRemoteSession(pi, id, getActiveSession), dueAt), delayMs);
519
523
  timer.unref();
520
524
  remoteSessionTimers.set(id, timer);
521
525
  }
@@ -611,6 +615,7 @@ function startWatchTask(
611
615
  getActiveSession?: ActiveSessionProvider,
612
616
  dependencies: TaskRuntimeDependencies = {},
613
617
  ): BackgroundTaskMeta {
618
+ admission?.assert();
614
619
  for (const [name, condition] of [["success_when", params.success_when], ["failure_when", params.failure_when]] as const) {
615
620
  const error = condition && validateCondition(condition);
616
621
  if (error) throw new Error(`${name}: ${error}`);
@@ -625,6 +630,7 @@ function startWatchTask(
625
630
  assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
626
631
  const commandLimits = backgroundExecutionLimits(sandboxPlan);
627
632
  const id = nextTaskId();
633
+ admission?.prepared?.(id);
628
634
  const now = Date.now();
629
635
  const timeoutSeconds = resolveWatchTimeoutSeconds(params.timeout_seconds);
630
636
  const remoteTask = params.ssh
@@ -731,6 +737,9 @@ function resumeRunningTask(
731
737
  scheduleLogRetention(pi, meta.id, getActiveSession);
732
738
  const remoteTask = resolvePersistedRemoteTask(meta, dependencies.remoteRunner);
733
739
  if (meta.kind === "command_watch") {
740
+ // Shared display refreshes can revisit an already supervised watch. They
741
+ // must not replace its captured interval with a new immediate poll.
742
+ if (watcherTimers.has(meta.id) || activePolls.has(meta.id)) return meta;
734
743
  scheduleWatch(pi, meta.id, 0, getActiveSession, remoteTask
735
744
  ? (timeoutMs) => remoteTask.runOnce(undefined, timeoutMs)
736
745
  : dependencies.watchPollRunner);
@@ -810,7 +819,8 @@ function scheduleHandoff(
810
819
  };
811
820
  const arm = () => {
812
821
  if (scheduledWorkSuspended) return;
813
- const timer = setTimeout(check, delayMs);
822
+ const dueAt = Date.now() + delayMs;
823
+ const timer = setTimeout(() => sourceWork("handoff", id, () => { if (!scheduledWorkSuspended) check(); }, dueAt), delayMs);
814
824
  timer.unref();
815
825
  handoffTimers.set(id, timer);
816
826
  };
@@ -953,7 +963,8 @@ function scheduleWatch(
953
963
  ): void {
954
964
  clearWatchTimer(id);
955
965
  if (scheduledWorkSuspended) return;
956
- const timer = setTimeout(() => void pollWatch(pi, id, getActiveSession, runOnce), delayMs);
966
+ const dueAt = Date.now() + delayMs;
967
+ const timer = setTimeout(() => void sourceWork("watch", id, () => scheduledWorkSuspended ? undefined : pollWatch(pi, id, getActiveSession, runOnce), dueAt), delayMs);
957
968
  timer.unref();
958
969
  watcherTimers.set(id, timer);
959
970
  }
@@ -1256,7 +1267,8 @@ function scheduleProcessTimeout(
1256
1267
  clearProcessTimeout(id);
1257
1268
  if (scheduledWorkSuspended) return;
1258
1269
  const delay = Math.max(0, deadlineAt - Date.now());
1259
- const timer = setTimeout(() => void timeoutProcess(pi, id, getActiveSession), delay);
1270
+ const dueAt = deadlineAt;
1271
+ const timer = setTimeout(() => void sourceWork("process-deadline", id, () => scheduledWorkSuspended ? undefined : timeoutProcess(pi, id, getActiveSession), dueAt), delay);
1260
1272
  timer.unref();
1261
1273
  processTimeoutTimers.set(id, timer);
1262
1274
  }
@@ -1363,7 +1375,9 @@ async function notifyTerminal(
1363
1375
  const pending = terminalFailureAttention(latest.id);
1364
1376
  const label = latest.name ? `${latest.name} (${latest.id})` : latest.id;
1365
1377
  const facts = formatCallbackFacts(latest);
1366
- getCallbackBatcher(pi).enqueue({
1378
+ const enqueue = (event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => deliverCompletion ? deliverCompletion(latest.callbackOrigin, event) : getCallbackBatcher(pi).enqueue(event);
1379
+ enqueue({
1380
+ receiptId: `background-legacy:${latest.id}:${latest.endedAt ?? latest.startedAt}`,
1367
1381
  source: "background-task",
1368
1382
  id: latest.id,
1369
1383
  label,
@@ -1453,7 +1467,9 @@ function launchArgvOf(commandSpec: CommandSpec, launchSpec: CommandSpec): string
1453
1467
  function scheduleLogRetention(pi: ExtensionAPI, id: string, getActiveSession?: ActiveSessionProvider): void {
1454
1468
  stopLogRetention(id);
1455
1469
  if (scheduledWorkSuspended) return;
1456
- const timer = setInterval(() => {
1470
+ let dueAt = Date.now() + LOG_RETENTION_CHECK_MS;
1471
+ const timer = setInterval(() => { const due = dueAt; dueAt = Date.now() + LOG_RETENTION_CHECK_MS; return sourceWork("log-retention", id, () => {
1472
+ if (scheduledWorkSuspended) return;
1457
1473
  const meta = readMeta(id);
1458
1474
  if (!meta || meta.status !== "running") {
1459
1475
  stopLogRetention(id);
@@ -1461,7 +1477,7 @@ function scheduleLogRetention(pi: ExtensionAPI, id: string, getActiveSession?: A
1461
1477
  }
1462
1478
  if (meta.kind === "process") enforceLogRetention(meta);
1463
1479
  if (observeTaskStallAttention(meta)) scheduleFailureAttention(pi, id, getActiveSession);
1464
- }, LOG_RETENTION_CHECK_MS);
1480
+ }, due); }, LOG_RETENTION_CHECK_MS);
1465
1481
  timer.unref();
1466
1482
  logRetentionTimers.set(id, timer);
1467
1483
  }
package/src/sandbox.ts CHANGED
@@ -214,7 +214,7 @@ export interface ForegroundSandboxPolicy {
214
214
  readonly denyWrite: readonly string[];
215
215
  /** Human-readable evidence for why `state` is what it is. */
216
216
  readonly reason: string;
217
- readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean }>;
217
+ readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean; processAccess?: "off" | "read" }>;
218
218
  readonly policySource?: "background" | "main-legacy";
219
219
  }
220
220
 
@@ -320,6 +320,7 @@ function readPermissions(value: unknown): ForegroundSandboxPolicy["permissions"]
320
320
  projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
321
321
  outsideProject: p.outsideProject as SandboxPermissions["outsideProject"],
322
322
  storedCredentials: p.storedCredentials as SandboxPermissions["storedCredentials"],
323
+ ...(p.processAccess === undefined ? {} : { processAccess: p.processAccess as "off" | "read" }),
323
324
  ...(p.shell === undefined ? {} : { shell: p.shell as boolean }),
324
325
  ...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds as number | null }),
325
326
  });
@@ -343,16 +344,18 @@ export function observeForegroundSandboxPolicy(pi: unknown): void {
343
344
  try {
344
345
  const published = data && typeof data === "object" ? data as Record<string, unknown> : undefined;
345
346
  const hasBackground = published && Object.hasOwn(published, "background");
346
- const policy = readPolicy(hasBackground ? published.background : data, hasBackground ? "Background tasks" : "Main");
347
- if (hasBackground && !policy) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
348
- const access = (value: unknown): unknown => {
349
- if (!value || typeof value !== "object") return undefined;
350
- return (value as { permissions?: { processAccess?: unknown } }).permissions?.processAccess;
351
- };
352
- mirror.mainConfined = published?.state !== "disabled" && published?.state !== "inactive";
353
- mirror.processAccess = access(data) === "read" && access(hasBackground ? published.background : data) === "read" ? "read" : "off";
354
- if (policy) Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
355
- if (policy) { mirror.policy = policy; mirror.error = undefined; }
347
+ const main = readPolicy(data);
348
+ const policy = hasBackground ? readPolicy(published.background, "Background tasks") : main;
349
+ if (hasBackground && (!main || !policy)) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
350
+ if (!policy || !main) return;
351
+ const isOff = (scope: ForegroundSandboxPolicy) => scope.state === "disabled" || scope.state === "inactive";
352
+ const allowsRead = (scope: ForegroundSandboxPolicy) => scope.permissions !== undefined &&
353
+ (isOff(scope) || scope.permissions.processAccess === "read");
354
+ mirror.mainConfined = !isOff(main);
355
+ mirror.processAccess = allowsRead(main) && allowsRead(policy) ? "read" : "off";
356
+ Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
357
+ mirror.policy = policy;
358
+ mirror.error = undefined;
356
359
  } catch (error) {
357
360
  mirror.error = error as Error;
358
361
  mirror.processAccess = "off";
@@ -901,3 +904,10 @@ function blocked(plan: ForegroundSandboxPlan & { confined: true }, detail: strin
901
904
  detail,
902
905
  );
903
906
  }
907
+
908
+ /** Fixed server adapter clears only its own scope mirror before publishing another captured grant. */
909
+ export function clearForegroundSandboxPolicy(pi: unknown): void {
910
+ observeForegroundSandboxPolicy(pi);
911
+ const events=eventBusOf(pi), mirror=events && mirrors.get(events);
912
+ if(mirror){mirror.policy=undefined;mirror.error=undefined;mirror.processAccess="off";mirror.mainConfined=false;}
913
+ }
@@ -158,6 +158,8 @@ export interface CallbackBatchEvent {
158
158
  }
159
159
 
160
160
  export interface UrgentCallbackEvent {
161
+ /** Durable recipient transcript identity for handoff/receipt crash recovery. */
162
+ receiptId?: string;
161
163
  source: CallbackSource;
162
164
  /** Notification identity (dedupe/receipts). */
163
165
  id: string;
@@ -208,6 +210,8 @@ export interface CallbackBatcher {
208
210
  toolEnded(toolCallId: string): Promise<boolean>;
209
211
  deliverUrgent(event: UrgentCallbackEvent): boolean | Promise<boolean>;
210
212
  cancel(): void;
213
+ /** Await already-started handoffs after the owner has cancelled scheduling. */
214
+ settled(): Promise<void>;
211
215
  pendingCount(): number;
212
216
  }
213
217
 
@@ -566,6 +570,7 @@ export function createCallbackBatcher(
566
570
  const pending = new Map<string, PendingEvent>();
567
571
  const inFlight = new Set<string>();
568
572
  const urgentInFlight = new Set<string>();
573
+ const urgentSettlements = new Set<Promise<boolean>>();
569
574
  const handedOff = new Map<string, number>();
570
575
  const activeTools = new Set<string>();
571
576
  let sequence = 0;
@@ -743,14 +748,17 @@ export function createCallbackBatcher(
743
748
  urgentInFlight.add(key);
744
749
  try {
745
750
  const handoff = host.sendMessage(
746
- { customType: event.customType, content: formatUrgentCallback(event, { maxBytes }), display: true },
751
+ { customType: event.customType, content: formatUrgentCallback(event, { maxBytes }), display: true,
752
+ ...(event.receiptId ? { details: { urgentEventId: event.receiptId } } : {}) },
747
753
  { deliverAs: "followUp", triggerTurn: true },
748
754
  );
749
755
  if (isPromiseLike(handoff)) {
750
- return Promise.resolve(handoff).then(
756
+ const settlement = Promise.resolve(handoff).then(
751
757
  () => acknowledge(),
752
758
  () => false,
753
- ).finally(() => urgentInFlight.delete(key));
759
+ ).finally(() => { urgentInFlight.delete(key); urgentSettlements.delete(settlement); });
760
+ urgentSettlements.add(settlement);
761
+ return settlement;
754
762
  }
755
763
  const acknowledged = acknowledge();
756
764
  urgentInFlight.delete(key);
@@ -797,6 +805,10 @@ export function createCallbackBatcher(
797
805
  return pending.size > 0 ? api.flush() : true;
798
806
  },
799
807
  deliverUrgent,
808
+ async settled() {
809
+ await flushPromise;
810
+ await Promise.all([...urgentSettlements]);
811
+ },
800
812
  cancel() {
801
813
  cancelTimer();
802
814
  pending.clear();
@@ -1072,6 +1072,9 @@ export function readFailureState(path: string): FailureState {
1072
1072
  for (const record of remaining ?? []) state = reduceFailure(state, record.event, record.observedAt);
1073
1073
  return remaining?.length ? storageProblem(state, "Failure evidence could not be persisted") : state;
1074
1074
  }
1075
+ /** Read-only projection: never retries or appends process-local pending writes. */
1076
+ export function readFailureStateReadOnly(path: string): FailureState { return readStoredState(path); }
1077
+
1075
1078
  function readStoredState(path: string): FailureState {
1076
1079
  let source: string;
1077
1080
  try { source = readFileSync(path, "utf8"); }
@@ -9,7 +9,8 @@ export const NAVIGATOR_ENTRY_TYPE = "pi-better-harness-navigator-panels";
9
9
  export const NAVIGATOR_STICKY_SETTING_ID = "navigator-sticky";
10
10
  type MouseEvent = { type: string; button: string; x: number; y: number; width: number; shift?: boolean; alt?: boolean; ctrl?: boolean };
11
11
  type PanelComponent = Component & { dispose?(): void; handleMouse?(event: MouseEvent): { handled: true; render: boolean } | undefined };
12
- export type NavigatorPanelFactory = (tui: TUI, theme: Theme) => PanelComponent;
12
+ export type NavigatorPanelLayout = { availableRows(): number };
13
+ export type NavigatorPanelFactory = (tui: TUI, theme: Theme, layout: NavigatorPanelLayout) => PanelComponent;
13
14
  type Panel = { factory: NavigatorPanelFactory; component?: PanelComponent | undefined };
14
15
  type Preference = { version: 1; sticky: boolean };
15
16
  type Owner = { pi: ExtensionAPI; stop?: (() => void) | undefined };
@@ -23,6 +24,8 @@ type State = {
23
24
  mounted: boolean;
24
25
  tui?: TUI | undefined;
25
26
  theme?: Theme | undefined;
27
+ host?: Component | undefined;
28
+ availableRows?: number | undefined;
26
29
  anchor?: string | undefined;
27
30
  pendingAnchor: boolean;
28
31
  generation: number;
@@ -61,14 +64,30 @@ function orderedPanels(s: State): Panel[] {
61
64
  }
62
65
  function buildPanels(s: State): void {
63
66
  if (!s.tui || !s.theme) return;
64
- for (const panel of orderedPanels(s)) panel.component ??= panel.factory(s.tui, s.theme);
67
+ for (const panel of orderedPanels(s)) panel.component ??= panel.factory(s.tui, s.theme, { availableRows: () => s.availableRows ?? Infinity });
68
+ }
69
+ // Count the editor, footer and other siblings following the host in regular mode.
70
+ // Never render ancestors here: they contain this host and would recurse.
71
+ function rowsAfter(root: object, target: Component, width: number): number | undefined {
72
+ if (root === target) return 0;
73
+ const children = (root as Component & { children?: Component[] }).children;
74
+ if (!children) return undefined;
75
+ for (let i = children.length - 1; i >= 0; i--) {
76
+ const after = rowsAfter(children[i]!, target, width);
77
+ if (after !== undefined) return after + children.slice(i + 1).reduce((sum, child) => sum + child.render(width).length, 0);
78
+ }
79
+ return undefined;
65
80
  }
66
81
  function renderPanels(s: State, width: number): string[] {
67
82
  buildPanels(s);
68
83
  const lines: string[] = [];
69
84
  s.ranges = [];
85
+ const after = s.sticky && s.tui && s.host ? rowsAfter(s.tui, s.host, width) : undefined;
86
+ const height = s.tui?.terminal?.rows;
87
+ const budget = after !== undefined && height ? Math.max(0, height - after) : Infinity;
70
88
  for (const panel of orderedPanels(s)) {
71
89
  if (!panel.component) continue;
90
+ s.availableRows = Math.max(0, budget - lines.length);
72
91
  const rendered = panel.component.render(width);
73
92
  s.ranges.push({ start: lines.length, end: lines.length + rendered.length, component: panel.component });
74
93
  lines.push(...rendered);
@@ -115,6 +134,7 @@ function clearHost(s: State): void {
115
134
  disposePanels(s);
116
135
  s.mounted = false;
117
136
  s.tui = undefined;
137
+ s.host = undefined;
118
138
  s.theme = undefined;
119
139
  }
120
140
  function adoptContext(s: State, ctx: ExtensionContext): void {
@@ -134,7 +154,7 @@ function mountHost(s: State): void {
134
154
  s.tui = tui;
135
155
  s.theme = theme;
136
156
  buildPanels(s);
137
- return {
157
+ const host: PanelComponent = {
138
158
  render(width: number) {
139
159
  const lines = renderPanels(s, width);
140
160
  if (s.sticky) return lines;
@@ -147,6 +167,8 @@ function mountHost(s: State): void {
147
167
  },
148
168
  dispose() { disposePanels(s); s.mounted = false; },
149
169
  };
170
+ s.host = host;
171
+ return host;
150
172
  }, { placement: "aboveEditor" });
151
173
  }
152
174
  function changeSticky(value: string, ctx: ExtensionContext): void {
@@ -247,4 +269,4 @@ export function __resetNavigatorPanelsForTests(): void {
247
269
  s.anchor = undefined;
248
270
  s.sticky = true;
249
271
  s.control = undefined;
250
- }
272
+ }