@tnunamak/dalan 0.8.1 → 0.8.3
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.
- package/CHANGELOG.md +61 -2
- package/CONTRIBUTING.md +2 -0
- package/README.md +8 -12
- package/bin/dalan.mjs +25 -4
- package/bin/dot-acp-agent.mjs +572 -76
- package/bin/dot-alert.mjs +9 -3
- package/bin/dot-deadman.mjs +3 -1
- package/bin/dot-heartbeat.mjs +14 -7
- package/bin/dot-pr-reviewer.mjs +3 -31
- package/bin/dot-worker.mjs +121 -34
- package/contracts/adapter-qualification.schema.json +94 -7
- package/docs/chatgpt-worker-onboarding.md +1 -1
- package/docs/codex-to-muse.md +2 -2
- package/docs/connect-chatgpt.md +1 -1
- package/docs/connection-longevity.md +2 -2
- package/docs/dalan-upgrade.md +8 -5
- package/docs/deadman.md +4 -0
- package/docs/design/authority-matrix.md +18 -0
- package/docs/design/failure-table.md +87 -0
- package/docs/design/identities.md +22 -0
- package/docs/design/pnpm-prepared-dependencies.md +64 -0
- package/docs/design/reuse-ledger.md +75 -0
- package/docs/design/target-architecture-v2.md +434 -0
- package/docs/local-agent-mcp.md +14 -0
- package/docs/local-agent-requester.md +2 -1
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +77 -14
- package/docs/pull-workers.md +11 -1
- package/docs/service-setup.md +10 -10
- package/docs/t3-integration.md +4 -2
- package/docs/t3-reverse-control.md +5 -5
- package/docs/test-suite-isolation.md +7 -6
- package/docs/trials/chatgpt-agent.md +47 -0
- package/docs/trials/claude-code-requester.md +68 -0
- package/docs/trials/muse.md +46 -0
- package/docs/usage.md +21 -7
- package/docs/worker-clients.md +1 -1
- package/integrations/t3/acp-kit/src/errors.mjs +6 -2
- package/integrations/t3/acp-kit/src/lock.mjs +46 -17
- package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
- package/package.json +4 -3
- package/packages/job-core/protocol/canonical.mjs +45 -7
- package/packages/job-core/transitions.mjs +4 -2
- package/scripts/upgrade-drain.mjs +96 -8
- package/scripts/worker-bridge-setup.mjs +215 -120
- package/src/ack-ledger.mjs +7 -1
- package/src/acp-bridge.mjs +256 -28
- package/src/admin-socket.mjs +32 -3
- package/src/alerts.mjs +17 -8
- package/src/answer-journal-retention.mjs +82 -0
- package/src/answer-journal.mjs +6 -4
- package/src/as-store.mjs +51 -6
- package/src/as.mjs +27 -5
- package/src/catalog-switch-inventory.mjs +70 -0
- package/src/check-response.mjs +4 -1
- package/src/cli-help.mjs +14 -3
- package/src/cli-name.mjs +13 -1
- package/src/connect-cli.mjs +159 -4
- package/src/deadman.mjs +8 -5
- package/src/delivery.mjs +2 -19
- package/src/destinations/index.mjs +75 -14
- package/src/drain-runner.mjs +5 -1
- package/src/follow-current.mjs +3 -1
- package/src/get-summary.mjs +11 -2
- package/src/git-env.mjs +1 -1
- package/src/gozar-routes.mjs +313 -94
- package/src/host-budget-storage.py +56 -6
- package/src/host-budget.mjs +98 -15
- package/src/host-execution-policy.mjs +17 -6
- package/src/legacy-names.mjs +0 -2
- package/src/lifecycle.mjs +44 -9
- package/src/loopback-probe.mjs +46 -0
- package/src/mcp-outcome.mjs +3 -1
- package/src/mcp-sse.mjs +2 -1
- package/src/mcp-stdio.mjs +192 -30
- package/src/patch-apply.mjs +212 -7
- package/src/phase-trace.mjs +73 -0
- package/src/prepared-go-modules.mjs +127 -0
- package/src/prepared-node-modules.mjs +225 -38
- package/src/prepared-pnpm.mjs +276 -0
- package/src/prepared-store-prune.mjs +52 -0
- package/src/projects.mjs +59 -7
- package/src/protocol-artifact-commands.mjs +28 -0
- package/src/protocol-finish.mjs +3 -2
- package/src/publication-authority.mjs +22 -0
- package/src/publish-plan.mjs +2 -2
- package/src/pull-queue.mjs +55 -20
- package/src/read-api.mjs +127 -0
- package/src/redaction.mjs +173 -0
- package/src/rejections.mjs +19 -3
- package/src/route-custody.mjs +90 -0
- package/src/route-publication.mjs +50 -0
- package/src/route-setup.mjs +184 -0
- package/src/schema-subset.mjs +5 -3
- package/src/server.mjs +503 -98
- package/src/service-launchd.mjs +5 -1
- package/src/service-update-lock.mjs +7 -4
- package/src/service-update-runtime.mjs +136 -21
- package/src/service-update.mjs +207 -51
- package/src/service.mjs +276 -77
- package/src/setup.mjs +48 -25
- package/src/signal.mjs +1 -1
- package/src/status-evidence.mjs +18 -5
- package/src/store.mjs +876 -120
- package/src/submission-policy.mjs +257 -56
- package/src/t3-control.mjs +1 -1
- package/src/t3.mjs +14 -8
- package/src/terminal-safe.mjs +9 -7
- package/src/tool-registry.mjs +134 -41
- package/src/try-exposure.mjs +53 -86
- package/src/try-hosted.mjs +257 -70
- package/src/try.mjs +48 -22
- package/src/work-order.mjs +11 -6
- package/src/worker-instructions.mjs +26 -4
- package/src/worker-runs.mjs +35 -0
- package/src/workers.mjs +34 -7
- package/src/workspace.mjs +354 -54
- package/systemd/dot-deadman.service +3 -1
- package/docs/dot-pr-reviewer.config.example.json +0 -9
- package/docs/pr-head-reviewer.md +0 -70
- package/src/pr-head-reviewer.mjs +0 -596
- package/systemd/dot-pr-reviewer.service +0 -11
- package/systemd/dot-pr-reviewer.timer +0 -10
package/src/service-update.mjs
CHANGED
|
@@ -11,13 +11,17 @@ const PACKAGE = '@tnunamak/dalan';
|
|
|
11
11
|
const HEALTH_TIMEOUT_MS = 30_000;
|
|
12
12
|
const fail = message => { throw new Error(message); };
|
|
13
13
|
const privateDir = dir => fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
14
|
+
// A receipt names the home it was installed for; the same directory reached through a link is still that home.
|
|
15
|
+
const realHome = dir => { try { return fs.realpathSync(dir); } catch { return path.resolve(dir); } };
|
|
16
|
+
const resolveHome = home => realHome(path.resolve(home ?? fail('home is required')));
|
|
17
|
+
const sameHome = (recorded, home) => typeof recorded === 'string' && (recorded === home || realHome(recorded) === realHome(home));
|
|
14
18
|
function readReceipt(home) {
|
|
15
19
|
const file = path.join(defaultPath(home, '.config/dot-bridge'), 'service-install.json');
|
|
16
20
|
let st, value;
|
|
17
21
|
try { st = fs.lstatSync(file); value = JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
18
22
|
catch { fail(`service receipt is missing or invalid: ${file}`); }
|
|
19
23
|
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
|
|
24
|
+
if (!value || value.schema_version !== 1 || !sameHome(value.home, home) || !value.unit) fail(`${file} has an unsupported service receipt`);
|
|
21
25
|
return { file, value };
|
|
22
26
|
}
|
|
23
27
|
function canonical(x) {
|
|
@@ -55,18 +59,28 @@ function catalogsEqual(a, b, workers) {
|
|
|
55
59
|
const hasCatalogs = catalogs => !!catalogs && Object.keys(catalogs).length > 0;
|
|
56
60
|
function releaseVersion(r, current) {
|
|
57
61
|
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');
|
|
62
|
+
if (typeof current !== 'string' || !/^\d+\.\d+\.\d+$/.test(current)) fail('installed service version is not a stable semantic version');
|
|
58
63
|
const parts = s => s.split('.').map(Number), a = parts(r.version), b = parts(current);
|
|
59
|
-
if (
|
|
64
|
+
if (a.some(n => !Number.isSafeInteger(n)) || b.some(n => !Number.isSafeInteger(n))) fail('installed service version is not a stable semantic version');
|
|
60
65
|
return a[0] > b[0] || a[0] === b[0] && (a[1] > b[1] || a[1] === b[1] && a[2] > b[2]);
|
|
61
66
|
}
|
|
62
67
|
function atomic(file, text) {
|
|
63
68
|
privateDir(path.dirname(file)); writeAtomic(file, text);
|
|
64
69
|
}
|
|
65
70
|
const failedFile = home => path.join(home, 'update-failed.json');
|
|
66
|
-
function
|
|
71
|
+
function clearFailedReleaseMarker(home, warnings) {
|
|
72
|
+
try { fs.rmSync(failedFile(home), { force: true }); }
|
|
73
|
+
catch { warnings.push('failed release marker cleanup failed'); }
|
|
74
|
+
}
|
|
75
|
+
function readFailed(home, active) {
|
|
67
76
|
try {
|
|
68
77
|
const v = JSON.parse(fs.readFileSync(failedFile(home), 'utf8'));
|
|
69
|
-
|
|
78
|
+
if (typeof v?.version !== 'string' || typeof v.integrity !== 'string') return null;
|
|
79
|
+
// A cleanup failure may leave the marker for the very bytes now selected.
|
|
80
|
+
// Do not infer integrity from the version alone or rewrite the marker here.
|
|
81
|
+
if (active?.repo && active.receipt.repo === active.repo && active.receipt.version === active.version &&
|
|
82
|
+
v.version === active.version && v.integrity === active.receipt.release_integrity) return null;
|
|
83
|
+
return v;
|
|
70
84
|
} catch { return null; }
|
|
71
85
|
}
|
|
72
86
|
function copyTree(src, dst) {
|
|
@@ -79,9 +93,34 @@ function copyTree(src, dst) {
|
|
|
79
93
|
fs.chmodSync(dst, st.mode & 0o777);
|
|
80
94
|
} else { fs.copyFileSync(src, dst); fs.chmodSync(dst, st.mode & 0o777); }
|
|
81
95
|
}
|
|
82
|
-
function replaceTree(src, dst) {
|
|
83
|
-
fs.
|
|
84
|
-
|
|
96
|
+
export function replaceTree(src, dst, { copy = copyTree } = {}) {
|
|
97
|
+
if (!fs.existsSync(src)) {
|
|
98
|
+
fs.rmSync(dst, { recursive: true, force: true });
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
const staging = dst + '.restore-' + process.pid;
|
|
102
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
103
|
+
try {
|
|
104
|
+
copy(src, staging);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
// Keep the existing destination until the replacement is ready and recover it if activation fails.
|
|
110
|
+
const aside=dst+'.previous-'+randomUUID();
|
|
111
|
+
let moved=false;
|
|
112
|
+
try {
|
|
113
|
+
if(fs.lstatSync(dst,{throwIfNoEntry:false})) { fs.renameSync(dst,aside); moved=true; }
|
|
114
|
+
fs.renameSync(staging,dst);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
if(moved) {
|
|
117
|
+
try { fs.renameSync(aside,dst); }
|
|
118
|
+
catch(rollbackError) { throw new AggregateError([error,rollbackError], 'restore activation and rollback failed; previous directory retained at '+aside); }
|
|
119
|
+
}
|
|
120
|
+
fs.rmSync(staging,{recursive:true,force:true});
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
if(moved) fs.rmSync(aside,{recursive:true,force:true});
|
|
85
124
|
}
|
|
86
125
|
function snapshot(home, txn) {
|
|
87
126
|
const target = path.join(txn, 'snapshot.pending'); fs.rmSync(target, { recursive: true, force: true }); privateDir(target);
|
|
@@ -156,24 +195,47 @@ function select(home, repo) {
|
|
|
156
195
|
const current = path.join(home, 'current'), tmp = path.join(home, `.current-${randomUUID()}`);
|
|
157
196
|
fs.symlinkSync(path.relative(home, repo), tmp); fs.renameSync(tmp, current);
|
|
158
197
|
}
|
|
159
|
-
function prune(home, active, previous) {
|
|
198
|
+
function prune(home, active, previous, receiptRepo) {
|
|
160
199
|
const root = path.join(home, 'versions'); if (!fs.existsSync(root)) return;
|
|
161
200
|
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 }));
|
|
162
|
-
const
|
|
201
|
+
const protectedPaths = [];
|
|
202
|
+
for (const target of [path.join(home, 'current'), receiptRepo]) {
|
|
203
|
+
try { if (target && fs.existsSync(target)) protectedPaths.push(fs.realpathSync(target)); } catch { /* an unavailable target cannot identify a version directory */ }
|
|
204
|
+
}
|
|
205
|
+
const keep = new Set([active, previous].filter(name => dirs.includes(name)));
|
|
206
|
+
for (const name of dirs) {
|
|
207
|
+
const directory = fs.realpathSync(path.join(root, name));
|
|
208
|
+
if (protectedPaths.some(target => {
|
|
209
|
+
const relative = path.relative(directory, target);
|
|
210
|
+
return relative === '' || relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
211
|
+
})) keep.add(name);
|
|
212
|
+
}
|
|
163
213
|
for (const name of dirs) { if (keep.size >= 3) break; keep.add(name); }
|
|
164
214
|
for (const name of dirs) if (!keep.has(name)) fs.rmSync(path.join(root, name), { recursive: true, force: true });
|
|
165
215
|
}
|
|
166
216
|
async function probeReady(probe, home, receipt, healthTimeoutMs = HEALTH_TIMEOUT_MS) {
|
|
167
217
|
const deadline = performance.now() + healthTimeoutMs;
|
|
168
218
|
let error;
|
|
169
|
-
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
219
|
+
for (let remaining = deadline - performance.now(); remaining > 0; remaining = deadline - performance.now()) {
|
|
220
|
+
const controller = new AbortController();
|
|
221
|
+
let timer;
|
|
222
|
+
const expired = new Promise((_, reject) => {
|
|
223
|
+
timer = setTimeout(() => {
|
|
224
|
+
reject(new Error('health probe did not respond'));
|
|
225
|
+
controller.abort();
|
|
226
|
+
}, Math.ceil(remaining));
|
|
227
|
+
});
|
|
228
|
+
try {
|
|
229
|
+
const live = await Promise.race([
|
|
230
|
+
probe(home, receipt, { timeout: Math.max(1, Math.min(remaining, 1000)), signal: controller.signal }),
|
|
231
|
+
expired,
|
|
232
|
+
]);
|
|
233
|
+
if (performance.now() < deadline) return live;
|
|
234
|
+
} catch (e) { error = e; }
|
|
235
|
+
finally { clearTimeout(timer); }
|
|
236
|
+
if (controller.signal.aborted) break;
|
|
237
|
+
const delay = Math.min(150, Math.max(0, deadline - performance.now()));
|
|
238
|
+
if (delay) await new Promise(resolve => setTimeout(resolve, delay));
|
|
177
239
|
}
|
|
178
240
|
throw new Error(`service health check timed out after ${healthTimeoutMs}ms${error ? `: ${error.message}` : ''}`);
|
|
179
241
|
}
|
|
@@ -185,10 +247,10 @@ function readJournal(home) {
|
|
|
185
247
|
let tx;
|
|
186
248
|
try { tx = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { fail('update transaction is invalid JSON'); }
|
|
187
249
|
const oldReceipt = tx?.oldReceipt;
|
|
188
|
-
if (tx.home
|
|
250
|
+
if (!sameHome(tx.home, home) || !oldReceipt || !sameHome(oldReceipt.home, home) || oldReceipt.schema_version !== 1 || !oldReceipt.unit ||
|
|
189
251
|
!tx.oldRepo || !tx.oldVersion || !tx.snapshot || !['prepared', 'switched', 'committed'].includes(tx.phase)) fail('invalid interrupted update transaction');
|
|
190
252
|
if (tx.unitFile !== (oldReceipt.unit && oldReceipt.platform !== 'darwin' ? unitPath(oldReceipt, home) : null) || !tx.oldCatalogs || typeof tx.oldCatalogs !== 'object') fail('update transaction control data is invalid');
|
|
191
|
-
if (path.resolve(tx.snapshot) !== path.join(home, 'update-backup', 'snapshot')) fail('update transaction snapshot path is invalid');
|
|
253
|
+
if (path.resolve(realHome(path.dirname(tx.snapshot)), path.basename(tx.snapshot)) !== path.join(home, 'update-backup', 'snapshot')) fail('update transaction snapshot path is invalid');
|
|
192
254
|
return { file, tx };
|
|
193
255
|
}
|
|
194
256
|
// Put the old package, unit and saved state back on disk. Touches no service and probes nothing.
|
|
@@ -213,7 +275,7 @@ function restoreFromJournal(home, tx) {
|
|
|
213
275
|
}
|
|
214
276
|
// Run at service start (ExecStartPre): finish filesystem recovery without touching systemd.
|
|
215
277
|
export function recoverService({ home }) {
|
|
216
|
-
home =
|
|
278
|
+
home = resolveHome(home);
|
|
217
279
|
if (!fs.existsSync(path.join(home, 'update-transaction.json'))) return { outcome: 'nothing_pending' };
|
|
218
280
|
let release;
|
|
219
281
|
try { release = acquireUpdateLock(home); }
|
|
@@ -251,29 +313,87 @@ function actualWorkers(home) {
|
|
|
251
313
|
if (!workers.length) fail('configured worker set is empty');
|
|
252
314
|
return workers;
|
|
253
315
|
}
|
|
316
|
+
// update-result.json is an optional record. If it cannot be written the outcome stands; the failure is reported as a warning.
|
|
317
|
+
// Each write carries the started-at stamp of the operation that produced it, and a write whose stamp is older than
|
|
318
|
+
// the stamp already in the file is refused: it is a stale result from an operation that started before a newer one
|
|
319
|
+
// finished. Callers must hold the update lock while calling this, so the stamp read and the write cannot interleave
|
|
320
|
+
// with another writer.
|
|
321
|
+
function readResultStamp(file) {
|
|
322
|
+
try {
|
|
323
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
324
|
+
return typeof value?.started_at_ms === 'number' && Number.isFinite(value.started_at_ms) ? value.started_at_ms : null;
|
|
325
|
+
} catch { return null; }
|
|
326
|
+
}
|
|
327
|
+
function recordResult(file, result, startedAtMs) {
|
|
328
|
+
try {
|
|
329
|
+
if (typeof startedAtMs === 'number') {
|
|
330
|
+
const existing = readResultStamp(file);
|
|
331
|
+
if (existing !== null && existing >= startedAtMs) return false;
|
|
332
|
+
}
|
|
333
|
+
atomic(file, JSON.stringify({ ...result, started_at_ms: startedAtMs, timestamp: new Date().toISOString() }));
|
|
334
|
+
return true;
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
const warning = 'could not write the optional update-result.json record';
|
|
338
|
+
console.error(`dalan: ${warning}`);
|
|
339
|
+
(result.warnings ??= []).push(warning);
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
const UPDATE_FAILURES = new Set(['rolled_back', 'rollback_failed', 'commit_uncertain']);
|
|
344
|
+
function failedUpdate(error, phase) {
|
|
345
|
+
const outcome = UPDATE_FAILURES.has(error.updateOutcome) ? error.updateOutcome : 'failed';
|
|
346
|
+
return { outcome, phase, error: `service update failed during ${phase.replaceAll('_', ' ')}` };
|
|
347
|
+
}
|
|
348
|
+
|
|
254
349
|
export async function updateService({ home, check = false, yes = false, retry = false }, seams = {}) {
|
|
350
|
+
// The stamp this operation started at orders its status write against a newer operation's.
|
|
351
|
+
const startedAtMs = Date.now();
|
|
255
352
|
if (check && retry) fail('--retry cannot be used with --check');
|
|
256
|
-
home =
|
|
353
|
+
home = resolveHome(home);
|
|
257
354
|
const latest = seams.latestRelease ?? defaultLatest, install = seams.installRelease ?? defaultInstall;
|
|
258
355
|
const probe = seams.probeService ?? defaultProbe, candidateProbe = seams.probeCandidate ?? defaultCandidate;
|
|
259
356
|
const control = seams.controlService ?? defaultControl, pruneVersions = seams.pruneVersions ?? prune;
|
|
260
357
|
const healthTimeoutMs = seams.healthTimeoutMs ?? HEALTH_TIMEOUT_MS;
|
|
261
358
|
if (!Number.isFinite(healthTimeoutMs) || healthTimeoutMs <= 0) fail('healthTimeoutMs must be a positive finite duration');
|
|
262
359
|
if (check) {
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
360
|
+
const checkFile = path.join(home, 'update-result.json');
|
|
361
|
+
let checked, phase = 'read_install';
|
|
362
|
+
try {
|
|
363
|
+
const receipt = adoptInstall(readReceipt(home).value, home), active = fs.existsSync(path.join(home, 'current')) ? fs.realpathSync(path.join(home, 'current')) : receipt.repo;
|
|
364
|
+
if (!active) fail('current service repository is missing');
|
|
365
|
+
const current = JSON.parse(fs.readFileSync(path.join(active, 'package.json'), 'utf8')).version;
|
|
366
|
+
phase = 'check_release';
|
|
367
|
+
const r = await latest(receipt); const forward = releaseVersion(r, current);
|
|
368
|
+
checked = { outcome: forward ? 'update_available' : 'up_to_date', current_version: current, latest_version: r.version };
|
|
369
|
+
return checked;
|
|
370
|
+
} catch (error) {
|
|
371
|
+
checked = failedUpdate(error, phase);
|
|
372
|
+
throw error;
|
|
373
|
+
} finally {
|
|
374
|
+
if (checked) {
|
|
375
|
+
// The check holds no lock while it waits on the registry, so an update may finish first. Take the
|
|
376
|
+
// update lock for this write, so the stamp read and the write cannot interleave with the update's write.
|
|
377
|
+
// When an update is already running, its own result supersedes this check, so the write is skipped.
|
|
378
|
+
let releaseCheckLock = null;
|
|
379
|
+
try { releaseCheckLock = acquireUpdateLock(home); } catch (error) {
|
|
380
|
+
if (!/already running/.test(error.message) && !/active in another/.test(error.message) && error.code !== 'session_busy') {
|
|
381
|
+
console.error('dalan: could not write the optional update-result.json record');
|
|
382
|
+
(checked.warnings ??= []).push('could not write the optional update-result.json record');
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
try { if (releaseCheckLock) recordResult(checkFile, checked, startedAtMs); }
|
|
386
|
+
finally { releaseCheckLock?.(); }
|
|
387
|
+
}
|
|
388
|
+
}
|
|
270
389
|
}
|
|
271
390
|
privateDir(home);
|
|
272
391
|
const releaseLock = acquireUpdateLock(home);
|
|
273
392
|
const resultFile = path.join(home, 'update-result.json');
|
|
274
|
-
let result, attempted;
|
|
393
|
+
let result, attempted, phase = 'recover';
|
|
275
394
|
try {
|
|
276
395
|
await recover(home, control, probe, healthTimeoutMs);
|
|
396
|
+
phase = 'read_install';
|
|
277
397
|
const { value: storedReceipt, file: receiptFile } = readReceipt(home);
|
|
278
398
|
const receipt = adoptInstall(storedReceipt, home);
|
|
279
399
|
let current = path.join(home, 'current');
|
|
@@ -281,19 +401,23 @@ export async function updateService({ home, check = false, yes = false, retry =
|
|
|
281
401
|
if (!oldRepo || !fs.existsSync(oldRepo)) fail('current service repository is missing');
|
|
282
402
|
const oldVersion = JSON.parse(fs.readFileSync(path.join(oldRepo, 'package.json'), 'utf8')).version;
|
|
283
403
|
const workers = actualWorkers(home);
|
|
404
|
+
phase = 'check_release';
|
|
284
405
|
const r = await latest(receipt), forward = releaseVersion(r, oldVersion);
|
|
285
406
|
if (!forward) { result = { outcome: 'up_to_date', current_version: oldVersion, latest_version: r.version }; return result; }
|
|
286
|
-
const failed = readFailed(home);
|
|
407
|
+
const failed = readFailed(home, { repo: oldRepo, version: oldVersion, receipt });
|
|
287
408
|
if (!retry && failed && failed.version === r.version && failed.integrity === r.dist.integrity) {
|
|
288
|
-
|
|
409
|
+
const reason = failed.outcome === 'commit_uncertain' ? 'has an uncertain earlier commit' : 'was rolled back earlier';
|
|
410
|
+
result = { outcome: 'skipped_failed_release', current_version: oldVersion, latest_version: r.version, failed_version: failed.version, message: `Release ${r.version} ${reason}; not retrying automatically. Run dalan service update --retry to try it again.` };
|
|
289
411
|
return result;
|
|
290
412
|
}
|
|
291
413
|
attempted = r;
|
|
414
|
+
phase = 'install';
|
|
292
415
|
const installed = await install(home, r);
|
|
293
416
|
const candidate = path.resolve(installed), versions = path.resolve(home, 'versions');
|
|
294
417
|
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');
|
|
295
418
|
const packageInfo = JSON.parse(fs.readFileSync(path.join(candidate, 'package.json'), 'utf8'));
|
|
296
419
|
if (packageInfo.name !== PACKAGE || packageInfo.version !== r.version) fail('installed candidate package identity does not match registry release');
|
|
420
|
+
phase = 'verify_candidate';
|
|
297
421
|
const base = await probe(home, receipt), legacy = base.legacy === true;
|
|
298
422
|
const configBeforeCandidate = configurationDigest(home, receipt);
|
|
299
423
|
const tested = await candidateProbe(home, receipt, candidate);
|
|
@@ -303,7 +427,7 @@ export async function updateService({ home, check = false, yes = false, retry =
|
|
|
303
427
|
const changedCatalog = !legacy && !catalogsEqual(base, tested, workers);
|
|
304
428
|
if (changedCatalog && !yes) {
|
|
305
429
|
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.' };
|
|
306
|
-
prune(home, oldVersion, r.version);
|
|
430
|
+
prune(home, oldVersion, r.version, receipt.repo);
|
|
307
431
|
return result;
|
|
308
432
|
}
|
|
309
433
|
// A catalog difference requires explicit consent; exact parity may proceed without it.
|
|
@@ -311,6 +435,7 @@ export async function updateService({ home, check = false, yes = false, retry =
|
|
|
311
435
|
const liveAgain = await probe(home, receipt);
|
|
312
436
|
if (liveAgain.version !== oldVersion || !legacy && !catalogsEqual(base, liveAgain, workers)) fail('live worker catalog changed during update; retry after connector refresh');
|
|
313
437
|
if (configurationDigest(home, receipt) !== digestBeforeRecheck || digestBeforeRecheck !== configBeforeCandidate) fail('service configuration changed during update; retry after connector refresh');
|
|
438
|
+
phase = 'switch';
|
|
314
439
|
// A macOS agent runs the package through the home's `current` link, so a switch needs no plist rewrite.
|
|
315
440
|
const unitFile = receipt.unit && receipt.platform !== 'darwin' ? unitPath(receipt, home) : null;
|
|
316
441
|
const txDir = path.join(home, 'update-backup'); privateDir(txDir);
|
|
@@ -327,9 +452,11 @@ export async function updateService({ home, check = false, yes = false, retry =
|
|
|
327
452
|
select(home, candidate);
|
|
328
453
|
if (unitFile) rewriteUnit(unitFile, current, home);
|
|
329
454
|
await control(receipt, 'daemon-reload'); await control(receipt, 'restart');
|
|
455
|
+
phase = 'health_check';
|
|
330
456
|
const live = await probeReady(probe, home, { ...receipt, repo: candidate }, healthTimeoutMs);
|
|
331
457
|
if (live.version !== r.version || !completeCatalogs(tested, live, workers) || !catalogsEqual(tested, live, workers)) fail('updated service health or worker catalogs failed');
|
|
332
|
-
|
|
458
|
+
phase = 'commit';
|
|
459
|
+
receipt.repo = candidate; receipt.version = r.version; receipt.release_integrity = r.dist.integrity;
|
|
333
460
|
atomic(receiptFile, JSON.stringify(receipt));
|
|
334
461
|
fs.rmSync(defaultPath(home, '.config/dot-bridge', 'service-catalog.json'), { force: true });
|
|
335
462
|
const committedTx = { ...tx, phase: 'committed' };
|
|
@@ -338,10 +465,11 @@ export async function updateService({ home, check = false, yes = false, retry =
|
|
|
338
465
|
let journal;
|
|
339
466
|
try { journal = JSON.parse(fs.readFileSync(path.join(home, 'update-transaction.json'), 'utf8')); }
|
|
340
467
|
catch { error.preserveCandidate = true; throw error; }
|
|
341
|
-
if (journal.phase === 'committed' && journal.home
|
|
468
|
+
if (journal.phase === 'committed' && sameHome(journal.home, home)) {
|
|
342
469
|
tx.phase = 'committed';
|
|
343
|
-
|
|
344
|
-
|
|
470
|
+
const cleanupWarnings = ['committed journal is visible but its durability check failed and recovery data was preserved'];
|
|
471
|
+
clearFailedReleaseMarker(home, cleanupWarnings);
|
|
472
|
+
result = { outcome: 'commit_uncertain', phase, previous_version: oldVersion, version: r.version, cleanup_warning: cleanupWarnings.join('; ') };
|
|
345
473
|
return result;
|
|
346
474
|
}
|
|
347
475
|
if (journal.phase !== 'switched') { error.preserveCandidate = true; throw error; }
|
|
@@ -349,23 +477,23 @@ export async function updateService({ home, check = false, yes = false, retry =
|
|
|
349
477
|
}
|
|
350
478
|
tx.phase = 'committed';
|
|
351
479
|
result = { outcome: 'updated', previous_version: oldVersion, version: r.version, ...(legacy ? { adopted_legacy_server: true } : {}) };
|
|
352
|
-
try { fs.rmSync(failedFile(home), { force: true }); } catch { /* stale record only skips the same release */ }
|
|
353
480
|
const cleanupWarnings = [];
|
|
354
|
-
|
|
355
|
-
try { fs.rmSync(
|
|
356
|
-
try {
|
|
481
|
+
clearFailedReleaseMarker(home, cleanupWarnings);
|
|
482
|
+
try { fs.rmSync(path.join(home, 'update-transaction.json'), { force: true }); } catch { cleanupWarnings.push('transaction marker cleanup failed'); }
|
|
483
|
+
try { fs.rmSync(txDir, { recursive: true, force: true }); } catch { cleanupWarnings.push('backup cleanup failed'); }
|
|
484
|
+
try { pruneVersions(home, r.version, oldVersion, receipt.repo); } catch { cleanupWarnings.push('version pruning failed'); }
|
|
357
485
|
if (cleanupWarnings.length) result.cleanup_warning = cleanupWarnings.join('; ');
|
|
358
486
|
} catch (error) {
|
|
359
487
|
if (error.preserveCandidate) {
|
|
360
488
|
const uncertain = new Error(`update commit state is uncertain; candidate and recovery data were preserved: ${error.message}`);
|
|
361
|
-
uncertain.updateOutcome = '
|
|
489
|
+
uncertain.updateOutcome = 'commit_uncertain';
|
|
362
490
|
throw uncertain;
|
|
363
491
|
}
|
|
364
492
|
let rollbackError;
|
|
365
493
|
try {
|
|
366
494
|
if (tx.phase === 'switched') validateSnapshot(tx);
|
|
367
|
-
await control(receipt, 'stop');
|
|
368
|
-
if (tx.phase === 'switched')
|
|
495
|
+
await control(receipt, 'stop');
|
|
496
|
+
if (tx.phase === 'switched') restoreFiles(home, tx);
|
|
369
497
|
await control(receipt, 'daemon-reload'); await control(receipt, 'restart');
|
|
370
498
|
const restored = await probeReady(probe, home, { ...receipt, repo: oldRepo }, healthTimeoutMs);
|
|
371
499
|
if (restored.version !== oldVersion || !legacy && !catalogsEqual(base, restored, workers)) fail('old service health verification failed');
|
|
@@ -377,23 +505,51 @@ export async function updateService({ home, check = false, yes = false, retry =
|
|
|
377
505
|
}
|
|
378
506
|
return result;
|
|
379
507
|
} catch (error) {
|
|
380
|
-
result =
|
|
381
|
-
if (attempted && (result.outcome
|
|
508
|
+
result = failedUpdate(error, phase);
|
|
509
|
+
if (attempted && UPDATE_FAILURES.has(result.outcome)) {
|
|
382
510
|
try { atomic(failedFile(home), JSON.stringify({ version: attempted.version, integrity: attempted.dist.integrity, outcome: result.outcome, timestamp: new Date().toISOString() })); } catch { /* best effort */ }
|
|
383
511
|
}
|
|
384
512
|
throw error;
|
|
385
513
|
} finally {
|
|
386
|
-
try { if (result)
|
|
514
|
+
try { if (result) recordResult(resultFile, result, startedAtMs); }
|
|
387
515
|
finally { releaseLock(); }
|
|
388
516
|
}
|
|
389
517
|
}
|
|
390
518
|
|
|
519
|
+
// Only outcomes persisted by updateService are accepted; recovery commands return their own ephemeral status.
|
|
520
|
+
const UPDATE_RESULT_OUTCOMES = new Set([
|
|
521
|
+
'update_available', 'up_to_date', 'skipped_failed_release', 'connector_refresh_required',
|
|
522
|
+
'updated', 'failed', 'rolled_back', 'rollback_failed', 'commit_uncertain',
|
|
523
|
+
]);
|
|
524
|
+
|
|
525
|
+
// Persisted fields written by updateService; do not publish arbitrary file keys.
|
|
526
|
+
const UPDATE_RESULT_FIELDS = [
|
|
527
|
+
'outcome', 'current_version', 'latest_version', 'candidate_version', 'failed_version',
|
|
528
|
+
'previous_version', 'version', 'connector_refresh_required', 'adopted_legacy_server',
|
|
529
|
+
'cleanup_warning', 'error', 'phase', 'message', 'timestamp',
|
|
530
|
+
];
|
|
531
|
+
|
|
391
532
|
export function serviceStatus({ home }) {
|
|
392
|
-
home =
|
|
533
|
+
home = resolveHome(home);
|
|
393
534
|
const { value: receipt } = readReceipt(home), current = path.join(home, 'current');
|
|
394
|
-
|
|
395
|
-
|
|
535
|
+
const repo = fs.existsSync(current) ? fs.realpathSync(current) : null;
|
|
536
|
+
const version = repo ? JSON.parse(fs.readFileSync(path.join(repo, 'package.json'), 'utf8')).version : receipt.version;
|
|
396
537
|
let last_result = null;
|
|
397
|
-
|
|
398
|
-
|
|
538
|
+
let raw;
|
|
539
|
+
try { raw = fs.readFileSync(path.join(home, 'update-result.json'), 'utf8'); }
|
|
540
|
+
catch (error) {
|
|
541
|
+
if (error.code !== 'ENOENT') last_result = { status: 'unavailable', reason: 'unreadable' };
|
|
542
|
+
}
|
|
543
|
+
if (raw !== undefined) {
|
|
544
|
+
try {
|
|
545
|
+
const result = JSON.parse(raw);
|
|
546
|
+
last_result = result && typeof result === 'object' && !Array.isArray(result) &&
|
|
547
|
+
Object.hasOwn(result, 'outcome') && UPDATE_RESULT_OUTCOMES.has(result.outcome)
|
|
548
|
+
? Object.fromEntries(UPDATE_RESULT_FIELDS.filter(key => Object.hasOwn(result, key)).map(key => [key, result[key]]))
|
|
549
|
+
: { status: 'unavailable', reason: 'malformed' };
|
|
550
|
+
} catch {
|
|
551
|
+
last_result = { status: 'unavailable', reason: 'malformed' };
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
return { version, auto_update: receipt.auto_update ?? false, last_result, failed_release: readFailed(home, { repo, version, receipt })?.version ?? null };
|
|
399
555
|
}
|