pi-better-server 0.7.3 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/package.json +1 -1
  2. package/src/runtime/background-tools.ts +146 -6
  3. package/src/runtime/background.ts +2 -2
  4. package/src/runtime/catalog.ts +30 -1
  5. package/src/runtime/ci-recovery.ts +172 -0
  6. package/src/runtime/domain/assignment-inbox.mjs +4 -0
  7. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  8. package/src/runtime/domain/assignment-observation.mjs +1 -0
  9. package/src/runtime/domain/background/supervisor/identity.mjs +5 -0
  10. package/src/runtime/domain/background/supervisor/supervisor.mjs +3 -4
  11. package/src/runtime/domain/background-service/ci-observation.domain.mjs +134 -0
  12. package/src/runtime/domain/background-service/ci-observation.ts +118 -0
  13. package/src/runtime/domain/background-service/managed-client.domain.mjs +6 -2
  14. package/src/runtime/domain/background-service/managed-client.ts +6 -2
  15. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +47 -7
  16. package/src/runtime/domain/background-service/managed-frontend.ts +36 -6
  17. package/src/runtime/domain/background-service/observed-waits.domain.mjs +36 -7
  18. package/src/runtime/domain/background-service/observed-waits.ts +33 -6
  19. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  20. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +1 -0
  21. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  22. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  23. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  24. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +7 -4
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  26. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +5 -11
  27. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +53 -1
  28. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +54 -1
  29. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -3
  30. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -5
  31. package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +5 -0
  32. package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +5 -0
  33. package/src/runtime/domain/background-service/supervisor/identity.ts +6 -0
  34. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +3 -4
  35. package/src/runtime/domain/background-service/supervisor/supervisor.ts +3 -4
  36. package/src/runtime/domain/catalog/catalog-schema.d.mts +6 -0
  37. package/src/runtime/domain/catalog/catalog-schema.mjs +1 -0
  38. package/src/runtime/domain/catalog/roles/role.supervisor.md +16 -0
  39. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +0 -2
  40. package/src/runtime/domain/coordinator/src/discovery.mjs +6 -4
  41. package/src/runtime/domain/coordinator/src/operations.mjs +5 -12
  42. package/src/runtime/domain/coordinator/src/schema.mjs +53 -1
  43. package/src/runtime/domain/coordinator/src/store.mjs +3 -3
  44. package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1 -0
  45. package/src/runtime/domain/subagents/catalog-schema.ts +1 -0
  46. package/src/runtime/domain/subagents/cleanup.domain.mjs +7 -10
  47. package/src/runtime/domain/subagents/cleanup.ts +6 -8
  48. package/src/runtime/domain/subagents/package.json +1 -1
  49. package/src/runtime/domain/subagents/registry.domain.mjs +9 -7
  50. package/src/runtime/domain/subagents/registry.ts +11 -6
  51. package/src/runtime/domain/subagents/retained-result.domain.mjs +3 -3
  52. package/src/runtime/domain/subagents/retained-result.ts +2 -3
  53. package/src/runtime/domain/subagents/roles/role.supervisor.md +16 -0
  54. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +14 -2
  55. package/src/runtime/domain/subagents/shared-catalog.ts +14 -2
  56. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  57. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +1 -0
  58. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  59. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  60. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  61. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +7 -4
  62. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  63. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +5 -11
  64. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +53 -1
  65. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +54 -1
  66. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -3
  67. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -5
  68. package/src/runtime/domain/subagents/supervisor-client.mjs +36 -0
  69. package/src/runtime/domain/subagents/worker-waits.domain.mjs +3 -4
  70. package/src/runtime/domain/subagents/worker-waits.ts +3 -3
  71. package/src/runtime/domain/subagents/workspace-files.domain.mjs +19 -5
  72. package/src/runtime/domain/subagents/workspace-files.ts +27 -5
  73. package/src/runtime/queries.ts +17 -3
  74. package/src/runtime/query-executor.ts +46 -3
  75. package/src/runtime/query-worker.mjs +6 -1
  76. package/src/runtime/read-model.ts +14 -5
  77. package/src/runtime/result-supervision.ts +16 -5
  78. package/src/runtime/shared-read-diagnosis.ts +29 -0
  79. package/src/runtime/supervisor-admission.ts +42 -0
  80. package/src/runtime/supervisor-decisions.ts +60 -0
  81. package/src/server.ts +9 -8
  82. package/src/version.ts +1 -1
