pi-better-server 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/package.json +1 -1
  2. package/scripts/measure-full-runtime/recovery-trace-loader.mjs +2 -2
  3. package/src/runtime/background-tools.ts +1 -1
  4. package/src/runtime/background.ts +9 -4
  5. package/src/runtime/domain/background/supervisor/identity.mjs +5 -0
  6. package/src/runtime/domain/background/supervisor/supervisor.mjs +3 -4
  7. package/src/runtime/domain/background-service/observed-waits.domain.mjs +30 -18
  8. package/src/runtime/domain/background-service/observed-waits.ts +33 -19
  9. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +34 -0
  10. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +33 -0
  11. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  12. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  13. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +4 -0
  14. package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-parent-callbacks.ts +5 -0
  15. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  16. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +7 -4
  17. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  18. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +5 -11
  19. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +20 -1
  20. package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +23 -1
  21. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +75 -6
  22. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +75 -5
  23. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +9 -6
  24. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +14 -8
  25. package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +5 -0
  26. package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +5 -0
  27. package/src/runtime/domain/background-service/supervisor/identity.ts +6 -0
  28. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +3 -4
  29. package/src/runtime/domain/background-service/supervisor/supervisor.ts +3 -4
  30. package/src/runtime/domain/coordinator/src/assignment-changes.mjs +34 -0
  31. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +0 -2
  32. package/src/runtime/domain/coordinator/src/background-parent-callbacks.mjs +4 -0
  33. package/src/runtime/domain/coordinator/src/discovery.mjs +6 -4
  34. package/src/runtime/domain/coordinator/src/operations.mjs +5 -12
  35. package/src/runtime/domain/coordinator/src/result-supervision.mjs +20 -1
  36. package/src/runtime/domain/coordinator/src/schema.mjs +75 -6
  37. package/src/runtime/domain/coordinator/src/store.mjs +9 -6
  38. package/src/runtime/domain/subagents/cleanup.domain.mjs +7 -10
  39. package/src/runtime/domain/subagents/cleanup.ts +6 -8
  40. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +14 -1
  41. package/src/runtime/domain/subagents/managed-launch-client.ts +15 -1
  42. package/src/runtime/domain/subagents/package.json +1 -1
  43. package/src/runtime/domain/subagents/registry.domain.mjs +34 -27
  44. package/src/runtime/domain/subagents/registry.ts +36 -24
  45. package/src/runtime/domain/subagents/retained-result.domain.mjs +3 -3
  46. package/src/runtime/domain/subagents/retained-result.ts +2 -3
  47. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +34 -0
  48. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +33 -0
  49. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  50. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  51. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.domain.mjs +4 -0
  52. package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-parent-callbacks.ts +5 -0
  53. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  54. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +7 -4
  55. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  56. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +5 -11
  57. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +20 -1
  58. package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +23 -1
  59. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +75 -6
  60. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +75 -5
  61. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +9 -6
  62. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +14 -8
  63. package/src/runtime/domain/subagents/worker-waits.domain.mjs +6 -20
  64. package/src/runtime/domain/subagents/worker-waits.ts +6 -17
  65. package/src/runtime/domain/subagents/workspace-files.domain.mjs +19 -5
  66. package/src/runtime/domain/subagents/workspace-files.ts +27 -5
  67. package/src/runtime/result-supervision.ts +46 -12
  68. package/src/server.ts +14 -6
  69. package/src/version.ts +1 -1
@@ -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); },
@@ -118,16 +121,16 @@ export function openStore(options) {
118
121
  alive();
119
122
  return readOperationRecords(ctx, filter);
120
123
  },
121
- listAssignmentCleanupOperations(limit, afterOperationId) {
124
+ listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
122
125
  alive();
123
- return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
126
+ return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
124
127
  },
125
128
  verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
126
129
  alive();
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;
@@ -140,7 +143,7 @@ export function openStore(options) {
140
143
  alive();
141
144
  return readOperationEvidence(ctx, requireId("operationId", operationId), terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision));
142
145
  },
