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/init.js CHANGED
@@ -1,42 +1,72 @@
1
- // `npx content-md init`: registers the MCP server with the user's coding tools and installs a short rule
2
- // so the agent knows when to use it. Idempotent: re-running updates the same entries.
3
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
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";
4
5
  import { homedir } from "node:os";
5
6
  import { dirname, join, relative, sep } from "node:path";
6
7
  import { fileURLToPath } from "node:url";
8
+ import { findRepoRules } from "./repo.js";
7
9
 
8
10
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
11
+ const PKG = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
9
12
  const RULES = readFileSync(join(ROOT, "guide/rules.md"), "utf8").trim();
10
- // Run through npx when installed that way (published package); otherwise point at this copy on disk,
11
- // so a local or global install works before anything is on npm.
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.
12
15
  const SERVER = ROOT.includes(`${sep}_npx${sep}`)
13
- ? { command: "npx", args: ["-y", "content-md"] }
16
+ ? { command: "npx", args: ["-y", `${PKG.name}@${PKG.version}`] }
14
17
  : { command: "node", args: [join(ROOT, "bin", "content-md.js")] };
15
18
  const START = "<!-- content-md:start -->", END = "<!-- content-md:end -->";
16
-
17
19
  const TARGETS = ["cursor", "claude", "codex", "vscode", "windsurf"];
20
+ const BLOCK_FILES = ["AGENTS.md", "CLAUDE.md", ".github/copilot-instructions.md", ".windsurfrules"];
18
21
 
22
+ // Only what this repo shows: a folder in your home directory says a tool is installed, not that this repo uses it.
19
23
  function detect(cwd) {
20
- const home = homedir();
21
24
  const found = [];
22
- if (existsSync(join(cwd, ".cursor")) || existsSync(join(home, ".cursor"))) found.push("cursor");
23
- if (existsSync(join(cwd, ".claude")) || existsSync(join(cwd, "CLAUDE.md")) || existsSync(join(home, ".claude"))) found.push("claude");
24
- if (existsSync(join(cwd, "AGENTS.md")) || existsSync(process.env.CODEX_HOME || join(home, ".codex"))) found.push("codex");
25
- if (existsSync(join(cwd, ".vscode"))) found.push("vscode");
26
- if (existsSync(join(home, ".codeium", "windsurf"))) found.push("windsurf");
27
- return found.length ? found : ["cursor", "claude", "codex"];
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`);
28
48
  }
29
49
 
30
50
  export function init(argv, cwd = process.cwd()) {
31
51
  const dry = argv.includes("--dry-run");
52
+ const full = argv.includes("--rules");
53
+ const global = argv.includes("--global");
32
54
  const asked = argv.includes("--all") ? TARGETS : TARGETS.filter((t) => argv.includes("--" + t));
33
55
  const targets = asked.length ? asked : detect(cwd);
34
- const done = [];
35
- const show = (p) => (p.startsWith(cwd) ? relative(cwd, p) : p.replace(homedir(), "~"));
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(), "~"));
36
64
 
37
65
  const write = (path, text) => {
66
+ if (!isInside(path) && !global) return false;
38
67
  if (!dry) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); }
39
- done.push(show(path));
68
+ (isInside(path) ? inside : outside).push(show(path));
69
+ return true;
40
70
  };
41
71
  const mergeJson = (path, key, entry) => {
42
72
  let data = {};
@@ -45,7 +75,7 @@ export function init(argv, cwd = process.cwd()) {
45
75
  catch { console.error(`Skipped ${show(path)}: it isn't valid JSON. Add this under "${key}": ${JSON.stringify({ "content-md": entry })}`); return; }
46
76
  }
47
77
  data[key] = { ...(data[key] || {}), "content-md": entry };
48
- write(path, JSON.stringify(data, null, 2) + "\n");
78
+ if (!write(path, JSON.stringify(data, null, 2) + "\n")) skipped.push({ path: show(path), add: `under "${key}": ${JSON.stringify({ "content-md": entry })}` });
49
79
  };
