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
@@ -1,6 +1,5 @@
1
1
  // Generated canonical coordinator. Do not edit directly.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
- import { bumpChangeRevision } from "./discovery.mjs";
4
3
  import { StoreError } from "./errors.mjs";
5
4
  import { columnText, getRow, getRows, run } from "./sqlite.mjs";
6
5
  import { requireWait, readPins } from "./rows.mjs";
@@ -108,7 +107,6 @@ export function recordAssignmentOutcome(ctx, input) {
108
107
  for (const e of retained)
109
108
  run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
110
109
  run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
111
- bumpChangeRevision(ctx);
112
110
  return record;
113
111
  });
114
112
  }
@@ -33,13 +33,15 @@ export function readDiscoveryClaim(ctx, scope) {
33
33
  return readClaim(ctx, requireId("scope", scope));
34
34
  }
35
35
  /** Read scope transfer and its discovery claim from one SQLite snapshot. */
36
- export function readDiscoveryState(ctx, scope) {
36
+ export function readDiscoveryState(ctx, scope, hostId) {
37
37
  scope = requireId("scope", scope);
38
38
  const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
39
39
  EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
40
- WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
41
- FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope);
42
- return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1 };
40
+ WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
41
+ EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
42
+ FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, hostId === undefined ? null : requireId("hostId", hostId), scope);
43
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
44
+ ...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
43
45
  }
