@jmanuelcorral/bond-app 0.1.5 → 0.2.0

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.
Files changed (80) hide show
  1. package/README.md +280 -23
  2. package/app/brand/TOKENS.md +5 -5
  3. package/app/layouts/bond.json +10 -14
  4. package/app/mods/bond-agents/api.js +35 -0
  5. package/app/mods/bond-agents/branch.svg +1 -0
  6. package/app/mods/bond-agents/brand.js +53 -2
  7. package/app/mods/bond-agents/config.js +4 -0
  8. package/app/mods/bond-agents/eye-off.svg +1 -0
  9. package/app/mods/bond-agents/eye.svg +1 -0
  10. package/app/mods/bond-agents/main.js +308 -327
  11. package/app/mods/bond-agents/model.js +376 -5
  12. package/app/mods/bond-board/api.js +35 -0
  13. package/app/mods/bond-board/branch.svg +1 -0
  14. package/app/mods/bond-board/brand.js +53 -2
  15. package/app/mods/bond-board/config.js +4 -0
  16. package/app/mods/bond-board/main.js +1000 -449
  17. package/app/mods/bond-board/model.js +170 -28
  18. package/app/mods/bond-pane/close.svg +1 -0
  19. package/app/mods/bond-pane/hide.svg +1 -0
  20. package/app/mods/bond-pane/main.js +103 -0
  21. package/app/mods/bond-pane/mod.json +1 -0
  22. package/app/mods/bond-pane/model.js +18 -0
  23. package/app/mods/bond-pane/split-down.svg +1 -0
  24. package/app/mods/bond-pane/split-right.svg +1 -0
  25. package/app/mods/bond-pane/unzoom.svg +1 -0
  26. package/app/mods/bond-pane/zoom.svg +1 -0
  27. package/app/mods/bond-settings/api.js +35 -0
  28. package/app/mods/bond-settings/brand.js +53 -2
  29. package/app/mods/bond-settings/config.js +4 -0
  30. package/app/mods/bond-settings/main.js +1216 -272
  31. package/app/mods/bond-settings/mod.json +1 -1
  32. package/app/mods/bond-status/api.js +35 -0
  33. package/app/mods/bond-status/brand.js +53 -2
  34. package/app/mods/bond-status/config.js +4 -0
  35. package/app/mods/bond-status/main.js +37 -15
  36. package/app/mods/bond-status/model.js +19 -1
  37. package/app/mods/bond-tabs/brand.js +53 -2
  38. package/app/mods/bond-tabs/main.js +45 -3
  39. package/app/mods/bond-titlebar/brand.js +53 -2
  40. package/app/mods/bond-titlebar/main.js +85 -29
  41. package/app/mods/bond-titlebar/version.js +3 -0
  42. package/app/themes/bond-dark.json +5 -5
  43. package/app/themes/bond-light.json +5 -5
  44. package/package.json +1 -1
  45. package/runner/Dockerfile +16 -2
  46. package/runner/SPIKE-BOND.md +6 -2
  47. package/runner/entrypoint.sh +16 -0
  48. package/runner/setup.sh +439 -8
  49. package/runner/versions.env +32 -1
  50. package/scripts/app-install.ts +322 -27
  51. package/src/cli.ts +562 -21
  52. package/src/config.ts +15 -3
  53. package/src/core/agy-login.ts +683 -0
  54. package/src/core/delivery.ts +125 -6
  55. package/src/core/doctor.ts +748 -0
  56. package/src/core/hub-session.ts +108 -91
  57. package/src/core/hub.ts +40 -8
  58. package/src/core/orchestrator.ts +1481 -187
  59. package/src/core/paths.ts +107 -0
  60. package/src/core/permissions.ts +143 -0
  61. package/src/core/pr-source.ts +147 -0
  62. package/src/core/repo-host.ts +60 -0
  63. package/src/core/service-windows.ts +180 -0
  64. package/src/core/service.ts +861 -0
  65. package/src/core/setup-install.ts +1380 -0
  66. package/src/core/setup.ts +62 -1
  67. package/src/core/watchdog.ts +6 -6
  68. package/src/db/database.ts +54 -7
  69. package/src/db/settings-repo.ts +332 -7
  70. package/src/db/ticket-repo.ts +73 -25
  71. package/src/index.ts +4 -4
  72. package/src/runner/azure-devops-client.ts +273 -0
  73. package/src/runner/docker-client.ts +93 -9
  74. package/src/runner/github-client.ts +148 -3
  75. package/src/runner/hc-client.ts +33 -5
  76. package/src/runner/image-builder.ts +123 -5
  77. package/src/runner/jira-client.ts +368 -0
  78. package/src/runner/tool-catalog.ts +84 -0
  79. package/src/server/app.ts +467 -8
  80. package/src/types.ts +140 -2