143
- readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
146
+ readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
144
147
  readDiscoveryClaim(scope) {
145
148
  alive();
146
149
  return readClaim(ctx, scope);
@@ -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);
@@ -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) {
@@ -2157,10 +2144,9 @@ export async function reconcileParkedWaits(service, outerOptions) {
2157
2144
  // Consumed waits cannot resume, but a missed exit observer may have left
2158
2145
  // their published writer claim behind. Reconcile that exact claim once.
2159
2146
  const candidates = [];
2160
- for await (const { meta, record } of scanParkRecords()) {
2161
- if (!isPendingPark(record) && !(record.phase === "consumed" && record.resumedBy
2162
- && record.resumeClaimId && record.resumeExitReconciledClaimId !== record.resumeClaimId))
2163
- continue;
2147
+ const needsReconciliation = (record) => isPendingPark(record) || (record.phase === "consumed"
2148
+ && !!record.resumedBy && !!record.resumeClaimId && record.resumeExitReconciledClaimId !== record.resumeClaimId);
2149
+ for await (const { meta, record } of scanParkRecords(undefined, needsReconciliation)) {
2164
2150
  candidates.push(parkedEntry(meta, record));
2165
2151
  }
2166
2152
  // Release earlier writers before admitting later waits in the conversation.
@@ -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". */
@@ -2719,9 +2708,9 @@ export async function reconcileParkedWaits(
2719
2708
  // Consumed waits cannot resume, but a missed exit observer may have left
2720
2709
  // their published writer claim behind. Reconcile that exact claim once.
2721
2710
  const candidates: ParkedWait[] = [];
2722
- for await (const { meta, record } of scanParkRecords()) {
2723
- if (!isPendingPark(record) && !(record.phase === "consumed" && record.resumedBy
2724
- && record.resumeClaimId && record.resumeExitReconciledClaimId !== record.resumeClaimId)) continue;
2711
+ const needsReconciliation = (record: ParkRecord) => isPendingPark(record) || (record.phase === "consumed"
2712
+ && !!record.resumedBy && !!record.resumeClaimId && record.resumeExitReconciledClaimId !== record.resumeClaimId);
2713
+ for await (const { meta, record } of scanParkRecords(undefined, needsReconciliation)) {
2725
2714
  candidates.push(parkedEntry(meta, record));
2726
2715
  }
2727
2716
  // Release earlier writers before admitting later waits in the conversation.
@@ -2,7 +2,7 @@
2
2
  // A private content store lets retained checkouts share identical Git objects and files.
3
3
  // Source files are never hardlinked into storage. Restoring a file makes an independent copy.
4
4
  import { createHash, randomUUID } from "node:crypto";
5
- import { chmodSync, closeSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, } from "node:fs";
5
+ import { chmodSync, closeSync, constants, copyFileSync, cpSync, existsSync, lchmodSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, } from "node:fs";
6
6
  import { dirname, join } from "node:path";
7
7
  function fileHash(path, buffer) {
8
8
  const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
@@ -71,7 +71,7 @@ export function snapshotTree(root, store, omit = new Set()) {
71
71
  walk("");
72
72
  return entries;
73
73
  }
74
- export function restoreTree(root, store, entries) {
74
+ function materializeTree(root, entries, copyRegularFile) {
75
75
  mkdirSync(root, { recursive: true, mode: 0o700 });
76
76
  const directories = new Set(["."]);
77
77
  for (const entry of entries) {
@@ -84,11 +84,12 @@ export function restoreTree(root, store, entries) {
84
84
  mkdirSync(dest);
85
85
  directories.add(entry.name);
86
86
  }
87
- else if (entry.type === "symlink")
87
+ else if (entry.type === "symlink") {
88
88
  symlinkSync(entry.target, dest);
89
+ lchmodSync?.(dest, entry.mode);
90
+ }
89
91
  else {
90
- copyFileSync(blobPath(store, entry.blob), dest, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
91
- chmodSync(dest, entry.mode);
92
+ copyRegularFile(entry, dest);
92
93
  }
93
94
  }
94
95
  for (const entry of entries.slice().reverse()) {
@@ -96,6 +97,19 @@ export function restoreTree(root, store, entries) {
96
97
  chmodSync(join(root, entry.name), entry.mode);
97
98
  }
98
99
  }
100
+ export function restoreTree(root, store, entries) {
101
+ materializeTree(root, entries, (entry, dest) => {
102
+ copyFileSync(blobPath(store, entry.blob), dest, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
103
+ chmodSync(dest, entry.mode);
104
+ });
105
+ }
106
+ export function copyTree(source, dest, entries) {
107
+ const rootMode = lstatSync(source).mode & 0o7777;
108
+ materializeTree(dest, entries, (entry, target) => {
109
+ cpSync(join(source, entry.name), target, { verbatimSymlinks: true, force: false, errorOnExist: true });
110
+ });
111
+ chmodSync(dest, rootMode);
112
+ }
99
113
  export function verifyTree(root, entries, omit) {
100
114
  if (JSON.stringify(snapshotTree(root, undefined, omit)) !== JSON.stringify(entries)) {
101
115
  throw new Error("Workspace contents changed or could not be recovered at " + root);
@@ -6,7 +6,9 @@ import {
6
6
  closeSync,
7
7
  constants,
8
8
  copyFileSync,
9
+ cpSync,
9
10
  existsSync,
11
+ lchmodSync,
10
12
  lstatSync,
11
13
  mkdirSync,
12
14
  openSync,
@@ -84,7 +86,11 @@ export function snapshotTree(root: string, store?: string, omit: ReadonlySet<str
84
86
  return entries;
85
87
  }
86
88
 
87
- export function restoreTree(root: string, store: string, entries: SavedEntry[]): void {
89
+ function materializeTree(
90
+ root: string,
91
+ entries: SavedEntry[],
92
+ copyRegularFile: (entry: Extract<SavedEntry, { type: "file" }>, dest: string) => void,
93
+ ): void {
88
94
  mkdirSync(root, { recursive: true, mode: 0o700 });
89
95
  const directories = new Set(["."]);
90
96
  for (const entry of entries) {
@@ -96,10 +102,11 @@ export function restoreTree(root: string, store: string, entries: SavedEntry[]):
96
102
  if (entry.type === "directory") {
97
103
  mkdirSync(dest);
98
104
  directories.add(entry.name);
99
- } else if (entry.type === "symlink") symlinkSync(entry.target, dest);
100
- else {
101
- copyFileSync(blobPath(store, entry.blob), dest, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
102
- chmodSync(dest, entry.mode);
105
+ } else if (entry.type === "symlink") {
106
+ symlinkSync(entry.target, dest);
107
+ lchmodSync?.(dest, entry.mode);
108
+ } else {
109
+ copyRegularFile(entry, dest);
103
110
  }
104
111
  }
105
112
  for (const entry of entries.slice().reverse()) {
@@ -107,6 +114,21 @@ export function restoreTree(root: string, store: string, entries: SavedEntry[]):
107
114
  }
108
115
  }
109
116
 
117
+ export function restoreTree(root: string, store: string, entries: SavedEntry[]): void {
118
+ materializeTree(root, entries, (entry, dest) => {
119
+ copyFileSync(blobPath(store, entry.blob), dest, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
120
+ chmodSync(dest, entry.mode);
121
+ });
122
+ }
123
+
124
+ export function copyTree(source: string, dest: string, entries: SavedEntry[]): void {
125
+ const rootMode = lstatSync(source).mode & 0o7777;
126
+ materializeTree(dest, entries, (entry, target) => {
127
+ cpSync(join(source, entry.name), target, { verbatimSymlinks: true, force: false, errorOnExist: true });
128
+ });
129
+ chmodSync(dest, rootMode);
130
+ }
131
+
110
132
  export function verifyTree(root: string, entries: SavedEntry[], omit?: ReadonlySet<string>): void {
111
133
  if (JSON.stringify(snapshotTree(root, undefined, omit)) !== JSON.stringify(entries)) {
112
134
  throw new Error("Workspace contents changed or could not be recovered at " + root);
@@ -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 { processGroupAlive } 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
 
@@ -39,7 +39,10 @@ export class RuntimeResultSupervision {
39
39
  readonly epoch: string;
40
40
  private observationReason?: string;
41
41
  private assignmentCleanup?: Promise<void>;
42
- private assignmentCleanupCursor?: string;
42
+ private closing?: Promise<void>;
43
+ get busy() { return this.assignmentCleanup !== undefined; }
44
+ private assignmentCleanupCursor?: { hostId: string; operationId: string };
45
+ private idleCleanupCursor?: { hostId: string; operationId: string; revision: number };
43
46
  private assignmentCleanupReason?: string;
44
47
  get reason() { return this.assignmentCleanupReason ?? this.observationReason; }
45
48
  private verificationMs: number;
@@ -193,13 +196,35 @@ export class RuntimeResultSupervision {
193
196
  }
194
197
  private reconcileAssignmentCleanup() {
195
198
  if (this.assignmentCleanup) return;
196
- const [operation] = this.store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
197
- this.assignmentCleanupCursor = operation?.operationId;
198
- if (!operation) {
199
- if (!this.store.listAssignmentCleanupOperations(1).length) this.assignmentCleanupReason = undefined;
200
- return;
201
- }
202
- const grant = this.store.resultSupervision(operation.operationId);
199
+ const cursor = this.assignmentCleanupCursor;
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 }) {
203
228
  if (!grant || (operation.terminalRevision === 0 && grant.epoch !== this.epoch) || grant.launchToken !== operation.launchToken || grant.hostId !== operation.supervision?.hostId ||
204
229
  grant.capability?.adapter !== "background-results-v1" || !grant.capability.captured || !grant.capability.current) {
205
230
  this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: exact supervision authority unavailable`;
@@ -216,20 +241,29 @@ export class RuntimeResultSupervision {
216
241
  if (inspection.terminal) {
217
242
  if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven") return;
218
243
  const pgid = inspection.command?.pgid ?? inspection.command?.pid;
219
- if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
244
+ if (processGroupExitVerified(pgid, inspection.cleanup?.groupEmpty)) {
220
245
  this.store.verifyAssignmentCleanup(operation.operationId, operation.launchToken, operation.terminalRevision);
221
246
  return;
222
247
  }
223
248
  this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: process group exit unverified`;
224
- 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;
225
251
  }
226
252
  this.assignmentCleanup = supervisor.stop(operation.taskId, { token: operation.launchToken, reason: "owning assignment ended" })
227
253
  .catch((error: unknown) => { this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: ${String(error)}`; })
228
254
  .finally(() => { this.assignmentCleanup = undefined; });
229
255
  }
230
256
  close() {
257
+ if (this.closing) return this.closing;
231
258
  this.closed = true; if (this.timer) clearTimeout(this.timer); this.watcher?.close();
232
259
  for (const watcher of this.taskWatchers.values()) watcher.close();
233
- this.taskWatchers.clear(); this.releaseStore();
260
+ this.taskWatchers.clear();
261
+ if (this.assignmentCleanup) {
262
+ this.closing = this.assignmentCleanup.then(() => this.releaseStore());
263
+ } else {
264
+ this.releaseStore();
265
+ this.closing = Promise.resolve();
266
+ }
267
+ return this.closing;
234
268
  }
235
269
  }
package/src/server.ts CHANGED
@@ -126,7 +126,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
126
126
  finally {
127
127
  try { await cancellations?.close(); }
128
128
  finally {
129
- resultSupervision?.close();
129
+ await resultSupervision?.close();
130
130
  controlStore.release();
131
131
  if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
132
132
  try { await (await launchInitialization?.catch(() => undefined))?.close();
@@ -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);
@@ -301,6 +301,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
301
301
  livenessReasons: [...[...runtimeClients.values()].map(id => ({ kind: "connection", id })),
302
302
  ...requests.values(),
303
303
  ...registry.lifecycleReasons(),
304
+ ...(resultSupervision?.busy ? [{ kind: "assignment-cleanup", id: resultSupervision.hostId }] : []),
304
305
  ...(resultSupervision?.livenessReasons() ?? []),
305
306
  ...(launches?.lifecycleReasons() ?? []),
306
307
  ...(backgroundTools?.lifecycleReasons() ?? []),
@@ -571,7 +572,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
571
572
  await cancellations?.close();
572
573
  await (await launchInitialization?.catch(() => undefined))?.close();
573
574
  await (await backgroundInitialization?.catch(() => undefined))?.close();
574
- resultSupervision?.close();
575
+ await resultSupervision?.close();
575
576
  controlStore.release();
576
577
  if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
577
578
  await workModel?.close();
@@ -628,7 +629,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
628
629
  upgradeBlockers = await work().upgradeObligations();
629
630
  if (upgradeBlockers.length) throw new Error(`Waiting for runtime work: ${JSON.stringify(upgradeBlockers)}`);
630
631
  if (launches?.cleaningRegistry) throw new Error("Waiting for subagent registry cleanup");
631
- if (inFlight > 0 || cancellations?.busy) throw new Error("Waiting for in-flight runtime admission");
632
+ if (inFlight > 0 || resultSupervision?.busy || cancellations?.busy) throw new Error("Waiting for in-flight runtime admission");
632
633
  commitActivationStop(request, lease, () => { draining = true; upgradeCommitted = true; });
633
634
  for (const hosted of live) {
634
635
  (hosted as HostedSession & { publishRuntimeEvent(event: unknown): void }).publishRuntimeEvent({
@@ -685,7 +686,14 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
685
686
  log(`runtime observation unavailable at idle shutdown: ${String(error)}`);
686
687
  }
687
688
  // No create/open can slip between this check and the synchronous admission fence.
688
- if (runtimeClients.size > 0 || registry.activeCount > 0 || inFlight > 0 || launches?.busy || backgroundTools?.busy || cancellations?.busy || sessionMaintenance?.busy || nativeHost.busy || registry.hasPendingOperations) return;
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;
689
697
  draining = true;
690
698
  idleStopping = true;
691
699
  idleEvidence = { at: now(), deadline: hostedUsed ? zeroSince! + config.daemonIdleMs : runtimeZeroSince! + config.runtimeIdleMs,
@@ -720,7 +728,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
720
728
  await cancellations?.close();
721
729
  await (await launchInitialization?.catch(() => undefined))?.close();
722
730
  await (await backgroundInitialization?.catch(() => undefined))?.close();
723
- resultSupervision?.close();
731
+ await resultSupervision?.close();
724
732
  controlStore.release();
725
733
  if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
726
734
  await workModel?.close();
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.0";
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 };