@ours.network/install 1.2.1-nightly.9 → 2.0.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 (65) hide show
  1. package/GATEWAY_SETUP.md +178 -0
  2. package/README.md +554 -9
  3. package/ROOTLESS_PODMAN_VALIDATION.md +210 -0
  4. package/assets/Dockerfile +15 -12
  5. package/assets/Dockerfile.gateway +5 -0
  6. package/assets/docker-compose.yaml +8 -1
  7. package/assets/fleet-settings.example.json +48 -0
  8. package/assets/gateway-entrypoint.sh +37 -0
  9. package/assets/release-lock.json +1234 -4529
  10. package/assets/release.json +32 -24
  11. package/assets/scripts/build/build-common.mjs +10 -1
  12. package/assets/scripts/build/build-sdk.mjs +6 -1
  13. package/assets/scripts/maintenance/build-context.mjs +1 -1
  14. package/assets/scripts/maintenance/daemon-owner.mjs +15 -0
  15. package/assets/scripts/maintenance/docker-layout-conversion.mjs +22 -7
  16. package/assets/scripts/maintenance/recover-notifications.mjs +36 -0
  17. package/assets/scripts/maintenance/release-graph.mjs +1 -1
  18. package/assets/scripts/maintenance/state-operation.mjs +76 -8
  19. package/assets/scripts/runtime/README.md +7 -0
  20. package/assets/scripts/runtime/client-setup.mjs +105 -20
  21. package/assets/scripts/runtime/daemon-client-prefix.mjs +115 -0
  22. package/assets/scripts/runtime/dependency-ready.mjs +13 -0
  23. package/assets/scripts/runtime/diagnostics.mjs +72 -0
  24. package/assets/scripts/runtime/entrypoint.sh +5 -1
  25. package/assets/scripts/runtime/health-messenger.mjs +7 -6
  26. package/assets/scripts/runtime/healthcheck.mjs +49 -15
  27. package/assets/scripts/runtime/notifications-gateway.mjs +90 -0
  28. package/assets/scripts/runtime/recover.mjs +202 -0
  29. package/assets/scripts/runtime/start-cowork.sh +5 -0
  30. package/assets/scripts/runtime/start-messenger.sh +29 -4
  31. package/assets/scripts/runtime/start-telegram.sh +5 -0
  32. package/assets/scripts/runtime/supervise.mjs +35 -0
  33. package/assets/sources.json +49 -33
  34. package/install.mjs +7 -2
  35. package/lib/boot-readiness.mjs +96 -0
  36. package/lib/build-transition.mjs +16 -0
  37. package/lib/client-cli.mjs +12 -2
  38. package/lib/container-engine.mjs +127 -0
  39. package/lib/diagnostics.mjs +1 -0
  40. package/lib/docker-conversion-runtime.mjs +7 -4
  41. package/lib/docker-layout-installation.mjs +2 -1
  42. package/lib/docker-recovery.mjs +60 -0
  43. package/lib/docker-runtime-repair.mjs +49 -14
  44. package/lib/effects.mjs +462 -136
  45. package/lib/gateway-transition.mjs +87 -0
  46. package/lib/gateway.mjs +227 -0
  47. package/lib/legacy-migration.mjs +13 -2
  48. package/lib/orchestrate-uninstall.mjs +23 -6
  49. package/lib/orchestrate.mjs +279 -36
  50. package/lib/ownership.mjs +63 -0
  51. package/lib/plan.mjs +37 -11
  52. package/lib/podman-preflight.mjs +40 -0
  53. package/lib/product.mjs +69 -0
  54. package/lib/removal-plan.mjs +437 -0
  55. package/lib/removal.mjs +749 -0
  56. package/lib/server-onboarding.mjs +182 -16
  57. package/lib/server-ports.mjs +17 -0
  58. package/lib/setup-options.mjs +119 -29
  59. package/lib/setup.mjs +86 -15
  60. package/lib/target.mjs +24 -8
  61. package/lib/uninstall.mjs +2 -2
  62. package/lib/usage.mjs +35 -9
  63. package/lib/welcome.mjs +219 -0
  64. package/lib/workspace-setup.mjs +154 -0
  65. package/package.json +4 -2
@@ -1,3 +1,5 @@
1
+ import { validateGatewayClientProfile } from './target.mjs';
2
+ import { enableGateway } from './gateway-transition.mjs';
1
3
  import { executeLegacyMigration } from './legacy-migration.mjs';
2
4
  // ours-install v3 — the orchestrator.
3
5
  //
@@ -26,7 +28,8 @@ import { executeLegacyMigration } from './legacy-migration.mjs';
26
28
 
27
29
  import { basename, dirname, join, resolve } from 'node:path';
28
30
  import { parseNetworkArgs, validateHostProfile, parseInstallArgs, resolveTarget, resolveProfileSelection, profileEnv, InstallUsageError } from './target.mjs';
