pi-better-server 0.8.0 → 0.8.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.
Files changed (69) 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/supervisor/identity.mjs +5 -0
  6. package/src/runtime/domain/background/supervisor/supervisor.mjs +3 -4
  7. package/src/runtime/domain/background-service/observed-waits.domain.mjs +30 -18
  8. package/src/runtime/domain/background-service/observed-waits.ts +33 -19
  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/assignment-outcomes.domain.mjs +0 -2
  12. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  13. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +4 -0
  14. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.ts +5 -0
  15. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  16. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +7 -4
  17. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  18. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +5 -11
  19. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +20 -1
  20. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +23 -1
  21. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +75 -6
  22. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +75 -5
  23. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +9 -6
  24. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +14 -8
  25. package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +5 -0
  26. package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +5 -0
  27. package/src/runtime/domain/background-service/supervisor/identity.ts +6 -0
  28. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +3 -4
  29. package/src/runtime/domain/background-service/supervisor/supervisor.ts +3 -4
  30. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +34 -0
  31. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +0 -2
  32. package/src/runtime/domain/coordinator/src/background-parent-callbacks.mjs +4 -0
  33. package/src/runtime/domain/coordinator/src/discovery.mjs +6 -4
  34. package/src/runtime/domain/coordinator/src/operations.mjs +5 -12
  35. package/src/runtime/domain/coordinator/src/result-supervision.mjs +20 -1
  36. package/src/runtime/domain/coordinator/src/schema.mjs +75 -6
  37. package/src/runtime/domain/coordinator/src/store.mjs +9 -6
  38. package/src/runtime/domain/subagents/cleanup.domain.mjs +7 -10
  39. package/src/runtime/domain/subagents/cleanup.ts +6 -8
  40. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +14 -1
  41. package/src/runtime/domain/subagents/managed-launch-client.ts +15 -1
  42. package/src/runtime/domain/subagents/package.json +1 -1
  43. package/src/runtime/domain/subagents/registry.domain.mjs +34 -27
  44. package/src/runtime/domain/subagents/registry.ts +36 -24
  45. package/src/runtime/domain/subagents/retained-result.domain.mjs +3 -3
  46. package/src/runtime/domain/subagents/retained-result.ts +2 -3
  47. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +34 -0
  48. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +33 -0
  49. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  50. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  51. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +4 -0
  52. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts +5 -0
  53. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  54. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +7 -4
  55. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  56. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +5 -11
  57. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +20 -1
  58. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +23 -1
  59. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +75 -6
  60. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +75 -5
  61. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +9 -6
  62. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +14 -8
  63. package/src/runtime/domain/subagents/worker-waits.domain.mjs +6 -20
  64. package/src/runtime/domain/subagents/worker-waits.ts +6 -17
  65. package/src/runtime/domain/subagents/workspace-files.domain.mjs +19 -5
  66. package/src/runtime/domain/subagents/workspace-files.ts +27 -5
  67. package/src/runtime/result-supervision.ts +46 -12
  68. package/src/server.ts +14 -6
  69. 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.0",
3
+ "version": "0.8.2",
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
  }
@@ -90,3 +90,8 @@ export function processGroupAlive(pgid) {
90
90
  return error.code !== "ESRCH";
91
91
  }
92
92
  }
93
+ /** Windows has no POSIX group probe. Older cleanup records used that probe there too. */
94
+ export function processGroupExitVerified(pgid, recordedEmpty = false) {
95
+ return process.platform !== "win32" && (recordedEmpty ||
96
+ (pgid !== undefined && Number.isSafeInteger(pgid) && pgid > 0 && !processGroupAlive(pgid)));
97
+ }
@@ -24,7 +24,7 @@ import { join, resolve } from "node:path";
24
24
  import { setTimeout as delay } from "node:timers/promises";
25
25
  import { validateCondition } from "../conditions.mjs";
26
26
  import { stopProcessGroup } from "../process.mjs";
