content-md 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/product.js ADDED
@@ -0,0 +1,283 @@
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 { readdirSync, readFileSync, statSync, existsSync } from "node:fs";
6
+ import { join, relative, extname, basename } from "node:path";
7
+ import { lintCopy } from "./tools.js";
8
+ import { inferIndustry, industryProfile, readSavedBrief, contextSlots, ASK_POLICY } from "./context.js";
9
+
10
+ const SKIP_DIRS = new Set(["docs", "dev-docs", "documentation", "examples", "example", "scripts", "node_modules", ".git", "dist", "build", ".next", "out", "coverage", "vendor", "Pods", ".turbo",
11
+ ".cache", "target", "__pycache__", ".venv", "venv", "public/build", "storybook-static", ".expo", "android/app/build", "DerivedData"]);
12
+ // server code: only flash/notice/alert/error strings, never tag text
13
+ const SERVER_EXT = new Set([".rb", ".py", ".ts", ".js", ".mjs", ".php", ".go", ".ex"]);
14
+ const SERVER_MSG = /\b(notice|alert|flash(?:\[:?\w+\]|\.\w+)?|error|message|msg|toast)\s*(?:=>|:|=|\()\s*(?:t\(\s*)?(["'])((?:(?!\2)[^\\\n]|\\.){4,300})\2/g;
15
+ // Client-side TS/JS (game logic, hooks, generators next to the UI): player-facing messages live here too.
16
+ const CLIENT_PATH = /(^|\/)(app|src|games?|components?|hooks?|features?|screens?|pages?|ui|views?|lib)\//;
17
+ 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.-]*$/;
18
+ 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;
19
+ function isClientScript(file) {
20
+ return /\.(ts|js|mjs)$/.test(file) && !SERVER_PATH.test(file) && (CLIENT_PATH.test(file) || /(^|\/)use[A-Z]\w*\.(ts|js)$/.test(file));
21
+ }
22
+ function extractFromClientScript(src, file) {
23
+ const out = [];
24
+ for (const m of src.matchAll(CLIENT_MSG)) {
25
+ const key = m[1] || m[4], raw = m[3] || m[6];
26
+ 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;
27
+ const t = raw.replace(/\$\{[^}]*\}/g, "{x}").replace(/\s+/g, " ").trim();
28
+ if (!/\s/.test(t) || !looksLikeCopy(t) || /^[a-z]+(\.[a-z]+)+$/i.test(t)) continue;
29
+ if (/^[A-Z]\w+: /.test(t) || /\b[a-z]+[A-Z]\w*\b|`|::|\w+\(\)/.test(t)) continue; // developer notes: "Module: ...", camelCase identifiers, code
30
+ 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 });
31
+ }
32
+ return out.map((s) => ({ ...s, element: s.element || guessElement(s.text) }));
33
+ }
34
+ function extractFromServer(src, file) {
35
+ const out = [];
36
+ const js = /\.(ts|js|mjs)$/.test(file);
37
+ if (isClientScript(file)) return extractFromClientScript(src, file);
38
+ for (const m of src.matchAll(SERVER_MSG)) {
39
+ if (js && !/^(toast|notice|flash|alert)/i.test(m[1])) continue; // in server JS/TS, error/message strings are mostly for developers
40
+ 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;
41
+ const t = m[3].replace(/\s+/g, " ").trim();
42
+ if (!/\s/.test(t) || !looksLikeCopy(t) || /#\{|%\(|\$\{/.test(t) && t.length < 12) continue;
43
+ out.push({ text: t, file, line: lineOf(src, m.index), element: /error|alert/i.test(m[1]) ? "inline-error" : "toast" });
44
+ }
45
+ return out;
46
+ }
47
+ const CODE_EXT = new Set([".tsx", ".jsx", ".vue", ".svelte", ".html", ".swift", ".kt", ".astro", ".erb", ".hbs"]);
48
+ const TEST_FILE = /(\.|_|-|\/)(test|spec|stories|story|storybookData|mock|fixture)s?\.|\/(__tests__|tests?|e2e|fixtures|mocks|stories)\//i;
49
+
50
+ function walk(root, max = 6000) {
51
+ const files = [];
52
+ const stack = [root];
53
+ while (stack.length && files.length < max) {
54
+ const dir = stack.pop();
55
+ let entries;
56
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { continue; }
57
+ for (const e of entries) {
58
+ if (e.name.startsWith(".") && e.name !== ".github") continue;
59
+ 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);
62
+ }
63
+ }
64
+ return files;
65
+ }
66
+
67
+ const readSafe = (p, cap = 400_000) => { try { const s = statSync(p); if (s.size > cap) return ""; return readFileSync(p, "utf8"); } catch { return ""; } };
68
+
69
+ // --- string extraction --------------------------------------------------------------
70
+ const PROP_ELEMENT = { title: "headline", heading: "headline", label: "label", placeholder: "placeholder", "aria-label": "label",
71
+ description: "body", subtitle: "body", message: "body", helperText: "helper-text", hint: "helper-text", tooltip: "tooltip",
72
+ emptyText: "body", confirmText: "primary-cta", cancelText: "secondary-cta", okText: "primary-cta", buttonText: "primary-cta", cta: "primary-cta", alt: null };
73
+ const looksLikeCopy = (t) => {
74
+ const s = t.trim();
75
+ if (s.length < 2 || s.length > 400) return false;
76
+ if (!/[A-Za-z]{2}/.test(s)) return false;
77
+ if (/^[a-z0-9_.-]+$/.test(s) && !/\s/.test(s)) return false; // keys, ids, class names
78
+ if (/^(https?:|\/|#|\.|@|\$\{|[A-Z_]{3,}$)/.test(s)) return false; // urls, paths, constants
79
+ if (/[{};=<>]|=>|\(\)|\bfunction\b|\bimport\b|\bconst\b/.test(s)) return false;
80
+ if (/^[a-z]+(-[a-z]+)+$/.test(s)) return false; // css-ish tokens
81
+ 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
+ if ((s.match(/%[A-Za-z-]/g) || []).length >= 2 || /:$/.test(s)) return false; // date formats, yaml parents
83
+ 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;
84
+ return true;
85
+ };
86
+ function guessElement(text, hint) {
87
+ if (hint) return hint;
88
+ const w = text.trim().split(/\s+/).length;
89
+ if (w <= 4 && !/[.!?]$/.test(text.trim())) return "label";
90
+ return "body";
91
+ }
92
+ const lineOf = (src, idx) => src.slice(0, idx).split("\n").length;
93
+
94
+ function extractFromCode(src, file) {
95
+ const out = [];
96
+ 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
+ // JSX/HTML text between tags; element from the tag name
98
+ const tagText = /<([A-Za-z][\w.]*)[^<>]*>([^<>{}]{2,400})</g;
99
+ let m;
100
+ while ((m = tagText.exec(src))) {
101
+ 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;
103
+ push(m[2], m.index + m[0].indexOf(m[2]), hint);
104
+ }
105
+ // string props: title="...", label: "...", placeholder={'...'}
106
+ const prop = /\b([A-Za-z-]+)\s*[=:]\s*\{?\s*(["'`])((?:(?!\2)[^\\\n]|\\.){2,400})\2/g;
107
+ while ((m = prop.exec(src))) {
108
+ const key = m[1];
109
+ if (!(key in PROP_ELEMENT) || PROP_ELEMENT[key] === null) continue;
110
+ push(m[3], m.index, PROP_ELEMENT[key]);
111
+ }
112
+ // toast/alert/confirm calls
113
+ 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;
114
+ while ((m = call.exec(src))) {
115
+ const fn = m[1];
116
+ if (fn === "t" && !/\s/.test(m[3])) continue; // i18n keys, not copy
117
+ push(m[3], m.index, /toast|notify/i.test(fn) ? "toast" : /error/i.test(fn) ? "inline-error" : null);
118
+ }
119
+ return out;
120
+ }
121
+
122
+ function flattenJson(obj, prefix, out) {
123
+ if (typeof obj === "string") out.push([prefix, obj]);
124
+ else if (obj && typeof obj === "object") for (const [k, v] of Object.entries(obj)) flattenJson(v, prefix ? `${prefix}.${k}` : k, out);
125
+ return out;
126
+ }
127
+ function keyElement(key) {
128
+ const k = key.toLowerCase();
129
+ if (/(button|cta|action|confirm|submit|cancel)$|\.(ok|save|delete|continue)$/.test(k)) return "primary-cta";
130
+ if (/(title|heading|header|headline)$/.test(k)) return "headline";
131
+ if (/(placeholder)$/.test(k)) return "placeholder";
132
+ if (/(label)$/.test(k)) return "label";
133
+ if (/(error|invalid|required)/.test(k)) return "inline-error";
134
+ if (/(toast|snackbar)/.test(k)) return "toast";
135
+ if (/(description|body|subtitle|message|text|empty|hint|help)$/.test(k)) return "body";
136
+ return null;
137
+ }
138
+ const LOCALE_FILE = /(^|\/)(locales?|i18n|lang|translations?|messages|strings)(\/|$)|(^|\/)(en|en-US|en_US|en-GB)\.(json|ya?ml)$|\.strings$|strings\.xml$|\.arb$/i;
139
+ function extractFromLocale(src, file) {
140
+ const out = [];
141
+ const ext = extname(file);
142
+ 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)) }); };
143
+ if (ext === ".json" || ext === ".arb") {
144
+ 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 */ }
145
+ } else if (ext === ".strings") {
146
+ for (const m of src.matchAll(/"([^"]+)"\s*=\s*"((?:[^"\\]|\\.)*)"\s*;/g)) add(m[1], m[2], lineOf(src, m.index));
147
+ } else if (ext === ".xml") {
148
+ for (const m of src.matchAll(/<string name="([^"]+)"[^>]*>([^<]+)<\/string>/g)) add(m[1], m[2], lineOf(src, m.index));
149
+ } else if (/\.ya?ml$/.test(ext)) {
150
+ for (const m of src.matchAll(/^[ \t]*([\w.-]+):[ \t]*["']?([^"'\n#]{2,400}?)["']?[ \t]*$/gm)) add(m[1], m[2], lineOf(src, m.index));
151
+ }
152
+ return out;
153
+ }
154
+
155
+ // A locale file counts as English when its path names English, or names no language at all.
156
+ const LANG_TOKEN = /(?:^|[\/._-])([a-z]{2,3})(?:[-_][A-Za-z0-9]{2,4})?(?=\.(?:json|ya?ml|arb|strings|xml|lproj)\b|\/)/g;
157
+ 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"]);
158
+ const isEnglishLocale = (f) => {
159
+ const codes = [...f.toLowerCase().matchAll(LANG_TOKEN)].map((m) => m[1]).filter((c) => !KNOWN_NOT_LANG.has(c));
160
+ const vals = f.match(/values-([a-z]{2})(?:-r[A-Z]{2})?\//);
161
+ if (vals) return vals[1] === "en";
162
+ return !codes.length || codes.includes("en");
163
+ };
164
+
165
+ export function collectStrings(root) {
166
+ const files = walk(root);
167
+ const strings = [];
168
+ for (const f of files) {
169
+ const rel = relative(root, f);
170
+ if (TEST_FILE.test("/" + rel)) continue;
171
+ 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));
173
+ else if (SERVER_EXT.has(extname(f)) && (isClientScript(rel) || !/(^|\/)(config|db|migrations?|spec|test|api)\//.test(rel))) strings.push(...extractFromServer(readSafe(f), rel));
174
+ }
175
+ // de-duplicate by text, keep first location and a count
176
+ const seen = new Map();
177
+ 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()] };
179
+ }
180
+
181
+ // --- read_product ----------------------------------------------------------------------
182
+ function manifest(root) {
183
+ const m = {};
184
+ const pj = readSafe(join(root, "package.json"));
185
+ 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 */ }
186
+ for (const f of ["pyproject.toml", "Cargo.toml", "app.json", "pubspec.yaml"]) {
187
+ const s = readSafe(join(root, f));
188
+ if (!s) continue;
189
+ const d = s.match(/description\s*[:=]\s*["']?([^"'\n]+)/); const n = s.match(/\bname\s*[:=]\s*["']?([^"'\n]+)/);
190
+ if (!m.name && n) m.name = n[1].trim(); if (!m.description && d) m.description = d[1].trim();
191
+ }
192
+ return m;
193
+ }
194
+ function readme(root) {
195
+ const f = ["README.md", "readme.md", "README.mdx", "README", "docs/README.md"].map((x) => join(root, x)).find(existsSync);
196
+ if (!f) return null;
197
+ const s = readSafe(f).replace(/<[^>]+>/g, " ").replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)/g, "")
198
+ .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);
200
+ }
201
+ const IND_KEYS = ["finance","commerce","productivity","social","ai-tools","health-fitness","media-entertainment","food-delivery","travel","education","developer-tools","mobility"];
202
+ const LANDING = /(^|\/)(index|home|landing|hero|pricing|about|features|marketing|welcome|onboarding|page)\.(tsx|jsx|vue|svelte|astro|html|mdx)$/i;
203
+
204
+ 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); };
205
+ function voiceStats(strings) {
206
+ const n = strings.length || 1;
207
+ const texts = strings.map((s) => s.text);
208
+ const pct = (f) => Math.round((100 * texts.filter(f).length) / n);
209
+ const sentences = texts.filter((t) => t.split(/\s+/).length >= 5);
210
+ const shortLabels = texts.filter((t) => t.split(/\s+/).length <= 4);
211
+ const words = texts.join(" ").toLowerCase().match(/[a-z']+/g) || [];
212
+ 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(" "));
213
+ 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(" "));
214
+ const freq = {};
215
+ for (const w of words) if (w.length > 3 && !STOP.has(w) && !UI_GENERIC.has(w)) freq[w] = (freq[w] || 0) + 1;
216
+ return {
217
+ strings: strings.length,
218
+ mean_words: +(texts.reduce((a, t) => a + t.split(/\s+/).length, 0) / n).toFixed(1),
219
+ title_case_labels_pct: Math.round((100 * shortLabels.filter(TITLE_CASE).length) / (shortLabels.length || 1)),
220
+ exclamation_pct: pct((t) => t.includes("!")),
221
+ we_pct: pct((t) => /\b(we|we're|we'll|we've|our|us)\b/i.test(t)),
222
+ 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)),
224
+ emoji_pct: pct((t) => /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(t)),
225
+ please_pct: pct((t) => /\bplease\b/i.test(t)),
226
+ domain_words: Object.entries(freq).sort((a, b) => b[1] - a[1]).slice(0, 25).map(([w]) => w),
227
+ };
228
+ }
229
+
230
+ export function readProduct({ root = process.cwd(), sample = 30 } = {}) {
231
+ if (!existsSync(root)) return { error: `No folder at ${root}. Pass the project root.` };
232
+ const { files, strings } = collectStrings(root);
233
+ const landing = strings.filter((s) => LANDING.test(s.file) && s.text.split(/\s+/).length >= 3).slice(0, 15).map((s) => s.text);
234
+ // a spread of the product's own lines: headlines, buttons and full sentences, most-used first
235
+ const pick = (f, n) => strings.filter(f).sort((a, b) => b.uses - a.uses || b.text.length - a.text.length).slice(0, n);
236
+ 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))];
237
+ const sentences = pick((s) => s.text.split(/\s+/).length >= 6 && /[.!?]$/.test(s.text) && !byUse.includes(s), sample - byUse.length);
238
+ const man = manifest(root), rd = readme(root), voice = voiceStats(strings);
239
+ const saved = readSavedBrief(root);
240
+ const guess = saved?.fields?.industry && IND_KEYS.includes(saved.fields.industry) ? { industry: saved.fields.industry, confidence: "high", candidates: [] }
241
+ : 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
+ const { slots, questions } = contextSlots({ manifest: man, readme: rd, voice, industryGuess: guess, saved });
243
+ return {
244
+ root, files_scanned: files,
245
+ saved_brief: saved ? { file: saved.file, text: saved.text } : null,
246
+ manifest: man,
247
+ readme: saved ? undefined : rd,
248
+ landing_copy: landing,
249
+ voice,
250
+ industry: { ...guess, profile: guess.industry ? industryProfile(guess.industry, voice) : null },
251
+ sample_lines: [...byUse, ...sentences].map((s) => ({ text: s.text, element: s.element, where: `${s.file}:${s.line}` })),
252
+ slots, questions, ask_policy: ASK_POLICY,
253
+ next: saved
254
+ ? "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.",
256
+ };
257
+ }
258
+
259
+ // --- audit_copy ------------------------------------------------------------------------------
260
+ 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
+ const SEV = { block: 5, warn: 3, note: 1 };
262
+
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));
267
+ 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));
270
+ const base = findings.reduce((a, f) => a + SEV[f.severity], 0);
271
+ const stakes = STAKES.test(s.text);
272
+ const reach = Math.min(3, Math.log2(1 + (s.uses || 1)));
273
+ return { text: s.text, element: s.element, where: s.file ? `${s.file}:${s.line}` : undefined, uses: s.uses,
274
+ score: base ? +(base * (stakes ? 1.5 : 1) + reach).toFixed(1) : 0, stakes: stakes ? "high" : "normal",
275
+ findings: findings.map((f) => `${f.severity} ${f.rule}: ${f.detail}`) };
276
+ });
277
+ const flagged = scored.filter((s) => s.score > 0).sort((a, b) => b.score - a.score);
278
+ return {
279
+ scanned: list.length, flagged: flagged.length, leave_alone: list.length - flagged.length,
280
+ 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.",
282
+ };
283
+ }
@@ -0,0 +1,338 @@
1
+ // find_reference v2: pick references by situation, role, length and tone, then spread them.
2
+ // Works on data/enriched.json (the enrichment pass). Pure functions, no network.
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { decide } from "./decider.js";
7
+ import { embedQuery, cosineTo } from "./embed.js";
8
+
9
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
10
+ const read = (p) => JSON.parse(readFileSync(join(ROOT, p), "utf8"));
11
+
12
+ export const HAS_ENRICHED = existsSync(join(ROOT, "data/enriched.json"));
13
+
14
+ let corrections = [], patterns, pidf, failures, lines, toneModel, toneRules, idf, catalogue, cidf, exampleSet;
15
+
16
+ function load() {
17
+ if (lines) return;
18
+ lines = HAS_ENRICHED ? read("data/enriched.json") : [];
19
+ toneModel = read("data/tone/model.json");
20
+ toneRules = read("data/tone/decider.json");
21
+ patterns = existsSync(join(ROOT, "data/patterns.json")) ? read("data/patterns.json") : [];
22
+ corrections = existsSync(join(ROOT, "data/corrections.json")) ? read("data/corrections.json") : [];
23
+ failures = existsSync(join(ROOT, "data/failures.json")) ? read("data/failures.json") : [];
24
+ catalogue = existsSync(join(ROOT, "data/catalogue.json")) ? read("data/catalogue.json") : [];
25
+ }
26
+
27
+ // ---- moment match: find the catalogue moments closest to the situation, borrow their facts
28
+ const ctext = (m) => `${m.m} ${m.j} ${(m.t || []).join(" ")} ${(m.q || []).join(" ")}`;
29
+ function momentMatches(situation, brief) {
30
+ if (!catalogue.length) return [];
31
+ if (!cidf) {
32
+ const df = new Map();
33
+ for (const m of catalogue) for (const w of stems(ctext(m))) df.set(w, (df.get(w) || 0) + 1);
34
+ const n = catalogue.length;
35
+ cidf = (w) => Math.log((n + 1) / ((df.get(w) || 0) + 1)) + 0.1;
36
+ }
37
+ const q = stems(`${situation} ${brief.trigger || ""} ${brief.cause || ""}`);
38
+ const scored = [];
39
+ for (const m of catalogue) {
40
+ const ctx = stems(ctext(m));
41
+ let tw = 0, tmax = 0;
42
+ for (const w of q) { const v = cidf(w); tmax += v; if (ctx.has(w)) tw += v; }
43
+ let sc = tmax ? tw / tmax : 0;
44
+ const ms = m.s || {};
45
+ for (const k of ["screen_state", "next_actor", "certainty", "cause", "stakes"]) if (brief[k] && ms[k] === brief[k]) sc += 0.05;
46
+ scored.push({ m, sc });
47
+ }
48
+ scored.sort((a, b) => b.sc - a.sc);
49
+ return scored.slice(0, 2).filter((x) => x.sc >= 0.4);
50
+ }
51
+ // ---- patterns: editorial rules with a Do and an Avoid line. The Do lines are illustrations, never real product lines.
52
+ const ROLE_TOPIC = { "primary-action": "Buttons", "secondary-action": "Buttons", "destructive-action": "Confirmation", "dismiss-action": "Buttons", "navigation-link": "Buttons", "field-label": "Forms", "field-helper": "Forms", "field-placeholder": "Forms", "field-error": "Validation", "field-success": "Validation", "legal-text": "Privacy", "badge": "Loading", "status-message": "Loading", "notification-title": "Notifications", "notification-body": "Notifications", "email-subject": "Notifications" };
53
+ function patternMatches(situation, roles, exclude = []) {
54
+ if (!patterns.length) return [];
55
+ const text = (p) => `${p.topic} ${p.rule} ${p.rule} ${p.do} ${p.avoid}`;
56
+ if (!pidf) {
57
+ const df = new Map();
58
+ for (const p of patterns) for (const w of stems(text(p))) df.set(w, (df.get(w) || 0) + 1);
59
+ const n = patterns.length;
60
+ pidf = (w) => Math.log((n + 1) / ((df.get(w) || 0) + 1)) + 0.1;
61
+ }
62
+ const qAll = [...stems(situation)].filter((w) => w.length > 2).sort((x, y) => pidf(y) - pidf(x)).slice(0, 12);
63
+ const q = new Set(qAll);
64
+ const topics = new Set(roles.map((r) => ROLE_TOPIC[r]).filter(Boolean));
65
+ const out = [];
66
+ for (const p of patterns) {
67
+ if (exclude.includes(p.id)) continue;
68
+ const ctx = stems(text(p));
69
+ let tw = 0, tmax = 0;
70
+ for (const w of q) { const v = pidf(w); tmax += v; if (ctx.has(w)) tw += v; }
71
+ let sc = tmax ? tw / tmax : 0;
72
+ if ([...topics].some((t) => p.topic.startsWith(t))) sc += 0.08;
73
+ out.push({ p, sc });
74
+ }
75
+ return out.sort((a, b) => b.sc - a.sc).slice(0, 2).filter((x) => x.sc >= +(process.env.UXW_PAT_MIN || 0.3));
76
+ }
77
+ const ACTION_ROLES = new Set(["primary-action", "secondary-action", "destructive-action", "dismiss-action", "navigation-link"]);
78
+
79
+ // ---- text helpers
80
+ const STOP = new Set("a an the to of and or for in on is are be your you we it this that with at by from as".split(" "));
81
+ const tokens = (s) => new Set(((s || "").toLowerCase().match(/[a-z0-9']+/g) || []).filter((w) => !STOP.has(w)));
82
+ const stem = (w) => w.replace(/(ing|ed|es|s)$/, "").slice(0, 6);
83
+ const stems = (s) => new Set([...tokens(s)].map(stem));
84
+ const wordCount = (t) => (t || "").trim().split(/\s+/).filter(Boolean).length;
85
+
86
+ function buildIdf() {
87
+ if (idf) return idf;
88
+ const df = new Map();
89
+ for (const l of lines) for (const w of stems(`${l.m} ${l.s?.task || ""} ${l.s?.situation || ""} ${l.t}`)) df.set(w, (df.get(w) || 0) + 1);
90
+ const n = lines.length;
91
+ idf = (w) => Math.log((n + 1) / ((df.get(w) || 0) + 1)) + 0.1;
92
+ return idf;
93
+ }
94
+
95
+ // ---- role: what a line does inside its component. The old `element` maps onto roles.
96
+ const ELEMENT_ROLES = {
97
+ headline: ["screen-title", "section-heading", "dialog-title", "notification-title", "email-subject"],
98
+ subtitle: ["explanation", "instruction", "value-prop", "greeting", "status-message"],
99
+ body: ["explanation", "instruction", "value-prop", "feature-point", "status-message", "greeting", "notification-body"],
100
+ "helper-text": ["explanation", "instruction", "field-helper", "status-message", "value-prop"],
101
+ "primary-cta": ["primary-action", "destructive-action"],
102
+ "secondary-cta": ["secondary-action", "dismiss-action"],
103
+ "tertiary-link": ["navigation-link", "secondary-action", "dismiss-action"],
104
+ label: ["field-label", "option-label", "list-meta"],
105
+ placeholder: ["field-placeholder"],
106
+ "inline-error": ["field-error"],
107
+ toast: ["status-message", "field-success"],
108
+ badge: ["badge"],
109
+ "legal-fineprint": ["legal-text"],
110
+ "title-bar": ["screen-title"],
111
+ };
112
+
113
+ // ---- tone
114
+ const neutralVec = () => toneModel.neutral_voice;
115
+ function lineVec(tone) {
116
+ const W = toneModel.words;
117
+ const vs = (tone || []).map((w) => W[w]?.vector).filter(Boolean);
118
+ if (!vs.length) return null; // no audible attitude
119
+ return vs[0].map((_, i) => vs.reduce((a, v) => a + v[i], 0) / vs.length);
120
+ }
121
+ const dist = (a, b, w) => Math.sqrt(a.reduce((acc, x, i) => acc + (w ? w[i] : 1) * (x - b[i]) ** 2, 0));
122
+
123
+ export function decideTone(situation) {
124
+ load();
125
+ return decide(situation, toneModel, toneRules);
126
+ }
127
+
128
+ // ---- situation match: weights from HOW-IT-WORKS.md
129
+ 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 };
130
+ function structScore(brief, s) {
131
+ let have = 0, hit = 0;
132
+ const why = [];
133
+ for (const [k, w] of Object.entries(STRUCT_W)) {
134
+ if (!brief[k] || !s?.[k]) continue;
135
+ have += w;
136
+ if (brief[k] === s[k]) { hit += w; why.push(`${k}: ${s[k]}`); }
137
+ }
138
+ const br = brief.risk || [];
139
+ if (br.length) {
140
+ have += 1.5;
141
+ const sr = s?.risk || [];
142
+ const inter = br.filter((r) => sr.includes(r)).length;
143
+ const uni = new Set([...br, ...sr]).size || 1;
144
+ hit += 1.5 * (inter / uni);
145
+ if (inter) why.push(`risk: ${br.filter((r) => sr.includes(r)).join(", ")}`);
146
+ }
147
+ return { score: have ? hit / have : 0, have, why };
148
+ }
149
+
150
+ const rating = (l) => (l.q >= 3 ? 1 : l.q === 2 ? 0.6 : 0.1);
151
+
152
+ function sim(a, b) {
153
+ if (a.p === b.p) return 1;
154
+ const x = tokens(a.tpl), y = tokens(b.tpl);
155
+ if (!x.size || !y.size) return 0;
156
+ let n = 0; for (const w of x) if (y.has(w)) n++;
157
+ return n / (x.size + y.size - n);
158
+ }
159
+
160
+ /**
161
+ * @param {object} a
162
+ * @param {string} [a.role] copy role (screen-title, explanation, primary-action ...)
163
+ * @param {string} [a.element] old-style element; mapped to roles when role is omitted
164
+ * @param {string} a.situation the moment in plain words
165
+ * @param {object} [a.brief] screen facts: screen_state, stakes, risk[], cause, reversibility, user_mindset, user_emotion, journey_stage, trigger, audience, voice
166
+ * @param {string[]} [a.tone] wanted tone words; when omitted and a brief is given, the tone decider picks them
167
+ * @param {string} [a.draft] current line, when rewriting
168
+ * @param {number} [a.target_words] length aim; defaults to the draft length
169
+ */
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 }) {
171
+ load();
172
+ if (!HAS_ENRICHED) return { error: "enriched data not installed" };
173
+ const idfFn = buildIdf();
174
+ const fromEnv = (process.env.UXW_EXCLUDE_PRODUCTS || "").split(",").filter(Boolean);
175
+ const exclude = new Set([...(exclude_products || []), ...fromEnv].map((p) => p.trim().toLowerCase()));
176
+ limit = Math.min(Math.max(limit, 1), +process.env.UXW_MAX_REFS || 3); // at most 3, and fewer when nothing else clears the floors
177
+
178
+ // 1. tone target: the caller's words, or the decider's answer for the brief
179
+ let decision = null;
180
+ if (!tone && Object.keys(brief).some((k) => k !== "voice")) {
181
+ decision = decideTone({ ...brief, role: role || undefined });
182
+ }
183
+ // 1b. catalogue moment: fills gaps in the brief (next_actor, certainty, ...), adds its terms and example lines
184
+ const mm = momentMatches(situation, brief);
185
+ const top1 = mm[0]?.m;
186
+ if (top1) {
187
+ brief = { ...top1.s, ...brief };
188
+ if (!tone && !decision && Object.keys(brief).some((k) => k !== "voice")) {
189
+ decision = decideTone({ ...brief, role: role || undefined });
190
+ }
191
+ }
192
+ const momentTerms = stems(mm.map((x) => `${x.m.m} ${(x.m.t || []).join(" ")}`).join(" "));
193
+ const momentExamples = new Set(mm.flatMap((x) => x.m.x || []).map((t) => t.toLowerCase()));
194
+
195
+ const toneWords = tone || (decision ? decision.tones : null);
196
+ const target = toneWords ? lineVec(toneWords) : decision ? decision.target : null;
197
+ const band = decision ? decision.band : null;
198
+
199
+ const roles = role ? [role] : element ? ELEMENT_ROLES[element] || [] : [];
200
+ const q = stems(situation);
201
+ const dq = tokens(draft);
202
+ const aim = target_words || (draft ? wordCount(draft) : null);
203
+ const axW = target ? target.map((x, i) => 1 + Math.abs(x - neutralVec()[i])) : null;
204
+
205
+ const pool = [];
206
+ for (const l of lines) {
207
+ // hard filters: role, product exclusion, platform, length, tone band, weak lines
208
+ if (roles.length && !roles.includes(l.r)) continue;
209
+ if (exclude.has(l.p.toLowerCase())) continue;
210
+ if (platform && l.pl !== platform) continue;
211
+ if (l.q <= 1) continue;
212
+ const n = wordCount(l.t);
213
+ if (aim && (n > aim * 2.5 + 2 || n < aim / 2.5 - 1)) continue;
214
+ const lv = lineVec(l.tone);
215
+ if (band && lv) {
216
+ const bad = lv.some((x, i) => x < band[i].min - 0.75 || x > band[i].max + 0.75);
217
+ if (bad) continue;
218
+ }
219
+
220
+ const st = structScore(brief, l.s);
221
+ const ctx = stems(`${l.m} ${l.s?.task || ""} ${l.s?.situation || ""} ${l.t}`);
222
+ let tw = 0, tmax = 0;
223
+ for (const w of q) { const v = idfFn(w); tmax += v; if (ctx.has(w)) tw += v; }
224
+ let text = tmax ? tw / tmax : 0;
225
+ const cs = qvec ? cosineTo(qvec, l.id) : null;
226
+ if (cs !== null) text = 0.5 * text + 0.5 * Math.max(0, Math.min(1, (cs - 0.15) / 0.55)); // hybrid: keywords + meaning
227
+ let mbonus = 0;
228
+ if (momentExamples.has(l.t.toLowerCase())) mbonus += 0.15;
229
+ if (l.tm && mm.some((x) => x.m.id === l.tm)) mbonus += 0.15;
230
+ if (momentTerms.size) { const lt = stems(`${l.t} ${l.m}`); let h = 0; for (const w of momentTerms) if (lt.has(w)) h++; mbonus += 0.1 * Math.min(1, h / Math.min(momentTerms.size, 4)); }
231
+ // buttons are matched on the screen they sit on, not on their own words
232
+ if (ACTION_ROLES.has(l.r) && (momentTerms.size || q.size)) {
233
+ const sc2 = stems(`${l.s?.task || ""} ${l.s?.situation || ""} ${l.m}`);
234
+ const want = new Set([...momentTerms, ...q]);
235
+ let h = 0; for (const w of sc2) if (want.has(w)) h++;
236
+ mbonus += 0.15 * Math.min(1, h / Math.max(2, Math.min(want.size, 5)));
237
+ }
238
+ if (draft) text = 0.8 * text + 0.2 * Math.min(1, [...dq].filter((w) => tokens(l.t).has(w)).length / Math.max(1, dq.size));
239
+ const tonefit = target ? Math.exp(-(dist(lv || neutralVec(), target, axW) ** 2) / 2) : 0.5;
240
+ const lenfit = aim ? Math.max(0, 1 - Math.abs(n - aim) / Math.max(aim, 3)) : 0.5;
241
+
242
+ // weights from HOW-IT-WORKS.md; when the caller gave no brief, the structure weight moves to the text match
243
+ const hasStruct = st.have > 0;
244
+ 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
+ + (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 });
248
+ }
249
+ pool.sort((a, b) => b.S - a.S);
250
+
251
+ // 2. MMR: spread across products and phrasing
252
+ const top = pool.slice(0, 40);
253
+ const picked = [];
254
+ const seenText = new Set();
255
+ while (picked.length < limit && top.length) {
256
+ let bi = -1, bv = -Infinity;
257
+ for (let i = 0; i < top.length; i++) {
258
+ const c = top[i];
259
+ if (seenText.has(c.l.t.toLowerCase())) continue;
260
+ const pen = picked.length ? Math.max(...picked.map((p) => sim(c.l, p.l))) : 0;
261
+ const v = 0.7 * c.S - 0.3 * pen;
262
+ if (v > bv) { bv = v; bi = i; }
263
+ }
264
+ if (bi < 0) break;
265
+ const c = top.splice(bi, 1)[0];
266
+ seenText.add(c.l.t.toLowerCase());
267
+ picked.push(c);
268
+ }
269
+
270
+ // guardrails: weak versions from past evals at a similar moment (word overlap on the situation, shared piece)
271
+ const guardrails = failures.map((f) => {
272
+ const fs = stems(f.situation); let h = 0; for (const w of q) if (fs.has(w)) h++;
273
+ const share = (!roles.length || !element) ? 1 : (f.elements.includes(element) ? 1 : 0);
274
+ return { f, sc: (q.size ? h / q.size : 0) * share };
275
+ }).filter((x) => x.sc >= 0.3).sort((a, b) => b.sc - a.sc).slice(0, 2)
276
+ .map(({ f }) => ({ weak_version: f.weak_version.slice(0, 6) }));
277
+
278
+ const briefOf = (l) => `${l.s?.task || "A screen"}. ${l.s?.situation || ""} Piece: ${l.r}. Stakes: ${l.s?.stakes || "unknown"}.${l.tone?.length ? " Tone: " + l.tone.join(", ") + "." : ""}`.replace(/\s+/g, " ").trim();
279
+ // one weak line for the same piece, so the model sees what to avoid
280
+ const avoidTones = new Set(decision ? decision.tempting.map((t) => t.word) : []);
281
+ let counter = null;
282
+ if (roles.length && picked.length) {
283
+ let cb = -1;
284
+ for (const l of lines) {
285
+ if (l.q > 1 || !roles.includes(l.r) || exclude.has(l.p.toLowerCase())) continue;
286
+ const ctx = stems(`${l.m} ${l.s?.task || ""} ${l.s?.situation || ""}`);
287
+ let h = 0; for (const w of q) if (ctx.has(w)) h++;
288
+ const av = (l.tone || []).filter((x) => avoidTones.has(x)).length;
289
+ const sc = h + 2 * av;
290
+ if (sc > cb) { cb = sc; counter = { line: l.t, role: l.r, brief: briefOf(l), why: av ? `its tone (${(l.tone || []).filter((x) => avoidTones.has(x)).join(", ")}) is wrong for this kind of moment` : "labelers rated it weak: it does not do its job for the person" }; }
291
+ }
292
+ }
293
+
294
+ 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),
296
+ moment: l.m, job: l.j, tone: l.tone, words: n,
297
+ matched_on: st.why, scores: { fit: +S.toFixed(3), situation: +text.toFixed(2), tone: +tonefit.toFixed(2) },
298
+ }));
299
+
300
+ const pm = patternMatches(situation, roles, exclude_patterns);
301
+ const patternRules = pm.map(({ p }) => ({ id: p.id, topic: p.topic, rule: p.rule, do_illustration: p.do, avoid: p.avoid }));
302
+ if (pm.length) counter = { line: pm[0].p.avoid, role: roles[0] || "line", brief: `Rule: ${pm[0].p.rule}.`, why: `it breaks the rule "${pm[0].p.rule}"` };
303
+
304
+ const esc = (x) => String(x ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;");
305
+ // correction example: a past overclaim at a similar state distinction (needs two trigger words in the situation, brief or tool state)
306
+ let correction;
307
+ { const blob = `${situation} ${JSON.stringify(brief || {})} ${JSON.stringify(state || {})}`.toLowerCase();
308
+ let bs = 0;
309
+ for (const c of corrections) { const s = c.triggers.filter((k) => blob.includes(k.toLowerCase())).length; if (s > bs) { bs = s; correction = c; } }
310
+ if (bs < 2) correction = undefined; }
311
+ const xml = refs.length || counter || pm.length || correction ? [
312
+ pm.length ? `<rules_matched note="The do lines are original illustrations of the rule, not real product lines.">\n${pm.map(({ p }) => `<rule>${esc(p.rule)}<do_illustration>${esc(p.do)}</do_illustration></rule>`).join("\n")}\n</rules_matched>` : "",
313
+ refs.length ? `<examples>\n${refs.map((r) => `<example piece="${r.role}"><brief>${esc(r.brief)}</brief><line>${esc(r.text)}</line></example>`).join("\n")}\n</examples>` : "",
314
+ counter ? `<counter_examples>\n<counter_example piece="${counter.role}"><brief>${esc(counter.brief)}</brief><line>${esc(counter.line)}</line><why_weak>${esc(counter.why)}</why_weak></counter_example>\n</counter_examples>` : "",
315
+ correction ? `<correction_example distinction="${esc(correction.distinction)}">A writer saw: ${esc(correction.saw.brief)} State: ${esc(JSON.stringify(correction.saw.state))}\nThey wrote: \"${esc(correction.wrote)}\"\nWhere it overclaimed: ${esc(correction.where)}\nCorrected: \"${esc(correction.corrected)}\"\nWhat the evidence permits: ${esc(correction.note)}</correction_example>` : "",
316
+ decision && decision.tempting.length ? `<tone_to_avoid>${decision.tempting.map((t) => t.word).join(", ")}</tone_to_avoid>` : "",
317
+ ].filter(Boolean).join("\n") : undefined;
318
+
319
+ return {
320
+ ...(xml ? { xml } : {}),
321
+ ...(patternRules.length ? { rules_matched: patternRules } : {}),
322
+ ...(correction ? { correction: { distinction: correction.distinction, wrote: correction.wrote, where: correction.where, corrected: correction.corrected, note: correction.note } } : {}),
323
+ moment: top1 ? { id: top1.id, name: top1.m, job: top1.j } : undefined,
324
+ tone: decision ? { words: decision.tones, instruction: decision.instruction, avoid: decision.tempting.map((t) => t.word), brief: decision.brief } : toneWords ? { words: toneWords } : undefined,
325
+ references: refs,
326
+ ...(counter ? { counter_example: counter } : {}),
327
+ ...(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.",
329
+ ...(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
+ };
331
+ }
332
+
333
+ // Same search with meaning added. Falls back to keyword scoring when the local embedder is not installed.
334
+ export async function findReferenceV2Async(args) {
335
+ load();
336
+ const qvec = await embedQuery(`${args.situation || ""} ${args.draft || ""}`.trim());
337
+ return findReferenceV2({ ...args, qvec });
338
+ }