content-md 1.0.0 → 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/CHANGELOG.md +79 -0
- package/README.md +38 -8
- package/bin/content-md.js +15 -2
- package/data/meta.json +1 -60
- package/guide/SKILL.md +4 -2
- package/guide/rubric.md +0 -9
- package/guide/rules.md +4 -2
- package/guide/voice.md +1 -1
- package/package.json +6 -5
- package/src/aivoice.js +7 -0
- package/src/context.js +12 -8
- package/src/init.js +103 -29
- package/src/product.js +58 -26
- package/src/reference2.js +71 -9
- package/src/repo.js +63 -0
- package/src/server.js +42 -15
- package/src/tools.js +98 -31
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
|
|
2
|
-
//
|
|
3
|
-
|
|
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
|
|
11
|
-
//
|
|
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",
|
|
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(
|
|
23
|
-
if (existsSync(join(cwd, ".claude")) || existsSync(join(cwd, "CLAUDE.md")) || existsSync(join(
|
|
24
|
-
if (existsSync(join(cwd, "AGENTS.md")) || existsSync(
|
|
25
|
-
if (existsSync(join(cwd, ".vscode"))) found.push("vscode");
|
|
26
|
-
if (existsSync(join(
|
|
27
|
-
return 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`);
|
|
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
|
-
|
|
35
|
-
|
|
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
|
-
|
|
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,84 @@ 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${
|
|
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
|
-
|
|
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
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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"),
|
|
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"),
|
|
121
|
+
upsertBlock(join(cwd, ".windsurfrules"), shared);
|
|
88
122
|
}
|
|
89
123
|
}
|
|
90
124
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
if (
|
|
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.");
|
|
94
168
|
}
|
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,36 @@ 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;
|
|
48
52
|
const TEST_FILE = /(\.|_|-|\/)(test|spec|stories|story|storybookData|mock|fixture)s?\.|\/(__tests__|tests?|e2e|fixtures|mocks|stories)\//i;
|
|
49
53
|
|
|
50
|
-
|
|
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) {
|
|
51
59
|
const files = [];
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
60
|
+
const queue = [root];
|
|
61
|
+
let truncated = false, head = 0;
|
|
62
|
+
while (head < queue.length) {
|
|
63
|
+
const dir = queue[head++];
|
|
55
64
|
let entries;
|
|
56
65
|
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { continue; }
|
|
57
66
|
for (const e of entries) {
|
|
58
67
|
if (e.name.startsWith(".") && e.name !== ".github") continue;
|
|
59
68
|
const p = join(dir, e.name);
|
|
60
|
-
if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name))
|
|
61
|
-
else if (e.isFile()
|
|
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
|
+
}
|
|
62
74
|
}
|
|
75
|
+
if (truncated) break;
|
|
63
76
|
}
|
|
77
|
+
files.truncated = truncated;
|
|
78
|
+
files.unvisited = truncated ? queue.slice(head).map((d) => relative(root, d)).slice(0, 20) : [];
|
|
64
79
|
return files;
|
|
65
80
|
}
|
|
66
81
|
|
|
@@ -99,7 +114,7 @@ function extractFromCode(src, file) {
|
|
|
99
114
|
let m;
|
|
100
115
|
while ((m = tagText.exec(src))) {
|
|
101
116
|
const tag = m[1].toLowerCase();
|
|
102
|
-
const hint = /button|cta
|
|
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;
|
|
103
118
|
push(m[2], m.index + m[0].indexOf(m[2]), hint);
|
|
104
119
|
}
|
|
105
120
|
// string props: title="...", label: "...", placeholder={'...'}
|
|
@@ -162,20 +177,21 @@ const isEnglishLocale = (f) => {
|
|
|
162
177
|
return !codes.length || codes.includes("en");
|
|
163
178
|
};
|
|
164
179
|
|
|
165
|
-
export function collectStrings(root) {
|
|
166
|
-
const files = walk(root);
|
|
180
|
+
export function collectStrings(root, sub) {
|
|
181
|
+
const files = walk(sub ? join(root, sub) : root);
|
|
167
182
|
const strings = [];
|
|
183
|
+
const ignore = readConfig(root).ignore.map((g) => g.replace(/^\.\//, ""));
|
|
168
184
|
for (const f of files) {
|
|
169
185
|
const rel = relative(root, f);
|
|
170
|
-
if (TEST_FILE.test("/" + rel)) continue;
|
|
186
|
+
if (TEST_FILE.test("/" + rel) || VENDOR_PATH.test("/" + rel) || ignore.some((g) => rel.startsWith(g))) continue;
|
|
171
187
|
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(
|
|
188
|
+
if (CODE_EXT.has(extname(f))) { const src = readSafe(f); if (!VENDOR_HEAD.test(src.slice(0, 400))) strings.push(...extractFromCode(src, rel)); }
|
|
173
189
|
else if (SERVER_EXT.has(extname(f)) && (isClientScript(rel) || !/(^|\/)(config|db|migrations?|spec|test|api)\//.test(rel))) strings.push(...extractFromServer(readSafe(f), rel));
|
|
174
190
|
}
|
|
175
191
|
// de-duplicate by text, keep first location and a count
|
|
176
192
|
const seen = new Map();
|
|
177
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 }); }
|
|
178
|
-
return { files: files.length, strings: [...seen.values()] };
|
|
194
|
+
return { files: files.length, strings: [...seen.values()], truncated: files.truncated, unvisited: files.unvisited };
|
|
179
195
|
}
|
|
180
196
|
|
|
181
197
|
// --- read_product ----------------------------------------------------------------------
|
|
@@ -196,7 +212,7 @@ function readme(root) {
|
|
|
196
212
|
if (!f) return null;
|
|
197
213
|
const s = readSafe(f).replace(/<[^>]+>/g, " ").replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)/g, "")
|
|
198
214
|
.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,
|
|
215
|
+
return s.slice(0, 1200);
|
|
200
216
|
}
|
|
201
217
|
const IND_KEYS = ["finance","commerce","productivity","social","ai-tools","health-fitness","media-entertainment","food-delivery","travel","education","developer-tools","mobility"];
|
|
202
218
|
const LANDING = /(^|\/)(index|home|landing|hero|pricing|about|features|marketing|welcome|onboarding|page)\.(tsx|jsx|vue|svelte|astro|html|mdx)$/i;
|
|
@@ -220,16 +236,16 @@ function voiceStats(strings) {
|
|
|
220
236
|
exclamation_pct: pct((t) => t.includes("!")),
|
|
221
237
|
we_pct: pct((t) => /\b(we|we're|we'll|we've|our|us)\b/i.test(t)),
|
|
222
238
|
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)),
|
|
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)),
|
|
224
240
|
emoji_pct: pct((t) => /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(t)),
|
|
225
241
|
please_pct: pct((t) => /\bplease\b/i.test(t)),
|
|
226
242
|
domain_words: Object.entries(freq).sort((a, b) => b[1] - a[1]).slice(0, 25).map(([w]) => w),
|
|
227
243
|
};
|
|
228
244
|
}
|
|
229
245
|
|
|
230
|
-
export function readProduct({ root = process.cwd(), sample =
|
|
246
|
+
export function readProduct({ root = process.cwd(), sample = 18 } = {}) {
|
|
231
247
|
if (!existsSync(root)) return { error: `No folder at ${root}. Pass the project root.` };
|
|
232
|
-
const { files, strings } = collectStrings(root);
|
|
248
|
+
const { files, strings, truncated, unvisited } = collectStrings(root);
|
|
233
249
|
const landing = strings.filter((s) => LANDING.test(s.file) && s.text.split(/\s+/).length >= 3).slice(0, 15).map((s) => s.text);
|
|
234
250
|
// a spread of the product's own lines: headlines, buttons and full sentences, most-used first
|
|
235
251
|
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 +253,16 @@ export function readProduct({ root = process.cwd(), sample = 30 } = {}) {
|
|
|
237
253
|
const sentences = pick((s) => s.text.split(/\s+/).length >= 6 && /[.!?]$/.test(s.text) && !byUse.includes(s), sample - byUse.length);
|
|
238
254
|
const man = manifest(root), rd = readme(root), voice = voiceStats(strings);
|
|
239
255
|
const saved = readSavedBrief(root);
|
|
240
|
-
const
|
|
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: [] }
|
|
241
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]]);
|
|
242
261
|
const { slots, questions } = contextSlots({ manifest: man, readme: rd, voice, industryGuess: guess, saved });
|
|
243
262
|
return {
|
|
244
|
-
root, files_scanned: files,
|
|
263
|
+
root, files_scanned: files, ...(truncated ? { truncated: true, warning: `Stopped after ${MAX_FILES} files; not read: ${unvisited.join(", ")}` } : {}),
|
|
245
264
|
saved_brief: saved ? { file: saved.file, text: saved.text } : null,
|
|
265
|
+
repo_rules: rules,
|
|
246
266
|
manifest: man,
|
|
247
267
|
readme: saved ? undefined : rd,
|
|
248
268
|
landing_copy: landing,
|
|
@@ -250,9 +270,9 @@ export function readProduct({ root = process.cwd(), sample = 30 } = {}) {
|
|
|
250
270
|
industry: { ...guess, profile: guess.industry ? industryProfile(guess.industry, voice) : null },
|
|
251
271
|
sample_lines: [...byUse, ...sentences].map((s) => ({ text: s.text, element: s.element, where: `${s.file}:${s.line}` })),
|
|
252
272
|
slots, questions, ask_policy: ASK_POLICY,
|
|
253
|
-
next: saved
|
|
273
|
+
next: first + (saved
|
|
254
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."
|
|
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.",
|
|
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.` : ""),
|
|
256
276
|
};
|
|
257
277
|
}
|
|
258
278
|
|
|
@@ -260,12 +280,20 @@ export function readProduct({ root = process.cwd(), sample = 30 } = {}) {
|
|
|
260
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;
|
|
261
281
|
const SEV = { block: 5, warn: 3, note: 1 };
|
|
262
282
|
|
|
263
|
-
export function auditCopy({ root = process.cwd(), strings, limit = 25, path_filter } = {}) {
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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(/\/$/, "")));
|
|
267
295
|
const scored = list.map((s) => {
|
|
268
|
-
const findings = lintCopy({ units: [{ element: s.element, text: s.text }] })
|
|
296
|
+
const findings = lintCopy({ units: [{ element: s.element, text: s.text }], allow: [...cfg.allow, ...(allow || [])] })
|
|
269
297
|
.filter((f) => !["variable", "long", "punctuation"].includes(f.rule));
|
|
270
298
|
const base = findings.reduce((a, f) => a + SEV[f.severity], 0);
|
|
271
299
|
const stakes = STAKES.test(s.text);
|
|
@@ -277,7 +305,11 @@ export function auditCopy({ root = process.cwd(), strings, limit = 25, path_filt
|
|
|
277
305
|
const flagged = scored.filter((s) => s.score > 0).sort((a, b) => b.score - a.score);
|
|
278
306
|
return {
|
|
279
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),
|
|
280
312
|
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.",
|
|
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\".",
|
|
282
314
|
};
|
|
283
315
|
}
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
247
|
-
|
|
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
|
|
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
|
}
|
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
|
+
}
|