pi-better-background-tasks 0.21.0 → 0.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.21.0",
3
+ "version": "0.21.2",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"f07f0ac547bcc01ddfb5d273f2cddb0c2c8ff9743466bf01bf7c37338e0160d5","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.0","contentId":"d724478c0095b68f6add8eb7254d05c9a4123634d19f3c1cebbef137b008a171"},"sha256":"672067dec2318dbe1d1eb2d958a6d459240cfda560f0224b6f6d964281d8b506"}
1
+ {"build":{"format":1,"sourceDigest":"c02d951603064af3401fd640dfd2c05b18ae97299509a55db82d58aa5c69a2f0","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.2","contentId":"d72a5f1211f34ae97dc84b1c891a38714ab7c41c429332549d4a115af142cd9c"},"sha256":"0286673fe48ab8553727b4794b39721ddb96573b9c31b885918ee4d1df0c1a68"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"f07f0ac547bcc01ddfb5d273f2cddb0c2c8ff9743466bf01bf7c37338e0160d5","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.0","contentId":"dde6692a582af9624f3a25fe630dab03cbe5fe8764c579a5b6003d9108642f73"},"sha256":"439146e7ba045e5e469fa332331f82eb930886b327947f98f72e763aa981fe84"}
1
+ {"build":{"format":1,"sourceDigest":"c02d951603064af3401fd640dfd2c05b18ae97299509a55db82d58aa5c69a2f0","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.2","contentId":"0357f903ca7cbcc813194f224e3e1816c0abade6322e8d1321f4b07c8df4a08c"},"sha256":"3f9e9896c4c7b46b6a147e618883616aef287eb5c5a54cb214175354a4741d9b"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"f07f0ac547bcc01ddfb5d273f2cddb0c2c8ff9743466bf01bf7c37338e0160d5","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.0","contentId":"8f15d59e446ed2c1d7cd4553b660cfcaf7bf320ee85e22a68001824a3cc2227b"},"sha256":"25abbfbf5f51171d999662360af4d117ce61a4f7c5a2e0a19ca8688b8d99bb5c"}
1
+ {"build":{"format":1,"sourceDigest":"c02d951603064af3401fd640dfd2c05b18ae97299509a55db82d58aa5c69a2f0","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.2","contentId":"9f205935cb4aee5fb4d817661f86939716c909213b47775c2dcf83f9755122d1"},"sha256":"e02abd34422fba070bc44c59ab190ee61f69b9f2a6c9d926e64485461bfb48ad"}
@@ -1 +1 @@
1
- {"build":{"format":1,"sourceDigest":"f07f0ac547bcc01ddfb5d273f2cddb0c2c8ff9743466bf01bf7c37338e0160d5","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.0","contentId":"5997e3a37e35aa17657ad455657d48a9888e0fcac075b93edbb357d6efcd479e"},"sha256":"7a073f9c9ef40cae1e7612e7a9a1fca2e712e04aec754f4e3b802c218107b84f"}
1
+ {"build":{"format":1,"sourceDigest":"c02d951603064af3401fd640dfd2c05b18ae97299509a55db82d58aa5c69a2f0","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.2","contentId":"36ab9cbfc092b10d96f6d83473057fd4552929ff53ec3972caee1ed83ef50242"},"sha256":"2cfa925caa8783e13a9b92dbe0e8fcac28bbe048978bbdbb08c9f4de78ab2bf1"}
@@ -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) {
@@ -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,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
  }
@@ -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);
@@ -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(
@@ -467,23 +467,17 @@ export function listAssignmentCleanupOperations(
467
467
  ctx: StoreContext,
468
468
  limit: number,
469
469
  afterOperationId?: string,
470
+ hostId?: string,
470
471
  ): OperationRecord[] {
471
472
  const requested = requireCounter("limit", limit);
472
473
  if (requested === 0) throw new StoreError("validation", "Invalid limit: must be at least 1");
473
474
  const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
474
- // Seek the partial index in cursor order rather than sorting all running operations.
475
+ const params = hostId === undefined ? [] : [requireId("hostId", hostId)];
475
476
  return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
476
477
  WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
477
- FROM operations op INDEXED BY operations_assignment_cleanup
478
- JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
479
- JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
480
- WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
481
- AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
482
- OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
483
- AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
484
- AND e.summary LIKE '%groupCleanup=unproven%'))
485
- AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
486
- ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
478
+ FROM assignment_cleanup_pending p CROSS JOIN operations op ON op.operation_id = p.operation_id
479
+ WHERE ${hostId === undefined ? "" : "p.supervision_host_id = ? AND "}p.operation_id > ?
480
+ ORDER BY p.operation_id LIMIT ?`, ...params, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
487
481
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
488
482
  }
489
483
 
@@ -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;
@@ -72,6 +72,52 @@ const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignme
72
72
  ON operations (operation_id, assignment_attempt_id)
73
73
  WHERE assignment_attempt_id IS NOT NULL`;
