pi-better-server 0.7.3 → 0.8.0

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 (39) 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-service/ci-observation.domain.mjs +134 -0
  10. package/src/runtime/domain/background-service/ci-observation.ts +118 -0
  11. package/src/runtime/domain/background-service/managed-client.domain.mjs +6 -2
  12. package/src/runtime/domain/background-service/managed-client.ts +6 -2
  13. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +47 -7
  14. package/src/runtime/domain/background-service/managed-frontend.ts +36 -6
  15. package/src/runtime/domain/background-service/observed-waits.domain.mjs +26 -0
  16. package/src/runtime/domain/background-service/observed-waits.ts +24 -0
  17. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  18. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +1 -0
  19. package/src/runtime/domain/catalog/catalog-schema.d.mts +6 -0
  20. package/src/runtime/domain/catalog/catalog-schema.mjs +1 -0
  21. package/src/runtime/domain/catalog/roles/role.supervisor.md +16 -0
  22. package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1 -0
  23. package/src/runtime/domain/subagents/catalog-schema.ts +1 -0
  24. package/src/runtime/domain/subagents/package.json +1 -1
  25. package/src/runtime/domain/subagents/roles/role.supervisor.md +16 -0
  26. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +14 -2
  27. package/src/runtime/domain/subagents/shared-catalog.ts +14 -2
  28. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  29. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +1 -0
  30. package/src/runtime/domain/subagents/supervisor-client.mjs +36 -0
  31. package/src/runtime/queries.ts +17 -3
  32. package/src/runtime/query-executor.ts +46 -3
  33. package/src/runtime/query-worker.mjs +6 -1
  34. package/src/runtime/read-model.ts +14 -5
  35. package/src/runtime/shared-read-diagnosis.ts +29 -0
  36. package/src/runtime/supervisor-admission.ts +42 -0
  37. package/src/runtime/supervisor-decisions.ts +60 -0
  38. package/src/server.ts +3 -3
  39. package/src/version.ts +1 -1
@@ -102,6 +102,7 @@ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConn
102
102
  this.revision(); return db; },
103
103
  changes() { this.revision(); return inbox.receive(db, identity); },
104
104
  acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
105
+ get hasPendingChanges() { return inbox.hasPendingChanges; },
105
106
  get changeMetrics() { return inbox.metrics; },
106
107
  get snapshotActive() { return snapshot; },
