@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/src/doctor.js
ADDED
|
@@ -0,0 +1,912 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
import { access, chmod, constants, lstat, readdir, readFile, statfs, unlink, writeFile } from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { runCommand } from './command.js';
|
|
6
|
+
import { assertPrivateSocket, connect, daemonPaths, lockAlive, readLock } from './index.js';
|
|
7
|
+
import { installedProgram, serviceFor } from './service.js';
|
|
8
|
+
import { jsonObject, agentSources, resolveAgent } from '@anhlp/alp-core/resolver';
|
|
9
|
+
import { loadHooks } from '@anhlp/alp-core/hooks';
|
|
10
|
+
import { isTrusted } from '@anhlp/alp-core/trust';
|
|
11
|
+
import { validateSkill } from '@anhlp/alp-core/skill-validate';
|
|
12
|
+
import { listProviders } from '@anhlp/alp-core/providers';
|
|
13
|
+
import { settingsWarnings, validateSettings, validateUserSettings } from '@anhlp/alp-core/validation';
|
|
14
|
+
import { readLogTail, scrubText } from '@anhlp/alp-core/log';
|
|
15
|
+
import { STATE_SCHEMA, migrationFile, readStateSchema } from '@anhlp/alp-core/state-schema';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* `alp doctor` (ALPD §36): checks what ALP needs from this machine and project, and
|
|
19
|
+
* what earlier runs may have left behind. Every check reports one of
|
|
20
|
+
* - ok: nothing to do;
|
|
21
|
+
* - info: worth knowing, nothing is wrong;
|
|
22
|
+
* - warn: something to fix, and ALP still works;
|
|
23
|
+
* - fail: ALP cannot work as configured.
|
|
24
|
+
* A check that `--fix` can repair carries a fix. Diagnosing only reads (alpd answers a
|
|
25
|
+
* status request and probes its own state directory); nothing is repaired unless the caller
|
|
26
|
+
* passes the checks to `repair`. Fixes only remove what nothing uses (stale locks, merged
|
|
27
|
+
* branches, entries for vanished projects, kept in a backup) or tighten modes; they never
|
|
28
|
+
* touch sessions, tasks, timelines, running work or unmerged branches. Every line a check
|
|
29
|
+
* reports is scrubbed of credentials, whatever it quotes.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
const firstLine = text => text.trim().split('\n')[0] ?? '';
|
|
33
|
+
|
|
34
|
+
/** The executable `command` names, as a spawn without a shell would find it (on Windows that adds .exe and .com). */
|
|
35
|
+
async function executable(command, env) {
|
|
36
|
+
const names = process.platform === 'win32' ? [command, `${command}.exe`, `${command}.com`] : [command];
|
|
37
|
+
const candidates = path.isAbsolute(command) ? names : (env.PATH ?? '').split(path.delimiter).filter(Boolean).flatMap(directory => names.map(name => path.join(directory, name)));
|
|
38
|
+
for (const candidate of candidates) {
|
|
39
|
+
try { await access(candidate, constants.X_OK); if ((await lstat(candidate)).isDirectory()) continue; return candidate; } catch {}
|
|
40
|
+
}
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** How to tell whether each native runtime is logged in. */
|
|
45
|
+
const RUNTIMES = [
|
|
46
|
+
{ kind: 'codex', variable: 'ALP_CODEX_BIN', login: ['login', 'status'], loggedIn: result => result.code === 0, hint: 'codex login' },
|
|
47
|
+
{
|
|
48
|
+
kind: 'claude', variable: 'ALP_CLAUDE_BIN', login: ['auth', 'status'], hint: 'claude auth login',
|
|
49
|
+
loggedIn: result => { try { return JSON.parse(result.stdout).loggedIn === true; } catch { return result.code === 0; } },
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
kind: 'antigravity', command: 'agy', variable: 'ALP_ANTIGRAVITY_BIN', login: ['models'], hint: 'agy and sign in',
|
|
53
|
+
loggedIn: result => result.code === 0,
|
|
54
|
+
},
|
|
55
|
+
];
|
|
56
|
+
|
|
57
|
+
async function runtimeChecks({ env, run }) {
|
|
58
|
+
const checks = [];
|
|
59
|
+
for (const runtime of RUNTIMES) {
|
|
60
|
+
const command = env[runtime.variable] || runtime.command || runtime.kind;
|
|
61
|
+
const found = await executable(command, env);
|
|
62
|
+
if (!found) {
|
|
63
|
+
checks.push({ id: runtime.kind, status: 'warn', summary: `${command} not found on PATH; ${runtime.kind} agents cannot run (set ${runtime.variable} to its path)` });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const version = await run(found, ['--version'], { env });
|
|
67
|
+
if (version.code !== 0) {
|
|
68
|
+
checks.push({ id: runtime.kind, status: 'fail', summary: `${found} --version failed: ${firstLine(version.stderr || version.stdout) || `exit ${version.code}`}` });
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
const login = await run(found, runtime.login, { env });
|
|
72
|
+
checks.push(runtime.loggedIn(login)
|
|
73
|
+
? { id: runtime.kind, status: 'ok', summary: `${firstLine(version.stdout)} at ${found}, logged in` }
|
|
74
|
+
: { id: runtime.kind, status: 'fail', summary: `${firstLine(version.stdout)} at ${found} is not logged in; run ${runtime.hint}` });
|
|
75
|
+
}
|
|
76
|
+
// One runtime is enough; with neither, nothing can run.
|
|
77
|
+
if (checks.every(check => check.status !== 'ok')) for (const check of checks) if (check.status === 'warn') check.status = 'fail';
|
|
78
|
+
return checks;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** An installed alpd service whose node, alpd.js or native alpd moved can no longer start alpd. */
|
|
82
|
+
async function serviceCheck(home, env) {
|
|
83
|
+
const service = serviceFor({ home, env });
|
|
84
|
+
const program = service && await installedProgram(service);
|
|
85
|
+
if (!program) return undefined;
|
|
86
|
+
const missing = [];
|
|
87
|
+
// [node, alpd.js], or [alpd, --service] for the native alpd (t-81b0.9): only the files.
|
|
88
|
+
for (const file of program.filter(arg => path.isAbsolute(arg))) if (!await lstat(file).then(() => true, () => false)) missing.push(file);
|
|
89
|
+
return missing.length
|
|
90
|
+
? { id: 'service', status: 'fail', summary: `the ${service.kind} service ${service.name} runs files that are gone; run alp daemon install again`, details: missing }
|
|
91
|
+
: { id: 'service', status: 'ok', summary: `${service.kind} runs alpd as ${service.name}` };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const seconds = ms => `${Math.round(ms / 1000)} s`;
|
|
95
|
+
|
|
96
|
+
/** Codes of the failures a start can stop at, and of the ones that mean another alpd is running. */
|
|
97
|
+
const STARTUP_CODES = new Set(['ALP_HOME_UNUSABLE', 'ALP_LOCK_FAILED', 'ALP_STARTUP_FAILED', 'ALP_IPC_LISTEN_FAILED']);
|
|
98
|
+
const GROUPS = [
|
|
99
|
+
{ 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' },
|
|
100
|
+
{ id: 'ipc log', match: /^ALP_(IPC|RPC)_/, hint: 'clients had trouble talking to alpd; alp daemon restart reopens the endpoint' },
|
|
101
|
+
{ 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' },
|
|
102
|
+
];
|
|
103
|
+
const 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' };
|
|
104
|
+
|
|
105
|
+
/** What a failed connection to alpd's socket means, as a code the log uses too. */
|
|
106
|
+
function ipcFailure(error) {
|
|
107
|
+
if (error?.code === 'ALP_IPC_TIMEOUT') return 'ALP_IPC_TIMEOUT';
|
|
108
|
+
if (error?.code === 'ENOENT') return 'ALP_IPC_SOCKET_MISSING';
|
|
109
|
+
if (error?.code === 'ECONNREFUSED') return 'ALP_IPC_REFUSED';
|
|
110
|
+
if (error?.code === 'EACCES' || error?.code === 'EPERM') return 'ALP_IPC_DENIED';
|
|
111
|
+
if (/private|owned by|ancestors|symlink/.test(error?.message ?? '')) return 'ALP_IPC_SOCKET_UNSAFE';
|
|
112
|
+
return 'ALP_IPC_FAILED';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Asks a running alpd for its status; `error` says why it could not be asked. */
|
|
116
|
+
async function askDaemon(lock, timeoutMs) {
|
|
117
|
+
let timer;
|
|
118
|
+
const attempt = connect(lock.socket, { name: 'alp-doctor', version: '1' }).then(async client => {
|
|
119
|
+
try { return await client.request('daemon.status'); } finally { client.close(); }
|
|
120
|
+
});
|
|
121
|
+
const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(Object.assign(new Error(`no answer within ${seconds(timeoutMs)}`), { code: 'ALP_IPC_TIMEOUT' })), timeoutMs); });
|
|
122
|
+
try { return { status: await Promise.race([attempt, timeout]) }; }
|
|
123
|
+
catch (error) { attempt.catch(() => {}); return { error }; }
|
|
124
|
+
finally { clearTimeout(timer); }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* alpd as a client sees it (ALPD §67): whether its IPC endpoint answers, and whether it is ready,
|
|
129
|
+
* which is more than alive: it accepts connections and its state is readable and writable now.
|
|
130
|
+
*/
|
|
131
|
+
async function daemonHealthChecks(lock, timeoutMs) {
|
|
132
|
+
if (!lockAlive(lock) || lock.maintenance) return [];
|
|
133
|
+
const { status, error } = await askDaemon(lock, timeoutMs);
|
|
134
|
+
if (error) {
|
|
135
|
+
const code = ipcFailure(error);
|
|
136
|
+
// A socket that is missing right after start is still being opened.
|
|
137
|
+
const starting = !lock.ready && Date.now() - Date.parse(lock.startedAt) < 60_000;
|
|
138
|
+
return [{
|
|
139
|
+
id: 'ipc', status: starting ? 'info' : 'fail',
|
|
140
|
+
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}`,
|
|
141
|
+
details: [`code ${code}`, ...(starting ? [] : ['alp daemon restart starts it again; its work is kept and continued'])],
|
|
142
|
+
}];
|
|
143
|
+
}
|
|
144
|
+
const checks = [{ id: 'ipc', status: 'ok', summary: `alpd answers on ${lock.socket} (protocol ${status.protocolVersion})` }];
|
|
145
|
+
const health = status.health;
|
|
146
|
+
if (!health) { checks.push({ id: 'readiness', status: 'info', summary: `alpd ${status.version} does not report readiness; alp daemon restart updates it` }); return checks; }
|
|
147
|
+
const failing = health.checks.filter(check => !check.ok);
|
|
148
|
+
checks.push(health.ready
|
|
149
|
+
? { id: 'readiness', status: 'ok', summary: 'alpd is ready: it accepts connections and reads and writes its state' }
|
|
150
|
+
: {
|
|
151
|
+
id: 'readiness', status: 'fail',
|
|
152
|
+
summary: `alpd is alive but not ready: ${failing.map(check => check.code ?? check.id).join(', ')}`,
|
|
153
|
+
details: failing.map(check => `${check.code ?? check.id}: ${check.message ?? 'failed'}`),
|
|
154
|
+
hint: 'new prompts may fail until this clears; alp doctor shows the state directory below',
|
|
155
|
+
});
|
|
156
|
+
if (!lock.ready) checks.push({ id: 'startup', status: 'warn', summary: 'alpd answers but has not finished starting' });
|
|
157
|
+
return checks;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The state directory alpd keeps sessions in, without writing to it (alpd probes its own writes). */
|
|
161
|
+
async function stateCheck(home) {
|
|
162
|
+
const directory = path.join(home, 'state');
|
|
163
|
+
const info = await lstat(directory).catch(() => undefined);
|
|
164
|
+
const target = info ? directory : home;
|
|
165
|
+
if (!info && !await lstat(home).then(() => true, () => false)) return { id: 'state', status: 'ok', summary: `${directory} is created when alpd first starts` };
|
|
166
|
+
try { await access(target, constants.R_OK | constants.W_OK | constants.X_OK); }
|
|
167
|
+
catch (error) {
|
|
168
|
+
return {
|
|
169
|
+
id: 'state', status: 'fail', 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`,
|
|
170
|
+
details: [error.message],
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
if (!info) return { id: 'state', status: 'ok', summary: `${directory} is created when alpd first starts` };
|
|
174
|
+
const unreadable = [];
|
|
175
|
+
const leftovers = [];
|
|
176
|
+
let records = 0;
|
|
177
|
+
for (const name of await readdir(path.join(directory, 'sessions')).catch(() => []).then(names => names.slice(0, 2000))) {
|
|
178
|
+
if (name.endsWith('.tmp')) { leftovers.push(name); continue; }
|
|
179
|
+
if (!name.endsWith('.json')) continue;
|
|
180
|
+
records++;
|
|
181
|
+
try { const record = JSON.parse(await readFile(path.join(directory, 'sessions', name), 'utf8')); if (record?.version !== 1 || typeof record.id !== 'string') unreadable.push(name); }
|
|
182
|
+
catch { unreadable.push(name); }
|
|
183
|
+
}
|
|
184
|
+
if (unreadable.length) return {
|
|
185
|
+
id: 'state', status: 'warn', 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)`,
|
|
186
|
+
details: [...unreadable.slice(0, 10), 'doctor never deletes them: copy or repair the files by hand'],
|
|
187
|
+
};
|
|
188
|
+
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)` : ''}` };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const brief = record => `${record.time} ${record.component} ${record.code ?? ''} ${record.msg}${record.sessionId ? ` [session ${record.sessionId}]` : ''}`.replace(/\s+/g, ' ').trim();
|
|
192
|
+
|
|
193
|
+
/** What alpd's own log says: where the last start stopped, and the failures logged since it was ready. */
|
|
194
|
+
async function logChecks(home, running) {
|
|
195
|
+
const file = daemonPaths(home).log;
|
|
196
|
+
let records;
|
|
197
|
+
try { records = (await readLogTail(file)).filter(record => !record.legacy); }
|
|
198
|
+
catch (error) { return [{ id: 'log', status: 'warn', summary: `${file} cannot be read: ${error.message}` }]; }
|
|
199
|
+
if (!records.length) return [];
|
|
200
|
+
const lastReady = records.findLastIndex(record => record.event === 'ready');
|
|
201
|
+
const since = records.slice(lastReady + 1);
|
|
202
|
+
const checks = [];
|
|
203
|
+
const failure = since.findLast(record => record.level === 'error' && STARTUP_CODES.has(record.code));
|
|
204
|
+
if (failure) checks.push({
|
|
205
|
+
id: 'startup', status: running ? 'info' : 'fail',
|
|
206
|
+
summary: `${running ? 'an attempt to start another alpd' : 'the last alpd'} failed at ${failure.time}: ${failure.code}, ${failure.msg}`,
|
|
207
|
+
details: [...(failure.error ? [`${failure.error.name ?? 'Error'}${failure.error.code ? ` ${failure.error.code}` : ''}: ${failure.error.message}`] : []), `log: ${file}`],
|
|
208
|
+
...(running ? {} : { hint: 'fix the cause and run alp daemon start; its work is kept and continued' }),
|
|
209
|
+
});
|
|
210
|
+
for (const group of GROUPS) {
|
|
211
|
+
const found = since.filter(record => (record.level === 'error' || record.level === 'warn') && group.match.test(record.code ?? ''));
|
|
212
|
+
if (!found.length) continue;
|
|
213
|
+
const counts = new Map();
|
|
214
|
+
for (const record of found) counts.set(record.code, (counts.get(record.code) ?? 0) + 1);
|
|
215
|
+
checks.push({
|
|
216
|
+
id: group.id, status: 'warn',
|
|
217
|
+
summary: `${found.length} problem${found.length > 1 ? 's' : ''} logged since alpd was last ready: ${[...counts].map(([code, count]) => `${code} x${count}`).join(', ')}`,
|
|
218
|
+
details: [...found.slice(-5).map(brief), group.hint],
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
return checks;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Sessions that ended in failure, from their records: what a provider failure left, with the codes the log uses. */
|
|
225
|
+
async function failedSessionsCheck(home) {
|
|
226
|
+
const directory = path.join(home, 'state', 'sessions');
|
|
227
|
+
const failed = [];
|
|
228
|
+
for (const name of await readdir(directory).catch(() => []).then(names => names.slice(0, 2000))) {
|
|
229
|
+
if (!name.endsWith('.json')) continue;
|
|
230
|
+
try {
|
|
231
|
+
const record = JSON.parse(await readFile(path.join(directory, name), 'utf8'));
|
|
232
|
+
if (record?.status === 'failed' && record.lastError) failed.push(record);
|
|
233
|
+
} catch {}
|
|
234
|
+
}
|
|
235
|
+
if (!failed.length) return undefined;
|
|
236
|
+
failed.sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)));
|
|
237
|
+
const recent = failed.filter(record => Date.now() - Date.parse(record.updatedAt) < 24 * 3600_000);
|
|
238
|
+
return {
|
|
239
|
+
id: 'failed sessions', status: recent.length ? 'warn' : 'info',
|
|
240
|
+
summary: `${failed.length} session${failed.length > 1 ? 's' : ''} ended in failure${recent.length ? `, ${recent.length} in the last day` : ''}; kept, nothing is deleted`,
|
|
241
|
+
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, ' ')),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function daemonCheck(home) {
|
|
246
|
+
const paths = daemonPaths(home);
|
|
247
|
+
const lock = await readLock(home);
|
|
248
|
+
const exists = file => lstat(file).then(() => true, () => false);
|
|
249
|
+
if (lockAlive(lock) && lock.maintenance) return { id: 'alpd', status: 'info', summary: `not running while alp ${lock.maintenance} runs (pid ${lock.pid})` };
|
|
250
|
+
if (lockAlive(lock)) return { id: 'alpd', status: 'ok', summary: `running (pid ${lock.pid}, ${lock.version})${lock.ready ? '' : ', starting'}` };
|
|
251
|
+
const stale = [];
|
|
252
|
+
if (await exists(paths.lock)) stale.push(paths.lock);
|
|
253
|
+
if (await exists(paths.socket)) stale.push(paths.socket);
|
|
254
|
+
const crashed = await exists(path.join(home, 'state', 'alpd.running'));
|
|
255
|
+
const after = crashed ? '; the last alpd stopped unexpectedly, and the next start continues its work' : '';
|
|
256
|
+
if (!stale.length) return { id: 'alpd', status: crashed ? 'info' : 'ok', summary: `not running${after}` };
|
|
257
|
+
return {
|
|
258
|
+
id: 'alpd', status: 'warn', summary: `not running, and left ${stale.map(file => path.basename(file)).join(' and ')} behind${after}`,
|
|
259
|
+
fix: {
|
|
260
|
+
describe: `remove ${stale.join(', ')}`,
|
|
261
|
+
async apply() {
|
|
262
|
+
// Check again: an alpd may have started meanwhile.
|
|
263
|
+
if (lockAlive(await readLock(home))) return 'skipped: alpd started meanwhile';
|
|
264
|
+
for (const file of stale) await unlink(file).catch(() => {});
|
|
265
|
+
return `removed ${stale.length} stale file${stale.length > 1 ? 's' : ''}`;
|
|
266
|
+
},
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Files and directories under ALP_HOME that hold logs, state or settings. */
|
|
272
|
+
async function privateEntries(home) {
|
|
273
|
+
const entries = [home];
|
|
274
|
+
for (const name of ['settings.json', 'alpd.lock', 'alpd.json', 'role-skills.json']) entries.push(path.join(home, name));
|
|
275
|
+
for (const directory of ['state', 'runs', 'logs', 'boards', 'worktrees', 'copies']) {
|
|
276
|
+
const full = path.join(home, directory);
|
|
277
|
+
entries.push(full);
|
|
278
|
+
if (directory === 'worktrees' || directory === 'copies') continue;
|
|
279
|
+
for (const name of await readdir(full).catch(() => [])) entries.push(path.join(full, name));
|
|
280
|
+
}
|
|
281
|
+
return entries;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function permissionsCheck(home) {
|
|
285
|
+
// Windows files have no group/other mode bits to read or tighten; the profile's ACL keeps the home private.
|
|
286
|
+
if (process.platform === 'win32') return { id: 'permissions', status: 'ok', summary: `${home} follows your Windows profile access rules` };
|
|
287
|
+
const open = [];
|
|
288
|
+
for (const entry of await privateEntries(home)) {
|
|
289
|
+
const info = await lstat(entry).catch(() => undefined);
|
|
290
|
+
if (!info || info.isSymbolicLink() || !(info.mode & 0o077)) continue;
|
|
291
|
+
open.push({ entry, mode: info.mode & 0o777, directory: info.isDirectory() });
|
|
292
|
+
}
|
|
293
|
+
if (!open.length) return { id: 'permissions', status: 'ok', summary: `${home} is private to you` };
|
|
294
|
+
return {
|
|
295
|
+
id: 'permissions', status: 'warn',
|
|
296
|
+
summary: `${open.length} entr${open.length > 1 ? 'ies' : 'y'} under ${home} readable by others; they hold task briefs, results and settings`,
|
|
297
|
+
details: open.map(item => `${item.mode.toString(8).padStart(4, '0')} ${item.entry}`),
|
|
298
|
+
fix: {
|
|
299
|
+
describe: 'remove group and other access from them',
|
|
300
|
+
async apply() {
|
|
301
|
+
for (const item of open) await chmod(item.entry, item.mode & 0o700).catch(() => {});
|
|
302
|
+
return `tightened ${open.length} entr${open.length > 1 ? 'ies' : 'y'}`;
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function userSettingsCheck(home) {
|
|
309
|
+
const file = path.join(home, 'settings.json');
|
|
310
|
+
try {
|
|
311
|
+
const text = await readFile(file, 'utf8').catch(error => { if (error.code === 'ENOENT') return undefined; throw error; });
|
|
312
|
+
if (text === undefined) return { id: 'user settings', status: 'ok', summary: `none (${file})` };
|
|
313
|
+
const settings = JSON.parse(text);
|
|
314
|
+
validateUserSettings(settings, file);
|
|
315
|
+
const warnings = settingsWarnings(settings, 'user');
|
|
316
|
+
return warnings.length
|
|
317
|
+
? { id: 'user settings', status: 'warn', summary: `${file}: ${warnings.length} key${warnings.length > 1 ? 's' : ''} ALP ignores`, details: warnings }
|
|
318
|
+
: { id: 'user settings', status: 'ok', summary: file };
|
|
319
|
+
} catch (error) {
|
|
320
|
+
return { id: 'user settings', status: 'fail', summary: `alpd ignores ${file}: ${error.message.replace(`${file}: `, '')}` };
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async function projectChecks(project, home) {
|
|
325
|
+
const checks = [];
|
|
326
|
+
const file = path.join(project, '.alp', 'settings.json');
|
|
327
|
+
let settings;
|
|
328
|
+
try {
|
|
329
|
+
settings = await jsonObject(file, 'INVALID_SETTINGS');
|
|
330
|
+
validateSettings(settings, file);
|
|
331
|
+
const warnings = settingsWarnings(settings, 'project');
|
|
332
|
+
checks.push(warnings.length
|
|
333
|
+
? { id: 'settings', status: 'warn', summary: `${file}: ${warnings.length} key${warnings.length > 1 ? 's' : ''} ALP ignores`, details: warnings }
|
|
334
|
+
: { id: 'settings', status: 'ok', summary: file });
|
|
335
|
+
} catch (error) {
|
|
336
|
+
checks.push({ id: 'settings', status: 'fail', summary: error.message });
|
|
337
|
+
return checks;
|
|
338
|
+
}
|
|
339
|
+
const sources = await agentSources(project, { library: home });
|
|
340
|
+
const agents = [...sources.keys()].sort((a, b) => a.localeCompare(b));
|
|
341
|
+
const broken = [];
|
|
342
|
+
const shadows = [];
|
|
343
|
+
const hooks = new Map();
|
|
344
|
+
// An override replaces the whole agent, so it misses later updates to the one it replaces.
|
|
345
|
+
for (const [agent, { source, overrides }] of sources) if (overrides) shadows.push(`${agent}: the ${source}'s copy replaces the ${overrides === 'builtin' ? 'built-in' : 'library'} agent`);
|
|
346
|
+
for (const agent of agents) {
|
|
347
|
+
try {
|
|
348
|
+
const resolved = await resolveAgent(project, { agent, library: home });
|
|
349
|
+
for (const hook of await loadHooks(resolved)) hooks.set(hook.path, { ...hook, agents: [...(hooks.get(hook.path)?.agents ?? []), agent] });
|
|
350
|
+
for (const skill of resolved.skills) if (!skill.path.startsWith(home + path.sep)) {
|
|
351
|
+
const library = path.join(home, 'skills', skill.name, 'SKILL.md');
|
|
352
|
+
if (await lstat(library).then(() => true, () => false)) shadows.push(`${agent}: ${skill.name} from the project replaces the library's`);
|
|
353
|
+
}
|
|
354
|
+
} catch (error) { broken.push(`${agent}: ${error.message}`); }
|
|
355
|
+
}
|
|
356
|
+
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' });
|
|
357
|
+
else if (broken.length) checks.push({ id: 'agents', status: 'fail', summary: `${broken.length} of ${agents.length} agents cannot start`, details: broken });
|
|
358
|
+
else checks.push({ id: 'agents', status: shadows.length ? 'info' : 'ok', summary: `${agents.length} agents resolve: ${agents.join(', ')}`, ...(shadows.length ? { details: shadows } : {}) });
|
|
359
|
+
if (hooks.size) checks.push(await hooksCheck(project, home, [...hooks.values()]));
|
|
360
|
+
if (settings.defaultAgent && !agents.includes(settings.defaultAgent)) checks.push({ id: 'agents', status: 'fail', summary: `defaultAgent ${settings.defaultAgent} is not an agent of this project` });
|
|
361
|
+
return checks;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** The command a hook starts, when it is a plain program name or path: the first word of its shell command. */
|
|
365
|
+
const program = command => /^\s*([\w./-]+)/.exec(command)?.[1];
|
|
366
|
+
const SHELL_WORDS = new Set(['cd', 'test', '[', 'echo', 'exit', 'true', 'false', 'set', 'export', 'if', 'for', 'while', 'exec', 'env', 'command', 'printf', 'read', 'source', '.']);
|
|
367
|
+
|
|
368
|
+
/** Hooks the agents use: whether the project's may run, and whether their programs exist (ALPD §45). */
|
|
369
|
+
async function hooksCheck(project, home, hooks) {
|
|
370
|
+
const missing = [];
|
|
371
|
+
for (const hook of hooks) {
|
|
372
|
+
const name = program(hook.command);
|
|
373
|
+
if (!name || SHELL_WORDS.has(name)) continue;
|
|
374
|
+
const candidates = name.includes('/') ? [path.resolve(project, name)] : (process.env.PATH ?? '').split(path.delimiter).filter(Boolean).map(directory => path.join(directory, name));
|
|
375
|
+
let found = false;
|
|
376
|
+
for (const candidate of candidates) if (await access(candidate, constants.X_OK).then(() => true, () => false)) { found = true; break; }
|
|
377
|
+
if (!found) missing.push(`${hook.name} (${hook.event}, used by ${hook.agents.join(', ')}): ${name} is not found`);
|
|
378
|
+
}
|
|
379
|
+
const fromProject = hooks.filter(hook => hook.project);
|
|
380
|
+
const trusted = fromProject.length ? await isTrusted(home, project) : true;
|
|
381
|
+
const details = [...missing, ...(!trusted ? [`not trusted yet: ${fromProject.map(hook => hook.name).join(', ')}; alpd asks the first time one runs, or run alp trust`] : [])];
|
|
382
|
+
return {
|
|
383
|
+
id: 'hooks', status: missing.length ? 'warn' : trusted ? 'ok' : 'info',
|
|
384
|
+
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` : ''}`,
|
|
385
|
+
...(details.length ? { details } : {}),
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* ACP providers of the library (ALPD §46): whether their commands exist, and what ALP
|
|
391
|
+
* cannot do for an agent it reaches through ACP.
|
|
392
|
+
*/
|
|
393
|
+
async function providersCheck(home, env) {
|
|
394
|
+
let providers;
|
|
395
|
+
try { providers = await listProviders(home); } catch (error) { return { id: 'providers', status: 'fail', summary: error.message }; }
|
|
396
|
+
if (!providers.length) return undefined;
|
|
397
|
+
const missing = [];
|
|
398
|
+
for (const provider of providers) if (!await executable(provider.command, { ...env, ...provider.env })) missing.push(`${provider.id}: ${provider.command} is not found`);
|
|
399
|
+
return {
|
|
400
|
+
id: 'providers', status: 'warn',
|
|
401
|
+
summary: `${providers.length} ACP provider${providers.length > 1 ? 's' : ''} (${providers.map(provider => provider.id).join(', ')})${missing.length ? `; ${missing.length} cannot start` : ''}`,
|
|
402
|
+
details: [...missing,
|
|
403
|
+
'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',
|
|
404
|
+
'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'],
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* The library's skills against the skill format, in legacy mode: a format problem is a warning
|
|
410
|
+
* (the skill still loads), an unsafe reference or link an error. Nothing is rewritten.
|
|
411
|
+
*/
|
|
412
|
+
async function skillFormatCheck(home) {
|
|
413
|
+
const directory = path.join(home, 'skills');
|
|
414
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
|
|
415
|
+
const failed = [];
|
|
416
|
+
const warned = [];
|
|
417
|
+
let checked = 0;
|
|
418
|
+
for (const entry of entries) {
|
|
419
|
+
// The skills the resolver loads: a plain directory name holding SKILL.md (not .git or notes).
|
|
420
|
+
if ((!entry.isDirectory() && !entry.isSymbolicLink()) || !/^[\w.-]+$/.test(entry.name) || entry.name.startsWith('.')) continue;
|
|
421
|
+
if (!(await lstat(path.join(directory, entry.name, 'SKILL.md')).then(() => true, () => false))) continue;
|
|
422
|
+
checked++;
|
|
423
|
+
try {
|
|
424
|
+
const report = await validateSkill(path.join(directory, entry.name));
|
|
425
|
+
if (!report.ok) failed.push(`${entry.name}: ${report.errors.map(finding => finding.message).join('; ')}`);
|
|
426
|
+
else if (report.warnings.length) warned.push(`${entry.name}: ${report.warnings.map(finding => finding.code).join(', ')}`);
|
|
427
|
+
} catch (error) { failed.push(`${entry.name}: could not be checked: ${error.message}`); }
|
|
428
|
+
}
|
|
429
|
+
if (!checked) return undefined;
|
|
430
|
+
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] };
|
|
431
|
+
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 };
|
|
432
|
+
return { id: 'skill-format', status: 'ok', summary: `the library's skills meet the skill format (${directory})` };
|
|
433
|
+
}
|
|
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 => { if (error.code === 'ENOENT') return undefined; throw error; });
|
|
440
|
+
if (text === undefined) return undefined;
|
|
441
|
+
roles = JSON.parse(text);
|
|
442
|
+
} catch (error) { return { id: 'skills', status: 'fail', summary: `${file}: ${error.message}` }; }
|
|
443
|
+
if (!roles || typeof roles !== 'object' || Array.isArray(roles)) return { id: 'skills', status: 'fail', summary: `${file}: expected an object of role names to skill lists` };
|
|
444
|
+
const missing = [];
|
|
445
|
+
for (const [role, names] of Object.entries(roles)) {
|
|
446
|
+
if (!Array.isArray(names)) { missing.push(`${role}: not a list`); continue; }
|
|
447
|
+
for (const name of names) {
|
|
448
|
+
if (typeof name !== 'string' || !await lstat(path.join(home, 'skills', name, 'SKILL.md')).then(() => true, () => false)) missing.push(`${role}: ${name}`);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return missing.length
|
|
452
|
+
? { id: 'skills', status: 'warn', summary: `${file} lists ${missing.length} skill${missing.length > 1 ? 's' : ''} the library lacks; agents start without them`, details: missing }
|
|
453
|
+
: { id: 'skills', status: 'ok', summary: `the library's skills exist (${file})` };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** The live book alpd continues at start: entries whose project is gone can never continue. */
|
|
457
|
+
async function liveCheck(home, running) {
|
|
458
|
+
const file = path.join(home, 'state', 'live.json');
|
|
459
|
+
let entries;
|
|
460
|
+
try { entries = JSON.parse(await readFile(file, 'utf8')); } catch { return undefined; }
|
|
461
|
+
if (!Array.isArray(entries)) return { id: 'live work', status: 'warn', summary: `${file} is not a list; alpd ignores it` };
|
|
462
|
+
const gone = [];
|
|
463
|
+
for (const entry of entries) {
|
|
464
|
+
if (typeof entry?.project !== 'string' || !await lstat(entry.project).then(() => true, () => false)) gone.push(entry);
|
|
465
|
+
}
|
|
466
|
+
if (!gone.length) return { id: 'live work', status: entries.length && !running ? 'info' : 'ok', summary: entries.length ? `${entries.length} assignment${entries.length > 1 ? 's' : ''} ${running ? 'running' : 'waiting for alpd to continue'}` : 'no running assignments' };
|
|
467
|
+
return {
|
|
468
|
+
id: 'live work', status: 'warn',
|
|
469
|
+
summary: `${gone.length} interrupted assignment${gone.length > 1 ? 's' : ''} belong to projects that no longer exist`,
|
|
470
|
+
details: gone.map(entry => `${entry?.agent} ${entry?.assignmentId} in ${entry?.project}`),
|
|
471
|
+
fix: running ? undefined : {
|
|
472
|
+
describe: `drop them from ${file}, keeping a copy beside it`,
|
|
473
|
+
async apply() {
|
|
474
|
+
const current = JSON.parse(await readFile(file, 'utf8'));
|
|
475
|
+
const ids = new Set(gone.map(entry => entry?.assignmentId));
|
|
476
|
+
const kept = current.filter(entry => !ids.has(entry?.assignmentId));
|
|
477
|
+
// What is dropped stays on disk, so a repair never loses a record.
|
|
478
|
+
await writeFile(`${file}.dropped-${Date.now()}.json`, JSON.stringify(current.filter(entry => ids.has(entry?.assignmentId)), null, 2) + '\n', { mode: 0o600 });
|
|
479
|
+
await writeFile(file, JSON.stringify(kept, null, 2) + '\n', { mode: 0o600 });
|
|
480
|
+
return `dropped ${current.length - kept.length}`;
|
|
481
|
+
},
|
|
482
|
+
},
|
|
483
|
+
...(running ? { hint: 'stop alpd to drop them' } : {}),
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Worktrees git lost track of, and alp/* branches: merged ones are dead weight, unmerged ones hold kept work. */
|
|
488
|
+
async function branchCheck(project, home, run) {
|
|
489
|
+
const git = args => run('git', args, { cwd: project });
|
|
490
|
+
const top = await git(['rev-parse', '--show-toplevel']);
|
|
491
|
+
if (top.code !== 0) return [];
|
|
492
|
+
const checks = [];
|
|
493
|
+
const worktrees = (await git(['worktree', 'list', '--porcelain'])).stdout.split('\n\n').filter(Boolean);
|
|
494
|
+
const prunable = worktrees.filter(block => /^prunable/m.test(block)).map(block => block.match(/^worktree (.*)$/m)?.[1]).filter(Boolean);
|
|
495
|
+
if (prunable.length) checks.push({
|
|
496
|
+
id: 'worktrees', status: 'warn', summary: `git still lists ${prunable.length} worktree${prunable.length > 1 ? 's' : ''} that no longer exist`, details: prunable,
|
|
497
|
+
fix: { describe: 'git worktree prune', async apply() { await git(['worktree', 'prune']); return 'pruned'; } },
|
|
498
|
+
});
|
|
499
|
+
const checkedOut = new Set(worktrees.map(block => block.match(/^branch refs\/heads\/(.*)$/m)?.[1]).filter(Boolean));
|
|
500
|
+
let live = [];
|
|
501
|
+
try { live = JSON.parse(await readFile(path.join(home, 'state', 'live.json'), 'utf8')); } catch {}
|
|
502
|
+
const inUse = new Set([...checkedOut, ...(Array.isArray(live) ? live.map(entry => entry?.worktree?.branch).filter(Boolean) : [])]);
|
|
503
|
+
const branches = (await git(['for-each-ref', '--format=%(refname:short)', 'refs/heads/alp/'])).stdout.split('\n').filter(Boolean);
|
|
504
|
+
if (!branches.length) return checks;
|
|
505
|
+
const merged = new Set((await git(['branch', '--format=%(refname:short)', '--merged', 'HEAD', '--list', 'alp/*'])).stdout.split('\n').filter(Boolean));
|
|
506
|
+
const spare = branches.filter(branch => merged.has(branch) && !inUse.has(branch));
|
|
507
|
+
const kept = branches.filter(branch => !merged.has(branch) && !inUse.has(branch));
|
|
508
|
+
if (spare.length) checks.push({
|
|
509
|
+
id: 'branches', status: 'warn', summary: `${spare.length} alp/* branch${spare.length > 1 ? 'es are' : ' is'} already merged into HEAD`, details: spare,
|
|
510
|
+
fix: {
|
|
511
|
+
describe: `delete ${spare.length > 1 ? 'them' : 'it'} with git branch -d`,
|
|
512
|
+
async apply() {
|
|
513
|
+
let deleted = 0;
|
|
514
|
+
for (const branch of spare) if ((await git(['branch', '-d', branch])).code === 0) deleted++;
|
|
515
|
+
return `deleted ${deleted}`;
|
|
516
|
+
},
|
|
517
|
+
},
|
|
518
|
+
});
|
|
519
|
+
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 });
|
|
520
|
+
if (!spare.length && !kept.length) checks.push({ id: 'branches', status: 'ok', summary: `${branches.length} alp/* branch${branches.length > 1 ? 'es' : ''} in use` });
|
|
521
|
+
return checks;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** A check with every line scrubbed: a message may quote what a runtime, a file or a user wrote. */
|
|
525
|
+
function scrubCheck(check) {
|
|
526
|
+
const clean = text => scrubText(text, { max: 1000 });
|
|
527
|
+
return {
|
|
528
|
+
...check, summary: clean(check.summary),
|
|
529
|
+
...(check.details ? { details: check.details.map(clean) } : {}),
|
|
530
|
+
...(check.hint ? { hint: clean(check.hint) } : {}),
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Runs every check. `project` is an ALP project root or undefined; `sandbox` says whether
|
|
536
|
+
* Claude can sandbox Bash here (undefined when unknown); `daemonEntry` is alpd's path.
|
|
537
|
+
*/
|
|
538
|
+
export { runCommand };
|
|
539
|
+
|
|
540
|
+
/** The state's schema (ALPD §68), and a migration or a restore cut short. Reads only. */
|
|
541
|
+
async function schemaChecks(home) {
|
|
542
|
+
let info;
|
|
543
|
+
try { info = await readStateSchema(home); }
|
|
544
|
+
catch (error) { return [{ id: 'schema', status: 'fail', summary: `${error.message} (ALP_${error.code ?? 'STATE_UNUSABLE'})` }]; }
|
|
545
|
+
const checks = [info.schema > STATE_SCHEMA
|
|
546
|
+
? { 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' }
|
|
547
|
+
: { 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}` }];
|
|
548
|
+
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' });
|
|
549
|
+
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' });
|
|
550
|
+
return checks;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** Checks whether directory `target` is inside directory `container`. */
|
|
554
|
+
function isInside(target, container) {
|
|
555
|
+
const resolve = directory => {
|
|
556
|
+
let current = path.resolve(directory);
|
|
557
|
+
let suffix = '';
|
|
558
|
+
for (;;) {
|
|
559
|
+
try { return path.join(realpathSync(current), suffix); }
|
|
560
|
+
catch {
|
|
561
|
+
const parent = path.dirname(current);
|
|
562
|
+
if (parent === current) return path.join(current, suffix);
|
|
563
|
+
suffix = path.join(path.basename(current), suffix);
|
|
564
|
+
current = parent;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
const resolvedTarget = resolve(target);
|
|
569
|
+
const resolvedContainer = resolve(container);
|
|
570
|
+
const relative = path.relative(resolvedContainer, resolvedTarget);
|
|
571
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Checks where ALP_HOME sits: staging and state live there (§12.6). Sandboxed sessions
|
|
576
|
+
* can write the temp directory and their workspace, so staged copies inside either could
|
|
577
|
+
* be modified by a sandboxed tool before alpd reads them (ALP_ATTACHMENT_STAGE_EXPOSED).
|
|
578
|
+
*/
|
|
579
|
+
async function homeLocationCheck(home, project) {
|
|
580
|
+
if (process.platform === 'win32' || !home) return { id: 'home', status: 'ok', summary: home ?? '' };
|
|
581
|
+
if (project && isInside(home, project)) {
|
|
582
|
+
return {
|
|
583
|
+
id: 'home', status: 'warn',
|
|
584
|
+
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)`,
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
const inTmp = isInside(home, os.tmpdir()) || isInside(home, '/tmp');
|
|
588
|
+
if (inTmp) {
|
|
589
|
+
return {
|
|
590
|
+
id: 'home', status: 'warn',
|
|
591
|
+
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)`,
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
return { id: 'home', status: 'ok', summary: home };
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const GIB = 1024 ** 3;
|
|
598
|
+
const formatSize = bytes => bytes >= GIB ? `${(bytes / GIB).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`;
|
|
599
|
+
|
|
600
|
+
/** Entries of `directory` whose names start with `prefix`, as full paths; none when it cannot be read. */
|
|
601
|
+
async function entries(directory, prefix = '') {
|
|
602
|
+
const names = await readdir(directory).catch(() => []);
|
|
603
|
+
return names.filter(name => name.startsWith(prefix)).map(name => path.join(directory, name));
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* What a path in a suggested command may hold, on every platform: ASCII letters and digits,
|
|
608
|
+
* `. _ - / \\ :` and a space (common in Windows user folders; literal inside single quotes in sh
|
|
609
|
+
* and PowerShell alike). Nothing else: no quote of any kind (PowerShell ends a single-quoted string
|
|
610
|
+
* at ' and at four typographic quotes), no shell syntax, no control, format or non-ASCII character.
|
|
611
|
+
*/
|
|
612
|
+
const QUOTABLE = /^[A-Za-z0-9._\-/\\: ]+$/;
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* A path for a suggested command (POSIX sh, or PowerShell on win32), in single quotes; undefined
|
|
616
|
+
* unless it is absolute (so it cannot read as an option) and every character is QUOTABLE, in which
|
|
617
|
+
* case nothing in it needs escaping. A path that is not gets no command at all.
|
|
618
|
+
*/
|
|
619
|
+
export function shellQuote(text, platform = process.platform) {
|
|
620
|
+
const value = String(text);
|
|
621
|
+
const absolute = platform === 'win32' ? path.win32.isAbsolute(value) : path.posix.isAbsolute(value);
|
|
622
|
+
return absolute && QUOTABLE.test(value) ? `'${value}'` : undefined;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* A path as alp doctor prints it: control, format and unusual space characters escaped as \u{hex},
|
|
627
|
+
* so it stays one line and reads as it is. A backslash is doubled, so the escaping is injective:
|
|
628
|
+
* a path that holds the text \u{a} prints as \\u{a}, never as a path with a newline would.
|
|
629
|
+
*/
|
|
630
|
+
export const printable = text => String(text).replace(/\\|[\p{C}\p{Zl}\p{Zp}]|(?! )\p{Zs}/gu, char => char === '\\' ? '\\\\' : `\\u{${char.codePointAt(0).toString(16)}}`);
|
|
631
|
+
|
|
632
|
+
/** Why a clean and pushed leftover has no command. */
|
|
633
|
+
const 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';
|
|
634
|
+
|
|
635
|
+
/** What each leftover state means, in the order alp doctor lists them. */
|
|
636
|
+
export const LEFTOVER_STATES = {
|
|
637
|
+
'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)',
|
|
638
|
+
dirty: 'dirty (uncommitted changes or untracked files, or a merge or rebase in progress; keep)',
|
|
639
|
+
'local-only': 'local-only data (ignored files such as .env, local config, node_modules or build output, which exist only here; keep)',
|
|
640
|
+
unpushed: 'unpushed (commits, or for a clone tags, branches or other refs, that no remote-tracking ref mirrors; keep)',
|
|
641
|
+
'in-use': 'in use (a running assignment, a retained result, this shell, or changed in the last day; keep)',
|
|
642
|
+
unknown: 'unknown (not a git checkout of its own, or git could not tell; check by hand)',
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
/** Paths ALP still owns: running assignments' worktrees and the retained results' checkouts. */
|
|
646
|
+
async function ownedPaths(home) {
|
|
647
|
+
const owned = new Set();
|
|
648
|
+
const read = async file => JSON.parse(await readFile(file, 'utf8'));
|
|
649
|
+
const live = await read(path.join(home, 'state', 'live.json')).catch(() => []);
|
|
650
|
+
for (const entry of Array.isArray(live) ? live : []) if (typeof entry?.worktree?.path === 'string') owned.add(realpathOr(entry.worktree.path));
|
|
651
|
+
const ledger = await read(path.join(home, 'state', 'assignment-results.json')).catch(() => undefined);
|
|
652
|
+
for (const entry of Array.isArray(ledger?.results) ? ledger.results : []) {
|
|
653
|
+
if (entry?.handled) continue;
|
|
654
|
+
for (const where of [entry?.worktree, entry?.checkout]) if (typeof where === 'string') owned.add(realpathOr(where));
|
|
655
|
+
}
|
|
656
|
+
return owned;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** Why a leftover alp doctor had no time left for is unknown. */
|
|
660
|
+
const NOT_CHECKED = 'not checked: alp doctor ran out of time; run it again, or check by hand';
|
|
661
|
+
|
|
662
|
+
/** Thrown when the classifying deadline passed: the leftover is unknown, not checked. */
|
|
663
|
+
class OutOfTime extends Error {}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Classifies one leftover directory (t-e80a) without changing it: clean-pushed when it is a git
|
|
667
|
+
* checkout of its own with no changes, no untracked files, no ignored files at all, no
|
|
668
|
+
* hidden index state or submodules, no operation in progress, and a HEAD (for a standalone clone:
|
|
669
|
+
* every ref, including tags and a stash) that a remote-tracking branch already holds. "Pushed" is
|
|
670
|
+
* what this clone last fetched. Anything git cannot answer is unknown. Each git command ends by
|
|
671
|
+
* `deadline`; past it the leftover is unknown, not checked.
|
|
672
|
+
*/
|
|
673
|
+
async function classifyLeftover(directory, { run, env, owned, here, recentMs, deadline, platform }) {
|
|
674
|
+
const real = realpathOr(directory);
|
|
675
|
+
const inside = (outer, inner) => inner === outer || inner.startsWith(outer.endsWith(path.sep) ? outer : outer + path.sep);
|
|
676
|
+
if ([...owned].some(owner => inside(real, owner) || inside(owner, real)) || inside(real, here)) return { path: directory, state: 'in-use' };
|
|
677
|
+
const git = async args => {
|
|
678
|
+
const left = deadline - Date.now();
|
|
679
|
+
if (left <= 0) throw new OutOfTime();
|
|
680
|
+
const result = await run('git', ['-C', directory, ...args], { env, timeoutMs: Math.min(10_000, left) });
|
|
681
|
+
// A command cut off by the deadline says nothing about the leftover.
|
|
682
|
+
if (Date.now() >= deadline) throw new OutOfTime();
|
|
683
|
+
return result;
|
|
684
|
+
};
|
|
685
|
+
const unknown = reason => ({ path: directory, state: 'unknown', reason });
|
|
686
|
+
// The top of every git checkout holds .git (a directory, or a file in a linked worktree): without it, no git is needed.
|
|
687
|
+
if (!await lstat(path.join(directory, '.git')).then(() => true, () => false)) return unknown('not a git checkout');
|
|
688
|
+
const where = await git(['rev-parse', '--show-toplevel', '--absolute-git-dir', '--git-common-dir']);
|
|
689
|
+
if (where.code !== 0) return unknown('not a git checkout');
|
|
690
|
+
const [top, gitDir, common] = where.stdout.trim().split('\n');
|
|
691
|
+
if (!top || !gitDir || !common || realpathOr(top) !== real) return unknown('not the top of a git checkout');
|
|
692
|
+
const commonDir = realpathOr(path.resolve(top, common));
|
|
693
|
+
// Untracked files are listed one by one whatever status.showUntrackedFiles says, and ignored ones
|
|
694
|
+
// too: git status alone does not show an ignored .env, which exists nowhere else. Any ignored
|
|
695
|
+
// file, node_modules and build output included, keeps the checkout: removing it loses them.
|
|
696
|
+
// git lists an ignored directory as one entry.
|
|
697
|
+
const status = await git(['-c', 'status.showUntrackedFiles=all', 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignored=matching']);
|
|
698
|
+
if (status.code !== 0) return unknown('git status failed');
|
|
699
|
+
const rows = status.stdout.split('\0').filter(Boolean);
|
|
700
|
+
if (rows.some(row => !row.startsWith('!! '))) return { path: directory, state: 'dirty' };
|
|
701
|
+
const ignored = rows.map(row => row.slice(3));
|
|
702
|
+
if (ignored.length) return { path: directory, state: 'local-only', reason: `ignored files: ${ignored.slice(0, 3).join(', ')}${ignored.length > 3 ? `, … ${ignored.length - 3} more` : ''}` };
|
|
703
|
+
// git status cannot see a change to a file marked assume-unchanged or skip-worktree, nor inside a submodule.
|
|
704
|
+
const index = await git(['ls-files', '-z', '-v', '--stage']);
|
|
705
|
+
if (index.code !== 0) return unknown('git could not list its index');
|
|
706
|
+
const tracked = index.stdout.split('\0').filter(Boolean);
|
|
707
|
+
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');
|
|
708
|
+
if (tracked.some(row => row.slice(2).startsWith('160000 '))) return unknown('it has submodules, whose own changes and commits this check does not read');
|
|
709
|
+
for (const name of ['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-merge', 'rebase-apply']) {
|
|
710
|
+
if (await lstat(path.join(gitDir, name)).then(() => true, () => false)) return { path: directory, state: 'dirty' };
|
|
711
|
+
}
|
|
712
|
+
// A worktree someone made by hand moments ago (a peer's, which ALP does not track) looks clean and pushed: recent work stays.
|
|
713
|
+
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))));
|
|
714
|
+
if (Date.now() - touched < recentMs) return { path: directory, state: 'in-use', reason: 'changed in the last day' };
|
|
715
|
+
const linked = realpathOr(gitDir) !== commonDir;
|
|
716
|
+
// A linked worktree's branches live in its main repository and stay there when it goes; a clone
|
|
717
|
+
// holds its own refs: every branch, tag, note and stash (--all), all of which must be on a remote.
|
|
718
|
+
const ahead = await git(['rev-list', '-n', '1', ...(linked ? ['HEAD'] : ['HEAD', '--all']), '--not', '--remotes']);
|
|
719
|
+
if (ahead.code !== 0) return unknown('git could not compare HEAD with the remotes');
|
|
720
|
+
if (ahead.stdout.trim()) return { path: directory, state: 'unpushed' };
|
|
721
|
+
if (!linked) {
|
|
722
|
+
// A clone's refs go with it, and a tag (or note, or other ref) on a pushed commit is not seen
|
|
723
|
+
// above. Without a fetch no one can tell which tags a remote has, so every local ref must be
|
|
724
|
+
// mirrored by a remote-tracking ref: a branch by name (its commits are checked above), any
|
|
725
|
+
// other ref by name and object (refs/tags/v1 by refs/remotes/<remote>/tags/v1).
|
|
726
|
+
const refs = await git(['for-each-ref', '--format=%(objectname) %(refname)']);
|
|
727
|
+
if (refs.code !== 0) return unknown('git could not list its refs');
|
|
728
|
+
const all = refs.stdout.split('\n').filter(Boolean).map(line => { const at = line.indexOf(' '); return [line.slice(at + 1), line.slice(0, at)]; });
|
|
729
|
+
// Matched by full ref name, refs/remotes/<remote>/<name> for a configured remote, so a branch
|
|
730
|
+
// x is not taken for origin/feature/x (nor for a remote named feature's x unless feature is one).
|
|
731
|
+
const remotes = await git(['remote']);
|
|
732
|
+
if (remotes.code !== 0) return unknown('git could not list its remotes');
|
|
733
|
+
const remoteNames = remotes.stdout.split('\n').map(line => line.trim()).filter(Boolean);
|
|
734
|
+
const mirrors = new Map(all.filter(([name]) => name.startsWith('refs/remotes/')));
|
|
735
|
+
const mirrored = ([name, object]) => {
|
|
736
|
+
const branch = name.startsWith('refs/heads/');
|
|
737
|
+
const rest = branch ? name.slice('refs/heads/'.length) : name.slice('refs/'.length);
|
|
738
|
+
return remoteNames.some(remote => {
|
|
739
|
+
const target = mirrors.get(`refs/remotes/${remote}/${rest}`);
|
|
740
|
+
return target !== undefined && (branch || target === object);
|
|
741
|
+
});
|
|
742
|
+
};
|
|
743
|
+
const local = all.filter(entry => !entry[0].startsWith('refs/remotes/') && !mirrored(entry));
|
|
744
|
+
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 ? `, … ${local.length - 3} more` : ''}` };
|
|
745
|
+
}
|
|
746
|
+
const list = await git(['worktree', 'list', '--porcelain']);
|
|
747
|
+
if (list.code !== 0) return unknown('git could not list its worktrees');
|
|
748
|
+
if (!linked) {
|
|
749
|
+
// Removing a clone removes the repository of every worktree made from it.
|
|
750
|
+
if ((list.stdout.match(/^worktree /gm) ?? []).length > 1) return { path: directory, state: 'in-use', reason: 'other worktrees use its repository' };
|
|
751
|
+
const quoted = shellQuote(directory, platform);
|
|
752
|
+
if (quoted === undefined) return { path: directory, state: 'clean-pushed', reason: UNQUOTABLE };
|
|
753
|
+
return { path: directory, state: 'clean-pushed', command: platform === 'win32' ? `Remove-Item -LiteralPath ${quoted} -Recurse -Force` : `rm -rf ${quoted}` };
|
|
754
|
+
}
|
|
755
|
+
const main = list.stdout.match(/^worktree (.*)$/m)?.[1];
|
|
756
|
+
if (!main) return unknown('git could not name its main worktree');
|
|
757
|
+
const [quotedMain, quoted] = [shellQuote(main, platform), shellQuote(directory, platform)];
|
|
758
|
+
if (quotedMain === undefined || quoted === undefined) return { path: directory, state: 'clean-pushed', reason: UNQUOTABLE };
|
|
759
|
+
return { path: directory, state: 'clean-pushed', command: `git -C ${quotedMain} worktree remove ${quoted}` };
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* Classifies leftovers eight at a time, within `budgetMs` in all: a machine can hold thousands
|
|
764
|
+
* (old test homes in the temp directory), and doctor must still answer. The deadline is hard:
|
|
765
|
+
* each git command is cut off when it comes, and doctor stops waiting then. Those not finished
|
|
766
|
+
* by then are unknown.
|
|
767
|
+
*/
|
|
768
|
+
async function classifyLeftovers(paths, { budgetMs, ...options }) {
|
|
769
|
+
const results = paths.map(directory => ({ path: directory, state: 'unknown', reason: NOT_CHECKED }));
|
|
770
|
+
const deadline = Date.now() + budgetMs;
|
|
771
|
+
let next = 0, done = false;
|
|
772
|
+
const worker = async () => {
|
|
773
|
+
while (!done && next < paths.length && Date.now() < deadline) {
|
|
774
|
+
const index = next++;
|
|
775
|
+
try {
|
|
776
|
+
const result = await classifyLeftover(paths[index], { ...options, deadline });
|
|
777
|
+
if (!done && Date.now() < deadline) results[index] = result;
|
|
778
|
+
} catch (error) { if (!(error instanceof OutOfTime)) results[index] = { path: paths[index], state: 'unknown', reason: `could not check: ${error?.message ?? error}` }; }
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
// A file system call that hangs (a stale network mount) is not cut off by a command timeout: stop waiting at the deadline.
|
|
782
|
+
let timer;
|
|
783
|
+
const expired = new Promise(resolve => { timer = setTimeout(resolve, Math.max(0, budgetMs)); });
|
|
784
|
+
await Promise.race([Promise.all(Array.from({ length: Math.min(8, paths.length) }, worker)), expired]);
|
|
785
|
+
clearTimeout(timer);
|
|
786
|
+
done = true;
|
|
787
|
+
return results;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/** How many suggested commands the text output shows; --json lists every one. */
|
|
791
|
+
const SHOWN_COMMANDS = 20;
|
|
792
|
+
|
|
793
|
+
/**
|
|
794
|
+
* Free space where ALP_HOME lives (t-2831), and what earlier runs left that takes room:
|
|
795
|
+
* worktrees under ALP_HOME/worktrees and alp-* directories in the temp directory. When
|
|
796
|
+
* the disk fills, alpd pauses work instead of stopping; this says so before it happens.
|
|
797
|
+
* Nothing is deleted, by --fix either: a leftover may hold someone's uncommitted work.
|
|
798
|
+
* Each leftover is classified (t-e80a): clean and pushed, dirty, local-only data, unpushed, in use, or
|
|
799
|
+
* unknown; only a clean and pushed one gets a command, for the user to run by hand.
|
|
800
|
+
* Classifying stops after `classifyMs` (10 s); what it did not reach is unknown. A clean one
|
|
801
|
+
* changed within `recentMs` (a day) is in use: someone may have just started in it.
|
|
802
|
+
*/
|
|
803
|
+
export async function diskCheck(home, { run = runCommand, env = process.env, free, tempDirs = [...new Set([os.tmpdir(), ...(process.platform === 'win32' ? [] : ['/tmp'])])], cwd = process.cwd(), classifyMs = 10_000, recentMs = 24 * 60 * 60 * 1000, platform = process.platform } = {}) {
|
|
804
|
+
let bytes = free;
|
|
805
|
+
if (bytes === undefined) {
|
|
806
|
+
try { const info = await statfs(home); bytes = Number(info.bavail) * Number(info.bsize); } catch {}
|
|
807
|
+
}
|
|
808
|
+
const worktrees = await entries(path.join(home, 'worktrees'));
|
|
809
|
+
const temp = [];
|
|
810
|
+
for (const directory of tempDirs) {
|
|
811
|
+
for (const entry of await entries(directory, 'alp-')) {
|
|
812
|
+
const info = await lstat(entry).catch(() => undefined);
|
|
813
|
+
if (info?.isDirectory() && !temp.includes(realpathOr(entry))) temp.push(realpathOr(entry));
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
/** Kilobytes du counts under the paths; undefined when du is missing, slow or fails. */
|
|
817
|
+
async function size(paths) {
|
|
818
|
+
if (!paths.length) return 0;
|
|
819
|
+
if (process.platform === 'win32') return undefined;
|
|
820
|
+
const result = await run('du', ['-sk', ...paths], { env, timeoutMs: 20_000 });
|
|
821
|
+
if (result.code !== 0 && !result.stdout) return undefined;
|
|
822
|
+
const total = result.stdout.split('\n').reduce((sum, line) => sum + (Number(line.split(/\s+/)[0]) || 0), 0);
|
|
823
|
+
return total * 1024;
|
|
824
|
+
}
|
|
825
|
+
// git must answer about each leftover itself, not about a repository the caller's environment names,
|
|
826
|
+
// and only read: GIT_OPTIONAL_LOCKS=0 keeps git status from refreshing the index of a worktree in use.
|
|
827
|
+
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' };
|
|
828
|
+
const groups = [[`${path.join(home, 'worktrees')}`, worktrees], [`${tempDirs.map(directory => path.join(directory, 'alp-*')).join(', ')}`, temp]].filter(([, paths]) => paths.length);
|
|
829
|
+
// Sizing and classifying run side by side: du alone can take many seconds over thousands of leftovers.
|
|
830
|
+
const [sizes, leftovers] = await Promise.all([
|
|
831
|
+
Promise.all(groups.map(([, paths]) => size(paths))),
|
|
832
|
+
ownedPaths(home).then(owned => classifyLeftovers([...new Set([...worktrees, ...temp])], { run, env: gitEnv, owned, here: realpathOr(cwd), budgetMs: classifyMs, recentMs, platform })),
|
|
833
|
+
]);
|
|
834
|
+
const details = groups.map(([label, paths], index) => `${paths.length} left in ${label}${sizes[index] === undefined ? '' : `, ${formatSize(sizes[index])}`}`);
|
|
835
|
+
for (const [state, meaning] of Object.entries(LEFTOVER_STATES)) {
|
|
836
|
+
const count = leftovers.filter(entry => entry.state === state).length;
|
|
837
|
+
if (count) details.push(`${count} ${meaning}`);
|
|
838
|
+
}
|
|
839
|
+
const unchecked = leftovers.filter(entry => entry.reason === NOT_CHECKED).length;
|
|
840
|
+
if (unchecked) details.push(` ${unchecked} of the unknown were not checked within ${classifyMs < 1000 ? `${classifyMs} ms` : `${Math.round(classifyMs / 1000)} s`}`);
|
|
841
|
+
// A clean and pushed leftover whose path no command can safely carry is listed by its path alone,
|
|
842
|
+
// as a shell comment: pasted with the rest, it runs nothing.
|
|
843
|
+
const commands = leftovers.filter(entry => entry.state === 'clean-pushed').map(entry => entry.command ?? `# remove by hand after checking (no safe command): ${printable(entry.path)}`);
|
|
844
|
+
for (const command of commands.slice(0, SHOWN_COMMANDS)) details.push(` ${command}`);
|
|
845
|
+
if (commands.length > SHOWN_COMMANDS) details.push(` … ${commands.length - SHOWN_COMMANDS} more; alp doctor --json lists every one`);
|
|
846
|
+
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.' : undefined;
|
|
847
|
+
const where = bytes === undefined ? 'free space unknown' : `${formatSize(bytes)} free`;
|
|
848
|
+
// Leftovers never change the status: some may be live.
|
|
849
|
+
const status = bytes !== undefined && bytes < 2 * GIB ? 'warn' : 'ok';
|
|
850
|
+
const summary = bytes !== undefined && bytes < 2 * GIB
|
|
851
|
+
? `${where} where ALP_HOME lives; when the disk is full, alpd pauses all work until space returns`
|
|
852
|
+
: `${where} where ALP_HOME lives`;
|
|
853
|
+
return { id: 'disk', status, summary, ...(details.length ? { details } : {}), ...(hint ? { hint } : {}), ...(leftovers.length ? { leftovers } : {}) };
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
function realpathOr(file) {
|
|
857
|
+
try { return realpathSync(file); } catch { return file; }
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
export async function diagnose({ home, project, env = process.env, run = runCommand, sandbox, daemonEntry, timeoutMs = 3000 } = {}) {
|
|
861
|
+
const checks = [];
|
|
862
|
+
if (daemonEntry) {
|
|
863
|
+
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` })));
|
|
864
|
+
}
|
|
865
|
+
checks.push(...await runtimeChecks({ env, run }));
|
|
866
|
+
checks.push(await homeLocationCheck(home, project));
|
|
867
|
+
if (home) checks.push(await diskCheck(home, { run, env }));
|
|
868
|
+
const daemon = await daemonCheck(home);
|
|
869
|
+
checks.push(daemon);
|
|
870
|
+
const service = await serviceCheck(home, env);
|
|
871
|
+
if (service) checks.push(service);
|
|
872
|
+
const running = daemon.status === 'ok' && daemon.summary.startsWith('running');
|
|
873
|
+
checks.push(...await daemonHealthChecks(await readLock(home), timeoutMs));
|
|
874
|
+
checks.push(await stateCheck(home));
|
|
875
|
+
const schema = await schemaChecks(home);
|
|
876
|
+
checks.push(...schema);
|
|
877
|
+
// State an ALP cannot read is left alone, by --fix too.
|
|
878
|
+
const unreadable = schema.some(check => check.id === 'schema' && check.status === 'fail');
|
|
879
|
+
checks.push(...await logChecks(home, running));
|
|
880
|
+
const failedSessions = await failedSessionsCheck(home);
|
|
881
|
+
if (failedSessions) checks.push(failedSessions);
|
|
882
|
+
if (sandbox !== undefined) checks.push(sandbox
|
|
883
|
+
? { id: 'sandbox', status: 'ok', summary: 'Claude sessions run Bash in an OS sandbox that holds their mode' }
|
|
884
|
+
: { 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` });
|
|
885
|
+
checks.push(await permissionsCheck(home));
|
|
886
|
+
checks.push(await userSettingsCheck(home));
|
|
887
|
+
const skills = await librarySkillsCheck(home);
|
|
888
|
+
if (skills) checks.push(skills);
|
|
889
|
+
const skillFormat = await skillFormatCheck(home);
|
|
890
|
+
if (skillFormat) checks.push(skillFormat);
|
|
891
|
+
const providers = await providersCheck(home, env);
|
|
892
|
+
if (providers) checks.push(providers);
|
|
893
|
+
const live = await liveCheck(home, running);
|
|
894
|
+
if (live && unreadable) delete live.fix;
|
|
895
|
+
if (live) checks.push(live);
|
|
896
|
+
if (project) {
|
|
897
|
+
checks.push(...await projectChecks(project, home));
|
|
898
|
+
checks.push(...await branchCheck(project, home, run));
|
|
899
|
+
}
|
|
900
|
+
return checks.map(scrubCheck);
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** Applies the fixes of the given checks in order; returns what each did. */
|
|
904
|
+
export async function repair(checks) {
|
|
905
|
+
const done = [];
|
|
906
|
+
for (const check of checks) {
|
|
907
|
+
if (!check.fix) continue;
|
|
908
|
+
try { done.push({ id: check.id, result: await check.fix.apply() }); }
|
|
909
|
+
catch (error) { done.push({ id: check.id, result: `failed: ${error.message}` }); }
|
|
910
|
+
}
|
|
911
|
+
return done;
|
|
912
|
+
}
|