74
74
 
75
+ // Terminal evidence is written before the operation's terminal revision in the same transaction.
76
+ function needsAssignmentCleanup(row: "op" | "NEW"): string {
77
+ return `(${row}.terminal_revision = 0 OR ${row}.terminal_outcome = 'lost' OR EXISTS (
78
+ SELECT 1 FROM operation_evidence e WHERE e.operation_id = ${row}.operation_id
79
+ AND e.terminal_revision = ${row}.terminal_revision AND e.kind = 'terminal-record'
80
+ AND e.summary LIKE '%groupCleanup=unproven%'))`;
81
+ }
82
+
83
+ const CLEANUP_FOR_ASSIGNMENT = `SELECT op.operation_id, op.supervision_host_id
84
+ FROM assignment_attempts a JOIN operations op ON op.assignment_attempt_id = a.attempt_id
85
+ WHERE a.assignment_id = NEW.assignment_id AND ${needsAssignmentCleanup("op")}`;
86
+
87
+ // Triggers also cover older processes that still have an open coordinator connection.
88
+ const PENDING_CLEANUP_DDL = [
89
+ `CREATE TABLE IF NOT EXISTS assignment_cleanup_pending (
90
+ operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
91
+ supervision_host_id TEXT
92
+ ) WITHOUT ROWID`,
93
+ `CREATE INDEX assignment_cleanup_host ON assignment_cleanup_pending(supervision_host_id, operation_id)`,
94
+ `CREATE INDEX assignment_attempts_by_assignment ON assignment_attempts(assignment_id, attempt_id)`,
95
+ `CREATE INDEX operations_by_assignment_attempt ON operations(assignment_attempt_id)
96
+ WHERE assignment_attempt_id IS NOT NULL`,
97
+ `CREATE TRIGGER assignment_cleanup_enqueue AFTER INSERT ON assignment_outcomes BEGIN
98
+ INSERT INTO assignment_cleanup_pending ${CLEANUP_FOR_ASSIGNMENT};
99
+ END`,
100
+ `CREATE TRIGGER assignment_cleanup_terminal AFTER UPDATE OF terminal_revision ON operations
101
+ WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.terminal_revision > 0 AND NOT ${needsAssignmentCleanup("NEW")} BEGIN
102
+ DELETE FROM assignment_cleanup_pending WHERE operation_id = NEW.operation_id;
103
+ END`,
104
+ `CREATE TRIGGER assignment_cleanup_transfer AFTER UPDATE OF supervision_host_id ON operations
105
+ WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.supervision_host_id IS NOT OLD.supervision_host_id BEGIN
106
+ UPDATE assignment_cleanup_pending SET supervision_host_id = NEW.supervision_host_id WHERE operation_id = NEW.operation_id;
107
+ END`,
108
+ `CREATE TRIGGER assignment_cleanup_verified AFTER INSERT ON coordinator_state
109
+ WHEN NEW.key GLOB 'assignment-cleanup-verified:*' BEGIN
110
+ DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
111
+ END`,
112
+ ];
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
+
75
121
  const DDL: readonly string[] = [
76
122
  `CREATE TABLE task_cancellation_authorities (
77
123
  credential_hash TEXT PRIMARY KEY,
@@ -293,6 +339,7 @@ const DDL: readonly string[] = [
293
339
  PRIMARY KEY (wait_id, generation)
294
340
  )`,
295
341
  RESULT_ADMISSION_FENCE,
342
+ ...PENDING_CLEANUP_DDL,
296
343
  ];
297
344
 
298
345
  const SCHEMA_VERSION_KEY = "schema_version";
@@ -320,6 +367,7 @@ export function ensureSchema(ctx: StoreContext): void {
320
367
  }
321
368
  ctx.transaction(() => {
322
369
  for (const statement of [...DDL, ...EXPIRY_INDEXES]) ctx.db.exec(statement);
370
+ if (process.platform === "win32") ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
323
371
  run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
324
372
  });
325
373
  return;
