// Generates synthetic accessibility-fix fixtures (MIT).
// Usage: node scripts/gen-tasks.mjs [--seed N] [--split public|hidden] [--out path] [--count N]
// Public split defaults to data/tasks.jsonl with seed 20261015.
// Hidden split defaults to artifacts/tasks.hidden.jsonl (gitignored, never published)
// and uses its own a11yh- id prefix so hidden ids never collide with public ones.
import { mkdir, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { createHash } from "node:crypto";
const args = process.argv.slice(2);
const get = (name, fallback) => {
const index = args.indexOf(name);
return index === -1 ? fallback : args[index + 1];
};
if (args.includes("--help")) {
console.log("Usage: node scripts/gen-tasks.mjs [--seed N] [--split public|hidden] [--out path] [--count N]");
process.exit(0);
}
const seed = Number(get("--seed", "20261015"));
const split = get("--split", "public");
const count = Number(get("--count", "40"));
const out = get("--out", split === "hidden" ? "artifacts/tasks.hidden.jsonl" : "data/tasks.jsonl");
if (!Number.isInteger(seed) || !Number.isInteger(count) || count < 1) throw new Error("seed and count must be positive integers");
if (split !== "public" && split !== "hidden") throw new Error("--split must be public or hidden");
function mulberry32(start) {
let state = start >>> 0;
return () => {
state += 1831565813;
let value = state;
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
const pick = (rng, list) => list[Math.floor(rng() * list.length)];
const pickN = (rng, list, n) => {
const copy = [...list];
const out = [];
while (out.length < Math.min(n, copy.length)) out.push(copy.splice(Math.floor(rng() * copy.length), 1)[0]);
return out;
};
const shuffle = (rng, list) => {
const a = [...list];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
// WCAG relative luminance for #rrggbb.
function luminance(hex) {
const h = hex.replace("#", "");
const [r, g, b] = [0, 2, 4].map((i) => {
const c = parseInt(h.slice(i, i + 2), 16) / 255;
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
const ratio = (a, b) => {
const [x, y] = [luminance(a), luminance(b)].sort((m, n) => n - m);
return (x + 0.05) / (y + 0.05);
};
const hex = (rng, lo, hi) => "#" + [0, 1, 2].map(() => (lo + Math.floor(rng() * (hi - lo + 1))).toString(16).padStart(2, "0")).join("");
// A passing foreground/background pair at >= minRatio. The default
// carries margin over the 4.5:1 rule so equivalent color spellings
// (hsl() with rounded channels, 8-digit hex) cannot dip a reference
// page under the threshold.
function goodPair(rng, minRatio = 4.75) {
for (let tries = 0; tries < 200; tries++) {
const bg = hex(rng, 200, 255);
const fg = hex(rng, 0, 120);
if (ratio(fg, bg) >= minRatio) return { fg, bg };
}
throw new Error("no good pair found");
}
// A failing pair against a fixed background (text lands in the 3.5-4.4 band
// so the defect is visible but not blatant).
function badFg(rng, bg) {
for (let tries = 0; tries < 400; tries++) {
const fg = hex(rng, 120, 190);
const r = ratio(fg, bg);
if (r < 4.5 && r > 2.5) return fg;
}
return "#8a8a8a";
}
// A passing foreground on a FIXED background: the inline span inherits
// the body background, so it must be drawn against it, not against a
// throwaway pair bg.
function goodFg(rng, bg, minRatio = 4.75) {
for (let tries = 0; tries < 400; tries++) {
const fg = hex(rng, 0, 130);
if (ratio(fg, bg) >= minRatio) return fg;
}
throw new Error("no good foreground found");
}
// A large-text pair in the passing 3:1-4.5 band (valid fix, tests the
// large-text threshold). The 3.3 floor leaves room for color-format
// rounding noise, same margin idea as goodPair.
function largePair(rng) {
for (let tries = 0; tries < 300; tries++) {
const bg = hex(rng, 200, 255);
const fg = hex(rng, 60, 160);
const r = ratio(fg, bg);
if (r >= 3.3 && r < 4.5) return { fg, bg };
}
throw new Error("no large pair found");
}
const CHECKS = [
["missing-alt", "1.1.1"], ["unlabeled-input", "3.3.2"], ["low-contrast", "1.4.3"],
["heading-order", "1.3.1"], ["tabindex-positive", "2.4.3"], ["div-button", "4.1.2"],
["missing-lang", "3.1.1"], ["no-focus-style", "2.4.7"], ["empty-link", "2.4.4"],
["table-headers", "1.3.1"],
];
const WCAG = Object.fromEntries(CHECKS);
const ADJ = ["Harbor", "Kestrel", "Northern", "River", "Garden", "Amber", "Cedar", "Juniper", "Misty", "Copper", "Silver", "Quiet", "Bright", "Willow", "Frost", "Ember", "Sage", "Coral", "Atlas", "Meadow"];
const NOUN = ["Lights", "Ridge", "Valley", "Crossing", "Mills", "Works", "Foundry", "Collective", "Cooperative", "Observatory", "Pantry", "Workshop", "Ledger", "Orchard", "Depot", "Exchange", "Studio", "Clinic", "Archive", "Guild"];
const KIND = ["newsletter", "field guide", "status report", "release notes", "handbook", "bulletin", "weekly digest", "product sheet", "setup guide", "survey results", "booking page", "service page"];
const TOPICS = [
["ferry sailings", "harbor notes", "crossing times"],
["grind settings", "care notes", "brew ratios"],
["sleeper bookings", "reading list", "departure board"],
["volunteer shifts", "meeting point", "supply list"],
["api keys", "rate limits", "endpoint status"],
["survey findings", "next steps", "member quotes"],
["trail conditions", "permit windows", "ranger notes"],
["menu changes", "supplier list", "order cutoffs"],
["rehearsal dates", "set list", "venue notes"],
["seed inventory", "planting calendar", "pest watch"],
["loan rates", "branch hours", "member news"],
["build artifacts", "test matrix", "deploy log"],
];
const NOTES = [
"New routes post every Sunday evening.", "Burrs carry a five year warranty.",
"Berths sell out around holidays.", "Gloves and bags are provided.",
"Keys rotate every ninety days.", "Two hundred members answered.",
"Permits open on the first Monday.", "Orders close at noon on Fridays.",
"Rehearsals move indoors in winter.", "Seed counts refresh monthly.",
"Rates lock for sixty days.", "Artifacts prune after thirty days.",
];
const SPANS = [
"Ferries run hourly on holidays.", "Free returns within thirty days.",
"Bring a lock for the cabin door.", "All ages welcome with an adult.",
"Sandbox data refreshes hourly.", "Evening hours were the top ask.",
"Boots are required past the gate.", "Late orders ship the next day.",
"Guests may watch the last set.", "Cover beds before a frost.",
"Statements arrive by post.", "Flaky tests quarantine on retry.",
];
const ALTS = [
"Ferry crossing the harbor at dusk", "Steel burr coffee grinder on a counter",
"Sleeper train under northern lights", "Volunteers clearing a riverbank",
"Soil sensor beside tomato plants", "Reading room with tall shelves",
"Trail marker above the treeline", "Stacked crates at the loading dock",
"String section tuning on stage", "Seed packets on a potting bench",
"Teller counter at the main branch", "Build monitor showing green jobs",
];
const CTA = ["Subscribe", "Add to basket", "Save article", "Join us", "Get a key", "Download PDF", "Book now", "Reserve a spot", "Notify me", "Start trial"];
const NAV2 = ["About", "FAQ", "Pricing", "News", "Docs", "Team", "Contact", "Archive"];
const FIELD_POOL = [
["name", "Full name", "text"], ["email", "Email address", "email"],
["phone", "Phone number", "tel"], ["org", "Organization", "text"],
["city", "City", "text"], ["note", "Delivery note", "text"],
];
const CLASS_A = ["note", "hint", "aside", "fine", "meta", "muted"];
const CLASS_B = ["cta", "btn-primary", "action", "primary-btn", "main-action", "go"];
const CAPTIONS = ["Crossing times", "Grind guide", "Departure board", "Cleanup shifts", "Endpoint limits", "Survey results", "Permit windows", "Order ledger", "Rehearsal slots", "Seed counts", "Rate sheet", "Build history"];
const COLHEADS = [["Option", "Detail", "Status"], ["Name", "Owner", "State"], ["Step", "Input", "Output"], ["Item", "Count", "Flag"]];
const CELLS = [["Standard", "Weekly", "Open"], ["Plus", "Daily", "Open"], ["Rush", "Hourly", "Full"], ["Basic", "Monthly", "Closed"], ["Trial", "Once", "Open"], ["Custom", "On call", "Open"]];
// One randomized but fully accessible page. Returns the HTML plus a hooks
// object with the exact strings defect breakers can target.
function buildFixed(rng) {
const title = `${pick(rng, ADJ)} ${pick(rng, NOUN)} ${pick(rng, KIND)}`;
const topics = pick(rng, TOPICS);
const [h2a, h2b, caption] = [topics[0], topics[1], pick(rng, CAPTIONS)];
const noteClass = pick(rng, CLASS_A);
const ctaClass = pick(rng, CLASS_B);
const noteText = pick(rng, NOTES);
const spanText = pick(rng, SPANS);
const heroAlt = pick(rng, ALTS);
const img = `https://example.com/${title.toLowerCase().replace(/[^a-z]+/g, "-")}.jpg`;
const ctaText = pick(rng, CTA);
const nav2 = pick(rng, NAV2);
const fields = pickN(rng, FIELD_POOL, 2 + Math.floor(rng() * 2));
const colheads = pick(rng, COLHEADS);
const rows = pickN(rng, CELLS, 2 + Math.floor(rng() * 2));
// Colors: every pair is generated to pass.
const body = goodPair(rng);
const note = goodPair(rng);
const spanFg = goodFg(rng, body.bg);
const cta = goodPair(rng);
const focusColor = goodPair(rng).fg;
// A large-text heading pair in the legal 3:1-4.5 band keeps the
// large-text path exercised without tripping the defect check.
const large = rng() < 0.5 ? largePair(rng) : null;
const largeRule = large ? `\n.big-head{color:${large.fg};background-color:${large.bg};font-size:26px;font-weight:700}` : "";
const bigHead = large ? `
${h2a}
` : `${h2a}
`;
const styleBlock = ``;
const skip = `Skip to content`;
const formFields = fields.map(([id, label, type]) =>
`\n`).join("\n");
const tableRows = rows.map((r) => `${r.map((c) => `| ${c} | `).join("")}
`).join("\n");
const table = `\n${caption}\n${colheads.map((c) => `| ${c} | `).join("")}
\n${tableRows}\n
`;
const sections = shuffle(rng, [
`
`,
`${noteText}
`,
`${spanText}
`,
table,
]);
const html = `
${title}
${styleBlock}
${bigHead}
${sections[0]}
${sections[1]}
${h2b}
${sections[2]}
${sections[3]}
`;
return {
html,
hooks: {
heroAlt: ` alt="${heroAlt}"`,
label: fields[1] ? `\n` : `\n`,
noteRule: `.${noteClass}{color:${note.fg};`,
noteBad: `.${noteClass}{color:${badFg(rng, note.bg)};`,
spanRule: ``,
spanBad: ``,
ctaButton: ``,
ctaText,
focusRule: `\na:focus-visible,.${ctaClass}:focus-visible{outline:3px solid ${focusColor};outline-offset:2px}`,
skip,
archive: `Archive`,
},
};
}
const TABS = ["Overview", "History", "Members", "Billing", "Usage", "Alerts", "Archive", "Notes"];
// Hard tier: a different page skeleton, not the easy page with extra
// defects. Grouped fields carry names through an aria-labelledby chain,
// a tab widget holds role/tabindex/handler parts, and the table spans
// headers across columns and rows - so a fixer tuned to the easy template
// leaves real barriers behind.
function buildHard(rng) {
const title = `${pick(rng, ADJ)} ${pick(rng, NOUN)} ${pick(rng, KIND)}`;
const topics = pick(rng, TOPICS);
const [h2a, h2b, h3c] = topics;
const caption = pick(rng, CAPTIONS);
const noteClass = pick(rng, CLASS_A);
const ctaClass = pick(rng, CLASS_B);
const noteText = pick(rng, NOTES);
const spanText = pick(rng, SPANS);
const heroAlt = pick(rng, ALTS);
const img = `https://example.com/${title.toLowerCase().replace(/[^a-z]+/g, "-")}.jpg`;
const ctaText = pick(rng, CTA);
const nav2 = pick(rng, NAV2);
const cardText = pick(rng, CTA.filter((c) => c !== ctaText));
const tabs = pickN(rng, TABS, 2);
const [f0, f1, f2] = pickN(rng, FIELD_POOL, 3);
const colheads = pick(rng, COLHEADS);
const cells = pickN(rng, CELLS, 4);
const body = goodPair(rng);
const note = goodPair(rng);
const spanFg = goodFg(rng, body.bg);
const cta = goodPair(rng);
const tabPair = goodPair(rng);
const focusColor = goodPair(rng).fg;
const large = rng() < 0.5 ? largePair(rng) : null;
const largeRule = large ? `\n.big-head{color:${large.fg};background-color:${large.bg};font-size:26px;font-weight:700}` : "";
const bigHead = large ? `${h2a}
` : `${h2a}
`;
const styleBlock = ``;
const skip = `Skip to content`;
const labelParts = f0[1].split(" ");
const labSpanA = `${labelParts[0]}`;
const labSpanB = `${labelParts.slice(1).join(" ") || pick(rng, topics)}`;
const tabA = `${tabs[0]}
`;
const tabB = `${tabs[1]}
`;
const tabsOpen = ``;
const label = `
`;
const cardHref = `/${cardText.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
const cardLink = `
${cardText}`;
const table = `
${caption}
| ${colheads[0]} | ${colheads[1]} |
| ${cells[0][0]} | ${cells[0][1]} | ${cells[0][2]} |
| ${cells[1][0]} | ${cells[1][1]} | ${cells[1][2]} |
| ${cells[2][0]} | ${cells[2][1]} | ${cells[2][2]} |
`;
const sections = shuffle(rng, [
`

`,
`
${noteText}
`,
`
${spanText}
`,
table,
]);
const html = `
${title}
${styleBlock}
${bigHead}
${sections[0]}
${sections[1]}
${h2b}
${tabsOpen}
${tabA}
${tabB}
${h3c}
${sections[2]}
${cardLink}
${sections[3]}
`;
return {
html,
hooks: {
heroAlt: ` alt="${heroAlt}"`,
label: `${label}\n`,
labSpanA,
labSpanB,
labelledby: `aria-labelledby="l-a l-b"`,
noteRule: `.${noteClass}{color:${note.fg};`,
noteBad: `.${noteClass}{color:${badFg(rng, note.bg)};`,
spanRule: ``,
spanBad: ``,
tabA,
tabsOpen,
ctaButton: ``,
ctaText,
focusRule: `\na:focus-visible,.${ctaClass}:focus-visible,[role=tab]:focus-visible{outline:3px solid ${focusColor};outline-offset:2px}`,
skip,
archive: `Archive`,
cardLink,
cardHref,
cardText,
heading3: `${h2b}
`,
},
};
}
// Each breaker rewrites one hook in the fixed page. Variants make the same
// defect appear in different disguises (role-button lookalikes, multi-step
// tab order, empty-label silences) so a template-aware regex fixer misses.
const BREAKERS = {
"missing-alt": (h) => [(p) => p.replace(h.hooks.heroAlt, ""), "alt removed"],
"unlabeled-input": (h, rng) => {
const variant = rng();
if (variant < 0.5) return [(p) => p.replace(h.hooks.label, ""), "label removed"];
if (variant < 0.8) return [(p) => p.replace(/