@@ -85,7 +85,7 @@ let cacheBytes = 0, cacheHits = 0, queryCount = 0, serializationCount = 0;
85
85
  let revisionPending = false, revisionDirty = false;
86
86
  const durations = [];
87
87
  const cacheComparisons = workerData.queryCacheDiagnostics ? [] : undefined;
88
- const metrics = () => ({ ...model.metrics, background: model.backgroundMetrics, sqlite: { ...connections }, cacheHits, queryCount, serializationCount, eventEncoding: { ...queryEncodingMetrics }, cacheBytes,
88
+ const metrics = () => ({ ...model.indexCounters, background: model.backgroundCounters, sqlite: { ...connections }, cacheHits, queryCount, serializationCount, eventEncoding: { ...queryEncodingMetrics }, cacheBytes,
89
89
  cacheEntries: cache.size, queryDurationMs: [...durations], ...(cacheComparisons ? { cacheComparisons: [...cacheComparisons] } : {}) });
90
90
  const snapshot = model.snapshot.bind(model);
91
91
  model.snapshot = scope => observeExecution("snapshot", () => {
@@ -156,6 +156,11 @@ function session(id) {
156
156
  }
157
157
 
158
158
  parentPort.on("message", async message => {
159
+ if (message.type === "inbox-diagnostics") {
160
+ try { parentPort.postMessage({ type: "inbox-diagnostics", sample: model.inboxDiagnostics }); }
161
+ catch (error) { parentPort.postMessage({ type: "inbox-diagnostics", error: String(error).slice(0, 512) }); }
162
+ return;
163
+ }
159
164
  if (message.type === "heartbeat-consumed") { heartbeatPending = false; return; }
160
165
  if (message.type === "cancel") {
161
166
  const request = requests.get(message.id);
@@ -138,8 +138,9 @@ export class WorkReadModel {
138
138
  }
139
139
  return { available: false, received: null, applied: null, pending: null };
140
140
  }
141
- get metrics() {
142
- return { ...this.counters, assignments: this.assignmentMetrics, initialization: { ...this.initialization }, checkpoints: { ...this.checkpoints.metrics, hotDisplay: this.parseStates.size, hotHealth: this.healthStates.size }, sourceWork: structuredClone(this.sourceWork), scheduling: { ...this.scheduling, queued: this.hints.size }, invalidations: { ...this.invalidations }, logReads: { ...logReadMetrics }, coordinatorConnections: Number(Boolean(this.reader?.connection(false))) + this.background.connectionCount,
141
+ get metrics() { return { ...this.indexCounters, assignments: this.assignmentMetrics }; }
142
+ get indexCounters() {
143
+ return { ...this.counters, initialization: { ...this.initialization }, checkpoints: { ...this.checkpoints.metrics, hotDisplay: this.parseStates.size, hotHealth: this.healthStates.size }, sourceWork: structuredClone(this.sourceWork), scheduling: { ...this.scheduling, queued: this.hints.size }, invalidations: { ...this.invalidations }, logReads: { ...logReadMetrics }, coordinatorConnections: Number(Boolean(this.reader?.connection(false))) + this.background.connectionCount,
143
144
  indexConnections: this.closed ? 0 : 1, sourceWatchers: this.watchers.size, sourceParentWatchers: this.rootParents.size, rootParentWatchers: this.rootParents.size };
144
145
  }
145
146
  readonly runs: string;
@@ -350,7 +351,13 @@ export class WorkReadModel {
350
351
  this.listeners.add(notify);
351
352
  return () => { this.listeners.delete(notify); release?.(); };
352
353
  }
353
- get backgroundMetrics() { return { ...this.background.metrics, registry: this.background.registryMetrics, changes: this.background.changeMetrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
354
+ get inboxDiagnostics() {
355
+ // The owner can yield while applying a batch. Only sample committed queue state.
356
+ if (this.db.isTransaction) return undefined;
357
+ return { assignments: this.assignmentMetrics, backgroundChanges: this.background.changeMetrics, observedAt: Date.now() };
358
+ }
359
+ get backgroundMetrics() { return { ...this.backgroundCounters, changes: this.background.changeMetrics }; }
360
+ get backgroundCounters() { return { ...this.background.metrics, registry: this.background.registryMetrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
354
361
  observation(reasons = this.observationInitialized ? this.livenessReasons({ refresh: false }) : []) {
355
362
  return { status: this.state, reason: this.reason, observedAt: Date.now(), reasons };
356
363
  }
@@ -409,10 +416,12 @@ export class WorkReadModel {
409
416
  entry.used = now;
410
417
  return entry;
411
418
  }
419
+ prepareBackgroundQuery() {
420
+ this.background.prepareQuery();
421
+ }
412
422
  contentRevision(scope: WorkScope = {}) {
413
423
  if (scope.background) {
414
424
  if (scope.backgroundHistory) return String(this.revision);
415
- this.background.prepareQuery();
416
425
  return hash([this.revision, this.background.sourceRevision(scope)]);
417
426
  }
418
427
  const entry = this.scopeEntry(scope);
@@ -509,7 +518,7 @@ export class WorkReadModel {
509
518
  this.reader.acknowledgeChanges(changes, false);
510
519
  snapshot.commit();
511
520
  for (const row of updated) this.projected.set(row.meta.id, row);
512
- if (this.reader.changeMetrics.more || this.reader.changeMetrics.pending) this.dirty = true;
521
+ if (this.reader.hasPendingChanges) this.dirty = true;
513
522
  this.coordinator = snapshot.revision;
514
523
  this.counters.assignmentProjections += updated.length; this.counters.projections += updated.length;
515
524
  this.invalidations.assignmentInput += updated.length;
@@ -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
  }
@@ -0,0 +1,29 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ export type ReadHealth = "ready" | "rebuilding" | "degraded";
4
+
5
+ /** Group only facts about this daemon's read plane. Never return a scope, operation or owner. */
6
+ export class SharedReadDiagnosis {
7
+ private incident?: { id: string; state: ReadHealth; generation: number; recommendation: string };
8
+ private readonly owners = new Map<string, boolean>();
9
+ verified(owner: string, incident: unknown) {
10
+ if (!this.incident || this.incident.id !== incident || !this.owners.has(owner)) return false;
11
+ this.owners.set(owner, true);
12
+ return true;
13
+ }
14
+ inspect(state: ReadHealth, generation: number, owner: string) {
15
+ if (state === "ready") { this.incident = undefined; this.owners.clear(); return; }
16
+ if (this.incident?.state === state && this.incident.generation === generation) {
17
+ if (!this.owners.has(owner) && this.owners.size < 512) this.owners.set(owner, false);
18
+ return [...this.owners.values()].includes(true)
19
+ ? { ...this.incident, recommendation: "An affected read has recovered. Retry your original observation by ID to verify recovery in this session." }
20
+ : this.incident;
21
+ }
22
+ this.owners.clear();
23
+ this.owners.set(owner, false);
24
+ const recommendation = state === "rebuilding"
25
+ ? "The daemon is rebuilding its shared read inventory. Keep the original operation running. Retry its observation by the original ID once inventory is ready."
26
+ : "The daemon read worker is degraded. Check worker recovery, then read the original operation by ID to verify its state.";
27
+ return this.incident = { id: randomUUID(), state, generation, recommendation };
28
+ }
29
+ }
@@ -0,0 +1,42 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ export type ReviewScenario = "stall-diagnosis" | "scope-review" | "commitment-followup";
6
+ export function reviewRevision(agentDir: string, scenario: string) {
7
+ try {
8
+ const raw = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8")).piBetterHarness?.supervisorMode;
9
+ if (raw?.enabled === true && Array.isArray(raw.scenarios) && raw.scenarios.includes(scenario))
10
+ return typeof raw.revision === "string" ? raw.revision : "initial";
11
+ } catch { /* Unreadable settings cannot authorize a review. */ }
12
+ }
13
+
14
+ /** One model analysis per daemon. Leases are short and disappear on daemon replacement. */
15
+ export class SupervisorAdmission {
16
+ private lease?: { token: string; owner: string; scenario: ReviewScenario; revision: string; expires: number };
17
+ private readonly revision: (scenario: ReviewScenario) => string | undefined;
18
+ private readonly now: () => number;
19
+ constructor(revision: (scenario: ReviewScenario) => string | undefined, now = Date.now) {
20
+ this.revision = revision;
21
+ this.now = now;
22
+ }
23
+ request(owner: string, command: Record<string, unknown>) {
24
+ const scenario = command.scenario;
25
+ if (scenario !== "stall-diagnosis" && scenario !== "scope-review" && scenario !== "commitment-followup") throw new Error("Unsupported Supervisor scenario");
26
+ const lease = this.lease;
27
+ const revision = this.revision(scenario);
28
+ if (lease && (lease.expires <= this.now() || lease.revision !== (lease.scenario === scenario ? revision : this.revision(lease.scenario)))) this.lease = undefined;
29
+ if (!revision) return { status: "disabled" };
30
+ if (command.action === "begin") {
31
+ if (this.lease) return { status: "busy" };
32
+ const token = randomUUID();
33
+ this.lease = { owner, scenario, token, revision, expires: this.now() + 45_000 };
34
+ return { status: "admitted", token };
35
+ }
36
+ if (command.action !== "finish" && command.action !== "release") throw new Error("Unsupported Supervisor action");
37
+ if (!this.lease || this.lease.owner !== owner || this.lease.scenario !== scenario || this.lease.token !== command.token)
38
+ return { status: "stale" };
39
+ this.lease = undefined;
40
+ return { status: command.action === "finish" ? "admitted" : "released" };
41
+ }
42
+ }
@@ -0,0 +1,60 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { createRequire } from "node:module";
3
+ import { join } from "node:path";
4
+
5
+ const fields = ["reference", "operation", "host", "resource", "effect"] as const;
6
+ type Scope = Record<typeof fields[number], string>;
7
+ const questionMs = 120_000;
8
+ export const decisionDurationMs = 60 * 60_000;
9
+
10
+ function exactScope(raw: unknown): Scope {
11
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("Missing decision scope");
12
+ const scope = {} as Scope;
13
+ for (const key of fields) {
14
+ const text = (raw as Scope)[key];
15
+ if (typeof text !== "string" || !text.trim() || text !== text.trim() || text.length > 200 || /[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/u.test(text)) throw new Error("Invalid decision scope");
16
+ scope[key] = text;
17
+ }
18
+ if (Object.keys(raw).length !== fields.length) throw new Error("Unsupported decision scope field");
19
+ return scope;
20
+ }
21
+
22
+ /** One local user's answer to a specific proposal in a trusted workspace; execution still uses normal tool authorization. */
23
+ export function supervisorDecision(agentDir: string, owner: { cwd: string; sessionId: string; projectTrusted: boolean },
24
+ command: Record<string, unknown>, now = Date.now()) {
25
+ if (!owner.projectTrusted) throw new Error("Supervisor decisions require a trusted workspace");
26
+ const scope = exactScope(command.scope);
27
+ const key = createHash("sha256").update(JSON.stringify([owner.cwd, scope])).digest("hex");
28
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite") as typeof import("node:sqlite");
29
+ const db = new DatabaseSync(join(agentDir, "supervisor-decisions.sqlite"));
30
+ try {
31
+ db.exec("CREATE TABLE IF NOT EXISTS decisions(id TEXT PRIMARY KEY, state TEXT NOT NULL, expires INTEGER NOT NULL, owner TEXT NOT NULL, token TEXT NOT NULL)");
32
+ db.exec("CREATE INDEX IF NOT EXISTS decisions_expiry ON decisions(expires)");
33
+ db.exec("BEGIN IMMEDIATE");
34
+ db.prepare("DELETE FROM decisions WHERE expires <= ?").run(now);
35
+ const row = db.prepare("SELECT * FROM decisions WHERE id=?").get(key);
36
+ const lookup = () => ({ status: row?.state ?? "missing", expires: row?.expires });
37
+ let result;
38
+ if (command.action === "decision-query") result = lookup();
39
+ else if (command.action === "decision-request") {
40
+ if (row) result = lookup();
41
+ else {
42
+ const token = randomUUID();
43
+ db.prepare("INSERT INTO decisions VALUES(?, 'pending', ?, ?, ?)").run(key, now + questionMs, owner.sessionId, token);
44
+ result = { status: "ask", token, scope, workspace: owner.cwd, timeoutMs: questionMs, durationMinutes: decisionDurationMs / 60_000 };
45
+ }
46
+ } else if (command.action === "decision-answer") {
47
+ if (row?.state !== "pending" || row.owner !== owner.sessionId || row.token !== command.token) result = { status: "stale" };
48
+ else if (command.answer === "cancelled") {
49
+ db.prepare("DELETE FROM decisions WHERE id=?").run(key);
50
+ result = { status: "cancelled" };
51
+ } else {
52
+ if (command.answer !== "approved" && command.answer !== "denied") throw new Error("Invalid decision answer");
53
+ db.prepare("UPDATE decisions SET state=?, expires=?, token='' WHERE id=?").run(command.answer, now + decisionDurationMs, key);
54
+ result = { status: command.answer, expires: now + decisionDurationMs };
55
+ }
56
+ } else throw new Error("Unsupported decision action");
57
+ db.exec("COMMIT");
58
+ return result;
59
+ } finally { db.close(); }
60
+ }
package/src/server.ts CHANGED
@@ -103,7 +103,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
103
103
  const initializeBackground = () => backgroundInitialization ??= (() => {
104
104
  options.rpcEvidence?.event('background', 0, 'init-pending');
105
105
  return createBackgroundTools(realpathSync(getAgentDir()), instanceId!, () => Boolean(pendingUpgrade), scope => work().snapshot(scope), config.runtimeIdleMs,
106
- options.rpcEvidence ? (slot, phase) => options.rpcEvidence!.event('adapter', slot, phase) : undefined)
106
+ options.rpcEvidence ? (slot, phase) => options.rpcEvidence!.event('adapter', slot, phase) : undefined, catalog.sources)
107
107
  .then(host => { options.rpcEvidence?.event('background', 0, 'init-returned'); return backgroundTools = host; })
108
108
  .catch(error => { options.rpcEvidence?.event('background', 0, 'init-failed'); backgroundInitialization = undefined; throw error; });
109
109
  })();
@@ -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();
@@ -140,7 +140,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
140
140
  }
141
141
  resultPorts.set(resultRoot, resultPort);
142
142
  if (controlStore.store.pendingTaskCancellations().length) cancellations = new RuntimeCancellation(realpathSync(getAgentDir()), instanceId!, options.cancellationFault);
143
- const catalog = new SharedCatalog(realpathSync(getAgentDir()), instanceId!);
143
+ const catalog = new SharedCatalog(realpathSync(getAgentDir()), instanceId!, () => workModel?.sharedReadHealth());
144
144
  const initializeLaunch = () => {
145
145
  if (!launchInitialization) {
146
146
  const pending = createSubagentLaunch(realpathSync(getAgentDir()), instanceId!, catalog, config.runtimeIdleMs);
@@ -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() ?? []),
@@ -367,7 +368,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
367
368
  catalogSubscription = subscription;
368
369
  return reply({ data: subscription.snapshot });
369
370
  }
370
- if (["runtime_register_catalog", "runtime_get_catalog", "runtime_get_catalog_scope", "runtime_edit_catalog"].includes(type)) {
371
+ if (["runtime_register_catalog", "runtime_get_catalog", "runtime_get_catalog_scope", "runtime_edit_catalog", "runtime_supervisor_review"].includes(type)) {
371
372
  if (!greeted) throw new Error(`${type} requires hello`);
372
373
  return reply({ data: catalogCommand(command) });
373
374
  }
@@ -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.7.3";
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 };