@@ -377,12 +425,34 @@ export function ensureSchema(ctx: StoreContext): void {
377
425
  function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
378
426
  for (const statement of EXPIRY_INDEXES) ctx.db.exec(statement);
379
427
  const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
380
- if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'")) return;
428
+ const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
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;
381
432
  ctx.transaction(() => {
382
- ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
383
- // Legacy writers leave the nullable provenance unset.
384
- if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
385
- ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
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))`);
449
+ }
450
+ ctx.db.exec(`INSERT OR IGNORE INTO assignment_cleanup_pending
451
+ SELECT op.operation_id, op.supervision_host_id FROM operations op
452
+ JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
453
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
454
+ WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
455
+ WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
386
456
  });
387
457
  }
388
458
 
@@ -9,11 +9,11 @@
9
9
  */
10
10
  import { expireWaits, overdueOperations } from "./expiry.ts";
11
11
  import { setUpgradeFence } from "./upgrade.ts";
12
- import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
12
+ import { parentRecoveryRevision, setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
13
13
  import { BackgroundRequests } from "./background-requests.ts";
14
14
  import { StoreError } from "./errors.ts";
15
15
  import { SubagentLaunchJournal } from "./subagent-launch.ts";
16
- import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
16
+ import { serverAssignmentCleanup, serverAssignmentCleanupRevision, resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
17
17
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
18
18
  import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
19
19
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
@@ -131,6 +131,8 @@ export interface Store {
131
131
  overdueOperations(): OperationRecord[];
132
132
  expireWaits(): number;
133
133
  hasSubagentManagement(): boolean;
134
+ serverAssignmentCleanupRevision(): number;
135
+ serverAssignmentCleanup(limit: number, after?: Parameters<typeof serverAssignmentCleanup>[2]): ReturnType<typeof serverAssignmentCleanup>;
134
136
  resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
135
137
  subagentLaunchJournal(): SubagentLaunchJournal;
136
138
  resultScopeManaged(scope: string): boolean;
@@ -169,6 +171,7 @@ export interface Store {
169
171
  // ---- operations ----
170
172
 
171
173
  backgroundRequests(): BackgroundRequests;
174
+ parentRecoveryRevision(scope: ParentCallbackScope): number;
172
175
  setParentCallbackPending(taskId: string, pending: boolean): boolean;
173
176
  listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
174
177
  listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
@@ -207,7 +210,7 @@ export interface Store {
207
210
  * Read up to 256 unfinished cleanup obligations in operation id order.
208
211
  * The cursor is exclusive. Start each new sweep without a cursor.
209
212
  */
210
- listAssignmentCleanupOperations(limit: number, afterOperationId?: string): OperationRecord[];
213
+ listAssignmentCleanupOperations(limit: number, afterOperationId?: string, hostId?: string): OperationRecord[];
211
214
  verifyAssignmentCleanup(operationId: string, launchToken: string, terminalRevision: number): boolean;
212
215
  /** Running operations currently assigned to this supervising host. */
213
216
  listRunningSupervisedBy(hostId: string): OperationRecord[];
@@ -217,7 +220,7 @@ export interface Store {
217
220
 
218
221
  /** The shared discovery leader for this store/supervisor scope, if recorded. */
219
222
  readDiscoveryClaim(scope: string): DiscoveryClaimRecord | null;
220
- readDiscoveryState(scope: string): ReturnType<typeof readDiscoveryState>;
223
+ readDiscoveryState(scope: string, hostId?: string): ReturnType<typeof readDiscoveryState>;
221
224
  /**
222
225
  * Compare-and-swap a discovery claim. The caller must name the exact claim it
223
226
  * observed, or null for none; a stale contender receives null and must not
@@ -369,6 +372,8 @@ export function openStore(options: StoreOptions): Store {
369
372
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
370
373
  resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
371
374
  hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
375
+ serverAssignmentCleanupRevision() { alive(); return serverAssignmentCleanupRevision(ctx); },
376
+ serverAssignmentCleanup(limit, after) { alive(); return serverAssignmentCleanup(ctx, limit, after); },
372
377
  resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
373
378
  resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
374
379
  handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
@@ -397,6 +402,7 @@ export function openStore(options: StoreOptions): Store {
397
402
  closed = true;
398
403
  db.close();
399
404
  },
405
+ parentRecoveryRevision(scope) { alive(); return parentRecoveryRevision(ctx, scope); },
400
406
  setParentCallbackPending(taskId, pending) { alive(); return setParentCallbackPending(ctx, taskId, pending); },
401
407
  listPendingParentCallbacks(scope, options) { alive(); return listPendingParentCallbacks(ctx, scope, options); },
402
408
  listRecentBackgroundTerminals(options) { alive(); return listRecentBackgroundTerminals(ctx, options); },
@@ -427,15 +433,15 @@ export function openStore(options: StoreOptions): Store {
427
433
  alive();
428
434
  return readOperationRecords(ctx, filter);
429
435
  },
430
- listAssignmentCleanupOperations(limit, afterOperationId) {
436
+ listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
431
437
  alive();
432
- return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
438
+ return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
433
439
  },
434
440
  verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
435
441
  alive();
436
442
  if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1) return false;
437
443
  return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
438
- SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
444
+ SELECT 'assignment-cleanup-verified:' || op.operation_id, 'v2:' || op.launch_token
439
445
  FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
440
446
  JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
441
447
  WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`,
@@ -453,7 +459,7 @@ export function openStore(options: StoreOptions): Store {
453
459
  terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision),
454
460
  );
455
461
  },
456
- readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
462
+ readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
457
463
  readDiscoveryClaim(scope) {
458
464
  alive();
459
465
  return readClaim(ctx, scope);
@@ -93,3 +93,8 @@ export function processGroupAlive(pgid) {
93
93
  return error.code !== "ESRCH";
94
94
  }
95
95
  }
96
+ /** Windows has no POSIX group probe. Older cleanup records used that probe there too. */
97
+ export function processGroupExitVerified(pgid, recordedEmpty = false) {
98
+ return process.platform !== "win32" && (recordedEmpty ||
99
+ (pgid !== undefined && Number.isSafeInteger(pgid) && pgid > 0 && !processGroupAlive(pgid)));
100
+ }
@@ -97,3 +97,9 @@ export function processGroupAlive(pgid: number | undefined): boolean {
97
97
  return (error as NodeJS.ErrnoException).code !== "ESRCH";
98
98
  }
99
99
  }
100
+
101
+ /** Windows has no POSIX group probe. Older cleanup records used that probe there too. */
102
+ export function processGroupExitVerified(pgid: number | undefined, recordedEmpty = false): boolean {
103
+ return process.platform !== "win32" && (recordedEmpty ||
104
+ (pgid !== undefined && Number.isSafeInteger(pgid) && pgid > 0 && !processGroupAlive(pgid)));
105
+ }
@@ -25,7 +25,7 @@ import { join, resolve } from "node:path";
25
25
  import { setTimeout as delay } from "node:timers/promises";
26
26
  import { validateCondition } from "../conditions.ts";
27
27
  import { stopProcessGroup } from "../process.ts";
28
- import { identityAlive, identityAllowsSignals, processGroupAlive, readStartToken, verifyProcessIdentity } from "./identity.ts";
28
+ import { identityAlive, identityAllowsSignals, processGroupAlive, processGroupExitVerified, readStartToken, verifyProcessIdentity } from "./identity.ts";
29
29
  import type { ProcessIdentityVerdict } from "./identity.ts";
30
30
  import { supervisorRunnerInvocation } from "./invocation.ts";
31
31
  import {
@@ -685,8 +685,7 @@ class Supervisor implements LocalSupervisor {
685
685
  // Unknown identity cannot authorize an external signal. A recorded process
686
686
  // that is gone is only "already gone" when its group is gone too; survivors
687
687
  // in a group whose leader died cannot be verified, so they are refused.
688
- const groupStillAlive = processGroupAlive(pgid);
689
- outcome = (verdict === "dead" || verdict === "absent") && !groupStillAlive ? "already-gone" : "refused-unknown-identity";
688
+ outcome = (verdict === "dead" || verdict === "absent") && processGroupExitVerified(pgid) ? "already-gone" : "refused-unknown-identity";
690
689
  groupEmpty = outcome === "already-gone" ? true : false;
691
690
  } else {
692
691
  /**
@@ -717,7 +716,7 @@ class Supervisor implements LocalSupervisor {
717
716
  while (Date.now() < killDeadline && processGroupAlive(pgid)) {
718
717
  await delay(25);
719
718
  }
720
- groupEmpty = !processGroupAlive(pgid);
719
+ groupEmpty = processGroupExitVerified(pgid);
721
720
  outcome = !groupEmpty ? "unproven" : signalledWhileVerified ? "killed" : "already-gone";
722
721
  }
723
722