content-md 0.0.0-stage → 1.0.2

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/init.js ADDED
@@ -0,0 +1,168 @@
1
+ // `npx content-md init`: registers the MCP server with the user's coding tools and adds a short pointer so the
2
+ // agent knows when to use it. By default it writes only inside the repo, pins the installed version, and
3
+ // defers to the repo's own copy rules. `npx content-md remove` takes everything back out.
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { dirname, join, relative, sep } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { findRepoRules } from "./repo.js";
9
+
10
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
11
+ const PKG = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
12
+ const RULES = readFileSync(join(ROOT, "guide/rules.md"), "utf8").trim();
13
+ // Run through npx when installed that way, pinned to this version so an editor never pulls a newer
14
+ // release on its own; otherwise point at this copy on disk.
15
+ const SERVER = ROOT.includes(`${sep}_npx${sep}`)
16
+ ? { command: "npx", args: ["-y", `${PKG.name}@${PKG.version}`] }
17
+ : { command: "node", args: [join(ROOT, "bin", "content-md.js")] };
18
+ const START = "<!-- content-md:start -->", END = "<!-- content-md:end -->";
19
+ const TARGETS = ["cursor", "claude", "codex", "vscode", "windsurf"];
20
+ const BLOCK_FILES = ["AGENTS.md", "CLAUDE.md", ".github/copilot-instructions.md", ".windsurfrules"];
21
+
22
+ // Only what this repo shows: a folder in your home directory says a tool is installed, not that this repo uses it.
23
+ function detect(cwd) {
24
+ const found = [];
25
+ if (existsSync(join(cwd, ".cursor")) || existsSync(join(cwd, ".cursorrules"))) found.push("cursor");
26
+ if (existsSync(join(cwd, ".claude")) || existsSync(join(cwd, "CLAUDE.md")) || existsSync(join(cwd, ".mcp.json"))) found.push("claude");
27
+ if (existsSync(join(cwd, "AGENTS.md")) || existsSync(join(cwd, ".codex"))) found.push("codex");
28
+ if (existsSync(join(cwd, ".vscode")) || existsSync(join(cwd, ".github", "copilot-instructions.md"))) found.push("vscode");
29
+ if (existsSync(join(cwd, ".windsurfrules")) || existsSync(join(cwd, ".windsurf"))) found.push("windsurf");
30
+ return found;
31
+ }
32
+
33
+ // What goes into shared instruction files by default: when to call the tools, and that the repo's rules win.
34
+ export function pointer(repoRules = []) {
35
+ const theirs = repoRules.length
36
+ ? `This repo's own copy rules come first: ${repoRules.map((r) => "`" + r.file + "`" + (r.sections ? ` (${r.sections.slice(0, 2).join(", ")})` : "")).join(", ")}. Where content-md disagrees with them, follow the repo.`
37
+ : "If this repo gains its own copy rules, glossary or voice guide, they come first. Where content-md disagrees with them, follow the repo.";
38
+ return `## Interface copy (content-md)
39
+
40
+ When you write or review user-facing copy (buttons, errors, empty states, dialogs, onboarding, notifications), use the \`content-md\` MCP tools: \`read_product\` once per session, \`get_guide\` for the pattern, \`decide_tone\` when the moment has stakes, and \`lint_copy\` on every draft. Reuse the product's own words.
41
+ ${theirs} Lint findings are prompts to look, not verdicts.`;
42
+ }
43
+
44
+ function rulesWithPrecedence(repoRules) {
45
+ if (!repoRules.length) return RULES;
46
+ const list = repoRules.map((r) => "`" + r.file + "`").join(", ");
47
+ return RULES.replace(/^(## UX writing\n)/, `$1\nThis repo's own copy rules come first (${list}). Read them before writing, and follow them wherever they differ from anything below.\n`);
48
+ }
49
+
50
+ export function init(argv, cwd = process.cwd()) {
51
+ const dry = argv.includes("--dry-run");
52
+ const full = argv.includes("--rules");
53
+ const global = argv.includes("--global");
54
+ const asked = argv.includes("--all") ? TARGETS : TARGETS.filter((t) => argv.includes("--" + t));
55
+ const targets = asked.length ? asked : detect(cwd);
56
+ if (!targets.length) {
57
+ console.log("No coding-tool setup found in this repo, so nothing was written. Name the tools you use:\n npx content-md init --claude (or --cursor, --codex, --vscode, --windsurf; several are fine)");
58
+ return;
59
+ }
60
+ const repoRules = findRepoRules(cwd);
61
+ const inside = [], outside = [], skipped = [];
62
+ const isInside = (p) => p.startsWith(cwd + sep);
63
+ const show = (p) => (isInside(p) ? relative(cwd, p) : p.replace(homedir(), "~"));
64
+
65
+ const write = (path, text) => {
66
+ if (!isInside(path) && !global) return false;
67
+ if (!dry) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); }
68
+ (isInside(path) ? inside : outside).push(show(path));
69
+ return true;
70
+ };
71
+ const mergeJson = (path, key, entry) => {
72
+ let data = {};
73
+ if (existsSync(path)) {
74
+ try { data = JSON.parse(readFileSync(path, "utf8") || "{}"); }
75
+ catch { console.error(`Skipped ${show(path)}: it isn't valid JSON. Add this under "${key}": ${JSON.stringify({ "content-md": entry })}`); return; }
76
+ }
77
+ data[key] = { ...(data[key] || {}), "content-md": entry };
78
+ if (!write(path, JSON.stringify(data, null, 2) + "\n")) skipped.push({ path: show(path), add: `under "${key}": ${JSON.stringify({ "content-md": entry })}` });
79
+ };
80
+ const upsertBlock = (path, block) => {
81
+ const old = existsSync(path) ? readFileSync(path, "utf8") : "";
82
+ const wrapped = `${START}\n${block}\n${END}`;
83
+ const next = old.includes(START)
84
+ ? old.replace(new RegExp(`${START}[\\s\\S]*?${END}`), wrapped)
85
+ : (old.trimEnd() ? old.trimEnd() + "\n\n" : "") + wrapped + "\n";
86
+ write(path, next);
87
+ };
88
+ const shared = full ? rulesWithPrecedence(repoRules) : pointer(repoRules);
89
+
90
+ for (const t of targets) {
91
+ if (t === "cursor") {
92
+ mergeJson(join(cwd, ".cursor", "mcp.json"), "mcpServers", SERVER);
93
+ // its own file, loaded only for copy work, so the full method fits here
94
+ write(join(cwd, ".cursor", "rules", "content-md.mdc"),
95
+ `---\ndescription: Writing or reviewing user-facing interface copy (buttons, errors, empty states, dialogs, onboarding, paywalls, notifications)\nalwaysApply: false\n---\n\n${rulesWithPrecedence(repoRules)}\n`);
96
+ }
97
+ if (t === "claude") {
98
+ mergeJson(join(cwd, ".mcp.json"), "mcpServers", SERVER);
99
+ let skill = readFileSync(join(ROOT, "guide/SKILL.md"), "utf8")
100
+ .replace(/^6\. If the project's shared folder.*$/m, existsSync(join(ROOT, "data", "screens.json"))
101
+ ? "6. Use the `content-md` MCP tools: `find_examples` for labeled shipped screens, as optional evidence (`quality: \"weak\"` shows what to avoid), `find_rules` for style-guide rules, and `lint_copy` on every draft. Cite a product only if a tool returned it."
102
+ : "6. Use the `content-md` MCP tools: `get_guide` for the pattern's playbook, `find_rules` for style-guide rules, and `lint_copy` on every draft.");
103
+ if (repoRules.length) skill = skill.replace(/^(---[\s\S]*?---\n)/, `$1\nThis repo's own copy rules come first (${repoRules.map((r) => "`" + r.file + "`").join(", ")}). Follow them wherever they differ from this skill.\n`);
104
+ write(join(cwd, ".claude", "skills", "content-md", "SKILL.md"), skill);
105
+ }
106
+ if (t === "codex") {
107
+ const cfg = join(process.env.CODEX_HOME || join(homedir(), ".codex"), "config.toml");
108
+ const old = existsSync(cfg) ? readFileSync(cfg, "utf8") : "";
109
+ const entry = `[mcp_servers.content-md]\ncommand = ${JSON.stringify(SERVER.command)}\nargs = ${JSON.stringify(SERVER.args)}\n`;
110
+ const re = /^\[mcp_servers\.(content-md|"content-md")\]\n(?:(?!\[)[^\n]*\n?)*/m;
111
+ const next = re.test(old) ? old.replace(re, entry + (/\n\n$/.test(old.match(re)[0]) ? "\n" : "")) : (old.trimEnd() ? old.trimEnd() + "\n\n" : "") + entry;
112
+ if (next !== old && !write(cfg, next)) skipped.push({ path: show(cfg), add: "\n" + entry });
113
+ upsertBlock(join(cwd, "AGENTS.md"), shared);
114
+ }
115
+ if (t === "vscode") {
116
+ mergeJson(join(cwd, ".vscode", "mcp.json"), "servers", { type: "stdio", ...SERVER });
117
+ upsertBlock(join(cwd, ".github", "copilot-instructions.md"), shared);
118
+ }
119
+ if (t === "windsurf") {
120
+ mergeJson(join(homedir(), ".codeium", "windsurf", "mcp_config.json"), "mcpServers", SERVER);
121
+ upsertBlock(join(cwd, ".windsurfrules"), shared);
122
+ }
123
+ }
124
+
125
+ const verb = dry ? "Would write" : "Wrote";
126
+ console.log(`content-md ${PKG.version} for ${targets.join(", ")}${SERVER.command === "npx" ? ` (server pinned to ${PKG.name}@${PKG.version})` : ""}`);
127
+ if (inside.length) { console.log(`\n${verb} in this repo:`); for (const p of inside) console.log(" " + p); }
128
+ if (outside.length) { console.log(`\n${verb} outside this repo (--global):`); for (const p of outside) console.log(" " + p); }
129
+ if (skipped.length) {
130
+ console.log("\nNot touched, because they are outside this repo. Add these yourself, or re-run with --global:");
131
+ for (const s of skipped) console.log(` ${s.path} ${s.add}`);
132
+ }
133
+ if (repoRules.length) console.log(`\nFound this repo's own copy rules, and told the agent they come first:\n${repoRules.map((r) => " " + r.file).join("\n")}`);
134
+ console.log(full ? "\nShared instruction files got the full method (--rules)." : "\nShared instruction files got a short pointer. Use --rules for the full method.");
135
+ console.log("Undo with `npx content-md remove`.");
136
+ if (!dry) console.log("Restart your editor or agent so it picks up the new MCP server.");
137
+ }
138
+
139
+ // Take out everything init added: marked blocks, our server entries, our rule and skill files.
140
+ export function remove(argv, cwd = process.cwd()) {
141
+ const dry = argv.includes("--dry-run");
142
+ const global = argv.includes("--global");
143
+ const done = [];
144
+ const show = (p) => (p.startsWith(cwd + sep) ? relative(cwd, p) : p.replace(homedir(), "~"));
145
+ const save = (p, text) => { if (!dry) writeFileSync(p, text); done.push(show(p)); };
146
+ for (const f of BLOCK_FILES) {
147
+ const p = join(cwd, f);
148
+ if (!existsSync(p)) continue;
149
+ const s = readFileSync(p, "utf8");
150
+ if (s.includes(START)) save(p, s.replace(new RegExp(`\\n*${START}[\\s\\S]*?${END}\\n?`), "\n").replace(/^\n+/, "").replace(/\n{3,}/g, "\n\n"));
151
+ }
152
+ const jsonFiles = [[join(cwd, ".cursor", "mcp.json"), "mcpServers"], [join(cwd, ".mcp.json"), "mcpServers"], [join(cwd, ".vscode", "mcp.json"), "servers"]];
153
+ if (global) jsonFiles.push([join(homedir(), ".codeium", "windsurf", "mcp_config.json"), "mcpServers"]);
154
+ for (const [p, key] of jsonFiles) {
155
+ if (!existsSync(p)) continue;
156
+ try { const j = JSON.parse(readFileSync(p, "utf8")); if (j[key]?.["content-md"]) { delete j[key]["content-md"]; save(p, JSON.stringify(j, null, 2) + "\n"); } } catch { /* leave invalid JSON alone */ }
157
+ }
158
+ for (const p of [join(cwd, ".cursor", "rules", "content-md.mdc"), join(cwd, ".claude", "skills", "content-md")]) {
159
+ if (existsSync(p)) { if (!dry) rmSync(p, { recursive: true, force: true }); done.push(show(p)); }
160
+ }
161
+ const cfg = join(process.env.CODEX_HOME || join(homedir(), ".codex"), "config.toml");
162
+ const re = /\n*^\[mcp_servers\.(content-md|"content-md")\]\n(?:(?!\[)[^\n]*\n?)*/m;
163
+ if (existsSync(cfg) && re.test(readFileSync(cfg, "utf8"))) {
164
+ if (global) save(cfg, readFileSync(cfg, "utf8").replace(re, "\n").replace(/^\n+/, ""));
165
+ else console.log(`${show(cfg)} still has [mcp_servers.content-md]. Remove it yourself, or re-run with --global.`);
166
+ }
167
+ console.log(done.length ? `${dry ? "Would remove content-md from" : "Removed content-md from"}:\n${done.map((p) => " " + p).join("\n")}` : "Nothing from content-md found here.");
168
+ }
package/src/product.js ADDED
@@ -0,0 +1,315 @@
1
+ // read_product and audit_copy: look at the codebase the agent is plugged into.
2
+ // read_product gathers evidence (manifest, README, landing copy, the product's own strings and how they sound)
3
+ // so the host model can write a short product brief. audit_copy pulls user-facing strings out of the code and
4
+ // ranks them by how badly they need rewriting, so the agent fixes the worst first and leaves good lines alone.
5
+ import { findRepoRules, readConfig } from "./repo.js";
6
+ import { readdirSync, readFileSync, statSync, existsSync } from "node:fs";
7
+ import { join, relative, extname, basename } from "node:path";
8
+ import { lintCopy } from "./tools.js";
9
+ import { inferIndustry, industryProfile, readSavedBrief, contextSlots, ASK_POLICY } from "./context.js";
10
+
11
+ const SKIP_DIRS = new Set(["docs", "dev-docs", "documentation", "examples", "example", "scripts", "node_modules", ".git", "dist", "build", ".next", "out", "coverage", "vendor", "Pods", ".turbo",
12
+ ".cache", "target", "__pycache__", ".venv", "venv", "public/build", "storybook-static", ".expo", "android/app/build", "DerivedData"]);
13
+ // server code: only flash/notice/alert/error strings, never tag text
14
+ const SERVER_EXT = new Set([".rb", ".py", ".ts", ".js", ".mjs", ".php", ".go", ".ex"]);
15
+ const SERVER_MSG = /\b(notice|alert|flash(?:\[:?\w+\]|\.\w+)?|error|message|msg|toast)\s*(?:=>|:|=|\()\s*(?:t\(\s*)?(["'])((?:(?!\2)[^\\\n]|\\.){4,300})\2/g;
16
+ // Client-side TS/JS (game logic, hooks, generators next to the UI): player-facing messages live here too.
17
+ const CLIENT_PATH = /(^|\/)(app|src|games?|components?|hooks?|features?|screens?|pages?|ui|views?|lib)\//;
18
+ const SERVER_PATH = /(^|\/)([\w-]*(server|api|backend)[\w-]*|functions|workers?|cli|bin|migrations?|seeds?|db|testing|test-utils|e2e|playwright|cypress|eslint[\w-]*|ci[\w-]*|\.?storybook|\.github)\/|\.config\.\w+$|(^|\/)(eslint|vite|webpack|jest|vitest|tailwind)[\w.-]*$/;
19
+ const CLIENT_MSG = /\b(message|msg|error|hint|label|title|subtitle|text|description|theme(?:Name)?|status|feedback|reason)\s*(?::|=)\s*(["'`])((?:(?!\2)[^\\\n]|\\.){4,300})\2|\bset(Message|Error|Hint|Toast|Status|Feedback|Notice|Label|Title)\s*\(\s*(["'`])((?:(?!\5)[^\\\n]|\\.){4,300})\5/g;
20
+ function isClientScript(file) {
21
+ return /\.(ts|js|mjs)$/.test(file) && !SERVER_PATH.test(file) && (CLIENT_PATH.test(file) || /(^|\/)use[A-Z]\w*\.(ts|js)$/.test(file));
22
+ }
23
+ function extractFromClientScript(src, file) {
24
+ const out = [];
25
+ for (const m of src.matchAll(CLIENT_MSG)) {
26
+ const key = m[1] || m[4], raw = m[3] || m[6];
27
+ if (/(console\.\w+|new \w*Error|throw|logger\.\w+|log\.\w+|assert\w*)\s*\(?\s*$/.test(src.slice(Math.max(0, m.index - 30), m.index))) continue;
28
+ const t = raw.replace(/\$\{[^}]*\}/g, "{x}").replace(/\s+/g, " ").trim();
29
+ if (!/\s/.test(t) || !looksLikeCopy(t) || /^[a-z]+(\.[a-z]+)+$/i.test(t)) continue;
30
+ if (/^[A-Z]\w+: /.test(t) || /\b[a-z]+[A-Z]\w*\b|`|::|\w+\(\)/.test(t)) continue; // developer notes: "Module: ...", camelCase identifiers, code
31
+ out.push({ text: t, file, line: lineOf(src, m.index), element: /error/i.test(key) ? "inline-error" : /label|title/i.test(key) ? "headline" : /hint|feedback|status|message|msg|toast|notice/i.test(key) ? "toast" : null });
32
+ }
33
+ return out.map((s) => ({ ...s, element: s.element || guessElement(s.text) }));
34
+ }
35
+ function extractFromServer(src, file) {
36
+ const out = [];
37
+ const js = /\.(ts|js|mjs)$/.test(file);
38
+ if (isClientScript(file)) return extractFromClientScript(src, file);
39
+ for (const m of src.matchAll(SERVER_MSG)) {
40
+ if (js && !/^(toast|notice|flash|alert)/i.test(m[1])) continue; // in server JS/TS, error/message strings are mostly for developers
41
+ if (/(console\.\w+|new \w*Error|throw|logger\.\w+|log\.\w+)\s*\(?\s*$/.test(src.slice(Math.max(0, m.index - 30), m.index))) continue;
42
+ const t = m[3].replace(/\s+/g, " ").trim();
43
+ if (!/\s/.test(t) || !looksLikeCopy(t) || /#\{|%\(|\$\{/.test(t) && t.length < 12) continue;
44
+ out.push({ text: t, file, line: lineOf(src, m.index), element: /error|alert/i.test(m[1]) ? "inline-error" : "toast" });
45
+ }
46
+ return out;
47
+ }
48
+ const CODE_EXT = new Set([".tsx", ".jsx", ".vue", ".svelte", ".html", ".swift", ".kt", ".astro", ".erb", ".hbs"]);
49
+ // vendored, generated and demo code: not the product's own copy
50
+ const VENDOR_PATH = /\/(vendor(ed)?|third[-_]?party|external|demos?|playground|sandbox|generated|__generated__|registry|shadcn[\w-]*|[\w-]*-studio)\//i;
51
+ const VENDOR_HEAD = /@generated|@vendored|DO NOT EDIT|auto-?generated/i;
52
+ const TEST_FILE = /(\.|_|-|\/)(test|spec|stories|story|storybookData|mock|fixture)s?\.|\/(__tests__|tests?|e2e|fixtures|mocks|stories)\//i;
53
+
54
+ // Breadth-first, so a large monorepo is covered level by level instead of one deep branch first.
55
+ // Only files the extractors read count toward the cap, and hitting it is reported, never silent.
56
+ const SCAN_EXT = /\.(tsx|jsx|vue|svelte|html|swift|kt|astro|erb|hbs|ts|js|mjs|rb|py|php|go|json|ya?ml|strings|xml|po|arb|properties|xliff|xlf)$/i;
57
+ export const MAX_FILES = +process.env.CONTENT_MD_MAX_FILES || 40000;
58
+ function walk(root, max = MAX_FILES) {
59
+ const files = [];
60
+ const queue = [root];
61
+ let truncated = false, head = 0;
62
+ while (head < queue.length) {
63
+ const dir = queue[head++];
64
+ let entries;
65
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { continue; }
66
+ for (const e of entries) {
67
+ if (e.name.startsWith(".") && e.name !== ".github") continue;
68
+ const p = join(dir, e.name);
69
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) queue.push(p); }
70
+ else if (e.isFile() && SCAN_EXT.test(e.name)) {
71
+ if (files.length >= max) { truncated = true; break; }
72
+ files.push(p);
73
+ }
74
+ }
75
+ if (truncated) break;
76
+ }
77
+ files.truncated = truncated;
78
+ files.unvisited = truncated ? queue.slice(head).map((d) => relative(root, d)).slice(0, 20) : [];
79
+ return files;
80
+ }
81
+
82
+ const readSafe = (p, cap = 400_000) => { try { const s = statSync(p); if (s.size > cap) return ""; return readFileSync(p, "utf8"); } catch { return ""; } };
83
+
84
+ // --- string extraction --------------------------------------------------------------
85
+ const PROP_ELEMENT = { title: "headline", heading: "headline", label: "label", placeholder: "placeholder", "aria-label": "label",
86
+ description: "body", subtitle: "body", message: "body", helperText: "helper-text", hint: "helper-text", tooltip: "tooltip",
87
+ emptyText: "body", confirmText: "primary-cta", cancelText: "secondary-cta", okText: "primary-cta", buttonText: "primary-cta", cta: "primary-cta", alt: null };
88
+ const looksLikeCopy = (t) => {
89
+ const s = t.trim();
90
+ if (s.length < 2 || s.length > 400) return false;
91
+ if (!/[A-Za-z]{2}/.test(s)) return false;
92
+ if (/^[a-z0-9_.-]+$/.test(s) && !/\s/.test(s)) return false; // keys, ids, class names
93
+ if (/^(https?:|\/|#|\.|@|\$\{|[A-Z_]{3,}$)/.test(s)) return false; // urls, paths, constants
94
+ if (/[{};=<>]|=>|\(\)|\bfunction\b|\bimport\b|\bconst\b/.test(s)) return false;
95
+ if (/^[a-z]+(-[a-z]+)+$/.test(s)) return false; // css-ish tokens
96
+ if (/^[A-Za-z]+[A-Z][\w]*(\[\])?$/.test(s) || /\[\]|\s\|\s|\w:\s*[A-Z]\w+[,|)]/.test(s)) return false; // type names, type unions
97
+ if ((s.match(/%[A-Za-z-]/g) || []).length >= 2 || /:$/.test(s)) return false; // date formats, yaml parents
98
+ if (/\b(px|rem|em|vh|vw|rgba?|flex|grid|w-\d|h-\d|text-|bg-|mt-|mb-|px-|py-)\b/.test(s) && !/[.!?]$/.test(s)) return false;
99
+ return true;
100
+ };
101
+ function guessElement(text, hint) {
102
+ if (hint) return hint;
103
+ const w = text.trim().split(/\s+/).length;
104
+ if (w <= 4 && !/[.!?]$/.test(text.trim())) return "label";
105
+ return "body";
106
+ }
107
+ const lineOf = (src, idx) => src.slice(0, idx).split("\n").length;
108
+
109
+ function extractFromCode(src, file) {
110
+ const out = [];
111
+ const push = (text, idx, hint) => { const t = text.replace(/\s+/g, " ").trim(); if (looksLikeCopy(t)) out.push({ text: t, file, line: lineOf(src, idx), element: guessElement(t, hint) }); };
112
+ // JSX/HTML text between tags; element from the tag name
113
+ const tagText = /<([A-Za-z][\w.]*)[^<>]*>([^<>{}]{2,400})</g;
114
+ let m;
115
+ while ((m = tagText.exec(src))) {
116
+ const tag = m[1].toLowerCase();
117
+ const hint = /^(a|link|navlink|navitem|menuitem|tab|tabs\.trigger|breadcrumb\w*|footer\w*)$|link$/.test(tag) ? "tertiary-link" : /button|cta/.test(tag) ? "primary-cta" : /^h[1-3]$|title|heading/.test(tag) ? "headline" : /label/.test(tag) ? "label" : /^p$|text|description|body|subtitle/.test(tag) ? "body" : null;
118
+ push(m[2], m.index + m[0].indexOf(m[2]), hint);
119
+ }
120
+ // string props: title="...", label: "...", placeholder={'...'}
121
+ const prop = /\b([A-Za-z-]+)\s*[=:]\s*\{?\s*(["'`])((?:(?!\2)[^\\\n]|\\.){2,400})\2/g;
122
+ while ((m = prop.exec(src))) {
123
+ const key = m[1];
124
+ if (!(key in PROP_ELEMENT) || PROP_ELEMENT[key] === null) continue;
125
+ push(m[3], m.index, PROP_ELEMENT[key]);
126
+ }
127
+ // toast/alert/confirm calls
128
+ const call = /\b(toast(?:\.\w+)?|alert|confirm|notify|showError|showToast|setError|Alert\.alert|Text|NSLocalizedString|stringResource|t)\s*\(\s*(["'`])((?:(?!\2)[^\\\n]|\\.){2,400})\2/g;
129
+ while ((m = call.exec(src))) {
130
+ const fn = m[1];
131
+ if (fn === "t" && !/\s/.test(m[3])) continue; // i18n keys, not copy
132
+ push(m[3], m.index, /toast|notify/i.test(fn) ? "toast" : /error/i.test(fn) ? "inline-error" : null);
133
+ }
134
+ return out;
135
+ }
136
+
137
+ function flattenJson(obj, prefix, out) {
138
+ if (typeof obj === "string") out.push([prefix, obj]);
139
+ else if (obj && typeof obj === "object") for (const [k, v] of Object.entries(obj)) flattenJson(v, prefix ? `${prefix}.${k}` : k, out);
140
+ return out;
141
+ }
142
+ function keyElement(key) {
143
+ const k = key.toLowerCase();
144
+ if (/(button|cta|action|confirm|submit|cancel)$|\.(ok|save|delete|continue)$/.test(k)) return "primary-cta";
145
+ if (/(title|heading|header|headline)$/.test(k)) return "headline";
146
+ if (/(placeholder)$/.test(k)) return "placeholder";
147
+ if (/(label)$/.test(k)) return "label";
148
+ if (/(error|invalid|required)/.test(k)) return "inline-error";
149
+ if (/(toast|snackbar)/.test(k)) return "toast";
150
+ if (/(description|body|subtitle|message|text|empty|hint|help)$/.test(k)) return "body";
151
+ return null;
152
+ }
153
+ const LOCALE_FILE = /(^|\/)(locales?|i18n|lang|translations?|messages|strings)(\/|$)|(^|\/)(en|en-US|en_US|en-GB)\.(json|ya?ml)$|\.strings$|strings\.xml$|\.arb$/i;
154
+ function extractFromLocale(src, file) {
155
+ const out = [];
156
+ const ext = extname(file);
157
+ const add = (key, text, line) => { const t = String(text).replace(/\s+/g, " ").trim(); if (looksLikeCopy(t)) out.push({ text: t, file, line, key, element: guessElement(t, keyElement(key)) }); };
158
+ if (ext === ".json" || ext === ".arb") {
159
+ try { for (const [k, v] of flattenJson(JSON.parse(src), "", [])) if (!k.startsWith("@")) add(k, v, lineOf(src, Math.max(0, src.indexOf(JSON.stringify(v).slice(0, 40))))); } catch { /* not json */ }
160
+ } else if (ext === ".strings") {
161
+ for (const m of src.matchAll(/"([^"]+)"\s*=\s*"((?:[^"\\]|\\.)*)"\s*;/g)) add(m[1], m[2], lineOf(src, m.index));
162
+ } else if (ext === ".xml") {
163
+ for (const m of src.matchAll(/<string name="([^"]+)"[^>]*>([^<]+)<\/string>/g)) add(m[1], m[2], lineOf(src, m.index));
164
+ } else if (/\.ya?ml$/.test(ext)) {
165
+ for (const m of src.matchAll(/^[ \t]*([\w.-]+):[ \t]*["']?([^"'\n#]{2,400}?)["']?[ \t]*$/gm)) add(m[1], m[2], lineOf(src, m.index));
166
+ }
167
+ return out;
168
+ }
169
+
170
+ // A locale file counts as English when its path names English, or names no language at all.
171
+ const LANG_TOKEN = /(?:^|[\/._-])([a-z]{2,3})(?:[-_][A-Za-z0-9]{2,4})?(?=\.(?:json|ya?ml|arb|strings|xml|lproj)\b|\/)/g;
172
+ const KNOWN_NOT_LANG = new Set(["app", "src", "lib", "ui", "web", "api", "pro", "dev", "msg", "res", "doc", "img", "css", "js", "ts", "all", "views", "values", "base"]);
173
+ const isEnglishLocale = (f) => {
174
+ const codes = [...f.toLowerCase().matchAll(LANG_TOKEN)].map((m) => m[1]).filter((c) => !KNOWN_NOT_LANG.has(c));
175
+ const vals = f.match(/values-([a-z]{2})(?:-r[A-Z]{2})?\//);
176
+ if (vals) return vals[1] === "en";
177
+ return !codes.length || codes.includes("en");
178
+ };
179
+
180
+ export function collectStrings(root, sub) {
181
+ const files = walk(sub ? join(root, sub) : root);
182
+ const strings = [];
183
+ const ignore = readConfig(root).ignore.map((g) => g.replace(/^\.\//, ""));
184
+ for (const f of files) {
185
+ const rel = relative(root, f);
186
+ if (TEST_FILE.test("/" + rel) || VENDOR_PATH.test("/" + rel) || ignore.some((g) => rel.startsWith(g))) continue;
187
+ if (LOCALE_FILE.test(rel)) { if (isEnglishLocale(rel)) strings.push(...extractFromLocale(readSafe(f), rel)); continue; }
188
+ if (CODE_EXT.has(extname(f))) { const src = readSafe(f); if (!VENDOR_HEAD.test(src.slice(0, 400))) strings.push(...extractFromCode(src, rel)); }
189
+ else if (SERVER_EXT.has(extname(f)) && (isClientScript(rel) || !/(^|\/)(config|db|migrations?|spec|test|api)\//.test(rel))) strings.push(...extractFromServer(readSafe(f), rel));
190
+ }
191
+ // de-duplicate by text, keep first location and a count
192
+ const seen = new Map();
193
+ for (const s of strings) { const k = s.text; if (seen.has(k)) seen.get(k).uses++; else seen.set(k, { ...s, uses: 1 }); }
194
+ return { files: files.length, strings: [...seen.values()], truncated: files.truncated, unvisited: files.unvisited };
195
+ }
196
+
197
+ // --- read_product ----------------------------------------------------------------------
198
+ function manifest(root) {
199
+ const m = {};
200
+ const pj = readSafe(join(root, "package.json"));
201
+ if (pj) try { const j = JSON.parse(pj); Object.assign(m, { name: j.name, description: j.description, keywords: j.keywords, homepage: j.homepage, frameworks: Object.keys({ ...j.dependencies, ...j.devDependencies }).filter((d) => /^(next|react|react-native|expo|vue|nuxt|svelte|@sveltejs\/kit|astro|electron|@angular\/core|@remix-run\/react|tailwindcss|stripe|@stripe\/stripe-js|@supabase\/supabase-js|firebase|openai|@anthropic-ai\/sdk|ai)$/.test(d)) }); } catch { /* ignore */ }
202
+ for (const f of ["pyproject.toml", "Cargo.toml", "app.json", "pubspec.yaml"]) {
203
+ const s = readSafe(join(root, f));
204
+ if (!s) continue;
205
+ const d = s.match(/description\s*[:=]\s*["']?([^"'\n]+)/); const n = s.match(/\bname\s*[:=]\s*["']?([^"'\n]+)/);
206
+ if (!m.name && n) m.name = n[1].trim(); if (!m.description && d) m.description = d[1].trim();
207
+ }
208
+ return m;
209
+ }
210
+ function readme(root) {
211
+ const f = ["README.md", "readme.md", "README.mdx", "README", "docs/README.md"].map((x) => join(root, x)).find(existsSync);
212
+ if (!f) return null;
213
+ const s = readSafe(f).replace(/<[^>]+>/g, " ").replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)/g, "")
214
+ .replace(/```[\s\S]*?```/g, "").replace(/[ \t]+/g, " ").replace(/\n[ \t|]*(?=\n)/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
215
+ return s.slice(0, 1200);
216
+ }
217
+ const IND_KEYS = ["finance","commerce","productivity","social","ai-tools","health-fitness","media-entertainment","food-delivery","travel","education","developer-tools","mobility"];
218
+ const LANDING = /(^|\/)(index|home|landing|hero|pricing|about|features|marketing|welcome|onboarding|page)\.(tsx|jsx|vue|svelte|astro|html|mdx)$/i;
219
+
220
+ const TITLE_CASE = (t) => { const w = t.replace(/[^A-Za-z ]/g, "").split(/\s+/).filter(Boolean); return w.length >= 3 && w.slice(1).filter((x) => x[0] === x[0].toUpperCase() && x.length > 3).length >= w.slice(1).filter((x) => x.length > 3).length && w.slice(1).some((x) => x.length > 3); };
221
+ function voiceStats(strings) {
222
+ const n = strings.length || 1;
223
+ const texts = strings.map((s) => s.text);
224
+ const pct = (f) => Math.round((100 * texts.filter(f).length) / n);
225
+ const sentences = texts.filter((t) => t.split(/\s+/).length >= 5);
226
+ const shortLabels = texts.filter((t) => t.split(/\s+/).length <= 4);
227
+ const words = texts.join(" ").toLowerCase().match(/[a-z']+/g) || [];
228
+ const UI_GENERIC = new Set("successfully please must enter select click tap continue cancel submit save delete edit remove update create name email password code data error invalid required failed success settings back next close done confirm learn more view open". split(" "));
229
+ const STOP = new Set("the a an to of and or for in on is are be your you we our it this that with at by from as can will has have not no all new my i me if do".split(" "));
230
+ const freq = {};
231
+ for (const w of words) if (w.length > 3 && !STOP.has(w) && !UI_GENERIC.has(w)) freq[w] = (freq[w] || 0) + 1;
232
+ return {
233
+ strings: strings.length,
234
+ mean_words: +(texts.reduce((a, t) => a + t.split(/\s+/).length, 0) / n).toFixed(1),
235
+ title_case_labels_pct: Math.round((100 * shortLabels.filter(TITLE_CASE).length) / (shortLabels.length || 1)),
236
+ exclamation_pct: pct((t) => t.includes("!")),
237
+ we_pct: pct((t) => /\b(we|we're|we'll|we've|our|us)\b/i.test(t)),
238
+ you_pct: pct((t) => /\b(you|your|you're|you'll)\b/i.test(t)),
239
+ contractions_pct: Math.round((100 * sentences.filter((t) => /\b\w+['’](re|ll|ve|t|s|d)\b/i.test(t)).length) / (sentences.length || 1)),
240
+ emoji_pct: pct((t) => /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(t)),
241
+ please_pct: pct((t) => /\bplease\b/i.test(t)),
242
+ domain_words: Object.entries(freq).sort((a, b) => b[1] - a[1]).slice(0, 25).map(([w]) => w),
243
+ };
244
+ }
245
+
246
+ export function readProduct({ root = process.cwd(), sample = 18 } = {}) {
247
+ if (!existsSync(root)) return { error: `No folder at ${root}. Pass the project root.` };
248
+ const { files, strings, truncated, unvisited } = collectStrings(root);
249
+ const landing = strings.filter((s) => LANDING.test(s.file) && s.text.split(/\s+/).length >= 3).slice(0, 15).map((s) => s.text);
250
+ // a spread of the product's own lines: headlines, buttons and full sentences, most-used first
251
+ const pick = (f, n) => strings.filter(f).sort((a, b) => b.uses - a.uses || b.text.length - a.text.length).slice(0, n);
252
+ const byUse = [...pick((s) => s.element === "headline", Math.ceil(sample / 4)), ...pick((s) => /cta/.test(s.element) && s.text.split(/\s+/).length >= 2, Math.ceil(sample / 4))];
253
+ const sentences = pick((s) => s.text.split(/\s+/).length >= 6 && /[.!?]$/.test(s.text) && !byUse.includes(s), sample - byUse.length);
254
+ const man = manifest(root), rd = readme(root), voice = voiceStats(strings);
255
+ const saved = readSavedBrief(root);
256
+ const cfg = readConfig(root), rules = findRepoRules(root);
257
+ const first = rules.length ? "Read the files in repo_rules first: the repo's own copy rules and glossary win over content-md wherever they differ. " : "";
258
+ const guess = cfg.industry && IND_KEYS.includes(cfg.industry) ? { industry: cfg.industry, confidence: "high", candidates: [] }
259
+ : saved?.fields?.industry && IND_KEYS.includes(saved.fields.industry) ? { industry: saved.fields.industry, confidence: "high", candidates: [] }
260
+ : inferIndustry([[`${man.name || ""} ${man.description || ""} ${(man.keywords || []).join(" ")}`, 4], [(rd || "").slice(0, 400), 2], [rd, 0.5], [landing.join(" "), 2], [voice.domain_words.join(" "), 3]]);
261
+ const { slots, questions } = contextSlots({ manifest: man, readme: rd, voice, industryGuess: guess, saved });
262
+ return {
263
+ root, files_scanned: files, ...(truncated ? { truncated: true, warning: `Stopped after ${MAX_FILES} files; not read: ${unvisited.join(", ")}` } : {}),
264
+ saved_brief: saved ? { file: saved.file, text: saved.text } : null,
265
+ repo_rules: rules,
266
+ manifest: man,
267
+ readme: saved ? undefined : rd,
268
+ landing_copy: landing,
269
+ voice,
270
+ industry: { ...guess, profile: guess.industry ? industryProfile(guess.industry, voice) : null },
271
+ sample_lines: [...byUse, ...sentences].map((s) => ({ text: s.text, element: s.element, where: `${s.file}:${s.line}` })),
272
+ slots, questions, ask_policy: ASK_POLICY,
273
+ next: first + (saved
274
+ ? "A saved brief exists: use it, fill any slot still marked unknown, and don't re-ask what it answers. Call save_product_brief only if something changed."
275
+ : "Fill every slot: read-and-fill slots from the README and strings, inferred slots by checking them against the sample lines. Then write a brief of at most six lines: (1) what the product is, in its own words; (2) who uses it and the niche; (3) the main job; (4) its current voice, quoting 2 or 3 sample lines, and how it differs from the industry baseline; (5) its own words for its things (reuse them); (6) what is at stake for its users. Mark what you inferred. Handle `questions` by the ask_policy (ask_person shows a form where the client supports it). Then call save_product_brief so the next session starts from it. Use the industry examples as evidence of what comparable products do, not as wording to copy. Keep the product's voice unless the person asks to change it; fix tics, not personality.") + (guess.industry ? ` Save industry "${guess.industry}" in the brief (or correct it), so find_reference and find_examples stay with comparable products.` : ""),
276
+ };
277
+ }
278
+
279
+ // --- audit_copy ------------------------------------------------------------------------------
280
+ const STAKES = /\b(pay|payment|card|charge|charged|refund|billing|invoice|subscription|cancel|delete|remove|permanent|password|account|verify|security|error|failed|couldn't|can't|unable|lost|expired|declined|money|balance|transfer|withdraw|privacy|data)\b/i;
281
+ const SEV = { block: 5, warn: 3, note: 1 };
282
+
283
+ export function auditCopy({ root = process.cwd(), strings, limit = 25, path_filter, allow } = {}) {
284
+ const cfg = readConfig(root);
285
+ let walked = null;
286
+ let list;
287
+ if (strings?.length) list = strings.map((s) => (typeof s === "string" ? { text: s, element: guessElement(s) } : { ...s, element: s.element || guessElement(s.text) }));
288
+ else {
289
+ // a path_filter that names a folder is walked directly, so it is never lost to the file cap
290
+ const sub = path_filter && existsSync(join(root, path_filter)) ? path_filter.replace(/\/$/, "") : undefined;
291
+ walked = collectStrings(root, sub);
292
+ list = walked.strings;
293
+ }
294
+ if (path_filter) list = list.filter((s) => (s.file || "").includes(path_filter.replace(/\/$/, "")));
295
+ const scored = list.map((s) => {
296
+ const findings = lintCopy({ units: [{ element: s.element, text: s.text }], allow: [...cfg.allow, ...(allow || [])] })
297
+ .filter((f) => !["variable", "long", "punctuation"].includes(f.rule));
298
+ const base = findings.reduce((a, f) => a + SEV[f.severity], 0);
299
+ const stakes = STAKES.test(s.text);
300
+ const reach = Math.min(3, Math.log2(1 + (s.uses || 1)));
301
+ return { text: s.text, element: s.element, where: s.file ? `${s.file}:${s.line}` : undefined, uses: s.uses,
302
+ score: base ? +(base * (stakes ? 1.5 : 1) + reach).toFixed(1) : 0, stakes: stakes ? "high" : "normal",
303
+ findings: findings.map((f) => `${f.severity} ${f.rule}: ${f.detail}`) };
304
+ });
305
+ const flagged = scored.filter((s) => s.score > 0).sort((a, b) => b.score - a.score);
306
+ return {
307
+ scanned: list.length, flagged: flagged.length, leave_alone: list.length - flagged.length,
308
+ ...(walked?.truncated ? { truncated: true, warning: `Stopped after ${MAX_FILES} files; these folders were not read: ${walked.unvisited.join(", ")}. Lines there were not checked. Pass path_filter with a folder to audit it directly.` } : {}),
309
+ ...(path_filter && !list.length ? { warning: `No user-facing strings found under '${path_filter}'. Check the path is relative to ${root}.` } : {}),
310
+ ...(cfg.error ? { config_error: cfg.error } : {}),
311
+ repo_rules: findRepoRules(root),
312
+ worst: flagged.slice(0, limit),
313
+ next: "Rewrite from the top of this list down. For each line: read the screen it sits on, call get_guide for its pattern, keep every word that already works, fix only what a finding names, and run lint_copy on the new line. Lines not listed passed every check: leave them as they are unless the person asks. A finding is a prompt to look, not a verdict; if the line is right for its moment, keep it and say why. Where the repo's own rules (repo_rules) accept a word or label, follow them; to silence it for good, add it to \"allow\" in .content-md.json, and add folders that aren't product UI to \"ignore\".",
314
+ };
315
+ }