@ours.network/install 2.1.4 → 2.1.7

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.
@@ -1,41 +1,11 @@
1
- /** Replace only the verified, user-owned npm CLI entry after managed cutover. */
2
- import { accessSync, constants, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, writeFileSync, chmodSync } from 'node:fs';
3
- import { dirname, isAbsolute, join, resolve } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import { createHash, randomUUID } from 'node:crypto';
1
+ /** The managed `ours` launcher bound to one installation record. */
2
+ import { dirname, isAbsolute, resolve } from 'node:path';
6
3
 
7
4
  const marker = '// ours-managed-cli-v1 ';
8
- const backupName = 'managed-cli-original.json';
9
- const sha = bytes => createHash('sha256').update(bytes).digest('hex');
10
- const uid = () => process.getuid();
11
5
  function absolute(path) {
12
6
  if (typeof path !== 'string' || !isAbsolute(path) || resolve(path) !== path || /[\r\n\0]/.test(path)) throw new Error('Managed CLI requires normalized absolute paths');
13
7
  return path;
14
8
  }
15
- function owned(path, { directory = false, writable = false } = {}) {
16
- const stat = lstatSync(path);
17
- if (stat.uid !== uid() || (directory ? !stat.isDirectory() : (!stat.isFile() || stat.nlink !== 1)) || (stat.mode & 0o022)) throw new Error(`Managed CLI refuses foreign or unsafe ownership: ${path}`);
18
- if (directory && realpathSync(path) !== path) throw new Error('Managed CLI directory must be canonical');
19
- if (writable) {
20
- if (!(stat.mode & 0o200)) throw new Error(`Managed CLI path is read-only: ${path}`);
21
- accessSync(path, constants.W_OK | (directory ? constants.X_OK : 0));
22
- }
23
- return stat;
24
- }
25
- function snapshot(path) {
26
- const stat = lstatSync(path);
27
- if (stat.uid !== uid() || (!stat.isSymbolicLink() && (!stat.isFile() || stat.nlink !== 1))) throw new Error('Managed CLI entry is not an owned file or symlink');
28
- if (!stat.isSymbolicLink() && (stat.mode & 0o022)) throw new Error('Managed CLI entry is writable by another user');
29
- return { kind: stat.isSymbolicLink() ? 'symlink' : 'file', dev: stat.dev, ino: stat.ino, uid: stat.uid, mode: stat.mode & 0o7777,
30
- size: stat.size, mtimeMs: stat.mtimeMs, ...(stat.isSymbolicLink() ? { link: readlinkSync(path), resolved: realpathSync(path) } : {}), digest: sha(readFileSync(path)) };
31
- }
32
- function readBackup(targetRoot) {
33
- const path = join(targetRoot, 'legacy-backup', backupName);
34
- owned(dirname(path), { directory: true }); owned(path);
35
- const value = JSON.parse(readFileSync(path, 'utf8'));
36
- if (value.schema !== 1 || value.targetRoot !== targetRoot || !value.original || typeof value.originalProgram !== 'string') throw new Error('Invalid managed CLI backup');
37
- return value;
38
- }
39
9
 
