@dreamtree-org/harness-device 0.1.2 → 0.1.4

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/src/upgrade.js ADDED
@@ -0,0 +1,151 @@
1
+ // Upgrades without downtime. A new version is installed next to the running
2
+ // one (pkg.next), checked, swapped in with renames, and then applied by the
3
+ // NEW version's own install in graceful mode: scripts replaced atomically,
4
+ // only services whose definitions changed are restarted, and the tmux
5
+ // service, which holds every agent session, is never restarted. If anything
6
+ // fails, the previous version is swapped back and re-applied.
7
+ //
8
+ // Automatic upgrades: hd-heal calls `upgrade --auto --detach` every
9
+ // AUTO_UPGRADE_HOURS; AUTO_UPGRADE limits how far it goes (patch, minor, all,
10
+ // off). The work runs detached from the heal job (which an upgrade may reload).
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { spawnSync } from 'node:child_process';
15
+ import { PKG, capture } from './util.js';
16
+ import { event } from './state.js';
17
+ import { sample } from './resources.js';
18
+
19
+ export const POLICIES = ['off', 'patch', 'minor', 'all'];
20
+
21
+ const parse = (v) => String(v).replace(/^v/, '').split('-')[0].split('.').map((x) => Number(x) || 0);
22
+
23
+ /** -1, 0 or 1. Pre-release versions never count as newer. */
24
+ export function compare(a, b) {
25
+ const p = parse(a);
26
+ const q = parse(b);
27
+ for (let i = 0; i < 3; i++) if (p[i] !== q[i]) return p[i] < q[i] ? -1 : 1;
28
+ return 0;
29
+ }
30
+
31
+ /** Is moving from `from` to `to` within the policy? */
32
+ export function allowedBy(policy, from, to) {
33
+ if (compare(to, from) <= 0 || String(to).includes('-')) return false;
34
+ const [a, b] = [parse(from), parse(to)];
35
+ if (policy === 'all') return true;
36
+ if (policy === 'minor') return a[0] === b[0];
37
+ if (policy === 'patch') return a[0] === b[0] && a[1] === b[1];
38
+ return false;
39
+ }
40
+
41
+ const pkgDir = (root) => path.join(root, 'node_modules', ...PKG.name.split('/'));
42
+
43
+ /** Where the services' copy lives and whether it came from npm or a source folder. */
44
+ export function installed(ctx) {
45
+ const dir = pkgDir(ctx.paths.pkg);
46
+ if (!fs.existsSync(dir)) return { version: null, source: 'none' };
47
+ const source = fs.lstatSync(dir).isSymbolicLink() ? 'folder' : 'npm';
48
+ let version = null;
49
+ try { version = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version; } catch { /* broken */ }
50
+ return { version, source, dir };
51
+ }
52
+
53
+ export function latest(ctx, tag = 'latest') {
54
+ const v = capture('npm', ['view', `${PKG.name}@${tag}`, 'version'], { env: ctx.env, timeout: 30000 }).trim();
55
+ return /^\d+\.\d+\.\d+/.test(v) ? v : null;
56
+ }
57
+
58
+ export async function check(ctx, { to } = {}) {
59
+ const inst = installed(ctx);
60
+ const policy = POLICIES.includes(String(ctx.cfg.AUTO_UPGRADE)) ? String(ctx.cfg.AUTO_UPGRADE) : 'minor';
61
+ const target = to || latest(ctx);
62
+ const current = inst.version || PKG.version;
63
+ const out = { current, latest: target, policy, source: inst.source, available: !!target && compare(target, current) > 0 };
64
+ out.autoAllowed = out.available && inst.source === 'npm' && allowedBy(policy, current, target);
65
+ if (!target) out.note = 'could not reach the npm registry';
66
+ else if (inst.source === 'folder') out.note = 'installed from a source folder: upgrade by updating that folder and running install';
67
+ else if (out.available && !out.autoAllowed) out.note = `newer version, outside AUTO_UPGRADE=${policy}: upgrade it yourself (harness-device upgrade)`;
68
+ return out;
69
+ }
70
+
71
+ function lock(ctx) {
72
+ const f = path.join(ctx.paths.state, 'upgrade.lock');
73
+ fs.mkdirSync(ctx.paths.state, { recursive: true });
74
+ try {
75
+ fs.writeFileSync(f, String(process.pid), { flag: 'wx' });
76
+ } catch {
77
+ const pid = Number(fs.readFileSync(f, 'utf8'));
78
+ let alive = false;
79
+ try { process.kill(pid, 0); alive = true; } catch { /* gone */ }
80
+ if (alive) throw new Error(`An upgrade is already running (pid ${pid}).`);
81
+ fs.writeFileSync(f, String(process.pid));
82
+ }
83
+ return () => fs.rmSync(f, { force: true });
84
+ }
85
+
86
+ const npmRun = (ctx, args) => spawnSync('npm', args, { env: ctx.env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 15 * 60000 });
87
+
88
+ /** Apply a version already in pkg: its own install, graceful, no system packages. */
89
+ function applyInstalled(ctx, log) {
90
+ const cli = path.join(pkgDir(ctx.paths.pkg), 'bin', 'harness-device.js');
91
+ const r = spawnSync(process.execPath, [cli, 'install', '--skip-system', '--skip-pkg', '--graceful'], { env: ctx.env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 15 * 60000 });
92
+ log((r.stdout || '') + (r.stderr || ''));
93
+ return r.status === 0;
94
+ }
95
+
96
+ /**
97
+ * Install `to` next to the running copy, swap it in, apply it gracefully.
98
+ * Rolls back to the previous copy if installing or applying fails.
99
+ */
100
+ export async function upgrade(ctx, { to, auto = false, log = () => {} } = {}) {
101
+ const c = await check(ctx, { to });
102
+ if (!c.latest) throw new Error('Could not reach the npm registry.');
103
+ if (c.source === 'folder') throw new Error('This device runs harness-device from a source folder; update the folder and run install instead.');
104
+ if (!c.available) return { upgraded: false, ...c, note: `already on ${c.current}` };
105
+ if (auto && !c.autoAllowed) return { upgraded: false, ...c };
106
+
107
+ // Never upgrade on top of a busy device: the next check tries again.
108
+ const s = await sample(ctx);
109
+ if (s.level === 'critical' || (auto && s.level === 'high')) {
110
+ event(ctx, `upgrade to ${c.latest} deferred: device ${s.level} (${s.reasons.join('; ')})`);
111
+ return { upgraded: false, deferred: true, ...c, note: `deferred, device ${s.level}: ${s.reasons.join('; ')}` };
112
+ }
113
+
114
+ const unlock = lock(ctx);
115
+ const p = ctx.paths;
116
+ const next = `${p.pkg}.next`;
117
+ const prev = `${p.pkg}.prev`;
118
+ try {
119
+ log(`upgrade ${c.current} → ${c.latest}: installing next to the running copy`);
120
+ fs.rmSync(next, { recursive: true, force: true });
121
+ fs.mkdirSync(next, { recursive: true });
122
+ const r = npmRun(ctx, ['install', '--prefix', next, '--no-fund', '--no-audit', '--omit=dev', `${PKG.name}@${c.latest}`]);
123
+ if (r.status !== 0) throw new Error(`npm install failed: ${(r.stderr || '').trim().split('\n').slice(-3).join(' ')}`);
124
+ const got = JSON.parse(fs.readFileSync(path.join(pkgDir(next), 'package.json'), 'utf8')).version;
125
+ if (got !== c.latest) throw new Error(`installed ${got}, expected ${c.latest}`);
126
+ const v = spawnSync(process.execPath, [path.join(pkgDir(next), 'bin', 'harness-device.js'), '--version'], { encoding: 'utf8', env: ctx.env });
127
+ if (v.status !== 0 || v.stdout.trim() !== c.latest) throw new Error('the new version does not start');
128
+
129
+ // Swap: the bin/ links point at pkg/node_modules/.bin, so they follow.
130
+ fs.rmSync(prev, { recursive: true, force: true });
131
+ fs.renameSync(p.pkg, prev);
132
+ fs.renameSync(next, p.pkg);
133
+ log('swapped in; applying (graceful: running sessions and unchanged services are left alone)');
134
+ if (!applyInstalled(ctx, log)) {
135
+ log('applying the new version failed; rolling back');
136
+ fs.renameSync(p.pkg, `${p.pkg}.failed-${c.latest}`);
137
+ fs.renameSync(prev, p.pkg);
138
+ applyInstalled(ctx, log);
139
+ event(ctx, `upgrade to ${c.latest} failed and was rolled back to ${c.current}`);
140
+ throw new Error(`Upgrade to ${c.latest} failed; rolled back to ${c.current}. See logs/upgrade.log.`);
141
+ }
142
+ event(ctx, `upgraded harness-device ${c.current} → ${c.latest}${auto ? ' (automatic)' : ''}`);
143
+ return { upgraded: true, from: c.current, to: c.latest, note: 'sessions keep running; each picks up the new device tools when it next restarts' };
144
+ } catch (e) {
145
+ fs.rmSync(next, { recursive: true, force: true });
146
+ if (!/rolled back/.test(e.message)) event(ctx, `upgrade to ${c.latest} failed: ${e.message}`);
147
+ throw e;
148
+ } finally {
149
+ unlock();
150
+ }
151
+ }