27
- import { identityAlive, identityAllowsSignals, processGroupAlive, readStartToken, verifyProcessIdentity } from "./identity.mjs";
27
+ import { identityAlive, identityAllowsSignals, processGroupAlive, processGroupExitVerified, readStartToken, verifyProcessIdentity } from "./identity.mjs";
28
28
  import { supervisorRunnerInvocation } from "./invocation.mjs";
29
29
  import { appendEvent, ensureSupervisorTaskDir, launchRequestHash, readClaimRecord, readCleanupRecord, readCommandRecord, readLaunchRecord, readLostRecord, readStopRequest, readTerminalRecord, resolveSupervisorDirectory, supervisorPaths, supervisorTaskIdForToken, SupervisorFenceBusyError, withStateFence, writeCleanupRecord, writeLaunchRecord, writeLostRecord, writeStopRequest, writeTerminalRecord, } from "./store.mjs";
30
30
  import { DEFAULT_CLAIM_GRACE_MS, DEFAULT_CLAIM_WAIT_MS, DEFAULT_MAX_LOG_BYTES, DEFAULT_STOP_WAIT_MS, DEFAULT_WATCH_INTERVAL_MS, DEFAULT_WATCH_TIMEOUT_MS, SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS, SUPERVISOR_INSPECT_FENCE_WAIT_MS, SUPERVISOR_POLL_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_TERMINATION_GRACE_MS, } from "./types.mjs";
@@ -606,8 +606,7 @@ class Supervisor {
606
606
  // Unknown identity cannot authorize an external signal. A recorded process
607
607
  // that is gone is only "already gone" when its group is gone too; survivors
608
608
  // in a group whose leader died cannot be verified, so they are refused.
609
- const groupStillAlive = processGroupAlive(pgid);
610
- outcome = (verdict === "dead" || verdict === "absent") && !groupStillAlive ? "already-gone" : "refused-unknown-identity";
609
+ outcome = (verdict === "dead" || verdict === "absent") && processGroupExitVerified(pgid) ? "already-gone" : "refused-unknown-identity";
611
610
  groupEmpty = outcome === "already-gone" ? true : false;
612
611
  }
