pi-better-background-tasks 0.21.1 → 0.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.21.1",
3
+ "version": "0.21.2",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"50cb9496e6037883197cc2f748546323d1ca69e95f8a5a9677a4bb309687e733","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.1","contentId":"0fd591f51ac98c9d1d4f9611a46d08da13c86851382d2109a909fc004b567943"},"sha256":"6a47351f9c0eec3516ba566c7a885ff3cc762bba05e33f5305db7a56fabf1982"}
1
+ {"build":{"format":1,"sourceDigest":"c02d951603064af3401fd640dfd2c05b18ae97299509a55db82d58aa5c69a2f0","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.2","contentId":"d72a5f1211f34ae97dc84b1c891a38714ab7c41c429332549d4a115af142cd9c"},"sha256":"0286673fe48ab8553727b4794b39721ddb96573b9c31b885918ee4d1df0c1a68"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"50cb9496e6037883197cc2f748546323d1ca69e95f8a5a9677a4bb309687e733","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.1","contentId":"a12968284314d7c54f2656ec7d1b1289e85535aea95b0203d92b5c0a2687347f"},"sha256":"4315671ab6da4d3ab3398143388c6ea5041e496ea9a757ee08021bf29e9f725c"}
1
+ {"build":{"format":1,"sourceDigest":"c02d951603064af3401fd640dfd2c05b18ae97299509a55db82d58aa5c69a2f0","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.2","contentId":"0357f903ca7cbcc813194f224e3e1816c0abade6322e8d1321f4b07c8df4a08c"},"sha256":"3f9e9896c4c7b46b6a147e618883616aef287eb5c5a54cb214175354a4741d9b"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"50cb9496e6037883197cc2f748546323d1ca69e95f8a5a9677a4bb309687e733","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.1","contentId":"9f474bd45ac5315217d6f20898e6b845c707172cc6a849e96c8e38bdc69803f2"},"sha256":"40ddd825229477fc75a2f8fdb6153d8a064b32c825e88897b74545b80e9d05a8"}
1
+ {"build":{"format":1,"sourceDigest":"c02d951603064af3401fd640dfd2c05b18ae97299509a55db82d58aa5c69a2f0","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.2","contentId":"9f205935cb4aee5fb4d817661f86939716c909213b47775c2dcf83f9755122d1"},"sha256":"e02abd34422fba070bc44c59ab190ee61f69b9f2a6c9d926e64485461bfb48ad"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"50cb9496e6037883197cc2f748546323d1ca69e95f8a5a9677a4bb309687e733","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.1","contentId":"3623fb69d87cbdcf92f946d5b34d89265136f9619a0f713d9aba52883ec882a5"},"sha256":"9729edc6beff7b4b5c547811d1a5142d765a04524538aef519faabc3330d9641"}
1
+ {"build":{"format":1,"sourceDigest":"c02d951603064af3401fd640dfd2c05b18ae97299509a55db82d58aa5c69a2f0","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.2","contentId":"36ab9cbfc092b10d96f6d83473057fd4552929ff53ec3972caee1ed83ef50242"},"sha256":"2cfa925caa8783e13a9b92dbe0e8fcac28bbe048978bbdbb08c9f4de78ab2bf1"}
@@ -882,6 +882,9 @@ export function supervisorTerminalPublication(operation: OperationRecord, inspec
882
882
  };
883
883
  }
884
884
 