40
10
  export function buildManagedCli(recordPath, installerPath) {
41
11
  absolute(recordPath); absolute(installerPath);
@@ -90,75 +60,3 @@ if (result.signal) { process.kill(process.pid, result.signal); process.exit(1);
90
60
  process.exit(result.status ?? 1);
91
61
  `;
92
62
  }
93
-
94
- export async function inspectManagedCli(effects, targetRoot) {
95
- if (!['linux', 'darwin'].includes(effects.platform?.platform ?? process.platform) || typeof process.getuid !== 'function') throw new Error('Managed CLI cutover supports Linux/macOS only');
96
- absolute(targetRoot);
97
- const output = async args => {
98
- const result = await effects.run(args[0], args.slice(1));
99
- if (result.code !== undefined && result.code !== 0) throw new Error('Cannot determine the existing global CLI selection');
100
- return absolute(result.stdout.trim());
101
- };
102
- const npmRoot = await output(['npm', 'root', '--global']);
103
- const prefix = await output(['npm', 'prefix', '--global']);
104
- const binPath = join(prefix, 'bin', 'ours');
105
- const selected = await output(['which', 'ours']);
106
- if (selected !== binPath) throw new Error('PATH selects another ours command; select the verified npm global bin before migration');
107
- owned(dirname(binPath), { directory: true, writable: true });
108
- const packageRoot = realpathSync(join(npmRoot, '@ours.network/cli'));
109
- const packagePath = join(packageRoot, 'package.json'); owned(packagePath);
110
- const pkg = JSON.parse(readFileSync(packagePath, 'utf8'));
111
- if (pkg.name !== '@ours.network/cli' || typeof pkg.bin?.ours !== 'string') throw new Error('Global package does not declare the expected ours CLI');
112
- const originalProgram = realpathSync(resolve(packageRoot, pkg.bin.ours));
113
- if (!originalProgram.startsWith(packageRoot + '/')) throw new Error('Global CLI bin escapes its package');
114
- owned(originalProgram); accessSync(originalProgram, constants.R_OK | constants.X_OK);
115
- const before = snapshot(binPath);
116
- let installed = false;
117
- let installerPath = fileURLToPath(new URL('../install.mjs', import.meta.url));
118
- if (before.kind === 'symlink') {
119
- if (before.resolved !== originalProgram) throw new Error('Global ours symlink does not target the verified npm CLI');
120
- } else {
121
- const contents = readFileSync(binPath, 'utf8');
122
- const line = contents.split('\n')[1];
123
- if (!line?.startsWith(marker)) throw new Error('Refusing to replace an unknown ours executable');
124
- const binding = JSON.parse(line.slice(marker.length));
125
- if (binding.schema !== 1 || binding.targetRoot !== targetRoot || binding.recordPath !== join(targetRoot, 'installation.json')) throw new Error('Managed CLI belongs to another installation');
126
- installerPath = absolute(binding.installerPath);
127
- if (contents !== buildManagedCli(binding.recordPath, installerPath)) throw new Error('Managed CLI launcher was modified');
128
- const backup = readBackup(targetRoot);
129
- if (backup.binPath !== binPath || backup.originalProgram !== originalProgram) throw new Error('Managed CLI backup selects another original executable');
130
- installed = true;
131
- }
132
- return { schema: 1, targetRoot, binPath, originalProgram, installerPath, before, installed };
133
- }
134
-
135
- export async function installManagedCli(record, cliPlan, effects, { rename = renameSync } = {}) {
136
- if (record.root !== cliPlan.targetRoot) throw new Error('Managed CLI target changed after inspection');
137
- const fresh = await inspectManagedCli(effects, record.root);
138
- if (fresh.binPath !== cliPlan.binPath || fresh.originalProgram !== cliPlan.originalProgram || JSON.stringify(fresh.before) !== JSON.stringify(cliPlan.before)) throw new Error('Global CLI changed after inspection; cutover refused');
139
- const installerPath = absolute(cliPlan.installerPath);
140
- owned(installerPath);
141
- if (realpathSync(installerPath) !== installerPath) throw new Error('Managed installer path must be canonical');
142
- if (fresh.installed && fresh.installerPath !== installerPath) throw new Error('Managed installer selection changed after inspection');
143
- if (fresh.installed) return { binPath: fresh.binPath, originalProgram: fresh.originalProgram, changed: false };
144
- owned(record.root, { directory: true });
145
- const backupDir = join(record.root, 'legacy-backup');
146
- if (!existsSync(backupDir)) mkdirSync(backupDir, { mode: 0o700 });
147
- const backupStat = owned(backupDir, { directory: true });
148
- if (backupStat.mode & 0o077) throw new Error('CLI backup directory must be private');
149
- const backupPath = join(backupDir, backupName);
150
- const backup = { schema: 1, targetRoot: record.root, binPath: fresh.binPath, originalProgram: fresh.originalProgram,
151
- original: fresh.before, ...(fresh.before.kind === 'file' ? { bytes: readFileSync(fresh.binPath).toString('base64') } : {}) };
152
- if (existsSync(backupPath)) {
153
- const original = readBackup(record.root);
154
- if (original.binPath !== backup.binPath || original.originalProgram !== backup.originalProgram) throw new Error('Existing CLI backup differs from the selected original');
155
- } else writeFileSync(backupPath, JSON.stringify(backup, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
156
- const contents = buildManagedCli(join(record.root, 'installation.json'), installerPath);
157
- const temporary = join(dirname(fresh.binPath), `.ours-managed-${randomUUID()}`);
158
- try {
159
- writeFileSync(temporary, contents, { flag: 'wx', mode: 0o700 }); chmodSync(temporary, 0o755);
160
- if (JSON.stringify(snapshot(fresh.binPath)) !== JSON.stringify(fresh.before)) throw new Error('Global CLI changed during cutover');
161
- rename(temporary, fresh.binPath);
162
- } finally { rmSync(temporary, { force: true }); }
163
- return { binPath: fresh.binPath, originalProgram: fresh.originalProgram, changed: true };
164
- }
@@ -24,6 +24,7 @@ import { tgConfigPath, coworkConfigPath } from './components.mjs';
24
24
  import { configJournal, reportRollback } from './journal.mjs';
25
25
  import { UNINSTALL_USAGE } from './usage.mjs';
26
26
  import { ok, info, warn, heading } from './ui.mjs';
27
+ import { UNSUPPORTED_LAYOUT, refuseOldLayout } from './plan.mjs';
27
28
 
28
29
  export const EXIT_OK = 0;
29
30
  export const EXIT_REFUSED = 2;
@@ -86,6 +87,7 @@ export async function runUninstall(argv, effects) {
86
87
  }
87
88
 
88
89
  const managed = effects.readJson(join(dir, 'installation.json'));
90
+ try { refuseOldLayout(managed, dir, path => effects.readJson(path)); } catch { effects.out(warn(`ours: ${UNSUPPORTED_LAYOUT}`)); return EXIT_REFUSED; }
89
91
  if (managed?.schema === 2 && ['docker', 'packages'].includes(managed.mode)) {
90
92
  if (contract.engaged || args.config || effects.env.OURS_CONFIG) {
91
93
  effects.out(warn('Managed server uninstall does not support legacy component/profile selections. Nothing was changed; use an explicit server uninstall with those selectors cleared.'));
@@ -1,7 +1,6 @@
1
1
  import { assertSecureNodeVersion } from './security-versions.mjs';
2
2
  import { validateGatewayClientProfile } from './target.mjs';
3
3
  import { enableGateway } from './gateway-transition.mjs';
4
- import { executeLegacyMigration } from './legacy-migration.mjs';
5
4
  // ours-install v3 — the orchestrator.
6
5
  //
7
6
  // This is the part that cannot be pure: it walks the flow, renders the screens
@@ -30,7 +29,7 @@ import { executeLegacyMigration } from './legacy-migration.mjs';
30
29
  import { basename, dirname, join, resolve } from 'node:path';
31
30
  import { parseNetworkArgs, validateHostProfile, parseInstallArgs, resolveTarget, resolveProfileSelection, profileEnv, InstallUsageError } from './target.mjs';
32
31
  import { NOTIFICATIONS_PRODUCER_FILE } from './server-onboarding.mjs';
33
- import { clientPackageNames, selectSourcePackages, validateInstallation, SERVER_SERVICES, planDaemonConfig, planServiceInstall, serviceInstallCommand } from './plan.mjs';
32
+ import { clientPackageNames, selectSourcePackages, validateInstallation, refuseOldLayout, MIGRATE_FROM_UNSUPPORTED, SERVER_SERVICES, planDaemonConfig, planServiceInstall, serviceInstallCommand } from './plan.mjs';
34
33
  import {
35
34
  COMPONENTS,
36
35
  planComponentSelection, planMcpAttachment, planTgAttachment, planCoworkAttachment,
@@ -1557,9 +1556,9 @@ export async function runInstall(argv, effects) {
1557
1556
 
1558
1557
  export async function runServerCommand(args, effects) {
1559
1558
  if (args.operation === 'status') return executeServerCommand(args, effects);
1560
- return effects.withInstallationLock(args.stateDir, () => args.migrateFrom
1561
- ? executeLegacyMigration(args, effects, executeServerCommand)
1562
- : executeServerCommand(args, effects));
1559
+ if (args.migrateFrom !== undefined) throw new InstallUsageError(MIGRATE_FROM_UNSUPPORTED);
1560
+ refuseOldLayout(effects.readJson(join(args.stateDir, 'installation.json')), args.stateDir, effects.readJson);
1561
+ return effects.withInstallationLock(args.stateDir, () => executeServerCommand(args, effects));
1563
1562
  }
1564
1563
 
1565
1564
  async function executeServerCommand(args, effects) {
@@ -1567,7 +1566,7 @@ async function executeServerCommand(args, effects) {
1567
1566
  let record = effects.readJson(recordPath);
1568
1567
  const existing = record !== null;
1569
1568
  if (existing) {
1570
- record = validateInstallation(record, args.stateDir);
1569
+ record = validateInstallation(refuseOldLayout(record, args.stateDir, effects.readJson), args.stateDir);
1571
1570
  if (args.containerEngine && args.containerEngine !== (record.containerEngine ?? 'docker')) throw new Error('Conflicting container engine; explicit migration is required');
1572
1571
  if (args.mode && args.mode !== record.mode) throw new Error('Conflicting runtime mode; retained installation was not changed');
1573
1572
  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.`);
@@ -1585,13 +1584,10 @@ async function executeServerCommand(args, effects) {
1585
1584
  if (existing && record.gateway.serverUrl !== args.serverUrl) throw new Error('Conflicting gateway server URL');
1586
1585
  record.gateway = { ...record.gateway, serverUrl: args.serverUrl };
1587
1586
  }
1588
- if (record.layoutConversion && !['install', 'start', 'stop', 'status'].includes(args.operation)) {
1589
- throw new Error('Layout conversion is incomplete; resume with server install or server start before changing state or authority');
1590
- }
1591
1587
  if (record.buildTransition && !['stop', 'status', record.buildTransition.operation].includes(args.operation)) {
1592
1588
  throw new Error(`Server build activation is incomplete; repeat server ${record.buildTransition.operation} before other mutations`);
1593
1589
  }
1594
- const showInstallProgress = args.operation === 'install' && !(existing && (record.schema === 1 || record.layoutConversion));
1590
+ const showInstallProgress = args.operation === 'install';
1595
1591
  const installStageCount = (existing ? 7 : 9) + (args.identityName ? 2 : 0)
1596
1592
  + (args.identityName && args.name && args.surname && (!existing || [undefined, null, args.identityName, `${args.name} ${args.surname}`].includes(record.messengerIdentity)) ? 1 : 0);
1597
1593
  let completedInstallStages = 0;
@@ -1618,19 +1614,7 @@ async function executeServerCommand(args, effects) {
1618
1614
  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, {
1619
1615
  existing, sourcePath: args.sources ?? record.sourcesPath, sourceManifest: args.resolvedSources, identityName: args.identityName, explicitPorts: args.explicitPorts,
1620
1616
  }));