613
612
  else {
@@ -642,7 +641,7 @@ class Supervisor {
642
641
  while (Date.now() < killDeadline && processGroupAlive(pgid)) {
643
642
  await delay(25);
644
643
  }
645
- groupEmpty = !processGroupAlive(pgid);
644
+ groupEmpty = processGroupExitVerified(pgid);
646
645
  outcome = !groupEmpty ? "unproven" : signalledWhileVerified ? "killed" : "already-gone";
647
646
  }
648
647
  const reason = outcome === "killed"
@@ -35,7 +35,7 @@ import { currentProcessStartToken, readProcessStartToken } from "./process-ident
35
35
  import { assertBackgroundExecutionAllowed, backgroundExecutionLimits, confineCommandSpec, resolveForegroundSandboxPlan, currentForegroundSandboxPolicy, resolveWorkerSandboxPlan, sandboxProvenance, } from "./sandbox.domain.mjs";
36
36
  import { openStore, cancellationCredential, } from "./shared-operation-coordinator/index.domain.mjs";
37
37
  import { createLocalSupervisor, defaultSupervisorDirectory, supervisorPaths, supervisorTaskIdForToken, } from "./supervisor/index.domain.mjs";
38
- import { processGroupAlive } from "./supervisor/identity.domain.mjs";
38
+ import { processGroupExitVerified } from "./supervisor/identity.domain.mjs";
39
39
  import { readStopRequest, writeTextAtomic } from "./supervisor/store.domain.mjs";
40
40
  import { ciObserverArgv, ciRunFromArgv, validCiRun } from "./ci-observation.domain.mjs";
41
41
  export const OBSERVED_WAITS_SERVICE_VERSION = 2;
@@ -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
  /**
@@ -788,11 +796,14 @@ export class ObservedWaitHost {
788
796
  return;
789
797
  this.authorityPassCache = new Map();
790
798
  try {
791
- const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope);
799
+ const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope, this.hostId);
792
800
  if (this.options.serverOwnedResults || discovery?.managed) {
793
801
  this.releaseDiscoveryAuthority();
794
- if (!this.options.serverOwnedResults)
802
+ if (!this.options.serverOwnedResults) {
795
803
  this.reconcileFollowerRunning();
804
+ if (discovery?.cleanupPending)
805
+ await this.reconcileAssignmentCleanup();
806
+ }
796
807
  this.reconcileOwnerChanges();
797
808
  this.retryPendingTerminalCallbacks();
798
809
  await this.dispatchOutbox();
@@ -803,13 +814,13 @@ export class ObservedWaitHost {
803
814
  if (role === "holder") {
804
815
  this.discoverObservedTasks();
805
816
  this.reconcileGlobalRunning();
806
- if (discovery.hasAssignmentTasks)
807
- await this.reconcileAssignmentCleanup();
808
817
  }
809
818
  else {
810
819
  this.reconcileFollowerRunning();
811
820
  this.reconcileOwnerChanges();
812
821
  }
822
+ if (discovery?.cleanupPending)
823
+ await this.reconcileAssignmentCleanup();
813
824
  this.retryPendingTerminalCallbacks();
814
825
  await this.dispatchOutbox();
815
826
  }
@@ -819,7 +830,7 @@ export class ObservedWaitHost {
819
830
  }
820
831
  async reconcileAssignmentCleanup() {
821
832
  const store = this.requireStore();
822
- const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
833
+ const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor, this.hostId);
823
834
  this.assignmentCleanupCursor = candidate?.operationId;
824
835
  if (!candidate || candidate.resultManaged || this.supervisionAuthority(candidate) !== "self")
825
836
  return;
@@ -833,7 +844,7 @@ export class ObservedWaitHost {
833
844
  if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven")
834
845
  return;
835
846
  const pgid = inspection.command?.pgid ?? inspection.command?.pid;
836
- if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
847
+ if (processGroupExitVerified(pgid, inspection.cleanup?.groupEmpty)) {
837
848
  store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
838
849
  return;
839
850
  }
@@ -899,7 +910,7 @@ export class ObservedWaitHost {
899
910
  }
900
911
  /**
901
912
  * A follower does not scan foreign operations. It refreshes the exact active
902
- * 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
903
914
  * callback recovery stays correct without multiplying the running-set scan.
904
915
  */
905
916
  reconcileOwnerChanges() {
@@ -912,21 +923,22 @@ export class ObservedWaitHost {
912
923
  return;
913
924
  let revision;
914
925
  try {
915
- revision = store.getChangeRevision();
926
+ revision = store.parentRecoveryRevision({ workspace: ctx.cwd, sessionId });
916
927
  }
917
928
  catch {
918
929
  return;
919
930
  }
920
931
  if (revision === this.lastChangeRevision && !this.pendingCallbackCursor)
921
932
  return;
922
- this.lastChangeRevision = revision;
923
933
  let operations;
924
934
  try {
925
- operations = this.activeParentTerminalOperations();
935
+ operations = this.activeParentTerminalOperations(false, revision);
926
936
  }
927
937
  catch {
938
+ this.lastChangeRevision = -1;
928
939
  return;
929
940
  }
941
+ this.lastChangeRevision = revision;
930
942
  let newest = this.lastOwnedTerminalAt;
931
943
  let visibleOwner;
932
944
  for (const operation of operations) {
@@ -77,7 +77,7 @@ import {
77
77
  type SupervisorStartOptions,
78
78
  type SupervisorTaskStatus,
79
79
  } from "./supervisor/index.js";
80
- import { processGroupAlive } from "./supervisor/identity.js";
80
+ import { processGroupExitVerified } from "./supervisor/identity.js";
81
81
  import { readStopRequest, writeTextAtomic } from "./supervisor/store.js";
82
82
  import { ciObserverArgv, ciRunFromArgv, validCiRun } from "./ci-observation.js";
83
83
  import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
@@ -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
 
@@ -1299,10 +1309,13 @@ export class ObservedWaitHost {
1299
1309
  if (!this.store || this.closed) return;
1300
1310
  this.authorityPassCache = new Map();
1301
1311
  try {
1302
- const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope);
1312
+ const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope, this.hostId);
1303
1313
  if (this.options.serverOwnedResults || discovery?.managed) {
1304
1314
  this.releaseDiscoveryAuthority();
1305
- if (!this.options.serverOwnedResults) this.reconcileFollowerRunning();
1315
+ if (!this.options.serverOwnedResults) {
1316
+ this.reconcileFollowerRunning();
1317
+ if (discovery?.cleanupPending) await this.reconcileAssignmentCleanup();
1318
+ }
1306
1319
  this.reconcileOwnerChanges();
1307
1320
  this.retryPendingTerminalCallbacks();
1308
1321
  await this.dispatchOutbox();
@@ -1313,11 +1326,11 @@ export class ObservedWaitHost {
1313
1326
  if (role === "holder") {
1314
1327
  this.discoverObservedTasks();
1315
1328
  this.reconcileGlobalRunning();
1316
- if (discovery!.hasAssignmentTasks) await this.reconcileAssignmentCleanup();
1317
1329
  } else {
1318
1330
  this.reconcileFollowerRunning();
1319
1331
  this.reconcileOwnerChanges();
1320
1332
  }
1333
+ if (discovery?.cleanupPending) await this.reconcileAssignmentCleanup();
1321
1334
  this.retryPendingTerminalCallbacks();
1322
1335
  await this.dispatchOutbox();
1323
1336
  } finally {
@@ -1327,7 +1340,7 @@ export class ObservedWaitHost {
1327
1340
 
1328
1341
  private async reconcileAssignmentCleanup(): Promise<void> {
1329
1342
  const store = this.requireStore();
1330
- const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
1343
+ const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor, this.hostId);
1331
1344
  this.assignmentCleanupCursor = candidate?.operationId;
1332
1345
  if (!candidate || candidate.resultManaged || this.supervisionAuthority(candidate) !== "self") return;
1333
1346
  const { taskId, launchToken } = candidate;
@@ -1338,7 +1351,7 @@ export class ObservedWaitHost {
1338
1351
  if (inspection.terminal) {
1339
1352
  if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven") return;
1340
1353
  const pgid = inspection.command?.pgid ?? inspection.command?.pid;
1341
- if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
1354
+ if (processGroupExitVerified(pgid, inspection.cleanup?.groupEmpty)) {
1342
1355
  store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
1343
1356
  return;
1344
1357
  }
@@ -1401,7 +1414,7 @@ export class ObservedWaitHost {
1401
1414
 
1402
1415
  /**
1403
1416
  * A follower does not scan foreign operations. It refreshes the exact active
1404
- * 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
1405
1418
  * callback recovery stays correct without multiplying the running-set scan.
1406
1419
  */
1407
1420
  private reconcileOwnerChanges(): void {
@@ -1412,18 +1425,19 @@ export class ObservedWaitHost {
1412
1425
  if (!sessionId) return;
1413
1426
  let revision: number;
1414
1427
  try {
1415
- revision = store.getChangeRevision();
1428
+ revision = store.parentRecoveryRevision({ workspace: ctx.cwd, sessionId });
1416
1429
  } catch {
1417
1430
  return;
1418
1431
  }
1419
1432
  if (revision === this.lastChangeRevision && !this.pendingCallbackCursor) return;
1420
- this.lastChangeRevision = revision;
1421
1433
  let operations: OperationRecord[];
1422
1434
  try {
1423
- operations = this.activeParentTerminalOperations();
1435
+ operations = this.activeParentTerminalOperations(false, revision);
1424
1436
  } catch {
1437
+ this.lastChangeRevision = -1;
1425
1438
  return;
1426
1439
  }
1440
+ this.lastChangeRevision = revision;
1427
1441
  let newest = this.lastOwnedTerminalAt;
1428
1442
  let visibleOwner: OwnerIdentity | undefined;
1429
1443
  for (const operation of operations) {
@@ -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 = [
@@ -1,7 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/shared-operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
2
2
  // Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
3
3
  import { createHash, randomUUID } from "node:crypto";
4
- import { bumpChangeRevision } from "./discovery.domain.mjs";
5
4
  import { StoreError } from "./errors.domain.mjs";
6
5
  import { columnText, getRow, getRows, run } from "./sqlite.domain.mjs";
7
6
  import { requireWait, readPins } from "./rows.domain.mjs";
@@ -109,7 +108,6 @@ export function recordAssignmentOutcome(ctx, input) {
109
108
  for (const e of retained)
110
109
  run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
111
110
  run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
112
- bumpChangeRevision(ctx);
113
111
  return record;
114
112
  });
115
113
  }
@@ -1,6 +1,5 @@
1
1
  // Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
- import { bumpChangeRevision } from "./discovery.ts";
4
3
  import { StoreError } from "./errors.ts";
5
4
  import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
6
5
  import { requireWait, readPins } from "./rows.ts";
@@ -121,7 +120,6 @@ export function recordAssignmentOutcome(ctx: StoreContext, input: AssignmentOutc
121
120
  }
122
121
  for (const e of retained) run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
123
122
  run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
124
- bumpChangeRevision(ctx);
125
123
  return record;
126
124
  });
127
125
  }
@@ -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);
@@ -34,13 +34,15 @@ export function readDiscoveryClaim(ctx, scope) {
34
34
  return readClaim(ctx, requireId("scope", scope));
35
35
  }
36
36
  /** Read scope transfer and its discovery claim from one SQLite snapshot. */
37
- export function readDiscoveryState(ctx, scope) {
37
+ export function readDiscoveryState(ctx, scope, hostId) {
38
38
  scope = requireId("scope", scope);
39
39
  const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
40
40
  EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
41
- WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
42
- FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope);
43
- return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1 };
41
+ WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
42
+ EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
43
+ FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, hostId === undefined ? null : requireId("hostId", hostId), scope);
44
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
45
+ ...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
44
46
  }
45
47
  export function tryClaimDiscovery(ctx, input) {
46
48
  const scope = requireId("scope", input.scope);
@@ -49,13 +49,16 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
49
49
  }
50
50
 
51
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; hasAssignmentTasks: boolean } {
52
+ export function readDiscoveryState(ctx: StoreContext, scope: string, hostId?: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean; cleanupPending?: boolean } {
53
53
  scope = requireId("scope", scope);
54
54
  const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
55
55
  EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
56
- WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
57
- FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope)!;
58
- return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1 };
56
+ WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
57
+ EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
58
+ FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope,
59
+ hostId === undefined ? null : requireId("hostId", hostId), scope)!;
60
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
61
+ ...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
59
62
  }
60
63
 
61
64
  export function tryClaimDiscovery(
@@ -313,24 +313,17 @@ export function listOperations(ctx, filter = {}) {
313
313
  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)
314
314
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
315
315
  }
316
- export function listAssignmentCleanupOperations(ctx, limit, afterOperationId) {
316
+ export function listAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId) {
317
317
  const requested = requireCounter("limit", limit);
318
318
  if (requested === 0)
319
319
  throw new StoreError("validation", "Invalid limit: must be at least 1");
320
320
  const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
321
- // Seek the partial index in cursor order rather than sorting all running operations.
321
+ const params = hostId === undefined ? [] : [requireId("hostId", hostId)];
322
322
  return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
323
323
  WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
324
- FROM operations op INDEXED BY operations_assignment_cleanup
325
- JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
326
- JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
327
- WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
328
- AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
329
- OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
330
- AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
331
- AND e.summary LIKE '%groupCleanup=unproven%'))
332
- AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
333
- ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
324
+ FROM assignment_cleanup_pending p CROSS JOIN operations op ON op.operation_id = p.operation_id
325
+ WHERE ${hostId === undefined ? "" : "p.supervision_host_id = ? AND "}p.operation_id > ?
326
+ ORDER BY p.operation_id LIMIT ?`, ...params, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
334
327
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
335
328
  }
336
329
  /** Running operations assigned to one supervising host, using the phase/host index. */