pi-better-server 0.7.3 → 0.8.1

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 (82) hide show
  1. package/package.json +1 -1
  2. package/src/runtime/background-tools.ts +146 -6
  3. package/src/runtime/background.ts +2 -2
  4. package/src/runtime/catalog.ts +30 -1
  5. package/src/runtime/ci-recovery.ts +172 -0
  6. package/src/runtime/domain/assignment-inbox.mjs +4 -0
  7. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  8. package/src/runtime/domain/assignment-observation.mjs +1 -0
  9. package/src/runtime/domain/background/supervisor/identity.mjs +5 -0
  10. package/src/runtime/domain/background/supervisor/supervisor.mjs +3 -4
  11. package/src/runtime/domain/background-service/ci-observation.domain.mjs +134 -0
  12. package/src/runtime/domain/background-service/ci-observation.ts +118 -0
  13. package/src/runtime/domain/background-service/managed-client.domain.mjs +6 -2
  14. package/src/runtime/domain/background-service/managed-client.ts +6 -2
  15. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +47 -7
  16. package/src/runtime/domain/background-service/managed-frontend.ts +36 -6
  17. package/src/runtime/domain/background-service/observed-waits.domain.mjs +36 -7
  18. package/src/runtime/domain/background-service/observed-waits.ts +33 -6
  19. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  20. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +1 -0
  21. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  22. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  23. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  24. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +7 -4
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  26. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +5 -11
  27. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +53 -1
  28. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +54 -1
  29. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -3
  30. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -5
  31. package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +5 -0
  32. package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +5 -0
  33. package/src/runtime/domain/background-service/supervisor/identity.ts +6 -0
  34. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +3 -4
  35. package/src/runtime/domain/background-service/supervisor/supervisor.ts +3 -4
  36. package/src/runtime/domain/catalog/catalog-schema.d.mts +6 -0
  37. package/src/runtime/domain/catalog/catalog-schema.mjs +1 -0
  38. package/src/runtime/domain/catalog/roles/role.supervisor.md +16 -0
  39. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +0 -2
  40. package/src/runtime/domain/coordinator/src/discovery.mjs +6 -4
  41. package/src/runtime/domain/coordinator/src/operations.mjs +5 -12
  42. package/src/runtime/domain/coordinator/src/schema.mjs +53 -1
  43. package/src/runtime/domain/coordinator/src/store.mjs +3 -3
  44. package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1 -0
  45. package/src/runtime/domain/subagents/catalog-schema.ts +1 -0
  46. package/src/runtime/domain/subagents/cleanup.domain.mjs +7 -10
  47. package/src/runtime/domain/subagents/cleanup.ts +6 -8
  48. package/src/runtime/domain/subagents/package.json +1 -1
  49. package/src/runtime/domain/subagents/registry.domain.mjs +9 -7
  50. package/src/runtime/domain/subagents/registry.ts +11 -6
  51. package/src/runtime/domain/subagents/retained-result.domain.mjs +3 -3
  52. package/src/runtime/domain/subagents/retained-result.ts +2 -3
  53. package/src/runtime/domain/subagents/roles/role.supervisor.md +16 -0
  54. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +14 -2
  55. package/src/runtime/domain/subagents/shared-catalog.ts +14 -2
  56. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  57. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +1 -0
  58. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  59. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  60. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  61. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +7 -4
  62. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  63. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +5 -11
  64. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +53 -1
  65. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +54 -1
  66. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -3
  67. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -5
  68. package/src/runtime/domain/subagents/supervisor-client.mjs +36 -0
  69. package/src/runtime/domain/subagents/worker-waits.domain.mjs +3 -4
  70. package/src/runtime/domain/subagents/worker-waits.ts +3 -3
  71. package/src/runtime/domain/subagents/workspace-files.domain.mjs +19 -5
  72. package/src/runtime/domain/subagents/workspace-files.ts +27 -5
  73. package/src/runtime/queries.ts +17 -3
  74. package/src/runtime/query-executor.ts +46 -3
  75. package/src/runtime/query-worker.mjs +6 -1
  76. package/src/runtime/read-model.ts +14 -5
  77. package/src/runtime/result-supervision.ts +16 -5
  78. package/src/runtime/shared-read-diagnosis.ts +29 -0
  79. package/src/runtime/supervisor-admission.ts +42 -0
  80. package/src/runtime/supervisor-decisions.ts +60 -0
  81. package/src/server.ts +9 -8
  82. package/src/version.ts +1 -1
