@hmharness/cli 0.23.28 → 0.23.30

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,248 @@
1
+ #!/usr/bin/env node
2
+ // heal-tree.cjs — self-healing completeness check for the hmharness board tree.
3
+ // TWIN COPY: scripts/heal-tree.cjs (repo installs) and
4
+ // packages/cli/board/heal-tree.cjs (ships in the npm package). Keep both in
5
+ // sync. install-kaihongos.cjs copies this file to <HMH_HOME>/heal-tree.cjs
6
+ // and the launcher hook (see installHealLayer) runs it before every start.
7
+ //
8
+ // WHY: a board auto-update swaps node_modules wholesale; any incompleteness
9
+ // in the package set — a lagging hardcoded list, a rename or split between
10
+ // releases — bricks the next launch with ERR_MODULE_NOT_FOUND. Repairs made
11
+ // INSIDE the tree are wiped by the same swap, so the healer lives outside it
12
+ // (in ~/.hmharness, the state dir no update touches).
13
+ //
14
+ // HOW: discover the required @hmharness/* set from the tree itself —
15
+ // 1. BFS over installed package.json "dependencies" (declared graph)
16
+ // 2. static scan of built code for '@hmharness/<name>' imports (catches
17
+ // undeclared-but-imported packages)
18
+ // then download any missing tarball from registry.npmjs.org at the version
19
+ // the tree is on; offline, restore from node_modules.bak at the same version.
20
+ // No hardcoded package list: immune to upstream growth. As a second layer it
21
+ // also re-extends the PACKAGES list of the embedded board installer, so the
22
+ // NEXT auto-update itself installs a complete tree.
23
+ //
24
+ // Exit 0 = tree verified complete. Exit 1 = could not complete (retried on
25
+ // the next launch). The launcher never blocks on this script.
26
+ const fs = require('fs');
27
+ const path = require('path');
28
+ const https = require('https');
29
+ const { spawnSync } = require('child_process');
30
+
31
+ // Board home is overridable so the same script serves non-default --home=
32
+ // installs; the launcher hook exports HMH_BOARD_HOME before invoking it.
33
+ const BOARD_HOME = process.env.HMH_BOARD_HOME || '/data/local/home';
34
+ const HROOT = path.join(BOARD_HOME, '.local', 'hmharness');
35
+ const NM = path.join(HROOT, 'node_modules', '@hmharness');
36
+ const HMH_HOME = path.join(BOARD_HOME, '.hmharness');
37
+ const LOG = path.join(HMH_HOME, 'heal.log');
38
+ const REG = 'https://registry.npmjs.org';
39
+ const MAX_ROUNDS = 6;
40
+
41
+ function log(msg) {
42
+ const line = '[' + new Date().toISOString() + '] ' + msg;
43
+ try { fs.appendFileSync(LOG, line + '\n'); } catch { /* best-effort */ }
44
+ }
45
+
46
+ // ---------- registry helpers (Node core only, busybox for tar) --------------
47
+ function download(url, file) {
48
+ return new Promise((resolve, reject) => {
49
+ let attempt = 0;
50
+ const go = () => {
51
+ attempt++;
52
+ const req = https.request(new URL(url), { headers: { 'User-Agent': 'hmh-heal' }, timeout: 45000 }, (res) => {
53
+ if (res.statusCode !== 200) { res.resume(); reject(new Error(url + ' -> ' + res.statusCode)); return; }
54
+ const out = fs.createWriteStream(file);
55
+ res.pipe(out);
56
+ out.on('finish', () => out.close(resolve));
57
+ out.on('error', reject);
58
+ });
59
+ req.on('timeout', () => { req.destroy(); retry(); });
60
+ req.on('error', (e) => {
61
+ if (attempt < 8 && /EAI_AGAIN|ENOTFOUND|ECONNRESET|ETIMEDOUT/.test(e.code || '')) setTimeout(retry, 2000 * attempt);
62
+ else reject(e);
63
+ });
64
+ req.end();
65
+ };
66
+ const retry = () => { if (attempt < 8) go(); else reject(new Error('retries exhausted: ' + url)); };
67
+ go();
68
+ });
69
+ }
70
+
71
+ function extract(tgz, dest) {
72
+ fs.rmSync(dest, { recursive: true, force: true });
73
+ fs.mkdirSync(dest, { recursive: true });
74
+ const cmds = [
75
+ ['busybox', ['tar', '-xzf', tgz, '-C', dest, '--strip-components=1']],
76
+ ['tar', ['-xzf', tgz, '-C', dest, '--strip-components=1']],
77
+ ];
78
+ for (const [bin, args] of cmds) {
79
+ const r = spawnSync(bin, args, { encoding: 'utf8' });
80
+ if (r.status === 0) return;
81
+ }
82
+ throw new Error('no usable tar');
83
+ }
84
+
85
+ /** Offline fallback: copy a package from the previous tree (node_modules.bak)
86
+ * when the registry is unreachable, but ONLY at the exact same version. */
87
+ function restoreFromBak(name, ver) {
88
+ const bakPkg = path.join(HROOT, 'node_modules.bak', '@hmharness', name, 'package.json');
89
+ try {
90
+ const bak = JSON.parse(fs.readFileSync(bakPkg, 'utf8'));
91
+ if (bak.version !== ver) return false;
92
+ fs.cpSync(path.dirname(bakPkg), path.join(NM, name), { recursive: true });
93
+ return true;
94
+ } catch { return false; }
95
+ }
96
+
97
+ // ---------- discovery -------------------------------------------------------
98
+ function readPkg(name) {
99
+ try { return JSON.parse(fs.readFileSync(path.join(NM, name, 'package.json'), 'utf8')); }
100
+ catch { return null; }
101
+ }
102
+
103
+ /** All @hmharness/* names referenced by the tree: declared deps (BFS) plus
104
+ * imports found in built code (catches undeclared imports). */
105
+ function discoverRequired() {
106
+ const have = new Set(fs.readdirSync(NM));
107
+ const declared = new Map(); // name -> Set of required version strings
108
+ const queue = ['cli'];
109
+ const seen = new Set();
110
+ while (queue.length) {
111
+ const n = queue.shift();
112
+ if (seen.has(n) || !have.has(n)) continue;
113
+ seen.add(n);
114
+ const deps = (readPkg(n) || {}).dependencies || {};
115
+ for (const [dep, ver] of Object.entries(deps)) {
116
+ if (!dep.startsWith('@hmharness/')) continue;
117
+ const sub = dep.slice(11);
118
+ if (!declared.has(sub)) declared.set(sub, new Set());
119
+ declared.get(sub).add(String(ver));
120
+ if (have.has(sub) && !seen.has(sub)) queue.push(sub);
121
+ }
122
+ }
123
+ // static import scan over built code (dist/, board/, root .js) for BOTH
124
+ // declared and undeclared references
125
+ const imported = new Set();
126
+ const scanDir = (dir) => {
127
+ let entries;
128
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
129
+ for (const e of entries) {
130
+ const p = path.join(dir, e.name);
131
+ if (e.isDirectory()) { if (e.name !== 'node_modules') scanDir(p); continue; }
132
+ if (!e.name.endsWith('.js') && !e.name.endsWith('.cjs') && !e.name.endsWith('.mjs')) continue;
133
+ let src;
134
+ try { src = fs.readFileSync(p, 'utf8'); } catch { continue; }
135
+ for (const m of src.matchAll(/@hmharness\/([a-z0-9][a-z0-9.-]*)/g)) imported.add(m[1]);
136
+ }
137
+ };
138
+ for (const n of have) scanDir(path.join(NM, n));
139
+ return { have, declared, imported };
140
+ }
141
+
142
+ /** Best version for a missing package: prefer the tree's cli version (first-party
143
+ * packages release in lockstep), then any explicitly declared version, then
144
+ * the max declared. */
145
+ function pickVersion(name, declared, cliVer) {
146
+ const vs = declared.get(name) || new Set();
147
+ if (vs.has(cliVer)) return cliVer;
148
+ const clean = [...vs].map((v) => v.replace(/[^0-9.]/g, '')).filter(Boolean).sort((a, b) => {
149
+ const pa = a.split('.').map(Number), pb = b.split('.').map(Number);
150
+ for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
151
+ return 0;
152
+ });
153
+ return clean[clean.length - 1] || cliVer;
154
+ }
155
+
156
+ // ---------- layer 2: patch the embedded installer's package list ------------
157
+ function patchEmbeddedInstaller(required) {
158
+ const inst = path.join(NM, 'cli', 'board', 'install-kaihongos.cjs');
159
+ if (!fs.existsSync(inst)) return;
160
+ let src;
161
+ try { src = fs.readFileSync(inst, 'utf8'); } catch { return; }
162
+ const m = src.match(/const PACKAGES = \[([^\]]*)\]/);
163
+ if (!m) return;
164
+ const cur = new Set([...m[1].matchAll(/'([a-z0-9-]+)'/g)].map((x) => x[1]));
165
+ const need = new Set([...cur, ...required]);
166
+ need.delete('cli');
167
+ if (need.size === cur.size - (cur.has('cli') ? 1 : 0)) return; // nothing new
168
+ const names = ['cli', ...[...need].sort()];
169
+ const arr = "const PACKAGES = [" + names.map((n) => "'" + n + "'").join(', ') + "];";
170
+ const next = src.replace(/const PACKAGES = \[[^\]]*\]/, arr +
171
+ '\n// (list auto-extended by heal-tree.cjs: registry deps + code imports)');
172
+ // write only when it still parses (write to a .cjs temp — node --check
173
+ // rejects unknown extensions — then check and swap)
174
+ try {
175
+ const tmp = inst + '.heal.cjs';
176
+ fs.writeFileSync(tmp, next);
177
+ const c2 = spawnSync(process.execPath, ['--check', tmp], { encoding: 'utf8' });
178
+ if (c2.status === 0) { fs.rmSync(inst, { force: true }); fs.renameSync(tmp, inst); log('patched embedded installer PACKAGES -> ' + names.length + ' packages'); }
179
+ else { fs.rmSync(tmp, { force: true }); log('warn: embedded installer patch failed --check (' + String((c2.stderr || '')).split('\n')[0].slice(0, 120) + '), left stock'); }
180
+ } catch (e) { log('warn: could not patch embedded installer: ' + e.message); }
181
+ }
182
+
183
+ // ---------- main ------------------------------------------------------------
184
+ (async () => {
185
+ // keep the log bounded
186
+ try { const st = fs.statSync(LOG); if (st.size > 256 * 1024) fs.rmSync(LOG); } catch { /* new */ }
187
+ // single-instance lock (5 min staleness). NOTE: exit via process.exitCode +
188
+ // return — process.exit() skips finally and would leak the lock dir.
189
+ const lock = path.join(HMH_HOME, '.heal.lock');
190
+ try {
191
+ const st = fs.statSync(lock);
192
+ if (Date.now() - st.mtimeMs < 5 * 60_000) { log('another heal is running, skipping (stamp untouched)'); process.exit(1); }
193
+ } catch { /* no lock */ }
194
+ fs.rmSync(lock, { recursive: true, force: true });
195
+ try { fs.mkdirSync(lock); } catch { /* ok */ }
196
+
197
+ let exitCode = 1;
198
+ try {
199
+ if (!fs.existsSync(path.join(NM, 'cli'))) {
200
+ log('FATAL: cli package missing entirely — run the board installer manually');
201
+ return;
202
+ }
203
+ const cliVer = readPkg('cli').version;
204
+ log('heal start · tree @' + cliVer);
205
+
206
+ let installedTotal = 0;
207
+ for (let round = 0; round < MAX_ROUNDS; round++) {
208
+ const { have, declared, imported } = discoverRequired();
209
+ const missing = [...new Set([...declared.keys(), ...imported])].filter((n) => !have.has(n));
210
+ if (missing.length === 0) {
211
+ // complete: patch the embedded installer so the NEXT auto-update
212
+ // itself installs a complete tree (layer 2), then report success
213
+ patchEmbeddedInstaller(new Set([...declared.keys(), ...imported]));
214
+ log('tree complete (' + have.size + ' first-party packages)' + (installedTotal ? ' · installed ' + installedTotal + ' this run' : ''));
215
+ exitCode = 0;
216
+ return;
217
+ }
218
+ let progressed = false;
219
+ let networkFailed = false;
220
+ for (const name of missing) {
221
+ const ver = pickVersion(name, declared, cliVer);
222
+ const tgz = path.join(HROOT, '.heal.tgz');
223
+ log('missing ' + name + ' -> installing @' + ver);
224
+ try {
225
+ await download(REG + '/@hmharness/' + name + '/-/' + name + '-' + ver + '.tgz', tgz);
226
+ extract(tgz, path.join(NM, name));
227
+ const got = readPkg(name);
228
+ if (!got || got.version !== ver) throw new Error('unpacked ' + (got && got.version) + ' != ' + ver);
229
+ log('installed ' + name + '@' + ver);
230
+ installedTotal++; progressed = true;
231
+ } catch (e) {
232
+ const notFound = /-> 404/.test(e.message);
233
+ log((notFound ? 'warn: ' : 'error: ') + name + '@' + ver + ': ' + e.message.slice(0, 140));
234
+ if (notFound) continue; // scan-only overmatch: ignore
235
+ // network failure: try the previous tree at the same version, else
236
+ // keep going — other packages may still download fine
237
+ networkFailed = true;
238
+ if (restoreFromBak(name, ver)) { log('restored ' + name + '@' + ver + ' from node_modules.bak (offline)'); installedTotal++; progressed = true; }
239
+ }
240
+ }
241
+ if (!progressed) { log('no progress this round' + (networkFailed ? ' (network unreachable — will retry next launch)' : '')); return; }
242
+ }
243
+ log('rounds exhausted');
244
+ } finally {
245
+ try { fs.rmdirSync(lock); } catch { /* already gone */ }
246
+ }
247
+ process.exitCode = exitCode;
248
+ })();
@@ -1,264 +1,352 @@
1
- #!/usr/bin/env node
2
- // install-kaihongos.cjs — one-command board installer for @hmharness/cli on
3
- // TWIN COPY: scripts/install-kaihongos.cjs (repo installs) and
4
- // packages/cli/board/install-kaihongos.cjs (ships in the npm package - the
5
- // board auto-update channel runs THIS one, settled design T28). Keep both
6
- // in sync when bumping FALLBACK_PINS.
7
- // KaihongOS / OpenHarmony 5.0 boards (no npm, no Python, read-only rootfs).
8
- //
9
- // What it does (idempotent, re-run any time):
10
- // 1. locates a usable Node >= 22 (the running one, or known board paths)
11
- // 2. resolves the @hmharness/* version set from registry.npmjs.org
12
- // (offline fallback: known-good pins below)
13
- // 3. downloads the 10 first-party tarballs and unpacks them under
14
- // <BOARD_HOME>/.local/hmharness/node_modules (staged, verified, swapped)
15
- // 4. writes a hardened launcher and installs it into THREE locations:
16
- // <BOARD_HOME>/.local/bin/hmh (user path, always writable)
17
- // /usr/local/bin/hmh (default PATH on classic shells)
18
- // /system/bin/hmh (read-only rootfs, remount dance;
19
- // ALSO visible inside isolated
20
- // tmpfs mount-namespace terminals
21
- // where /bin -> /system/bin)
22
- // 5. first run: `hmh init` if config.json is missing
23
- //
24
- // Usage:
25
- // node install-kaihongos.cjs # install/upgrade to latest
26
- // node install-kaihongos.cjs --bin-only # only (re)write launchers
27
- // node install-kaihongos.cjs --home=/x # non-default board home
28
- //
29
- // Only Node core modules are used; tar extraction uses busybox tar.
30
- const fs = require('fs');
31
- const path = require('path');
32
- const https = require('https');
33
- const { spawnSync } = require('child_process');
34
-
35
- // ---------- board constants -------------------------------------------------
36
- let BOARD_HOME = '/data/local/home'; // KaihongOS board home
37
- let BIN_ONLY = false;
38
-
39
- for (const a of process.argv.slice(2)) {
40
- if (a.startsWith('--home=')) BOARD_HOME = a.slice(7);
41
- else if (a === '--bin-only') BIN_ONLY = true;
42
- else { console.error('unknown arg:', a); process.exit(2); }
43
- }
44
-
45
- const ROOT = path.join(BOARD_HOME, '.local', 'hmharness');
46
- const NM = path.join(ROOT, 'node_modules');
47
- const HMH_HOME = path.join(BOARD_HOME, '.hmharness');
48
- const REG = 'https://registry.npmjs.org';
49
- const PACKAGES = ['cli', 'web', 'agent', 'kernel', 'sandbox', 'evolution',
50
- 'domain-ops', 'evaluation', 'observability', 'domain-harmony'];
51
-
52
- // Known-good pin set (offline fallback when the registry is unreachable).
1
+ #!/usr/bin/env node
2
+ // install-kaihongos.cjs — one-command board installer for @hmharness/cli on
3
+ // TWIN COPY: scripts/install-kaihongos.cjs (repo installs) and
4
+ // packages/cli/board/install-kaihongos.cjs (ships in the npm package - the
5
+ // board auto-update channel runs THIS one, settled design T28). Keep both
6
+ // in sync when bumping FALLBACK_PINS.
7
+ // KaihongOS / OpenHarmony 5.0 boards (no npm, no Python, read-only rootfs).
8
+ //
9
+ // What it does (idempotent, re-run any time):
10
+ // 1. locates a usable Node >= 22 (the running one, or known board paths)
11
+ // 2. resolves the @hmharness/* version set from registry.npmjs.org
12
+ // (offline fallback: known-good pins below)
13
+ // 3. downloads the first-party tarballs and unpacks them under
14
+ // <BOARD_HOME>/.local/hmharness/node_modules (staged, verified, swapped)
15
+ // 4. writes a hardened launcher and installs it into THREE locations:
16
+ // <BOARD_HOME>/.local/bin/hmh (user path, always writable)
17
+ // /usr/local/bin/hmh (default PATH on classic shells)
18
+ // /system/bin/hmh (read-only rootfs, remount dance;
19
+ // ALSO visible inside isolated
20
+ // tmpfs mount-namespace terminals
21
+ // where /bin -> /system/bin)
22
+ // 5. installs the SELF-HEAL layer (heal-tree.cjs + a launcher-sourced hook):
23
+ // the package set below is a FLOOR, extendHeal covers the rest — see
24
+ // "why the heal layer exists" above installHealLayer()
25
+ // 6. first run: `hmh init` if config.json is missing
26
+ //
27
+ // Usage:
28
+ // node install-kaihongos.cjs # install/upgrade to latest
29
+ // node install-kaihongos.cjs --bin-only # only (re)write launchers+heal
30
+ // node install-kaihongos.cjs --home=/x # non-default board home
31
+ //
32
+ // Only Node core modules are used; tar extraction uses busybox tar.
33
+ const fs = require('fs');
34
+ const path = require('path');
35
+ const https = require('https');
36
+ const { spawnSync } = require('child_process');
37
+
38
+ // ---------- board constants -------------------------------------------------
39
+ let BOARD_HOME = '/data/local/home'; // KaihongOS board home
40
+ let BIN_ONLY = false;
41
+
42
+ for (const a of process.argv.slice(2)) {
43
+ if (a.startsWith('--home=')) BOARD_HOME = a.slice(7);
44
+ else if (a === '--bin-only') BIN_ONLY = true;
45
+ else { console.error('unknown arg:', a); process.exit(2); }
46
+ }
47
+
48
+ const ROOT = path.join(BOARD_HOME, '.local', 'hmharness');
49
+ const NM = path.join(ROOT, 'node_modules');
50
+ const HMH_HOME = path.join(BOARD_HOME, '.hmharness');
51
+ const REG = 'https://registry.npmjs.org';
52
+ // FLOOR list only. resolveVersions() unions this with whatever the latest cli
53
+ // DECLARES as first-party deps, so new first-party packages are picked up
54
+ // without editing this file — the historical failure mode was exactly that
55
+ // lag: the list said 10 while cli had grown to 15 (cognitive, environments,
56
+ // lsp, browser, extension ...), every auto-update shipped an incomplete tree
57
+ // and the next launch died with ERR_MODULE_NOT_FOUND.
58
+ let PACKAGES = ['cli', 'web', 'agent', 'kernel', 'sandbox', 'evolution',
59
+ 'domain-ops', 'evaluation', 'observability', 'domain-harmony',
60
+ 'cognitive', 'environments', 'lsp', 'browser', 'extension'];
61
+
62
+ // Known-good pin set (offline fallback when the registry is unreachable).
63
+ // The release bot keeps versions synced; the NAMES must cover the full
64
+ // first-party set so the offline path cannot produce an incomplete tree.
53
65
  const FALLBACK_PINS = {
54
- cli: '0.23.28', web: '0.23.28', agent: '0.23.28', kernel: '0.23.28',
55
- sandbox: '0.23.28', evolution: '0.23.28', 'domain-ops': '0.23.28',
56
- evaluation: '0.23.28', observability: '0.23.28', 'domain-harmony': '0.23.28',
57
- };
58
-
59
- // ---------- helpers ---------------------------------------------------------
60
- function log(msg) { console.log(msg); }
61
-
62
- function httpsJSON(url, timeoutMs) {
63
- return new Promise((resolve, reject) => {
64
- const req = https.request(new URL(url), { headers: { 'User-Agent': 'hmh-kaihongos-installer' }, timeout: timeoutMs || 20000 }, (res) => {
65
- if (res.statusCode !== 200) { res.resume(); reject(new Error(url + ' -> ' + res.statusCode)); return; }
66
- const chunks = [];
67
- res.on('data', (c) => chunks.push(c));
68
- res.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch (e) { reject(e); } });
69
- });
70
- req.on('timeout', () => { req.destroy(new Error('timeout')); });
71
- req.on('error', reject);
72
- req.end();
73
- });
74
- }
75
-
76
- function download(url, file) {
77
- return new Promise((resolve, reject) => {
78
- let attempt = 0;
79
- function go() {
80
- attempt++;
81
- const req = https.request(new URL(url), { headers: { 'User-Agent': 'hmh-kaihongos-installer' }, timeout: 30000 }, (res) => {
82
- if (res.statusCode !== 200) { res.resume(); reject(new Error(url + ' -> ' + res.statusCode)); return; }
83
- const out = fs.createWriteStream(file);
84
- res.pipe(out);
85
- out.on('finish', () => out.close(resolve));
86
- out.on('error', reject);
87
- });
88
- req.on('timeout', () => { req.destroy(); retry(); });
89
- req.on('error', (e) => {
90
- if (attempt < 10 && /EAI_AGAIN|ENOTFOUND|ECONNRESET|ETIMEDOUT/.test(e.code || '')) setTimeout(retry, 1500 * attempt);
91
- else reject(e);
92
- });
93
- req.end();
94
- }
95
- function retry() { if (attempt < 10) go(); else reject(new Error('retries exhausted: ' + url)); }
96
- go();
97
- });
98
- }
99
-
100
- function extract(tgz, dest) {
101
- fs.mkdirSync(dest, { recursive: true });
102
- // busybox tar is present on KaihongOS / OpenHarmony boards and understands
103
- // --strip-components. (GNU/toybox tar also fine if busybox is missing.)
104
- const cmds = [
105
- ['busybox', ['tar', '-xzf', tgz, '-C', dest, '--strip-components=1']],
106
- ['tar', ['-xzf', tgz, '-C', dest, '--strip-components=1']],
107
- ];
108
- for (const [bin, args] of cmds) {
109
- const r = spawnSync(bin, args, { encoding: 'utf8' });
110
- if (r.status === 0) return;
111
- if (r.error && r.error.code !== 'ENOENT') log(' warn: ' + bin + ' tar: ' + (r.stderr || r.error.message).slice(0, 120));
112
- }
113
- throw new Error('no usable tar (tried busybox tar, tar)');
114
- }
115
-
116
- async function resolveVersions() {
117
- log('resolving latest @hmharness/cli from registry ...');
118
- const meta = await httpsJSON(REG + '/@hmharness/cli');
119
- const cliLatest = meta['dist-tags'].latest;
120
- const deps = (meta.versions[cliLatest].dependencies) || {};
121
- const pins = { cli: cliLatest };
122
- for (const n of PACKAGES.slice(1)) {
123
- const want = deps['@hmharness/' + n];
124
- if (want && want !== '*') { pins[n] = want.replace(/[^0-9.]/g, ''); continue; }
125
- const m = await httpsJSON(REG + '/@hmharness/' + n);
126
- pins[n] = m['dist-tags'].latest;
127
- }
128
- return pins;
129
- }
130
-
131
- // ---------- node discovery --------------------------------------------------
132
- function findNode() {
133
- const cands = [process.execPath,
134
- path.join(BOARD_HOME, 'dsh-pack/node/bin/node'),
135
- path.join(BOARD_HOME, '.ohos/node/bin/node'),
136
- '/usr/local/bin/node', '/usr/bin/node', '/system/bin/node'];
137
- for (const c of cands) {
138
- try {
139
- fs.accessSync(c, fs.constants.X_OK);
140
- const v = spawnSync(c, ['--version'], { encoding: 'utf8' });
141
- if (v.status === 0) { const maj = parseInt((v.stdout || '').replace('v', ''), 10); if (maj >= 22) return c; }
142
- } catch (_) { /* next */ }
143
- }
144
- return null;
145
- }
146
-
147
- // ---------- launcher --------------------------------------------------------
148
- function launcherSource(nodeBin) {
149
- return [
150
- '#!/system/bin/sh',
151
- '# hmh launcher — KaihongOS board install (generated by install-kaihongos.cjs)',
152
- '# Board layout is fixed under ' + BOARD_HOME + ', independent of caller HOME/PATH.',
153
- 'HROOT="' + ROOT + '"',
154
- 'HNODE="' + nodeBin + '"',
155
- '[ -x "$HNODE" ] || for c in node ' + BOARD_HOME + '/dsh-pack/node/bin/node ' + BOARD_HOME + '/.ohos/node/bin/node; do',
156
- ' [ -x "$c" ] && HNODE="$c" && break',
157
- 'done',
158
- '# optional board-wide secrets file (edit or remove — keys normally live in config.json)',
159
- '[ -f ' + BOARD_HOME + '/.config/apikeys.env ] && . ' + BOARD_HOME + '/.config/apikeys.env',
160
- '# board shells run with HOME=/ — force a real writable HOME and a stable state dir',
161
- '[ -z "${HMH_HOME:-}" ] && export HMH_HOME="' + HMH_HOME + '"',
162
- 'export HOME="' + BOARD_HOME + '"',
163
- 'export NODE_ALLOW_JIT="${NODE_ALLOW_JIT:-1}"',
164
- '# drop --jitless inherited from sandbox profiles; board root shell can JIT',
165
- 'NODE_OPTIONS="$(echo "${NODE_OPTIONS:-}" | sed \'s|--jitless||g; s/ */ /g\')"',
166
- 'NODE_OPTIONS="$(echo "$NODE_OPTIONS" | sed \'s/^ *//;s/ *$//\')"',
167
- '[ -n "$NODE_OPTIONS" ] && export NODE_OPTIONS',
168
- '# optional DevEco-layout toolchain shims (hvigorw / ohpm)',
169
- '[ -z "${HM_DEVECO_HOME:-}" ] && [ -d ' + BOARD_HOME + '/.local/hm-devtools ] && export HM_DEVECO_HOME="' + BOARD_HOME + '/.local/hm-devtools"',
170
- 'exec "$HNODE" "$HROOT/node_modules/@hmharness/cli/dist/main.js" "$@"',
171
- '',
172
- ].join('\n');
173
- }
174
-
175
- function writeLauncher(nodeBin) {
176
- const src = launcherSource(nodeBin);
177
- const userBin = path.join(BOARD_HOME, '.local', 'bin');
178
- fs.mkdirSync(userBin, { recursive: true });
179
- fs.writeFileSync(path.join(userBin, 'hmh'), src);
180
- fs.chmodSync(path.join(userBin, 'hmh'), 0o755);
181
- log('launcher: ' + path.join(userBin, 'hmh'));
182
-
183
- // System locations live on the read-only rootfs — remount rw, copy, restore ro.
184
- // /system/bin matters most: isolated tmpfs-namespace terminals (ttyd web
185
- // terminals, containers) see no /usr at all, but /bin -> /system/bin + /data.
186
- for (const sysBin of ['/usr/local/bin', '/system/bin']) {
187
- try { fs.mkdirSync(sysBin, { recursive: true }); } catch (_) { /* exists */ }
188
- const target = path.join(sysBin, 'hmh');
189
- const rw = spawnSync('mount', ['-o', 'remount,rw', '/'], { encoding: 'utf8' });
190
- try {
191
- fs.writeFileSync(target, src);
192
- fs.chmodSync(target, 0o755);
193
- log('launcher: ' + target + (rw.status === 0 ? ' (rootfs remounted rw then ro)' : ''));
194
- } catch (e) {
195
- log('warn: could not write ' + target + ': ' + e.message);
196
- } finally {
197
- if (rw.status === 0) spawnSync('mount', ['-o', 'remount,ro', '/'], { encoding: 'utf8' });
198
- }
199
- }
200
- }
201
-
202
- // ---------- main ------------------------------------------------------------
203
- (async () => {
204
- log('board home: ' + BOARD_HOME);
205
- const nodeBin = findNode();
206
- if (!nodeBin) { console.error('FATAL: no Node >= 22 found (looked at PATH, dsh-pack, .ohos). hmh needs Node >= 22.'); process.exit(1); }
207
- log('node: ' + nodeBin + ' (' + (spawnSync(nodeBin, ['--version'], { encoding: 'utf8' }).stdout || '').trim() + ')');
208
-
209
- if (!BIN_ONLY) {
210
- let pins;
211
- try { pins = await resolveVersions(); }
212
- catch (e) {
213
- log('warn: registry unreachable (' + e.message.slice(0, 80) + ') — falling back to known-good pins');
214
- pins = Object.assign({}, FALLBACK_PINS);
215
- }
216
- for (const n of PACKAGES) log(' @hmharness/' + n + '@' + pins[n]);
217
-
218
- const STAGE = NM + '.new';
219
- fs.rmSync(STAGE, { recursive: true, force: true });
220
- fs.mkdirSync(path.join(STAGE, '@hmharness'), { recursive: true });
221
- for (const name of PACKAGES) {
222
- const ver = pins[name];
223
- const tgz = path.join(ROOT, '.stage.tgz');
224
- process.stdout.write('download ' + name + '@' + ver + ' ... ');
225
- await download(REG + '/@hmharness/' + name + '/-/' + name + '-' + ver + '.tgz', tgz);
226
- const dest = path.join(STAGE, '@hmharness', name);
227
- extract(tgz, dest);
228
- const pkg = JSON.parse(fs.readFileSync(path.join(dest, 'package.json'), 'utf8'));
229
- if (pkg.version !== ver) throw new Error(name + ': unpacked ' + pkg.version + ' != ' + ver);
230
- log('ok');
231
- }
232
- fs.rmSync(path.join(ROOT, '.stage.tgz'), { force: true });
233
-
234
- // syntax-check the staged CLI entrypoint before swapping anything
235
- const main = path.join(STAGE, '@hmharness', 'cli', 'dist', 'main.js');
236
- const chk = spawnSync(nodeBin, ['--check', main], { encoding: 'utf8' });
237
- if (chk.status !== 0) throw new Error('staged main.js failed --check: ' + (chk.stderr || '').slice(0, 200));
238
- log('staged CLI entrypoint OK');
239
-
240
- const BAK = NM + '.bak';
241
- fs.rmSync(BAK, { recursive: true, force: true });
242
- if (fs.existsSync(NM)) fs.renameSync(NM, BAK);
243
- fs.renameSync(STAGE, NM);
244
- log('installed @hmharness/cli@' + pins.cli + ' (previous tree kept at ' + BAK + ')');
245
- }
246
-
247
- writeLauncher(nodeBin);
248
-
249
- // first run: create the state skeleton + blank config (never overwrite)
250
- if (!fs.existsSync(path.join(HMH_HOME, 'config.json'))) {
251
- log('first run: creating config skeleton at ' + HMH_HOME);
252
- const r = spawnSync(nodeBin, [path.join(NM, '@hmharness', 'cli', 'dist', 'main.js'), 'init'], {
253
- encoding: 'utf8', env: Object.assign({}, process.env, { HMH_HOME, HOME: BOARD_HOME }),
254
- });
255
- log((r.stdout || r.stderr || '').trim().split('\n').slice(-3).join('\n'));
256
- }
257
-
258
- console.log('\nnext steps:');
259
- console.log(' 1. put your provider keys in ' + path.join(HMH_HOME, 'config.json'));
260
- console.log(' (presets for 38 vendors: docs/PROVIDERS.md)');
261
- console.log(' 2. hmh check # verify toolchain');
262
- console.log(' 3. hmh tui # or: hmh web start → http://127.0.0.1:7788');
263
- console.log('pitfalls & details: docs/KAIHONGOS.md');
264
- })().catch((e) => { console.error('INSTALL FAILED:', e.message); process.exit(1); });
66
+ cli: '0.23.30', web: '0.23.30', agent: '0.23.30', kernel: '0.23.30',
67
+ sandbox: '0.23.30', evolution: '0.23.30', 'domain-ops': '0.23.30',
68
+ evaluation: '0.23.30', observability: '0.23.30', 'domain-harmony': '0.23.30',
69
+ };
70
+
71
+ // ---------- helpers ---------------------------------------------------------
72
+ function log(msg) { console.log(msg); }
73
+
74
+ function httpsJSON(url, timeoutMs) {
75
+ return new Promise((resolve, reject) => {
76
+ const req = https.request(new URL(url), { headers: { 'User-Agent': 'hmh-kaihongos-installer' }, timeout: timeoutMs || 20000 }, (res) => {
77
+ if (res.statusCode !== 200) { res.resume(); reject(new Error(url + ' -> ' + res.statusCode)); return; }
78
+ const chunks = [];
79
+ res.on('data', (c) => chunks.push(c));
80
+ res.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch (e) { reject(e); } });
81
+ });
82
+ req.on('timeout', () => { req.destroy(new Error('timeout')); });
83
+ req.on('error', reject);
84
+ req.end();
85
+ });
86
+ }
87
+
88
+ function download(url, file) {
89
+ return new Promise((resolve, reject) => {
90
+ let attempt = 0;
91
+ function go() {
92
+ attempt++;
93
+ const req = https.request(new URL(url), { headers: { 'User-Agent': 'hmh-kaihongos-installer' }, timeout: 30000 }, (res) => {
94
+ if (res.statusCode !== 200) { res.resume(); reject(new Error(url + ' -> ' + res.statusCode)); return; }
95
+ const out = fs.createWriteStream(file);
96
+ res.pipe(out);
97
+ out.on('finish', () => out.close(resolve));
98
+ out.on('error', reject);
99
+ });
100
+ req.on('timeout', () => { req.destroy(); retry(); });
101
+ req.on('error', (e) => {
102
+ if (attempt < 10 && /EAI_AGAIN|ENOTFOUND|ECONNRESET|ETIMEDOUT/.test(e.code || '')) setTimeout(retry, 1500 * attempt);
103
+ else reject(e);
104
+ });
105
+ req.end();
106
+ }
107
+ function retry() { if (attempt < 10) go(); else reject(new Error('retries exhausted: ' + url)); }
108
+ go();
109
+ });
110
+ }
111
+
112
+ function extract(tgz, dest) {
113
+ fs.mkdirSync(dest, { recursive: true });
114
+ // busybox tar is present on KaihongOS / OpenHarmony boards and understands
115
+ // --strip-components. (GNU/toybox tar also fine if busybox is missing.)
116
+ const cmds = [
117
+ ['busybox', ['tar', '-xzf', tgz, '-C', dest, '--strip-components=1']],
118
+ ['tar', ['-xzf', tgz, '-C', dest, '--strip-components=1']],
119
+ ];
120
+ for (const [bin, args] of cmds) {
121
+ const r = spawnSync(bin, args, { encoding: 'utf8' });
122
+ if (r.status === 0) return;
123
+ if (r.error && r.error.code !== 'ENOENT') log(' warn: ' + bin + ' tar: ' + (r.stderr || r.error.message).slice(0, 120));
124
+ }
125
+ throw new Error('no usable tar (tried busybox tar, tar)');
126
+ }
127
+
128
+ async function resolveVersions() {
129
+ log('resolving latest @hmharness/cli from registry ...');
130
+ const meta = await httpsJSON(REG + '/@hmharness/cli');
131
+ const cliLatest = meta['dist-tags'].latest;
132
+ const deps = (meta.versions[cliLatest].dependencies) || {};
133
+ // dynamic package set: floor ∪ first-party deps the latest cli declares —
134
+ // new upstream packages ride along without this file being touched
135
+ const names = new Set(PACKAGES);
136
+ for (const d of Object.keys(deps)) {
137
+ if (d.startsWith('@hmharness/')) names.add(d.slice('@hmharness/'.length));
138
+ }
139
+ names.delete('cli');
140
+ PACKAGES = ['cli', ...[...names].sort()];
141
+ log(' package set (' + PACKAGES.length + '): ' + PACKAGES.join(', '));
142
+ const pins = { cli: cliLatest };
143
+ for (const n of PACKAGES.slice(1)) {
144
+ const want = deps['@hmharness/' + n];
145
+ if (want && want !== '*') { pins[n] = want.replace(/[^0-9.]/g, ''); continue; }
146
+ // not declared by the latest cli: pin to the cli version itself —
147
+ // first-party packages release in lockstep, and a per-package dist-tag
148
+ // lookup can drift or 404 for brand-new names
149
+ pins[n] = cliLatest;
150
+ }
151
+ return pins;
152
+ }
153
+
154
+ // ---------- node discovery --------------------------------------------------
155
+ function findNode() {
156
+ const cands = [process.execPath,
157
+ path.join(BOARD_HOME, 'dsh-pack/node/bin/node'),
158
+ path.join(BOARD_HOME, '.ohos/node/bin/node'),
159
+ '/usr/local/bin/node', '/usr/bin/node', '/system/bin/node'];
160
+ for (const c of cands) {
161
+ try {
162
+ fs.accessSync(c, fs.constants.X_OK);
163
+ const v = spawnSync(c, ['--version'], { encoding: 'utf8' });
164
+ if (v.status === 0) { const maj = parseInt((v.stdout || '').replace('v', ''), 10); if (maj >= 22) return c; }
165
+ } catch (_) { /* next */ }
166
+ }
167
+ return null;
168
+ }
169
+
170
+ // ---------- launcher --------------------------------------------------------
171
+ function launcherSource(nodeBin) {
172
+ return [
173
+ '#!/system/bin/sh',
174
+ '# hmh launcher — KaihongOS board install (generated by install-kaihongos.cjs)',
175
+ '# Board layout is fixed under ' + BOARD_HOME + ', independent of caller HOME/PATH.',
176
+ 'HROOT="' + ROOT + '"',
177
+ 'HNODE="' + nodeBin + '"',
178
+ '[ -x "$HNODE" ] || for c in node ' + BOARD_HOME + '/dsh-pack/node/bin/node ' + BOARD_HOME + '/.ohos/node/bin/node; do',
179
+ ' [ -x "$c" ] && HNODE="$c" && break',
180
+ 'done',
181
+ '# optional board-wide secrets file (edit or remove — keys normally live in config.json)',
182
+ '[ -f ' + BOARD_HOME + '/.config/apikeys.env ] && . ' + BOARD_HOME + '/.config/apikeys.env',
183
+ '# board shells run with HOME=/ — force a real writable HOME and a stable state dir',
184
+ '[ -z "${HMH_HOME:-}" ] && export HMH_HOME="' + HMH_HOME + '"',
185
+ 'export HOME="' + BOARD_HOME + '"',
186
+ 'export NODE_ALLOW_JIT="${NODE_ALLOW_JIT:-1}"',
187
+ '# drop --jitless inherited from sandbox profiles; board root shell can JIT',
188
+ 'NODE_OPTIONS="$(echo "${NODE_OPTIONS:-}" | sed \'s|--jitless||g; s/ */ /g\')"',
189
+ 'NODE_OPTIONS="$(echo "$NODE_OPTIONS" | sed \'s/^ *//;s/ *$//\')"',
190
+ '[ -n "$NODE_OPTIONS" ] && export NODE_OPTIONS',
191
+ '# optional DevEco-layout toolchain shims (hvigorw / ohpm)',
192
+ '[ -z "${HM_DEVECO_HOME:-}" ] && [ -d ' + BOARD_HOME + '/.local/hm-devtools ] && export HM_DEVECO_HOME="' + BOARD_HOME + '/.local/hm-devtools"',
193
+ 'exec "$HNODE" "$HROOT/node_modules/@hmharness/cli/dist/main.js" "$@"',
194
+ '',
195
+ ].join('\n');
196
+ }
197
+
198
+ function writeLauncher(nodeBin) {
199
+ const src = launcherSource(nodeBin);
200
+ const userBin = path.join(BOARD_HOME, '.local', 'bin');
201
+ fs.mkdirSync(userBin, { recursive: true });
202
+ fs.writeFileSync(path.join(userBin, 'hmh'), src);
203
+ fs.chmodSync(path.join(userBin, 'hmh'), 0o755);
204
+ log('launcher: ' + path.join(userBin, 'hmh'));
205
+
206
+ // System locations live on the read-only rootfs — remount rw, copy, restore ro.
207
+ // /system/bin matters most: isolated tmpfs-namespace terminals (ttyd web
208
+ // terminals, containers) see no /usr at all, but /bin -> /system/bin + /data.
209
+ for (const sysBin of ['/usr/local/bin', '/system/bin']) {
210
+ try { fs.mkdirSync(sysBin, { recursive: true }); } catch (_) { /* exists */ }
211
+ const target = path.join(sysBin, 'hmh');
212
+ const rw = spawnSync('mount', ['-o', 'remount,rw', '/'], { encoding: 'utf8' });
213
+ try {
214
+ fs.writeFileSync(target, src);
215
+ fs.chmodSync(target, 0o755);
216
+ log('launcher: ' + target + (rw.status === 0 ? ' (rootfs remounted rw then ro)' : ''));
217
+ } catch (e) {
218
+ log('warn: could not write ' + target + ': ' + e.message);
219
+ } finally {
220
+ if (rw.status === 0) spawnSync('mount', ['-o', 'remount,ro', '/'], { encoding: 'utf8' });
221
+ }
222
+ }
223
+ }
224
+
225
+ // ---------- self-heal layer --------------------------------------------------
226
+ // Why: the board auto-update channel re-runs THIS installer from inside the
227
+ // freshly downloaded npm package. Even with the dynamic package set above,
228
+ // belt-and-braces says the installed tree should be able to repair itself:
229
+ // a package renamed, split, or added between releases cannot brick the
230
+ // board install. The heal script discovers required @hmharness/* packages
231
+ // from the tree ITSELF (deps graph BFS + a static import scan of built
232
+ // code), so it never goes stale the way any hardcoded list does.
233
+ //
234
+ // Two pieces are installed, both OUTSIDE node_modules (which every update
235
+ // swaps wholesale):
236
+ // 1. <HMH_HOME>/heal-tree.cjs — the repair script (this file's
237
+ // sibling twin: scripts/heal-tree.cjs / packages/cli/board/heal-tree.cjs)
238
+ // 2. a marked hook block in <BOARD_HOME>/.config/apikeys.env — the stock
239
+ // launcher template always sources that file before exec'ing the CLI,
240
+ // and the updater never touches user config, so it is the one durable
241
+ // pre-start hook point. A no-op heal run costs ~0.1s; failures never
242
+ // block startup.
243
+ const HEAL_HOOK_BEGIN = '# >>> hmh board self-heal hook (installed by install-kaihongos.cjs; keep) <<<';
244
+ const HEAL_HOOK_END = '# <<< end hmh board self-heal hook >>>';
245
+
246
+ function healHookSource() {
247
+ return [
248
+ HEAL_HOOK_BEGIN,
249
+ '# Runs heal-tree.cjs BEFORE the CLI starts: verifies the vendor tree is',
250
+ '# complete and repairs it (registry, or node_modules.bak offline) when an',
251
+ '# auto-update left packages missing. No-op cost ~0.1s; never blocks start.',
252
+ 'if [ -d ' + NM + '/@hmharness ]; then',
253
+ ' _HMH_HEAL_NODE="${HNODE:-' + path.join(BOARD_HOME, 'dsh-pack/node/bin/node.bin') + '}"',
254
+ ' if [ -x "$_HMH_HEAL_NODE" ]; then',
255
+ ' HMH_BOARD_HOME="' + BOARD_HOME + '" \\',
256
+ ' "$_HMH_HEAL_NODE" ' + path.join(HMH_HOME, 'heal-tree.cjs') + ' >>' + path.join(HMH_HOME, 'heal.log') + ' 2>&1 \\',
257
+ ' || echo "hmh: self-heal could not complete (see ' + path.join(HMH_HOME, 'heal.log') + ') — starting anyway" >&2',
258
+ ' fi',
259
+ 'fi',
260
+ 'unset _HMH_HEAL_NODE',
261
+ HEAL_HOOK_END,
262
+ '',
263
+ ].join('\n');
264
+ }
265
+
266
+ function installHealLayer() {
267
+ const sibling = path.join(__dirname, 'heal-tree.cjs');
268
+ if (!fs.existsSync(sibling)) { log('warn: heal-tree.cjs not found beside installer — self-heal layer NOT installed'); return; }
269
+ const healDst = path.join(HMH_HOME, 'heal-tree.cjs');
270
+ fs.mkdirSync(HMH_HOME, { recursive: true });
271
+ fs.writeFileSync(healDst, fs.readFileSync(sibling, 'utf8'));
272
+ fs.chmodSync(healDst, 0o600);
273
+ log('heal: ' + healDst);
274
+
275
+ // merge the hook into apikeys.env, preserving whatever the user keeps there
276
+ const envFile = path.join(BOARD_HOME, '.config', 'apikeys.env');
277
+ fs.mkdirSync(path.dirname(envFile), { recursive: true });
278
+ let prev = '';
279
+ try { prev = fs.readFileSync(envFile, 'utf8'); } catch (_) { /* new */ }
280
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
281
+ const stripped = prev
282
+ .replace(new RegExp(esc(HEAL_HOOK_BEGIN) + '[\\s\\S]*?' + esc(HEAL_HOOK_END) + '\\n?', 'g'), '')
283
+ .replace(/\n{3,}/g, '\n\n');
284
+ const next = (stripped.endsWith('\n') || stripped === '' ? stripped : stripped + '\n') + healHookSource();
285
+ fs.writeFileSync(envFile, next);
286
+ log('heal hook: ' + envFile + (prev.trim() ? ' (existing content preserved)' : ''));
287
+ }
288
+
289
+ // ---------- main ------------------------------------------------------------
290
+ (async () => {
291
+ log('board home: ' + BOARD_HOME);
292
+ const nodeBin = findNode();
293
+ if (!nodeBin) { console.error('FATAL: no Node >= 22 found (looked at PATH, dsh-pack, .ohos). hmh needs Node >= 22.'); process.exit(1); }
294
+ log('node: ' + nodeBin + ' (' + (spawnSync(nodeBin, ['--version'], { encoding: 'utf8' }).stdout || '').trim() + ')');
295
+
296
+ if (!BIN_ONLY) {
297
+ let pins;
298
+ try { pins = await resolveVersions(); }
299
+ catch (e) {
300
+ log('warn: registry unreachable (' + e.message.slice(0, 80) + ') — falling back to known-good pins');
301
+ pins = Object.assign({}, FALLBACK_PINS);
302
+ }
303
+ for (const n of PACKAGES) log(' @hmharness/' + n + '@' + pins[n]);
304
+
305
+ const STAGE = NM + '.new';
306
+ fs.rmSync(STAGE, { recursive: true, force: true });
307
+ fs.mkdirSync(path.join(STAGE, '@hmharness'), { recursive: true });
308
+ for (const name of PACKAGES) {
309
+ const ver = pins[name];
310
+ const tgz = path.join(ROOT, '.stage.tgz');
311
+ process.stdout.write('download ' + name + '@' + ver + ' ... ');
312
+ await download(REG + '/@hmharness/' + name + '/-/' + name + '-' + ver + '.tgz', tgz);
313
+ const dest = path.join(STAGE, '@hmharness', name);
314
+ extract(tgz, dest);
315
+ const pkg = JSON.parse(fs.readFileSync(path.join(dest, 'package.json'), 'utf8'));
316
+ if (pkg.version !== ver) throw new Error(name + ': unpacked ' + pkg.version + ' != ' + ver);
317
+ log('ok');
318
+ }
319
+ fs.rmSync(path.join(ROOT, '.stage.tgz'), { force: true });
320
+
321
+ // syntax-check the staged CLI entrypoint before swapping anything
322
+ const main = path.join(STAGE, '@hmharness', 'cli', 'dist', 'main.js');
323
+ const chk = spawnSync(nodeBin, ['--check', main], { encoding: 'utf8' });
324
+ if (chk.status !== 0) throw new Error('staged main.js failed --check: ' + (chk.stderr || '').slice(0, 200));
325
+ log('staged CLI entrypoint OK');
326
+
327
+ const BAK = NM + '.bak';
328
+ fs.rmSync(BAK, { recursive: true, force: true });
329
+ if (fs.existsSync(NM)) fs.renameSync(NM, BAK);
330
+ fs.renameSync(STAGE, NM);
331
+ log('installed @hmharness/cli@' + pins.cli + ' (previous tree kept at ' + BAK + ')');
332
+ }
333
+
334
+ writeLauncher(nodeBin);
335
+ installHealLayer();
336
+
337
+ // first run: create the state skeleton + blank config (never overwrite)
338
+ if (!fs.existsSync(path.join(HMH_HOME, 'config.json'))) {
339
+ log('first run: creating config skeleton at ' + HMH_HOME);
340
+ const r = spawnSync(nodeBin, [path.join(NM, '@hmharness', 'cli', 'dist', 'main.js'), 'init'], {
341
+ encoding: 'utf8', env: Object.assign({}, process.env, { HMH_HOME, HOME: BOARD_HOME }),
342
+ });
343
+ log((r.stdout || r.stderr || '').trim().split('\n').slice(-3).join('\n'));
344
+ }
345
+
346
+ console.log('\nnext steps:');
347
+ console.log(' 1. put your provider keys in ' + path.join(HMH_HOME, 'config.json'));
348
+ console.log(' (presets for 38 vendors: docs/PROVIDERS.md)');
349
+ console.log(' 2. hmh check # verify toolchain');
350
+ console.log(' 3. hmh tui # or: hmh web start → http://127.0.0.1:7788');
351
+ console.log('pitfalls & details: docs/KAIHONGOS.md');
352
+ })().catch((e) => { console.error('INSTALL FAILED:', e.message); process.exit(1); });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cli",
3
- "version": "0.23.28",
3
+ "version": "0.23.30",
4
4
  "description": "hmharness command line: one-shot tasks, an interactive REPL, a fullscreen TUI, the web frontend, and direct tool invocation.",
