master
Colby Knox Full test suite in the page repo: npm test runs here (the published package carries only test/brand.mjs) 625499c
#!/usr/bin/env node
// Batch tests: node test/batch.mjs
//
// Applying a style and a showcase moves the pose, and automated Generate
// refuses lint measured against an older pose. Batch has to re-measure for
// each part or every part fails with "state.lint is stale". This runs the real
// verb against a real server and a stub registry, with a saved style, and
// asserts:
//   - every good part generates, and its provenance carries the attestation,
//   - warnings come back in results[],
//   - a part with a hard-fail finding is skipped with its findings, and the
//     parts after it still generate,
//   - a headline that would run onto the showcase image at the style's size
//     is stepped down until it clears (reported as batch-title-fitted), and
//     one that cannot clear at the legibility floor is skipped,
//   - every hero's stamp carries the checks measured in its own render.
import http from 'http';
import { spawn, execFileSync } from 'child_process';
import fs from 'fs';
import net from 'net';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';

const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
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 freePort = () => new Promise((res) => { const s = net.createServer().listen(0, () => { const p = s.address().port; s.close(() => res(p)); }); });

const guide = (owner, status, errors) => ({
  owner, status, version: 1, sha: 'a'.repeat(40), can_edit: false, owner_kind: 'org', visibility: 'public',
  page: owner + '/brand', url: 'http://stub/' + owner + '/brand',
  editable_by: { rule: 'org-members', owner_kind: 'org', who: [owner], text: 'Any member of ' + owner + ' can edit ' + owner + '/brand.' },
  brand: { brand_manifest: '1.0', owner, name: owner, status, confirmed_by: 'someone', confirmed_at: '2026-01-01T00:00:00Z',
    colors: { primary: '#ff0000', background: '#101010', text: '#ffffff' },
    typography: { display: { family: 'Inter' }, body: { family: 'Inter' } }, logos: { mark: 'assets/mark.svg' } },
  assets: { mark: 'http://stub/' + owner + '/brand/files/assets/mark.svg', fonts: [] },
  hints: [], warnings: [], errors: errors || [],
});
const GUIDES = { goodco: guide('goodco', 'confirmed'), badco: guide('badco', 'invalid', [{ field: 'colors.primary', message: 'not a color' }]), nologo: guide('nologo', 'confirmed') };
const MARK_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="120" height="40"><rect width="120" height="40" fill="#ff0000"/></svg>';
const registry = http.createServer((req, res) => {
  // The guide's logo file: goodco's exists, nologo's is missing (hero-studio#76).
  if (/\/brand\/files\/assets\/mark\.svg$/.test(req.url)) {
    if (req.url.startsWith('/goodco/')) { res.writeHead(200, { 'Content-Type': 'image/svg+xml' }); return res.end(MARK_SVG); }
    res.writeHead(404); return res.end('not found');
  }
  const m = req.url.match(/^\/api\/owners\/([^/]+)\/brand/);
  const g = m && GUIDES[decodeURIComponent(m[1])];
  res.writeHead(g ? 200 : 404, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(g || { error: 'not found' }));
});
const regPort = await freePort();
await new Promise((r) => registry.listen(regPort, r));
for (const g of Object.values(GUIDES)) g.assets.mark = 'http://127.0.0.1:' + regPort + '/' + g.owner + '/brand/files/assets/mark.svg';

// The studio records every page it is told about in data/pages.json, and writes
// its exports next to the package. Put both back whatever happens.
const pagesFile = path.join(ROOT, 'data', 'pages.json');
const pagesBefore = fs.readFileSync(pagesFile);
const genDir = path.join(ROOT, 'generated');
const listGenerated = () => { try { return new Set(fs.readdirSync(genDir)); } catch { return new Set(); } };
const genBefore = listGenerated();

const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'hs-batch-'));
const styleName = 'batch-test-' + process.pid;
const styleDir = path.join(os.homedir(), '.adom', 'instances', 'hero-studio', 'styles');
const styleFile = path.join(styleDir, styleName + '.json');
fs.mkdirSync(styleDir, { recursive: true });
fs.writeFileSync(styleFile, JSON.stringify({ name: styleName,
  style: { mode: 'app', guides: false, layout: 'bleed-right', fontSize: { title: 12 }, showcase: { chrome: '', cover: false } },
  gate: { page: 'goodco/gated', human: 'tester', ts: 1 } }));