50
80
  const upsertBlock = (path, block) => {
51
81
  const old = existsSync(path) ? readFileSync(path, "utf8") : "";
@@ -55,40 +85,89 @@ export function init(argv, cwd = process.cwd()) {
55
85
  : (old.trimEnd() ? old.trimEnd() + "\n\n" : "") + wrapped + "\n";
56
86
  write(path, next);
57
87
  };
88
+ const shared = full ? rulesWithPrecedence(repoRules) : pointer(repoRules);
58
89
 
59
90
  for (const t of targets) {
60
91
  if (t === "cursor") {
61
92
  mergeJson(join(cwd, ".cursor", "mcp.json"), "mcpServers", SERVER);
93
+ // its own file, loaded only for copy work, so the full method fits here
62
94
  write(join(cwd, ".cursor", "rules", "content-md.mdc"),
63
- `---\ndescription: Writing or reviewing user-facing interface copy (buttons, errors, empty states, dialogs, onboarding, paywalls, notifications)\nalwaysApply: false\n---\n\n${RULES}\n`);
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`);
64
96
  }
65
97
  if (t === "claude") {
66
98
  mergeJson(join(cwd, ".mcp.json"), "mcpServers", SERVER);
67
- const skill = readFileSync(join(ROOT, "guide/SKILL.md"), "utf8")
99
+ let skill = readFileSync(join(ROOT, "guide/SKILL.md"), "utf8")
68
100
  .replace(/^6\. If the project's shared folder.*$/m, existsSync(join(ROOT, "data", "screens.json"))
69
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."
70
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`);
71
104
  write(join(cwd, ".claude", "skills", "content-md", "SKILL.md"), skill);
72
105
  }
73
106
  if (t === "codex") {
74
107
  const cfg = join(process.env.CODEX_HOME || join(homedir(), ".codex"), "config.toml");
75
108
  const old = existsSync(cfg) ? readFileSync(cfg, "utf8") : "";
76
- if (!/^\[mcp_servers\.(content-md|"content-md")\]/m.test(old)) {
77
- write(cfg, (old.trimEnd() ? old.trimEnd() + "\n\n" : "") + `[mcp_servers.content-md]\ncommand = ${JSON.stringify(SERVER.command)}\nargs = ${JSON.stringify(SERVER.args)}\n`);
78
- }
79
- upsertBlock(join(cwd, "AGENTS.md"), RULES);
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);
80
114
  }
81
115
  if (t === "vscode") {
82
116
  mergeJson(join(cwd, ".vscode", "mcp.json"), "servers", { type: "stdio", ...SERVER });
83
- upsertBlock(join(cwd, ".github", "copilot-instructions.md"), RULES);
117
+ upsertBlock(join(cwd, ".github", "copilot-instructions.md"), shared);
84
118
  }
85
119
  if (t === "windsurf") {
86
120
  mergeJson(join(homedir(), ".codeium", "windsurf", "mcp_config.json"), "mcpServers", SERVER);
87
- upsertBlock(join(cwd, ".windsurfrules"), RULES);
121
+ upsertBlock(join(cwd, ".windsurfrules"), shared);
88
122
  }
89
123
  }
90
124
 
91
- console.log(`${dry ? "Would set up" : "Set up"} content-md for ${targets.join(", ")}:`);
92
- for (const p of done) console.log(" " + p);
93
- if (!dry) console.log("\nRestart your editor or agent so it picks up the new MCP server.");
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"]) {
157
+ delete j[key]["content-md"];
158
+ // a repo file that held only our server is removed, not left behind as {"mcpServers": {}}
159
+ const empty = !Object.keys(j[key]).length && Object.keys(j).length === 1 && p.startsWith(cwd);
160
+ if (empty) { if (!dry) rmSync(p, { force: true }); done.push(show(p)); } else save(p, JSON.stringify(j, null, 2) + "\n");
161
+ } } catch { /* leave invalid JSON alone */ }
162
+ }
163
+ for (const p of [join(cwd, ".cursor", "rules", "content-md.mdc"), join(cwd, ".claude", "skills", "content-md")]) {
164
+ if (existsSync(p)) { if (!dry) rmSync(p, { recursive: true, force: true }); done.push(show(p)); }
165
+ }
166
+ const cfg = join(process.env.CODEX_HOME || join(homedir(), ".codex"), "config.toml");
167
+ const re = /\n*^\[mcp_servers\.(content-md|"content-md")\]\n(?:(?!\[)[^\n]*\n?)*/m;
168
+ if (existsSync(cfg) && re.test(readFileSync(cfg, "utf8"))) {
169
+ if (global) save(cfg, readFileSync(cfg, "utf8").replace(re, "\n").replace(/^\n+/, ""));
170
+ else console.log(`${show(cfg)} still has [mcp_servers.content-md]. Remove it yourself, or re-run with --global.`);
171
+ }
172
+ 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.");
94
173
  }
package/src/product.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // read_product gathers evidence (manifest, README, landing copy, the product's own strings and how they sound)
3
3
  // so the host model can write a short product brief. audit_copy pulls user-facing strings out of the code and
4
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";
5
6
  import { readdirSync, readFileSync, statSync, existsSync } from "node:fs";
6
7
  import { join, relative, extname, basename } from "node:path";
7
8
  import { lintCopy } from "./tools.js";