1621
- if (existing && (record.schema === 1 || record.layoutConversion)
1622
- && ['install', 'start', 'restart', 'update', 'rebuild'].includes(args.operation)) {
1623
- record = record.mode === 'docker'
1624
- ? await effects.convertDockerInstallation(record, args.operation)
1625
- : await effects.convertPackageInstallation(record, args.operation);
1626
- if (['install', 'start', 'restart'].includes(args.operation)) {
1627
- effects.out(ok(`Server ${args.operation} completed after layout conversion for ${record.root}`));
1628
- return EXIT_OK;
1629
- }
1630
- }
1631
- if (args.operation === 'stop' && record.layoutConversion) {
1632
- await effects.stopPendingConversion(record);
1633
- } else if (args.operation === 'install') {
1617
+ if (args.operation === 'install') {
1634
1618
  if (!existing) {
1635
1619
  await installStage('Installation setup', 'Save the selected packages and installation settings.', async () => {
1636
1620
  await effects.initializeSelection(record, args.resolvedSources);
@@ -1695,9 +1679,6 @@ async function executeServerCommand(args, effects) {
1695
1679
  if (args.operation === 'status') effects.out(JSON.stringify({
1696
1680
  mode: record.mode, instanceId: record.instanceId, schema: record.schema, running,
1697
1681
  ...(record.buildTransition ? { buildTransition: record.buildTransition.phase } : {}),
1698
- ...(record.layoutConversion ? {
1699
- layoutConversion: record.schema === 1 ? 'preparation-pending' : 'activation-pending',
1700
- } : {}),
1701
1682
  }));
1702
1683
  if (args.operation === 'status') return EXIT_OK;
1703
1684
  }
package/lib/plan.mjs CHANGED
@@ -349,25 +349,31 @@ export async function resolveSourcePolicy(manifest, role, clients = [], resolveN
349
349
  return exact;
350
350
  }
351
351
 
352
- /** Installer-owned physical layout; package defaults remain unchanged. */
352
+ /** Installer-owned physical layout (schema 2); package defaults remain unchanged. */
353
353
  export function installationPaths(record) {
354
- const root = record.root;
355
- const shared = record.schema === 2;
356
- const state = shared ? join(root, 'storage', 'state') : root;
357
- const daemon = join(state, shared ? 'daemon' : 'data');
358
- const credentials = Object.fromEntries(['telegram', 'cowork', 'messenger'].map(service => [
359
- service, shared ? join(state, 'credentials', service, 'daemon-token') : join(root, 'credentials', `${service}-token`),
360
- ]));
354
+ const state = join(record.root, 'storage', 'state');
355
+ const daemon = join(state, 'daemon');
356
+ const credentials = Object.fromEntries(['telegram', 'cowork', 'messenger'].map(service => [service, join(state, 'credentials', service, 'daemon-token')]));
361
357
  return {
362
358
  state, daemon, mcp: join(state, 'mcp'), telegram: join(state, 'telegram'),
363
359
  cowork: join(state, 'cowork'), messenger: join(state, 'messenger'), credentials,
364
- config: shared ? join(daemon, 'config.json') : join(root, 'config.json'),
360
+ config: join(daemon, 'config.json'),
365
361
  };
366
362
  }
367
363
 
364
+ export const UNSUPPORTED_LAYOUT = 'Unsupported old installation layout (schema 1 / legacy ~/.ours). Migration from old layouts is no longer supported; install fresh into a new folder. Existing data was not changed.';
365
+ export const MIGRATE_FROM_UNSUPPORTED = '--migrate-from is no longer supported: migration from old installation layouts (schema 1 / legacy ~/.ours) was removed. Install fresh into a new folder; existing data was not changed.';
366
+ /** Schema-1 selections, pending layout conversions and unfinished ~/.ours imports are refused before any write. */
367
+ export function refuseOldLayout(record, root, readJson) {
368
+ if (record && (record.schema === 1 || record.layoutConversion !== undefined
369
+ || (record.legacyMigrationSource !== undefined && readJson(join(root, 'legacy-migration.json'))?.phase !== 'complete'))) throw new Error(UNSUPPORTED_LAYOUT);
370
+ return record;
371
+ }
372
+
368
373
  export function validateInstallation(record, root) {
374
+ if (record?.schema === 1 || record?.layoutConversion !== undefined) throw new Error(UNSUPPORTED_LAYOUT);
369
375
  if (record) validateContainerEngine(record);
370
- if (!record || ![1, 2].includes(record.schema) || !['docker', 'packages'].includes(record.mode)
376
+ if (!record || record.schema !== 2 || !['docker', 'packages'].includes(record.mode)
371
377
  || record.root !== root || record.configPath !== installationPaths(record).config
372
378
  || record.sourcesPath !== join(root, 'sources.json') || record.workDir !== join(root, 'runtime')
373
379
  || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(record.instanceId ?? '')
@@ -377,41 +383,18 @@ export function validateInstallation(record, root) {
377
383
  throw new Error('Invalid or conflicting installation selection');
378
384
  }
379
385
  if (record.product !== undefined && (!PRODUCTS.includes(record.product) || record.product === 'workspace'
380
- || record.schema !== 2 || record.mode !== 'docker' || record.gateway !== undefined
386
+ || record.mode !== 'docker' || record.gateway !== undefined
381
387
  || JSON.stringify(record.services) !== JSON.stringify(['daemon']))) {
382
388
  throw new Error('Invalid plugin-only installation selection');
383
389
  }
384
- if (record.gateway !== undefined && (record.schema !== 2 || record.mode !== 'docker' || record.gateway?.version !== 1
390
+ if (record.gateway !== undefined && (record.mode !== 'docker' || record.gateway?.version !== 1
385
391
  || Object.keys(record.gateway).some(key => !['version', 'serverUrl'].includes(key)) || record.services.at(-1) !== 'gateway')) {
386
392
  throw new Error('Invalid gateway installation selection');
387
393
  }
388
394
  if (record.gateway) gatewayAddress(record);
389
- if (record.layoutConversion !== undefined) {
390
- // DEPRECATED (introduced in 2.0): legacy managed-layout conversion only.
391
- // Removal target: 3.0, after supported installs convert and upgrade inputs
392
- // no longer need this reader. Retain backups and supported archive import.
393
- const conversion = record.layoutConversion;
394
- const source = conversion?.sourceRecord;
395
- if (conversion?.version !== 1 || source?.schema !== 1 || source.layoutConversion !== undefined
396
- || typeof conversion.backupPath !== 'string'
397
- || dirname(conversion.backupPath) !== join(root, 'storage', 'backups')
398
- || resolve(conversion.backupPath) !== conversion.backupPath
399
- || !Array.isArray(conversion.runningServices)
400
- || new Set(conversion.runningServices).size !== conversion.runningServices.length) {
401
- throw new Error('Invalid layout conversion record');
402
- }
403
- validateInstallation(source, root);
404
- if (JSON.stringify(source.containerBinding) !== JSON.stringify(record.containerBinding)) throw new Error('Conflicting conversion backend');
405
- if (['mode', 'containerEngine', 'instanceId', 'project', 'sourcesPath', 'workDir'].some(key => source[key] !== record[key])
406
- || JSON.stringify(source.services) !== JSON.stringify(record.services)
407
- || conversion.runningServices.some(service => !source.services.includes(service))) {
408
- throw new Error('Conflicting layout conversion source');
409
- }
410
- }
411
395
  if (record.buildTransition !== undefined) {
412
396
  const transition = record.buildTransition, candidate = transition?.candidate;
413
- if (record.schema !== 2 || record.layoutConversion || !candidate
414
- || candidate.buildTransition !== undefined || candidate.layoutConversion !== undefined
397
+ if (!candidate || candidate.buildTransition !== undefined
415
398
  || dirname(candidate.root ?? '') !== root || !/^\.build-[A-Za-z0-9]{6}$/.test(basename(candidate.root ?? ''))
416
399
  || !/^ours-build[0-9a-f]{32}$/.test(candidate.project ?? '')
417
400
  || !['update', 'rebuild'].includes(transition.operation)
package/lib/prompt.mjs CHANGED
@@ -132,11 +132,11 @@ function choose(write, fd, question, choices, defaults, multiple, {
132
132
  drawn = true;
133
133
  choices.forEach((choice, i) => {
134
134
  const marker = multiple ? (selected[i] ? c.green('[x]') : '[ ]') : (i === current ? c.green('(●)') : '( )');
135
- write(`\r\x1b[K ${i === current ? c.cyan('> ') : ' '}${marker} ${choice.label}\n`);
135
+ write(`\r\x1b[K ${i === current ? c.cyan('> ') : ' '}${marker} ${i === current ? c.bold(choice.label) : choice.label}\n`);
136
136
  });
137
137
  };
138
138
  try {
139
- write(`\x1b[?25l ${question}\n ${c.bold('↑/↓')} move${multiple ? ', ' + c.bold('Space') + ' toggle' : ''}, ${c.bold('Enter')} confirm\n`);
139
+ write(`\x1b[?25l\n ${c.bold(question)}\n ${c.gray(`↑/↓ move${multiple ? ', Space toggle' : ''}, Enter confirm`)}\n`);
140
140
  redraw();
141
141
  for (;;) {
142
142
  const byte = next();
package/lib/removal.mjs CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  import { basename, dirname, join, resolve } from 'node:path';
13
13
  import { modify, applyEdits, parse as parseJsonc } from 'jsonc-parser';
14
- import { validateInstallation, unitNameForStateDir } from './plan.mjs';
14
+ import { validateInstallation, refuseOldLayout, unitNameForStateDir, UNSUPPORTED_LAYOUT } from './plan.mjs';
15
15
  import { validateContainerEngine, runContainer } from './container-engine.mjs';
16
16
  import { classifyStateDir } from './detect.mjs';
17
17
  import { stripManagedBlock, YAML_BLOCK, MD_BLOCK } from './uninstall.mjs';
@@ -101,8 +101,12 @@ export async function discoverFootprint(effects, { stateDirs = [], journal = nul
101
101
  continue;
102
102
  }
103
103
  let record;
104
- try { record = validateInstallation(json(text), root); if (record.containerBinding || record.containerEngine) validateContainerEngine(record); }
105
- catch { keep('data', `Folder ${root}`, 'its Ours installation record is damaged, so nothing in it is removed automatically; repair or remove the folder yourself, then run the removal again', true); continue; }
104
+ try { record = refuseOldLayout(validateInstallation(json(text), root), root, path => json(effects.readText(path) ?? '')); if (record.containerBinding || record.containerEngine) validateContainerEngine(record); }
105
+ catch (error) {
106
+ keep('data', `Folder ${root}`, error.message === UNSUPPORTED_LAYOUT ? 'it holds an old installation layout this installer no longer supports, so nothing in it is removed automatically; remove the folder yourself if you no longer need it'
107
+ : 'its Ours installation record is damaged, so nothing in it is removed automatically; repair or remove the folder yourself, then run the removal again', true);
108
+ continue;
109
+ }
106
110
  if (retained && retained.instanceId !== record.instanceId) { keep('data', `Folder ${root}`, 'it now holds a different Ours installation than the unfinished removal recorded'); continue; }
107
111
  const item = { ...journalInstallation(record), ...(retained?.candidateProjects?.length ? { candidateProjects: [...new Set([...retained.candidateProjects, ...journalInstallation(record).candidateProjects])] } : {}), ...(retained?.images ? { images: retained.images } : {}), record, tombstone: tombstone(root, 'root', record.instanceId) };
108
112
  item.ownedImages = json(effects.readText(join(root, 'owned-images.json')) ?? '')?.images ?? null;
@@ -534,7 +538,16 @@ async function executeStep(step, effects, context) {
534
538
  const [image] = JSON.parse(found.stdout);
535
539
  if (image.Id !== id) { problems.push(`${tag} changed since it was checked and was left in place`); continue; }
536
540
  // Remove only this name. An image ID still named or used elsewhere stays.
537
- try { await runContainer(effects, step.installation, ['image', 'rm', tag]); }
541
+ try {
542
+ await runContainer(effects, step.installation, ['image', 'rm', tag]);
543
+ // A published image this installer pulled keeps only its registry digest name;
544
+ // drop that too once no other name uses it. A still-used image stays in place.
545
+ if (!(image.RepoTags ?? []).some(other => other !== tag && !/^(?:docker\.io\/)?adaptframework\/ours-(?:runtime|maintenance)@/.test(other))) {
546
+ for (const digest of (image.RepoDigests ?? []).filter(name => /^(?:docker\.io\/)?adaptframework\/ours-(?:runtime|maintenance)@sha256:[0-9a-f]{64}$/.test(name))) {
547
+ try { await runContainer(effects, step.installation, ['image', 'rm', digest]); } catch { /* still used elsewhere */ }
548
+ }
549
+ }
550
+ }
538
551
  catch {
539
552
  let users = '';
540
553
  try { users = (await runContainer(effects, step.installation, ['ps', '-a', '--filter', `ancestor=${id}`, '--format', '{{.Names}}'])).stdout.split(/\s+/).filter(Boolean).join(', '); } catch { /* named generically below */ }
@@ -112,7 +112,7 @@ process.stdout.write(JSON.stringify(output));
112
112
  return { rows, root: roots[0] };
113
113
  }
114
114
  function retained({ rows, root }) {
115
- effects.out?.(`Retained ${rows.length} existing ${rows.length === 1 ? 'identity' : 'identities'}; Human identity: ${root.name}.`);
115
+ effects.out?.(`Retained ${rows.length} existing ${rows.length === 1 ? 'identity' : 'identities'}, including your Human identity.`);
116
116
  return { name: root.name, cid: root.cid, created: false };
117
117
  }
118
118
  return {
@@ -123,7 +123,7 @@ process.stdout.write(JSON.stringify(output));
123
123
  const prior = await identities(record);
124
124
  if (prior.root) return retained(prior);
125
125
  if (prior.rows.some(row => row.name === name)) throw new Error('Requested Human identity name already exists; no identity was changed');
126
- effects.out?.(`Creating Human identity ${name}; retaining ${prior.rows.length} existing identities.`);
126
+ effects.out?.(`Creating your Human identity; retaining ${prior.rows.length} existing identities.`);
127
127
  try {
128
128
  await identityCommand(record, 'create-root', name);
129
129
  } catch (error) {
@@ -137,7 +137,7 @@ process.stdout.write(JSON.stringify(output));
137
137
  const after = await identities(record);
138
138
  if (!after.root) throw new Error('Human identity creation completed without a visible root');
139
139
  if (after.root.name !== name) return retained(after);
140
- effects.out?.(`Human identity ${after.root.name} is ready.`);
140
+ effects.out?.('Your Human identity is ready.');
141
141
  return { name: after.root.name, cid: after.root.cid, created: true };
142
142
  },
143
143
  /**
@@ -166,10 +166,10 @@ process.stdout.write(JSON.stringify(output));
166
166
  };
167
167
  if (prior.rows.some(row => row.name === name)) {
168
168
  const row = await adopt(prior);
169
- effects.out?.(`Retained Messenger identity ${name}.`);
169
+ effects.out?.('Retained your Messenger identity.');
170
170
  return { name, cid: row.cid, created: false };
171
171
  }
172
- effects.out?.(`Creating Messenger identity ${name} under ${prior.root.name}; retaining ${prior.rows.length} existing identities.`);
172
+ effects.out?.(`Creating your Messenger identity; retaining ${prior.rows.length} existing identities.`);
173
173
  let result;
174
174
  try {
175
175
  result = await identityCommand(record, 'create-role', name);
@@ -187,7 +187,7 @@ process.stdout.write(JSON.stringify(output));
187
187
  if (result?.created?.hierarchy !== 'role' || result.created.underRoot !== prior.root.name || after.root?.cid !== prior.root.cid
188
188
  || !listed(row) || result.created.info?.cid !== row.cid || !under(result.current, row))
189
189
  throw new Error('Messenger identity creation completed without a usable identity under the Human identity');
190
- effects.out?.(`Messenger identity ${name} is ready.`);
190
+ effects.out?.('Your Messenger identity is ready.');
191
191
  return { name, cid: row.cid, created: true };
192
192
  },
193
193
  async serverEnsureHumanProfile(record, human) {