pi-better-server 0.8.1 → 0.8.3

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 (45) hide show
  1. package/package.json +1 -1
  2. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +2 -2
  3. package/src/runtime/background-tools.ts +1 -1
  4. package/src/runtime/background.ts +9 -4
  5. package/src/runtime/domain/background-service/observed-waits.domain.mjs +20 -11
  6. package/src/runtime/domain/background-service/observed-waits.ts +24 -13
  7. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +10 -9
  8. package/src/runtime/domain/background-service/shared-navigator.ts +10 -9
  9. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +34 -0
  10. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +33 -0
  11. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +4 -0
  12. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.ts +5 -0
  13. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +20 -1
  14. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +23 -1
  15. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +30 -13
  16. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +28 -11
  17. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +6 -3
  18. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +9 -3
  19. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +34 -0
  20. package/src/runtime/domain/coordinator/src/background-parent-callbacks.mjs +4 -0
  21. package/src/runtime/domain/coordinator/src/result-supervision.mjs +20 -1
  22. package/src/runtime/domain/coordinator/src/schema.mjs +30 -13
  23. package/src/runtime/domain/coordinator/src/store.mjs +6 -3
  24. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +14 -1
  25. package/src/runtime/domain/subagents/managed-launch-client.ts +15 -1
  26. package/src/runtime/domain/subagents/package.json +1 -1
  27. package/src/runtime/domain/subagents/registry.domain.mjs +32 -27
  28. package/src/runtime/domain/subagents/registry.ts +30 -23
  29. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +10 -9
  30. package/src/runtime/domain/subagents/shared-navigator.ts +10 -9
  31. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +34 -0
  32. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +33 -0
  33. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +4 -0
  34. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts +5 -0
  35. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +20 -1
  36. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +23 -1
  37. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +30 -13
  38. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +28 -11
  39. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +6 -3
  40. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +9 -3
  41. package/src/runtime/domain/subagents/worker-waits.domain.mjs +3 -16
  42. package/src/runtime/domain/subagents/worker-waits.ts +3 -14
  43. package/src/runtime/result-supervision.ts +33 -10
  44. package/src/server.ts +8 -1
  45. package/src/version.ts +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-server",
3
- "version": "0.8.1",
3
+ "version": "0.8.3",
4
4
  "description": "Daemon that hosts Pi agent sessions behind a local Unix socket with session-addressed Pi RPC.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -16,8 +16,8 @@ export function instrumentRecoveryTrace(source) {
16
16
  };
17
17
  const traceBeforeContext = { owner: service.activeOrigin, state: traceRecoveryState() };
18
18
  service.noteParentContext(ctx, { recover: false });`);
19
- replace('const recoveryVersion = authority.backgroundDigest([lease.store.getChangeRevision(), record.branchIds]);', `
20
- const traceCoordinatorRevision = lease.store.getChangeRevision();
19
+ replace('const recoveryVersion = authority.backgroundDigest([lease.store.parentRecoveryRevision(record.owner), record.branchIds]);', `
20
+ const traceCoordinatorRevision = lease.store.parentRecoveryRevision(record.owner);
21
21
  const recoveryVersion = authority.backgroundDigest([traceCoordinatorRevision, record.branchIds]);`);
