pi-better-server 0.8.1 → 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 (41) hide show
  1. package/package.json +1 -1
  2. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +2 -2
  3. package/src/runtime/background-tools.ts +1 -1
  4. package/src/runtime/background.ts +9 -4
  5. package/src/runtime/domain/background-service/observed-waits.domain.mjs +20 -11
  6. package/src/runtime/domain/background-service/observed-waits.ts +24 -13
  7. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +34 -0
  8. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +33 -0
  9. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +4 -0
  10. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.ts +5 -0
  11. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +20 -1
  12. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +23 -1
  13. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +30 -13
  14. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +28 -11
  15. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +6 -3
  16. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +9 -3
  17. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +34 -0
  18. package/src/runtime/domain/coordinator/src/background-parent-callbacks.mjs +4 -0
  19. package/src/runtime/domain/coordinator/src/result-supervision.mjs +20 -1
  20. package/src/runtime/domain/coordinator/src/schema.mjs +30 -13
  21. package/src/runtime/domain/coordinator/src/store.mjs +6 -3
  22. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +14 -1
  23. package/src/runtime/domain/subagents/managed-launch-client.ts +15 -1
  24. package/src/runtime/domain/subagents/package.json +1 -1
  25. package/src/runtime/domain/subagents/registry.domain.mjs +32 -27
  26. package/src/runtime/domain/subagents/registry.ts +30 -23
  27. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +34 -0
  28. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +33 -0
  29. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +4 -0
  30. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts +5 -0
  31. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +20 -1
  32. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +23 -1
  33. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +30 -13
  34. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +28 -11
  35. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +6 -3
  36. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +9 -3
  37. package/src/runtime/domain/subagents/worker-waits.domain.mjs +3 -16
  38. package/src/runtime/domain/subagents/worker-waits.ts +3 -14
  39. package/src/runtime/result-supervision.ts +33 -10
  40. package/src/server.ts +8 -1
  41. package/src/version.ts +1 -1
@@ -3,7 +3,8 @@
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  import { getRow, run } from "./sqlite.domain.mjs";
5
5
  import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.domain.mjs";
6
- import { requireId, requirePath } from "./validate.domain.mjs";
6
+ import { mapOperation } from "./rows.domain.mjs";
7
+ import { requireCounter, requireId, requirePath } from "./validate.domain.mjs";
7
8
  const PREFIX = "result-supervision-v1:";
8
9
  /** A bounded observation page. A gap requires restoring active authority, not history. */
