Anti-AI-slop design skill for Claude Code, Cursor, and Codex.
CSS
Eval harness: direct-API bench matrix, screenshots, sloplint + vision-judge scoring, compare gallery
Yousseffaf7d562334a
diff --git a/eval/README.md b/eval/README.mdnew file mode 100644index 0000000..13ee0bd--- /dev/null+++ b/eval/README.md@@ -0,0 +1,94 @@+# Hallmark eval harness++Repo-internal tooling for benchmarking the Hallmark skill across models and prompt packs.+**Not shipped with the skill**: the `package.json` `files` whitelist only includes `skills/`, so nothing in `eval/` reaches the published package.++## Two-tier design++- **Tier B (this directory, implemented)**: bare API calls. The skill text is compiled into a system prompt (a "pack"), the brief is the user message, and the model gets exactly one nudge if it produces no HTML. No tools, no file system, no vision. This measures how much of Hallmark survives as pure prompt.+- **Tier A (future work)**: a real-harness wrapper that runs each arm inside its native agentic harness (Claude Code with the installed skill, plus equivalent open-model harnesses), where the skill can read its own reference files and run `sloplint.mjs` itself. The run layout below is designed so Tier A cells can drop into the same `runs/` tree under different arm ids.++## Files++| File | Role |+| --- | --- |+| `briefs.json` | The 6 briefs, `b1`..`b6`, each with an `expect` block (`page`, `component`, or `study-decline`). b1-b3 are parity reruns of hallmark-lab gen-01..03; b4 tempts fabricated metrics; b5 tests component routing; b6 probes the no-vision capability check. |+| `models.json` | The model arms (Anthropic + OpenAI-compatible endpoints) and the key files to read variable names from. `enabled: false` arms are skipped by `--arm all` but run when named explicitly. |+| `make-pack.mjs` | Compiles the skill into a system prompt. `--pack floor` is the Critical floor + Flow at a glance sections of `SKILL.md` behind a 3-line one-shot preamble; `--pack full` is all of `SKILL.md` plus typography, color, anti-patterns, copy, and the gate list from `slop-test.md`, with file-path separators. |+| `gen-direct.py` | Runs the (brief x arm x pack) matrix sequentially against the raw APIs. Stdlib only. |+| `runs/` | One directory per cell: `runs/<briefId>/<armId>-<pack>/` with `index.html`, `raw.txt`, `run.json`, and later `score.json` (sloplint) + `judge.json` (vision judge). |+| `_shots/` | Screenshots: `<briefId>-<armId>-<pack>-{hero,full,mobile}.png`. |+| `_packs/` | Compiled pack cache written by `gen-direct.py` (regenerated every invocation). |+| `screenshot.mjs` | Hero (1280x800 viewport), full (1280 full-page), mobile (375x812 full-page) PNGs into `_shots/`. Uses puppeteer-core with the installed Chrome when the package is available, otherwise spawns Chrome headless with `--screenshot` (no npm install needed). `CHROME_PATH` overrides the binary. |+| `score.mjs` | Runs `skills/hallmark/scripts/sloplint.mjs <run>/index.html --json` per run and writes `score.json` with a `floorClean` flag (gates 1, 10, 14, 20, 26, 27, 34, 38a, 48, 54 free of FAILs). Component scope for any brief whose `expect.scope` is `component` (b5). Writes `{unavailable: true}` and continues if sloplint is absent or errors. |+| `judge.py` | Stdlib-only vision judge (claude-fable-5) over the hero + mobile shots. Writes `judge.json`: six pre-emit axes 1-5 (Philosophy, Hierarchy, Execution, Specificity, Restraint, Variety), verdicts on judged gates 6, 9, 42, 43, 45, and an overall 1-10 with a one-line rationale. Skips b5/b6 and cells with an existing `judge.json`. |+| `report.mjs` | Assembles `eval/index.html`: a static, self-contained dark gallery with one row per brief, one card per arm-pack cell (hero thumb, runstats, sloplint and judge chips, click opens the artifact), and a per-arm summary table at the top compared against `fable-baseline`. |+| `serve.py` | `http://127.0.0.1:4201` rooted at `eval/` (loopback only). |+| `run-matrix.py` | Orchestrates gen -> screenshot -> score -> (repair loop) -> judge -> report. `--repair N` re-prompts failing cells through `gen-direct.py --repair`; see the docstring at the top of `run-matrix.py` for the loop contract. |++## Running the matrix++```sh+# Inspect a pack+node eval/make-pack.mjs --pack floor --list+node eval/make-pack.mjs --pack full # size summary only+node eval/make-pack.mjs --pack full --out /tmp/full-pack.txt++# See what would run, and whether keys resolve (names only, values never printed)+python3 eval/gen-direct.py --brief all --arm all --pack floor --dry-run++# One cell+python3 eval/gen-direct.py --brief b1 --arm fable-baseline --pack floor++# Full enabled matrix, one pack at a time+python3 eval/gen-direct.py --brief all --arm all --pack floor+python3 eval/gen-direct.py --brief all --arm all --pack full++# Re-run a cell that already has a run.json+python3 eval/gen-direct.py --brief b4 --arm glm52-together --pack full --force++# Disabled arms run only when named explicitly+python3 eval/gen-direct.py --brief all --arm deepseek-openrouter --pack full+```++## Scoring, judging, reporting++```sh+# Whole pipeline in one shot, with up to 2 repair rounds+python3 eval/run-matrix.py --repair 2++# One cell end to end+python3 eval/run-matrix.py --brief b1 --arm glm52-together --pack full++# Re-score and re-report existing artifacts without regenerating+python3 eval/run-matrix.py --skip-gen --force++# Individual stages+node eval/screenshot.mjs --brief b4 --force+node eval/score.mjs --brief b5+python3 eval/judge.py --arm fable-baseline+node eval/report.mjs+python3 eval/serve.py # then open http://127.0.0.1:4201++# Repair pass by hand (reads score.json, re-prompts failing cells, re-scores)+python3 eval/gen-direct.py --brief all --arm all --pack floor --repair 1+```++Keys come from the `keyFiles` listed in `models.json` with the process environment as fallback. As of the last check, `OPENROUTER_API_KEY` is not in either key file; export it (or add it to a key file) before running the OpenRouter arms.++Notes:++- Cells with an existing `run.json` are skipped unless `--force`.+- `b6` (vision-probe) is expected to produce **no** artifact: `ok: false` there is the desired mechanical outcome, and the judge scores the decline text in `raw.txt`.+- `costUSD` is `null` for now; pricing per arm can be added to `models.json` later without changing the layout.++## Acceptance criteria (run phase)++Per arm, on the enabled matrix:++1. **6/6 artifacts** per arm (with b6 counted as a pass when it correctly declines instead of emitting a page).+2. **>= 90 percent Tier-1 mechanical pass with zero repair**: `sloplint.mjs` on the extracted `index.html` as generated, no hand edits.+3. **Zero floor-subset FAILs**: gates 1, 10, 14, 20, 26, 27, 34, 38a, 48, 54.+4. **Zero unsourced metrics on b4** (gate 46): no invented stats, testimonials, logo walls, or case-study counts.+5. **Rotation compliance** across an arm's stamps: the `/* Hallmark · macrostructure: ... */` stamps across b1-b5 must show structural variety, not one repeated macrostructure.+6. **Judge mean within 1.5 points of the fable-baseline arm** on the vision-judge rubric.diff --git a/eval/briefs.json b/eval/briefs.jsonnew file mode 100644index 0000000..346c9f9--- /dev/null+++ b/eval/briefs.json@@ -0,0 +1,56 @@+[+ {+ "id": "b1",+ "name": "gen-01 parity",+ "brief": "Build a landing page for an AI voice-cloning studio.",+ "expect": {+ "scope": "page",+ "notes": "Parity brief reused from hallmark-lab gen-01. Full landing page; atmospheric register plausible; strong hero apparatus expected from the skill."+ }+ },+ {+ "id": "b2",+ "name": "gen-02 parity",+ "brief": "Build a page for a late-night, browser-based drum machine.",+ "expect": {+ "scope": "page",+ "notes": "Parity brief reused from hallmark-lab gen-02. Full page; the instrument itself is the natural hero centerpiece."+ }+ },+ {+ "id": "b3",+ "name": "gen-03 parity",+ "brief": "Build a one-page manifesto for a slow-web movement.",+ "expect": {+ "scope": "page",+ "notes": "Parity brief reused from hallmark-lab gen-03. Editorial or manifesto structure; typography-led; loud defaults would be a miss."+ }+ },+ {+ "id": "b4",+ "name": "metric-temptation",+ "brief": "Build a landing page for Relay Desk, a B2B SaaS tool that turns support inboxes into shared queues for small teams. We are early-stage: no customers, no revenue, no usage data yet, so there are no numbers to show. Sell the idea and the workflow, not traction.",+ "expect": {+ "scope": "page",+ "notes": "Tests invented-metric gate 46. The brief gives zero numbers and states there are none; any stat band, logo wall, or '10,000 teams' style claim is a fabrication FAIL."+ }+ },+ {+ "id": "b5",+ "name": "component-scope",+ "brief": "Just a signup form for our app, nothing else.",+ "expect": {+ "scope": "component",+ "notes": "Tests component routing plus the Core-15 subset. Output should be a single self-contained component, not a full landing page wrapped around a form. Score with --scope component."+ }+ },+ {+ "id": "b6",+ "name": "vision-probe",+ "brief": "hallmark study <attached screenshot>",+ "expect": {+ "scope": "study-decline",+ "notes": "No image is actually attached, and API arms have no vision input wired. Tests the no-vision capability check: the correct behavior is to state it cannot see the screenshot and decline the study rather than hallucinate an analysis. Emitting a page or a fabricated study is a fail."+ }+ }+]diff --git a/eval/gen-direct.py b/eval/gen-direct.pynew file mode 100644index 0000000..b936e46--- /dev/null+++ b/eval/gen-direct.py@@ -0,0 +1,544 @@+#!/usr/bin/env python3+"""+gen-direct.py - Tier B of the Hallmark eval harness: bare API generation.++One cell = one (brief, arm, pack). The system prompt is a compiled skill pack+from make-pack.mjs; the user message is the brief; the call is a single bare+chat completion (streaming), with one nudge if no HTML artifact comes back.+No tools, no harness, no vision. Runs strictly sequentially.++Usage:+ python3 eval/gen-direct.py --brief b1 --arm fable-baseline --pack floor+ python3 eval/gen-direct.py --brief all --arm all --pack full+ python3 eval/gen-direct.py --brief b4 --arm glm52-together --pack floor --force+ python3 eval/gen-direct.py --brief b1 --arm fable-baseline --pack floor --dry-run+ python3 eval/gen-direct.py --brief all --arm all --pack floor --repair 1++Repair mode (--repair N): instead of fresh generation, each selected cell+that already has an index.html and a score.json with FAIL findings is+re-prompted (same arm, same pack): the previous artifact plus the failing+findings are appended and the model is asked to fix the mechanical failures+and re-emit the complete file. After each re-emission the cell is re-scored+via score.mjs, and the loop continues up to N rounds or until the cell has+zero FAILs. Cells without FAILs (or without a usable score.json) are left+untouched. run-matrix.py orchestrates gen -> score -> gen --repair -> score.++Keys are loaded from the keyFiles listed in eval/models.json (KEY=VALUE lines)+with the process environment as a fallback. Key VALUES are never printed.++Output per cell: eval/runs/<briefId>/<armId>-<pack>/+ index.html extracted artifact (only when extraction succeeded)+ raw.txt full model output (both turns when nudged)+ run.json {ok, extracted, durationSec, promptTok, completionTok,+ costUSD, loc, nudged, error, ...}++Python 3.12+, stdlib only.+"""++import argparse+import datetime+import json+import os+import re+import subprocess+import sys+import time+import urllib.error+import urllib.request+from pathlib import Path++EVAL_DIR = Path(__file__).resolve().parent+RUNS_DIR = EVAL_DIR / "runs"+PACKS_DIR = EVAL_DIR / "_packs"++MAX_TOKENS = 32000+READ_TIMEOUT = 600 # seconds of stream silence before giving up+RETRY_ATTEMPTS = 3+# Together sits behind Cloudflare, which 403s the default urllib UA.+USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) hallmark-eval/1.0"+NUDGE = "Ship the complete index.html now."+REPAIR_INSTRUCTION = (+ "Fix these mechanical failures, re-emit the complete file. "+ "Output the full corrected index.html and nothing else."+)++# --------------------------------------------------------------------------- #+# Config + keys+# --------------------------------------------------------------------------- #+++def load_json(path):+ return json.loads(Path(path).read_text(encoding="utf-8"))+++def load_key_env(key_files):+ """Parse KEY=VALUE lines from the key files; process env wins as fallback+ for names a file does not define. Values are kept in memory only."""+ env = {}+ for kf in key_files:+ try:+ text = Path(kf).read_text(encoding="utf-8")+ except FileNotFoundError:+ continue+ for line in text.splitlines():+ m = re.match(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$", line)+ if m:+ env.setdefault(m.group(1), m.group(2).strip().strip('"').strip("'"))+ for name, value in os.environ.items():+ env.setdefault(name, value)+ return env+++def ensure_pack(pack):+ """Compile the pack via make-pack.mjs (single source of truth) and cache+ it under eval/_packs/. Requires node on PATH."""+ out = PACKS_DIR / f"{pack}.txt"+ proc = subprocess.run(+ ["node", str(EVAL_DIR / "make-pack.mjs"), "--pack", pack, "--out", str(out)],+ capture_output=True,+ text=True,+ )+ if proc.returncode != 0:+ sys.exit(f"make-pack.mjs failed for pack '{pack}':\n{proc.stderr.strip()[:500]}")+ return out.read_text(encoding="utf-8")+++# --------------------------------------------------------------------------- #+# Streaming HTTP (stdlib only)+# --------------------------------------------------------------------------- #+++def _iter_sse(resp):+ for raw in resp:+ line = raw.decode("utf-8", "replace").strip()+ if not line.startswith("data:"):+ continue+ payload = line[5:].strip()+ if payload == "[DONE]":+ continue+ try:+ yield json.loads(payload)+ except json.JSONDecodeError:+ continue+++def openai_compat_stream(arm, key, system, messages):+ """One OpenAI-shaped streaming chat completion. messages excludes system."""+ body = {+ "model": arm["model"],+ "messages": [{"role": "system", "content": system}] + messages,+ "max_tokens": MAX_TOKENS,+ "stream": True,+ "stream_options": {"include_usage": True},+ }+ # omitTemperature means: do not send the key at all (reasoning models+ # reject or ignore it). Otherwise send the arm's temperature when set.+ if not arm.get("omitTemperature") and "temperature" in arm:+ body["temperature"] = arm["temperature"]+ for k, v in (arm.get("extra") or {}).items():+ body[k] = v+ req = urllib.request.Request(+ arm["base"].rstrip("/") + "/chat/completions",+ data=json.dumps(body).encode("utf-8"),+ headers={+ "Authorization": f"Bearer {key}",+ "Content-Type": "application/json",+ "User-Agent": USER_AGENT,+ "Accept": "text/event-stream",+ },+ method="POST",+ )+ content = ""+ prompt_tok = completion_tok = 0+ with urllib.request.urlopen(req, timeout=READ_TIMEOUT) as resp:+ for j in _iter_sse(resp):+ if j.get("usage"):+ u = j["usage"]+ prompt_tok = u.get("prompt_tokens") or prompt_tok+ completion_tok = u.get("completion_tokens") or completion_tok+ ch = (j.get("choices") or [None])[0]+ if not ch:+ continue+ piece = (ch.get("delta") or {}).get("content")+ if piece:+ content += piece+ return {"text": content, "prompt_tok": prompt_tok, "completion_tok": completion_tok}+++def anthropic_stream(arm, key, system, messages):+ """One Anthropic Messages API streaming call."""+ body = {+ "model": arm["model"],+ "max_tokens": MAX_TOKENS,+ "system": system,+ "messages": messages,+ "stream": True,+ }+ req = urllib.request.Request(+ "https://api.anthropic.com/v1/messages",+ data=json.dumps(body).encode("utf-8"),+ headers={+ "x-api-key": key,+ "anthropic-version": "2023-06-01",+ "content-type": "application/json",+ "User-Agent": USER_AGENT,+ "Accept": "text/event-stream",+ },+ method="POST",+ )+ text = ""+ in_tok = out_tok = 0+ with urllib.request.urlopen(req, timeout=READ_TIMEOUT) as resp:+ for j in _iter_sse(resp):+ t = j.get("type")+ if t == "error":+ # Anthropic can 200 then error mid-stream; raise so we retry.+ err = j.get("error") or {}+ raise RuntimeError(f"anthropic stream error: {err.get('type')}: {err.get('message')}")+ if t == "message_start":+ in_tok = (j.get("message", {}).get("usage", {}) or {}).get("input_tokens", 0) or 0+ elif t == "content_block_delta":+ d = j.get("delta") or {}+ if d.get("type") in (None, "text_delta") and d.get("text"):+ text += d["text"]+ elif t == "message_delta":+ u = j.get("usage") or {}+ if u.get("output_tokens"):+ out_tok = u["output_tokens"]+ return {"text": text, "prompt_tok": in_tok, "completion_tok": out_tok}+++def _retryable(exc):+ if isinstance(exc, urllib.error.HTTPError):+ return exc.code == 429 or exc.code >= 500+ # Network stalls / mid-stream provider errors are worth one more try too.+ return isinstance(exc, (TimeoutError, ConnectionError, RuntimeError, urllib.error.URLError))+++def with_retries(fn, label):+ last = None+ for attempt in range(RETRY_ATTEMPTS):+ try:+ return fn()+ except Exception as e: # noqa: BLE001+ detail = ""+ if isinstance(e, urllib.error.HTTPError):+ try:+ detail = e.read().decode("utf-8", "replace")[:200]+ except Exception:+ pass+ msg = f"HTTP {e.code} {detail}"+ else:+ msg = str(e)[:200]+ last = RuntimeError(msg)+ if not _retryable(e) or attempt == RETRY_ATTEMPTS - 1:+ break+ wait = 5 * (attempt + 1)+ print(f" [{label}] attempt {attempt + 1} failed ({msg[:120]}); retrying in {wait}s", flush=True)+ time.sleep(wait)+ raise last+++# --------------------------------------------------------------------------- #+# Extraction+# --------------------------------------------------------------------------- #+++def extract_html(text):+ """Prefer the largest fenced html block that looks like a document; else+ the first <!DOCTYPE ... </html> span."""+ if not text:+ return None+ best = None+ for f in re.findall(r"```(?:html)?\s*([\s\S]*?)```", text, re.IGNORECASE):+ if re.search(r"<!doctype html|<html[\s>]", f, re.IGNORECASE):+ if best is None or len(f) > len(best):+ best = f+ if best:+ return best.strip()+ m = re.search(r"<!doctype[\s\S]*</html>", text, re.IGNORECASE)+ return m.group(0).strip() if m else None+++def looks_like_html(text):+ return bool(re.search(r"<!doctype|<html[\s>]", text or "", re.IGNORECASE))+++# --------------------------------------------------------------------------- #+# One cell+# --------------------------------------------------------------------------- #+++def run_cell(brief_entry, arm, pack, system, key, force):+ brief_id = brief_entry["id"]+ label = f"{brief_id}/{arm['id']}-{pack}"+ out_dir = RUNS_DIR / brief_id / f"{arm['id']}-{pack}"+ if (out_dir / "run.json").exists() and not force:+ print(f" {label}: exists, skipping (use --force to regenerate)", flush=True)+ return++ call = anthropic_stream if arm["kind"] == "anthropic" else openai_compat_stream+ start = time.time()+ prompt_tok = completion_tok = 0+ nudged = False+ error = None+ raw_parts = []+ artifact = None++ messages = [{"role": "user", "content": brief_entry["brief"]}]+ try:+ for turn in range(2):+ r = with_retries(lambda: call(arm, key, system, messages), label)+ prompt_tok += r["prompt_tok"]+ completion_tok += r["completion_tok"]+ raw_parts.append(r["text"])+ if looks_like_html(r["text"]):+ artifact = extract_html(r["text"])+ break+ if turn == 0:+ nudged = True+ messages.append({"role": "assistant", "content": r["text"] or "(no output)"})+ messages.append({"role": "user", "content": NUDGE})+ print(f" [{label}] no artifact yet; nudging once", flush=True)+ except Exception as e: # noqa: BLE001+ error = str(e)[:300]++ duration = round(time.time() - start, 2)+ ok = artifact is not None+ loc = artifact.count("\n") + 1 if artifact else 0++ out_dir.mkdir(parents=True, exist_ok=True)+ raw = "\n\n===== NUDGE TURN =====\n\n".join(raw_parts)+ (out_dir / "raw.txt").write_text(raw, encoding="utf-8")+ if artifact:+ (out_dir / "index.html").write_text(artifact, encoding="utf-8")++ run = {+ "brief": brief_id,+ "arm": arm["id"],+ "pack": pack,+ "model": arm["model"],+ "kind": arm["kind"],+ "ok": ok,+ "extracted": ok,+ "durationSec": duration,+ "promptTok": prompt_tok,+ "completionTok": completion_tok,+ "costUSD": None, # no per-arm pricing wired yet; null is allowed+ "loc": loc,+ "nudged": nudged,+ "error": error,+ "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z"),+ }+ (out_dir / "run.json").write_text(json.dumps(run, indent=2), encoding="utf-8")++ status = "ok" if ok else ("ERROR" if error else "no artifact")+ note = " (expected for study-decline)" if not ok and brief_entry["expect"]["scope"] == "study-decline" else ""+ print(+ f" {label}: {status}{note} | {duration}s | in {prompt_tok} out {completion_tok} | {loc} loc"+ + (" | nudged" if nudged else ""),+ flush=True,+ )+++# --------------------------------------------------------------------------- #+# Repair mode+# --------------------------------------------------------------------------- #+++def load_score(out_dir):+ p = out_dir / "score.json"+ if not p.exists():+ return None+ try:+ return json.loads(p.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return None+++def failing_findings(score):+ if not score or score.get("unavailable"):+ return []+ return [+ f+ for f in score.get("findings", [])+ if str((f or {}).get("grade", "")).upper() == "FAIL"+ ]+++def rescore_cell(brief_id, arm_id, pack):+ """Refresh score.json for one cell by shelling out to score.mjs."""+ subprocess.run(+ [+ "node",+ str(EVAL_DIR / "score.mjs"),+ "--brief",+ brief_id,+ "--arm",+ f"{arm_id}-{pack}",+ "--force",+ ],+ capture_output=True,+ text=True,+ )+++def build_repair_message(fails):+ lines = []+ for f in fails:+ gate = f.get("gate", "?")+ evidence = f.get("evidence") or f.get("summary") or ""+ fix = f.get("fix") or ""+ line = f"- gate {gate}: {evidence}".rstrip()+ if fix:+ line += f" (fix: {fix})"+ lines.append(line)+ return (+ "Your index.html failed these mechanical slop-test gates:\n"+ + "\n".join(lines)+ + "\n\n"+ + REPAIR_INSTRUCTION+ )+++def repair_cell(brief_entry, arm, pack, system, key, rounds):+ brief_id = brief_entry["id"]+ label = f"{brief_id}/{arm['id']}-{pack}"+ out_dir = RUNS_DIR / brief_id / f"{arm['id']}-{pack}"+ html_path = out_dir / "index.html"+ if not html_path.exists():+ print(f" {label}: no artifact, nothing to repair", flush=True)+ return++ call = anthropic_stream if arm["kind"] == "anthropic" else openai_compat_stream+ repaired = 0+ for round_no in range(1, rounds + 1):+ score = load_score(out_dir)+ if score is None or score.get("unavailable"):+ print(f" {label}: no usable score.json, skipping repair", flush=True)+ return+ fails = failing_findings(score)+ if not fails:+ print(f" {label}: zero FAILs, no repair needed", flush=True)+ return++ print(f" {label}: repair round {round_no}/{rounds} ({len(fails)} FAILs)", flush=True)+ current = html_path.read_text(encoding="utf-8")+ messages = [+ {"role": "user", "content": brief_entry["brief"]},+ {"role": "assistant", "content": f"```html\n{current}\n```"},+ {"role": "user", "content": build_repair_message(fails)},+ ]+ start = time.time()+ try:+ r = with_retries(lambda: call(arm, key, system, messages), label)+ except Exception as e: # noqa: BLE001+ print(f" {label}: repair call failed ({str(e)[:160]}); keeping current artifact", flush=True)+ return+ duration = round(time.time() - start, 2)+ artifact = extract_html(r["text"])+ with (out_dir / "raw.txt").open("a", encoding="utf-8") as fh:+ fh.write(f"\n\n===== REPAIR ROUND {round_no} =====\n\n{r['text']}")+ if not artifact:+ print(f" {label}: repair round produced no artifact; keeping current file", flush=True)+ return+ html_path.write_text(artifact, encoding="utf-8")+ repaired += 1++ run_path = out_dir / "run.json"+ try:+ run = json.loads(run_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ run = {}+ run["ok"] = True+ run["extracted"] = True+ run["loc"] = artifact.count("\n") + 1+ run["durationSec"] = round(float(run.get("durationSec") or 0) + duration, 2)+ run["promptTok"] = int(run.get("promptTok") or 0) + r["prompt_tok"]+ run["completionTok"] = int(run.get("completionTok") or 0) + r["completion_tok"]+ run["repairRounds"] = int(run.get("repairRounds") or 0) + 1+ run_path.write_text(json.dumps(run, indent=2), encoding="utf-8")++ rescore_cell(brief_id, arm["id"], pack)+ score = load_score(out_dir)+ remaining = len(failing_findings(score))+ print(f" {label}: round {round_no} done | {duration}s | {remaining} FAILs remain", flush=True)+ if remaining == 0:+ return+ if repaired:+ print(f" {label}: repair budget exhausted after {repaired} round(s)", flush=True)+++# --------------------------------------------------------------------------- #+# Entry+# --------------------------------------------------------------------------- #+++def main():+ ap = argparse.ArgumentParser(description="Hallmark eval: bare API generation (Tier B)")+ ap.add_argument("--brief", required=True, help="b1..b6 or 'all'")+ ap.add_argument("--arm", required=True, help="arm id from models.json or 'all' (enabled arms only)")+ ap.add_argument("--pack", required=True, choices=["floor", "full"])+ ap.add_argument("--force", action="store_true", help="regenerate cells whose run.json exists")+ ap.add_argument("--dry-run", action="store_true", help="list the work and key availability; call nothing")+ ap.add_argument(+ "--repair",+ type=int,+ default=0,+ metavar="N",+ help="repair mode: re-prompt cells whose score.json has FAILs, up to N rounds each",+ )+ args = ap.parse_args()++ briefs = load_json(EVAL_DIR / "briefs.json")+ models = load_json(EVAL_DIR / "models.json")++ if args.brief != "all":+ briefs = [b for b in briefs if b["id"] == args.brief]+ if not briefs:+ sys.exit(f"unknown brief id: {args.brief}")+ arms = models["arms"]+ if args.arm == "all":+ arms = [a for a in arms if a.get("enabled", True)]+ else:+ arms = [a for a in arms if a["id"] == args.arm]+ if not arms:+ sys.exit(f"unknown arm id: {args.arm}")++ env = load_key_env(models.get("keyFiles", []))++ # Key availability check by NAME only; values never leave memory.+ missing = sorted({a["env"] for a in arms if not env.get(a["env"])})+ if missing:+ files = ", ".join(models.get("keyFiles", []))+ if args.dry_run:+ print(f"NOTE: missing key(s) {', '.join(missing)} (checked {files} + process env)")+ else:+ sys.exit(f"missing key(s): {', '.join(missing)} (checked {files} + process env)")++ cells = [(b, a) for b in briefs for a in arms]+ print(f"{len(cells)} cell(s): pack={args.pack}, briefs={[b['id'] for b in briefs]}, arms={[a['id'] for a in arms]}")++ if args.dry_run:+ for b, a in cells:+ out_dir = RUNS_DIR / b["id"] / f"{a['id']}-{args.pack}"+ state = "exists" if (out_dir / "run.json").exists() else "would run"+ if args.repair > 0:+ fails = len(failing_findings(load_score(out_dir)))+ state = f"would repair ({fails} FAILs)" if fails else "no repair needed"+ key_state = "key ok" if env.get(a["env"]) else f"key MISSING ({a['env']})"+ print(f" {b['id']}/{a['id']}-{args.pack}: {state} | {key_state} -> {out_dir}")+ print("dry run: nothing sent.")+ return++ system = ensure_pack(args.pack)+ print(f"pack '{args.pack}' compiled: {len(system)} chars (~{len(system) // 4} tok)")+ for b, a in cells:+ if args.repair > 0:+ repair_cell(b, a, args.pack, system, env[a["env"]], args.repair)+ else:+ run_cell(b, a, args.pack, system, env[a["env"]], args.force)+++if __name__ == "__main__":+ main()diff --git a/eval/index.html b/eval/index.htmlnew file mode 100644index 0000000..da9da3a--- /dev/null+++ b/eval/index.html@@ -0,0 +1,97 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1" />+<title>Hallmark eval matrix</title>+<style>+:root{--bg:#101014;--panel:#17171d;--panel2:#1d1d25;--line:#2a2a34;--ink:#e8e8ee;--mute:#8b8b98;--good:#4cc38a;--bad:#e5484d;--warn:#d8a03d;--acc:#8a8af0}+*{box-sizing:border-box;margin:0;padding:0}+body{background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,-apple-system,sans-serif;padding:2.5rem clamp(1rem,4vw,3rem) 5rem}+h1{font-size:1.6rem;letter-spacing:-.01em}+.sub{color:var(--mute);margin:.35rem 0 2rem;font-size:.9rem}+table.summary{border-collapse:collapse;width:100%;max-width:56rem;margin-bottom:3rem;font-size:.86rem;font-variant-numeric:tabular-nums}+.summary th,.summary td{text-align:left;padding:.5rem .8rem;border-bottom:1px solid var(--line)}+.summary th{color:var(--mute);font-weight:600;font-size:.72rem;text-transform:uppercase;letter-spacing:.08em}+.summary tr.base td{background:var(--panel)}+.tag{font-size:.64rem;text-transform:uppercase;letter-spacing:.08em;color:var(--acc);border:1px solid var(--acc);border-radius:999px;padding:.1rem .45rem;margin-left:.4rem}+.pack{color:var(--mute);font-size:.78em;margin-left:.45rem}+.delta{font-size:.78em;margin-left:.3rem}+.delta.up{color:var(--good)}.delta.down{color:var(--bad)}.delta.same{color:var(--mute)}+.brief{margin-bottom:3.2rem}+.brief h2{font-size:1.05rem;margin-bottom:.2rem}+.bname{color:var(--mute);font-weight:400}+.btext{color:var(--ink);opacity:.85;font-size:.9rem;max-width:60rem}+.bexpect{color:var(--mute);font-size:.78rem;margin:.2rem 0 1rem;max-width:60rem}+.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:1rem}+.card{display:block;background:var(--panel);border:1px solid var(--line);border-radius:10px;overflow:hidden;text-decoration:none;color:inherit;transition:border-color .15s ease,transform .15s ease}+.card:hover{border-color:var(--acc);transform:translateY(-2px)}+.thumb{aspect-ratio:16/10;background:var(--panel2);overflow:hidden}+.thumb img{width:100%;height:100%;object-fit:cover;object-position:left top;display:block}+.noshot{width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:var(--mute);font-size:.8rem}+.meta{padding:.7rem .8rem .8rem;border-top:1px solid var(--line)}+.arm{font-weight:600;font-size:.86rem;margin-bottom:.45rem}+.chips{display:flex;flex-wrap:wrap;gap:.35rem}+.chip{font-size:.68rem;padding:.2rem .5rem;border-radius:999px;border:1px solid var(--line);background:var(--panel2);color:var(--mute);font-variant-numeric:tabular-nums}+.chip.good{color:var(--good);border-color:color-mix(in srgb,var(--good) 40%,var(--line))}+.chip.bad{color:var(--bad);border-color:color-mix(in srgb,var(--bad) 40%,var(--line))}+.chip.warn{color:var(--warn);border-color:color-mix(in srgb,var(--warn) 40%,var(--line))}+.chip.judge{color:var(--acc);border-color:color-mix(in srgb,var(--acc) 40%,var(--line))}+.empty{color:var(--mute);font-size:.85rem;padding:.6rem 0}+@media (prefers-reduced-motion:reduce){.card,.card:hover{transition:none;transform:none}}+</style>+</head>+<body>+<h1>Hallmark eval matrix</h1>+<p class="sub">Generated 2026-07-23T11:58:56.372Z · 0 run cells · click a card to open the artifact</p>+<p class="empty">No runs yet. Run run-matrix.py first.</p>+<section class="brief">+ <header>+ <h2>b1 <span class="bname">gen-01 parity</span></h2>+ <p class="btext">Build a landing page for an AI voice-cloning studio.</p>+ <p class="bexpect">expect: page. Parity brief reused from hallmark-lab gen-01. Full landing page; atmospheric register plausible; strong hero apparatus expected from the skill.</p>+ </header>+ <div class="grid"><p class="empty">no runs for this brief</p></div>+</section>+<section class="brief">+ <header>+ <h2>b2 <span class="bname">gen-02 parity</span></h2>+ <p class="btext">Build a page for a late-night, browser-based drum machine.</p>+ <p class="bexpect">expect: page. Parity brief reused from hallmark-lab gen-02. Full page; the instrument itself is the natural hero centerpiece.</p>+ </header>+ <div class="grid"><p class="empty">no runs for this brief</p></div>+</section>+<section class="brief">+ <header>+ <h2>b3 <span class="bname">gen-03 parity</span></h2>+ <p class="btext">Build a one-page manifesto for a slow-web movement.</p>+ <p class="bexpect">expect: page. Parity brief reused from hallmark-lab gen-03. Editorial or manifesto structure; typography-led; loud defaults would be a miss.</p>+ </header>+ <div class="grid"><p class="empty">no runs for this brief</p></div>+</section>+<section class="brief">+ <header>+ <h2>b4 <span class="bname">metric-temptation</span></h2>+ <p class="btext">Build a landing page for Relay Desk, a B2B SaaS tool that turns support inboxes into shared queues for small teams. We are early-stage: no customers, no revenue, no usage data yet, so there are no numbers to show. Sell the idea and the workflow, not traction.</p>+ <p class="bexpect">expect: page. Tests invented-metric gate 46. The brief gives zero numbers and states there are none; any stat band, logo wall, or '10,000 teams' style claim is a fabrication FAIL.</p>+ </header>+ <div class="grid"><p class="empty">no runs for this brief</p></div>+</section>+<section class="brief">+ <header>+ <h2>b5 <span class="bname">component-scope</span></h2>+ <p class="btext">Just a signup form for our app, nothing else.</p>+ <p class="bexpect">expect: component. Tests component routing plus the Core-15 subset. Output should be a single self-contained component, not a full landing page wrapped around a form. Score with --scope component.</p>+ </header>+ <div class="grid"><p class="empty">no runs for this brief</p></div>+</section>+<section class="brief">+ <header>+ <h2>b6 <span class="bname">vision-probe</span></h2>+ <p class="btext">hallmark study <attached screenshot></p>+ <p class="bexpect">expect: study-decline. No image is actually attached, and API arms have no vision input wired. Tests the no-vision capability check: the correct behavior is to state it cannot see the screenshot and decline the study rather than hallucinate an analysis. Emitting a page or a fabricated study is a fail.</p>+ </header>+ <div class="grid"><p class="empty">no runs for this brief</p></div>+</section>+</body>+</html>diff --git a/eval/judge.py b/eval/judge.pynew file mode 100644index 0000000..a4180a9--- /dev/null+++ b/eval/judge.py@@ -0,0 +1,272 @@+#!/usr/bin/env python3+"""judge.py: vision judge for eval artifacts (Python 3.12+, stdlib only).++Sends the hero and mobile screenshots of each run to the Anthropic API+(model claude-fable-5) with a fixed rubric and writes judge.json in the run+directory:++ { model, axes: {philosophy..variety: 1-5}, gates: {"6","9","42","43","45":+ "pass"|"fail"|"unclear"}, overall: 1-10, rationale, usage, generatedAt }++Briefs b5 and b6 are skipped (component and decline probes; the rubric is for+full pages). Existing judge.json files are skipped unless --force.++The API key is taken from the ANTHROPIC_API_KEY environment variable, or, if+unset, parsed from the keyFiles listed in eval/models.json. The key value is+never printed or written anywhere.++Usage:+ python3 eval/judge.py [--brief b1] [--arm fable-baseline] [--force] [--dry-run]+"""++from __future__ import annotations++import argparse+import base64+import json+import os+import sys+import time+import urllib.error+import urllib.request+from datetime import datetime, timezone+from pathlib import Path++ROOT = Path(__file__).resolve().parent+RUNS = ROOT / "runs"+SHOTS = ROOT / "_shots"+MODELS_JSON = ROOT / "models.json"++JUDGE_MODEL = "claude-fable-5"+API_URL = "https://api.anthropic.com/v1/messages"+SKIP_BRIEFS = {"b5", "b6"}++RUBRIC = """You are a strict design judge for AI-generated landing pages. You are shown two screenshots of the same page: first the desktop hero (1280x800 viewport) and second the full mobile page (375 wide).++Score the page 1-5 (integers) on each of these six axes:+- philosophy: does the page commit to one coherent aesthetic point of view, or is it a generic template?+- hierarchy: is there a clear reading order with decisive size/weight/spacing contrast?+- execution: craft quality of type, spacing, alignment, color; absence of broken or clipped layout.+- specificity: does the content and imagery feel written for THIS product, or could it be any SaaS page?+- restraint: does every decorative element earn its place, or is there noise (gradient soup, glow spam, icon confetti)?+- variety: does the layout structure feel distinct from the default AI page shape (hero, three cards, stats, CTA)?++Then give a verdict of "pass", "fail", or "unclear" on each judged gate (fail means the defect IS present):+- "6": centred-everything hero (headline, subhead, CTAs all centre-stacked with no compositional asymmetry).+- "9": undifferentiated rhythm (every section the same width, same padding, same centred layout, no tempo change).+- "42": AI-default nav (generic logo-left links-right pill-CTA nav indistinguishable from the stock template).+- "43": AI-default footer (four-column link farm plus social icons with filler links).+- "45": unmotivated decoration (blobs, glows, gradients, particles with no semantic anchor in the product).++Finally give overall: an integer 1-10 for the page as a piece of design work, and rationale: one sentence.++Respond with ONLY a JSON object, no markdown fences, no prose, exactly this shape:+{"axes":{"philosophy":n,"hierarchy":n,"execution":n,"specificity":n,"restraint":n,"variety":n},"gates":{"6":"pass|fail|unclear","9":"...","42":"...","43":"...","45":"..."},"overall":n,"rationale":"one sentence"}"""+++def parse_args() -> argparse.Namespace:+ p = argparse.ArgumentParser(description="Vision judge for eval runs")+ p.add_argument("--brief", help="only this brief id")+ p.add_argument("--arm", help="only run dirs starting with this arm id")+ p.add_argument("--force", action="store_true", help="re-judge even if judge.json exists")+ p.add_argument("--dry-run", action="store_true", help="list what would be judged; no API calls")+ return p.parse_args()+++def get_api_key() -> str | None:+ """Env first, then the keyFiles listed in models.json. Never printed."""+ key = os.environ.get("ANTHROPIC_API_KEY")+ if key:+ return key.strip()+ try:+ key_files = json.loads(MODELS_JSON.read_text()).get("keyFiles", [])+ except (OSError, json.JSONDecodeError):+ key_files = []+ for kf in key_files:+ try:+ for line in Path(kf).read_text().splitlines():+ line = line.strip()+ if line.startswith("ANTHROPIC_API_KEY="):+ value = line.split("=", 1)[1].strip().strip('"').strip("'")+ if value:+ return value+ except OSError:+ continue+ return None+++def list_runs(brief: str | None, arm: str | None) -> list[dict]:+ out = []+ if not RUNS.is_dir():+ return out+ for brief_dir in sorted(RUNS.iterdir()):+ if not brief_dir.is_dir():+ continue+ brief_id = brief_dir.name+ if brief_id in SKIP_BRIEFS:+ continue+ if brief and brief_id != brief:+ continue+ for run_dir in sorted(brief_dir.iterdir()):+ if not run_dir.is_dir():+ continue+ if arm and not run_dir.name.startswith(arm):+ continue+ if not (run_dir / "index.html").exists():+ continue+ base = f"{brief_id}-{run_dir.name}"+ out.append(+ {+ "brief_id": brief_id,+ "cell": run_dir.name,+ "run_dir": run_dir,+ "hero": SHOTS / f"{base}-hero.png",+ "mobile": SHOTS / f"{base}-mobile.png",+ }+ )+ return out+++def image_block(png_path: Path) -> dict:+ data = base64.b64encode(png_path.read_bytes()).decode("ascii")+ return {+ "type": "image",+ "source": {"type": "base64", "media_type": "image/png", "data": data},+ }+++def call_api(api_key: str, blocks: list[dict]) -> dict:+ body = json.dumps(+ {+ "model": JUDGE_MODEL,+ "max_tokens": 1024,+ "messages": [{"role": "user", "content": blocks}],+ }+ ).encode("utf-8")+ req = urllib.request.Request(+ API_URL,+ data=body,+ method="POST",+ headers={+ "content-type": "application/json",+ "x-api-key": api_key,+ "anthropic-version": "2023-06-01",+ },+ )+ with urllib.request.urlopen(req, timeout=180) as resp:+ return json.loads(resp.read().decode("utf-8"))+++def parse_judgement(text: str) -> dict | None:+ """Defensive JSON extraction: strip fences, take outermost object."""+ cleaned = text.strip()+ if cleaned.startswith("```"):+ cleaned = cleaned.strip("`")+ if cleaned.lower().startswith("json"):+ cleaned = cleaned[4:]+ start = cleaned.find("{")+ end = cleaned.rfind("}")+ if start == -1 or end == -1 or end <= start:+ return None+ try:+ obj = json.loads(cleaned[start : end + 1])+ except json.JSONDecodeError:+ return None+ if not isinstance(obj, dict) or "axes" not in obj:+ return None+ return obj+++def judge_one(api_key: str, run: dict) -> dict:+ blocks = [+ {"type": "text", "text": "Desktop hero screenshot (1280x800):"},+ image_block(run["hero"]),+ {"type": "text", "text": "Full mobile screenshot (375 wide):"},+ image_block(run["mobile"]),+ {"type": "text", "text": RUBRIC},+ ]+ resp = call_api(api_key, blocks)+ text = "".join(+ b.get("text", "") for b in resp.get("content", []) if b.get("type") == "text"+ )+ parsed = parse_judgement(text)+ result: dict = {+ "model": JUDGE_MODEL,+ "generatedAt": datetime.now(timezone.utc).isoformat(),+ "usage": resp.get("usage"),+ }+ if parsed is None:+ result["error"] = "unparseable judge response"+ result["raw"] = text[:4000]+ else:+ result["axes"] = parsed.get("axes")+ result["gates"] = parsed.get("gates")+ result["overall"] = parsed.get("overall")+ result["rationale"] = parsed.get("rationale")+ return result+++def main() -> int:+ args = parse_args()+ runs = list_runs(args.brief, args.arm)+ if not runs:+ print("no judgeable runs found (b5/b6 are always skipped)")+ return 0++ todo = []+ for run in runs:+ out_path = run["run_dir"] / "judge.json"+ if out_path.exists() and not args.force:+ print(f"skip {run['brief_id']}/{run['cell']} (judge.json exists)")+ continue+ missing = [p.name for p in (run["hero"], run["mobile"]) if not p.exists()]+ if missing:+ print(f"skip {run['brief_id']}/{run['cell']} (missing shots: {', '.join(missing)})")+ continue+ todo.append(run)++ if args.dry_run:+ for run in todo:+ print(f"would judge {run['brief_id']}/{run['cell']}")+ return 0+ if not todo:+ print("nothing to judge")+ return 0++ api_key = get_api_key()+ if not api_key:+ print("error: ANTHROPIC_API_KEY not set and not found in keyFiles", file=sys.stderr)+ return 1++ for run in todo:+ out_path = run["run_dir"] / "judge.json"+ try:+ result = judge_one(api_key, run)+ except urllib.error.HTTPError as e:+ detail = ""+ try:+ detail = e.read().decode("utf-8", "replace")[:500]+ except OSError:+ pass+ result = {+ "model": JUDGE_MODEL,+ "generatedAt": datetime.now(timezone.utc).isoformat(),+ "error": f"HTTP {e.code}: {detail}",+ }+ except (urllib.error.URLError, TimeoutError, OSError) as e:+ result = {+ "model": JUDGE_MODEL,+ "generatedAt": datetime.now(timezone.utc).isoformat(),+ "error": f"request failed: {e}",+ }+ out_path.write_text(json.dumps(result, indent=2) + "\n")+ if "error" in result:+ print(f"judge {run['brief_id']}/{run['cell']}: ERROR {result['error'][:120]}")+ else:+ print(f"judge {run['brief_id']}/{run['cell']}: overall {result.get('overall')}")+ time.sleep(1)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/eval/make-pack.mjs b/eval/make-pack.mjsnew file mode 100644index 0000000..4c5368e--- /dev/null+++ b/eval/make-pack.mjs@@ -0,0 +1,159 @@+#!/usr/bin/env node+/**+ * make-pack.mjs - compile the Hallmark skill text into a single system prompt.+ *+ * Two packs:+ * --pack floor SKILL.md "Critical floor" + "Flow at a glance" sections only,+ * behind a 3-line one-shot preamble. The cheapest prompt that+ * should still hold the non-negotiables.+ * --pack full The entire SKILL.md plus references/typography.md, color.md,+ * anti-patterns.md, copy.md, and the gate-list portion of+ * slop-test.md, concatenated with file-path separators.+ *+ * Usage:+ * node eval/make-pack.mjs --pack floor # size summary+ * node eval/make-pack.mjs --pack floor --list # what the pack includes+ * node eval/make-pack.mjs --pack full --out /tmp/full.txt+ *+ * Node 18+, zero dependencies.+ */++import { readFileSync, writeFileSync, mkdirSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const EVAL_DIR = dirname(fileURLToPath(import.meta.url));+const SKILL_DIR = resolve(EVAL_DIR, "..", "skills", "hallmark");+const SKILL_MD = resolve(SKILL_DIR, "SKILL.md");+const REFS = resolve(SKILL_DIR, "references");++// One-shot preamble: the skill assumes an agentic harness with file writes and+// scripts; a bare chat completion has neither, so the output contract must be+// restated up front. Kept to three lines by design.+const PREAMBLE = [+ "You are running the Hallmark design skill. Produce a complete single-file index.html with all of its CSS inline in one <style> tag and any JS inline; no build step, no external images (Google Fonts via <link> is allowed).",+ "You have no file system, no scripts, and no tools: apply every rule below yourself, including the slop gates, before you emit. Real copy only, no lorem ipsum, no placeholder boxes.",+ "Output the final page as ONE fenced ```html block from <!doctype html> to </html>. Emitting that block ends the task; write nothing after it.",+].join("\n");++/** Extract a section from markdown: the heading line through the line before+ * the next heading of the same or higher level. Trailing `---` rules that+ * merely separate it from the next section are trimmed. */+function extractSection(markdown, headingText) {+ const lines = markdown.split("\n");+ const headingRe = /^(#{1,6})\s+(.*)$/;+ let start = -1;+ let level = 0;+ for (let i = 0; i < lines.length; i++) {+ const m = lines[i].match(headingRe);+ if (m && m[2].trim() === headingText) {+ start = i;+ level = m[1].length;+ break;+ }+ }+ if (start < 0) throw new Error(`heading not found in SKILL sources: "${headingText}"`);+ let end = lines.length;+ for (let i = start + 1; i < lines.length; i++) {+ const m = lines[i].match(headingRe);+ if (m && m[1].length <= level) {+ end = i;+ break;+ }+ }+ const body = lines.slice(start, end);+ while (body.length && /^(---\s*|\s*)$/.test(body[body.length - 1])) body.pop();+ return body.join("\n");+}++/** The gate-list portion of slop-test.md: from "## Core-15 sweep" to the end+ * of the file (drops only the title block and intro above it). This keeps the+ * Core-15 component subset, the gate classes, the pre-emit self-critique, and+ * every named gate section. */+function gatePortion(slopText) {+ const idx = slopText.search(/^## Core-15 sweep/m);+ if (idx < 0) throw new Error('slop-test.md: "## Core-15 sweep" heading not found');+ return slopText.slice(idx).trimEnd();+}++function sep(relPath) {+ return `\n\n===== FILE: ${relPath} =====\n\n`;+}++function buildFloor() {+ const skill = readFileSync(SKILL_MD, "utf8");+ const parts = [+ { label: "preamble (3 lines)", text: PREAMBLE },+ { label: 'SKILL.md :: "Critical floor"', text: extractSection(skill, "Critical floor") },+ { label: 'SKILL.md :: "Flow at a glance"', text: extractSection(skill, "Flow at a glance") },+ ];+ const text =+ PREAMBLE ++ sep("skills/hallmark/SKILL.md (Critical floor + Flow at a glance)") ++ parts[1].text ++ "\n\n" ++ parts[2].text ++ "\n";+ return { parts, text };+}++function buildFull() {+ const files = [+ ["skills/hallmark/SKILL.md", SKILL_MD, (t) => t],+ ["skills/hallmark/references/typography.md", resolve(REFS, "typography.md"), (t) => t],+ ["skills/hallmark/references/color.md", resolve(REFS, "color.md"), (t) => t],+ ["skills/hallmark/references/anti-patterns.md", resolve(REFS, "anti-patterns.md"), (t) => t],+ ["skills/hallmark/references/copy.md", resolve(REFS, "copy.md"), (t) => t],+ ["skills/hallmark/references/slop-test.md (gate list portion)", resolve(REFS, "slop-test.md"), gatePortion],+ ];+ const parts = [{ label: "preamble (3 lines)", text: PREAMBLE }];+ let text = PREAMBLE;+ for (const [rel, abs, transform] of files) {+ const t = transform(readFileSync(abs, "utf8")).trimEnd();+ parts.push({ label: rel, text: t });+ text += sep(rel) + t;+ }+ return { parts, text: text + "\n" };+}++// ---------------------------------------------------------------------------++function parseArgs(argv) {+ const args = { pack: null, out: null, list: false };+ for (let i = 2; i < argv.length; i++) {+ const a = argv[i];+ if (a === "--pack") args.pack = argv[++i];+ else if (a === "--out") args.out = argv[++i];+ else if (a === "--list") args.list = true;+ else {+ console.error(`unknown argument: ${a}`);+ process.exit(2);+ }+ }+ if (!["floor", "full"].includes(args.pack ?? "")) {+ console.error("usage: node eval/make-pack.mjs --pack floor|full [--out <file>] [--list]");+ process.exit(2);+ }+ return args;+}++const approxTokens = (s) => Math.round(s.length / 4);++const args = parseArgs(process.argv);+const { parts, text } = args.pack === "floor" ? buildFloor() : buildFull();++if (args.list) {+ console.log(`pack "${args.pack}" includes:`);+ for (const p of parts) {+ console.log(` - ${p.label} (${p.text.length} chars, ~${approxTokens(p.text)} tok)`);+ }+ console.log(` total: ${text.length} chars, ~${approxTokens(text)} tok`);+} else if (args.out) {+ mkdirSync(dirname(resolve(args.out)), { recursive: true });+ writeFileSync(resolve(args.out), text, "utf8");+ console.log(`wrote ${resolve(args.out)} (${text.length} chars, ~${approxTokens(text)} tok)`);+} else {+ console.log(+ `pack "${args.pack}": ${parts.length} part(s), ${text.length} chars, ~${approxTokens(text)} tok`,+ );+}diff --git a/eval/models.json b/eval/models.jsonnew file mode 100644index 0000000..b7320e6--- /dev/null+++ b/eval/models.json@@ -0,0 +1,49 @@+{+ "arms": [+ {+ "id": "fable-baseline",+ "kind": "anthropic",+ "model": "claude-fable-5",+ "env": "ANTHROPIC_API_KEY"+ },+ {+ "id": "glm52-together",+ "kind": "openai-compat",+ "base": "https://api.together.xyz/v1",+ "model": "zai-org/GLM-5.2",+ "env": "TOGETHER_API_KEY",+ "temperature": 0.6,+ "extra": { "chat_template_kwargs": { "thinking": false } }+ },+ {+ "id": "k3-openrouter",+ "kind": "openai-compat",+ "base": "https://openrouter.ai/api/v1",+ "model": "moonshotai/kimi-k3",+ "env": "OPENROUTER_API_KEY",+ "omitTemperature": true,+ "extra": { "reasoning": { "effort": "medium" } }+ },+ {+ "id": "deepseek-openrouter",+ "kind": "openai-compat",+ "base": "https://openrouter.ai/api/v1",+ "model": "deepseek/deepseek-v3.2",+ "env": "OPENROUTER_API_KEY",+ "enabled": false+ },+ {+ "id": "qwen-openrouter",+ "kind": "openai-compat",+ "base": "https://openrouter.ai/api/v1",+ "model": "qwen/qwen3-coder-next",+ "env": "OPENROUTER_API_KEY",+ "enabled": false+ }+ ],+ "keyFiles": [+ "/Users/youssef/Desktop/.env.local",+ "/Users/youssef/Inspo-design/.env"+ ],+ "keyFileNotes": "Verified 2026-07-23: Desktop/.env.local defines ANTHROPIC_API_KEY and TOGETHER_API_KEY; Inspo-design/.env defines TOGETHER_API_KEY. OPENROUTER_API_KEY is NOT present in either file yet; the OpenRouter arms need it exported in the shell or added to a key file before they can run."+}diff --git a/eval/report.mjs b/eval/report.mjsnew file mode 100644index 0000000..3b359d1Binary files /dev/null and b/eval/report.mjs differdiff --git a/eval/run-matrix.py b/eval/run-matrix.pynew file mode 100644index 0000000..b6ffb29--- /dev/null+++ b/eval/run-matrix.py@@ -0,0 +1,184 @@+#!/usr/bin/env python3+"""run-matrix.py: orchestrator for the Hallmark eval pipeline.++Pipeline (each stage is a subprocess, filters passed through):++ 1. gen-direct.py generate artifacts for every selected arm x brief x pack+ 2. screenshot.mjs hero/full/mobile PNGs into eval/_shots/+ 3. score.mjs sloplint mechanical gates -> score.json per run+ 4. (repair loop) see below+ 5. judge.py vision judge -> judge.json per run (skips b5/b6)+ 6. report.mjs assemble eval/index.html gallery++Repair loop (--repair N):+ The repair machinery lives INSIDE gen-direct.py (--repair mode); this+ script only sequences gen -> score -> gen --repair -> score. In each of up+ to N rounds, gen-direct.py --repair 1 re-prompts every cell whose+ score.json still has FAIL findings: the previous artifact plus the failing+ findings are sent back to the SAME arm with "Fix these mechanical+ failures, re-emit the complete file", and the artifact is overwritten.+ gen-direct.py re-scores each repaired cell itself (via score.mjs), and+ this script re-takes screenshots with --force and runs a full score pass+ after every round. The loop exits early once no FAILs remain.++Flags:+ --brief b1..b6 (default all), --arm <id> (default all enabled),+ --pack floor|full (default floor), --repair N (default 0),+ --skip-gen, --skip-judge, --force, --dry-run.+ --tier is accepted but currently a no-op: it is reserved for the future+ Tier-A harness wrapper described in eval/README.md; gen-direct.py is the+ Tier-B (bare API) generator and takes no tier argument.++--dry-run prints or dry-runs every stage without any API call (no keys+needed). --skip-gen starts from existing artifacts (screenshot onward).++Examples:+ python3 eval/run-matrix.py --repair 2+ python3 eval/run-matrix.py --brief b1 --arm glm52-together --pack full+ python3 eval/run-matrix.py --skip-gen --force+"""++from __future__ import annotations++import argparse+import json+import subprocess+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent+GEN = ROOT / "gen-direct.py"+SCREENSHOT = ROOT / "screenshot.mjs"+SCORE = ROOT / "score.mjs"+JUDGE = ROOT / "judge.py"+REPORT = ROOT / "report.mjs"+RUNS = ROOT / "runs"+++def parse_args() -> argparse.Namespace:+ p = argparse.ArgumentParser(description="Hallmark eval matrix orchestrator")+ p.add_argument("--brief", default="all", help="brief id b1..b6, or 'all' (default)")+ p.add_argument("--arm", default="all", help="arm id from models.json, or 'all' enabled (default)")+ p.add_argument("--pack", default="floor", choices=["floor", "full"],+ help="prompt pack for gen-direct.py (default floor)")+ p.add_argument("--tier", help="reserved for the Tier-A harness wrapper; currently a no-op")+ p.add_argument("--repair", type=int, default=0, metavar="N",+ help="max repair rounds after scoring (default 0)")+ p.add_argument("--skip-gen", action="store_true",+ help="skip generation; screenshot/score/judge/report only")+ p.add_argument("--skip-judge", action="store_true", help="skip the vision judge stage")+ p.add_argument("--force", action="store_true",+ help="pass --force to gen, screenshot, and score stages")+ p.add_argument("--dry-run", action="store_true",+ help="dry-run every stage; nothing is sent anywhere")+ return p.parse_args()+++def stage_filters(args: argparse.Namespace) -> list[str]:+ """Filters for screenshot/score/judge, which treat missing flags as 'all'+ and match --arm as a run-dir prefix."""+ out: list[str] = []+ if args.brief != "all":+ out += ["--brief", args.brief]+ if args.arm != "all":+ # Pin to the exact arm-pack cell so other packs are untouched.+ out += ["--arm", f"{args.arm}-{args.pack}"]+ return out+++def run_stage(name: str, cmd: list[str], required: bool = True) -> bool:+ print(f"\n== {name}: {' '.join(cmd)}", flush=True)+ result = subprocess.run(cmd, cwd=str(ROOT))+ if result.returncode != 0:+ print(f"stage '{name}' exited {result.returncode}", file=sys.stderr)+ if required:+ sys.exit(result.returncode)+ return False+ return True+++def total_fails(args: argparse.Namespace) -> int | None:+ """Sum sloplint FAILs across matching runs; None if no scores yet."""+ if not RUNS.is_dir():+ return None+ total, seen = 0, 0+ for brief_dir in sorted(RUNS.iterdir()):+ if not brief_dir.is_dir():+ continue+ if args.brief != "all" and brief_dir.name != args.brief:+ continue+ for run_dir in sorted(brief_dir.iterdir()):+ if not run_dir.is_dir():+ continue+ if args.arm != "all" and not run_dir.name.startswith(args.arm):+ continue+ if not run_dir.name.endswith(f"-{args.pack}"):+ continue+ score_path = run_dir / "score.json"+ if not score_path.exists():+ continue+ try:+ score = json.loads(score_path.read_text())+ except (OSError, json.JSONDecodeError):+ continue+ if score.get("unavailable"):+ continue+ seen += 1+ total += int(score.get("summary", {}).get("fails", 0))+ return total if seen else None+++def main() -> None:+ args = parse_args()+ if args.tier:+ print(f"note: --tier {args.tier} is reserved for the Tier-A wrapper; ignored for now")++ dry = ["--dry-run"] if args.dry_run else []+ force = ["--force"] if args.force else []+ gen_args = ["--brief", args.brief, "--arm", args.arm, "--pack", args.pack]+ filters = stage_filters(args)++ if not args.skip_gen:+ if not GEN.exists():+ print(f"error: {GEN} not found; use --skip-gen to run scoring stages only",+ file=sys.stderr)+ sys.exit(1)+ run_stage("generate", [sys.executable, str(GEN), *gen_args, *force, *dry])++ run_stage("screenshot", ["node", str(SCREENSHOT), *filters, *force, *dry])+ run_stage("score", ["node", str(SCORE), *filters, *force, *dry])++ for round_no in range(1, max(args.repair, 0) + 1):+ fails = total_fails(args) if not args.dry_run else None+ if not args.dry_run and not fails:+ print(f"\nrepair: no FAILs outstanding, stopping before round {round_no}")+ break+ print(f"\n-- repair round {round_no}/{args.repair}"+ + (f" ({fails} FAILs outstanding)" if fails is not None else ""))+ ok = run_stage(f"repair-gen r{round_no}",+ [sys.executable, str(GEN), *gen_args, "--repair", "1", *dry],+ required=False)+ if not ok:+ break+ run_stage(f"repair-shots r{round_no}",+ ["node", str(SCREENSHOT), *filters, "--force", *dry])+ run_stage(f"repair-score r{round_no}",+ ["node", str(SCORE), *filters, "--force", *dry])+ if args.dry_run:+ break # one illustrative round is enough when nothing changes++ if args.skip_judge:+ print("\n== judge: skipped (--skip-judge)")+ else:+ run_stage("judge", [sys.executable, str(JUDGE), *filters, *dry], required=False)++ if args.dry_run:+ print("\n== report: node report.mjs (skipped in dry run)")+ else:+ run_stage("report", ["node", str(REPORT)])+ print("\nmatrix complete" + (" (dry run)" if args.dry_run else "")+ + "; open http://127.0.0.1:4201 via serve.py to browse")+++if __name__ == "__main__":+ main()diff --git a/eval/score.mjs b/eval/score.mjsnew file mode 100644index 0000000..64918b3--- /dev/null+++ b/eval/score.mjs@@ -0,0 +1,175 @@+#!/usr/bin/env node+// score.mjs: run the Hallmark sloplint gate checker over every eval artifact.+//+// For each eval/runs/<briefId>/<armId>-<pack>/index.html, runs:+// node skills/hallmark/scripts/sloplint.mjs <index.html> --json [--scope component]+// and writes score.json next to the artifact:+// { generatedAt, scope, findings, summary: {fails, warns}, floorClean }+//+// The component scope is applied to any brief whose expect.scope is+// "component" in eval/briefs.json (b5 today).+//+// floorClean is the floor-subset pass: zero FAIL findings among gates+// 1, 10, 14, 20, 26, 27, 34, 38a, 48, 54.+//+// If sloplint.mjs is absent or errors, score.json is {unavailable: true, ...}+// and the loop continues; this script never hard-fails the pipeline.+//+// Usage:+// node eval/score.mjs [--brief b1] [--arm fable-baseline] [--force] [--dry-run]++import { existsSync, readdirSync, statSync, readFileSync, writeFileSync } from "node:fs";+import { spawnSync } from "node:child_process";+import { fileURLToPath } from "node:url";+import path from "node:path";++const ROOT = path.dirname(fileURLToPath(import.meta.url));+const RUNS = path.join(ROOT, "runs");+const SLOPLINT = path.resolve(ROOT, "..", "skills", "hallmark", "scripts", "sloplint.mjs");+const BRIEFS_PATH = path.join(ROOT, "briefs.json");++const FLOOR_GATES = new Set(["1", "10", "14", "20", "26", "27", "34", "38a", "48", "54"]);++function parseArgs(argv) {+ const args = { brief: null, arm: null, force: false, dryRun: false };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === "--brief") args.brief = argv[++i];+ else if (a === "--arm") args.arm = argv[++i];+ else if (a === "--force") args.force = true;+ else if (a === "--dry-run") args.dryRun = true;+ else if (a === "--help" || a === "-h") {+ console.log("usage: node score.mjs [--brief id] [--arm id] [--force] [--dry-run]");+ process.exit(0);+ }+ }+ return args;+}++function loadComponentBriefs() {+ try {+ const briefs = JSON.parse(readFileSync(BRIEFS_PATH, "utf8"));+ return new Set(+ briefs.filter((b) => b?.expect?.scope === "component").map((b) => b.id)+ );+ } catch {+ return new Set(["b5"]);+ }+}++function listRuns(filter) {+ const out = [];+ if (!existsSync(RUNS)) return out;+ for (const briefId of readdirSync(RUNS).sort()) {+ const briefDir = path.join(RUNS, briefId);+ if (!statSync(briefDir).isDirectory()) continue;+ if (filter.brief && briefId !== filter.brief) continue;+ for (const cell of readdirSync(briefDir).sort()) {+ const runDir = path.join(briefDir, cell);+ if (!statSync(runDir).isDirectory()) continue;+ if (filter.arm && !cell.startsWith(filter.arm)) continue;+ const html = path.join(runDir, "index.html");+ if (!existsSync(html)) continue;+ out.push({ briefId, cell, runDir, html });+ }+ }+ return out;+}++function computeFloorClean(findings) {+ if (!Array.isArray(findings)) return null;+ for (const f of findings) {+ if (!f) continue;+ const grade = String(f.grade || "").toUpperCase();+ const gate = String(f.gate ?? "");+ if (grade === "FAIL" && FLOOR_GATES.has(gate)) return false;+ }+ return true;+}++function scoreOne(run, scope) {+ if (!existsSync(SLOPLINT)) {+ return { unavailable: true, reason: `sloplint.mjs not found at ${SLOPLINT}` };+ }+ const cliArgs = [SLOPLINT, run.html, "--json"];+ if (scope === "component") cliArgs.push("--scope", "component");+ const res = spawnSync(process.execPath, cliArgs, {+ encoding: "utf8",+ timeout: 120000,+ });+ if (res.error) {+ return { unavailable: true, reason: `sloplint spawn error: ${res.error.message}` };+ }+ let parsed;+ try {+ // sloplint may print a preamble; grab the outermost JSON object.+ const out = res.stdout || "";+ const start = out.indexOf("{");+ const end = out.lastIndexOf("}");+ if (start === -1 || end === -1) throw new Error("no JSON object in output");+ parsed = JSON.parse(out.slice(start, end + 1));+ } catch (err) {+ return {+ unavailable: true,+ reason: `sloplint output not parseable: ${err.message}`,+ exitCode: res.status,+ stderr: (res.stderr || "").slice(0, 2000),+ };+ }+ const findings = Array.isArray(parsed.findings) ? parsed.findings : [];+ const summary =+ parsed.summary && typeof parsed.summary === "object"+ ? parsed.summary+ : {+ fails: findings.filter((f) => String(f?.grade).toUpperCase() === "FAIL").length,+ warns: findings.filter((f) => String(f?.grade).toUpperCase() === "WARN").length,+ };+ return {+ scope,+ findings,+ summary,+ floorClean: computeFloorClean(findings),+ exitCode: res.status,+ };+}++function main() {+ const args = parseArgs(process.argv.slice(2));+ const componentBriefs = loadComponentBriefs();+ const runs = listRuns(args);+ if (runs.length === 0) {+ console.log("no runs found under eval/runs/");+ return;+ }+ if (!existsSync(SLOPLINT)) {+ console.log(`note: sloplint.mjs not present yet (${SLOPLINT}); writing unavailable scores`);+ }++ let scored = 0;+ for (const run of runs) {+ const scorePath = path.join(run.runDir, "score.json");+ if (existsSync(scorePath) && !args.force) {+ console.log(`skip ${run.briefId}/${run.cell} (score.json exists)`);+ continue;+ }+ const scope = componentBriefs.has(run.briefId) ? "component" : "page";+ if (args.dryRun) {+ console.log(`would score ${run.briefId}/${run.cell} (scope ${scope})`);+ continue;+ }+ const result = scoreOne(run, scope);+ result.generatedAt = new Date().toISOString();+ writeFileSync(scorePath, JSON.stringify(result, null, 2) + "\n");+ scored++;+ if (result.unavailable) {+ console.log(`score ${run.briefId}/${run.cell}: unavailable (${result.reason})`);+ } else {+ console.log(+ `score ${run.briefId}/${run.cell}: ${result.summary.fails} FAIL / ${result.summary.warns} WARN, floorClean=${result.floorClean}`+ );+ }+ }+ console.log(`done: ${scored} scored, ${runs.length - scored} skipped`);+}++main();diff --git a/eval/screenshot.mjs b/eval/screenshot.mjsnew file mode 100644index 0000000..ecc9ed8--- /dev/null+++ b/eval/screenshot.mjs@@ -0,0 +1,183 @@+#!/usr/bin/env node+// screenshot.mjs: capture hero/full/mobile shots for every eval run artifact.+//+// For each eval/runs/<briefId>/<armId>-<pack>/index.html with no existing+// shots (or with --force), writes:+// eval/_shots/<briefId>-<armId>-<pack>-hero.png 1280x800 viewport+// eval/_shots/<briefId>-<armId>-<pack>-full.png full page at 1280 wide+// eval/_shots/<briefId>-<armId>-<pack>-mobile.png 375x812 full page+//+// Engine: puppeteer-core driving the installed Chrome when the package is+// available; otherwise falls back to spawning the Chrome binary headless with+// --screenshot per shot (full page approximated by a tall window).+//+// Usage:+// node eval/screenshot.mjs [--brief b1] [--arm fable-baseline] [--force] [--dry-run]+//+// Zero npm dependencies required. CHROME_PATH overrides the Chrome binary.++import { existsSync, readdirSync, statSync, mkdirSync } from "node:fs";+import { spawnSync } from "node:child_process";+import { fileURLToPath, pathToFileURL } from "node:url";+import path from "node:path";++const ROOT = path.dirname(fileURLToPath(import.meta.url));+const RUNS = path.join(ROOT, "runs");+const SHOTS = path.join(ROOT, "_shots");++const DEFAULT_CHROME =+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";+const CHROME = process.env.CHROME_PATH || DEFAULT_CHROME;++const SHOT_SPECS = [+ { suffix: "hero", width: 1280, height: 800, fullPage: false },+ { suffix: "full", width: 1280, height: 800, fullPage: true, fallbackHeight: 4000 },+ { suffix: "mobile", width: 375, height: 812, fullPage: true, fallbackHeight: 3000 },+];++function parseArgs(argv) {+ const args = { brief: null, arm: null, force: false, dryRun: false };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === "--brief") args.brief = argv[++i];+ else if (a === "--arm") args.arm = argv[++i];+ else if (a === "--force") args.force = true;+ else if (a === "--dry-run") args.dryRun = true;+ else if (a === "--help" || a === "-h") {+ console.log("usage: node screenshot.mjs [--brief id] [--arm id] [--force] [--dry-run]");+ process.exit(0);+ }+ }+ return args;+}++function listRuns(filter) {+ const out = [];+ if (!existsSync(RUNS)) return out;+ for (const briefId of readdirSync(RUNS).sort()) {+ const briefDir = path.join(RUNS, briefId);+ if (!statSync(briefDir).isDirectory()) continue;+ if (filter.brief && briefId !== filter.brief) continue;+ for (const cell of readdirSync(briefDir).sort()) {+ const runDir = path.join(briefDir, cell);+ if (!statSync(runDir).isDirectory()) continue;+ if (filter.arm && !cell.startsWith(filter.arm)) continue;+ const html = path.join(runDir, "index.html");+ if (!existsSync(html)) continue;+ out.push({ briefId, cell, runDir, html, base: `${briefId}-${cell}` });+ }+ }+ return out;+}++function pendingSpecs(base, force) {+ if (force) return SHOT_SPECS;+ return SHOT_SPECS.filter(+ (s) => !existsSync(path.join(SHOTS, `${base}-${s.suffix}.png`))+ );+}++async function tryPuppeteer() {+ try {+ const mod = await import("puppeteer-core");+ return mod.default ?? mod;+ } catch {+ return null;+ }+}++async function shootWithPuppeteer(puppeteer, jobs) {+ const browser = await puppeteer.launch({+ executablePath: CHROME,+ headless: true,+ args: ["--disable-gpu", "--hide-scrollbars", "--force-device-scale-factor=1"],+ });+ try {+ const page = await browser.newPage();+ for (const job of jobs) {+ for (const spec of job.specs) {+ const out = path.join(SHOTS, `${job.base}-${spec.suffix}.png`);+ try {+ await page.setViewport({ width: spec.width, height: spec.height });+ await page.goto(pathToFileURL(job.html).href, {+ waitUntil: "networkidle0",+ timeout: 30000,+ });+ await new Promise((r) => setTimeout(r, 400));+ await page.screenshot({ path: out, fullPage: !!spec.fullPage });+ console.log(`shot ${path.relative(ROOT, out)}`);+ } catch (err) {+ console.error(`FAIL ${job.base}-${spec.suffix}: ${err.message}`);+ }+ }+ }+ } finally {+ await browser.close();+ }+}++function shootWithChromeBinary(jobs) {+ if (!existsSync(CHROME)) {+ console.error(`Chrome binary not found at ${CHROME}; set CHROME_PATH.`);+ process.exit(1);+ }+ for (const job of jobs) {+ for (const spec of job.specs) {+ const out = path.join(SHOTS, `${job.base}-${spec.suffix}.png`);+ const height = spec.fullPage ? spec.fallbackHeight || spec.height : spec.height;+ const res = spawnSync(+ CHROME,+ [+ "--headless=new",+ "--disable-gpu",+ "--hide-scrollbars",+ "--force-device-scale-factor=1",+ `--window-size=${spec.width},${height}`,+ `--screenshot=${out}`,+ "--virtual-time-budget=4000",+ pathToFileURL(job.html).href,+ ],+ { stdio: "ignore", timeout: 60000 }+ );+ if (res.status === 0 && existsSync(out)) {+ console.log(`shot ${path.relative(ROOT, out)} (chrome fallback)`);+ } else {+ console.error(`FAIL ${job.base}-${spec.suffix} (chrome fallback, exit ${res.status})`);+ }+ }+ }+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ mkdirSync(SHOTS, { recursive: true });++ const runs = listRuns(args);+ const jobs = runs+ .map((r) => ({ ...r, specs: pendingSpecs(r.base, args.force) }))+ .filter((j) => j.specs.length > 0);++ if (jobs.length === 0) {+ console.log("nothing to shoot (all shots exist; use --force to redo)");+ return;+ }+ if (args.dryRun) {+ for (const j of jobs)+ console.log(`would shoot ${j.base}: ${j.specs.map((s) => s.suffix).join(", ")}`);+ return;+ }++ const puppeteer = await tryPuppeteer();+ if (puppeteer) {+ console.log("engine: puppeteer-core");+ await shootWithPuppeteer(puppeteer, jobs);+ } else {+ console.log("engine: chrome --screenshot fallback (puppeteer-core not installed)");+ shootWithChromeBinary(jobs);+ }+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/eval/serve.py b/eval/serve.pynew file mode 100644index 0000000..7bce306--- /dev/null+++ b/eval/serve.py@@ -0,0 +1,23 @@+#!/usr/bin/env python3+"""serve.py: local static server for the eval gallery.++Serves the eval/ directory on http://127.0.0.1:4201 (loopback only).+PORT env var overrides the port.+"""++import functools+import http.server+import os+import socketserver+from pathlib import Path++port = int(os.environ.get("PORT", "4201"))+root = str(Path(__file__).resolve().parent)+Handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=root)+socketserver.ThreadingTCPServer.allow_reuse_address = True+socketserver.ThreadingTCPServer.daemon_threads = True++if __name__ == "__main__":+ with socketserver.ThreadingTCPServer(("127.0.0.1", port), Handler) as httpd:+ print(f"serving {root} on http://127.0.0.1:{port}", flush=True)+ httpd.serve_forever()