885
+ type CallbackPageCursor = { revision: number; after?: string };
886
+ type CallbackRecoveryState = { revision: number; branch: string; delivery?: CallbackPageCursor; claims?: CallbackPageCursor };
887
+
885
888
  export class ObservedWaitHost {
886
889
  readonly service: BackgroundOperationService;
887
890
  private store?: Store;
@@ -985,8 +988,8 @@ export class ObservedWaitHost {
985
988
  private authorityPassCache?: Map<string, "live" | "dead" | "unknown">;
986
989
  /** Running operations this follower is currently assigned to supervise. */
987
990
  private readonly followerRunningTasks = new Set<string>();
988
- private readonly unscopedCallbackRecovery = { revision: -1, branch: "", delivery: undefined as string | undefined, claims: undefined as string | undefined };
989
- private readonly callbackRecoveryScopes = new Map<string, { revision: number; delivery?: string; claims?: string; branch: string }>();
991
+ private readonly unscopedCallbackRecovery: CallbackRecoveryState = { revision: -1, branch: "" };
992
+ private readonly callbackRecoveryScopes = new Map<string, CallbackRecoveryState>();
990
993
  private recoveryScopeState() {
991
994
  if (!this.activeOrigin) return this.unscopedCallbackRecovery;
992
995
  // Concurrent foregrounds can retain different branch snapshots of one session.
@@ -1001,9 +1004,9 @@ export class ObservedWaitHost {
1001
1004
  private get lastChangeRevision() { return this.recoveryScopeState().revision; }
1002
1005
  private set lastChangeRevision(value: number) { this.recoveryScopeState().revision = value; }
1003
1006
  private get pendingCallbackCursor() { return this.recoveryScopeState().delivery; }
1004
- private set pendingCallbackCursor(value: string | undefined) { this.recoveryScopeState().delivery = value; }
1007
+ private set pendingCallbackCursor(value: CallbackPageCursor | undefined) { this.recoveryScopeState().delivery = value; }
1005
1008
  private get pendingClaimCursor() { return this.recoveryScopeState().claims; }
1006
- private set pendingClaimCursor(value: string | undefined) { this.recoveryScopeState().claims = value; }
1009
+ private set pendingClaimCursor(value: CallbackPageCursor | undefined) { this.recoveryScopeState().claims = value; }
1007
1010
  private get activeBranchSignature() { return this.recoveryScopeState().branch; }
1008
1011
  private set activeBranchSignature(value: string) { this.recoveryScopeState().branch = value; }
1009
1012
  private lastOwnedTerminalAt = 0;
@@ -1172,13 +1175,20 @@ export class ObservedWaitHost {
1172
1175
  }
1173
1176
  }
1174
1177
 
1175
- private activeParentTerminalOperations(claims = false): OperationRecord[] {
1178
+ private activeParentTerminalOperations(claims = false, knownRevision?: number): OperationRecord[] {
1176
1179
  const origin = this.activeOrigin;
1177
1180
  if (!this.store || !origin?.sessionId) return [];
1178
- const page = this.store.listPendingParentCallbacks({ sessionId: origin.sessionId, workspace: origin.cwd },
1179
- { after: claims ? this.pendingClaimCursor : this.pendingCallbackCursor, limit: 256 });
1180
- const next = page.length === 256 ? page.at(-1)!.operationId : undefined;
1181
- if (claims) this.pendingClaimCursor = next; else this.pendingCallbackCursor = next;
1181
+ const scope = { sessionId: origin.sessionId, workspace: origin.cwd };
1182
+ const revision = knownRevision ?? this.store.parentRecoveryRevision(scope);
1183
+ const state = this.recoveryScopeState();
1184
+ const key = claims ? "claims" : "delivery";
1185
+ const cursor = state[key];
1186
+ const startRevision = cursor?.after ? cursor.revision : revision;
1187
+ const page = this.store.listPendingParentCallbacks(scope, { after: cursor?.after, limit: 256 });
1188
+ if (page.length === 256) state[key] = { after: page.at(-1)!.operationId, revision: startRevision };
1189
+ // Finish the current sweep before revisiting callbacks inserted behind its cursor.
1190
+ else if (revision !== startRevision) state[key] = { revision };
1191
+ else delete state[key];
1182
1192
  return page;
1183
1193
  }
1184
1194
 
@@ -1404,7 +1414,7 @@ export class ObservedWaitHost {
1404
1414
 
1405
1415
  /**
1406
1416
  * A follower does not scan foreign operations. It refreshes the exact active
1407
- * owner's terminal records only when the shared change revision advances, so
1417
+ * owner's terminal records only when that parent's recovery revision advances, so
1408
1418
  * callback recovery stays correct without multiplying the running-set scan.
1409
1419
  */
1410
1420
  private reconcileOwnerChanges(): void {
@@ -1415,18 +1425,19 @@ export class ObservedWaitHost {
1415
1425
  if (!sessionId) return;
1416
1426
  let revision: number;
1417
1427
  try {
1418
- revision = store.getChangeRevision();
1428
+ revision = store.parentRecoveryRevision({ workspace: ctx.cwd, sessionId });
1419
1429
  } catch {
1420
1430
  return;
1421
1431
  }
1422
1432
  if (revision === this.lastChangeRevision && !this.pendingCallbackCursor) return;
1423
- this.lastChangeRevision = revision;
1424
1433
  let operations: OperationRecord[];
1425
1434
  try {
1426
- operations = this.activeParentTerminalOperations();
1435
+ operations = this.activeParentTerminalOperations(false, revision);
1427
1436
  } catch {
1437
+ this.lastChangeRevision = -1;
1428
1438
  return;
1429
1439
  }
1440
+ this.lastChangeRevision = revision;
1430
1441
  let newest = this.lastOwnedTerminalAt;
1431
1442
  let visibleOwner: OwnerIdentity | undefined;
1432
1443
  for (const operation of operations) {
@@ -35,6 +35,39 @@ export function ensureAssignmentChanges(ctx: StoreContext): void {
35
35
  const records = action === "UPDATE" ? ["OLD", "NEW"] : [action === "DELETE" ? "OLD" : "NEW"];
36
36
  ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS assignment_change_${table}_${action.toLowerCase()} AFTER ${action} ON ${table} BEGIN ${records.map(r => `INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace) ${select(r)};`).join(" ")} END;`);
37
37
  }
38
+ // An idle scan may span several pages. Insertions and authority transfers can
39
+ // put a new candidate behind its cursor; deleting completed work cannot.
40
+ const advanceCleanup = `INSERT INTO coordinator_state VALUES ('server-assignment-cleanup-revision', '1')
41
+ ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1;`;
42
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS server_cleanup_added AFTER INSERT ON assignment_cleanup_pending
43
+ WHEN NEW.supervision_host_id GLOB 'server:*' BEGIN ${advanceCleanup} END;
44
+ CREATE TRIGGER IF NOT EXISTS server_cleanup_transferred AFTER UPDATE OF supervision_host_id ON assignment_cleanup_pending
45
+ WHEN NEW.supervision_host_id GLOB 'server:*' AND NEW.supervision_host_id IS NOT OLD.supervision_host_id
46
+ BEGIN ${advanceCleanup} END;`);
47
+ // The result grant can arrive after the assignment already ended.
48
+ for (const event of ["INSERT", "UPDATE"]) ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS server_cleanup_grant_${event}
49
+ AFTER ${event} ON coordinator_state WHEN NEW.key GLOB 'result-supervision-v1:*' AND EXISTS (
50
+ SELECT 1 FROM assignment_cleanup_pending WHERE operation_id=substr(NEW.key,length('result-supervision-v1:')+1)
51
+ AND supervision_host_id GLOB 'server:*') BEGIN ${advanceCleanup} END`);
52
+ // A foreground polls the branch views of one parent. Keep their durable
53
+ // recovery revision even after older entries roll out of the change journal.
54
+ ctx.db.exec(`CREATE TABLE IF NOT EXISTS background_recovery_scopes (
55
+ workspace TEXT NOT NULL, session_id TEXT NOT NULL, revision INTEGER NOT NULL,
56
+ PRIMARY KEY(workspace,session_id)) WITHOUT ROWID`);
57
+ const recoverySources = [
58
+ ["operation_added", "INSERT ON operations", "NEW.owner_kind='parent-session'", "NEW.owner_workspace", "NEW.owner_session_id"],
59
+ ["operation_changed", "UPDATE OF terminal_revision, supervision_host_id ON operations",
60
+ "NEW.owner_kind='parent-session' AND (NEW.terminal_revision<>OLD.terminal_revision OR NEW.supervision_host_id IS NOT OLD.supervision_host_id)", "NEW.owner_workspace", "NEW.owner_session_id"],
61
+ ["callback_added", "INSERT ON background_parent_callbacks", "1", "NEW.owner_workspace", "NEW.owner_session_id"],
62
+ ["callback_removed", "DELETE ON background_parent_callbacks", "1", "OLD.owner_workspace", "OLD.owner_session_id"],
63
+ ["delivery_added", "INSERT ON outbox_events", "NEW.event_type='dependency-ready' AND NEW.state='pending' AND NEW.recipient_kind='parent-session'", "NEW.recipient_workspace", "NEW.recipient_session_id"],
64
+ ["delivery_released", "UPDATE OF state ON outbox_events", "NEW.event_type='dependency-ready' AND NEW.state='pending' AND OLD.state<>'pending' AND NEW.recipient_kind='parent-session'", "NEW.recipient_workspace", "NEW.recipient_session_id"],
65
+ ];
66
+ for (const [name, event, condition, workspace, session] of recoverySources) {
67
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS background_recovery_${name} AFTER ${event} WHEN ${condition}
68
+ BEGIN INSERT INTO background_recovery_scopes VALUES(${workspace},${session},1)
69
+ ON CONFLICT(workspace,session_id) DO UPDATE SET revision=revision+1; END`);
70
+ }
38
71
  // These are observation inputs, not execution or delivery authority. Old
39
72
  // cooperative SQL writers inherit the same atomic invalidation triggers.
40
73
  const backgroundSources = [
@@ -17,6 +17,11 @@ export interface RecentBackgroundTerminalPage {
17
17
  const pageSize = (limit = 256) => Math.max(1, Math.min(256, requireCounter('limit', limit)));
18
18
  const scopeValues = (scope: ParentCallbackScope) => [requirePath('workspace', scope.workspace), requireId('sessionId', scope.sessionId)] as const;
19
19
 
20
+ export function parentRecoveryRevision(ctx: StoreContext, scope: ParentCallbackScope): number {
21
+ const row = getRow(ctx, 'SELECT revision FROM background_recovery_scopes WHERE workspace=? AND session_id=?', ...scopeValues(scope));
22
+ return Number(row?.revision ?? 0);
23
+ }
24
+
20
25
  export function setParentCallbackPending(ctx: StoreContext, taskId: string, pending: boolean): boolean {
21
26
  taskId = requireId('taskId', taskId);
22
27
  pending = requireBoolean('pending', pending);
@@ -2,7 +2,8 @@
2
2
  import { isDeepStrictEqual } from "node:util";
3
3
  import { getRow, run, type StoreContext } from "./sqlite.ts";
4
4
  import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.ts";
5
- import { requireId, requirePath } from "./validate.ts";
5
+ import { mapOperation } from "./rows.ts";
6
+ import { requireCounter, requireId, requirePath } from "./validate.ts";
6
7
  import type { RecordTerminalOutcomeInput } from "./types.ts";
7
8
  import type { OwnerIdentity } from "./types.ts";
8
9
 
@@ -43,6 +44,27 @@ export function resultSupervision(ctx: StoreContext, operationId: string): Resul
43
44
  return row ? JSON.parse(String(row.value)) : null;
44
45
  }
45
46
 
47
+ /** Changes that can make a server cleanup candidate eligible behind an idle scan cursor. */
48
+ export function serverAssignmentCleanupRevision(ctx: StoreContext): number {
49
+ return Number(ctx.db.prepare("SELECT value FROM coordinator_state WHERE key='server-assignment-cleanup-revision'").get()?.value ?? 0);
50
+ }
51
+
52
+ /** Pending cleanup under the root daemon's result authority, including past epochs. */
53
+ export function serverAssignmentCleanup(ctx: StoreContext, limit: number, after?: { hostId: string; operationId: string }) {
54
+ const host = after ? requireId("hostId", after.hostId) : "server:";
55
+ if (!host.startsWith("server:")) throw new Error("Expected a server cleanup cursor");
56
+ // 'server;' is the exclusive upper bound of the 'server:' prefix in SQLite binary order.
57
+ const rows = ctx.db.prepare(`SELECT op.*, CASE WHEN json_valid(s.value) THEN s.value END AS grant_json
58
+ FROM assignment_cleanup_pending p
59
+ CROSS JOIN operations op ON op.operation_id = p.operation_id
60
+ CROSS JOIN coordinator_state s ON s.key = ? || p.operation_id
61
+ WHERE (p.supervision_host_id, p.operation_id) > (?, ?) AND p.supervision_host_id < 'server;'
62
+ ORDER BY p.supervision_host_id, p.operation_id LIMIT ?`).all(PREFIX,
63
+ host, after ? requireId("operationId", after.operationId) : "",
64
+ Math.min(256, requireCounter("limit", limit)));
65
+ return rows.map(row => ({ operation: mapOperation(row), grant: JSON.parse(String(row.grant_json)) as ResultSupervision | null }));
66
+ }
67
+
46
68
  /** The admitting host has stopped its local route before this exact-owner CAS. */
47
69
  export function handoffResultSupervision(ctx: StoreContext, input: {
48
70
  operationId: string; expectedHostId: string; directory: string; hostId: string; epoch: string;
@@ -111,6 +111,13 @@ const PENDING_CLEANUP_DDL = [
111
111
  END`,
112
112
  ];
113
113
 
114
+ // Legacy Windows clients can keep writing through an open connection after migration.
115
+ const WINDOWS_CLEANUP_PROOF_GUARD = `CREATE TRIGGER assignment_cleanup_windows_proof BEFORE INSERT ON coordinator_state
116
+ WHEN NEW.key GLOB 'assignment-cleanup-verified:*' AND NEW.value IS NOT (
117
+ SELECT 'v2:' || launch_token FROM operations
118
+ WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1))
119
+ BEGIN SELECT RAISE(IGNORE); END`;
120
+
114
121
  const DDL: readonly string[] = [
115
122
  `CREATE TABLE task_cancellation_authorities (
116
123
  credential_hash TEXT PRIMARY KEY,
@@ -360,6 +367,7 @@ export function ensureSchema(ctx: StoreContext): void {
360
367
  }
361
368
  ctx.transaction(() => {
362
369
  for (const statement of [...DDL, ...EXPIRY_INDEXES]) ctx.db.exec(statement);
370
+ if (process.platform === "win32") ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
363
371
  run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
364
372
  });
365
373
  return;
@@ -418,19 +426,28 @@ function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
418
426
  for (const statement of EXPIRY_INDEXES) ctx.db.exec(statement);
419
427
  const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
420
428
  const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
421
- if (hasPending()) return;
429
+ const needsWindowsGuard = () => process.platform === "win32" &&
430
+ !getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND name = 'assignment_cleanup_windows_proof'");
431
+ if (hasPending() && !needsWindowsGuard()) return;
422
432
  ctx.transaction(() => {
423
- if (hasPending()) return;
424
- ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
425
- // Legacy writers leave the nullable provenance unset.
426
- if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
427
- ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
428
- for (const statement of PENDING_CLEANUP_DDL) ctx.db.exec(statement);
429
- if (process.platform === "win32") {
430
- // Earlier Windows writers mistook an unsupported group probe for proof of exit.
431
- ctx.db.exec("DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*'");
433
+ const createQueue = !hasPending();
434
+ const installGuard = needsWindowsGuard();
435
+ if (!createQueue && !installGuard) return;
436
+ if (createQueue) {
437
+ ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
438
+ // Legacy writers leave the nullable provenance unset.
439
+ if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
440
+ ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
441
+ for (const statement of PENDING_CLEANUP_DDL) ctx.db.exec(statement);
442
+ }
443
+ if (installGuard) {
444
+ ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
445
+ // Discard marks from writers which treated an unsupported Windows group probe as proof.
446
+ ctx.db.exec(`DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*' AND value IS NOT (
447
+ SELECT 'v2:' || launch_token FROM operations
448
+ WHERE operation_id = substr(coordinator_state.key, length('assignment-cleanup-verified:') + 1))`);
432
449
  }
433
- ctx.db.exec(`INSERT INTO assignment_cleanup_pending
450
+ ctx.db.exec(`INSERT OR IGNORE INTO assignment_cleanup_pending
434
451
  SELECT op.operation_id, op.supervision_host_id FROM operations op
435
452
  JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
436
453
  JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
@@ -9,11 +9,11 @@
9
9
  */
10
10
  import { expireWaits, overdueOperations } from "./expiry.ts";
11
11
  import { setUpgradeFence } from "./upgrade.ts";
12
- import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
12
+ import { parentRecoveryRevision, setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
13
13
  import { BackgroundRequests } from "./background-requests.ts";
14
14
  import { StoreError } from "./errors.ts";
15
15
  import { SubagentLaunchJournal } from "./subagent-launch.ts";
16
- import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
16
+ import { serverAssignmentCleanup, serverAssignmentCleanupRevision, resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
17
17
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
18
18
  import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
19
19
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
@@ -131,6 +131,8 @@ export interface Store {
131
131
  overdueOperations(): OperationRecord[];
132
132
  expireWaits(): number;
133
133
  hasSubagentManagement(): boolean;
134
+ serverAssignmentCleanupRevision(): number;
135
+ serverAssignmentCleanup(limit: number, after?: Parameters<typeof serverAssignmentCleanup>[2]): ReturnType<typeof serverAssignmentCleanup>;
134
136
  resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
135
137
  subagentLaunchJournal(): SubagentLaunchJournal;
136
138
  resultScopeManaged(scope: string): boolean;
@@ -169,6 +171,7 @@ export interface Store {
169
171
  // ---- operations ----
170
172
 
171
173
  backgroundRequests(): BackgroundRequests;
174
+ parentRecoveryRevision(scope: ParentCallbackScope): number;
172
175
  setParentCallbackPending(taskId: string, pending: boolean): boolean;
173
176
  listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
174
177
  listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
@@ -369,6 +372,8 @@ export function openStore(options: StoreOptions): Store {
369
372
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
370
373
  resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
371
374
  hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
375
+ serverAssignmentCleanupRevision() { alive(); return serverAssignmentCleanupRevision(ctx); },
376
+ serverAssignmentCleanup(limit, after) { alive(); return serverAssignmentCleanup(ctx, limit, after); },
372
377
  resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
373
378
  resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
374
379
  handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
@@ -397,6 +402,7 @@ export function openStore(options: StoreOptions): Store {
397
402
  closed = true;
398
403
  db.close();
399
404
  },
405
+ parentRecoveryRevision(scope) { alive(); return parentRecoveryRevision(ctx, scope); },
400
406
  setParentCallbackPending(taskId, pending) { alive(); return setParentCallbackPending(ctx, taskId, pending); },
401
407
  listPendingParentCallbacks(scope, options) { alive(); return listPendingParentCallbacks(ctx, scope, options); },
402
408
  listRecentBackgroundTerminals(options) { alive(); return listRecentBackgroundTerminals(ctx, options); },
@@ -435,7 +441,7 @@ export function openStore(options: StoreOptions): Store {
435
441
  alive();
436
442
  if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1) return false;
437
443
  return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
438
- SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
444
+ SELECT 'assignment-cleanup-verified:' || op.operation_id, 'v2:' || op.launch_token
439
445
  FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
440
446
  JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
441
447
  WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`,