@tnunamak/dalan 0.6.0 → 0.6.2

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.
@@ -0,0 +1,393 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { randomUUID, createHash } from 'node:crypto';
5
+ import { defaultPath } from './paths.mjs';
6
+ import { acquireUpdateLock } from './service-update-lock.mjs';
7
+ import { writeAtomic } from './as-files.mjs';
8
+ import { latestRelease as defaultLatest, installRelease as defaultInstall, probeService as defaultProbe, probeCandidate as defaultCandidate, controlService as defaultControl } from './service-update-runtime.mjs';
9
+
10
+ const PACKAGE = '@tnunamak/dalan';
11
+ const HEALTH_TIMEOUT_MS = 30_000;
12
+ const fail = message => { throw new Error(message); };
13
+ const privateDir = dir => fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
14
+ function readReceipt(home) {
15
+ const file = path.join(defaultPath(home, '.config/dot-bridge'), 'service-install.json');
16
+ let st, value;
17
+ try { st = fs.lstatSync(file); value = JSON.parse(fs.readFileSync(file, 'utf8')); }
18
+ catch { fail(`service receipt is missing or invalid: ${file}`); }
19
+ if (!st.isFile() || st.isSymbolicLink() || (st.mode & 0o777) !== 0o600) fail(`${file} must be a private regular file`);
20
+ if (!value || value.schema_version !== 1 || value.home !== home || !value.unit) fail(`${file} has an unsupported service receipt`);
21
+ return { file, value };
22
+ }
23
+ function canonical(x) {
24
+ if (Array.isArray(x)) return `[${x.map(canonical).join(',')}]`;
25
+ if (x && typeof x === 'object') return `{${Object.keys(x).sort().map(k => `${JSON.stringify(k)}:${canonical(x[k])}`).join(',')}}`;
26
+ return JSON.stringify(x);
27
+ }
28
+ function canonicalCatalogs(catalogs) {
29
+ return canonical(Object.fromEntries(Object.keys(catalogs ?? {}).sort().map(worker => [worker,
30
+ [...(catalogs[worker] ?? [])].sort((a, b) => String(a?.name).localeCompare(String(b?.name)))])));
31
+ }
32
+ function configurationDigest(home, receipt) {
33
+ const root = defaultPath(home, '.config/dot-bridge');
34
+ const hash = createHash('sha256');
35
+ hash.update(canonical({ enable_workspace: !!receipt.enable_workspace, enable_t3: !!receipt.enable_t3 }));
36
+ for (const name of ['workers.json', 'workers-repos.json', 'as.json', 'as-jwks.json', 'as-cookie-keys.json', 'as-storage.key', 'operator.key', 'env']) {
37
+ const file = path.join(root, name);
38
+ let st;
39
+ try { st = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') { hash.update(`missing:${name}`); continue; } throw error; }
40
+ if (!st.isFile() || st.isSymbolicLink()) fail(`configuration input must be a regular file: ${file}`);
41
+ hash.update(`file:${name}:${st.mode & 0o777}:`); hash.update(fs.readFileSync(file));
42
+ }
43
+ return hash.digest('hex');
44
+ }
45
+ function completeCatalogs(a, b, workers) {
46
+ if (!a?.catalogs || !b?.catalogs) return false;
47
+ const keysA = Object.keys(a.catalogs).sort(), keysB = Object.keys(b.catalogs).sort();
48
+ if (canonical(keysA) !== canonical(keysB) || canonical(keysA) !== canonical([...workers].sort())) return false;
49
+ return true;
50
+ }
51
+ function catalogsEqual(a, b, workers) {
52
+ return completeCatalogs(a, b, workers) && canonicalCatalogs(a.catalogs) === canonicalCatalogs(b.catalogs);
53
+ }
54
+ function releaseVersion(r, current) {
55
+ if (!r || r.name !== PACKAGE || typeof r.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(r.version) || typeof r.dist?.integrity !== 'string' || !r.dist.integrity.startsWith('sha512-')) fail('registry returned invalid stable release metadata');
56
+ const parts = s => s.split('.').map(Number), a = parts(r.version), b = parts(current);
57
+ if (!/^\d+\.\d+\.\d+$/.test(current) || a.some(n => !Number.isSafeInteger(n))) fail('installed service version is not a stable semantic version');
58
+ return a[0] > b[0] || a[0] === b[0] && (a[1] > b[1] || a[1] === b[1] && a[2] > b[2]);
59
+ }
60
+ function atomic(file, text) {
61
+ privateDir(path.dirname(file)); writeAtomic(file, text);
62
+ }
63
+ const failedFile = home => path.join(home, 'update-failed.json');
64
+ function readFailed(home) {
65
+ try {
66
+ const v = JSON.parse(fs.readFileSync(failedFile(home), 'utf8'));
67
+ return typeof v?.version === 'string' && typeof v.integrity === 'string' ? v : null;
68
+ } catch { return null; }
69
+ }
70
+ function copyTree(src, dst) {
71
+ const st = fs.lstatSync(src);
72
+ if (st.isSymbolicLink()) { fs.symlinkSync(fs.readlinkSync(src), dst); return; }
73
+ if (!st.isDirectory() && !st.isFile()) return;
74
+ if (st.isDirectory()) {
75
+ fs.mkdirSync(dst, { recursive: true, mode: st.mode & 0o777 });
76
+ for (const name of fs.readdirSync(src)) copyTree(path.join(src, name), path.join(dst, name));
77
+ fs.chmodSync(dst, st.mode & 0o777);
78
+ } else { fs.copyFileSync(src, dst); fs.chmodSync(dst, st.mode & 0o777); }
79
+ }
80
+ function replaceTree(src, dst) {
81
+ fs.rmSync(dst, { recursive: true, force: true });
82
+ if (fs.existsSync(src)) copyTree(src, dst);
83
+ }
84
+ function snapshot(home, txn) {
85
+ const target = path.join(txn, 'snapshot.pending'); fs.rmSync(target, { recursive: true, force: true }); privateDir(target);
86
+ const roots = {};
87
+ for (const item of ['.config', '.local']) {
88
+ const src = path.join(home, item);
89
+ if (fs.existsSync(src)) {
90
+ const st = fs.lstatSync(src);
91
+ if (!st.isDirectory() || st.isSymbolicLink()) fail(`cannot snapshot non-directory service state: ${src}`);
92
+ roots[item] = true; copyTree(src, path.join(target, item));
93
+ } else roots[item] = false;
94
+ }
95
+ atomic(path.join(target, '.snapshot-complete.json'), JSON.stringify({ complete: true, roots }));
96
+ const ready = path.join(txn, 'snapshot'); fs.rmSync(ready, { recursive: true, force: true }); fs.renameSync(target, ready); return ready;
97
+ }
98
+ function validateSnapshot(tx) {
99
+ const root = tx.snapshot;
100
+ let marker;
101
+ try {
102
+ const st = fs.lstatSync(root);
103
+ if (!st.isDirectory() || st.isSymbolicLink()) fail('transaction snapshot is not a real directory');
104
+ marker = JSON.parse(fs.readFileSync(path.join(root, '.snapshot-complete.json'), 'utf8'));
105
+ } catch { fail('transaction snapshot is missing or incomplete; refusing to restore service state'); }
106
+ if (marker.complete !== true || !marker.roots || typeof marker.roots['.config'] !== 'boolean' || typeof marker.roots['.local'] !== 'boolean') fail('transaction snapshot completion marker is invalid');
107
+ for (const item of ['.config', '.local']) {
108
+ const file = path.join(root, item), exists = fs.existsSync(file);
109
+ if (exists !== marker.roots[item]) fail(`transaction snapshot is incomplete for ${item}; refusing to restore service state`);
110
+ if (exists) { const st = fs.lstatSync(file); if (!st.isDirectory() || st.isSymbolicLink()) fail(`transaction snapshot is invalid for ${item}`); }
111
+ }
112
+ }
113
+ function unitPath(receipt, home) {
114
+ if (!/^[A-Za-z0-9_.@-]+$/.test(String(receipt.unit ?? ''))) fail('invalid service unit name in receipt');
115
+ const xdg = process.env.XDG_CONFIG_HOME;
116
+ const dir = receipt.unit_dir || path.join(xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), '.config'), 'systemd/user');
117
+ if (!path.isAbsolute(dir) || dir.includes('\n')) fail('invalid service unit directory in receipt');
118
+ const name = String(receipt.unit).endsWith('.service') ? String(receipt.unit) : `${receipt.unit}.service`;
119
+ return path.join(dir, name);
120
+ }
121
+ // A 0.6.0 or 0.6.1 receipt names no package, node binary or unit directory. Read them from the unit that runs the service,
122
+ // so the first update adopts the install with no hand step and keeps the node binary the service already uses.
123
+ function adoptInstall(receipt, home) {
124
+ if (receipt.repo && receipt.node && receipt.unit_dir) return receipt;
125
+ const file = unitPath(receipt, home);
126
+ let text;
127
+ try { const st = fs.lstatSync(file); if (!st.isFile() || st.isSymbolicLink()) fail('not a regular file'); text = fs.readFileSync(file, 'utf8'); }
128
+ catch { fail(`cannot read the service unit to adopt this install: ${file}`); }
129
+ const repo = text.match(/^WorkingDirectory=(.+)$/m)?.[1], exec = text.match(/^ExecStart=(\S+) (\S+)$/m);
130
+ if (!repo || !exec || exec[2] !== `${repo}/src/server.mjs` || !path.isAbsolute(repo) || !path.isAbsolute(exec[1])) fail(`service unit does not contain a supported Dalan command: ${file}`);
131
+ return { ...receipt, repo: receipt.repo ?? repo, node: receipt.node ?? exec[1], unit_dir: receipt.unit_dir ?? path.dirname(file) };
132
+ }
133
+ function rewriteUnit(file, current, home) {
134
+ if (!fs.existsSync(file)) fail(`service unit is missing: ${file}`);
135
+ const st = fs.lstatSync(file);
136
+ if (!st.isFile() || st.isSymbolicLink()) fail(`service unit must be a regular file: ${file}`);
137
+ const before = fs.readFileSync(file, 'utf8');
138
+ const oldRepo = before.match(/^WorkingDirectory=(.+)$/m)?.[1];
139
+ const exec = before.match(/^ExecStart=(.+)$/m)?.[1];
140
+ if (!oldRepo || !exec || !exec.endsWith('/src/server.mjs')) fail(`service unit does not contain a supported Dalan command: ${file}`);
141
+ const after = before.split('\n').map(line => /^WorkingDirectory=/.test(line) ? `WorkingDirectory=${current}` : /^ExecStart=/.test(line) ? line.replace(/\/src\/server\.mjs(?:\s.*)?$/, `${path.sep}src${path.sep}server.mjs`) : line).join('\n');
142
+ // Preserve the selected package in ExecStart, including its node executable prefix.
143
+ const fixed = after.replaceAll(`${oldRepo}/src/server.mjs`, `${current}/src/server.mjs`);
144
+ const lines = fixed.split('\n').filter(l => !/^ExecStartPre=.*\sservice recover\s/.test(l));
145
+ const i = lines.findIndex(l => /^ExecStart=/.test(l));
146
+ const execLine = lines[i].slice('ExecStart='.length), nodeBin = execLine.slice(0, execLine.indexOf(' '));
147
+ lines.splice(i + 1, 0, `ExecStartPre=${nodeBin} ${current}/bin/dalan.mjs service recover --home ${home} --quiet`);
148
+ atomic(file, lines.join('\n')); fs.chmodSync(file, st.mode & 0o777); return before;
149
+ }
150
+ function select(home, repo) {
151
+ const current = path.join(home, 'current'), tmp = path.join(home, `.current-${randomUUID()}`);
152
+ fs.symlinkSync(path.relative(home, repo), tmp); fs.renameSync(tmp, current);
153
+ }
154
+ function prune(home, active, previous) {
155
+ const root = path.join(home, 'versions'); if (!fs.existsSync(root)) return;
156
+ const dirs = fs.readdirSync(root, { withFileTypes: true }).filter(d => d.isDirectory() && !d.isSymbolicLink()).map(d => d.name).sort((a,b) => b.localeCompare(a, undefined, { numeric: true }));
157
+ const keep = new Set([active, previous]);
158
+ for (const name of dirs) { if (keep.size >= 3) break; keep.add(name); }
159
+ for (const name of dirs) if (!keep.has(name)) fs.rmSync(path.join(root, name), { recursive: true, force: true });
160
+ }
161
+ async function probeReady(probe, home, receipt, healthTimeoutMs = HEALTH_TIMEOUT_MS) {
162
+ const deadline = performance.now() + healthTimeoutMs;
163
+ let error;
164
+ while (performance.now() < deadline) {
165
+ const remaining = deadline - performance.now();
166
+ try { return await probe(home, receipt, { timeout: Math.max(1, Math.min(remaining, 1000)) }); }
167
+ catch (e) {
168
+ error = e;
169
+ const delay = Math.min(150, Math.max(0, deadline - performance.now()));
170
+ if (delay) await new Promise(resolve => setTimeout(resolve, delay));
171
+ }
172
+ }
173
+ throw new Error(`service health check timed out after ${healthTimeoutMs}ms${error ? `: ${error.message}` : ''}`);
174
+ }
175
+ function readJournal(home) {
176
+ const file = path.join(home, 'update-transaction.json');
177
+ let txStat;
178
+ try { txStat = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
179
+ if (!txStat.isFile() || txStat.isSymbolicLink() || (txStat.mode & 0o777) !== 0o600) fail('update transaction must be a private regular file');
180
+ let tx;
181
+ try { tx = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { fail('update transaction is invalid JSON'); }
182
+ const oldReceipt = tx?.oldReceipt;
183
+ if (tx.home !== home || !oldReceipt || oldReceipt.home !== home || oldReceipt.schema_version !== 1 || !oldReceipt.unit ||
184
+ !tx.oldRepo || !tx.oldVersion || !tx.snapshot || !['prepared', 'switched', 'committed'].includes(tx.phase)) fail('invalid interrupted update transaction');
185
+ if (tx.unitFile !== (oldReceipt.unit ? unitPath(oldReceipt, home) : null) || !tx.oldCatalogs || typeof tx.oldCatalogs !== 'object') fail('update transaction control data is invalid');
186
+ if (path.resolve(tx.snapshot) !== path.join(home, 'update-backup', 'snapshot')) fail('update transaction snapshot path is invalid');
187
+ return { file, tx };
188
+ }
189
+ // Put the old package, unit and saved state back on disk. Touches no service and probes nothing.
190
+ function restoreFiles(home, tx) {
191
+ validateSnapshot(tx);
192
+ select(home, tx.oldRepo);
193
+ if (tx.unitFile && tx.oldUnit != null) atomic(tx.unitFile, tx.oldUnit);
194
+ for (const item of ['.config', '.local']) replaceTree(path.join(tx.snapshot, item), path.join(home, item));
195
+ }
196
+ function discardJournal(home, tx) {
197
+ fs.rmSync(path.join(home, 'update-transaction.json'), { force: true });
198
+ fs.rmSync(path.dirname(tx.snapshot), { recursive: true, force: true });
199
+ }
200
+ function restoreFromJournal(home, tx) {
201
+ if (tx.phase === 'committed') {
202
+ fs.rmSync(path.join(home, 'update-transaction.json'), { force: true });
203
+ try { fs.rmSync(path.dirname(tx.snapshot), { recursive: true, force: true }); } catch { /* committed service stays selected */ }
204
+ return;
205
+ }
206
+ if (tx.phase === 'switched') restoreFiles(home, tx);
207
+ discardJournal(home, tx);
208
+ }
209
+ // Run at service start (ExecStartPre): finish filesystem recovery without touching systemd.
210
+ export function recoverService({ home }) {
211
+ home = path.resolve(home ?? fail('home is required'));
212
+ if (!fs.existsSync(path.join(home, 'update-transaction.json'))) return { outcome: 'nothing_pending' };
213
+ let release;
214
+ try { release = acquireUpdateLock(home); }
215
+ catch (error) { if (/already running/.test(error.message)) return { outcome: 'update_running' }; throw error; }
216
+ try {
217
+ const journal = readJournal(home);
218
+ if (!journal) return { outcome: 'nothing_pending' };
219
+ restoreFromJournal(home, journal.tx);
220
+ return { outcome: 'recovered' };
221
+ } finally { release(); }
222
+ }
223
+ async function recover(home, control, probe, healthTimeoutMs) {
224
+ const journal = readJournal(home);
225
+ if (!journal) return;
226
+ const { tx } = journal, oldReceipt = tx.oldReceipt;
227
+ if (tx.phase === 'committed') return restoreFromJournal(home, tx);
228
+ if (tx.phase === 'prepared') {
229
+ await control(oldReceipt, 'restart');
230
+ const live = await probeReady(probe, home, { ...oldReceipt, repo: tx.oldRepo }, healthTimeoutMs);
231
+ if (live.version !== tx.oldVersion || tx.oldCatalogs && !catalogsEqual({ catalogs: tx.oldCatalogs }, live, Object.keys(tx.oldCatalogs))) fail('interrupted update recovery could not verify old service');
232
+ } else {
233
+ validateSnapshot(tx);
234
+ await control(oldReceipt, 'stop'); restoreFiles(home, tx);
235
+ await control(oldReceipt, 'daemon-reload'); await control(oldReceipt, 'restart');
236
+ const live = await probeReady(probe, home, { ...oldReceipt, repo: tx.oldRepo }, healthTimeoutMs);
237
+ if (tx.oldCatalogs && (live.version !== tx.oldVersion || !catalogsEqual({ catalogs: tx.oldCatalogs }, live, Object.keys(tx.oldCatalogs)))) fail('interrupted update recovery restored selection but old service health failed');
238
+ }
239
+ discardJournal(home, tx);
240
+ }
241
+ function actualWorkers(home) {
242
+ const file = path.join(defaultPath(home, '.config/dot-bridge'), 'workers.json');
243
+ let value;
244
+ try { value = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { fail(`cannot read configured workers: ${file}`); }
245
+ const workers = Object.keys(value?.workers ?? {}).sort();
246
+ if (!workers.length) fail('configured worker set is empty');
247
+ return workers;
248
+ }
249
+ export async function updateService({ home, check = false, yes = false, retry = false }, seams = {}) {
250
+ if (check && retry) fail('--retry cannot be used with --check');
251
+ home = path.resolve(home ?? fail('home is required'));
252
+ const latest = seams.latestRelease ?? defaultLatest, install = seams.installRelease ?? defaultInstall;
253
+ const probe = seams.probeService ?? defaultProbe, candidateProbe = seams.probeCandidate ?? defaultCandidate;
254
+ const control = seams.controlService ?? defaultControl, pruneVersions = seams.pruneVersions ?? prune;
255
+ const healthTimeoutMs = seams.healthTimeoutMs ?? HEALTH_TIMEOUT_MS;
256
+ if (!Number.isFinite(healthTimeoutMs) || healthTimeoutMs <= 0) fail('healthTimeoutMs must be a positive finite duration');
257
+ if (check) {
258
+ const receipt = adoptInstall(readReceipt(home).value, home), active = fs.existsSync(path.join(home, 'current')) ? fs.realpathSync(path.join(home, 'current')) : receipt.repo;
259
+ if (!active) fail('current service repository is missing');
260
+ const current = JSON.parse(fs.readFileSync(path.join(active, 'package.json'), 'utf8')).version;
261
+ const r = await latest(receipt); const forward = releaseVersion(r, current);
262
+ const result = { outcome: forward ? 'update_available' : 'up_to_date', current_version: current, latest_version: r.version };
263
+ if (!forward) result.outcome = 'up_to_date';
264
+ atomic(path.join(home, 'update-result.json'), JSON.stringify({ ...result, timestamp: new Date().toISOString() })); return result;
265
+ }
266
+ privateDir(home);
267
+ const releaseLock = acquireUpdateLock(home);
268
+ const resultFile = path.join(home, 'update-result.json');
269
+ let result, attempted;
270
+ try {
271
+ await recover(home, control, probe, healthTimeoutMs);
272
+ const { value: storedReceipt, file: receiptFile } = readReceipt(home);
273
+ const receipt = adoptInstall(storedReceipt, home);
274
+ let current = path.join(home, 'current');
275
+ let oldRepo = fs.existsSync(current) ? fs.realpathSync(current) : receipt.repo;
276
+ if (!oldRepo || !fs.existsSync(oldRepo)) fail('current service repository is missing');
277
+ const oldVersion = JSON.parse(fs.readFileSync(path.join(oldRepo, 'package.json'), 'utf8')).version;
278
+ const workers = actualWorkers(home);
279
+ const r = await latest(receipt), forward = releaseVersion(r, oldVersion);
280
+ if (!forward) { result = { outcome: 'up_to_date', current_version: oldVersion, latest_version: r.version }; return result; }
281
+ const failed = readFailed(home);
282
+ if (!retry && failed && failed.version === r.version && failed.integrity === r.dist.integrity) {
283
+ result = { outcome: 'skipped_failed_release', current_version: oldVersion, latest_version: r.version, failed_version: failed.version, message: `Release ${r.version} was rolled back earlier; not retrying automatically. Run dalan service update --retry to try it again.` };
284
+ return result;
285
+ }
286
+ attempted = r;
287
+ const installed = await install(home, r);
288
+ const candidate = path.resolve(installed), versions = path.resolve(home, 'versions');
289
+ if (candidate !== path.join(versions, r.version, 'node_modules', '@tnunamak', 'dalan') || !candidate.startsWith(`${versions}${path.sep}`) || fs.realpathSync(candidate) !== candidate) fail('candidate repository does not match exact package version path');
290
+ const packageInfo = JSON.parse(fs.readFileSync(path.join(candidate, 'package.json'), 'utf8'));
291
+ if (packageInfo.name !== PACKAGE || packageInfo.version !== r.version) fail('installed candidate package identity does not match registry release');
292
+ const base = await probe(home, receipt);
293
+ const configBeforeCandidate = configurationDigest(home, receipt);
294
+ const tested = await candidateProbe(home, receipt, candidate);
295
+ if (configurationDigest(home, receipt) !== configBeforeCandidate) fail('service configuration changed during candidate self-check; retry update');
296
+ if (base.version !== oldVersion || tested.version !== r.version) fail('service probe returned an unexpected package version');
297
+ if (!completeCatalogs(base, tested, workers)) fail('candidate self-check failed or worker catalogs are incomplete');
298
+ const changedCatalog = !catalogsEqual(base, tested, workers);
299
+ if (changedCatalog && !yes) {
300
+ result = { outcome: 'connector_refresh_required', current_version: oldVersion, candidate_version: r.version, connector_refresh_required: true, message: 'Worker tool catalogs changed. Run dalan service update --yes with the same --home to switch, then refresh hosted connectors.' };
301
+ prune(home, oldVersion, r.version);
302
+ return result;
303
+ }
304
+ // A catalog difference requires explicit consent; exact parity may proceed without it.
305
+ const digestBeforeRecheck = configurationDigest(home, receipt);
306
+ const liveAgain = await probe(home, receipt);
307
+ if (liveAgain.version !== oldVersion || !catalogsEqual(base, liveAgain, workers)) fail('live worker catalog changed during update; retry after connector refresh');
308
+ if (configurationDigest(home, receipt) !== digestBeforeRecheck || digestBeforeRecheck !== configBeforeCandidate) fail('service configuration changed during update; retry after connector refresh');
309
+ const unitFile = receipt.unit ? unitPath(receipt, home) : null;
310
+ const txDir = path.join(home, 'update-backup'); privateDir(txDir);
311
+ const tx = { home, oldRepo, candidate, snapshot: path.join(txDir, 'snapshot'), unitFile, oldUnit: unitFile && fs.existsSync(unitFile) ? fs.readFileSync(unitFile, 'utf8') : null, oldCatalogs: base.catalogs, oldVersion, oldReceipt: { ...receipt }, phase: 'prepared' };
312
+ if (unitFile && tx.oldUnit == null) fail(`service unit is missing: ${unitFile}`);
313
+ atomic(path.join(home, 'update-transaction.json'), JSON.stringify(tx));
314
+ try {
315
+ await control(receipt, 'stop');
316
+ if (configurationDigest(home, receipt) !== configBeforeCandidate) fail('service configuration changed while stopping; update cancelled');
317
+ snapshot(home, txDir);
318
+ if (configurationDigest(home, receipt) !== configBeforeCandidate) fail('service configuration changed while preparing switch; update cancelled');
319
+ tx.phase = 'switched'; atomic(path.join(home, 'update-transaction.json'), JSON.stringify(tx));
320
+ atomic(defaultPath(home, '.config/dot-bridge', 'service-catalog.json'), JSON.stringify({ version: r.version, catalogs: tested.catalogs }));
321
+ select(home, candidate);
322
+ if (unitFile) rewriteUnit(unitFile, current, home);
323
+ await control(receipt, 'daemon-reload'); await control(receipt, 'restart');
324
+ const live = await probeReady(probe, home, { ...receipt, repo: candidate }, healthTimeoutMs);
325
+ if (live.version !== r.version || !completeCatalogs(tested, live, workers) || !catalogsEqual(tested, live, workers)) fail('updated service health or worker catalogs failed');
326
+ receipt.repo = candidate; receipt.version = r.version;
327
+ atomic(receiptFile, JSON.stringify(receipt));
328
+ fs.rmSync(defaultPath(home, '.config/dot-bridge', 'service-catalog.json'), { force: true });
329
+ const committedTx = { ...tx, phase: 'committed' };
330
+ try { atomic(path.join(home, 'update-transaction.json'), JSON.stringify(committedTx)); }
331
+ catch (error) {
332
+ let journal;
333
+ try { journal = JSON.parse(fs.readFileSync(path.join(home, 'update-transaction.json'), 'utf8')); }
334
+ catch { error.preserveCandidate = true; throw error; }
335
+ if (journal.phase === 'committed' && journal.home === home) {
336
+ tx.phase = 'committed';
337
+ try { fs.rmSync(failedFile(home), { force: true }); } catch { /* see above */ }
338
+ result = { outcome: 'updated', previous_version: oldVersion, version: r.version, cleanup_warning: `committed journal is visible but its durability check failed: ${error.message}; recovery data was preserved` };
339
+ return result;
340
+ }
341
+ if (journal.phase !== 'switched') { error.preserveCandidate = true; throw error; }
342
+ throw error;
343
+ }
344
+ tx.phase = 'committed';
345
+ result = { outcome: 'updated', previous_version: oldVersion, version: r.version };
346
+ try { fs.rmSync(failedFile(home), { force: true }); } catch { /* stale record only skips the same release */ }
347
+ const cleanupWarnings = [];
348
+ try { fs.rmSync(path.join(home, 'update-transaction.json'), { force: true }); } catch (error) { cleanupWarnings.push(`transaction marker cleanup failed: ${error.message}`); }
349
+ try { fs.rmSync(txDir, { recursive: true, force: true }); } catch (error) { cleanupWarnings.push(`backup cleanup failed: ${error.message}`); }
350
+ try { pruneVersions(home, r.version, oldVersion); } catch (error) { cleanupWarnings.push(`version pruning failed: ${error.message}`); }
351
+ if (cleanupWarnings.length) result.cleanup_warning = cleanupWarnings.join('; ');
352
+ } catch (error) {
353
+ if (error.preserveCandidate) {
354
+ const uncertain = new Error(`update commit state is uncertain; candidate and recovery data were preserved: ${error.message}`);
355
+ uncertain.updateOutcome = 'rollback_failed';
356
+ throw uncertain;
357
+ }
358
+ let rollbackError;
359
+ try {
360
+ if (tx.phase === 'switched') validateSnapshot(tx);
361
+ await control(receipt, 'stop'); select(home, oldRepo); if (unitFile && tx.oldUnit != null) atomic(unitFile, tx.oldUnit);
362
+ if (tx.phase === 'switched') for (const item of ['.config', '.local']) replaceTree(path.join(txDir, 'snapshot', item), path.join(home, item));
363
+ await control(receipt, 'daemon-reload'); await control(receipt, 'restart');
364
+ const restored = await probeReady(probe, home, { ...receipt, repo: oldRepo }, healthTimeoutMs);
365
+ if (restored.version !== oldVersion || !catalogsEqual(base, restored, workers)) fail('old service health verification failed');
366
+ fs.rmSync(path.join(home, 'update-transaction.json'), { force: true }); fs.rmSync(txDir, { recursive: true, force: true });
367
+ } catch (e) { rollbackError = e; }
368
+ if (rollbackError) { const e = new Error(`update failed: ${error.message}; rollback failed: ${rollbackError.message}`); e.updateOutcome = 'rollback_failed'; throw e; }
369
+ error.updateOutcome = 'rolled_back';
370
+ throw error;
371
+ }
372
+ return result;
373
+ } catch (error) {
374
+ result = { outcome: error.updateOutcome ?? 'failed', error: error.message };
375
+ if (attempted && (result.outcome === 'rolled_back' || result.outcome === 'rollback_failed')) {
376
+ try { atomic(failedFile(home), JSON.stringify({ version: attempted.version, integrity: attempted.dist.integrity, outcome: result.outcome, timestamp: new Date().toISOString() })); } catch { /* best effort */ }
377
+ }
378
+ throw error;
379
+ } finally {
380
+ try { if (result) atomic(resultFile, JSON.stringify({ ...result, timestamp: new Date().toISOString() })); }
381
+ finally { releaseLock(); }
382
+ }
383
+ }
384
+
385
+ export function serviceStatus({ home }) {
386
+ home = path.resolve(home ?? fail('home is required'));
387
+ const { value: receipt } = readReceipt(home), current = path.join(home, 'current');
388
+ let version = receipt.version;
389
+ if (fs.existsSync(current)) version = JSON.parse(fs.readFileSync(path.join(fs.realpathSync(current), 'package.json'), 'utf8')).version;
390
+ let last_result = null;
391
+ try { last_result = JSON.parse(fs.readFileSync(path.join(home, 'update-result.json'), 'utf8')); } catch { /* no update attempt */ }
392
+ return { version, auto_update: receipt.auto_update ?? false, last_result, failed_release: readFailed(home)?.version ?? null };
393
+ }
package/src/service.mjs CHANGED
@@ -7,9 +7,11 @@ import { createHash, randomBytes } from 'node:crypto';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { isIP } from 'node:net';
9
9
  import { defaultPath } from './paths.mjs';
10
- import { initAsFiles } from './as-files.mjs';
10
+ import { initAsFiles, writeAtomic } from './as-files.mjs';
11
11
  import { parseWorkers } from './workers.mjs';
12
12
  import { parseArgs } from '../scripts/live-trial/common.mjs';
13
+ import { resolveGozarCommand } from './try-exposure.mjs';
14
+ import { autoUpdateUnits, setAutoUpdate } from './service-auto-update.mjs';
13
15
 
14
16
  const REPO = fileURLToPath(new URL('..', import.meta.url));
15
17
  const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
@@ -48,10 +50,11 @@ function validateTopology({ port, target, lanPort = null, verifyCmd }) {
48
50
  function parseOptions(argv, env) {
49
51
  const parsed = parseArgs(argv, {
50
52
  values: ['--home', '--public-url', '--port', '--target', '--worker', '--verify-cmd', '--gozar-bin', '--lan-port'],
51
- flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--json', '--help'],
53
+ flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--auto-update', '--no-auto-update', '--json', '--help'],
52
54
  });
53
55
  if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
54
56
  if (parsed['--help']) return { help: true };
57
+ if (parsed['--auto-update'] && parsed['--no-auto-update']) fail('choose --auto-update or --no-auto-update');
55
58
  const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
56
59
  if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a systemd unit');
57
60
  const origin = parseOrigin(parsed['--public-url']);
@@ -70,10 +73,11 @@ function parseOptions(argv, env) {
70
73
  }
71
74
  if (new Set(workers).size !== workers.length) fail('--worker names must be unique');
72
75
  if (parsed['--verify-cmd']?.length > 4096) fail('--verify-cmd is too long');
73
- const gozarBin = parsed['--gozar-bin'] ?? env.GOZAR_BIN ?? 'gozar';
74
- if (!gozarBin || gozarBin.startsWith('-')) fail('--gozar-bin must name a command');
76
+ const gozarBin = parsed['--gozar-bin'];
77
+ if (gozarBin !== undefined && (!gozarBin || gozarBin.startsWith('-'))) fail('--gozar-bin must name a command');
75
78
  return { home, origin, port, target, lanPort, enableWorkspace: parsed['--enable-workspace'] === true, enableT3: parsed['--enable-t3'] === true, workers, verifyCmd: parsed['--verify-cmd'] ?? null,
76
- gozarBin, writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
79
+ gozarBin, autoUpdate: parsed['--auto-update'] ? true : parsed['--no-auto-update'] ? false : undefined,
80
+ writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
77
81
  }
78
82
 
79
83
  function assertRealDirectoryPath(target, { owner = false } = {}) {
@@ -104,7 +108,7 @@ function nodePath(execPath) {
104
108
 
105
109
  function unitName(home) { return `dalan-${createHash('sha256').update(home).digest('hex').slice(0, 10)}`; }
106
110
 
107
- function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), proxy = null } = {}) {
111
+ function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), proxy = null, recover = true } = {}) {
108
112
  const name = unitName(home);
109
113
  for (const [label, value] of [['home', home], ['repo', repo], ['node', node]]) {
110
114
  if (!SAFE_PATH.test(value)) fail(`${label} contains characters that cannot be written safely in a systemd unit`);
@@ -113,6 +117,7 @@ function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), pr
113
117
  [`${name}.service`]: [
114
118
  '[Unit]', 'Description=Dalan worker bridge', 'After=network-online.target', '', '[Service]',
115
119
  `WorkingDirectory=${repo}`, `ExecStart=${node} ${path.join(repo, 'src/server.mjs')}`,
120
+ ...(recover ? [`ExecStartPre=${node} ${path.join(repo, 'bin/dalan.mjs')} service recover --home ${home} --quiet`] : []),
116
121
  `Environment=HOME=${home}`, 'Environment=NODE_ENV=production', 'Environment=DALAN_AUTH_MODE=builtin',
117
122
  'Environment=DALAN_BIND_HOST=127.0.0.1', 'Environment=DALAN_GOZAR_SERVICE=1', 'Environment=DALAN_CATALOG_PROFILE=stable',
118
123
  `Environment=DALAN_ENABLE_WORKSPACE=${o.enableWorkspace ? '1' : '0'}`, `Environment=DALAN_ENABLE_T3_TOOLS=${o.enableT3 ? '1' : '0'}`,
@@ -203,7 +208,7 @@ function checkHomeScope(home, configDir, o, workers) {
203
208
  if (!fs.existsSync(home)) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
204
209
  const rootEntries = fs.readdirSync(home);
205
210
  if (!rootEntries.length) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
206
- const rootAllowed = ['.config', '.local', '.tmp', 'resource-url'];
211
+ const rootAllowed = ['.config', '.local', '.tmp', 'resource-url', 'current', 'versions', 'update-result.json', 'update-failed.json', 'update-transaction.json', 'update-backup', 'update-lock.sqlite', 'update-lock.sqlite-journal'];
207
212
  if (rootEntries.some(name => !rootAllowed.includes(name))) fail(`${home} contains unrelated data; use a fresh home or one created by dalan service migrate-workers`);
208
213
  if (!rootEntries.includes('.config')) fail(`${home} has no Dalan config directory; refusing to adopt it`);
209
214
  const configRoot = path.join(home, '.config');
@@ -220,6 +225,7 @@ function checkHomeScope(home, configDir, o, workers) {
220
225
  const receiptFile = path.join(configDir, 'service-install.json');
221
226
  const entries = fs.readdirSync(configDir);
222
227
  const hasReceipt = entries.includes('service-install.json');
228
+ if (!hasReceipt && rootEntries.some(name => !['.config', '.local', '.tmp', 'resource-url'].includes(name))) fail(`${home} contains update data without a service receipt`);
223
229
  if (hasReceipt) {
224
230
  const info = fs.lstatSync(receiptFile);
225
231
  if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) fail(`${receiptFile} must be a private regular file`);
@@ -305,6 +311,35 @@ function socketIsReady(socketPath, timeoutMs = 30000) {
305
311
  });
306
312
  }
307
313
 
314
+ // Gozar refuses a state path whose ancestors are writable by group or others, but only
315
+ // when `service add` runs, after the bridge is already started. Apply the same rule first.
316
+ function assertGozarStatePath(env) {
317
+ const stateHome = env.GOZAR_HOME ?? path.join(env.HOME ?? os.homedir(), '.local', 'state', 'gozar');
318
+ let canonical = path.resolve(stateHome);
319
+ const missing = [];
320
+ for (;;) {
321
+ try { canonical = path.join(fs.realpathSync(canonical), ...missing); break; }
322
+ catch (error) {
323
+ if (error.code !== 'ENOENT') return; // Gozar reports other failures itself.
324
+ const parent = path.dirname(canonical);
325
+ if (parent === canonical) return;
326
+ missing.unshift(path.basename(canonical));
327
+ canonical = parent;
328
+ }
329
+ }
330
+ const uid = process.getuid();
331
+ const chain = [];
332
+ for (let dir = canonical; ; dir = path.dirname(dir)) { chain.unshift(dir); if (path.dirname(dir) === dir) break; }
333
+ for (const dir of chain) {
334
+ let stat;
335
+ try { stat = fs.lstatSync(dir); } catch { return; }
336
+ const rootSticky = stat.uid === 0 && (stat.mode & 0o1000);
337
+ if (!stat.isDirectory() || stat.isSymbolicLink()) fail(`Gozar refuses its state path: ${dir} must be a real directory. Set GOZAR_HOME to a private directory, then retry.`);
338
+ if (stat.uid !== 0 && stat.uid !== uid) fail(`Gozar refuses its state path: ${dir} must be owned by you or root. Set GOZAR_HOME to a directory you own, then retry.`);
339
+ if ((stat.mode & 0o022) && !rootSticky) fail(`Gozar refuses its state path: ${dir} is writable by group or others. Run: chmod go-w ${dir} (then retry service install)`);
340
+ }
341
+ }
342
+
308
343
  export async function installService(o, seams = {}) {
309
344
  const env = seams.env ?? process.env;
310
345
  if ((seams.platform ?? process.platform) !== 'linux') fail('dalan service install currently requires Linux with a systemd user manager');
@@ -321,31 +356,67 @@ export async function installService(o, seams = {}) {
321
356
  const configDir = path.dirname(profile.file);
322
357
  const homeScope = checkHomeScope(o.home, configDir, o, profile.workers);
323
358
  const proxy = o.target.host === '127.0.0.1' && o.target.port === o.port ? null : (seams.proxy ?? findProxy());
324
- const { files, enable, name } = unitFiles(o, { home: o.home, repo: seams.repo ?? REPO, node: seams.node ?? nodePath(process.execPath), proxy });
359
+ const repo = seams.repo ?? REPO, node = seams.node ?? nodePath(process.execPath);
360
+ const receiptFile = homeScope.receiptFile;
361
+ const previous = homeScope.hasReceipt ? JSON.parse(fs.readFileSync(receiptFile, 'utf8')) : null;
362
+ const autoUpdate = o.autoUpdate ?? previous?.auto_update ?? !homeScope.hasReceipt;
363
+ const current = path.join(o.home, 'current');
364
+ const hasCurrent = fs.existsSync(current) || (() => { try { fs.lstatSync(current); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } })();
365
+ if (hasCurrent && !fs.lstatSync(current).isSymbolicLink()) fail(`${current} must be the service package symlink`);
366
+ const { files, enable, name } = unitFiles(o, { home: o.home, repo: current, node, proxy });
367
+ const updateUnits = autoUpdateUnits({ home: o.home, unit: name, node });
368
+ Object.assign(files, updateUnits.files);
369
+ let replaceLegacyUnit = false;
325
370
  // Check every collision before creating the bridge home or the first unit file.
326
371
  for (const [filename, text] of Object.entries(files)) {
327
372
  const file = path.join(unitDir, filename);
328
- if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) fail(`${file} already exists with different contents; refusing to overwrite it`);
373
+ if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) {
374
+ const actual = fs.lstatSync(file).isFile() ? fs.readFileSync(file, 'utf8') : '';
375
+ const oldRepo = actual.match(/^WorkingDirectory=(.+)$/m)?.[1];
376
+ const oldNode = actual.match(/^ExecStart=(\S+) /m)?.[1];
377
+ const expected = filename === `${name}.service` && previous && oldRepo && oldNode && SAFE_PATH.test(oldRepo) && SAFE_PATH.test(oldNode)
378
+ ? unitFiles(o, { home: o.home, repo: oldRepo, node: oldNode, proxy, recover: false }).files[filename] : null;
379
+ // Only the exact former generated unit can be enrolled or retried after interruption.
380
+ if (expected && actual === expected) replaceLegacyUnit = true;
381
+ else fail(`${file} already exists with different contents; refusing to overwrite it`);
382
+ }
329
383
  }
330
384
  if (o.writeUnitsOnly) {
385
+ if (replaceLegacyUnit) fail('rerun without --write-units-only to enroll an existing service for updates');
331
386
  writeUnits(unitDir, files);
332
387
  return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), target: o.target.value, started: false, route: null };
333
388
  }
389
+ // An explicit --gozar-bin wins; otherwise the bundled Gozar, GOZAR_BIN, then PATH.
390
+ const gozar = o.gozarBin !== undefined ? { binary: o.gozarBin, args: [] }
391
+ : resolveGozarCommand({ env, resolveBundled: seams.resolveBundled, which: seams.which });
392
+ if (!gozar.binary) fail('Gozar is unavailable; reinstall @tnunamak/dalan with its dependencies, or install gozar on PATH or set GOZAR_BIN to an executable path, then retry service install.');
393
+ assertGozarStatePath(env);
394
+ const needsEnrollmentRestart = replaceLegacyUnit || !!previous && (!previous.repo || previous.enrollment_pending === true);
334
395
  const spawn = seams.spawn ?? spawnSync;
335
396
  runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
336
397
  fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
337
- if (!homeScope.hasReceipt) writePrivate(homeScope.receiptFile, `${JSON.stringify(installReceipt(o.home, configDir, o, profile.workers), null, 2)}\n`);
398
+ if (!homeScope.hasReceipt) writePrivate(receiptFile, `${JSON.stringify({ ...installReceipt(o.home, configDir, o, profile.workers), repo, node, unit_dir: unitDir, auto_update: autoUpdate }, null, 2)}\n`);
399
+ if (!hasCurrent) fs.symlinkSync(repo, current);
338
400
  const homeFiles = prepareHome(o, profile);
401
+ if (needsEnrollmentRestart) {
402
+ writeAtomic(receiptFile, `${JSON.stringify({ ...previous, repo: previous.repo ?? repo, node, unit_dir: unitDir, auto_update: autoUpdate, enrollment_pending: true }, null, 2)}\n`);
403
+ }
404
+ if (replaceLegacyUnit) {
405
+ const file = path.join(unitDir, `${name}.service`), mode = fs.statSync(file).mode & 0o777;
406
+ writeAtomic(file, files[`${name}.service`]);
407
+ fs.chmodSync(file, mode);
408
+ }
339
409
  writeUnits(unitDir, files);
340
410
  runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
341
411
  runCommand('systemctl', ['--user', 'enable', '--now', ...enable], { env, spawn });
412
+ if (needsEnrollmentRestart) runCommand('systemctl', ['--user', 'restart', `${name}.service`], { env, spawn });
342
413
  const dataDir = defaultPath(o.home, '.local/share/dot-bridge');
343
414
  const ready = await (seams.waitForSocket ?? socketIsReady)(path.join(dataDir, 'admin.sock'), seams.socketTimeoutMs ?? 30000);
344
415
  if (!ready) fail(`Dalan did not start on its admin socket; the unit and home remain for inspection: systemctl --user status ${name}.service`);
345
416
  const gozarArgs = ['service', 'add', '--origin', o.origin, '--target', o.target.value];
346
417
  if (o.verifyCmd) gozarArgs.push('--verify-cmd', o.verifyCmd);
347
418
  gozarArgs.push('--json');
348
- const output = runCommand(o.gozarBin ?? env.GOZAR_BIN ?? 'gozar', gozarArgs, { env, spawn, timeout: 120000 });
419
+ const output = runCommand(gozar.binary, [...gozar.args, ...gozarArgs], { env, spawn, timeout: 120000 });
349
420
  let routeReply;
350
421
  try { routeReply = JSON.parse(output); } catch { fail('Gozar returned invalid JSON for service add; the bridge is running but its route is unverified'); }
351
422
  if (routeReply?.schemaVersion !== 1 || routeReply?.route?.origin !== o.origin || routeReply?.route?.target !== o.target.value) {
@@ -354,9 +425,15 @@ export async function installService(o, seams = {}) {
354
425
  if (routeReply.route.verification?.status !== 'verified') {
355
426
  fail(`Gozar did not verify the service route; the bridge is running and the service route needs repair: ${JSON.stringify(routeReply).slice(0, 1500)}`);
356
427
  }
428
+ await setAutoUpdate({ home: o.home, enabled: autoUpdate }, { ...seams, env, spawn });
429
+ if (needsEnrollmentRestart) {
430
+ const enrolled = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
431
+ delete enrolled.enrollment_pending;
432
+ writeAtomic(receiptFile, `${JSON.stringify(enrolled, null, 2)}\n`);
433
+ }
357
434
  return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), port: o.port,
358
435
  workers: profile.workers, public_url: `${o.origin}/<secret>/mcp`, resource_url_file: homeFiles.resourceFile,
359
- target: o.target.value, started: true, route: routeReply.route };
436
+ target: o.target.value, started: true, route: routeReply.route, auto_update: autoUpdate };
360
437
  }
