by adom
The hero-image lab with a human gate: `hero-studio pose <owner/slug>` opens the studio in front of the human, posed for their package, and blocks until they click Generate, producing the provenance-stamped 2000x1250 PNG the registry's hero gate requires. The image carries the title and artwork; the exported image also bakes the type pill (top right) and full wiki slug (bottom right); the page shows the hero bare, and only the homepage marquee overlays its own dynamic info. Every hero wears its P
master
Drew Owens
Compose through the renderer ladder; the surface posts its lint again
874d299
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
#!/usr/bin/env node
// Compose through the renderer ladder, and lint freshness: node test/compose-ladder.mjs
//
// On a container with no local Chrome (an aarch64 Hydrogen Mac workspace that
// renders through pup on the host), an attested re-generate was impossible:
// - POST /generate refused with HUMAN_GATE "state.lint is stale" whenever
// lintMeta.poseRev !== poseRev, and its hint said GET /compose.png;
// - /compose.png spawned render-hero.mjs only, the local Chrome leg, so it
// died with "Chrome not found" and never tried pup;
// - render-pup.mjs printed no LINT_JSON, so even a pup render measured
// nothing;
// - the open surface stopped posting its lint in 0.20.4, so nothing could
// refresh state.lint there at all.
//
// This needs no Chrome and no desktop. It starts a real server on a spare
// port with a temporary HOME and a dead local renderer, and puts a stub
// `adom-bridge` first on PATH that answers the pup verbs render-pup.mjs uses
// (and evaluates render-pup's own lint expression against a fake window). The
// real bridge is never called. It asserts:
// - the stale refusal's hint names compose through pup on this box,
// - GET /compose.png renders via pup (X-Hero-Renderer), and the findings it
// measured land in state.lint fresh, source compose, renderer pup, intact
// through a CLI that escapes slashes,
// - the attested Generate then gets past the stale-lint refusal,
// - a pose change during a compose leaves its findings stale; a second
// compose and a Generate are refused while one runs,
// - a failing leg reports its reason and leaves state.lint alone,
// - ?renderer=local pins the local leg,
// - surface lint posts: {lint, lintPoseRev} is fresh and does not bump
// poseRev, an outdated one is dropped, the legacy {lint} still lands,
// - {fitAck} clears state.fitPending without touching the pose,
// - the surface's runLint and runFit (lifted out of app.js) post exactly
// that: lint with its rev, deduped, held while a typed text is unsaved,
// and an answer to every fit,
// - the full-import passthrough really passes through (it used to throw on
// renderLint and fall back to re-rendering the import).
import { spawn, execFileSync } from 'child_process';
import net from 'net';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';
const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const PLAT = createRequire(import.meta.url)(path.join(ROOT, 'platform.cjs'));
let pass = 0; const fails = [];
const ok = (name, cond, detail) => { if (cond) { pass++; console.log(' ok ' + name); } else { fails.push(name); console.log(' FAIL ' + name + (detail ? ': ' + detail : '')); } };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// The surface's side, pure (no browser): runLint and runFit lifted out of
// public/js/app.js with their collaborators stubbed. test/render-view.mjs
// checks the same against a real page when a Chrome is available.
{
const app = fs.readFileSync(path.join(ROOT, 'public/js/app.js'), 'utf8');
const lintSrc = app.match(/\nfunction runLint\(\) \{[\s\S]*?\n\}\n/);
const fitSrc = app.match(/\nfunction runFit\(maxCqw\) \{[\s\S]*?\n\}\n/);
ok('app.js defines runLint and runFit', !!lintSrc && !!fitSrc);
if (lintSrc && fitSrc) {
const sent = [];
const env = { state: { poseRev: 5, fontSize: { title: 8 } }, drafts: {}, items: null, fit: null };
const mk = new Function('env', 'sent',
'let state = env.state; let lastLintKey = ""; const textDrafts = env.drafts;\n' +
'const computeLint = () => env.items; const send = (p) => sent.push(JSON.parse(JSON.stringify(p)));\n' +
'const solveTitleFit = () => env.fit; const handleToast = () => {};\n' +
lintSrc[0] + fitSrc[0] + '\nreturn { runLint, runFit, setState: (s) => { state = s; } };');
const s = mk(env, sent);
env.items = [{ id: 'headroom', level: 'info', msg: 'published headroom: 40px', el: 'el-title' }];
s.runLint();
ok('surface runLint posts {lint, lintPoseRev} with the rev it rendered, el stripped', sent.length === 1 && JSON.stringify(sent[0]) === JSON.stringify({ lint: [{ id: 'headroom', level: 'info', msg: 'published headroom: 40px' }], lintPoseRev: 5 }), JSON.stringify(sent));
s.runLint();
ok('surface runLint does not repeat the same findings for the same rev', sent.length === 1, JSON.stringify(sent));
s.setState({ poseRev: 6, fontSize: { title: 8 } });
s.runLint();
ok('surface runLint re-posts the same findings for a new rev (keeps them fresh)', sent.length === 2 && sent[1].lintPoseRev === 6, JSON.stringify(sent));
env.drafts.headline = 'typed, not saved yet';
s.setState({ poseRev: 7, fontSize: { title: 8 } });
s.runLint();
ok('surface runLint holds while a typed text is unsaved', sent.length === 2, JSON.stringify(sent));
delete env.drafts.headline;
s.runLint();
ok('and posts once the draft has landed', sent.length === 3 && sent[2].lintPoseRev === 7, JSON.stringify(sent));
env.items = null;
s.runLint();
ok('surface runLint posts nothing when the hero cannot be measured', sent.length === 3);
sent.length = 0;
env.fit = null; s.runFit(null);
env.fit = { size: 8 }; s.runFit(null);
env.fit = { size: 9.5 }; s.runFit(null);
ok('surface runFit always answers: fitAck when nothing fits or the size stays, fontSize when it moves', JSON.stringify(sent) === JSON.stringify([{ fitAck: true }, { fitAck: true }, { fontSize: { title: 9.5 } }]), JSON.stringify(sent));
}
}
const PY = PLAT.pythonWithPillow();
if (!PY) {
console.log(' SKIP the server half: no Python with Pillow, and render-pup.mjs crops with PIL');
console.log('\n' + pass + ' passed, ' + fails.length + ' failed');
process.exit(fails.length ? 1 : 0);
}
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'hs-compose-'));
const BIN = path.join(tmp, 'bin');
fs.mkdirSync(BIN);
const STUB_DIR = BIN;
const py = (code, ...args) => execFileSync(PY.cmd, [...PY.args, '-c', code, ...args], { stdio: 'pipe' });
// What the stub host "screenshots": the render window at 1720x1180 with the
// 16px #ff00fe sentinel at viewport (0,0); #hero measures 1600x1000 at y=40.
py('import sys\nfrom PIL import Image\nim = Image.new("RGB", (1720, 1180), (20, 24, 40))\n' +
'im.paste((255, 0, 254), (0, 0, 16, 16))\nim.save(sys.argv[1])\n', path.join(STUB_DIR, 'shot.png'));
// What the surface's linter would measure. Quotes, a slash, a backslash and
// non-ASCII, so the transport has to be exact.
const LINT = [
{ id: 'headroom', level: 'info', msg: 'published headroom: 312px between the lowest image-zone text and the marquee band at export scale (2000x1250)' },
{ id: 'band-el-sub', level: 'warn', msg: 'subtitle "Adom / Hero" extends 5px into the band \\ café — shrink it' },
];
fs.writeFileSync(path.join(STUB_DIR, 'lint.json'), JSON.stringify(LINT));
fs.writeFileSync(path.join(BIN, 'adom-bridge'), `#!/usr/bin/env node
// Stub Adom Bridge for test/compose-ladder.mjs: the pup verbs render-pup.mjs
// calls, nothing else. Flag files in this directory steer it: slow (ms to
// stall the screenshot), fail (the screenshot fails).
const fs = require('fs');
const vm = require('vm');
const DIR = __dirname;
let a = process.argv.slice(2);
if (a[0] === '--ai-thread') a = a.slice(2);
const ti = a.indexOf('--target'); if (ti >= 0) a.splice(ti, 2);
const verb = a[0] || '';
let args = {}; try { args = a[1] ? JSON.parse(a[1]) : {}; } catch {}
fs.appendFileSync(DIR + '/calls.log', verb + (args.expr && String(args.expr).includes('__computeLint') ? ' lint' : '') + '\\n');
const say = (o) => console.log(JSON.stringify(o));
if (verb === 'bridge_list') {
console.log('pup 3.0.8 running: pup_status pup_open_window pup_navigate pup_eval pup_screenshot pup_alert_window');
} else if (verb === 'pup_status') {
say({ ok: true, sessions: [] });
} else if (verb === 'pup_open_window' || verb === 'pup_navigate') {
say({ ok: true, sessionId: args.sessionId });
} else if (verb === 'pup_eval') {
const e = String(args.expr || '');
let result = null;
if (e.includes('__computeLint')) {
const lint = JSON.parse(fs.readFileSync(DIR + '/lint.json', 'utf8'));
result = vm.runInNewContext(e, { window: { __computeLint: () => lint }, TextEncoder });
} else if (e.includes('document.readyState')) result = 'HS-READY';
else if (e.includes('__traceError')) result = 'HS-TRACE-READY';
else if (e.includes("__hsAssets==='ready'")) result = 'HS-ASSETS-READY';
else if (e.includes("__hsAssets='wait'")) result = 'HS-ASSETS-STARTED';
else if (e.includes('HSBOX@')) result = 'HSBOX@0,40,1600,1000,1@XOBSH';
// some CLIs escape forward slashes in their JSON: the lint must survive it
console.log(JSON.stringify({ ok: true, result }).replace(/\\//g, '\\\\/'));
} else if (verb === 'pup_screenshot') {
if (fs.existsSync(DIR + '/slow')) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(fs.readFileSync(DIR + '/slow', 'utf8')) || 1500);
if (fs.existsSync(DIR + '/fail')) { console.error('stub: the host refused the screenshot'); process.exit(1); }
say({ ok: true, path: DIR + '/shot.png' });
} else {
console.error('stub: unknown verb ' + verb);
process.exit(2);
}
`);
fs.chmodSync(path.join(BIN, 'adom-bridge'), 0o755);
const calls = () => { try { return fs.readFileSync(path.join(STUB_DIR, 'calls.log'), 'utf8').trim().split('\n').filter(Boolean); } catch { return []; } };
const clearCalls = () => { try { fs.unlinkSync(path.join(STUB_DIR, 'calls.log')); } catch {} };
const PORT = await new Promise((res) => { const s = net.createServer().listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => res(p)); }); });
const THREAD = 'compose ladder test';
// No local renderer (isolated renderer lookup, no Chrome), the host reaches
// the studio on HERO_STUDIO_URL, a dead registry (nothing leaves this box).
const env = { ...process.env, HOME: tmp, USERPROFILE: tmp, PATH: BIN + path.delimiter + process.env.PATH,
HERO_STUDIO_RENDERER_HOME: path.join(tmp, 'rh'), HERO_STUDIO_RENDERER_ISOLATED: '1', CHROME: path.join(tmp, 'no-chrome'),
HERO_STUDIO_URL: 'http://127.0.0.1:{{port}}/', ADOM_WIKI_REGISTRY: 'http://127.0.0.1:9', ADOM_TARGET: '', HERO_STUDIO_PORT: String(PORT) };
delete env.VSCODE_PROXY_URI; delete env.HERO_RENDERER; delete env.PUPPETEER_CORE; delete env.ADOM_AI_THREAD;
// The temporary HOME would hide a Pillow installed with pip --user; keep the
// real user site so the crop and the stamp find it.
try { env.PYTHONUSERBASE = env.PYTHONUSERBASE || execFileSync(PY.cmd, [...PY.args, '-m', 'site', '--user-base'], { encoding: 'utf8' }).trim(); } catch {}
const genDir = path.join(ROOT, 'generated');
const genBefore = new Set(fs.existsSync(genDir) ? fs.readdirSync(genDir) : []);
const server = spawn(process.execPath, [path.join(ROOT, 'server.js'), '--port', String(PORT), '--host', '127.0.0.1', '--ai-thread', THREAD, '--ttl', '1'],
{ env, cwd: ROOT, stdio: ['ignore', 'pipe', 'pipe'] });
let serverErr = '';
server.stderr.on('data', (c) => { serverErr += c; });
const base = 'http://127.0.0.1:' + PORT;
const getState = async () => (await fetch(base + '/state')).json();
const postJson = async (p, body) => (await fetch(base + p, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(Object.assign({ aiThread: THREAD }, body)) })).json();
const pngSize = (buf) => (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47) ? [buf.readUInt32BE(16), buf.readUInt32BE(20)] : null;
const ATTEST = { human: 'drew', quote: 'looks good, ship it' };
let up = false;
for (let i = 0; i < 50 && !up; i++) { try { up = (await fetch(base + '/state')).ok; } catch {} if (!up) await sleep(200); }
ok('a hero-studio server answers on :' + PORT, up, serverErr.slice(-300));
if (!up) { server.kill(); fs.rmSync(tmp, { recursive: true, force: true }); console.log('\n' + pass + ' passed, ' + fails.length + ' failed'); process.exit(1); }
let sse = null;
try {
const st0 = await getState();
ok('the box under test is pup-only: local renderer dead, pup reachable', st0.renderer && !st0.renderer.local.ok && st0.renderer.pup.ok, JSON.stringify(st0.renderer));
ok('GET /state carries poseRev', Number.isInteger(st0.poseRev), String(st0.poseRev));
ok('never-measured lint reads stale, and the reason names the surface and pup', st0.lintMeta && st0.lintMeta.stale === true && /surface/.test(st0.lintMeta.reason || '') && /pup/.test(st0.lintMeta.reason || ''), JSON.stringify(st0.lintMeta));
// 1. the refusal Drew hit, now with a hint that works on this box
const g0 = await postJson('/generate', { attest: ATTEST });
ok('attested Generate on stale lint refuses with HUMAN_GATE "state.lint is stale"', g0.ok === false && g0.errorCode === 'HUMAN_GATE' && /^state\.lint is stale/.test(g0.error || ''), JSON.stringify(g0).slice(0, 300));
ok('the stale hint names compose through the host browser via pup on a box with no local renderer', /hero-studio compose/.test(g0.hint || '') && /via pup/.test(g0.hint || '') && /no local renderer/.test(g0.hint || ''), g0.hint);
// 2. compose renders through pup and measures lint there
clearCalls();
const revBefore = (await getState()).poseRev;
const c1 = await fetch(base + '/compose.png');
const c1buf = Buffer.from(await c1.arrayBuffer());
ok('GET /compose.png answers 200 image/png with no local Chrome', c1.status === 200 && /image\/png/.test(c1.headers.get('content-type') || ''), c1.status + ' ' + c1buf.toString('utf8', 0, 300));
ok('compose says it rendered via pup (X-Hero-Renderer)', c1.headers.get('x-hero-renderer') === 'pup', String(c1.headers.get('x-hero-renderer')));
const sz = pngSize(c1buf);
ok('the composed PNG is the cropped #hero, 1600x1000', sz && sz[0] === 1600 && sz[1] === 1000, JSON.stringify(sz));
ok('render-pup evaluated window.__computeLint in the render view', calls().includes('pup_eval lint'), calls().join(','));
const st1 = await getState();
ok('compose stored the measured findings exactly (quotes, slash, backslash, non-ASCII intact)', JSON.stringify(st1.lint) === JSON.stringify(LINT), JSON.stringify(st1.lint));
ok('lintMeta: fresh, source compose, renderer pup, at the pose the render loaded', st1.lintMeta && st1.lintMeta.stale === false && st1.lintMeta.source === 'compose' && st1.lintMeta.renderer === 'pup' && st1.lintMeta.poseRev === revBefore, JSON.stringify(st1.lintMeta));
ok('compose did not move the pose', st1.poseRev === revBefore, st1.poseRev + ' vs ' + revBefore);
// 3. the attested Generate gets past the stale-lint refusal
const g1 = await postJson('/generate', { attest: ATTEST });
ok('after compose, the attested Generate is no longer refused as stale', !/stale/.test(g1.error || ''), JSON.stringify(g1).slice(0, 300));
// 4. a pose change while a compose runs: findings stamped with the start rev
fs.writeFileSync(path.join(STUB_DIR, 'slow'), '2500');
const revStart = (await getState()).poseRev;
const slowCompose = fetch(base + '/compose.png').then(async (r) => ({ status: r.status, renderer: r.headers.get('x-hero-renderer'), body: Buffer.from(await r.arrayBuffer()) }));
await sleep(700);
const busy = await fetch(base + '/compose.png');
ok('a second compose while one runs answers 503', busy.status === 503, busy.status + ' ' + (await busy.text()).slice(0, 120));
const gBusy = await postJson('/generate', { attest: ATTEST });
ok('Generate while a compose runs is refused, naming the compose', gBusy.ok === false && /compose is running/.test(gBusy.error || ''), JSON.stringify(gBusy).slice(0, 200));
const moved = await postJson('/state', { headline: 'Moved during the render' });
ok('a pose change during the compose lands', moved.ok === true);
const slow = await slowCompose;
fs.unlinkSync(path.join(STUB_DIR, 'slow'));
ok('the slow compose still renders via pup', slow.status === 200 && slow.renderer === 'pup', slow.status + ' ' + slow.body.toString('utf8', 0, 200));
const st2 = await getState();
ok('findings from a render that started before the change are stamped with its start rev, so they read stale', st2.lintMeta.poseRev === revStart && st2.poseRev > revStart && st2.lintMeta.stale === true, JSON.stringify({ meta: st2.lintMeta, poseRev: st2.poseRev, revStart }));
// 5. a failing pup leg: reason reported, state.lint untouched
fs.writeFileSync(path.join(STUB_DIR, 'fail'), '1');
const lintBefore = JSON.stringify(st2.lint);
const cf = await fetch(base + '/compose.png');
const cfBody = await cf.json().catch(() => ({}));
fs.unlinkSync(path.join(STUB_DIR, 'fail'));
ok('a failed compose answers 500 with the leg and its reason, and a hint', cf.status === 500 && cfBody.ok === false && /^pup: /.test(cfBody.error || '') && /doctor/.test(cfBody.hint || ''), cf.status + ' ' + JSON.stringify(cfBody).slice(0, 300));
ok('a failed compose leaves state.lint as it was', JSON.stringify((await getState()).lint) === lintBefore);
// 6. ?renderer=local pins the local leg (dead here), like POST /generate {renderer}
clearCalls();
const cl = await fetch(base + '/compose.png?renderer=local');
const clBody = await cl.json().catch(() => ({}));
ok('?renderer=local runs only the local leg', cl.status === 500 && /^local: /.test(clBody.error || '') && !/pup:/.test(clBody.error || '') && calls().length === 0, cl.status + ' ' + JSON.stringify(clBody).slice(0, 300) + ' calls=' + calls().join(','));
// 7. surface lint posts
const s0 = await getState();
const SURF = [{ id: 'headroom', level: 'info', msg: 'published headroom: 200px' }];
const p1 = await postJson('/state', { lint: SURF, lintPoseRev: s0.poseRev });
const s1 = await getState();
ok('a surface post {lint, lintPoseRev} at the current rev lands fresh, source surface', p1.ok && JSON.stringify(s1.lint) === JSON.stringify(SURF) && s1.lintMeta.source === 'surface' && s1.lintMeta.stale === false && s1.lintMeta.poseRev === s0.poseRev, JSON.stringify(s1.lintMeta));
ok('a lint post does not bump poseRev (no re-measure loop)', s1.poseRev === s0.poseRev, s1.poseRev + ' vs ' + s0.poseRev);
ok('lintPoseRev is not merged into state', !('lintPoseRev' in s1));
const p2 = await postJson('/state', { lint: [{ id: 'old', level: 'warn', msg: 'measured on an older pose' }], lintPoseRev: s0.poseRev - 1 });
const s2 = await getState();
ok('lint measured at an older poseRev is dropped and says so', p2.ok && /dropped/.test(p2.lintDropped || '') && JSON.stringify(s2.lint) === JSON.stringify(SURF) && s2.lintMeta.poseRev === s0.poseRev, JSON.stringify({ lintDropped: p2.lintDropped, lint: s2.lint }));
await postJson('/state', { subtitle: 'a pose change' });
const s3 = await getState();
ok('a pose change makes the surface findings stale', s3.poseRev === s0.poseRev + 1 && s3.lintMeta.stale === true, JSON.stringify({ poseRev: s3.poseRev, meta: s3.lintMeta }));
const LEGACY = [{ id: 'headroom', level: 'info', msg: 'posted by hand' }];
await postJson('/state', { lint: LEGACY });
const s4 = await getState();
ok('the legacy {aiThread, lint} post still lands fresh without bumping poseRev', JSON.stringify(s4.lint) === JSON.stringify(LEGACY) && s4.lintMeta.stale === false && s4.poseRev === s3.poseRev, JSON.stringify({ poseRev: s4.poseRev, meta: s4.lintMeta }));
// 8. fitAck: a surface that answered a fit without moving the title
const ac = new AbortController();
sse = ac;
fetch(base + '/events', { signal: ac.signal }).then(async (r) => { try { for await (const _ of r.body) {} } catch {} }).catch(() => {});
await sleep(300);
const f0 = await postJson('/fit', {});
const s5 = await getState();
ok('POST /fit with a surface connected sets state.fitPending', f0.ok === true && !!s5.fitPending, JSON.stringify(f0).slice(0, 200));
await postJson('/state', { fitAck: true });
const s6 = await getState();
ok('{fitAck} clears state.fitPending', s6.fitPending === null, JSON.stringify(s6.fitPending));
ok('{fitAck} neither moves the pose nor lands in state', s6.poseRev === s5.poseRev && !('fitAck' in s6), s6.poseRev + ' vs ' + s5.poseRev);
ac.abort(); sse = null;
// 9. the full-import passthrough really passes through
const imp = path.join(tmp, 'import.png');
py('import sys\nfrom PIL import Image\nImage.new("RGB", (1600, 1000), (200, 40, 90)).save(sys.argv[1])\n', imp);
const src = 'data:image/png;base64,' + fs.readFileSync(imp).toString('base64');
await postJson('/state', { mode: 'component', showcase: { src, full: true, cover: false, chrome: '' }, overlay: { pill: false, scores: false, author: false, slug: false, logo: false }, lint: [] });
clearCalls();
const gp = await postJson('/generate', { fromGate: true });
const con = await (await fetch(base + '/console')).text();
ok('a full import with every overlay off generates', gp.ok === true && !!gp.file, JSON.stringify(gp).slice(0, 300));
ok('it passed through: no render leg ran, no "passthrough write failed"', calls().length === 0 && !/passthrough write failed/.test(con), 'calls=' + calls().join(',') + ' ' + (con.match(/passthrough write failed[^"]*/) || [''])[0]);
if (gp.file) {
const meta = fs.readFileSync(path.join(genDir, gp.file)).toString('latin1');
ok('its provenance says renderer passthrough', /"renderer":"passthrough"/.test(meta));
}
} finally {
if (sse) sse.abort();
server.kill();
// remove only what this run added to generated/
try { for (const f of fs.readdirSync(genDir)) if (!genBefore.has(f)) fs.rmSync(path.join(genDir, f), { force: true }); } catch {}
fs.rmSync(tmp, { recursive: true, force: true });
}
console.log('\n' + pass + ' passed, ' + fails.length + ' failed');
process.exit(fails.length ? 1 : 0);