pi-better-server 0.8.0 → 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 (49) hide show
  1. package/package.json +1 -1
  2. package/src/runtime/domain/background/supervisor/identity.mjs +5 -0
  3. package/src/runtime/domain/background/supervisor/supervisor.mjs +3 -4
  4. package/src/runtime/domain/background-service/observed-waits.domain.mjs +10 -7
  5. package/src/runtime/domain/background-service/observed-waits.ts +9 -6
  6. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  7. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  8. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  9. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +7 -4
  10. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  11. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +5 -11
  12. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +53 -1
  13. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +54 -1
  14. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -3
  15. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -5
  16. package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +5 -0
  17. package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +5 -0
  18. package/src/runtime/domain/background-service/supervisor/identity.ts +6 -0
  19. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +3 -4
  20. package/src/runtime/domain/background-service/supervisor/supervisor.ts +3 -4
  21. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +0 -2
  22. package/src/runtime/domain/coordinator/src/discovery.mjs +6 -4
  23. package/src/runtime/domain/coordinator/src/operations.mjs +5 -12
  24. package/src/runtime/domain/coordinator/src/schema.mjs +53 -1
  25. package/src/runtime/domain/coordinator/src/store.mjs +3 -3
  26. package/src/runtime/domain/subagents/cleanup.domain.mjs +7 -10
  27. package/src/runtime/domain/subagents/cleanup.ts +6 -8
  28. package/src/runtime/domain/subagents/package.json +1 -1
  29. package/src/runtime/domain/subagents/registry.domain.mjs +9 -7
  30. package/src/runtime/domain/subagents/registry.ts +11 -6
  31. package/src/runtime/domain/subagents/retained-result.domain.mjs +3 -3
  32. package/src/runtime/domain/subagents/retained-result.ts +2 -3
  33. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  34. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  35. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  36. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +7 -4
  37. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  38. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +5 -11
  39. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +53 -1
  40. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +54 -1
  41. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -3
  42. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -5
  43. package/src/runtime/domain/subagents/worker-waits.domain.mjs +3 -4
  44. package/src/runtime/domain/subagents/worker-waits.ts +3 -3
  45. package/src/runtime/domain/subagents/workspace-files.domain.mjs +19 -5
  46. package/src/runtime/domain/subagents/workspace-files.ts +27 -5
  47. package/src/runtime/result-supervision.ts +16 -5
  48. package/src/server.ts +6 -5
  49. package/src/version.ts +1 -1
@@ -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);
@@ -2157,10 +2157,9 @@ export async function reconcileParkedWaits(service, outerOptions) {
2157
2157
  // Consumed waits cannot resume, but a missed exit observer may have left
2158
2158
  // their published writer claim behind. Reconcile that exact claim once.
2159
2159
  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;
2160
+ const needsReconciliation = (record) => isPendingPark(record) || (record.phase === "consumed"
2161
+ && !!record.resumedBy && !!record.resumeClaimId && record.resumeExitReconciledClaimId !== record.resumeClaimId);
2162
+ for await (const { meta, record } of scanParkRecords(undefined, needsReconciliation)) {
2164
2163
  candidates.push(parkedEntry(meta, record));
2165
2164
  }
2166
2165
  // Release earlier writers before admitting later waits in the conversation.
@@ -2719,9 +2719,9 @@ export async function reconcileParkedWaits(
2719
2719
  // Consumed waits cannot resume, but a missed exit observer may have left
2720
2720
  // their published writer claim behind. Reconcile that exact claim once.
2721
2721
  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;
2722
+ const needsReconciliation = (record: ParkRecord) => isPendingPark(record) || (record.phase === "consumed"
2723
+ && !!record.resumedBy && !!record.resumeClaimId && record.resumeExitReconciledClaimId !== record.resumeClaimId);
2724
+ for await (const { meta, record } of scanParkRecords(undefined, needsReconciliation)) {
2725
2725
  candidates.push(parkedEntry(meta, record));
2726
2726
  }
2727
2727
  // 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 } 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,6 +39,8 @@ export class RuntimeResultSupervision {
39
39
  readonly epoch: string;
40
40
  private observationReason?: string;
41
41
  private assignmentCleanup?: Promise<void>;
42
+ private closing?: Promise<void>;
43
+ get busy() { return this.assignmentCleanup !== undefined; }
42
44
  private assignmentCleanupCursor?: string;
43
45
  private assignmentCleanupReason?: string;
44
46
  get reason() { return this.assignmentCleanupReason ?? this.observationReason; }
@@ -193,10 +195,11 @@ export class RuntimeResultSupervision {
193
195
  }
194
196
  private reconcileAssignmentCleanup() {
195
197
  if (this.assignmentCleanup) return;
196
- const [operation] = this.store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
198
+ const cursor = this.assignmentCleanupCursor;
199
+ const [operation] = this.store.listAssignmentCleanupOperations(1, cursor);
197
200
  this.assignmentCleanupCursor = operation?.operationId;
198
201
  if (!operation) {
199
- if (!this.store.listAssignmentCleanupOperations(1).length) this.assignmentCleanupReason = undefined;
202
+ if (cursor === undefined) this.assignmentCleanupReason = undefined;
200
203
  return;
201
204
  }
202
205
  const grant = this.store.resultSupervision(operation.operationId);
@@ -216,7 +219,7 @@ export class RuntimeResultSupervision {
216
219
  if (inspection.terminal) {
217
220
  if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven") return;
218
221
  const pgid = inspection.command?.pgid ?? inspection.command?.pid;
219
- if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
222
+ if (processGroupExitVerified(pgid, inspection.cleanup?.groupEmpty)) {
220
223
  this.store.verifyAssignmentCleanup(operation.operationId, operation.launchToken, operation.terminalRevision);
221
224
  return;
222
225
  }
@@ -228,8 +231,16 @@ export class RuntimeResultSupervision {
228
231
  .finally(() => { this.assignmentCleanup = undefined; });
229
232
  }
230
233
  close() {
234
+ if (this.closing) return this.closing;
231
235
  this.closed = true; if (this.timer) clearTimeout(this.timer); this.watcher?.close();
232
236
  for (const watcher of this.taskWatchers.values()) watcher.close();
233
- this.taskWatchers.clear(); this.releaseStore();
237
+ this.taskWatchers.clear();
238
+ if (this.assignmentCleanup) {
239
+ this.closing = this.assignmentCleanup.then(() => this.releaseStore());
240
+ } else {
241
+ this.releaseStore();
242
+ this.closing = Promise.resolve();
243
+ }
244
+ return this.closing;
234
245
  }
235
246
  }
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();
@@ -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,7 @@ 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;
689
690
  draining = true;
690
691
  idleStopping = true;
691
692
  idleEvidence = { at: now(), deadline: hostedUsed ? zeroSince! + config.daemonIdleMs : runtimeZeroSince! + config.runtimeIdleMs,
@@ -720,7 +721,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
720
721
  await cancellations?.close();
721
722
  await (await launchInitialization?.catch(() => undefined))?.close();
722
723
  await (await backgroundInitialization?.catch(() => undefined))?.close();
723
- resultSupervision?.close();
724
+ await resultSupervision?.close();
724
725
  controlStore.release();
725
726
  if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
726
727
  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.1";
3
3
 
4
4
  export const SERVER_EXTENSION_VERSIONS: Readonly<Record<string, string>> = { "pi-better-server": SERVER_VERSION };