@@ -0,0 +1,748 @@
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
+ checks.push({
333
+ id: 'herdr-app',
334
+ name: 'herdr-app',
335
+ status: herdrAppOk ? 'ok' : 'fail',
336
+ essential: true,
337
+ detail: !herdrAppRes.ok
338
+ ? `not found (min ${MIN_HERDR_APP_VERSION})`
339
+ : herdrAppOk
340
+ ? `${herdrAppVer} (>= ${MIN_HERDR_APP_VERSION})`
341
+ : `${herdrAppVer ?? 'unknown'} < ${MIN_HERDR_APP_VERSION}`,
342
+ fix: herdrAppOk
343
+ ? undefined
344
+ : fixByPlatform(platform, {
345
+ 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`,
346
+ 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`,
347
+ 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`,
348
+ }),
349
+ meta: { version: herdrAppVer, min: MIN_HERDR_APP_VERSION },
350
+ });
351
+
352
+ // 4. hc (herdr-core)
353
+ const hcRes = await runCommand('hc', ['--version']);
354
+ const hcVer = hcRes.ok ? extractSemver(hcRes.stdout) : null;
355
+ const hcOk = Boolean(hcVer && compareVersions(hcVer, MIN_HC_VERSION) >= 0);
356
+ checks.push({
357
+ id: 'hc',
358
+ name: 'hc (herdr-core)',
359
+ status: hcOk ? 'ok' : 'fail',
360
+ essential: true,
361
+ detail: !hcRes.ok
362
+ ? `not found (min ${MIN_HC_VERSION})`
363
+ : hcOk
364
+ ? `${hcVer} (>= ${MIN_HC_VERSION})`
365
+ : `${hcVer ?? 'unknown'} < ${MIN_HC_VERSION}`,
366
+ fix: hcOk
367
+ ? undefined
368
+ : fixByPlatform(platform, {
369
+ 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`,
370
+ 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`,
371
+ 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`,
372
+ }),
373
+ meta: { version: hcVer, min: MIN_HC_VERSION },
374
+ });
375
+
376
+ // 5. bond CLI
377
+ const targetBondVersion = readBondVersionFromEnv();
378
+ const bondRes = await runCommand('bond', ['--version']);
379
+ const bondVer = bondRes.ok ? extractSemver(bondRes.stdout) : null;
380
+ const bondMissing = !bondRes.ok;
381
+ const bondOutdated = !bondMissing && bondVer !== null && compareVersions(bondVer, targetBondVersion) < 0;
382
+ checks.push({
383
+ id: 'bond',
384
+ name: 'bond CLI',
385
+ status: bondMissing ? 'fail' : bondOutdated ? 'warn' : 'ok',
386
+ essential: true,
387
+ detail: bondMissing
388
+ ? `not found (expected ${targetBondVersion})`
389
+ : bondOutdated
390
+ ? `${bondVer} < ${targetBondVersion}`
391
+ : `${bondVer ?? 'installed'} (target ${targetBondVersion})`,
392
+ fix:
393
+ !bondMissing && !bondOutdated
394
+ ? undefined
395
+ : fixByPlatform(platform, {
396
+ linux: `npm install -g @jmanuelcorral/bond@${targetBondVersion} --@jmanuelcorral:registry=https://registry.npmjs.org/`,
397
+ macos: `npm install -g @jmanuelcorral/bond@${targetBondVersion} --@jmanuelcorral:registry=https://registry.npmjs.org/`,
398
+ windows: `npm install -g @jmanuelcorral/bond@${targetBondVersion} --@jmanuelcorral:registry=https://registry.npmjs.org/`,
399
+ }),
400
+ meta: { version: bondVer, target: targetBondVersion },
401
+ });
402
+
403
+ // 6. gh CLI (optional)
404
+ const ghRes = await runCommand('gh', ['--version']);
405
+ const ghVer = ghRes.ok ? extractSemver(ghRes.stdout) : null;
406
+ checks.push({
407
+ id: 'gh',
408
+ name: 'GitHub CLI (gh)',
409
+ status: ghRes.ok ? 'ok' : 'warn',
410
+ essential: false,
411
+ detail: ghRes.ok ? `${ghVer ?? 'installed'} (optional)` : 'not found (optional)',
412
+ fix: ghRes.ok
413
+ ? undefined
414
+ : fixByPlatform(platform, {
415
+ linux: 'Optional: install gh (https://cli.github.com/) if you use GitHub CLI workflows',
416
+ macos: 'Optional: brew install gh',
417
+ windows: 'Optional: winget install GitHub.cli',
418
+ }),
419
+ meta: { version: ghVer },
420
+ });
421
+
422
+ // 7. Layout, mods and themes in herdr-app home
423
+ let appStatus: AppIntegrationCheckResult;
424
+ try {
425
+ appStatus = checkApp(home);
426
+ } catch (err: unknown) {
427
+ appStatus = {
428
+ installed: false,
429
+ upToDate: false,
430
+ missing: ['app'],
431
+ outdated: [],
432
+ foreign: [],
433
+ };
434
+ }
435
+ const appOk = appStatus.installed && appStatus.upToDate;
436
+ const appProblems = [...appStatus.missing, ...appStatus.outdated, ...appStatus.foreign];
437
+ checks.push({
438
+ id: 'app-integration',
439
+ name: 'Layout, mods & themes',
440
+ status: !appStatus.installed ? 'fail' : appOk ? 'ok' : 'warn',
441
+ essential: true,
442
+ detail: appOk
443
+ ? `installed and up to date in ${home}`
444
+ : !appStatus.installed
445
+ ? `missing in ${home}: ${appStatus.missing.join(', ')}`
446
+ : `outdated or modified in ${home}: ${appProblems.join(', ')}`,
447
+ fix: appOk
448
+ ? undefined
449
+ : fixByPlatform(platform, {
450
+ linux: `bond-app install --home "${home}"${appStatus.outdated.length || appStatus.foreign.length ? ' --force' : ''}`,
451
+ macos: `bond-app install --home "${home}"${appStatus.outdated.length || appStatus.foreign.length ? ' --force' : ''}`,
452
+ windows: `bond-app install --home "${home}"${appStatus.outdated.length || appStatus.foreign.length ? ' --force' : ''}`,
453
+ }),
454
+ meta: { home, ...appStatus },
455
+ });
456
+
457
+ // 8. Data directory and token permissions
458
+ const tokenPath = path.join(dataDir, 'token');
459
+ if (!fs.existsSync(dataDir)) {
460
+ checks.push({
461
+ id: 'data-dir',
462
+ name: 'Data dir & token',
463
+ status: 'warn',
464
+ essential: false,
465
+ detail: `${dataDir} does not exist yet (created on first start)`,
466
+ fix: fixByPlatform(platform, {
467
+ linux: `mkdir -p "${dataDir}" && chmod 700 "${dataDir}" (or run bond-app start)`,
468
+ macos: `mkdir -p "${dataDir}" && chmod 700 "${dataDir}" (or run bond-app start)`,
469
+ windows: `Run bond-app start to initialize ${dataDir}`,
470
+ }),
471
+ meta: { dataDir, tokenPath },
472
+ });
473
+ } else {
474
+ let dirPermBad = false;
475
+ let tokenPermBad = false;
476
+ const tokenExists = fs.existsSync(tokenPath);
477
+ if (platform !== 'windows') {
478
+ try {
479
+ const dStat = fs.statSync(dataDir);
480
+ if ((dStat.mode & 0o077) !== 0) dirPermBad = true;
481
+ } catch {
482
+ dirPermBad = true;
483
+ }
484
+ if (tokenExists) {
485
+ try {
486
+ const tStat = fs.statSync(tokenPath);
487
+ if ((tStat.mode & 0o077) !== 0) tokenPermBad = true;
488
+ } catch {
489
+ tokenPermBad = true;
490
+ }
491
+ }
492
+ } else {
493
+ const winUser = currentWindowsUsername(deps.username);
494
+ if (winUser) {
495
+ const dirAcl = await runCommand('icacls', [dataDir]);
496
+ if (dirAcl.ok && !checkIcaclsOutput(dirAcl.stdout, winUser).ok) {
497
+ dirPermBad = true;
498
+ }
499
+ if (tokenExists) {
500
+ const tokAcl = await runCommand('icacls', [tokenPath]);
501
+ if (tokAcl.ok && !checkIcaclsOutput(tokAcl.stdout, winUser).ok) {
502
+ tokenPermBad = true;
503
+ }
504
+ }
505
+ }
506
+ }
507
+ if (dirPermBad || tokenPermBad) {
508
+ const expectedLabel = platform === 'windows' ? 'user-only ACL' : '0700';
509
+ const expectedTokenLabel = platform === 'windows' ? 'user-only ACL' : '0600';
510
+ const issues = [
511
+ ...(dirPermBad ? [`${dataDir} permissions too open (expected ${expectedLabel})`] : []),
512
+ ...(tokenPermBad ? [`${tokenPath} permissions too open (expected ${expectedTokenLabel})`] : []),
513
+ ];
514
+ const winFixParts = [
515
+ ...(dirPermBad ? [`icacls "${dataDir}" /inheritance:r /grant:r "%USERNAME%:F"`] : []),
516
+ ...(tokenPermBad ? [`icacls "${tokenPath}" /inheritance:r /grant:r "%USERNAME%:F"`] : []),
517
+ ];
518
+ checks.push({
519
+ id: 'data-dir',
520
+ name: 'Data dir & token',
521
+ status: 'fail',
522
+ essential: true,
523
+ detail: issues.join('; '),
524
+ fix: fixByPlatform(platform, {
525
+ linux: `${dirPermBad ? `chmod 700 "${dataDir}"` : ''}${dirPermBad && tokenPermBad ? ' && ' : ''}${tokenPermBad ? `chmod 600 "${tokenPath}"` : ''}`,
526
+ macos: `${dirPermBad ? `chmod 700 "${dataDir}"` : ''}${dirPermBad && tokenPermBad ? ' && ' : ''}${tokenPermBad ? `chmod 600 "${tokenPath}"` : ''}`,
527
+ windows: winFixParts.join(' && '),
528
+ }),
529
+ meta: { dataDir, tokenPath, tokenExists, dirPermBad, tokenPermBad },
530
+ });
531
+ } else if (!tokenExists) {
532
+ checks.push({
533
+ id: 'data-dir',
534
+ name: 'Data dir & token',
535
+ status: 'warn',
536
+ essential: false,
537
+ detail: `${dataDir} ok, token not created yet (generated on first start)`,
538
+ fix: fixByPlatform(platform, {
539
+ linux: 'Run bond-app start once to generate the API token',
540
+ macos: 'Run bond-app start once to generate the API token',
541
+ windows: 'Run bond-app start once to generate the API token',
542
+ }),
543
+ meta: { dataDir, tokenPath, tokenExists: false },
544
+ });
545
+ } else {
546
+ checks.push({
547
+ id: 'data-dir',
548
+ name: 'Data dir & token',
549
+ status: 'ok',
550
+ essential: true,
551
+ detail: `${dataDir} and token permissions ok`,
552
+ meta: { dataDir, tokenPath, tokenExists: true },
553
+ });
554
+ }
555
+ }
556
+
557
+ // 9. Orchestrator status
558
+ let healthOk = false;
559
+ try {
560
+ const h = await checkHealth(host, port, 1500);
561
+ healthOk = h.ok;
562
+ } catch {
563
+ healthOk = false;
564
+ }
565
+ checks.push({
566
+ id: 'orchestrator',
567
+ name: 'Orchestrator API',
568
+ status: healthOk ? 'ok' : 'warn',
569
+ essential: false,
570
+ detail: healthOk ? `listening at http://${host}:${port}` : `not reachable at http://${host}:${port}`,
571
+ fix: healthOk
572
+ ? undefined
573
+ : fixByPlatform(platform, {
574
+ linux: `Start the orchestrator: bond-app start --port ${port}`,
575
+ macos: `Start the orchestrator: bond-app start --port ${port}`,
576
+ windows: `Start the orchestrator: bond-app start --port ${port}`,
577
+ }),
578
+ meta: { host, port, running: healthOk },
579
+ });
580
+
581
+ // 9b. User service status
582
+ const svcStatus = await getServiceStatus({
583
+ port,
584
+ host,
585
+ dataDir,
586
+ deps: {
587
+ runCommand,
588
+ platform: deps.platform,
589
+ ...deps.serviceDeps,
590
+ },
591
+ });
592
+ let svcStatusVal: DoctorStatus = 'warn';
593
+ let svcDetail = svcStatus.detail;
594
+ let svcFix: string | undefined;
595
+ if (!svcStatus.supported || !svcStatus.available) {
596
+ svcStatusVal = 'warn';
597
+ } else if (svcStatus.installed && svcStatus.active) {
598
+ svcStatusVal = 'ok';
599
+ } else if (svcStatus.installed && !svcStatus.active) {
600
+ svcStatusVal = 'warn';
601
+ svcFix = 'bond-app service start';
602
+ } else {
603
+ svcStatusVal = 'warn';
604
+ svcDetail = 'not installed (orchestrator runs manually with bond-app start)';
605
+ svcFix = 'bond-app service install';
606
+ }
607
+ checks.push({
608
+ id: 'service',
609
+ name: 'User service',
610
+ status: svcStatusVal,
611
+ essential: false,
612
+ detail: svcDetail,
613
+ fix: svcFix,
614
+ meta: {
615
+ manager: svcStatus.manager,
616
+ supported: svcStatus.supported,
617
+ available: svcStatus.available,
618
+ installed: svcStatus.installed,
619
+ active: svcStatus.active,
620
+ enabled: svcStatus.enabled,
621
+ unitPath: svcStatus.unitPath,
622
+ },
623
+ });
624
+
625
+ // 10. Runner image
626
+ let liveSetup: SetupStateSummary | null = null;
627
+ if (!explicitImage && healthOk) {
628
+ let apiToken = process.env.BOND_APP_AUTH_TOKEN || '';
629
+ if (!apiToken && fs.existsSync(tokenPath)) {
630
+ try {
631
+ apiToken = fs.readFileSync(tokenPath, 'utf8').trim();
632
+ } catch {
633
+ apiToken = '';
634
+ }
635
+ }
636
+ if (apiToken) {
637
+ try {
638
+ liveSetup = await fetchSetupState(host, port, apiToken, 1500);
639
+ } catch {
640
+ liveSetup = null;
641
+ }
642
+ }
643
+ }
644
+
645
+ if (liveSetup?.image) {
646
+ const expectedRecipe = liveSetup.recipe || (deps.expectedRecipeHash ?? runnerRecipeHash)();
647
+ if (!liveSetup.image.present) {
648
+ checks.push({
649
+ id: 'runner-image',
650
+ name: 'Runner image',
651
+ status: 'warn',
652
+ essential: false,
653
+ detail: `orchestrator reports runner image not found (built in app wizard)`,
654
+ fix: fixByPlatform(platform, {
655
+ linux: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
656
+ macos: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
657
+ windows: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: docker build -t ${runnerImage} runner/)`,
658
+ }),
659
+ meta: { image: runnerImage, present: false, source: 'api' },
660
+ });
661
+ } else {
662
+ const imageRecipe = liveSetup.image.recipe ?? '';
663
+ const recipeOk = imageRecipe === expectedRecipe;
664
+ checks.push({
665
+ id: 'runner-image',
666
+ name: 'Runner image',
667
+ status: recipeOk ? 'ok' : 'warn',
668
+ essential: false,
669
+ detail: recipeOk
670
+ ? `orchestrator image present and recipe up to date (${expectedRecipe})`
671
+ : `orchestrator image recipe outdated (image: ${imageRecipe || 'none'}, current: ${expectedRecipe})`,
672
+ fix: recipeOk
673
+ ? undefined
674
+ : fixByPlatform(platform, {
675
+ linux: `Rebuild '${runnerImage}' in Settings → Image (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
676
+ macos: `Rebuild '${runnerImage}' in Settings → Image (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
677
+ windows: `Rebuild '${runnerImage}' in Settings → Image (or: docker build -t ${runnerImage} runner/)`,
678
+ }),
679
+ meta: { image: runnerImage, present: true, imageRecipe, expectedRecipe, source: 'api' },
680
+ });
681
+ }
682
+ } else if (!dockerReady) {
683
+ checks.push({
684
+ id: 'runner-image',
685
+ name: 'Runner image',
686
+ status: 'warn',
687
+ essential: false,
688
+ detail: `cannot inspect '${runnerImage}' because Docker is not ready`,
689
+ fix: fixByPlatform(platform, {
690
+ linux: 'Fix Docker first, then build the runner image from the app wizard or Settings',
691
+ macos: 'Fix Docker first, then build the runner image from the app wizard or Settings',
692
+ windows: 'Fix Docker first, then build the runner image from the app wizard or Settings',
693
+ }),
694
+ meta: { image: runnerImage },
695
+ });
696
+ } else {
697
+ const inspect = imageInspectRes ?? (await runCommand('docker', ['image', 'inspect', runnerImage, '--format', `{{index .Config.Labels "${LABEL_RECIPE}"}}`]));
698
+ if (!inspect.ok) {
699
+ checks.push({
700
+ id: 'runner-image',
701
+ name: 'Runner image',
702
+ status: 'warn',
703
+ essential: false,
704
+ detail: `image '${runnerImage}' not found (built in app wizard)`,
705
+ fix: fixByPlatform(platform, {
706
+ linux: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
707
+ macos: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
708
+ windows: `Open herdr-app wizard or Settings → Image to build '${runnerImage}' (or: docker build -t ${runnerImage} runner/)`,
709
+ }),
710
+ meta: { image: runnerImage, present: false },
711
+ });
712
+ } else {
713
+ const imageRecipe = inspect.stdout.trim();
714
+ const expectedRecipe = (deps.expectedRecipeHash ?? runnerRecipeHash)();
715
+ const recipeOk = imageRecipe === expectedRecipe;
716
+ checks.push({
717
+ id: 'runner-image',
718
+ name: 'Runner image',
719
+ status: recipeOk ? 'ok' : 'warn',
720
+ essential: false,
721
+ detail: recipeOk
722
+ ? `'${runnerImage}' present and recipe up to date (${expectedRecipe})`
723
+ : `'${runnerImage}' recipe outdated (image: ${imageRecipe || 'none'}, current: ${expectedRecipe})`,
724
+ fix: recipeOk
725
+ ? undefined
726
+ : fixByPlatform(platform, {
727
+ linux: `Rebuild '${runnerImage}' in Settings → Image (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
728
+ macos: `Rebuild '${runnerImage}' in Settings → Image (or: DOCKER_BUILDKIT=0 docker build -t ${runnerImage} runner/)`,
729
+ windows: `Rebuild '${runnerImage}' in Settings → Image (or: docker build -t ${runnerImage} runner/)`,
730
+ }),
731
+ meta: { image: runnerImage, present: true, imageRecipe, expectedRecipe },
732
+ });
733
+ }
734
+ }
735
+
736
+ const summary = {
737
+ ok: checks.filter((c) => c.status === 'ok').length,
738
+ warn: checks.filter((c) => c.status === 'warn').length,
739
+ fail: checks.filter((c) => c.status === 'fail').length,
740
+ };
741
+
742
+ return {
743
+ ok: summary.fail === 0,
744
+ platform,
745
+ checks,
746
+ summary,
747
+ };
748
+ }