9
10
  export function resultSupervisionChanges(ctx, after) {
@@ -28,6 +29,24 @@ export function resultSupervision(ctx, operationId) {
28
29
  const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", PREFIX + requireId("operationId", operationId));
29
30
  return row ? JSON.parse(String(row.value)) : null;
30
31
  }
32
+ /** Changes that can make a server cleanup candidate eligible behind an idle scan cursor. */
33
+ export function serverAssignmentCleanupRevision(ctx) {
34
+ return Number(ctx.db.prepare("SELECT value FROM coordinator_state WHERE key='server-assignment-cleanup-revision'").get()?.value ?? 0);
35
+ }
36
+ /** Pending cleanup under the root daemon's result authority, including past epochs. */
37
+ export function serverAssignmentCleanup(ctx, limit, after) {
38
+ const host = after ? requireId("hostId", after.hostId) : "server:";
39
+ if (!host.startsWith("server:"))
40
+ throw new Error("Expected a server cleanup cursor");
41
+ // 'server;' is the exclusive upper bound of the 'server:' prefix in SQLite binary order.
42
+ const rows = ctx.db.prepare(`SELECT op.*, CASE WHEN json_valid(s.value) THEN s.value END AS grant_json
43
+ FROM assignment_cleanup_pending p
44
+ CROSS JOIN operations op ON op.operation_id = p.operation_id
45
+ CROSS JOIN coordinator_state s ON s.key = ? || p.operation_id
46
+ WHERE (p.supervision_host_id, p.operation_id) > (?, ?) AND p.supervision_host_id < 'server;'
47
+ ORDER BY p.supervision_host_id, p.operation_id LIMIT ?`).all(PREFIX, host, after ? requireId("operationId", after.operationId) : "", Math.min(256, requireCounter("limit", limit)));
48
+ return rows.map(row => ({ operation: mapOperation(row), grant: JSON.parse(String(row.grant_json)) }));
49
+ }
31
50
  /** The admitting host has stopped its local route before this exact-owner CAS. */
32
51
  export function handoffResultSupervision(ctx, input) {
33
52
  const operationId = requireId("operationId", input.operationId);
@@ -2,7 +2,8 @@
2
2
  import { isDeepStrictEqual } from "node:util";
3
3
  import { getRow, run, type StoreContext } from "./sqlite.ts";
4
4
  import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.ts";
5
- import { requireId, requirePath } from "./validate.ts";
5
+ import { mapOperation } from "./rows.ts";
6
+ import { requireCounter, requireId, requirePath } from "./validate.ts";
6
7
  import type { RecordTerminalOutcomeInput } from "./types.ts";
7
8
  import type { OwnerIdentity } from "./types.ts";
8
9
 
@@ -43,6 +44,27 @@ export function resultSupervision(ctx: StoreContext, operationId: string): Resul
43
44
  return row ? JSON.parse(String(row.value)) : null;
44
45
  }
45
46
 
47
+ /** Changes that can make a server cleanup candidate eligible behind an idle scan cursor. */
48
+ export function serverAssignmentCleanupRevision(ctx: StoreContext): number {
49
+ return Number(ctx.db.prepare("SELECT value FROM coordinator_state WHERE key='server-assignment-cleanup-revision'").get()?.value ?? 0);
50
+ }
51
+
52
+ /** Pending cleanup under the root daemon's result authority, including past epochs. */
53
+ export function serverAssignmentCleanup(ctx: StoreContext, limit: number, after?: { hostId: string; operationId: string }) {
54
+ const host = after ? requireId("hostId", after.hostId) : "server:";
55
+ if (!host.startsWith("server:")) throw new Error("Expected a server cleanup cursor");
56
+ // 'server;' is the exclusive upper bound of the 'server:' prefix in SQLite binary order.
57
+ const rows = ctx.db.prepare(`SELECT op.*, CASE WHEN json_valid(s.value) THEN s.value END AS grant_json
58
+ FROM assignment_cleanup_pending p
59
+ CROSS JOIN operations op ON op.operation_id = p.operation_id
60
+ CROSS JOIN coordinator_state s ON s.key = ? || p.operation_id
61
+ WHERE (p.supervision_host_id, p.operation_id) > (?, ?) AND p.supervision_host_id < 'server;'
62
+ ORDER BY p.supervision_host_id, p.operation_id LIMIT ?`).all(PREFIX,
63
+ host, after ? requireId("operationId", after.operationId) : "",
64
+ Math.min(256, requireCounter("limit", limit)));
65
+ return rows.map(row => ({ operation: mapOperation(row), grant: JSON.parse(String(row.grant_json)) as ResultSupervision | null }));
66
+ }
67
+
46
68
  /** The admitting host has stopped its local route before this exact-owner CAS. */
47
69
  export function handoffResultSupervision(ctx: StoreContext, input: {
48
70
  operationId: string; expectedHostId: string; directory: string; hostId: string; epoch: string;
@@ -104,6 +104,12 @@ const PENDING_CLEANUP_DDL = [
104
104
  DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
105
105
  END`,
106
106
  ];
107
+ // Legacy Windows clients can keep writing through an open connection after migration.
108
+ const WINDOWS_CLEANUP_PROOF_GUARD = `CREATE TRIGGER assignment_cleanup_windows_proof BEFORE INSERT ON coordinator_state
109
+ WHEN NEW.key GLOB 'assignment-cleanup-verified:*' AND NEW.value IS NOT (
110
+ SELECT 'v2:' || launch_token FROM operations
111
+ WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1))
112
+ BEGIN SELECT RAISE(IGNORE); END`;
107
113
  const DDL = [
108
114
  `CREATE TABLE task_cancellation_authorities (
109
115
  credential_hash TEXT PRIMARY KEY,
@@ -345,6 +351,8 @@ export function ensureSchema(ctx) {
345
351
  ctx.transaction(() => {
346
352
  for (const statement of [...DDL, ...EXPIRY_INDEXES])
347
353
  ctx.db.exec(statement);
354
+ if (process.platform === "win32")
355
+ ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
348
356
  run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
349
357
  });
350
358
  return;
@@ -397,23 +405,32 @@ function ensureAssignmentCleanupSchema(ctx) {
397
405
  ctx.db.exec(statement);
398
406
  const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
399
407
  const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
400
- if (hasPending())
408
+ const needsWindowsGuard = () => process.platform === "win32" &&
409
+ !getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND name = 'assignment_cleanup_windows_proof'");
410
+ if (hasPending() && !needsWindowsGuard())
401
411
  return;
402
412
  ctx.transaction(() => {
403
- if (hasPending())
413
+ const createQueue = !hasPending();
414
+ const installGuard = needsWindowsGuard();
415
+ if (!createQueue && !installGuard)
404
416
  return;
405
- ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
406
- // Legacy writers leave the nullable provenance unset.
407
- if (!hasColumn())
408
- ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
409
- ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
410
- for (const statement of PENDING_CLEANUP_DDL)
411
- ctx.db.exec(statement);
412
- if (process.platform === "win32") {
413
- // Earlier Windows writers mistook an unsupported group probe for proof of exit.
414
- ctx.db.exec("DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*'");
417
+ if (createQueue) {
418
+ ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
419
+ // Legacy writers leave the nullable provenance unset.
420
+ if (!hasColumn())
421
+ ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
422
+ ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
423
+ for (const statement of PENDING_CLEANUP_DDL)
424
+ ctx.db.exec(statement);
425
+ }
426
+ if (installGuard) {
427
+ ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
428
+ // Discard marks from writers which treated an unsupported Windows group probe as proof.
429
+ ctx.db.exec(`DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*' AND value IS NOT (
430
+ SELECT 'v2:' || launch_token FROM operations
431
+ WHERE operation_id = substr(coordinator_state.key, length('assignment-cleanup-verified:') + 1))`);
415
432
  }
416
- ctx.db.exec(`INSERT INTO assignment_cleanup_pending
433
+ ctx.db.exec(`INSERT OR IGNORE INTO assignment_cleanup_pending
417
434
  SELECT op.operation_id, op.supervision_host_id FROM operations op
418
435
  JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
419
436
  JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
@@ -111,6 +111,13 @@ const PENDING_CLEANUP_DDL = [
111
111
  END`,
112
112
  ];
113
113
 
114
+ // Legacy Windows clients can keep writing through an open connection after migration.
115
+ const WINDOWS_CLEANUP_PROOF_GUARD = `CREATE TRIGGER assignment_cleanup_windows_proof BEFORE INSERT ON coordinator_state
116
+ WHEN NEW.key GLOB 'assignment-cleanup-verified:*' AND NEW.value IS NOT (
117
+ SELECT 'v2:' || launch_token FROM operations
118
+ WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1))
119
+ BEGIN SELECT RAISE(IGNORE); END`;
120
+
114
121
  const DDL: readonly string[] = [
115
122
  `CREATE TABLE task_cancellation_authorities (
116
123
  credential_hash TEXT PRIMARY KEY,
@@ -360,6 +367,7 @@ export function ensureSchema(ctx: StoreContext): void {
360
367
  }
361
368
  ctx.transaction(() => {
362
369
  for (const statement of [...DDL, ...EXPIRY_INDEXES]) ctx.db.exec(statement);
370
+ if (process.platform === "win32") ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
363
371
  run(ctx, "INSERT INTO schema_meta (key, value) VALUES (?, ?)", SCHEMA_VERSION_KEY, String(SCHEMA_VERSION));
364
372
  });
365
373
  return;
@@ -418,19 +426,28 @@ function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
418
426
  for (const statement of EXPIRY_INDEXES) ctx.db.exec(statement);
419
427
  const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
420
428
  const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
421
- if (hasPending()) return;
429
+ const needsWindowsGuard = () => process.platform === "win32" &&
430
+ !getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND name = 'assignment_cleanup_windows_proof'");
431
+ if (hasPending() && !needsWindowsGuard()) return;
422
432
  ctx.transaction(() => {
423
- if (hasPending()) return;
424
- ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
425
- // Legacy writers leave the nullable provenance unset.
426
- if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
427
- ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
428
- for (const statement of PENDING_CLEANUP_DDL) ctx.db.exec(statement);
429
- if (process.platform === "win32") {
430
- // Earlier Windows writers mistook an unsupported group probe for proof of exit.
431
- ctx.db.exec("DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*'");
433
+ const createQueue = !hasPending();
434
+ const installGuard = needsWindowsGuard();
435
+ if (!createQueue && !installGuard) return;
436
+ if (createQueue) {
437
+ ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
438
+ // Legacy writers leave the nullable provenance unset.
439
+ if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
440
+ ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
441
+ for (const statement of PENDING_CLEANUP_DDL) ctx.db.exec(statement);
442
+ }
443
+ if (installGuard) {
444
+ ctx.db.exec(WINDOWS_CLEANUP_PROOF_GUARD);
445
+ // Discard marks from writers which treated an unsupported Windows group probe as proof.
446
+ ctx.db.exec(`DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*' AND value IS NOT (
447
+ SELECT 'v2:' || launch_token FROM operations
448
+ WHERE operation_id = substr(coordinator_state.key, length('assignment-cleanup-verified:') + 1))`);
432
449
  }
433
- ctx.db.exec(`INSERT INTO assignment_cleanup_pending
450
+ ctx.db.exec(`INSERT OR IGNORE INTO assignment_cleanup_pending
434
451
  SELECT op.operation_id, op.supervision_host_id FROM operations op
435
452
  JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
436
453
  JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
@@ -10,11 +10,11 @@
10
10
  */
11
11
  import { expireWaits, overdueOperations } from "./expiry.domain.mjs";
12
12
  import { setUpgradeFence } from "./upgrade.domain.mjs";
13
- import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks } from "./background-parent-callbacks.domain.mjs";
13
+ import { parentRecoveryRevision, setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks } from "./background-parent-callbacks.domain.mjs";
14
14
  import { BackgroundRequests } from "./background-requests.domain.mjs";
15
15
  import { StoreError } from "./errors.domain.mjs";
16
16
  import { SubagentLaunchJournal } from "./subagent-launch.domain.mjs";
17
- import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.domain.mjs";
17
+ import { serverAssignmentCleanup, serverAssignmentCleanupRevision, resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.domain.mjs";
18
18
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.domain.mjs";
19
19
  import { repairFailedResume } from "./recovery.domain.mjs";
20
20
  import { recordAssignmentOutcome, getAssignmentOutcome, inspectAssignmentOutcome, consumeAssignmentOutcome, registerAssignment, receiptAssignmentOutcome } from "./assignment-outcomes.domain.mjs";
@@ -59,6 +59,8 @@ export function openStore(options) {
59
59
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
60
60
  resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
61
61
  hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
62
+ serverAssignmentCleanupRevision() { alive(); return serverAssignmentCleanupRevision(ctx); },
63
+ serverAssignmentCleanup(limit, after) { alive(); return serverAssignmentCleanup(ctx, limit, after); },
62
64
  resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
63
65
  resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
64
66
  handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
@@ -88,6 +90,7 @@ export function openStore(options) {
88
90
  closed = true;
89
91
  db.close();
90
92
  },
93
+ parentRecoveryRevision(scope) { alive(); return parentRecoveryRevision(ctx, scope); },
91
94
  setParentCallbackPending(taskId, pending) { alive(); return setParentCallbackPending(ctx, taskId, pending); },
92
95
  listPendingParentCallbacks(scope, options) { alive(); return listPendingParentCallbacks(ctx, scope, options); },
93
96
  listRecentBackgroundTerminals(options) { alive(); return listRecentBackgroundTerminals(ctx, options); },
@@ -127,7 +130,7 @@ export function openStore(options) {
127
130
  if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1)
128
131
  return false;
129
132
  return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
130
- SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
133
+ SELECT 'assignment-cleanup-verified:' || op.operation_id, 'v2:' || op.launch_token
131
134
  FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
132
135
  JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
133
136
  WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`, operationId, launchToken, terminalRevision) > 0;
@@ -9,11 +9,11 @@
9
9
  */
10
10
  import { expireWaits, overdueOperations } from "./expiry.ts";
11
11
  import { setUpgradeFence } from "./upgrade.ts";
12
- import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
12
+ import { parentRecoveryRevision, setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
13
13
  import { BackgroundRequests } from "./background-requests.ts";
14
14
  import { StoreError } from "./errors.ts";
15
15
  import { SubagentLaunchJournal } from "./subagent-launch.ts";
16
- import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
16
+ import { serverAssignmentCleanup, serverAssignmentCleanupRevision, resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
17
17
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
18
18
  import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
19
19
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
@@ -131,6 +131,8 @@ export interface Store {
131
131
  overdueOperations(): OperationRecord[];
132
132
  expireWaits(): number;
133
133
  hasSubagentManagement(): boolean;
134
+ serverAssignmentCleanupRevision(): number;
135
+ serverAssignmentCleanup(limit: number, after?: Parameters<typeof serverAssignmentCleanup>[2]): ReturnType<typeof serverAssignmentCleanup>;
134
136
  resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
135
137
  subagentLaunchJournal(): SubagentLaunchJournal;
136
138
  resultScopeManaged(scope: string): boolean;
@@ -169,6 +171,7 @@ export interface Store {
169
171
  // ---- operations ----
170
172
 
171
173
  backgroundRequests(): BackgroundRequests;
174
+ parentRecoveryRevision(scope: ParentCallbackScope): number;
172
175
  setParentCallbackPending(taskId: string, pending: boolean): boolean;
173
176
  listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
174
177
  listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
@@ -369,6 +372,8 @@ export function openStore(options: StoreOptions): Store {
369
372
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
370
373
  resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
371
374
  hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
375
+ serverAssignmentCleanupRevision() { alive(); return serverAssignmentCleanupRevision(ctx); },
376
+ serverAssignmentCleanup(limit, after) { alive(); return serverAssignmentCleanup(ctx, limit, after); },
372
377
  resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
373
378
  resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
374
379
  handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
@@ -397,6 +402,7 @@ export function openStore(options: StoreOptions): Store {
397
402
  closed = true;
398
403
  db.close();
399
404
  },
405
+ parentRecoveryRevision(scope) { alive(); return parentRecoveryRevision(ctx, scope); },
400
406
  setParentCallbackPending(taskId, pending) { alive(); return setParentCallbackPending(ctx, taskId, pending); },
401
407
  listPendingParentCallbacks(scope, options) { alive(); return listPendingParentCallbacks(ctx, scope, options); },
402
408
  listRecentBackgroundTerminals(options) { alive(); return listRecentBackgroundTerminals(ctx, options); },
@@ -435,7 +441,7 @@ export function openStore(options: StoreOptions): Store {
435
441
  alive();
436
442
  if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1) return false;
437
443
  return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
438
- SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
444
+ SELECT 'assignment-cleanup-verified:' || op.operation_id, 'v2:' || op.launch_token
439
445
  FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
440
446
  JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
441
447
  WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`,
@@ -1196,14 +1196,7 @@ function parkedEntry(meta, record) {
1196
1196
  }
1197
1197
  /** Parked runs whose wait can still resume (including held ones). */
1198
1198
  export function parkedWaits() {
1199
- const parked = [];
1200
- for (const meta of listPendingParkedRuns()) {
1201
- const record = readParkRecord(meta.id);
1202
- if (!record || !isPendingPark(record))
1203
- continue;
1204
- parked.push(parkedEntry(meta, record));
1205
- }
1206
- return parked;
1199
+ return listPendingParkedRuns().map(meta => parkedEntry(meta, meta.park));
1207
1200
  }
1208
1201
  export function parkedWaitForRun(runId) {
1209
1202
  const meta = readMeta(runId);
@@ -1839,14 +1832,8 @@ export async function recoverStagedPark(park, service, options = {}) {
1839
1832
  }
1840
1833
  /** Every park record (any phase) that published `attemptId` as its resume. */
1841
1834
  export function parkedWaitsForResumedAttempt(attemptId) {
1842
- const found = [];
1843
- for (const meta of listParkRecordCandidates()) {
1844
- const record = readParkRecord(meta.id);
1845
- if (!record || record.resumedBy !== attemptId)
1846
- continue;
1847
- found.push(parkedEntry(meta, record));
1848
- }
1849
- return found;
1835
+ return listParkRecordCandidates(undefined, record => record.resumedBy === attemptId)
1836
+ .map(meta => parkedEntry(meta, meta.park));
1850
1837
  }
1851
1838
  /** Terminal for the purposes of "this attempt will never interpret the wait again". */
1852
1839
  export function isTerminalAttempt(meta) {
@@ -1670,13 +1670,7 @@ function parkedEntry(meta: RunMeta, record: ParkRecord): ParkedWait {
1670
1670
 
1671
1671
  /** Parked runs whose wait can still resume (including held ones). */
1672
1672
  export function parkedWaits(): ParkedWait[] {
1673
- const parked: ParkedWait[] = [];
1674
- for (const meta of listPendingParkedRuns()) {
1675
- const record = readParkRecord(meta.id);
1676
- if (!record || !isPendingPark(record)) continue;
1677
- parked.push(parkedEntry(meta, record));
1678
- }
1679
- return parked;
1673
+ return listPendingParkedRuns().map(meta => parkedEntry(meta, meta.park));
1680
1674
  }
1681
1675
 
1682
1676
  export function parkedWaitForRun(runId: string): ParkedWait | null {
@@ -2394,13 +2388,8 @@ export async function recoverStagedPark(
2394
2388
 
2395
2389
  /** Every park record (any phase) that published `attemptId` as its resume. */
2396
2390
  export function parkedWaitsForResumedAttempt(attemptId: string): ParkedWait[] {
2397
- const found: ParkedWait[] = [];
2398
- for (const meta of listParkRecordCandidates()) {
2399
- const record = readParkRecord(meta.id);
2400
- if (!record || record.resumedBy !== attemptId) continue;
2401
- found.push(parkedEntry(meta, record));
2402
- }
2403
- return found;
2391
+ return listParkRecordCandidates(undefined, record => record.resumedBy === attemptId)
2392
+ .map(meta => parkedEntry(meta, meta.park));
2404
2393
  }
2405
2394
 
2406
2395
  /** Terminal for the purposes of "this attempt will never interpret the wait again". */
@@ -8,7 +8,7 @@ import { createLocalSupervisor } from "./domain/background/supervisor/supervisor
8
8
  // @ts-expect-error Generated canonical durable stop records.
9
9
  import { readStopRequest } from "./domain/background/supervisor/store.mjs";
10
10
  // @ts-expect-error Generated canonical process identity checks.
11
- import { processGroupExitVerified } from "./domain/background/supervisor/identity.mjs";
11
+ import { processGroupExitVerified, verifyProcessIdentity } from "./domain/background/supervisor/identity.mjs";
12
12
  // @ts-expect-error Generated canonical terminal evidence rules.
13
13
  import { supervisorTerminalPublication } from "./domain/background/terminal-publication.mjs";
14
14
 
@@ -41,7 +41,8 @@ export class RuntimeResultSupervision {
41
41
  private assignmentCleanup?: Promise<void>;
42
42
  private closing?: Promise<void>;
43
43
  get busy() { return this.assignmentCleanup !== undefined; }
44
- private assignmentCleanupCursor?: string;
44
+ private assignmentCleanupCursor?: { hostId: string; operationId: string };
45
+ private idleCleanupCursor?: { hostId: string; operationId: string; revision: number };
45
46
  private assignmentCleanupReason?: string;
46
47
  get reason() { return this.assignmentCleanupReason ?? this.observationReason; }
47
48
  private verificationMs: number;
@@ -196,13 +197,34 @@ export class RuntimeResultSupervision {
196
197
  private reconcileAssignmentCleanup() {
197
198
  if (this.assignmentCleanup) return;
198
199
  const cursor = this.assignmentCleanupCursor;
199
- const [operation] = this.store.listAssignmentCleanupOperations(1, cursor);
200
- this.assignmentCleanupCursor = operation?.operationId;
201
- if (!operation) {
202
- if (cursor === undefined) this.assignmentCleanupReason = undefined;
203
- return;
204
- }
205
- const grant = this.store.resultSupervision(operation.operationId);
200
+ const [candidate] = this.store.serverAssignmentCleanup(1, cursor);
201
+ this.assignmentCleanupCursor = candidate && { hostId: candidate.operation.supervision.hostId, operationId: candidate.operation.operationId };
202
+ if (candidate) this.advanceAssignmentCleanup(candidate);
203
+ else if (!cursor) this.assignmentCleanupReason = undefined;
204
+ }
205
+
206
+ /** At idle, inspect the durable queue even when the last stop promise has settled. */
207
+ hasCleanupAtIdle(revision: number): boolean {
208
+ if (this.assignmentCleanup) return true;
209
+ const release = this.budget.enter("control");
210
+ if (!release) return true;
211
+ try {
212
+ const after = this.idleCleanupCursor?.revision === revision ? this.idleCleanupCursor : undefined;
213
+ const page = this.store.serverAssignmentCleanup(ENTITY_BUDGET, after);
214
+ this.idleCleanupCursor = undefined;
215
+ for (const candidate of page) {
216
+ try { this.advanceAssignmentCleanup(candidate); }
217
+ catch (error) { this.assignmentCleanupReason = `Assignment cleanup for ${candidate.operation.taskId}: ${String(error)}`; }
218
+ if (this.assignmentCleanup) return true;
219
+ }
220
+ if (page.length < ENTITY_BUDGET) return false;
221
+ const last = page.at(-1).operation;
222
+ this.idleCleanupCursor = { hostId: last.supervision.hostId, operationId: last.operationId, revision };
223
+ return true;
224
+ } finally { release(); }
225
+ }
226
+
227
+ private advanceAssignmentCleanup({ operation, grant }: { operation: any; grant: any }) {
206
228
  if (!grant || (operation.terminalRevision === 0 && grant.epoch !== this.epoch) || grant.launchToken !== operation.launchToken || grant.hostId !== operation.supervision?.hostId ||
207
229
  grant.capability?.adapter !== "background-results-v1" || !grant.capability.captured || !grant.capability.current) {
208
230
  this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: exact supervision authority unavailable`;
@@ -224,7 +246,8 @@ export class RuntimeResultSupervision {
224
246
  return;
225
247
  }
226
248
  this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: process group exit unverified`;
227
- if (!pgid) return;
249
+ // A group with an unprovable leader stays on the durable queue for recovery.
250
+ if (!pgid || verifyProcessIdentity(inspection.command.pid, inspection.command.pidStartTime) !== "verified") return;
228
251
  }
229
252
  this.assignmentCleanup = supervisor.stop(operation.taskId, { token: operation.launchToken, reason: "owning assignment ended" })
230
253
  .catch((error: unknown) => { this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: ${String(error)}`; })
package/src/server.ts CHANGED
@@ -135,7 +135,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
135
135
  }
136
136
  }
137
137
  };
138
- if (controlStore.store.resultSupervisions(true).length || controlStore.store.listAssignmentCleanupOperations(1).length) {
138
+ if (controlStore.store.resultSupervisions(true).length || controlStore.store.serverAssignmentCleanup(1).length) {
139
139
  resultSupervision = new RuntimeResultSupervision(resultRoot, instanceId!, config.runtimeIdleMs);
140
140
  }
141
141
  resultPorts.set(resultRoot, resultPort);
@@ -687,6 +687,13 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
687
687
  }
688
688
  // No create/open can slip between this check and the synchronous admission fence.
689
689
  if (runtimeClients.size > 0 || registry.activeCount > 0 || inFlight > 0 || launches?.busy || backgroundTools?.busy || resultSupervision?.busy || cancellations?.busy || sessionMaintenance?.busy || nativeHost.busy || registry.hasPendingOperations) return;
690
+ // An assignment can end after startup or between two asynchronous stops.
691
+ const cleanupRevision = controlStore.store.serverAssignmentCleanupRevision();
692
+ if (!resultSupervision && controlStore.store.serverAssignmentCleanup(1).length) {
693
+ resultSupervision = new RuntimeResultSupervision(resultRoot, instanceId!, config.runtimeIdleMs);
694
+ }
695
+ if (resultSupervision?.hasCleanupAtIdle(cleanupRevision) || resultSupervision?.livenessReasons().length) return;
696
+ if (controlStore.store.serverAssignmentCleanupRevision() !== cleanupRevision) return;
690
697
  draining = true;
691
698
  idleStopping = true;
692
699
  idleEvidence = { at: now(), deadline: hostedUsed ? zeroSince! + config.daemonIdleMs : runtimeZeroSince! + config.runtimeIdleMs,
package/src/version.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** Kept equal to package.json `version`; a test pins that. */
2
- export const SERVER_VERSION = "0.8.1";
2
+ export const SERVER_VERSION = "0.8.2";
3
3
 
4
4
  export const SERVER_EXTENSION_VERSIONS: Readonly<Record<string, string>> = { "pi-better-server": SERVER_VERSION };