pi-better-server 0.6.0 → 0.7.1

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 (142) hide show
  1. package/package.json +4 -3
  2. package/scripts/measure-full-runtime/frontend.ts +10 -2
  3. package/scripts/measure-full-runtime.mjs +2 -0
  4. package/src/codex/return.ts +3 -2
  5. package/src/detach/extension.ts +20 -3
  6. package/src/event-log.ts +40 -12
  7. package/src/hosted-session.ts +11 -5
  8. package/src/remote-client/packages.ts +1 -4
  9. package/src/runtime/background-tools.ts +54 -8
  10. package/src/runtime/background.ts +16 -4
  11. package/src/runtime/domain/background/process.mjs +49 -11
  12. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  13. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  14. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  15. package/src/runtime/domain/background-service/index.ts +19 -0
  16. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  17. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  18. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  19. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  20. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  21. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  22. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  23. package/src/runtime/domain/background-service/process.ts +45 -11
  24. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  25. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  26. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  27. package/src/runtime/domain/background-service/runtime.ts +8 -73
  28. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  29. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  30. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  31. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  32. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  33. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  34. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  35. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  36. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  37. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  38. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  39. package/src/runtime/domain/background-service/stall.ts +7 -4
  40. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  41. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  42. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  43. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  44. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  45. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  46. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  47. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  48. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  49. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  50. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  51. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  52. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  53. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  54. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  55. package/src/runtime/domain/background-service/tools.ts +26 -16
  56. package/src/runtime/domain/background-service/types.ts +4 -2
  57. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  58. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  59. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  60. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  61. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  62. package/src/runtime/domain/log-paths.mjs +8 -1
  63. package/src/runtime/domain/parse.mjs +9 -5
  64. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  65. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  66. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  67. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  68. package/src/runtime/domain/session-store.mjs +7 -0
  69. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  70. package/src/runtime/domain/subagents/README.md +12 -10
  71. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  72. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  73. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  74. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  75. package/src/runtime/domain/subagents/batch.mjs +13 -5
  76. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  77. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  78. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  79. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  80. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  81. package/src/runtime/domain/subagents/config.ts +8 -2
  82. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  83. package/src/runtime/domain/subagents/continuation.ts +4 -2
  84. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  85. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  86. package/src/runtime/domain/subagents/failures.ts +10 -2
  87. package/src/runtime/domain/subagents/finalization.domain.mjs +39 -32
  88. package/src/runtime/domain/subagents/finalization.ts +37 -30
  89. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  90. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  91. package/src/runtime/domain/subagents/index.domain.mjs +208 -75
  92. package/src/runtime/domain/subagents/index.ts +213 -75
  93. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +508 -0
  94. package/src/runtime/domain/subagents/isolated-workspace.ts +551 -0
  95. package/src/runtime/domain/subagents/list.mjs +2 -2
  96. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  97. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  98. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  99. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  100. package/src/runtime/domain/subagents/package.json +4 -2
  101. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  102. package/src/runtime/domain/subagents/parse.ts +10 -5
  103. package/src/runtime/domain/subagents/registry.domain.mjs +31 -25
  104. package/src/runtime/domain/subagents/registry.ts +31 -13
  105. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  106. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  107. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  108. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  109. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  110. package/src/runtime/domain/subagents/session-store.ts +9 -0
  111. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  112. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  113. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  114. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  115. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  116. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  117. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  118. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  119. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  120. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  121. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  122. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  123. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  124. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  125. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  126. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  127. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  128. package/src/runtime/domain/subagents/tools.ts +4 -7
  129. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  130. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  131. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  132. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  133. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  134. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  135. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  136. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  137. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  138. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  139. package/src/runtime/read-model.ts +4 -2
  140. package/src/runtime/root.ts +5 -2
  141. package/src/shared-ssh-core/index.ts +1 -1
  142. package/src/version.ts +1 -1
@@ -29,12 +29,15 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
29
29
 
30
30
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
31
31
 
32
+ import { describeSupervisedProgress, supervisedProgress, type SupervisedProgress } from "./supervised-progress.js";
33
+ import { formatProgressDuration } from "./stall.js";
32
34
  import { validateCondition } from "./conditions.js";
33
35
  import {
34
36
  STEP_GATE_COMMAND_ENV,
35
37
  commandExecution,
36
38
  parseStepGateFailure,
37
39
  processExists,
40
+ resolveWindowsLaunchShell,
38
41
  stepGateScript,
39
42
  validateCommandSpec,
40
43
  } from "./process.js";
@@ -74,7 +77,7 @@ import {
74
77
  type SupervisorTaskStatus,
75
78
  } from "./supervisor/index.js";
76
79
  import { processGroupAlive } from "./supervisor/identity.js";
