@ours.network/install 1.2.1-nightly.9 → 2.0.1

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