@anhlp/alp-client 0.0.0-stage → 0.0.1-beta.10
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/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +45 -2
- package/dist/acp-probe.d.ts +45 -0
- package/dist/acp-probe.js +46 -0
- package/dist/antigravity-probe.d.ts +33 -0
- package/dist/antigravity-probe.js +101 -0
- package/dist/command.d.ts +5 -0
- package/dist/command.js +35 -0
- package/dist/doctor.d.ts +21 -0
- package/dist/doctor.js +850 -0
- package/dist/index.d.ts +216 -0
- package/dist/index.js +702 -0
- package/dist/integration-lock.d.ts +37 -0
- package/dist/integration-lock.js +199 -0
- package/dist/ipc.d.ts +42 -0
- package/dist/ipc.js +69 -0
- package/dist/library-test.d.ts +94 -0
- package/dist/library-test.js +37 -0
- package/dist/mcp-probe.d.ts +24 -0
- package/dist/mcp-probe.js +147 -0
- package/dist/portable.d.ts +20 -0
- package/dist/portable.js +36 -0
- package/dist/prompt.d.ts +32 -0
- package/dist/prompt.js +59 -0
- package/dist/render.d.ts +6 -0
- package/dist/render.js +123 -0
- package/dist/rpc/client.d.ts +82 -0
- package/dist/rpc/client.js +292 -0
- package/dist/rpc/errors.d.ts +42 -0
- package/dist/rpc/errors.js +34 -0
- package/dist/rpc/framing.d.ts +21 -0
- package/dist/rpc/framing.js +57 -0
- package/dist/rpc/handshake.d.ts +24 -0
- package/dist/rpc/handshake.js +10 -0
- package/dist/rpc/reconnect.d.ts +97 -0
- package/dist/rpc/reconnect.js +227 -0
- package/dist/rpc/registry.d.ts +227 -0
- package/dist/rpc/registry.js +223 -0
- package/dist/rpc/terminal-directory.d.ts +24 -0
- package/dist/rpc/terminal-directory.js +70 -0
- package/dist/rpc/timers.d.ts +11 -0
- package/dist/rpc/timers.js +11 -0
- package/dist/service.d.ts +50 -0
- package/dist/service.js +145 -0
- package/dist/setup.d.ts +8 -0
- package/dist/setup.js +273 -0
- package/dist/supervise.d.ts +14 -0
- package/dist/supervise.js +91 -0
- package/dist/websocket.d.ts +51 -0
- package/dist/websocket.js +190 -0
- package/package.json +174 -4
- package/src/acp-probe.js +53 -0
- package/src/antigravity-probe.js +113 -0
- package/src/command.js +20 -0
- package/src/doctor.d.ts +21 -0
- package/src/doctor.js +912 -0
- package/src/index.js +813 -0
- package/src/integration-lock.js +203 -0
- package/src/ipc.js +92 -0
- package/src/library-test.js +41 -0
- package/src/mcp-probe.js +118 -0
- package/src/portable.js +30 -0
- package/src/prompt.js +64 -0
- package/src/render.js +139 -0
- package/src/rpc/client.js +296 -0
- package/src/rpc/errors.js +54 -0
- package/src/rpc/framing.js +61 -0
- package/src/rpc/handshake.js +21 -0
- package/src/rpc/reconnect.js +226 -0
- package/src/rpc/registry.js +229 -0
- package/src/rpc/terminal-directory.js +61 -0
- package/src/rpc/timers.js +16 -0
- package/src/service.js +158 -0
- package/src/setup.js +316 -0
- package/src/supervise.d.ts +14 -0
- package/src/supervise.js +97 -0
- package/src/websocket.js +259 -0
package/dist/doctor.js
ADDED
|
@@ -0,0 +1,850 @@
|
|
|
1
|
+
// packages/client/src/doctor.js
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { access, chmod, constants, lstat, readdir, readFile, statfs, unlink, writeFile } from "node:fs/promises";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { runCommand } from "./command.js";
|
|
7
|
+
import { assertPrivateSocket, connect, daemonPaths, lockAlive, readLock } from "./index.js";
|
|
8
|
+
import { installedProgram, serviceFor } from "./service.js";
|
|
9
|
+
import { jsonObject, agentSources, resolveAgent } from "@anhlp/alp-core/resolver";
|
|
10
|
+
import { loadHooks } from "@anhlp/alp-core/hooks";
|
|
11
|
+
import { isTrusted } from "@anhlp/alp-core/trust";
|
|
12
|
+
import { validateSkill } from "@anhlp/alp-core/skill-validate";
|
|
13
|
+
import { listProviders } from "@anhlp/alp-core/providers";
|
|
14
|
+
import { settingsWarnings, validateSettings, validateUserSettings } from "@anhlp/alp-core/validation";
|
|
15
|
+
import { readLogTail, scrubText } from "@anhlp/alp-core/log";
|
|
16
|
+
import { STATE_SCHEMA, migrationFile, readStateSchema } from "@anhlp/alp-core/state-schema";
|
|
17
|
+
var firstLine = (text) => text.trim().split("\n")[0] ?? "";
|
|
18
|
+
async function executable(command, env) {
|
|
19
|
+
const names = process.platform === "win32" ? [command, `${command}.exe`, `${command}.com`] : [command];
|
|
20
|
+
const candidates = path.isAbsolute(command) ? names : (env.PATH ?? "").split(path.delimiter).filter(Boolean).flatMap((directory) => names.map((name) => path.join(directory, name)));
|
|
21
|
+
for (const candidate of candidates) {
|
|
22
|
+
try {
|
|
23
|
+
await access(candidate, constants.X_OK);
|
|
24
|
+
if ((await lstat(candidate)).isDirectory()) continue;
|
|
25
|
+
return candidate;
|
|
26
|
+
} catch {
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return void 0;
|
|
30
|
+
}
|
|
31
|
+
var RUNTIMES = [
|
|
32
|
+
{ kind: "codex", variable: "ALP_CODEX_BIN", login: ["login", "status"], loggedIn: (result) => result.code === 0, hint: "codex login" },
|
|
33
|
+
{
|
|
34
|
+
kind: "claude",
|
|
35
|
+
variable: "ALP_CLAUDE_BIN",
|
|
36
|
+
login: ["auth", "status"],
|
|
37
|
+
hint: "claude auth login",
|
|
38
|
+
loggedIn: (result) => {
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(result.stdout).loggedIn === true;
|
|
41
|
+
} catch {
|
|
42
|
+
return result.code === 0;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
kind: "antigravity",
|
|
48
|
+
command: "agy",
|
|
49
|
+
variable: "ALP_ANTIGRAVITY_BIN",
|
|
50
|
+
login: ["models"],
|
|
51
|
+
hint: "agy and sign in",
|
|
52
|
+
loggedIn: (result) => result.code === 0
|
|
53
|
+
}
|
|
54
|
+
];
|
|
55
|
+
async function runtimeChecks({ env, run }) {
|
|
56
|
+
const checks = [];
|
|
57
|
+
for (const runtime of RUNTIMES) {
|
|
58
|
+
const command = env[runtime.variable] || runtime.command || runtime.kind;
|
|
59
|
+
const found = await executable(command, env);
|
|
60
|
+
if (!found) {
|
|
61
|
+
checks.push({ id: runtime.kind, status: "warn", summary: `${command} not found on PATH; ${runtime.kind} agents cannot run (set ${runtime.variable} to its path)` });
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const version = await run(found, ["--version"], { env });
|
|
65
|
+
if (version.code !== 0) {
|
|
66
|
+
checks.push({ id: runtime.kind, status: "fail", summary: `${found} --version failed: ${firstLine(version.stderr || version.stdout) || `exit ${version.code}`}` });
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const login = await run(found, runtime.login, { env });
|
|
70
|
+
checks.push(runtime.loggedIn(login) ? { id: runtime.kind, status: "ok", summary: `${firstLine(version.stdout)} at ${found}, logged in` } : { id: runtime.kind, status: "fail", summary: `${firstLine(version.stdout)} at ${found} is not logged in; run ${runtime.hint}` });
|
|
71
|
+
}
|
|
72
|
+
if (checks.every((check) => check.status !== "ok")) {
|
|
73
|
+
for (const check of checks) if (check.status === "warn") check.status = "fail";
|
|
74
|
+
}
|
|
75
|
+
return checks;
|
|
76
|
+
}
|
|
77
|
+
async function serviceCheck(home, env) {
|
|
78
|
+
const service = serviceFor({ home, env });
|
|
79
|
+
const program2 = service && await installedProgram(service);
|
|
80
|
+
if (!program2) return void 0;
|
|
81
|
+
const missing = [];
|
|
82
|
+
for (const file of program2.filter((arg) => path.isAbsolute(arg))) if (!await lstat(file).then(() => true, () => false)) missing.push(file);
|
|
83
|
+
return missing.length ? { id: "service", status: "fail", summary: `the ${service.kind} service ${service.name} runs files that are gone; run alp daemon install again`, details: missing } : { id: "service", status: "ok", summary: `${service.kind} runs alpd as ${service.name}` };
|
|
84
|
+
}
|
|
85
|
+
var seconds = (ms) => `${Math.round(ms / 1e3)} s`;
|
|
86
|
+
var STARTUP_CODES = /* @__PURE__ */ new Set(["ALP_HOME_UNUSABLE", "ALP_LOCK_FAILED", "ALP_STARTUP_FAILED", "ALP_IPC_LISTEN_FAILED"]);
|
|
87
|
+
var GROUPS = [
|
|
88
|
+
{ id: "persistence log", match: /^ALP_(PERSISTENCE|STATE|RECORD|TIMELINE)_/, hint: "alpd could not read or write its state; check free space and the permissions of the state directory" },
|
|
89
|
+
{ id: "ipc log", match: /^ALP_(IPC|RPC)_/, hint: "clients had trouble talking to alpd; alp daemon restart reopens the endpoint" },
|
|
90
|
+
{ id: "provider log", match: /^ALP_PROVIDER_/, hint: "a runtime process failed or would not start; the runtime checks above say whether it is installed and logged in" }
|
|
91
|
+
];
|
|
92
|
+
var STATE_FAILURES = { ENOENT: "is missing", EACCES: "is not accessible to you", EPERM: "is not accessible to you", EROFS: "is on a read-only filesystem", ENOSPC: "has no space left" };
|
|
93
|
+
function ipcFailure(error) {
|
|
94
|
+
if (error?.code === "ALP_IPC_TIMEOUT") return "ALP_IPC_TIMEOUT";
|
|
95
|
+
if (error?.code === "ENOENT") return "ALP_IPC_SOCKET_MISSING";
|
|
96
|
+
if (error?.code === "ECONNREFUSED") return "ALP_IPC_REFUSED";
|
|
97
|
+
if (error?.code === "EACCES" || error?.code === "EPERM") return "ALP_IPC_DENIED";
|
|
98
|
+
if (/private|owned by|ancestors|symlink/.test(error?.message ?? "")) return "ALP_IPC_SOCKET_UNSAFE";
|
|
99
|
+
return "ALP_IPC_FAILED";
|
|
100
|
+
}
|
|
101
|
+
async function askDaemon(lock, timeoutMs) {
|
|
102
|
+
let timer;
|
|
103
|
+
const attempt = connect(lock.socket, { name: "alp-doctor", version: "1" }).then(async (client) => {
|
|
104
|
+
try {
|
|
105
|
+
return await client.request("daemon.status");
|
|
106
|
+
} finally {
|
|
107
|
+
client.close();
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
const timeout = new Promise((_, reject) => {
|
|
111
|
+
timer = setTimeout(() => reject(Object.assign(new Error(`no answer within ${seconds(timeoutMs)}`), { code: "ALP_IPC_TIMEOUT" })), timeoutMs);
|
|
112
|
+
});
|
|
113
|
+
try {
|
|
114
|
+
return { status: await Promise.race([attempt, timeout]) };
|
|
115
|
+
} catch (error) {
|
|
116
|
+
attempt.catch(() => {
|
|
117
|
+
});
|
|
118
|
+
return { error };
|
|
119
|
+
} finally {
|
|
120
|
+
clearTimeout(timer);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
async function daemonHealthChecks(lock, timeoutMs) {
|
|
124
|
+
if (!lockAlive(lock) || lock.maintenance) return [];
|
|
125
|
+
const { status, error } = await askDaemon(lock, timeoutMs);
|
|
126
|
+
if (error) {
|
|
127
|
+
const code = ipcFailure(error);
|
|
128
|
+
const starting = !lock.ready && Date.now() - Date.parse(lock.startedAt) < 6e4;
|
|
129
|
+
return [{
|
|
130
|
+
id: "ipc",
|
|
131
|
+
status: starting ? "info" : "fail",
|
|
132
|
+
summary: `alpd (pid ${lock.pid}) is running but ${starting ? "does not answer yet, it is still starting" : "cannot be reached"} on ${lock.socket}: ${code}, ${error.message}`,
|
|
133
|
+
details: [`code ${code}`, ...starting ? [] : ["alp daemon restart starts it again; its work is kept and continued"]]
|
|
134
|
+
}];
|
|
135
|
+
}
|
|
136
|
+
const checks = [{ id: "ipc", status: "ok", summary: `alpd answers on ${lock.socket} (protocol ${status.protocolVersion})` }];
|
|
137
|
+
const health = status.health;
|
|
138
|
+
if (!health) {
|
|
139
|
+
checks.push({ id: "readiness", status: "info", summary: `alpd ${status.version} does not report readiness; alp daemon restart updates it` });
|
|
140
|
+
return checks;
|
|
141
|
+
}
|
|
142
|
+
const failing = health.checks.filter((check) => !check.ok);
|
|
143
|
+
checks.push(health.ready ? { id: "readiness", status: "ok", summary: "alpd is ready: it accepts connections and reads and writes its state" } : {
|
|
144
|
+
id: "readiness",
|
|
145
|
+
status: "fail",
|
|
146
|
+
summary: `alpd is alive but not ready: ${failing.map((check) => check.code ?? check.id).join(", ")}`,
|
|
147
|
+
details: failing.map((check) => `${check.code ?? check.id}: ${check.message ?? "failed"}`),
|
|
148
|
+
hint: "new prompts may fail until this clears; alp doctor shows the state directory below"
|
|
149
|
+
});
|
|
150
|
+
if (!lock.ready) checks.push({ id: "startup", status: "warn", summary: "alpd answers but has not finished starting" });
|
|
151
|
+
return checks;
|
|
152
|
+
}
|
|
153
|
+
async function stateCheck(home) {
|
|
154
|
+
const directory = path.join(home, "state");
|
|
155
|
+
const info = await lstat(directory).catch(() => void 0);
|
|
156
|
+
const target = info ? directory : home;
|
|
157
|
+
if (!info && !await lstat(home).then(() => true, () => false)) return { id: "state", status: "ok", summary: `${directory} is created when alpd first starts` };
|
|
158
|
+
try {
|
|
159
|
+
await access(target, constants.R_OK | constants.W_OK | constants.X_OK);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
return {
|
|
162
|
+
id: "state",
|
|
163
|
+
status: "fail",
|
|
164
|
+
summary: `${target} ${STATE_FAILURES[error.code] ?? `cannot be used (${error.code ?? error.message})`}: alpd cannot ${error.code === "ENOENT" ? "find" : "write"} its sessions; ALP_STATE_NOT_WRITABLE`,
|
|
165
|
+
details: [error.message]
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
if (!info) return { id: "state", status: "ok", summary: `${directory} is created when alpd first starts` };
|
|
169
|
+
const unreadable = [];
|
|
170
|
+
const leftovers = [];
|
|
171
|
+
let records = 0;
|
|
172
|
+
for (const name of await readdir(path.join(directory, "sessions")).catch(() => []).then((names) => names.slice(0, 2e3))) {
|
|
173
|
+
if (name.endsWith(".tmp")) {
|
|
174
|
+
leftovers.push(name);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (!name.endsWith(".json")) continue;
|
|
178
|
+
records++;
|
|
179
|
+
try {
|
|
180
|
+
const record = JSON.parse(await readFile(path.join(directory, "sessions", name), "utf8"));
|
|
181
|
+
if (record?.version !== 1 || typeof record.id !== "string") unreadable.push(name);
|
|
182
|
+
} catch {
|
|
183
|
+
unreadable.push(name);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (unreadable.length) return {
|
|
187
|
+
id: "state",
|
|
188
|
+
status: "warn",
|
|
189
|
+
summary: `${unreadable.length} of ${records} session record${records > 1 ? "s" : ""} in ${directory} cannot be read; alpd skips ${unreadable.length > 1 ? "them" : "it"} and ${unreadable.length > 1 ? "those sessions are" : "that session is"} not listed (ALP_RECORD_UNREADABLE)`,
|
|
190
|
+
details: [...unreadable.slice(0, 10), "doctor never deletes them: copy or repair the files by hand"]
|
|
191
|
+
};
|
|
192
|
+
return { id: "state", status: "ok", summary: `${directory} is readable and writable; ${records} session record${records === 1 ? "" : "s"}${leftovers.length ? `, ${leftovers.length} temporary file${leftovers.length > 1 ? "s" : ""} left by an interrupted write (alpd removes them)` : ""}` };
|
|
193
|
+
}
|
|
194
|
+
var brief = (record) => `${record.time} ${record.component} ${record.code ?? ""} ${record.msg}${record.sessionId ? ` [session ${record.sessionId}]` : ""}`.replace(/\s+/g, " ").trim();
|
|
195
|
+
async function logChecks(home, running) {
|
|
196
|
+
const file = daemonPaths(home).log;
|
|
197
|
+
let records;
|
|
198
|
+
try {
|
|
199
|
+
records = (await readLogTail(file)).filter((record) => !record.legacy);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
return [{ id: "log", status: "warn", summary: `${file} cannot be read: ${error.message}` }];
|
|
202
|
+
}
|
|
203
|
+
if (!records.length) return [];
|
|
204
|
+
const lastReady = records.findLastIndex((record) => record.event === "ready");
|
|
205
|
+
const since = records.slice(lastReady + 1);
|
|
206
|
+
const checks = [];
|
|
207
|
+
const failure = since.findLast((record) => record.level === "error" && STARTUP_CODES.has(record.code));
|
|
208
|
+
if (failure) checks.push({
|
|
209
|
+
id: "startup",
|
|
210
|
+
status: running ? "info" : "fail",
|
|
211
|
+
summary: `${running ? "an attempt to start another alpd" : "the last alpd"} failed at ${failure.time}: ${failure.code}, ${failure.msg}`,
|
|
212
|
+
details: [...failure.error ? [`${failure.error.name ?? "Error"}${failure.error.code ? ` ${failure.error.code}` : ""}: ${failure.error.message}`] : [], `log: ${file}`],
|
|
213
|
+
...running ? {} : { hint: "fix the cause and run alp daemon start; its work is kept and continued" }
|
|
214
|
+
});
|
|
215
|
+
for (const group of GROUPS) {
|
|
216
|
+
const found = since.filter((record) => (record.level === "error" || record.level === "warn") && group.match.test(record.code ?? ""));
|
|
217
|
+
if (!found.length) continue;
|
|
218
|
+
const counts = /* @__PURE__ */ new Map();
|
|
219
|
+
for (const record of found) counts.set(record.code, (counts.get(record.code) ?? 0) + 1);
|
|
220
|
+
checks.push({
|
|
221
|
+
id: group.id,
|
|
222
|
+
status: "warn",
|
|
223
|
+
summary: `${found.length} problem${found.length > 1 ? "s" : ""} logged since alpd was last ready: ${[...counts].map(([code, count]) => `${code} x${count}`).join(", ")}`,
|
|
224
|
+
details: [...found.slice(-5).map(brief), group.hint]
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
return checks;
|
|
228
|
+
}
|
|
229
|
+
async function failedSessionsCheck(home) {
|
|
230
|
+
const directory = path.join(home, "state", "sessions");
|
|
231
|
+
const failed = [];
|
|
232
|
+
for (const name of await readdir(directory).catch(() => []).then((names) => names.slice(0, 2e3))) {
|
|
233
|
+
if (!name.endsWith(".json")) continue;
|
|
234
|
+
try {
|
|
235
|
+
const record = JSON.parse(await readFile(path.join(directory, name), "utf8"));
|
|
236
|
+
if (record?.status === "failed" && record.lastError) failed.push(record);
|
|
237
|
+
} catch {
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (!failed.length) return void 0;
|
|
241
|
+
failed.sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)));
|
|
242
|
+
const recent = failed.filter((record) => Date.now() - Date.parse(record.updatedAt) < 24 * 36e5);
|
|
243
|
+
return {
|
|
244
|
+
id: "failed sessions",
|
|
245
|
+
status: recent.length ? "warn" : "info",
|
|
246
|
+
summary: `${failed.length} session${failed.length > 1 ? "s" : ""} ended in failure${recent.length ? `, ${recent.length} in the last day` : ""}; kept, nothing is deleted`,
|
|
247
|
+
details: failed.slice(0, 5).map((record) => `${record.updatedAt} ${record.session?.agent ?? "session"} ${record.id} (${record.session?.runtime ?? "unknown runtime"}) ${record.lastError.code ?? ""} ${String(record.lastError.message).slice(0, 200)}`.replace(/\s+/g, " "))
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
async function daemonCheck(home) {
|
|
251
|
+
const paths = daemonPaths(home);
|
|
252
|
+
const lock = await readLock(home);
|
|
253
|
+
const exists = (file) => lstat(file).then(() => true, () => false);
|
|
254
|
+
if (lockAlive(lock) && lock.maintenance) return { id: "alpd", status: "info", summary: `not running while alp ${lock.maintenance} runs (pid ${lock.pid})` };
|
|
255
|
+
if (lockAlive(lock)) return { id: "alpd", status: "ok", summary: `running (pid ${lock.pid}, ${lock.version})${lock.ready ? "" : ", starting"}` };
|
|
256
|
+
const stale = [];
|
|
257
|
+
if (await exists(paths.lock)) stale.push(paths.lock);
|
|
258
|
+
if (await exists(paths.socket)) stale.push(paths.socket);
|
|
259
|
+
const crashed = await exists(path.join(home, "state", "alpd.running"));
|
|
260
|
+
const after = crashed ? "; the last alpd stopped unexpectedly, and the next start continues its work" : "";
|
|
261
|
+
if (!stale.length) return { id: "alpd", status: crashed ? "info" : "ok", summary: `not running${after}` };
|
|
262
|
+
return {
|
|
263
|
+
id: "alpd",
|
|
264
|
+
status: "warn",
|
|
265
|
+
summary: `not running, and left ${stale.map((file) => path.basename(file)).join(" and ")} behind${after}`,
|
|
266
|
+
fix: {
|
|
267
|
+
describe: `remove ${stale.join(", ")}`,
|
|
268
|
+
async apply() {
|
|
269
|
+
if (lockAlive(await readLock(home))) return "skipped: alpd started meanwhile";
|
|
270
|
+
for (const file of stale) await unlink(file).catch(() => {
|
|
271
|
+
});
|
|
272
|
+
return `removed ${stale.length} stale file${stale.length > 1 ? "s" : ""}`;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
async function privateEntries(home) {
|
|
278
|
+
const entries2 = [home];
|
|
279
|
+
for (const name of ["settings.json", "alpd.lock", "alpd.json", "role-skills.json"]) entries2.push(path.join(home, name));
|
|
280
|
+
for (const directory of ["state", "runs", "logs", "boards", "worktrees", "copies"]) {
|
|
281
|
+
const full = path.join(home, directory);
|
|
282
|
+
entries2.push(full);
|
|
283
|
+
if (directory === "worktrees" || directory === "copies") continue;
|
|
284
|
+
for (const name of await readdir(full).catch(() => [])) entries2.push(path.join(full, name));
|
|
285
|
+
}
|
|
286
|
+
return entries2;
|
|
287
|
+
}
|
|
288
|
+
async function permissionsCheck(home) {
|
|
289
|
+
if (process.platform === "win32") return { id: "permissions", status: "ok", summary: `${home} follows your Windows profile access rules` };
|
|
290
|
+
const open = [];
|
|
291
|
+
for (const entry of await privateEntries(home)) {
|
|
292
|
+
const info = await lstat(entry).catch(() => void 0);
|
|
293
|
+
if (!info || info.isSymbolicLink() || !(info.mode & 63)) continue;
|
|
294
|
+
open.push({ entry, mode: info.mode & 511, directory: info.isDirectory() });
|
|
295
|
+
}
|
|
296
|
+
if (!open.length) return { id: "permissions", status: "ok", summary: `${home} is private to you` };
|
|
297
|
+
return {
|
|
298
|
+
id: "permissions",
|
|
299
|
+
status: "warn",
|
|
300
|
+
summary: `${open.length} entr${open.length > 1 ? "ies" : "y"} under ${home} readable by others; they hold task briefs, results and settings`,
|
|
301
|
+
details: open.map((item) => `${item.mode.toString(8).padStart(4, "0")} ${item.entry}`),
|
|
302
|
+
fix: {
|
|
303
|
+
describe: "remove group and other access from them",
|
|
304
|
+
async apply() {
|
|
305
|
+
for (const item of open) await chmod(item.entry, item.mode & 448).catch(() => {
|
|
306
|
+
});
|
|
307
|
+
return `tightened ${open.length} entr${open.length > 1 ? "ies" : "y"}`;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
async function userSettingsCheck(home) {
|
|
313
|
+
const file = path.join(home, "settings.json");
|
|
314
|
+
try {
|
|
315
|
+
const text = await readFile(file, "utf8").catch((error) => {
|
|
316
|
+
if (error.code === "ENOENT") return void 0;
|
|
317
|
+
throw error;
|
|
318
|
+
});
|
|
319
|
+
if (text === void 0) return { id: "user settings", status: "ok", summary: `none (${file})` };
|
|
320
|
+
const settings = JSON.parse(text);
|
|
321
|
+
validateUserSettings(settings, file);
|
|
322
|
+
const warnings = settingsWarnings(settings, "user");
|
|
323
|
+
return warnings.length ? { id: "user settings", status: "warn", summary: `${file}: ${warnings.length} key${warnings.length > 1 ? "s" : ""} ALP ignores`, details: warnings } : { id: "user settings", status: "ok", summary: file };
|
|
324
|
+
} catch (error) {
|
|
325
|
+
return { id: "user settings", status: "fail", summary: `alpd ignores ${file}: ${error.message.replace(`${file}: `, "")}` };
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
async function projectChecks(project, home) {
|
|
329
|
+
const checks = [];
|
|
330
|
+
const file = path.join(project, ".alp", "settings.json");
|
|
331
|
+
let settings;
|
|
332
|
+
try {
|
|
333
|
+
settings = await jsonObject(file, "INVALID_SETTINGS");
|
|
334
|
+
validateSettings(settings, file);
|
|
335
|
+
const warnings = settingsWarnings(settings, "project");
|
|
336
|
+
checks.push(warnings.length ? { id: "settings", status: "warn", summary: `${file}: ${warnings.length} key${warnings.length > 1 ? "s" : ""} ALP ignores`, details: warnings } : { id: "settings", status: "ok", summary: file });
|
|
337
|
+
} catch (error) {
|
|
338
|
+
checks.push({ id: "settings", status: "fail", summary: error.message });
|
|
339
|
+
return checks;
|
|
340
|
+
}
|
|
341
|
+
const sources = await agentSources(project, { library: home });
|
|
342
|
+
const agents = [...sources.keys()].sort((a, b) => a.localeCompare(b));
|
|
343
|
+
const broken = [];
|
|
344
|
+
const shadows = [];
|
|
345
|
+
const hooks = /* @__PURE__ */ new Map();
|
|
346
|
+
for (const [agent, { source, overrides }] of sources) if (overrides) shadows.push(`${agent}: the ${source}'s copy replaces the ${overrides === "builtin" ? "built-in" : "library"} agent`);
|
|
347
|
+
for (const agent of agents) {
|
|
348
|
+
try {
|
|
349
|
+
const resolved = await resolveAgent(project, { agent, library: home });
|
|
350
|
+
for (const hook of await loadHooks(resolved)) hooks.set(hook.path, { ...hook, agents: [...hooks.get(hook.path)?.agents ?? [], agent] });
|
|
351
|
+
for (const skill of resolved.skills) if (!skill.path.startsWith(home + path.sep)) {
|
|
352
|
+
const library = path.join(home, "skills", skill.name, "SKILL.md");
|
|
353
|
+
if (await lstat(library).then(() => true, () => false)) shadows.push(`${agent}: ${skill.name} from the project replaces the library's`);
|
|
354
|
+
}
|
|
355
|
+
} catch (error) {
|
|
356
|
+
broken.push(`${agent}: ${error.message}`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (!agents.length) checks.push({ id: "agents", status: "fail", summary: "no agents: neither ALP's built-ins nor the library nor the project define one" });
|
|
360
|
+
else if (broken.length) checks.push({ id: "agents", status: "fail", summary: `${broken.length} of ${agents.length} agents cannot start`, details: broken });
|
|
361
|
+
else checks.push({ id: "agents", status: shadows.length ? "info" : "ok", summary: `${agents.length} agents resolve: ${agents.join(", ")}`, ...shadows.length ? { details: shadows } : {} });
|
|
362
|
+
if (hooks.size) checks.push(await hooksCheck(project, home, [...hooks.values()]));
|
|
363
|
+
if (settings.defaultAgent && !agents.includes(settings.defaultAgent)) checks.push({ id: "agents", status: "fail", summary: `defaultAgent ${settings.defaultAgent} is not an agent of this project` });
|
|
364
|
+
return checks;
|
|
365
|
+
}
|
|
366
|
+
var program = (command) => /^\s*([\w./-]+)/.exec(command)?.[1];
|
|
367
|
+
var SHELL_WORDS = /* @__PURE__ */ new Set(["cd", "test", "[", "echo", "exit", "true", "false", "set", "export", "if", "for", "while", "exec", "env", "command", "printf", "read", "source", "."]);
|
|
368
|
+
async function hooksCheck(project, home, hooks) {
|
|
369
|
+
const missing = [];
|
|
370
|
+
for (const hook of hooks) {
|
|
371
|
+
const name = program(hook.command);
|
|
372
|
+
if (!name || SHELL_WORDS.has(name)) continue;
|
|
373
|
+
const candidates = name.includes("/") ? [path.resolve(project, name)] : (process.env.PATH ?? "").split(path.delimiter).filter(Boolean).map((directory) => path.join(directory, name));
|
|
374
|
+
let found = false;
|
|
375
|
+
for (const candidate of candidates) if (await access(candidate, constants.X_OK).then(() => true, () => false)) {
|
|
376
|
+
found = true;
|
|
377
|
+
break;
|
|
378
|
+
}
|
|
379
|
+
if (!found) missing.push(`${hook.name} (${hook.event}, used by ${hook.agents.join(", ")}): ${name} is not found`);
|
|
380
|
+
}
|
|
381
|
+
const fromProject = hooks.filter((hook) => hook.project);
|
|
382
|
+
const trusted = fromProject.length ? await isTrusted(home, project) : true;
|
|
383
|
+
const details = [...missing, ...!trusted ? [`not trusted yet: ${fromProject.map((hook) => hook.name).join(", ")}; alpd asks the first time one runs, or run alp trust`] : []];
|
|
384
|
+
return {
|
|
385
|
+
id: "hooks",
|
|
386
|
+
status: missing.length ? "warn" : trusted ? "ok" : "info",
|
|
387
|
+
summary: `${hooks.length} hook${hooks.length > 1 ? "s" : ""}${fromProject.length ? `, ${fromProject.length} from the project${trusted ? ", which the user trusts" : ", not trusted yet"}` : ""}${missing.length ? `; ${missing.length} cannot start` : ""}`,
|
|
388
|
+
...details.length ? { details } : {}
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
async function providersCheck(home, env) {
|
|
392
|
+
let providers;
|
|
393
|
+
try {
|
|
394
|
+
providers = await listProviders(home);
|
|
395
|
+
} catch (error) {
|
|
396
|
+
return { id: "providers", status: "fail", summary: error.message };
|
|
397
|
+
}
|
|
398
|
+
if (!providers.length) return void 0;
|
|
399
|
+
const missing = [];
|
|
400
|
+
for (const provider of providers) if (!await executable(provider.command, { ...env, ...provider.env })) missing.push(`${provider.id}: ${provider.command} is not found`);
|
|
401
|
+
return {
|
|
402
|
+
id: "providers",
|
|
403
|
+
status: "warn",
|
|
404
|
+
summary: `${providers.length} ACP provider${providers.length > 1 ? "s" : ""} (${providers.map((provider) => provider.id).join(", ")})${missing.length ? `; ${missing.length} cannot start` : ""}`,
|
|
405
|
+
details: [
|
|
406
|
+
...missing,
|
|
407
|
+
"ALP has no sandbox around an ACP agent: it holds the session's mode only by answering the permission requests the agent sends, so a command the agent runs without asking runs unchecked",
|
|
408
|
+
"ALP cannot steer an ACP agent mid-turn (mail waits for the turn to end), resumes its sessions only when it supports session/load, and cannot recall them or give them review copies"
|
|
409
|
+
]
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
async function skillFormatCheck(home) {
|
|
413
|
+
const directory = path.join(home, "skills");
|
|
414
|
+
const entries2 = await readdir(directory, { withFileTypes: true }).catch(() => []);
|
|
415
|
+
const failed = [];
|
|
416
|
+
const warned = [];
|
|
417
|
+
let checked = 0;
|
|
418
|
+
for (const entry of entries2) {
|
|
419
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink() || !/^[\w.-]+$/.test(entry.name) || entry.name.startsWith(".")) continue;
|
|
420
|
+
if (!await lstat(path.join(directory, entry.name, "SKILL.md")).then(() => true, () => false)) continue;
|
|
421
|
+
checked++;
|
|
422
|
+
try {
|
|
423
|
+
const report = await validateSkill(path.join(directory, entry.name));
|
|
424
|
+
if (!report.ok) failed.push(`${entry.name}: ${report.errors.map((finding) => finding.message).join("; ")}`);
|
|
425
|
+
else if (report.warnings.length) warned.push(`${entry.name}: ${report.warnings.map((finding) => finding.code).join(", ")}`);
|
|
426
|
+
} catch (error) {
|
|
427
|
+
failed.push(`${entry.name}: could not be checked: ${error.message}`);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
if (!checked) return void 0;
|
|
431
|
+
if (failed.length) return { id: "skill-format", status: "fail", summary: `${failed.length} library skill${failed.length > 1 ? "s have" : " has"} an unsafe link or an unreadable file (alp skill check <name> explains)`, details: [...failed, ...warned] };
|
|
432
|
+
if (warned.length) return { id: "skill-format", status: "warn", summary: `${warned.length} library skill${warned.length > 1 ? "s do" : " does"} not fully meet the skill format; they still load (alp skill check <name> explains)`, details: warned };
|
|
433
|
+
return { id: "skill-format", status: "ok", summary: `the library's skills meet the skill format (${directory})` };
|
|
434
|
+
}
|
|
435
|
+
async function librarySkillsCheck(home) {
|
|
436
|
+
const file = path.join(home, "role-skills.json");
|
|
437
|
+
let roles;
|
|
438
|
+
try {
|
|
439
|
+
const text = await readFile(file, "utf8").catch((error) => {
|
|
440
|
+
if (error.code === "ENOENT") return void 0;
|
|
441
|
+
throw error;
|
|
442
|
+
});
|
|
443
|
+
if (text === void 0) return void 0;
|
|
444
|
+
roles = JSON.parse(text);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
return { id: "skills", status: "fail", summary: `${file}: ${error.message}` };
|
|
447
|
+
}
|
|
448
|
+
if (!roles || typeof roles !== "object" || Array.isArray(roles)) return { id: "skills", status: "fail", summary: `${file}: expected an object of role names to skill lists` };
|
|
449
|
+
const missing = [];
|
|
450
|
+
for (const [role, names] of Object.entries(roles)) {
|
|
451
|
+
if (!Array.isArray(names)) {
|
|
452
|
+
missing.push(`${role}: not a list`);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
for (const name of names) {
|
|
456
|
+
if (typeof name !== "string" || !await lstat(path.join(home, "skills", name, "SKILL.md")).then(() => true, () => false)) missing.push(`${role}: ${name}`);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
return missing.length ? { id: "skills", status: "warn", summary: `${file} lists ${missing.length} skill${missing.length > 1 ? "s" : ""} the library lacks; agents start without them`, details: missing } : { id: "skills", status: "ok", summary: `the library's skills exist (${file})` };
|
|
460
|
+
}
|
|
461
|
+
async function liveCheck(home, running) {
|
|
462
|
+
const file = path.join(home, "state", "live.json");
|
|
463
|
+
let entries2;
|
|
464
|
+
try {
|
|
465
|
+
entries2 = JSON.parse(await readFile(file, "utf8"));
|
|
466
|
+
} catch {
|
|
467
|
+
return void 0;
|
|
468
|
+
}
|
|
469
|
+
if (!Array.isArray(entries2)) return { id: "live work", status: "warn", summary: `${file} is not a list; alpd ignores it` };
|
|
470
|
+
const gone = [];
|
|
471
|
+
for (const entry of entries2) {
|
|
472
|
+
if (typeof entry?.project !== "string" || !await lstat(entry.project).then(() => true, () => false)) gone.push(entry);
|
|
473
|
+
}
|
|
474
|
+
if (!gone.length) return { id: "live work", status: entries2.length && !running ? "info" : "ok", summary: entries2.length ? `${entries2.length} assignment${entries2.length > 1 ? "s" : ""} ${running ? "running" : "waiting for alpd to continue"}` : "no running assignments" };
|
|
475
|
+
return {
|
|
476
|
+
id: "live work",
|
|
477
|
+
status: "warn",
|
|
478
|
+
summary: `${gone.length} interrupted assignment${gone.length > 1 ? "s" : ""} belong to projects that no longer exist`,
|
|
479
|
+
details: gone.map((entry) => `${entry?.agent} ${entry?.assignmentId} in ${entry?.project}`),
|
|
480
|
+
fix: running ? void 0 : {
|
|
481
|
+
describe: `drop them from ${file}, keeping a copy beside it`,
|
|
482
|
+
async apply() {
|
|
483
|
+
const current = JSON.parse(await readFile(file, "utf8"));
|
|
484
|
+
const ids = new Set(gone.map((entry) => entry?.assignmentId));
|
|
485
|
+
const kept = current.filter((entry) => !ids.has(entry?.assignmentId));
|
|
486
|
+
await writeFile(`${file}.dropped-${Date.now()}.json`, JSON.stringify(current.filter((entry) => ids.has(entry?.assignmentId)), null, 2) + "\n", { mode: 384 });
|
|
487
|
+
await writeFile(file, JSON.stringify(kept, null, 2) + "\n", { mode: 384 });
|
|
488
|
+
return `dropped ${current.length - kept.length}`;
|
|
489
|
+
}
|
|
490
|
+
},
|
|
491
|
+
...running ? { hint: "stop alpd to drop them" } : {}
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
async function branchCheck(project, home, run) {
|
|
495
|
+
const git = (args) => run("git", args, { cwd: project });
|
|
496
|
+
const top = await git(["rev-parse", "--show-toplevel"]);
|
|
497
|
+
if (top.code !== 0) return [];
|
|
498
|
+
const checks = [];
|
|
499
|
+
const worktrees = (await git(["worktree", "list", "--porcelain"])).stdout.split("\n\n").filter(Boolean);
|
|
500
|
+
const prunable = worktrees.filter((block) => /^prunable/m.test(block)).map((block) => block.match(/^worktree (.*)$/m)?.[1]).filter(Boolean);
|
|
501
|
+
if (prunable.length) checks.push({
|
|
502
|
+
id: "worktrees",
|
|
503
|
+
status: "warn",
|
|
504
|
+
summary: `git still lists ${prunable.length} worktree${prunable.length > 1 ? "s" : ""} that no longer exist`,
|
|
505
|
+
details: prunable,
|
|
506
|
+
fix: { describe: "git worktree prune", async apply() {
|
|
507
|
+
await git(["worktree", "prune"]);
|
|
508
|
+
return "pruned";
|
|
509
|
+
} }
|
|
510
|
+
});
|
|
511
|
+
const checkedOut = new Set(worktrees.map((block) => block.match(/^branch refs\/heads\/(.*)$/m)?.[1]).filter(Boolean));
|
|
512
|
+
let live = [];
|
|
513
|
+
try {
|
|
514
|
+
live = JSON.parse(await readFile(path.join(home, "state", "live.json"), "utf8"));
|
|
515
|
+
} catch {
|
|
516
|
+
}
|
|
517
|
+
const inUse = /* @__PURE__ */ new Set([...checkedOut, ...Array.isArray(live) ? live.map((entry) => entry?.worktree?.branch).filter(Boolean) : []]);
|
|
518
|
+
const branches = (await git(["for-each-ref", "--format=%(refname:short)", "refs/heads/alp/"])).stdout.split("\n").filter(Boolean);
|
|
519
|
+
if (!branches.length) return checks;
|
|
520
|
+
const merged = new Set((await git(["branch", "--format=%(refname:short)", "--merged", "HEAD", "--list", "alp/*"])).stdout.split("\n").filter(Boolean));
|
|
521
|
+
const spare = branches.filter((branch) => merged.has(branch) && !inUse.has(branch));
|
|
522
|
+
const kept = branches.filter((branch) => !merged.has(branch) && !inUse.has(branch));
|
|
523
|
+
if (spare.length) checks.push({
|
|
524
|
+
id: "branches",
|
|
525
|
+
status: "warn",
|
|
526
|
+
summary: `${spare.length} alp/* branch${spare.length > 1 ? "es are" : " is"} already merged into HEAD`,
|
|
527
|
+
details: spare,
|
|
528
|
+
fix: {
|
|
529
|
+
describe: `delete ${spare.length > 1 ? "them" : "it"} with git branch -d`,
|
|
530
|
+
async apply() {
|
|
531
|
+
let deleted = 0;
|
|
532
|
+
for (const branch of spare) if ((await git(["branch", "-d", branch])).code === 0) deleted++;
|
|
533
|
+
return `deleted ${deleted}`;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
});
|
|
537
|
+
if (kept.length) checks.push({ id: "branches", status: "info", summary: `${kept.length} alp/* branch${kept.length > 1 ? "es hold" : " holds"} unmerged work from finished or interrupted assignments; merge or delete ${kept.length > 1 ? "them" : "it"} yourself`, details: kept });
|
|
538
|
+
if (!spare.length && !kept.length) checks.push({ id: "branches", status: "ok", summary: `${branches.length} alp/* branch${branches.length > 1 ? "es" : ""} in use` });
|
|
539
|
+
return checks;
|
|
540
|
+
}
|
|
541
|
+
function scrubCheck(check) {
|
|
542
|
+
const clean = (text) => scrubText(text, { max: 1e3 });
|
|
543
|
+
return {
|
|
544
|
+
...check,
|
|
545
|
+
summary: clean(check.summary),
|
|
546
|
+
...check.details ? { details: check.details.map(clean) } : {},
|
|
547
|
+
...check.hint ? { hint: clean(check.hint) } : {}
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
async function schemaChecks(home) {
|
|
551
|
+
let info;
|
|
552
|
+
try {
|
|
553
|
+
info = await readStateSchema(home);
|
|
554
|
+
} catch (error) {
|
|
555
|
+
return [{ id: "schema", status: "fail", summary: `${error.message} (ALP_${error.code ?? "STATE_UNUSABLE"})` }];
|
|
556
|
+
}
|
|
557
|
+
const checks = [info.schema > STATE_SCHEMA ? { id: "schema", status: "fail", summary: `state schema ${info.schema}${info.by ? ` from ${info.by}` : ""} is newer than this ALP knows (${STATE_SCHEMA}): alpd refuses to start and changes nothing in it (ALP_STATE_SCHEMA_TOO_NEW)`, hint: "run the ALP that wrote it, or a newer one; docs/alp/data-recovery.md says more" } : { id: "schema", status: info.schema < STATE_SCHEMA ? "info" : "ok", summary: info.fresh ? `no state yet; alpd starts it at schema ${STATE_SCHEMA}` : info.schema < STATE_SCHEMA ? `state schema ${info.schema}: alpd migrates it to ${STATE_SCHEMA} at its next start, after saving a backup in ${path.join(home, "backups")}` : `state schema ${info.schema}` }];
|
|
558
|
+
if (await lstat(migrationFile(home)).then(() => true, () => false)) checks.push({ id: "migration", status: "warn", summary: "a state migration was cut short; alpd continues it at its next start, or puts the state back if it fails" });
|
|
559
|
+
if (await lstat(path.join(home, "restore-journal.json")).then(() => true, () => false)) checks.push({ id: "restore", status: "warn", summary: "a restore was cut short; alpd or the next alp restore moves the earlier data back first" });
|
|
560
|
+
return checks;
|
|
561
|
+
}
|
|
562
|
+
function isInside(target, container) {
|
|
563
|
+
const resolve = (directory) => {
|
|
564
|
+
let current = path.resolve(directory);
|
|
565
|
+
let suffix = "";
|
|
566
|
+
for (; ; ) {
|
|
567
|
+
try {
|
|
568
|
+
return path.join(realpathSync(current), suffix);
|
|
569
|
+
} catch {
|
|
570
|
+
const parent = path.dirname(current);
|
|
571
|
+
if (parent === current) return path.join(current, suffix);
|
|
572
|
+
suffix = path.join(path.basename(current), suffix);
|
|
573
|
+
current = parent;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
const resolvedTarget = resolve(target);
|
|
578
|
+
const resolvedContainer = resolve(container);
|
|
579
|
+
const relative = path.relative(resolvedContainer, resolvedTarget);
|
|
580
|
+
return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
581
|
+
}
|
|
582
|
+
async function homeLocationCheck(home, project) {
|
|
583
|
+
if (process.platform === "win32" || !home) return { id: "home", status: "ok", summary: home ?? "" };
|
|
584
|
+
if (project && isInside(home, project)) {
|
|
585
|
+
return {
|
|
586
|
+
id: "home",
|
|
587
|
+
status: "warn",
|
|
588
|
+
summary: `ALP_HOME (${home}) is inside this project's workspace, which sandboxed sessions may write: a tool could change staged attachment copies before they are read; keep ALP_HOME outside workspaces (default ~/.alp)`
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
const inTmp = isInside(home, os.tmpdir()) || isInside(home, "/tmp");
|
|
592
|
+
if (inTmp) {
|
|
593
|
+
return {
|
|
594
|
+
id: "home",
|
|
595
|
+
status: "warn",
|
|
596
|
+
summary: `ALP_HOME (${home}) is inside the temp directory, which sandboxed sessions may write: a tool could change staged attachment copies before they are read; keep ALP_HOME outside it (default ~/.alp)`
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
return { id: "home", status: "ok", summary: home };
|
|
600
|
+
}
|
|
601
|
+
var GIB = 1024 ** 3;
|
|
602
|
+
var formatSize = (bytes) => bytes >= GIB ? `${(bytes / GIB).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`;
|
|
603
|
+
async function entries(directory, prefix = "") {
|
|
604
|
+
const names = await readdir(directory).catch(() => []);
|
|
605
|
+
return names.filter((name) => name.startsWith(prefix)).map((name) => path.join(directory, name));
|
|
606
|
+
}
|
|
607
|
+
var QUOTABLE = /^[A-Za-z0-9._\-/\\: ]+$/;
|
|
608
|
+
function shellQuote(text, platform = process.platform) {
|
|
609
|
+
const value = String(text);
|
|
610
|
+
const absolute = platform === "win32" ? path.win32.isAbsolute(value) : path.posix.isAbsolute(value);
|
|
611
|
+
return absolute && QUOTABLE.test(value) ? `'${value}'` : void 0;
|
|
612
|
+
}
|
|
613
|
+
var printable = (text) => String(text).replace(new RegExp("\\\\|[\\p{C}\\p{Zl}\\p{Zp}]|(?! )\\p{Zs}", "gu"), (char) => char === "\\" ? "\\\\" : `\\u{${char.codePointAt(0).toString(16)}}`);
|
|
614
|
+
var UNQUOTABLE = "no command: its path holds characters other than ASCII letters, digits, space and . _ - / \\ :, which a pasted command might not carry safely; check it and remove it by hand";
|
|
615
|
+
var LEFTOVER_STATES = {
|
|
616
|
+
"clean-pushed": "clean and pushed (no changes, no untracked or ignored files, and every commit and, for a clone, every ref on a remote it last fetched; remove by hand with the command shown, given only for a plain ASCII path)",
|
|
617
|
+
dirty: "dirty (uncommitted changes or untracked files, or a merge or rebase in progress; keep)",
|
|
618
|
+
"local-only": "local-only data (ignored files such as .env, local config, node_modules or build output, which exist only here; keep)",
|
|
619
|
+
unpushed: "unpushed (commits, or for a clone tags, branches or other refs, that no remote-tracking ref mirrors; keep)",
|
|
620
|
+
"in-use": "in use (a running assignment, a retained result, this shell, or changed in the last day; keep)",
|
|
621
|
+
unknown: "unknown (not a git checkout of its own, or git could not tell; check by hand)"
|
|
622
|
+
};
|
|
623
|
+
async function ownedPaths(home) {
|
|
624
|
+
const owned = /* @__PURE__ */ new Set();
|
|
625
|
+
const read = async (file) => JSON.parse(await readFile(file, "utf8"));
|
|
626
|
+
const live = await read(path.join(home, "state", "live.json")).catch(() => []);
|
|
627
|
+
for (const entry of Array.isArray(live) ? live : []) if (typeof entry?.worktree?.path === "string") owned.add(realpathOr(entry.worktree.path));
|
|
628
|
+
const ledger = await read(path.join(home, "state", "assignment-results.json")).catch(() => void 0);
|
|
629
|
+
for (const entry of Array.isArray(ledger?.results) ? ledger.results : []) {
|
|
630
|
+
if (entry?.handled) continue;
|
|
631
|
+
for (const where of [entry?.worktree, entry?.checkout]) if (typeof where === "string") owned.add(realpathOr(where));
|
|
632
|
+
}
|
|
633
|
+
return owned;
|
|
634
|
+
}
|
|
635
|
+
var NOT_CHECKED = "not checked: alp doctor ran out of time; run it again, or check by hand";
|
|
636
|
+
var OutOfTime = class extends Error {
|
|
637
|
+
};
|
|
638
|
+
async function classifyLeftover(directory, { run, env, owned, here, recentMs, deadline, platform }) {
|
|
639
|
+
const real = realpathOr(directory);
|
|
640
|
+
const inside = (outer, inner) => inner === outer || inner.startsWith(outer.endsWith(path.sep) ? outer : outer + path.sep);
|
|
641
|
+
if ([...owned].some((owner) => inside(real, owner) || inside(owner, real)) || inside(real, here)) return { path: directory, state: "in-use" };
|
|
642
|
+
const git = async (args) => {
|
|
643
|
+
const left = deadline - Date.now();
|
|
644
|
+
if (left <= 0) throw new OutOfTime();
|
|
645
|
+
const result = await run("git", ["-C", directory, ...args], { env, timeoutMs: Math.min(1e4, left) });
|
|
646
|
+
if (Date.now() >= deadline) throw new OutOfTime();
|
|
647
|
+
return result;
|
|
648
|
+
};
|
|
649
|
+
const unknown = (reason) => ({ path: directory, state: "unknown", reason });
|
|
650
|
+
if (!await lstat(path.join(directory, ".git")).then(() => true, () => false)) return unknown("not a git checkout");
|
|
651
|
+
const where = await git(["rev-parse", "--show-toplevel", "--absolute-git-dir", "--git-common-dir"]);
|
|
652
|
+
if (where.code !== 0) return unknown("not a git checkout");
|
|
653
|
+
const [top, gitDir, common] = where.stdout.trim().split("\n");
|
|
654
|
+
if (!top || !gitDir || !common || realpathOr(top) !== real) return unknown("not the top of a git checkout");
|
|
655
|
+
const commonDir = realpathOr(path.resolve(top, common));
|
|
656
|
+
const status = await git(["-c", "status.showUntrackedFiles=all", "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching"]);
|
|
657
|
+
if (status.code !== 0) return unknown("git status failed");
|
|
658
|
+
const rows = status.stdout.split("\0").filter(Boolean);
|
|
659
|
+
if (rows.some((row) => !row.startsWith("!! "))) return { path: directory, state: "dirty" };
|
|
660
|
+
const ignored = rows.map((row) => row.slice(3));
|
|
661
|
+
if (ignored.length) return { path: directory, state: "local-only", reason: `ignored files: ${ignored.slice(0, 3).join(", ")}${ignored.length > 3 ? `, \u2026 ${ignored.length - 3} more` : ""}` };
|
|
662
|
+
const index = await git(["ls-files", "-z", "-v", "--stage"]);
|
|
663
|
+
if (index.code !== 0) return unknown("git could not list its index");
|
|
664
|
+
const tracked = index.stdout.split("\0").filter(Boolean);
|
|
665
|
+
if (tracked.some((row) => row[0] === "S" || /[a-z]/.test(row[0]))) return unknown("some files are marked assume-unchanged or skip-worktree, which git status does not check");
|
|
666
|
+
if (tracked.some((row) => row.slice(2).startsWith("160000 "))) return unknown("it has submodules, whose own changes and commits this check does not read");
|
|
667
|
+
for (const name of ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply"]) {
|
|
668
|
+
if (await lstat(path.join(gitDir, name)).then(() => true, () => false)) return { path: directory, state: "dirty" };
|
|
669
|
+
}
|
|
670
|
+
const touched = Math.max(...await Promise.all([directory, path.join(gitDir, "index"), path.join(gitDir, "HEAD")].map((file) => lstat(file).then((info) => info.mtimeMs, () => 0))));
|
|
671
|
+
if (Date.now() - touched < recentMs) return { path: directory, state: "in-use", reason: "changed in the last day" };
|
|
672
|
+
const linked = realpathOr(gitDir) !== commonDir;
|
|
673
|
+
const ahead = await git(["rev-list", "-n", "1", ...linked ? ["HEAD"] : ["HEAD", "--all"], "--not", "--remotes"]);
|
|
674
|
+
if (ahead.code !== 0) return unknown("git could not compare HEAD with the remotes");
|
|
675
|
+
if (ahead.stdout.trim()) return { path: directory, state: "unpushed" };
|
|
676
|
+
if (!linked) {
|
|
677
|
+
const refs = await git(["for-each-ref", "--format=%(objectname) %(refname)"]);
|
|
678
|
+
if (refs.code !== 0) return unknown("git could not list its refs");
|
|
679
|
+
const all = refs.stdout.split("\n").filter(Boolean).map((line) => {
|
|
680
|
+
const at = line.indexOf(" ");
|
|
681
|
+
return [line.slice(at + 1), line.slice(0, at)];
|
|
682
|
+
});
|
|
683
|
+
const remotes = await git(["remote"]);
|
|
684
|
+
if (remotes.code !== 0) return unknown("git could not list its remotes");
|
|
685
|
+
const remoteNames = remotes.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
686
|
+
const mirrors = new Map(all.filter(([name]) => name.startsWith("refs/remotes/")));
|
|
687
|
+
const mirrored = ([name, object]) => {
|
|
688
|
+
const branch = name.startsWith("refs/heads/");
|
|
689
|
+
const rest = branch ? name.slice("refs/heads/".length) : name.slice("refs/".length);
|
|
690
|
+
return remoteNames.some((remote) => {
|
|
691
|
+
const target = mirrors.get(`refs/remotes/${remote}/${rest}`);
|
|
692
|
+
return target !== void 0 && (branch || target === object);
|
|
693
|
+
});
|
|
694
|
+
};
|
|
695
|
+
const local = all.filter((entry) => !entry[0].startsWith("refs/remotes/") && !mirrored(entry));
|
|
696
|
+
if (local.length) return { path: directory, state: "unpushed", reason: `local refs no remote-tracking ref mirrors: ${local.slice(0, 3).map(([name]) => name).join(", ")}${local.length > 3 ? `, \u2026 ${local.length - 3} more` : ""}` };
|
|
697
|
+
}
|
|
698
|
+
const list = await git(["worktree", "list", "--porcelain"]);
|
|
699
|
+
if (list.code !== 0) return unknown("git could not list its worktrees");
|
|
700
|
+
if (!linked) {
|
|
701
|
+
if ((list.stdout.match(/^worktree /gm) ?? []).length > 1) return { path: directory, state: "in-use", reason: "other worktrees use its repository" };
|
|
702
|
+
const quoted2 = shellQuote(directory, platform);
|
|
703
|
+
if (quoted2 === void 0) return { path: directory, state: "clean-pushed", reason: UNQUOTABLE };
|
|
704
|
+
return { path: directory, state: "clean-pushed", command: platform === "win32" ? `Remove-Item -LiteralPath ${quoted2} -Recurse -Force` : `rm -rf ${quoted2}` };
|
|
705
|
+
}
|
|
706
|
+
const main = list.stdout.match(/^worktree (.*)$/m)?.[1];
|
|
707
|
+
if (!main) return unknown("git could not name its main worktree");
|
|
708
|
+
const [quotedMain, quoted] = [shellQuote(main, platform), shellQuote(directory, platform)];
|
|
709
|
+
if (quotedMain === void 0 || quoted === void 0) return { path: directory, state: "clean-pushed", reason: UNQUOTABLE };
|
|
710
|
+
return { path: directory, state: "clean-pushed", command: `git -C ${quotedMain} worktree remove ${quoted}` };
|
|
711
|
+
}
|
|
712
|
+
async function classifyLeftovers(paths, { budgetMs, ...options }) {
|
|
713
|
+
const results = paths.map((directory) => ({ path: directory, state: "unknown", reason: NOT_CHECKED }));
|
|
714
|
+
const deadline = Date.now() + budgetMs;
|
|
715
|
+
let next = 0, done = false;
|
|
716
|
+
const worker = async () => {
|
|
717
|
+
while (!done && next < paths.length && Date.now() < deadline) {
|
|
718
|
+
const index = next++;
|
|
719
|
+
try {
|
|
720
|
+
const result = await classifyLeftover(paths[index], { ...options, deadline });
|
|
721
|
+
if (!done && Date.now() < deadline) results[index] = result;
|
|
722
|
+
} catch (error) {
|
|
723
|
+
if (!(error instanceof OutOfTime)) results[index] = { path: paths[index], state: "unknown", reason: `could not check: ${error?.message ?? error}` };
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
let timer;
|
|
728
|
+
const expired = new Promise((resolve) => {
|
|
729
|
+
timer = setTimeout(resolve, Math.max(0, budgetMs));
|
|
730
|
+
});
|
|
731
|
+
await Promise.race([Promise.all(Array.from({ length: Math.min(8, paths.length) }, worker)), expired]);
|
|
732
|
+
clearTimeout(timer);
|
|
733
|
+
done = true;
|
|
734
|
+
return results;
|
|
735
|
+
}
|
|
736
|
+
var SHOWN_COMMANDS = 20;
|
|
737
|
+
async function diskCheck(home, { run = runCommand, env = process.env, free, tempDirs = [.../* @__PURE__ */ new Set([os.tmpdir(), ...process.platform === "win32" ? [] : ["/tmp"]])], cwd = process.cwd(), classifyMs = 1e4, recentMs = 24 * 60 * 60 * 1e3, platform = process.platform } = {}) {
|
|
738
|
+
let bytes = free;
|
|
739
|
+
if (bytes === void 0) {
|
|
740
|
+
try {
|
|
741
|
+
const info = await statfs(home);
|
|
742
|
+
bytes = Number(info.bavail) * Number(info.bsize);
|
|
743
|
+
} catch {
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
const worktrees = await entries(path.join(home, "worktrees"));
|
|
747
|
+
const temp = [];
|
|
748
|
+
for (const directory of tempDirs) {
|
|
749
|
+
for (const entry of await entries(directory, "alp-")) {
|
|
750
|
+
const info = await lstat(entry).catch(() => void 0);
|
|
751
|
+
if (info?.isDirectory() && !temp.includes(realpathOr(entry))) temp.push(realpathOr(entry));
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
async function size(paths) {
|
|
755
|
+
if (!paths.length) return 0;
|
|
756
|
+
if (process.platform === "win32") return void 0;
|
|
757
|
+
const result = await run("du", ["-sk", ...paths], { env, timeoutMs: 2e4 });
|
|
758
|
+
if (result.code !== 0 && !result.stdout) return void 0;
|
|
759
|
+
const total = result.stdout.split("\n").reduce((sum, line) => sum + (Number(line.split(/\s+/)[0]) || 0), 0);
|
|
760
|
+
return total * 1024;
|
|
761
|
+
}
|
|
762
|
+
const gitEnv = { ...Object.fromEntries(Object.entries(env).filter(([name]) => !/^GIT_(DIR|WORK_TREE|INDEX_FILE|COMMON_DIR|OBJECT_DIRECTORY|NAMESPACE|CEILING_DIRECTORIES)$/.test(name))), GIT_OPTIONAL_LOCKS: "0" };
|
|
763
|
+
const groups = [[`${path.join(home, "worktrees")}`, worktrees], [`${tempDirs.map((directory) => path.join(directory, "alp-*")).join(", ")}`, temp]].filter(([, paths]) => paths.length);
|
|
764
|
+
const [sizes, leftovers] = await Promise.all([
|
|
765
|
+
Promise.all(groups.map(([, paths]) => size(paths))),
|
|
766
|
+
ownedPaths(home).then((owned) => classifyLeftovers([.../* @__PURE__ */ new Set([...worktrees, ...temp])], { run, env: gitEnv, owned, here: realpathOr(cwd), budgetMs: classifyMs, recentMs, platform }))
|
|
767
|
+
]);
|
|
768
|
+
const details = groups.map(([label, paths], index) => `${paths.length} left in ${label}${sizes[index] === void 0 ? "" : `, ${formatSize(sizes[index])}`}`);
|
|
769
|
+
for (const [state, meaning] of Object.entries(LEFTOVER_STATES)) {
|
|
770
|
+
const count = leftovers.filter((entry) => entry.state === state).length;
|
|
771
|
+
if (count) details.push(`${count} ${meaning}`);
|
|
772
|
+
}
|
|
773
|
+
const unchecked = leftovers.filter((entry) => entry.reason === NOT_CHECKED).length;
|
|
774
|
+
if (unchecked) details.push(` ${unchecked} of the unknown were not checked within ${classifyMs < 1e3 ? `${classifyMs} ms` : `${Math.round(classifyMs / 1e3)} s`}`);
|
|
775
|
+
const commands = leftovers.filter((entry) => entry.state === "clean-pushed").map((entry) => entry.command ?? `# remove by hand after checking (no safe command): ${printable(entry.path)}`);
|
|
776
|
+
for (const command of commands.slice(0, SHOWN_COMMANDS)) details.push(` ${command}`);
|
|
777
|
+
if (commands.length > SHOWN_COMMANDS) details.push(` \u2026 ${commands.length - SHOWN_COMMANDS} more; alp doctor --json lists every one`);
|
|
778
|
+
const hint = details.length ? "ALP deletes none of these, and --fix does not either. Only a clean and pushed leftover gets a command, for you to run by hand, and only when its path is plain ASCII; inspect the others before removing anything." : void 0;
|
|
779
|
+
const where = bytes === void 0 ? "free space unknown" : `${formatSize(bytes)} free`;
|
|
780
|
+
const status = bytes !== void 0 && bytes < 2 * GIB ? "warn" : "ok";
|
|
781
|
+
const summary = bytes !== void 0 && bytes < 2 * GIB ? `${where} where ALP_HOME lives; when the disk is full, alpd pauses all work until space returns` : `${where} where ALP_HOME lives`;
|
|
782
|
+
return { id: "disk", status, summary, ...details.length ? { details } : {}, ...hint ? { hint } : {}, ...leftovers.length ? { leftovers } : {} };
|
|
783
|
+
}
|
|
784
|
+
function realpathOr(file) {
|
|
785
|
+
try {
|
|
786
|
+
return realpathSync(file);
|
|
787
|
+
} catch {
|
|
788
|
+
return file;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
async function diagnose({ home, project, env = process.env, run = runCommand, sandbox, daemonEntry, timeoutMs = 3e3 } = {}) {
|
|
792
|
+
const checks = [];
|
|
793
|
+
if (daemonEntry) {
|
|
794
|
+
checks.push(await lstat(daemonEntry).then(() => ({ id: "build", status: "ok", summary: daemonEntry }), () => ({ id: "build", status: "fail", summary: `alpd is not built (${daemonEntry}); run npm run build` })));
|
|
795
|
+
}
|
|
796
|
+
checks.push(...await runtimeChecks({ env, run }));
|
|
797
|
+
checks.push(await homeLocationCheck(home, project));
|
|
798
|
+
if (home) checks.push(await diskCheck(home, { run, env }));
|
|
799
|
+
const daemon = await daemonCheck(home);
|
|
800
|
+
checks.push(daemon);
|
|
801
|
+
const service = await serviceCheck(home, env);
|
|
802
|
+
if (service) checks.push(service);
|
|
803
|
+
const running = daemon.status === "ok" && daemon.summary.startsWith("running");
|
|
804
|
+
checks.push(...await daemonHealthChecks(await readLock(home), timeoutMs));
|
|
805
|
+
checks.push(await stateCheck(home));
|
|
806
|
+
const schema = await schemaChecks(home);
|
|
807
|
+
checks.push(...schema);
|
|
808
|
+
const unreadable = schema.some((check) => check.id === "schema" && check.status === "fail");
|
|
809
|
+
checks.push(...await logChecks(home, running));
|
|
810
|
+
const failedSessions = await failedSessionsCheck(home);
|
|
811
|
+
if (failedSessions) checks.push(failedSessions);
|
|
812
|
+
if (sandbox !== void 0) checks.push(sandbox ? { id: "sandbox", status: "ok", summary: "Claude sessions run Bash in an OS sandbox that holds their mode" } : { id: "sandbox", status: "warn", summary: `no Bash sandbox for Claude (${process.platform === "linux" ? "install bubblewrap and socat" : "Seatbelt is missing"}): read-only Claude agents rely on their permission rules alone, and review copies on Claude cannot start` });
|
|
813
|
+
checks.push(await permissionsCheck(home));
|
|
814
|
+
checks.push(await userSettingsCheck(home));
|
|
815
|
+
const skills = await librarySkillsCheck(home);
|
|
816
|
+
if (skills) checks.push(skills);
|
|
817
|
+
const skillFormat = await skillFormatCheck(home);
|
|
818
|
+
if (skillFormat) checks.push(skillFormat);
|
|
819
|
+
const providers = await providersCheck(home, env);
|
|
820
|
+
if (providers) checks.push(providers);
|
|
821
|
+
const live = await liveCheck(home, running);
|
|
822
|
+
if (live && unreadable) delete live.fix;
|
|
823
|
+
if (live) checks.push(live);
|
|
824
|
+
if (project) {
|
|
825
|
+
checks.push(...await projectChecks(project, home));
|
|
826
|
+
checks.push(...await branchCheck(project, home, run));
|
|
827
|
+
}
|
|
828
|
+
return checks.map(scrubCheck);
|
|
829
|
+
}
|
|
830
|
+
async function repair(checks) {
|
|
831
|
+
const done = [];
|
|
832
|
+
for (const check of checks) {
|
|
833
|
+
if (!check.fix) continue;
|
|
834
|
+
try {
|
|
835
|
+
done.push({ id: check.id, result: await check.fix.apply() });
|
|
836
|
+
} catch (error) {
|
|
837
|
+
done.push({ id: check.id, result: `failed: ${error.message}` });
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
return done;
|
|
841
|
+
}
|
|
842
|
+
export {
|
|
843
|
+
LEFTOVER_STATES,
|
|
844
|
+
diagnose,
|
|
845
|
+
diskCheck,
|
|
846
|
+
printable,
|
|
847
|
+
repair,
|
|
848
|
+
runCommand,
|
|
849
|
+
shellQuote
|
|
850
|
+
};
|