@anhlp/alp-client 0.0.1-beta.7 → 0.0.1-beta.9

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/src/doctor.d.ts CHANGED
@@ -10,5 +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 function diskCheck(home: string, options?: { run?: CommandRunner; env?: NodeJS.ProcessEnv; free?: number; tempDirs?: string[] }): 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[] }>;
14
21
  export function repair(checks: DoctorCheck[]): Promise<Array<{ id: string; result: string }>>;
package/src/doctor.js CHANGED
@@ -8,6 +8,7 @@ import { installedProgram, serviceFor } from './service.js';
8
8
  import { jsonObject, agentSources, resolveAgent } from '@anhlp/alp-core/resolver';
9
9
  import { loadHooks } from '@anhlp/alp-core/hooks';
10
10
  import { isTrusted } from '@anhlp/alp-core/trust';
11
+ import { validateSkill } from '@anhlp/alp-core/skill-validate';
11
12
  import { listProviders } from '@anhlp/alp-core/providers';
12
13
  import { settingsWarnings, validateSettings, validateUserSettings } from '@anhlp/alp-core/validation';
13
14
  import { readLogTail, scrubText } from '@anhlp/alp-core/log';
@@ -77,13 +78,14 @@ async function runtimeChecks({ env, run }) {
77
78
  return checks;
78
79
  }
79
80
 
80
- /** An installed alpd service whose node or alpd.js moved can no longer start alpd. */
81
+ /** An installed alpd service whose node, alpd.js or native alpd moved can no longer start alpd. */
81
82
  async function serviceCheck(home, env) {
82
83
  const service = serviceFor({ home, env });
83
84
  const program = service && await installedProgram(service);
84
85
  if (!program) return undefined;
85
86
  const missing = [];
86
- for (const file of program) if (!await lstat(file).then(() => true, () => false)) missing.push(file);
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);
87
89
  return missing.length
88
90
  ? { id: 'service', status: 'fail', summary: `the ${service.kind} service ${service.name} runs files that are gone; run alp daemon install again`, details: missing }
89
91
  : { id: 'service', status: 'ok', summary: `${service.kind} runs alpd as ${service.name}` };
@@ -403,6 +405,33 @@ async function providersCheck(home, env) {
403
405
  };
404
406
  }
405
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
+
406
435
  async function librarySkillsCheck(home) {
407
436
  const file = path.join(home, 'role-skills.json');
408
437
  let roles;
@@ -574,13 +603,204 @@ async function entries(directory, prefix = '') {
574
603
  return names.filter(name => name.startsWith(prefix)).map(name => path.join(directory, name));
575
604
  }
576
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
+
577
793
  /**
578
794
  * Free space where ALP_HOME lives (t-2831), and what earlier runs left that takes room:
579
795
  * worktrees under ALP_HOME/worktrees and alp-* directories in the temp directory. When
580
796
  * the disk fills, alpd pauses work instead of stopping; this says so before it happens.
581
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.
582
802
  */
583
- export async function diskCheck(home, { run = runCommand, env = process.env, free, tempDirs = [...new Set([os.tmpdir(), ...(process.platform === 'win32' ? [] : ['/tmp'])])] } = {}) {
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 } = {}) {
584
804
  let bytes = free;
585
805
  if (bytes === undefined) {
586
806
  try { const info = await statfs(home); bytes = Number(info.bavail) * Number(info.bsize); } catch {}
@@ -602,20 +822,35 @@ export async function diskCheck(home, { run = runCommand, env = process.env, fre
602
822
  const total = result.stdout.split('\n').reduce((sum, line) => sum + (Number(line.split(/\s+/)[0]) || 0), 0);
603
823
  return total * 1024;
604
824
  }
605
- const details = [];
606
- for (const [label, paths] of [[`${path.join(home, 'worktrees')}`, worktrees], [`${tempDirs.map(directory => path.join(directory, 'alp-*')).join(', ')}`, temp]]) {
607
- if (!paths.length) continue;
608
- const used = await size(paths);
609
- details.push(`${paths.length} left in ${label}${used === undefined ? '' : `, ${formatSize(used)}`}`);
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}`);
610
838
  }
611
- const hint = details.length ? 'ALP deletes none of these: some may belong to running assignments or hold uncommitted work. Remove those you no longer need (git worktree remove, or rm -rf).' : undefined;
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;
612
847
  const where = bytes === undefined ? 'free space unknown' : `${formatSize(bytes)} free`;
613
- // Leftovers are listed, not judged: some may be live.
848
+ // Leftovers never change the status: some may be live.
614
849
  const status = bytes !== undefined && bytes < 2 * GIB ? 'warn' : 'ok';
615
850
  const summary = bytes !== undefined && bytes < 2 * GIB
616
851
  ? `${where} where ALP_HOME lives; when the disk is full, alpd pauses all work until space returns`
617
852
  : `${where} where ALP_HOME lives`;
618
- return { id: 'disk', status, summary, ...(details.length ? { details } : {}), ...(hint ? { hint } : {}) };
853
+ return { id: 'disk', status, summary, ...(details.length ? { details } : {}), ...(hint ? { hint } : {}), ...(leftovers.length ? { leftovers } : {}) };
619
854
  }
620
855
 
621
856
  function realpathOr(file) {
@@ -651,6 +886,8 @@ export async function diagnose({ home, project, env = process.env, run = runComm
651
886
  checks.push(await userSettingsCheck(home));
652
887
  const skills = await librarySkillsCheck(home);
653
888
  if (skills) checks.push(skills);
889
+ const skillFormat = await skillFormatCheck(home);
890
+ if (skillFormat) checks.push(skillFormat);
654
891
  const providers = await providersCheck(home, env);
655
892
  if (providers) checks.push(providers);
656
893
  const live = await liveCheck(home, running);