@@ -45,22 +46,40 @@ function extractFromServer(src, file) {
45
46
  return out;
46
47
  }
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
+ // backend tools, crawlers and infrastructure at the repo's top level: their messages never reach the product's users
53
+ const NON_PRODUCT_PATH = /^\/(tools|infra|infrastructure|ops|deploy|terraform|crawlers?|scrapers?|etl|pipelines?)\/|\/[\w-]*(crawler|scraper)s?\//i;
54
+ // admin and internal pages: the reader is the team, so naming an env variable is the fix, not a leak
55
+ export const ADMIN_PATH = /(^|\/|\()(admin|internal|staff|backoffice|back-office|ops|debug)(\)|\/)|(^|\/)[\w-]*[a-z](Admin|Internal)[A-Z]\w*\.|(^|\/)(admin|internal)[A-Z-]/;
48
56
  const TEST_FILE = /(\.|_|-|\/)(test|spec|stories|story|storybookData|mock|fixture)s?\.|\/(__tests__|tests?|e2e|fixtures|mocks|stories)\//i;
49
57
 
50
- function walk(root, max = 6000) {
58
+ // Breadth-first, so a large monorepo is covered level by level instead of one deep branch first.
59
+ // Only files the extractors read count toward the cap, and hitting it is reported, never silent.
60
+ 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;
61
+ export const MAX_FILES = +process.env.CONTENT_MD_MAX_FILES || 40000;
62
+ function walk(root, max = MAX_FILES) {
51
63
  const files = [];
52
- const stack = [root];
53
- while (stack.length && files.length < max) {
54
- const dir = stack.pop();
64
+ const queue = [root];
65
+ let truncated = false, head = 0;
66
+ while (head < queue.length) {
67
+ const dir = queue[head++];
55
68
  let entries;
56
69
  try { entries = readdirSync(dir, { withFileTypes: true }); } catch { continue; }
57
70
  for (const e of entries) {
58
71
  if (e.name.startsWith(".") && e.name !== ".github") continue;
59
72
  const p = join(dir, e.name);
60
- if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) stack.push(p); }
61
- else if (e.isFile()) files.push(p);
73
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) queue.push(p); }
74
+ else if (e.isFile() && SCAN_EXT.test(e.name)) {
75
+ if (files.length >= max) { truncated = true; break; }
76
+ files.push(p);
77
+ }
62
78
  }
79
+ if (truncated) break;
63
80
  }
81
+ files.truncated = truncated;
82
+ files.unvisited = truncated ? queue.slice(head).map((d) => relative(root, d)).slice(0, 20) : [];
64
83
  return files;
65
84
  }
66
85
 
@@ -77,6 +96,8 @@ const looksLikeCopy = (t) => {
77
96
  if (/^[a-z0-9_.-]+$/.test(s) && !/\s/.test(s)) return false; // keys, ids, class names
78
97
  if (/^(https?:|\/|#|\.|@|\$\{|[A-Z_]{3,}$)/.test(s)) return false; // urls, paths, constants
79
98
  if (/[{};=<>]|=>|\(\)|\bfunction\b|\bimport\b|\bconst\b/.test(s)) return false;
99
+ // JSX/TS code that leaks between tags: ternaries, logical operators, optional chains, object-literal keys
100
+ if (/&&|&amp;&amp;|\|\||\?\.|\.length\b|\?\s*\($|^[)\]:,?]|\b(null|undefined)\s*[,:)]/.test(s)) return false;
80
101
  if (/^[a-z]+(-[a-z]+)+$/.test(s)) return false; // css-ish tokens
81
102
  if (/^[A-Za-z]+[A-Z][\w]*(\[\])?$/.test(s) || /\[\]|\s\|\s|\w:\s*[A-Z]\w+[,|)]/.test(s)) return false; // type names, type unions
82
103
  if ((s.match(/%[A-Za-z-]/g) || []).length >= 2 || /:$/.test(s)) return false; // date formats, yaml parents
@@ -95,11 +116,11 @@ function extractFromCode(src, file) {
95
116
  const out = [];
96
117
  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) }); };
97
118
  // JSX/HTML text between tags; element from the tag name
98
- const tagText = /<([A-Za-z][\w.]*)[^<>]*>([^<>{}]{2,400})</g;
119
+ const tagText = /<([A-Za-z][\w.]*)[^<>]*>([^<>{}]{2,400})(?=<)/g; // lookahead, so "<p>A<br />B</p>" yields both A and B
99
120
  let m;
100
121
  while ((m = tagText.exec(src))) {
101
122
  const tag = m[1].toLowerCase();
102
- const hint = /button|cta|^a$|link/.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;
123
+ 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;
103
124
  push(m[2], m.index + m[0].indexOf(m[2]), hint);
104
125
  }