44
46
  export function tryClaimDiscovery(ctx, input) {
45
47
  const scope = requireId("scope", input.scope);
@@ -312,24 +312,17 @@ export function listOperations(ctx, filter = {}) {
312
312
  return getRows(ctx, `SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
313
313
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
314
314
  }
315
- export function listAssignmentCleanupOperations(ctx, limit, afterOperationId) {
315
+ export function listAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId) {
316
316
  const requested = requireCounter("limit", limit);
317
317
  if (requested === 0)
318
318
  throw new StoreError("validation", "Invalid limit: must be at least 1");
319
319
  const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
320
- // Seek the partial index in cursor order rather than sorting all running operations.
320
+ const params = hostId === undefined ? [] : [requireId("hostId", hostId)];
321
321
  return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
322
322
  WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
323
- FROM operations op INDEXED BY operations_assignment_cleanup
324
- JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
325
- JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
326
- WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
327
- AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
328
- OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
329
- AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
330
- AND e.summary LIKE '%groupCleanup=unproven%'))
331
- AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
332
- ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
323
+ FROM assignment_cleanup_pending p CROSS JOIN operations op ON op.operation_id = p.operation_id
324
+ WHERE ${hostId === undefined ? "" : "p.supervision_host_id = ? AND "}p.operation_id > ?
325
+ ORDER BY p.operation_id LIMIT ?`, ...params, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
333
326
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
334
327
  }
335
328
  /** Running operations assigned to one supervising host, using the phase/host index. */
@@ -67,6 +67,42 @@ const EXPIRY_INDEXES = [
67
67
  const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
68
68
  ON operations (operation_id, assignment_attempt_id)
69
69
  WHERE assignment_attempt_id IS NOT NULL`;
70
+ // Terminal evidence is written before the operation's terminal revision in the same transaction.
71
+ function needsAssignmentCleanup(row) {
72
+ return `(${row}.terminal_revision = 0 OR ${row}.terminal_outcome = 'lost' OR EXISTS (
73
+ SELECT 1 FROM operation_evidence e WHERE e.operation_id = ${row}.operation_id
74
+ AND e.terminal_revision = ${row}.terminal_revision AND e.kind = 'terminal-record'
75
+ AND e.summary LIKE '%groupCleanup=unproven%'))`;
76
+ }
77
+ const CLEANUP_FOR_ASSIGNMENT = `SELECT op.operation_id, op.supervision_host_id
78
+ FROM assignment_attempts a JOIN operations op ON op.assignment_attempt_id = a.attempt_id
79
+ WHERE a.assignment_id = NEW.assignment_id AND ${needsAssignmentCleanup("op")}`;
80
+ // Triggers also cover older processes that still have an open coordinator connection.
81
+ const PENDING_CLEANUP_DDL = [
82
+ `CREATE TABLE IF NOT EXISTS assignment_cleanup_pending (
83
+ operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
84
+ supervision_host_id TEXT
85
+ ) WITHOUT ROWID`,
86
+ `CREATE INDEX assignment_cleanup_host ON assignment_cleanup_pending(supervision_host_id, operation_id)`,
87
+ `CREATE INDEX assignment_attempts_by_assignment ON assignment_attempts(assignment_id, attempt_id)`,
88
+ `CREATE INDEX operations_by_assignment_attempt ON operations(assignment_attempt_id)
89
+ WHERE assignment_attempt_id IS NOT NULL`,
90
+ `CREATE TRIGGER assignment_cleanup_enqueue AFTER INSERT ON assignment_outcomes BEGIN
91
+ INSERT INTO assignment_cleanup_pending ${CLEANUP_FOR_ASSIGNMENT};
92
+ END`,
93
+ `CREATE TRIGGER assignment_cleanup_terminal AFTER UPDATE OF terminal_revision ON operations
94
+ WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.terminal_revision > 0 AND NOT ${needsAssignmentCleanup("NEW")} BEGIN
95
+ DELETE FROM assignment_cleanup_pending WHERE operation_id = NEW.operation_id;
96
+ END`,
97
+ `CREATE TRIGGER assignment_cleanup_transfer AFTER UPDATE OF supervision_host_id ON operations
98
+ WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.supervision_host_id IS NOT OLD.supervision_host_id BEGIN
99
+ UPDATE assignment_cleanup_pending SET supervision_host_id = NEW.supervision_host_id WHERE operation_id = NEW.operation_id;
100
+ END`,
101
+ `CREATE TRIGGER assignment_cleanup_verified AFTER INSERT ON coordinator_state
102
+ WHEN NEW.key GLOB 'assignment-cleanup-verified:*' BEGIN
103
+ DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
104
+ END`,
105
+ ];
70
106
  const DDL = [
71
107
  `CREATE TABLE task_cancellation_authorities (
72
108
  credential_hash TEXT PRIMARY KEY,
@@ -288,6 +324,7 @@ const DDL = [
288
324
  PRIMARY KEY (wait_id, generation)
289
325
  )`,
290
326
  RESULT_ADMISSION_FENCE,
327
+ ...PENDING_CLEANUP_DDL,
291
328
  ];
292
329
  const SCHEMA_VERSION_KEY = "schema_version";
293
330
  function existingTables(ctx) {
@@ -358,14 +395,29 @@ function ensureAssignmentCleanupSchema(ctx) {
358
395
  for (const statement of EXPIRY_INDEXES)
359
396
  ctx.db.exec(statement);
360
397
  const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
361
- if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'"))
398
+ const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
399
+ if (hasPending())
362
400
  return;
363
401
  ctx.transaction(() => {
402
+ if (hasPending())
403
+ return;
364
404
  ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
365
405
  // Legacy writers leave the nullable provenance unset.
366
406
  if (!hasColumn())
367
407
  ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
368
408
  ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
409
+ for (const statement of PENDING_CLEANUP_DDL)
410
+ ctx.db.exec(statement);
411
+ if (process.platform === "win32") {
412
+ // Earlier Windows writers mistook an unsupported group probe for proof of exit.
413
+ ctx.db.exec("DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*'");
414
+ }
415
+ ctx.db.exec(`INSERT INTO assignment_cleanup_pending
416
+ SELECT op.operation_id, op.supervision_host_id FROM operations op
417
+ JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
418
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
419
+ WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
420
+ WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
369
421
  });
370
422
  }
371
423
  /**
@@ -117,9 +117,9 @@ export function openStore(options) {
117
117
  alive();
118
118
  return readOperationRecords(ctx, filter);
119
119
  },
120
- listAssignmentCleanupOperations(limit, afterOperationId) {
120
+ listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
121
121
  alive();
122
- return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
122
+ return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
123
123
  },
124
124
  verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
125
125
  alive();
@@ -139,7 +139,7 @@ export function openStore(options) {
139
139
  alive();
140
140
  return readOperationEvidence(ctx, requireId("operationId", operationId), terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision));
141
141
  },
142
- readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
142
+ readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
143
143
  readDiscoveryClaim(scope) {
144
144
  alive();
145
145
  return readClaim(ctx, scope);
@@ -768,24 +768,21 @@ export function enforceRegistrySizeCapOnce(options = {}) {
768
768
  };
769
769
  const bytesById = new Map(entries.map((entry) => [entry.id, entry.bytes]));
770
770
  const removed = [];
771
- let retainedBytes = 0;
771
+ let reclaimedBytes = 0;
772
772
  for (const id of plan.remove) {
773
- const outcome = removeSizeCappedRun(id, scope, errors);
774
- if (outcome === "removed")
775
- removed.push(id);
776
- else if (outcome === "retained")
777
- retainedBytes += bytesById.get(id) ?? 0;
773
+ if (removeSizeCappedRun(id, scope, errors) !== "removed")
774
+ continue;
775
+ removed.push(id);
776
+ reclaimedBytes += bytesById.get(id) ?? 0;
778
777
  }
779
- // A candidate the recheck retained is still on disk, so the byte account and
780
- // the shortfall it reports stay honest.
781
- const keptBytes = plan.keptBytes + retainedBytes;
778
+ const keptBytes = totalBytes - reclaimedBytes;
782
779
  try {
783
780
  writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
784
781
  }
785
782
  catch (err) {
786
783
  errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
787
784
  }
788
- return { ...plan, ran: true, removed, keptBytes, overBudget: keptBytes > maxBytes, errors };
785
+ return { ran: true, remove: plan.remove, removed, reclaimedBytes, keptBytes, overBudget: keptBytes > maxBytes, errors };
789
786
  }
790
787
  /**
791
788
  * Remove one planned size-cap candidate, serialized with its conversation.
@@ -969,15 +969,13 @@ export function enforceRegistrySizeCapOnce(options: SizeCapOptions = {}): SizeCa
969
969
  };
970
970
  const bytesById = new Map(entries.map((entry) => [entry.id, entry.bytes]));
971
971
  const removed: string[] = [];
972
- let retainedBytes = 0;
972
+ let reclaimedBytes = 0;
973
973
  for (const id of plan.remove) {
974
- const outcome = removeSizeCappedRun(id, scope, errors);
975
- if (outcome === "removed") removed.push(id);
976
- else if (outcome === "retained") retainedBytes += bytesById.get(id) ?? 0;
974
+ if (removeSizeCappedRun(id, scope, errors) !== "removed") continue;
975
+ removed.push(id);
976
+ reclaimedBytes += bytesById.get(id) ?? 0;
977
977
  }
978
- // A candidate the recheck retained is still on disk, so the byte account and
979
- // the shortfall it reports stay honest.
980
- const keptBytes = plan.keptBytes + retainedBytes;
978
+ const keptBytes = totalBytes - reclaimedBytes;
981
979
 
982
980
  try {
983
981
  writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
@@ -985,7 +983,7 @@ export function enforceRegistrySizeCapOnce(options: SizeCapOptions = {}): SizeCa
985
983
  errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
986
984
  }
987
985
 
988
- return { ...plan, ran: true, removed, keptBytes, overBudget: keptBytes > maxBytes, errors };
986
+ return { ran: true, remove: plan.remove, removed, reclaimedBytes, keptBytes, overBudget: keptBytes > maxBytes, errors };
989
987
  }
990
988
 
991
989
  /**
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.39.0",
3
+ "version": "0.39.1",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -184,24 +184,26 @@ export function listParkRecordCandidates(metas = listMetas()) {
184
184
  || (volatileIds.has(meta.id) && existsSync(parkRecordPath(meta.id))));
185
185
  }
186
186
  /** Read recovery sidecars in batches so a large registry does not block socket replies. */
187
- export async function* scanParkRecords(metas = listMetas()) {
187
+ export async function* scanParkRecords(metas = listMetas(), include) {
188
188
  const runs = join(baseDir(), "runs");
189
- const volatileIds = new Set(await readdir(runs).catch(() => []));
189
+ const volatileIds = await readdir(runs).then(ids => new Set(ids), (error) => error.code === "ENOENT" ? new Set() : undefined);
190
190
  const batchSize = 32;
191
191
  for (let offset = 0; offset < metas.length; offset += batchSize) {
192
192
  const batch = await Promise.all(metas.slice(offset, offset + batchSize).map(async (meta) => {
193
- if (!meta.park && !volatileIds.has(meta.id))
193
+ if (meta.park && include && !include(meta.park))
194
+ return;
195
+ if (volatileIds && !volatileIds.has(meta.id))
196
+ return meta.park ? { meta, record: meta.park } : undefined;
197
+ if (!volatileIds && !meta.park)
194
198
  return;
195
199
  try {
196
200
  const record = parseParkRecord(JSON.parse(await readFile(join(runs, meta.id, "park.json"), "utf-8")));
197
- if (record)
201
+ if (record && (!include || include(record)))
198
202
  return { meta, record };
199
203
  }
200
204
  catch (error) {
201
205
  if (error.code === "ENOENT" && meta.park) {
202
- const record = readMeta(meta.id)?.park;
203
- if (record)
204
- return { meta, record };
206
+ return { meta, record: meta.park };
205
207
  }
206
208
  }
207
209
  }));
@@ -544,20 +544,25 @@ export function listParkRecordCandidates(metas: readonly RunMeta[] = listMetas()
544
544
  }
545
545
 
546
546
  /** Read recovery sidecars in batches so a large registry does not block socket replies. */
547
- export async function* scanParkRecords(metas: readonly RunMeta[] = listMetas()): AsyncGenerator<{ meta: RunMeta; record: ParkRecord }> {
547
+ export async function* scanParkRecords(
548
+ metas: readonly RunMeta[] = listMetas(),
549
+ include?: (record: ParkRecord) => boolean,
550
+ ): AsyncGenerator<{ meta: RunMeta; record: ParkRecord }> {
548
551
  const runs = join(baseDir(), "runs");
549
- const volatileIds = new Set(await readdir(runs).catch(() => [] as string[]));
552
+ const volatileIds = await readdir(runs).then(ids => new Set(ids),
553
+ (error: NodeJS.ErrnoException) => error.code === "ENOENT" ? new Set<string>() : undefined);
550
554
  const batchSize = 32;
551
555
  for (let offset = 0; offset < metas.length; offset += batchSize) {
552
556
  const batch = await Promise.all(metas.slice(offset, offset + batchSize).map(async (meta) => {
553
- if (!meta.park && !volatileIds.has(meta.id)) return;
557
+ if (meta.park && include && !include(meta.park)) return;
558
+ if (volatileIds && !volatileIds.has(meta.id)) return meta.park ? { meta, record: meta.park } : undefined;
559
+ if (!volatileIds && !meta.park) return;
554
560
  try {
555
561
  const record = parseParkRecord(JSON.parse(await readFile(join(runs, meta.id, "park.json"), "utf-8")));
556
- if (record) return { meta, record };
562
+ if (record && (!include || include(record))) return { meta, record };
557
563
  } catch (error) {
558
564
  if ((error as NodeJS.ErrnoException).code === "ENOENT" && meta.park) {
559
- const record = readMeta(meta.id)?.park;
560
- if (record) return { meta, record };
565
+ return { meta, record: meta.park };
561
566
  }
562
567
  }
563
568
  }));
@@ -1,7 +1,7 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/retained-result.ts. Do not edit directly.
2
- import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
2
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync, } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
- import { snapshotTree, verifyTree } from "./workspace-files.domain.mjs";
4
+ import { copyTree, snapshotTree, verifyTree } from "./workspace-files.domain.mjs";
5
5
  import { resultDir } from "./session-store.domain.mjs";
6
6
  // Published only while retiring a quiescent attempt. A result record can answer reads,
7
7
  // but cannot authorize admission, revive a writer or make a failed attempt resumable.
@@ -26,7 +26,7 @@ export function retainResult(meta, logPath, scratch) {
26
26
  if (scratch && existsSync(scratch)) {
27
27
  const files = snapshotTree(scratch);
28
28
  if (files.some((entry) => entry.name !== ".sandbox-anchor")) {
29
- cpSync(scratch, join(temp, "scratch"), { recursive: true, verbatimSymlinks: true });
29
+ copyTree(scratch, join(temp, "scratch"), files);
30
30
  verifyTree(join(temp, "scratch"), files);
31
31
  verifyTree(scratch, files);
32
32
  savedScratch = join(dir, "scratch");
@@ -1,6 +1,5 @@
1
1
  import {
2
2
  copyFileSync,
3
- cpSync,
4
3
  existsSync,
5
4
  mkdirSync,
6
5
  mkdtempSync,
@@ -10,7 +9,7 @@ import {
10
9
  writeFileSync,
11
10
  } from "node:fs";
12
11
  import { dirname, join } from "node:path";
13
- import { snapshotTree, verifyTree } from "./workspace-files.ts";
12
+ import { copyTree, snapshotTree, verifyTree } from "./workspace-files.ts";
14
13
  import type { RunMeta } from "./registry.ts";
15
14
  import { resultDir } from "./session-store.ts";
16
15
 
@@ -35,7 +34,7 @@ export function retainResult(meta: RunMeta, logPath: string, scratch?: string):
35
34
  if (scratch && existsSync(scratch)) {
36
35
  const files = snapshotTree(scratch);
37
36
  if (files.some((entry) => entry.name !== ".sandbox-anchor")) {
38
- cpSync(scratch, join(temp, "scratch"), { recursive: true, verbatimSymlinks: true });
37
+ copyTree(scratch, join(temp, "scratch"), files);
39
38
  verifyTree(join(temp, "scratch"), files);
40
39
  verifyTree(scratch, files);
41
40
  savedScratch = join(dir, "scratch");
@@ -1,7 +1,6 @@
1
1
  // Generated fixed launch domain from packages/pi-better-subagents/shared-operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
2
2
  // Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
3
3
  import { createHash, randomUUID } from "node:crypto";
4
- import { bumpChangeRevision } from "./discovery.domain.mjs";
5
4
  import { StoreError } from "./errors.domain.mjs";
6
5
  import { columnText, getRow, getRows, run } from "./sqlite.domain.mjs";
7
6
  import { requireWait, readPins } from "./rows.domain.mjs";
@@ -109,7 +108,6 @@ export function recordAssignmentOutcome(ctx, input) {
109
108
  for (const e of retained)
110
109
  run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
111
110
  run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
112
- bumpChangeRevision(ctx);
113
111
  return record;
114
112
  });
115
113
  }
@@ -1,6 +1,5 @@
1
1
  // Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
- import { bumpChangeRevision } from "./discovery.ts";
4
3
  import { StoreError } from "./errors.ts";
5
4
  import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
6
5
  import { requireWait, readPins } from "./rows.ts";
@@ -121,7 +120,6 @@ export function recordAssignmentOutcome(ctx: StoreContext, input: AssignmentOutc
121
120
  }
122
121
  for (const e of retained) run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
123
122
  run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
124
- bumpChangeRevision(ctx);
125
123
  return record;
126
124
  });
127
125
  }
@@ -34,13 +34,15 @@ export function readDiscoveryClaim(ctx, scope) {
34
34
  return readClaim(ctx, requireId("scope", scope));
35
35
  }
36
36
  /** Read scope transfer and its discovery claim from one SQLite snapshot. */
37
- export function readDiscoveryState(ctx, scope) {
37
+ export function readDiscoveryState(ctx, scope, hostId) {
38
38
  scope = requireId("scope", scope);
39
39
  const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
40
40
  EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
41
- WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
42
- FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope);
43
- return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1 };
41
+ WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
42
+ EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
43
+ FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, hostId === undefined ? null : requireId("hostId", hostId), scope);
44
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
45
+ ...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
44
46
  }
45
47
  export function tryClaimDiscovery(ctx, input) {
46
48
  const scope = requireId("scope", input.scope);
@@ -49,13 +49,16 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
49
49
  }
50
50
 
51
51
  /** Read scope transfer and its discovery claim from one SQLite snapshot. */
52
- export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean } {
52
+ export function readDiscoveryState(ctx: StoreContext, scope: string, hostId?: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean; cleanupPending?: boolean } {
53
53
  scope = requireId("scope", scope);
54
54
  const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
55
55
  EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
56
- WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
57
- FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope)!;
58
- return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1 };
56
+ WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
57
+ EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
58
+ FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope,
59
+ hostId === undefined ? null : requireId("hostId", hostId), scope)!;
60
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
61
+ ...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
59
62
  }
60
63
 
61
64
  export function tryClaimDiscovery(
@@ -313,24 +313,17 @@ export function listOperations(ctx, filter = {}) {
313
313
  return getRows(ctx, `SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
314
314
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
315
315
  }
316
- export function listAssignmentCleanupOperations(ctx, limit, afterOperationId) {
316
+ export function listAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId) {
317
317
  const requested = requireCounter("limit", limit);
318
318
  if (requested === 0)
319
319
  throw new StoreError("validation", "Invalid limit: must be at least 1");
320
320
  const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
321
- // Seek the partial index in cursor order rather than sorting all running operations.
321
+ const params = hostId === undefined ? [] : [requireId("hostId", hostId)];
322
322
  return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
323
323
  WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
324
- FROM operations op INDEXED BY operations_assignment_cleanup
325
- JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
326
- JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
327
- WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
328
- AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
329
- OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
330
- AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
331
- AND e.summary LIKE '%groupCleanup=unproven%'))
332
- AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
333
- ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
324
+ FROM assignment_cleanup_pending p CROSS JOIN operations op ON op.operation_id = p.operation_id
325
+ WHERE ${hostId === undefined ? "" : "p.supervision_host_id = ? AND "}p.operation_id > ?
326
+ ORDER BY p.operation_id LIMIT ?`, ...params, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
334
327
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
335
328
  }
336
329
  /** Running operations assigned to one supervising host, using the phase/host index. */
@@ -467,23 +467,17 @@ export function listAssignmentCleanupOperations(
467
467
  ctx: StoreContext,
468
468
  limit: number,
469
469
  afterOperationId?: string,
470
+ hostId?: string,
470
471
  ): OperationRecord[] {
471
472
  const requested = requireCounter("limit", limit);
472
473
  if (requested === 0) throw new StoreError("validation", "Invalid limit: must be at least 1");
473
474
  const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
474
- // Seek the partial index in cursor order rather than sorting all running operations.
475
+ const params = hostId === undefined ? [] : [requireId("hostId", hostId)];
475
476
  return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
476
477
  WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
477
- FROM operations op INDEXED BY operations_assignment_cleanup
478
- JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
479
- JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
480
- WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
481
- AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
482
- OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
483
- AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
484
- AND e.summary LIKE '%groupCleanup=unproven%'))
485
- AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
486
- ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
478
+ FROM assignment_cleanup_pending p CROSS JOIN operations op ON op.operation_id = p.operation_id
479
+ WHERE ${hostId === undefined ? "" : "p.supervision_host_id = ? AND "}p.operation_id > ?
480
+ ORDER BY p.operation_id LIMIT ?`, ...params, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
487
481
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
488
482
  }
489
483
 
@@ -68,6 +68,42 @@ const EXPIRY_INDEXES = [
68
68
  const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
69
69
  ON operations (operation_id, assignment_attempt_id)
70
70
  WHERE assignment_attempt_id IS NOT NULL`;
71
+ // Terminal evidence is written before the operation's terminal revision in the same transaction.
72
+ function needsAssignmentCleanup(row) {
73
+ return `(${row}.terminal_revision = 0 OR ${row}.terminal_outcome = 'lost' OR EXISTS (
74
+ SELECT 1 FROM operation_evidence e WHERE e.operation_id = ${row}.operation_id
75
+ AND e.terminal_revision = ${row}.terminal_revision AND e.kind = 'terminal-record'
76
+ AND e.summary LIKE '%groupCleanup=unproven%'))`;
77
+ }
78
+ const CLEANUP_FOR_ASSIGNMENT = `SELECT op.operation_id, op.supervision_host_id
79
+ FROM assignment_attempts a JOIN operations op ON op.assignment_attempt_id = a.attempt_id
80
+ WHERE a.assignment_id = NEW.assignment_id AND ${needsAssignmentCleanup("op")}`;
81
+ // Triggers also cover older processes that still have an open coordinator connection.
82
+ const PENDING_CLEANUP_DDL = [
83
+ `CREATE TABLE IF NOT EXISTS assignment_cleanup_pending (
84
+ operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
85
+ supervision_host_id TEXT
86
+ ) WITHOUT ROWID`,
87
+ `CREATE INDEX assignment_cleanup_host ON assignment_cleanup_pending(supervision_host_id, operation_id)`,
88
+ `CREATE INDEX assignment_attempts_by_assignment ON assignment_attempts(assignment_id, attempt_id)`,
89
+ `CREATE INDEX operations_by_assignment_attempt ON operations(assignment_attempt_id)
90
+ WHERE assignment_attempt_id IS NOT NULL`,
91
+ `CREATE TRIGGER assignment_cleanup_enqueue AFTER INSERT ON assignment_outcomes BEGIN
92
+ INSERT INTO assignment_cleanup_pending ${CLEANUP_FOR_ASSIGNMENT};
93
+ END`,
94
+ `CREATE TRIGGER assignment_cleanup_terminal AFTER UPDATE OF terminal_revision ON operations
95
+ WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.terminal_revision > 0 AND NOT ${needsAssignmentCleanup("NEW")} BEGIN
96
+ DELETE FROM assignment_cleanup_pending WHERE operation_id = NEW.operation_id;
97
+ END`,
98
+ `CREATE TRIGGER assignment_cleanup_transfer AFTER UPDATE OF supervision_host_id ON operations
99
+ WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.supervision_host_id IS NOT OLD.supervision_host_id BEGIN
100
+ UPDATE assignment_cleanup_pending SET supervision_host_id = NEW.supervision_host_id WHERE operation_id = NEW.operation_id;
101
+ END`,
102
+ `CREATE TRIGGER assignment_cleanup_verified AFTER INSERT ON coordinator_state
103
+ WHEN NEW.key GLOB 'assignment-cleanup-verified:*' BEGIN
104
+ DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
105
+ END`,
106
+ ];
71
107
  const DDL = [
72
108
  `CREATE TABLE task_cancellation_authorities (
73
109
  credential_hash TEXT PRIMARY KEY,
@@ -289,6 +325,7 @@ const DDL = [
289
325
  PRIMARY KEY (wait_id, generation)
290
326
  )`,
291
327
  RESULT_ADMISSION_FENCE,
328
+ ...PENDING_CLEANUP_DDL,
292
329
  ];
293
330
  const SCHEMA_VERSION_KEY = "schema_version";
294
331
  function existingTables(ctx) {
@@ -359,14 +396,29 @@ function ensureAssignmentCleanupSchema(ctx) {
359
396
  for (const statement of EXPIRY_INDEXES)
360
397
  ctx.db.exec(statement);
361
398
  const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
362
- if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'"))
399
+ const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
400
+ if (hasPending())
363
401
  return;
364
402
  ctx.transaction(() => {
403
+ if (hasPending())
404
+ return;
365
405
  ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
366
406
  // Legacy writers leave the nullable provenance unset.
367
407
  if (!hasColumn())
368
408
  ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
369
409
  ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
410
+ for (const statement of PENDING_CLEANUP_DDL)
411
+ ctx.db.exec(statement);
412
+ if (process.platform === "win32") {
413
+ // Earlier Windows writers mistook an unsupported group probe for proof of exit.
414
+ ctx.db.exec("DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*'");
415
+ }
416
+ ctx.db.exec(`INSERT INTO assignment_cleanup_pending
417
+ SELECT op.operation_id, op.supervision_host_id FROM operations op
418
+ JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
419
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
420
+ WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
421
+ WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
370
422
  });
371
423
  }
372
424
  /**