pi-better-server 0.2.4 → 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.
Files changed (109) hide show
  1. package/package.json +6 -3
  2. package/scripts/measure-shared-reads/daemon.mjs +7 -0
  3. package/scripts/measure-shared-reads/probe.mjs +10 -0
  4. package/scripts/measure-shared-reads.mjs +165 -0
  5. package/scripts/test-on-pi.sh +21 -3
  6. package/src/cli.ts +39 -2
  7. package/src/client.ts +9 -4
  8. package/src/daemon-owner.ts +48 -6
  9. package/src/handshake.ts +8 -7
  10. package/src/lifecycle-config.ts +4 -0
  11. package/src/paths.ts +1 -11
  12. package/src/protocol.ts +7 -0
  13. package/src/registry.ts +2 -1
  14. package/src/runtime/background-history.ts +241 -0
  15. package/src/runtime/background.ts +182 -0
  16. package/src/runtime/cancellation.ts +99 -0
  17. package/src/runtime/catalog-admission.ts +50 -0
  18. package/src/runtime/catalog.ts +133 -0
  19. package/src/runtime/client.ts +111 -0
  20. package/src/runtime/domain/assignment-observation.d.mts +1 -0
  21. package/src/runtime/domain/assignment-observation.mjs +120 -0
  22. package/src/runtime/domain/assignment-projection.d.mts +1 -0
  23. package/src/runtime/domain/assignment-projection.mjs +245 -0
  24. package/src/runtime/domain/background/conditions.mjs +93 -0
  25. package/src/runtime/domain/background/process-identity.mjs +110 -0
  26. package/src/runtime/domain/background/process.mjs +511 -0
  27. package/src/runtime/domain/background/registry.mjs +374 -0
  28. package/src/runtime/domain/background/snapshot.mjs +73 -0
  29. package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
  30. package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
  31. package/src/runtime/domain/background/supervisor/store.mjs +604 -0
  32. package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
  33. package/src/runtime/domain/background/supervisor/types.mjs +47 -0
  34. package/src/runtime/domain/background/terminal-publication.mjs +58 -0
  35. package/src/runtime/domain/background/types.mjs +3 -0
  36. package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
  37. package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
  38. package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
  39. package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
  40. package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
  41. package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
  42. package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
  43. package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
  44. package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
  45. package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
  46. package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
  47. package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
  48. package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
  49. package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
  50. package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
  51. package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
  52. package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
  53. package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
  54. package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
  55. package/src/runtime/domain/catalog/thinking.d.mts +8 -0
  56. package/src/runtime/domain/catalog/thinking.mjs +22 -0
  57. package/src/runtime/domain/coordinator/index.mjs +50 -0
  58. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
  59. package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
  60. package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
  61. package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
  62. package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
  63. package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
  64. package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
  65. package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
  66. package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
  67. package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
  68. package/src/runtime/domain/coordinator/src/store.mjs +245 -0
  69. package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
  70. package/src/runtime/domain/coordinator/src/types.mjs +24 -0
  71. package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
  72. package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
  73. package/src/runtime/domain/health-observation.d.mts +3 -0
  74. package/src/runtime/domain/health-observation.mjs +613 -0
  75. package/src/runtime/domain/health-surface.mjs +279 -0
  76. package/src/runtime/domain/log-cursor.mjs +148 -0
  77. package/src/runtime/domain/log-paths.mjs +13 -0
  78. package/src/runtime/domain/parse.d.mts +2 -0
  79. package/src/runtime/domain/parse.mjs +1173 -0
  80. package/src/runtime/domain/process-status.d.mts +1 -0
  81. package/src/runtime/domain/process-status.mjs +25 -0
  82. package/src/runtime/domain/session-store.d.mts +2 -0
  83. package/src/runtime/domain/session-store.mjs +489 -0
  84. package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
  85. package/src/runtime/domain/shared-harness-settings.mjs +126 -0
  86. package/src/runtime/domain/shared-log-utils.mjs +1223 -0
  87. package/src/runtime/domain/shared-stall-detector.mjs +37 -0
  88. package/src/runtime/domain/widget.d.mts +1 -0
  89. package/src/runtime/domain/widget.mjs +250 -0
  90. package/src/runtime/guardian.ts +189 -0
  91. package/src/runtime/health-config.ts +27 -0
  92. package/src/runtime/local-client.ts +34 -0
  93. package/src/runtime/mutation-store.ts +34 -0
  94. package/src/runtime/queries.ts +76 -0
  95. package/src/runtime/query-executor.ts +277 -0
  96. package/src/runtime/query-worker.mjs +119 -0
  97. package/src/runtime/read-model.ts +409 -0
  98. package/src/runtime/result-supervision.ts +63 -0
  99. package/src/runtime/root.ts +29 -0
  100. package/src/runtime/socket.ts +10 -0
  101. package/src/runtime/status-cli.ts +11 -0
  102. package/src/runtime/work-client.d.mts +14 -0
  103. package/src/runtime/work-client.mjs +102 -0
  104. package/src/server.ts +199 -14
  105. package/src/session-activity.ts +22 -2
  106. package/src/startup/activation.ts +32 -5
  107. package/src/startup/ensure.ts +13 -1
  108. package/src/startup/install.ts +2 -0
  109. package/src/version.ts +4 -0
