pi-better-server 0.3.0 → 0.4.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.
- package/package.json +4 -1
- package/scripts/measure-shared-reads.mjs +25 -5
- package/scripts/test-on-pi.sh +3 -2
- package/src/daemon-owner.ts +2 -1
- package/src/handshake.ts +1 -1
- package/src/protocol.ts +2 -0
- package/src/runtime/background.ts +12 -3
- package/src/runtime/cancellation.ts +10 -6
- package/src/runtime/catalog-admission.ts +50 -0
- package/src/runtime/catalog.ts +133 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -1
- package/src/runtime/domain/assignment-observation.mjs +18 -1
- package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
- package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
- package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
- package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
- package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
- package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
- package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
- package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
- package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
- package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
- package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
- package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
- package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
- package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
- package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
- package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
- package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
- package/src/runtime/domain/catalog/thinking.d.mts +8 -0
- package/src/runtime/domain/catalog/thinking.mjs +22 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +9 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +5 -3
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +17 -1
- package/src/runtime/domain/coordinator/src/store.mjs +11 -1
- package/src/runtime/mutation-store.ts +34 -0
- package/src/runtime/query-executor.ts +58 -9
- package/src/runtime/query-worker.mjs +3 -2
- package/src/runtime/read-model.ts +111 -59
- package/src/runtime/result-supervision.ts +63 -0
- package/src/runtime/work-client.d.mts +1 -0
- package/src/runtime/work-client.mjs +16 -2
- package/src/server.ts +66 -5
- package/src/version.ts +1 -1
|
@@ -7,6 +7,7 @@ import { realpathSync, statSync } from "node:fs";
|
|
|
7
7
|
import { tmpdir } from "node:os";
|
|
8
8
|
import { createRequire } from "node:module";
|
|
9
9
|
import { setImmediate as yieldTurn } from "node:timers/promises";
|
|
10
|
+
import { performance } from "node:perf_hooks";
|
|
10
11
|
import { createAssignmentProjector } from "./domain/assignment-projection.mjs";
|
|
11
12
|
import { createAssignmentReader } from "./domain/assignment-observation.mjs";
|
|
12
13
|
import { parseArchivedAttempt, parseArchivedSessionState } from "./domain/session-store.mjs";
|
|
@@ -40,6 +41,11 @@ export class WorkReadModel {
|
|
|
40
41
|
private projected = new Map<string, { meta: any; assignment: any; sourceRevision: string; display?: { spend: string; tool: string }; health?: any }>();
|
|
41
42
|
private logs = new Map<string, string>();
|
|
42
43
|
private processes = new Map<string, string>();
|
|
44
|
+
private staged?: {
|
|
45
|
+
files: WorkReadModel["files"]; projected: WorkReadModel["projected"];
|
|
46
|
+
logs: Map<string, string>; processes: Map<string, string>; healthRevision: string;
|
|
47
|
+
coordinator: string; coordinatorConversations?: Map<string, string>;
|
|
48
|
+
};
|
|
43
49
|
private healthRevision = "";
|
|
44
50
|
private details = new Map<string, { revision: string; value: any }>();
|
|
45
51
|
private watchers: FSWatcher[] = [];
|
|
@@ -85,7 +91,7 @@ export class WorkReadModel {
|
|
|
85
91
|
this.watchers.push(watcher);
|
|
86
92
|
} catch { /* Missing roots are discovered by the compatibility inventory. */ }
|
|
87
93
|
}
|
|
88
|
-
this.timer = setInterval(() => { void this.reconcile(); }, options.intervalMs ?? 1000);
|
|
94
|
+
this.timer = setInterval(() => { if (!this.pending) void this.reconcile(); }, options.intervalMs ?? 1000);
|
|
89
95
|
this.timer.unref();
|
|
90
96
|
}
|
|
91
97
|
|
|
@@ -107,18 +113,21 @@ export class WorkReadModel {
|
|
|
107
113
|
...this.background.livenessReasons(options),
|
|
108
114
|
];
|
|
109
115
|
}
|
|
110
|
-
async ensureId(id: string) {
|
|
116
|
+
async ensureId(id: string): Promise<boolean> {
|
|
111
117
|
if (!safeId.test(id)) throw new Error("Invalid run ID");
|
|
112
|
-
if (this.state === "rebuilding")
|
|
113
|
-
if (this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)) return;
|
|
118
|
+
if (this.state === "rebuilding") return false;
|
|
119
|
+
if (this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)) return true;
|
|
114
120
|
try { await stat(join(this.runs, id, "meta.json")); }
|
|
115
|
-
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return; throw error; }
|
|
116
|
-
//
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
await
|
|
120
|
-
|
|
121
|
-
|
|
121
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return true; throw error; }
|
|
122
|
+
// Repair a newly written ID without letting a global inventory consume its read deadline.
|
|
123
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
124
|
+
try {
|
|
125
|
+
return await Promise.race([
|
|
126
|
+
this.reconcile().then(() => !!this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)),
|
|
127
|
+
new Promise<false>(resolve => { timeout = setTimeout(() => resolve(false), 100); }),
|
|
128
|
+
]);
|
|
129
|
+
} finally {
|
|
130
|
+
if (timeout) clearTimeout(timeout);
|
|
122
131
|
}
|
|
123
132
|
}
|
|
124
133
|
invalidate(reason: string) {
|
|
@@ -147,52 +156,73 @@ export class WorkReadModel {
|
|
|
147
156
|
private async scan() {
|
|
148
157
|
this.metrics.inventories++;
|
|
149
158
|
if (this.background.refresh()) this.publish();
|
|
159
|
+
let releaseCoordinator: (() => void) | undefined;
|
|
160
|
+
const baseline = this.staged ?? { files: this.files, projected: this.projected, logs: this.logs, processes: this.processes,
|
|
161
|
+
healthRevision: this.healthRevision, coordinator: this.coordinator, coordinatorConversations: this.coordinatorConversations };
|
|
150
162
|
try {
|
|
151
163
|
const next = new Map<string, { signature: string; meta: any }>();
|
|
152
164
|
let batch = 0;
|
|
165
|
+
let sliceStarted = performance.now();
|
|
153
166
|
for (const [directory, archived] of [[this.markers, true], [this.archives, true], [this.runs, false]] as const) {
|
|
154
167
|
let names: string[];
|
|
155
168
|
try { names = await readdir(directory); }
|
|
156
169
|
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
170
|
+
// Bound filesystem concurrency without serializing every archive round trip.
|
|
171
|
+
const candidates = names.filter(name => safeId.test(archived ? name.replace(/\.json$/, "") : name)
|
|
172
|
+
&& (!archived || name.endsWith(".json")));
|
|
173
|
+
for (let offset = 0; offset < candidates.length; offset += 32) {
|
|
174
|
+
const group = candidates.slice(offset, offset + 32);
|
|
175
|
+
const observations = await Promise.all(group.map(async name => {
|
|
176
|
+
const path = archived ? join(directory, name) : join(directory, name, "meta.json");
|
|
177
|
+
try { return { info: await stat(path, { bigint: true }) }; }
|
|
178
|
+
catch (error) { return { error }; }
|
|
179
|
+
}));
|
|
180
|
+
for (const [index, name] of group.entries()) {
|
|
181
|
+
const id = archived ? name.replace(/\.json$/, "") : name;
|
|
182
|
+
const path = archived ? join(directory, name) : join(directory, name, "meta.json");
|
|
183
|
+
try {
|
|
184
|
+
const observation = observations[index]!;
|
|
185
|
+
if (!observation.info) throw observation.error;
|
|
186
|
+
const info = observation.info;
|
|
187
|
+
const signature = `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
|
188
|
+
let entry = baseline.files.get(path);
|
|
189
|
+
if (entry?.signature !== signature) {
|
|
190
|
+
this.metrics.metadataReads++;
|
|
191
|
+
const raw = await readFile(path, "utf8");
|
|
192
|
+
if (directory === this.markers) {
|
|
193
|
+
const marker = parseArchivedSessionState(raw, id);
|
|
194
|
+
if (!marker) throw new Error(`Unusable session marker: ${id}`);
|
|
195
|
+
entry = { signature, meta: marker };
|
|
196
|
+
next.set(path, entry);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
const meta = archived ? parseArchivedAttempt(raw, id, join(this.archives, "../sessions")) : JSON.parse(raw);
|
|
200
|
+
if (meta?.id !== id || typeof meta.cwd !== "string" || !Number.isFinite(meta.startedAt) || typeof meta.status !== "string") throw new Error(`Unusable run record: ${id}`);
|
|
201
|
+
entry = { signature, meta };
|
|
174
202
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
203
|
+
next.set(path, entry!);
|
|
204
|
+
} catch (error) {
|
|
205
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
206
|
+
}
|
|
207
|
+
if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
|
|
208
|
+
await yieldTurn(); sliceStarted = performance.now();
|
|
178
209
|
}
|
|
179
|
-
|
|
180
|
-
} catch (error) {
|
|
181
|
-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
210
|
+
if (this.closed) return;
|
|
182
211
|
}
|
|
183
|
-
if (++batch % 256 === 0) await yieldTurn();
|
|
184
|
-
if (this.closed) return;
|
|
185
212
|
}
|
|
186
213
|
}
|
|
187
214
|
let coordinator: string;
|
|
188
|
-
try {
|
|
189
|
-
|
|
215
|
+
try {
|
|
216
|
+
const snapshot = this.reader.beginSnapshot();
|
|
217
|
+
coordinator = snapshot.revision; releaseCoordinator = snapshot.release;
|
|
218
|
+
} catch { coordinator = "unknown"; }
|
|
219
|
+
const coordinatorConversations = coordinator === baseline.coordinator ? baseline.coordinatorConversations : this.reader.conversationRevisions();
|
|
190
220
|
const logs = new Map<string, string>();
|
|
191
221
|
const processes = new Map<string, string>();
|
|
192
222
|
const logFamilies = new Set<string>();
|
|
193
223
|
for (const [path, entry] of next) {
|
|
194
224
|
if (!path.startsWith(this.runs + sep)) continue;
|
|
195
|
-
let signature =
|
|
225
|
+
let signature = baseline.logs.get(entry.meta.id);
|
|
196
226
|
{
|
|
197
227
|
try {
|
|
198
228
|
const info = await stat(join(this.runs, entry.meta.id, "output.log"), { bigint: true });
|
|
@@ -200,13 +230,14 @@ export class WorkReadModel {
|
|
|
200
230
|
} catch (error) { signature = (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
|
|
201
231
|
}
|
|
202
232
|
logs.set(entry.meta.id, signature);
|
|
203
|
-
if (signature !==
|
|
233
|
+
if (signature !== baseline.logs.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
|
|
204
234
|
const status = effectiveStatus(entry.meta); processes.set(entry.meta.id, status);
|
|
205
|
-
if (status !==
|
|
235
|
+
if (status !== baseline.processes.get(entry.meta.id)) logFamilies.add(JSON.stringify([entry.meta.sessionId, entry.meta.cwd]));
|
|
236
|
+
if (performance.now() - sliceStarted >= 8) { await yieldTurn(); sliceStarted = performance.now(); }
|
|
206
237
|
}
|
|
207
238
|
const healthConfig = await readHealthConfig(this.agentDir, next.size > 0);
|
|
208
|
-
const changed = next.size !==
|
|
209
|
-
if (!changed && !logFamilies.size && coordinator === this.coordinator && healthConfig.revision === this.healthRevision && this.state === "ready") return;
|
|
239
|
+
const changed = next.size !== baseline.files.size || [...next].some(([path, entry]) => baseline.files.get(path)?.signature !== entry.signature);
|
|
240
|
+
if (!this.staged && !changed && !logFamilies.size && coordinator === this.coordinator && healthConfig.revision === this.healthRevision && this.state === "ready") return;
|
|
210
241
|
const metas = new Map<string, any>();
|
|
211
242
|
const markers = new Map([...next].filter(([path]) => path.startsWith(this.markers + sep)).map(([, entry]) => [entry.meta.sessionId, entry.meta]));
|
|
212
243
|
for (const [path, entry] of next) {
|
|
@@ -218,20 +249,20 @@ export class WorkReadModel {
|
|
|
218
249
|
const attempts = [...metas.values()];
|
|
219
250
|
const affected = new Set<string>(logFamilies);
|
|
220
251
|
const family = (meta: any) => JSON.stringify([meta.sessionId, meta.cwd]);
|
|
221
|
-
for (const [path, entry] of [...
|
|
222
|
-
if (
|
|
252
|
+
for (const [path, entry] of [...baseline.files, ...next]) {
|
|
253
|
+
if (baseline.files.get(path)?.signature !== next.get(path)?.signature) affected.add(family(entry.meta));
|
|
223
254
|
}
|
|
224
|
-
if (coordinator !==
|
|
255
|
+
if (coordinator !== baseline.coordinator) for (const meta of attempts) {
|
|
225
256
|
if (!(meta.assignment || meta.operations || meta.park)) continue;
|
|
226
257
|
const owner = JSON.stringify([meta.operations?.conversationId ?? meta.sessionId, meta.operations?.workspace ?? meta.cwd]);
|
|
227
|
-
if (!coordinatorConversations || !
|
|
228
|
-
coordinatorConversations.get(owner) !==
|
|
258
|
+
if (!coordinatorConversations || !baseline.coordinatorConversations ||
|
|
259
|
+
coordinatorConversations.get(owner) !== baseline.coordinatorConversations.get(owner)) affected.add(family(meta));
|
|
229
260
|
}
|
|
230
261
|
const project = createAssignmentProjector({ attempts, observe: (owner: any) => this.reader.read(owner) });
|
|
231
262
|
const rows = [];
|
|
232
263
|
for (const meta of attempts) {
|
|
233
|
-
let row =
|
|
234
|
-
if (!row || !row.assignment.verified || healthConfig.revision !==
|
|
264
|
+
let row = baseline.projected.get(meta.id);
|
|
265
|
+
if (!row || !row.assignment.verified || healthConfig.revision !== baseline.healthRevision || affected.has(family(meta))) {
|
|
235
266
|
this.metrics.projections++;
|
|
236
267
|
const assignment = project(meta, processes.get(meta.id) ?? meta.status);
|
|
237
268
|
const parsed = logs.get(meta.id) && logs.get(meta.id) !== "missing" ? parseRun(meta.id, { logPath: join(this.runs, meta.id, "output.log") }) : undefined;
|
|
@@ -240,19 +271,39 @@ export class WorkReadModel {
|
|
|
240
271
|
row = { meta, assignment, display, health, sourceRevision: hash([meta, assignment.revision, display, health]) };
|
|
241
272
|
}
|
|
242
273
|
rows.push(row);
|
|
243
|
-
if (++batch % 256 === 0
|
|
274
|
+
if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
|
|
275
|
+
await yieldTurn(); sliceStarted = performance.now();
|
|
276
|
+
}
|
|
244
277
|
}
|
|
245
278
|
let after: string;
|
|
246
279
|
try { after = this.reader.revision(); } catch { after = "unknown"; }
|
|
247
280
|
if (after !== coordinator) { this.state = "degraded"; this.reason = "Coordinator changed during observation; retrying."; this.dirty = true; this.publish(); return; }
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
281
|
+
// Retry caches are never queryable. Validate all unpublished families again before committing them.
|
|
282
|
+
this.staged = { files: next, projected: new Map(rows.map(row => [row.meta.id, row])), logs, processes,
|
|
283
|
+
healthRevision: healthConfig.revision, coordinator, coordinatorConversations };
|
|
284
|
+
const uncommitted = new Set(affected);
|
|
285
|
+
for (const [path, entry] of [...this.files, ...next]) {
|
|
286
|
+
if (this.files.get(path)?.signature !== next.get(path)?.signature) uncommitted.add(family(entry.meta));
|
|
287
|
+
}
|
|
288
|
+
const verify = [...next].filter(([, entry]) => uncommitted.has(family(entry.meta)));
|
|
289
|
+
for (let offset = 0; offset < verify.length; offset += 32) {
|
|
290
|
+
const group = verify.slice(offset, offset + 32);
|
|
291
|
+
const observations = await Promise.all(group.map(async ([path]) => {
|
|
292
|
+
try { return { info: await stat(path, { bigint: true }) }; }
|
|
293
|
+
catch (error) { return { error }; }
|
|
294
|
+
}));
|
|
295
|
+
for (const [index, [, entry]] of group.entries()) {
|
|
296
|
+
const observation = observations[index]!;
|
|
297
|
+
if (!observation.info) throw observation.error;
|
|
298
|
+
const info = observation.info;
|
|
299
|
+
if (`${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}` !== entry.signature) {
|
|
300
|
+
this.dirty = true;
|
|
301
|
+
throw new Error("Source changed during observation; retaining the previous snapshot while reconciling.");
|
|
302
|
+
}
|
|
303
|
+
if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
|
|
304
|
+
await yieldTurn(); sliceStarted = performance.now();
|
|
305
|
+
}
|
|
254
306
|
}
|
|
255
|
-
if (++batch % 256 === 0) await yieldTurn();
|
|
256
307
|
}
|
|
257
308
|
if (this.closed) return;
|
|
258
309
|
this.db.exec("BEGIN");
|
|
@@ -273,6 +324,7 @@ export class WorkReadModel {
|
|
|
273
324
|
this.files = next; this.logs = logs; this.processes = processes; this.healthRevision = healthConfig.revision; this.coordinator = coordinator; this.inventory++;
|
|
274
325
|
this.coordinatorConversations = coordinatorConversations;
|
|
275
326
|
this.projected = new Map(rows.map(row => [row.meta.id, row]));
|
|
327
|
+
this.staged = undefined;
|
|
276
328
|
const previousState = this.state;
|
|
277
329
|
const previousReason = this.reason;
|
|
278
330
|
this.state = rows.some(row => !row.assignment.verified) ? "degraded" : "ready";
|
|
@@ -281,7 +333,7 @@ export class WorkReadModel {
|
|
|
281
333
|
} catch (error) {
|
|
282
334
|
if (this.closed) return;
|
|
283
335
|
this.state = "degraded"; this.reason = String(error).slice(0, 512); this.publish();
|
|
284
|
-
}
|
|
336
|
+
} finally { releaseCoordinator?.(); }
|
|
285
337
|
}
|
|
286
338
|
|
|
287
339
|
snapshot(scope: WorkScope = {}): WorkSnapshot {
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { acquireMutationStore } from "./mutation-store.ts";
|
|
5
|
+
// @ts-expect-error Generated canonical supervisor.
|
|
6
|
+
import { createLocalSupervisor } from "./domain/background/supervisor/supervisor.mjs";
|
|
7
|
+
// @ts-expect-error Generated canonical terminal evidence rules.
|
|
8
|
+
import { supervisorTerminalPublication } from "./domain/background/terminal-publication.mjs";
|
|
9
|
+
|
|
10
|
+
export function hasResultSupervision(root: string): boolean {
|
|
11
|
+
const path = join(root, "operation-coordinator.sqlite");
|
|
12
|
+
if (!existsSync(path)) return false;
|
|
13
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
14
|
+
const db = new DatabaseSync(path, { readOnly: true });
|
|
15
|
+
try { return !!db.prepare("SELECT 1 FROM coordinator_state WHERE key LIKE 'result-supervision-v1:%' LIMIT 1").get(); }
|
|
16
|
+
finally { db.close(); }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Mechanical observation only. Never launches, stops, claims resumes or consumes results. */
|
|
20
|
+
export class RuntimeResultSupervision {
|
|
21
|
+
private store: any;
|
|
22
|
+
private releaseStore: () => void;
|
|
23
|
+
private timer: NodeJS.Timeout;
|
|
24
|
+
readonly hostId: string;
|
|
25
|
+
readonly epoch: string;
|
|
26
|
+
reason?: string;
|
|
27
|
+
constructor(root: string, epoch: string) {
|
|
28
|
+
this.epoch = epoch;
|
|
29
|
+
this.hostId = `server:${epoch}`;
|
|
30
|
+
const lease = acquireMutationStore(root);
|
|
31
|
+
this.store = lease.store;
|
|
32
|
+
this.releaseStore = lease.release;
|
|
33
|
+
this.reconcile();
|
|
34
|
+
this.timer = setInterval(() => this.reconcile(), 250);
|
|
35
|
+
this.timer.unref();
|
|
36
|
+
}
|
|
37
|
+
reconcile() {
|
|
38
|
+
try {
|
|
39
|
+
this.reason = undefined;
|
|
40
|
+
for (let grant of this.store.resultSupervisions(true)) {
|
|
41
|
+
const operation = this.store.getOperation(grant.operationId);
|
|
42
|
+
if (!operation || operation.terminalRevision > 0) continue;
|
|
43
|
+
if (grant.capability?.adapter !== "background-results-v1" || !grant.capability.captured || !grant.capability.current) {
|
|
44
|
+
this.reason = "permission-unavailable: captured Background adapter or permission source unavailable";
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (grant.epoch !== this.epoch) {
|
|
48
|
+
// Daemon startup has already proved the preceding root owner exited.
|
|
49
|
+
grant = { ...grant, hostId: this.hostId, epoch: this.epoch };
|
|
50
|
+
this.store.recoverResultSupervision(grant);
|
|
51
|
+
}
|
|
52
|
+
const inspection = createLocalSupervisor({ directory: grant.directory }).inspect(operation.taskId);
|
|
53
|
+
if (!inspection || inspection.token !== grant.launchToken) {
|
|
54
|
+
this.reason = "reconciling: exact runner evidence unavailable; no replacement command is permitted";
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (inspection.terminal) this.store.publishSupervisedResult({ operationId: operation.operationId,
|
|
58
|
+
epoch: this.epoch, publication: supervisorTerminalPublication(operation, inspection) });
|
|
59
|
+
}
|
|
60
|
+
} catch (error) { this.reason = String(error); }
|
|
61
|
+
}
|
|
62
|
+
close() { clearInterval(this.timer); this.releaseStore(); }
|
|
63
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { connect } from "node:net";
|
|
2
|
+
import { performance } from "node:perf_hooks";
|
|
2
3
|
|
|
3
4
|
/** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
|
|
4
5
|
export class WorkClient {
|
|
@@ -6,6 +7,7 @@ export class WorkClient {
|
|
|
6
7
|
snapshot;
|
|
7
8
|
pending = new Map();
|
|
8
9
|
listeners = new Set();
|
|
10
|
+
catalogListeners = new Set();
|
|
9
11
|
sequence = 0;
|
|
10
12
|
scope;
|
|
11
13
|
buffer = "";
|
|
@@ -23,6 +25,7 @@ export class WorkClient {
|
|
|
23
25
|
try {
|
|
24
26
|
const message = JSON.parse(line);
|
|
25
27
|
if (message.type === "event") {
|
|
28
|
+
if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
|
|
26
29
|
if (message.event.type === "resync_required") { this.degrade(message.event.reason); void this.resync().catch(error => this.degrade(String(error))); }
|
|
27
30
|
else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
|
|
28
31
|
} else {
|
|
@@ -50,6 +53,7 @@ export class WorkClient {
|
|
|
50
53
|
});
|
|
51
54
|
}
|
|
52
55
|
onChange(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
|
|
56
|
+
onCatalog(listener) { this.catalogListeners.add(listener); return () => this.catalogListeners.delete(listener); }
|
|
53
57
|
notify() { for (const listener of this.listeners) listener(this.snapshot); }
|
|
54
58
|
degrade(reason) {
|
|
55
59
|
this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
|
|
@@ -77,12 +81,22 @@ export class WorkClient {
|
|
|
77
81
|
const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
|
|
78
82
|
this.accept(snapshot); return snapshot;
|
|
79
83
|
}
|
|
80
|
-
async get(scope) {
|
|
84
|
+
async get(scope) {
|
|
85
|
+
await this.ready;
|
|
86
|
+
const until = performance.now() + 3500;
|
|
87
|
+
for (let attempt = 0; ; attempt++) {
|
|
88
|
+
const value = await this.request("runtime_get_snapshot", { scope });
|
|
89
|
+
if (!scope?.id || value.status !== "rebuilding" || value.rows.length || performance.now() >= until) return value;
|
|
90
|
+
// A newly written ID may join an inventory without holding the shared RPC queue.
|
|
91
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(250, 50 * 2 ** attempt, until - performance.now())));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
81
94
|
fail(error) {
|
|
82
95
|
if (this.closed) return;
|
|
83
96
|
this.closed = true;
|
|
84
97
|
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
|
85
98
|
this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
|
|
99
|
+
for (const listener of this.catalogListeners) listener({ status: "revoked" });
|
|
86
100
|
}
|
|
87
|
-
close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); }
|
|
101
|
+
close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); this.catalogListeners.clear(); }
|
|
88
102
|
}
|
package/src/server.ts
CHANGED
|
@@ -20,6 +20,9 @@ import { HostedSession } from "./hosted-session.ts";
|
|
|
20
20
|
import { readLifecycleConfig, type LifecycleConfig } from "./lifecycle-config.ts";
|
|
21
21
|
import { runtimeRoot } from "./runtime/root.ts";
|
|
22
22
|
import { RuntimeCancellation, hasPendingCancellation } from "./runtime/cancellation.ts";
|
|
23
|
+
import { RuntimeResultSupervision, hasResultSupervision } from "./runtime/result-supervision.ts";
|
|
24
|
+
import { SharedCatalog } from "./runtime/catalog.ts";
|
|
25
|
+
import { mutationStoreMetrics } from "./runtime/mutation-store.ts";
|
|
23
26
|
import { WorkQueryExecutor } from "./runtime/query-executor.ts";
|
|
24
27
|
|
|
25
28
|
export interface DaemonOptions extends Partial<LifecycleConfig> {
|
|
@@ -89,16 +92,39 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
89
92
|
const instanceId = owner.status === "live" ? owner.owner.token : undefined;
|
|
90
93
|
admitDaemonStartup({ canonicalServerDir: serverDir, agentDir: getAgentDir(), build, intent: startupIntentFromEnv(process.env) });
|
|
91
94
|
let cancellations: RuntimeCancellation | undefined;
|
|
92
|
-
|
|
95
|
+
let resultSupervision: RuntimeResultSupervision | undefined;
|
|
96
|
+
const resultPortKey = Symbol.for("pi-better-server:result-supervision-ports-v1");
|
|
97
|
+
const resultPorts: Map<string, any> = (globalThis as any)[resultPortKey] ??= new Map();
|
|
98
|
+
const resultRoot = realpathSync(getAgentDir());
|
|
99
|
+
const resultPort = { status() {
|
|
100
|
+
resultSupervision ??= new RuntimeResultSupervision(resultRoot, instanceId!);
|
|
101
|
+
resultSupervision.reconcile();
|
|
102
|
+
return { hostId: resultSupervision.hostId, epoch: resultSupervision.epoch, reason: resultSupervision.reason };
|
|
103
|
+
} };
|
|
93
104
|
let workModel: WorkQueryExecutor | undefined;
|
|
105
|
+
let registry!: SessionRegistry;
|
|
106
|
+
cleanupStartup = async () => {
|
|
107
|
+
try { await registry?.shutdown(); }
|
|
108
|
+
finally {
|
|
109
|
+
try { await cancellations?.close(); }
|
|
110
|
+
finally {
|
|
111
|
+
resultSupervision?.close();
|
|
112
|
+
if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
|
|
113
|
+
await workModel?.close();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
if (hasResultSupervision(getAgentDir())) resultSupervision = new RuntimeResultSupervision(resultRoot, instanceId!);
|
|
118
|
+
resultPorts.set(resultRoot, resultPort);
|
|
119
|
+
if (hasPendingCancellation(getAgentDir())) cancellations = new RuntimeCancellation(realpathSync(getAgentDir()), instanceId!, options.cancellationFault);
|
|
120
|
+
const catalog = new SharedCatalog(realpathSync(getAgentDir()), instanceId!);
|
|
94
121
|
const work = () => {
|
|
95
122
|
if (!workModel) {
|
|
96
123
|
workModel = new WorkQueryExecutor(realpathSync(getAgentDir()), instanceId!);
|
|
97
124
|
}
|
|
98
125
|
return workModel;
|
|
99
126
|
};
|
|
100
|
-
|
|
101
|
-
cleanupStartup = async () => { await registry.shutdown(); await cancellations?.close(); await workModel?.close(); };
|
|
127
|
+
registry = new SessionRegistry({ serverDir, sessionOptions: options.sessionOptions, eventLog: options.eventLog, log, sessionIdleMs: config.sessionIdleMs, now, workClient: () => createLocalWorkClient(work(), realpathSync(getAgentDir())) });
|
|
102
128
|
await registry.resumeAll();
|
|
103
129
|
const nativeHost = new NativeClientHost(registry);
|
|
104
130
|
// Structural port permits independent integration with the shared maintenance owner.
|
|
@@ -141,6 +167,8 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
141
167
|
};
|
|
142
168
|
const control = new ConnectionControl(send);
|
|
143
169
|
let greeted = false;
|
|
170
|
+
const catalogCommand = catalog.connection();
|
|
171
|
+
let catalogSubscription: { close(): void } | undefined;
|
|
144
172
|
let workQueries: ReturnType<WorkQueryExecutor["connect"]> | undefined;
|
|
145
173
|
let runtimeInFlight = 0;
|
|
146
174
|
|
|
@@ -191,10 +219,16 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
191
219
|
livenessReasons: [...[...runtimeClients.values()].map(id => ({ kind: "connection", id })),
|
|
192
220
|
...registry.list().filter(session => session.live).map(session => ({ kind: "hosted-session", id: session.sessionId })),
|
|
193
221
|
...(observation?.reasons ?? [])],
|
|
222
|
+
livenessObservation: observation ?? { status: "unobserved", reasons: [], observedAt: null },
|
|
194
223
|
nextIdleDeadline: runtimeClients.size > 0 || registry.activeCount > 0 ? null
|
|
195
224
|
: hostedUsed ? config.daemonIdleMs === 0 || zeroSince === undefined ? null : zeroSince + config.daemonIdleMs
|
|
196
225
|
: runtimeZeroSince === undefined ? null : runtimeZeroSince + config.runtimeIdleMs } });
|
|
197
226
|
}
|
|
227
|
+
if (type === "runtime_result_supervision") {
|
|
228
|
+
if (!greeted) throw new Error("not_accepted: supervision requires hello");
|
|
229
|
+
if (Object.keys(command).some(key => !["id", "type"].includes(key))) throw new Error("not_accepted: unsupported supervision field");
|
|
230
|
+
return reply({ data: resultPort.status() });
|
|
231
|
+
}
|
|
198
232
|
if (type === "runtime_cancel_task" || type === "runtime_query_cancellation" || type === "runtime_cancellation_status") {
|
|
199
233
|
if (!greeted) throw new Error("not_accepted: cancellation requires hello");
|
|
200
234
|
if (runtimeInFlight >= 32) throw new Error("not_accepted: too many in-flight runtime requests");
|
|
@@ -205,6 +239,25 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
205
239
|
return reply({ data: await cancellations.handle(command) });
|
|
206
240
|
} finally { runtimeInFlight--; }
|
|
207
241
|
}
|
|
242
|
+
if (type === "runtime_bind_catalog_host") {
|
|
243
|
+
if (!greeted) throw new Error(`${type} requires hello`);
|
|
244
|
+
catalog.admission.bind(command.authority, socket);
|
|
245
|
+
return reply({ data: { bound: true } });
|
|
246
|
+
}
|
|
247
|
+
if (type === "runtime_subscribe_catalog") {
|
|
248
|
+
if (!greeted) throw new Error(`${type} requires hello`);
|
|
249
|
+
catalogSubscription?.close();
|
|
250
|
+
const subscription = catalog.observe(() => catalogCommand({ type: "runtime_get_catalog", overlay: command.overlay }), snapshot => {
|
|
251
|
+
if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
|
|
252
|
+
send({ type: "event", event: { type: "runtime_catalog_snapshot", snapshot } } as unknown as ServerMessage);
|
|
253
|
+
});
|
|
254
|
+
catalogSubscription = subscription;
|
|
255
|
+
return reply({ data: subscription.snapshot });
|
|
256
|
+
}
|
|
257
|
+
if (["runtime_register_catalog", "runtime_get_catalog", "runtime_get_catalog_scope", "runtime_edit_catalog"].includes(type)) {
|
|
258
|
+
if (!greeted) throw new Error(`${type} requires hello`);
|
|
259
|
+
return reply({ data: catalogCommand(command) });
|
|
260
|
+
}
|
|
208
261
|
if (type === "runtime_register_client") {
|
|
209
262
|
if (!greeted) throw new Error("runtime_register_client requires hello");
|
|
210
263
|
if (typeof command.clientId !== "string" || !command.clientId || command.clientId.length > 256) throw new Error("Invalid runtime client identity");
|
|
@@ -235,6 +288,9 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
235
288
|
try {
|
|
236
289
|
workQueries ??= work().connect(socket);
|
|
237
290
|
const data = await workQueries.handle(command);
|
|
291
|
+
if (type === "runtime_get_metrics") {
|
|
292
|
+
return reply({ data: { ...JSON.parse(data.json), mutationSqlite: mutationStoreMetrics(getAgentDir()) } });
|
|
293
|
+
}
|
|
238
294
|
if (socket.writableLength > 4 * 1024 * 1024) { socket.destroy(); return; }
|
|
239
295
|
// Snapshot JSON is encoded in the worker; only the small envelope runs here.
|
|
240
296
|
const envelope = JSON.stringify({ id, type: "response", command: type, success: true });
|
|
@@ -366,6 +422,8 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
366
422
|
socket.on("data", (chunk: string) => decoder.push(chunk));
|
|
367
423
|
socket.on("error", () => undefined);
|
|
368
424
|
socket.on("close", () => {
|
|
425
|
+
catalogSubscription?.close();
|
|
426
|
+
catalog.admission.close(socket);
|
|
369
427
|
workQueries?.close();
|
|
370
428
|
sockets.delete(socket);
|
|
371
429
|
runtimeClients.delete(socket);
|
|
@@ -378,6 +436,8 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
378
436
|
|
|
379
437
|
cleanupStartup = async () => {
|
|
380
438
|
await cancellations?.close();
|
|
439
|
+
resultSupervision?.close();
|
|
440
|
+
if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
|
|
381
441
|
await workModel?.close();
|
|
382
442
|
for (const socket of sockets) socket.destroy();
|
|
383
443
|
server.close();
|
|
@@ -494,6 +554,8 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
494
554
|
for (const socket of sockets) socket.destroy();
|
|
495
555
|
await closed;
|
|
496
556
|
await cancellations?.close();
|
|
557
|
+
resultSupervision?.close();
|
|
558
|
+
if (resultPorts.get(resultRoot) === resultPort) resultPorts.delete(resultRoot);
|
|
497
559
|
await workModel?.close();
|
|
498
560
|
await registry.shutdown();
|
|
499
561
|
await Promise.allSettled([...dispatches]);
|
|
@@ -515,8 +577,7 @@ export async function startDaemon(options: DaemonOptions = {}): Promise<Daemon>
|
|
|
515
577
|
}
|
|
516
578
|
return daemon;
|
|
517
579
|
} catch (error) {
|
|
518
|
-
await cleanupStartup();
|
|
519
|
-
releaseOwner();
|
|
580
|
+
try { await cleanupStartup(); } finally { releaseOwner(); }
|
|
520
581
|
throw error;
|
|
521
582
|
}
|
|
522
583
|
}
|
package/src/version.ts
CHANGED