22
22
  replace('metrics.reconciles++;', `
23
23
  const traceAfterContext = traceRecoveryState();
@@ -306,7 +306,7 @@ export async function createBackgroundTools(root: string, instance: string, drai
306
306
  if (!observe)
307
307
  throw new Error('Shared Background observation unavailable');
308
308
  // Recovery is indexed and bounded independently of display readiness.
309
- const recoveryVersion = authority.backgroundDigest([lease.store.getChangeRevision(), record.branchIds]);
309
+ const recoveryVersion = authority.backgroundDigest([lease.store.parentRecoveryRevision(record.owner), record.branchIds]);
310
310
  if (recoveryVersions.get(viewKey) !== recoveryVersion || service.hasPendingParentCallbackRecovery()) {
311
311
  metrics.reconciles++;
312
312
  service.noteParentContext(ctx);
@@ -292,10 +292,13 @@ export class BackgroundObservation {
292
292
  const previousRows = new Map(this.rows.map(row => [row.id, row]));
293
293
  for (const row of rows) { const previous = previousRows.get(row.id); if (previous
294
294
  && (previous.status !== row.status || previous.active !== row.active)) this.history?.invalidateOperation(row.operationId); }
295
+ // One worker can be visible to one of many subscribed parents. Resolve its
296
+ // files, waits and captured recipient once in this source refresh.
297
+ const projected = new Map(rows.map(row => [row.operationId, row]));
295
298
  for (const entry of this.legacy.values()) {
296
299
  const scopedRevision = this.hasInputVersions ? this.scopeVersions.get(JSON.stringify([entry.origin.cwd, entry.origin.sessionId])) ?? 0 : revision;
297
300
  if (hasPendingIndex) this.refreshPending(entry, scopedRevision);
298
- this.refreshRecent(entry, scopedRevision);
301
+ this.refreshRecent(entry, scopedRevision, projected);
299
302
  const active = this.visibleLegacy(entry.origin);
300
303
  const retained = entry.rows.map(row => readMeta(row.id)).filter((row: any) => row && row.dismissedAt === undefined
301
304
  && row.status !== "running" && (!row.endedAt || Date.now() - row.endedAt < 30000));
@@ -451,7 +454,7 @@ export class BackgroundObservation {
451
454
  ? row.owner.workspace === origin.cwd && row.owner.sessionId === origin.sessionId
452
455
  : row.parentRecipient?.workspace === origin.cwd && row.parentRecipient?.sessionId === origin.sessionId;
453
456
  }
454
- private refreshRecent(entry: BackgroundScope, revision: number): void {
457
+ private refreshRecent(entry: BackgroundScope, revision: number, projected = new Map<string, any>()): void {
455
458
  if (!this.db) return;
456
459
  if (entry.recentRevision === undefined || !this.hasInputVersions && entry.recentRevision !== revision) {
457
460
  const operations = this.db.prepare(`SELECT * FROM operations o WHERE observer_kind='local-supervisor' AND (
@@ -477,8 +480,10 @@ export class BackgroundObservation {
477
480
  }
478
481
  for (const [id, op] of this.changedOperations) {
479
482
  const direct = op?.owner_kind === "parent-session" && op.owner_workspace === entry.origin.cwd && op.owner_session_id === (entry.origin.sessionId ?? "");
480
- const row = (direct || op?.owner_kind === "worker-conversation") && op.observer_kind === "local-supervisor"
481
- && op.terminal_revision > 0 && Date.now() - op.terminal_at < 30000 && this.project([op])[0];
483
+ const recent = (direct || op?.owner_kind === "worker-conversation") && op.observer_kind === "local-supervisor"
484
+ && op.terminal_revision > 0 && Date.now() - op.terminal_at < 30000;
485
+ if (recent && !projected.has(id)) projected.set(id, this.project([op])[0]);
486
+ const row = recent && projected.get(id);
482
487
  if (row && this.belongsToDurableOrigin(row, entry.origin)) rows.set(id, row);
483
488
  else rows.delete(id);
484
489
  }
@@ -461,7 +461,7 @@ export class ObservedWaitHost {
461
461
  authorityPassCache;
462
462
  /** Running operations this follower is currently assigned to supervise. */
463
463
  followerRunningTasks = new Set();
464
- unscopedCallbackRecovery = { revision: -1, branch: "", delivery: undefined, claims: undefined };
464
+ unscopedCallbackRecovery = { revision: -1, branch: "" };
465
465
  callbackRecoveryScopes = new Map();
466
466
  recoveryScopeState() {
467
467
  if (!this.activeOrigin)
@@ -653,16 +653,24 @@ export class ObservedWaitHost {
653
653
  this.attemptTerminalCallback(operation, this.statusOf(operation.operationId), operation.terminalOutcome, []);
654
654
  }
655
655
  }
656
- activeParentTerminalOperations(claims = false) {
656
+ activeParentTerminalOperations(claims = false, knownRevision) {
657
657
  const origin = this.activeOrigin;
658
658
  if (!this.store || !origin?.sessionId)
659
659
  return [];
660
- const page = this.store.listPendingParentCallbacks({ sessionId: origin.sessionId, workspace: origin.cwd }, { after: claims ? this.pendingClaimCursor : this.pendingCallbackCursor, limit: 256 });
661
- const next = page.length === 256 ? page.at(-1).operationId : undefined;
662
- if (claims)
663
- this.pendingClaimCursor = next;
660
+ const scope = { sessionId: origin.sessionId, workspace: origin.cwd };
661
+ const revision = knownRevision ?? this.store.parentRecoveryRevision(scope);
662
+ const state = this.recoveryScopeState();
663
+ const key = claims ? "claims" : "delivery";
664
+ const cursor = state[key];
665
+ const startRevision = cursor?.after ? cursor.revision : revision;
666
+ const page = this.store.listPendingParentCallbacks(scope, { after: cursor?.after, limit: 256 });
667
+ if (page.length === 256)
668
+ state[key] = { after: page.at(-1).operationId, revision: startRevision };
669
+ // Finish the current sweep before revisiting callbacks inserted behind its cursor.
670
+ else if (revision !== startRevision)
671
+ state[key] = { revision };
664
672
  else
665
- this.pendingCallbackCursor = next;
673
+ delete state[key];
666
674
  return page;
667
675
  }
668
676
  /**
@@ -902,7 +910,7 @@ export class ObservedWaitHost {
902
910
  }
903
911
  /**
904
912
  * A follower does not scan foreign operations. It refreshes the exact active
905
- * owner's terminal records only when the shared change revision advances, so
913
+ * owner's terminal records only when that parent's recovery revision advances, so
906
914
  * callback recovery stays correct without multiplying the running-set scan.
907
915
  */
908
916
  reconcileOwnerChanges() {
@@ -915,21 +923,22 @@ export class ObservedWaitHost {
915
923
  return;
916
924
  let revision;
917
925
  try {
918
- revision = store.getChangeRevision();
926
+ revision = store.parentRecoveryRevision({ workspace: ctx.cwd, sessionId });
919
927
  }
920
928
  catch {
921
929
  return;
922
930
  }
923
931
  if (revision === this.lastChangeRevision && !this.pendingCallbackCursor)
924
932
  return;
925
- this.lastChangeRevision = revision;
926
933
  let operations;
927
934
  try {
928
- operations = this.activeParentTerminalOperations();
935
+ operations = this.activeParentTerminalOperations(false, revision);
929
936
  }
930
937
  catch {
938
+ this.lastChangeRevision = -1;
931
939
  return;
932
940
  }
941
+ this.lastChangeRevision = revision;
933
942
  let newest = this.lastOwnedTerminalAt;
934
943
  let visibleOwner;
935
944
  for (const operation of operations) {
@@ -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) {
@@ -693,21 +693,22 @@ function providerGroupLabel(label, fg) {
693
693
  }
694
694
  function formatMainListRow(row, selected, fg, width) {
695
695
  const prefix = (selected ? fg("accent", "› ") : " ") + (row.treeDepth === 1 ? dim(` ${row.lastChild ? "└─" : "├─"} `, fg) : "");
696
- const name = row.name || row.id;
696
+ const name = rowDisplayName(row);
697
+ const summary = singleLine(rowSummary(row));
697
698
  const indicator = statusIndicator(row);
698
699
  const status = fg(indicator.color, indicator.glyph);
699
700
  const elapsed = singleLine(row.elapsed || "-");
700
- const available = Math.max(24, width || MAIN_LIST_FALLBACK_WIDTH);
701
701
  const elapsedWidth = Math.min(Math.max(piVisibleWidth(elapsed), 4), 12);
702
702
  const statusWidth = 2;
703
703
  const leftPrefixWidth = piVisibleWidth(prefix) + statusWidth + 1;
704
- const maxNameWidth = Math.max(8, Math.floor(available * 0.36));
705
- const nameWidth = Math.max(8, Math.min(44, maxNameWidth, available - leftPrefixWidth - elapsedWidth - 10));
706
- const rightWidth = Math.max(8, available - leftPrefixWidth - nameWidth - 1);
707
- const summaryWidth = Math.max(1, rightWidth - elapsedWidth - 1);
708
- const left = `${prefix}${fit(status, statusWidth)} ${fit(name, nameWidth)}`;
709
- const right = `${dim(fitRight(rowSummary(row), summaryWidth), fg)} ${fitRight(elapsed, elapsedWidth)}`;
710
- const gap = Math.max(1, available - piVisibleWidth(left) - piVisibleWidth(right));
704
+ const textWidth = Math.max(0, width - leftPrefixWidth - elapsedWidth - 2);
705
+ // Reserve a readable title when both texts are long. Each side can use the other's spare cells.
706
+ const preferredNameWidth = Math.max(8, Math.ceil(textWidth / 3), textWidth - piVisibleWidth(summary));
707
+ const nameWidth = Math.min(piVisibleWidth(name), textWidth, preferredNameWidth);
708
+ const summaryWidth = textWidth - nameWidth;
709
+ const left = `${prefix}${fit(status, statusWidth)} ${piTruncateToWidth(name, nameWidth)}`;
710
+ const right = `${dim(fitRight(summary, summaryWidth), fg)} ${fitRight(elapsed, elapsedWidth)}`;
711
+ const gap = Math.max(1, width - piVisibleWidth(left) - piVisibleWidth(right));
711
712
  return `${left}${" ".repeat(gap)}${right}`;
712
713
  }
713
714
  function statusGlyph(row) {
@@ -778,21 +778,22 @@ function providerGroupLabel(label: string, fg: (color: string, value: string) =>
778
778
 
779
779
  function formatMainListRow(row: InternalRow, selected: boolean, fg: (color: string, value: string) => string, width: number): string {
780
780
  const prefix = (selected ? fg("accent", "› ") : " ") + (row.treeDepth === 1 ? dim(` ${row.lastChild ? "└─" : "├─"} `, fg) : "");
781
- const name = row.name || row.id;
781
+ const name = rowDisplayName(row);
782
+ const summary = singleLine(rowSummary(row));
782
783
  const indicator = statusIndicator(row);
783
784
  const status = fg(indicator.color, indicator.glyph);
784
785
  const elapsed = singleLine(row.elapsed || "-");
785
- const available = Math.max(24, width || MAIN_LIST_FALLBACK_WIDTH);
786
786
  const elapsedWidth = Math.min(Math.max(piVisibleWidth(elapsed), 4), 12);
787
787
  const statusWidth = 2;
788
788
  const leftPrefixWidth = piVisibleWidth(prefix) + statusWidth + 1;
789
- const maxNameWidth = Math.max(8, Math.floor(available * 0.36));
790
- const nameWidth = Math.max(8, Math.min(44, maxNameWidth, available - leftPrefixWidth - elapsedWidth - 10));
791
- const rightWidth = Math.max(8, available - leftPrefixWidth - nameWidth - 1);
792
- const summaryWidth = Math.max(1, rightWidth - elapsedWidth - 1);
793
- const left = `${prefix}${fit(status, statusWidth)} ${fit(name, nameWidth)}`;
794
- const right = `${dim(fitRight(rowSummary(row), summaryWidth), fg)} ${fitRight(elapsed, elapsedWidth)}`;
795
- const gap = Math.max(1, available - piVisibleWidth(left) - piVisibleWidth(right));
789
+ const textWidth = Math.max(0, width - leftPrefixWidth - elapsedWidth - 2);
790
+ // Reserve a readable title when both texts are long. Each side can use the other's spare cells.
791
+ const preferredNameWidth = Math.max(8, Math.ceil(textWidth / 3), textWidth - piVisibleWidth(summary));
792
+ const nameWidth = Math.min(piVisibleWidth(name), textWidth, preferredNameWidth);
793
+ const summaryWidth = textWidth - nameWidth;
794
+ const left = `${prefix}${fit(status, statusWidth)} ${piTruncateToWidth(name, nameWidth)}`;
795
+ const right = `${dim(fitRight(summary, summaryWidth), fg)} ${fitRight(elapsed, elapsedWidth)}`;
796
+ const gap = Math.max(1, width - piVisibleWidth(left) - piVisibleWidth(right));
796
797
  return `${left}${" ".repeat(gap)}${right}`;
797
798
  }
798
799
 
@@ -34,6 +34,40 @@ export function ensureAssignmentChanges(ctx) {
34
34
  const records = action === "UPDATE" ? ["OLD", "NEW"] : [action === "DELETE" ? "OLD" : "NEW"];
35
35
  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;`);
36
36
  }
37
+ // An idle scan may span several pages. Insertions and authority transfers can
38
+ // put a new candidate behind its cursor; deleting completed work cannot.
39
+ const advanceCleanup = `INSERT INTO coordinator_state VALUES ('server-assignment-cleanup-revision', '1')
40
+ ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1;`;
41
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS server_cleanup_added AFTER INSERT ON assignment_cleanup_pending
42
+ WHEN NEW.supervision_host_id GLOB 'server:*' BEGIN ${advanceCleanup} END;
43
+ CREATE TRIGGER IF NOT EXISTS server_cleanup_transferred AFTER UPDATE OF supervision_host_id ON assignment_cleanup_pending
44
+ WHEN NEW.supervision_host_id GLOB 'server:*' AND NEW.supervision_host_id IS NOT OLD.supervision_host_id
45
+ BEGIN ${advanceCleanup} END;`);
46
+ // The result grant can arrive after the assignment already ended.
47
+ for (const event of ["INSERT", "UPDATE"])
48
+ 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
+ }
37
71
  // These are observation inputs, not execution or delivery authority. Old
38
72
  // cooperative SQL writers inherit the same atomic invalidation triggers.
39
73
  const backgroundSources = [
@@ -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 = [
@@ -7,6 +7,10 @@ import { getRow, getRows, run } from "./sqlite.domain.mjs";
7
7
  import { requireBoolean, requireCounter, requireId, requirePath } from "./validate.domain.mjs";
8
8
  const pageSize = (limit = 256) => Math.max(1, Math.min(256, requireCounter('limit', limit)));
9
9
  const scopeValues = (scope) => [requirePath('workspace', scope.workspace), requireId('sessionId', scope.sessionId)];
10
+ export function parentRecoveryRevision(ctx, scope) {
11
+ const row = getRow(ctx, 'SELECT revision FROM background_recovery_scopes WHERE workspace=? AND session_id=?', ...scopeValues(scope));
12
+ return Number(row?.revision ?? 0);
13
+ }
10
14
  export function setParentCallbackPending(ctx, taskId, pending) {
11
15
  taskId = requireId('taskId', taskId);
12
16
  pending = requireBoolean('pending', pending);
@@ -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);
@@ -3,7 +3,8 @@
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  import { getRow, run } from "./sqlite.domain.mjs";
5
5
  import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.domain.mjs";
6
- import { requireId, requirePath } from "./validate.domain.mjs";
6
+ import { mapOperation } from "./rows.domain.mjs";
7
+ import { requireCounter, requireId, requirePath } from "./validate.domain.mjs";
7
8
  const PREFIX = "result-supervision-v1:";
8
9
  /** A bounded observation page. A gap requires restoring active authority, not history. */
9
10
  export function resultSupervisionChanges(ctx, after) {
@@ -28,6 +29,24 @@ export function resultSupervision(ctx, operationId) {
28
29
  const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", PREFIX + requireId("operationId", operationId));
29
30
  return row ? JSON.parse(String(row.value)) : null;
30
31
  }
32
+ /** Changes that can make a server cleanup candidate eligible behind an idle scan cursor. */
33
+ export function serverAssignmentCleanupRevision(ctx) {
34
+ return Number(ctx.db.prepare("SELECT value FROM coordinator_state WHERE key='server-assignment-cleanup-revision'").get()?.value ?? 0);
35
+ }
36
+ /** Pending cleanup under the root daemon's result authority, including past epochs. */
37
+ export function serverAssignmentCleanup(ctx, limit, after) {
38
+ const host = after ? requireId("hostId", after.hostId) : "server:";
39
+ if (!host.startsWith("server:"))
40
+ throw new Error("Expected a server cleanup cursor");
41
+ // 'server;' is the exclusive upper bound of the 'server:' prefix in SQLite binary order.
42
+ const rows = ctx.db.prepare(`SELECT op.*, CASE WHEN json_valid(s.value) THEN s.value END AS grant_json
43
+ FROM assignment_cleanup_pending p
44
+ CROSS JOIN operations op ON op.operation_id = p.operation_id
45
+ CROSS JOIN coordinator_state s ON s.key = ? || p.operation_id
46
+ WHERE (p.supervision_host_id, p.operation_id) > (?, ?) AND p.supervision_host_id < 'server;'
47
+ ORDER BY p.supervision_host_id, p.operation_id LIMIT ?`).all(PREFIX, host, after ? requireId("operationId", after.operationId) : "", Math.min(256, requireCounter("limit", limit)));
48
+ return rows.map(row => ({ operation: mapOperation(row), grant: JSON.parse(String(row.grant_json)) }));
49
+ }
31
50
  /** The admitting host has stopped its local route before this exact-owner CAS. */
32
51
  export function handoffResultSupervision(ctx, input) {
33
52
  const operationId = requireId("operationId", input.operationId);
@@ -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;
@@ -104,6 +104,12 @@ const PENDING_CLEANUP_DDL = [
104
104
  DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
105
105
  END`,
106
106
  ];
107
+ // Legacy Windows clients can keep writing through an open connection after migration.
108
+ const WINDOWS_CLEANUP_PROOF_GUARD = `CREATE TRIGGER assignment_cleanup_windows_proof BEFORE INSERT ON coordinator_state
109
+ WHEN NEW.key GLOB 'assignment-cleanup-verified:*' AND NEW.value IS NOT (
110
+ SELECT 'v2:' || launch_token FROM operations
111
+ WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1))
112
+ BEGIN SELECT RAISE(IGNORE); END`;
107
113
  const DDL = [
108
114
  `CREATE TABLE task_cancellation_authorities (
109
115
  credential_hash TEXT PRIMARY KEY,
@@ -345,6 +351,8 @@ export function ensureSchema(ctx) {
345
351
  ctx.transaction(() => {
346
352
  for (const statement of [...DDL, ...EXPIRY_INDEXES])
347
353
  ctx.db.exec(statement);
354
+ if (process.platform === "win32")
355
+ ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
348
356
  run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
349
357
  });
350
358
  return;
@@ -397,23 +405,32 @@ function ensureAssignmentCleanupSchema(ctx) {
397
405
  ctx.db.exec(statement);
398
406
  const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
399
407
  const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
400
- if (hasPending())
408
+ const needsWindowsGuard = () => process.platform === "win32" &&
409
+ !getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND name = 'assignment_cleanup_windows_proof'");
410
+ if (hasPending() && !needsWindowsGuard())
401
411
  return;
402
412
  ctx.transaction(() => {
403
- if (hasPending())
413
+ const createQueue = !hasPending();
414
+ const installGuard = needsWindowsGuard();
415
+ if (!createQueue && !installGuard)
404
416
  return;
405
- ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
406
- // Legacy writers leave the nullable provenance unset.
407
- if (!hasColumn())
408
- ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
409
- ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
410
- for (const statement of PENDING_CLEANUP_DDL)
411
- ctx.db.exec(statement);
412
- if (process.platform === "win32") {
413
- // Earlier Windows writers mistook an unsupported group probe for proof of exit.
414
- ctx.db.exec("DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*'");
417
+ if (createQueue) {
418
+ ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
419
+ // Legacy writers leave the nullable provenance unset.
420
+ if (!hasColumn())
421
+ ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
422
+ ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
423
+ for (const statement of PENDING_CLEANUP_DDL)
424
+ ctx.db.exec(statement);
425
+ }
426
+ if (installGuard) {
427
+ ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
428
+ // Discard marks from writers which treated an unsupported Windows group probe as proof.
429
+ ctx.db.exec(`DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*' AND value IS NOT (
430
+ SELECT 'v2:' || launch_token FROM operations
431
+ WHERE operation_id = substr(coordinator_state.key, length('assignment-cleanup-verified:') + 1))`);
415
432
  }
416
- ctx.db.exec(`INSERT INTO assignment_cleanup_pending
433
+ ctx.db.exec(`INSERT OR IGNORE INTO assignment_cleanup_pending
417
434
  SELECT op.operation_id, op.supervision_host_id FROM operations op
418
435
  JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
419
436
  JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
@@ -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