@ours.network/install 2.1.3 → 2.1.6

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,297 +0,0 @@
1
- import * as fs from 'node:fs';
2
- import { dirname, join, relative, resolve } from 'node:path';
3
- import { randomUUID } from 'node:crypto';
4
- import { installationPaths, validateInstallation, SERVER_SERVICES } from './plan.mjs';
5
- import { copyPrivateTree, createArchive, validateArchive, scanSource } from '../assets/scripts/maintenance/state-archive.mjs';
6
- import { publishNoReplace } from '../assets/scripts/maintenance/state-native.mjs';
7
-
8
- import { recordNames, readBuildRecords, initializeBuildMarker } from '../assets/scripts/maintenance/build-context.mjs';
9
- const PROVENANCE_DIRECTORY = '.ours-provenance';
10
- const COMPONENTS = [...SERVER_SERVICES, 'mcp'];
11
- const CONSUMERS = SERVER_SERVICES.filter(service => service !== 'daemon');
12
-
13
- function privateFile(path) {
14
- const stat = fs.lstatSync(path);
15
- if (!stat.isFile() || stat.uid !== process.getuid() || stat.gid !== process.getgid() || (stat.mode & 0o7777) !== 0o600) {
16
- throw new Error(`Unsafe conversion source file: ${path}`);
17
- }
18
- return fs.readFileSync(path);
19
- }
20
-
21
- function readConfig(path) {
22
- const value = JSON.parse(privateFile(path));
23
- if (!value || Array.isArray(value) || typeof value !== 'object') {
24
- throw new Error('Conversion source configuration must be an object');
25
- }
26
- return value;
27
- }
28
-
29
- function writeConfig(path, value) {
30
- fs.writeFileSync(path, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
31
- fs.chmodSync(path, 0o600);
32
- }
33
-
34
- function conversionPaths(record, staging) {
35
- const paths = installationPaths(record);
36
- const parent = join(record.root, 'storage', '.maintenance');
37
- if (dirname(staging) !== parent || resolve(staging) !== staging || fs.realpathSync(parent) !== parent) {
38
- throw new Error('Conversion staging must use the selected private maintenance directory');
39
- }
40
- const parentStat = fs.lstatSync(parent);
41
- if (!parentStat.isDirectory() || parentStat.uid !== process.getuid() || parentStat.gid !== process.getgid() || (parentStat.mode & 0o7777) !== 0o700) {
42
- throw new Error('Conversion staging parent must be private and owned by the operator');
43
- }
44
- return {
45
- paths,
46
- staged: path => join(staging, relative(paths.state, path)),
47
- };
48
- }
49
-
50
- // DEPRECATED (introduced in 2.0): legacy managed-layout conversion only.
51
- // Removal target: 3.0 after supported upgrades no longer need this reader.
52
- // Retain protected backups and supported archive import.
53
- // The caller holds installation exclusion and has stopped/prepared all writers.
54
- export async function stageLegacyPackageState(sourceRecord, staging) {
55
- validateInstallation(sourceRecord, sourceRecord.root);
56
- if (sourceRecord.schema !== 1 || sourceRecord.mode !== 'packages') {
57
- throw new Error('Select a legacy managed package installation');
58
- }
59
- const source = installationPaths(sourceRecord);
60
- const targetRecord = { ...sourceRecord, schema: 2 };
61
- targetRecord.configPath = installationPaths(targetRecord).config;
62
- const { paths: target, staged } = conversionPaths(targetRecord, staging);
63
- const ownership = { uid: process.getuid(), gid: process.getgid() };
64
- const configBytes = privateFile(source.config);
65
- const config = readConfig(source.config);
66
- const nestedConfig = join(source.daemon, 'config.json');
67
- if (fs.existsSync(nestedConfig) && !privateFile(nestedConfig).equals(configBytes)) {
68
- throw new Error('Conflicting daemon config sources require explicit resolution');
69
- }
70
- const applicationConfig = config.networkMcp?.applicationConfigPath;
71
- if (applicationConfig && applicationConfig !== join(source.mcp, 'config.json')) {
72
- throw new Error('External MCP configuration ownership requires explicit resolution');
73
- }
74
- if (config.networkMcp && (
75
- config.networkMcp.profile?.credentialPath !== join(source.daemon, 'daemon-token') ||
76
- config.networkMcp.profile?.expectedInstanceId !== sourceRecord.instanceId
77
- )) {
78
- throw new Error('MCP profile does not select this managed installation');
79
- }
80
- if (fs.existsSync(join(source.daemon, '.mcp'))) {
81
- throw new Error('Conflicting embedded and separate MCP sources require explicit resolution');
82
- }
83
- const provenance = readBuildRecords(sourceRecord.workDir);
84
- fs.mkdirSync(staging, { mode: 0o700 });
85
- try {
86
- for (const component of COMPONENTS) {
87
- copyPrivateTree(source[component], staged(target[component]), ownership);
88
- if (component === 'mcp') continue;
89
- const marker = join(staged(target[component]), PROVENANCE_DIRECTORY);
90
- initializeBuildMarker(marker, provenance);
91
- }
92
- fs.writeFileSync(staged(target.config), configBytes, { mode: 0o600 });
93
- for (const consumer of CONSUMERS) {
94
- const destination = staged(target.credentials[consumer]);
95
- fs.mkdirSync(dirname(destination), { recursive: true, mode: 0o700 });
96
- fs.writeFileSync(destination, privateFile(source.credentials[consumer]), { mode: 0o600, flag: 'wx' });
97
- }
98
- scanSource(staging, ownership);
99
- return targetRecord;
100
- } catch (error) {
101
- fs.rmSync(staging, { recursive: true, force: true });
102
- throw error;
103
- }
104
- }
105
-
106
- /** Call only after archiving and validating the still-unmodified staged payload. */
107
- export function bindConvertedPackageState(targetRecord, staging) {
108
- validateInstallation(targetRecord, targetRecord.root);
109
- const { paths, staged } = conversionPaths(targetRecord, staging);
110
- const configPath = staged(paths.config);
111
- const config = readConfig(configPath);
112
- config.stateDir = paths.daemon;
113
- if (config.networkMcp) {
114
- config.networkMcp.applicationConfigPath = join(paths.mcp, 'config.json');
115
- config.networkMcp.profile.credentialPath = join(paths.daemon, 'daemon-token');
116
- writeConfig(join(staged(paths.mcp), 'profile.json'), config.networkMcp.profile);
117
- }
118
- writeConfig(configPath, config);
119
- const coworkPath = join(staged(paths.cowork), 'config.json');
120
- if (fs.existsSync(coworkPath)) {
121
- const cowork = readConfig(coworkPath);
122
- cowork.stateDir = paths.cowork;
123
- writeConfig(coworkPath, cowork);
124
- }
125
- }
126
-
127
- /** Prepare stopped source data; publication and service activation belong to the caller. */
128
- export async function prepareLegacyPackageState(sourceRecord, staging, backupPath) {
129
- validateInstallation(sourceRecord, sourceRecord.root);
130
- const backupParent = join(sourceRecord.root, 'storage', 'backups');
131
- if (dirname(backupPath) !== backupParent || resolve(backupPath) !== backupPath || fs.realpathSync(backupParent) !== backupParent) {
132
- throw new Error('Conversion backup must use the selected backup directory');
133
- }
134
- const targetRecord = await stageLegacyPackageState(sourceRecord, staging);
135
- try {
136
- const provenance = readBuildRecords(sourceRecord.workDir);
137
- // createArchive validates the complete archive before publishing it without replacement.
138
- // Keep original configuration bytes in the backup, then bind the deployment copy.
139
- await createArchive(staging, backupPath, {
140
- domain: 'server',
141
- uid: process.getuid(),
142
- gid: process.getgid(),
143
- provenance,
144
- });
145
- bindConvertedPackageState(targetRecord, staging);
146
- return targetRecord;
147
- } catch (error) {
148
- fs.rmSync(staging, { recursive: true, force: true });
149
- throw error;
150
- }
151
- }
152
-
153
- function pathExists(path) {
154
- try { fs.lstatSync(path); return true; }
155
- catch (error) { if (error.code === 'ENOENT') return false; throw error; }
156
- }
157
-
158
- function ensureConversionDirectory(path) {
159
- if (!pathExists(path)) fs.mkdirSync(path, { mode: 0o700 });
160
- const stat = fs.lstatSync(path);
161
- if (!stat.isDirectory() || stat.uid !== process.getuid() || stat.gid !== process.getgid()
162
- || (stat.mode & 0o7777) !== 0o700 || fs.realpathSync(path) !== path) {
163
- throw new Error(`Unsafe conversion directory: ${path}`);
164
- }
165
- }
166
-
167
- function removePrivateTree(path) {
168
- if (!pathExists(path)) return;
169
- scanSource(path, { uid: process.getuid(), gid: process.getgid() });
170
- fs.rmSync(path, { recursive: true });
171
- }
172
-
173
- export function validateConvertedPackageState(record, tree = installationPaths(record).state) {
174
- const paths = installationPaths(record);
175
- const physical = path => join(tree, relative(paths.state, path));
176
- scanSource(tree, { uid: process.getuid(), gid: process.getgid() });
177
- const records = readBuildRecords(record.workDir);
178
- const BUILD_RECORDS = recordNames(records);
179
- for (const component of SERVER_SERVICES) {
180
- const marker = join(physical(paths[component]), PROVENANCE_DIRECTORY);
181
- if (fs.readdirSync(marker).sort().join() !== [...BUILD_RECORDS].sort().join()) {
182
- throw new Error(`Incomplete converted ${component} provenance`);
183
- }
184
- for (const name of BUILD_RECORDS) {
185
- if (!privateFile(join(marker, name)).equals(records[name])) {
186
- throw new Error(`Converted ${component} differs from the selected build`);
187
- }
188
- }
189
- const configPath = join(physical(paths[component]), 'config.json');
190
- if (pathExists(configPath)) readConfig(configPath);
191
- }
192
- const daemon = readConfig(physical(paths.config));
193
- const profile = readConfig(join(physical(paths.mcp), 'profile.json'));
194
- if (daemon.stateDir !== paths.daemon || daemon.port !== record.port
195
- || daemon.networkMcp?.applicationConfigPath !== join(paths.mcp, 'config.json')
196
- || profile.expectedInstanceId !== record.instanceId
197
- || profile.credentialPath !== join(paths.daemon, 'daemon-token')
198
- || profile.endpoint !== `http://127.0.0.1:${record.port}`
199
- || JSON.stringify(daemon.networkMcp.profile) !== JSON.stringify(profile)) {
200
- throw new Error('Converted daemon/MCP deployment configuration is inconsistent');
201
- }
202
- if (pathExists(join(physical(paths.mcp), 'config.json'))) readConfig(join(physical(paths.mcp), 'config.json'));
203
- if (readConfig(join(physical(paths.cowork), 'config.json')).stateDir !== paths.cowork) {
204
- throw new Error('Converted Cowork configuration selects another state directory');
205
- }
206
- for (const credential of [profile.credentialPath, ...Object.values(paths.credentials)]) {
207
- if (!privateFile(physical(credential)).length) throw new Error('Converted managed credential is empty');
208
- }
209
- }
210
-
211
- /** The caller holds the installation lock. The record is the sole selection commit. */
212
- export async function convertPackageInstallation(record, operation, effects) {
213
- validateInstallation(record, record.root);
214
- if (record.mode !== 'packages' || (record.schema !== 1 && !record.layoutConversion)) {
215
- throw new Error('Select a legacy or pending package installation');
216
- }
217
- const selectionPath = join(record.root, 'installation.json');
218
- const writeSelection = value => effects.writeJson(selectionPath, JSON.stringify(value, null, 2) + '\n');
219
- const source = record.layoutConversion?.sourceRecord ?? record;
220
- const resumingPublished = record.schema === 2;
221
- const storage = join(record.root, 'storage');
222
- const maintenance = join(storage, '.maintenance');
223
- const backups = join(storage, 'backups');
224
- const targetState = join(storage, 'state');
225
- const staging = join(maintenance, 'layout-conversion');
226
-
227
- if (record.schema === 1) {
228
- if (readConfig(source.configPath).stateDir !== installationPaths(source).daemon) {
229
- throw new Error('Daemon authority source differs from the selected legacy state');
230
- }
231
- ensureConversionDirectory(record.root);
232
- for (const path of [storage, maintenance, backups]) ensureConversionDirectory(path);
233
- if (!record.layoutConversion && (pathExists(targetState) || pathExists(staging))) {
234
- throw new Error('Unowned conversion destination already exists');
235
- }
236
- await effects.prepareInstallation(source, { runtimeOnly: true });
237
- if (!record.layoutConversion) {
238
- const runningServices = await effects.serverLifecycle(source, 'status');
239
- record = {
240
- ...source,
241
- layoutConversion: {
242
- version: 1, sourceRecord: source, runningServices,
243
- backupPath: join(backups, `before-layout-2-${randomUUID()}`),
244
- },
245
- };
246
- writeSelection(record);
247
- }
248
- await effects.retireLegacyServices(source);
249
- await effects.prepareLegacyPackageSource(source);
250
- removePrivateTree(staging);
251
- try {
252
- const target = await stageLegacyPackageState(source, staging);
253
- const archiveOptions = {
254
- domain: 'server', uid: process.getuid(), gid: process.getgid(),
255
- provenance: readBuildRecords(source.workDir),
256
- };
257
- const backupPath = record.layoutConversion.backupPath;
258
- if (pathExists(backupPath)) await validateArchive(backupPath, archiveOptions);
259
- else await createArchive(staging, backupPath, archiveOptions);
260
- await effects.retainConvertedPackageAuthority(source, join(staging, 'daemon'));
261
- bindConvertedPackageState(target, staging);
262
- validateConvertedPackageState(target, staging);
263
- // A schema-1 pending record reserves this destination. Rebuild an interrupted
264
- // publication from the stopped source; never merge two copies of state.
265
- removePrivateTree(targetState);
266
- publishNoReplace(staging, targetState);
267
- record = { ...target, layoutConversion: record.layoutConversion };
268
- writeSelection(record);
269
- } finally {
270
- removePrivateTree(staging);
271
- }
272
- }
273
-
274
- const selected = ['install', 'start'].includes(operation)
275
- ? record.services : record.layoutConversion.runningServices;
276
- if (resumingPublished) {
277
- // A previous readiness failure can leave some new-layout services running.
278
- // Offline validation and residue preparation require stopping those writers.
279
- await effects.serverLifecycle(record, 'stop');
280
- await effects.prepareLegacyPackageSource(record);
281
- }
282
- validateConvertedPackageState(record);
283
- await effects.serverLifecycle(record, 'start', selected);
284
-
285
- // Selection is already committed: cleanup retries stay on the new state.
286
- const oldPaths = installationPaths(source);
287
- for (const component of COMPONENTS) removePrivateTree(oldPaths[component]);
288
- removePrivateTree(join(source.root, 'credentials'));
289
- if (pathExists(source.configPath)) {
290
- privateFile(source.configPath);
291
- fs.unlinkSync(source.configPath);
292
- }
293
- const finished = { ...record };
294
- delete finished.layoutConversion;
295
- writeSelection(finished);
296
- return finished;
297
- }
@@ -1,213 +0,0 @@
1
- /** Local-only migration: preserve opaque daemon state and retire its old launcher. */
2
- import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync } from 'node:fs';
3
- import { join, basename } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import { inspectLegacyState, stageLegacyState, withLegacyStateLock, ensureLegacyLockSupport } from './legacy-state.mjs';
6
- import { inspectManagedCli, installManagedCli } from './managed-cli.mjs';
7
- import { atomicWriteConfig } from './config.mjs';
8
- import { classifyUnit, unitPathForStateDir, validateInstallation } from './plan.mjs';
9
-
10
- const journalPath = root => join(root, 'legacy-migration.json');
11
- const parse = result => JSON.parse(result.stdout);
12
- const phases = ['prepared', 'stopped', 'copied', 'activating', 'verified', 'complete'];
13
- function readJournal(root) {
14
- const path = journalPath(root);
15
- if (!existsSync(path)) return null;
16
- const j = JSON.parse(readFileSync(path));
17
- if (j.schema !== 1 || j.targetRoot !== root || !phases.includes(j.phase) || !Array.isArray(j.identities)) throw new Error('Invalid legacy migration journal');
18
- return j;
19
- }
20
- // Legacy cutover publishes a Docker/package launcher; Podman cutover is not supported.
21
- function rejectPodmanMigration(options, effects, ...records) {
22
- if (options.containerEngine === 'podman' || records.some(record => record?.containerEngine === 'podman')
23
- || effects.readJson(join(options.stateDir, 'installation.json'))?.containerEngine === 'podman') {
24
- throw new Error('Legacy migration to Podman is not supported. Use a fresh Podman installation or migrate with Docker/packages.');
25
- }
26
- }
27
- function selection(source) {
28
- return { env: { OURS_CONFIG: source.configPath, OURS_STATE_DIR: source.stateDir, OURS_PORT: String(source.config.port ?? 3050), OURS_API_TOKEN: undefined, OURS_DAEMON_ID: undefined, OURS_DAEMON_URL: undefined, OURS_DAEMON_CREDENTIAL_PATH: undefined }, sensitive: true };
29
- }
30
- async function oldCommand(effects, source, args, options = {}) {
31
- return effects.run(source.originalProgram ?? 'ours', [...args, '--config', source.configPath, '--state-dir', source.stateDir, '--json'], { ...selection(source), ...options });
32
- }
33
- function validateIdentities(rows, source) {
34
- if (!Array.isArray(rows) || !rows.length || rows.some(r => !['root', 'role'].includes(r.kind) || typeof r.cid !== 'string' || !r.cid || typeof r.name !== 'string')) throw new Error('Legacy identities are not fully restored; migration requires a healthy source daemon');
35
- const roots = rows.filter(r => r.kind === 'root');
36
- if (roots.length !== 1 || roots[0].name !== source.rootName) throw new Error('Legacy Human identity does not match its stored root');
37
- return rows.map(({ name, kind, cid }) => ({ name, kind, cid })).sort((a,b) => a.name.localeCompare(b.name));
38
- }
39
-
40
- export async function inspectLegacyMigration(options, effects, deps = {}) {
41
- const journal = readJournal(options.stateDir);
42
- rejectPodmanMigration(options, effects, journal?.record, options.legacyPlan?.journal?.record);
43
- const inspect = deps.inspectLegacyState ?? inspectLegacyState;
44
- await (deps.ensureLegacyLockSupport ?? ensureLegacyLockSupport)();
45
- const cliPlan = options.dryRun ? null : await (deps.inspectManagedCli ?? inspectManagedCli)(effects, options.stateDir);
46
- if (journal) {
47
- if (journal.sourceConfig !== options.migrateFrom) throw new Error('Another legacy source is already selected for this target');
48
- return { journal, cliPlan, source: journal.phase === 'complete' ? null : { ...inspect(options.migrateFrom, options.stateDir), originalProgram: cliPlan?.originalProgram } };
49
- }
50
- const source = { ...inspect(options.migrateFrom, options.stateDir), originalProgram: cliPlan?.originalProgram };
51
- if (options.mode === 'docker' && options.stateDir.includes(':')) throw new Error('Docker migration requires an installation path without colon characters');
52
- if (effects.readJson(join(options.stateDir, 'installation.json'))) throw new Error('Legacy migration requires a new managed installation root');
53
- if (existsSync(options.stateDir) && readdirSync(options.stateDir).length) throw new Error('Legacy migration target must be empty');
54
- if (options.dryRun) return { source, journal: { schema: 1, sourceConfig: source.configPath, sourceStateDir: source.stateDir, targetRoot: options.stateDir, phase: 'prepared', identities: [], service: null } };
55
- // The owning CLI verifies endpoint, process and state directory. No PID guessing.
56
- const status = parse(await oldCommand(effects, source, ['daemon', 'status']));
57
- if (status.state !== 'running' || status.stateDir !== source.stateDir) throw new Error('Start the legacy daemon before migration so its identities can be verified');
58
- const identities = validateIdentities(parse(await oldCommand(effects, source, ['identity', 'list'])), source);
59
- const service = parse(await oldCommand(effects, source, ['daemon', 'uninstall-service', '--dry-run']));
60
- if (service.conflict) {
61
- const legacy = effects.platform?.platform === 'linux' && source.stateDir === join(effects.home, '.ours')
62
- ? unitPathForStateDir(source.stateDir, effects.home) : null;
63
- if (!legacy?.ok || legacy.path !== service.serviceFile || classifyUnit(effects.readText(legacy.path)).kind !== 'legacy') {
64
- throw new Error('Legacy boot service ownership could not be verified: ' + service.conflict.message);
65
- }
66
- service.legacyUnit = legacy.unit;
67
- }
68
- return { source, cliPlan, journal: { schema: 1, sourceConfig: source.configPath, sourceStateDir: source.stateDir, targetRoot: options.stateDir,
69
- phase: 'prepared', identities, service, sourcePort: source.config.port ?? 3050 } };
70
- }
71
-
72
- export async function prepareMigrationCliRuntime(record, effects) {
73
- const root = join(record.root, 'launcher-runtime');
74
- const entry = join(root, 'node_modules', '@ours.network', 'install', 'install.mjs');
75
- const ready = join(root, '.ready');
76
- if (existsSync(ready) && existsSync(entry)) return entry;
77
- mkdirSync(root, { recursive: true, mode: 0o700 });
78
- effects.out('Preparing permanent management commands so ours will keep working after this installer exits.');
79
- const packageRoot = fileURLToPath(new URL('..', import.meta.url));
80
- const packed = parse(await effects.run('npm', ['pack', packageRoot, '--ignore-scripts', '--pack-destination', root, '--json']));
81
- if (!Array.isArray(packed) || packed.length !== 1 || typeof packed[0].filename !== 'string' || basename(packed[0].filename) !== packed[0].filename) throw new Error('Cannot prepare the persistent installer package');
82
- await effects.run('npm', ['install', '--prefix', root, '--prefer-offline', '--ignore-scripts', '--no-audit', '--no-fund', join(root, packed[0].filename)], { stream: true });
83
- if (!existsSync(entry)) throw new Error('Persistent installer entry is missing');
84
- await effects.run(process.execPath, [entry, '--help']);
85
- atomicWriteConfig(ready, 'ready\n');
86
- return entry;
87
- }
88
-
89
- /** Called under the normal installation lock; retries never overwrite imported state. */
90
- export async function executeLegacyMigration(args, effects, install, deps = {}) {
91
- const retainedJournal = readJournal(args.stateDir);
92
- rejectPodmanMigration(args, effects, retainedJournal?.record, args.legacyPlan?.journal?.record);
93
- const stage = deps.stageLegacyState ?? stageLegacyState;
94
- const lock = deps.withLegacyStateLock ?? withLegacyStateLock;
95
- const save = (root, value) => (deps.atomicWriteConfig ?? atomicWriteConfig)(journalPath(root), JSON.stringify(value, null, 2) + '\n');
96
- const prepareCli = deps.prepareMigrationCliRuntime ?? prepareMigrationCliRuntime;
97
- const inspected = args.legacyPlan ?? await inspectLegacyMigration(args, effects, deps);
98
- let journal = retainedJournal ?? inspected.journal;
99
- rejectPodmanMigration(args, effects, journal?.record);
100
- if (journal.phase === 'complete') {
101
- const retained = effects.readJson(join(args.stateDir, 'installation.json'));
102
- inspected.cliPlan.installerPath = await prepareCli(retained, effects);
103
- await (deps.installManagedCli ?? installManagedCli)(retained, inspected.cliPlan, effects);
104
- const rows = validateIdentities(parse(await effects.run('ours', ['identity', 'list', '--json'])), { rootName: journal.identities.find(row => row.kind === 'root')?.name });
105
- if (JSON.stringify(rows) !== JSON.stringify(journal.identities)) throw new Error('Completed migration identity verification failed; no replacement Human was created');
106
- effects.out('Legacy migration already completed; retained identities verified.');
107
- return 0;
108
- }
109
- const source = inspected.source;
110
- let record;
111
- let sourceLock;
112
- let activationAttempted = phases.indexOf(journal.phase) >= phases.indexOf('activating');
113
- const wrapped = { ...effects,
114
- newInstallation(root, mode) {
115
- if (journal.record) {
116
- if (journal.record.root !== root || journal.record.mode !== mode) throw new Error('Migration target selection changed');
117
- return validateInstallation(journal.record, root);
118
- }
119
- return effects.newInstallation(root, mode);
120
- },
121
- async initializeSelection(selected, manifest) {
122
- record = selected;
123
- selected.legacyMigrationSource = args.migrateFrom;
124
- journal.record = selected;
125
- journal.sourcePolicy = args.sourcePolicy;
126
- journal.sourceManifest = manifest;
127
- save(selected.root, journal);
128
- effects.writeJson(join(selected.root, 'installation.json'), JSON.stringify(selected, null, 2) + '\n');
129
- await effects.initializeSelection(selected, manifest, { retainConfig: true });
130
- },
131
- async serverPreflight(selected, operation, options) {
132
- if (journal.record && !existsSync(selected.sourcesPath)) {
133
- if (!journal.sourceManifest) throw new Error('Migration journal lacks its retained package selection');
134
- await effects.initializeSelection(selected, journal.sourceManifest, { retainConfig: true });
135
- }
136
- return effects.serverPreflight(selected, operation, options);
137
- },
138
- async prepareInstallation(selected) {
139
- record = selected;
140
- if (!existsSync(selected.sourcesPath)) {
141
- const manifest = journal.sourceManifest ?? await effects.resolveSourcePolicy(args.sourcePolicy, 'server');
142
- await effects.initializeSelection(selected, manifest, { retainConfig: true });
143
- }
144
- await effects.prepareInstallation(selected, { runtimeOnly: true });
145
- if (selected.mode === 'docker') await effects.prepareLegacyDockerImport(selected);
146
- inspected.cliPlan.installerPath = await prepareCli(selected, effects);
147
- journal.cliInstallerPath = inspected.cliPlan.installerPath;
148
- if (activationAttempted) await effects.serverLifecycle(selected, 'stop');
149
- // Backups contain secrets; the enclosing installation is private.
150
- const backup = join(selected.root, 'legacy-backup');
151
- mkdirSync(backup, { mode: 0o700, recursive: true });
152
- const configBackup = join(backup, 'config.json');
153
- if (!existsSync(configBackup)) writeFileSync(configBackup, readFileSync(source.configPath), { flag: 'wx', mode: 0o600 });
154
- if (journal.service.serviceFile && existsSync(journal.service.serviceFile) && !existsSync(join(backup, 'service'))) {
155
- writeFileSync(join(backup, 'service'), readFileSync(journal.service.serviceFile), { flag: 'wx', mode: 0o600 });
156
- }
157
- save(selected.root, journal);
158
- if (!activationAttempted) {
159
- effects.out('Migration: retire the old boot service and stop its daemon.');
160
- if (journal.service.legacyUnit) await effects.run('systemctl', ['--user', 'disable', '--now', journal.service.legacyUnit]);
161
- else await oldCommand(effects, source, ['daemon', 'uninstall-service', '--yes']);
162
- await oldCommand(effects, source, ['daemon', 'stop']);
163
- journal.phase = 'stopped'; save(selected.root, journal);
164
- }
165
- // Hold the SDK-compatible owner lock until activation finishes, including failures.
166
- sourceLock = await lock(source.stateDir);
167
- effects.out('Migration: copy retained identities, keys, history and session state.');
168
- stage(source, selected);
169
- if (selected.mode === 'docker') await effects.importLegacyDockerState(selected);
170
- if (!activationAttempted) { journal.phase = 'copied'; save(selected.root, journal); }
171
- await effects.prepareInstallation(selected);
172
- },
173
- async serverLifecycle(selected, operation, services) {
174
- if (operation === 'start') {
175
- activationAttempted = true;
176
- journal.phase = 'activating'; save(selected.root, journal);
177
- }
178
- return effects.serverLifecycle(selected, operation, services);
179
- },
180
- async serverEnsureIdentity(selected) {
181
- const rows = await effects.serverListIdentities(selected);
182
- const actual = validateIdentities(rows, source);
183
- if (JSON.stringify(actual) !== JSON.stringify(journal.identities)) throw new Error('Migrated identities differ from the source; no replacement Human was created');
184
- journal.phase = 'verified'; save(selected.root, journal);
185
- const root = actual.find(r => r.kind === 'root');
186
- return { ...root, created: false };
187
- },
188
- };
189
- try {
190
- const result = await install({ ...args, migrate: true }, wrapped);
191
- if (result !== 0) throw new Error('Migrated server setup did not complete');
192
- // Publish an explicit host profile; a daemon --config file is not a client profile.
193
- const directory = join(record.root, 'legacy-client');
194
- mkdirSync(directory, { recursive: true, mode: 0o700 });
195
- const credentialPath = join(directory, 'credential');
196
- if (!existsSync(credentialPath)) await effects.serverAccess(record, 'access-issue', { output: credentialPath });
197
- const profile = { endpoint: `http://127.0.0.1:${record.port}`, expectedInstanceId: record.instanceId, credentialPath };
198
- atomicWriteConfig(join(directory, 'profile.json'), JSON.stringify(profile, null, 2) + '\n');
199
- await (deps.installManagedCli ?? installManagedCli)(record, inspected.cliPlan, effects);
200
- const defaultRows = validateIdentities(parse(await effects.run('ours', ['identity', 'list', '--json'])), source);
201
- if (JSON.stringify(defaultRows) !== JSON.stringify(journal.identities)) throw new Error('Default ours command does not select the migrated identities');
202
- journal.phase = 'complete'; save(record.root, journal);
203
- effects.out(`Migration complete. Original state remains at ${source.stateDir}; original config/service are backed up in ${join(record.root, 'legacy-backup')}. Do not start the original state alongside the migrated daemon.`);
204
- return 0;
205
- } catch (error) {
206
- if (record && activationAttempted) {
207
- try { await effects.serverLifecycle(record, 'stop'); }
208
- catch { throw new Error(`Migration activation failed and destination shutdown could not be confirmed. Keep the source stopped; repair this same target. ${error.message}`); }
209
- throw new Error(`Migration paused after activation; source remains stopped to avoid diverging identity sessions. Repeat the same migration command to repair the retained target. ${error.message}`);
210
- }
211
- throw new Error(`Migration paused before activation; source data is retained. Repeat the same migration command. ${error.message}`);
212
- } finally { await sourceLock?.close(); }
213
- }