@@ -0,0 +1,241 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readdir, stat } from "node:fs/promises";
3
+ import { watch, statSync, type FSWatcher } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { setImmediate as yieldTurn } from "node:timers/promises";
6
+ import type { WorkScope } from "./read-model.ts";
7
+ // @ts-expect-error Generated canonical cursor and scope functions.
8
+ import { rowCursorKey, pageRows, sessionScopeKey } from "./domain/shared-log-utils.mjs";
9
+ // @ts-expect-error Generated canonical passive registry inspection.
10
+ import { inspectMeta, tasksDir } from "./domain/background/registry.mjs";
11
+
12
+ const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
13
+ async function identity(path: string): Promise<string> {
14
+ try { const s = await stat(path, { bigint: true }); return `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`; }
15
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing"; throw error; }
16
+ }
17
+ function currentIdentity(path: string): string {
18
+ try { const s = statSync(path, { bigint: true }); return `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`; }
19
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing"; throw error; }
20
+ }
21
+
22
+ /** Explicit history builds share the root index; ordinary activity never opens the archive. */
23
+ export class BackgroundHistory {
24
+ private db: any;
25
+ private directory: string;
26
+ private source: () => any;
27
+ private project: (operations: any[]) => any[];
28
+ private changed: () => void;
29
+ private pending?: Promise<void>;
30
+ private completed = 0;
31
+ private version = "";
32
+ private closed = false;
33
+ private generation = 0;
34
+ private watchers = new Map<string, FSWatcher>();
35
+ private activated = false;
36
+ private scheduled = false;
37
+ private timer?: ReturnType<typeof setInterval>;
38
+ private changes = 0;
39
+ private observedVersion = "";
40
+ status: "ready" | "rebuilding" | "degraded" = "rebuilding";
41
+ reason?: string;
42
+ readonly metrics = { inventories: 0, metadataReads: 0, projections: 0 };
43
+
44
+ constructor(db: any, directory: string, source: () => any, project: (operations: any[]) => any[], changed: () => void) {
45
+ this.db = db; this.directory = directory; this.source = source; this.project = project; this.changed = changed;
46
+ db.exec(`CREATE TABLE background_history (key TEXT PRIMARY KEY, id TEXT, workspace TEXT, session TEXT,
47
+ known INTEGER, unreadable INTEGER, state TEXT, started REAL, payload TEXT, signature TEXT, failure TEXT, spawn_pid INTEGER, active INTEGER, context TEXT);
48
+ CREATE INDEX background_history_scope ON background_history(workspace, session, state, started DESC, id DESC);
49
+ CREATE INDEX background_history_process ON background_history(workspace, session, spawn_pid, state, started DESC, id DESC);
50
+ CREATE INDEX background_history_state ON background_history(state, started DESC, id DESC);
51
+ CREATE INDEX background_history_order ON background_history(started DESC, id DESC);
52
+ CREATE TABLE background_history_revisions (workspace TEXT, session TEXT, state TEXT, content INTEGER, failure INTEGER,
53
+ PRIMARY KEY (workspace, session, state));`);
54
+ }
55
+
56
+ private sourceVersion() {
57
+ const db = this.source();
58
+ const roots = [tasksDir(), join(this.directory, "observed")].map(path => {
59
+ try { const s = statSync(path, { bigint: true }); return `${s.dev}:${s.ino}:${s.mtimeNs}:${s.ctimeNs}`; }
60
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing"; throw error; }
61
+ });
62
+ return JSON.stringify([db ? db.prepare("PRAGMA data_version").get().data_version : "absent", roots]);
63
+ }
64
+
65
+ private observeSources() {
66
+ for (const path of [dirname(tasksDir()), this.directory]) {
67
+ if (this.watchers.has(path)) continue;
68
+ try {
69
+ const watcher = watch(path, { recursive: true }, (_event, file) => {
70
+ if (!file || /(?:meta|result|lost|launch|claim)\.json$|failures\.jsonl(?:\.observed)?$|^observed[/\\].*\.json$/.test(String(file))) this.invalidate();
71
+ });
72
+ watcher.on("error", () => { this.watchers.delete(path); watcher.close(); this.status = "degraded"; this.reason = "Background history watcher failed; reconciling source signatures"; this.invalidate(); });
73
+ this.watchers.set(path, watcher);
74
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
75
+ }
76
+ }
77
+
78
+ invalidate() {
79
+ this.completed = 0; this.generation++;
80
+ if (!this.activated || this.closed || this.scheduled) return;
81
+ this.scheduled = true;
82
+ setImmediate(() => { this.scheduled = false; if (!this.closed && !this.pending) this.startRefresh(); });
83
+ }
84
+
85
+ reconcile() {
86
+ if (!this.activated || this.closed) return;
87
+ const version = this.sourceVersion();
88
+ if (version !== this.observedVersion) { this.observedVersion = version; this.invalidate(); }
89
+ }
90
+
91
+ private startRefresh(version?: string) {
92
+ if (this.closed || this.pending) return;
93
+ const previous = this.status, changes = this.changes;
94
+ this.status = "rebuilding";
95
+ this.pending = Promise.resolve().then(() => this.refresh(version ?? this.sourceVersion())).catch(error => {
96
+ if (!this.closed) { this.status = "degraded"; this.reason = String(error); }
97
+ }).finally(() => {
98
+ this.pending = undefined;
99
+ if (this.closed) return;
100
+ if (changes !== this.changes || previous !== this.status) this.changed();
101
+ if (this.status === "rebuilding") this.invalidate();
102
+ });
103
+ }
104
+
105
+ read(scope: WorkScope) {
106
+ this.observeSources();
107
+ if (!this.activated) {
108
+ this.activated = true;
109
+ this.timer = setInterval(() => this.startRefresh(), 30000); this.timer.unref();
110
+ }
111
+ const version = this.sourceVersion();
112
+ this.observedVersion = version;
113
+ // Legacy writers have no entity notification yet; share one slower signature inventory.
114
+ if (!this.pending && (this.version !== version || Date.now() - this.completed >= 30000)) {
115
+ this.startRefresh(version);
116
+ }
117
+ const resource = `list:${sessionScopeKey({ all: scope.backgroundAll, origin: { cwd: scope.cwd, sessionId: scope.sessionId }, processId: scope.processId })}:${[...(scope.statuses ?? [])].sort().join(",")}`;
118
+ const clauses = ["unreadable = 0"], args: any[] = [];
119
+ if (!scope.backgroundAll) clauses.push("known = 1");
120
+ if (!scope.backgroundAll) { clauses.push("workspace = ? AND session = ?"); args.push(scope.cwd, scope.sessionId ?? ""); }
121
+ if (!scope.backgroundAll && !scope.sessionId) { clauses.push("spawn_pid = ?"); args.push(scope.processId ?? -1); }
122
+ if (scope.statuses?.length) { clauses.push(`(state IN (${scope.statuses.map(() => "?").join(",")})${scope.statuses.includes("running") ? " OR active = 1" : ""})`); args.push(...scope.statuses); }
123
+ if (scope.active !== undefined) { clauses.push("active = ?"); args.push(scope.active ? 1 : 0); }
124
+ const where = clauses.join(" AND ");
125
+ const aggregate = this.db.prepare(`SELECT count(*) AS n FROM background_history WHERE ${where}`).get(...args);
126
+ const anchor = rowCursorKey(scope.cursor, resource);
127
+ const after = anchor ? " AND (started < ? OR (started = ? AND id < ?))" : "";
128
+ const anchorArgs = anchor ? [anchor.time, anchor.time, anchor.id] : [];
129
+ const before = anchor ? Number(this.db.prepare(`SELECT count(*) AS n FROM background_history WHERE ${where} AND (started > ? OR (started = ? AND id >= ?))`).get(...args, ...anchorArgs).n) : 0;
130
+ const selected = this.db.prepare(`SELECT key, id, payload, context FROM background_history WHERE ${where}${after} ORDER BY started DESC, id DESC LIMIT ?`)
131
+ .all(...args, ...anchorArgs, (scope.limit ?? 10) + 1);
132
+ for (const row of selected) {
133
+ const path = row.key.startsWith("d:") ? join(this.directory, "observed", `${row.id}.json`) : join(tasksDir(), row.id, "meta.json");
134
+ if (row.context !== currentIdentity(path)) { this.invalidate(); this.status = "rebuilding"; }
135
+ }
136
+ const records = selected.map((row: any) => JSON.parse(row.payload));
137
+ const page = pageRows(records, { resource, cursor: scope.cursor, limit: scope.limit ?? 10, maxBytes: Number.MAX_SAFE_INTEGER,
138
+ indexed: { total: Number(aggregate.n), before }, keyOf: (meta: any) => ({ time: meta.startedAt, id: meta.id }), render: () => "" });
139
+ const revisionStates = scope.statuses?.length ? [...new Set([...scope.statuses, ...(scope.statuses.includes("running") ? ["starting"] : [])])] : ["*"];
140
+ const revisions = this.db.prepare(`SELECT sum(content) AS content, sum(failure) AS failure FROM background_history_revisions
141
+ WHERE workspace = ? AND session = ? AND state IN (${revisionStates.map(() => "?").join(",")})`)
142
+ .get(scope.backgroundAll ? "" : scope.cwd, scope.backgroundAll ? "" : scope.sessionId || `process:${scope.processId ?? -1}`, ...revisionStates);
143
+ const diagnostics = this.db.prepare("SELECT sum(unreadable) AS unreadable, sum(known = 0 AND unreadable = 0) AS unknown FROM background_history").get();
144
+ return { records: records.slice(0, scope.limit ?? 10).map((meta: any) => ({ id: meta.id, found: true, readable: true, meta })),
145
+ page: { total: Number(aggregate.n), before, nextCursor: page.nextCursor, resource,
146
+ contentRevision: digest([aggregate.n, revisions.content, diagnostics.unreadable, diagnostics.unknown]), failureRevision: digest(revisions.failure),
147
+ unreadable: Number(diagnostics.unreadable ?? 0), unknown: scope.backgroundAll ? 0 : Number(diagnostics.unknown ?? 0) } };
148
+ }
149
+
150
+ private async refresh(version: string) {
151
+ const generation = this.generation;
152
+ this.metrics.inventories++;
153
+ const seen = new Set<string>();
154
+ const upsert = this.db.prepare(`INSERT OR REPLACE INTO background_history VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
155
+ const previous = this.db.prepare("SELECT * FROM background_history WHERE key = ?");
156
+ const bump = (row: any, content: boolean, failure: boolean) => {
157
+ const session = row.session || `process:${row.spawn_pid ?? -1}`;
158
+ const keys = new Map([[JSON.stringify([row.workspace, session, row.state]), [row.workspace, session, row.state]],
159
+ [JSON.stringify([row.workspace, session, "*"]), [row.workspace, session, "*"]],
160
+ [JSON.stringify(["", "", row.state]), ["", "", row.state]], [JSON.stringify(["", "", "*"]), ["", "", "*"]]]);
161
+ for (const key of keys.values()) this.db.prepare(`INSERT INTO background_history_revisions VALUES (?, ?, ?, ?, ?)
162
+ ON CONFLICT(workspace, session, state) DO UPDATE SET content = content + excluded.content, failure = failure + excluded.failure`)
163
+ .run(...key, content ? 1 : 0, failure ? 1 : 0);
164
+ };
165
+ const updateFailure = (key: string, failure: string) => {
166
+ const old = previous.get(key);
167
+ if (old.failure !== failure) { this.changes++; bump(old, false, true); this.db.prepare("UPDATE background_history SET failure = ? WHERE key = ?").run(failure, key); }
168
+ };
169
+ const save = (key: string, meta: any, signature: string, failure: string, unreadable = false, context = signature) => {
170
+ seen.add(key);
171
+ const old = previous.get(key);
172
+ if (old?.signature === signature) { updateFailure(key, failure); return; }
173
+ const origin = meta?.callbackOrigin;
174
+ const known = origin && typeof origin.cwd === "string";
175
+ upsert.run(key, meta?.id ?? key, origin?.cwd ?? "", origin?.sessionId ?? "", known ? 1 : 0, unreadable ? 1 : 0,
176
+ meta?.status ?? "", meta?.startedAt ?? 0, JSON.stringify(meta ?? null), signature, failure, meta?.spawnPid ?? null,
177
+ meta?.durable ? Number(meta.active) : Number(meta?.status === "running"), context);
178
+ this.changes++;
179
+ if (old) bump(old, true, old.failure !== failure);
180
+ bump(previous.get(key), true, old?.failure !== failure);
181
+ };
182
+ const source = this.source();
183
+ let last = "";
184
+ if (source) for (;;) {
185
+ if (this.closed) return;
186
+ const operations = source.prepare(`SELECT * FROM operations WHERE owner_kind = 'parent-session' AND observer_kind = 'local-supervisor'
187
+ AND operation_id > ? ORDER BY operation_id LIMIT 128`).all(last);
188
+ if (!operations.length) break;
189
+ for (const op of operations) {
190
+ if (this.closed) return;
191
+ const key = `d:${op.operation_id}`;
192
+ const waits = source.prepare(`SELECT w.* FROM waits w JOIN wait_dependencies d ON w.wait_id = d.wait_id AND w.generation = d.generation
193
+ WHERE d.operation_id = ? ORDER BY w.wait_id, w.generation`).all(op.operation_id);
194
+ const context = await identity(join(this.directory, "observed", `${op.task_id}.json`));
195
+ const signature = digest([op, waits, context,
196
+ await identity(join(this.directory, "tasks", op.task_id, "result.json")), await identity(join(this.directory, "tasks", op.task_id, "lost.json")),
197
+ // Active runner/wait facts come from the current shared projection.
198
+ op.phase === "running" ? this.project([op]) : null]);
199
+ let meta;
200
+ if (previous.get(key)?.signature !== signature) {
201
+ this.metrics.projections++;
202
+ meta = this.project([op])[0];
203
+ if (meta?.dismissedAt !== undefined) continue;
204
+ meta = { ...meta, callbackOrigin: { cwd: op.owner_workspace, sessionId: op.owner_session_id }, logPath: meta.logPaths?.stdout ?? "" };
205
+ }
206
+ if (meta) save(key, meta, signature, "", false, context);
207
+ else if (previous.get(key)?.signature === signature) seen.add(key);
208
+ }
209
+ last = operations.at(-1).operation_id;
210
+ await yieldTurn();
211
+ }
212
+ let ids: string[] = [];
213
+ try { ids = await readdir(tasksDir()); }
214
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
215
+ let batch = 0;
216
+ for (const id of ids) {
217
+ if (this.closed) return;
218
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) continue;
219
+ const key = `l:${id}`, path = join(tasksDir(), id);
220
+ const signature = await identity(join(path, "meta.json"));
221
+ const failure = digest([await identity(join(path, "failures.jsonl")), await identity(join(path, "failures.jsonl.observed"))]);
222
+ if (previous.get(key)?.signature === signature) { seen.add(key); updateFailure(key, failure); }
223
+ else {
224
+ this.metrics.metadataReads++;
225
+ const record = inspectMeta(id);
226
+ if (record.found) save(key, record.meta, signature, failure, !record.meta);
227
+ }
228
+ if (++batch % 128 === 0) await yieldTurn();
229
+ }
230
+ if (this.closed) return;
231
+ for (const row of this.db.prepare("SELECT key FROM background_history").all()) {
232
+ if (!seen.has(row.key)) { this.changes++; bump(previous.get(row.key), true, true); this.db.prepare("DELETE FROM background_history WHERE key = ?").run(row.key); }
233
+ }
234
+ this.version = version;
235
+ this.completed = generation === this.generation ? Date.now() : 0;
236
+ this.status = generation === this.generation && version === this.sourceVersion() ? "ready" : "rebuilding";
237
+ this.reason = undefined;
238
+ }
239
+
240
+ async close() { this.closed = true; if (this.timer) clearInterval(this.timer); for (const watcher of this.watchers.values()) watcher.close(); this.watchers.clear(); await this.pending; }
241
+ }
@@ -0,0 +1,182 @@
1
+ import { processMatchesStart } from "../daemon-owner.ts";
2
+ import { createRequire } from "node:module";
3
+ import { readFileSync, statSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ // @ts-expect-error Generated canonical passive runner observation.
7
+ import { snapshot } from "./domain/background/snapshot.mjs";
8
+ // @ts-expect-error Generated canonical registry queries.
9
+ import { observeMetasForOrigin, belongsToOrigin, readMeta } from "./domain/background/registry.mjs";
10
+ import { BackgroundHistory } from "./background-history.ts";
11
+ import type { WorkScope } from "./read-model.ts";
12
+
13
+ /** Root-owned query connection; never opens a supervisor or mutates source facts. */
14
+ export class BackgroundObservation {
15
+ private db: any;
16
+ private identity?: string;
17
+ private knownCoordinator = false;
18
+ private rows: any[] = [];
19
+ private signature = "";
20
+ private root: string;
21
+ private directory: string;
22
+ private enabled = false;
23
+ private history?: BackgroundHistory;
24
+ private legacy = new Map<string, { origin: { cwd: string; sessionId?: string }; rows: any[]; references: number }>();
25
+ status: "ready" | "degraded" = "ready";
26
+ reason?: string;
27
+ get connectionCount() { return this.db ? 1 : 0; }
28
+ get scopeCount() { return this.legacy.size; }
29
+ livenessReasons(options: { refresh?: boolean } = {}) {
30
+ if (options.refresh !== false) {
31
+ this.enabled = true;
32
+ this.refresh();
33
+ }
34
+ if (!this.db) return [];
35
+ const version = this.db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value;
36
+ if (!["1", "2", "3", "4"].includes(version)) return [];
37
+ let operations: any[] = [];
38
+ try { operations = this.db ? this.db.prepare("SELECT * FROM operations WHERE phase = 'running' AND observer_kind = 'local-supervisor' AND terminal_revision = 0").all() : []; }
39
+ catch (error) { this.status = "degraded"; this.reason = String(error); return []; }
40
+ return operations.flatMap((op: any) => {
41
+ try {
42
+ const inspection = snapshot(this.directoryFor(op), op.task_id);
43
+ const claim = inspection?.claim;
44
+ return claim && !inspection.terminal && inspection.token === op.launch_token && processMatchesStart(claim.pid, claim.pidStartTime)
45
+ ? [{ kind: "runner", id: op.task_id, owner: { kind: op.owner_kind, sessionId: op.owner_session_id, workspace: op.owner_workspace }, operationId: op.operation_id,
46
+ lastProgressAt: inspection.command?.startedAt ?? claim.claimedAt,
47
+ nextDeadline: inspection.launch.timeoutSeconds ? inspection.launch.createdAt + inspection.launch.timeoutSeconds * 1000 : null,
48
+ recovery: "observe-existing-runner" }] : [];
49
+ } catch (error) { this.status = "degraded"; this.reason = String(error); return []; }
50
+ });
51
+ }
52
+ readonly metrics = { runnerSnapshots: 0, activeQueries: 0, historyQueries: 0 };
53
+ private directoryFor(op: any): string {
54
+ if (!op.supervision_host_id?.startsWith("server:")) return this.directory;
55
+ const row = this.db.prepare("SELECT value FROM coordinator_state WHERE key = ?").get(`result-supervision-v1:${op.operation_id}`);
56
+ if (!row) throw new Error("Captured result-supervision directory unavailable");
57
+ const grant = JSON.parse(row.value);
58
+ if (grant.launchToken !== op.launch_token || typeof grant.directory !== "string") throw new Error("Captured runner execution identity differs");
59
+ return grant.directory;
60
+ }
61
+ constructor(root: string, directory = join(tmpdir(), process.env.VITEST_POOL_ID ? `pi-better-background-tasks-vitest-${process.env.VITEST_POOL_ID}` : "pi-better-background-tasks", "supervisor"), indexDb?: any, changed = () => {}) {
62
+ this.root = root; this.directory = directory;
63
+ if (indexDb) this.history = new BackgroundHistory(indexDb, directory, () => {
64
+ if (this.status === "degraded") throw new Error(this.reason);
65
+ return this.db;
66
+ }, operations => this.project(operations), changed);
67
+ }
68
+ refresh(): boolean {
69
+ if (!this.enabled) return false;
70
+ try {
71
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
72
+ const path = join(this.root, "operation-coordinator.sqlite");
73
+ let identity;
74
+ try { const info = statSync(path, { bigint: true }); identity = `${info.dev}:${info.ino}`; }
75
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
76
+ if (identity !== this.identity) { this.history?.invalidate(); this.db?.close(); this.db = undefined; this.identity = identity; }
77
+ if (!identity && this.knownCoordinator) throw new Error("Coordinator source disappeared; retaining the previous observation");
78
+ if (identity) {
79
+ this.db ??= new DatabaseSync(path, { readOnly: true });
80
+ this.knownCoordinator = true;
81
+ const version = this.db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value;
82
+ if (!["1", "2", "3", "4"].includes(version)) throw new Error("Unsupported coordinator schema");
83
+ }
84
+ this.metrics.activeQueries++;
85
+ const operations = this.db ? this.db.prepare("SELECT * FROM operations WHERE phase = 'running' AND observer_kind = 'local-supervisor'").all() : [];
86
+ // Revisit only known recent terminal identities, never enumerate completed history.
87
+ for (const row of this.rows) {
88
+ if (operations.some((op: any) => op.operation_id === row.operationId)) continue;
89
+ if (row.endedAt && Date.now() - row.endedAt >= 30000) continue;
90
+ const operation = this.db.prepare("SELECT * FROM operations WHERE operation_id = ?").get(row.operationId);
91
+ if (operation) operations.push(operation);
92
+ }
93
+ const rows = this.project(operations);
94
+ for (const entry of this.legacy.values()) {
95
+ const active = observeMetasForOrigin(entry.origin);
96
+ const retained = entry.rows.map(row => readMeta(row.id)).filter((row: any) => row && row.dismissedAt === undefined
97
+ && row.status !== "running" && (!row.endedAt || Date.now() - row.endedAt < 30000));
98
+ entry.rows = [...active, ...retained];
99
+ }
100
+ const signature = JSON.stringify([rows, [...this.legacy.values()].flatMap(entry => entry.rows).sort((a, b) => a.id.localeCompare(b.id))]);
101
+ const changed = signature !== this.signature || this.status !== "ready";
102
+ if (changed) this.history?.invalidate();
103
+ this.rows = rows; this.signature = signature; this.status = "ready"; this.reason = undefined;
104
+ this.history?.reconcile();
105
+ return changed;
106
+ } catch (error) {
107
+ const reason = String(error);
108
+ const changed = this.status !== "degraded" || this.reason !== reason;
109
+ this.status = "degraded"; this.reason = reason;
110
+ return changed;
111
+ }
112
+ }
113
+ private project(operations: any[]) {
114
+ return operations.map((op: any) => {
115
+ this.metrics.runnerSnapshots++;
116
+ const directory = this.directoryFor(op);
117
+ const inspection = snapshot(directory, op.task_id);
118
+ let context: any = {};
119
+ try { context = JSON.parse(readFileSync(join(directory, "observed", `${op.task_id}.json`), "utf8")); }
120
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
121
+ const terminal = inspection?.terminal === true || op.terminal_revision > 0;
122
+ const status = inspection?.terminal ? inspection.status : op.terminal_revision > 0 ? op.terminal_outcome : inspection?.status ?? "running";
123
+ const waits = this.db.prepare(`SELECT w.wait_id, w.generation, w.phase FROM waits w JOIN wait_dependencies d
124
+ ON w.wait_id = d.wait_id AND w.generation = d.generation WHERE d.operation_id = ?
125
+ AND w.owner_kind = ? AND w.owner_session_id = ? AND w.owner_workspace = ?
126
+ AND w.phase NOT IN ('consumed', 'cancelled') AND w.dispatch_disarmed = 0`).all(op.operation_id, op.owner_kind, op.owner_session_id, op.owner_workspace)
127
+ .map((w: any) => ({ waitId: w.wait_id, generation: w.generation, phase: w.phase }));
128
+ return { durable: true, id: op.task_id, operationId: op.operation_id, kind: context.kind ?? inspection?.kind ?? "process",
129
+ status, active: !terminal, terminal, attention: terminal && status !== "succeeded", waits,
130
+ owner: { kind: op.owner_kind, sessionId: op.owner_session_id, workspace: op.owner_workspace },
131
+ startedAt: inspection?.result?.startedAt ?? inspection?.launch.createdAt ?? op.created_at,
132
+ endedAt: inspection?.result?.endedAt ?? op.terminal_at ?? undefined,
133
+ cwd: inspection?.launch.cwd ?? op.owner_workspace, name: context.name, command: context.command, argv: context.argv,
134
+ dismissedAt: context.dismissedAt, exitCode: inspection?.result?.exitCode ?? null, logPaths: inspection?.logs ?? {} };
135
+ }).filter(Boolean);
136
+ }
137
+ private legacyScope(scope: { cwd?: string; sessionId?: string }) {
138
+ if (!scope.cwd) throw new Error("Background activity requires an exact workspace");
139
+ const key = JSON.stringify([scope.cwd, scope.sessionId]);
140
+ let entry = this.legacy.get(key);
141
+ if (!entry) {
142
+ if (this.legacy.size >= 128) {
143
+ const oldest = [...this.legacy].find(([, value]) => value.references === 0);
144
+ if (!oldest) throw new Error("runtime-overloaded: Background scope capacity reached; retry later");
145
+ this.legacy.delete(oldest[0]);
146
+ }
147
+ const origin = { cwd: scope.cwd, sessionId: scope.sessionId };
148
+ entry = { origin, rows: observeMetasForOrigin(origin), references: 0 };
149
+ }
150
+ this.legacy.delete(key); this.legacy.set(key, entry);
151
+ return entry;
152
+ }
153
+ retain(scope: { cwd?: string; sessionId?: string }) {
154
+ const entry = this.legacyScope(scope);
155
+ entry.references++;
156
+ let released = false;
157
+ return () => { if (!released) { released = true; entry.references--; } };
158
+ }
159
+ read(scope: WorkScope, index?: any): any[] {
160
+ if (!this.enabled) { this.enabled = true; this.refresh(); }
161
+ const legacy = this.legacyScope(scope);
162
+ if (scope.backgroundHistory) { this.metrics.historyQueries++; return index.records.map((record: any) => record.meta); }
163
+ const legacyRows = legacy.rows;
164
+ const rows = this.rows;
165
+ return [...rows.filter(row => row.owner.kind === "parent-session" && row.dismissedAt === undefined
166
+ && (scope.backgroundAll || row.owner.workspace === scope.cwd && row.owner.sessionId === scope.sessionId) && (!scope.active || row.active)),
167
+ ...legacyRows.filter((row: any) => (scope.backgroundAll || row.callbackOrigin && belongsToOrigin(row, legacy.origin)
168
+ && (scope.sessionId || row.spawnPid === scope.processId)) && (!scope.active || row.status === "running"))];
169
+ }
170
+ close(): Promise<void> {
171
+ if (this.history) return this.history.close().then(() => { this.db?.close(); });
172
+ this.db?.close(); return Promise.resolve();
173
+ }
174
+ get historyStatus() { return this.history?.status ?? "degraded"; }
175
+ get historyReason() { return this.history?.reason; }
176
+ get historyMetrics() { return this.history?.metrics; }
177
+ historyIndex(scope: WorkScope) {
178
+ this.read({ ...scope, backgroundHistory: false });
179
+ if (!this.history) throw new Error("Background history requires the shared root index");
180
+ return this.history.read(scope);
181
+ }
182
+ }
@@ -0,0 +1,99 @@
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; only stop is invoked here.
6
+ import { createLocalSupervisor } from "./domain/background/supervisor/supervisor.mjs";
7
+ // @ts-expect-error Generated canonical durable stop records.
8
+ import { readStopRequest, writeStopRequest } from "./domain/background/supervisor/store.mjs";
9
+ // @ts-expect-error Generated canonical host publication contract.
10
+ import { supervisorTerminalPublication } from "./domain/background/terminal-publication.mjs";
11
+
12
+ export type CancellationStage = "accepted" | "before-stop-file" | "after-stop-file" | "after-process-action";
13
+
14
+ /** Startup reads only durable intents, without activating mutation ownership for query clients. */
15
+ export function hasPendingCancellation(root: string): boolean {
16
+ const path = join(root, "operation-coordinator.sqlite");
17
+ if (!existsSync(path)) return false;
18
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
19
+ const db = new DatabaseSync(path, { readOnly: true });
20
+ try {
21
+ const columns = db.prepare("PRAGMA table_info(task_cancellation_requests)").all();
22
+ if (!columns.some((column: any) => column.name === "result_json")) return false;
23
+ return !!db.prepare("SELECT 1 FROM task_cancellation_requests WHERE result_json IS NULL LIMIT 1").get();
24
+ } finally { db.close(); }
25
+ }
26
+
27
+ /** Cancellation only: no arbitrary method, module, launch or wait dispatch. */
28
+ export class RuntimeCancellation {
29
+ private store: any;
30
+ private releaseStore: () => void;
31
+ private pending = new Map<string, Promise<unknown>>();
32
+ readonly epoch: number;
33
+ private fault?: (stage: CancellationStage) => void;
34
+ get busy() { return this.pending.size > 0; }
35
+ constructor(root: string, instanceId: string, fault?: (stage: CancellationStage) => void) {
36
+ this.fault = fault;
37
+ const lease = acquireMutationStore(root);
38
+ this.store = lease.store;
39
+ this.releaseStore = lease.release;
40
+ try {
41
+ this.epoch = this.store.cancellationRuntimeEpoch(instanceId);
42
+ for (const admission of this.store.pendingTaskCancellations()) void this.execute(admission);
43
+ } catch (error) { this.releaseStore(); throw error; }
44
+ }
45
+ async handle(command: Record<string, unknown>) {
46
+ if (Object.keys(command).some(key => !["id", "type", "credential"].includes(key))) throw new Error("not_accepted: unsupported cancellation field");
47
+ if (command.type === "runtime_cancellation_status") return { runtimeEpoch: this.epoch };
48
+ if (typeof command.credential !== "string") throw new Error("not_accepted: permission-unavailable: cancellation credential required");
49
+ let admission;
50
+ try { admission = this.store.authorizedTaskCancellation(command.credential); }
51
+ catch (error) { throw new Error(`not_accepted: ${String(error)}`); }
52
+ const previous = this.store.getTaskCancellation(admission.request);
53
+ if (command.type === "runtime_query_cancellation") return previous?.result?.status === "outcome_unknown" ? { ...previous, state: "outcome_unknown" } : previous ?? { state: "not_accepted" };
54
+ if (command.type !== "runtime_cancel_task") throw new Error("not_accepted: unsupported cancellation operation");
55
+ if (previous?.result) return previous.result.status === "outcome_unknown" ? { ...previous, state: "outcome_unknown" } : previous;
56
+ try { this.store.acceptAuthorizedTaskCancellation({ credential: command.credential, runtimeEpoch: this.epoch }); }
57
+ catch (error) { throw new Error(`not_accepted: ${String(error)}`); }
58
+ this.fault?.("accepted");
59
+ return this.execute(admission);
60
+ }
61
+ private execute(admission: any): Promise<any> {
62
+ const key = JSON.stringify([admission.request.owner, admission.request.idempotencyKey]);
63
+ const running = this.pending.get(key);
64
+ if (running) return running;
65
+ const intent = this.store.getTaskCancellation(admission.request);
66
+ const execution = Promise.resolve().then(async () => {
67
+ try {
68
+ const supervisor = createLocalSupervisor({ directory: admission.directory });
69
+ const stop = readStopRequest(admission.directory, intent.taskId);
70
+ if (stop && stop.token !== intent.expectedLaunchToken) throw new Error("Exact stop token mismatch; refusing recovery");
71
+ let result;
72
+ if (stop) {
73
+ // A durable stop may already have caused a signal before the crash.
74
+ // Observe that exact execution; never repeat an ambiguous process action.
75
+ result = supervisor.inspect(intent.taskId);
76
+ if (result?.token !== intent.expectedLaunchToken) throw new Error("Exact launch token mismatch; refusing recovery");
77
+ } else {
78
+ const inspection = supervisor.snapshot(intent.taskId);
79
+ if (inspection?.token !== intent.expectedLaunchToken) throw new Error("Exact launch token mismatch; refusing action");
80
+ this.fault?.("before-stop-file");
81
+ writeStopRequest(admission.directory, { version: 1, taskId: intent.taskId, token: intent.expectedLaunchToken, requestedAt: Date.now(), reason: intent.reason });
82
+ this.fault?.("after-stop-file");
83
+ result = await supervisor.stop(intent.taskId, { token: intent.expectedLaunchToken, reason: intent.reason });
84
+ this.fault?.("after-process-action");
85
+ }
86
+ if (!result) throw new Error("Exact launch record unavailable; no replacement execution is permitted");
87
+ const inspection = result.inspection ?? result;
88
+ const operation = this.store.getOperation(intent.operationId);
89
+ return this.store.finishTaskCancellationIntent({ request: admission.request, status: result.status, terminal: result.terminal,
90
+ ...(result.terminal ? { publication: supervisorTerminalPublication(operation, inspection) } : {}) });
91
+ } catch {
92
+ return { ...this.store.unknownTaskCancellation(admission.request), state: "outcome_unknown" };
93
+ } finally { this.pending.delete(key); }
94
+ });
95
+ this.pending.set(key, execution);
96
+ return execution;
97
+ }
98
+ async close() { await Promise.all(this.pending.values()); this.releaseStore(); }
99
+ }
@@ -0,0 +1,50 @@
1
+ import { createHash, timingSafeEqual } from "node:crypto";
2
+ import { lstatSync, readFileSync, realpathSync, rmSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { processMatchesStart } from "../daemon-owner.ts";
5
+
6
+ /** Private fixed-host registrations, not client-supplied trust decisions. */
7
+ export class CatalogAdmission {
8
+ private live = new Map<string, object>();
9
+ private revoked = new Set<string>();
10
+ private root: string;
11
+ private instanceId: string;
12
+ constructor(agentDir: string, instanceId: string) { this.root = join(realpathSync(agentDir), "catalog-host-admission"); this.instanceId = instanceId; }
13
+ read(authority: any) {
14
+ if (!authority || typeof authority.id !== "string" || !/^[a-f0-9-]{36}$/.test(authority.id)
15
+ || typeof authority.secret !== "string" || !/^[a-f0-9]{64}$/.test(authority.secret)) throw new Error("catalog-authority-refused");
16
+ const root = lstatSync(this.root), path = join(this.root, `${authority.id}.json`), file = lstatSync(path);
17
+ if (!root.isDirectory() || root.isSymbolicLink() || (root.mode & 0o077) !== 0 || root.uid !== process.getuid?.()
18
+ || !file.isFile() || file.isSymbolicLink() || (file.mode & 0o077) !== 0 || file.uid !== root.uid || file.size > 8192) throw new Error("catalog-authority-refused");
19
+ const record = JSON.parse(readFileSync(path, "utf8"));
20
+ const digest = createHash("sha256").update(authority.secret).digest("hex");
21
+ if (record.version !== 1 || record.serverInstance !== this.instanceId || record.id !== authority.id || record.generation !== authority.generation
22
+ || typeof record.secretHash !== "string" || record.secretHash.length !== digest.length
23
+ || !timingSafeEqual(Buffer.from(record.secretHash), Buffer.from(digest))
24
+ || record.cwd !== authority.cwd || record.cwd !== realpathSync(record.cwd)
25
+ || record.sessionId !== authority.sessionId || record.branchId !== authority.branchId
26
+ || typeof record.projectTrusted !== "boolean" || !Number.isSafeInteger(record.pid) || record.pid <= 0
27
+ || typeof record.sessionId !== "string" || !record.sessionId || typeof record.branchId !== "string" || !record.branchId
28
+ || typeof record.overlayDigest !== "string" || !/^[a-f0-9]{64}$/.test(record.overlayDigest)) throw new Error("catalog-authority-refused");
29
+ if (!processMatchesStart(record.pid, record.pidStartTime)) throw new Error("catalog-host-identity-refused");
30
+ return record;
31
+ }
32
+ bind(authority: unknown, socket: object) {
33
+ const record = this.read(authority);
34
+ if (this.revoked.has(record.id)) throw new Error("catalog-host-revoked");
35
+ if (this.live.has(record.id) && this.live.get(record.id) !== socket) throw new Error("catalog-host-already-bound");
36
+ this.live.set(record.id, socket);
37
+ }
38
+ verify(authority: unknown) {
39
+ const record = this.read(authority);
40
+ if (!this.live.has(record.id)) throw new Error("catalog-host-revoked");
41
+ return record;
42
+ }
43
+ close(socket: object) {
44
+ for (const [id, owner] of this.live) if (owner === socket) {
45
+ this.live.delete(id);
46
+ try { rmSync(join(this.root, `${id}.json`), { force: true }); }
47
+ catch { this.revoked.add(id); }
48
+ }
49
+ }
50
+ }