const PORT = await freePort();
const env = { ...process.env, ADOM_WIKI_REGISTRY: 'http://127.0.0.1:' + regPort, HERO_STUDIO_PORT: String(PORT) };
const server = spawn(process.execPath, [path.join(ROOT, 'server.js'), '--port', String(PORT), '--ai-thread', 'batch test', '--ttl', '1'], { env, stdio: 'ignore' });
let code = 1;
try {
  let up = false;
  for (let i = 0; i < 50 && !up; i++) { try { up = (await fetch('http://localhost:' + PORT + '/state')).ok; } catch {} if (!up) await new Promise((r) => setTimeout(r, 200)); }
  ok('a studio answers', up);

  const partsFile = path.join(tmp, 'parts.json');
  // A plain 16:10 screenshot for the showcase image.
  const shot = path.join(tmp, 'shot.png');
  execFileSync('python3', ['-c', "from PIL import Image; Image.new('RGB', (1600, 1000), (40, 60, 90)).save('" + shot + "')"]);
  fs.writeFileSync(partsFile, JSON.stringify([
    { ref: 'goodco/batch-one', title: 'Batch One', type: 'app', headline: 'First part', subtitle: 'one' },
    { ref: 'badco/batch-bad', title: 'Batch Bad', type: 'app', headline: 'Broken guide', subtitle: 'two' },
    { ref: 'goodco/batch-two', title: 'Batch Two', type: 'app', headline: 'Second part', subtitle: 'three' },
    { ref: 'goodco/batch-long', title: 'Batch Long', type: 'app', headline: 'Soldermask lamination, simulated', subtitle: 'four', showcase: shot },
    { ref: 'goodco/batch-huge', title: 'Batch Huge', type: 'app', headline: 'Supercalifragilisticexpialidocious pneumonoultramicroscopic', subtitle: 'five', showcase: shot },
    { ref: 'nologo/batch-nologo', title: 'Batch No Logo', type: 'app', headline: 'Logo file missing', subtitle: 'six' },
  ]));
  const run = await new Promise((res) => {
    const c = spawn(process.execPath, [path.join(ROOT, 'drive.mjs'), '--ai-thread', 'batch test', '--port', String(PORT), 'batch',
      '--style', styleName, '--parts', partsFile, '--pace', '0.1', '--human', 'tester', '--quote', 'looks right'], { env, stdio: ['ignore', 'pipe', 'pipe'] });
    let out = ''; let err = '';
    c.stdout.on('data', (d) => { out += d; });
    c.stderr.on('data', (d) => { err += d; });
    c.on('close', (status) => res({ status, out, err }));
  });
  let results = [];
  try { results = JSON.parse(run.out).results; } catch {}
  const [one, bad, two, long, huge, nologo] = results;
  ok('nothing fails as stale', !/stale/.test(run.err), run.err.slice(-400));
  ok('the first good part generates', one && one.ok && one.file, JSON.stringify(one));
  ok('  and reports its warnings as a list', one && Array.isArray(one.warnings), JSON.stringify(one));
  ok('the hard-fail part is skipped, naming the finding', bad && !bad.ok && /brand-invalid/.test(bad.error), JSON.stringify(bad));
  ok('  and returns its findings', bad && (bad.lint || []).some((l) => l.level === 'fail' && l.id === 'brand-invalid'), JSON.stringify(bad));
  ok('the part after it still generates', two && two.ok && two.file && two.file !== (one && one.file), JSON.stringify(two));
  ok('a long headline is stepped down until it clears the showcase image', long && long.ok && (long.warnings || []).some((l) => l.id === 'batch-title-fitted'), JSON.stringify(long));
  ok('  and nothing it shipped touches the image', long && !(long.warnings || []).some((l) => /^showcase-/.test(l.id)), JSON.stringify(long));
  ok('a headline that cannot clear at the floor is skipped', huge && !huge.ok && /showcase-|clip-/.test(huge.error), JSON.stringify(huge));
  ok('a part whose logo file is missing is skipped, not exported with an empty slot', nologo && !nologo.ok && /owner-logo-missing/.test(nologo.error), JSON.stringify(nologo));
  const pngs = [one, two, long].filter((r) => r && r.file);
  for (const r of pngs) {
    const text = fs.readFileSync(path.join(genDir, r.file)).toString('latin1');
    ok(r.file.replace(/-\d+\.png$/, '') + ' carries the style and the attestation', text.includes(styleName) && text.includes('looks right'));
    ok('  and the checks from its own render', /"lint":\{"source":"render","findings":\[/.test(text));
    // The owner's logo (the stub's solid red mark) is painted in the top-left
    // wordmark slot of the exported file, not just set as a CSS background.
    const red = execFileSync('python3', ['-c', "import sys; from PIL import Image; im=Image.open(sys.argv[1]).convert('RGB'); w,h=im.size; px=im.crop((0,0,w*3//10,h*2//10)).getdata(); print(sum(1 for p in px if p[0]>230 and p[1]<40 and p[2]<40))", path.join(genDir, r.file)]).toString().trim();
    ok('  and wears the owner logo', Number(red) > 200, 'red pixels in the logo corner: ' + red);
  }
  code = fails.length ? 1 : 0;
} finally {
  server.kill();
  await new Promise((r) => setTimeout(r, 300));
  registry.close();
  fs.writeFileSync(pagesFile, pagesBefore);
  fs.rmSync(styleFile, { force: true });
  fs.rmSync(tmp, { recursive: true, force: true });
  for (const f of listGenerated()) if (!genBefore.has(f)) fs.rmSync(path.join(genDir, f), { recursive: true, force: true });
}
console.log('\n' + pass + ' passed, ' + fails.length + ' failed');
process.exit(code);