@jmanuelcorral/bond-app 0.1.6 → 0.2.1

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.
@@ -0,0 +1,757 @@
1
+ import fs from 'node:fs';
2
+ import http from 'node:http';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify } from 'node:util';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ import { MIN_HC_VERSION, MIN_HERDR_APP_VERSION, compareVersions } from '../runner/hc-client.ts';
10
+ import { LABEL_RECIPE, runnerRecipeHash } from '../runner/image-builder.ts';
11
+ import { checkAppInstalled, type AppIntegrationCheckResult } from '../../scripts/app-install.ts';
12
+ import { checkHttpHealth } from '../cli.ts';
13
+ import { getServiceStatus, type ServiceDeps } from './service.ts';
14
+ import { defaultDataDir, defaultHerdrAppHome } from './paths.ts';
15
+ import { checkIcaclsOutput, currentWindowsUsername } from './permissions.ts';
16
+
17
+ const execFileAsync = promisify(execFile);
18
+ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
19
+
20
+ export type DoctorStatus = 'ok' | 'warn' | 'fail';
21
+ export type DoctorPlatform = 'linux' | 'macos' | 'windows';
22
+
23
+ export interface DoctorCheck {
24
+ id: string;
25
+ name: string;
26
+ status: DoctorStatus;
27
+ essential: boolean;
28
+ detail: string;
29
+ fix?: string;
30
+ meta?: Record<string, unknown>;
31
+ }
32
+
33
+ export interface DoctorReport {
34
+ ok: boolean;
35
+ platform: DoctorPlatform;
36
+ checks: DoctorCheck[];
37
+ summary: {
38
+ ok: number;
39
+ warn: number;
40
+ fail: number;
41
+ };
42
+ }
43
+
44
+ export interface CommandOutput {
45
+ ok: boolean;
46
+ stdout: string;
47
+ stderr: string;
48
+ error?: string;
49
+ }
50
+
51
+ export interface SetupStateSummary {
52
+ image?: { present: boolean; recipe?: string };
53
+ recipe?: string;
54
+ }
55
+
56
+ export interface DoctorDeps {
57
+ runCommand?: (cmd: string, args: string[], timeoutMs?: number) => Promise<CommandOutput>;
58
+ checkHealth?: (host: string, port: number, timeoutMs?: number) => Promise<{ ok: boolean; statusCode?: number; data?: unknown }>;
59
+ fetchSetupState?: (host: string, port: number, token: string, timeoutMs?: number) => Promise<SetupStateSummary | null>;
60
+ checkApp?: (home: string) => AppIntegrationCheckResult;
61
+ getFreeSpaceBytes?: (targetPath: string) => number | null;
62
+ nodeVersion?: string;
63
+ platform?: NodeJS.Platform;
64
+ username?: string;
65
+ expectedRecipeHash?: () => string;
66
+ serviceDeps?: ServiceDeps;
67
+ }
68
+
69
+ export interface DoctorOptions {
70
+ port?: number;
71
+ host?: string;
72
+ dataDir?: string;
73
+ home?: string;
74
+ runnerImage?: string;
75
+ deps?: DoctorDeps;
76
+ }
77
+
78
+ export const MIN_DOCKER_FREE_BYTES = 4 * 1024 * 1024 * 1024; // ~4 GB for runner image
79
+
80
+ export function normalizePlatform(platform: NodeJS.Platform = process.platform): DoctorPlatform {
81
+ if (platform === 'darwin') return 'macos';
82
+ if (platform === 'win32') return 'windows';
83
+ return 'linux';
84
+ }
85
+
86
+ export function readMinNodeVersion(root: string = repoRoot): string {
87
+ try {
88
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) as {
89
+ engines?: { node?: string };
90
+ };
91
+ const raw = pkg.engines?.node || '>=22.15.0';
92
+ const m = /(\d+\.\d+\.\d+)/.exec(raw);
93
+ return m ? m[1] : '22.15.0';
94
+ } catch {
95
+ return '22.15.0';
96
+ }
97
+ }
98
+
99
+ export function readBondVersionFromEnv(root: string = repoRoot): string {
100
+ try {
101
+ const content = fs.readFileSync(path.join(root, 'runner', 'versions.env'), 'utf8');
102
+ const m = /^BOND_VERSION=([^\s#]+)/m.exec(content);
103
+ return m ? m[1].trim() : '1.16.8';
104
+ } catch {
105
+ return '1.16.8';
106
+ }
107
+ }
108
+
109
+ async function defaultRunCommand(cmd: string, args: string[], timeoutMs = 10_000): Promise<CommandOutput> {
110
+ try {
111
+ const needsShell = process.platform === 'win32' && (cmd === 'npm' || cmd === 'bond' || cmd === 'bond-app');
112
+ const { stdout, stderr } = await execFileAsync(cmd, args, {
113
+ encoding: 'utf8',
114
+ timeout: timeoutMs,
115
+ shell: needsShell,
116
+ });
117
+ return { ok: true, stdout: stdout || '', stderr: stderr || '' };
118
+ } catch (err: unknown) {
119
+ const e = err as { stdout?: string; stderr?: string; message?: string };
120
+ return {
121
+ ok: false,
122
+ stdout: typeof e.stdout === 'string' ? e.stdout : '',
123
+ stderr: typeof e.stderr === 'string' ? e.stderr : '',
124
+ error: e.message || String(err),
125
+ };
126
+ }
127
+ }
128
+
129
+ function defaultFetchSetupState(
130
+ host: string,
131
+ port: number,
132
+ token: string,
133
+ timeoutMs = 1500
134
+ ): Promise<SetupStateSummary | null> {
135
+ return new Promise((resolve) => {
136
+ const req = http.get(
137
+ {
138
+ host,
139
+ port,
140
+ path: '/api/v1/setup',
141
+ headers: {
142
+ Host: `${host}:${port}`,
143
+ Authorization: `Bearer ${token}`,
144
+ },
145
+ timeout: timeoutMs,
146
+ },
147
+ (res) => {
148
+ let body = '';
149
+ res.setEncoding('utf8');
150
+ res.on('data', (chunk) => {
151
+ body += chunk;
152
+ });
153
+ res.on('end', () => {
154
+ if (res.statusCode === 200) {
155
+ try {
156
+ resolve(JSON.parse(body) as SetupStateSummary);
157
+ } catch {
158
+ resolve(null);
159
+ }
160
+ } else {
161
+ resolve(null);
162
+ }
163
+ });
164
+ }
165
+ );
166
+ req.on('timeout', () => {
167
+ req.destroy();
168
+ resolve(null);
169
+ });
170
+ req.on('error', () => {
171
+ resolve(null);
172
+ });
173
+ });
174
+ }
175
+
176
+ function defaultGetFreeSpaceBytes(targetPath: string): number | null {
177
+ try {
178
+ let probe = targetPath;
179
+ while (!fs.existsSync(probe)) {
180
+ const parent = path.dirname(probe);
181
+ if (parent === probe) break;
182
+ probe = parent;
183
+ }
184
+ const stat = fs.statfsSync(probe);
185
+ return Number(stat.bavail) * Number(stat.bsize);
186
+ } catch {
187
+ return null;
188
+ }
189
+ }
190
+
191
+ function extractSemver(text: string): string | null {
192
+ const m = /(\d+\.\d+\.\d+)/.exec(text);
193
+ return m ? m[1] : null;
194
+ }
195
+
196
+ function formatGiB(bytes: number): string {
197
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
198
+ }
199
+
200
+ function fixByPlatform(platform: DoctorPlatform, fixes: Record<DoctorPlatform, string>): string {
201
+ return fixes[platform];
202
+ }
203
+
204
+ export async function runDoctor(options: DoctorOptions = {}): Promise<DoctorReport> {
205
+ const deps = options.deps ?? {};
206
+ const runCommand = deps.runCommand ?? defaultRunCommand;
207
+ const checkHealth = deps.checkHealth ?? checkHttpHealth;
208
+ const fetchSetupState = deps.fetchSetupState ?? defaultFetchSetupState;
209
+ const checkApp = deps.checkApp ?? checkAppInstalled;
210
+ const getFreeSpaceBytes = deps.getFreeSpaceBytes ?? defaultGetFreeSpaceBytes;
211
+ const platform = normalizePlatform(deps.platform ?? process.platform);
212
+
213
+ const port = options.port ?? parseInt(process.env.BOND_APP_PORT || '3000', 10);
214
+ const host = options.host ?? process.env.BOND_APP_HOST ?? '127.0.0.1';
215
+ const rawPlatform = deps.platform ?? process.platform;
216
+ const dataDir = options.dataDir ?? defaultDataDir({ platform: rawPlatform });
217
+ const home = options.home ?? defaultHerdrAppHome({ platform: rawPlatform });
218
+ const explicitImage = options.runnerImage;
219
+ const runnerImage = explicitImage ?? (process.env.RUNNER_IMAGE || 'bond-app-runner:p5');
220
+
221
+ const checks: DoctorCheck[] = [];
222
+
223
+ // 1. Node.js
224
+ const minNode = readMinNodeVersion();
225
+ const nodeVer = (deps.nodeVersion ?? process.versions.node).replace(/^v/, '');
226
+ const nodeOk = compareVersions(nodeVer, minNode) >= 0;
227
+ checks.push({
228
+ id: 'node',
229
+ name: 'Node.js',
230
+ status: nodeOk ? 'ok' : 'fail',
231
+ essential: true,
232
+ detail: nodeOk ? `v${nodeVer} (>= ${minNode})` : `v${nodeVer} < ${minNode}`,
233
+ fix: nodeOk
234
+ ? undefined
235
+ : fixByPlatform(platform, {
236
+ linux: `Install Node.js >= ${minNode} (e.g. nvm install 22 && nvm use 22, or via your distro package manager)`,
237
+ macos: `Install Node.js >= ${minNode} (e.g. brew install node@22 or nvm install 22)`,
238
+ windows: `Install Node.js >= ${minNode} (e.g. winget install OpenJS.NodeJS.LTS)`,
239
+ }),
240
+ meta: { version: nodeVer, min: minNode },
241
+ });
242
+
243
+ // 2. Docker (CLI, daemon without sudo, free space) & runner image pre-check
244
+ const dockerVersionRes = await runCommand('docker', ['--version']);
245
+ let dockerReady = false;
246
+ let imageInspectRes: CommandOutput | null = null;
247
+ if (!dockerVersionRes.ok) {
248
+ checks.push({
249
+ id: 'docker',
250
+ name: 'Docker',
251
+ status: 'fail',
252
+ essential: true,
253
+ detail: 'docker CLI not found',
254
+ fix: fixByPlatform(platform, {
255
+ linux: 'Install Docker Engine (https://docs.docker.com/engine/install/) and run: sudo usermod -aG docker $USER && newgrp docker',
256
+ macos: 'Install Docker Desktop for Apple Silicon (brew install --cask docker)',
257
+ windows: 'Install Docker Desktop for Windows with WSL2 (winget install Docker.DockerDesktop)',
258
+ }),
259
+ });
260
+ } else {
261
+ const dockerVer = extractSemver(dockerVersionRes.stdout) || dockerVersionRes.stdout.trim();
262
+ const dockerInfoRes = await runCommand('docker', ['info', '--format', '{{.ServerVersion}}']);
263
+ if (!dockerInfoRes.ok) {
264
+ const errText = `${dockerInfoRes.stderr} ${dockerInfoRes.error ?? ''}`.toLowerCase();
265
+ const permDenied = errText.includes('permission denied') || errText.includes('got permission denied');
266
+ checks.push({
267
+ id: 'docker',
268
+ name: 'Docker',
269
+ status: 'fail',
270
+ essential: true,
271
+ detail: permDenied
272
+ ? `CLI ${dockerVer} installed, but daemon requires permissions (no sudo allowed)`
273
+ : `CLI ${dockerVer} installed, but Docker daemon is not reachable`,
274
+ fix: permDenied
275
+ ? fixByPlatform(platform, {
276
+ linux: 'Add your user to the docker group: sudo usermod -aG docker $USER && newgrp docker',
277
+ macos: 'Restart Docker Desktop (open -a Docker)',
278
+ windows: 'Ensure your user is in the docker-users group and Docker Desktop is running',
279
+ })
280
+ : fixByPlatform(platform, {
281
+ linux: 'Start the Docker daemon: sudo systemctl start docker',
282
+ macos: 'Start Docker Desktop: open -a Docker',
283
+ windows: 'Start Docker Desktop from the Start Menu',
284
+ }),
285
+ meta: { version: dockerVer },
286
+ });
287
+ } else {
288
+ dockerReady = true;
289
+ imageInspectRes = await runCommand('docker', ['image', 'inspect', runnerImage, '--format', `{{index .Config.Labels "${LABEL_RECIPE}"}}`]);
290
+ const freeBytes = getFreeSpaceBytes(os.tmpdir());
291
+ const spaceOk = freeBytes === null || freeBytes >= MIN_DOCKER_FREE_BYTES;
292
+ if (!spaceOk && !imageInspectRes.ok) {
293
+ checks.push({
294
+ id: 'docker',
295
+ name: 'Docker',
296
+ status: 'fail',
297
+ essential: true,
298
+ detail: `CLI ${dockerVer}, daemon ok, but only ${formatGiB(freeBytes)} free (~4.0 GB needed for runner image)`,
299
+ fix: fixByPlatform(platform, {
300
+ linux: 'Free disk space (e.g. docker system prune) so at least 4 GB is available',
301
+ macos: 'Free disk space in macOS / Docker Desktop (Settings → Resources → Disk image size)',
302
+ windows: 'Free disk space on Windows / Docker Desktop WSL2 disk',
303
+ }),
304
+ meta: { version: dockerVer, freeBytes },
305
+ });
306
+ } else {
307
+ checks.push({
308
+ id: 'docker',
309
+ name: 'Docker',
310
+ status: spaceOk ? 'ok' : 'warn',
311
+ essential: true,
312
+ detail: spaceOk
313
+ ? `CLI ${dockerVer}, daemon accessible${freeBytes !== null ? `, ${formatGiB(freeBytes)} free` : ''}`
314
+ : `CLI ${dockerVer}, daemon accessible, low free disk space (${formatGiB(freeBytes!)})`,
315
+ fix: spaceOk
316
+ ? undefined
317
+ : fixByPlatform(platform, {
318
+ linux: 'Free disk space (e.g. docker system prune)',
319
+ macos: 'Free disk space in Docker Desktop Resources',
320
+ windows: 'Free disk space in Docker Desktop WSL2',
321
+ }),
322
+ meta: { version: dockerVer, freeBytes },
323
+ });
324
+ }
325
+ }
326
+ }
327
+
328
+ // 3. herdr-app
329
+ const herdrAppRes = await runCommand('herdr-app', ['--version']);
330
+ const herdrAppVer = herdrAppRes.ok ? extractSemver(herdrAppRes.stdout) : null;
331
+ const herdrAppOk = Boolean(herdrAppVer && compareVersions(herdrAppVer, MIN_HERDR_APP_VERSION) >= 0);
332
+ // Installed but unable to start: a system library is missing (usually the graphical stack on a
333
+ // server or a minimal install, e.g. libxcb.so.1).
334
+ const missingLib = herdrAppRes.ok
335
+ ? null
336
+ : /error while loading shared libraries: ([^\s:]+)/.exec(`${herdrAppRes.stderr}\n${herdrAppRes.error ?? ''}`)?.[1] ?? null;
337
+ checks.push({
338
+ id: 'herdr-app',
339
+ name: 'herdr-app',
340
+ status: herdrAppOk ? 'ok' : 'fail',
341
+ essential: true,
342
+ detail: missingLib
343
+ ? `installed but cannot start: missing system library ${missingLib}`
344
+ : !herdrAppRes.ok
345
+ ? `not found (min ${MIN_HERDR_APP_VERSION})`
346
+ : herdrAppOk
347
+ ? `${herdrAppVer} (>= ${MIN_HERDR_APP_VERSION})`
348
+ : `${herdrAppVer ?? 'unknown'} < ${MIN_HERDR_APP_VERSION}`,
349
+ fix: herdrAppOk
350
+ ? undefined
351
+ : missingLib
352
+ ? `Install the package that provides ${missingLib} (herdr-app is a desktop app; on Debian/Ubuntu: sudo apt install libxcb1 libxkbcommon0, on Arch: sudo pacman -S libxcb libxkbcommon)`
353
+ : fixByPlatform(platform, {
354
+ linux: `Download herdr-app >= ${MIN_HERDR_APP_VERSION} from https://releases.herdr.dev/app/latest.json (linux-x86_64 or linux-aarch64), verify sha256, and place binary in ~/.local/bin/herdr-app`,
355
+ macos: `Download herdr-app >= ${MIN_HERDR_APP_VERSION} from https://releases.herdr.dev/app/latest.json (macos-aarch64), verify sha256, and place binary in ~/.local/bin/herdr-app`,
356
+ windows: `Download herdr-app >= ${MIN_HERDR_APP_VERSION} from https://releases.herdr.dev/app/latest.json (windows-x86_64), verify sha256, place herdr-app.exe in %LOCALAPPDATA%\\Programs\\bond and add to PATH`,
357
+ }),
358
+ meta: { version: herdrAppVer, min: MIN_HERDR_APP_VERSION },
359
+ });
360
+
361
+ // 4. hc (herdr-core)
362
+ const hcRes = await runCommand('hc', ['--version']);
363
+ const hcVer = hcRes.ok ? extractSemver(hcRes.stdout) : null;
364
+ const hcOk = Boolean(hcVer && compareVersions(hcVer, MIN_HC_VERSION) >= 0);
365
+ checks.push({
366
+ id: 'hc',
367
+ name: 'hc (herdr-core)',
368
+ status: hcOk ? 'ok' : 'fail',
369
+ essential: true,
370
+ detail: !hcRes.ok
371
+ ? `not found (min ${MIN_HC_VERSION})`
372
+ : hcOk
373
+ ? `${hcVer} (>= ${MIN_HC_VERSION})`
374
+ : `${hcVer ?? 'unknown'} < ${MIN_HC_VERSION}`,
375
+ fix: hcOk
376
+ ? undefined
377
+ : fixByPlatform(platform, {
378
+ linux: `Download herdr-core >= ${MIN_HC_VERSION} from https://releases.herdr.dev/core/latest.json, verify sha256, install herdr-core in ~/.local/bin and symlink hc -> herdr-core`,
379
+ macos: `Download herdr-core >= ${MIN_HC_VERSION} from https://releases.herdr.dev/core/latest.json, verify sha256, install herdr-core in ~/.local/bin and symlink hc -> herdr-core`,
380
+ windows: `Download herdr-core >= ${MIN_HC_VERSION} from https://releases.herdr.dev/core/latest.json (windows-x86_64.zip), verify sha256, place herdr-core.exe and hc.exe in %LOCALAPPDATA%\\Programs\\bond and add to PATH`,
381
+ }),
382
+ meta: { version: hcVer, min: MIN_HC_VERSION },
383
+ });
384
+
385
+ // 5. bond CLI
386
+ const targetBondVersion = readBondVersionFromEnv();
387
+ const bondRes = await runCommand('bond', ['--version']);
388
+ const bondVer = bondRes.ok ? extractSemver(bondRes.stdout) : null;
389
+ const bondMissing = !bondRes.ok;
390
+ const bondOutdated = !bondMissing && bondVer !== null && compareVersions(bondVer, targetBondVersion) < 0;
391
+ checks.push({
392
+ id: 'bond',
393
+ name: 'bond CLI',
394
+ status: bondMissing ? 'fail' : bondOutdated ? 'warn' : 'ok',
395
+ essential: true,
396
+ detail: bondMissing
397
+ ? `not found (expected ${targetBondVersion})`
398
+ : bondOutdated
399
+ ? `${bondVer} < ${targetBondVersion}`
400
+ : `${bondVer ?? 'installed'} (target ${targetBondVersion})`,
401
+ fix:
402
+ !bondMissing && !bondOutdated
403
+ ? undefined
404
+ : fixByPlatform(platform, {
405
+ linux: `npm install -g @jmanuelcorral/bond@${targetBondVersion} --@jmanuelcorral:registry=https://registry.npmjs.org/`,
406
+ macos: `npm install -g @jmanuelcorral/bond@${targetBondVersion} --@jmanuelcorral:registry=https://registry.npmjs.org/`,
407
+ windows: `npm install -g @jmanuelcorral/bond@${targetBondVersion} --@jmanuelcorral:registry=https://registry.npmjs.org/`,
408
+ }),
409
+ meta: { version: bondVer, target: targetBondVersion },
410
+ });
411
+
412
+ // 6. gh CLI (optional)
413
+ const ghRes = await runCommand('gh', ['--version']);
414
+ const ghVer = ghRes.ok ? extractSemver(ghRes.stdout) : null;
415
+ checks.push({
416
+ id: 'gh',
417
+ name: 'GitHub CLI (gh)',
418
+ status: ghRes.ok ? 'ok' : 'warn',
419
+ essential: false,
420
+ detail: ghRes.ok ? `${ghVer ?? 'installed'} (optional)` : 'not found (optional)',
421
+ fix: ghRes.ok
422
+ ? undefined
423
+ : fixByPlatform(platform, {
424
+ linux: 'Optional: install gh (https://cli.github.com/) if you use GitHub CLI workflows',
425
+ macos: 'Optional: brew install gh',
426
+ windows: 'Optional: winget install GitHub.cli',
427
+ }),
428
+ meta: { version: ghVer },
429
+ });
430
+
431
+ // 7. Layout, mods and themes in herdr-app home
432
+ let appStatus: AppIntegrationCheckResult;
433
+ try {
434
+ appStatus = checkApp(home);
435
+ } catch (err: unknown) {
436
+ appStatus = {
437
+ installed: false,
438
+ upToDate: false,
439
+ missing: ['app'],
440
+ outdated: [],
441
+ foreign: [],
442
+ };
443
+ }
444
+ const appOk = appStatus.installed && appStatus.upToDate;
445
+ const appProblems = [...appStatus.missing, ...appStatus.outdated, ...appStatus.foreign];
446
+ checks.push({
447
+ id: 'app-integration',
448
+ name: 'Layout, mods & themes',
449
+ status: !appStatus.installed ? 'fail' : appOk ? 'ok' : 'warn',
450
+ essential: true,
451
+ detail: appOk
452
+ ? `installed and up to date in ${home}`
453
+ : !appStatus.installed
454
+ ? `missing in ${home}: ${appStatus.missing.join(', ')}`
455
+ : `outdated or modified in ${home}: ${appProblems.join(', ')}`,
456
+ fix: appOk
457
+ ? undefined
458
+ : fixByPlatform(platform, {
459
+ linux: `bond-app install --home "${home}"${appStatus.outdated.length || appStatus.foreign.length ? ' --force' : ''}`,
460
+ macos: `bond-app install --home "${home}"${appStatus.outdated.length || appStatus.foreign.length ? ' --force' : ''}`,
461
+ windows: `bond-app install --home "${home}"${appStatus.outdated.length || appStatus.foreign.length ? ' --force' : ''}`,
462
+ }),
463
+ meta: { home, ...appStatus },
464
+ });
465
+
466
+ // 8. Data directory and token permissions
467
+ const tokenPath = path.join(dataDir, 'token');
468
+ if (!fs.existsSync(dataDir)) {
469
+ checks.push({
470
+ id: 'data-dir',
471
+ name: 'Data dir & token',
472
+ status: 'warn',
473
+ essential: false,
474
+ detail: `${dataDir} does not exist yet (created on first start)`,
475
+ fix: fixByPlatform(platform, {
476
+ linux: `mkdir -p "${dataDir}" && chmod 700 "${dataDir}" (or run bond-app start)`,
477
+ macos: `mkdir -p "${dataDir}" && chmod 700 "${dataDir}" (or run bond-app start)`,
478
+ windows: `Run bond-app start to initialize ${dataDir}`,
479
+ }),
480
+ meta: { dataDir, tokenPath },
481
+ });
482
+ } else {
483
+ let dirPermBad = false;
484
+ let tokenPermBad = false;
485
+ const tokenExists = fs.existsSync(tokenPath);
486
+ if (platform !== 'windows') {
487
+ try {
488
+ const dStat = fs.statSync(dataDir);
489
+ if ((dStat.mode & 0o077) !== 0) dirPermBad = true;
490
+ } catch {
491
+ dirPermBad = true;
492
+ }
493
+ if (tokenExists) {
494
+ try {
495
+ const tStat = fs.statSync(tokenPath);
496
+ if ((tStat.mode & 0o077) !== 0) tokenPermBad = true;
497
+ } catch {
498
+ tokenPermBad = true;
499
+ }
500
+ }
501
+ } else {
502
+ const winUser = currentWindowsUsername(deps.username);
503
+ if (winUser) {
504
+ const dirAcl = await runCommand('icacls', [dataDir]);
505
+ if (dirAcl.ok && !checkIcaclsOutput(dirAcl.stdout, winUser).ok) {
506
+ dirPermBad = true;
507
+ }
508
+ if (tokenExists) {
509
+ const tokAcl = await runCommand('icacls', [tokenPath]);
510
+ if (tokAcl.ok && !checkIcaclsOutput(tokAcl.stdout, winUser).ok) {
511
+ tokenPermBad = true;
512
+ }
513
+ }
514
+ }
515
+ }
516
+ if (dirPermBad || tokenPermBad) {
517
+ const expectedLabel = platform === 'windows' ? 'user-only ACL' : '0700';
518
+ const expectedTokenLabel = platform === 'windows' ? 'user-only ACL' : '0600';
519
+ const issues = [
520
+ ...(dirPermBad ? [`${dataDir} permissions too open (expected ${expectedLabel})`] : []),
521
+ ...(tokenPermBad ? [`${tokenPath} permissions too open (expected ${expectedTokenLabel})`] : []),
522
+ ];
523
+ const winFixParts = [
524
+ ...(dirPermBad ? [`icacls "${dataDir}" /inheritance:r /grant:r "%USERNAME%:F"`] : []),
525
+ ...(tokenPermBad ? [`icacls "${tokenPath}" /inheritance:r /grant:r "%USERNAME%:F"`] : []),
526
+ ];
527
+ checks.push({
528
+ id: 'data-dir',
529
+ name: 'Data dir & token',
530
+ status: 'fail',
531
+ essential: true,
532
+ detail: issues.join('; '),
533
+ fix: fixByPlatform(platform, {
534
+ linux: `${dirPermBad ? `chmod 700 "${dataDir}"` : ''}${dirPermBad && tokenPermBad ? ' && ' : ''}${tokenPermBad ? `chmod 600 "${tokenPath}"` : ''}`,
535
+ macos: `${dirPermBad ? `chmod 700 "${dataDir}"` : ''}${dirPermBad && tokenPermBad ? ' && ' : ''}${tokenPermBad ? `chmod 600 "${tokenPath}"` : ''}`,
536
+ windows: winFixParts.join(' && '),
537
+ }),
538
+ meta: { dataDir, tokenPath, tokenExists, dirPermBad, tokenPermBad },
539
+ });
540
+ } else if (!tokenExists) {
541
+ checks.push({
542
+ id: 'data-dir',
543
+ name: 'Data dir & token',
544
+ status: 'warn',
545
+ essential: false,
546
+ detail: `${dataDir} ok, token not created yet (generated on first start)`,
547
+ fix: fixByPlatform(platform, {
548
+ linux: 'Run bond-app start once to generate the API token',
549
+ macos: 'Run bond-app start once to generate the API token',
550
+ windows: 'Run bond-app start once to generate the API token',
551
+ }),
552
+ meta: { dataDir, tokenPath, tokenExists: false },
553
+ });
554
+ } else {
555
+ checks.push({
556
+ id: 'data-dir',
557
+ name: 'Data dir & token',
558
+ status: 'ok',
559
+ essential: true,
560
+ detail: `${dataDir} and token permissions ok`,
561
+ meta: { dataDir, tokenPath, tokenExists: true },
562
+ });
563
+ }
564
+ }
565
+
566
+ // 9. Orchestrator status
567
+ let healthOk = false;
568
+ try {
569
+ const h = await checkHealth(host, port, 1500);
570
+ healthOk = h.ok;
571
+ } catch {
572
+ healthOk = false;
573
+ }
574
+ checks.push({
575
+ id: 'orchestrator',
576
+ name: 'Orchestrator API',
577
+ status: healthOk ? 'ok' : 'warn',
578
+ essential: false,
579
+ detail: healthOk ? `listening at http://${host}:${port}` : `not reachable at http://${host}:${port}`,
580
+ fix: healthOk
581
+ ? undefined
582
+ : fixByPlatform(platform, {
583
+ linux: `Start the orchestrator: bond-app start --port ${port}`,
584
+ macos: `Start the orchestrator: bond-app start --port ${port}`,
585
+ windows: `Start the orchestrator: bond-app start --port ${port}`,
586
+ }),
587
+ meta: { host, port, running: healthOk },
588
+ });
589
+
590
+ // 9b. User service status
591
+ const svcStatus = await getServiceStatus({
592
+ port,
593
+ host,
594
+ dataDir,
595
+ deps: {
596
+ runCommand,
597
+ platform: deps.platform,
598
+ ...deps.serviceDeps,
599
+ },
600
+ });
601
+ let svcStatusVal: DoctorStatus = 'warn';
602
+ let svcDetail = svcStatus.detail;
603
+ let svcFix: string | undefined;
604
+ if (!svcStatus.supported || !svcStatus.available) {
605
+ svcStatusVal = 'warn';
606
+ } else if (svcStatus.installed && svcStatus.active) {
607
+ svcStatusVal = 'ok';
608
+ } else if (svcStatus.installed && !svcStatus.active) {
609
+ svcStatusVal = 'warn';
610
+ svcFix = 'bond-app service start';
611
+ } else {
612
+ svcStatusVal = 'warn';
613
+ svcDetail = 'not installed (orchestrator runs manually with bond-app start)';
614
+ svcFix = 'bond-app service install';
615
+ }
616
+ checks.push({
617
+ id: 'service',
618
+ name: 'User service',
619
+ status: svcStatusVal,
620
+ essential: false,
621
+ detail: svcDetail,
622
+ fix: svcFix,
623
+ meta: {
624
+ manager: svcStatus.manager,
625
+ supported: svcStatus.supported,
626
+ available: svcStatus.available,
627
+ installed: svcStatus.installed,
628
+ active: svcStatus.active,
629
+ enabled: svcStatus.enabled,
630
+ unitPath: svcStatus.unitPath,
631
+ },
632
+ });
633
+
634
+ // 10. Runner image
635
+ let liveSetup: SetupStateSummary | null = null;
636
+ if (!explicitImage && healthOk) {
637
+ let apiToken = process.env.BOND_APP_AUTH_TOKEN || '';
638
+ if (!apiToken && fs.existsSync(tokenPath)) {
639
+ try {
640
+ apiToken = fs.readFileSync(tokenPath, 'utf8').trim();
641
+ } catch {
642
+ apiToken = '';
643
+ }
644
+ }
645
+ if (apiToken) {
646
+ try {
647
+ liveSetup = await fetchSetupState(host, port, apiToken, 1500);
648
+ } catch {
649
+ liveSetup = null;
650
+ }
651
+ }
652
+ }
653
+
654
+ if (liveSetup?.image) {
655
+ const expectedRecipe = liveSetup.recipe || (deps.expectedRecipeHash ?? runnerRecipeHash)();
656
+ if (!liveSetup.image.present) {
657
+ checks.push({
658
+ id: 'runner-image',
659
+ name: 'Runner image',
660
+ status: 'warn',
661
+ essential: false,
662
+ detail: `orchestrator reports runner image not found (built in app wizard)`,
663
+ fix: fixByPlatform(platform, {
664
+ linux: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
665
+ macos: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
666
+ windows: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: docker build -t ${runnerImage} runner/)`,
667
+ }),
668
+ meta: { image: runnerImage, present: false, source: 'api' },
669
+ });
670
+ } else {
671
+ const imageRecipe = liveSetup.image.recipe ?? '';
672
+ const recipeOk = imageRecipe === expectedRecipe;
673
+ checks.push({
674
+ id: 'runner-image',
675
+ name: 'Runner image',
676
+ status: recipeOk ? 'ok' : 'warn',
677
+ essential: false,
678
+ detail: recipeOk
679
+ ? `orchestrator image present and recipe up to date (${expectedRecipe})`
680
+ : `orchestrator image recipe outdated (image: ${imageRecipe || 'none'}, current: ${expectedRecipe})`,
681
+ fix: recipeOk
682
+ ? undefined
683
+ : fixByPlatform(platform, {
684
+ linux: `Rebuild '${runnerImage}' in Settings → Image (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
685
+ macos: `Rebuild '${runnerImage}' in Settings → Image (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
686
+ windows: `Rebuild '${runnerImage}' in Settings → Image (or: docker build -t ${runnerImage} runner/)`,
687
+ }),
688
+ meta: { image: runnerImage, present: true, imageRecipe, expectedRecipe, source: 'api' },
689
+ });
690
+ }
691
+ } else if (!dockerReady) {
692
+ checks.push({
693
+ id: 'runner-image',
694
+ name: 'Runner image',
695
+ status: 'warn',
696
+ essential: false,
697
+ detail: `cannot inspect '${runnerImage}' because Docker is not ready`,
698
+ fix: fixByPlatform(platform, {
699
+ linux: 'Fix Docker first, then build the runner image from the app wizard or Settings',
700
+ macos: 'Fix Docker first, then build the runner image from the app wizard or Settings',
701
+ windows: 'Fix Docker first, then build the runner image from the app wizard or Settings',
702
+ }),
703
+ meta: { image: runnerImage },
704
+ });
705
+ } else {
706
+ const inspect = imageInspectRes ?? (await runCommand('docker', ['image', 'inspect', runnerImage, '--format', `{{index .Config.Labels "${LABEL_RECIPE}"}}`]));
707
+ if (!inspect.ok) {
708
+ checks.push({
709
+ id: 'runner-image',
710
+ name: 'Runner image',
711
+ status: 'warn',
712
+ essential: false,
713
+ detail: `image '${runnerImage}' not found (built in app wizard)`,
714
+ fix: fixByPlatform(platform, {
715
+ linux: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
716
+ macos: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
717
+ windows: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: docker build -t ${runnerImage} runner/)`,
718
+ }),
719
+ meta: { image: runnerImage, present: false },
720
+ });
721
+ } else {
722
+ const imageRecipe = inspect.stdout.trim();
723
+ const expectedRecipe = (deps.expectedRecipeHash ?? runnerRecipeHash)();
724
+ const recipeOk = imageRecipe === expectedRecipe;
725
+ checks.push({
726
+ id: 'runner-image',
727
+ name: 'Runner image',
728
+ status: recipeOk ? 'ok' : 'warn',
729
+ essential: false,
730
+ detail: recipeOk
731
+ ? `'${runnerImage}' present and recipe up to date (${expectedRecipe})`
732
+ : `'${runnerImage}' recipe outdated (image: ${imageRecipe || 'none'}, current: ${expectedRecipe})`,
733
+ fix: recipeOk
734
+ ? undefined
735
+ : fixByPlatform(platform, {
736
+ linux: `Rebuild '${runnerImage}' in Settings → Image (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
737
+ macos: `Rebuild '${runnerImage}' in Settings → Image (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
738
+ windows: `Rebuild '${runnerImage}' in Settings → Image (or: docker build -t ${runnerImage} runner/)`,
739
+ }),
740
+ meta: { image: runnerImage, present: true, imageRecipe, expectedRecipe },
741
+ });
742
+ }
743
+ }
744
+
745
+ const summary = {
746
+ ok: checks.filter((c) => c.status === 'ok').length,
747
+ warn: checks.filter((c) => c.status === 'warn').length,
748
+ fail: checks.filter((c) => c.status === 'fail').length,
749
+ };
750
+
751
+ return {
752
+ ok: summary.fail === 0,
753
+ platform,
754
+ checks,
755
+ summary,
756
+ };
757
+ }