@@ -77,8 +77,9 @@ 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
+ import { ciObserverArgv, ciRunFromArgv, validCiRun } from "./ci-observation.js";
82
83
  import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
83
84
  import type { SpawnTaskParams, WatchTaskParams } from "./runtime.js";
84
85
 
@@ -575,6 +576,7 @@ function rpcCode(error: unknown): string {
575
576
  }
576
577
 
577
578
  export interface ObservedWaitHostOptions {
579
+ currentOutcomeId?: () => string | undefined;
578
580
  /** Fixed server admission guard, checked immediately before external dispatch. */
579
581
  assertAdmission?: () => void;
580
582
  /** Fixed native adapter alone may authorize an explicit cross-owner stop. */
@@ -687,6 +689,7 @@ interface LaunchContext {
687
689
  readonly supervisionPolicy?: ForegroundSandboxPlan;
688
690
  /** Owner branch anchor captured at launch (undefined when unavailable). */
689
691
  readonly branchId?: string | null;
692
+ readonly ciObservation?: { repo: string; runId: string; attempt: number; outcomeId: string };
690
693
  callbackPendingAt?: number;
691
694
  callbackDeliveredAt?: number;
692
695
  callbackDeferredReason?: string;
@@ -1296,10 +1299,13 @@ export class ObservedWaitHost {
1296
1299
  if (!this.store || this.closed) return;
1297
1300
  this.authorityPassCache = new Map();
1298
1301
  try {
1299
- const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope);
1302
+ const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope, this.hostId);
1300
1303
  if (this.options.serverOwnedResults || discovery?.managed) {
1301
1304
  this.releaseDiscoveryAuthority();
1302
- if (!this.options.serverOwnedResults) this.reconcileFollowerRunning();
1305
+ if (!this.options.serverOwnedResults) {
1306
+ this.reconcileFollowerRunning();
1307
+ if (discovery?.cleanupPending) await this.reconcileAssignmentCleanup();
1308
+ }
1303
1309
  this.reconcileOwnerChanges();
1304
1310
  this.retryPendingTerminalCallbacks();
1305
1311
  await this.dispatchOutbox();
@@ -1310,11 +1316,11 @@ export class ObservedWaitHost {
1310
1316
  if (role === "holder") {
1311
1317
  this.discoverObservedTasks();
1312
1318
  this.reconcileGlobalRunning();
1313
- if (discovery!.hasAssignmentTasks) await this.reconcileAssignmentCleanup();
1314
1319
  } else {
1315
1320
  this.reconcileFollowerRunning();
1316
1321
  this.reconcileOwnerChanges();
1317
1322
  }
1323
+ if (discovery?.cleanupPending) await this.reconcileAssignmentCleanup();
1318
1324
  this.retryPendingTerminalCallbacks();
1319
1325
  await this.dispatchOutbox();
1320
1326
  } finally {
@@ -1324,7 +1330,7 @@ export class ObservedWaitHost {
1324
1330
 
1325
1331
  private async reconcileAssignmentCleanup(): Promise<void> {
1326
1332
  const store = this.requireStore();
1327
- const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
1333
+ const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor, this.hostId);
1328
1334
  this.assignmentCleanupCursor = candidate?.operationId;
1329
1335
  if (!candidate || candidate.resultManaged || this.supervisionAuthority(candidate) !== "self") return;
1330
1336
  const { taskId, launchToken } = candidate;
@@ -1335,7 +1341,7 @@ export class ObservedWaitHost {
1335
1341
  if (inspection.terminal) {
1336
1342
  if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven") return;
1337
1343
  const pgid = inspection.command?.pgid ?? inspection.command?.pid;
1338
- if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
1344
+ if (processGroupExitVerified(pgid, inspection.cleanup?.groupEmpty)) {
1339
1345
  store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
1340
1346
  return;
1341
1347
  }
@@ -1534,6 +1540,9 @@ export class ObservedWaitHost {
1534
1540
  authorityRef: this.parentAuthority(owner, prepared.plan),
1535
1541
  intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
1536
1542
  });
1543
+ const outcomeId = this.options.currentOutcomeId?.();
1544
+ const ciRun = outcomeId && !prepared.spec.env && prepared.cwd === owner.workspace
1545
+ ? ciRunFromArgv(input.kind, ciObserverArgv(prepared.spec)) : undefined;
1537
1546
  const launchContext: LaunchContext = {
1538
1547
  kind: input.kind,
1539
1548
  parentOrigin: this.parentOrigin,
@@ -1546,6 +1555,7 @@ export class ObservedWaitHost {
1546
1555
  sandbox: prepared.provenance,
1547
1556
  supervisionPolicy: prepared.plan,
1548
1557
  branchId: owner.branchId ?? null,
1558
+ ...(ciRun && outcomeId ? { ciObservation: { ...ciRun, outcomeId } } : {}),
1549
1559
  };
1550
1560
  // Persist supervision metadata outside the task execution record so a
1551
1561
  // replacement host can still notify the right parent and never re-route a
@@ -1799,6 +1809,21 @@ export class ObservedWaitHost {
1799
1809
  return this.projectDurable(operation, now);
1800
1810
  }
1801
1811
 
1812
+ /** Resolve exact owner and immutable launch/terminal evidence, not a display projection. */
1813
+ ciObservation(origin: BackgroundTaskCallbackOrigin, taskId: string, outcomeId: string, branchIds: readonly string[]) {
1814
+ if (!LOCAL_DURABLE_ID.test(taskId)) return;
1815
+ const operation = this.operationForTask(taskId);
1816
+ if (!operation || !this.belongsToParentOrigin(operation, origin)
1817
+ || !operation.owner.branchId || !branchIds.includes(operation.owner.branchId)) return;
1818
+ const directory = this.observationDirectory(operation);
1819
+ if (!directory) return;
1820
+ const context = this.readLaunchContext(taskId, directory);
1821
+ if (!context?.ciObservation || context.ciObservation.outcomeId !== outcomeId || context.dismissedAt !== undefined) return;
1822
+ const inspection = this.passiveSnapshot(taskId, directory);
1823
+ if (!inspection || inspection.token !== operation.launchToken) return;
1824
+ return { run: context.ciObservation, operation, inspection, policy: context.supervisionPolicy, callback: context.callback };
1825
+ }
1826
+
1802
1827
  /** Rebuild a live incident from the runner checkpoint. Only the native handoff writes its receipt. */
1803
1828
  pendingStallAlert(origin: BackgroundTaskCallbackOrigin, taskId: string, waits: readonly { waitId: string; generation: number }[]) {
1804
1829
  const operation = this.operationForTask(taskId);
@@ -4484,6 +4509,8 @@ export class ObservedWaitHost {
4484
4509
  ...(value.supervisionPolicy && typeof value.supervisionPolicy === "object"
4485
4510
  ? { supervisionPolicy: value.supervisionPolicy } : {}),
4486
4511
  ...(typeof value.branchId === "string" || value.branchId === null ? { branchId: value.branchId } : {}),
4512
+ ...(value.ciObservation && typeof value.ciObservation.outcomeId === "string" && validCiRun(value.ciObservation)
4513
+ ? { ciObservation: value.ciObservation } : {}),
4487
4514
  ...(typeof value.callbackPendingAt === "number" ? { callbackPendingAt: value.callbackPendingAt } : {}),
4488
4515
  ...(typeof value.callbackDeliveredAt === "number" ? { callbackDeliveredAt: value.callbackDeliveredAt }
4489
4516
  : typeof (value as { callbackNotifiedAt?: unknown }).callbackNotifiedAt === "number"
@@ -129,6 +129,9 @@ export class AssignmentInbox {
129
129
  throw error;
130
130
  }
131
131
  }
132
+ get hasPendingChanges() {
133
+ return Boolean(this.more || this.db.prepare(`SELECT 1 FROM ${this.prefix}pending LIMIT 1`).get());
134
+ }
132
135
  get metrics() {
133
136
  const pending = this.db.prepare(`SELECT count(*) AS pending, min(since) AS oldestPendingAt FROM ${this.prefix}pending`).get();
134
137
  return { ...this.db.prepare(`SELECT * FROM ${this.prefix}position`).get(),
@@ -102,6 +102,7 @@ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConn
102
102
  this.revision(); return db; },
103
103
  changes() { this.revision(); return inbox.receive(db, identity); },
104
104
  acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
105
+ get hasPendingChanges() { return inbox.hasPendingChanges; },
105
106
  get changeMetrics() { return inbox.metrics; },
106
107
  get snapshotActive() { return snapshot; },
107
108
  beginSnapshot() {
@@ -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
  }
@@ -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. */
@@ -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
 
@@ -68,6 +68,42 @@ const EXPIRY_INDEXES = [
68
68
  const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
69
69
  ON operations (operation_id, assignment_attempt_id)
70
70
  WHERE assignment_attempt_id IS NOT NULL`;
71
+ // Terminal evidence is written before the operation's terminal revision in the same transaction.
72
+ function needsAssignmentCleanup(row) {
73
+ return `(${row}.terminal_revision = 0 OR ${row}.terminal_outcome = 'lost' OR EXISTS (
74
+ SELECT 1 FROM operation_evidence e WHERE e.operation_id = ${row}.operation_id
75
+ AND e.terminal_revision = ${row}.terminal_revision AND e.kind = 'terminal-record'
76
+ AND e.summary LIKE '%groupCleanup=unproven%'))`;
77
+ }
78
+ const CLEANUP_FOR_ASSIGNMENT = `SELECT op.operation_id, op.supervision_host_id
79
+ FROM assignment_attempts a JOIN operations op ON op.assignment_attempt_id = a.attempt_id
80
+ WHERE a.assignment_id = NEW.assignment_id AND ${needsAssignmentCleanup("op")}`;
81
+ // Triggers also cover older processes that still have an open coordinator connection.
82
+ const PENDING_CLEANUP_DDL = [
83
+ `CREATE TABLE IF NOT EXISTS assignment_cleanup_pending (
84
+ operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
85
+ supervision_host_id TEXT
86
+ ) WITHOUT ROWID`,
87
+ `CREATE INDEX assignment_cleanup_host ON assignment_cleanup_pending(supervision_host_id, operation_id)`,
88
+ `CREATE INDEX assignment_attempts_by_assignment ON assignment_attempts(assignment_id, attempt_id)`,
89
+ `CREATE INDEX operations_by_assignment_attempt ON operations(assignment_attempt_id)
90
+ WHERE assignment_attempt_id IS NOT NULL`,
91
+ `CREATE TRIGGER assignment_cleanup_enqueue AFTER INSERT ON assignment_outcomes BEGIN
92
+ INSERT INTO assignment_cleanup_pending ${CLEANUP_FOR_ASSIGNMENT};
93
+ END`,
94
+ `CREATE TRIGGER assignment_cleanup_terminal AFTER UPDATE OF terminal_revision ON operations
95
+ WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.terminal_revision > 0 AND NOT ${needsAssignmentCleanup("NEW")} BEGIN
96
+ DELETE FROM assignment_cleanup_pending WHERE operation_id = NEW.operation_id;
97
+ END`,
98
+ `CREATE TRIGGER assignment_cleanup_transfer AFTER UPDATE OF supervision_host_id ON operations
99
+ WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.supervision_host_id IS NOT OLD.supervision_host_id BEGIN
100
+ UPDATE assignment_cleanup_pending SET supervision_host_id = NEW.supervision_host_id WHERE operation_id = NEW.operation_id;
101
+ END`,
102
+ `CREATE TRIGGER assignment_cleanup_verified AFTER INSERT ON coordinator_state
103
+ WHEN NEW.key GLOB 'assignment-cleanup-verified:*' BEGIN
104
+ DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
105
+ END`,
106
+ ];
71
107
  const DDL = [
72
108
  `CREATE TABLE task_cancellation_authorities (
73
109
  credential_hash TEXT PRIMARY KEY,
@@ -289,6 +325,7 @@ const DDL = [
289
325
  PRIMARY KEY (wait_id, generation)
290
326
  )`,
291
327
  RESULT_ADMISSION_FENCE,
328
+ ...PENDING_CLEANUP_DDL,
292
329
  ];
293
330
  const SCHEMA_VERSION_KEY = "schema_version";
294
331
  function existingTables(ctx) {
@@ -359,14 +396,29 @@ function ensureAssignmentCleanupSchema(ctx) {
359
396
  for (const statement of EXPIRY_INDEXES)
360
397
  ctx.db.exec(statement);
361
398
  const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
362
- if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'"))
399
+ const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
400
+ if (hasPending())
363
401
  return;
364
402
  ctx.transaction(() => {
403
+ if (hasPending())
404
+ return;
365
405
  ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
366
406
  // Legacy writers leave the nullable provenance unset.
367
407
  if (!hasColumn())
368
408
  ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
369
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:*'");
415
+ }
416
+ ctx.db.exec(`INSERT INTO assignment_cleanup_pending
417
+ SELECT op.operation_id, op.supervision_host_id FROM operations op
418
+ JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
419
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
420
+ WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
421
+ WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
370
422
  });
371
423
  }
372
424
  /**
@@ -72,6 +72,45 @@ 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
+
75
114
  const DDL: readonly string[] = [
76
115
  `CREATE TABLE task_cancellation_authorities (
77
116
  credential_hash TEXT PRIMARY KEY,
@@ -293,6 +332,7 @@ const DDL: readonly string[] = [
293
332
  PRIMARY KEY (wait_id, generation)
294
333
  )`,
295
334
  RESULT_ADMISSION_FENCE,
335
+ ...PENDING_CLEANUP_DDL,
296
336
  ];
297
337
 
298
338
  const SCHEMA_VERSION_KEY = "schema_version";
@@ -377,12 +417,25 @@ export function ensureSchema(ctx: StoreContext): void {
377
417
  function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
378
418
  for (const statement of EXPIRY_INDEXES) ctx.db.exec(statement);
379
419
  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;
420
+ const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
421
+ if (hasPending()) return;
381
422
  ctx.transaction(() => {
423
+ if (hasPending()) return;
382
424
  ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
383
425
  // Legacy writers leave the nullable provenance unset.
384
426
  if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
385
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:*'");
432
+ }
433
+ ctx.db.exec(`INSERT INTO assignment_cleanup_pending
434
+ SELECT op.operation_id, op.supervision_host_id FROM operations op
435
+ JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
436
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
437
+ WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
438
+ WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
386
439
  });
387
440
  }
388
441
 
@@ -118,9 +118,9 @@ export function openStore(options) {
118
118
  alive();
119
119
  return readOperationRecords(ctx, filter);
120
120
  },
121
- listAssignmentCleanupOperations(limit, afterOperationId) {
121
+ listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
122
122
  alive();
123
- return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
123
+ return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
124
124
  },
125
125
  verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
126
126
  alive();
@@ -140,7 +140,7 @@ export function openStore(options) {
140
140
  alive();
141
141
  return readOperationEvidence(ctx, requireId("operationId", operationId), terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision));
142
142
  },
143
- readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
143
+ readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
144
144
  readDiscoveryClaim(scope) {
145
145
  alive();
146
146
  return readClaim(ctx, scope);
@@ -207,7 +207,7 @@ export interface Store {
207
207
  * Read up to 256 unfinished cleanup obligations in operation id order.
208
208
  * The cursor is exclusive. Start each new sweep without a cursor.
209
209
  */
210
- listAssignmentCleanupOperations(limit: number, afterOperationId?: string): OperationRecord[];
210
+ listAssignmentCleanupOperations(limit: number, afterOperationId?: string, hostId?: string): OperationRecord[];
211
211
  verifyAssignmentCleanup(operationId: string, launchToken: string, terminalRevision: number): boolean;
212
212
  /** Running operations currently assigned to this supervising host. */
213
213
  listRunningSupervisedBy(hostId: string): OperationRecord[];
@@ -217,7 +217,7 @@ export interface Store {
217
217
 
218
218
  /** The shared discovery leader for this store/supervisor scope, if recorded. */
219
219
  readDiscoveryClaim(scope: string): DiscoveryClaimRecord | null;
220
- readDiscoveryState(scope: string): ReturnType<typeof readDiscoveryState>;
220
+ readDiscoveryState(scope: string, hostId?: string): ReturnType<typeof readDiscoveryState>;
221
221
  /**
222
222
  * Compare-and-swap a discovery claim. The caller must name the exact claim it
223
223
  * observed, or null for none; a stale contender receives null and must not
@@ -427,9 +427,9 @@ export function openStore(options: StoreOptions): Store {
427
427
  alive();
428
428
  return readOperationRecords(ctx, filter);
429
429
  },
430
- listAssignmentCleanupOperations(limit, afterOperationId) {
430
+ listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
431
431
  alive();
432
- return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
432
+ return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
433
433
  },
434
434
  verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
435
435
  alive();
@@ -453,7 +453,7 @@ export function openStore(options: StoreOptions): Store {
453
453
  terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision),
454
454
  );
455
455
  },
456
- readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
456
+ readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
457
457
  readDiscoveryClaim(scope) {
458
458
  alive();
459
459
  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
+ }
@@ -91,3 +91,8 @@ export function processGroupAlive(pgid) {
91
91
  return error.code !== "ESRCH";
92
92
  }
93
93
  }
94
+ /** Windows has no POSIX group probe. Older cleanup records used that probe there too. */
95
+ export function processGroupExitVerified(pgid, recordedEmpty = false) {
96
+ return process.platform !== "win32" && (recordedEmpty ||
97
+ (pgid !== undefined && Number.isSafeInteger(pgid) && pgid > 0 && !processGroupAlive(pgid)));
98
+ }
@@ -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.domain.mjs";
27
27
  import { stopProcessGroup } from "../process.domain.mjs";
28
- import { identityAlive, identityAllowsSignals, processGroupAlive, readStartToken, verifyProcessIdentity } from "./identity.domain.mjs";
28
+ import { identityAlive, identityAllowsSignals, processGroupAlive, processGroupExitVerified, readStartToken, verifyProcessIdentity } from "./identity.domain.mjs";
29
29
  import { supervisorRunnerInvocation } from "./invocation.domain.mjs";
30
30
  import { appendEvent, ensureSupervisorTaskDir, launchRequestHash, readClaimRecord, readCleanupRecord, readCommandRecord, readLaunchRecord, readLostRecord, readStopRequest, readTerminalRecord, resolveSupervisorDirectory, supervisorPaths, supervisorTaskIdForToken, SupervisorFenceBusyError, withStateFence, writeCleanupRecord, writeLaunchRecord, writeLostRecord, writeStopRequest, writeTerminalRecord, } from "./store.domain.mjs";
31
31
  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.domain.mjs";
@@ -607,8 +607,7 @@ class Supervisor {
607
607
  // Unknown identity cannot authorize an external signal. A recorded process
608
608
  // that is gone is only "already gone" when its group is gone too; survivors
609
609
  // in a group whose leader died cannot be verified, so they are refused.
610
- const groupStillAlive = processGroupAlive(pgid);
611
- outcome = (verdict === "dead" || verdict === "absent") && !groupStillAlive ? "already-gone" : "refused-unknown-identity";
610
+ outcome = (verdict === "dead" || verdict === "absent") && processGroupExitVerified(pgid) ? "already-gone" : "refused-unknown-identity";
612
611
  groupEmpty = outcome === "already-gone" ? true : false;
613
612
  }
614
613
  else {
@@ -643,7 +642,7 @@ class Supervisor {
643
642
  while (Date.now() < killDeadline && processGroupAlive(pgid)) {
644
643
  await delay(25);
645
644
  }
646
- groupEmpty = !processGroupAlive(pgid);
645
+ groupEmpty = processGroupExitVerified(pgid);
647
646
  outcome = !groupEmpty ? "unproven" : signalledWhileVerified ? "killed" : "already-gone";
648
647
  }
649
648
  const reason = outcome === "killed"
@@ -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
 
@@ -74,6 +74,12 @@ export declare const APPROVED_ROLE_DEFAULTS: readonly [{
74
74
  readonly model: "openai/gpt-6-astra";
75
75
  readonly effort: "high";
76
76
  readonly tier: "frontier";
77
+ }, {
78
+ readonly id: "role.supervisor";
79
+ readonly name: "Supervisor";
80
+ readonly model: "openai/gpt-6.1-sol";
81
+ readonly effort: "medium";
82
+ readonly tier: "balanced";
77
83
  }, {
78
84
  readonly id: "role.writer";
79
85
  readonly name: "Writer";
@@ -71,6 +71,7 @@ export const APPROVED_ROLE_DEFAULTS = [
71
71
  { id: "role.developer", name: "Developer", model: "openai/gpt-6.1-sol", effort: "high", tier: "balanced" },
72
72
  { id: "role.reviewer", name: "Reviewer", model: "openai/gpt-6-astra", effort: "medium", tier: "frontier" },
73
73
  { id: "role.architect", name: "Architect", model: "openai/gpt-6-astra", effort: "high", tier: "frontier" },
74
+ { id: "role.supervisor", name: "Supervisor", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
74
75
  { id: "role.writer", name: "Writer", model: "openai/gpt-6.1-terra", effort: "medium", tier: undefined },
75
76
  ];
76
77
  export const DiagnosticCodes = {