5
5
  "type": "module",
6
6
  "main": "dist/main.js",
@@ -45,20 +45,20 @@
45
45
  "build": "tsc -p tsconfig.build.json"
46
46
  },
47
47
  "dependencies": {
48
- "@hmharness/agent": "0.23.28",
49
- "@hmharness/browser": "0.23.28",
50
- "@hmharness/cognitive": "0.23.28",
51
- "@hmharness/domain-harmony": "0.23.28",
52
- "@hmharness/domain-ops": "0.23.28",
53
- "@hmharness/environments": "0.23.28",
54
- "@hmharness/evaluation": "0.23.28",
55
- "@hmharness/evolution": "0.23.28",
56
- "@hmharness/extension": "0.23.28",
57
- "@hmharness/kernel": "0.23.28",
58
- "@hmharness/observability": "0.23.28",
59
- "@hmharness/sandbox": "0.23.28",
60
- "@hmharness/web": "0.23.28",
48
+ "@hmharness/agent": "0.23.30",
49
+ "@hmharness/browser": "0.23.30",
50
+ "@hmharness/cognitive": "0.23.30",
51
+ "@hmharness/domain-harmony": "0.23.30",
52
+ "@hmharness/domain-ops": "0.23.30",
53
+ "@hmharness/environments": "0.23.30",
54
+ "@hmharness/evaluation": "0.23.30",
55
+ "@hmharness/evolution": "0.23.30",
56
+ "@hmharness/extension": "0.23.30",
57
+ "@hmharness/kernel": "0.23.30",
58
+ "@hmharness/observability": "0.23.30",
59
+ "@hmharness/sandbox": "0.23.30",
60
+ "@hmharness/web": "0.23.30",
61
61
  "qrcode": "^1.5.4",
62
- "@hmharness/lsp": "0.23.28"
62
+ "@hmharness/lsp": "0.23.30"
63
63
  }
