@ours.network/install 1.2.1-nightly.5 → 1.2.1-nightly.50

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 (64) hide show
  1. package/GATEWAY_SETUP.md +178 -0
  2. package/README.md +548 -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 +1219 -4524
  10. package/assets/release.json +37 -19
  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 +18 -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/notifications-gateway.mjs +90 -0
  27. package/assets/scripts/runtime/recover.mjs +165 -0
  28. package/assets/scripts/runtime/start-cowork.sh +5 -0
  29. package/assets/scripts/runtime/start-messenger.sh +29 -4
  30. package/assets/scripts/runtime/start-telegram.sh +5 -0
  31. package/assets/scripts/runtime/supervise.mjs +35 -0
  32. package/assets/sources.json +54 -28
  33. package/install.mjs +7 -2
  34. package/lib/boot-readiness.mjs +96 -0
  35. package/lib/build-transition.mjs +16 -0
  36. package/lib/client-cli.mjs +127 -0
  37. package/lib/container-engine.mjs +127 -0
  38. package/lib/diagnostics.mjs +1 -0
  39. package/lib/docker-conversion-runtime.mjs +7 -4
  40. package/lib/docker-layout-installation.mjs +2 -1
  41. package/lib/docker-recovery.mjs +60 -0
  42. package/lib/docker-runtime-repair.mjs +74 -19
  43. package/lib/effects.mjs +499 -140
  44. package/lib/gateway-transition.mjs +87 -0
  45. package/lib/gateway.mjs +159 -0
  46. package/lib/legacy-migration.mjs +13 -2
  47. package/lib/orchestrate-uninstall.mjs +23 -6
  48. package/lib/orchestrate.mjs +219 -44
  49. package/lib/ownership.mjs +63 -0
  50. package/lib/plan.mjs +37 -11
  51. package/lib/podman-preflight.mjs +40 -0
  52. package/lib/product.mjs +69 -0
  53. package/lib/removal-plan.mjs +437 -0
  54. package/lib/removal.mjs +749 -0
  55. package/lib/server-onboarding.mjs +182 -16
  56. package/lib/server-ports.mjs +17 -0
  57. package/lib/setup-options.mjs +119 -29
  58. package/lib/setup.mjs +83 -22
  59. package/lib/target.mjs +24 -8
  60. package/lib/uninstall.mjs +2 -2
  61. package/lib/usage.mjs +35 -9
  62. package/lib/welcome.mjs +219 -0
  63. package/lib/workspace-setup.mjs +83 -0
  64. 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;
