pi-goal-delegate 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +89 -0
- package/README.md +391 -296
- package/package.json +2 -2
- package/skills/delegate/SKILL.md +128 -44
- package/src/command.ts +88 -27
- package/src/contract.ts +9 -0
- package/src/doctor.ts +385 -0
- package/src/index.ts +426 -303
- package/src/registry.ts +31 -8
- package/src/result-schema.ts +23 -12
- package/src/retention.ts +87 -26
- package/src/run.ts +20 -11
- package/src/spawn.ts +1 -1
- package/src/verify.ts +13 -0
package/src/doctor.ts
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* doctor.ts - the installation and health self-check.
|
|
3
|
+
*
|
|
4
|
+
* Three failures motivated this module, and all three were silent:
|
|
5
|
+
*
|
|
6
|
+
* 1. The extension was installed through a symlink whose target moved. Pi
|
|
7
|
+
* dropped the extension, no tool existed, and nothing said so for six days.
|
|
8
|
+
* 2. The run-record root became unwritable. A start would fail, but only when
|
|
9
|
+
* somebody tried one, and the message was about a path rather than a cause.
|
|
10
|
+
* 3. Records were removed by retention, which is observable only after the fact:
|
|
11
|
+
* a run was "gone" and nobody knew whether it had ever existed.
|
|
12
|
+
*
|
|
13
|
+
* Every check answers one question with `ok`, `warn` or `fail`. A `fail` is an
|
|
14
|
+
* installation that will not work; a `warn` is a working installation with
|
|
15
|
+
* something to know. The same checks run at `session_start` for the one failure
|
|
16
|
+
* that has to be announced before it costs anything.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { randomUUID } from "node:crypto";
|
|
20
|
+
import { closeSync, existsSync, lstatSync, openSync, readFileSync, readdirSync, realpathSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
21
|
+
import { dirname, join, resolve } from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
import { formatDuration, isTerminal, MAX_MAX_LIVE, MAX_TIMEOUT_MINUTES, SPEC_ENV } from "./contract.ts";
|
|
24
|
+
import { observability, supportsFence } from "./identity.ts";
|
|
25
|
+
import { maxCostUsd, maxLive, type RunRegistry } from "./registry.ts";
|
|
26
|
+
import { scanRetention } from "./retention.ts";
|
|
27
|
+
import { delegateRoot, piCommand } from "./spawn.ts";
|
|
28
|
+
import { gitAvailable } from "./worktree.ts";
|
|
29
|
+
|
|
30
|
+
export type CheckLevel = "ok" | "warn" | "fail";
|
|
31
|
+
|
|
32
|
+
export interface DoctorCheck {
|
|
33
|
+
/** Stable short name, padded into the report. */
|
|
34
|
+
name: string;
|
|
35
|
+
level: CheckLevel;
|
|
36
|
+
/** What was measured, on one line. */
|
|
37
|
+
detail: string;
|
|
38
|
+
/** What to do about a warn or a fail. */
|
|
39
|
+
hint?: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface DoctorReport {
|
|
43
|
+
checks: DoctorCheck[];
|
|
44
|
+
/** No check failed. A warning is a working installation. */
|
|
45
|
+
ok: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface DoctorInput {
|
|
49
|
+
/** The session registry, when this runs inside a session. */
|
|
50
|
+
registry?: RunRegistry;
|
|
51
|
+
sessionId?: string;
|
|
52
|
+
cwd?: string;
|
|
53
|
+
/** This process is a delegated child rather than a session. */
|
|
54
|
+
isChild?: boolean;
|
|
55
|
+
/** The run root to check. Defaults to the environment's delegate root. */
|
|
56
|
+
root?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Where this module lives, and therefore where the package it belongs to lives. */
|
|
60
|
+
function packageRoot(): string {
|
|
61
|
+
return resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Whether a directory accepts the same create, write and unlink a start needs.
|
|
66
|
+
*
|
|
67
|
+
* The name is unique and opened exclusively: a health check must never truncate
|
|
68
|
+
* or remove an existing file, including a probe left by another process.
|
|
69
|
+
*/
|
|
70
|
+
function probeWritable(root: string): { ok: boolean; detail: string } {
|
|
71
|
+
try {
|
|
72
|
+
// Follow a symlink to a directory: the start path follows it too.
|
|
73
|
+
const stats = statSync(root);
|
|
74
|
+
if (!stats.isDirectory()) return { ok: false, detail: root + " is not a directory" };
|
|
75
|
+
} catch (error) {
|
|
76
|
+
return { ok: false, detail: "cannot inspect " + root + ": " + (error as Error).message };
|
|
77
|
+
}
|
|
78
|
+
const probe = join(root, ".doctor-probe-" + process.pid + "-" + randomUUID());
|
|
79
|
+
let fd: number | undefined;
|
|
80
|
+
let created = false;
|
|
81
|
+
let problem: string | undefined;
|
|
82
|
+
try {
|
|
83
|
+
fd = openSync(probe, "wx", 0o600);
|
|
84
|
+
created = true;
|
|
85
|
+
writeFileSync(fd, "probe");
|
|
86
|
+
} catch (error) {
|
|
87
|
+
problem = "cannot create and write a record: " + (error as Error).message;
|
|
88
|
+
}
|
|
89
|
+
if (fd !== undefined) {
|
|
90
|
+
try {
|
|
91
|
+
closeSync(fd);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
problem ??= "cannot close the probe: " + (error as Error).message;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (created) {
|
|
97
|
+
try {
|
|
98
|
+
unlinkSync(probe);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
problem ??= "cannot remove the probe: " + (error as Error).message;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (problem) return { ok: false, detail: problem };
|
|
104
|
+
return { ok: true, detail: "probed with an exclusive create and an unlink" };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Probe the nearest existing path entry when the run root itself is missing. */
|
|
108
|
+
function probeCreatable(root: string): { ok: boolean; detail: string } {
|
|
109
|
+
let candidate = resolve(root);
|
|
110
|
+
while (true) {
|
|
111
|
+
try {
|
|
112
|
+
// lstat detects a broken symlink as an existing but unusable path entry.
|
|
113
|
+
lstatSync(candidate);
|
|
114
|
+
return probeWritable(candidate);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
117
|
+
if (code !== "ENOENT") {
|
|
118
|
+
return { ok: false, detail: "cannot inspect " + candidate + ": " + (error as Error).message };
|
|
119
|
+
}
|
|
120
|
+
const parent = dirname(candidate);
|
|
121
|
+
if (parent === candidate) return { ok: false, detail: "no existing ancestor of " + root + " can be inspected" };
|
|
122
|
+
candidate = parent;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function probeRunRoot(root: string): { ok: boolean; detail: string } {
|
|
128
|
+
return existsSync(root) ? probeWritable(root) : probeCreatable(root);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The package manifest, and whether the entries it declares still resolve. */
|
|
132
|
+
function checkManifest(): DoctorCheck {
|
|
133
|
+
const root = packageRoot();
|
|
134
|
+
const path = join(root, "package.json");
|
|
135
|
+
let manifest: {
|
|
136
|
+
name?: unknown;
|
|
137
|
+
version?: unknown;
|
|
138
|
+
pi?: { extensions?: unknown; skills?: unknown };
|
|
139
|
+
};
|
|
140
|
+
try {
|
|
141
|
+
manifest = JSON.parse(readFileSync(path, "utf8"));
|
|
142
|
+
} catch (error) {
|
|
143
|
+
return { name: "manifest", level: "fail", detail: "package.json is unreadable: " + (error as Error).message };
|
|
144
|
+
}
|
|
145
|
+
const name = typeof manifest.name === "string" ? manifest.name : "(unnamed)";
|
|
146
|
+
const version = typeof manifest.version === "string" ? manifest.version : "(no version)";
|
|
147
|
+
const extensions = Array.isArray(manifest.pi?.extensions) ? manifest.pi.extensions : [];
|
|
148
|
+
const skills = Array.isArray(manifest.pi?.skills) ? manifest.pi.skills : [];
|
|
149
|
+
const missing = [...extensions, ...skills]
|
|
150
|
+
.filter((entry): entry is string => typeof entry === "string")
|
|
151
|
+
.map((entry) => resolve(root, entry))
|
|
152
|
+
.filter((entry) => !existsSync(entry));
|
|
153
|
+
if (missing.length > 0) {
|
|
154
|
+
return {
|
|
155
|
+
name: "manifest",
|
|
156
|
+
level: "fail",
|
|
157
|
+
detail: name + " " + version + " declares " + missing.map((entry) => resolve(root, entry)).join(", ") + " which do not exist",
|
|
158
|
+
hint: "reinstall the package; this is the shape of a symlinked checkout whose target moved",
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
return { name: "manifest", level: "ok", detail: name + " " + version + " · " + extensions.length + " extension, " + skills.length + " skill path" };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The command that starts a child, and the file it runs. */
|
|
165
|
+
function checkLauncher(): DoctorCheck {
|
|
166
|
+
const { command, prefix } = piCommand();
|
|
167
|
+
const entry = prefix[0];
|
|
168
|
+
// A bare name is resolved through PATH by the spawn, so nothing here can
|
|
169
|
+
// answer for it; a path is a file, and a file that is not there is the bug.
|
|
170
|
+
const isPath = command.includes("/") || command.includes("\\");
|
|
171
|
+
if (isPath && !existsSync(command)) {
|
|
172
|
+
return {
|
|
173
|
+
name: "launcher",
|
|
174
|
+
level: "fail",
|
|
175
|
+
detail: "the child launcher does not exist: " + command,
|
|
176
|
+
hint: "set PI_DELEGATE_PI_COMMAND (or PI_DELEGATE_PI_ENTRY) to the command that starts Pi",
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
if (entry && !existsSync(entry)) {
|
|
180
|
+
return {
|
|
181
|
+
name: "launcher",
|
|
182
|
+
level: "fail",
|
|
183
|
+
detail: "the Pi entry point does not exist: " + entry,
|
|
184
|
+
hint: "set PI_DELEGATE_PI_ENTRY to the JavaScript entry of this Pi install",
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
name: "launcher",
|
|
189
|
+
level: "ok",
|
|
190
|
+
detail: command + (entry ? " " + entry : "") + " · child runs in --mode json",
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function checkRunRoot(root: string): DoctorCheck {
|
|
195
|
+
const exists = existsSync(root);
|
|
196
|
+
const writable = probeRunRoot(root);
|
|
197
|
+
if (!writable.ok) {
|
|
198
|
+
return {
|
|
199
|
+
name: "run root",
|
|
200
|
+
level: "fail",
|
|
201
|
+
detail: root + " is not writable: " + writable.detail,
|
|
202
|
+
hint: "PI_DELEGATE_HOME selects another root",
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
if (!exists) {
|
|
206
|
+
return {
|
|
207
|
+
name: "run root",
|
|
208
|
+
level: "warn",
|
|
209
|
+
detail: root + " does not exist yet · no delegation has run",
|
|
210
|
+
hint: "it is created with the first delegate_start",
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
const scan = scanRetention({ root });
|
|
214
|
+
const size = formatBytes(scan.bytes);
|
|
215
|
+
return { name: "run root", level: "ok", detail: root + " · " + scan.total + " records · " + size };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function checkRetention(root: string, registry: RunRegistry | undefined): DoctorCheck {
|
|
219
|
+
const scan = scanRetention({ root, isLive: (runId) => Boolean(registry?.get(runId) && !registry.get(runId)?.outcome) });
|
|
220
|
+
if (scan.total === 0) return { name: "retention", level: "ok", detail: "no records to reclaim" };
|
|
221
|
+
if (scan.removable.length === 0) {
|
|
222
|
+
const policy = scan.policy;
|
|
223
|
+
const bytes = policy.maxBytes > 0 ? formatBytes(policy.maxBytes) : "no byte cap";
|
|
224
|
+
const age = policy.maxAgeDays > 0 ? policy.maxAgeDays + " days" : "no age rule";
|
|
225
|
+
return {
|
|
226
|
+
name: "retention",
|
|
227
|
+
level: "ok",
|
|
228
|
+
detail: scan.total + " records, " + formatBytes(scan.bytes) + " · keep " + policy.keepRuns + " / " + age + " / " + bytes + " · nothing to remove",
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
name: "retention",
|
|
233
|
+
level: "warn",
|
|
234
|
+
detail: scan.removable.length + " of " + scan.total + " records would be removed by the next prune: " + scan.removable.slice(0, 5).join(", "),
|
|
235
|
+
hint: "PI_DELEGATE_MAX_RUNS, PI_DELEGATE_RETENTION_DAYS and PI_DELEGATE_MAX_BYTES set the policy",
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function checkLive(registry: RunRegistry | undefined): DoctorCheck {
|
|
240
|
+
if (!registry) return { name: "live", level: "ok", detail: "no session registry (a child or a headless check)" };
|
|
241
|
+
// The predicate that decides what "live" means lives in contract.ts, so this
|
|
242
|
+
// check and the admission gate cannot disagree about a run that is not done.
|
|
243
|
+
const live = registry
|
|
244
|
+
.list()
|
|
245
|
+
.filter((handle) => !isTerminal(handle.status))
|
|
246
|
+
.map((handle) => handle.runId);
|
|
247
|
+
const limit = maxLive();
|
|
248
|
+
if (live.length === 0) return { name: "live", level: "ok", detail: "nothing running · limit " + limit };
|
|
249
|
+
const detail = live.length + " live of " + limit + " · " + live.slice(0, 3).join(", ");
|
|
250
|
+
return { name: "live", level: live.length >= limit ? "warn" : "ok", detail, hint: live.length >= limit ? "a new start is refused until one settles" : undefined };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function checkGit(): DoctorCheck {
|
|
254
|
+
if (!gitAvailable()) {
|
|
255
|
+
return { name: "git", level: "warn", detail: "git did not run · worktree: true is unavailable", hint: "install git to give parallel children their own checkout" };
|
|
256
|
+
}
|
|
257
|
+
return { name: "git", level: "ok", detail: "available · worktree: true usable" };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function checkLimits(): DoctorCheck {
|
|
261
|
+
const spend = maxCostUsd();
|
|
262
|
+
const verifyTimeout = Number(process.env.PI_DELEGATE_VERIFY_TIMEOUT_MS ?? 120_000);
|
|
263
|
+
return {
|
|
264
|
+
name: "limits",
|
|
265
|
+
level: "ok",
|
|
266
|
+
detail:
|
|
267
|
+
"max live " + maxLive() + " of " + MAX_MAX_LIVE + " · " +
|
|
268
|
+
(spend > 0 ? "$" + spend + " per run" : "spend cap off") +
|
|
269
|
+
" · verify timeout " + (Number.isFinite(verifyTimeout) ? Math.round(verifyTimeout / 1000) + "s" : "default") +
|
|
270
|
+
" · run cap " + MAX_TIMEOUT_MINUTES + " minutes",
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function checkSession(input: DoctorInput): DoctorCheck {
|
|
275
|
+
const where = input.cwd ?? process.cwd();
|
|
276
|
+
const session = input.sessionId ? input.sessionId : "(no session id)";
|
|
277
|
+
const mode = input.isChild ? "delegated child" : "top-level session";
|
|
278
|
+
if (input.isChild && !process.env[SPEC_ENV]) {
|
|
279
|
+
return { name: "session", level: "warn", detail: session + " in " + where + " · " + mode + " with no spec path" };
|
|
280
|
+
}
|
|
281
|
+
return { name: "session", level: "ok", detail: session + " in " + where + " · " + mode };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function checkContainment(): DoctorCheck {
|
|
285
|
+
const level = observability();
|
|
286
|
+
if (supportsFence()) {
|
|
287
|
+
return { name: "containment", level: "ok", detail: "linux: procfs identity, tag scan, group fence" };
|
|
288
|
+
}
|
|
289
|
+
if (level === "partial") {
|
|
290
|
+
return { name: "containment", level: "ok", detail: "process group only: cancellation works, absence is proven by signal 0" };
|
|
291
|
+
}
|
|
292
|
+
return {
|
|
293
|
+
name: "containment",
|
|
294
|
+
level: "warn",
|
|
295
|
+
detail: "no process table: a cancel reports unproven, never gone",
|
|
296
|
+
hint: "expected on Windows; the tree is asked to die and the verdict says so",
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function formatBytes(bytes: number): string {
|
|
301
|
+
if (bytes < 1024) return bytes + " B";
|
|
302
|
+
if (bytes < 1024 * 1024) return Math.round(bytes / 102.4) / 10 + " KiB";
|
|
303
|
+
if (bytes < 1024 * 1024 * 1024) return Math.round(bytes / 1024 / 102.4) / 10 + " MiB";
|
|
304
|
+
return Math.round(bytes / 1024 / 1024 / 102.4) / 10 + " GiB";
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Run every check. Nothing here throws: a check that cannot answer says so. */
|
|
308
|
+
export function runDoctor(input: DoctorInput = {}): DoctorReport {
|
|
309
|
+
const root = input.root ?? delegateRoot();
|
|
310
|
+
const checks: DoctorCheck[] = [];
|
|
311
|
+
const guarded = (name: string, run: () => DoctorCheck) => {
|
|
312
|
+
try {
|
|
313
|
+
checks.push(run());
|
|
314
|
+
} catch (error) {
|
|
315
|
+
checks.push({ name, level: "fail", detail: "the check itself failed: " + (error as Error).message });
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
guarded("manifest", () => checkManifest());
|
|
319
|
+
guarded("run root", () => checkRunRoot(root));
|
|
320
|
+
guarded("git", () => checkGit());
|
|
321
|
+
guarded("launcher", () => checkLauncher());
|
|
322
|
+
guarded("live", () => checkLive(input.registry));
|
|
323
|
+
guarded("retention", () => checkRetention(root, input.registry));
|
|
324
|
+
guarded("limits", () => checkLimits());
|
|
325
|
+
guarded("session", () => checkSession(input));
|
|
326
|
+
guarded("containment", () => checkContainment());
|
|
327
|
+
return { checks, ok: checks.every((check) => check.level !== "fail") };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** The report as a human reads it: one line per check, aligned. */
|
|
331
|
+
export function formatDoctor(report: DoctorReport): string {
|
|
332
|
+
const width = Math.max(...report.checks.map((check) => check.name.length));
|
|
333
|
+
const lines = ["delegate doctor"];
|
|
334
|
+
for (const check of report.checks) {
|
|
335
|
+
lines.push(" " + check.name.padEnd(width) + " " + check.level.padEnd(4) + " " + check.detail);
|
|
336
|
+
if (check.hint) lines.push(" " + " ".repeat(width) + " " + check.hint);
|
|
337
|
+
}
|
|
338
|
+
lines.push("");
|
|
339
|
+
lines.push(report.ok ? "Every check passed." : "At least one check failed; delegations will not work until it does.");
|
|
340
|
+
return lines.join("\n");
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* The one problem worth announcing at `session_start`.
|
|
345
|
+
*
|
|
346
|
+
* A run root that cannot be written is the failure mode that used to surface
|
|
347
|
+
* days later as a start that failed for an unrelated-looking reason. Every other
|
|
348
|
+
* check is on demand, because a warning on every session is a warning nobody
|
|
349
|
+
* reads.
|
|
350
|
+
*/
|
|
351
|
+
export function startupWarning(root: string = delegateRoot()): string | undefined {
|
|
352
|
+
const probe = probeRunRoot(root);
|
|
353
|
+
if (probe.ok) return undefined;
|
|
354
|
+
return "delegate: the run-record root " + root + " is not writable (" + probe.detail + "). Delegations will fail; run /delegate doctor.";
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Age of the oldest record, for a caller that wants it without the full scan. */
|
|
358
|
+
export function oldestRecordAge(root: string = delegateRoot()): string | undefined {
|
|
359
|
+
const scan = scanRetention({ root });
|
|
360
|
+
return scan.oldestAgeMs === undefined ? undefined : formatDuration(scan.oldestAgeMs);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** The paths a support request needs, in one string. */
|
|
364
|
+
export function describePaths(root: string = delegateRoot()): string {
|
|
365
|
+
const real = (() => {
|
|
366
|
+
try {
|
|
367
|
+
return realpathSync(root);
|
|
368
|
+
} catch {
|
|
369
|
+
return root;
|
|
370
|
+
}
|
|
371
|
+
})();
|
|
372
|
+
let entries = 0;
|
|
373
|
+
try {
|
|
374
|
+
entries = readdirSync(root).length;
|
|
375
|
+
} catch {
|
|
376
|
+
entries = 0;
|
|
377
|
+
}
|
|
378
|
+
let mode = "missing";
|
|
379
|
+
try {
|
|
380
|
+
mode = "0" + (statSync(root).mode & 0o777).toString(8);
|
|
381
|
+
} catch {
|
|
382
|
+
// a root that does not exist has no mode
|
|
383
|
+
}
|
|
384
|
+
return "root " + real + " (" + mode + ", " + entries + " entries) · extension " + packageRoot();
|
|
385
|
+
}
|