mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-11 21:57:14 +03:00
* Route the direction hand by verdict, add the pick card, enforce salience parity The decision round previously rendered every dealt challenger as an equal full card whatever the weighing said, so a world that fused poorly (an underwater world dealt to a flower shop) sat at the same visual weight as the assigned direction, and concept-level fusion had no surviving output. Three changes, all presentation-layer; the dice, the assignment, and the two-axis weighing are untouched: - Verdict routing: the weighing closes with wins / competitive / declined per challenger, decided before any borrowing. Declined challengers render demoted (narrow, quiet, catalog art as a labeled thumb, "Adopt anyway"), reordered to the end of the deck by the page itself, still adoptable, never silently dropped. Donations return as named "raised by" lines on the assigned card: a declined challenger donates ambition and system discipline, never its clothes. - The pick card: one card for the model's top-ranked grounded candidate when the dice assigned another, kicker MY PICK, honest familiarity risk on its face. One card, never a ranked list, never the lead position; the anti-menu rule survives with exactly this carve-out. - Salience parity: a card's imagery weight is capped by the assigned card's. With a text-only assigned card (no image generation in the harness), full-bleed catalog heroes demote to labeled thumbs, so what looks important is the verdict's call, never rendering luck. serve-question payload gains additive fields (verdict, kept, raised); old payloads render unchanged. concept-seed's rendered instructions carry the verdict/donation contract and the pick-card carve-out. Covered by two Playwright tests in the new-work e2e suite (verdict routing + parity). Design exploration and rationale were worked through with the maintainer; research grounding is impeccable.style/research lessons 3-5. AI-assisted change. Co-Authored-By: Claude Code <noreply@anthropic.com> * Add Safer/Bolder re-roll registers to the direction round The re-roll gains the user's steering wheel on the familiar-to-bold axis. The decision page renders two register buttons beside the plain re-roll (payload: reroll: { registers: ["safer", "bolder"] }; booleans still work), the answer carries the chosen register, and concept-seed gains --register. The design constraint that shaped the implementation: a register changes only what a round INSTRUCTS, never what it DEALT. The same key and reroll count reproduce the same deal whatever the register, so the exclusion chain never forks and the reproduction contract holds with no API change. - bolder: the dealt foreign forms become the whole hand, every challenger a full card; the first-dealt challenger leads (assignment by deal order, so the dice still choose). The pick card sits out; the canon stays. - safer: the round's dealt hand is spent unseen and stays excluded; the model presents its remaining conventional grounded candidates (at most three) plus the canon executed against named competitors. This is the one sanctioned lineup of the model's own ranked list, existing only by explicit user request. Works degraded (needs no catalog); bolder degrades to a plain grounded round, disclosed. Registers are user steering, never the model's to pre-select. Covered by a concept-seed unit test (same-deal invariant, validation) and a Playwright test (button, answer field, REGISTER directive). AI-assisted change. Co-Authored-By: Claude Code <noreply@anthropic.com> * Add the execution-contract round: comp-led or code-led, chosen after the direction The build previously went comp-led for everyone, silently: a generated comp led and the build chased it, which produces the boldest compositions and also the measured worst-of-both-worlds failure (ambitious design landed poorly, no motion, fix rounds after). Models already defect from it by quietly skipping comp generation, which is unsanctioned code-led with no contract to catch it. This makes the fork explicit and both paths defection-proof: - Comp-led: the comp is law and non-optional once chosen; visualize.md and the comp-is-king build phases run as today. - Code-led: no comp of this page, skipped by contract rather than drift. The QUALITY BAR boards still calibrate finish, and the ambition moves into the written direction contract (FIRST VIEWPORT plus a named signature interaction and motion grammar), audited by the finish reviewer in behavior. Not a discount on commitment. Placement: a second round on the same open table, right after the direction lands. Sketches stay in the direction round (they pick the world); comps are what code-led skips (they bind the composition). The chosen world sets the default lead; the user flips freely; a standing preference recorded in PRODUCT.md skips the round on later surfaces; with no image generation there is no fork, code-led is the only path. Mechanism: serve-question gains payload-level followup: true, which keeps the detached server alive after a pick (exactly like re-roll), swaps the page to the loading hand instead of goodbye, marks the answer with followup: true so --wait keeps the table, and prints a FOLLOWUP OPEN directive telling the agent to deliver the next round via --update. Covered by a Playwright test driving the full two-round flow. AI-assisted change. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix: address PR review bot findings - Degraded safer register no longer contradicts itself (greptile, Copilot, cursor): the degraded template previously said "the assigned index is suspended; the user picks" and then emitted ASSIGNED INDEX, the mandatory build instruction, and the restated footer anyway. The degraded safer path now suppresses the assignment machinery entirely, matching the non-degraded safer round, and restates the user-picks behavior for truncated readers instead. - A declined card's declared sketch no longer renders a full media face (Copilot): the renderer ignores sketch slots on declined cards outright, so a stray sketch cannot buy back the salience the verdict took away. - Bolder rounds no longer carry the generic weighing instruction (cursor): it measures against the assigned grounded direction, which the bolder register suspends; a leader-relative variant weighs the fused challengers against the first-dealt leader instead. All three pinned by new assertions in tests/concept-seed.test.mjs and tests/new-work-e2e.test.mjs. AI-assisted change. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix: followup never arms the loading hand in blocking serve mode cursor[bot] caught a client/server disagreement: the page interpolated its FOLLOWUP constant from the payload alone, so a followup: true payload served in blocking mode (no --start) would leave the browser on a loading hand that nothing resolves, since a blocking server exits on any pick and has no update channel. The page constant is now armed only when the server is detached, blocking rounds get the goodbye screen as before, and new-work.md states that followup belongs only on a detached round; blocking and structured-tool channels run the build-path round as its own second question. Pinned in tests/serve-question.test.mjs. AI-assisted change. Co-Authored-By: Claude Code <noreply@anthropic.com> * Add card-kind choice telemetry and the bolder routing disambiguation The choice ping previously fired only when a dealt catalog challenger won, so pick-share and canon-share had no denominator and the decision page's new spectrum could not be measured. The ping now fires once per resolved attended round on API-dealt rolls: --kind names which card class won (assigned / pick / challenger / canon), --chosen carries the catalog id only when a dealt challenger won, and --register rides along when the round came from a steered hand. Grounded candidates' names never leave the machine (the ping carries the kind alone), the legacy id-only shape stays valid, and DO_NOT_TRACK / IMPECCABLE_NO_TELEMETRY still disable the ping entirely. The seed's TELEMETRY block teaches the new invocation. Also the naming-collision guard: "bolder" said while a direction round is open routes to the Bolder hand register, never the bolder refinement command; one line each in bolder.md and new-work.md. The /api/chosen field additions land in a sister impeccable-site PR; the API ignores unknown fields meanwhile, so this is safe to ship first. AI-assisted change. Co-Authored-By: Claude Code <noreply@anthropic.com> * fix: ping test survives a DO_NOT_TRACK shell cursor[bot]: the pingChosen unit test cleared only IMPECCABLE_NO_TELEMETRY, so a developer shell with DO_NOT_TRACK set failed the success-path assertions. The test now clears both, restores prior values in finally, and passes under DO_NOT_TRACK=1. AI-assisted change. Co-Authored-By: Claude Code <noreply@anthropic.com> --------- Co-authored-by: Claude Code <noreply@anthropic.com>
254 lines
12 KiB
JavaScript
254 lines
12 KiB
JavaScript
import { describe, it } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { spawn } from 'node:child_process';
|
|
import { writeFileSync, mkdtempSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { EventEmitter } from 'node:events';
|
|
|
|
import { browserOpenCommand, openSystemBrowser } from '../skill/scripts/lib/open-system-browser.mjs';
|
|
|
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
const SCRIPT = path.join(ROOT, 'skill', 'scripts', 'serve-question.mjs');
|
|
|
|
function startServer(payload, extraArgs = []) {
|
|
const dir = mkdtempSync(path.join(tmpdir(), 'serve-question-'));
|
|
const payloadPath = path.join(dir, 'q.json');
|
|
writeFileSync(payloadPath, JSON.stringify(payload));
|
|
const child = spawn(process.execPath, [SCRIPT, '--payload', payloadPath, '--no-open', '--timeout', '30', ...extraArgs], {
|
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
});
|
|
return new Promise((resolve, reject) => {
|
|
let out = '';
|
|
const timer = setTimeout(() => reject(new Error(`no URL in output: ${out}`)), 10000);
|
|
child.stdout.on('data', (chunk) => {
|
|
out += chunk;
|
|
const match = out.match(/QUESTION URL: (http:\/\/127\.0\.0\.1:\d+\/)/);
|
|
if (match) { clearTimeout(timer); resolve({ child, url: match[1], read: () => out }); }
|
|
});
|
|
});
|
|
}
|
|
|
|
const PAYLOAD = {
|
|
title: 'Choose the visual world',
|
|
question: 'The roll assigned Fillmore Handbill.',
|
|
options: [
|
|
{ id: 'assigned', label: 'Fillmore Handbill', kicker: 'THE ROLL', lineage: '1966-71 psychedelic handbills' },
|
|
{ id: 'challenger-1', label: 'Teletext Service', body: 'block-mosaic broadcast pages' },
|
|
],
|
|
reroll: true,
|
|
steer: true,
|
|
};
|
|
|
|
describe('serve-question', () => {
|
|
it('opens Windows URLs through cmd.exe and reserves the start title argument', () => {
|
|
assert.deepEqual(
|
|
browserOpenCommand('http://127.0.0.1:1234/', { platform: 'win32', comspec: 'cmd.exe' }),
|
|
{ command: 'cmd.exe', args: ['/c', 'start', '', 'http://127.0.0.1:1234/'] },
|
|
);
|
|
});
|
|
|
|
it('absorbs asynchronous system-opener failures after printing the URL', () => {
|
|
const child = new EventEmitter();
|
|
child.unref = () => {};
|
|
assert.equal(openSystemBrowser('http://127.0.0.1:1234/', {
|
|
platform: 'linux',
|
|
spawnImpl: () => child,
|
|
}), true);
|
|
assert.equal(child.listenerCount('error'), 1);
|
|
assert.doesNotThrow(() => child.emit('error', Object.assign(new Error('missing opener'), { code: 'ENOENT' })));
|
|
});
|
|
|
|
it('serves the page, records the answer, prints ANSWER, exits 0', async () => {
|
|
const { child, url, read } = await startServer(PAYLOAD);
|
|
const html = await (await fetch(url)).text();
|
|
assert.match(html, /Fillmore Handbill/);
|
|
assert.match(html, /THE ROLL/);
|
|
assert.match(html, /Re-roll/);
|
|
const post = await fetch(`${url}answer`, {
|
|
method: 'POST',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ optionId: 'assigned', steer: 'warmer palette' }),
|
|
});
|
|
assert.equal(post.status, 200);
|
|
const code = await new Promise((resolve) => child.on('exit', resolve));
|
|
assert.equal(code, 0);
|
|
assert.match(read(), /ANSWER: \{"optionId":"assigned","steer":"warmer palette"\}/);
|
|
});
|
|
|
|
it('re-roll answers round-trip with their own id', async () => {
|
|
const { child, url, read } = await startServer(PAYLOAD);
|
|
await fetch(`${url}answer`, {
|
|
method: 'POST',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ optionId: 'reroll', steer: '' }),
|
|
});
|
|
const code = await new Promise((resolve) => child.on('exit', resolve));
|
|
assert.equal(code, 0);
|
|
assert.match(read(), /"optionId":"reroll"/);
|
|
});
|
|
|
|
it('start/wait cycle: daemonize, poll WAITING, then collect the answer', async () => {
|
|
const dir = mkdtempSync(path.join(tmpdir(), 'serve-question-'));
|
|
const payloadPath = path.join(dir, 'q.json');
|
|
writeFileSync(payloadPath, JSON.stringify(PAYLOAD));
|
|
const run = (args) => new Promise((resolve) => {
|
|
const child = spawn(process.execPath, [SCRIPT, ...args], { cwd: dir, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
let out = '';
|
|
child.stdout.on('data', (chunk) => { out += chunk; });
|
|
child.on('exit', (code) => resolve({ code, out }));
|
|
});
|
|
const started = await run(['--start', '--payload', payloadPath, '--no-open', '--key', 'tk']);
|
|
assert.equal(started.code, 0);
|
|
const url = started.out.match(/QUESTION URL: (\S+)/)?.[1];
|
|
assert.ok(url, started.out);
|
|
const waiting = await run(['--wait', '--key', 'tk', '--poll', '1']);
|
|
assert.equal(waiting.code, 3);
|
|
await fetch(`${url}answer`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'assigned', steer: '' }) });
|
|
const collected = await run(['--wait', '--key', 'tk', '--poll', '5']);
|
|
assert.equal(collected.code, 0);
|
|
assert.match(collected.out, /"optionId":"assigned"/);
|
|
});
|
|
|
|
it('headless detection spares the modes that never open a browser', async () => {
|
|
// Only the blocking serve path auto-opens a URL. --wait polls a daemon
|
|
// that is already running, --stop kills one, --schema just prints text,
|
|
// so a headless environment must not turn any of them into exit 2: the
|
|
// documented flow polls --wait while it exits 3, and new-work.md tells
|
|
// the agent to read --schema first.
|
|
const dir = mkdtempSync(path.join(tmpdir(), 'serve-question-'));
|
|
const payloadPath = path.join(dir, 'q.json');
|
|
writeFileSync(payloadPath, JSON.stringify(PAYLOAD));
|
|
const headlessEnv = { ...process.env, CI: '1' };
|
|
delete headlessEnv.IMPECCABLE_QUESTION_FORCE;
|
|
const run = (args) => new Promise((resolve) => {
|
|
const child = spawn(process.execPath, [SCRIPT, ...args], { cwd: dir, env: headlessEnv, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
let out = '';
|
|
child.stdout.on('data', (chunk) => { out += chunk; });
|
|
child.on('exit', (code) => resolve({ code, out }));
|
|
});
|
|
|
|
const schema = await run(['--schema']);
|
|
assert.equal(schema.code, 0, `--schema under CI must print, got ${schema.code}: ${schema.out}`);
|
|
|
|
const started = await run(['--start', '--payload', payloadPath, '--no-open', '--key', 'hk']);
|
|
assert.equal(started.code, 0, started.out);
|
|
try {
|
|
const waiting = await run(['--wait', '--key', 'hk', '--poll', '1']);
|
|
assert.equal(waiting.code, 3, `--wait under CI must report WAITING, got ${waiting.code}: ${waiting.out}`);
|
|
} finally {
|
|
const stopped = await run(['--stop', '--key', 'hk']);
|
|
assert.equal(stopped.code, 0, `--stop under CI must kill the daemon, got ${stopped.code}: ${stopped.out}`);
|
|
}
|
|
});
|
|
|
|
it('headless detection still blocks the path that would open a browser', async () => {
|
|
const dir = mkdtempSync(path.join(tmpdir(), 'serve-question-'));
|
|
const payloadPath = path.join(dir, 'q.json');
|
|
writeFileSync(payloadPath, JSON.stringify(PAYLOAD));
|
|
const headlessEnv = { ...process.env, CI: '1' };
|
|
delete headlessEnv.IMPECCABLE_QUESTION_FORCE;
|
|
const code = await new Promise((resolve) => {
|
|
const child = spawn(process.execPath, [SCRIPT, '--payload', payloadPath], { cwd: dir, env: headlessEnv, stdio: 'ignore' });
|
|
child.on('exit', resolve);
|
|
});
|
|
assert.equal(code, 2);
|
|
});
|
|
|
|
it('rejects an empty payload', async () => {
|
|
const dir = mkdtempSync(path.join(tmpdir(), 'serve-question-'));
|
|
const payloadPath = path.join(dir, 'q.json');
|
|
writeFileSync(payloadPath, JSON.stringify({ options: [] }));
|
|
const code = await new Promise((resolve) => {
|
|
const child = spawn(process.execPath, [SCRIPT, '--payload', payloadPath, '--no-open'], { stdio: 'ignore' });
|
|
child.on('exit', resolve);
|
|
});
|
|
assert.equal(code, 1);
|
|
});
|
|
|
|
it('trusts a fresh heartbeat over a failed kill probe, and still detects true death', async () => {
|
|
const dir = mkdtempSync(path.join(tmpdir(), 'serve-question-'));
|
|
const qdir = path.join(dir, '.impeccable', 'questions');
|
|
const { mkdirSync } = await import('node:fs');
|
|
mkdirSync(qdir, { recursive: true });
|
|
// Fresh heartbeat + a pid that cannot be signaled (throws like a sandbox
|
|
// EPERM or a recycled pid): the wait must keep WAITING (exit 3), never
|
|
// declare the server gone (exit 2). Pid 1 throws EPERM for a normal user.
|
|
writeFileSync(path.join(qdir, 'beat1.state.json'), JSON.stringify({ pid: 1, port: 1, url: 'http://127.0.0.1:1/', lastBeat: Date.now() }));
|
|
const waiting = await new Promise((resolve) => {
|
|
const child = spawn(process.execPath, [SCRIPT, '--wait', '--key', 'beat1', '--poll', '2'], { cwd: dir, stdio: 'ignore' });
|
|
child.on('exit', resolve);
|
|
});
|
|
assert.equal(waiting, 3, 'fresh heartbeat must read as alive regardless of the kill probe');
|
|
// Stale heartbeat + a pid that is genuinely gone (ESRCH): server dead, exit 2.
|
|
writeFileSync(path.join(qdir, 'dead1.state.json'), JSON.stringify({ pid: 999999999 >>> 8, port: 1, url: 'http://127.0.0.1:1/' }));
|
|
const dead = await new Promise((resolve) => {
|
|
const child = spawn(process.execPath, [SCRIPT, '--wait', '--key', 'dead1', '--poll', '2'], { cwd: dir, stdio: 'ignore' });
|
|
child.on('exit', resolve);
|
|
});
|
|
assert.equal(dead, 2, 'a truly missing process must still read as gone');
|
|
});
|
|
|
|
it('renders anatomy, streams late sketches, and returns the chosen sketch', async () => {
|
|
const dir = mkdtempSync(path.join(tmpdir(), 'serve-question-'));
|
|
const sketchPath = path.join(dir, 'sketches', 'assigned.webp');
|
|
const payload = {
|
|
title: 'Choose the visual world',
|
|
options: [
|
|
{
|
|
id: 'assigned', label: 'Fillmore Handbill', kicker: 'THE ROLL',
|
|
thesis: 'The gig poster idea.', palette: ['#e8452c', '#f5d64c'], materials: ['letterpress'],
|
|
viewport: 'Full-bleed dated bill.', risk: 'Nostalgia trap.',
|
|
sketch: sketchPath, hero: 'https://impeccable.style/worlds/cards/x-hero.webp',
|
|
},
|
|
{ id: 'challenger-1', label: 'Teletext Service', case: 'Fuses cleanly.' },
|
|
],
|
|
reroll: true,
|
|
canon: true,
|
|
canonCard: { label: 'The category standard', thesis: 'What the category ships.' },
|
|
steer: true,
|
|
followup: true,
|
|
};
|
|
const { child, url, read } = await startServer(payload);
|
|
const html = await (await fetch(url)).text();
|
|
// Anatomy renders: chips, tags, fact labels, thesis.
|
|
assert.match(html, /swatches/);
|
|
// A blocking server has no update channel, so even a followup payload
|
|
// must not arm the page's loading-hand path (detached mode arms it; the
|
|
// new-work e2e suite covers that side).
|
|
assert.match(html, /const FOLLOWUP = false/);
|
|
assert.match(html, /background:#e8452c/);
|
|
assert.match(html, /class="tag">letterpress/);
|
|
assert.match(html, /The gig poster idea\./);
|
|
assert.match(html, /Fuses cleanly\./);
|
|
// The inspiration image rides picture-in-picture beside the sketch slot.
|
|
assert.match(html, /class="pip"/);
|
|
assert.match(html, /media sketching/);
|
|
// canonCard renders as a subordinate card and suppresses the footer action.
|
|
assert.match(html, /card canon/);
|
|
assert.match(html, /Play it straight</);
|
|
assert.doesNotMatch(html, /<button id="canon"/);
|
|
// The sketch slot 404s until the file lands, then serves it.
|
|
const slot = html.match(/data-sketch="(\/img\/\d+)"/)?.[1];
|
|
assert.ok(slot, 'sketch slot registered before the file exists');
|
|
assert.equal((await fetch(url.replace(/\/$/, '') + slot)).status, 404);
|
|
const { mkdirSync } = await import('node:fs');
|
|
mkdirSync(path.dirname(sketchPath), { recursive: true });
|
|
writeFileSync(sketchPath, 'RIFFxxxxWEBP');
|
|
assert.equal((await fetch(url.replace(/\/$/, '') + slot)).status, 200);
|
|
// The page polls with a cache-busting query; the route must tolerate it.
|
|
assert.equal((await fetch(url.replace(/\/$/, '') + slot + '?t=1')).status, 200);
|
|
// The answer carries the chosen card's sketch for comp seeding.
|
|
await fetch(`${url}answer`, {
|
|
method: 'POST',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ optionId: 'assigned', steer: '' }),
|
|
});
|
|
const code = await new Promise((resolve) => child.on('exit', resolve));
|
|
assert.equal(code, 0);
|
|
assert.match(read(), /"sketch":/);
|
|
assert.match(read(), /CHOSEN SKETCH:/);
|
|
});
|
|
});
|