105
126
  // string props: title="...", label: "...", placeholder={'...'}
@@ -162,20 +183,21 @@ const isEnglishLocale = (f) => {
162
183
  return !codes.length || codes.includes("en");
163
184
  };
164
185
 
165
- export function collectStrings(root) {
166
- const files = walk(root);
186
+ export function collectStrings(root, sub) {
187
+ const files = walk(sub ? join(root, sub) : root);
167
188
  const strings = [];
189
+ const ignore = readConfig(root).ignore.map((g) => g.replace(/^\.\//, ""));
168
190
  for (const f of files) {
169
191
  const rel = relative(root, f);
170
- if (TEST_FILE.test("/" + rel)) continue;
192
+ if (TEST_FILE.test("/" + rel) || VENDOR_PATH.test("/" + rel) || NON_PRODUCT_PATH.test("/" + rel) || ignore.some((g) => rel.startsWith(g))) continue;
171
193
  if (LOCALE_FILE.test(rel)) { if (isEnglishLocale(rel)) strings.push(...extractFromLocale(readSafe(f), rel)); continue; }
172
- if (CODE_EXT.has(extname(f))) strings.push(...extractFromCode(readSafe(f), rel));
194
+ if (CODE_EXT.has(extname(f))) { const src = readSafe(f); if (!VENDOR_HEAD.test(src.slice(0, 400))) strings.push(...extractFromCode(src, rel)); }
173
195
  else if (SERVER_EXT.has(extname(f)) && (isClientScript(rel) || !/(^|\/)(config|db|migrations?|spec|test|api)\//.test(rel))) strings.push(...extractFromServer(readSafe(f), rel));
174
196
  }
175
197
  // de-duplicate by text, keep first location and a count
176
198
  const seen = new Map();
177
199
  for (const s of strings) { const k = s.text; if (seen.has(k)) seen.get(k).uses++; else seen.set(k, { ...s, uses: 1 }); }
178
- return { files: files.length, strings: [...seen.values()] };
200
+ return { files: files.length, strings: [...seen.values()], truncated: files.truncated, unvisited: files.unvisited };
179
201
  }
180
202
 
181
203
  // --- read_product ----------------------------------------------------------------------
@@ -196,7 +218,7 @@ function readme(root) {
196
218
  if (!f) return null;
197
219
  const s = readSafe(f).replace(/<[^>]+>/g, " ").replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)/g, "")
198
220
  .replace(/```[\s\S]*?```/g, "").replace(/[ \t]+/g, " ").replace(/\n[ \t|]*(?=\n)/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
199
- return s.slice(0, 1800);
221
+ return s.slice(0, 1200);
200
222
  }
201
223
  const IND_KEYS = ["finance","commerce","productivity","social","ai-tools","health-fitness","media-entertainment","food-delivery","travel","education","developer-tools","mobility"];
202
224
  const LANDING = /(^|\/)(index|home|landing|hero|pricing|about|features|marketing|welcome|onboarding|page)\.(tsx|jsx|vue|svelte|astro|html|mdx)$/i;
@@ -220,16 +242,16 @@ function voiceStats(strings) {
220
242
  exclamation_pct: pct((t) => t.includes("!")),
221
243
  we_pct: pct((t) => /\b(we|we're|we'll|we've|our|us)\b/i.test(t)),
222
244
  you_pct: pct((t) => /\b(you|your|you're|you'll)\b/i.test(t)),
223
- contractions_pct: Math.round((100 * sentences.filter((t) => /\b\w+'(re|ll|ve|t|s|d)\b/i.test(t)).length) / (sentences.length || 1)),
245
+ contractions_pct: Math.round((100 * sentences.filter((t) => /\b\w+['’](re|ll|ve|t|s|d)\b/i.test(t)).length) / (sentences.length || 1)),
224
246
  emoji_pct: pct((t) => /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(t)),
225
247
  please_pct: pct((t) => /\bplease\b/i.test(t)),
226
248
  domain_words: Object.entries(freq).sort((a, b) => b[1] - a[1]).slice(0, 25).map(([w]) => w),
227
249
  };
228
250
  }
229
251
 
230
- export function readProduct({ root = process.cwd(), sample = 30 } = {}) {
252
+ export function readProduct({ root = process.cwd(), sample = 18 } = {}) {
231
253
  if (!existsSync(root)) return { error: `No folder at ${root}. Pass the project root.` };
232
- const { files, strings } = collectStrings(root);
254
+ const { files, strings, truncated, unvisited } = collectStrings(root);
233
255
  const landing = strings.filter((s) => LANDING.test(s.file) && s.text.split(/\s+/).length >= 3).slice(0, 15).map((s) => s.text);
234
256
  // a spread of the product's own lines: headlines, buttons and full sentences, most-used first
235
257
  const pick = (f, n) => strings.filter(f).sort((a, b) => b.uses - a.uses || b.text.length - a.text.length).slice(0, n);
@@ -237,12 +259,16 @@ export function readProduct({ root = process.cwd(), sample = 30 } = {}) {
237
259
  const sentences = pick((s) => s.text.split(/\s+/).length >= 6 && /[.!?]$/.test(s.text) && !byUse.includes(s), sample - byUse.length);
238
260
  const man = manifest(root), rd = readme(root), voice = voiceStats(strings);
239
261
  const saved = readSavedBrief(root);
240
- const guess = saved?.fields?.industry && IND_KEYS.includes(saved.fields.industry) ? { industry: saved.fields.industry, confidence: "high", candidates: [] }
262
+ const cfg = readConfig(root), rules = findRepoRules(root);
263
+ 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. " : "";
264
+ const guess = cfg.industry && IND_KEYS.includes(cfg.industry) ? { industry: cfg.industry, confidence: "high", candidates: [] }
265
+ : saved?.fields?.industry && IND_KEYS.includes(saved.fields.industry) ? { industry: saved.fields.industry, confidence: "high", candidates: [] }
241
266
  : 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]]);
242
267
  const { slots, questions } = contextSlots({ manifest: man, readme: rd, voice, industryGuess: guess, saved });
243
268
  return {
244
- root, files_scanned: files,
269
+ root, files_scanned: files, ...(truncated ? { truncated: true, warning: `Stopped after ${MAX_FILES} files; not read: ${unvisited.join(", ")}` } : {}),
245
270
  saved_brief: saved ? { file: saved.file, text: saved.text } : null,
271
+ repo_rules: rules,
246
272
  manifest: man,
247
273
  readme: saved ? undefined : rd,
248
274
  landing_copy: landing,
@@ -250,9 +276,9 @@ export function readProduct({ root = process.cwd(), sample = 30 } = {}) {
250
276
  industry: { ...guess, profile: guess.industry ? industryProfile(guess.industry, voice) : null },
251
277
  sample_lines: [...byUse, ...sentences].map((s) => ({ text: s.text, element: s.element, where: `${s.file}:${s.line}` })),
252
278
  slots, questions, ask_policy: ASK_POLICY,
253
- next: saved
279
+ next: first + (saved
254
280
  ? "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."
255
- : "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.",
281
+ : "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.` : ""),
256
282
  };
257
283
  }
258
284
 
@@ -260,13 +286,23 @@ export function readProduct({ root = process.cwd(), sample = 30 } = {}) {
260
286
  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;
261
287
  const SEV = { block: 5, warn: 3, note: 1 };
262
288
 
263
- export function auditCopy({ root = process.cwd(), strings, limit = 25, path_filter } = {}) {
264
- let list = strings?.length ? strings.map((s) => (typeof s === "string" ? { text: s, element: guessElement(s) } : { ...s, element: s.element || guessElement(s.text) }))
265
- : collectStrings(root).strings;
266
- if (path_filter) list = list.filter((s) => (s.file || "").includes(path_filter));
289
+ export function auditCopy({ root = process.cwd(), strings, limit = 25, path_filter, allow } = {}) {
290
+ const cfg = readConfig(root);
291
+ let walked = null;
292
+ let list;
293
+ if (strings?.length) list = strings.map((s) => (typeof s === "string" ? { text: s, element: guessElement(s) } : { ...s, element: s.element || guessElement(s.text) }));
294
+ else {
295
+ // a path_filter that names a folder is walked directly, so it is never lost to the file cap
296
+ const sub = path_filter && existsSync(join(root, path_filter)) ? path_filter.replace(/\/$/, "") : undefined;
297
+ walked = collectStrings(root, sub);
298
+ list = walked.strings;
299
+ }
300
+ if (path_filter) list = list.filter((s) => (s.file || "").includes(path_filter.replace(/\/$/, "")));
267
301
  const scored = list.map((s) => {
268
- const findings = lintCopy({ units: [{ element: s.element, text: s.text }] })
269
- .filter((f) => !["variable", "long", "punctuation"].includes(f.rule));
302
+ const admin = s.file && ADMIN_PATH.test(s.file);
303
+ const findings = lintCopy({ units: [{ element: s.element, text: s.text }], allow: [...cfg.allow, ...(allow || [])] })
304
+ .filter((f) => !["variable", "long", "punctuation"].includes(f.rule))
305
+ .map((f) => (admin && f.rule === "raw-code" ? { ...f, severity: "note", detail: f.detail.replace(/;.*$/, "; fine on an admin page if naming it is the fix") } : f));
270
306
  const base = findings.reduce((a, f) => a + SEV[f.severity], 0);
271
307
  const stakes = STAKES.test(s.text);
272
308
  const reach = Math.min(3, Math.log2(1 + (s.uses || 1)));
@@ -277,7 +313,11 @@ export function auditCopy({ root = process.cwd(), strings, limit = 25, path_filt
277
313
  const flagged = scored.filter((s) => s.score > 0).sort((a, b) => b.score - a.score);
278
314
  return {
279
315
  scanned: list.length, flagged: flagged.length, leave_alone: list.length - flagged.length,
316
+ ...(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.` } : {}),
317
+ ...(path_filter && !list.length ? { warning: `No user-facing strings found under '${path_filter}'. Check the path is relative to ${root}.` } : {}),
318
+ ...(cfg.error ? { config_error: cfg.error } : {}),
319
+ repo_rules: findRepoRules(root),
280
320
  worst: flagged.slice(0, limit),
281
- 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.",
321
+ 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\".",
282
322
  };
283
323
  }
package/src/reference2.js CHANGED
@@ -22,6 +22,45 @@ function load() {
22
22
  corrections = existsSync(join(ROOT, "data/corrections.json")) ? read("data/corrections.json") : [];
23
23
  failures = existsSync(join(ROOT, "data/failures.json")) ? read("data/failures.json") : [];
24
24
  catalogue = existsSync(join(ROOT, "data/catalogue.json")) ? read("data/catalogue.json") : [];
25
+ buildIndustries();
26
+ }
27
+
28
+ // ---- industry fit: a publishing app should not get hotel or fitness lines as evidence
29
+ const NEAR = {
30
+ finance: ["commerce"], commerce: ["finance", "food-delivery", "travel"], productivity: ["developer-tools", "ai-tools", "education"],
31
+ "ai-tools": ["productivity", "developer-tools"], "developer-tools": ["productivity", "ai-tools"], social: ["media-entertainment"],
32
+ "media-entertainment": ["social", "education"], education: ["media-entertainment", "productivity"], "health-fitness": [],
33
+ travel: ["mobility", "commerce"], mobility: ["travel", "food-delivery"], "food-delivery": ["commerce", "mobility"],
34
+ };
35
+ export const INDUSTRIES = Object.keys(NEAR);
36
+ let indOf = new Map(), flavour = {};
37
+ function buildIndustries() {
38
+ if (!existsSync(join(ROOT, "data/screens.json"))) return;
39
+ for (const s of read("data/screens.json")) if (s.product && s.industry) indOf.set(s.product.toLowerCase(), s.industry);
40
+ // words a line's industry uses far more than everyone else: "booking", "workout", "ride"... A line that
41
+ // carries one is about that industry's world, not a general moment, so it only travels to near industries.
42
+ const per = {}, all = new Map(); let total = 0;
43
+ const totals = {};
44
+ for (const l of lines) {
45
+ const ind = indOf.get(l.p.toLowerCase()); if (!ind || ind === "other") continue;
46
+ per[ind] ||= new Map(); totals[ind] = (totals[ind] || 0) + 1; total++;
47
+ for (const w of new Set(stems(l.t))) { per[ind].set(w, (per[ind].get(w) || 0) + 1); all.set(w, (all.get(w) || 0) + 1); }
48
+ }
49
+ for (const [ind, m] of Object.entries(per)) {
50
+ flavour[ind] = new Set([...m].filter(([w, c]) => c >= 4 && w.length > 2 && c / totals[ind] > 4 * ((all.get(w) || 0) / total)).map(([w]) => w));
51
+ }
52
+ }
53
+ const industryOf = (p) => indOf.get(String(p).toLowerCase());
54
+ function industryFit(l, want) {
55
+ if (!want) return { bonus: 0 };
56
+ const li = industryOf(l.p);
57
+ if (!li || li === "other") return { bonus: 0 };
58
+ if (li === want) return { bonus: 0.12, same: true };
59
+ if (NEAR[want]?.includes(li)) return { bonus: 0.04 };
60
+ const words = stems(l.t);
61
+ const mine = flavour[li] || new Set(), theirs = flavour[want] || new Set();
62
+ for (const w of words) if (mine.has(w) && !theirs.has(w)) return { drop: true };
63
+ return { bonus: -0.05, far: true };
25
64
  }
26
65
 
27
66
  // ---- moment match: find the catalogue moments closest to the situation, borrow their facts
@@ -120,10 +159,27 @@ function lineVec(tone) {
120
159
  }
121
160
  const dist = (a, b, w) => Math.sqrt(a.reduce((acc, x, i) => acc + (w ? w[i] : 1) * (x - b[i]) ** 2, 0));
122
161
 
123
- export function decideTone(situation) {
162
+ const TONE_FACTS = ["screen_state", "stakes", "cause", "reversibility", "user_emotion", "user_mindset", "journey_stage", "trigger", "risk"];
163
+ export function decideTone(situation = {}) {
164
+ const given = TONE_FACTS.filter((k) => situation[k] != null && situation[k] !== "" && !(Array.isArray(situation[k]) && !situation[k].length));
165
+ if (!given.length) return { error: "No facts given, so there is no tone to decide.", needs: "At least screen_state (e.g. error, success, empty, blocked) and stakes (low, medium, high). cause, reversibility and user_emotion sharpen it." };
124
166
  load();
125
- return decide(situation, toneModel, toneRules);
167
+ const d = decide(situation, toneModel, toneRules);
168
+ if (d && !d.instruction) d.instruction = FALLBACK_INSTR[situation.screen_state] || `Write it ${d.tones.join(" and ")}: say what happened and what the person can do next, in the product's own voice.`;
169
+ return d;
126
170
  }
171
+ // when no rule in the decider fires, an instruction from the screen state still beats none
172
+ const FALLBACK_INSTR = {
173
+ error: "Say plainly what didn't work and the one thing to do next; no blame, no jokes, no exclamation marks.",
174
+ blocked: "Say what's stopping them and how to get past it, or who can.",
175
+ empty: "Lead with what the person can do here, then the one action that starts it.",
176
+ loading: "Say what's happening and, if you know it, how long it takes; don't promise a result.",
177
+ success: "Confirm what happened in the headline, then give the detail they'll need later.",
178
+ partial: "Lead with what didn't work, then what did, then what to do about the rest.",
179
+ "first time": "Say what this is for in the person's terms and the first step; skip the welcome speech.",
180
+ returning: "Pick up where they left off; skip the introduction.",
181
+ offline: "Say what still works offline and what will happen when they reconnect, only if the product does it.",
182
+ };
127
183
 
128
184
  // ---- situation match: weights from HOW-IT-WORKS.md
129
185
  const STRUCT_W = { screen_state: 3, cause: 2, reversibility: 2, stakes: 2, journey_stage: 2, user_mindset: 1.5, trigger: 1, user_emotion: 0.5, audience: 0.5, surface: 0.5 };
@@ -167,7 +223,8 @@ function sim(a, b) {
167
223
  * @param {string} [a.draft] current line, when rewriting
168
224
  * @param {number} [a.target_words] length aim; defaults to the draft length
169
225
  */
170
- export function findReferenceV2({ role, element, situation, brief = {}, tone, draft, target_words, pattern, platform, limit = 3, exclude_products, exclude_patterns = [], state, qvec, min_fit = 0.35, min_situation = 0.04 }) {
226
+ export function findReferenceV2({ role, element, situation, brief = {}, tone, draft, target_words, pattern, platform, limit = 3, exclude_products, exclude_patterns = [], state, qvec, industry, min_fit = 0.4, min_situation = 0.22 }) {
227
+ if (industry && !NEAR[industry]) industry = undefined;
171
228
  load();
172
229
  if (!HAS_ENRICHED) return { error: "enriched data not installed" };
173
230
  const idfFn = buildIdf();
@@ -178,7 +235,7 @@ export function findReferenceV2({ role, element, situation, brief = {}, tone, dr
178
235
  // 1. tone target: the caller's words, or the decider's answer for the brief
179
236
  let decision = null;
180
237
  if (!tone && Object.keys(brief).some((k) => k !== "voice")) {
181
- decision = decideTone({ ...brief, role: role || undefined });
238
+ decision = decideTone({ ...brief, role: role || undefined }); if (decision?.error) decision = null;
182
239
  }
183
240
  // 1b. catalogue moment: fills gaps in the brief (next_actor, certainty, ...), adds its terms and example lines
184
241
  const mm = momentMatches(situation, brief);
@@ -186,7 +243,7 @@ export function findReferenceV2({ role, element, situation, brief = {}, tone, dr
186
243
  if (top1) {
187
244
  brief = { ...top1.s, ...brief };
188
245
  if (!tone && !decision && Object.keys(brief).some((k) => k !== "voice")) {
189
- decision = decideTone({ ...brief, role: role || undefined });
246
+ decision = decideTone({ ...brief, role: role || undefined }); if (decision?.error) decision = null;
190
247
  }
191
248
  }
192
249
  const momentTerms = stems(mm.map((x) => `${x.m.m} ${(x.m.t || []).join(" ")}`).join(" "));
@@ -208,7 +265,10 @@ export function findReferenceV2({ role, element, situation, brief = {}, tone, dr
208
265
  if (roles.length && !roles.includes(l.r)) continue;
209
266
  if (exclude.has(l.p.toLowerCase())) continue;
210
267
  if (platform && l.pl !== platform) continue;
268
+ const ifit = industryFit(l, industry);
269
+ if (ifit.drop) continue;
211
270
  if (l.q <= 1) continue;
271
+ if (!/[a-z]{2,}.*\b[a-z]{2,}|^[A-Za-z]{3,}/i.test(l.t) || /^[\d\s+\-().:\/#%$€£,]+$/.test(l.t)) continue; // numbers, codes and stray tokens aren't copy
212
272
  const n = wordCount(l.t);
213
273
  if (aim && (n > aim * 2.5 + 2 || n < aim / 2.5 - 1)) continue;
214
274
  const lv = lineVec(l.tone);
@@ -243,8 +303,10 @@ export function findReferenceV2({ role, element, situation, brief = {}, tone, dr
243
303
  const hasStruct = st.have > 0;
244
304
  const S = (hasStruct ? 0.4 : 0.1) * st.score + (hasStruct ? 0.25 : 0.55) * text + 0.15 * tonefit + 0.1 * lenfit + 0.1 * rating(l)
245
305
  + (pattern && l.pat === pattern ? 0.05 : 0) + mbonus;
246
- if (S < min_fit || text < min_situation) continue; // a weak shot is worse than none
247
- pool.push({ l, S, st, text, tonefit, n });
306
+ // industry only reorders lines that already fit; a penalty can push one under the floor, a bonus can't lift one over it
307
+ if (S + Math.min(0, ifit.bonus) < min_fit || text < min_situation) continue; // a weak shot is worse than none
308
+ if (ifit.far && text < 0.4) continue; // from an unrelated industry, only a close match on the moment earns a place
309
+ pool.push({ l, S: S + ifit.bonus, st, text, tonefit, n, same: !!ifit.same });
248
310
  }
249
311
  pool.sort((a, b) => b.S - a.S);
250
312
 
@@ -292,7 +354,7 @@ export function findReferenceV2({ role, element, situation, brief = {}, tone, dr
292
354
  }
293
355
 
294
356
  const refs = picked.map(({ l, S, st, text, tonefit, n }) => ({
295
- product: l.p, platform: l.pl, pattern: l.pat, role: l.r, text: l.t, template: l.tpl, brief: briefOf(l),
357
+ product: l.p, industry: industryOf(l.p), platform: l.pl, pattern: l.pat, role: l.r, text: l.t, template: l.tpl, brief: briefOf(l),
296
358
  moment: l.m, job: l.j, tone: l.tone, words: n,
297
359
  matched_on: st.why, scores: { fit: +S.toFixed(3), situation: +text.toFixed(2), tone: +tonefit.toFixed(2) },
298
360
  }));
@@ -325,7 +387,7 @@ export function findReferenceV2({ role, element, situation, brief = {}, tone, dr
325
387
  references: refs,
326
388
  ...(counter ? { counter_example: counter } : {}),
327
389
  ...(guardrails.length ? { guardrails, guardrails_note: "Versions written for similar moments that judges scored poorly. Do not repeat their mistakes; do not copy them either." } : {}),
328
- how_to_use: "Each reference is a pair: the brief (what the screen was for) and the line it got. Learn the mapping from brief to line; do not reuse the wording. Use references only as evidence of how others shaped this moment. Pick the one closest in situation and role. Write your line from its template: keep its structure, opening move, sentence count and length (within 30%). Before the final line, state in two short lists what you BORROWED (structure, verb, order, length) and what you CHANGED (the facts, the words, the tone). Do not copy its product facts. Then run compare_to_reference.",
390
+ how_to_use: "Each reference is a pair: the brief (what the screen was for) and the line it got, from another product. Treat them as evidence of how others shaped this moment, not as a template: in our tests, writing from the rules beat adapting the nearest line. Take what the pairs share (what the line carries, its order, its length) and write in this product's own words and voice; the repo's own rules and glossary win over anything here. Don't carry over another product's facts or claims. A reference from a different industry (see its industry field) shows a shape at most." + (industry ? "" : " Pass industry (read_product returns it) to keep references to comparable products."),
329
391
  ...(refs.length ? {} : { note: "No reference cleared the quality and situation floors. That is a result, not a failure: write from the rules and the decide_tone answer, and do not go looking for a weaker reference. Describing the moment in a different short clause may find one." }),
330
392
  };
331
393
  }