107
108
  beginSnapshot() {
@@ -74,6 +74,12 @@ export declare const APPROVED_ROLE_DEFAULTS: readonly [{
74
74
  readonly model: "openai/gpt-6-astra";
75
75
  readonly effort: "high";
76
76
  readonly tier: "frontier";
77
+ }, {
78
+ readonly id: "role.supervisor";
79
+ readonly name: "Supervisor";
80
+ readonly model: "openai/gpt-6.1-sol";
81
+ readonly effort: "medium";
82
+ readonly tier: "balanced";
77
83
  }, {
78
84
  readonly id: "role.writer";
79
85
  readonly name: "Writer";
@@ -71,6 +71,7 @@ export const APPROVED_ROLE_DEFAULTS = [
71
71
  { id: "role.developer", name: "Developer", model: "openai/gpt-6.1-sol", effort: "high", tier: "balanced" },
72
72
  { id: "role.reviewer", name: "Reviewer", model: "openai/gpt-6-astra", effort: "medium", tier: "frontier" },
73
73
  { id: "role.architect", name: "Architect", model: "openai/gpt-6-astra", effort: "high", tier: "frontier" },
74
+ { id: "role.supervisor", name: "Supervisor", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
74
75
  { id: "role.writer", name: "Writer", model: "openai/gpt-6.1-terra", effort: "medium", tier: undefined },
75
76
  ];
76
77
  export const DiagnosticCodes = {
@@ -0,0 +1,16 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.supervisor
5
+ name: Supervisor
6
+ description: Diagnoses blocked or stalled Outcomes and reviews scope drift using evidence supplied for the affected owner.
7
+ defaults:
8
+ model: openai/gpt-6.1-sol
9
+ effort: medium
10
+ tier: balanced
11
+ ---
12
+ Start from the current Outcome, acceptance criteria and evidence supplied for this owner. Cite the observations that support your diagnosis. If one fact would distinguish plausible causes, request the smallest authorized read-only check.
13
+
14
+ For a blocker, propose a recovery action, its prerequisites and a check of the original operation. If a CI watcher exits while its remote run is active, suggest resuming observation by the original run ID. For a stall, identify the last change to an acceptance criterion and test why progress stopped. For scope drift, identify necessary investigations and which planned steps the owner can prune.
15
+
16
+ Return the next action and its expected observable result to the execution owner. Consult prior interventions and approvals when supplied. Repeat a recommendation only when the evidence changes what the owner needs to do. Do not restart builds, wake sessions, grant approvals, or change an Outcome. The daemon controls delivery and the execution owner controls recovery.
@@ -71,6 +71,7 @@ export const APPROVED_ROLE_DEFAULTS = [
71
71
  { id: "role.developer", name: "Developer", model: "openai/gpt-6.1-sol", effort: "high", tier: "balanced" },
72
72
  { id: "role.reviewer", name: "Reviewer", model: "openai/gpt-6-astra", effort: "medium", tier: "frontier" },
73
73
  { id: "role.architect", name: "Architect", model: "openai/gpt-6-astra", effort: "high", tier: "frontier" },
74
+ { id: "role.supervisor", name: "Supervisor", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
74
75
  { id: "role.writer", name: "Writer", model: "openai/gpt-6.1-terra", effort: "medium", tier: undefined },
75
76
  ];
76
77
  export const DiagnosticCodes = {
@@ -85,6 +85,7 @@ export const APPROVED_ROLE_DEFAULTS = [
85
85
  { id: "role.developer", name: "Developer", model: "openai/gpt-6.1-sol", effort: "high", tier: "balanced" },
86
86
  { id: "role.reviewer", name: "Reviewer", model: "openai/gpt-6-astra", effort: "medium", tier: "frontier" },
87
87
  { id: "role.architect", name: "Architect", model: "openai/gpt-6-astra", effort: "high", tier: "frontier" },
88
+ { id: "role.supervisor", name: "Supervisor", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
88
89
  { id: "role.writer", name: "Writer", model: "openai/gpt-6.1-terra", effort: "medium", tier: undefined },
89
90
  ] as const;
90
91
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.38.0",
3
+ "version": "0.39.0",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,16 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.supervisor
5
+ name: Supervisor
6
+ description: Diagnoses blocked or stalled Outcomes and reviews scope drift using evidence supplied for the affected owner.
7
+ defaults:
8
+ model: openai/gpt-6.1-sol
9
+ effort: medium
10
+ tier: balanced
11
+ ---
12
+ Start from the current Outcome, acceptance criteria and evidence supplied for this owner. Cite the observations that support your diagnosis. If one fact would distinguish plausible causes, request the smallest authorized read-only check.
13
+
14
+ For a blocker, propose a recovery action, its prerequisites and a check of the original operation. If a CI watcher exits while its remote run is active, suggest resuming observation by the original run ID. For a stall, identify the last change to an acceptance criterion and test why progress stopped. For scope drift, identify necessary investigations and which planned steps the owner can prune.
15
+
16
+ Return the next action and its expected observable result to the execution owner. Consult prior interventions and approvals when supplied. Repeat a recommendation only when the evidence changes what the owner needs to do. Do not restart builds, wake sessions, grant approvals, or change an Outcome. The daemon controls delivery and the execution owner controls recovery.
@@ -5,7 +5,7 @@ import { connectWorkClient } from "./shared-work-client.mjs";
5
5
  import { catalogSnapshotFromWire, defaultUserRoot } from "./catalog-store.domain.mjs";
6
6
  import { catalogHostAuthority } from "./catalog-host-admission.domain.mjs";
7
7
  /** Short-lived catalog connection. No transcript or permission authority travels here. */
8
- export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess, signal) {
8
+ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess, signal, hostAuthority = catalogHostAuthority) {
9
9
  signal?.throwIfAborted();
10
10
  const agentDir = realpathSync(userRoot);
11
11
  let registration;
@@ -22,7 +22,7 @@ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessi
22
22
  throw new Error("Invalid canonical runtime registration");
23
23
  const client = await connectCatalogClient(agentDir, registration.serverDir, undefined, signal);
24
24
  const register = async (setupSignal) => {
25
- const authority = await catalogHostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
25
+ const authority = await hostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
26
26
  setupSignal?.throwIfAborted();
27
27
  await client.request("runtime_register_catalog", { cwd, sessionId: authority?.sessionId ?? sessionId, authority, projectAccess: projectAccess === false ? "deny" : undefined });
28
28
  };
@@ -39,6 +39,18 @@ export async function openSharedCatalog(cwd, userRoot = defaultUserRoot(), sessi
39
39
  const wire = await client.request("runtime_get_catalog", { overlay });
40
40
  return catalogSnapshotFromWire(wire);
41
41
  },
42
+ async decision(action, scope, token, answer) {
43
+ await register();
44
+ return client.request("runtime_supervisor_review", { action, scope, token, answer });
45
+ },
46
+ async sharedReadDiagnosis(verifiedIncident) {
47
+ await register();
48
+ return client.request("runtime_supervisor_review", { action: "read-health", verifiedIncident });
49
+ },
50
+ async review(scenario, action, token) {
51
+ await register();
52
+ return client.request("runtime_supervisor_review", { scenario, action, token });
53
+ },
42
54
  async edit(edit) { await register(); return client.request("runtime_edit_catalog", edit); },
43
55
  async scopedAgents(scope) { await register(); return client.request("runtime_get_catalog_scope", { scope }); },
44
56
  async subscribe(changed) {
@@ -6,7 +6,7 @@ import type { AgentSessionOverrides } from "./agent-session-settings.ts";
6
6
  import { catalogHostAuthority } from "./catalog-host-admission.ts";
7
7
 
8
8
  /** Short-lived catalog connection. No transcript or permission authority travels here. */
9
- export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess?: boolean, signal?: AbortSignal) {
9
+ export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(), sessionId = "catalog", projectAccess?: boolean, signal?: AbortSignal, hostAuthority = catalogHostAuthority) {
10
10
  signal?.throwIfAborted();
11
11
  const agentDir = realpathSync(userRoot);
12
12
  let registration;
@@ -19,7 +19,7 @@ export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(
19
19
  if (registration.version !== 1 || registration.agentDir !== agentDir) throw new Error("Invalid canonical runtime registration");
20
20
  const client = await connectCatalogClient(agentDir, registration.serverDir, undefined, signal);
21
21
  const register = async (setupSignal?: AbortSignal) => {
22
- const authority = await catalogHostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
22
+ const authority = await hostAuthority(agentDir, cwd, join(registration.serverDir, "pi-server.sock"));
23
23
  setupSignal?.throwIfAborted();
24
24
  await client.request("runtime_register_catalog", { cwd, sessionId: authority?.sessionId ?? sessionId, authority, projectAccess: projectAccess === false ? "deny" : undefined });
25
25
  };
@@ -32,6 +32,18 @@ export async function openSharedCatalog(cwd: string, userRoot = defaultUserRoot(
32
32
  const wire = await client.request("runtime_get_catalog", { overlay });
33
33
  return catalogSnapshotFromWire(wire);
34
34
  },
35
+ async decision(action: string, scope: Record<string, string>, token?: string, answer?: string) {
36
+ await register();
37
+ return client.request("runtime_supervisor_review", { action, scope, token, answer });
38
+ },
39
+ async sharedReadDiagnosis(verifiedIncident?: string): Promise<{ status: string; incident?: { id: string; recommendation: string } }> {
40
+ await register();
41
+ return client.request("runtime_supervisor_review", { action: "read-health", verifiedIncident });
42
+ },
43
+ async review(scenario: string, action: "begin" | "finish" | "release", token?: string): Promise<{ status: string; token?: string }> {
44
+ await register();
45
+ return client.request("runtime_supervisor_review", { scenario, action, token });
46
+ },
35
47
  async edit(edit: Record<string, unknown>) { await register(); return client.request("runtime_edit_catalog", edit); },
36
48
  async scopedAgents(scope: "user" | "project") { await register(); return client.request("runtime_get_catalog_scope", { scope }); },
37
49
  async subscribe(changed: (snapshot: CatalogSnapshot | undefined) => void) {
@@ -129,6 +129,9 @@ export class AssignmentInbox {
129
129
  throw error;
130
130
  }
131
131
  }
132
+ get hasPendingChanges() {
133
+ return Boolean(this.more || this.db.prepare(`SELECT 1 FROM ${this.prefix}pending LIMIT 1`).get());
134
+ }
132
135
  get metrics() {
133
136
  const pending = this.db.prepare(`SELECT count(*) AS pending, min(since) AS oldestPendingAt FROM ${this.prefix}pending`).get();
134
137
  return { ...this.db.prepare(`SELECT * FROM ${this.prefix}position`).get(),
@@ -102,6 +102,7 @@ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConn
102
102
  this.revision(); return db; },
103
103
  changes() { this.revision(); return inbox.receive(db, identity); },
104
104
  acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
105
+ get hasPendingChanges() { return inbox.hasPendingChanges; },
105
106
  get changeMetrics() { return inbox.metrics; },
106
107
  get snapshotActive() { return snapshot; },
107
108
  beginSnapshot() {
@@ -0,0 +1,36 @@
1
+ // Generated fixed launch domain from packages/pi-better-subagents/supervisor-client.mjs. Do not edit directly.
2
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
3
+ import { createCatalogHostAdapter } from "./catalog-host-admission.domain.mjs";
4
+ import { createAgentSessionSettings } from "./agent-session-settings.domain.mjs";
5
+ import { openSharedCatalog } from "./shared-catalog.domain.mjs";
6
+ import { resolveSelection } from "./catalog-resolver.domain.mjs";
7
+ export async function openSupervisorClient(pi, ctx, signal) {
8
+ const settings = createAgentSessionSettings(pi);
9
+ settings.restore(ctx);
10
+ // Pi loads extensions independently. Bind this request to its own live host context.
11
+ const host = createCatalogHostAdapter();
12
+ host.noteCatalogHostContext(ctx, () => settings.snapshot());
13
+ let catalog;
14
+ try {
15
+ catalog = await openSharedCatalog(ctx.cwd, getAgentDir(), ctx.sessionManager.getSessionId(), undefined, signal, host.catalogHostAuthority);
16
+ }
17
+ catch (error) {
18
+ host.closeCatalogHost();
19
+ throw error;
20
+ }
21
+ return {
22
+ close() { catalog.close(); host.closeCatalogHost(); },
23
+ review: catalog.review,
24
+ decision: catalog.decision,
25
+ sharedReadDiagnosis: catalog.sharedReadDiagnosis,
26
+ async role() {
27
+ settings.restore(ctx);
28
+ const snapshot = await catalog.get(settings.snapshot());
29
+ const selected = resolveSelection(snapshot, { roleId: "role.supervisor" });
30
+ if (!selected.launchable || !selected.effective)
31
+ return;
32
+ const { instructions, model, effort } = selected.effective;
33
+ return { revision: snapshot.revision, instructions, model: model.value, effort: effort.value };
34
+ },
35
+ };
36
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Socket } from "node:net";
2
- import type { WorkReadModel, WorkScope } from "./read-model.ts";
2
+ import type { WorkReadModel, WorkScope, WorkSnapshot } from "./read-model.ts";
3
3
 
4
4
  const eventEncodings = new WeakMap<object, string>();
5
5
  const snapshotEncodings = new WeakMap<object, string>();
@@ -8,6 +8,10 @@ export function snapshotJSON(snapshot: object): string {
8
8
  if (json === undefined) { json = JSON.stringify(snapshot); snapshotEncodings.set(snapshot, json); }
9
9
  return json;
10
10
  }
11
+ // The global sequence may advance while a session's Background rows and deadlines stay unchanged.
12
+ function backgroundNotificationKey(snapshot: WorkSnapshot) {
13
+ return JSON.stringify([snapshot.scopeRevision, snapshot.status, snapshot.reason, snapshot.nextDeadline]);
14
+ }
11
15
  export const queryEncodingMetrics = { serializations: 0, frames: 0, bytes: 0 };
12
16
 
13
17
  export function workScope(input: unknown): WorkScope {
@@ -35,6 +39,7 @@ export class WorkQueries {
35
39
  private dispose?: () => void;
36
40
  private paused = false;
37
41
  private lastSnapshotSeq?: number;
42
+ private lastBackgroundKey?: string;
38
43
  private model: WorkReadModel;
39
44
  private socket: Socket;
40
45
  private maxQueuedBytes: number;
@@ -51,8 +56,10 @@ export class WorkQueries {
51
56
  }
52
57
  private event(event: unknown) {
53
58
  if (this.socket.destroyed || this.paused) return;
54
- if (this.socket.writableLength > this.maxQueuedBytes) { this.paused = true; return; }
55
59
  const snapshot = (event as any)?.type === "runtime_snapshot" ? (event as any).snapshot : undefined;
60
+ const key = snapshot && this.lastBackgroundKey !== undefined ? backgroundNotificationKey(snapshot) : undefined;
61
+ if (key !== undefined && key === this.lastBackgroundKey) return;
62
+ if (this.socket.writableLength > this.maxQueuedBytes) { this.paused = true; return; }
56
63
  let line: string;
57
64
  if (snapshot) {
58
65
  let prefix = eventEncodings.get(snapshot);
@@ -68,7 +75,10 @@ export class WorkQueries {
68
75
  this.socket.write(JSON.stringify({ type: "event", event: { type: "resync_required", reason: "snapshot-too-large: narrow the scope or limit" } }) + "\n");
69
76
  return;
70
77
  }
71
- if (snapshot) this.lastSnapshotSeq = snapshot.seq;
78
+ if (snapshot) {
79
+ this.lastSnapshotSeq = snapshot.seq;
80
+ this.lastBackgroundKey = key;
81
+ }
72
82
  this.socket.write(line);
73
83
  queryEncodingMetrics.frames++; queryEncodingMetrics.bytes += Buffer.byteLength(line);
74
84
  }
@@ -76,11 +86,15 @@ export class WorkQueries {
76
86
  if (command.type === "runtime_unsubscribe") { this.close(); return { unsubscribed: true }; }
77
87
  if (command.type === "runtime_get_metrics") return { ...this.model.metrics };
78
88
  const scope = workScope(command.scope);
89
+ // An explicit read must see new commits. Publication callbacks already observe
90
+ // the reconciled state and must not poll the inbox again for every subscriber.
91
+ if (scope.background && !scope.backgroundHistory) this.model.prepareBackgroundQuery();
79
92
  const snapshot = this.model.snapshot(scope);
80
93
  if (Buffer.byteLength(snapshotJSON(snapshot)) > 4 * 1024 * 1024 - 1024) throw new Error("state-degraded: snapshot exceeds the 4 MiB frame allowance; narrow the scope or limit");
81
94
  if (command.type === "runtime_subscribe") {
82
95
  this.close();
83
96
  this.lastSnapshotSeq = snapshot.seq;
97
+ this.lastBackgroundKey = scope.background && !scope.backgroundHistory ? backgroundNotificationKey(snapshot) : undefined;
84
98
  this.dispose = this.model.onChange(() => {
85
99
  try {
86
100
  this.event({ type: "runtime_snapshot", snapshot: this.model.snapshot({ ...scope, cursor: undefined }) });
@@ -8,6 +8,8 @@ import { executionPhases, inventoryPhases } from "./read-watchdog-probe.ts";
8
8
  import { notifyWorkBudget } from "./work-budget.ts";
9
9
  import { HostSourceWatches } from "./source-watch.ts";
10
10
 
11
+ const INBOX_DIAGNOSTICS_WAIT_MS = 100;
12
+
11
13
  export interface EncodedRead { json: string }
12
14
  interface Waiter { connection: number; expiresAt: number; deadline: ReturnType<typeof setTimeout>; resolve(value: EncodedRead): void; reject(error: Error): void }
13
15
  interface Query {
@@ -16,7 +18,7 @@ interface Query {
16
18
  }
17
19
  export type ReadStream = Pick<Duplex, "destroyed" | "writableLength" | "write" | "on" | "once" | "off">;
18
20
  interface Stream { socket: ReadStream; paused: boolean; generation: number; drain: () => void; close: () => void }
19
- interface WorkerMetrics { sourceWatchers?: number; inventories?: number; coordinatorConnections?: number; indexConnections?: number; sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
21
+ interface WorkerMetrics { background?: Record<string, unknown>; sourceWatchers?: number; inventories?: number; coordinatorConnections?: number; indexConnections?: number; sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
20
22
  export interface QueryExecutorOptions {
21
23
  queryCacheDiagnostics?: boolean;
22
24
  capacity?: number; timeoutMs?: number; maxConnections?: number; watchdogMs?: number;
@@ -54,6 +56,8 @@ export class WorkQueryExecutor {
54
56
  private heartbeat!: BigInt64Array;
55
57
  private probe?: Int32Array;
56
58
  private workerMetrics: WorkerMetrics = {};
59
+ private inboxSample?: WorkReadModel["inboxDiagnostics"];
60
+ private inboxRequest?: { ready: Promise<boolean>; finish(fresh: boolean, error?: string): void };
57
61
  private lastObservation: Omit<ReturnType<WorkReadModel["observation"]>, "observedAt"> & { observedAt: number | null } = {
58
62
  status: "rebuilding", reason: "Initial source inventory is rebuilding.", observedAt: null, reasons: [],
59
63
  };
@@ -189,6 +193,7 @@ export class WorkQueryExecutor {
189
193
  this.workerGeneration++;
190
194
  this.internalRecoveryDemand = false;
191
195
  this.exited = false; this.failure = undefined; this.termination = undefined;
196
+ this.inboxSample = undefined;
192
197
  this.workerMetrics = {}; this.workerConnections.clear(); this.revision++;
193
198
  this.lastResponse = performance.now();
194
199
  this.lastObservation = { status: "rebuilding", reason: "Read worker is recovering its source inventory.", observedAt: null, reasons: [] };
@@ -232,12 +237,21 @@ export class WorkQueryExecutor {
232
237
  return JSON.parse(result.json);
233
238
  }
234
239
 
240
+ sharedReadHealth() {
241
+ return { state: this.observation().status, generation: this.workerGeneration };
242
+ }
243
+
235
244
  observation() {
236
245
  return this.failure ? { ...this.lastObservation, status: "degraded" as const, reason: this.failure.message } : this.lastObservation;
237
246
  }
238
247
 
239
248
  metrics() {
240
- return { ...this.workerMetrics, sourceSubscriptions: this.sourceWatches.metrics(), executor: { active: this.active ? 1 : 0, queued: this.queue.length,
249
+ const unavailable = { available: false, received: null, applied: null, pending: null };
250
+ return { ...this.workerMetrics,
251
+ assignments: this.inboxSample?.assignments ?? unavailable,
252
+ background: { ...this.workerMetrics.background, changes: this.inboxSample?.backgroundChanges ?? unavailable },
253
+ inboxDiagnosticsObservedAt: this.inboxSample?.observedAt ?? null,
254
+ sourceSubscriptions: this.sourceWatches.metrics(), executor: { active: this.active ? 1 : 0, queued: this.queue.length,
241
255
  clients: this.streams.size, completed: this.completed, singleflightHits: this.coalesced, rejected: this.rejected,
242
256
  cancelled: this.cancelled, timeouts: this.timeouts, queueTimeouts: this.queueTimeouts, callerTimeouts: this.callerTimeouts,
243
257
  capacity: this.options.capacity ?? 64, waitMs: [...this.waits], readMs: [...this.durations],
@@ -247,9 +261,30 @@ export class WorkQueryExecutor {
247
261
  status: this.failure ? "degraded" : "ready" } };
248
262
  }
249
263
 
264
+ private sampleInbox(): Promise<boolean> {
265
+ if (this.failure || this.closed) return Promise.resolve(false);
266
+ if (this.inboxRequest) return this.inboxRequest.ready;
267
+
268
+ let finish!: (fresh: boolean, error?: string) => void;
269
+ const ready = new Promise<boolean>((resolve, reject) => {
270
+ // Return cached diagnostics on timeout, but keep the worker request single-flight until its reply.
271
+ const timer = setTimeout(() => resolve(false), INBOX_DIAGNOSTICS_WAIT_MS);
272
+ finish = (fresh, error) => {
273
+ clearTimeout(timer);
274
+ if (error) reject(new Error(error));
275
+ else resolve(fresh);
276
+ };
277
+ });
278
+ this.inboxRequest = { ready, finish };
279
+ this.worker.postMessage({ type: "inbox-diagnostics" });
280
+ return ready;
281
+ }
282
+
250
283
  private request(connection: number, input: Record<string, unknown>): Promise<EncodedRead> {
251
284
  if (connection !== 0 && !this.streams.has(connection)) return Promise.reject(new Error("runtime-unavailable: client disconnected"));
252
- if (input.type === "runtime_get_metrics") return Promise.resolve({ json: JSON.stringify(this.metrics()) });
285
+ if (input.type === "runtime_get_metrics") {
286
+ return this.sampleInbox().then(fresh => ({ json: JSON.stringify({ ...this.metrics(), inboxDiagnosticsFresh: fresh }) }));
287
+ }
253
288
  if (this.failure) {
254
289
  if (connection === 0) this.internalRecoveryDemand = true;
255
290
  this.scheduleRecovery(); return Promise.reject(this.failure);
@@ -324,6 +359,12 @@ export class WorkQueryExecutor {
324
359
  if (message.id === this.active?.id) { this.active = undefined; this.pump(); }
325
360
  return;
326
361
  }
362
+ if (message.type === "inbox-diagnostics") {
363
+ if (message.sample) this.inboxSample = message.sample;
364
+ this.inboxRequest?.finish(Boolean(message.sample), message.error);
365
+ this.inboxRequest = undefined;
366
+ return;
367
+ }
327
368
  if (message.metrics) this.workerMetrics = message.metrics;
328
369
  if (message.observation) this.lastObservation = message.observation;
329
370
  if (message.type === "terminal-logs") {
@@ -406,6 +447,8 @@ export class WorkQueryExecutor {
406
447
  if ([...this.queue, ...(this.active ? [this.active] : [])].some(query =>
407
448
  [...query.waiters].some(waiter => waiter.connection === 0))) this.internalRecoveryDemand = true;
408
449
  this.failure = error; this.lag.disable();
450
+ this.inboxRequest?.finish(false);
451
+ this.inboxRequest = undefined;
409
452
  for (const query of [...this.queue, ...(this.active ? [this.active] : [])]) this.finish(query, error);
410
453
  this.queue = []; this.active = undefined;
411
454
  for (const connection of this.streams.keys()) this.event(connection, JSON.stringify({ type: "event",
@@ -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;
@@ -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
+ }