@anhlp/alp-client 0.0.0-beta.2 → 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/README.md +23 -1
- package/dist/acp-probe.d.ts +3 -2
- package/dist/acp-probe.js +11 -2
- package/dist/antigravity-probe.d.ts +1 -2
- package/dist/antigravity-probe.js +11 -5
- package/dist/command.js +3 -1
- package/dist/doctor.d.ts +8 -0
- package/dist/doctor.js +276 -13
- package/dist/index.d.ts +123 -8
- package/dist/index.js +332 -52
- package/dist/integration-lock.d.ts +37 -0
- package/dist/integration-lock.js +199 -0
- package/dist/mcp-probe.js +1 -1
- package/dist/portable.d.ts +3 -1
- package/dist/portable.js +11 -2
- package/dist/render.js +3 -0
- package/dist/rpc/handshake.d.ts +6 -1
- package/dist/rpc/handshake.js +4 -2
- 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/service.d.ts +2 -2
- package/dist/service.js +3 -1
- package/dist/setup.d.ts +7 -1
- package/dist/setup.js +159 -32
- package/dist/supervise.d.ts +3 -1
- package/dist/supervise.js +26 -16
- package/package.json +11 -3
- package/src/acp-probe.js +10 -3
- package/src/antigravity-probe.js +12 -5
- package/src/command.js +3 -1
- package/src/doctor.d.ts +8 -0
- package/src/doctor.js +345 -3
- package/src/index.js +411 -55
- package/src/integration-lock.js +203 -0
- package/src/mcp-probe.js +1 -1
- package/src/portable.js +4 -1
- package/src/render.js +3 -0
- package/src/rpc/handshake.js +7 -2
- package/src/rpc/registry.js +229 -0
- package/src/rpc/terminal-directory.js +61 -0
- package/src/service.js +7 -3
- package/src/setup.js +201 -35
- package/src/supervise.d.ts +3 -1
- package/src/supervise.js +31 -19
package/dist/supervise.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export function holdDaemon(home: string, by?: string): Promise<void>;
|
|
2
2
|
export function releaseHold(home: string): Promise<void>;
|
|
3
3
|
export function daemonHeld(home: string): Promise<boolean>;
|
|
4
|
-
export function startDaemon(options: { home: string; entry?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number }): Promise<string>;
|
|
4
|
+
export function startDaemon(options: { home: string; entry?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number; signal?: AbortSignal }): Promise<string>;
|
|
5
5
|
export function superviseDaemon(options: {
|
|
6
6
|
home: string;
|
|
7
7
|
entry?: string | (() => string | undefined);
|
|
@@ -9,4 +9,6 @@ export function superviseDaemon(options: {
|
|
|
9
9
|
intervalMs?: number;
|
|
10
10
|
misses?: number;
|
|
11
11
|
log?: (message: string) => void;
|
|
12
|
+
/** Who keeps alpd up, for the log: "alpd started with <by>". */
|
|
13
|
+
by?: string;
|
|
12
14
|
}): (() => Promise<void>) & { started: Promise<void> };
|
package/dist/supervise.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// packages/client/src/supervise.js
|
|
2
2
|
import { mkdir, unlink, writeFile, stat } from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
|
-
import { ensureDaemon, lockAlive, readLock } from "./index.js";
|
|
4
|
+
import { daemonStartTimeoutMs, ensureDaemon, lockAlive, readLock, withDaemonLifecycle } from "./index.js";
|
|
5
5
|
import { installedProgram, serviceFor, startService } from "./service.js";
|
|
6
6
|
var holdFile = (home) => path.join(home, "state", "alpd.held");
|
|
7
7
|
async function holdDaemon(home, by = "alp daemon stop") {
|
|
@@ -15,33 +15,43 @@ async function releaseHold(home) {
|
|
|
15
15
|
async function daemonHeld(home) {
|
|
16
16
|
return stat(holdFile(home)).then(() => true, () => false);
|
|
17
17
|
}
|
|
18
|
-
async function whenReady(home, timeoutMs) {
|
|
18
|
+
async function whenReady(home, timeoutMs, signal) {
|
|
19
19
|
const deadline = Date.now() + timeoutMs;
|
|
20
20
|
while (Date.now() < deadline) {
|
|
21
|
+
signal?.throwIfAborted();
|
|
21
22
|
const lock = await readLock(home);
|
|
22
23
|
if (lockAlive(lock) && lock.ready) return lock.socket;
|
|
23
24
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
24
25
|
}
|
|
25
26
|
throw new Error(`alpd did not become ready within ${timeoutMs / 1e3} s; see ${path.join(home, "logs")}`);
|
|
26
27
|
}
|
|
27
|
-
async function startDaemon({ home, entry, env = process.env, timeoutMs =
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
await
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
28
|
+
async function startDaemon({ home, entry, env = process.env, timeoutMs = daemonStartTimeoutMs(env), automatic = false, signal }) {
|
|
29
|
+
return withDaemonLifecycle(home, "start", async () => {
|
|
30
|
+
signal?.throwIfAborted();
|
|
31
|
+
if (automatic) {
|
|
32
|
+
if (await daemonHeld(home)) return;
|
|
33
|
+
} else await releaseHold(home);
|
|
34
|
+
const lock = await readLock(home);
|
|
35
|
+
signal?.throwIfAborted();
|
|
36
|
+
if (lockAlive(lock)) return lock.ready ? lock.socket : whenReady(home, timeoutMs, signal);
|
|
37
|
+
const service = serviceFor({ home, env });
|
|
38
|
+
if (service && await installedProgram(service)) {
|
|
39
|
+
signal?.throwIfAborted();
|
|
40
|
+
await startService(service);
|
|
41
|
+
return whenReady(home, timeoutMs, signal);
|
|
42
|
+
}
|
|
43
|
+
return ensureDaemon({ home, entry, env, timeoutMs, lifecycleLocked: true, signal });
|
|
44
|
+
}, { signal });
|
|
37
45
|
}
|
|
38
46
|
function superviseDaemon({ home, entry, env = process.env, intervalMs = 5e3, misses = 2, log = () => {
|
|
39
|
-
} }) {
|
|
47
|
+
}, by }) {
|
|
40
48
|
let stopped = false;
|
|
41
49
|
let missed = 0;
|
|
42
50
|
let starting;
|
|
43
|
-
const start = (reason) => {
|
|
44
|
-
starting ??= startDaemon({ home, entry: typeof entry === "function" ? entry() : entry, env
|
|
51
|
+
const start = (reason, automatic = true) => {
|
|
52
|
+
starting ??= startDaemon({ home, entry: typeof entry === "function" ? entry() : entry, env, automatic }).then((socket) => {
|
|
53
|
+
if (socket) log(`alpd ${reason}`);
|
|
54
|
+
}, (error) => log(`could not start alpd: ${error?.message ?? error}`)).finally(() => {
|
|
45
55
|
starting = void 0;
|
|
46
56
|
missed = 0;
|
|
47
57
|
});
|
|
@@ -59,7 +69,7 @@ function superviseDaemon({ home, entry, env = process.env, intervalMs = 5e3, mis
|
|
|
59
69
|
}
|
|
60
70
|
if (++missed >= misses && !stopped) await start("was down; started it again");
|
|
61
71
|
};
|
|
62
|
-
const initial = start(
|
|
72
|
+
const initial = start(by ? `started with ${by}` : "started", false);
|
|
63
73
|
const timer = setInterval(() => {
|
|
64
74
|
void check();
|
|
65
75
|
}, intervalMs);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anhlp/alp-client",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.1-beta.10",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "ALP client: portable JSON-RPC SDK, WebSocket and Node IPC transports, daemon discovery and setup",
|
|
6
6
|
"files": [
|
|
@@ -57,6 +57,14 @@
|
|
|
57
57
|
"types": "./dist/index.d.ts",
|
|
58
58
|
"default": "./src/index.js"
|
|
59
59
|
},
|
|
60
|
+
"./integration-lock": {
|
|
61
|
+
"alp-source": {
|
|
62
|
+
"types": "./src/integration-lock.js",
|
|
63
|
+
"default": "./src/integration-lock.js"
|
|
64
|
+
},
|
|
65
|
+
"types": "./dist/integration-lock.d.ts",
|
|
66
|
+
"default": "./src/integration-lock.js"
|
|
67
|
+
},
|
|
60
68
|
"./ipc": {
|
|
61
69
|
"alp-source": {
|
|
62
70
|
"types": "./src/ipc.js",
|
|
@@ -142,8 +150,8 @@
|
|
|
142
150
|
"node": ">=22.12"
|
|
143
151
|
},
|
|
144
152
|
"dependencies": {
|
|
145
|
-
"@anhlp/alp-core": "0.0.
|
|
146
|
-
"@anhlp/alp-protocol": "0.0.
|
|
153
|
+
"@anhlp/alp-core": "0.0.1-beta.10",
|
|
154
|
+
"@anhlp/alp-protocol": "0.0.1-beta.10"
|
|
147
155
|
},
|
|
148
156
|
"scripts": {
|
|
149
157
|
"build": "node ../../scripts/build-workspace.mjs client",
|
package/src/acp-probe.js
CHANGED
|
@@ -7,12 +7,17 @@ import { stdioSession } from './mcp-probe.js';
|
|
|
7
7
|
* it also opens a session in `cwd`, as Paseo does, to read the models and modes the agent
|
|
8
8
|
* offers (ALPD §65); an agent that offers none leaves them out.
|
|
9
9
|
* @param {{ command: string, args?: string[], env?: Record<string, string>, label?: string, id?: string }} provider
|
|
10
|
-
* @param {{ cwd?: string, timeoutMs?: number, discover?: boolean }} [options]
|
|
10
|
+
* @param {{ cwd?: string, timeoutMs?: number, discover?: boolean, signal?: AbortSignal }} [options]
|
|
11
11
|
* @returns {Promise<{ protocolVersion: number, agent?: { name?: string, title?: string, version?: string }, loadSession: boolean, mcpHttp: boolean, authMethods: string[],
|
|
12
12
|
* models?: Array<{ id: string, label: string, description?: string }>, currentModel?: string, modes?: Array<{ id: string, label: string, description?: string }>, currentMode?: string }>}
|
|
13
13
|
*/
|
|
14
|
-
export async function probeAcp(provider, { cwd, timeoutMs = 20_000, discover = false } = {}) {
|
|
14
|
+
export async function probeAcp(provider, { cwd, timeoutMs = 20_000, discover = false, signal } = {}) {
|
|
15
|
+
signal?.throwIfAborted();
|
|
15
16
|
const session = stdioSession({ command: provider.command, args: provider.args ?? [], env: provider.env ?? {} }, cwd, timeoutMs);
|
|
17
|
+
let closing;
|
|
18
|
+
const abort = () => { closing ??= session.close(); };
|
|
19
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
20
|
+
if (signal?.aborted) abort();
|
|
16
21
|
try {
|
|
17
22
|
const result = await session.request('initialize', {
|
|
18
23
|
protocolVersion: 1,
|
|
@@ -41,6 +46,8 @@ export async function probeAcp(provider, { cwd, timeoutMs = 20_000, discover = f
|
|
|
41
46
|
authMethods: (result.authMethods ?? []).map(method => method?.name ?? method?.id).filter(Boolean),
|
|
42
47
|
};
|
|
43
48
|
} finally {
|
|
44
|
-
|
|
49
|
+
signal?.removeEventListener('abort', abort);
|
|
50
|
+
await (closing ?? session.close());
|
|
51
|
+
signal?.throwIfAborted();
|
|
45
52
|
}
|
|
46
53
|
}
|
package/src/antigravity-probe.js
CHANGED
|
@@ -12,6 +12,16 @@ const DEFAULT_ANTIGRAVITY_MODELS = [
|
|
|
12
12
|
];
|
|
13
13
|
|
|
14
14
|
const ANTIGRAVITY_MODES = [
|
|
15
|
+
{
|
|
16
|
+
id: 'read-only',
|
|
17
|
+
label: 'Read only',
|
|
18
|
+
description: 'agy reads and searches; it denies file edits and terminal commands (--sandbox, request-review).',
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
id: 'workspace-write',
|
|
22
|
+
label: 'Workspace write',
|
|
23
|
+
description: 'agy edits files and runs commands in its terminal sandbox inside the workspace (--mode accept-edits --sandbox, proceed-in-sandbox).',
|
|
24
|
+
},
|
|
15
25
|
{
|
|
16
26
|
id: 'full-access',
|
|
17
27
|
label: 'Full access',
|
|
@@ -54,7 +64,7 @@ function runCommand(command, args, { env = process.env, cwd, timeoutMs = 20_000
|
|
|
54
64
|
|
|
55
65
|
/**
|
|
56
66
|
* Probes Antigravity CLI for version, status and available models.
|
|
57
|
-
* @param {{ command?: string, args?: string[], env?: Record<string, string>, label?: string, id?: string
|
|
67
|
+
* @param {{ command?: string, args?: string[], env?: Record<string, string>, label?: string, id?: string}} [provider]
|
|
58
68
|
* @param {{ cwd?: string, timeoutMs?: number }} [options]
|
|
59
69
|
*/
|
|
60
70
|
export async function probeAntigravity(provider = {}, { cwd, timeoutMs = 20_000 } = {}) {
|
|
@@ -97,10 +107,7 @@ export async function probeAntigravity(provider = {}, { cwd, timeoutMs = 20_000
|
|
|
97
107
|
agent: { name: 'antigravity', title: 'Antigravity', version },
|
|
98
108
|
models,
|
|
99
109
|
currentModel: models[0]?.id,
|
|
100
|
-
modes:
|
|
101
|
-
id: 'read-only', label: 'Read only (instructions)',
|
|
102
|
-
description: 'For new sessions: prompt-only read-only behavior. agy still runs with full access; no OS sandbox enforces this mode.',
|
|
103
|
-
}] : ANTIGRAVITY_MODES,
|
|
110
|
+
modes: ANTIGRAVITY_MODES,
|
|
104
111
|
currentMode: 'full-access',
|
|
105
112
|
};
|
|
106
113
|
}
|
package/src/command.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
+
import { scriptCommand } from '@anhlp/alp-core/packaged';
|
|
2
3
|
|
|
3
4
|
/** Runs a command; resolves with its exit code and output, never rejects. */
|
|
4
5
|
export function runCommand(command, args, { cwd, env = process.env, timeoutMs = 15_000 } = {}) {
|
|
@@ -6,7 +7,8 @@ export function runCommand(command, args, { cwd, env = process.env, timeoutMs =
|
|
|
6
7
|
let child;
|
|
7
8
|
// Windows cannot exec a script by its shebang; a JavaScript command runs under this Node, as the Codex transport does.
|
|
8
9
|
const script = process.platform === 'win32' && /\.[cm]?js$/i.test(command);
|
|
9
|
-
|
|
10
|
+
const run = script ? scriptCommand(command, args) : { command, args };
|
|
11
|
+
try { child = spawn(run.command, run.args, { cwd, env: run.env ? { ...env, ...run.env } : env, stdio: ['ignore', 'pipe', 'pipe'] }); }
|
|
10
12
|
catch (error) { resolve({ code: -1, stdout: '', stderr: error.message }); return; }
|
|
11
13
|
let stdout = '', stderr = '';
|
|
12
14
|
child.stdout.on('data', chunk => { stdout += chunk; });
|
package/src/doctor.d.ts
CHANGED
|
@@ -10,4 +10,12 @@ export type CommandResult = { code: number; stdout: string; stderr: string };
|
|
|
10
10
|
export type CommandRunner = (command: string, args: string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv; timeoutMs?: number }) => Promise<CommandResult>;
|
|
11
11
|
export const runCommand: CommandRunner;
|
|
12
12
|
export function diagnose(options?: { home?: string; project?: string; env?: NodeJS.ProcessEnv; run?: CommandRunner; sandbox?: boolean; daemonEntry?: string; timeoutMs?: number }): Promise<DoctorCheck[]>;
|
|
13
|
+
export type LeftoverState = 'clean-pushed' | 'dirty' | 'local-only' | 'unpushed' | 'in-use' | 'unknown';
|
|
14
|
+
export type Leftover = { path: string; state: LeftoverState; reason?: string; command?: string };
|
|
15
|
+
export const LEFTOVER_STATES: Record<LeftoverState, string>;
|
|
16
|
+
/** An absolute path of ASCII letters, digits, space and . _ - / \ : in single quotes, for sh or PowerShell; undefined for any other path. */
|
|
17
|
+
export function shellQuote(text: string, platform?: NodeJS.Platform): string | undefined;
|
|
18
|
+
/** A path as alp doctor prints it in a comment line: escaped injectively, on one line. */
|
|
19
|
+
export function printable(text: unknown): string;
|
|
20
|
+
export function diskCheck(home: string, options?: { run?: CommandRunner; env?: NodeJS.ProcessEnv; free?: number; tempDirs?: string[]; cwd?: string; classifyMs?: number; recentMs?: number; platform?: NodeJS.Platform }): Promise<DoctorCheck & { leftovers?: Leftover[] }>;
|
|
13
21
|
export function repair(checks: DoctorCheck[]): Promise<Array<{ id: string; result: string }>>;
|
package/src/doctor.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
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';
|
|
2
4
|
import path from 'node:path';
|
|
3
5
|
import { runCommand } from './command.js';
|
|
4
6
|
import { assertPrivateSocket, connect, daemonPaths, lockAlive, readLock } from './index.js';
|
|
@@ -6,6 +8,7 @@ import { installedProgram, serviceFor } from './service.js';
|
|
|
6
8
|
import { jsonObject, agentSources, resolveAgent } from '@anhlp/alp-core/resolver';
|
|
7
9
|
import { loadHooks } from '@anhlp/alp-core/hooks';
|
|
8
10
|
import { isTrusted } from '@anhlp/alp-core/trust';
|
|
11
|
+
import { validateSkill } from '@anhlp/alp-core/skill-validate';
|
|
9
12
|
import { listProviders } from '@anhlp/alp-core/providers';
|
|
10
13
|
import { settingsWarnings, validateSettings, validateUserSettings } from '@anhlp/alp-core/validation';
|
|
11
14
|
import { readLogTail, scrubText } from '@anhlp/alp-core/log';
|
|
@@ -75,13 +78,14 @@ async function runtimeChecks({ env, run }) {
|
|
|
75
78
|
return checks;
|
|
76
79
|
}
|
|
77
80
|
|
|
78
|
-
/** An installed alpd service whose node
|
|
81
|
+
/** An installed alpd service whose node, alpd.js or native alpd moved can no longer start alpd. */
|
|
79
82
|
async function serviceCheck(home, env) {
|
|
80
83
|
const service = serviceFor({ home, env });
|
|
81
84
|
const program = service && await installedProgram(service);
|
|
82
85
|
if (!program) return undefined;
|
|
83
86
|
const missing = [];
|
|
84
|
-
|
|
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);
|
|
85
89
|
return missing.length
|
|
86
90
|
? { id: 'service', status: 'fail', summary: `the ${service.kind} service ${service.name} runs files that are gone; run alp daemon install again`, details: missing }
|
|
87
91
|
: { id: 'service', status: 'ok', summary: `${service.kind} runs alpd as ${service.name}` };
|
|
@@ -401,6 +405,33 @@ async function providersCheck(home, env) {
|
|
|
401
405
|
};
|
|
402
406
|
}
|
|
403
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
|
+
|
|
404
435
|
async function librarySkillsCheck(home) {
|
|
405
436
|
const file = path.join(home, 'role-skills.json');
|
|
406
437
|
let roles;
|
|
@@ -519,12 +550,321 @@ async function schemaChecks(home) {
|
|
|
519
550
|
return checks;
|
|
520
551
|
}
|
|
521
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
|
+
|
|
522
860
|
export async function diagnose({ home, project, env = process.env, run = runCommand, sandbox, daemonEntry, timeoutMs = 3000 } = {}) {
|
|
523
861
|
const checks = [];
|
|
524
862
|
if (daemonEntry) {
|
|
525
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` })));
|
|
526
864
|
}
|
|
527
865
|
checks.push(...await runtimeChecks({ env, run }));
|
|
866
|
+
checks.push(await homeLocationCheck(home, project));
|
|
867
|
+
if (home) checks.push(await diskCheck(home, { run, env }));
|
|
528
868
|
const daemon = await daemonCheck(home);
|
|
529
869
|
checks.push(daemon);
|
|
530
870
|
const service = await serviceCheck(home, env);
|
|
@@ -546,6 +886,8 @@ export async function diagnose({ home, project, env = process.env, run = runComm
|
|
|
546
886
|
checks.push(await userSettingsCheck(home));
|
|
547
887
|
const skills = await librarySkillsCheck(home);
|
|
548
888
|
if (skills) checks.push(skills);
|
|
889
|
+
const skillFormat = await skillFormatCheck(home);
|
|
890
|
+
if (skillFormat) checks.push(skillFormat);
|
|
549
891
|
const providers = await providersCheck(home, env);
|
|
550
892
|
if (providers) checks.push(providers);
|
|
551
893
|
const live = await liveCheck(home, running);
|