content-md 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.js ADDED
@@ -0,0 +1,202 @@
1
+ // MCP server over stdio. The host's own model (Codex, Cursor, Claude Code...) does the writing;
2
+ // this server gives it the playbooks, shipped examples, style-guide rules and a linter.
3
+ import { readFileSync } from "node:fs";
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import { z } from "zod";
7
+ import { findReferenceV2Async, decideTone, HAS_ENRICHED } from "./reference2.js";
8
+ import { readProduct, auditCopy } from "./product.js";
9
+ import { saveProductBrief, askPerson } from "./context.js";
10
+ import { META, PATTERNS, ELEMENTS, HAS_EXAMPLES, findExamples, findRules, getGuide, lintCopy, findReference, compareToReference } from "./tools.js";
11
+
12
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
13
+
14
+ const INSTRUCTIONS_FULL = `Use these tools whenever you write or review interface copy: buttons, errors, empty states, dialogs, onboarding, permissions, paywalls, checkout, notifications, tooltips, loading states or AI chat UI, including strings in code.
15
+ Write from the rules, the tone decision and the pattern playbook. Shipped copy is optional evidence, not a template.
16
+ 0. In a codebase, call read_product once per session. Use the saved brief if there is one; otherwise fill its slots from the repo, write the short brief, ask the person at most two questions that would change the copy (ask_person; otherwise state your assumption), and save it with save_product_brief unless the person said not to touch files. Write for that product, its audience and its own words, and keep its voice. To improve existing copy, call audit_copy and fix the worst lines first; leave unflagged lines alone.
17
+ 1. Call get_guide with the pattern once per task and follow it.
18
+ 2. If the moment has stakes or feeling (an error, money, a deletion, a success), call decide_tone with the facts of the moment, and use its tone words and instruction.
19
+ 3. State-check before you write: name the screen state and what the product actually knows. Do not claim more than that.
20
+ 4. Write every piece the screen needs. When rewriting, keep labels, buttons and titles that already work.
21
+ 5. Optional: call find_reference when you want evidence for a decision, or pass the tool state when the copy describes progress or an outcome, to get a correction example. If it returns nothing, write from the rules.
22
+ 6. Run lint_copy on every draft and fix each block and warn, or say why you kept it. Run a promise audit only when a claim goes beyond what the state says. In a codebase, back each claim in help, policy or onboarding copy with a file and line, and drop what you can't back. Never invent a source, name, date or figure as an example. Score each string 1-3 with the rubric in the guide and return nothing below 2.
23
+ Lead with paste-ready copy. If you quote a shipped line, quote it exactly as a tool returned it.`;
24
+ const INSTRUCTIONS = HAS_EXAMPLES ? INSTRUCTIONS_FULL : `Use these tools whenever you write or review interface copy, including strings in code.
25
+ 0. In a codebase, call read_product once and write the product brief it asks for; to improve existing copy, call audit_copy and fix the worst lines first.
26
+ 1. Call get_guide with the pattern once per task and follow it.
27
+ 2. If the moment has stakes or feeling, call decide_tone first.
28
+ 3. State-check, write every piece the screen needs, then run lint_copy on every draft and fix each block and warn, or say why you kept it. Score each string 1-3 with the rubric in the guide and return nothing below 2.
29
+ Lead with paste-ready copy, recommend one option, and cite the rule behind it.`;
30
+
31
+ const json = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 1) }] });
32
+ const pattern = z.enum(PATTERNS);
33
+ const element = z.enum(ELEMENTS);
34
+
35
+ export async function serve() {
36
+ const server = new McpServer({ name: "content-md", version: pkg.version }, { instructions: INSTRUCTIONS });
37
+
38
+ server.registerTool("get_guide", {
39
+ title: "UX writing guide",
40
+ description: `The voice, workflow, universal rules and the playbook for one UI pattern, built from ${META.sources} public style guides and a labeled set of shipped interface copy. Call once at the start of any copy task.`,
41
+ inputSchema: { pattern: pattern.optional().describe("The UI situation. Omit to get every playbook.") },
42
+ annotations: { readOnlyHint: true },
43
+ }, async ({ pattern }) => ({ content: [{ type: "text", text: getGuide({ pattern }) }] }));
44
+
45
+ if (HAS_EXAMPLES) server.registerTool("find_examples", {
46
+ title: "Find shipped examples",
47
+ description: `Optional evidence: search labeled shipped screens for how a situation was worded. Returns whole screens (headline, body and buttons together); each piece is rated gold, strong, solid or weak, with labeler notes. Use quality 'weak' to see what to avoid. For a single line, use find_reference. Cite a product only if a tool returned it.`,
48
+ inputSchema: {
49
+ pattern,
50
+ element: element.optional().describe("Only screens containing this piece"),
51
+ query: z.string().optional().describe("Key nouns of the situation, e.g. 'card declined refund'"),
52
+ platform: z.enum(["ios", "web"]).optional(),
53
+ quality: z.enum(["best", "weak"]).optional(),
54
+ limit: z.number().int().min(1).max(10).optional(),
55
+ },
56
+ annotations: { readOnlyHint: true },
57
+ }, async (args) => json(findExamples(args)));
58
+
59
+ if (HAS_EXAMPLES) server.registerTool("find_reference", {
60
+ title: "Find the closest reference",
61
+ description: `Optional evidence for one element in one situation. Returns the closest shipped lines, best first (often none: then write from the rules), each with its shape (opening move, sentence count, target length), the headline it sat under, a labeler note and its link. Use them to check a decision, not as a template. Pass the old line as draft when rewriting, and the tool state when copy describes progress or an outcome.`,
62
+ inputSchema: {
63
+ element: element.optional().describe("The piece you are writing, e.g. body, helper-text, headline, primary-cta"),
64
+ situation: z.string().describe("The moment in plain words, about the person's goal, not your feature name. Write it the way the references are tagged: a short clause saying what the line does for the person, e.g. 'promising a reminder before the free trial ends', 'telling the person what the page holds and what they can do there', 'promise that their data is never sold'. Call again with a second wording if the first list looks off."),
65
+ state: z.object({}).passthrough().optional().describe("What the product's own tool or API reports about the item (e.g. {status: \"submitted\", reviewed: false}). Used to find a correction example when the copy could claim more than that state supports."),
66
+ pattern: pattern.optional().describe("Boosts this pattern; omit to search every pattern"),
67
+ draft: z.string().optional().describe("The current line, when rewriting"),
68
+ platform: z.enum(["ios", "web"]).optional(),
69
+ limit: z.number().int().min(1).max(8).optional(),
70
+ role: z.string().optional().describe("The line's job inside its component, e.g. screen-title, explanation, field-helper, primary-action. Takes the place of element."),
71
+ brief: z.object({}).passthrough().optional().describe("Facts of the moment: screen_state, stakes, risk[], cause, reversibility, user_mindset, user_emotion, journey_stage, trigger. Gives tone- and situation-aware matching."),
72
+ tone: z.array(z.string()).optional().describe("Wanted tone words; omit to let the tone decider choose from the brief"),
73
+ target_words: z.number().int().optional(),
74
+ },
75
+ annotations: { readOnlyHint: true },
76
+ }, async (args) => json(HAS_ENRICHED && (args.brief || args.tone || args.role) ? await findReferenceV2Async(args) : findReference(args)));
77
+
78
+ if (HAS_ENRICHED) server.registerTool("decide_tone", {
79
+ title: "Decide the tone for a moment",
80
+ description: "Call this before find_reference when the moment has stakes or feeling (an error, a payment, a deletion, a success). Give the facts of the moment; get back two tone words, one concrete instruction, the tones to avoid and the mistakes writers are tempted to make. Voice stays the product's; tone moves with the moment.",
81
+ inputSchema: {
82
+ screen_state: z.enum(["default", "empty", "loading", "success", "error", "offline", "blocked", "confirming"]).optional(),
83
+ stakes: z.enum(["low", "medium", "high"]).optional(),
84
+ risk: z.array(z.enum(["money", "data-loss", "privacy", "security", "access", "commitment"])).optional(),
85
+ cause: z.enum(["user", "product", "third-party", "none"]).optional().describe("Who caused the problem"),
86
+ reversibility: z.enum(["reversible", "hard-to-undo", "irreversible", "n/a"]).optional(),
87
+ user_mindset: z.enum(["exploring", "evaluating", "task-focused", "hesitant", "worried", "frustrated", "stuck", "accomplished", "elsewhere"]).optional(),
88
+ user_emotion: z.string().optional(),
89
+ journey_stage: z.enum(["discover", "sign-up", "sign-in", "onboarding", "first-use", "core-task", "transaction", "upgrade", "account", "re-engagement", "support", "offboarding"]).optional(),
90
+ trigger: z.enum(["user-action", "system-event", "error", "first-launch", "time-based", "milestone"]).optional(),
91
+ audience: z.enum(["consumer", "professional", "developer"]).optional(),
92
+ voice: z.string().optional().describe("The product's voice key, e.g. plain, playful, formal; omit for plain"),
93
+ },
94
+ annotations: { readOnlyHint: true },
95
+ }, async (args) => { const d = decideTone(args); return json({ tones: d.tones, also_fits: d.also_fits, instruction: d.instruction, register: d.register, purpose: d.purpose, mood: d.mood, avoid: d.wrong, tempting_mistakes: d.tempting, brief: d.brief }); });
96
+
97
+ server.registerTool("compare_to_reference", {
98
+ title: "Compare a line to its reference",
99
+ description: "Deterministic shape check of a candidate against its reference: same opening move (verb, subject, frame, noun), same sentence count, length within 30%, same ending (statement or question), plus the words they share. Run on every candidate before presenting it.",
100
+ inputSchema: {
101
+ reference: z.string().describe("The reference line exactly as shipped"),
102
+ candidate: z.string().describe("Your line"),
103
+ },
104
+ annotations: { readOnlyHint: true },
105
+ }, async (args) => json(compareToReference(args)));
106
+
107
+ server.registerTool("find_rules", {
108
+ title: "Find style-guide rules",
109
+ description: `Look up rules from ${META.sources} public style guides (NN/g, Apple HIG, Material, Polaris, GOV.UK, Atlassian, Carbon, Microsoft, Mailchimp and more), with do/don't examples. Use to settle a doubt or justify a choice.`,
110
+ inputSchema: {
111
+ pattern: pattern.optional(),
112
+ element: element.optional(),
113
+ query: z.string().optional().describe("Topic words, e.g. 'apology', 'button casing'"),
114
+ limit: z.number().int().min(1).max(20).optional(),
115
+ },
116
+ annotations: { readOnlyHint: true },
117
+ }, async (args) => json(findRules(args)));
118
+
119
+ server.registerTool("lint_copy", {
120
+ title: "Lint copy",
121
+ description: "Deterministic pass/fail checks on one screen's copy (pass the tool state, stakes and expected pieces for the full set): state overclaim, tone fence at high stakes, plural handling, verb-only buttons, missing pieces, template leaks, raw error codes, filler, generic buttons, blame words, 'Are you sure', body repeating headline, casing, length, emoji at high stakes. Severity block > warn > note. Run on every draft before presenting it.",
122
+ inputSchema: {
123
+ pattern: pattern.optional(),
124
+ units: z.array(z.object({ element, text: z.string() })).min(1).describe("Every piece of copy on the screen, in order"),
125
+ state: z.object({}).passthrough().optional().describe("What the product's tool or API reports about the item. Turns on the state-overclaim check: copy that claims approved, delivered, charged, live, complete etc. without that evidence is blocked."),
126
+ stakes: z.enum(["low", "medium", "high"]).optional().describe("From decide_tone. At high, exclamation marks and light words are flagged."),
127
+ expected_pieces: z.array(element).optional().describe("The pieces the screen needs; any missing one is blocked."),
128
+ original: z.array(z.object({ element: z.string(), text: z.string() })).optional().describe("When rewriting: the old pieces. Short originals that were changed are noted."),
129
+ },
130
+ annotations: { readOnlyHint: true },
131
+ }, async (args) => {
132
+ const findings = lintCopy(args);
133
+ const pass = !findings.some((f) => f.severity === "block" || f.severity === "warn");
134
+ return json({ pass, findings: findings.length ? findings : "No findings.", ...(pass ? {} : { next: "Fix every block and warn, then run lint_copy again, or say why you kept one." }) });
135
+ });
136
+
137
+ server.registerTool("read_product", {
138
+ title: "Read the product",
139
+ description: "Read the codebase you are working in to learn what the product is, who uses it and how it already sounds: manifest, README, landing copy, a sample of its own UI strings with file:line, and voice numbers (casing, 'we', exclamation marks, contractions, the product's own words). Call it once per session before writing or reviewing copy in a repo, then write the short product brief it asks for.",
140
+ inputSchema: {
141
+ root: z.string().optional().describe("Project root; defaults to the folder the server was started in"),
142
+ sample: z.number().int().min(5).max(80).optional(),
143
+ },
144
+ annotations: { readOnlyHint: true },
145
+ }, async (args) => json(readProduct(args)));
146
+
147
+ server.registerTool("save_product_brief", {
148
+ title: "Save the product brief",
149
+ description: "Save the product brief (and any answers the person gave) into a marked block in AGENTS.md, or CLAUDE.md if that's what the repo uses, so every later session and every agent starts from it instead of asking again. Replaces the block if it exists; leaves the rest of the file alone.",
150
+ inputSchema: {
151
+ root: z.string().optional(),
152
+ file: z.string().optional().describe("Relative path to write to; defaults to wherever the brief already is, else AGENTS.md"),
153
+ fields: z.object({
154
+ product: z.string(), audience: z.string(), industry: z.string().optional(), job: z.string().optional(), voice: z.string(),
155
+ terms: z.string().optional(), stakes: z.string().optional(), constraints: z.string().optional(),
156
+ "examples of current voice": z.string().optional(),
157
+ }).passthrough(),
158
+ },
159
+ }, async (args) => json(saveProductBrief(args)));
160
+
161
+ server.registerTool("ask_person", {
162
+ title: "Ask the person",
163
+ description: "Ask the person up to two questions from read_product's `questions`, as a short form with options, where the client supports it. If it can't, it returns the questions for you to ask in chat. Only call it after checking the conversation, saved brief and repo yourself, and only for answers that change the copy.",
164
+ inputSchema: {
165
+ questions: z.array(z.object({ slot: z.string(), question: z.string(), options: z.array(z.string()).min(2), default: z.string(), why: z.string().optional() })).min(1).max(2),
166
+ },
167
+ }, async ({ questions }) => json(await askPerson(server, questions)));
168
+
169
+ server.registerTool("audit_copy", {
170
+ title: "Audit existing copy",
171
+ description: "Find the user-facing strings in the codebase (locale files, JSX/HTML text, titles, labels, placeholders, toasts, alerts) or in a list you pass, run every lint and AI-voice check on each, and rank them worst first, weighting lines where money, data or access is at stake. Use it to decide which copy to rewrite and which to leave alone.",
172
+ inputSchema: {
173
+ root: z.string().optional(),
174
+ path_filter: z.string().optional().describe("Only strings from files whose path contains this, e.g. 'settings' or 'checkout'"),
175
+ strings: z.array(z.union([z.string(), z.object({ text: z.string(), element: element.optional() })])).optional().describe("Audit these instead of scanning the repo"),
176
+ limit: z.number().int().min(1).max(100).optional(),
177
+ },
178
+ annotations: { readOnlyHint: true },
179
+ }, async (args) => json(auditCopy(args)));
180
+
181
+ server.registerPrompt("write-copy", {
182
+ title: "Write UX copy",
183
+ description: "Write the copy for a screen or component",
184
+ argsSchema: { situation: z.string().describe("What the screen is for and what just happened") },
185
+ }, ({ situation }) => ({
186
+ messages: [{ role: "user", content: { type: "text", text: `Write the interface copy for this situation, using the content-md tools (get_guide, decide_tone when the moment has stakes, lint_copy):\n\n${situation}` } }],
187
+ }));
188
+
189
+ server.registerPrompt("review-copy", {
190
+ title: "Review UX copy",
191
+ description: "Review existing copy and fix it",
192
+ argsSchema: { copy: z.string().describe("The copy, a file path, or a description of where it lives") },
193
+ }, ({ copy }) => ({
194
+ messages: [{ role: "user", content: { type: "text", text: `Review this interface copy with the content-md tools (get_guide, lint_copy). Give a one-line verdict, then findings as original -> problem -> fix, most harmful first, then the revised copy:\n\n${copy}` } }],
195
+ }));
196
+
197
+ server.registerResource("guide", "content-md://guide", {
198
+ title: "UX writing guide", description: "Full voice guide and all pattern playbooks", mimeType: "text/markdown",
199
+ }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/markdown", text: getGuide({}) }] }));
200
+
201
+ await server.connect(new StdioServerTransport());
202
+ }
package/src/tools.js ADDED
@@ -0,0 +1,416 @@
1
+ import { aiVoice } from "./aivoice.js";
2
+ // The four tools behind the MCP server. Pure functions over the bundled data.
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const read = (p) => readFileSync(join(ROOT, p), "utf8");
9
+
10
+ export const META = JSON.parse(read("data/meta.json"));
11
+ export const PATTERNS = META.patterns;
12
+ export const ELEMENTS = META.elements;
13
+ // The public build ships without the whole-screen dataset; find_examples is then left out.
14
+ export const HAS_EXAMPLES = existsSync(join(ROOT, "data/screens.json"));
15
+
16
+ let screens, rules, skill, voice, rubric, patternIndex;
17
+ function load() {
18
+ if (!rules) {
19
+ screens = HAS_EXAMPLES ? JSON.parse(read("data/screens.json")) : [];
20
+ rules = JSON.parse(read("data/rules.json"));
21
+ skill = read("guide/SKILL.md");
22
+ voice = read("guide/voice.md");
23
+ rubric = read("guide/rubric.md");
24
+ try { patternIndex = read("guide/patterns.md"); } catch { patternIndex = ""; }
25
+ }
26
+ }
27
+
28
+ const STOP = new Set("a an the to of and or for in on is are be your you we it this that with at by from as".split(" "));
29
+ const tokens = (s) => new Set(((s || "").toLowerCase().match(/[a-z0-9']+/g) || []).filter((w) => !STOP.has(w)));
30
+ const overlap = (a, b) => { let n = 0; for (const w of a) if (b.has(w)) n++; return n; };
31
+
32
+ // u.s is a batch-aware rank computed in scripts/build-data.py (raw scores differ by labeler)
33
+ const score = (u) => u.s;
34
+
35
+ export function findExamples({ pattern, element, query, platform, industry, quality = "best", limit = 5, exclude_products }) {
36
+ load();
37
+ // UXW_EXCLUDE_PRODUCTS (comma-separated) lets evals hide the product under test
38
+ const fromEnv = (process.env.UXW_EXCLUDE_PRODUCTS || "").split(",").filter(Boolean);
39
+ const exclude = new Set([...(exclude_products || []), ...fromEnv].map((p) => p.trim().toLowerCase()));
40
+ const q = tokens(query);
41
+ const ranked = [];
42
+ for (const s of screens) {
43
+ if (s.p !== pattern || exclude.has(s.product.toLowerCase())) continue;
44
+ if (platform && s.platform !== platform) continue;
45
+ if (industry && s.industry !== industry) continue;
46
+ let hits = s.copy.filter((u) => !element || u.e === element);
47
+ if (quality === "weak") hits = hits.filter((u) => u.r === "weak");
48
+ if (!hits.length) continue;
49
+ const base = quality === "weak" ? 10 : Math.max(...hits.map(score));
50
+ const words = new Set();
51
+ for (const u of s.copy) for (const w of tokens(u.t + " " + (u.n || ""))) words.add(w);
52
+ ranked.push([base + 2 * overlap(q, words), s]);
53
+ }
54
+ ranked.sort((a, b) => b[0] - a[0]);
55
+ return ranked.slice(0, Math.min(limit, 10)).map(([, s]) => ({
56
+ product: s.product, platform: s.platform, industry: s.industry,
57
+ copy: s.copy.map((u) => ({
58
+ element: u.e, text: u.t, rating: u.r,
59
+ ...(u.n ? { note: u.n } : {}),
60
+ })),
61
+ }));
62
+ }
63
+
64
+ export function findRules({ pattern, element, query, limit = 8 }) {
65
+ load();
66
+ const q = tokens(query);
67
+ const ranked = [];
68
+ for (const r of rules) {
69
+ if (pattern && r.pattern !== pattern && r.pattern !== "general") continue;
70
+ if (element && r.element && r.element !== element) continue;
71
+ let s = (r.pattern === pattern ? 2 : 0) + (element && r.element === element ? 1 : 0) + (r.strength === "must" ? 1 : 0);
72
+ s += 2 * overlap(q, new Set([...tokens(r.rule), ...tokens(r.topic)]));
73
+ ranked.push([s, r]);
74
+ }
75
+ ranked.sort((a, b) => b[0] - a[0]);
76
+ return ranked.slice(0, Math.min(limit, 20)).map(([, r]) => ({
77
+ rule: r.rule, why: r.why, do: r.do, dont: r.dont, strength: r.strength, source: r.source,
78
+ }));
79
+ }
80
+
81
+ // SKILL.md headings for each pattern
82
+ const PLAYBOOK = {
83
+ "empty-state": "Empty state", error: "Error", "toast-snackbar": "Toast", "confirmation-dialog": "Confirmation dialog",
84
+ "settings-destructive": "Account or workspace deletion", onboarding: "Onboarding", "permission-request": "Permission request",
85
+ "loading-progress": "Loading and progress", "search-no-results": "Search with no results", offline: "Offline",
86
+ "push-notification": "Push notification", success: "Success", "paywall-upsell": "Paywall", "auth-form": "Sign-up and login",
87
+ "tooltip-coachmark": "Tooltip", checkout: "Checkout", "ai-chat": "AI chat interface",
88
+ "settings-preferences": "Settings and preferences", "navigation-menu": "Menus and navigation",
89
+ "form-general": "Forms", "verification-kyc": "Identity verification", "invite-share": "Invite and share",
90
+ "referral-rewards": "Referral and rewards", "rating-review-prompt": "Rating and review",
91
+ "subscription-management": "Subscription management", "help-support": "Help and support",
92
+ "update-maintenance": "Updates and maintenance", "consent-privacy": "Consent and privacy", email: "Email",
93
+ };
94
+
95
+ function section(md, level, startsWith) {
96
+ const lines = md.split("\n");
97
+ const prefix = "#".repeat(level) + " ";
98
+ const i = lines.findIndex((l) => l.startsWith(prefix + startsWith));
99
+ if (i < 0) return "";
100
+ let j = i + 1;
101
+ while (j < lines.length && !(/^#{1,6} /.test(lines[j]) && lines[j].match(/^#+/)[0].length <= level)) j++;
102
+ return lines.slice(i, j).join("\n").trim();
103
+ }
104
+
105
+ export function getGuide({ pattern }) {
106
+ load();
107
+ const parts = [voice.trim()];
108
+ for (const h of ["Universal rules", "What screenshots can't show", "Defaults where sources disagree"]) parts.push(section(skill, 2, h));
109
+ if (pattern) parts.push("## Playbook for this pattern\n\n" + section(skill, 3, PLAYBOOK[pattern]));
110
+ else parts.push(section(skill, 2, "Pattern playbooks"));
111
+ parts.push(rubric.trim());
112
+ parts.push(section(skill, 2, "Review checklist"));
113
+ if (patternIndex) parts.push(patternIndex.trim());
114
+ return parts.filter(Boolean).join("\n\n");
115
+ }
116
+
117
+ // --- lint ---------------------------------------------------------------
118
+
119
+ const FILLER = [/\bsuccessfully\b/gi, /\bsimply\b/gi, /\bplease note\b/gi, /\bit looks like\b/gi,
120
+ /\bit seems\b/gi, /\boops\b/gi, /\bwhoops\b/gi, /\bno worries\b/gi, /\bto get started\b/gi,
121
+ /\bin order to\b/gi, /\bkindly\b/gi, /\beasily\b/gi, /\bseamless(ly)?\b/gi];
122
+ const VAGUE = [
123
+ [/\bjust\b/gi, "just", "cut 'just' if it only softens; keep it when it means 'only' or 'a moment ago'"],
124
+ [/\b(for (a|your) better experience|for your convenience|to meet your needs|get the most out of)\b/gi, "vague-benefit", "name the concrete benefit or end the sentence sooner"],
125
+ [/\b(all done|taken care of|that's sorted)\b/gi, "vague-completion", "name what was done, and what wasn't, if the person can't otherwise tell"],
126
+ [/\b(here you can|this (page|screen|section|tab) (lets|allows|enables) you to|(allows|enables) you to)\b/gi, "capability-wrapper", "start with the verb: 'Export your data', not 'Here you can export your data'"],
127
+ [/\b(sit tight|hang tight|working (our|its) magic|grab a coffee|good things take time)\b/gi, "loading-performance", "say what's loading, or how long, or nothing"],
128
+ [/\b(click|tap) here\b/gi, "click-here", "make the link the words that say where it goes"],
129
+ [/\b(designed to help you|built to help you|we've made it (simple|easy)|we made it (simple|easy))\b/gi, "design-intent", "describe what the person can do, not what the team intended"],
130
+ [/\b(we're|we are) (excited|thrilled|delighted|happy) to (introduce|announce|share|launch)\b/gi, "company-excitement", "lead with what's new for the person"],
131
+ [/\b(your journey starts here|the possibilities are endless|the sky's the limit|let the magic begin)\b/gi, "pep-talk", "say what to add first and what it gives them"],
132
+ ];
133
+ const GENERIC_CTA = new Set(["ok", "okay", "yes", "no", "submit", "continue", "next", "confirm", "click here", "proceed", "go"]);
134
+ const BLAME = [/\binvalid\b/gi, /\billegal\b/gi, /\bfailed to\b/gi, /\bwrong\b/gi, /\byou must\b/gi, /\berror occurred\b/gi];
135
+ const ABSOLUTES = [/\bnever\b/gi, /\balways\b/gi, /\bguarantee[ds]?\b/gi, /\b100%/gi];
136
+ const LEAK = [/\bundefined\b/gi, /\bnull\b/gi, /\bNaN\b/g, /\[object/gi, /%[sd]\b/g];
137
+ const CODE = [/\b(error|err)[ _-]?\d{2,}\b/gi, /\b[A-Z]{2,}_[A-Z_]{2,}\b/g, /\b0x[0-9a-f]+\b/gi, /\bexception\b/gi];
138
+ const SENTENCE_ELEMENTS = new Set(["body", "helper-text", "inline-error", "legal-fineprint"]);
139
+ const LIMITS = { headline: 10, "primary-cta": 4, "secondary-cta": 4, "tertiary-link": 5, toast: 12, body: 35, "inline-error": 20, badge: 3, label: 4, "title-bar": 5 };
140
+ const HIGH_STAKES = new Set(["error", "checkout", "settings-destructive", "confirmation-dialog", "offline", "paywall-upsell"]);
141
+ const EMOJI = /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u;
142
+
143
+ const find = (pats, t) => pats.flatMap((p) => [...t.matchAll(new RegExp(p.source, p.flags.includes("g") ? p.flags : p.flags + "g"))].map((m) => m[0]));
144
+
145
+ // state-claim words and the state evidence that justifies each
146
+ const STATE_CLAIMS = [
147
+ [/\b(approved|accepted)\b/i, /approved|accepted|"decision":"(approved|accepted)"|"approvals":[1-9]/i, "approved or accepted"],
148
+ [/\bdelivered\b/i, /delivered_at":"|"(message_status|status|state|delivery)":"delivered"|"delivered":true/i, "delivered"],
149
+ [/\b(read|seen|opened)\b(?! (the|our|this))/i, /read_at":"|opened_at":"|"(read|seen|opened)":true/i, "read or opened"],
150
+ [/\b(charged|paid|deducted|taken from)\b/i, /"captured":true|"(payment|status|state)":"(charged|paid|captured)"|"charged":true|"paid":true/i, "charged or paid"],
151
+ [/\b(live|published)\b/i, /"page_live":true|"published":true|"(status|state|post|page)":"(live|published)"/i, "live or published"],
152
+ [/\b(verified|checked)\b/i, /"verified":true|"(status|state)":"verified"/i, "verified"],
153
+ [/\b(synced|backed up)\b/i, /"synced":true|"(status|state)":"(synced|backed_up|complete)"/i, "synced or backed up"],
154
+ [/\b(completed?|done|finished)\b/i, /"(file_ready|ready|completed|done)":true|"(status|state|export|backup|job)":"(complete|completed|ready|done|finished)"/i, "complete or ready"],
155
+ [/\b(confirmed|booked|reserved)\b/i, /"confirmed[a-z_]*":true|"(status|state)":"(confirmed|booked|reserved)"|carrier_confirmed":true/i, "confirmed or booked"],
156
+ [/\b(arrived|joined|refunded|returned|settled)\b/i, /"(arrived|joined|refunded|settled|received|accepted|member|money_returned)":true|"(status|state|transfer|payout|order|refund)":"(arrived|joined|refunded|settled|received|delivered|returned)"|"delivered":true|bank_credit":"/i, "arrived, joined, refunded or settled"],
157
+ ];
158
+ const NEG_BEFORE = /(not|n't|never|no|yet|until|before|once|when|after|if|unless|soon|we'll|we will|will be|can't|gets?|may|might|could|whether)\W*(\w+\W+){0,6}$/i;
159
+ const CASUAL = /\b(yay|hooray|awesome|oops|whoops|uh[- ]oh|great news|woohoo|nice one|hang tight|good news)\b/i;
160
+ const ONE_WORD_OK = new Set(["cancel", "close", "back", "next", "done", "skip", "retry", "dismiss", "later", "ok", "okay"]);
161
+
162
+ export function lintCopy({ units, pattern, state, stakes, expected_pieces, original }) {
163
+ const out = [];
164
+ const add = (unit, severity, rule, detail) => out.push({ unit, severity, rule, detail });
165
+ const texts = units.map((u) => u.text || "");
166
+ units.forEach((u, i) => {
167
+ const el = u.element || "", t = u.text || "";
168
+ const low = t.trim().toLowerCase().replace(/[.!]+$/, "");
169
+ const words = t.split(/\s+/).filter(Boolean).length;
170
+ for (const m of find(LEAK, t)) add(i, "block", "template-leak", `'${m}' looks like an unfilled variable`);
171
+ for (const m of t.match(/\{[^}]*\}/g) || []) add(i, "note", "variable", `'${m}': check it reads well for every value, including empty, 1 and long ones`);
172
+ for (const m of find(CODE, t)) add(i, "block", "raw-code", `'${m}' is a system code; say what happened and the fix`);
173
+ for (const m of find(FILLER, t)) add(i, "warn", "filler", `cut '${m}'`);
174
+ for (const [re, id, msg] of VAGUE) for (const m of t.match(re) || []) add(i, "note", id, `'${m}': ${msg}`);
175
+ if ((el === "primary-cta" || el === "secondary-cta") && GENERIC_CTA.has(low)) add(i, "warn", "generic-button", `'${t}' doesn't say what happens; use verb + object`);
176
+ if (el === "headline" && ["success", "error", "warning", "oops", "uh oh"].includes(low)) add(i, "warn", "empty-headline", `'${t}' names a state, not what happened`);
177
+ if (el === "inline-error" || el === "toast" || pattern === "error") {
178
+ for (const m of find(BLAME, t)) add(i, "warn", "blame-or-verdict", `'${m}' judges; give the fix instead`);
179
+ if (t.includes("!")) add(i, "warn", "exclaiming-at-failure", "no exclamation marks on errors");
180
+ }
181
+ for (const m of find(ABSOLUTES, t)) add(i, "note", "absolute", `'${m}': only promise what is always true`);
182
+ if (/\b0 (items|results|\w+s)\b/i.test(t) && (pattern === "empty-state" || pattern === "search-no-results")) add(i, "warn", "literal-zero", "don't show a count of zero; say what will appear and how");
183
+ if (["primary-cta", "secondary-cta", "tertiary-link"].includes(el) && ["LOGIN", "Login"].includes(t.trim())) add(i, "note", "login-noun", "the verb is 'Log in'");
184
+ const alpha = t.replace(/[^A-Za-z ]/g, "").split(/\s+/).filter(Boolean);
185
+ if (alpha.length >= 2 && t === t.toUpperCase()) add(i, "note", "all-caps", "sentence case reads faster; 95% of exemplars use it");
186
+ else if (["headline", "primary-cta", "secondary-cta", "title-bar"].includes(el) && alpha.length >= 3 &&
187
+ alpha.slice(1).filter((w) => w[0] === w[0].toUpperCase()).length >= Math.max(2, alpha.length - 2)) add(i, "note", "title-case", "use sentence case");
188
+ if (LIMITS[el] && words > LIMITS[el]) add(i, "note", "long", `${words} words; exemplar ${el}s rarely pass ${LIMITS[el]}`);
189
+ if (SENTENCE_ELEMENTS.has(el) && words > 6 && !/[.?!:)"']$/.test(t.trim())) add(i, "note", "punctuation", "full-sentence copy ends with a full stop");
190
+ if (HIGH_STAKES.has(pattern) && EMOJI.test(t)) add(i, "warn", "emoji-at-stakes", "no emoji where money, data or access is at stake");
191
+ });
192
+ // state overclaim: a claim word with no supporting evidence in the tool state
193
+ if (state && Object.keys(state).length) {
194
+ const sj = JSON.stringify(state).replace(/\s/g, "");
195
+ units.forEach((u, i) => {
196
+ const x = u.text || "";
197
+ for (const [re, support, label] of STATE_CLAIMS) {
198
+ const g = new RegExp(re.source, "gi"); let m;
199
+ while ((m = g.exec(x))) {
200
+ if (NEG_BEFORE.test(x.slice(Math.max(0, m.index - 30), m.index))) continue;
201
+ if (!support.test(sj) && !sj.toLowerCase().includes(m[0].toLowerCase())) add(i, "block", "state-overclaim", `'${m[0]}' claims ${label}, but the state you were given does not show it; say what the state supports`);
202
+ }
203
+ }
204
+ });
205
+ }
206
+ // structural tics measured against shipped copy: "No X yet" empty states, narrating where things will appear, two even sentences
207
+ units.forEach((u, i) => {
208
+ const x = (u.text || "").trim();
209
+ if (u.element === "headline" && /^no\b[^.!?]*\byet\b/i.test(x)) add(i, "warn", "no-x-yet", `'${x}' is the most common model empty-state headline (49% of model lines, 5.5% of shipped); lead with what the person gets or can do ("Add your first contact")`);
210
+ if (/\b(will|'ll)\s+(show up|appear|be listed|be shown|be displayed)\s+here\b|\blisted here\b|\byou('ll| will) see (it|them|\w+) here\b/i.test(x)) add(i, "warn", "narrating-location", "says where content will appear instead of what the person gets; say what it is and what to do");
211
+ if (u.element === "body") {
212
+ const sents = x.split(/(?<=[.!?])\s+/).filter((t) => t.split(/\s+/).length > 1);
213
+ if (sents.length === 2 && Math.abs(sents[0].split(/\s+/).length - sents[1].split(/\s+/).length) <= 2) add(i, "note", "even-sentences", "two sentences of near-equal length read mechanical; give them different jobs and lengths, or use one");
214
+ }
215
+ });
216
+ // rewrite: short originals that already worked should stay unless there is a reason
217
+ if (Array.isArray(original)) original.forEach((o) => {
218
+ const ow = (o.text || "").trim();
219
+ if (!ow || ow.split(/\s+/).length > 3) return;
220
+ const same = units.find((u) => u.element === o.element && (u.text || "").trim() === ow);
221
+ if (!same && units.some((u) => u.element === o.element)) add(null, "note", "changed-short-original", `the original ${o.element} '${ow}' was short; keep it unless it is wrong for the state, unclear or misses a fact`);
222
+ });
223
+ // tics: describing the screen, inventing a cause, hinting at an outcome the facts do not give
224
+ units.forEach((u, i) => {
225
+ const x = u.text || "";
226
+ if (/\b(shown|displayed|appears?|visible)\s+(before|when|after|while|until)\b/i.test(x) || /\bthis (screen|page|message|notice|popup)\b/i.test(x))
227
+ add(i, "warn", "screen-meta", "the copy describes the screen instead of the situation; say what is happening to the person");
228
+ if (state && Object.keys(state).length) {
229
+ const sj2 = JSON.stringify(state).toLowerCase();
230
+ for (const m of x.matchAll(/\b(because|due to|as a result of)\s+([a-z' ]{3,40})/gi)) {
231
+ const words = m[2].toLowerCase().split(/\s+/).filter((w) => w.length > 3);
232
+ if (words.length && !words.some((w) => sj2.includes(w))) add(i, "warn", "invented-cause", `'${m[0].trim()}': the state you were given does not give this reason; drop it or say only what is known`);
233
+ }
234
+ if (/\b(received|submitted|got) your (application|request|submission|claim|order)\b/i.test(x) && !/(offer|approv|accept|eligible)/i.test(sj2) === false)
235
+ add(i, "note", "outcome-hint", "make sure 'received' does not suggest a result the facts do not show");
236
+ }
237
+ });
238
+ // tone fence at high stakes
239
+ if (stakes === "high") units.forEach((u, i) => {
240
+ if ((u.text || "").includes("!")) add(i, "warn", "tone-fence", "no exclamation marks when the stakes are high");
241
+ if (CASUAL.test(u.text || "")) add(i, "warn", "tone-fence", `'${(u.text.match(CASUAL) || [""])[0]}' is too light for high stakes`);
242
+ });
243
+ // plural and variable handling
244
+ units.forEach((u, i) => {
245
+ const x = u.text || "";
246
+ for (const m of x.match(/\b\w+\(s\)/g) || []) add(i, "warn", "plural", `'${m}': write the singular and plural forms (plural rule) instead of (s)`);
247
+ for (const m of x.match(/\{(count|n|num|number|total|qty)\w*\}\s+[a-z]+/gi) || []) add(i, "warn", "plural", `'${m}': a count variable needs plural forms for 1 and other`);
248
+ for (const m of x.match(/\b1 [a-z]+s\b/gi) || []) add(i, "warn", "plural", `'${m}': singular needed for one`);
249
+ });
250
+ // action-label specificity: one word, no object
251
+ units.forEach((u, i) => {
252
+ if (!["primary-cta", "secondary-cta"].includes(u.element)) return;
253
+ const w = (u.text || "").trim().split(/\s+/).filter(Boolean);
254
+ if (w.length === 1 && !ONE_WORD_OK.has(w[0].toLowerCase().replace(/[.!]/g, ""))) add(i, "warn", "action-label", `'${u.text}' is a verb alone; name the thing it acts on`);
255
+ });
256
+ // missing pieces
257
+ if (Array.isArray(expected_pieces)) for (const e of expected_pieces) if (!units.some((u) => u.element === e)) add(null, "block", "missing-piece", `no '${e}' in the copy; the screen needs it`);
258
+ const heads = units.flatMap((u, i) => (u.element === "headline" ? [i] : []));
259
+ const bodies = units.flatMap((u, i) => (u.element === "body" ? [i] : []));
260
+ for (const h of heads) for (const b of bodies) {
261
+ const ht = tokens(texts[h]);
262
+ const ov = ht.size ? overlap(ht, tokens(texts[b])) / ht.size : 0;
263
+ if (ov >= 0.7) add(b, "warn", "body-repeats-headline", "the body should add why, what's lost, or what's next");
264
+ else if (ov >= 0.5) add(b, "note", "body-repeats-headline", "half the headline's words come back in the body; check it adds something");
265
+ }
266
+ const ctas = units.filter((u) => u.element === "primary-cta" || u.element === "secondary-cta");
267
+ for (const c of ctas) {
268
+ const ct = (c.text || "").trim().toLowerCase();
269
+ if (ct.split(/\s+/).length < 2) continue;
270
+ bodies.forEach((b) => { if ((texts[b] || "").toLowerCase().includes(ct)) add(b, "note", "body-repeats-button", `the body repeats '${c.text}'; the button already says it`); });
271
+ }
272
+ const labels = units.flatMap((u, i) => (["label", "field-label"].includes(u.element) ? [i] : []));
273
+ units.forEach((u, i) => {
274
+ if (!["helper-text", "tooltip", "placeholder"].includes(u.element)) return;
275
+ for (const l of labels) {
276
+ const lt = tokens(texts[l]); const ut = tokens(texts[i]);
277
+ if (lt.size && ut.size <= lt.size + 3 && overlap(lt, ut) / lt.size >= 0.8) add(i, "note", "helper-echoes-label", `'${u.text}' restates the label; give the format, limit or example instead`);
278
+ }
279
+ });
280
+ if (ctas.length === 2 && ctas.every((c) => /\bcancel\b/i.test(c.text))) add(null, "warn", "cancel-cancel", "both buttons say Cancel; name each outcome ('Keep plan' / 'Cancel plan')");
281
+ if (["error", "offline", "search-no-results"].includes(pattern) &&
282
+ !units.some((u) => ["primary-cta", "secondary-cta", "tertiary-link"].includes(u.element)) &&
283
+ !texts.some((x) => /\b(try|check|tap|go to|use|remove|clear)\b/i.test(x))) add(null, "warn", "no-way-forward", "nothing tells people what to do next");
284
+ units.forEach((u, i) => { for (const f of aiVoice(u.text, u.element)) add(i, f.severity, f.rule, f.detail); });
285
+ const order = { block: 0, warn: 1, note: 2 };
286
+ return out.sort((a, b) => order[a.severity] - order[b.severity]);
287
+ }
288
+
289
+ // --- reference-first ----------------------------------------------------
290
+ // find_reference: the single closest real line for one element in one situation, with its shape.
291
+ // compare_to_reference: deterministic shape check of a candidate against its reference (rubric check 4).
292
+
293
+ const PRONOUN_START = new Set(["you", "you're", "you'll", "you've", "your", "we", "we're", "we'll", "we've", "our", "i", "i'm", "my", "they", "their", "this", "that", "it", "it's", "there", "these"]);
294
+ const FRAME_START = new Set(["when", "before", "after", "if", "once", "while", "until", "in", "on", "at", "by", "for", "from", "with", "during", "every", "each", "a", "an", "the", "here", "to"]);
295
+ const NOT_VERBS = new Set(["no", "not", "all", "new", "more", "free", "only", "now", "today", "almost", "nothing", "something", "everything", "welcome", "thanks", "thank", "sorry", "hi", "hello", "oops", "success", "error"]);
296
+ const COMMON_VERBS = new Set(("get find save add try start create make keep see view open share invite join use set turn choose pick select upload download " +
297
+ "send check review edit delete remove cancel upgrade unlock explore browse discover search learn read write track manage connect allow enable " +
298
+ "continue sign log go take build plan book pay buy apply verify confirm update restore retry change finish complete stay leave let enter type tap " +
299
+ "click follow meet earn claim redeem show hide stop pause resume reset submit import export move copy sync back ask contact talk call watch listen").split(" "));
300
+
301
+ const words = (t) => (t || "").trim().split(/\s+/).filter(Boolean);
302
+ const sentences = (t) => ((t || "").trim().match(/[^.!?]+[.!?]*/g) || []).filter((s) => /[A-Za-z0-9]/.test(s)).length || 1;
303
+
304
+ export function shapeOf(text) {
305
+ const w = words(text);
306
+ const first = (w[0] || "").toLowerCase().replace(/[^a-z']/g, "");
307
+ let opening;
308
+ if (PRONOUN_START.has(first)) opening = "subject";
309
+ else if (/^\d/.test(w[0] || "")) opening = "number";
310
+ else if (FRAME_START.has(first)) opening = "frame";
311
+ else if (COMMON_VERBS.has(first) || (!NOT_VERBS.has(first) && /^[A-Z][a-z]+$/.test(w[0] || "") && !first.endsWith("s") && !first.endsWith("ing") && w.length > 1 && /^(a|an|the|your|you|my|our|it|them|more|new|all|\w+)$/i.test(w[1] || "") && COMMON_VERBS.has(first))) opening = "verb";
312
+ else if (first.endsWith("ing")) opening = "verb-ing";
313
+ else opening = "noun";
314
+ const label = { subject: `Subject first ('${w[0]} …')`, verb: `Verb first ('${w[0]} …')`, "verb-ing": `-ing verb first ('${w[0]} …')`,
315
+ number: `Number first ('${w[0]} …')`, frame: `Frame first ('${w.slice(0, 2).join(" ")} …'): time, place, condition or article`, noun: `Noun first ('${w[0]} …')` }[opening];
316
+ const n = w.length;
317
+ return {
318
+ opening, first_word: w[0] || "", sentences: sentences(text), words: n,
319
+ length_range: [Math.max(1, Math.floor(n * 0.7)), Math.ceil(n * 1.3)],
320
+ summary: `${label} · ${sentences(text)} sentence${sentences(text) > 1 ? "s" : ""} · ${n} words (stay within ${Math.max(1, Math.floor(n * 0.7))} to ${Math.ceil(n * 1.3)})`,
321
+ question: /\?\s*$/.test((text || "").trim()),
322
+ };
323
+ }
324
+
325
+ // Ratings only break ties: a line that fits the moment must beat a prettier line that does not.
326
+ const SUPPORT = new Set(["helper-text", "body", "subtitle", "description"]);
327
+ const stem = (w) => w.replace(/(ing|ed|es|s)$/, "").slice(0, 6);
328
+ const stems = (set) => new Set([...set].map(stem));
329
+ let momentIdf = null;
330
+ function idfOf() {
331
+ if (momentIdf) return momentIdf;
332
+ const df = new Map(); let n = 0;
333
+ for (const s of screens) for (const u of s.copy) if (u.m) { n++; for (const w of stems(tokens(u.m))) df.set(w, (df.get(w) || 0) + 1); }
334
+ momentIdf = (w) => Math.log((n + 1) / ((df.get(w) || 0) + 1));
335
+ return momentIdf;
336
+ }
337
+ const weighted = (a, b, idf) => { let t = 0; for (const w of a) if (b.has(w)) t += idf(w); return t; };
338
+
339
+ const RATING_W = { gold: 1.5, strong: 1, solid: 0.5, weak: -5 };
340
+
341
+ export function findReference({ element, situation, pattern, draft, platform, limit = 3, exclude_products }) {
342
+ load();
343
+ const fromEnv = (process.env.UXW_EXCLUDE_PRODUCTS || "").split(",").filter(Boolean);
344
+ const exclude = new Set([...(exclude_products || []), ...fromEnv].map((p) => p.trim().toLowerCase()));
345
+ const q = tokens(situation);
346
+ const idf = idfOf();
347
+ const qs = stems(q);
348
+ const dq = tokens(draft);
349
+ const dn = draft ? words(draft).length : 0;
350
+ const ranked = [];
351
+ for (const s of screens) {
352
+ if (exclude.has(s.product.toLowerCase())) continue;
353
+ if (platform && s.platform !== platform) continue;
354
+ const ctx = new Set();
355
+ for (const u of s.copy) for (const w of tokens(u.t + " " + (u.n || ""))) ctx.add(w);
356
+ const ctxHit = overlap(q, ctx);
357
+ for (const u of s.copy) {
358
+ const fam = SUPPORT.has(element) && SUPPORT.has(u.e);
359
+ if ((u.e !== element && !fam) || u.r === "weak") continue;
360
+ const own = tokens(u.t + " " + (u.n || ""));
361
+ const mom = tokens(u.m || "");
362
+ const momHit = weighted(qs, stems(mom), idf);
363
+ let score = (u.e === element ? 0 : -2) + (RATING_W[u.r] || 0) + 3 * momHit + 2 * overlap(q, own) + 0.5 * ctxHit + (pattern && s.p === pattern ? 2 : 0);
364
+ if (draft) {
365
+ score += 1.5 * overlap(dq, tokens(u.t));
366
+ const n = words(u.t).length;
367
+ if (n >= dn * 0.5 && n <= dn * 2) score += 1;
368
+ }
369
+ if (q.size && overlap(q, own) + ctxHit + momHit === 0) score -= 4;
370
+ ranked.push([score, s, u]);
371
+ }
372
+ }
373
+ ranked.sort((a, b) => b[0] - a[0]);
374
+ const seen = new Set();
375
+ const out = [];
376
+ for (const [score, s, u] of ranked) {
377
+ const key = u.t.toLowerCase();
378
+ if (seen.has(key)) continue;
379
+ seen.add(key);
380
+ const head = s.copy.find((x) => x.e === "headline");
381
+ out.push({
382
+ product: s.product, pattern: s.p, platform: s.platform, element: u.e, text: u.t, rating: u.r,
383
+ ...(u.n ? { note: u.n } : {}),
384
+ ...(u.m ? { moment: u.m, job: u.j } : {}),
385
+ ...(head && head.t !== u.t ? { headline_on_screen: head.t } : {}),
386
+ shape: shapeOf(u.t).summary, match_score: Math.round(score * 10) / 10,
387
+ });
388
+ if (out.length >= Math.min(limit, 8)) break;
389
+ }
390
+ return out;
391
+ }
392
+
393
+ export function compareToReference({ reference, candidate }) {
394
+ const r = shapeOf(reference), c = shapeOf(candidate);
395
+ const rt = tokens(reference), ct = tokens(candidate);
396
+ const shared = [...rt].filter((w) => ct.has(w));
397
+ const checks = {
398
+ same_opening_move: r.opening === c.opening,
399
+ same_sentence_count: r.sentences === c.sentences,
400
+ length_within_30_percent: c.words >= r.length_range[0] && c.words <= r.length_range[1],
401
+ same_ending: r.question === c.question,
402
+ };
403
+ const failed = Object.entries(checks).filter(([, v]) => !v).map(([k]) => k);
404
+ return {
405
+ verdict: failed.length ? "off-shape" : "on-shape",
406
+ checks, failed,
407
+ reference_shape: r.summary, candidate_shape: c.summary,
408
+ shared_words: shared,
409
+ hint: failed.length ? failed.map((f) => ({
410
+ same_opening_move: `The reference opens ${r.opening === "verb" ? "with a verb" : r.opening === "subject" ? "with a subject doing something" : `with a ${r.opening}`} ('${r.first_word}'); yours opens with '${c.first_word}'. Use the same opening move.`,
411
+ same_sentence_count: `The reference has ${r.sentences} sentence(s); yours has ${c.sentences}.`,
412
+ length_within_30_percent: `The reference is ${r.words} words; aim for ${r.length_range[0]} to ${r.length_range[1]}. Yours is ${c.words}.`,
413
+ same_ending: r.question ? "The reference asks a question; yours doesn't." : "The reference makes a statement; yours ends on a question.",
414
+ })[f]) : ["Matches the reference's shape. Now check the facts against the code."],
415
+ };
416
+ }