import assert from 'node:assert/strict'; import { once } from 'node:events'; import { createHash } from 'node:crypto'; import { createServer } from 'node:http'; import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import isolation from '../../test-fixtures/isolation.js'; const { runIsolated, spawnIsolated } = isolation; // noko-engine.nu against a local release server: a good download is unpacked // beside the installed engine and switched atomically; a bundle that does not // match its size or checksum, or holds the wrong tree, never replaces anything // and leaves no partial file; the previous engine stays until confirmed, and a // rolled-back revision is never installed again. `serve` runs the bundle's // executable with the shared model cache. No real release, network or engine. const script = fileURLToPath(new URL('noko-engine.nu', import.meta.url)); const directory = mkdtempSync(join(tmpdir(), 'nuguland-noko-engine-')); const data = join(directory, 'data', 'nuguland', 'noko'); const engine = join(data, 'engine'); const files = new Map(); const server = createServer((request, response) => { const body = files.get(request.url); response.writeHead(body === undefined ? 404 : 200); response.end(body ?? ''); }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const release = `http://127.0.0.1:${server.address().port}/releases/speak_to_me`; const revision = letter => letter.repeat(40); // Version-manager shims resolve per directory and refuse an untrusted private HOME. const path = process.env.PATH.split(':').filter(entry => !entry.includes('/mise/shims')).join(':'); const sha = bytes => createHash('sha256').update(bytes).digest('hex'); // A bundle as Luci publishes it: one speak_to_me/ tree with the executable, its // catalog and a copy of the manifest; the executable reports how it was run. function bundle(rev, { tree = 'speak_to_me', extra = false, manifestRevision = rev } = {}) { const stage = mkdtempSync(join(directory, 'bundle-')); const root = join(stage, tree); mkdirSync(join(root, 'bin'), { recursive: true }); mkdirSync(join(root, 'assets')); writeFileSync(join(root, 'assets', 'pipeline.json'), JSON.stringify({ revision: rev })); writeFileSync(join(root, 'manifest.json'), JSON.stringify({ schema: 1, name: 'speak_to_me', revision: manifestRevision })); writeFileSync(join(root, 'bin', 'speak_to_me'), `#!/bin/sh for last in "$@"; do :; done printf '{"argv":"%s","catalog":%s}\\n' "$*" "$(cat "$last/pipeline.json")" `, { mode: 0o755 }); if (extra) mkdirSync(join(stage, 'stray')); const archive = join(stage, 'bundle.tar.zst'); const made = runIsolated('tar', ['--zstd', '--create', '--file', archive, '--directory', stage, ...readdirSync(stage).filter(name => name !== 'bundle.tar.zst')], { encoding: 'utf8' }); assert.equal(made.status, 0, made.stderr); const bytes = readFileSync(archive); rmSync(stage, { recursive: true, force: true }); return bytes; } function publish(rev, bytes, { size = bytes.length, checksum = sha(bytes), url } = {}) { const file = 'speak_to_me-x86_64-linux.tar.zst'; files.set(`/releases/speak_to_me/${rev}/${file}`, bytes); files.set('/releases/speak_to_me/latest/manifest.json', JSON.stringify({ schema: 1, name: 'speak_to_me', revision: rev, built_at: '2026-11-20T10:00:00Z', target: 'x86_64-unknown-linux-gnu', bundle: { file, url: url ?? `${release}/${rev}/${file}`, size, sha256: checksum }, })); } async function run(...args) { const child = spawnIsolated('nu', ['--no-config-file', script, ...args], { directory, env: { NOKO_RELEASE_URL: release, PATH: path }, stdio: ['ignore', 'pipe', 'pipe'], }); let stdout = '', stderr = ''; child.stdout.on('data', chunk => { stdout += chunk; }); child.stderr.on('data', chunk => { stderr += chunk; }); const [code] = await once(child, 'close'); return { code, stderr, events: stdout.trim().split('\n').filter(Boolean).map(line => JSON.parse(line)) }; } async function ok(...args) { const result = await run(...args); assert.equal(result.code, 0, `${args}: ${result.stderr}`); return result.events; } async function refused(pattern, ...args) { const result = await run(...args); assert.notEqual(result.code, 0, `${args} must fail`); assert.match(result.stderr, pattern); assert.equal(result.events.filter(event => event.event === 'done').length, 0); return result; } const link = name => lstatSync(join(engine, name), { throwIfNoEntry: false })?.isSymbolicLink() ? readlinkSync(join(engine, name)) : null; // Only finished revisions and the links: no partial download or unpack directory. const entries = () => readdirSync(engine).filter(name => name !== 'current' && name !== 'previous' && name !== 'rejected').sort(); try { const [a, b, c, d] = ['a', 'b', 'c', 'd'].map(revision); let [status] = await ok('status'); assert.deepEqual(status, { event: 'status', installed: null, previous: null, staged: [], typing: status.typing }); assert.equal(typeof status.typing, 'boolean'); await refused(/update check failed/, 'check'); publish(a, bundle(a)); assert.deepEqual((await ok('check'))[0], { event: 'latest', revision: a, size: files.get(`/releases/speak_to_me/${a}/speak_to_me-x86_64-linux.tar.zst`).length, installed: null, staged: false, rejected: false }); // A partial file of an interrupted run is cleared, not resumed. mkdirSync(engine, { recursive: true }); writeFileSync(join(engine, `.download-${a}.tar.zst`), 'interrupted'); const first = await ok('install'); assert.deepEqual(first.map(event => event.event).filter((event, index, all) => all.indexOf(event) === index), ['start', 'download', 'verify', 'unpack', 'done']); const progress = first.map(event => event.progress); assert.deepEqual(progress, [...progress].sort((x, y) => x - y), 'progress never runs backwards'); assert.deepEqual(first.at(-1), { event: 'done', label: 'ready', progress: 1, revision: a }); assert.deepEqual(entries(), [a]); [status] = await ok('status'); assert.deepEqual([status.installed, status.staged], [null, [a]], 'unpacked is not yet switched'); assert.deepEqual((await ok('switch', a))[0], { event: 'switched', revision: a, previous: null }); assert.equal(link('current'), a); assert.equal((await ok('install')).at(-1).revision, a, 'an installed revision is not fetched again'); // `serve` runs the read-only bundle with the shared model cache as data root. const served = await ok('serve', a); assert.deepEqual(served, [{ argv: `serve --data-root ${data}/models --assets-dir ${join(engine, a, 'speak_to_me', 'assets')}`, catalog: { revision: a } }]); assert(!existsSync(join(data, 'assets')), 'no assets link is left in the data root'); assert(lstatSync(join(data, 'models')).isDirectory()); await refused(/no such engine revision/, 'serve', b); await refused(/no such engine revision/, 'serve', '../a'); // A download that does not match its manifest replaces nothing. const good = bundle(b); publish(b, good, { checksum: sha('other bytes') }); await refused(/did not match its checksum/, 'install'); publish(b, good, { size: good.length + 1 }); await refused(/did not match its size/, 'install'); publish(b, bundle(b, { extra: true })); await refused(/one speak_to_me directory/, 'install'); publish(b, bundle(b, { manifestRevision: c })); await refused(/another revision/, 'install'); publish(b, good, { url: `${release.replace('127.0.0.1', 'localhost')}/${b}/speak_to_me-x86_64-linux.tar.zst` }); await refused(/unexpected bundle location/, 'check'); await refused(/unexpected bundle location/, 'install'); assert.deepEqual(entries(), [a], 'failed downloads leave no partial file and no unpacked tree'); assert.equal(link('current'), a); // A good update: unpacked beside, switched atomically, previous kept until confirmed. publish(b, good); assert.equal((await ok('check'))[0].installed, a); await ok('install'); assert.deepEqual(entries(), [a, b]); assert.equal(link('current'), a, 'install never switches'); assert.deepEqual((await ok('switch', b))[0], { event: 'switched', revision: b, previous: a }); assert.deepEqual([link('current'), link('previous')], [b, a]); assert.deepEqual((await ok('confirm'))[0], { event: 'confirmed', revision: b }); assert.deepEqual([entries(), link('previous')], [[b], null]); // A revision that failed its first run goes back and is never installed again. publish(c, bundle(c)); await ok('install'); await ok('switch', c); assert.deepEqual((await ok('rollback'))[0], { event: 'rolled-back', revision: b }); assert.deepEqual([link('current'), link('previous'), entries()], [b, null, [b]]); assert.equal((await ok('check'))[0].rejected, true); await refused(/failed its first run/, 'install'); await refused(/no previous engine/, 'rollback'); // A newer staged revision supersedes an older one that never switched. publish(a, bundle(a)); await ok('install'); publish(d, bundle(d)); await ok('install'); assert.deepEqual(entries(), [b, d]); [status] = await ok('status'); assert.deepEqual([status.installed, status.staged], [b, [d]]); await refused(/invalid operation/, 'remove'); console.log('noko-engine.test.mjs: PASS'); } finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); rmSync(directory, { recursive: true, force: true }); }