aboutsummaryrefslogtreecommitdiffstats
path: root/cli/src/commands/doctor.ts
blob: 6c5af0d54ad392291babf8b056b09fc2a6970f46 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/**
 * `sl0ppi doctor` — is this installation coherent?
 *
 * Split into "gather facts" (IO) and "judge them" (pure), so the judging is
 * testable and the output cannot drift from the rules.
 *
 * It reports what it can actually verify. Notably it CANNOT fully validate a
 * project's layout fragment: sl0ppij has no parse-only mode, so a fragment is
 * only really checked when a tab is created from it. The structural check here
 * catches the common breakages (empty file, unbalanced braces, someone wrapping
 * the fragment in `layout {}`) and says so rather than implying more.
 */

import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { discoverProjects, LAYOUT_FILE, MARKER_DIR } from "../core/discover.ts";
import { loadRegistry, registryPath, type Registry } from "../core/root.ts";
import { Sl0ppij } from "../core/sl0ppij.ts";

export type Level = "ok" | "warn" | "fail";

export interface Check {
  level: Level;
  label: string;
  detail: string;
  /** What the user should do about it. */
  fix?: string;
}

export interface Facts {
  sl0ppijVersion?: string;
  piVersion?: string;
  configDir?: string;
  configFile: boolean;
  plugins: { name: string; present: boolean }[];
  registry: Registry;
  liveSessions: string[];
  roots: { session: string; root: string; exists: boolean; projects: number }[];
  fragments: { relPath: string; issue?: string }[];
  externalTools: { name: string; present: boolean; neededBy: string }[];
}

/** The judging half: pure, so the rules are testable. */
export function report(facts: Facts): Check[] {
  const checks: Check[] = [];

  checks.push(
    facts.sl0ppijVersion
      ? { level: "ok", label: "sl0ppij", detail: facts.sl0ppijVersion }
      : {
          level: "fail",
          label: "sl0ppij",
          detail: "not found on PATH",
          fix: "install sl0ppi, or set SL0PPI_BIN to the binary",
        },
  );

  checks.push(
    facts.piVersion
      ? { level: "ok", label: "pi", detail: facts.piVersion }
      : {
          level: "warn",
          label: "pi",
          detail: "not found on PATH",
          fix: "agent panes will fail to start; install pi",
        },
  );

  checks.push(
    facts.configFile
      ? { level: "ok", label: "config", detail: facts.configDir ?? "found" }
      : {
          level: "warn",
          label: "config",
          detail: `no config.kdl in ${facts.configDir ?? "the config dir"}`,
          fix: "run the installer, or `make install-config` from a checkout",
        },
  );

  for (const plugin of facts.plugins) {
    checks.push(
      plugin.present
        ? { level: "ok", label: `plugin ${plugin.name}`, detail: "installed" }
        : {
            level: "warn",
            label: `plugin ${plugin.name}`,
            detail: "missing",
            fix: "the shipped layout expects it; reinstall to restore it",
          },
    );
  }

  for (const tool of facts.externalTools) {
    if (!tool.present) {
      checks.push({
        level: "warn",
        label: tool.name,
        detail: `not found; ${tool.neededBy} needs it`,
        fix: `install ${tool.name}`,
      });
    }
  }

  if (Object.keys(facts.registry).length === 0) {
    checks.push({
      level: "ok",
      label: "roots",
      detail: "none registered yet",
      fix: "run `sl0ppi up` in a directory of projects",
    });
  }

  for (const root of facts.roots) {
    if (!root.exists) {
      checks.push({
        level: "warn",
        label: `root ${root.session}`,
        detail: `${root.root} does not exist`,
        fix: "if it is an unmounted filesystem, mount it; otherwise remove it from " +
          registryPath(),
      });
      continue;
    }
    const live = facts.liveSessions.includes(root.session) ? "session live" : "session not running";
    checks.push({
      level: "ok",
      label: `root ${root.session}`,
      detail: `${root.root} — ${root.projects} project(s), ${live}`,
    });
  }

  for (const fragment of facts.fragments) {
    if (fragment.issue) {
      checks.push({
        level: "warn",
        label: `layout ${fragment.relPath}`,
        detail: fragment.issue,
        fix: "see `sl0ppi init` for the expected shape (pane nodes only)",
      });
    }
  }

  return checks;
}