29
- import { selectSourcePackages, validateInstallation, SERVER_SERVICES, planDaemonConfig, planServiceInstall, serviceInstallCommand } from './plan.mjs';
31
+ import { NOTIFICATIONS_PRODUCER_FILE } from './server-onboarding.mjs';
32
+ import { clientPackageNames, selectSourcePackages, validateInstallation, SERVER_SERVICES, planDaemonConfig, planServiceInstall, serviceInstallCommand } from './plan.mjs';
30
33
  import {
31
34
  COMPONENTS,
32
35
  planComponentSelection, planMcpAttachment, planTgAttachment, planCoworkAttachment,
@@ -38,11 +41,13 @@ import { configJournal, reportRollback } from './journal.mjs';
38
41
  import { detectDaemons, planDaemonSelection, resolveSelection } from './detect.mjs';
39
42
  import { detectPlatform, resolveChannel } from './logic.mjs';
40
43
  import { daemonEnv } from './effects.mjs';
44
+ import { productOf, serverRole, PRODUCT_LABELS } from './product.mjs';
41
45
  import {
42
46
  buildClaudeMarketplace, buildCodexMarketplace, marketplaceJson, marketplacePaths,
43
47
  validateChannelVersion,
44
48
  } from './marketplace.mjs';
45
49
  import { USAGE } from './usage.mjs';
50
+ import { installerFailure } from './diagnostics.mjs';
46
51
  import { ok, info, warn, heading, banner, box, c, progress } from './ui.mjs';
47
52
 
48
53
  export const EXIT_OK = 0;
@@ -87,21 +92,17 @@ async function perform(effects, dryRun, label, thunk) {
87
92
  const reason = (error) => (error instanceof Error ? error.message : String(error));
88
93
 
89
94
  function clientDiagnostic(error) {
90
- return reason(error)
91
- .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
92
- .replace(/\bBearer\s+[^\s,;]+/gi, 'Bearer [redacted]')
93
- .replace(/((?:api[_-]?key|api[_-]?token|access[_-]?token|refresh[_-]?token|token|password|secret|authorization|credential)\s*["']?\s*[:=]\s*["']?)[^\s"',;]+/gi, '$1[redacted]')
94
- .replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, '$1[redacted]@')
95
- .replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 700);
95
+ return installerFailure(error);
96
96
  }
97
97
 
98
98
  function clientRetry(effects, imported, integrations) {
99
99
  effects.out(info(`Saved server connection: ${imported.configPath}.`));
100
- if (integrations.includes('fleet') && !imported.settings.fleetSettingsPath) {
100
+ if (integrations.includes('fleet') && !imported.settings.disableFleetAgentsSetup && !imported.settings.fleetSettingsPath) {
101
101
  effects.out(info('Saved profile and settings retained. Run ours-install, choose Connect to an existing server, and reuse the saved profile to finish the interactive Fleet configuration.'));
102
102
  return;
103
103
  }
104
104
  const args = ['client', 'install', '--config', imported.configPath, '--integrations', integrations.join(',') || 'none', '--sources', imported.settings.sourcesPath];
105
+ if (imported.settings.disableFleetAgentsSetup) args.push('--disable-fleet-agents-setup');
105
106
  if (imported.settings.fleetSettingsPath) args.push('--fleet-settings', imported.settings.fleetSettingsPath);
106
107
  const command = `ours-install client install ${args.slice(2).map((value, i) => i % 2 === 0 ? value : shellQuote(value)).join(' ')}`;
107
108
  effects.out(info(`Saved profile and settings retained; re-run ${command}`));
@@ -145,6 +146,7 @@ function incompatibleUpgrade(target, cliDependencies) {
145
146
  async function prepareIncompatibleUpgrade(args, effects, target, cliPkg, mismatch) {
146
147
  const dir = target.stateDir;
147
148
  const configPath = join(dir, 'config.json');
149
+ const owner = effects.readJson(join(dir, 'ours-cli-daemon.json'))?.owner === '@ours.network/daemon' ? ['ours-daemon'] : ['ours', 'daemon'];
148
150
  if (mismatch.unknown) {
149
151
  effects.out(warn(`ours: cannot verify whether ${cliPkg} can restore daemon v${mismatch.runningVersion}. Nothing was changed.`));
150
152
  effects.out(info('Check npm registry access and re-run; compatibility checks fail closed.'));
@@ -188,13 +190,13 @@ async function prepareIncompatibleUpgrade(args, effects, target, cliPkg, mismatc
188
190
  }
189
191
 
190
192
  await perform(effects, false, 'stop the incompatible daemon', () => effects.run(
191
- 'ours', ['daemon', 'stop', '--state-dir', dir, '--config', configPath], { stream: true },
193
+ owner[0], [...owner.slice(1), 'stop', '--state-dir', dir, '--config', configPath], { stream: true },
192
194
  ));
193
195
  try {
194
196
  await perform(effects, false, `back up complete daemon state to ${backupPath}`, () => effects.copyDir(dir, backupPath));
195
197
  } catch (error) {
196
198
  try {
197
- await effects.run('ours', ['daemon', 'start', '--state-dir', dir, '--config', configPath], { stream: true });
199
+ await effects.run(owner[0], [...owner.slice(1), 'start', '--state-dir', dir, '--config', configPath], { stream: true });
198
200
  effects.out(ok('backup failed, but the old daemon was started again'));
199
201
  } catch {
200
202
  effects.out(warn(`backup failed and the old daemon did not restart; its state is still untouched at ${dir}`));
@@ -203,11 +205,11 @@ async function prepareIncompatibleUpgrade(args, effects, target, cliPkg, mismatc
203
205
  }
204
206
  try {
205
207
  await perform(effects, false, 'remove the incompatible daemon boot service', () => effects.run(
206
- 'ours', ['daemon', 'uninstall-service', '--yes', '--state-dir', dir, '--config', configPath], { stream: true },
208
+ owner[0], [...owner.slice(1), 'uninstall-service', '--yes', '--state-dir', dir, '--config', configPath], { stream: true },
207
209
  ));
208
210
  } catch (error) {
209
211
  try {
210
- await effects.run('ours', ['daemon', 'start', '--state-dir', dir, '--config', configPath], { stream: true });
212
+ await effects.run(owner[0], [...owner.slice(1), 'start', '--state-dir', dir, '--config', configPath], { stream: true });
211
213
  effects.out(ok(`service removal failed, but the old daemon was started again; backup retained at ${backupPath}`));
212
214
  } catch {
213
215
  effects.out(warn(`service removal failed and the old daemon did not restart; state remains at ${dir} and the backup is at ${backupPath}`));
@@ -368,14 +370,13 @@ export async function runDaemonPhase(args, effects, exactSuite = null) {
368
370
  const mcpPkg = exactSuite?.packages?.mcp
369
371
  ? `@ours.network/mcp@${exactSuite.packages.mcp}`
370
372
  : componentSpec(componentByKey('mcp'), args.channel);
371
- // The CLI intentionally publishes only `latest`; unlike the lockstep MCP and
372
- // connector packages it has no nightly dist-tag. Keep this untagged on every
373
- // installer channel, and inspect that package's SDK dependency for the gate.
374
- const cliPkg = '@ours.network/cli';
373
+ // Inspect the runtime package SDK compatibility before replacing the owner.
374
+ const cliPkg = args.channel === 'nightly' ? '@ours.network/cli@nightly' : '@ours.network/cli';
375
+ const daemonPkg = args.channel === 'nightly' ? '@ours.network/daemon@nightly' : '@ours.network/daemon';
375
376
  if (!creating && target.daemonVersion) {
376
- const mismatch = incompatibleUpgrade(target, effects.packageDependencies(cliPkg));
377
+ const mismatch = incompatibleUpgrade(target, effects.packageDependencies(daemonPkg));
377
378
  if (mismatch) {
378
- const prepared = await prepareIncompatibleUpgrade(args, effects, target, cliPkg, mismatch);
379
+ const prepared = await prepareIncompatibleUpgrade(args, effects, target, daemonPkg, mismatch);
379
380
  if (prepared.refused) return { target, refused: prepared.refused, steps };
380
381
  creating = prepared.purged === true;
381
382
  target.backupPath = prepared.backupPath;
@@ -384,6 +385,18 @@ export async function runDaemonPhase(args, effects, exactSuite = null) {
384
385
  }
385
386
  await perform(effects, args.dryRun, `MCP server installed (npm i -g ${mcpPkg})`, () => effects.run('npm', ['i', '-g', mcpPkg]));
386
387
  steps.push({ id: 'mcp-package', changed: true, packageRefresh: true });
388
+ await perform(effects, args.dryRun, 'daemon runtime installed', () => effects.run('npm', ['i', '-g', daemonPkg]));
389
+ // A retained global unit still points into the old CLI package. Rewrite and
390
+ // activate that owned unit before npm replaces its executable with thin CLI.
391
+ let migratedService;
392
+ if (!creating) {
393
+ const retained = planServiceInstall({ stateDir: dir, home: effects.home, readText: effects.readText, platform: effects.platform?.platform });
394
+ if (retained.unitPath && effects.readText(retained.unitPath) !== null) {
395
+ try { migratedService = await runServicePhase(args, effects, dir, target.port); }
396
+ catch (error) { await recoverDaemon(args, effects, dir, join(dir, 'config.json'), target.port); throw error; }
397
+ if (migratedService.refused) return { target, refused: migratedService.refused, steps };
398
+ }
399
+ }
387
400
  await perform(effects, args.dryRun, `ours CLI installed (npm i -g ${cliPkg})`, () => effects.run('npm', ['i', '-g', cliPkg]));
388
401
  steps.push({ id: 'cli', changed: true, packageRefresh: true });
389
402
 
@@ -418,14 +431,14 @@ export async function runDaemonPhase(args, effects, exactSuite = null) {
418
431
 
419
432
  try {
420
433
  if (creating) {
421
- await perform(effects, args.dryRun, `start the daemon on port ${target.port}`, () => effects.run('ours', ['daemon', 'start', '--config', configPath], { stream: true }));
434
+ await perform(effects, args.dryRun, `start the daemon on port ${target.port}`, () => effects.run('ours-daemon', [ 'start', '--config', configPath], { stream: true }));
422
435
  steps.push({ id: 'start', changed: true });
423
436
  } else {
424
- await perform(effects, args.dryRun, `restart the daemon on port ${target.port}`, () => effects.run('ours', ['daemon', 'restart', '--config', configPath], { stream: true }));
437
+ await perform(effects, args.dryRun, `restart the daemon on port ${target.port}`, () => effects.run('ours-daemon', [ 'restart', '--config', configPath], { stream: true }));
425
438
  steps.push({ id: 'restart', changed: true });
426
439
  }
427
440
 
428
- const service = await runServicePhase(args, effects, dir, target.port);
441
+ const service = migratedService ?? await runServicePhase(args, effects, dir, target.port);
429
442
  if (service.unsupported) serviceUnsupported = service.unsupported;
430
443
  if (service.refused) {
431
444
  // A REFUSAL IS A FAILURE TO REACH THE STATE, not a special case. An unknown
@@ -455,7 +468,7 @@ export async function runDaemonPhase(args, effects, exactSuite = null) {
455
468
  effects.out(recovery.recovered
456
469
  ? ok('your daemon is running again — nothing was committed, and the service is unchanged')
457
470
  : warn('and the daemon did NOT come back up — start it yourself before anything else: '
458
- + `ours daemon start --config ${configPath}`));
471
+ + `ours-daemon start --config ${configPath}`));
459
472
  }
460
473
  throw error;
461
474
  }
@@ -478,7 +491,7 @@ export async function runDaemonPhase(args, effects, exactSuite = null) {
478
491
  async function recoverDaemon(args, effects, dir, configPath, port) {
479
492
  if (args.dryRun) return null;
480
493
  try {
481
- await effects.run('ours', ['daemon', 'start', '--config', configPath]);
494
+ await effects.run('ours-daemon', [ 'start', '--config', configPath]);
482
495
  return { recovered: true };
483
496
  } catch (recoveryError) {
484
497
  return { recovered: false, reason: reason(recoveryError) };
@@ -829,7 +842,7 @@ export async function runIdentityPhase(args, effects, { target, mcpReady }) {
829
842
  }
830
843
  if (/not running|not reachable|ECONNREFUSED|connect/i.test(text)) {
831
844
  effects.out(warn("The daemon isn't reachable yet — couldn't create your human identity."));
832
- effects.out(info(`Fix: run 'ours daemon start --config ${env.OURS_CONFIG}', then 'ours identity create-root --config ${env.OURS_CONFIG} --name "${name}"'.`));
845
+ effects.out(info(`Fix: run 'ours-daemon start --config ${env.OURS_CONFIG}', then 'ours identity create-root --config ${env.OURS_CONFIG} --name "${name}"'.`));
833
846
  return { key: 'identity', label: 'Human identity', state: 'failed', note: 'daemon not reachable' };
834
847
  }
835
848
  effects.out(warn(`Couldn't create your human identity: ${text.split('\n')[0]}`));
@@ -919,6 +932,29 @@ export async function runHarnessPhase(args, effects, { target, isDefaultStateDir
919
932
  let manual = plan.manual;
920
933
  if (exactSuite?.localPackages?.[plan.name]) {
921
934
  const registration = await effects.prepareClientMarketplace(plan.name, exactSuite.localPackages[plan.name]);
935
+ // Codex refuses to re-add a marketplace name from a new folder. An update
936
+ // moves it to a new download folder: replace only a registration that
937
+ // points into an earlier download folder of this installer.
938
+ if (plan.name === 'codex') {
939
+ const current = await effects.codexMarketplace?.();
940
+ const source = current?.marketplaceSource;
941
+ if (current && !(source?.sourceType === 'local' && source?.source === registration)) {
942
+ const earlier = source?.sourceType === 'local' && typeof source.source === 'string'
943
+ && /^[0-9a-f]{16}\/marketplaces\/codex$/.test(source.source.slice(join(effects.home, '.ours-client-install').length + 1))
944
+ && source.source.startsWith(join(effects.home, '.ours-client-install') + '/');
945
+ if (!earlier) {
946
+ const where = source?.source ?? 'another source';
947
+ effects.out(warn(`Codex already has a plugin source named ours-codex-marketplace from ${where}, which this installer did not create. It was left unchanged. Remove it with: codex plugin marketplace remove ours-codex-marketplace, then run the installer again.`));
948
+ rows.push({ ...row, state: 'failed', failedCommand: ['codex', 'plugin', 'marketplace', 'add', registration], failedStep: `Register ${plan.label} marketplace`, detail: `a different ours-codex-marketplace source (${where}) is registered` });
949
+ continue;
950
+ }
951
+ const moved = await attempt(effects, false, 'codex plugin marketplace remove ours-codex-marketplace (earlier download folder)', () => effects.run('codex', ['plugin', 'marketplace', 'remove', 'ours-codex-marketplace'], { env: profileEnv(target) }), clientDiagnostic);
952
+ if (!moved.ok) {
953
+ rows.push({ ...row, state: 'failed', failedCommand: ['codex', 'plugin', 'marketplace', 'remove', 'ours-codex-marketplace'], failedStep: `Move ${plan.label} marketplace`, detail: clientDiagnostic(moved.error) });
954
+ continue;
955
+ }
956
+ }
957
+ }
922
958
  const steps = plan.name === 'codex'
923
959
  ? [['codex', 'plugin', 'marketplace', 'add', registration], ['codex', 'plugin', 'add', 'ours@ours-codex-marketplace']]
924
960
  : [['claude', 'plugin', 'marketplace', 'add', registration], ['claude', 'plugin', await effects.hasClaudePlugin() ? 'update' : 'install', 'ours@ours.network']];
@@ -981,6 +1017,168 @@ export async function runHarnessPhase(args, effects, { target, isDefaultStateDir
981
1017
  return rows;
982
1018
  }
983
1019
 
1020
+ export const FLEET_MANAGED_CLI_CAPABILITY = 'managed-cli.setup-v1';
1021
+
1022
+ /**
1023
+ * Ask the Fleet release that was just installed to prepare and validate its own
1024
+ * managed CLI policy. Fleet owns the commands, paths and harness rules; nothing
1025
+ * about them is duplicated here. The command is static: it starts no agent
1026
+ * session and no model. Its findings are reported, never turned into an
1027
+ * installation failure, and never widened on the operator's behalf.
1028
+ */
1029
+ export async function runFleetManagedCliSetup(args, effects, plan, target) {
1030
+ const fleet = args.acquiredFleet || plan.init[0];
1031
+ const env = target.mode === 'host-profile' ? profileEnv(target) : daemonEnv(target.stateDir, target.port);
1032
+ const requested = args.fleetTaskWorkflowAgents ?? [];
1033
+ const manual = `${fleet === plan.init[0] ? fleet : shellQuote(fleet)} managed-cli setup --configuration ${shellQuote(plan.configPath)}`;
1034
+ // Version-matched: the capability is asked of the exact Fleet that was installed.
1035
+ const capabilities = await effects.fleetCapabilities(fleet, env);
1036
+ if (!capabilities.includes(FLEET_MANAGED_CLI_CAPABILITY)) {
1037
+ if (requested.length) effects.out(warn(`The installed Fleet does not provide managed CLI setup (${FLEET_MANAGED_CLI_CAPABILITY}); --fleet-task-workflow was not applied to ${requested.join(', ')} and nothing was changed.`));
1038
+ return { state: 'unavailable' };
1039
+ }
1040
+ let report;
1041
+ try {
1042
+ const result = await effects.run(fleet, ['managed-cli', 'setup', '--configuration', plan.configPath, '--json',
1043
+ ...requested.flatMap(agent => ['--enable', agent])], { env, allowCodes: [0, 1] });
1044
+ report = JSON.parse(result.stdout ?? '');
1045
+ if (report?.version !== 1 || !Array.isArray(report.roles)) throw new Error('unrecognised report');
1046
+ } catch (error) {
1047
+ effects.out(warn(`Fleet managed CLI setup did not complete (${installerFailure(error)}). Nothing else was changed; retry: ${manual}`));
1048
+ return { state: 'failed' };
1049
+ }
1050
+ for (const item of report.enabled ?? [])
1051
+ effects.out(ok(`${item.changed ? 'Enabled' : 'Already enabled:'} Fleet task commands for ${item.agent} (${item.file}). Its permissions were not changed.`));
1052
+ const declared = report.roles.filter(role => role.setup?.state !== 'not-declared');
1053
+ if (!declared.length) {
1054
+ effects.out(info('No Fleet agent is set up to run Fleet task commands from a command sandbox; nothing was generated and no permission changed.'));
1055
+ effects.out(info(`To allow it for one agent, re-run with --fleet-task-workflow <Agent> or run: ${manual} --enable <Agent>`));
1056
+ return { state: 'none', report };
1057
+ }
1058
+ const good = ['prepared', 'generated-at-launch', 'not-required'];
1059
+ for (const role of declared) {
1060
+ const line = `${role.role} (${role.harness}/${role.session}): ${role.setup.state} — ${role.setup.detail}`;
1061
+ effects.out((good.includes(role.setup.state) ? ok : warn)(`Fleet task commands, ${line}`));
1062
+ for (const scope of role.scope ?? []) effects.out(info(` ${scope}`));
1063
+ for (const note of role.warnings ?? []) effects.out(info(` note: ${note}`));
1064
+ if (role.session_policy === 'restart-required')
1065
+ effects.out(warn(` ${role.role} is still running the previous policy; restart it (ours-fleet restart ${role.role}) to load this one.`));
1066
+ }
1067
+ for (const item of report.removed ?? []) effects.out(info(`Removed obsolete Fleet-generated policy ${item.path} (${item.detail ?? 'no longer needed'}).`));
1068
+ effects.out(info('This is generated configuration only. It was not executed: no agent session or model was started, and it is not evidence that a command reached a supervisor. Check with: ours-fleet doctor'));
1069
+ return { state: declared.every(role => good.includes(role.setup.state)) ? 'prepared' : 'attention', report };
1070
+ }
1071
+
1072
+ export const FLEET_SERVICE_REFRESH_CAPABILITY = 'service.refresh-v1';
1073
+
1074
+ /** Order matters only for the supervisor: it stops and resumes agents, so it goes last. */
1075
+ const FLEET_RESTART_ORDER = ['web', 'watchdogs', 'supervisor'];
1076
+ const FLEET_RESTART_TIMEOUT_MS = 120_000;
1077
+
1078
+ /** Whether this installer runs inside `unit`'s cgroup, where restarting it would kill this run. */
1079
+ function insideUnit(effects, unit) {
1080
+ const cgroup = effects.readText('/proc/self/cgroup');
1081
+ return cgroup === null || cgroup.split('\n').some(line => line.split(':').slice(2).join(':').split('/').includes(unit));
1082
+ }
1083
+
1084
+ /** The platform's own restart command for a Fleet service definition. */
1085
+ function fleetRestartCommand(effects, service) {
1086
+ return effects.platform.platform === 'darwin'
1087
+ ? `launchctl kickstart -k gui/$(id -u)/${basename(service.path, '.plist')}`
1088
+ : `systemctl --user try-restart ${basename(service.path)}`;
1089
+ }
1090
+
1091
+ /**
1092
+ * An active Fleet service started from the replaced release keeps running it.
1093
+ * Restart each one that `service refresh` reports running a stale release once
1094
+ * its definition starts this release, then confirm with the read-only
1095
+ * `service check` that it now runs this release. The restart is systemd's
1096
+ * `try-restart`, which acts only on an active unit, so a service stopped at
1097
+ * any point is never started. A service whose definition still points
1098
+ * elsewhere, launchd, or the unit hosting this run is left alone with a notice
1099
+ * naming the manual restart; a running state Fleet cannot determine is never
1100
+ * restarted and is reported as unconfirmed.
1101
+ */
1102
+ async function restartStaleFleetServices(effects, fleet, shown, env, services) {
1103
+ const attention = [];
1104
+ for (const service of services.filter(service => service.running === 'unknown' && (service.state === 'refreshed' || service.state === 'current'))) {
1105
+ attention.push(service.service);
1106
+ effects.out(warn(`Could not confirm which release the Fleet ${service.service} service is running; if it is running and was started before this update, restart it: ${fleetRestartCommand(effects, service)}${service.service === 'supervisor' ? ' (agents resume through their supervisor)' : ''}.`));
1107
+ }
1108
+ const stale = services.filter(service => service.running === 'stale')
1109
+ .sort((a, b) => FLEET_RESTART_ORDER.indexOf(a.service) - FLEET_RESTART_ORDER.indexOf(b.service));
1110
+ if (!stale.length) return attention;
1111
+ const linux = effects.platform.platform === 'linux';
1112
+ const restarted = [];
1113
+ for (const service of stale) {
1114
+ const unit = basename(service.path);
1115
+ const left = why => { attention.push(service.service); effects.out(warn(`Running Fleet ${service.service} service still uses the previous release: ${why}; when convenient: ${fleetRestartCommand(effects, service)}${service.service === 'supervisor' ? ' (agents resume through their supervisor)' : ''}.`)); };
1116
+ if (!linux) { left('this installer restarts Fleet services only under systemd'); continue; }
1117
+ if (service.state !== 'refreshed' && service.state !== 'current') { left('its definition does not start this release yet, so a restart would not help'); continue; }
1118
+ if (insideUnit(effects, unit)) { left('this installer runs inside it, so restarting it would stop this run'); continue; }
1119
+ try {
1120
+ // try-restart: a unit stopped since the report was taken stays stopped.
1121
+ await effects.run('systemctl', ['--user', 'try-restart', unit], { timeout: FLEET_RESTART_TIMEOUT_MS });
1122
+ restarted.push(service);
1123
+ } catch (error) {
1124
+ left(`restarting it failed (${installerFailure(error)})`);
1125
+ }
1126
+ }
1127
+ if (!restarted.length) return attention;
1128
+ let checked;
1129
+ try {
1130
+ const result = await effects.run(fleet, ['service', 'check', '--json'], { env, allowCodes: [1] });
1131
+ checked = JSON.parse(result.stdout ?? '').services;
1132
+ if (!Array.isArray(checked)) throw new Error('unrecognised report');
1133
+ } catch (error) {
1134
+ effects.out(warn(`Restarted Fleet ${restarted.map(service => service.service).join(', ')} service, but could not confirm which release it runs (${installerFailure(error)}); check: ${shown} service check`));
1135
+ return [...attention, ...restarted.map(service => service.service)];
1136
+ }
1137
+ for (const service of restarted) {
1138
+ const now = checked.find(entry => entry.service === service.service);
1139
+ if (now?.running === 'current') effects.out(ok(`Restarted Fleet ${service.service} service; it now runs this release${service.service === 'supervisor' ? ' and resumes its agents' : ''}.`));
1140
+ else {
1141
+ attention.push(service.service);
1142
+ effects.out(warn(now?.running === 'stopped'
1143
+ ? `Fleet ${service.service} service is not running after the restart (it was stopped, or exited); this installer did not start it. Check: systemctl --user status ${basename(service.path)}`
1144
+ : `Restarted Fleet ${service.service} service, but it is not confirmed on this release (${now?.running ?? 'not reported'}); check: systemctl --user status ${basename(service.path)}`));
1145
+ }
1146
+ }
1147
+ return attention;
1148
+ }
1149
+
1150
+ /**
1151
+ * Fleet service definitions pin the release tree that wrote them, and an update
1152
+ * installs a new tree. Ask the installed Fleet to re-point its own existing
1153
+ * definitions (it never creates, starts, stops or restarts a service), then
1154
+ * restart only the services that were already running the replaced release.
1155
+ */
1156
+ export async function runFleetServiceRefresh(args, effects, plan, target) {
1157
+ const fleet = args.acquiredFleet || plan.init[0];
1158
+ const env = target.mode === 'host-profile' ? profileEnv(target) : daemonEnv(target.stateDir, target.port);
1159
+ const capabilities = await effects.fleetCapabilities(fleet, env);
1160
+ if (!capabilities.includes(FLEET_SERVICE_REFRESH_CAPABILITY)) return { state: 'unavailable' };
1161
+ const shown = fleet === plan.init[0] ? fleet : shellQuote(fleet);
1162
+ const manual = `${shown} service refresh`;
1163
+ let services;
1164
+ try {
1165
+ const result = await effects.run(fleet, ['service', 'refresh', '--json'], { env });
1166
+ services = JSON.parse(result.stdout ?? '').services;
1167
+ if (!Array.isArray(services)) throw new Error('unrecognised report');
1168
+ } catch (error) {
1169
+ effects.out(warn(`Fleet service definitions were not refreshed (${installerFailure(error)}). After a reboot the previous Fleet release may start; retry: ${manual}`));
1170
+ return { state: 'failed' };
1171
+ }
1172
+ for (const service of services) {
1173
+ if (service.state === 'refreshed') effects.out(ok(`Fleet ${service.service} service now starts this release (${service.path}).`));
1174
+ if (service.state === 'unrecognized') effects.out(warn(`Fleet ${service.service} service definition was left unchanged: ${service.detail ?? 'not generated by Fleet'} (${service.path}).`));
1175
+ if (service.state === 'stale') effects.out(warn(`Fleet ${service.service} service still starts another release${service.detail ? `: ${service.detail}` : ''}; retry: ${manual}`));
1176
+ if (service.state === 'reload-failed') effects.out(warn(`Fleet ${service.service} service definition was updated, but the service manager did not reload it, so it still starts the previous release${service.detail ? ` (${service.detail})` : ''}; retry: systemctl --user daemon-reload`));
1177
+ }
1178
+ const unrestarted = await restartStaleFleetServices(effects, fleet, shown, env, services);
1179
+ return { state: unrestarted.length || services.some(service => service.state !== 'refreshed' && service.state !== 'current' && service.state !== 'absent') ? 'attention' : 'refreshed', services };
1180
+ }
1181
+
984
1182
  /** Install Fleet and let its interactive wizard publish the owned configuration. */
985
1183
  export async function runFleetPhase(args, effects, { target, isDefaultStateDir }) {
986
1184
  effects.out(heading('ours-fleet (your always-online agent team)'));
@@ -997,6 +1195,18 @@ export async function runFleetPhase(args, effects, { target, isDefaultStateDir }
997
1195
  return { key: 'fleet', label: plan.label, state: 'skipped' };
998
1196
  }
999
1197
  const install = args.acquiredFleet ? { ok: true } : await attempt(effects, args.dryRun, plan.install.join(' '), () => effects.run(plan.install[0], plan.install.slice(1)));
1198
+ if (args.disableFleetAgentsSetup) {
1199
+ if (!install.ok) return { key: 'fleet', label: plan.label, state: 'failed', note: 'Fleet installation failed' };
1200
+ effects.out(ok('Fleet CLI installed; agent and model setup deferred to the App. Existing Fleet configuration was retained.'));
1201
+ // A retained configuration may already declare the workflow; its generated policy names the package path this run just replaced.
1202
+ // A retained configuration means Fleet was set up before, so its service
1203
+ // definitions may pin the release this run just replaced.
1204
+ if (!args.dryRun && effects.readText(plan.configPath) !== null) {
1205
+ await runFleetManagedCliSetup(args, effects, plan, target);
1206
+ await runFleetServiceRefresh(args, effects, plan, target);
1207
+ }
1208
+ return { key: 'fleet', label: plan.label, state: 'installed', note: 'agents setup deferred' };
1209
+ }
1000
1210
  // Fleet owns its v2 manifest, roles, models and permissions. With no prepared
1001
1211
  // settings, its wizard keeps the user's terminal while this invocation carries
1002
1212
  // the selected daemon; --settings makes the same call strictly noninteractive.
@@ -1020,6 +1230,8 @@ export async function runFleetPhase(args, effects, { target, isDefaultStateDir }
1020
1230
  return { key: 'fleet', label: plan.label, state: 'failed', note: 'Fleet configuration was not published' };
1021
1231
  }
1022
1232
  effects.out(ok('ours-fleet installed and initialized; no fleet roles were started.'));
1233
+ if (!args.dryRun) await runFleetManagedCliSetup(args, effects, plan, target);
1234
+ if (!args.dryRun) await runFleetServiceRefresh(args, effects, plan, target);
1023
1235
  if (plan.instruction) effects.out(info(plan.instruction));
1024
1236
  return { key: 'fleet', label: plan.label, state: 'installed', note: `configured at ${plan.configPath}; stopped` };
1025
1237
  }
@@ -1303,15 +1515,23 @@ async function executeServerCommand(args, effects) {
1303
1515
  const existing = record !== null;
1304
1516
  if (existing) {
1305
1517
  record = validateInstallation(record, args.stateDir);
1518
+ if (args.containerEngine && args.containerEngine !== (record.containerEngine ?? 'docker')) throw new Error('Conflicting container engine; explicit migration is required');
1306
1519
  if (args.mode && args.mode !== record.mode) throw new Error('Conflicting runtime mode; retained installation was not changed');
1520
+ if (args.product && args.product !== productOf(record)) throw new Error(`This installation is ${PRODUCT_LABELS[productOf(record)].toLowerCase()}; it is kept as it is. Use a separate empty directory for the other kind of installation.`);
1307
1521
  if (args.operation !== 'update' && args.sources && (record.sourcePolicyHash
1308
1522
  ? effects.sourcePolicyHash(args.sources) !== record.sourcePolicyHash
1309
1523
  : effects.readText(args.sources) !== effects.readText(record.sourcesPath))) throw new Error('Conflicting source selection; use explicit server update');
1310
1524
  } else {
1311
1525
  if (args.operation !== 'install' || !args.mode) throw new Error('First server install requires --mode');
1312
- record = effects.newInstallation(args.stateDir, args.mode);
1526
+ record = effects.newInstallation(args.stateDir, args.mode, args);
1313
1527
  for (const key of ['port', 'coworkPort', 'messengerPort']) if (args[key] !== undefined) record[key] = args[key];
1314
1528
  }
1529
+ if (effects.readJson(join(record.root, 'gateway-transition.json')) && args.operation !== 'gateway-enable' && args.operation !== 'status') throw new Error('Interrupted gateway migration; run server gateway-enable before other changes');
1530
+ if (args.serverUrl && args.operation === 'install') {
1531
+ if (!record.gateway) throw new Error('Use server gateway-enable to migrate an existing Docker installation');
1532
+ if (existing && record.gateway.serverUrl !== args.serverUrl) throw new Error('Conflicting gateway server URL');
1533
+ record.gateway = { ...record.gateway, serverUrl: args.serverUrl };
1534
+ }
1315
1535
  if (record.layoutConversion && !['install', 'start', 'stop', 'status'].includes(args.operation)) {
1316
1536
  throw new Error('Layout conversion is incomplete; resume with server install or server start before changing state or authority');
1317
1537
  }
@@ -1319,7 +1539,8 @@ async function executeServerCommand(args, effects) {
1319
1539
  throw new Error(`Server build activation is incomplete; repeat server ${record.buildTransition.operation} before other mutations`);
1320
1540
  }
1321
1541
  const showInstallProgress = args.operation === 'install' && !(existing && (record.schema === 1 || record.layoutConversion));
1322
- const installStageCount = (existing ? 7 : 9) + (args.identityName ? 2 : 0);
1542
+ const installStageCount = (existing ? 7 : 9) + (args.identityName ? 2 : 0)
1543
+ + (args.identityName && args.name && args.surname && (!existing || [undefined, null, args.identityName, `${args.name} ${args.surname}`].includes(record.messengerIdentity)) ? 1 : 0);
1323
1544
  let completedInstallStages = 0;
1324
1545
  const installStage = async (label, explanation, action) => {
1325
1546
  if (!showInstallProgress) return action();
@@ -1337,12 +1558,12 @@ async function executeServerCommand(args, effects) {
1337
1558
  if ((!existing || args.operation === 'update') && !record.buildTransition) {
1338
1559
  args.resolvedSources = await installStage('Package selection', 'Resolve the selected server packages before installation.', async () => {
1339
1560
  const policy = args.sourcePolicy ?? (args.sources ? effects.readJson(args.sources) : effects.packagedSourcePolicy());
1340
- return effects.resolveSourcePolicy(policy, 'server');
1561
+ return effects.resolveSourcePolicy(policy, serverRole(record));
1341
1562
  });
1342
1563
  }
1343
1564
  if (!existing && args.sources) record.sourcePolicyHash = effects.sourcePolicyHash(args.sources);
1344
1565
  await installStage('Prerequisite checks', record.mode === 'docker' ? 'Check Docker Engine and Docker Compose.' : 'Check native tools and the user service manager.', () => effects.serverPreflight(record, args.operation, {
1345
- existing, sourcePath: args.sources ?? record.sourcesPath, sourceManifest: args.resolvedSources, identityName: args.identityName,
1566
+ existing, sourcePath: args.sources ?? record.sourcesPath, sourceManifest: args.resolvedSources, identityName: args.identityName, explicitPorts: args.explicitPorts,
1346
1567
  }));
1347
1568
  if (existing && (record.schema === 1 || record.layoutConversion)
1348
1569
  && ['install', 'start', 'restart', 'update', 'rebuild'].includes(args.operation)) {
@@ -1372,13 +1593,28 @@ async function executeServerCommand(args, effects) {
1372
1593
  if (args.identityName) {
1373
1594
  await installStage('Daemon startup', 'Start the daemon and restore its retained identities.', () => effects.serverLifecycle(record, 'start', ['daemon']));
1374
1595
  const identity = await installStage('Human identity', 'Keep the existing Human identity, or create it on a fresh daemon.', () => effects.serverEnsureIdentity(record, args.identityName));
1375
- record.messengerIdentity = identity.name;
1596
+ // Messenger runs as the person's own identity under the Human identity when Name and Surname are known.
1597
+ // An installation whose Messenger already runs as some other identity under it keeps that identity.
1598
+ const person = args.name && args.surname ? `${args.name} ${args.surname}` : undefined;
1599
+ const selected = existing ? record.messengerIdentity : undefined;
1600
+ if (person && (!selected || selected === identity.name || selected === person)) {
1601
+ const own = await installStage('Messenger identity', 'Keep or create your own identity under the Human identity; Messenger runs as it.', () => effects.serverEnsureMessengerIdentity(record, person));
1602
+ record.messengerIdentity = own.name;
1603
+ } else if (selected && selected !== identity.name
1604
+ && (await effects.serverListIdentities(record)).some(row => row.name === selected && row.kind === 'role' && row.temp === null)) {
1605
+ record.messengerIdentity = selected;
1606
+ } else record.messengerIdentity = identity.name;
1376
1607
  effects.writeJson(recordPath, JSON.stringify(record, null, 2) + '\n');
1377
1608
  await installStage('Application startup', 'Start the selected applications and check readiness.', () => effects.serverLifecycle(record, 'start', record.services.filter(name => name !== 'daemon')));
1378
1609
  } else {
1379
1610
  await installStage('Service startup', 'Start the daemon and selected services, then check readiness.', () => effects.serverLifecycle(record, 'start'));
1380
1611
  }
1612
+ if (record.gateway) await effects.verifyGateway(record);
1381
1613
  if (showInstallProgress) effects.out(progress(installStageCount, installStageCount, 'Installation complete', 'The selected services are ready.'));
1614
+ } else if (args.operation === 'uninstall') {
1615
+ await effects.serverUninstall(record);
1616
+ } else if (args.operation === 'gateway-enable') {
1617
+ await enableGateway(record, args, effects);
1382
1618
  } else if (['backup', 'restore', 'reset'].includes(args.operation)) {
1383
1619
  await effects.serverMaintenance(record, args);
1384
1620
  } else if (['update', 'rebuild'].includes(args.operation)) {
@@ -1426,7 +1662,7 @@ export async function runClientCommand(command, effects) {
1426
1662
  configPath = managedPath;
1427
1663
  }
1428
1664
  let profile;
1429
- if (configPath) profile = validateHostProfile(effects.readProfile(configPath));
1665
+ if (configPath) profile = validateGatewayClientProfile(effects.readProfile(configPath));
1430
1666
  else if (!command.preset && effects.interactive) {
1431
1667
  const endpoint = await effects.askLine('Server HTTP or HTTPS endpoint: ', 'http://127.0.0.1:3050');
1432
1668
  const credentialPath = await effects.askLine('Private issued-token file: ', '');
@@ -1434,14 +1670,13 @@ export async function runClientCommand(command, effects) {
1434
1670
  profile = await effects.discoverClientProfile(endpoint, credentialPath);
1435
1671
  }
1436
1672
  if (!profile) throw new InstallUsageError('client install requires a complete network profile; supply --config or use the interactive client setup');
1437
- if (saved && (saved.endpoint !== profile.endpoint || saved.expectedInstanceId !== profile.expectedInstanceId))
1673
+ if (saved && saved.expectedInstanceId !== profile.expectedInstanceId)
1438
1674
  throw new InstallUsageError('Managed client already selects another server; existing default was not changed');
1439
1675
  for (const name of ['OURS_API_TOKEN', 'OURS_PORT', 'OURS_STATE_DIR', 'OURS_DAEMON_ID']) {
1440
1676
  if (effects.env[name]?.trim()) throw new InstallUsageError(`${name} conflicts with client profile selection`);
1441
1677
  }
1442
1678
  effects.out(info(`Selected server ${profile.endpoint} (instance ${profile.expectedInstanceId}).`));
1443
1679
  await effects.verifyHostProfile(configPath || profile);
1444
- await effects.verifyPackagedMcp(configPath || profile);
1445
1680
  const settings = saved?.installer ?? (configPath ? effects.readJson(configPath)?.installer : undefined);
1446
1681
  const settingsBase = saved ? dirname(managedPath) : configPath ? dirname(configPath) : process.cwd();
1447
1682
  let integrations = command.integrations ?? settings?.integrations;
@@ -1451,11 +1686,12 @@ export async function runClientCommand(command, effects) {
1451
1686
  }
1452
1687
  if (!Array.isArray(integrations) || integrations.some(name => !['codex', 'claude-code', 'fleet'].includes(name)) || new Set(integrations).size !== integrations.length) throw new InstallUsageError('installer.integrations must be an array of codex, claude-code and/or fleet; use an empty array for CLI only');
1453
1688
  let fleetSettingsPath = command.preset ? command.fleetSettingsPath : settings?.fleetSettingsPath;
1454
- if (command.nonInteractive && integrations.includes('fleet') && !fleetSettingsPath) throw new InstallUsageError('Fleet in CLI mode requires --fleet-settings; no interactive wizard will be opened');
1689
+ const disableFleetAgentsSetup = command.disableFleetAgentsSetup ?? settings?.disableFleetAgentsSetup ?? false;
1690
+ if (command.nonInteractive && !disableFleetAgentsSetup && integrations.includes('fleet') && !fleetSettingsPath) throw new InstallUsageError('Fleet in CLI mode requires --fleet-settings; no interactive wizard will be opened');
1455
1691
  if (fleetSettingsPath !== undefined && (typeof fleetSettingsPath !== 'string' || !fleetSettingsPath))
1456
1692
  throw new InstallUsageError('installer.fleetSettingsPath must be a non-empty path when supplied');
1457
1693
  if (fleetSettingsPath) fleetSettingsPath = resolve(settingsBase, fleetSettingsPath);
1458
- const selectedClients = [...new Set(['sdk', 'cli', ...integrations])];
1694
+ const selectedClients = clientPackageNames(integrations);
1459
1695
  let sourcesPath = settings?.sourcesPath;
1460
1696
  let resolvedSources;
1461
1697
  if (command.sourcePolicy) {
@@ -1468,7 +1704,10 @@ export async function runClientCommand(command, effects) {
1468
1704
  resolvedSources = await effects.resolveSourcePolicy(policy, 'client', selectedClients);
1469
1705
  }
1470
1706
  effects.out(progress(0, 4, 'Client configuration', 'Prepare the selected integrations and private connection profile.'));
1471
- const imported = effects.importClientProfile({ profile, sourcesPath, sources: resolvedSources, integrations, fleetSettingsPath, refresh: !!command.preset });
1707
+ if (profile.serverUrl && integrations.includes('fleet')) await effects.qualifyGatewayClient({ profile, sourcesPath, sources: resolvedSources, integrations, refresh: !!command.preset });
1708
+ // A prepared local profile may carry the Fleet notification producer credential beside it.
1709
+ const notificationsProducerPath = configPath && configPath !== managedPath && effects.exists?.(join(dirname(configPath), NOTIFICATIONS_PRODUCER_FILE)) ? join(dirname(configPath), NOTIFICATIONS_PRODUCER_FILE) : undefined;
1710
+ const imported = effects.importClientProfile({ profile, sourcesPath, sources: resolvedSources, integrations, fleetSettingsPath, disableFleetAgentsSetup, refresh: !!command.preset, notificationsProducerPath });
1472
1711
  let phase = 'Validate saved server connection';
1473
1712
  try {
1474
1713
  await effects.verifyHostProfile(imported.configPath);
@@ -1476,7 +1715,8 @@ export async function runClientCommand(command, effects) {
1476
1715
  phase = 'Acquire client packages';
1477
1716
  const exactSuite = await effects.acquireClientPackages(imported.configPath, imported.settings.sourcesPath, integrations, { refresh: !!command.preset });
1478
1717
  const args = { assumeYes: true, dryRun: false, channel: 'latest', clientIntegrations: integrations,
1479
- acquiredFleet: exactSuite.fleetBin, fleetSettingsPath: imported.settings.fleetSettingsPath };
1718
+ acquiredFleet: exactSuite.fleetBin, fleetSettingsPath: imported.settings.fleetSettingsPath, disableFleetAgentsSetup: imported.settings.disableFleetAgentsSetup,
1719
+ fleetTaskWorkflowAgents: command.fleetTaskWorkflowAgents };
1480
1720
  const target = { mode: 'host-profile', managed: true, configPath: imported.configPath, profile: imported.profile, endpoint: imported.profile.endpoint };
1481
1721
  effects.out(progress(2, 4, 'Client integrations', 'Register the selected agent integrations.'));
1482
1722
  phase = 'Register client integrations';
@@ -1494,6 +1734,9 @@ export async function runClientCommand(command, effects) {
1494
1734
  for (const name of incomplete) explainClientFailure(effects, name, summary.find(row => row.key === name));
1495
1735
  clientRetry(effects, imported, integrations);
1496
1736
  } else effects.out(ok(`Client setup complete. New clients discover ${imported.configPath}; no OURS_CONFIG export is required.`));
1737
+ // Fleet's web service reads its producer credential when it starts; agents keep running across a web restart.
1738
+ if (imported.notificationsProducerChanged && integrations.includes('fleet'))
1739
+ effects.out(info('Notifications are ready for Fleet. Run `ours-fleet web restart` so a running Fleet web console starts producing them.'));
1497
1740
  if (!incomplete.length) effects.out(progress(4, 4, 'Client setup complete', 'All selected integrations are configured.'));
1498
1741
  return incomplete.length ? EXIT_REFUSED : EXIT_OK;
1499
1742
  } catch (error) {
@@ -0,0 +1,63 @@
1
+ // Ownership records written at installation time, read by complete removal.
2
+ //
3
+ // A client generation under ~/.ours-client-install can serve more than one
4
+ // managed installation, and identical selections are not proof of who uses it.
5
+ // Each acquisition therefore records the installation instances it was acquired
6
+ // for. Server roots record the image IDs this installer built, so removal never
7
+ // relies on an image name alone.
8
+ import { join } from 'node:path';
9
+
10
+ export const OWNERS_FILE = 'owners.json';
11
+ export const OWNED_IMAGES_FILE = 'owned-images.json';
12
+ const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
13
+
14
+ const IMAGE_ID = /^sha256:[0-9a-f]{64}$/;
15
+ const IMAGE_TAG = /^ours-[a-z0-9]+:[a-z-]+$/;
16
+
17
+ /** A generation's owner record: absent, invalid (damaged or unknown format) or the owner IDs. */
18
+ export function readOwners(effects, generation) {
19
+ const text = effects.readText(join(generation, OWNERS_FILE));
20
+ if (text === null) return { state: 'absent' };
21
+ const instances = parseOwners(text);
22
+ return instances ? { state: 'valid', instances } : { state: 'invalid' };
23
+ }
24
+
25
+ function parseOwners(text) {
26
+ try {
27
+ const value = JSON.parse(text);
28
+ if (value?.schema !== 1 || !Array.isArray(value.instances) || value.instances.some(id => !UUID.test(id)) || Object.keys(value).length !== 2) return null;
29
+ return [...new Set(value.instances)];
30
+ } catch { return null; }
31
+ }
32
+
33
+ /**
34
+ * The next owner record for a generation, or null when nothing changes. A
35
+ * damaged record is never replaced: that would forget its earlier owners.
36
+ */
37
+ export function addOwner(text, instanceId) {
38
+ if (!UUID.test(instanceId ?? '')) return null;
39
+ const instances = text === null || text === undefined ? [] : parseOwners(text);
40
+ if (instances === null) throw new Error('The owner record of the downloaded Ours programs is damaged; it was left unchanged');
41
+ if (instances.includes(instanceId)) return null;
42
+ return JSON.stringify({ schema: 1, instances: [...instances, instanceId] }, null, 2) + '\n';
43
+ }
44
+
45
+ /** The next owned-images record for a server root; a damaged record is left as it is. */
46
+ export function ownedImagesRecord(text, images) {
47
+ let current = {};
48
+ if (text !== null && text !== undefined) {
49
+ let value;
50
+ try { value = JSON.parse(text); } catch { return null; }
51
+ if (value?.schema !== 1 || !value.images || typeof value.images !== 'object' || Array.isArray(value.images)
52
+ || Object.entries(value.images).some(([tag, id]) => !IMAGE_TAG.test(tag) || !IMAGE_ID.test(id))) return null;
53
+ current = value.images;
54
+ }
55
+ const added = Object.fromEntries(Object.entries(images ?? {}).filter(([tag, id]) => IMAGE_TAG.test(tag) && IMAGE_ID.test(id)));
56
+ const next = { ...current, ...added };
57
+ return JSON.stringify(current) === JSON.stringify(next) ? null : JSON.stringify({ schema: 1, images: next }, null, 2) + '\n';
58
+ }
59
+
60
+ /** Tags whose image this run created or replaced: a tag it found unchanged is never adopted. */
61
+ export function changedImages(before, after) {
62
+ return Object.fromEntries(Object.entries(after ?? {}).filter(([tag, id]) => (before ?? {})[tag] !== id));
63
+ }