mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-11 21:57:14 +03:00
Hero gate reads type, strips, and invented ink as numbers; every region needs a note; missing beats the text relaxation
From the first human review of sweep-3 builds (pins on 12 samples): fonts at the wrong size, weight, colour, or place; nav bars too tall; kickers and dividers the comp does not have; a footer strip pushed off the frame that read as drift on ground colour alone; a drawing filed as chrome with no note to catch it. - lib/hero-checks.mjs: textRegionCheck (cap height, line count, ink density, ink colour, first-line offset vs the comp crop, measured fresh), chromeStripCheck (first rule row), inventedInk (build energy over a calm comp cell and neighbourhood). Wired into gateHero as reasons; invented ink vetoes at 4% of cells. - comp-diff verdictFor: detailRaw < 0.15 is missing whatever the palette. - comp-spec: every region carries a note. - font-fingerprint: the tall-line filter takes its median over lines with real mass, so two display lines above a small line are not 'tall'. AI-assisted (Claude Code).
This commit is contained in:
@@ -101,9 +101,9 @@ When an approved comp exists, it is a spatial contract, not a mood board: only t
|
||||
Then, in order, each closed by `node {{scripts_path}}/build-phase.mjs advance` (every script below lives under `{{scripts_path}}/` and runs with `node`; exit 2 means the gate failed and printed why; fix that and advance again; write nothing for a later phase while an earlier gate is open):
|
||||
|
||||
0. **comps.** The comp round from [visualize.md](visualize.md): three compositional comps of the requested surface at its own viewport under `.impeccable/mocks/`, each with a prompt sidecar, put in front of the user; the chosen one's sidecar gets `"approved": true`. The gate counts them and reads the approval; a `start --comp` skips this phase because it already happened.
|
||||
1. **spec.** Measure the comp: `comp-spec.mjs --comp <comp> --grid` writes a coordinate grid over the comp; open it, name every salient region by grid span in a regions file (kind `plate` / `image` / `texture` for anything painted: every illustration, photograph, figure, product object, and material texture; `text` / `control` / `chrome` for what code draws), and run `comp-spec.mjs --comp <comp> --regions <file>`. The spec carries each region's box, sampled palette, and medium; `comp-spec.mjs --print` is the build's reference from here on. Type is measured, not guessed: `font-match.mjs --measure <text region>` reads the comp's cap height, width class, and weight off the pixels, and `font-match.mjs --rank <region> --text "..."` takes its candidates from a fingerprint index of the Google Fonts catalog (the nearest faces to the crop's shape) plus any names you pass with `--candidates`, renders them at that cap height with the region's words, and ranks them by fingerprint distance (its `USE` line is the CSS; its proof sheet shows the comp over the top three); with no browser resolvable it records the catalog's nearest face and says the size is estimated, which is still the choice to build on. Do not install a browser to rank, and never write a `chosen` face into the spec by hand: the gate accepts only what font-match wrote. The spec gate refuses to close until the lead text region is measured and ranked. A region note that describes painted material (a diagram, drawing, photograph, texture) under a code kind is refused at the spec: reclassify it as a plate, or reword the note if code really draws it. The script refuses a regions file that leaves comp ink unnamed (callouts, a parts table, a notes block): what is never named can never be missing, so everything the comp shows gets a region. It also refuses a `text` / `control` / `chrome` region larger than a quarter of the comp: that is a column, not an element, and a column scored as one region hides the plates, tables, and notes inside it. Name each element inside it (`container: true` only when it truly is one undivided element). Anything not in the spec does not exist on the page: no borders, rules, containers, or chrome the comp does not show. Only three concessions exist: fonts (the closest obtainable face), icons (exact match unless the user chose an icon library), and genuine defects in the comp such as spelling errors. <!-- rule:skill-comp-spec -->
|
||||
1. **spec.** Measure the comp: `comp-spec.mjs --comp <comp> --grid` writes a coordinate grid over the comp; open it, name every salient region by grid span in a regions file (kind `plate` / `image` / `texture` for anything painted: every illustration, photograph, figure, product object, and material texture; `text` / `control` / `chrome` for what code draws; every region carries a `note` saying what the comp shows there, which the plate prompt and the gate messages read), and run `comp-spec.mjs --comp <comp> --regions <file>`. The spec carries each region's box, sampled palette, and medium; `comp-spec.mjs --print` is the build's reference from here on. Type is measured, not guessed: `font-match.mjs --measure <text region>` reads the comp's cap height, width class, and weight off the pixels, and `font-match.mjs --rank <region> --text "..."` takes its candidates from a fingerprint index of the Google Fonts catalog (the nearest faces to the crop's shape) plus any names you pass with `--candidates`, renders them at that cap height with the region's words, and ranks them by fingerprint distance (its `USE` line is the CSS; its proof sheet shows the comp over the top three); with no browser resolvable it records the catalog's nearest face and says the size is estimated, which is still the choice to build on. Do not install a browser to rank, and never write a `chosen` face into the spec by hand: the gate accepts only what font-match wrote. The spec gate refuses to close until the lead text region is measured and ranked. A region note that describes painted material (a diagram, drawing, photograph, texture) under a code kind is refused at the spec: reclassify it as a plate, or reword the note if code really draws it. The script refuses a regions file that leaves comp ink unnamed (callouts, a parts table, a notes block): what is never named can never be missing, so everything the comp shows gets a region. It also refuses a `text` / `control` / `chrome` region larger than a quarter of the comp: that is a column, not an element, and a column scored as one region hides the plates, tables, and notes inside it. Name each element inside it (`container: true` only when it truly is one undivided element). Anything not in the spec does not exist on the page: no borders, rules, containers, or chrome the comp does not show. Only three concessions exist: fonts (the closest obtainable face), icons (exact match unless the user chose an icon library), and genuine defects in the comp such as spelling errors. <!-- rule:skill-comp-spec -->
|
||||
2. **plates.** Every raster region ships as a plate: an illustration, photo, or figure regenerated at asset resolution from its comp crop, UI text removed, at its `plate` path (ink on flat ground is generated on a chroma key and keyed to alpha, so it sits on the page's own ground rather than a second paper); a texture (paper, cloth, grain) is a clean patch of the comp region mirror-tiled to size, generated only when no clean patch exists. `generate-image.mjs --plate <id>` does one region end to end and scores it against the crop; a harness-native image tool takes the crop (`comp-spec.mjs --crop <id>`) as its input image and `comp-spec.mjs --plate-prompt <id>` as its prompt, then `embed-prompt.mjs`. With parallel subagents, spawn the shipped asset producer (`impeccable-asset-producer`; `impeccable_asset_producer` in codex; `/impeccable-asset-producer` in Cursor; on GitHub Copilot say "Use the impeccable-asset-producer agent") with the spec path and let it produce them all; without subagents, produce them here. A crop of the comp is a reference, never a shipping pixel. The gate checks every plate exists, is at least 1.5x the region's size, and reads as the region. Page code waits for this gate: a page written before its plates exist is a page that draws its material in CSS. A single-file deliverable changes nothing here: the plate is produced the same way and inlined as a data URI. `--force` exists for one case only, the user downgrading the comp's authority in words you quote in `--reason`; the script refuses every other reason. <!-- rule:skill-plates-before-page -->
|
||||
3. **hero.** Build only the first viewport, at the comp's own dimensions, the comp's words copied verbatim (the user approved that comp with those words; rewording is a stated decision after the hero passes, never a silent one inside it), every text region sized from its measured cap height and set in its ranked face, plates first: place every plate at its spec box (`object-fit: cover`, an `<img>`, a background image, or an inlined data URI named for it) before any text or control, capture into `.impeccable/review/hero-repro.png`, run `build-phase.mjs record hero` once so you see the plate regions read as match before any text exists, then lay the semantic layer over the plates from the spec's palette and boxes and advance. The gate first refuses while any plate is unreferenced by the source, then runs `comp-diff.mjs`, writes `.impeccable/review/diff/hero/` (side-by-side, heatmap, one paired crop per region, `report.json`), and passes at 72% overall with no region missing. When it fails, open the region crops it lists, in order, before editing: a region scored `missing` needs its material, `contradicted` needs its structure re-derived from the spec box, `drift` is where size and spacing edits belong; the gate refuses a third attempt that only nudges values on the same region. This is where the run's ambition is won or lost, and a retry here costs minutes where a rebuild verdict at the finish costs the run. <!-- rule:skill-hero-gate -->
|
||||
3. **hero.** Build only the first viewport, at the comp's own dimensions, the comp's words copied verbatim (the user approved that comp with those words; rewording is a stated decision after the hero passes, never a silent one inside it), every text region sized from its measured cap height and set in its ranked face, plates first: place every plate at its spec box (`object-fit: cover`, an `<img>`, a background image, or an inlined data URI named for it) before any text or control, capture into `.impeccable/review/hero-repro.png`, run `build-phase.mjs record hero` once so you see the plate regions read as match before any text exists, then lay the semantic layer over the plates from the spec's palette and boxes and advance. The gate first refuses while any plate is unreferenced by the source, then runs `comp-diff.mjs`, writes `.impeccable/review/diff/hero/` (side-by-side, heatmap, one paired crop per region, `report.json`), and passes at 72% overall with no region missing and no reading outstanding: the gate also reads each text region's cap height, line count, weight, ink colour, and position against the comp, each chrome strip's height off its rule, and the frame for ink where the comp is calm (a kicker, an extra nav item, a divider), and says each miss as a number ("cap height 78px in the build, 103px in the comp"); those numbers are the edit. When it fails, open the region crops it lists, in order, before editing: a region scored `missing` needs its material, `contradicted` needs its structure re-derived from the spec box, `drift` is where size and spacing edits belong; the gate refuses a third attempt that only nudges values on the same region. This is where the run's ambition is won or lost, and a retry here costs minutes where a rebuild verdict at the finish costs the run. <!-- rule:skill-hero-gate -->
|
||||
4. **sections.** Build the rest of the surface inside the spec's system: the same corner language, line weights, and palette, and nothing the comp never shows. Where the comp does not cover a region, it inherits the recorded system.
|
||||
5. **motion.** The signature interaction, reveals, and motion, orchestrated once rather than scattered.
|
||||
6. **responsive.** The other viewports, and the first viewport at common desktop widths (1280 to 1600), not only at the comp's exact size: fluid columns, no fixed-pixel grid that wraps a hundred pixels narrower. Capture `desktop.png` (1440 wide, full page) and `mobile.png` (390 wide) into `.impeccable/review/`; the gate diffs the desktop capture against the comp and refuses a first viewport that only held at the comp's width. A comp'd surface that is mobile-first was comped portrait; the plates were produced for that frame.
|
||||
|
||||
@@ -69,7 +69,8 @@ import { createRequire } from 'node:module';
|
||||
import { decodePng, loadRaster } from './lib/png.mjs';
|
||||
const require = createRequire(import.meta.url);
|
||||
import { crop, createImage, blit } from './lib/raster.mjs';
|
||||
import { compare, verdictFor } from './comp-diff.mjs';
|
||||
import { compare, verdictFor, alignBuild, bestShift } from './comp-diff.mjs';
|
||||
import { textRegionCheck, chromeStripCheck, inventedInk } from './lib/hero-checks.mjs';
|
||||
import { SPEC_PATH, BUILD_DIR, loadSpec, plateReference } from './comp-spec.mjs';
|
||||
import { choiceStamped } from './font-match.mjs';
|
||||
|
||||
@@ -357,6 +358,32 @@ export function organicClipRegions(artifactFile, spec) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Fraction of grid cells with invented ink that fails the hero. */
|
||||
export const INVENTED_MIN = 0.04;
|
||||
|
||||
/**
|
||||
* Text, chrome and invented-ink readings for the hero: the comp and the
|
||||
* build aligned the way comp-diff aligns them, then per-region checks from
|
||||
* lib/hero-checks.mjs. Returns { text: [], chrome: [], invented }.
|
||||
*/
|
||||
export function heroReadings(state, spec, buildPath) {
|
||||
if (!spec || !state.comp) return null;
|
||||
const comp = loadRaster(state.comp).image;
|
||||
const build = loadRaster(buildPath).image;
|
||||
let aligned = alignBuild(comp, build, 'top');
|
||||
const shift = bestShift(comp, aligned);
|
||||
if (shift.dx || shift.dy) { const shifted = createImage(aligned.width, aligned.height, [255, 255, 255, 255]); blit(shifted, aligned, -shift.dx, -shift.dy); aligned = shifted; }
|
||||
const text = [], chrome = [];
|
||||
for (const r of spec.regions) {
|
||||
if (!r.px) continue;
|
||||
const a = crop(comp, r.px.x, r.px.y, r.px.w, r.px.h), b = crop(aligned, r.px.x, r.px.y, r.px.w, r.px.h);
|
||||
if (r.kind === 'text') { const t = textRegionCheck(r, a, b); text.push(...t.findings); }
|
||||
else if (r.kind === 'chrome' || r.kind === 'control') { const c = chromeStripCheck(r, a, b); chrome.push(...c.findings); }
|
||||
}
|
||||
const invented = inventedInk(comp, aligned);
|
||||
return { text, chrome, invented };
|
||||
}
|
||||
|
||||
export function gateHero(state, { buildPath = HERO_REPRO, specPath = SPEC_PATH, min = HERO_MIN, outDir = path.join('.impeccable', 'review', 'diff', 'hero'), artifact = null } = {}) {
|
||||
if (!fs.existsSync(buildPath)) return { ok: false, reasons: [`no hero capture at ${buildPath}: screenshot the first viewport at the comp's own dimensions (${state.breakpoint || 'comp size'}) into that path`] };
|
||||
const specForRefs = loadSpec(specPath);
|
||||
@@ -469,6 +496,20 @@ export function gateHero(state, { buildPath = HERO_REPRO, specPath = SPEC_PATH,
|
||||
const organic = organicClipRegions(artifactFile, specForRefs);
|
||||
for (const r of organic) reasons.push(`artifact draws an organic clip-path (${r.snippet}) inside raster region ${r.id}'s box; that region ships as its plate, never as a polygon`);
|
||||
}
|
||||
// Numbers a designer reads off the side-by-side: type set at the wrong
|
||||
// size, weight, colour, or place; a nav bar too tall; ink where the comp
|
||||
// has none (a kicker, a divider, a second row). Each was a pin in the
|
||||
// first human review of builds the region scores had passed.
|
||||
let readings = null;
|
||||
try { readings = heroReadings(state, specForRefs, buildPath); } catch (e) { reasons.push(`hero readings errored (${e.message}); the region scores above stand`); }
|
||||
if (readings) {
|
||||
for (const f of readings.text) reasons.push(f);
|
||||
for (const f of readings.chrome) reasons.push(f);
|
||||
if (readings.invented && readings.invented.fraction >= INVENTED_MIN) {
|
||||
const cells = readings.invented.cells.map((c) => c.label);
|
||||
reasons.push(`the build carries ink in ${cells.length} grid cells where the comp is calm (${cells.slice(0, 12).join(', ')}${cells.length > 12 ? ', ...' : ''}); nothing exists on the page that the comp does not show (a kicker, an extra nav item, a divider, a second row of controls); remove it or name it in a stated decision after the hero passes`);
|
||||
}
|
||||
}
|
||||
const worstRegions = [...report.regions].sort((a, b) => a.score.overall - b.score.overall).slice(0, 3);
|
||||
const regionDir = path.join(outDir, 'regions');
|
||||
return {
|
||||
|
||||
@@ -133,6 +133,12 @@ export function bestShift(comp, build, workWidth = 256) {
|
||||
|
||||
export function verdictFor(s, kind = null) {
|
||||
const painted = kind === 'plate' || kind === 'image' || kind === 'texture';
|
||||
// Nothing drawn where the comp drew something is missing whatever the
|
||||
// palette says: a footer strip the build pushed below the fold read as
|
||||
// 'drift' on ground colour alone (detail 4%, structure 92%). detailRaw is
|
||||
// 1 when the comp region itself is calm, so a low value already means the
|
||||
// comp had material there.
|
||||
if (s.detailRaw != null && s.detailRaw < 0.15) return 'missing';
|
||||
if (painted && s.detail < 0.5) return 'missing';
|
||||
// For text, chrome, and controls "missing" means the build has nothing
|
||||
// there, not that a thin strip sits a few pixels off: require the build's
|
||||
|
||||
@@ -135,6 +135,13 @@ export function measureRegions(comp, regionsInput, compPath) {
|
||||
if (seen.has(raw.id)) throw new Error(`duplicate region id ${raw.id}`);
|
||||
seen.add(raw.id);
|
||||
const kind = raw.kind && KINDS.has(raw.kind) ? raw.kind : 'band';
|
||||
// Every region says what it is. The note is what the plate prompt, the
|
||||
// gate messages, and the painted-material check read; a regions file of
|
||||
// bare ids and kinds is a list of boxes, and a session that named a
|
||||
// carburetor drawing "chrome" with no note was caught by nothing.
|
||||
if (kind !== 'band' && !(raw.note && String(raw.note).trim().length >= 8)) {
|
||||
throw new Error(`region ${raw.id} has no note. Say in a few words what the comp shows there (the element, its material, its role): the note drives the plate prompt and the gate's messages, and a drawing named as chrome is only caught by what its note says.`);
|
||||
}
|
||||
// The note is the model's own reading of the region. A note that names
|
||||
// painted material (a drawing, diagram, photo, illustration, texture)
|
||||
// filed under a code kind is a plate about to be redrawn in SVG: the
|
||||
|
||||
@@ -134,8 +134,14 @@ function findLines(bin) {
|
||||
// carburetor drawing). When several lines exist, ones far taller than the
|
||||
// median are not lettering: leave them out of the mass reference and out
|
||||
// of the result.
|
||||
if (lines.length >= 3) {
|
||||
const hs = lines.map((l) => l.y1 - l.y0).sort((a, b) => a - b);
|
||||
// The median is taken over lines carrying real mass (rule slivers and
|
||||
// tittles do not vote), and needs three of them: two 145px headline lines
|
||||
// above a 26px artist line were dropped as 'tall' against a median pulled
|
||||
// to 28 by three slivers.
|
||||
const massMax = Math.max(1, ...lines.map((l) => l.mass));
|
||||
const real = lines.filter((l) => l.mass >= massMax * 0.05);
|
||||
if (real.length >= 3) {
|
||||
const hs = real.map((l) => l.y1 - l.y0).sort((a, b) => a - b);
|
||||
const medH = hs[Math.floor(hs.length / 2)];
|
||||
for (const ln of lines) if (ln.y1 - ln.y0 > medH * 3) ln.tall = true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* Hero-gate checks that name a miss as a number the model can act on.
|
||||
*
|
||||
* comp-diff scores regions; these read what a designer reads when the two
|
||||
* frames sit side by side and says it as numbers: the headline is set at
|
||||
* cap 78px where the comp's is 103; it wraps to four lines where the comp
|
||||
* has three; its ink is #2a2a2a where the comp's is #a72f1b; it starts
|
||||
* 60px lower in its box; the masthead is 92px tall where the comp's is 58;
|
||||
* these grid cells carry ink the comp does not have (a kicker, a divider, a
|
||||
* second nav row). Every one of those was a pin in the first human review
|
||||
* of the third sweep, on builds the region scores had already let through.
|
||||
*
|
||||
* All functions are pure over decoded rasters and the spec; the gate wires
|
||||
* them and decides what vetoes.
|
||||
*/
|
||||
import { fingerprint } from './font-fingerprint.mjs';
|
||||
import { crop } from './raster.mjs';
|
||||
import { dominantColors, deltaE, detailGrid } from './image-metrics.mjs';
|
||||
import { inkBox } from '../comp-diff.mjs';
|
||||
|
||||
/** Dominant ink colour of a crop: the heaviest cluster that is not the ground. */
|
||||
export function inkColor(img) {
|
||||
const cols = dominantColors(img, 4);
|
||||
if (!cols.length) return null;
|
||||
const ground = cols[0];
|
||||
const ink = cols.find((c) => c !== ground && deltaE(c.lab, ground.lab) > 20) || null;
|
||||
return { ground, ink };
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare one text region's build crop against the comp's measurement.
|
||||
* `region` is a spec region with `type.comp` (font-match --measure) and
|
||||
* `px`; `compCrop` / `buildCrop` are the region crops at comp scale.
|
||||
* Returns { findings: string[], metrics }.
|
||||
*/
|
||||
export function textRegionCheck(region, compCrop, buildCrop, { capTol = 0.22, minCap = 10 } = {}) {
|
||||
const findings = [];
|
||||
// Measure the comp crop now rather than trusting spec.type.comp: the spec
|
||||
// may carry an older fingerprint's reading, and this check has to agree
|
||||
// with itself on both sides.
|
||||
const comp = fingerprint(compCrop);
|
||||
if (!comp || !comp.capHeightPx || comp.capHeightPx < minCap || comp.glyphs < 6) return { findings, metrics: null };
|
||||
// rotated type (a spine set vertical) reads as many short 'lines' of one
|
||||
// or two glyphs; the fingerprint has nothing to say about it
|
||||
if (comp.lines >= 5 && comp.glyphs / comp.lines < 3) return { findings, metrics: null };
|
||||
// a cap taller than half the box is a drawing read as a glyph, not type
|
||||
if (comp.capHeightPx > compCrop.height * 0.6) return { findings, metrics: null };
|
||||
const bfp = fingerprint(buildCrop);
|
||||
const metrics = { comp: { cap: comp.capHeightPx, lines: comp.lines, glyphs: comp.glyphs }, build: bfp ? { cap: bfp.capHeightPx, lines: bfp.lines, glyphs: bfp.glyphs } : null };
|
||||
if (!bfp || bfp.glyphs < 4) {
|
||||
// nothing legible in the box: comp-diff's missing/contradicted covers it
|
||||
return { findings, metrics };
|
||||
}
|
||||
const capDelta = (bfp.capHeightPx - comp.capHeightPx) / comp.capHeightPx;
|
||||
if (Math.abs(capDelta) > capTol) {
|
||||
findings.push(`text ${region.id}: cap height ${bfp.capHeightPx}px in the build, ${comp.capHeightPx}px in the comp (${capDelta > 0 ? '+' : ''}${Math.round(capDelta * 100)}%); set font-size so the cap height renders at ${comp.capHeightPx}px${region.type.chosen ? ` (font-match ranked ${region.type.chosen.family} ${region.type.chosen.weight} at ${region.type.chosen.fontSizePx}px)` : ''}`);
|
||||
}
|
||||
if (comp.lines >= 2 && bfp.lines !== comp.lines && Math.abs(bfp.lines - comp.lines) >= 1) {
|
||||
findings.push(`text ${region.id}: ${bfp.lines} line${bfp.lines === 1 ? '' : 's'} in the build, ${comp.lines} in the comp; the measure (max-width, font-size, letter-spacing) wraps it differently, so the block is a different shape`);
|
||||
}
|
||||
// weight: compare ink density of tall glyphs when both sides have it and
|
||||
// the sizes agree (density at a different cap is a different reading)
|
||||
if (comp.densTall != null && bfp.densTall != null && Math.abs(capDelta) <= capTol) {
|
||||
const r = bfp.densTall / comp.densTall;
|
||||
if (r > 1.25) findings.push(`text ${region.id}: the face renders ${Math.round((r - 1) * 100)}% heavier than the comp's (ink density ${bfp.densTall.toFixed(2)} vs ${comp.densTall.toFixed(2)}); drop a weight step or use the ranked face`);
|
||||
else if (r < 0.75) findings.push(`text ${region.id}: the face renders ${Math.round((1 - r) * 100)}% lighter than the comp's (ink density ${bfp.densTall.toFixed(2)} vs ${comp.densTall.toFixed(2)}); raise a weight step or use the ranked face`);
|
||||
}
|
||||
// colour: dominant ink of each crop
|
||||
const ca = inkColor(compCrop), cb = inkColor(buildCrop);
|
||||
if (ca && cb && ca.ink && cb.ink) {
|
||||
const d = deltaE(ca.ink.lab, cb.ink.lab);
|
||||
if (d > 22) findings.push(`text ${region.id}: ink is ${cb.ink.hex} in the build, ${ca.ink.hex} in the comp; use the comp's colour`);
|
||||
}
|
||||
// vertical placement inside the box: top of ink
|
||||
const ba = inkBox(compCrop), bb = inkBox(buildCrop);
|
||||
if (ba && bb) {
|
||||
const dy = bb.y - ba.y;
|
||||
if (Math.abs(dy) > Math.max(12, compCrop.height * 0.15)) findings.push(`text ${region.id}: its first line starts ${Math.abs(Math.round(dy))}px ${dy > 0 ? 'lower' : 'higher'} than in the comp (${bb.y}px vs ${ba.y}px into the region box); the spacing above it is ${dy > 0 ? 'too large' : 'too small'}`);
|
||||
const dx = bb.x - ba.x;
|
||||
if (Math.abs(dx) > Math.max(12, compCrop.width * 0.15)) findings.push(`text ${region.id}: it starts ${Math.abs(Math.round(dx))}px ${dx > 0 ? 'further right' : 'further left'} than in the comp`);
|
||||
}
|
||||
metrics.capDelta = +capDelta.toFixed(3);
|
||||
return { findings, metrics };
|
||||
}
|
||||
|
||||
/**
|
||||
* Rows of a crop that carry a horizontal rule: a row whose gray step from
|
||||
* the row above (or below) is strong across at least `span` of the width.
|
||||
* Returns row indices sorted top to bottom.
|
||||
*/
|
||||
export function ruleRows(img, { span = 0.5, step = 28 } = {}) {
|
||||
const W = img.width, H = img.height;
|
||||
const gray = (x, y) => { const i = (y * W + x) * 4; return 0.299 * img.data[i] + 0.587 * img.data[i + 1] + 0.114 * img.data[i + 2]; };
|
||||
const rows = [];
|
||||
for (let y = 1; y < H - 1; y++) {
|
||||
let strong = 0;
|
||||
for (let x = 0; x < W; x++) { const d = Math.max(Math.abs(gray(x, y) - gray(x, y - 1)), Math.abs(gray(x, y) - gray(x, y + 1))); if (d > step) strong++; }
|
||||
if (strong >= W * span) rows.push(y);
|
||||
}
|
||||
// collapse adjacent rows into one edge
|
||||
const out = [];
|
||||
for (const y of rows) if (!out.length || y - out[out.length - 1] > 3) out.push(y);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A thin chrome region (masthead, nav bar, footer strip) has a height, and
|
||||
* its height is where its rule sits. Compare the first horizontal rule's row
|
||||
* in comp vs build; fall back to the ink extents when neither has a rule.
|
||||
*/
|
||||
export function chromeStripCheck(region, compCrop, buildCrop) {
|
||||
const findings = [];
|
||||
const strip = compCrop.height <= compCrop.width * 0.35;
|
||||
if (!strip) return { findings };
|
||||
const ra = ruleRows(compCrop), rb = ruleRows(buildCrop);
|
||||
if (ra.length && rb.length) {
|
||||
// the rule that closes the strip is the first one from the top (a grid
|
||||
// row often carries the next element's top edge lower down)
|
||||
const ya = ra[0], yb = rb[0];
|
||||
const dy = yb - ya;
|
||||
if (Math.abs(dy) > Math.max(5, compCrop.height * 0.06)) findings.push(`${region.kind} ${region.id}: its rule sits ${ya}px into the box in the comp and ${yb}px in the build (${dy > 0 ? '+' : ''}${dy}px), so the strip is ${dy > 0 ? 'taller' : 'shorter'} than the comp's; match the height, not only the position`);
|
||||
return { findings, comp: ya, build: yb };
|
||||
}
|
||||
const ba = inkBox(compCrop), bb = inkBox(buildCrop);
|
||||
if (!ba || !bb) return { findings };
|
||||
if (ba.w >= compCrop.width * 0.6 && ba.h <= compCrop.height * 0.6) {
|
||||
const dh = bb.h - ba.h;
|
||||
if (Math.abs(dh) > Math.max(10, ba.h * 0.25)) findings.push(`${region.kind} ${region.id}: its ink is ${bb.h}px tall in the build and ${ba.h}px in the comp (${dh > 0 ? '+' : ''}${dh}px); match the height, not only the position`);
|
||||
}
|
||||
return { findings, comp: ba, build: bb };
|
||||
}
|
||||
|
||||
/**
|
||||
* Cells of the frame where the build carries ink and the comp is calm.
|
||||
* Returns { cells: [{col,row,label}], fraction } on a cols x rows grid.
|
||||
* `floor` is the comp energy under which a cell counts as calm; `added` is
|
||||
* the build energy over which the build counts as inked.
|
||||
*/
|
||||
export function inventedInk(comp, build, { cols = 10, rows = 10, floor = 10, added = 12, ratio = 2.5 } = {}) {
|
||||
const a = detailGrid(comp, cols, rows, 512), b = detailGrid(build, cols, rows, 512);
|
||||
const cells = [];
|
||||
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
|
||||
const i = r * cols + c;
|
||||
// calm in the comp (grain, flat ground) and inked in the build well past
|
||||
// what grain would give: a kicker over paper, a divider, a nav row
|
||||
if (!(a.cells[i] < floor && b.cells[i] > Math.max(added, a.cells[i] * ratio))) continue;
|
||||
// the comp must be calm around the cell too: a hard edge one pixel over
|
||||
// the cell boundary in the build (a bar shifted by a subpixel of the
|
||||
// alignment) reads as invented otherwise
|
||||
let neighbourhood = 0, n = 0;
|
||||
for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) { const rr = r + dr, cc = c + dc; if (rr < 0 || cc < 0 || rr >= rows || cc >= cols) continue; neighbourhood += a.cells[rr * cols + cc]; n++; }
|
||||
if (neighbourhood / n >= floor * 2) continue;
|
||||
cells.push({ col: c, row: r, label: `${String.fromCharCode(65 + c)}${r}`, comp: +a.cells[i].toFixed(1), build: +b.cells[i].toFixed(1) });
|
||||
}
|
||||
return { cells, fraction: cells.length / (cols * rows) };
|
||||
}
|
||||
+15
-15
@@ -48,7 +48,7 @@ describe('comp-spec', () => {
|
||||
it('measures regions with palette, pixel box, medium, and plate path', () => {
|
||||
const comp = makeComp();
|
||||
const spec = measureRegions(comp, { allowUncovered: true, regions: [
|
||||
{ id: 'masthead', kind: 'chrome', grid: 'A0:J0' },
|
||||
{ id: 'masthead', kind: 'chrome', grid: 'A0:J0', note: 'navy masthead bar' },
|
||||
{ id: 'art', kind: 'plate', grid: 'F1:J4', note: 'noise plate' },
|
||||
] }, 'comp.png');
|
||||
assert.equal(spec.regions.length, 2);
|
||||
@@ -76,18 +76,18 @@ describe('comp-spec', () => {
|
||||
|
||||
it('refuses a code region that covers a column of the comp, unless container', () => {
|
||||
const comp = makeComp();
|
||||
assert.throws(() => measureRegions(comp, { allowUncovered: true, regions: [{ id: 'parts-column', kind: 'chrome', grid: 'G0:J9' }] }, 'c.png'), /covers 40% of the comp/);
|
||||
const ok = measureRegions(comp, { allowUncovered: true, regions: [{ id: 'parts-column', kind: 'chrome', grid: 'G0:J9', container: true }] }, 'c.png');
|
||||
assert.throws(() => measureRegions(comp, { allowUncovered: true, regions: [{ id: 'parts-column', kind: 'chrome', grid: 'G0:J9', note: 'right column of parts' }] }, 'c.png'), /covers 40% of the comp/);
|
||||
const ok = measureRegions(comp, { allowUncovered: true, regions: [{ id: 'parts-column', kind: 'chrome', grid: 'G0:J9', container: true, note: 'right column of parts' }] }, 'c.png');
|
||||
assert.equal(ok.regions[0].kind, 'chrome');
|
||||
const plate = measureRegions(comp, { allowUncovered: true, regions: [{ id: 'art', kind: 'plate', grid: 'G0:J9' }] }, 'c.png');
|
||||
const plate = measureRegions(comp, { allowUncovered: true, regions: [{ id: 'art', kind: 'plate', grid: 'G0:J9', note: 'noise plate' }] }, 'c.png');
|
||||
assert.equal(plate.regions[0].medium, 'raster');
|
||||
});
|
||||
|
||||
it('refuses a regions file that leaves comp ink unnamed, unless allowUncovered', () => {
|
||||
const comp = makeComp();
|
||||
// only the masthead named: the headline, plate, and list are ink no region covers
|
||||
assert.throws(() => measureRegions(comp, { regions: [{ id: 'masthead', kind: 'chrome', grid: 'A0:J0' }] }, 'c.png'), /carry ink no region names/);
|
||||
const spec = measureRegions(comp, { allowUncovered: true, regions: [{ id: 'masthead', kind: 'chrome', grid: 'A0:J0' }] }, 'c.png');
|
||||
assert.throws(() => measureRegions(comp, { regions: [{ id: 'masthead', kind: 'chrome', grid: 'A0:J0', note: 'navy masthead bar' }] }, 'c.png'), /carry ink no region names/);
|
||||
const spec = measureRegions(comp, { allowUncovered: true, regions: [{ id: 'masthead', kind: 'chrome', grid: 'A0:J0', note: 'navy masthead bar' }] }, 'c.png');
|
||||
assert.ok(spec.uncoveredInkCells.length > 3);
|
||||
});
|
||||
|
||||
@@ -155,10 +155,10 @@ describe('build-phase state machine (CLI)', () => {
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'build-phase-'));
|
||||
fs.writeFileSync(path.join(dir, 'comp.png'), encodePng(makeComp()));
|
||||
fs.writeFileSync(path.join(dir, 'regions.json'), JSON.stringify({ regions: [
|
||||
{ id: 'masthead', kind: 'chrome', grid: 'A0:J0' },
|
||||
{ id: 'headline', kind: 'text', grid: 'A1:D2' },
|
||||
{ id: 'masthead', kind: 'chrome', grid: 'A0:J0', note: 'navy masthead bar' },
|
||||
{ id: 'headline', kind: 'text', grid: 'A1:D2', note: 'two-line block headline' },
|
||||
{ id: 'art', kind: 'plate', grid: 'F1:J4', note: 'noise plate' },
|
||||
{ id: 'list', kind: 'control', grid: 'A5:J9', container: true },
|
||||
{ id: 'list', kind: 'control', grid: 'A5:J9', container: true, note: 'ruled list rows' },
|
||||
] }));
|
||||
});
|
||||
after(() => { try { fs.rmSync(dir, { recursive: true, force: true }); } catch {} });
|
||||
@@ -242,7 +242,7 @@ describe('build-phase state machine (CLI)', () => {
|
||||
fs.writeFileSync(path.join(dir, '.impeccable', 'review', 'hero-repro.png'), encodePng(flat));
|
||||
// no source references the plate yet: refused before any diff runs
|
||||
let res = run(PHASE_SCRIPT, ['advance'], dir);
|
||||
assert.equal(res.status, 2, res.stdout);
|
||||
assert.equal(res.status, 2, res.stdout + res.stderr);
|
||||
assert.match(res.stdout, /not referenced by any source file/);
|
||||
fs.writeFileSync(path.join(dir, 'index.html'), '<img src="assets/plates/art.png" alt="">');
|
||||
res = run(PHASE_SCRIPT, ['advance'], dir);
|
||||
@@ -285,8 +285,8 @@ describe('build-phase state machine (CLI)', () => {
|
||||
fillRect(comp, 40, 300, 160, 40, [19, 33, 48, 255]);
|
||||
fs.writeFileSync(path.join(d4, 'comp.png'), encodePng(comp));
|
||||
fs.writeFileSync(path.join(d4, 'regions.json'), JSON.stringify({ allowUncovered: true, regions: [
|
||||
{ id: 'masthead', kind: 'chrome', grid: 'A0:J0' },
|
||||
{ id: 'cta', kind: 'control', box: { x: 0, y: 0.5, w: 0.5, h: 0.5 } },
|
||||
{ id: 'masthead', kind: 'chrome', grid: 'A0:J0', note: 'navy masthead bar' },
|
||||
{ id: 'cta', kind: 'control', box: { x: 0, y: 0.5, w: 0.5, h: 0.5 }, note: 'black CTA button' },
|
||||
] }));
|
||||
run(PHASE_SCRIPT, ['start', '--comp', 'comp.png', '--artifact', 'index.html'], d4);
|
||||
run(SPEC_SCRIPT, ['--comp', 'comp.png', '--regions', 'regions.json'], d4);
|
||||
@@ -312,9 +312,9 @@ describe('build-phase state machine (CLI)', () => {
|
||||
const comp = makeComp();
|
||||
fs.writeFileSync(path.join(d3, 'comp.png'), encodePng(comp));
|
||||
fs.writeFileSync(path.join(d3, 'regions.json'), JSON.stringify({ allowUncovered: true, regions: [
|
||||
{ id: 'masthead', kind: 'chrome', grid: 'A0:J0' },
|
||||
{ id: 'art', kind: 'plate', grid: 'F1:J4' },
|
||||
{ id: 'list', kind: 'control', grid: 'A5:J9', container: true },
|
||||
{ id: 'masthead', kind: 'chrome', grid: 'A0:J0', note: 'navy masthead bar' },
|
||||
{ id: 'art', kind: 'plate', grid: 'F1:J4', note: 'noise plate' },
|
||||
{ id: 'list', kind: 'control', grid: 'A5:J9', container: true, note: 'ruled list rows' },
|
||||
] }));
|
||||
run(PHASE_SCRIPT, ['start', '--comp', 'comp.png', '--artifact', 'index.html'], d3);
|
||||
run(SPEC_SCRIPT, ['--comp', 'comp.png', '--regions', 'regions.json'], d3);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createImage, fillRect, drawText } from '../skill/scripts/lib/raster.mjs';
|
||||
import { textRegionCheck, chromeStripCheck, inventedInk, ruleRows, inkColor } from '../skill/scripts/lib/hero-checks.mjs';
|
||||
|
||||
const paper = [235, 232, 220, 255], ink = [20, 20, 20, 255];
|
||||
function textCrop({ scale = 4, lines = 2, color = ink, y0 = 20, x0 = 12, w = 460, h = 200 } = {}) {
|
||||
const img = createImage(w, h, paper);
|
||||
for (let i = 0; i < lines; i++) drawText(img, 'KEEP OLD IRON', x0, y0 + i * (scale * 9), color, scale);
|
||||
return img;
|
||||
}
|
||||
|
||||
describe('hero-checks: text regions', () => {
|
||||
const region = { id: 'headline', kind: 'text', type: { chosen: { family: 'Six Caps', weight: 400, fontSizePx: 40 } } };
|
||||
it('says nothing when the build sets the type as the comp does', () => {
|
||||
const { findings } = textRegionCheck(region, textCrop(), textCrop());
|
||||
assert.deepEqual(findings, []);
|
||||
});
|
||||
it('names a cap-height miss with the ranked face and size', () => {
|
||||
const { findings } = textRegionCheck(region, textCrop({ scale: 4 }), textCrop({ scale: 6, lines: 2 }));
|
||||
assert.ok(findings.some((f) => /cap height .*px in the build, .*px in the comp/.test(f) && /Six Caps 400 at 40px/.test(f)), findings.join('\n'));
|
||||
});
|
||||
it('names a different line count', () => {
|
||||
const { findings } = textRegionCheck(region, textCrop({ lines: 3 }), textCrop({ lines: 2 }));
|
||||
assert.ok(findings.some((f) => /2 lines in the build, 3 in the comp/.test(f)), findings.join('\n'));
|
||||
});
|
||||
it('names a colour change and a vertical shift', () => {
|
||||
const { findings } = textRegionCheck(region, textCrop(), textCrop({ color: [180, 40, 30, 255], y0: 80 }));
|
||||
assert.ok(findings.some((f) => /ink is #/.test(f)), findings.join('\n'));
|
||||
assert.ok(findings.some((f) => /starts 60px lower/.test(f)), findings.join('\n'));
|
||||
});
|
||||
it('stays quiet on rotated or unmeasurable comp crops', () => {
|
||||
const blank = createImage(300, 300, paper);
|
||||
assert.deepEqual(textRegionCheck(region, blank, textCrop()).findings, []);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hero-checks: chrome strips and invented ink', () => {
|
||||
it('reads a strip height off its rule', () => {
|
||||
const mk = (ruleY) => { const img = createImage(800, 100, paper); fillRect(img, 0, ruleY, 800, 2, ink); drawText(img, 'THREADS GARAGE', 20, 12, ink, 2); return img; };
|
||||
assert.deepEqual(ruleRows(mk(60)), [59]); // the edge row above the rule
|
||||
const { findings } = chromeStripCheck({ id: 'masthead', kind: 'chrome' }, mk(44), mk(70));
|
||||
assert.ok(findings.some((f) => /43px into the box in the comp and 69px in the build/.test(f)), findings.join('\n'));
|
||||
assert.deepEqual(chromeStripCheck({ id: 'masthead', kind: 'chrome' }, mk(44), mk(47)).findings, []);
|
||||
});
|
||||
it('lists cells where the build carries ink over a calm comp', () => {
|
||||
const comp = createImage(1000, 1000, paper);
|
||||
const build = createImage(1000, 1000, paper);
|
||||
drawText(build, 'SECTION KICKER', 20, 20, ink, 3);
|
||||
fillRect(build, 100, 500, 800, 2, ink);
|
||||
const r = inventedInk(comp, build);
|
||||
assert.ok(r.cells.length >= 3, `cells ${r.cells.length}`);
|
||||
assert.ok(r.cells.some((c) => c.row === 0), 'the kicker row');
|
||||
assert.deepEqual(inventedInk(comp, comp).cells, []);
|
||||
});
|
||||
it('inkColor separates ink from ground', () => {
|
||||
const c = inkColor(textCrop({ color: [180, 40, 30, 255] }));
|
||||
assert.ok(c.ink && /^#[0-9a-f]{6}$/.test(c.ink.hex));
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user