@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
package/src/cli.ts CHANGED
@@ -8,31 +8,63 @@
8
8
  * - --version, --help.
9
9
  */
10
10
  import fs from 'node:fs';
11
- import os from 'node:os';
12
11
  import path from 'node:path';
13
12
  import http from 'node:http';
14
13
  import { spawn, execFileSync } from 'node:child_process';
15
14
  import { fileURLToPath } from 'node:url';
16
15
 
17
16
  import { bootstrap } from './index.ts';
17
+ import type { ServerHooks } from './server/app.ts';
18
18
  import { MIN_HC_VERSION, MIN_HERDR_APP_VERSION } from './runner/hc-client.ts';
19
19
  import { install, parseInstallArgs, removeLauncher } from '../scripts/app-install.ts';
20
+ import { runDoctor, type DoctorDeps, type DoctorReport } from './core/doctor.ts';
21
+ import {
22
+ maybeHandleFirstRun,
23
+ runSetup,
24
+ runUninstall,
25
+ runUpdate,
26
+ warnFirstRunIfNeeded,
27
+ type SetupDeps,
28
+ } from './core/setup-install.ts';
29
+ import {
30
+ getServiceStatus,
31
+ installService,
32
+ restartService,
33
+ startService,
34
+ stopService,
35
+ uninstallService,
36
+ type ServiceAction,
37
+ type ServiceDeps,
38
+ } from './core/service.ts';
39
+ import { defaultDataDir, defaultHerdrAppHome, defaultLauncherDataHome } from './core/paths.ts';
40
+ import { restrictPathSync } from './core/permissions.ts';
20
41
 
21
42
  const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
22
43
  const pkgJson = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8'));
23
44
  export const VERSION = pkgJson.version as string;
24
45
 