@@ -86,6 +91,37 @@ async function perform(effects, dryRun, label, thunk) {
86
91
 
87
92
  const reason = (error) => (error instanceof Error ? error.message : String(error));
88
93
 
94
+ function clientDiagnostic(error) {
95
+ return installerFailure(error);
96
+ }
97
+
98
+ function clientRetry(effects, imported, integrations) {
99
+ effects.out(info(`Saved server connection: ${imported.configPath}.`));
100
+ if (integrations.includes('fleet') && !imported.settings.disableFleetAgentsSetup && !imported.settings.fleetSettingsPath) {
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
+ return;
103
+ }
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');
106
+ if (imported.settings.fleetSettingsPath) args.push('--fleet-settings', imported.settings.fleetSettingsPath);
107
+ const command = `ours-install client install ${args.slice(2).map((value, i) => i % 2 === 0 ? value : shellQuote(value)).join(' ')}`;
108
+ effects.out(info(`Saved profile and settings retained; re-run ${command}`));
109
+ }
110
+
111
+ function explainClientFailure(effects, name, row) {
112
+ const label = { codex: 'Codex', 'claude-code': 'Claude Code', fleet: 'Fleet' }[name];
113
+ const command = name === 'claude-code' ? 'claude' : name;
114
+ if (row?.note === 'not installed') {
115
+ effects.out(warn(`${label}: executable not found on PATH. Install ${label} or make its executable available in this shell, then check ${command} --version before retrying.`));
116
+ } else if (row?.manual) {
117
+ effects.out(warn(`${label}: cannot register the plugin automatically — ${clientDiagnostic(row.note)}. Use the real executable (check ${command} --version), or register the displayed local marketplace manually.`));
118
+ } else {
119
+ effects.out(warn(`${label}: ${row?.failedStep ?? 'integration setup'} failed. ${clientDiagnostic(row?.detail ?? row?.note ?? 'The integration did not report successful completion. Review the messages above.')} Fix the reported command error before retrying.`));
120
+ if (row?.failedCommand) effects.out(info(`Failed command: ${row.failedCommand.map(shellQuote).join(' ')}`));
121
+ }
122
+ }
123
+
124
+
89
125
  function semverMajor(version) {
90
126
  const match = /^(?:[~^<>= ]*)(\d+)\./.exec(String(version ?? '').trim());
91
127
  return match ? Number(match[1]) : null;
@@ -110,6 +146,7 @@ function incompatibleUpgrade(target, cliDependencies) {
110
146
  async function prepareIncompatibleUpgrade(args, effects, target, cliPkg, mismatch) {
111
147
  const dir = target.stateDir;
112
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'];
113
150
  if (mismatch.unknown) {
114
151
  effects.out(warn(`ours: cannot verify whether ${cliPkg} can restore daemon v${mismatch.runningVersion}. Nothing was changed.`));
115
152
  effects.out(info('Check npm registry access and re-run; compatibility checks fail closed.'));
@@ -153,13 +190,13 @@ async function prepareIncompatibleUpgrade(args, effects, target, cliPkg, mismatc
153
190
  }
154
191
 
155
192
  await perform(effects, false, 'stop the incompatible daemon', () => effects.run(
156
- 'ours', ['daemon', 'stop', '--state-dir', dir, '--config', configPath], { stream: true },
193
+ owner[0], [...owner.slice(1), 'stop', '--state-dir', dir, '--config', configPath], { stream: true },
157
194
  ));
158
195
  try {
159
196
  await perform(effects, false, `back up complete daemon state to ${backupPath}`, () => effects.copyDir(dir, backupPath));
160
197
  } catch (error) {
161
198
  try {
162
- 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 });
163
200
  effects.out(ok('backup failed, but the old daemon was started again'));
164
201
  } catch {
165
202
  effects.out(warn(`backup failed and the old daemon did not restart; its state is still untouched at ${dir}`));
@@ -168,11 +205,11 @@ async function prepareIncompatibleUpgrade(args, effects, target, cliPkg, mismatc
168
205
  }
169
206
  try {
170
207
  await perform(effects, false, 'remove the incompatible daemon boot service', () => effects.run(
171
- '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 },
172
209
  ));
173
210
  } catch (error) {
174
211
  try {
175
- 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 });
176
213
  effects.out(ok(`service removal failed, but the old daemon was started again; backup retained at ${backupPath}`));
177
214
  } catch {
178
215
  effects.out(warn(`service removal failed and the old daemon did not restart; state remains at ${dir} and the backup is at ${backupPath}`));
@@ -193,11 +230,11 @@ async function prepareIncompatibleUpgrade(args, effects, target, cliPkg, mismatc
193
230
  * rather than one harness. So a failure here is one honest line plus whatever
194
231
  * the caller wants to say about retrying, and the walk continues.
195
232
  */
196
- async function attempt(effects, dryRun, label, thunk) {
233
+ async function attempt(effects, dryRun, label, thunk, formatReason = reason) {
197
234
  try {
198
235
  return { ok: true, ...(await perform(effects, dryRun, label, thunk)) };
199
236
  } catch (error) {
200
- effects.out(warn(`${label} — did not complete: ${reason(error)}`));
237
+ effects.out(warn(`${label} — did not complete: ${formatReason(error)}`));
201
238
  return { ok: false, error };
202
239
  }
203
240
  }
@@ -333,14 +370,13 @@ export async function runDaemonPhase(args, effects, exactSuite = null) {
333
370
  const mcpPkg = exactSuite?.packages?.mcp
334
371
  ? `@ours.network/mcp@${exactSuite.packages.mcp}`
335
372
  : componentSpec(componentByKey('mcp'), args.channel);
336
- // The CLI intentionally publishes only `latest`; unlike the lockstep MCP and
337
- // connector packages it has no nightly dist-tag. Keep this untagged on every
338
- // installer channel, and inspect that package's SDK dependency for the gate.
339
- 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';
340
376
  if (!creating && target.daemonVersion) {
341
- const mismatch = incompatibleUpgrade(target, effects.packageDependencies(cliPkg));
377
+ const mismatch = incompatibleUpgrade(target, effects.packageDependencies(daemonPkg));
342
378
  if (mismatch) {
343
- const prepared = await prepareIncompatibleUpgrade(args, effects, target, cliPkg, mismatch);
379
+ const prepared = await prepareIncompatibleUpgrade(args, effects, target, daemonPkg, mismatch);
344
380
  if (prepared.refused) return { target, refused: prepared.refused, steps };
345
381
  creating = prepared.purged === true;
346
382
  target.backupPath = prepared.backupPath;
@@ -349,6 +385,18 @@ export async function runDaemonPhase(args, effects, exactSuite = null) {
349
385
  }
350
386
  await perform(effects, args.dryRun, `MCP server installed (npm i -g ${mcpPkg})`, () => effects.run('npm', ['i', '-g', mcpPkg]));
351
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
+ }
352
400
  await perform(effects, args.dryRun, `ours CLI installed (npm i -g ${cliPkg})`, () => effects.run('npm', ['i', '-g', cliPkg]));
353
401
  steps.push({ id: 'cli', changed: true, packageRefresh: true });
354
402
 
@@ -383,14 +431,14 @@ export async function runDaemonPhase(args, effects, exactSuite = null) {
383
431
 
384
432
  try {
385
433
  if (creating) {
386
- 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 }));
387
435
  steps.push({ id: 'start', changed: true });
388
436
  } else {
389
- 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 }));
390
438
  steps.push({ id: 'restart', changed: true });
391
439
  }
392
440
 
393
- const service = await runServicePhase(args, effects, dir, target.port);
441
+ const service = migratedService ?? await runServicePhase(args, effects, dir, target.port);
394
442
  if (service.unsupported) serviceUnsupported = service.unsupported;
395
443
  if (service.refused) {
396
444
  // A REFUSAL IS A FAILURE TO REACH THE STATE, not a special case. An unknown
@@ -420,7 +468,7 @@ export async function runDaemonPhase(args, effects, exactSuite = null) {
420
468
  effects.out(recovery.recovered
421
469
  ? ok('your daemon is running again — nothing was committed, and the service is unchanged')
422
470
  : warn('and the daemon did NOT come back up — start it yourself before anything else: '
423
- + `ours daemon start --config ${configPath}`));
471
+ + `ours-daemon start --config ${configPath}`));
424
472
  }
425
473
  throw error;
426
474
  }
@@ -443,7 +491,7 @@ export async function runDaemonPhase(args, effects, exactSuite = null) {
443
491
  async function recoverDaemon(args, effects, dir, configPath, port) {
444
492
  if (args.dryRun) return null;
445
493
  try {
446
- await effects.run('ours', ['daemon', 'start', '--config', configPath]);
494
+ await effects.run('ours-daemon', [ 'start', '--config', configPath]);
447
495
  return { recovered: true };
448
496
  } catch (recoveryError) {
449
497
  return { recovered: false, reason: reason(recoveryError) };
@@ -794,7 +842,7 @@ export async function runIdentityPhase(args, effects, { target, mcpReady }) {
794
842
  }
795
843
  if (/not running|not reachable|ECONNREFUSED|connect/i.test(text)) {
796
844
  effects.out(warn("The daemon isn't reachable yet — couldn't create your human identity."));
797
- 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}"'.`));
798
846
  return { key: 'identity', label: 'Human identity', state: 'failed', note: 'daemon not reachable' };
799
847
  }
800
848
  effects.out(warn(`Couldn't create your human identity: ${text.split('\n')[0]}`));
@@ -817,6 +865,9 @@ export async function runIdentityPhase(args, effects, { target, mcpReady }) {
817
865
  export async function runHarnessPhase(args, effects, { target, isDefaultStateDir, exactSuite = null }) {
818
866
  effects.out(heading('Harness plugins'));
819
867
  const detected = (await effects.detectHarnesses()).filter(h => !args.clientIntegrations || args.clientIntegrations.includes(h.name));
868
+ for (const name of args.clientIntegrations ?? []) {
869
+ if (name !== 'fleet' && !detected.some(h => h.name === name)) detected.push({ name, status: 'absent' });
870
+ }
820
871
  for (const h of detected) {
821
872
  if (h.status === 'ok') effects.out(ok(`'${h.command ?? h.name}' → ${h.detail ?? 'real program'} (its plugin can be installed)`));
822
873
  else if (h.status === 'alias') effects.out(warn(`'${h.command ?? h.name}' → ${h.detail} (I won't call it — manual steps below)`));
@@ -826,7 +877,7 @@ export async function runHarnessPhase(args, effects, { target, isDefaultStateDir
826
877
  if (detected.every((h) => h.status === 'absent')) {
827
878
  effects.out(info('No Claude Code, Codex or Hermes found — install one and re-run to wire it up.'));
828
879
  effects.out(info('Your daemon is unaffected; nothing else in this run depends on a harness.'));
829
- return [];
880
+ return args.clientIntegrations ? detected.map(h => ({ key: h.name, state: 'skipped', note: 'not installed' })) : [];
830
881
  }
831
882
 
832
883
  const plans = planHarnessPlugins({
@@ -851,7 +902,7 @@ export async function runHarnessPhase(args, effects, { target, isDefaultStateDir
851
902
  if (plan.action === 'manual' && exactSuite?.localPackages?.[plan.name]) {
852
903
  const root = await effects.prepareClientMarketplace(plan.name, exactSuite.localPackages[plan.name]);
853
904
  effects.out(warn(`${plan.label} requires manual registration of exact local marketplace ${root}; ${target.managed ? 'the saved client default is retained' : `keep OURS_CONFIG=${target.configPath}`}.`));
854
- rows.push({ ...row, state: 'failed', note: 'native executable unavailable' });
905
+ rows.push({ ...row, state: 'failed', note: plan.reason, manual: true });
855
906
  continue;
856
907
  }
857
908
  if (plan.action === 'manual') {
@@ -873,7 +924,7 @@ export async function runHarnessPhase(args, effects, { target, isDefaultStateDir
873
924
  effects.out(warn(`${plan.label} — ${plan.reason}; install it yourself with:`));
874
925
  for (const step of manual) effects.out(info(` ${step}`));
875
926
  if (plan.envLine) effects.out(info(`Before later native launches, set: ${plan.envLine}`));
876
- rows.push({ ...row, state: 'skipped', note: plan.reason });
927
+ rows.push({ ...row, state: 'skipped', note: plan.reason, manual: true });
877
928
  continue;
878
929
  }
879
930
 
@@ -881,16 +932,42 @@ export async function runHarnessPhase(args, effects, { target, isDefaultStateDir
881
932
  let manual = plan.manual;
882
933
  if (exactSuite?.localPackages?.[plan.name]) {
883
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
+ }
884
958
  const steps = plan.name === 'codex'
885
959
  ? [['codex', 'plugin', 'marketplace', 'add', registration], ['codex', 'plugin', 'add', 'ours@ours-codex-marketplace']]
886
960
  : [['claude', 'plugin', 'marketplace', 'add', registration], ['claude', 'plugin', await effects.hasClaudePlugin() ? 'update' : 'install', 'ours@ours.network']];
887
- let failed = false;
961
+ let failure = null;
888
962
  for (const step of steps) {
889
- const outcome = await attempt(effects, false, step.join(' '), () => effects.run(step[0], step.slice(1), { env: profileEnv(target) }));
890
- if (!outcome.ok) { failed = true; break; }
963
+ const outcome = await attempt(effects, false, step.join(' '), () => effects.run(step[0], step.slice(1), { env: profileEnv(target) }), clientDiagnostic);
964
+ if (!outcome.ok) {
965
+ failure = { failedCommand: step, failedStep: step[2] === 'marketplace' ? `Register ${plan.label} marketplace` : `Install ${plan.label} plugin`, detail: clientDiagnostic(outcome.error) };
966
+ break;
967
+ }
891
968
  }
892
969
  effects.out(info(target.managed ? `Native ${plan.name} launches use the saved client default.` : `Native ${plan.name} launches must retain OURS_CONFIG=${target.configPath}.`));
893
- rows.push({ ...row, state: failed ? 'failed' : 'installed' });
970
+ rows.push({ ...row, state: failure ? 'failed' : 'installed', ...(failure ?? {}) });
894
971
  continue;
895
972
  }
896
973
 
@@ -940,6 +1017,58 @@ export async function runHarnessPhase(args, effects, { target, isDefaultStateDir
940
1017
  return rows;
941
1018
  }
942
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
+
943
1072
  /** Install Fleet and let its interactive wizard publish the owned configuration. */
944
1073
  export async function runFleetPhase(args, effects, { target, isDefaultStateDir }) {
945
1074
  effects.out(heading('ours-fleet (your always-online agent team)'));
@@ -956,6 +1085,13 @@ export async function runFleetPhase(args, effects, { target, isDefaultStateDir }
956
1085
  return { key: 'fleet', label: plan.label, state: 'skipped' };
957
1086
  }
958
1087
  const install = args.acquiredFleet ? { ok: true } : await attempt(effects, args.dryRun, plan.install.join(' '), () => effects.run(plan.install[0], plan.install.slice(1)));
1088
+ if (args.disableFleetAgentsSetup) {
1089
+ if (!install.ok) return { key: 'fleet', label: plan.label, state: 'failed', note: 'Fleet installation failed' };
1090
+ effects.out(ok('Fleet CLI installed; agent and model setup deferred to the App. Existing Fleet configuration was retained.'));
1091
+ // A retained configuration may already declare the workflow; its generated policy names the package path this run just replaced.
1092
+ if (!args.dryRun && effects.readText(plan.configPath) !== null) await runFleetManagedCliSetup(args, effects, plan, target);
1093
+ return { key: 'fleet', label: plan.label, state: 'installed', note: 'agents setup deferred' };
1094
+ }
959
1095
  // Fleet owns its v2 manifest, roles, models and permissions. With no prepared
960
1096
  // settings, its wizard keeps the user's terminal while this invocation carries
961
1097
  // the selected daemon; --settings makes the same call strictly noninteractive.
@@ -979,6 +1115,7 @@ export async function runFleetPhase(args, effects, { target, isDefaultStateDir }
979
1115
  return { key: 'fleet', label: plan.label, state: 'failed', note: 'Fleet configuration was not published' };
980
1116
  }
981
1117
  effects.out(ok('ours-fleet installed and initialized; no fleet roles were started.'));
1118
+ if (!args.dryRun) await runFleetManagedCliSetup(args, effects, plan, target);
982
1119
  if (plan.instruction) effects.out(info(plan.instruction));
983
1120
  return { key: 'fleet', label: plan.label, state: 'installed', note: `configured at ${plan.configPath}; stopped` };
984
1121
  }
@@ -1262,15 +1399,23 @@ async function executeServerCommand(args, effects) {
1262
1399
  const existing = record !== null;
1263
1400
  if (existing) {
1264
1401
  record = validateInstallation(record, args.stateDir);
1402
+ if (args.containerEngine && args.containerEngine !== (record.containerEngine ?? 'docker')) throw new Error('Conflicting container engine; explicit migration is required');
1265
1403
  if (args.mode && args.mode !== record.mode) throw new Error('Conflicting runtime mode; retained installation was not changed');
1404
+ 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.`);
1266
1405
  if (args.operation !== 'update' && args.sources && (record.sourcePolicyHash
1267
1406
  ? effects.sourcePolicyHash(args.sources) !== record.sourcePolicyHash
1268
1407
  : effects.readText(args.sources) !== effects.readText(record.sourcesPath))) throw new Error('Conflicting source selection; use explicit server update');
1269
1408
  } else {
1270
1409
  if (args.operation !== 'install' || !args.mode) throw new Error('First server install requires --mode');
1271
- record = effects.newInstallation(args.stateDir, args.mode);
1410
+ record = effects.newInstallation(args.stateDir, args.mode, args);
1272
1411
  for (const key of ['port', 'coworkPort', 'messengerPort']) if (args[key] !== undefined) record[key] = args[key];
1273
1412
  }
1413
+ 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');
1414
+ if (args.serverUrl && args.operation === 'install') {
1415
+ if (!record.gateway) throw new Error('Use server gateway-enable to migrate an existing Docker installation');
1416
+ if (existing && record.gateway.serverUrl !== args.serverUrl) throw new Error('Conflicting gateway server URL');
1417
+ record.gateway = { ...record.gateway, serverUrl: args.serverUrl };
1418
+ }
1274
1419
  if (record.layoutConversion && !['install', 'start', 'stop', 'status'].includes(args.operation)) {
1275
1420
  throw new Error('Layout conversion is incomplete; resume with server install or server start before changing state or authority');
1276
1421
  }
@@ -1278,7 +1423,8 @@ async function executeServerCommand(args, effects) {
1278
1423
  throw new Error(`Server build activation is incomplete; repeat server ${record.buildTransition.operation} before other mutations`);
1279
1424
  }
1280
1425
  const showInstallProgress = args.operation === 'install' && !(existing && (record.schema === 1 || record.layoutConversion));
1281
- const installStageCount = (existing ? 7 : 9) + (args.identityName ? 2 : 0);
1426
+ const installStageCount = (existing ? 7 : 9) + (args.identityName ? 2 : 0)
1427
+ + (args.identityName && args.name && args.surname && (!existing || [undefined, null, args.identityName, `${args.name} ${args.surname}`].includes(record.messengerIdentity)) ? 1 : 0);
1282
1428
  let completedInstallStages = 0;
1283
1429
  const installStage = async (label, explanation, action) => {
1284
1430
  if (!showInstallProgress) return action();
@@ -1296,12 +1442,12 @@ async function executeServerCommand(args, effects) {
1296
1442
  if ((!existing || args.operation === 'update') && !record.buildTransition) {
1297
1443
  args.resolvedSources = await installStage('Package selection', 'Resolve the selected server packages before installation.', async () => {
1298
1444
  const policy = args.sourcePolicy ?? (args.sources ? effects.readJson(args.sources) : effects.packagedSourcePolicy());
1299
- return effects.resolveSourcePolicy(policy, 'server');
1445
+ return effects.resolveSourcePolicy(policy, serverRole(record));
1300
1446
  });
1301
1447
  }
1302
1448
  if (!existing && args.sources) record.sourcePolicyHash = effects.sourcePolicyHash(args.sources);
1303
1449
  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, {
1304
- existing, sourcePath: args.sources ?? record.sourcesPath, sourceManifest: args.resolvedSources, identityName: args.identityName,
1450
+ existing, sourcePath: args.sources ?? record.sourcesPath, sourceManifest: args.resolvedSources, identityName: args.identityName, explicitPorts: args.explicitPorts,
1305
1451
  }));
1306
1452
  if (existing && (record.schema === 1 || record.layoutConversion)
1307
1453
  && ['install', 'start', 'restart', 'update', 'rebuild'].includes(args.operation)) {
@@ -1331,13 +1477,28 @@ async function executeServerCommand(args, effects) {
1331
1477
  if (args.identityName) {
1332
1478
  await installStage('Daemon startup', 'Start the daemon and restore its retained identities.', () => effects.serverLifecycle(record, 'start', ['daemon']));
1333
1479
  const identity = await installStage('Human identity', 'Keep the existing Human identity, or create it on a fresh daemon.', () => effects.serverEnsureIdentity(record, args.identityName));
1334
- record.messengerIdentity = identity.name;
1480
+ // Messenger runs as the person's own identity under the Human identity when Name and Surname are known.
1481
+ // An installation whose Messenger already runs as some other identity under it keeps that identity.
1482
+ const person = args.name && args.surname ? `${args.name} ${args.surname}` : undefined;
1483
+ const selected = existing ? record.messengerIdentity : undefined;
1484
+ if (person && (!selected || selected === identity.name || selected === person)) {
1485
+ const own = await installStage('Messenger identity', 'Keep or create your own identity under the Human identity; Messenger runs as it.', () => effects.serverEnsureMessengerIdentity(record, person));
1486
+ record.messengerIdentity = own.name;
1487
+ } else if (selected && selected !== identity.name
1488
+ && (await effects.serverListIdentities(record)).some(row => row.name === selected && row.kind === 'role' && row.temp === null)) {
1489
+ record.messengerIdentity = selected;
1490
+ } else record.messengerIdentity = identity.name;
1335
1491
  effects.writeJson(recordPath, JSON.stringify(record, null, 2) + '\n');
1336
1492
  await installStage('Application startup', 'Start the selected applications and check readiness.', () => effects.serverLifecycle(record, 'start', record.services.filter(name => name !== 'daemon')));
1337
1493
  } else {
1338
1494
  await installStage('Service startup', 'Start the daemon and selected services, then check readiness.', () => effects.serverLifecycle(record, 'start'));
1339
1495
  }
1496
+ if (record.gateway) await effects.verifyGateway(record);
1340
1497
  if (showInstallProgress) effects.out(progress(installStageCount, installStageCount, 'Installation complete', 'The selected services are ready.'));
1498
+ } else if (args.operation === 'uninstall') {
1499
+ await effects.serverUninstall(record);
1500
+ } else if (args.operation === 'gateway-enable') {
1501
+ await enableGateway(record, args, effects);
1341
1502
  } else if (['backup', 'restore', 'reset'].includes(args.operation)) {
1342
1503
  await effects.serverMaintenance(record, args);
1343
1504
  } else if (['update', 'rebuild'].includes(args.operation)) {
@@ -1385,22 +1546,21 @@ export async function runClientCommand(command, effects) {
1385
1546
  configPath = managedPath;
1386
1547
  }
1387
1548
  let profile;
1388
- if (configPath) profile = validateHostProfile(effects.readProfile(configPath));
1549
+ if (configPath) profile = validateGatewayClientProfile(effects.readProfile(configPath));
1389
1550
  else if (!command.preset && effects.interactive) {
1390
- const endpoint = await effects.askLine('Server HTTP endpoint: ', 'http://127.0.0.1:3050');
1551
+ const endpoint = await effects.askLine('Server HTTP or HTTPS endpoint: ', 'http://127.0.0.1:3050');
1391
1552
  const credentialPath = await effects.askLine('Private issued-token file: ', '');
1392
1553
  if (!credentialPath) throw new InstallUsageError('Client setup requires an issued-token file');
1393
1554
  profile = await effects.discoverClientProfile(endpoint, credentialPath);
1394
1555
  }
1395
1556
  if (!profile) throw new InstallUsageError('client install requires a complete network profile; supply --config or use the interactive client setup');
1396
- if (saved && (saved.endpoint !== profile.endpoint || saved.expectedInstanceId !== profile.expectedInstanceId))
1557
+ if (saved && saved.expectedInstanceId !== profile.expectedInstanceId)
1397
1558
  throw new InstallUsageError('Managed client already selects another server; existing default was not changed');
1398
1559
  for (const name of ['OURS_API_TOKEN', 'OURS_PORT', 'OURS_STATE_DIR', 'OURS_DAEMON_ID']) {
1399
1560
  if (effects.env[name]?.trim()) throw new InstallUsageError(`${name} conflicts with client profile selection`);
1400
1561
  }
1401
1562
  effects.out(info(`Selected server ${profile.endpoint} (instance ${profile.expectedInstanceId}).`));
1402
1563
  await effects.verifyHostProfile(configPath || profile);
1403
- await effects.verifyPackagedMcp(configPath || profile);
1404
1564
  const settings = saved?.installer ?? (configPath ? effects.readJson(configPath)?.installer : undefined);
1405
1565
  const settingsBase = saved ? dirname(managedPath) : configPath ? dirname(configPath) : process.cwd();
1406
1566
  let integrations = command.integrations ?? settings?.integrations;
@@ -1408,13 +1568,14 @@ export async function runClientCommand(command, effects) {
1408
1568
  integrations = [];
1409
1569
  for (const name of ['codex', 'claude-code', 'fleet']) if (await effects.ask(`Install ${name}?`, name !== 'fleet')) integrations.push(name);
1410
1570
  }
1411
- if (!Array.isArray(integrations) || !integrations.length || integrations.some(name => !['codex', 'claude-code', 'fleet'].includes(name)) || new Set(integrations).size !== integrations.length) throw new InstallUsageError('installer.integrations must select codex, claude-code and/or fleet');
1571
+ 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');
1412
1572
  let fleetSettingsPath = command.preset ? command.fleetSettingsPath : settings?.fleetSettingsPath;
1413
- if (command.nonInteractive && integrations.includes('fleet') && !fleetSettingsPath) throw new InstallUsageError('Fleet in CLI mode requires --fleet-settings; no interactive wizard will be opened');
1573
+ const disableFleetAgentsSetup = command.disableFleetAgentsSetup ?? settings?.disableFleetAgentsSetup ?? false;
1574
+ if (command.nonInteractive && !disableFleetAgentsSetup && integrations.includes('fleet') && !fleetSettingsPath) throw new InstallUsageError('Fleet in CLI mode requires --fleet-settings; no interactive wizard will be opened');
1414
1575
  if (fleetSettingsPath !== undefined && (typeof fleetSettingsPath !== 'string' || !fleetSettingsPath))
1415
1576
  throw new InstallUsageError('installer.fleetSettingsPath must be a non-empty path when supplied');
1416
1577
  if (fleetSettingsPath) fleetSettingsPath = resolve(settingsBase, fleetSettingsPath);
1417
- const selectedClients = [...new Set(['sdk', ...(integrations.includes('fleet') ? ['cli'] : []), ...integrations])];
1578
+ const selectedClients = clientPackageNames(integrations);
1418
1579
  let sourcesPath = settings?.sourcesPath;
1419
1580
  let resolvedSources;
1420
1581
  if (command.sourcePolicy) {
@@ -1427,30 +1588,44 @@ export async function runClientCommand(command, effects) {
1427
1588
  resolvedSources = await effects.resolveSourcePolicy(policy, 'client', selectedClients);
1428
1589
  }
1429
1590
  effects.out(progress(0, 4, 'Client configuration', 'Prepare the selected integrations and private connection profile.'));
1430
- const imported = effects.importClientProfile({ profile, sourcesPath, sources: resolvedSources, integrations, fleetSettingsPath, refresh: !!command.preset });
1591
+ if (profile.serverUrl && integrations.includes('fleet')) await effects.qualifyGatewayClient({ profile, sourcesPath, sources: resolvedSources, integrations, refresh: !!command.preset });
1592
+ // A prepared local profile may carry the Fleet notification producer credential beside it.
1593
+ const notificationsProducerPath = configPath && configPath !== managedPath && effects.exists?.(join(dirname(configPath), NOTIFICATIONS_PRODUCER_FILE)) ? join(dirname(configPath), NOTIFICATIONS_PRODUCER_FILE) : undefined;
1594
+ const imported = effects.importClientProfile({ profile, sourcesPath, sources: resolvedSources, integrations, fleetSettingsPath, disableFleetAgentsSetup, refresh: !!command.preset, notificationsProducerPath });
1595
+ let phase = 'Validate saved server connection';
1431
1596
  try {
1432
1597
  await effects.verifyHostProfile(imported.configPath);
1433
1598
  effects.out(progress(1, 4, 'Client packages', 'Acquire and verify the selected client package versions.'));
1599
+ phase = 'Acquire client packages';
1434
1600
  const exactSuite = await effects.acquireClientPackages(imported.configPath, imported.settings.sourcesPath, integrations, { refresh: !!command.preset });
1435
1601
  const args = { assumeYes: true, dryRun: false, channel: 'latest', clientIntegrations: integrations,
1436
- acquiredFleet: exactSuite.fleetBin, fleetSettingsPath: imported.settings.fleetSettingsPath };
1602
+ acquiredFleet: exactSuite.fleetBin, fleetSettingsPath: imported.settings.fleetSettingsPath, disableFleetAgentsSetup: imported.settings.disableFleetAgentsSetup,
1603
+ fleetTaskWorkflowAgents: command.fleetTaskWorkflowAgents };
1437
1604
  const target = { mode: 'host-profile', managed: true, configPath: imported.configPath, profile: imported.profile, endpoint: imported.profile.endpoint };
1438
1605
  effects.out(progress(2, 4, 'Client integrations', 'Register the selected agent integrations.'));
1606
+ phase = 'Register client integrations';
1439
1607
  const summary = await runHarnessPhase(args, effects, { target, isDefaultStateDir: false, exactSuite });
1440
1608
  if (integrations.includes('fleet')) {
1441
1609
  effects.out(progress(3, 4, 'Fleet configuration', 'Apply prepared settings or open the selected Fleet wizard.'));
1610
+ phase = 'Configure Fleet';
1442
1611
  summary.push(await runFleetPhase(args, effects, { target, isDefaultStateDir: false }));
1443
1612
  }
1444
1613
  const incomplete = integrations.filter(name => !summary.some(row => row.key === name && row.state === 'installed'));
1445
1614
  if (effects.env.OURS_CONFIG && resolve(effects.env.OURS_CONFIG) !== imported.configPath)
1446
1615
  effects.out(warn('This shell has an explicit OURS_CONFIG override. Unset it for new clients to use the saved default; installer did not edit your shell.'));
1447
- effects.out(incomplete.length
1448
- ? warn(`Client setup incomplete (${incomplete.join(', ')}); saved profile and settings retained. Re-run ours-install client install.`)
1449
- : ok(`Client setup complete. New clients discover ${imported.configPath}; no OURS_CONFIG export is required.`));
1616
+ if (incomplete.length) {
1617
+ effects.out(warn(`Client setup incomplete (${incomplete.join(', ')}). The selected client integrations need attention:`));
1618
+ for (const name of incomplete) explainClientFailure(effects, name, summary.find(row => row.key === name));
1619
+ clientRetry(effects, imported, integrations);
1620
+ } else effects.out(ok(`Client setup complete. New clients discover ${imported.configPath}; no OURS_CONFIG export is required.`));
1621
+ // Fleet's web service reads its producer credential when it starts; agents keep running across a web restart.
1622
+ if (imported.notificationsProducerChanged && integrations.includes('fleet'))
1623
+ effects.out(info('Notifications are ready for Fleet. Run `ours-fleet web restart` so a running Fleet web console starts producing them.'));
1450
1624
  if (!incomplete.length) effects.out(progress(4, 4, 'Client setup complete', 'All selected integrations are configured.'));
1451
1625
  return incomplete.length ? EXIT_REFUSED : EXIT_OK;
1452
1626
  } catch (error) {
1453
- effects.out(warn(`Client setup incomplete: ${reason(error)}. Saved profile and settings retained; re-run ours-install client install.`));
1627
+ effects.out(warn(`Client setup incomplete: ${phase} failed — ${clientDiagnostic(error)}. Fix this error before retrying.`));
1628
+ clientRetry(effects, imported, integrations);
1454
1629
  return EXIT_REFUSED;
1455
1630
  }
1456
1631
  }
@@ -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
+ }