64
64
  }
@@ -1,79 +1,89 @@
1
- {
2
- "notes": [
3
- {
4
- "v": "0.23.28",
5
- "date": "2026-10-06",
6
- "note": "评测四层分层守卫(Hidden 只有 evaluator 可写,自进化训练料永不进 Hidden)+ 首个真实学习目标(技能挖掘→holdout 重放→门禁晋升全链)+ 轨迹记录器排空契约(finish 可等待=完成即落盘)"
7
- },
8
- {
9
- "v": "0.23.27",
10
- "date": "2026-10-06",
11
- "note": "Cognitive OS 升级包 P0+P1 九件上线:认知账本(认知事件只增记录+谱系链)、Prediction OS 三预测族统一、认知归因(观察 lift)、学习目标注册表(六要素契约)、统一评测 12 指标、Capability Broker(拒认默认+RLM 零继承)、Transfer 5×5 矩阵(重叠≠证据)、Evidence Ledger 统一谱系、版本一致性机检接入发布门禁"
12
- },
13
- {
14
- "v": "0.23.26",
15
- "date": "2026-10-06",
16
- "note": "会话独立运行(对标 dsh 3080):多会话真并行——每会话独立子进程/队列/审批/中断,输入区跟随当前会话;端口收复只驱逐自家族守护(extension serve 等不再被误杀);侧栏各会话显示运行状态点"
17
- },
18
- {
19
- "v": "0.23.25",
20
- "date": "2026-10-06",
21
- "note": "浏览器扩展对话面板:侧栏直接和助手对话(你的 provider 当大脑,page_read/page_act 工具环当面执行留审计),桥守护 install 完即自动拉起;零配对装载即连;Code World Model 三传感器族生产接线(LSP 符号/诊断 + 浏览器观察 + 构建判定)"
22
- },
23
- {
24
- "v": "0.23.24",
25
- "date": "2026-10-05",
26
- "note": "七浏览器真装验证:Chrome/Edge/Brave/Opera/夸克/Firefox/BrowserOS 两连跑全绿;Firefox 走 Marionette 临时装载 + 演示页同源配对;MV3 主机权限边界如实上报,只读命令可重放"
27
- },
28
- {
29
- "v": "0.23.23",
30
- "date": "2026-10-04",
31
- "note": "更新体验:后台更新时 TUI 内轻提示(开始/完成),升级后首次启动显示一行更新简报——无弹窗但不再失联"
32
- },
33
- {
34
- "v": "0.23.22",
35
- "date": "2026-10-04",
36
- "note": "审计研究基建池全量:COG-MEA 长任务循环、版本化评测任务集(数据集指纹+种子+留出)、沙箱红队加固、WM-2 观测因果挖掘、Code World Model"
37
- },
38
- {
39
- "v": "0.23.21",
40
- "date": "2026-10-04",
41
- "note": "BrowserOS AI 浏览器包(第 15 包)+ ACP 服务器(BrowserOS 助手面板可直接驱动 hmh)+ flaky 根因修复"
42
- },
43
- {
44
- "v": "0.23.20",
45
- "date": "2026-10-04",
46
- "note": "认知消融三臂阶梯仪器(ablate --task --ladder3,支持 --difficulty=hard)"
47
- },
48
- {
49
- "v": "0.23.19",
50
- "date": "2026-10-04",
51
- "note": "能力 OS 首片:LSP 源信任 + sha256 钉扎(DevEco 本地 clangd 自动发现并钉扎,PATH 源一次性信任)"
52
- },
53
- {
54
- "v": "0.23.18",
55
- "date": "2026-10-04",
56
- "note": "群体循环远程吸收:absorb --from=<url>(协议墙+大小上限+免内容校验)"
57
- },
58
- {
59
- "v": "0.23.17",
60
- "date": "2026-10-04",
61
- "note": "12 周计划收官特性:DevEco 本地 LSP 服务器发现(官方 clangd 全链路)"
62
- },
63
- {
64
- "v": "0.23.16",
65
- "date": "2026-10-03",
66
- "note": "发布链三防线(private 包/依赖覆盖预检/板级兜底钉随版);@hmharness/lsp 首发修复全新安装;KaihongOS 板级自动更新通道生效"
67
- },
68
- {
69
- "v": "0.23.15",
70
- "date": "2026-10-03",
71
- "note": "热修:补上 0.23.14 缺失的 lsp 依赖发布;发布预检加入依赖覆盖与 private 检查"
72
- },
73
- {
74
- "v": "0.23.14",
75
- "date": "2026-10-02",
76
- "note": "无垫片更新链(更新弹窗根因修复,node 直跑 npm-cli.js);KaihongOS 板端随包安装器;长会话队列断路器与崩溃断点召回"
77
- }
78
- ]
79
- }
1
+ {
2
+ "notes": [
3
+ {
4
+ "v": "0.23.30",
5
+ "date": "2026-10-07",
6
+ "note": "0.24 研究里程碑:学习改变行动的跨环境证据(规划门判别力随动作词表丰富度上升,harmonyos 达 0.71-0.97);认知账本 2.0 可回放 DAG;Skill 2.0 schema;泛化实验室把 0.39 拒绝归因为触发/前置条件轴;Web 驾驶舱升八态(规划/验证/恢复/终态可见)"
7
+ },
8
+ {
9
+ "v": "0.23.29",
10
+ "date": "2026-10-07",
11
+ "note": "学习 OS 真实数据里程碑:world_model 目标在本机 365 条真实轨迹上以 86.3% 相对校准改进通过 holdout 门禁,5/5 种子分割鲁棒(符号检验 p=0.031);技能目标同轮诚实拒绝(挖掘不泛化);多种子统计强化仪器随版"
12
+ },
13
+ {
14
+ "v": "0.23.28",
15
+ "date": "2026-10-06",
16
+ "note": "评测四层分层守卫(Hidden 只有 evaluator 可写,自进化训练料永不进 Hidden)+ 首个真实学习目标(技能挖掘→holdout 重放→门禁晋升全链)+ 轨迹记录器排空契约(finish 可等待=完成即落盘)"
17
+ },
18
+ {
19
+ "v": "0.23.27",
20
+ "date": "2026-10-06",
21
+ "note": "Cognitive OS 升级包 P0+P1 九件上线:认知账本(认知事件只增记录+谱系链)、Prediction OS 三预测族统一、认知归因(观察 lift)、学习目标注册表(六要素契约)、统一评测 12 指标、Capability Broker(拒认默认+RLM 零继承)、Transfer 5×5 矩阵(重叠≠证据)、Evidence Ledger 统一谱系、版本一致性机检接入发布门禁"
22
+ },
23
+ {
24
+ "v": "0.23.26",
25
+ "date": "2026-10-06",
26
+ "note": "会话独立运行(对标 dsh 3080):多会话真并行——每会话独立子进程/队列/审批/中断,输入区跟随当前会话;端口收复只驱逐自家族守护(extension serve 等不再被误杀);侧栏各会话显示运行状态点"
27
+ },
28
+ {
29
+ "v": "0.23.25",
30
+ "date": "2026-10-06",
31
+ "note": "浏览器扩展对话面板:侧栏直接和助手对话(你的 provider 当大脑,page_read/page_act 工具环当面执行留审计),桥守护 install 完即自动拉起;零配对装载即连;Code World Model 三传感器族生产接线(LSP 符号/诊断 + 浏览器观察 + 构建判定)"
32
+ },
33
+ {
34
+ "v": "0.23.24",
35
+ "date": "2026-10-05",
36
+ "note": "七浏览器真装验证:Chrome/Edge/Brave/Opera/夸克/Firefox/BrowserOS 两连跑全绿;Firefox 走 Marionette 临时装载 + 演示页同源配对;MV3 主机权限边界如实上报,只读命令可重放"
37
+ },
38
+ {
39
+ "v": "0.23.23",
40
+ "date": "2026-10-04",
41
+ "note": "更新体验:后台更新时 TUI 内轻提示(开始/完成),升级后首次启动显示一行更新简报——无弹窗但不再失联"
42
+ },
43
+ {
44
+ "v": "0.23.22",
45
+ "date": "2026-10-04",
46
+ "note": "审计研究基建池全量:COG-MEA 长任务循环、版本化评测任务集(数据集指纹+种子+留出)、沙箱红队加固、WM-2 观测因果挖掘、Code World Model"
47
+ },
48
+ {
49
+ "v": "0.23.21",
50
+ "date": "2026-10-04",
51
+ "note": "BrowserOS AI 浏览器包(第 15 包)+ ACP 服务器(BrowserOS 助手面板可直接驱动 hmh)+ flaky 根因修复"
52
+ },
53
+ {
54
+ "v": "0.23.20",
55
+ "date": "2026-10-04",
56
+ "note": "认知消融三臂阶梯仪器(ablate --task --ladder3,支持 --difficulty=hard)"
57
+ },
58
+ {
59
+ "v": "0.23.19",
60
+ "date": "2026-10-04",
61
+ "note": "能力 OS 首片:LSP 源信任 + sha256 钉扎(DevEco 本地 clangd 自动发现并钉扎,PATH 源一次性信任)"
62
+ },
63
+ {
64
+ "v": "0.23.18",
65
+ "date": "2026-10-04",
66
+ "note": "群体循环远程吸收:absorb --from=<url>(协议墙+大小上限+免内容校验)"
67
+ },
68
+ {
69
+ "v": "0.23.17",
70
+ "date": "2026-10-04",
71
+ "note": "12 周计划收官特性:DevEco 本地 LSP 服务器发现(官方 clangd 全链路)"
72
+ },
73
+ {
74
+ "v": "0.23.16",
75
+ "date": "2026-10-03",
76
+ "note": "发布链三防线(private 包/依赖覆盖预检/板级兜底钉随版);@hmharness/lsp 首发修复全新安装;KaihongOS 板级自动更新通道生效"
77
+ },
78
+ {
79
+ "v": "0.23.15",
80
+ "date": "2026-10-03",
81
+ "note": "热修:补上 0.23.14 缺失的 lsp 依赖发布;发布预检加入依赖覆盖与 private 检查"
82
+ },
83
+ {
84
+ "v": "0.23.14",
85
+ "date": "2026-10-02",
86
+ "note": "无垫片更新链(更新弹窗根因修复,node 直跑 npm-cli.js);KaihongOS 板端随包安装器;长会话队列断路器与崩溃断点召回"
87
+ }
88
+ ]
89
+ }