361
438
 
362
439
  export async function serviceMain(argv, seams = {}) {
@@ -365,11 +442,40 @@ export async function serviceMain(argv, seams = {}) {
365
442
  const { migrationMain } = await import('./service-migrate-workers.mjs');
366
443
  return migrationMain(args);
367
444
  }
445
+ if (action === 'recover') {
446
+ const parsed = parseArgs(args, { values: ['--home'], flags: ['--quiet', '--help'] });
447
+ if (parsed['--help']) return serviceMain(['help'], seams);
448
+ if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
449
+ const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
450
+ const { recoverService } = await import('./service-update.mjs');
451
+ const result = recoverService({ home });
452
+ if (!parsed['--quiet']) (seams.out ?? console.log)(JSON.stringify(result));
453
+ return result;
454
+ }
455
+ if (['update', 'status', 'auto-update'].includes(action)) {
456
+ const parsed = parseArgs(args, { values: ['--home'], flags: ['--check', '--yes', '--retry', '--json', '--help'] });
457
+ if (parsed['--help']) return serviceMain(['help'], seams);
458
+ const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
459
+ let result;
460
+ if (action === 'auto-update') {
461
+ if (parsed._.length !== 1 || !['on', 'off'].includes(parsed._[0]) || parsed['--check'] || parsed['--yes'] || parsed['--retry']) fail('use dalan service auto-update on|off [--home DIR]');
462
+ result = await setAutoUpdate({ home, enabled: parsed._[0] === 'on' }, seams);
463
+ } else {
464
+ if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
465
+ if (parsed['--check'] && parsed['--retry']) fail('--check cannot be used with --retry');
466
+ if (parsed['--check'] && parsed['--yes']) fail('--check cannot be used with --yes');
467
+ if (action === 'status' && (parsed['--check'] || parsed['--yes'] || parsed['--retry'])) fail('service status does not accept --check, --yes or --retry');
468
+ const updater = await import('./service-update.mjs');
469
+ result = await updater[action === 'status' ? 'serviceStatus' : 'updateService']({ home, check: !!parsed['--check'], yes: !!parsed['--yes'], retry: !!parsed['--retry'] }, seams);
470
+ }
471
+ (seams.out ?? console.log)(parsed['--json'] ? JSON.stringify(result) : JSON.stringify(result, null, 2));
472
+ return result;
473
+ }
368
474
  if (action === 'help' || action === '--help' || !action) {
369
- (seams.out ?? console.log)('Usage: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--write-units-only]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]');
475
+ (seams.out ?? console.log)('Usage: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--auto-update|--no-auto-update] [--write-units-only]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]\n dalan service update [--check|--yes] [--retry] [--home DIR] [--json]\n dalan service auto-update on|off [--home DIR]\n dalan service status [--home DIR] [--json]\n dalan service recover --home DIR [--quiet]\nNew installs check daily with jitter. Catalog changes stage until --yes authorizes a connector refresh. --check reports availability without installing. Linux systemd only.');
370
476
  return null;
371
477
  }
372
- if (action !== 'install') fail('use dalan service install or dalan service migrate-workers');
478
+ if (action !== 'install') fail('use dalan service install, update, auto-update, status, recover or migrate-workers');
373
479
  const o = parseOptions(args, seams.env ?? process.env);
374
480
  if (o.help) return serviceMain(['help'], seams);
375
481
  const result = await installService(o, seams);