content-md 1.0.0 → 1.0.3

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/repo.js ADDED
@@ -0,0 +1,63 @@
1
+ // The repo's own say over content-md: its copy rules, glossary and voice guide (which win over ours),
2
+ // and an optional .content-md.json for words the linter should accept and paths audit_copy should skip.
3
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
4
+ import { join, relative } from "node:path";
5
+
6
+ const START = "<!-- content-md:start -->", END = "<!-- content-md:end -->";
7
+ const INSTR_FILES = ["AGENTS.md", "CLAUDE.md", ".github/copilot-instructions.md", ".windsurfrules", ".cursorrules"];
8
+ const GUIDE_NAME = /(^|[-_ .])(glossary|terminology|voice|tone|copy|content[-_ ]?(guide|style|design|rules)|style[-_ ]?guide|writing[-_ ]?(guide|style|rules)|microcopy|ux[-_ ]?writing|word[-_ ]?list)([-_ .]|$)/i;
9
+ const RULE_HEADING = /^#{1,4}\s+.*\b(copy|voice|tone|glossary|terminology|wording|microcopy|ux writing|writing style|content style|user-facing (text|strings|copy)|style guide)\b.*$/gim;
10
+ const DOC_DIRS = ["", "docs", "doc", "documentation", "guides", "design", "content", ".github", "brand"];
11
+
12
+ const read = (p) => { try { return readFileSync(p, "utf8"); } catch { return ""; } };
13
+ const stripOurs = (s) => s.replace(new RegExp(`${START}[\\s\\S]*?${END}`, "g"), "");
14
+
15
+ // Files and headings where the repo states its own copy rules. Our own marked block doesn't count.
16
+ export function findRepoRules(root) {
17
+ const found = [];
18
+ for (const f of INSTR_FILES) {
19
+ const s = stripOurs(read(join(root, f)));
20
+ const heads = [...s.matchAll(RULE_HEADING)].map((m) => m[0].replace(/^#+\s*/, "").trim()).filter((h) => !/content-md/i.test(h));
21
+ if (heads.length) found.push({ file: f, sections: heads.slice(0, 6) });
22
+ }
23
+ if (existsSync(join(root, ".cursor", "rules"))) {
24
+ for (const f of readdirSync(join(root, ".cursor", "rules"))) {
25
+ if (/^content-md/.test(f)) continue;
26
+ const s = read(join(root, ".cursor", "rules", f));
27
+ if (GUIDE_NAME.test(f) || RULE_HEADING.test(s)) found.push({ file: `.cursor/rules/${f}` });
28
+ RULE_HEADING.lastIndex = 0;
29
+ }
30
+ }
31
+ for (const d of DOC_DIRS) {
32
+ const dir = join(root, d);
33
+ let names = [];
34
+ try { if (statSync(dir).isDirectory()) names = readdirSync(dir); } catch { continue; }
35
+ for (const n of names) {
36
+ if (!/\.(md|mdx|txt|json|ya?ml)$/i.test(n) || /^(readme|changelog|license|contributing|code_of_conduct|security)\b/i.test(n)) continue;
37
+ if (GUIDE_NAME.test(n.replace(/\.[a-z]+$/i, ""))) found.push({ file: relative(root, join(dir, n)) });
38
+ }
39
+ }
40
+ const seen = new Set();
41
+ return found.filter((f) => (seen.has(f.file) ? false : seen.add(f.file)));
42
+ }
43
+
44
+ // .content-md.json: { "allow": ["Inbox", "Continue"], "ignore": ["src/legacy/"], "industry": "media-entertainment" }
45
+ export function readConfig(root) {
46
+ const p = join(root, ".content-md.json");
47
+ if (!existsSync(p)) return { allow: [], ignore: [] };
48
+ try {
49
+ const j = JSON.parse(read(p));
50
+ return { allow: Array.isArray(j.allow) ? j.allow.map(String) : [], ignore: Array.isArray(j.ignore) ? j.ignore.map(String) : [], industry: typeof j.industry === "string" ? j.industry : undefined };
51
+ } catch { return { allow: [], ignore: [], error: ".content-md.json isn't valid JSON; ignored it." }; }
52
+ }
53
+
54
+ // A word or line the repo accepts: exact line match, or a whole-word match for single terms.
55
+ export function allowMatcher(allow = []) {
56
+ const lines = new Set(allow.map((a) => a.trim().toLowerCase()));
57
+ const words = allow.filter((a) => !/\s/.test(a.trim())).map((a) => a.trim().toLowerCase());
58
+ return {
59
+ line: (t) => lines.has(String(t).trim().toLowerCase().replace(/[.!?]$/, "")),
60
+ word: (w) => words.includes(String(w).toLowerCase()),
61
+ any: allow.length > 0,
62
+ };
63
+ }
package/src/server.js CHANGED
@@ -4,16 +4,18 @@ import { readFileSync } from "node:fs";
4
4
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
6
  import { z } from "zod";
7
- import { findReferenceV2Async, decideTone, HAS_ENRICHED } from "./reference2.js";
7
+ import { findReferenceV2Async, decideTone, HAS_ENRICHED, INDUSTRIES } from "./reference2.js";
8
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";
9
+ import { saveProductBrief, askPerson, readSavedBrief } from "./context.js";
10
+ import { readConfig } from "./repo.js";
11
+ import { normElement, META, PATTERNS, ELEMENTS, HAS_EXAMPLES, findExamples, findRules, getGuide, lintCopy, findReference, compareToReference } from "./tools.js";
11
12
 
12
13
  const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
13
14
 
14
15
  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.
16
+ The repo's own copy rules, glossary and voice guide come first: where they differ from this guidance, follow them, and reuse the product's own words. read_product lists the files where the repo states its rules.
15
17
  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.
18
+ 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 (it writes .content-md/product.md, not your instruction files) 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
19
  1. Call get_guide with the pattern once per task and follow it.
18
20
  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
21
  3. State-check before you write: name the screen state and what the product actually knows. Do not claim more than that.
@@ -22,15 +24,26 @@ Write from the rules, the tone decision and the pattern playbook. Shipped copy i
22
24
  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
25
  Lead with paste-ready copy. If you quote a shipped line, quote it exactly as a tool returned it.`;
24
26
  const INSTRUCTIONS = HAS_EXAMPLES ? INSTRUCTIONS_FULL : `Use these tools whenever you write or review interface copy, including strings in code.
27
+ The repo's own copy rules, glossary and voice guide come first: where they differ from this guidance, follow them.
25
28
  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
29
  1. Call get_guide with the pattern once per task and follow it.
27
30
  2. If the moment has stakes or feeling, call decide_tone first.
28
31
  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
32
  Lead with paste-ready copy, recommend one option, and cite the rule behind it.`;
30
33
 
34
+ // the repo's industry, from .content-md.json or the saved product brief, so references stay on-domain by default
35
+ function repoIndustry(root = process.cwd()) {
36
+ const c = readConfig(root).industry || readSavedBrief(root)?.fields?.industry;
37
+ return c && INDUSTRIES.includes(c) ? c : undefined;
38
+ }
31
39
  const json = (data) => ({ content: [{ type: "text", text: JSON.stringify(data, null, 1) }] });
32
40
  const pattern = z.enum(PATTERNS);
33
- const element = z.enum(ELEMENTS);
41
+ // accepts the common words agents guess ("button", "title", "link") and maps them to the element names
42
+ const element = z.string().transform((e, ctx) => {
43
+ const n = normElement(e);
44
+ if (!ELEMENTS.includes(n)) { ctx.addIssue({ code: "custom", message: `Unknown element '${e}'. Use one of: ${ELEMENTS.join(", ")} (button, title, link, error and similar are accepted too).` }); return z.NEVER; }
45
+ return n;
46
+ }).describe(`One of ${ELEMENTS.join(", ")}. Common words like button, title, heading, link, error and description are accepted.`);
34
47
 
35
48
  export async function serve() {
36
49
  const server = new McpServer({ name: "content-md", version: pkg.version }, { instructions: INSTRUCTIONS });
@@ -38,9 +51,12 @@ export async function serve() {
38
51
  server.registerTool("get_guide", {
39
52
  title: "UX writing guide",
40
53
  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.") },
54
+ inputSchema: {
55
+ pattern: pattern.optional().describe("The UI situation. Omit to get the universal rules and the list of patterns."),
56
+ full: z.boolean().optional().describe("Also return every topic in the pattern index (about 18,000 more characters). Rarely needed."),
57
+ },
42
58
  annotations: { readOnlyHint: true },
43
- }, async ({ pattern }) => ({ content: [{ type: "text", text: getGuide({ pattern }) }] }));
59
+ }, async ({ pattern, full }) => ({ content: [{ type: "text", text: getGuide({ pattern, full }) }] }));
44
60
 
45
61
  if (HAS_EXAMPLES) server.registerTool("find_examples", {
46
62
  title: "Find shipped examples",
@@ -52,9 +68,15 @@ export async function serve() {
52
68
  platform: z.enum(["ios", "web"]).optional(),
53
69
  quality: z.enum(["best", "weak"]).optional(),
54
70
  limit: z.number().int().min(1).max(10).optional(),
71
+ industry: z.enum(INDUSTRIES).optional().describe("Only screens from this industry. Defaults to the repo's saved brief or .content-md.json; if that leaves nothing, all industries are searched and each result says its industry."),
55
72
  },
56
73
  annotations: { readOnlyHint: true },
57
- }, async (args) => json(findExamples(args)));
74
+ }, async (args) => {
75
+ const industry = args.industry || repoIndustry();
76
+ let res = industry ? findExamples({ ...args, industry }) : [];
77
+ if (!res.length) res = findExamples({ ...args, industry: undefined });
78
+ return json(res);
79
+ });
58
80
 
59
81
  if (HAS_EXAMPLES) server.registerTool("find_reference", {
60
82
  title: "Find the closest reference",
@@ -71,9 +93,13 @@ export async function serve() {
71
93
  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
94
  tone: z.array(z.string()).optional().describe("Wanted tone words; omit to let the tone decider choose from the brief"),
73
95
  target_words: z.number().int().optional(),
96
+ industry: z.enum(INDUSTRIES).optional().describe("The product's industry, as read_product returns it. Keeps references to comparable products and drops lines about another industry's world (a booking, a workout). Defaults to the repo's saved brief or .content-md.json."),
74
97
  },
75
98
  annotations: { readOnlyHint: true },
76
- }, async (args) => json(HAS_ENRICHED && (args.brief || args.tone || args.role) ? await findReferenceV2Async(args) : findReference(args)));
99
+ }, async (args) => {
100
+ const industry = args.industry || repoIndustry();
101
+ return json(HAS_ENRICHED ? await findReferenceV2Async({ ...args, element: normElement(args.element), industry }) : findReference(args));
102
+ });
77
103
 
78
104
  if (HAS_ENRICHED) server.registerTool("decide_tone", {
79
105
  title: "Decide the tone for a moment",
@@ -92,7 +118,7 @@ export async function serve() {
92
118
  voice: z.string().optional().describe("The product's voice key, e.g. plain, playful, formal; omit for plain"),
93
119
  },
94
120
  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 }); });
121
+ }, async (args) => { const d = decideTone(args); if (d.error) return json(d); 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
122
 
97
123
  server.registerTool("compare_to_reference", {
98
124
  title: "Compare a line to its reference",
@@ -126,10 +152,11 @@ export async function serve() {
126
152
  stakes: z.enum(["low", "medium", "high"]).optional().describe("From decide_tone. At high, exclamation marks and light words are flagged."),
127
153
  expected_pieces: z.array(element).optional().describe("The pieces the screen needs; any missing one is blocked."),
128
154
  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."),
155
+ allow: z.array(z.string()).optional().describe("Words or whole lines the repo's own rules or glossary accept (e.g. 'Continue', 'Inbox'); they are never flagged. Entries in the repo's .content-md.json are added automatically."),
129
156
  },
130
157
  annotations: { readOnlyHint: true },
131
158
  }, async (args) => {
132
- const findings = lintCopy(args);
159
+ const findings = lintCopy({ ...args, allow: [...(args.allow || []), ...readConfig(process.cwd()).allow] });
133
160
  const pass = !findings.some((f) => f.severity === "block" || f.severity === "warn");
134
161
  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
162
  });
@@ -146,10 +173,10 @@ export async function serve() {
146
173
 
147
174
  server.registerTool("save_product_brief", {
148
175
  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.",
176
+ description: "Save the product brief (and any answers the person gave) to .content-md/product.md, its own file, so later sessions start from it instead of asking again. It never edits AGENTS.md or CLAUDE.md unless you pass file. Tell the person where you saved it.",
150
177
  inputSchema: {
151
178
  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"),
179
+ file: z.string().optional().describe("Relative path to write to; defaults to wherever the brief already is, else .content-md/product.md. Only pass AGENTS.md or CLAUDE.md if the person asks."),
153
180
  fields: z.object({
154
181
  product: z.string(), audience: z.string(), industry: z.string().optional(), job: z.string().optional(), voice: z.string(),
155
182
  terms: z.string().optional(), stakes: z.string().optional(), constraints: z.string().optional(),
@@ -162,7 +189,7 @@ export async function serve() {
162
189
  title: "Ask the person",
163
190
  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
191
  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),
192
+ questions: z.array(z.object({ question: z.string(), slot: z.string().optional().describe("The read_product slot this answers; defaults to q1, q2"), options: z.array(z.string()).optional(), default: z.string().optional(), why: z.string().optional() })).min(1).max(2),
166
193
  },
167
194
  }, async ({ questions }) => json(await askPerson(server, questions)));
168
195
 
@@ -196,7 +223,7 @@ export async function serve() {
196
223
 
197
224
  server.registerResource("guide", "content-md://guide", {
198
225
  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({}) }] }));
226
+ }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/markdown", text: getGuide({ full: true }) }] }));
200
227
 
201
228
  await server.connect(new StdioServerTransport());
202
229
  }
package/src/tools.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { allowMatcher } from "./repo.js";
1
2
  import { aiVoice } from "./aivoice.js";
2
3
  // The four tools behind the MCP server. Pure functions over the bundled data.
3
4
  import { existsSync, readFileSync } from "node:fs";
@@ -49,7 +50,10 @@ export function findExamples({ pattern, element, query, platform, industry, qual
49
50
  const base = quality === "weak" ? 10 : Math.max(...hits.map(score));
50
51
  const words = new Set();
51
52
  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
+ // with a query, the match on the situation decides the order and quality breaks ties; no word in common, no result
54
+ const ov = overlap(q, words);
55
+ if (q.size && !ov) continue;
56
+ ranked.push([q.size ? 10 * ov / q.size + base / 6 : base, s]);
53
57
  }
54
58
  ranked.sort((a, b) => b[0] - a[0]);
55
59
  return ranked.slice(0, Math.min(limit, 10)).map(([, s]) => ({
@@ -102,15 +106,35 @@ function section(md, level, startsWith) {
102
106
  return lines.slice(i, j).join("\n").trim();
103
107
  }
104
108
 
105
- export function getGuide({ pattern }) {
109
+ // which pattern-index topics fit a pattern; buttons always come along
110
+ const INDEX_TOPICS = [
111
+ [/error|offline|valid|fail|declin|wrong/, "Validation, errors"], [/empty|search|filter|no-results/, "Search, filters"],
112
+ [/loading|progress|status|update|maintenance|sync|upload/, "Loading, background"], [/delete|confirm|destructive|dialog|cancel|remove/, "Confirmation, review"],
113
+ [/onboard|permission|sign|login|log-in|account|welcome|verif|kyc|password/, "Onboarding, permissions"], [/checkout|pay|billing|subscri|paywall|pric|refund|invoice|plan|trial/, "Checkout, billing"],
114
+ [/privacy|consent|shar|cookie|trust/, "Privacy, consent"], [/notif|push|email|toast|alert|reminder/, "Notifications, alerts"],
115
+ [/\bai\b|ai-|chat|assistant|agent|generat/, "AI assistants"], [/form|field|input|setting|profile/, "Forms and questions"],
116
+ ];
117
+ function indexFor(pattern) {
118
+ if (!patternIndex) return "";
119
+ const key = `${pattern} ${PLAYBOOK[pattern] || ""}`.toLowerCase();
120
+ const topics = ["Buttons, links", ...INDEX_TOPICS.filter(([re]) => re.test(key)).map(([, t]) => t)].slice(0, 3);
121
+ const head = patternIndex.split(/\n### /)[0].trim();
122
+ return [head, ...topics.map((t) => section(patternIndex, 3, t)).filter(Boolean)].join("\n\n");
123
+ }
124
+
125
+ export function getGuide({ pattern, full = false }) {
106
126
  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());
127
+ const parts = [voice.trim(), section(skill, 2, "Universal rules")];
128
+ if (pattern) {
129
+ parts.push("## Playbook for this pattern\n\n" + section(skill, 3, PLAYBOOK[pattern]));
130
+ parts.push(rubric.trim());
131
+ parts.push(full ? patternIndex.trim() : indexFor(pattern));
132
+ } else {
133
+ for (const h of ["What screenshots can't show", "Defaults where sources disagree"]) parts.push(section(skill, 2, h));
134
+ parts.push(full ? section(skill, 2, "Pattern playbooks") : `## Patterns\n\nCall get_guide again with one of these for its playbook: ${PATTERNS.join(", ")}.`);
135
+ parts.push(rubric.trim());
136
+ parts.push(section(skill, 2, "Review checklist"));
137
+ }
114
138
  return parts.filter(Boolean).join("\n\n");
115
139
  }