25
- export function findExecutable(name: string, customPath?: string): string | null {
46
+ export function findExecutable(
47
+ name: string,
48
+ customPath?: string,
49
+ platform: NodeJS.Platform = process.platform
50
+ ): string | null {
26
51
  const pathEnv = customPath ?? process.env.PATH ?? '';
52
+ const candidates =
53
+ platform === 'win32' && !/\.(exe|cmd|bat)$/i.test(name)
54
+ ? [`${name}.exe`, `${name}.cmd`, name]
55
+ : [name];
56
+ const mode = platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK;
27
57
  for (const dir of pathEnv.split(path.delimiter)) {
28
58
  if (!dir || !path.isAbsolute(dir)) continue;
29
- const full = path.join(dir, name);
30
- try {
31
- fs.accessSync(full, fs.constants.X_OK);
32
- const st = fs.statSync(full);
33
- if (st.isFile()) return full;
34
- } catch {
35
- // not executable or does not exist
59
+ for (const candidate of candidates) {
60
+ const full = path.join(dir, candidate);
61
+ try {
62
+ fs.accessSync(full, mode);
63
+ const st = fs.statSync(full);
64
+ if (st.isFile()) return full;
65
+ } catch {
66
+ // not executable or does not exist
67
+ }
36
68
  }
37
69
  }
38
70
  return null;
@@ -209,9 +241,40 @@ export async function queryStatus(opts: StatusOptions): Promise<StatusResult> {
209
241
  };
210
242
  }
211
243
 
244
+ /**
245
+ * «Reiniciar orquestador»: start this same command again, detached, with the same argv,
246
+ * execArgv and environment (so RUNNER_IMAGE, --port and --data-dir survive). Its output
247
+ * goes to <data dir>/orchestrator.log: the terminal that started us may be gone.
248
+ */
249
+ export function relaunchSelf(dataDir: string, spawnFn: typeof spawn = spawn): number | undefined {
250
+ fs.mkdirSync(dataDir, { recursive: true });
251
+ const logPath = path.join(dataDir, 'orchestrator.log');
252
+ const fd = fs.openSync(logPath, 'a', 0o600);
253
+ try {
254
+ restrictPathSync(logPath, 0o600);
255
+ } catch {
256
+ // ignore permission errors
257
+ }
258
+ try {
259
+ const child = spawnFn(process.execPath, [...process.execArgv, ...process.argv.slice(1)], {
260
+ detached: true,
261
+ stdio: ['ignore', fd, fd],
262
+ env: process.env,
263
+ cwd: process.cwd(),
264
+ });
265
+ child.unref();
266
+ console.log(`[bond-app] Restarting in the background (pid ${child.pid}); log: ${logPath}`);
267
+ return child.pid;
268
+ } finally {
269
+ fs.closeSync(fd);
270
+ }
271
+ }
272
+
212
273
  export async function handleStart(
213
274
  args: string[],
214
- bootstrapFn: (overrides?: any) => Promise<{ server: any; orchestrator: any; port: number }> = bootstrap
275
+ bootstrapFn: (overrides?: any, hooks?: ServerHooks) => Promise<{ server: any; orchestrator: any; port: number }> = bootstrap,
276
+ relaunchFn: (dataDir: string) => unknown = relaunchSelf,
277
+ setupDeps?: SetupDeps
215
278
  ): Promise<number> {
216
279
  const overrides: Record<string, any> = {};
217
280
  for (let i = 0; i < args.length; i++) {
@@ -236,8 +299,53 @@ export async function handleStart(
236
299
  }
237
300
  }
238
301
 
302
+ const isTTY = setupDeps?.isTTY ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
303
+ if (isTTY) {
304
+ const firstRun = await maybeHandleFirstRun({
305
+ fromStart: true,
306
+ dataDir: overrides.dataDir,
307
+ deps: setupDeps,
308
+ });
309
+ if (firstRun.ranSetup && !firstRun.setupOk) {
310
+ return 1;
311
+ }
312
+ } else {
313
+ warnFirstRunIfNeeded({ dataDir: overrides.dataDir, deps: setupDeps });
314
+ }
315
+
316
+ const startPort = overrides.port ?? parseInt(process.env.BOND_APP_PORT || '3000', 10);
317
+ const startHost = overrides.host ?? process.env.BOND_APP_HOST ?? '127.0.0.1';
318
+ const startDataDir =
319
+ overrides.dataDir ?? process.env.BOND_APP_DATA_DIR ?? defaultDataDir();
320
+
321
+ if (bootstrapFn === bootstrap || setupDeps?.serviceDeps || setupDeps?.checkHealth) {
322
+ const svcStatus = await getServiceStatus({
323
+ port: startPort,
324
+ host: startHost,
325
+ dataDir: startDataDir,
326
+ deps: setupDeps?.serviceDeps,
327
+ });
328
+ if (svcStatus.active) {
329
+ console.error(
330
+ `bond-app: port ${startPort} is already in use by the bond-app user service (${svcStatus.serviceName}).`
331
+ );
332
+ console.error('Stop it first with: bond-app service stop');
333
+ return 1;
334
+ }
335
+
336
+ const checkHealthFn = setupDeps?.checkHealth ?? checkHttpHealth;
337
+ const existingHealth = await checkHealthFn(startHost, startPort, 1000).catch(() => ({ ok: false }));
338
+ if (existingHealth.ok) {
339
+ console.error(
340
+ `bond-app: port ${startPort} is already in use by a running orchestrator at http://${startHost}:${startPort}.`
341
+ );
342
+ return 1;
343
+ }
344
+ }
345
+
239
346
  return new Promise<number>((resolve, reject) => {
240
347
  let shuttingDown = false;
348
+ let restartRequested = false;
241
349
  let serverInstance: any = null;
242
350
  let orchestratorInstance: any = null;
243
351
  let bootstrapPromise: Promise<{ server: any; orchestrator: any }> | null = null;
@@ -263,7 +371,11 @@ export async function handleStart(
263
371
  }
264
372
  try {
265
373
  if (serverInstance) {
266
- await new Promise<void>((r) => serverInstance.close(() => r()));
374
+ await new Promise<void>((r) => {
375
+ serverInstance.close(() => r());
376
+ // Keep-alive connections (the mods poll) would hold close() open.
377
+ serverInstance.closeAllConnections?.();
378
+ });
267
379
  }
268
380
  } catch (err: any) {
269
381
  console.warn(`[bond-app] Error closing HTTP server: ${err?.message || err}`);
@@ -276,6 +388,18 @@ export async function handleStart(
276
388
  console.warn(`[bond-app] Error stopping orchestrator: ${err?.message || err}`);
277
389
  }
278
390
  console.log('[bond-app] Orchestrator stopped cleanly.');
391
+ if (restartRequested) {
392
+ const dataDir = orchestratorInstance?.config?.dataDir
393
+ || overrides.dataDir
394
+ || defaultDataDir();
395
+ try {
396
+ relaunchFn(dataDir);
397
+ } catch (err: any) {
398
+ console.error(`[bond-app] Could not restart: ${err?.message || err}`);
399
+ resolve(1);
400
+ return;
401
+ }
402
+ }
279
403
  resolve(0);
280
404
  };
281
405
 
@@ -285,7 +409,13 @@ export async function handleStart(
285
409
  process.once('SIGINT', sigintHandler);
286
410
  process.once('SIGTERM', sigtermHandler);
287
411
 
288
- bootstrapPromise = bootstrapFn(overrides);
412
+ const hooks: ServerHooks = {
413
+ onRestart: () => {
414
+ restartRequested = true;
415
+ void shutdown('restart request');
416
+ },
417
+ };
418
+ bootstrapPromise = bootstrapFn(overrides, hooks);
289
419
  bootstrapPromise
290
420
  .then(({ server, orchestrator }) => {
291
421
  serverInstance = server;
@@ -307,10 +437,7 @@ export async function handleInstall(args: string[]): Promise<number> {
307
437
  }
308
438
 
309
439
  if (args.includes('--remove-launcher')) {
310
- const dataHome =
311
- process.env.XDG_DATA_HOME && path.isAbsolute(process.env.XDG_DATA_HOME)
312
- ? process.env.XDG_DATA_HOME
313
- : path.join(os.homedir(), '.local', 'share');
440
+ const dataHome = defaultLauncherDataHome();
314
441
  const { removed, kept } = removeLauncher(dataHome);
315
442
  console.log(
316
443
  removed.length
@@ -368,8 +495,8 @@ export async function handleOpen(args: string[]): Promise<number> {
368
495
  export async function handleStatus(args: string[]): Promise<number> {
369
496
  let port = parseInt(process.env.BOND_APP_PORT || '3000', 10);
370
497
  let host = process.env.BOND_APP_HOST || '127.0.0.1';
371
- let dataDir = process.env.BOND_APP_DATA_DIR || path.join(os.homedir(), '.bond-app');
372
- let home = process.env.HERDR_APP_HOME || path.join(os.homedir(), '.config', 'herdr-app');
498
+ let dataDir = defaultDataDir();
499
+ let home = defaultHerdrAppHome();
373
500
  let json = false;
374
501
 
375
502
  for (let i = 0; i < args.length; i++) {
@@ -422,14 +549,316 @@ export async function handleStatus(args: string[]): Promise<number> {
422
549
  return res.running ? 0 : 1;
423
550
  }
424
551
 
552
+ export async function handleDoctor(args: string[], deps?: DoctorDeps): Promise<number> {
553
+ let port = parseInt(process.env.BOND_APP_PORT || '3000', 10);
554
+ let host = process.env.BOND_APP_HOST || '127.0.0.1';
555
+ let dataDir = defaultDataDir();
556
+ let home = defaultHerdrAppHome();
557
+ let runnerImage: string | undefined = undefined;
558
+ let json = false;
559
+
560
+ for (let i = 0; i < args.length; i++) {
561
+ const arg = args[i];
562
+ if (arg === '--port') {
563
+ const v = args[++i];
564
+ if (!v || v.startsWith('--')) throw new Error('--port requires a value');
565
+ port = parseInt(v, 10);
566
+ } else if (arg === '--host') {
567
+ const v = args[++i];
568
+ if (!v || v.startsWith('--')) throw new Error('--host requires a value');
569
+ host = v;
570
+ } else if (arg === '--data-dir') {
571
+ const v = args[++i];
572
+ if (!v || v.startsWith('--')) throw new Error('--data-dir requires a value');
573
+ dataDir = path.resolve(v);
574
+ } else if (arg === '--home') {
575
+ const v = args[++i];
576
+ if (!v || v.startsWith('--')) throw new Error('--home requires a value');
577
+ home = path.resolve(v);
578
+ } else if (arg === '--image') {
579
+ const v = args[++i];
580
+ if (!v || v.startsWith('--')) throw new Error('--image requires a value');
581
+ runnerImage = v;
582
+ } else if (arg === '--json') {
583
+ json = true;
584
+ } else if (arg === '-h' || arg === '--help') {
585
+ printDoctorHelp();
586
+ return 0;
587
+ } else {
588
+ throw new Error(`unknown option '${arg}' for doctor`);
589
+ }
590
+ }
591
+
592
+ const report: DoctorReport = await runDoctor({ port, host, dataDir, home, runnerImage, deps });
593
+
594
+ if (json) {
595
+ console.log(JSON.stringify(report, null, 2));
596
+ return report.ok ? 0 : 1;
597
+ }
598
+
599
+ console.log(`bond-app doctor (${report.platform})`);
600
+ for (const c of report.checks) {
601
+ const icon = c.status === 'ok' ? '✓' : c.status === 'warn' ? '!' : '✗';
602
+ console.log(` ${icon} ${c.name}: ${c.detail}`);
603
+ if (c.fix) {
604
+ console.log(` fix: ${c.fix}`);
605
+ }
606
+ }
607
+ console.log(`Summary: ${report.summary.ok} ok, ${report.summary.warn} warn, ${report.summary.fail} fail`);
608
+
609
+ return report.ok ? 0 : 1;
610
+ }
611
+
612
+ export async function handleSetup(args: string[], deps?: SetupDeps): Promise<number> {
613
+ let yes = false;
614
+ let noLauncher = false;
615
+ let noService = false;
616
+ let dryRun = false;
617
+ let port: number | undefined = undefined;
618
+ let host: string | undefined = undefined;
619
+ let dataDir: string | undefined = undefined;
620
+ let home: string | undefined = undefined;
621
+ let runnerImage: string | undefined = undefined;
622
+
623
+ for (let i = 0; i < args.length; i++) {
624
+ const arg = args[i];
625
+ if (arg === '--yes' || arg === '-y') {
626
+ yes = true;
627
+ } else if (arg === '--no-launcher') {
628
+ noLauncher = true;
629
+ } else if (arg === '--no-service') {
630
+ noService = true;
631
+ } else if (arg === '--dry-run') {
632
+ dryRun = true;
633
+ } else if (arg === '--port') {
634
+ const v = args[++i];
635
+ if (!v || v.startsWith('--')) throw new Error('--port requires a value');
636
+ port = parseInt(v, 10);
637
+ } else if (arg === '--host') {
638
+ const v = args[++i];
639
+ if (!v || v.startsWith('--')) throw new Error('--host requires a value');
640
+ host = v;
641
+ } else if (arg === '--data-dir') {
642
+ const v = args[++i];
643
+ if (!v || v.startsWith('--')) throw new Error('--data-dir requires a value');
644
+ dataDir = path.resolve(v);
645
+ } else if (arg === '--home') {
646
+ const v = args[++i];
647
+ if (!v || v.startsWith('--')) throw new Error('--home requires a value');
648
+ home = path.resolve(v);
649
+ } else if (arg === '--image') {
650
+ const v = args[++i];
651
+ if (!v || v.startsWith('--')) throw new Error('--image requires a value');
652
+ runnerImage = v;
653
+ } else if (arg === '-h' || arg === '--help') {
654
+ printSetupHelp();
655
+ return 0;
656
+ } else {
657
+ throw new Error(`unknown option '${arg}' for setup`);
658
+ }
659
+ }
660
+
661
+ const res = await runSetup({
662
+ yes,
663
+ noLauncher,
664
+ noService,
665
+ dryRun,
666
+ port,
667
+ host,
668
+ dataDir,
669
+ home,
670
+ runnerImage,
671
+ deps,
672
+ });
673
+ return res.ok ? 0 : 1;
674
+ }
675
+
676
+ export async function handleUpdate(args: string[], deps?: SetupDeps): Promise<number> {
677
+ let dryRun = false;
678
+ let port: number | undefined = undefined;
679
+ let host: string | undefined = undefined;
680
+ let dataDir: string | undefined = undefined;
681
+ let home: string | undefined = undefined;
682
+ let runnerImage: string | undefined = undefined;
683
+
684
+ for (let i = 0; i < args.length; i++) {
685
+ const arg = args[i];
686
+ if (arg === '--dry-run') {
687
+ dryRun = true;
688
+ } else if (arg === '--port') {
689
+ const v = args[++i];
690
+ if (!v || v.startsWith('--')) throw new Error('--port requires a value');
691
+ port = parseInt(v, 10);
692
+ } else if (arg === '--host') {
693
+ const v = args[++i];
694
+ if (!v || v.startsWith('--')) throw new Error('--host requires a value');
695
+ host = v;
696
+ } else if (arg === '--data-dir') {
697
+ const v = args[++i];
698
+ if (!v || v.startsWith('--')) throw new Error('--data-dir requires a value');
699
+ dataDir = path.resolve(v);
700
+ } else if (arg === '--home') {
701
+ const v = args[++i];
702
+ if (!v || v.startsWith('--')) throw new Error('--home requires a value');
703
+ home = path.resolve(v);
704
+ } else if (arg === '--image') {
705
+ const v = args[++i];
706
+ if (!v || v.startsWith('--')) throw new Error('--image requires a value');
707
+ runnerImage = v;
708
+ } else if (arg === '-h' || arg === '--help') {
709
+ printUpdateHelp();
710
+ return 0;
711
+ } else {
712
+ throw new Error(`unknown option '${arg}' for update`);
713
+ }
714
+ }
715
+
716
+ const res = await runUpdate({ dryRun, port, host, dataDir, home, runnerImage, deps });
717
+ return res.ok ? 0 : 1;
718
+ }
719
+
720
+ export async function handleUninstall(args: string[], deps?: SetupDeps): Promise<number> {
721
+ let purge = false;
722
+ let yes = false;
723
+ let dryRun = false;
724
+ let port: number | undefined = undefined;
725
+ let host: string | undefined = undefined;
726
+ let dataDir: string | undefined = undefined;
727
+ let home: string | undefined = undefined;
728
+
729
+ for (let i = 0; i < args.length; i++) {
730
+ const arg = args[i];
731
+ if (arg === '--purge') {
732
+ purge = true;
733
+ } else if (arg === '--yes' || arg === '-y') {
734
+ yes = true;
735
+ } else if (arg === '--dry-run') {
736
+ dryRun = true;
737
+ } else if (arg === '--port') {
738
+ const v = args[++i];
739
+ if (!v || v.startsWith('--')) throw new Error('--port requires a value');
740
+ port = parseInt(v, 10);
741
+ } else if (arg === '--host') {
742
+ const v = args[++i];
743
+ if (!v || v.startsWith('--')) throw new Error('--host requires a value');
744
+ host = v;
745
+ } else if (arg === '--data-dir') {
746
+ const v = args[++i];
747
+ if (!v || v.startsWith('--')) throw new Error('--data-dir requires a value');
748
+ dataDir = path.resolve(v);
749
+ } else if (arg === '--home') {
750
+ const v = args[++i];
751
+ if (!v || v.startsWith('--')) throw new Error('--home requires a value');
752
+ home = path.resolve(v);
753
+ } else if (arg === '-h' || arg === '--help') {
754
+ printUninstallHelp();
755
+ return 0;
756
+ } else {
757
+ throw new Error(`unknown option '${arg}' for uninstall`);
758
+ }
759
+ }
760
+
761
+ const res = await runUninstall({ purge, yes, dryRun, port, host, dataDir, home, deps });
762
+ return res.ok ? 0 : 1;
763
+ }
764
+
765
+ export async function handleService(args: string[], deps?: ServiceDeps): Promise<number> {
766
+ if (args.length === 0 || args[0] === '-h' || args[0] === '--help') {
767
+ printServiceHelp();
768
+ return 0;
769
+ }
770
+
771
+ const sub = args[0] as ServiceAction;
772
+ const validActions: ServiceAction[] = ['status', 'install', 'start', 'stop', 'restart', 'uninstall'];
773
+ if (!validActions.includes(sub)) {
774
+ throw new Error(`unknown service action '${args[0]}' (expected: ${validActions.join('|')})`);
775
+ }
776
+
777
+ let port: number | undefined = undefined;
778
+ let host: string | undefined = undefined;
779
+ let dataDir: string | undefined = undefined;
780
+ let runnerImage: string | undefined = undefined;
781
+ let serviceName: string | undefined = undefined;
782
+ let json = false;
783
+
784
+ for (let i = 1; i < args.length; i++) {
785
+ const arg = args[i];
786
+ if (arg === '--port') {
787
+ const v = args[++i];
788
+ if (!v || v.startsWith('--')) throw new Error('--port requires a value');
789
+ port = parseInt(v, 10);
790
+ } else if (arg === '--host') {
791
+ const v = args[++i];
792
+ if (!v || v.startsWith('--')) throw new Error('--host requires a value');
793
+ host = v;
794
+ } else if (arg === '--data-dir') {
795
+ const v = args[++i];
796
+ if (!v || v.startsWith('--')) throw new Error('--data-dir requires a value');
797
+ dataDir = path.resolve(v);
798
+ } else if (arg === '--image') {
799
+ const v = args[++i];
800
+ if (!v || v.startsWith('--')) throw new Error('--image requires a value');
801
+ runnerImage = v;
802
+ } else if (arg === '--name') {
803
+ const v = args[++i];
804
+ if (!v || v.startsWith('--')) throw new Error('--name requires a value');
805
+ serviceName = v;
806
+ } else if (arg === '--json') {
807
+ json = true;
808
+ } else if (arg === '-h' || arg === '--help') {
809
+ printServiceHelp();
810
+ return 0;
811
+ } else {
812
+ throw new Error(`unknown option '${arg}' for service ${sub}`);
813
+ }
814
+ }
815
+
816
+ const opts = { port, host, dataDir, runnerImage, serviceName, deps };
817
+
818
+ if (sub === 'status') {
819
+ const st = await getServiceStatus(opts);
820
+ if (json) {
821
+ console.log(JSON.stringify(st, null, 2));
822
+ return st.supported && st.active ? 0 : 1;
823
+ }
824
+ console.log(`bond-app service (${st.manager}): ${st.detail}`);
825
+ if (st.unitPath) console.log(` unit: ${st.unitPath}`);
826
+ console.log(` installed: ${st.installed ? 'yes' : 'no'}, active: ${st.active ? 'yes' : 'no'}`);
827
+ return st.supported && st.active ? 0 : 1;
828
+ }
829
+
830
+ const actionMap = {
831
+ install: installService,
832
+ start: startService,
833
+ stop: stopService,
834
+ restart: restartService,
835
+ uninstall: uninstallService,
836
+ } as const;
837
+
838
+ const res = await actionMap[sub](opts);
839
+ if (json) {
840
+ console.log(JSON.stringify(res, null, 2));
841
+ } else if (res.ok) {
842
+ console.log(`bond-app service ${sub}: ${res.detail}`);
843
+ } else {
844
+ console.error(`bond-app service ${sub}: ${res.detail}`);
845
+ }
846
+ return res.ok ? 0 : 1;
847
+ }
848
+
425
849
  export function printHelp(): void {
426
850
  console.log(`Usage: bond-app <command> [options]
427
851
 
428
852
  Commands:
853
+ setup Check requirements, install binaries/mods, prepare ~/.bond-app and open herdr-app
854
+ update Update bond-app and bond via npm, reinstall mods, restart service and check image
855
+ uninstall Remove service, bond-app mods/layout/themes and launcher (data only with --purge)
856
+ service Manage the orchestrator user service (status|install|start|stop|restart|uninstall)
429
857
  start Run the orchestrator in the foreground (default data dir: ~/.bond-app)
430
858
  install Install bond layout, mods and themes into herdr-app
431
859
  open Open herdr-app and switch to the bond layout
432
860
  status Check the status of the orchestrator and herdr-app integration
861
+ doctor Diagnose requirements, binaries, mods, data dir, orchestrator and image
433
862
 
434
863
  Options:
435
864
  -v, --version Show version number
@@ -496,9 +925,111 @@ Options:
496
925
  `);
497
926
  }
498
927
 
499
- export async function runCli(argv: string[]): Promise<number> {
928
+ function printDoctorHelp(): void {
929
+ console.log(`Usage: bond-app doctor [options]
930
+
931
+ Diagnose environment requirements without modifying anything.
932
+ Exits 0 if no essential check fails, 1 otherwise.
933
+
934
+ Options:
935
+ --port <port> Orchestrator port to query (default: 3000 or $BOND_APP_PORT)
936
+ --host <host> Orchestrator host to query (default: 127.0.0.1 or $BOND_APP_HOST)
937
+ --data-dir <path> Data directory (default: ~/.bond-app or $BOND_APP_DATA_DIR)
938
+ --home <dir> Target herdr-app config directory (default: ~/.config/herdr-app or $HERDR_APP_HOME)
939
+ --image <name> Runner image name (default: bond-app-runner:p5 or $RUNNER_IMAGE)
940
+ --json Output report in JSON format
941
+ -h, --help Show this help
942
+ `);
943
+ }
944
+
945
+ function printSetupHelp(): void {
946
+ console.log(`Usage: bond-app setup [options]
947
+
948
+ Idempotent installer: checks Node and Docker, installs/updates herdr-app and hc
949
+ (with sha256 verification), installs bond CLI and bond-app, installs layout/mods/themes,
950
+ prepares ~/.bond-app and token, checks runner image, opens herdr-app and writes setup.json.
951
+
952
+ Options:
953
+ --yes, -y Accept defaults without interactive prompts (installs desktop launcher and user service)
954
+ --no-launcher Skip installing the desktop launcher
955
+ --no-service Skip installing the orchestrator user service (run manually with bond-app start)
956
+ --dry-run Show what would be done without modifying anything
957
+ --port <port> Orchestrator port (default: 3000 or $BOND_APP_PORT)
958
+ --host <host> Orchestrator host (default: 127.0.0.1 or $BOND_APP_HOST)
959
+ --data-dir <path> Data directory (default: ~/.bond-app or $BOND_APP_DATA_DIR)
960
+ --home <dir> Target herdr-app config directory (default: ~/.config/herdr-app or $HERDR_APP_HOME)
961
+ --image <name> Runner image name (default: bond-app-runner:p5 or $RUNNER_IMAGE)
962
+ -h, --help Show this help
963
+ `);
964
+ }
965
+
966
+ function printUpdateHelp(): void {
967
+ console.log(`Usage: bond-app update [options]
968
+
969
+ Update bond-app and bond via npm (public registry), reinstall layout/mods/themes,
970
+ restart the user service if installed, and warn if the runner image recipe is outdated.
971
+
972
+ Options:
973
+ --dry-run Show what would be done without modifying anything
974
+ --port <port> Orchestrator port (default: 3000 or $BOND_APP_PORT)
975
+ --host <host> Orchestrator host (default: 127.0.0.1 or $BOND_APP_HOST)
976
+ --data-dir <path> Data directory (default: ~/.bond-app or $BOND_APP_DATA_DIR)
977
+ --home <dir> Target herdr-app config directory (default: ~/.config/herdr-app or $HERDR_APP_HOME)
978
+ --image <name> Runner image name (default: bond-app-runner:p5 or $RUNNER_IMAGE)
979
+ -h, --help Show this help
980
+ `);
981
+ }
982
+
983
+ function printUninstallHelp(): void {
984
+ console.log(`Usage: bond-app uninstall [options]
985
+
986
+ Remove the orchestrator user service, bond-app's layout/mods/themes and desktop launcher.
987
+ Preserves ~/.bond-app unless --purge is given. Never uninstalls herdr-app, hc or bond.
988
+
989
+ Options:
990
+ --purge Also remove ~/.bond-app (database, token and credentials)
991
+ --yes, -y Confirm --purge without prompting
992
+ --dry-run Show what would be done without modifying anything
993
+ --port <port> Orchestrator port (default: 3000 or $BOND_APP_PORT)
994
+ --host <host> Orchestrator host (default: 127.0.0.1 or $BOND_APP_HOST)
995
+ --data-dir <path> Data directory (default: ~/.bond-app or $BOND_APP_DATA_DIR)
996
+ --home <dir> Target herdr-app config directory (default: ~/.config/herdr-app or $HERDR_APP_HOME)
997
+ -h, --help Show this help
998
+ `);
999
+ }
1000
+
1001
+ function printServiceHelp(): void {
1002
+ console.log(`Usage: bond-app service <action> [options]
1003
+
1004
+ Manage the orchestrator user service (systemd --user on Linux, launchd on macOS).
1005
+
1006
+ Actions:
1007
+ status Show service installation and running state
1008
+ install Write unit/plist file, enable and start the service
1009
+ start Start the installed service
1010
+ stop Stop the running service
1011
+ restart Restart the service
1012
+ uninstall Stop, disable and remove the unit/plist file
1013
+
1014
+ Options:
1015
+ --port <port> Orchestrator port (default: 3000 or $BOND_APP_PORT)
1016
+ --host <host> Loopback host to bind to (default: 127.0.0.1 or $BOND_APP_HOST)
1017
+ --data-dir <path> Data directory (default: ~/.bond-app or $BOND_APP_DATA_DIR)
1018
+ --image <name> Runner image name to store in service environment ($RUNNER_IMAGE)
1019
+ --name <name> Custom unit/label name (default: bond-app / dev.bond-app.orchestrator)
1020
+ --json Output result in JSON format
1021
+ -h, --help Show this help
1022
+ `);
1023
+ }
1024
+
1025
+ export async function runCli(argv: string[], setupDeps?: SetupDeps): Promise<number> {
500
1026
  const [cmd, ...rest] = argv;
501
- if (!cmd || cmd === '-h' || cmd === '--help' || cmd === 'help') {
1027
+ if (!cmd) {
1028
+ printHelp();
1029
+ const firstRun = await maybeHandleFirstRun({ fromStart: false, deps: setupDeps });
1030
+ return firstRun.setupOk ? 0 : 1;
1031
+ }
1032
+ if (cmd === '-h' || cmd === '--help' || cmd === 'help') {
502
1033
  printHelp();
503
1034
  return 0;
504
1035
  }
@@ -508,14 +1039,24 @@ export async function runCli(argv: string[]): Promise<number> {
508
1039
  }
509
1040
 
510
1041
  switch (cmd) {
1042
+ case 'setup':
1043
+ return await handleSetup(rest, setupDeps);
1044
+ case 'update':
1045
+ return await handleUpdate(rest, setupDeps);
1046
+ case 'uninstall':
1047
+ return await handleUninstall(rest, setupDeps);
1048
+ case 'service':
1049
+ return await handleService(rest, setupDeps?.serviceDeps);
511
1050
  case 'start':
512
- return await handleStart(rest);
1051
+ return await handleStart(rest, bootstrap, relaunchSelf, setupDeps);
513
1052
  case 'install':
514
1053
  return await handleInstall(rest);
515
1054
  case 'open':
516
1055
  return await handleOpen(rest);
517
1056
  case 'status':
518
1057
  return await handleStatus(rest);
1058
+ case 'doctor':
1059
+ return await handleDoctor(rest);
519
1060
  default:
520
1061
  console.error(`bond-app: unknown command '${cmd}'\n`);
521
1062
  printHelp();