77
- import { readStopRequest } from "./supervisor/store.js";
80
+ import { readStopRequest, writeTextAtomic } from "./supervisor/store.js";
78
81
  import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
79
82
  import type { SpawnTaskParams, WatchTaskParams } from "./runtime.js";
80
83
 
@@ -400,6 +403,7 @@ export interface AcknowledgeView {
400
403
  }
401
404
 
402
405
  export interface StatusView {
406
+ readonly progress?: SupervisedProgress;
403
407
  readonly taskId: string;
404
408
  readonly operationId: string;
405
409
  readonly kind: DurableTaskKind;
@@ -422,6 +426,7 @@ export interface StatusView {
422
426
 
423
427
  /** Read-only projection of one supervised durable task for list/navigator/Goal. */
424
428
  export interface DurableTaskProjection {
429
+ readonly progress?: SupervisedProgress;
425
430
  readonly parentAgentId?: string;
426
431
  readonly parentRecipient?: { sessionId: string; workspace: string; branchId?: string | null };
427
432
  readonly readOnly?: boolean;
@@ -1791,6 +1796,102 @@ export class ObservedWaitHost {
1791
1796
  return this.projectDurable(operation, now);
1792
1797
  }
1793
1798
 
1799
+ /** Rebuild a live incident from the runner checkpoint. Only the native handoff writes its receipt. */
1800
+ pendingStallAlert(origin: BackgroundTaskCallbackOrigin, taskId: string, waits: readonly { waitId: string; generation: number }[]) {
1801
+ const operation = this.operationForTask(taskId);
1802
+ if (!operation || operation.terminalRevision || !this.belongsToParentOrigin(operation, origin)) return;
1803
+ const branchId = operation.owner.branchId;
1804
+ if (!this.isParentOriginActive(origin, branchId)) return;
1805
+ const directory = this.observationDirectory(operation);
1806
+ if (!directory) return;
1807
+ const context = this.readLaunchContext(taskId, directory);
1808
+ if (!context?.callback) return;
1809
+ const inspection = this.passiveSnapshot(taskId, directory);
1810
+ if (!inspection || inspection.token !== operation.launchToken || inspection.stopRequestedAt !== undefined) return;
1811
+ const now = this.options.now?.() ?? Date.now();
1812
+ const progress = supervisedProgress(inspection, now);
1813
+ if (!progress?.alertDue) return;
1814
+ const receiptId = `background-stall:${operation.operationId}:${progress.observedAt}`;
1815
+ const receiptPath = join(inspection.taskDir, "stall-receipt");
1816
+ try {
1817
+ if (readFileSync(receiptPath, "utf8") === receiptId) return;
1818
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
1819
+ const lines = [describeSupervisedProgress(progress, now)!,
1820
+ `Task has run for ${formatProgressDuration(now - inspection.launch.createdAt)}.`];
1821
+ for (const ref of waits) {
1822
+ const wait = this.requireStore().getWait(ref);
1823
+ if (!wait || wait.phase === "cancelled" || wait.phase === "consumed" || !sameOwner(wait.owner, operation.owner)) continue;
1824
+ if (!wait.dependencies.some(dep => dep.operationId === operation.operationId)) continue;
1825
+ const others = wait.dependencies.filter(dep => dep.operationId !== operation.operationId);
1826
+ const siblings = others.slice(0, 8).map(dep => {
1827
+ const sibling = this.requireStore().getOperation(dep.operationId);
1828
+ return `${sibling?.taskId ?? dep.operationId} ${sibling?.terminalOutcome ?? sibling?.phase ?? "unknown"}`;
1829
+ });
1830
+ if (others.length > siblings.length) siblings.push(`+${others.length - siblings.length} more`);
1831
+ lines.push(`Wait ${ref.waitId} ${wait.phase}${siblings.length ? ". Other tasks: " + siblings.join(", ") : ""}`);
1832
+ }
1833
+ const output = [inspection.logs.stdout, inspection.logs.stderr].map(path => lastLines(tail(path).text, 1).slice(-300)).filter(Boolean);
1834
+ lines.push(...output, `Evidence: bg_task_log id=${taskId}`);
1835
+ const notification = { taskId, operationId: operation.operationId, origin, branchId, urgent: true,
1836
+ event: { source: "background-task", id: receiptId, inspectId: taskId, label: context.name ?? taskId,
1837
+ status: "suspected stall", customType: "background-task-stall", content: lines.join("\n"), detailTool: "bg_task_status" } };
1838
+ return { notification, delivery: { receiptId, delivered: () => writeTextAtomic(receiptPath, receiptId), defer: () => {} } };
1839
+ }
1840
+
1841
+ /** Review an ongoing parent wait using durable launch, progress and handoff evidence. */
1842
+ backgroundWaitReview(origin: BackgroundTaskCallbackOrigin, taskId: string, waits: readonly { waitId: string; generation: number }[], intervalMs: number) {
1843
+ const operation = this.operationForTask(taskId);
1844
+ if (!operation || operation.terminalRevision || !this.belongsToParentOrigin(operation, origin)) return;
1845
+ const branchId = operation.owner.branchId;
1846
+ if (!this.isParentOriginActive(origin, branchId)) return;
1847
+ const wait = waits.map(ref => this.requireStore().getWait(ref)).find(record => record?.phase === "waiting"
1848
+ && sameOwner(record.owner, operation.owner)
1849
+ && record.dependencies.some(dep => dep.operationId === operation.operationId));
1850
+ if (!wait) return;
1851
+ const directory = this.observationDirectory(operation);
1852
+ if (!directory) return;
1853
+ const context = this.readLaunchContext(taskId, directory);
1854
+ if (!context?.callback) return;
1855
+ const inspection = this.passiveSnapshot(taskId, directory);
1856
+ if (!inspection || inspection.token !== operation.launchToken || inspection.stopRequestedAt !== undefined) return;
1857
+ const clock = this.options.now ?? Date.now;
1858
+ const now = clock();
1859
+ const progress = supervisedProgress(inspection, now);
1860
+ if (!progress) return;
1861
+ const receiptPath = join(inspection.taskDir, "wait-review-receipt.json");
1862
+ const incident = [wait.waitId, wait.generation, progress.observedAt].join(":");
1863
+ const firstReviewAnchor = Math.max(wait.createdAt, progress.observedAt);
1864
+ let anchor = firstReviewAnchor;
1865
+ try {
1866
+ const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
1867
+ if (receipt?.incident === incident && Number.isFinite(receipt.deliveredAt)) {
1868
+ anchor = Math.max(anchor, receipt.deliveredAt);
1869
+ }
1870
+ } catch (error) {
1871
+ if (!(error instanceof SyntaxError) && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
1872
+ }
1873
+ const dueAt = anchor + intervalMs;
1874
+ if (now < dueAt) return { dueAt };
1875
+
1876
+ const receiptId = `background-wait-review:${operation.operationId}:${incident}:${anchor}`;
1877
+ const lines = [
1878
+ `Task has run for ${formatProgressDuration(now - inspection.launch.createdAt)}. No observed progress for ${formatProgressDuration(now - progress.observedAt)}.`,
1879
+ `Wait ${wait.waitId} is still waiting. Reassess the blocker and report the next step.`,
1880
+ `Continuation note: ${oneLine(wait.continuationNote, 250)}`,
1881
+ ];
1882
+ if (inspection.kind === "watch") {
1883
+ const lastCheck = lastLines(tail(inspection.logs.events).text, 12).split("\n").reverse().find(line => / check #\d+ exit=/.test(line));
1884
+ if (lastCheck) lines.push(`Latest check: ${oneLine(lastCheck, 200)}`);
1885
+ }
1886
+ const output = [inspection.logs.stdout, inspection.logs.stderr].map(path => lastLines(tail(path).text, 1).slice(-300)).filter(Boolean);
1887
+ lines.push(...output, `Evidence: bg_task_log id=${taskId}`);
1888
+ const notification = { taskId, operationId: operation.operationId, origin, branchId, urgent: true,
1889
+ event: { source: "background-task", id: receiptId, inspectId: taskId, label: context.name ?? taskId,
1890
+ status: "wait review due", customType: "background-wait-review", content: lines.join("\n"), detailTool: "bg_task_status" } };
1891
+ return { dueAt, alert: { notification, delivery: { receiptId,
1892
+ delivered: () => writeTextAtomic(receiptPath, JSON.stringify({ incident, deliveredAt: clock() })), defer: () => {} } } };
1893
+ }
1894
+
1794
1895
  /** Accumulated projection work, for performance regression proof. */
1795
1896
  getDurableProjectionMetrics(): DurableProjectionMetrics {
1796
1897
  return { ...this.projectionMetrics };
@@ -1903,13 +2004,24 @@ export class ObservedWaitHost {
1903
2004
  return true;
1904
2005
  }
1905
2006
 
2007
+ private observationDirectory(operation: OperationRecord): string | undefined {
2008
+ if (!operation.supervision?.hostId?.startsWith("server:")) return this.directory;
2009
+ const grant = this.store?.resultSupervision(operation.operationId);
2010
+ if (!grant || grant.launchToken !== operation.launchToken || !sameOwner(grant.owner, operation.owner)) return;
2011
+ return grant.directory;
2012
+ }
2013
+
2014
+ private passiveSnapshot(taskId: string, directory: string | undefined): SupervisorInspection | undefined {
2015
+ if (!directory || !LOCAL_DURABLE_ID.test(taskId)) return;
2016
+ const supervisor = directory === this.directory ? this.supervisor : createLocalSupervisor({ directory });
2017
+ try { return supervisor.snapshot(taskId); } catch { return; }
2018
+ }
2019
+
1906
2020
  private projectDurable(operation: OperationRecord, now: number): DurableTaskProjection | undefined {
1907
- const context = this.launchContext(operation.taskId);
1908
- // Projection is the rendering path: a snapshot reads the durable records
1909
- // without taking the cross-process fence or spawning `ps`.
1910
- const inspection = LOCAL_DURABLE_ID.test(operation.taskId)
1911
- ? (() => { try { return this.supervisor.snapshot(operation.taskId); } catch { return undefined; } })()
1912
- : undefined;
2021
+ const directory = this.observationDirectory(operation);
2022
+ const context = directory === this.directory ? this.launchContext(operation.taskId)
2023
+ : directory ? this.readLaunchContext(operation.taskId, directory) : undefined;
2024
+ const inspection = this.passiveSnapshot(operation.taskId, directory);
1913
2025
  const storeStatus = operation.terminalRevision > 0 ? this.statusOf(operation.operationId) : undefined;
1914
2026
  const status: SupervisorTaskStatus = inspection?.terminal ? inspection.status : storeStatus ?? inspection?.status ?? "running";
1915
2027
  const terminal = inspection?.terminal === true || operation.terminalRevision > 0;
@@ -1933,6 +2045,7 @@ export class ObservedWaitHost {
1933
2045
  status,
1934
2046
  active,
1935
2047
  terminal,
2048
+ progress: active ? supervisedProgress(inspection, now) : undefined,
1936
2049
  attention: terminal && status !== "succeeded",
1937
2050
  ...(context?.name ?? inspection?.launch.name ? { name: context?.name ?? inspection?.launch.name } : {}),
1938
2051
  cwd: inspection?.launch.cwd ?? context?.cwd ?? operation.owner.workspace,
@@ -1966,7 +2079,8 @@ export class ObservedWaitHost {
1966
2079
 
1967
2080
  private statusForOperation(operation: OperationRecord, owner: OwnerIdentity): StatusView {
1968
2081
  const store = this.requireStore(), taskId = operation.taskId;
1969
- const inspection = this.inspect(taskId);
2082
+ const directory = this.observationDirectory(operation);
2083
+ const inspection = directory === this.directory ? this.inspect(taskId) : this.passiveSnapshot(taskId, directory);
1970
2084
  this.reconcileInspection(operation, inspection);
1971
2085
  const current = store.getOperation(operation.operationId) ?? operation;
1972
2086
  if (this.watchedRunningTasks.delete(taskId) && current.terminalRevision > 0) {
@@ -1990,14 +2104,14 @@ export class ObservedWaitHost {
1990
2104
  );
1991
2105
  }
1992
2106
  this.recordReadsForTask(owner, current);
1993
- const paths = supervisorPaths(this.directory, taskId);
2107
+ const paths = inspection?.logs ?? supervisorPaths(this.directory, taskId);
1994
2108
  const gateText = inspection ? `${tail(paths.stderr).text}` : "";
1995
2109
  const waits = store.listWaits({ pendingOnly: true })
1996
2110
  .filter((wait) => sameOwner(wait.owner, owner))
1997
2111
  .filter((wait) => wait.dependencies.some((dep) => dep.operationId === current.operationId))
1998
2112
  .map((wait) => this.waitView(wait));
1999
2113
  const result = inspection?.result;
2000
- const launched = this.launchContext(taskId);
2114
+ const launched = directory === this.directory ? this.launchContext(taskId) : directory ? this.readLaunchContext(taskId, directory) : undefined;
2001
2115
  const stepGate = result && launched?.gated ? parseStepGateFailure(gateText, taskId) : undefined;
2002
2116
  const kind = inspection?.kind ?? launched?.kind ?? "process";
2003
2117
  return {
@@ -2006,6 +2120,7 @@ export class ObservedWaitHost {
2006
2120
  kind: kind === "watch" ? "watch" : "process",
2007
2121
  status: inspection?.status ?? this.statusOf(current.operationId),
2008
2122
  phase: current.phase,
2123
+ progress: current.terminalRevision === 0 ? supervisedProgress(inspection, this.options.now?.() ?? Date.now()) : undefined,
2009
2124
  exitCode: result?.exitCode ?? null,
2010
2125
  signal: result?.signal ?? null,
2011
2126
  ...supervisionReasonFields(inspection),
@@ -2024,10 +2139,12 @@ export class ObservedWaitHost {
2024
2139
  private log(taskId: string, owner: OwnerIdentity, options: { lines?: number } = {}): LogView {
2025
2140
  const store = this.requireStore();
2026
2141
  const operation = this.ownedOperation(taskId, owner);
2027
- const inspection = this.inspect(taskId);
2142
+ const directory = this.observationDirectory(operation);
2143
+ const inspection = directory === this.directory ? this.inspect(taskId) : this.passiveSnapshot(taskId, directory);
2028
2144
  this.reconcileInspection(operation, inspection);
2029
2145
  this.recordReadsForTask(owner, store.getOperation(operation.operationId) ?? operation);
2030
- const paths = supervisorPaths(this.directory, taskId);
2146
+ if (!directory) throw new Error("Captured Background log directory unavailable");
2147
+ const paths = inspection?.logs ?? supervisorPaths(directory, taskId);
2031
2148
  const lines = Math.max(1, Math.floor(options.lines ?? 40));
2032
2149
  const stdout = tail(paths.stdout);
2033
2150
  const stderr = tail(paths.stderr);
@@ -2064,6 +2181,8 @@ export class ObservedWaitHost {
2064
2181
  `${view.taskId} ${view.kind}: ${view.status} (${view.phase})`,
2065
2182
  `operation: ${view.operationId}; terminal revision: ${view.terminalRevision}${view.terminalOutcome ? ` (${view.terminalOutcome})` : ""}`,
2066
2183
  ];
2184
+ const progress = view.progress && describeSupervisedProgress(view.progress, this.options.now?.() ?? Date.now());
2185
+ if (progress) lines.push(progress);
2067
2186
  if (view.sandbox) {
2068
2187
  lines.push(`sandbox: ${view.sandbox.confinement}${view.sandbox.backend ? `; ${oneLine(view.sandbox.backend, 40)}` : ""}; source: ${oneLine(view.sandbox.policySource, 80)}; later changes do not affect this task.`);
2069
2188
  }
@@ -3133,6 +3252,7 @@ export class ObservedWaitHost {
3133
3252
  ? resolveWorkerSandboxPlan(this.pi, workerPolicy, params, tool)
3134
3253
  : resolveForegroundSandboxPlan(this.pi, false, params, tool);
3135
3254
  assertBackgroundExecutionAllowed(spec, plan, { remote: false, cwd });
3255
+ if (spec.shell !== false) spec.resolvedWindowsShell = resolveWindowsLaunchShell(this.pi);
3136
3256
  const limits = backgroundExecutionLimits(plan);
3137
3257
  const gated = kind === "process" && params.require_successful_steps === true;
3138
3258
  if (gated) {
@@ -3269,10 +3389,16 @@ export class ObservedWaitHost {
3269
3389
  throw error;
3270
3390
  }
3271
3391
  }
3272
- const inspection = this.inspect(operation.taskId);
3392
+ let inspection: SupervisorInspection | undefined;
3393
+ let unavailable = false;
3394
+ try {
3395
+ if (LOCAL_DURABLE_ID.test(operation.taskId)) inspection = this.supervisor.inspect(operation.taskId, { recordLost: true });
3396
+ } catch {
3397
+ unavailable = true;
3398
+ }
3273
3399
  if (!inspection) {
3274
3400
  const now = this.options.now?.() ?? Date.now();
3275
- if (now - operation.createdAt >= 30_000) {
3401
+ if (!unavailable && now - operation.createdAt >= 30_000) {
3276
3402
  // The supervisor writes its launch record before spawning. No record
3277
3403
  // after the claim grace means no execution can be witnessed; this is
3278
3404
  // `lost`, never a success and never a silent retry.
@@ -3295,14 +3421,15 @@ export class ObservedWaitHost {
3295
3421
  void this.dispatchOutbox();
3296
3422
  return;
3297
3423
  }
3424
+ const reason = unavailable ? "durable supervisor records could not be read" : "no durable supervisor record exists for this operation";
3298
3425
  try {
3299
- if (claimed || operation.health !== "unmonitored" || operation.healthReason !== "no durable supervisor record exists for this operation") {
3426
+ if (claimed || operation.health !== "unmonitored" || operation.healthReason !== reason) {
3300
3427
  this.store?.recordSupervision({
3301
3428
  operationId: operation.operationId,
3302
3429
  owner: operation.owner,
3303
3430
  expectedHostId: this.hostId,
3304
3431
  health: "unmonitored",
3305
- reason: "no durable supervisor record exists for this operation",
3432
+ reason,
3306
3433
  });
3307
3434
  }
3308
3435
  } catch { /* the owner may have been superseded; health is observational */ }
@@ -3459,7 +3586,7 @@ export class ObservedWaitHost {
3459
3586
  return;
3460
3587
  }
3461
3588
  this.options.logger?.(`observed waits: ${operation.taskId} ${status} (revision ${recorded.operation.terminalRevision})`);
3462
- this.attemptTerminalCallback(operation, status, outcome, refs, { pendingWithoutContext: true });
3589
+ this.attemptTerminalCallback(recorded.operation, status, outcome, refs, { pendingWithoutContext: true });
3463
3590
  this.emitDurableTaskChange(operation.owner);
3464
3591
  // The parent callback is independent from the worker's wait: a worker may be
3465
3592
  // parked, while the parent session still learns that the supervised task ended.
@@ -3504,6 +3631,11 @@ export class ObservedWaitHost {
3504
3631
  skip("already delivered");
3505
3632
  return;
3506
3633
  }
3634
+ if (this.waitDeliveredTerminalRevision(operation, context)) {
3635
+ this.pendingTerminalCallbacks.delete(operation.taskId);
3636
+ this.store?.setParentCallbackPending(operation.taskId, false);
3637
+ return;
3638
+ }
3507
3639
  const waitPending = this.store?.listWaits({ owner: operation.owner, pendingOnly: true })
3508
3640
  .some((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId)) ?? false;
3509
3641
  if (waitPending) {
@@ -3679,6 +3811,12 @@ export class ObservedWaitHost {
3679
3811
  && proof.terminalRevision === event.terminalRevision;
3680
3812
  }
3681
3813
 
3814
+ private waitDeliveredTerminalRevision(operation: OperationRecord, context: LaunchContext): boolean {
3815
+ if (operation.terminalRevision === 0) return false;
3816
+ return Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision)
3817
+ || (this.store?.hasDeliveredWaitDependency(operation.operationId, operation.terminalRevision, operation.owner) ?? false);
3818
+ }
3819
+
3682
3820
  private recordOutboxHandoffProof(taskId: string, event: OutboxEventRecord): void {
3683
3821
  const context = this.currentLaunchContext(taskId);
3684
3822
  if (!context) return;
@@ -3890,7 +4028,13 @@ export class ObservedWaitHost {
3890
4028
  } catch { /* the store closed between handoff and receipt */ }
3891
4029
  // Key the recovered receipt to this exact event. Never use the
3892
4030
  // standalone task callback's receipt as proof for a wait.
3893
- if (!receipted && taskId) this.recordOutboxHandoffProof(taskId, event);
4031
+ if (taskId) {
4032
+ this.pendingTerminalCallbacks.delete(taskId);
4033
+ if (!receipted) this.recordOutboxHandoffProof(taskId, event);
4034
+ else {
4035
+ try { store.setParentCallbackPending(taskId, false); } catch { /* the wait receipt survives for recovery */ }
4036
+ }
4037
+ }
3894
4038
  },
3895
4039
  defer: (reason: string) => {
3896
4040
  if (settled) return;
@@ -4293,16 +4437,16 @@ export class ObservedWaitHost {
4293
4437
  }
4294
4438
  }
4295
4439
 
4296
- private sidecarPath(taskId: string): string {
4297
- return join(this.directory, "observed", `${taskId}.json`);
4440
+ private sidecarPath(taskId: string, directory = this.directory): string {
4441
+ return join(directory, "observed", `${taskId}.json`);
4298
4442
  }
4299
4443
 
4300
4444
  private writeLaunchContext(taskId: string, context: LaunchContext): void {
4301
4445
  try {
4302
4446
  const operation = this.operationForTask(taskId);
4303
4447
  const parent = operation?.owner.kind === "parent-session";
4304
- const outboxDelivered = operation && Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision);
4305
- const pending = context.callback !== false && context.callbackDeliveredAt === undefined && !outboxDelivered;
4448
+ const pending = context.callback !== false && context.callbackDeliveredAt === undefined
4449
+ && (!parent || !this.waitDeliveredTerminalRevision(operation, context));
4306
4450
  // Publish the obligation before the sidecar: a crash may leave a pending
4307
4451
  // candidate, but cannot hide an accepted callback. Retire only after the
4308
4452
  // delivered/disabled sidecar is durable, so replay can prove suppression.
@@ -4316,9 +4460,9 @@ export class ObservedWaitHost {
4316
4460
  } catch { /* retain an obligation if the exact sidecar cannot be persisted */ }
4317
4461
  }
4318
4462
 
4319
- private readLaunchContext(taskId: string): LaunchContext | undefined {
4463
+ private readLaunchContext(taskId: string, directory = this.directory): LaunchContext | undefined {
4320
4464
  try {
4321
- const value = JSON.parse(readFileSync(this.sidecarPath(taskId), "utf8")) as Partial<LaunchContext>;
4465
+ const value = JSON.parse(readFileSync(this.sidecarPath(taskId, directory), "utf8")) as Partial<LaunchContext>;
4322
4466
  if (value.kind !== "process" && value.kind !== "watch") return undefined;
4323
4467
  return {
4324
4468
  kind: value.kind,
@@ -1,7 +1,8 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/process.ts. Do not edit directly.
2
2
  import { spawn, spawnSync } from "node:child_process";
3
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
4
- import { dirname, join } from "node:path";
3
+ import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join, win32 } from "node:path";
5
6
  /** Known Git for Windows locations; `bash -lc` needs a real bash, not the WSL shim. */
6
7
  const WINDOWS_BASH_CANDIDATES = [
7
8
  "C:\\Program Files\\Git\\bin\\bash.exe",
@@ -14,7 +15,8 @@ const WINDOWS_BASH_CANDIDATES = [
14
15
  * POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
15
16
  * on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
16
17
  * either of which would run the command inside WSL instead of Windows. Prefer
17
- * an explicit override, then Git for Windows, then a non-WSL `bash.exe` on PATH.
18
+ * an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
19
+ * `bash.exe` on PATH.
18
20
  *
19
21
  * Resolved lazily at spawn time, not module load: env-injection extensions
20
22
  * (e.g. pi-env) may apply settings.json `env` values after this module is
@@ -22,27 +24,62 @@ const WINDOWS_BASH_CANDIDATES = [
22
24
  *
23
25
  * Exposed for tests and reuse.
24
26
  */
25
- export function resolveDefaultShell() {
27
+ export function resolveDefaultShell(shellPath) {
26
28
  const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
27
29
  if (fromEnv)
28
30
  return fromEnv;
29
31
  if (process.platform !== "win32")
30
32
  return "/bin/bash";
31
- for (const candidate of WINDOWS_BASH_CANDIDATES) {
33
+ const configured = shellPath ?? readWindowsShellSetting();
34
+ const tried = [];
35
+ if (configured?.trim()) {
36
+ const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
37
+ tried.push(candidate);
38
+ try {
39
+ accessSync(candidate, constants.F_OK);
40
+ return candidate;
41
+ }
42
+ catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
43
+ }
44
+ const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
45
+ .filter((directory) => Boolean(directory))
46
+ .map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
47
+ for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
48
+ tried.push(candidate);
32
49
  if (existsSync(candidate))
33
50
  return candidate;
34
51
  }
35
- for (const dir of (process.env.PATH ?? "").split(";")) {
52
+ for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
36
53
  const trimmed = dir.trim();
37
54
  if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed))
38
55
  continue;
39
- const candidate = join(trimmed, "bash.exe");
56
+ const candidate = win32.join(trimmed, "bash.exe");
57
+ tried.push(candidate);
40
58
  if (existsSync(candidate))
41
59
  return candidate;
42
60
  }
43
- // Nothing usable found: keep the POSIX default so the failure surfaces as a
44
- // logged spawn error for the task instead of crashing the whole host process.
45
- return "/bin/bash";
61
+ throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
62
+ + "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
63
+ }
64
+ function readWindowsShellSetting() {
65
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
66
+ try {
67
+ const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
68
+ return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
69
+ }
70
+ catch {
71
+ return undefined;
72
+ }
73
+ }
74
+ /** Capture effective session settings before dispatching a Windows launch. */
75
+ export function resolveWindowsLaunchShell(pi) {
76
+ if (process.platform !== "win32")
77
+ return undefined;
78
+ const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
79
+ if (override)
80
+ return override;
81
+ const settings = pi.getSettings?.();
82
+ return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
46
83
  }
47
84
  /** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
48
85
  const TERMINATION_GRACE_MS = 2_000;
@@ -495,7 +532,8 @@ export function commandExecution(spec) {
495
532
  const [command, ...args] = spec.argv;
496
533
  return { execPath: command, execArgs: args };
497
534
  }
498
- return { execPath: resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
535
+ const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
536
+ return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
499
537
  }
500
538
  function spawnArgs(spec, detached, stdio) {
501
539
  const env = { ...process.env, ...spec.env };
@@ -1,6 +1,7 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
3
- import { dirname, join } from "node:path";
2
+ import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, win32 } from "node:path";
4
5
  import type { ChildProcess } from "node:child_process";
5
6
  import type { CommandResult, CommandSpec, StepGateFailure } from "./types.js";
6
7
 
@@ -17,7 +18,8 @@ const WINDOWS_BASH_CANDIDATES = [
17
18
  * POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
18
19
  * on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
19
20
  * either of which would run the command inside WSL instead of Windows. Prefer
20
- * an explicit override, then Git for Windows, then a non-WSL `bash.exe` on PATH.
21
+ * an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
22
+ * `bash.exe` on PATH.
21
23
  *
22
24
  * Resolved lazily at spawn time, not module load: env-injection extensions
23
25
  * (e.g. pi-env) may apply settings.json `env` values after this module is
@@ -25,22 +27,53 @@ const WINDOWS_BASH_CANDIDATES = [
25
27
  *
26
28
  * Exposed for tests and reuse.
27
29
  */
28
- export function resolveDefaultShell(): string {
30
+ export function resolveDefaultShell(shellPath?: string): string {
29
31
  const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
30
32
  if (fromEnv) return fromEnv;
31
33
  if (process.platform !== "win32") return "/bin/bash";
32
- for (const candidate of WINDOWS_BASH_CANDIDATES) {
34
+ const configured = shellPath ?? readWindowsShellSetting();
35
+ const tried: string[] = [];
36
+ if (configured?.trim()) {
37
+ const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
38
+ tried.push(candidate);
39
+ try {
40
+ accessSync(candidate, constants.F_OK);
41
+ return candidate;
42
+ } catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
43
+ }
44
+ const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
45
+ .filter((directory): directory is string => Boolean(directory))
46
+ .map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
47
+ for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
48
+ tried.push(candidate);
33
49
  if (existsSync(candidate)) return candidate;
34
50
  }
35
- for (const dir of (process.env.PATH ?? "").split(";")) {
51
+ for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
36
52
  const trimmed = dir.trim();
37
53
  if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed)) continue;
38
- const candidate = join(trimmed, "bash.exe");
54
+ const candidate = win32.join(trimmed, "bash.exe");
55
+ tried.push(candidate);
39
56
  if (existsSync(candidate)) return candidate;
40
57
  }
41
- // Nothing usable found: keep the POSIX default so the failure surfaces as a
42
- // logged spawn error for the task instead of crashing the whole host process.
43
- return "/bin/bash";
58
+ throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
59
+ + "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
60
+ }
61
+
62
+ function readWindowsShellSetting(): string | undefined {
63
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
64
+ try {
65
+ const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
66
+ return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
67
+ } catch { return undefined; }
68
+ }
69
+
70
+ /** Capture effective session settings before dispatching a Windows launch. */
71
+ export function resolveWindowsLaunchShell(pi: object): string | undefined {
72
+ if (process.platform !== "win32") return undefined;
73
+ const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
74
+ if (override) return override;
75
+ const settings = (pi as { getSettings?(): { shellPath?: unknown } }).getSettings?.();
76
+ return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
44
77
  }
45
78
 
46
79
  /** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
@@ -507,7 +540,8 @@ export function commandExecution(spec: CommandSpec): { execPath: string; execArg
507
540
  const [command, ...args] = spec.argv!;
508
541
  return { execPath: command!, execArgs: args };
509
542
  }
510
- return { execPath: resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command!] };
543
+ const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
544
+ return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command!] };
511
545
  }
512
546
 
513
547
  /** Stdio for a spawned task: stdin is always ignored; stdout/stderr are piped (collected) or ignored (redirected into the log by the child itself). */
@@ -0,0 +1,16 @@
1
+ // Generated fixed launch domain from packages/pi-better-background-tasks/src/review-settings.ts. Do not edit directly.
2
+ import { readHarnessSetting, updateHarnessSetting } from "./shared-harness-settings.domain.mjs";
3
+ export const DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES = 10;
4
+ const key = "backgroundReviewIntervalMinutes";
5
+ function validMinutes(value) {
6
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 1440;
7
+ }
8
+ export function readBackgroundReviewInterval(seams) {
9
+ const value = readHarnessSetting(key, seams);
10
+ return validMinutes(value) ? value : DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES;
11
+ }
12
+ export function saveBackgroundReviewInterval(minutes, seams) {
13
+ if (!validMinutes(minutes))
14
+ throw new Error("Background review interval must be a whole number from 1 to 1440 minutes.");
15
+ updateHarnessSetting(key, () => minutes, seams);
16
+ }
@@ -0,0 +1,18 @@
1
+ import { readHarnessSetting, updateHarnessSetting, type HarnessSettingsSeams } from "./shared-harness-settings.ts";
2
+
3
+ export const DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES = 10;
4
+ const key = "backgroundReviewIntervalMinutes";
5
+
6
+ function validMinutes(value: unknown): value is number {
7
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 1440;
8
+ }
9
+
10
+ export function readBackgroundReviewInterval(seams?: HarnessSettingsSeams): number {
11
+ const value = readHarnessSetting(key, seams);
12
+ return validMinutes(value) ? value : DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES;
13
+ }
14
+
15
+ export function saveBackgroundReviewInterval(minutes: number, seams?: HarnessSettingsSeams): void {
16
+ if (!validMinutes(minutes)) throw new Error("Background review interval must be a whole number from 1 to 1440 minutes.");
17
+ updateHarnessSetting(key, () => minutes, seams);
18
+ }