content-md 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,400 @@
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
+ 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 };
64
+ }
65
+
66
+ // ---- moment match: find the catalogue moments closest to the situation, borrow their facts
67
+ const ctext = (m) => `${m.m} ${m.j} ${(m.t || []).join(" ")} ${(m.q || []).join(" ")}`;
68
+ function momentMatches(situation, brief) {
69
+ if (!catalogue.length) return [];
70
+ if (!cidf) {
71
+ const df = new Map();
72
+ for (const m of catalogue) for (const w of stems(ctext(m))) df.set(w, (df.get(w) || 0) + 1);
73
+ const n = catalogue.length;
74
+ cidf = (w) => Math.log((n + 1) / ((df.get(w) || 0) + 1)) + 0.1;
75
+ }
76
+ const q = stems(`${situation} ${brief.trigger || ""} ${brief.cause || ""}`);
77
+ const scored = [];
78
+ for (const m of catalogue) {
79
+ const ctx = stems(ctext(m));
80
+ let tw = 0, tmax = 0;
81
+ for (const w of q) { const v = cidf(w); tmax += v; if (ctx.has(w)) tw += v; }
82
+ let sc = tmax ? tw / tmax : 0;
83
+ const ms = m.s || {};
84
+ for (const k of ["screen_state", "next_actor", "certainty", "cause", "stakes"]) if (brief[k] && ms[k] === brief[k]) sc += 0.05;
85
+ scored.push({ m, sc });
86
+ }
87
+ scored.sort((a, b) => b.sc - a.sc);
88
+ return scored.slice(0, 2).filter((x) => x.sc >= 0.4);
89
+ }
90
+ // ---- patterns: editorial rules with a Do and an Avoid line. The Do lines are illustrations, never real product lines.
91
+ 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" };
92
+ function patternMatches(situation, roles, exclude = []) {
93
+ if (!patterns.length) return [];
94
+ const text = (p) => `${p.topic} ${p.rule} ${p.rule} ${p.do} ${p.avoid}`;
95
+ if (!pidf) {
96
+ const df = new Map();
97
+ for (const p of patterns) for (const w of stems(text(p))) df.set(w, (df.get(w) || 0) + 1);
98
+ const n = patterns.length;
99
+ pidf = (w) => Math.log((n + 1) / ((df.get(w) || 0) + 1)) + 0.1;
100
+ }
101
+ const qAll = [...stems(situation)].filter((w) => w.length > 2).sort((x, y) => pidf(y) - pidf(x)).slice(0, 12);
102
+ const q = new Set(qAll);
103
+ const topics = new Set(roles.map((r) => ROLE_TOPIC[r]).filter(Boolean));
104
+ const out = [];
105
+ for (const p of patterns) {
106
+ if (exclude.includes(p.id)) continue;
107
+ const ctx = stems(text(p));
108
+ let tw = 0, tmax = 0;
109
+ for (const w of q) { const v = pidf(w); tmax += v; if (ctx.has(w)) tw += v; }
110
+ let sc = tmax ? tw / tmax : 0;
111
+ if ([...topics].some((t) => p.topic.startsWith(t))) sc += 0.08;
112
+ out.push({ p, sc });
113
+ }
114
+ return out.sort((a, b) => b.sc - a.sc).slice(0, 2).filter((x) => x.sc >= +(process.env.UXW_PAT_MIN || 0.3));
115
+ }
116
+ const ACTION_ROLES = new Set(["primary-action", "secondary-action", "destructive-action", "dismiss-action", "navigation-link"]);
117
+
118
+ // ---- text helpers
119
+ 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(" "));
120
+ const tokens = (s) => new Set(((s || "").toLowerCase().match(/[a-z0-9']+/g) || []).filter((w) => !STOP.has(w)));
121
+ const stem = (w) => w.replace(/(ing|ed|es|s)$/, "").slice(0, 6);
122
+ const stems = (s) => new Set([...tokens(s)].map(stem));
123
+ const wordCount = (t) => (t || "").trim().split(/\s+/).filter(Boolean).length;
124
+
125
+ function buildIdf() {
126
+ if (idf) return idf;
127
+ const df = new Map();
128
+ 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);
129
+ const n = lines.length;
130
+ idf = (w) => Math.log((n + 1) / ((df.get(w) || 0) + 1)) + 0.1;
131
+ return idf;
132
+ }
133
+
134
+ // ---- role: what a line does inside its component. The old `element` maps onto roles.
135
+ const ELEMENT_ROLES = {
136
+ headline: ["screen-title", "section-heading", "dialog-title", "notification-title", "email-subject"],
137
+ subtitle: ["explanation", "instruction", "value-prop", "greeting", "status-message"],
138
+ body: ["explanation", "instruction", "value-prop", "feature-point", "status-message", "greeting", "notification-body"],
139
+ "helper-text": ["explanation", "instruction", "field-helper", "status-message", "value-prop"],
140
+ "primary-cta": ["primary-action", "destructive-action"],
141
+ "secondary-cta": ["secondary-action", "dismiss-action"],
142
+ "tertiary-link": ["navigation-link", "secondary-action", "dismiss-action"],
143
+ label: ["field-label", "option-label", "list-meta"],
144
+ placeholder: ["field-placeholder"],
145
+ "inline-error": ["field-error"],
146
+ toast: ["status-message", "field-success"],
147
+ badge: ["badge"],
148
+ "legal-fineprint": ["legal-text"],
149
+ "title-bar": ["screen-title"],
150
+ };
151
+
152
+ // ---- tone
153
+ const neutralVec = () => toneModel.neutral_voice;
154
+ function lineVec(tone) {
155
+ const W = toneModel.words;
156
+ const vs = (tone || []).map((w) => W[w]?.vector).filter(Boolean);
157
+ if (!vs.length) return null; // no audible attitude
158
+ return vs[0].map((_, i) => vs.reduce((a, v) => a + v[i], 0) / vs.length);
159
+ }
160
+ const dist = (a, b, w) => Math.sqrt(a.reduce((acc, x, i) => acc + (w ? w[i] : 1) * (x - b[i]) ** 2, 0));
161
+
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." };
166
+ load();
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;
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
+ };
183
+
184
+ // ---- situation match: weights from HOW-IT-WORKS.md
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 };
186
+ function structScore(brief, s) {
187
+ let have = 0, hit = 0;
188
+ const why = [];
189
+ for (const [k, w] of Object.entries(STRUCT_W)) {
190
+ if (!brief[k] || !s?.[k]) continue;
191
+ have += w;
192
+ if (brief[k] === s[k]) { hit += w; why.push(`${k}: ${s[k]}`); }
193
+ }
194
+ const br = brief.risk || [];
195
+ if (br.length) {
196
+ have += 1.5;
197
+ const sr = s?.risk || [];
198
+ const inter = br.filter((r) => sr.includes(r)).length;
199
+ const uni = new Set([...br, ...sr]).size || 1;
200
+ hit += 1.5 * (inter / uni);
201
+ if (inter) why.push(`risk: ${br.filter((r) => sr.includes(r)).join(", ")}`);
202
+ }
203
+ return { score: have ? hit / have : 0, have, why };
204
+ }
205
+
206
+ const rating = (l) => (l.q >= 3 ? 1 : l.q === 2 ? 0.6 : 0.1);
207
+
208
+ function sim(a, b) {
209
+ if (a.p === b.p) return 1;
210
+ const x = tokens(a.tpl), y = tokens(b.tpl);
211
+ if (!x.size || !y.size) return 0;
212
+ let n = 0; for (const w of x) if (y.has(w)) n++;
213
+ return n / (x.size + y.size - n);
214
+ }
215
+
216
+ /**
217
+ * @param {object} a
218
+ * @param {string} [a.role] copy role (screen-title, explanation, primary-action ...)
219
+ * @param {string} [a.element] old-style element; mapped to roles when role is omitted
220
+ * @param {string} a.situation the moment in plain words
221
+ * @param {object} [a.brief] screen facts: screen_state, stakes, risk[], cause, reversibility, user_mindset, user_emotion, journey_stage, trigger, audience, voice
222
+ * @param {string[]} [a.tone] wanted tone words; when omitted and a brief is given, the tone decider picks them
223
+ * @param {string} [a.draft] current line, when rewriting
224
+ * @param {number} [a.target_words] length aim; defaults to the draft length
225
+ */
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;
228
+ load();
229
+ if (!HAS_ENRICHED) return { error: "enriched data not installed" };
230
+ const idfFn = buildIdf();
231
+ const fromEnv = (process.env.UXW_EXCLUDE_PRODUCTS || "").split(",").filter(Boolean);
232
+ const exclude = new Set([...(exclude_products || []), ...fromEnv].map((p) => p.trim().toLowerCase()));
233
+ limit = Math.min(Math.max(limit, 1), +process.env.UXW_MAX_REFS || 3); // at most 3, and fewer when nothing else clears the floors
234
+
235
+ // 1. tone target: the caller's words, or the decider's answer for the brief
236
+ let decision = null;
237
+ if (!tone && Object.keys(brief).some((k) => k !== "voice")) {
238
+ decision = decideTone({ ...brief, role: role || undefined }); if (decision?.error) decision = null;
239
+ }
240
+ // 1b. catalogue moment: fills gaps in the brief (next_actor, certainty, ...), adds its terms and example lines
241
+ const mm = momentMatches(situation, brief);
242
+ const top1 = mm[0]?.m;
243
+ if (top1) {
244
+ brief = { ...top1.s, ...brief };
245
+ if (!tone && !decision && Object.keys(brief).some((k) => k !== "voice")) {
246
+ decision = decideTone({ ...brief, role: role || undefined }); if (decision?.error) decision = null;
247
+ }
248
+ }
249
+ const momentTerms = stems(mm.map((x) => `${x.m.m} ${(x.m.t || []).join(" ")}`).join(" "));
250
+ const momentExamples = new Set(mm.flatMap((x) => x.m.x || []).map((t) => t.toLowerCase()));
251
+
252
+ const toneWords = tone || (decision ? decision.tones : null);
253
+ const target = toneWords ? lineVec(toneWords) : decision ? decision.target : null;
254
+ const band = decision ? decision.band : null;
255
+
256
+ const roles = role ? [role] : element ? ELEMENT_ROLES[element] || [] : [];
257
+ const q = stems(situation);
258
+ const dq = tokens(draft);
259
+ const aim = target_words || (draft ? wordCount(draft) : null);
260
+ const axW = target ? target.map((x, i) => 1 + Math.abs(x - neutralVec()[i])) : null;
261
+
262
+ const pool = [];
263
+ for (const l of lines) {
264
+ // hard filters: role, product exclusion, platform, length, tone band, weak lines
265
+ if (roles.length && !roles.includes(l.r)) continue;
266
+ if (exclude.has(l.p.toLowerCase())) continue;
267
+ if (platform && l.pl !== platform) continue;
268
+ const ifit = industryFit(l, industry);
269
+ if (ifit.drop) continue;
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
272
+ const n = wordCount(l.t);
273
+ if (aim && (n > aim * 2.5 + 2 || n < aim / 2.5 - 1)) continue;
274
+ const lv = lineVec(l.tone);
275
+ if (band && lv) {
276
+ const bad = lv.some((x, i) => x < band[i].min - 0.75 || x > band[i].max + 0.75);
277
+ if (bad) continue;
278
+ }
279
+
280
+ const st = structScore(brief, l.s);
281
+ const ctx = stems(`${l.m} ${l.s?.task || ""} ${l.s?.situation || ""} ${l.t}`);
282
+ let tw = 0, tmax = 0;
283
+ for (const w of q) { const v = idfFn(w); tmax += v; if (ctx.has(w)) tw += v; }
284
+ let text = tmax ? tw / tmax : 0;
285
+ const cs = qvec ? cosineTo(qvec, l.id) : null;
286
+ if (cs !== null) text = 0.5 * text + 0.5 * Math.max(0, Math.min(1, (cs - 0.15) / 0.55)); // hybrid: keywords + meaning
287
+ let mbonus = 0;
288
+ if (momentExamples.has(l.t.toLowerCase())) mbonus += 0.15;
289
+ if (l.tm && mm.some((x) => x.m.id === l.tm)) mbonus += 0.15;
290
+ 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)); }
291
+ // buttons are matched on the screen they sit on, not on their own words
292
+ if (ACTION_ROLES.has(l.r) && (momentTerms.size || q.size)) {
293
+ const sc2 = stems(`${l.s?.task || ""} ${l.s?.situation || ""} ${l.m}`);
294
+ const want = new Set([...momentTerms, ...q]);
295
+ let h = 0; for (const w of sc2) if (want.has(w)) h++;
296
+ mbonus += 0.15 * Math.min(1, h / Math.max(2, Math.min(want.size, 5)));
297
+ }
298
+ 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));
299
+ const tonefit = target ? Math.exp(-(dist(lv || neutralVec(), target, axW) ** 2) / 2) : 0.5;
300
+ const lenfit = aim ? Math.max(0, 1 - Math.abs(n - aim) / Math.max(aim, 3)) : 0.5;
301
+
302
+ // weights from HOW-IT-WORKS.md; when the caller gave no brief, the structure weight moves to the text match
303
+ const hasStruct = st.have > 0;
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)
305
+ + (pattern && l.pat === pattern ? 0.05 : 0) + mbonus;
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 });
310
+ }
311
+ pool.sort((a, b) => b.S - a.S);
312
+
313
+ // 2. MMR: spread across products and phrasing
314
+ const top = pool.slice(0, 40);
315
+ const picked = [];
316
+ const seenText = new Set();
317
+ while (picked.length < limit && top.length) {
318
+ let bi = -1, bv = -Infinity;
319
+ for (let i = 0; i < top.length; i++) {
320
+ const c = top[i];
321
+ if (seenText.has(c.l.t.toLowerCase())) continue;
322
+ const pen = picked.length ? Math.max(...picked.map((p) => sim(c.l, p.l))) : 0;
323
+ const v = 0.7 * c.S - 0.3 * pen;
324
+ if (v > bv) { bv = v; bi = i; }
325
+ }
326
+ if (bi < 0) break;
327
+ const c = top.splice(bi, 1)[0];
328
+ seenText.add(c.l.t.toLowerCase());
329
+ picked.push(c);
330
+ }
331
+
332
+ // guardrails: weak versions from past evals at a similar moment (word overlap on the situation, shared piece)
333
+ const guardrails = failures.map((f) => {
334
+ const fs = stems(f.situation); let h = 0; for (const w of q) if (fs.has(w)) h++;
335
+ const share = (!roles.length || !element) ? 1 : (f.elements.includes(element) ? 1 : 0);
336
+ return { f, sc: (q.size ? h / q.size : 0) * share };
337
+ }).filter((x) => x.sc >= 0.3).sort((a, b) => b.sc - a.sc).slice(0, 2)
338
+ .map(({ f }) => ({ weak_version: f.weak_version.slice(0, 6) }));
339
+
340
+ 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();
341
+ // one weak line for the same piece, so the model sees what to avoid
342
+ const avoidTones = new Set(decision ? decision.tempting.map((t) => t.word) : []);
343
+ let counter = null;
344
+ if (roles.length && picked.length) {
345
+ let cb = -1;
346
+ for (const l of lines) {
347
+ if (l.q > 1 || !roles.includes(l.r) || exclude.has(l.p.toLowerCase())) continue;
348
+ const ctx = stems(`${l.m} ${l.s?.task || ""} ${l.s?.situation || ""}`);
349
+ let h = 0; for (const w of q) if (ctx.has(w)) h++;
350
+ const av = (l.tone || []).filter((x) => avoidTones.has(x)).length;
351
+ const sc = h + 2 * av;
352
+ 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" }; }
353
+ }
354
+ }
355
+
356
+ const refs = picked.map(({ l, S, st, text, tonefit, n }) => ({
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),
358
+ moment: l.m, job: l.j, tone: l.tone, words: n,
359
+ matched_on: st.why, scores: { fit: +S.toFixed(3), situation: +text.toFixed(2), tone: +tonefit.toFixed(2) },
360
+ }));
361
+
362
+ const pm = patternMatches(situation, roles, exclude_patterns);
363
+ const patternRules = pm.map(({ p }) => ({ id: p.id, topic: p.topic, rule: p.rule, do_illustration: p.do, avoid: p.avoid }));
364
+ 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}"` };
365
+
366
+ const esc = (x) => String(x ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;");
367
+ // correction example: a past overclaim at a similar state distinction (needs two trigger words in the situation, brief or tool state)
368
+ let correction;
369
+ { const blob = `${situation} ${JSON.stringify(brief || {})} ${JSON.stringify(state || {})}`.toLowerCase();
370
+ let bs = 0;
371
+ for (const c of corrections) { const s = c.triggers.filter((k) => blob.includes(k.toLowerCase())).length; if (s > bs) { bs = s; correction = c; } }
372
+ if (bs < 2) correction = undefined; }
373
+ const xml = refs.length || counter || pm.length || correction ? [
374
+ 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>` : "",
375
+ 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>` : "",
376
+ 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>` : "",
377
+ 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>` : "",
378
+ decision && decision.tempting.length ? `<tone_to_avoid>${decision.tempting.map((t) => t.word).join(", ")}</tone_to_avoid>` : "",
379
+ ].filter(Boolean).join("\n") : undefined;
380
+
381
+ return {
382
+ ...(xml ? { xml } : {}),
383
+ ...(patternRules.length ? { rules_matched: patternRules } : {}),
384
+ ...(correction ? { correction: { distinction: correction.distinction, wrote: correction.wrote, where: correction.where, corrected: correction.corrected, note: correction.note } } : {}),
385
+ moment: top1 ? { id: top1.id, name: top1.m, job: top1.j } : undefined,
386
+ tone: decision ? { words: decision.tones, instruction: decision.instruction, avoid: decision.tempting.map((t) => t.word), brief: decision.brief } : toneWords ? { words: toneWords } : undefined,
387
+ references: refs,
388
+ ...(counter ? { counter_example: counter } : {}),
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." } : {}),
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."),
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." }),
392
+ };
393
+ }
394
+
395
+ // Same search with meaning added. Falls back to keyword scoring when the local embedder is not installed.
396
+ export async function findReferenceV2Async(args) {
397
+ load();
398
+ const qvec = await embedQuery(`${args.situation || ""} ${args.draft || ""}`.trim());
399
+ return findReferenceV2({ ...args, qvec });
400
+ }
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
+ }