116
140
 
@@ -118,7 +142,9 @@ export function getGuide({ pattern }) {
118
142
 
119
143
  const FILLER = [/\bsuccessfully\b/gi, /\bsimply\b/gi, /\bplease note\b/gi, /\bit looks like\b/gi,
120
144
  /\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];
145
+ /\bin order to\b/gi, /\bkindly\b/gi, /\beasily\b/gi, /\bseamless(ly)?\b/gi, /\buh[- ]?oh\b/gi, /\byikes\b/gi, /\bwhoopsie\b/gi];
146
+ // misspellings that turn up in shipped strings; a typo was the most common reason labelers scored a line 1
147
+ const TYPOS = { occured: "occurred", occuring: "occurring", occurence: "occurrence", recieve: "receive", recieved: "received", recieving: "receiving", seperate: "separate", seperately: "separately", untill: "until", sucess: "success", sucessful: "successful", succesful: "successful", sucessfully: "successfully", succesfully: "successfully", adress: "address", accomodate: "accommodate", definately: "definitely", wich: "which", thier: "their", existant: "existent", independant: "independent", refered: "referred", begining: "beginning", commited: "committed", transfered: "transferred", alot: "a lot", teh: "the", recomend: "recommend", reccomend: "recommend", neccessary: "necessary", necesary: "necessary", priviledge: "privilege", acheive: "achieve", wierd: "weird", tommorow: "tomorrow", tomorow: "tomorrow", calender: "calendar", embarass: "embarrass", guarentee: "guarantee", maintainance: "maintenance", noticable: "noticeable", publically: "publicly", occassion: "occasion", supercede: "supersede", accross: "across", agressive: "aggressive", arguement: "argument", beleive: "believe", buisness: "business", collegue: "colleague", concious: "conscious", enviroment: "environment", foward: "forward", goverment: "government", happend: "happened", immediatly: "immediately", knowlege: "knowledge", lenght: "length", paymnet: "payment", passowrd: "password", pasword: "password", acount: "account", accout: "account", verfiy: "verify", verifcation: "verification", notifcation: "notification", subcription: "subscription", subscribtion: "subscription", availible: "available", avaliable: "available", sumbit: "submit", submision: "submission", submited: "submitted" };
122
148
  const VAGUE = [
123
149
  [/\bjust\b/gi, "just", "cut 'just' if it only softens; keep it when it means 'only' or 'a moment ago'"],
124
150
  [/\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"],
@@ -130,11 +156,19 @@ const VAGUE = [
130
156
  [/\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
157
  [/\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
158
  ];
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];
159
+ const GENERIC_CTA = new Set(["ok", "okay", "yes", "no", "click here", "proceed", "go"]);
160
+ // standard labels people expect; only a note, because a repo's own glossary may ask for them
161
+ const STANDARD_CTA = new Set(["submit", "continue", "next", "confirm"]);
162
+ const BLAME = [/\binvalid\b/gi, /\billegal\b/gi, /\byou (forgot|didn't|did not|failed)\b/gi];
163
+ // a verdict is fine when the same line gives the fix ("Something went wrong. Try again.")
164
+ const VERDICT = [/\bfailed to\b/gi, /\b(went|gone) wrong\b/gi, /\ban? (unexpected |unknown )?error (has )?occurred\b/gi];
165
+ const hasFix = (t) => t.split(/(?<=[.!?:;])\s+|,\s+(?=(?:please\s+)?[a-z]+\b)/i).some((z) => FIX_VERB.test(z.replace(/^\s*(please|then|or|and|so)\s+/i, "").split(/\s+/).slice(0, 2).join(" "))) || /\b(try again|contact (us|support)|reach out|get in touch|check (your|the|that)|make sure|you can (try|retry|still)|later|for (support|help))\b/i.test(t);
166
+ const FIX_VERB = /^(try|visit|see|read|follow|check|tap|click|go to|use|remove|clear|contact|email|reach|ask|write to|sign in|log in|reload|refresh|wait|choose|pick|select|update|reconnect|enter|add|make sure|restart|open|turn on|allow)\b/i;
167
+ const ABSOLUTES = [/\bnever\b/gi, /\balways\b/gi, /\bguarantee[ds]?\b/gi, /\b100% (secure|safe|private|accurate|guaranteed|reliable|free|uptime|satisf\w*)/gi];
168
+ const LEAK = [/\bNaN\b/g, /\[object/gi, /%[sd]\b/g];
169
+ // "null"/"undefined" leak only where a value was meant to be: not after words that make it prose ("returns null", "is undefined")
170
+ const LEAK_WORD = /(?<!\b(?:is|be|are|was|were|returns?|or|to|as|of|when|if|set|and|not|a|the|means?)\s)\b(null|undefined)\b/gi;
171
+ const CODE = [/\b(error|err)[ _-]?\d{2,}\b/gi, /\b[A-Z]{2,}_[A-Z_]{2,}\b/g, /\b0x[0-9a-f]+\b/gi, /\b[A-Z]\w+Exception\b/g];
138
172
  const SENTENCE_ELEMENTS = new Set(["body", "helper-text", "inline-error", "legal-fineprint"]);
139
173
  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
174
  const HIGH_STAKES = new Set(["error", "checkout", "settings-destructive", "confirmation-dialog", "offline", "paywall-upsell"]);
@@ -155,11 +189,20 @@ const STATE_CLAIMS = [
155
189
  [/\b(confirmed|booked|reserved)\b/i, /"confirmed[a-z_]*":true|"(status|state)":"(confirmed|booked|reserved)"|carrier_confirmed":true/i, "confirmed or booked"],
156
190
  [/\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
191
  ];
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;
192
+ const NEG_BEFORE = /(not|n't|never|no|yet|until|before|once|when|after|if|unless|soon|will|'ll|won't|going to|should|would|expect\w*|can't|gets?|may|might|could|whether|to be|to get)\W*(\w+\W+){0,6}$/i;
159
193
  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"]);
194
+ // verbs that usually need an object on a button; a lone noun or a brand name ("Akahu", "Billing") isn't flagged
195
+ const ACTION_VERBS = new Set("add create make new import export connect link unlink disconnect invite join leave open view show hide manage change set reset update upgrade downgrade renew restore archive unarchive move rename duplicate merge split assign transfer pay buy order book schedule reschedule cancel approve reject decline accept request claim redeem enable disable activate deactivate install uninstall sync refresh run start stop pause resume send resend submit post reply forward print sign register subscribe unsubscribe follow unfollow block unblock report mute unmute pin unpin lock unlock verify test try configure customize select choose pick generate convert attach detach review preview".split(" "));
196
+ const ONE_WORD_OK = new Set(["add", "open", "view", "create", "new", "export", "import", "invite", "join", "follow", "pay", "buy", "reply", "post", "print", "sign in", "log in", "accept", "decline", "approve", "reject", "connect", "install", "update", "upgrade", "refresh", "reset", "archive", "restore", "pause", "resume", "start", "stop", "play", "filter", "sort", "select", "preview", "review", "cancel", "close", "back", "next", "done", "skip", "retry", "dismiss", "later", "ok", "okay", "continue", "submit", "confirm", "accept", "agree", "start", "finish", "verify", "resend", "save", "send", "edit", "delete", "remove", "share", "copy", "undo", "search", "apply", "publish", "upload", "download", "inbox", "terms", "privacy", "settings", "help", "home", "more"]);
161
197
 
162
- export function lintCopy({ units, pattern, state, stakes, expected_pieces, original }) {
198
+ // typographic quotes and apostrophes ("won’t", “Save”) read the same as straight ones for every check
199
+ const norm = (t) => String(t ?? "").replace(/[\u2018\u2019\u02BC\u2032]/g, "'").replace(/[\u201C\u201D\u2033]/g, '"').replace(/\u2026/g, "...").replace(/\u00A0/g, " ");
200
+ const ELEMENT_ALIAS = { button: "primary-cta", cta: "primary-cta", "primary-button": "primary-cta", "secondary-button": "secondary-cta", link: "tertiary-link", title: "headline", heading: "headline", description: "body", text: "body", paragraph: "body", error: "inline-error", "error-message": "inline-error", snackbar: "toast", notification: "toast", hint: "helper-text", "helper": "helper-text", caption: "helper-text", input: "label", "field-label": "label", "nav-item": "tertiary-link", tab: "tertiary-link" };
201
+ export const normElement = (e) => ELEMENT_ALIAS[String(e || "").toLowerCase()] || e;
202
+
203
+ export function lintCopy({ units, pattern, state, stakes, expected_pieces, original, allow }) {
204
+ units = (units || []).map((u) => ({ ...u, element: normElement(u.element), text: norm(u.text) }));
205
+ if (Array.isArray(original)) original = original.map((o) => ({ ...o, element: normElement(o.element), text: norm(o.text) }));
163
206
  const out = [];
164
207
  const add = (unit, severity, rule, detail) => out.push({ unit, severity, rule, detail });
165
208
  const texts = units.map((u) => u.text || "");
@@ -167,22 +210,30 @@ export function lintCopy({ units, pattern, state, stakes, expected_pieces, origi
167
210
  const el = u.element || "", t = u.text || "";
168
211
  const low = t.trim().toLowerCase().replace(/[.!]+$/, "");
169
212
  const words = t.split(/\s+/).filter(Boolean).length;
213
+ if (!t.trim()) { add(i, "block", "empty-text", `the ${el || "piece"} has no text; write it, or drop the piece`); return; }
214
+ for (const w of t.toLowerCase().match(/[a-z]+/g) || []) if (TYPOS[w]) add(i, "warn", "typo", `'${w}' should be '${TYPOS[w]}'`);
170
215
  for (const m of find(LEAK, t)) add(i, "block", "template-leak", `'${m}' looks like an unfilled variable`);
216
+ if (/^are you sure\b/i.test(t.trim())) add(i, /[.?!]\s+\S/.test(t.trim()) ? "note" : "warn", "are-you-sure", "'Are you sure' asks for confidence, not a decision; name the action and what it costs ('Delete this draft? You can't undo this.')");
217
+ if (el === "headline" && /^(nothing (to see )?here|nothing (here )?yet|it's (quiet|empty) (in )?here|there (are|is) no\b[^.!?]*\b(here|yet|at the moment|right now|currently|to show|found|available)\b|you (don't|do not) have any\b|you haven't\b.*\byet\b|no \w+( \w+)? (found|available|at the moment|right now|currently|to show))/i.test(t.trim())) add(i, "warn", "absence-headline", `'${t.trim()}' leads with what's missing; lead with what the person gets or can do ("Add your first contact")`);
218
+ if (el !== "helper-text" && el !== "legal-fineprint") for (const m of t.match(LEAK_WORD) || []) add(i, "block", "template-leak", `'${m}' looks like an unfilled variable`);
171
219
  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
220
  for (const m of find(CODE, t)) add(i, "block", "raw-code", `'${m}' is a system code; say what happened and the fix`);
173
221
  for (const m of find(FILLER, t)) add(i, "warn", "filler", `cut '${m}'`);
174
222
  for (const [re, id, msg] of VAGUE) for (const m of t.match(re) || []) add(i, "note", id, `'${m}': ${msg}`);
175
223
  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`);
224
+ if ((el === "primary-cta" || el === "secondary-cta") && STANDARD_CTA.has(low)) add(i, "note", "standard-button", `'${t}' is a standard label; fine where the next step is obvious or the repo's glossary asks for it, otherwise name the action`);
176
225
  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`);
226
+ const isFailure = el === "inline-error" || pattern === "error" || /^(failed to|couldn't|could not|unable to|something went wrong|an? (unexpected |unknown )?error)\b/i.test(t) || (el === "toast" && /\b(couldn't|can't|cannot|failed|unable|error|wrong|not (be )?(saved|sent|found|added|deleted))\b/i.test(t));
227
+ if (isFailure) {
228
+ for (const m of find(BLAME, t)) add(i, "warn", "blame-or-verdict", `'${m}' judges the person or their input; say what's needed instead`);
229
+ if (!hasFix(t)) for (const m of find(VERDICT, t)) add(i, "warn", "verdict-no-fix", `'${m}' gives the verdict with no fix; say what to do next, or what still works`);
179
230
  if (t.includes("!")) add(i, "warn", "exclaiming-at-failure", "no exclamation marks on errors");
180
231
  }
181
232
  for (const m of find(ABSOLUTES, t)) add(i, "note", "absolute", `'${m}': only promise what is always true`);
182
233
  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
234
  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
235
  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");
236
+ if (alpha.length >= 2 && t === t.toUpperCase() && !/\d/.test(t) && alpha.some((w) => w.length > 4)) add(i, "note", "all-caps", "sentence case reads faster; 95% of exemplars use it");
186
237
  else if (["headline", "primary-cta", "secondary-cta", "title-bar"].includes(el) && alpha.length >= 3 &&
187
238
  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
239
  if (LIMITS[el] && words > LIMITS[el]) add(i, "note", "long", `${words} words; exemplar ${el}s rarely pass ${LIMITS[el]}`);
@@ -206,11 +257,16 @@ export function lintCopy({ units, pattern, state, stakes, expected_pieces, origi
206
257
  // structural tics measured against shipped copy: "No X yet" empty states, narrating where things will appear, two even sentences
207
258
  units.forEach((u, i) => {
208
259
  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");
260
+ if (u.element === "headline" && /^no\b[^.!?]*\byet\b/i.test(x)) {
261
+ for (let k = out.length - 1; k >= 0; k--) if (out[k].unit === i && out[k].rule === "absence-headline") out.splice(k, 1); // one finding per problem
262
+ 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")`);
263
+ }
264
+ if (/\b(will|'ll)\s+(show up|appear|be listed|be shown|be displayed)\s+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
265
  if (u.element === "body") {
212
266
  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");
267
+ const wc = sents.map((z) => z.split(/\s+/).length);
268
+ // "Couldn't save. Try again." is a verdict and its fix, not a rhythm problem
269
+ if (sents.length === 2 && Math.abs(wc[0] - wc[1]) <= 2 && Math.min(...wc) >= 7 && !/^(please |try |check |make sure |contact |go to |tap |click |select |choose |enter |add |use )/i.test(sents[1])) add(i, "note", "even-sentences", "two sentences of near-equal length read mechanical; give them different jobs and lengths, or use one");
214
270
  }
215
271
  });
216
272
  // rewrite: short originals that already worked should stay unless there is a reason
@@ -223,7 +279,7 @@ export function lintCopy({ units, pattern, state, stakes, expected_pieces, origi
223
279
  // tics: describing the screen, inventing a cause, hinting at an outcome the facts do not give
224
280
  units.forEach((u, i) => {
225
281
  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))
282
+ if (/\b(shown|displayed|appears?|visible)\s+(before|when|after|while|until)\b/i.test(x) || /\bthis (screen|page|message|notice|popup) (shows|lists|displays|contains|is where|appears)\b/i.test(x) || /\bthis (message|notice|popup)\b/i.test(x))
227
283
  add(i, "warn", "screen-meta", "the copy describes the screen instead of the situation; say what is happening to the person");
228
284
  if (state && Object.keys(state).length) {
229
285
  const sj2 = JSON.stringify(state).toLowerCase();
@@ -231,7 +287,7 @@ export function lintCopy({ units, pattern, state, stakes, expected_pieces, origi
231
287
  const words = m[2].toLowerCase().split(/\s+/).filter((w) => w.length > 3);
232
288
  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
289
  }
234
- if (/\b(received|submitted|got) your (application|request|submission|claim|order)\b/i.test(x) && !/(offer|approv|accept|eligible)/i.test(sj2) === false)
290
+ if (/\b(received|submitted|got) your (application|request|submission|claim|order)\b/i.test(x) && !/(offer|approv|accept|eligible)/i.test(sj2))
235
291
  add(i, "note", "outcome-hint", "make sure 'received' does not suggest a result the facts do not show");
236
292
  }
237
293
  });
@@ -244,14 +300,17 @@ export function lintCopy({ units, pattern, state, stakes, expected_pieces, origi
244
300
  units.forEach((u, i) => {
245
301
  const x = u.text || "";
246
302
  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`);
303
+ for (const m of x.match(/\{(count|n|num|number|total|qty|amount)(_\w+|[A-Z]\w*)?\}\s+[a-z]+/g) || []) add(i, "warn", "plural", `'${m}': a count variable needs plural forms for 1 and other`);
248
304
  for (const m of x.match(/\b1 [a-z]+s\b/gi) || []) add(i, "warn", "plural", `'${m}': singular needed for one`);
249
305
  });
250
306
  // action-label specificity: one word, no object
251
307
  units.forEach((u, i) => {
252
308
  if (!["primary-cta", "secondary-cta"].includes(u.element)) return;
253
309
  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`);
310
+ const lw = w[0]?.toLowerCase().replace(/[.!]/g, "");
311
+ // a bare verb is fine when the headline or body on the same screen names the object ("Delete this draft?" / "Delete")
312
+ const named = units.some((v) => ["headline", "body", "title-bar"].includes(v.element) && v.text.trim());
313
+ if (w.length === 1 && !named && !ONE_WORD_OK.has(lw) && ACTION_VERBS.has(lw)) add(i, "note", "action-label", `'${u.text}' is a verb alone; name the thing it acts on unless the screen already does`);
255
314
  });
256
315
  // missing pieces
257
316
  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`);
@@ -278,12 +337,23 @@ export function lintCopy({ units, pattern, state, stakes, expected_pieces, origi
278
337
  }
279
338
  });
280
339
  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");
340
+ const prose = texts.join(" ").trim();
341
+ const latin = (prose.match(/[A-Za-z]/g) || []).length / Math.max(1, (prose.match(/\p{L}/gu) || []).length);
342
+ const english = /\b(the|to|you|your|we|is|are|was|can|not|of|and|try|this|it|in|on|for)\b/i.test(prose) || prose.split(/\s+/).length <= 3;
343
+ if (["error", "offline", "search-no-results"].includes(pattern) && prose && latin > 0.7 && english &&
344
+ !units.some((u) => ["primary-cta", "secondary-cta", "tertiary-link"].includes(u.element) && u.text.trim()) &&
345
+ !texts.some((x) => hasFix(x) || /\b(try|check|tap|go to|use|remove|clear|contact|email|reach|ask|write to|sign in|log in|reload|refresh|wait|choose|pick|select|update|reconnect|visit)\b/i.test(x))) add(null, "warn", "no-way-forward", "nothing tells people what to do next");
284
346
  units.forEach((u, i) => { for (const f of aiVoice(u.text, u.element)) add(i, f.severity, f.rule, f.detail); });
285
347
  const order = { block: 0, warn: 1, note: 2 };
286
- return out.sort((a, b) => order[a.severity] - order[b.severity]);
348
+ // the repo's own accepted words and lines (allow list or .content-md.json) never get flagged
349
+ const ok = allowMatcher(allow);
350
+ const kept = !ok.any ? out : out.filter((f) => {
351
+ if (f.rule === "state-overclaim" || f.rule === "missing-piece") return true;
352
+ if (f.unit != null && ok.line(units[f.unit]?.text || "")) return false;
353
+ const quoted = [...(f.detail || "").matchAll(/'([^']+)'/g)].map((m) => m[1]);
354
+ return !quoted.length || !quoted.every((q) => ok.word(q) || ok.line(q));
355
+ });
356
+ return kept.sort((a, b) => order[a.severity] - order[b.severity]);
287
357
  }
288
358
 
289
359
  // --- reference-first ----------------------------------------------------
@@ -316,7 +386,7 @@ export function shapeOf(text) {
316
386
  const n = w.length;
317
387
  return {
318
388
  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)],
389
+ length_range: [Math.max(1, Math.ceil(n * 0.7 - 1e-9)), Math.max(1, Math.floor(n * 1.3 + 1e-9))],
320
390
  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
391
  question: /\?\s*$/.test((text || "").trim()),
322
392
  };