/**
 * Cheap structural check of a fragment.
 *
 * Deliberately conservative: sl0ppij has no parse-only mode, so anything
 * subtler than this would be guessing at the KDL dialect.
 */
export function checkFragment(text: string): string | undefined {
  const stripped = text
    .split("\n")
    .map((line) => line.replace(/\/\/.*$/, "").trim())
    .join("\n")
    .trim();

  if (stripped.length === 0) return "empty (the default single-agent pane will be used)";

  const open = (stripped.match(/\{/g) ?? []).length;
  const close = (stripped.match(/\}/g) ?? []).length;
  if (open !== close) return `unbalanced braces (${open} open, ${close} close)`;

  if (/^\s*layout\s*\{/m.test(stripped)) {
    return "wraps its panes in `layout {}`; a fragment is pane nodes only";
  }
  if (/^\s*tab\b/m.test(stripped)) {
    return "declares a `tab`; sl0ppi adds that (it carries the project's identity)";
  }
  return undefined;
}

export interface GatherOptions {
  client: Sl0ppij;
  configDir?: string;
  depth: number;
}

export function gather(options: GatherOptions): Facts {
  const { client } = options;

  const version = (bin: string, args: string[]): string | undefined => {
    try {
      const proc = new Sl0ppij({ bin }).run(args, { session: false });
      return proc.code === 0 ? proc.stdout.trim().split("\n")[0] : undefined;
    } catch {
      return undefined;
    }
  };

  const configDir = options.configDir ?? defaultConfigDir();
  const registry = loadRegistry();

  const roots = Object.entries(registry).map(([session, root]) => ({
    session,
    root,
    exists: existsSync(root),
    projects: existsSync(root) ? discoverProjects(root, { depth: options.depth }).length : 0,
  }));

  const fragments: { relPath: string; issue?: string }[] = [];
  for (const root of roots) {
    if (!root.exists) continue;
    for (const relPath of discoverProjects(root.root, { depth: options.depth })) {
      const path = join(root.root, relPath, MARKER_DIR, LAYOUT_FILE);
      if (!existsSync(path)) continue; // no fragment is fine: the default applies
      fragments.push({ relPath, issue: checkFragment(readFileSync(path, "utf8")) });
    }
  }

  return {
    sl0ppijVersion: version(client.bin, ["--version"]),
    piVersion: version(process.env.SL0PPI_PI ?? "pi", ["--version"]),
    configDir,
    configFile: existsSync(join(configDir, "config.kdl")),
    plugins: ["pane-finder.wasm", "zjstatus.wasm"].map((name) => ({
      name,
      present: existsSync(join(configDir, "plugins", name)),
    })),
    registry,
    liveSessions: safe(() => client.liveSessions(), []),
    roots,
    fragments,
    // The known packaging hole: `pir` ships in the tarball but its runtime deps
    // do not. Better to say so than to let it fail at the moment of use.
    externalTools: [
      { name: "python3", present: onPath("python3"), neededBy: "pir" },
      { name: "fzf", present: onPath("fzf"), neededBy: "pir" },
    ],
  };
}

export function worstLevel(checks: Check[]): Level {
  if (checks.some((c) => c.level === "fail")) return "fail";
  if (checks.some((c) => c.level === "warn")) return "warn";
  return "ok";
}

export function formatCheck(check: Check): string {
  const mark = check.level === "ok" ? "ok  " : check.level === "warn" ? "warn" : "FAIL";
  const fix = check.fix && check.level !== "ok" ? `\n         -> ${check.fix}` : "";
  return `  ${mark}  ${check.label.padEnd(22)} ${check.detail}${fix}`;
}

function defaultConfigDir(): string {
  const env = process.env;
  if (env.SL0PPIJ_CONFIG_DIR) return env.SL0PPIJ_CONFIG_DIR;
  const home = env.HOME ?? "";
  return join(home, ".config", "sl0ppij");
}

function onPath(tool: string): boolean {
  const dirs = (process.env.PATH ?? "").split(":").filter(Boolean);
  return dirs.some((dir) => existsSync(join(dir, tool)));
}

function safe<T>(fn: () => T, fallback: T): T {
  try {
    return fn();
  } catch {
    return fallback;
  }
}