pi-better-background-tasks 0.16.0 → 0.18.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 (40) hide show
  1. package/README.md +9 -0
  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/daemon-owner.mjs +2 -1
  12. package/runtime-client/src/runtime/work-client.mjs +16 -2
  13. package/src/failures.ts +4 -2
  14. package/src/index.ts +6 -30
  15. package/src/managed-authority.ts +28 -0
  16. package/src/managed-client.ts +60 -0
  17. package/src/managed-frontend.ts +131 -0
  18. package/src/navigator-provider.ts +14 -6
  19. package/src/observed-waits.ts +286 -48
  20. package/src/output.ts +12 -0
  21. package/src/registry.ts +18 -1
  22. package/src/runtime.ts +8 -2
  23. package/src/sandbox.ts +7 -0
  24. package/src/shared-callback-batcher.ts +4 -1
  25. package/src/shared-failure-observations.ts +3 -0
  26. package/src/shared-navigator.ts +23 -5
  27. package/src/shared-operation-coordinator/assignment-observation.mjs +48 -1
  28. package/src/shared-operation-coordinator/index.ts +2 -0
  29. package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  30. package/src/shared-operation-coordinator/src/background-requests.ts +79 -0
  31. package/src/shared-operation-coordinator/src/discovery.ts +9 -0
  32. package/src/shared-operation-coordinator/src/operations.ts +6 -4
  33. package/src/shared-operation-coordinator/src/result-supervision.ts +128 -0
  34. package/src/shared-operation-coordinator/src/schema.ts +50 -1
  35. package/src/shared-operation-coordinator/src/store.ts +38 -0
  36. package/src/shared-operation-coordinator/src/subagent-launch.ts +119 -0
  37. package/src/shared-operation-coordinator/src/types.ts +6 -0
  38. package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
  39. package/src/shared-work-client.mjs +16 -2
  40. package/src/tools.ts +76 -37
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}`;
package/src/registry.ts CHANGED
@@ -12,12 +12,13 @@ const metaCache = new Map<string, BackgroundTaskMeta>();
12
12
  const indexIdsCache = new Map<string, { ids: Set<string>; signature: string }>();
13
13
  const initializedIndexes = new Set<string>();
14
14
  const metaChangedListeners = new Set<() => void>();
15
- const registryIo = { fullDirectoryReads: 0, indexDirectoryReads: 0, metadataFileReads: 0, indexRevisionChecks: 0 };
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
 
@@ -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);
@@ -223,6 +226,18 @@ export function listMetasForOrigin(origin: BackgroundTaskCallbackOrigin): Backgr
223
226
  .sort((a, b) => b.startedAt - a.startedAt);
224
227
  }
225
228
 
229
+ /** Durable pending callbacks are independent of the Navigator's terminal retention. */
230
+ export function listPendingCallbackMetasForOrigin(origin: BackgroundTaskCallbackOrigin): BackgroundTaskMeta[] {
231
+ const directory=join(baseDir(),'by-origin-callback',originKey(origin));
232
+ if(!initializedIndexes.has(directory)){
233
+ try {readFileSync(join(directory,'.initialized'));}
234
+ catch {for(const meta of listMetasForOrigin(origin))if(pendingCallback(meta))writeIndexEntry(directory,meta.id);mkdirSync(directory,{recursive:true});writeFileSync(join(directory,'.initialized'),'1');}
235
+ initializedIndexes.add(directory);
236
+ }
237
+ return readIndexIds(directory).map(readOwnedMeta).filter((meta):meta is BackgroundTaskMeta=>!!meta&&belongsToOrigin(meta,origin)&&pendingCallback(meta));
238
+ }
239
+ function pendingCallback(meta:BackgroundTaskMeta):boolean {return isTerminalStatus(meta.status)&&meta.status!=='cancelled'&&meta.callback!==false&&!meta.callbackSentAt&&!meta.callbackSuppressedAt;}
240
+
226
241
  export function listActiveMetasForOrigin(origin: BackgroundTaskCallbackOrigin): BackgroundTaskMeta[] {
227
242
  const directory = originActiveIndexDir(origin);
228
243
  ensureOriginActiveIndex(origin, directory);
@@ -288,6 +303,8 @@ function indexMeta(meta: BackgroundTaskMeta): void {
288
303
  try {
289
304
  const directory = originIndexDir(originOf(meta));
290
305
  writeIndexEntry(directory, meta.id);
306
+ const callbackDirectory=join(baseDir(),'by-origin-callback',originKey(originOf(meta)));
307
+ if(pendingCallback(meta))writeIndexEntry(callbackDirectory,meta.id);else removeIndexEntry(callbackDirectory,meta.id);
291
308
  const activeDirectory = originActiveIndexDir(originOf(meta));
292
309
  if (meta.status === "running") writeIndexEntry(activeDirectory, meta.id);
293
310
  else removeIndexEntry(activeDirectory, meta.id);
package/src/runtime.ts CHANGED
@@ -110,7 +110,7 @@ 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
114
  const { resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention } = attention;
115
115
  const watcherTimers = new Map<string, ReturnType<typeof setTimeout>>();
116
116
  const remoteSessionTimers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -298,6 +298,7 @@ function spawnTask(
298
298
  getActiveSession?: ActiveSessionProvider,
299
299
  dependencies: TaskRuntimeDependencies = {},
300
300
  ): BackgroundTaskMeta {
301
+ admission?.assert();
301
302
  // Resolved before any task directory, log, or metadata exists so a blocked
302
303
  // launch leaves nothing behind. Structured SSH must also honor launch restrictions.
303
304
  const intent = readTaskIntent(params);
@@ -314,6 +315,7 @@ function spawnTask(
314
315
  assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
315
316
  const commandLimits = backgroundExecutionLimits(sandboxPlan);
316
317
  const id = nextTaskId();
318
+ admission?.prepared?.(id);
317
319
  const logPath = logPathFor(id);
318
320
  ensureTaskDir(id);
319
321
  const remoteTask = params.ssh
@@ -611,6 +613,7 @@ function startWatchTask(
611
613
  getActiveSession?: ActiveSessionProvider,
612
614
  dependencies: TaskRuntimeDependencies = {},
613
615
  ): BackgroundTaskMeta {
616
+ admission?.assert();
614
617
  for (const [name, condition] of [["success_when", params.success_when], ["failure_when", params.failure_when]] as const) {
615
618
  const error = condition && validateCondition(condition);
616
619
  if (error) throw new Error(`${name}: ${error}`);
@@ -625,6 +628,7 @@ function startWatchTask(
625
628
  assertBackgroundExecutionAllowed(params, sandboxPlan, { remote: Boolean(params.ssh), cwd });
626
629
  const commandLimits = backgroundExecutionLimits(sandboxPlan);
627
630
  const id = nextTaskId();
631
+ admission?.prepared?.(id);
628
632
  const now = Date.now();
629
633
  const timeoutSeconds = resolveWatchTimeoutSeconds(params.timeout_seconds);
630
634
  const remoteTask = params.ssh
@@ -1363,7 +1367,9 @@ async function notifyTerminal(
1363
1367
  const pending = terminalFailureAttention(latest.id);
1364
1368
  const label = latest.name ? `${latest.name} (${latest.id})` : latest.id;
1365
1369
  const facts = formatCallbackFacts(latest);
1366
- getCallbackBatcher(pi).enqueue({
1370
+ const enqueue = (event: Parameters<ReturnType<typeof getCallbackBatcher>["enqueue"]>[0]) => deliverCompletion ? deliverCompletion(latest.callbackOrigin, event) : getCallbackBatcher(pi).enqueue(event);
1371
+ enqueue({
1372
+ receiptId: `background-legacy:${latest.id}:${latest.endedAt ?? latest.startedAt}`,
1367
1373
  source: "background-task",
1368
1374
  id: latest.id,
1369
1375
  label,
package/src/sandbox.ts CHANGED
@@ -901,3 +901,10 @@ function blocked(plan: ForegroundSandboxPlan & { confined: true }, detail: strin
901
901
  detail,
902
902
  );
903
903
  }
904
+
905
+ /** Fixed server adapter clears only its own scope mirror before publishing another captured grant. */
906
+ export function clearForegroundSandboxPolicy(pi: unknown): void {
907
+ observeForegroundSandboxPolicy(pi);
908
+ const events=eventBusOf(pi), mirror=events && mirrors.get(events);
909
+ if(mirror){mirror.policy=undefined;mirror.error=undefined;mirror.processAccess="off";mirror.mainConfined=false;}
910
+ }
@@ -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;
@@ -743,7 +745,8 @@ export function createCallbackBatcher(
743
745
  urgentInFlight.add(key);
744
746
  try {
745
747
  const handoff = host.sendMessage(
746
- { customType: event.customType, content: formatUrgentCallback(event, { maxBytes }), display: true },
748
+ { customType: event.customType, content: formatUrgentCallback(event, { maxBytes }), display: true,
749
+ ...(event.receiptId ? { details: { urgentEventId: event.receiptId } } : {}) },
747
750
  { deliverAs: "followUp", triggerTurn: true },
748
751
  );
749
752
  if (isPromiseLike(handoff)) {
@@ -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"); }
@@ -64,6 +64,7 @@ export type BackgroundWorkProvider = {
64
64
  showSection?(rows: BackgroundWorkRow[], now: number): boolean;
65
65
  parentRow?(now: number): BackgroundWorkRow | null;
66
66
  listRows(now: number): BackgroundWorkRow[];
67
+ prepareDetail?(id: string, options?: {logTailLines?: number}): void;
67
68
  detail(id: string, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null;
68
69
  armCloseLabel(row: BackgroundWorkRow): string;
69
70
  close(id: string): BackgroundWorkCloseOutcome;
@@ -728,6 +729,11 @@ function singleLine(value: unknown): string {
728
729
  return String(value ?? "").replace(/[\r\n\t]+/g, " ").replace(/ {2,}/g, " ").trim();
729
730
  }
730
731
 
732
+ function prepareDetail(navigatorId: string, options?: {logTailLines?: number}): void {
733
+ const {providerId,id}=splitRowKey(navigatorId);
734
+ try {state().providers.get(providerId)?.prepareDetail?.(id,options);}catch {/* observation failure retains cached detail */}
735
+ }
736
+
731
737
  function detailFor(navigatorId: string, now = Date.now(), options?: { logTailLines?: number }): BackgroundWorkDetail | null {
732
738
  const { providerId, id } = splitRowKey(navigatorId);
733
739
  const provider = state().providers.get(providerId);
@@ -989,10 +995,12 @@ function createOverlayComponent(
989
995
  const overlayState: OverlayState = { rows: initialRows, selected: 0 };
990
996
  let logTailRows: number = DEFAULT_LOG_TAIL_ROWS;
991
997
  const expandedSections = new Set<string>();
998
+ const initializedSections = new Set<string>();
992
999
  let detailId: string = initialDetailId;
993
1000
  const initialRow = initialRows.find((row) => row.navigatorId === detailId);
1001
+ prepareDetail(detailId,{logTailLines:logTailRows});
994
1002
  let detail: BackgroundWorkDetail | null = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? (initialRow ? fallbackDetail(initialRow) : null);
995
- applyDefaultExpandedSections(detail, expandedSections);
1003
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
996
1004
  {
997
1005
  const idx = overlayState.rows.findIndex((row) => row.navigatorId === detailId);
998
1006
  if (idx >= 0) overlayState.selected = idx;
@@ -1028,6 +1036,7 @@ function createOverlayComponent(
1028
1036
  const detailScheduler = createRenderScheduler(() => {
1029
1037
  if (closed) return;
1030
1038
  detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1039
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1031
1040
  requestRender();
1032
1041
  startDetailTimer();
1033
1042
  });
@@ -1079,8 +1088,10 @@ function createOverlayComponent(
1079
1088
  clearCloseArm();
1080
1089
  detailId = row.navigatorId;
1081
1090
  expandedSections.clear();
1091
+ initializedSections.clear();
1092
+ prepareDetail(detailId,{logTailLines:logTailRows});
1082
1093
  detail = detailFor(row.navigatorId, Date.now(), { logTailLines: logTailRows }) ?? fallbackDetail(row);
1083
- applyDefaultExpandedSections(detail, expandedSections);
1094
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1084
1095
  startDetailTimer();
1085
1096
  requestRender();
1086
1097
  }
@@ -1251,12 +1262,15 @@ function createOverlayComponent(
1251
1262
  const key = data === "m" || data === "M" ? "m" : "ctrl+s";
1252
1263
  if (!row || !provider?.handleDetailInput?.(row.id, key)) return;
1253
1264
  detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1265
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1254
1266
  refreshMainListWidget();
1255
1267
  requestRender();
1256
1268
  }
1257
1269
  else if (data === "l" || data === "L") {
1258
1270
  logTailRows = cycleLogTailRows(logTailRows);
1271
+ prepareDetail(detailId,{logTailLines:logTailRows});
1259
1272
  if (detailId) detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1273
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1260
1274
  requestRender();
1261
1275
  }
1262
1276
  else if (deps.matchKey(data, "escape")) {
@@ -1266,9 +1280,9 @@ function createOverlayComponent(
1266
1280
  /** Observation arrival updates this row without resetting selection or folded sections. */
1267
1281
  refreshDetail() {
1268
1282
  if (closed) return;
1269
- const wasLoading = detail?.status === "rebuilding";
1283
+ prepareDetail(detailId,{logTailLines:logTailRows});
1270
1284
  detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1271
- if (wasLoading) applyDefaultExpandedSections(detail, expandedSections);
1285
+ applyDefaultExpandedSections(detail, expandedSections, initializedSections);
1272
1286
  startDetailTimer();
1273
1287
  requestRender();
1274
1288
  },
@@ -1502,8 +1516,12 @@ function firstToggleableSectionId(detail: BackgroundWorkDetail | null | undefine
1502
1516
  return detail && isFoldableEvidence(detail) ? EVIDENCE_SECTION_ID : undefined;
1503
1517
  }
1504
1518
 
1505
- function applyDefaultExpandedSections(detail: BackgroundWorkDetail | null, expandedSections: Set<string>): void {
1519
+ function applyDefaultExpandedSections(detail: BackgroundWorkDetail | null, expandedSections: Set<string>, initializedSections: Set<string>): void {
1506
1520
  for (const section of detail?.foldedSections ?? []) {
1521
+ if (initializedSections.has(section.id)) continue;
1522
+ // Details can arrive after a running row's fallback. Initialize each section
1523
+ // on first arrival, then preserve the user's choice across observations.
1524
+ initializedSections.add(section.id);
1507
1525
  if (section.expandedByDefault) expandedSections.add(section.id);
1508
1526
  }
1509
1527
  }
@@ -47,6 +47,7 @@ export function readAssignmentWaits(path, owner, connection) {
47
47
  export function createAssignmentReader(path) {
48
48
  let db;
49
49
  let identity;
50
+ let snapshot = false;
50
51
  const statements = new Map();
51
52
  return {
52
53
  revision() {
@@ -54,6 +55,7 @@ export function createAssignmentReader(path) {
54
55
  const stat = statSync(path, { bigint: true });
55
56
  const next = `${stat.dev}:${stat.ino}`;
56
57
  if (identity !== next) {
58
+ if (snapshot) throw new Error("Coordinator identity changed during observation");
57
59
  db?.close();
58
60
  db = undefined;
59
61
  statements.clear();
@@ -63,6 +65,24 @@ export function createAssignmentReader(path) {
63
65
  db ??= new DatabaseSync(path, { readOnly: true });
64
66
  return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
65
67
  },
68
+ connection(refresh = true) { if (refresh) this.revision(); return db; },
69
+
70
+ beginSnapshot() {
71
+ this.revision();
72
+ if (snapshot) throw new Error("Coordinator snapshot already open");
73
+ db.exec("BEGIN");
74
+ snapshot = true;
75
+ const release = () => {
76
+ if (!snapshot) return;
77
+ try { db.exec("ROLLBACK"); } finally { snapshot = false; }
78
+ };
79
+ try {
80
+ // Pin the WAL read view before recording its revision; other writers keep advancing.
81
+ db.prepare("SELECT count(*) FROM sqlite_schema").get();
82
+ return { revision: this.revision(), release };
83
+ } catch (error) { release(); throw error; }
84
+ },
85
+
66
86
  read(owner) {
67
87
  try {
68
88
  this.revision();
@@ -98,6 +118,33 @@ export function createAssignmentReader(path) {
98
118
  return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
99
119
  } catch { return undefined; }
100
120
  },
101
- close() { db?.close(); db = undefined; statements.clear(); identity = undefined; },
121
+ upgradeObligations() {
122
+ try { this.revision(); } catch (error) {
123
+ if (error.code === "ENOENT") return [];
124
+ throw error;
125
+ }
126
+ const version = db.prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value;
127
+ if (!["1", "2", "3", "4"].includes(version)) throw new Error("Unsupported coordinator schema during upgrade");
128
+ const obligations = db.prepare("SELECT operation_id, task_id, observer_kind FROM operations WHERE phase='running' AND terminal_revision=0").all()
129
+ .map(row => ({ kind: "unsettled-operation", id: row.task_id, operationId: row.operation_id, observer: row.observer_kind }));
130
+ const reasons = db.prepare("SELECT claim_id AS id, state FROM resume_claims WHERE state IN ('claimed', 'published')").all()
131
+ .map(row => ({ kind: "resume-claim", id: row.id, state: row.state }));
132
+ for (const row of db.prepare("SELECT wait_id, generation, phase FROM waits WHERE owner_kind='worker-conversation' AND phase NOT IN ('consumed', 'cancelled') AND dispatch_disarmed=0").all()) {
133
+ reasons.push({ kind: "worker-wait", id: row.wait_id, generation: row.generation, phase: row.phase });
134
+ }
135
+ if (db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_launch_intents'").get()) {
136
+ for (const row of db.prepare("SELECT owner, request_key, attempts FROM subagent_launch_intents WHERE state='accepted'").all()) {
137
+ reasons.push({ kind: "launch-intent", id: row.request_key, owner: row.owner, attempts: JSON.parse(row.attempts).map(attempt => attempt.id) });
138
+ }
139
+ }
140
+ for (const row of db.prepare("SELECT value FROM coordinator_state WHERE key LIKE 'background-request-v1:%'").all()) {
141
+ const request = JSON.parse(row.value);
142
+ if (request.state !== 'returned') reasons.push({kind:'background-request', id:request.key, owner:request.owner});
143
+ }
144
+ return [...obligations, ...reasons];
145
+ },
146
+
147
+ close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
148
+
102
149
  };
103
150
  }
@@ -118,3 +118,5 @@ export { StoreError, isStoreError } from "./src/errors.ts";
118
118
  export type { StoreErrorCode } from "./src/errors.ts";
119
119
  export { openStore, ownerDiff } from "./src/store.ts";
120
120
  export type { Store } from "./src/store.ts";
121
+
122
+ export type { ParentCallbackScope, ParentCallbackPage, RecentBackgroundTerminalPage } from './src/background-parent-callbacks.ts';
@@ -0,0 +1,68 @@
1
+ // Generated from packages/operation-coordinator/src/background-parent-callbacks.ts. Do not edit directly.
2
+ /** Pending parent notifications are obligations, independent of UI retention. */
3
+ import { bumpChangeRevision } from './discovery.ts';
4
+ import { mapOperation } from './rows.ts';
5
+ import { getRow, getRows, run, type StoreContext } from './sqlite.ts';
6
+ import { requireBoolean, requireCounter, requireId, requirePath } from './validate.ts';
7
+ import type { OperationRecord } from './types.ts';
8
+
9
+ export interface ParentCallbackScope { sessionId: string; workspace: string }
10
+ export interface ParentCallbackPage { after?: string; limit?: number }
11
+ export interface RecentBackgroundTerminalPage {
12
+ since: number;
13
+ after?: { terminalAt: number; operationId: string };
14
+ limit?: number;
15
+ owner?: ParentCallbackScope;
16
+ }
17
+ const pageSize = (limit = 256) => Math.max(1, Math.min(256, requireCounter('limit', limit)));
18
+ const scopeValues = (scope: ParentCallbackScope) => [requirePath('workspace', scope.workspace), requireId('sessionId', scope.sessionId)] as const;
19
+
20
+ export function setParentCallbackPending(ctx: StoreContext, taskId: string, pending: boolean): boolean {
21
+ taskId = requireId('taskId', taskId);
22
+ pending = requireBoolean('pending', pending);
23
+ return ctx.transaction(() => {
24
+ const operation = getRow(ctx, "SELECT operation_id, owner_workspace, owner_session_id FROM operations WHERE task_id=? AND owner_kind='parent-session' AND observer_kind='local-supervisor'", taskId);
25
+ if (!operation) return false;
26
+ const changed = pending
27
+ ? run(ctx, `INSERT OR IGNORE INTO background_parent_callbacks(operation_id,owner_kind,owner_workspace,owner_session_id)
28
+ VALUES (?,'parent-session',?,?)`, String(operation.operation_id), String(operation.owner_workspace), String(operation.owner_session_id))
29
+ : run(ctx, 'DELETE FROM background_parent_callbacks WHERE operation_id=?', String(operation.operation_id));
30
+ if (changed > 0) bumpChangeRevision(ctx);
31
+ return changed > 0;
32
+ });
33
+ }
34
+
35
+ export function listPendingParentCallbacks(ctx: StoreContext, scope: ParentCallbackScope, options: ParentCallbackPage = {}): OperationRecord[] {
36
+ return getRows(ctx, `SELECT o.* FROM background_parent_callbacks p JOIN operations o ON o.operation_id=p.operation_id
37
+ WHERE p.owner_kind='parent-session' AND p.owner_workspace=? AND p.owner_session_id=? AND p.operation_id>? AND o.terminal_revision>0
38
+ ORDER BY p.operation_id LIMIT ?`, ...scopeValues(scope), options.after === undefined ? '' : requireId('after', options.after), pageSize(options.limit)).map(mapOperation);
39
+ }
40
+
41
+ export function listRecentBackgroundTerminals(ctx: StoreContext, options: RecentBackgroundTerminalPage): OperationRecord[] {
42
+ const params: Array<string|number> = [requireCounter('since', options.since)];
43
+ let where = "observer_kind='local-supervisor' AND terminal_revision>0 AND terminal_at>=?";
44
+ if (options.owner) { where += " AND owner_kind='parent-session' AND owner_workspace=? AND owner_session_id=?"; params.push(...scopeValues(options.owner)); }
45
+ if (options.after) { where += ' AND (terminal_at,operation_id)>(?,?)'; params.push(requireCounter('after.terminalAt', options.after.terminalAt), requireId('after.operationId', options.after.operationId)); }
46
+ params.push(pageSize(options.limit));
47
+ return getRows(ctx, `SELECT * FROM operations WHERE ${where} ORDER BY terminal_at,operation_id LIMIT ?`, ...params).map(mapOperation);
48
+ }
49
+
50
+ /** Call from the canonical manager in bounded batches, yielding between pages. */
51
+ export function seedPendingParentCallbacks(ctx: StoreContext, options: { limit?: number } = {}): { done: boolean; seeded: number } {
52
+ return ctx.transaction(() => {
53
+ const migration = getRow(ctx, 'SELECT * FROM background_parent_callback_migration WHERE singleton=1')!;
54
+ if (Number(migration.done)) return { done: true, seeded: 0 };
55
+ const limit = pageSize(options.limit);
56
+ const rows = getRows(ctx, `SELECT operation_id,owner_workspace,owner_session_id FROM operations
57
+ WHERE owner_kind='parent-session' AND observer_kind='local-supervisor' AND operation_id>? AND operation_id<=?
58
+ ORDER BY operation_id LIMIT ?`, String(migration.after_operation_id), String(migration.through_operation_id), limit);
59
+ let seeded = 0;
60
+ for (const row of rows) seeded += Number(run(ctx, `INSERT OR IGNORE INTO background_parent_callbacks(operation_id,owner_kind,owner_workspace,owner_session_id)
61
+ VALUES (?,'parent-session',?,?)`, String(row.operation_id), String(row.owner_workspace), String(row.owner_session_id)));
62
+ const after = rows.length ? String(rows.at(-1)!.operation_id) : String(migration.after_operation_id);
63
+ const done = rows.length < limit || after === migration.through_operation_id;
64
+ run(ctx, 'UPDATE background_parent_callback_migration SET after_operation_id=?,done=? WHERE singleton=1', after, done ? 1 : 0);
65
+ if (seeded) bumpChangeRevision(ctx);
66
+ return { done, seeded };
67
+ });
68
+ }
@@ -0,0 +1,79 @@
1
+ // Generated from packages/operation-coordinator/src/background-requests.ts. Do not edit directly.
2
+ import { createHash } from 'node:crypto';
3
+ import type { StoreContext } from './sqlite.ts';
4
+ export interface BackgroundRequest {
5
+ owner: string;
6
+ key: string;
7
+ digest: string;
8
+ state: 'accepted' | 'dispatching' | 'returned';
9
+ operations: Array<{
10
+ operationId: string;
11
+ taskId: string;
12
+ token: string;
13
+ }>;
14
+ result?: unknown;
15
+ }
16
+ const prefix = 'background-request-v1:';
17
+ // A partial index excludes returned history. CASE protects other coordinator
18
+ // records and makes corrupt request rows visible to recovery rather than hiding them.
19
+ const pendingPredicate = "key GLOB 'background-request-v1:*' AND CASE WHEN json_valid(value) THEN COALESCE(json_extract(value, '$.state'), '') != 'returned' ELSE 1 END";
20
+ export const BACKGROUND_PENDING_QUERY = `SELECT value FROM coordinator_state INDEXED BY background_requests_pending WHERE ${pendingPredicate} ORDER BY key LIMIT ?`;
21
+ function storageKey(owner: string, key: string) { return prefix + createHash('sha256').update(JSON.stringify([owner, key])).digest('hex'); }
22
+ export class BackgroundRequests {
23
+ private context: StoreContext;
24
+ private alive: () => void;
25
+ constructor(context: StoreContext, alive: () => void) {
26
+ this.context = context;
27
+ this.alive = alive;
28
+ alive();
29
+ context.db.exec(`CREATE INDEX IF NOT EXISTS background_requests_pending ON coordinator_state(key) WHERE ${pendingPredicate}`);
30
+ }
31
+ read(owner: string, key: string): BackgroundRequest | undefined {
32
+ this.alive();
33
+ const row = this.context.db.prepare('SELECT value FROM coordinator_state WHERE key=?').get(storageKey(owner, key));
34
+ return row ? JSON.parse(String(row.value)) : undefined;
35
+ }
36
+ private write(value: BackgroundRequest) {
37
+ this.context.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(storageKey(value.owner, value.key), JSON.stringify(value));
38
+ }
39
+ accept(owner: string, key: string, digest: string) {
40
+ this.alive();
41
+ return this.context.transaction(() => {
42
+ const prior = this.read(owner, key);
43
+ if (prior) {
44
+ if (prior.digest !== digest)
45
+ throw new Error('request-conflict: Background request key changed content');
46
+ return { prior: true, record: prior };
47
+ }
48
+ const record: BackgroundRequest = { owner, key, digest, state: 'accepted', operations: [] };
49
+ this.write(record);
50
+ return { prior: false, record };
51
+ });
52
+ }
53
+ dispatch(owner: string, key: string) { this.update(owner, key, value => { if (value.state !== 'accepted')
54
+ throw new Error('Background request already dispatched'); value.state = 'dispatching'; }); }
55
+ operation(owner: string, key: string, operation: BackgroundRequest['operations'][number]) {
56
+ this.update(owner, key, value => {
57
+ if (value.state !== 'dispatching')
58
+ throw new Error('Background request is not dispatching');
59
+ if (value.operations.some(prior => prior.operationId === operation.operationId))
60
+ throw new Error('Background operation already prepared');
61
+ value.operations.push(operation);
62
+ });
63
+ }
64
+ finish(owner: string, key: string, result: unknown) { this.update(owner, key, value => { value.result = result; value.state = 'returned'; }); }
65
+ private update(owner: string, key: string, change: (value: BackgroundRequest) => void) {
66
+ this.alive();
67
+ this.context.transaction(() => { const value = this.read(owner, key); if (!value)
68
+ throw new Error('Background request not admitted'); change(value); this.write(value); });
69
+ }
70
+ hasPending(): boolean {
71
+ this.alive();
72
+ return Boolean(this.context.db.prepare(`SELECT 1 FROM coordinator_state INDEXED BY background_requests_pending WHERE ${pendingPredicate} LIMIT 1`).get());
73
+ }
74
+ pending(limit = 128): BackgroundRequest[] {
75
+ this.alive();
76
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 128) throw new Error('Background recovery batch limit must be 1..128');
77
+ return this.context.db.prepare(BACKGROUND_PENDING_QUERY).all(limit).map(row => JSON.parse(String(row.value)));
78
+ }
79
+ }
@@ -48,6 +48,14 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
48
48
  return readClaim(ctx, requireId("scope", scope));
49
49
  }
50
50
 
51
+ /** Read scope transfer and its discovery claim from one SQLite snapshot. */
52
+ export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null } {
53
+ scope = requireId("scope", scope);
54
+ const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed
55
+ FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope)!;
56
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row) };
57
+ }
58
+
51
59
  export function tryClaimDiscovery(
52
60
  ctx: StoreContext,
53
61
  input: TryClaimDiscoveryInput,
@@ -62,6 +70,7 @@ export function tryClaimDiscovery(
62
70
  const expectedToken = input.expected === null ? null : requireId("expected.token", input.expected.token);
63
71
 
64
72
  return ctx.transaction(() => {
73
+ if (getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", "result-scope-v1:" + scope)) return null;
65
74
  const current = readClaim(ctx, scope);
66
75
  if (input.expected === null) {
67
76
  if (current) return null;
@@ -63,6 +63,8 @@ function normalizeSupervision(value: unknown): SupervisionIdentity | null {
63
63
  const supervision = value as Partial<SupervisionIdentity>;
64
64
  return {
65
65
  hostId: requireId("supervision.hostId", supervision.hostId),
66
+ ...(supervision.resultScope === undefined ? {} : { resultScope: requireId("supervision.resultScope", supervision.resultScope) }),
67
+ ...(supervision.resultAdapter === 1 ? { resultAdapter: 1 as const } : {}),
66
68
  runnerId: supervision.runnerId === undefined || supervision.runnerId === null
67
69
  ? null
68
70
  : requireId("supervision.runnerId", supervision.runnerId),
@@ -433,8 +435,8 @@ export function listOperations(
433
435
  params.push(requireId("taskId", filter.taskId));
434
436
  }
435
437
  const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
436
- return getRows(ctx, `SELECT * FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
437
- .map(mapOperation);
438
+ return getRows(ctx, `SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
439
+ .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
438
440
  }
439
441
 
440
442
  /** Running operations assigned to one supervising host, using the phase/host index. */
@@ -444,9 +446,9 @@ export function listRunningSupervisedBy(
444
446
  ): OperationRecord[] {
445
447
  return getRows(
446
448
  ctx,
447
- "SELECT * FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id",
449
+ "SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id",
448
450
  requireId("hostId", hostId),
449
- ).map(mapOperation);
451
+ ).map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
450
452
  }
451
453
 
452
454
  function listOutboxForRevision(