content-md 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/guide/voice.md ADDED
@@ -0,0 +1,66 @@
1
+ # UX writing: voice, workflow and limits
2
+
3
+ You are a senior content designer. You write and review the words inside software: buttons, errors, empty states, dialogs, onboarding, permissions, paywalls, checkout, notifications and AI chat interfaces. Your judgment comes from 8,876 lines of shipped interface copy from 703 iOS and web products, each labeled for its job and rated weak, solid, strong or gold (most are solid; 778 are strong or gold), and from 413 rules gathered from 16 public style guides. You can search both with your tools.
4
+
5
+ ## How you talk to the person you're working with
6
+
7
+ - Lead with the copy. The first thing they read is the recommended version, ready to paste.
8
+ - Recommend one option. Offer at most two alternatives, and only when they differ in a way that matters (a different strategy, not a synonym swap). Give each a one-line reason.
9
+ - Back your choices with evidence: name the product that does it well ("Booking.com puts the cancellation cutoff in the confirmation") or the rule and its source. Never invent an example; only cite what your tools returned.
10
+ - Be direct and warm, like a good colleague in a design review. No praise padding, no "Great question", no hedging stacks. If the draft is already good, say so in one line and stop.
11
+ - When reviewing, quote the original, name what's wrong in plain words, and show the fix. Order findings by how much they'd hurt the user.
12
+ - When something essential is missing (what happens to the user's data, the price after the trial, the reason for the permission), don't guess facts. Write the copy with a clearly marked slot like [renewal price] and ask for the one fact you need. Ask at most one question per turn; otherwise state your assumption and go.
13
+ - Match the person's vocabulary. Don't lecture them on UX writing theory unless they ask why.
14
+
15
+ ## How you work on every request
16
+
17
+ 1. Name the pattern (from the playbooks) and the pieces needed: headline, body, primary button, secondary button, helper text, and so on. If you were given a screenshot or a frame, read every piece of text on it first.
18
+ 2. Name the one job of each piece. Cut any piece that has none.
19
+ 3. Call `find_examples` for the pattern with the key nouns of the situation, and once with `quality: "weak"` when you're reviewing. Call `find_rules` when you're unsure or need to justify a call.
20
+ 4. Write the button first. It is the decision; the headline and body exist to make it obvious.
21
+ 5. Run `lint_copy` on your draft. Fix every `block` and `warn`, or say in one line why you kept it. `note`s are judgment calls.
22
+ 6. Score each string with the rubric below and rewrite anything that scores 1. Read it once more in the user's situation: stressed, in a hurry, maybe on a phone.
23
+
24
+ ## The default voice
25
+
26
+ Use this voice unless a brand profile below says otherwise. It is what the best-scored copy in the dataset has in common.
27
+
28
+ **Plain, specific, calm.** Say what happened, what it means for the person, and what they can do next.
29
+
30
+ - **Specific beats short.** Exemplar headlines run about 5 words and bodies about 13; weak ones are shorter (3 and 11) because they leave out the thing people need. Add the number, the time, the name of the thing, the consequence. Then cut every word that doesn't carry one of those.
31
+ - **Next step, always.** The most common device in exemplar copy is a stated next step, followed by a specific number and a stated consequence.
32
+ - **Sentence case** everywhere (95% of exemplars). No periods on headlines or buttons; full stops on full sentences.
33
+ - **"You" for the person, "we" for the product** when it's taking responsibility or explaining itself. Buttons and labels are impersonal ("Delete event"). Copy in the user's own voice ("I agree...", prompt chips) only for consent lines and suggestions.
34
+ - **Verb + object buttons** that match the headline's noun. Both buttons in a pair name their outcome.
35
+
36
+ **Tone moves with the moment; the voice doesn't.** Neutral is the base for every pattern in the data. Shift from it like this:
37
+
38
+ | moment | tone | why |
39
+ |---|---|---|
40
+ | empty states, onboarding, first-run | friendly, encouraging | nothing is at stake; invite action |
41
+ | success, celebration | neutral to friendly; one warm word at most | the useful part is what happens next |
42
+ | errors, offline, payment failures | neutral, direct, empathetic only when the user lost something | they want the fix, not a feeling |
43
+ | destructive actions, confirmations, cancellations | direct, concrete about loss | clarity is the kindness here |
44
+ | paywalls, checkout | neutral and exact about money | trust is the conversion lever |
45
+ | permissions | direct, benefit first, a reassurance that matches the fear | people decide in seconds |
46
+
47
+ Humor appears in about 1% of exemplar copy, only in empty states and celebrations. Never joke about loss, money, errors, health or deletion. No emoji where money, data or access is at stake.
48
+
49
+ ## Lines you don't cross, whatever the brand profile says
50
+
51
+ - Don't write manipulative copy: confirmshaming declines ("No thanks, I don't like saving money"), hidden or misleading prices, fake urgency or scarcity, pre-checked consent, or a cancel flow designed to confuse. If asked, say briefly why it backfires and write the honest version that still sells.
52
+ - Don't promise what the product can't guarantee ("never", "always", "100% secure") unless the person confirms it is literally true.
53
+ - Don't blame the user. Don't show raw error codes as the message.
54
+ - Money copy states the amount, when it's charged, whether it recurs, and how to cancel.
55
+
56
+ ## Output
57
+
58
+ For writing requests, give, in this order:
59
+ 1. **Recommended**: each piece labeled by element, ready to paste.
60
+ 2. **Why**: one or two lines, with the evidence.
61
+ 3. **Alternatives** (only if they earn it): one line each on when to pick it.
62
+ 4. **Check**: any lint findings you kept on purpose, and any [slots] that need real values.
63
+
64
+ For reviews: a short verdict line, then findings as original → problem → fix, most harmful first, then the full revised screen.
65
+
66
+
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "content-md",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.2",
4
+ "description": "UX writing tools for coding agents (Codex, Cursor, Claude Code, VS Code, Windsurf): a tone decider, playbooks for 35 UI patterns, 194 pattern rules, 413 style-guide rules and a copy linter, as an MCP server.",
5
+ "type": "module",
6
+ "bin": {
7
+ "content-md": "bin/content-md.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "data",
13
+ "guide",
14
+ "CHANGELOG.md"
15
+ ],
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "keywords": [
20
+ "mcp",
21
+ "ux-writing",
22
+ "microcopy",
23
+ "content-design",
24
+ "cursor",
25
+ "codex",
26
+ "claude-code"
27
+ ],
28
+ "license": "MIT",
29
+ "dependencies": {
30
+ "@modelcontextprotocol/sdk": "^1.32.1",
31
+ "zod": "^3.25.0"
32
+ },
33
+ "scripts": {
34
+ "test": "node --test test/*.test.mjs"
35
+ }
36
+ }
package/src/aivoice.js ADDED
@@ -0,0 +1,57 @@
1
+ // AI-voice checks: constructions that model-written interface copy uses far more often than shipped copy.
2
+ // Each check carries the rate measured on model lines vs shipped lines (eval/aivoice/measure.mjs); only checks
3
+ // where models clearly over-use the construction are kept, and the measured rates are shown in the finding,
4
+ // so the agent can weigh it instead of obeying it.
5
+ import { readFileSync } from "node:fs";
6
+
7
+ // id, regex, elements it applies to (null = all), message
8
+ export const CHECKS = [
9
+ ["hedge", /\b(may|might|could|possibly|perhaps|likely|typically|usually|generally|in most cases|in some cases)\b/i, null,
10
+ "hedge: say it plainly if it's true; if it isn't known, say what is"],
11
+ ["throat-clearing", /^(here's|here is|let's|good news|quick note|just so you know|heads up|before you (go|start|continue)|to (help|make sure|keep)|we want to|we're here to|we'd love to|we noticed)\b/i, null,
12
+ "throat-clearing opener: start with the point"],
13
+ ["explains-the-obvious", /\b(this (means|lets|helps|allows|ensures|way)|so (that )?you can|which means|so you('ll)? (always|never)|to make sure|in order to)\b/i, null,
14
+ "explains what the person can already see or infer; cut the explanation or the line"],
15
+ ["padded-reassurance", /\b(don't worry|no need to worry|rest assured|nothing to worry|we've got you|take your time|whenever you're ready|at any time|anytime|no pressure|safe and secure|you're in control|you're all set)\b/i, null,
16
+ "reassurance nobody asked for; keep it only when it answers a real fear in this moment"],
17
+ ["you-can", /\b(you can|you'll be able to|you are able to|you're able to|feel free to)\b/i, null,
18
+ "'you can' softens an instruction; use the imperative ('Add a card') or say what happens"],
19
+ ["triad", /\b[\w'-]+(?: [\w'-]+){0,2}, [\w'-]+(?: [\w'-]+){0,2},? (and|or) [\w'-]+/i, ["body", "headline", "helper-text", "toast"],
20
+ "list of three: check all three are needed here; two concrete items usually beat three"],
21
+ ["not-x-but-y", /\b(not just|not only|isn't just|aren't just|it's not about|rather than|instead of just)\b/i, null,
22
+ "'not X but Y' sets up a contrast nobody raised; say the Y"],
23
+ ["dash-aside", /\s[—–]\s|\s—|—\s|\w—\w/, null,
24
+ "dash aside: use a full stop or comma; shipped interface copy rarely uses dashes"],
25
+ ["marketing-filler", /\b(seamless(ly)?|effortless(ly)?|empower\w*|elevate\w*|unlock\w*|supercharge\w*|journey|dive in|delve|tailored|curated|hassle[- ]free|streamlin\w*|leverag\w*|robust|game[- ]chang\w*|peace of mind|all in one place|everything you need|in just a few)\b/i, null,
26
+ "marketing filler; name the actual thing it does"],
27
+ ["help-you", /\b(help(s)? you|helping you)\b/i, null,
28
+ "'helps you' is a hedge on a benefit; say the benefit ('Track every bill' not 'Helps you track your bills')"],
29
+ ["instant-promise", /\b(instantly|right away|in seconds|immediately|in no time)\b/i, null,
30
+ "speed promise: keep it only if the product guarantees it"],
31
+ ];
32
+
33
+ let RATES = {};
34
+ try { RATES = JSON.parse(readFileSync(new URL("../data/aivoice-rates.json", import.meta.url), "utf8")); } catch { /* rates optional */ }
35
+
36
+ export function aiVoice(text, element) {
37
+ const out = [];
38
+ const t = (text || "").trim();
39
+ for (const [id, re, els, msg] of CHECKS) {
40
+ const r = RATES[id];
41
+ if (r && r.keep === false) continue;
42
+ if (els && element && !els.includes(element)) continue;
43
+ const m = t.match(re);
44
+ if (!m) continue;
45
+ // "you can" that grants permission or names an option is meaning, not a tic: "You can change this later",
46
+ // "If you lose it, you can reset it". The tic is a sentence-initial "You can" standing in for an instruction.
47
+ if (id === "you-can" && !/feel free/i.test(m[0])) {
48
+ const at = m.index, after = t.slice(at + m[0].length, at + m[0].length + 40);
49
+ const sentenceStart = at === 0 || /[.!?:]\s*$/.test(t.slice(0, at));
50
+ if (!sentenceStart || /^\s+(\w+\s+){0,3}?(later|anytime|any time|always|also|still|now|change|undo|cancel|edit|switch|skip|turn|come back|return|remove|delete|leave|opt out|unsubscribe)\b/i.test(after) || /\b(later|anytime|any time|whenever)\b/i.test(t.slice(at)) || /\bif\b/i.test(t.slice(0, at))) continue;
51
+ }
52
+ const sev = r?.severity || "note";
53
+ const ev = r && r.show_rates !== false ? ` (in ${r.model_pct}% of model lines vs ${r.shipped_pct}% of shipped)` : "";
54
+ out.push({ severity: sev, rule: id === "marketing-filler" ? id : `ai-${id}`, detail: `'${m[0].trim()}': ${msg}${ev}` });
55
+ }
56
+ return out;
57
+ }
package/src/context.js ADDED
@@ -0,0 +1,143 @@
1
+ // Product context: match the product to an industry in the shipped dataset, track what is known about it as
2
+ // slots (filled from the repo or a saved brief, inferred, or unknown), decide which unknowns are worth a question,
3
+ // and save the brief into AGENTS.md / CLAUDE.md so nobody is asked twice.
4
+ // Asking policy (from clarification research, see eval/product-awareness/README.md): ask only when the answer would
5
+ // change the copy and the stakes justify interrupting; at most two questions to the person per session; for
6
+ // everything else, check the conversation and repo first, then state the assumption and go on.
7
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
8
+ import { join, dirname } from "node:path";
9
+
10
+ let IND = {};
11
+ try { IND = JSON.parse(readFileSync(new URL("../data/industries.json", import.meta.url), "utf8")); } catch { /* optional */ }
12
+
13
+ const START = "<!-- content-md:product -->", END = "<!-- /content-md:product -->";
14
+ const BRIEF_FILES = [".content-md/product.md", "AGENTS.md", "CLAUDE.md", ".github/copilot-instructions.md", ".cursor/rules/content-md-product.mdc"];
15
+
16
+ // parts: [[text, weight]]. The product's own description and UI words count more than a README written for contributors.
17
+ export function inferIndustry(parts) {
18
+ const freq = {};
19
+ for (const [text, wt] of parts) for (const w of (text || "").toLowerCase().match(/[a-z][a-z-]+/g) || []) {
20
+ const base = w.endsWith("ies") ? w.slice(0, -3) + "y" : /[^s]s$/.test(w) ? w.slice(0, -1) : w;
21
+ freq[w] = (freq[w] || 0) + wt; if (base !== w) freq[base] = (freq[base] || 0) + wt;
22
+ }
23
+ const scores = Object.entries(IND).map(([ind, p]) => [ind, p.keywords.reduce((a, k) => a + Math.min(6, freq[k] || 0), 0)]).sort((a, b) => b[1] - a[1]);
24
+ const [top, second] = scores;
25
+ if (!top || top[1] < 3) return { industry: null, confidence: "none", candidates: scores.slice(0, 3).map(([i, s]) => ({ industry: i, score: s })) };
26
+ const confidence = top[1] >= 2 * (second?.[1] || 0) && top[1] >= 8 ? "high" : top[1] >= 1.3 * (second?.[1] || 0) ? "medium" : "low";
27
+ return { industry: top[0], confidence, candidates: scores.slice(0, 3).map(([i, s]) => ({ industry: i, score: s })) };
28
+ }
29
+
30
+ export function industryProfile(ind, productVoice) {
31
+ const p = IND[ind];
32
+ if (!p) return null;
33
+ const delta = {};
34
+ if (productVoice) for (const k of ["we_pct", "you_pct", "exclamation_pct", "contractions_pct", "emoji_pct"]) {
35
+ if (productVoice[k] == null || p.voice[k] == null) continue;
36
+ const d = productVoice[k] - p.voice[k];
37
+ if (Math.abs(d) >= Math.max(3, p.voice[k] * 0.6)) delta[k] = `${productVoice[k]}% here vs ${p.voice[k]}% across ${ind} products`;
38
+ }
39
+ return { industry: ind, lines_in_dataset: p.lines, comparable_products: (p.products || []).slice(0, 8), industry_voice: p.voice,
40
+ common_tones: p.tone_families, registers: p.registers, audience: p.audience,
41
+ examples: Object.fromEntries(Object.entries(p.examples || {}).slice(0, 3).map(([k, v]) => [k, (v || []).slice(0, 2)])),
42
+ voice_differences: Object.keys(delta).length ? delta : "none worth noting",
43
+ note: "Industry norms are a baseline, not a target. Where this product's own voice differs, keep the product's voice; use the industry only to fill gaps." };
44
+ }
45
+
46
+ export function readSavedBrief(root) {
47
+ for (const f of BRIEF_FILES) {
48
+ const p = join(root, f);
49
+ if (!existsSync(p)) continue;
50
+ const s = readFileSync(p, "utf8");
51
+ const i = s.indexOf(START), j = s.indexOf(END);
52
+ if (i >= 0 && j > i) {
53
+ const body = s.slice(i + START.length, j).trim();
54
+ const fields = {};
55
+ for (const m of body.matchAll(/^- \*\*([^*]+)\*\*:\s*(.+)$/gm)) fields[m[1].trim().toLowerCase()] = m[2].trim();
56
+ return { file: f, text: body, fields };
57
+ }
58
+ }
59
+ return null;
60
+ }
61
+
62
+ // Slots the copy depends on. impact = how much a wrong guess changes the copy; ask = who can answer.
63
+ const SLOTS = [
64
+ { id: "product", label: "What the product is", impact: "high", ask: "repo" },
65
+ { id: "audience", label: "Who uses it", impact: "high", ask: "person",
66
+ q: "Who mostly uses this product?", options: ["Consumers", "Professionals at work", "Developers"], defaultFrom: (ind) => ({ professional: "Professionals at work", developer: "Developers" })[Object.keys(IND[ind]?.audience || {})[0]] || "Consumers", why: "changes vocabulary, how much is explained, and formality" },
67
+ { id: "industry", label: "Industry / niche", impact: "medium", ask: "repo" },
68
+ { id: "job", label: "Main job people hire it for", impact: "medium", ask: "repo" },
69
+ { id: "voice", label: "Voice to write in", impact: "high", ask: "person",
70
+ q: "Should new copy match the product's current voice, or are you changing it?", options: ["Match the current voice", "Make it plainer and calmer", "Make it warmer and more casual"], why: "decides whether existing lines are the model or the problem" },
71
+ { id: "terms", label: "Words the product uses for its own things", impact: "medium", ask: "repo" },
72
+ { id: "stakes", label: "What is at stake for users", impact: "medium", ask: "repo" },
73
+ { id: "constraints", label: "Legal, brand or regulatory rules", impact: "high", ask: "person", only_if: (ind) => ["finance", "health-fitness"].includes(ind),
74
+ q: "Is there approved or legal wording this copy must use (fees, risk, medical or financial claims)?", options: ["No, write freely within the facts", "Yes, I'll paste it", "Check with legal before shipping"], why: "regulated claims can't be paraphrased" },
75
+ ];
76
+
77
+ export function contextSlots({ manifest, readme, voice, industryGuess, saved }) {
78
+ const f = saved?.fields || {};
79
+ const fill = (id, value, source) => ({ value, source });
80
+ const known = {
81
+ product: f["product"] ? fill("product", f["product"], "saved brief") : manifest?.description ? fill("product", manifest.description, "repo: manifest") : readme ? fill("product", null, "repo: README (summarise it)") : null,
82
+ audience: f["audience"] ? fill("audience", f["audience"], "saved brief") : null,
83
+ industry: f["industry"] ? fill("industry", f["industry"], "saved brief") : industryGuess.industry ? fill("industry", industryGuess.industry, `inferred (${industryGuess.confidence} confidence)`) : null,
84
+ job: f["job"] ? fill("job", f["job"], "saved brief") : readme ? fill("job", null, "repo: README (summarise it)") : null,
85
+ voice: f["voice"] ? fill("voice", f["voice"], "saved brief") : null,
86
+ terms: f["terms"] ? fill("terms", f["terms"], "saved brief") : voice?.domain_words?.length ? fill("terms", voice.domain_words.slice(0, 12).join(", "), "repo: UI strings") : null,
87
+ stakes: f["stakes"] ? fill("stakes", f["stakes"], "saved brief") : industryGuess.industry ? fill("stakes", null, "infer from the industry and the strings") : null,
88
+ constraints: f["constraints"] ? fill("constraints", f["constraints"], "saved brief") : null,
89
+ };
90
+ const slots = [], questions = [];
91
+ for (const s of SLOTS) {
92
+ if (s.only_if && !s.only_if(industryGuess.industry)) continue;
93
+ const k = known[s.id];
94
+ const state = !k ? "unknown" : k.value ? (/inferred/.test(k.source) ? "inferred" : "filled") : "read-and-fill";
95
+ slots.push({ slot: s.id, label: s.label, state, value: k?.value ?? null, source: k?.source ?? null });
96
+ const lowConfIndustry = s.id === "industry" && state === "inferred" && industryGuess.confidence === "low";
97
+ if ((state === "unknown" && s.ask === "person") || lowConfIndustry) {
98
+ questions.push({ slot: s.id, impact: s.impact,
99
+ question: lowConfIndustry ? `Which best describes this product: ${industryGuess.candidates.map((c) => c.industry).join(", ")}?` : s.q,
100
+ options: lowConfIndustry ? industryGuess.candidates.map((c) => c.industry) : s.options,
101
+ default: lowConfIndustry ? industryGuess.industry : s.defaultFrom ? s.defaultFrom(industryGuess.industry) : s.options[0], why: s.why || "picks the comparable products and their norms",
102
+ first_check: "the conversation so far, AGENTS.md/CLAUDE.md, the README, docs, marketing pages and design-system notes; only ask if none of them answers it" });
103
+ }
104
+ }
105
+ const order = { high: 0, medium: 1, low: 2 };
106
+ questions.sort((a, b) => order[a.impact] - order[b.impact]);
107
+ return { slots, questions: questions.slice(0, 3) };
108
+ }
109
+
110
+ export const ASK_POLICY = "Before asking the person anything, answer each question yourself from the conversation, the saved brief, the repo and its docs. Ask the person only what is still unknown AND would change the copy for this task: at most two questions per session, high-impact first, each with options and your default. If the task is low-stakes or the person wants speed, don't ask: use the default, say in one line what you assumed, and go on. Never ask what the code already answers. After answers, call save_product_brief so later sessions start with them.";
111
+
112
+ export function saveProductBrief({ root = process.cwd(), fields, file }) {
113
+ const order = ["product", "audience", "industry", "job", "voice", "terms", "stakes", "constraints", "examples of current voice"];
114
+ const lines = order.filter((k) => fields[k]).map((k) => `- **${k[0].toUpperCase() + k.slice(1)}**: ${String(fields[k]).replace(/\n/g, " ")}`);
115
+ for (const [k, v] of Object.entries(fields)) if (!order.includes(k) && v) lines.push(`- **${k}**: ${String(v).replace(/\n/g, " ")}`);
116
+ const block = `${START}\n## Product context for interface copy\n\nWritten by the content-md tools; edit freely. Copy in this repo is written for this product and audience.\n\n${lines.join("\n")}\n${END}`;
117
+ const saved = readSavedBrief(root);
118
+ // its own file by default, so saving a brief never edits the repo's agent instructions
119
+ const target = join(root, file || saved?.file || ".content-md/product.md");
120
+ mkdirSync(dirname(target), { recursive: true });
121
+ const old = existsSync(target) ? readFileSync(target, "utf8") : "";
122
+ const next = old.includes(START) ? old.replace(new RegExp(`${START}[\\s\\S]*?${END}`), block) : (old.trimEnd() ? old.trimEnd() + "\n\n" : "") + block + "\n";
123
+ writeFileSync(target, next);
124
+ return { saved_to: target, fields: Object.keys(fields) };
125
+ }
126
+
127
+ // Elicitation where the client supports it (form mode); otherwise the questions go back to the agent to ask in chat.
128
+ export async function askPerson(server, questions) {
129
+ const caps = server.server.getClientCapabilities?.() || {};
130
+ if (!caps.elicitation) return { asked: false, reason: "This client can't show a question form. Ask these in chat, one message, options included, and say which default you'll use if there's no answer.", questions };
131
+ const properties = {}, required = [];
132
+ for (const [n, q] of questions.slice(0, 2).entries()) {
133
+ q.slot ||= `q${n + 1}`;
134
+ properties[q.slot] = { type: "string", title: q.question, ...(q.why ? { description: q.why } : {}), ...(q.options?.length >= 2 ? { enum: q.options } : {}), ...(q.default ? { default: q.default } : {}) };
135
+ }
136
+ try {
137
+ const r = await server.server.elicitInput({ mode: "form", message: "Two quick questions so the copy fits your product. Skip to use the defaults.", requestedSchema: { type: "object", properties, required } });
138
+ if (r.action === "accept") return { asked: true, answers: r.content, next: "Call save_product_brief with these answers and the rest of the brief." };
139
+ return { asked: true, answers: null, action: r.action, next: "The person skipped. Use the defaults, say so in one line, and don't ask again this session." };
140
+ } catch (e) {
141
+ return { asked: false, reason: `Form failed (${e.message}). Ask in chat instead.`, questions };
142
+ }
143
+ }
package/src/decider.js ADDED
@@ -0,0 +1,109 @@
1
+ // Tone decider. Pure function, no dependencies. Load model.json and decider.json, then call decide(situation).
2
+ // situation keys: screen_state, stakes, risk (array), cause, reversibility, user_mindset, user_emotion,
3
+ // journey_stage, trigger, audience, role, voice (a key of rules.voices or a 7-number vector).
4
+
5
+ const clamp = (x, lo = -2, hi = 2) => Math.max(lo, Math.min(hi, x));
6
+
7
+ function matches(when, s) {
8
+ return Object.entries(when).every(([k, v]) => {
9
+ const have = s[k];
10
+ const want = Array.isArray(v) ? v : [v];
11
+ if (Array.isArray(have)) return have.some((h) => want.includes(h));
12
+ return want.includes(have);
13
+ });
14
+ }
15
+
16
+ function featureEntries(s, rules) {
17
+ const out = [];
18
+ for (const [name, table] of Object.entries(rules.features)) {
19
+ const vals = name === "risk" ? (s.risk || []) : (s[name] != null ? [s[name]] : []);
20
+ for (const v of vals) if (table[v]) out.push({ feature: name, value: v, ...table[v] });
21
+ }
22
+ return out;
23
+ }
24
+
25
+ export function decide(s, model, rules) {
26
+ const axes = rules.axes, n = rules.neutral, ix = Object.fromEntries(axes.map((a, i) => [a, i]));
27
+ const entries = featureEntries(s, rules);
28
+
29
+ // 1. Moment target: neutral voice plus every feature's push.
30
+ const push = n.map(() => 0), count = n.map(() => 0);
31
+ const trace = [];
32
+ for (const e of entries) {
33
+ const d = Object.entries(e.delta);
34
+ for (const [a, v] of d) { push[ix[a]] += v; count[ix[a]] += 1; }
35
+ if (d.length || Object.keys(e.band).length) trace.push({ feature: e.feature, value: e.value, delta: e.delta, band: e.band, why: e.why || "" });
36
+ }
37
+ // Related signals overlap (a frustrated user on an error screen is one fact seen twice), so divide by sqrt(count).
38
+ const t = n.map((x, i) => clamp(x + (count[i] ? push[i] / Math.sqrt(count[i]) : 0)));
39
+
40
+ // 2. Bands: intersect every feature's fence. Each end remembers who set it.
41
+ const lo = axes.map(() => ({ v: -2, by: null })), hi = axes.map(() => ({ v: 2, by: null }));
42
+ for (const e of entries) for (const [a, [l, h]] of Object.entries(e.band)) {
43
+ const i = ix[a];
44
+ if (l != null && l > lo[i].v) lo[i] = { v: l, by: e };
45
+ if (h != null && h < hi[i].v) hi[i] = { v: h, by: e };
46
+ }
47
+ for (let i = 0; i < axes.length; i++) if (lo[i].v > hi[i].v) hi[i] = { v: lo[i].v, by: lo[i].by }; // safety end wins
48
+
49
+ // 3. Voice: the brand pulls the tone toward itself, less as stakes rise, never outside the bands.
50
+ const voiceKey = typeof s.voice === "string" ? s.voice : null;
51
+ const v = Array.isArray(s.voice) ? s.voice : (rules.voices[voiceKey || "plain"] || rules.voices.plain).vector;
52
+ let f = rules.flex[s.stakes || "low"] ?? rules.flex.low;
53
+ if (["error", "confirming"].includes(s.screen_state)) f = Math.min(f, rules.flex.medium);
54
+ const out = t.map((x, i) => clamp(x + f * (v[i] - n[i]), lo[i].v, hi[i].v));
55
+ const voicePull = t.map((x, i) => +(out[i] - x).toFixed(2));
56
+
57
+ // 4. Name it: score words by weighted distance; axes the moment moved most count most.
58
+ const w = out.map((x, i) => 1 + Math.abs(x - n[i]));
59
+ const dist = (a, b) => Math.sqrt(a.reduce((acc, x, i) => acc + w[i] * (x - b[i]) ** 2, 0));
60
+ const violation = (x) => x.reduce((acc, xi, i) => acc + Math.max(0, lo[i].v - xi, xi - hi[i].v), 0);
61
+ const W = model.words;
62
+ const ctx = rules.word_contexts || {};
63
+ const eligible = (k) => !ctx[k] || ctx[k].any.some((c) => matches(c, s));
64
+ // Prior from shipped copy: a word rarely heard in real interfaces costs a little more, so rare tones need a stronger case.
65
+ const prior = { beta: 0, cost: {}, max: 0, ...(rules.word_prior || {}) };
66
+ const usableLabels = model.label_set.filter((k) => W[k].ui_fit === "label" && eligible(k) && violation(W[k].vector) <= 0.75);
67
+ let best = null;
68
+ for (let a = 0; a < usableLabels.length; a++) for (let b = a + 1; b < usableLabels.length; b++) {
69
+ const x = W[usableLabels[a]].vector, y = W[usableLabels[b]].vector;
70
+ if (dist(x, y) < 0.75) continue; // near-synonyms add nothing
71
+ const mid = x.map((xi, i) => (xi + y[i]) / 2);
72
+ const score = dist(mid, out) + 0.25 * (dist(x, out) + dist(y, out)) / 2 + 0.3 * (violation(x) + violation(y))
73
+ + prior.beta * ((prior.cost[usableLabels[a]] ?? prior.max) + (prior.cost[usableLabels[b]] ?? prior.max));
74
+ if (!best || score < best.score) best = { score, pair: [usableLabels[a], usableLabels[b]] };
75
+ }
76
+ const tones = best.pair.sort((p, q) => dist(W[p].vector, out) - dist(W[q].vector, out));
77
+ const also = Object.keys(W).filter((k) => W[k].ui_fit === "usable" && violation(W[k].vector) <= 0.5 && !tones.includes(k))
78
+ .sort((p, q) => dist(W[p].vector, out) - dist(W[q].vector, out)).slice(0, 4);
79
+
80
+ // 5. Wrong for this moment: label tones that break a fence, and the misfires that sit closest (the tempting mistakes).
81
+ const breaks = model.label_set.filter((k) => W[k].ui_fit === "label").map((k) => {
82
+ const x = W[k].vector; let worst = null;
83
+ x.forEach((xi, i) => {
84
+ const over = Math.max(lo[i].v - xi, xi - hi[i].v);
85
+ if (over > 0 && (!worst || over > worst.over)) worst = { over, axis: axes[i], end: lo[i].v - xi > 0 ? lo[i] : hi[i] };
86
+ });
87
+ return worst ? { word: k, over: worst.over, axis: worst.axis, reason: `${worst.axis} must stay ${worst.end === lo[axes.indexOf(worst.axis)] ? "at or above" : "at or below"} ${worst.end.v} here (${worst.end.by.feature}: ${worst.end.by.value}${worst.end.by.why ? ", " + worst.end.by.why : ""})` } : null;
88
+ }).filter(Boolean).sort((p, q) => q.over - p.over).slice(0, 4);
89
+ const tempting = (rules.tempting_set || []).filter((k) => W[k])
90
+ .sort((p, q) => dist(W[p].vector, out) - dist(W[q].vector, out)).slice(0, 3)
91
+ .map((k) => ({ word: k, reason: W[k].why_avoid }));
92
+
93
+ const pick = (list, key) => (list.find((r) => matches(r.when, s)) || {})[key];
94
+ const instruction = pick(rules.instructions, "text") || null; // no rule matched: no instruction, rather than a generic one
95
+ const cap = (x) => x[0].toUpperCase() + x.slice(1);
96
+ return {
97
+ target: out.map((x) => +x.toFixed(2)),
98
+ moment_only: t.map((x) => +x.toFixed(2)),
99
+ voice_pull: voicePull, flex: f,
100
+ band: axes.map((a, i) => ({ axis: a, min: lo[i].v, max: hi[i].v, min_by: lo[i].by && `${lo[i].by.feature}: ${lo[i].by.value}`, max_by: hi[i].by && `${hi[i].by.feature}: ${hi[i].by.value}` })),
101
+ tones, also_fits: also, wrong: breaks, tempting,
102
+ instruction,
103
+ register: pick(rules.register_rules, "register"),
104
+ purpose: pick(rules.purpose_rules, "purpose"),
105
+ mood: pick(rules.mood_rules, "mood"),
106
+ brief: `${cap(tones[0])} and ${tones[1]}.` + (instruction ? ` ${instruction}` : ""),
107
+ trace,
108
+ };
109
+ }
package/src/embed.js ADDED
@@ -0,0 +1,65 @@
1
+ // Optional meaning search, OFF by default (set UXW_SEMANTIC=1 to turn it on) with a standard small model (all-MiniLM-L6-v2) through transformers.js. Without the package or the vectors the tool stays on keyword matching.
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ let tried = false;
8
+ let state; // { embedder, model, dim, ids: Map(id -> row), vecs: Int8Array } | null
9
+
10
+ export const MODEL = "Xenova/all-MiniLM-L6-v2";
11
+ export const MODEL_ID = `${MODEL}:q8`;
12
+ // transformers.js downloads the model once into its cache, then runs locally. No API key.
13
+ export async function makeEmbedder() {
14
+ const { pipeline } = await import("@huggingface/transformers");
15
+ const ex = await pipeline("feature-extraction", MODEL, { dtype: "q8" });
16
+ const run = async (t) => (await ex(t, { pooling: "mean", normalize: true })).data;
17
+ return { model: MODEL_ID, embed: run, embedMany: async (ts) => { const o = await ex(ts, { pooling: "mean", normalize: true }); const d = o.dims[1]; return ts.map((_, i) => o.data.slice(i * d, (i + 1) * d)); } };
18
+ }
19
+
20
+ async function loadMeta() {
21
+ if (state) return state;
22
+ const m = JSON.parse(readFileSync(join(ROOT, "data/emb.meta.json"), "utf8"));
23
+ const buf = readFileSync(join(ROOT, "data/emb.bin"));
24
+ state = { embedder: null, dim: m.dim, ids: new Map(m.ids.map((id, i) => [id, i])), vecs: new Int8Array(buf.buffer, buf.byteOffset, buf.length) };
25
+ return state;
26
+ }
27
+
28
+ export async function loadSemantic() {
29
+ if (state?.embedder || tried) return state ?? null;
30
+ tried = true; // one attempt per run: offline or missing package means keyword search
31
+ if (process.env.UXW_SEMANTIC !== "1") return null;
32
+ const meta = join(ROOT, "data/emb.meta.json"), bin = join(ROOT, "data/emb.bin");
33
+ if (!existsSync(meta) || !existsSync(bin)) return null;
34
+ try {
35
+ const m = JSON.parse(readFileSync(meta, "utf8"));
36
+ const embedder = await makeEmbedder();
37
+ if (embedder.model !== m.model) return null; // vectors from a different model are not comparable
38
+ const buf = readFileSync(bin);
39
+ state = { embedder, dim: m.dim, ids: new Map(m.ids.map((id, i) => [id, i])), vecs: new Int8Array(buf.buffer, buf.byteOffset, buf.length) };
40
+ } catch { /* keep keyword search */ }
41
+ return state?.embedder ? state : null;
42
+ }
43
+
44
+ // Query vectors can be precomputed (UXW_QVEC_CACHE=file.json, {text: [384 numbers]}) for offline runs and evals.
45
+ let qcache;
46
+ function cached(text) {
47
+ if (qcache === undefined) { try { qcache = process.env.UXW_QVEC_CACHE ? JSON.parse(readFileSync(process.env.UXW_QVEC_CACHE, "utf8")) : null; } catch { qcache = null; } }
48
+ return qcache?.[text] ? Float32Array.from(qcache[text]) : null;
49
+ }
50
+ export const embedQuery = async (text) => {
51
+ if (process.env.UXW_SEMANTIC !== "1" || !existsSync(join(ROOT, "data/emb.bin"))) return null;
52
+ const c = cached(text);
53
+ if (c) { await loadMeta(); return c; }
54
+ const s = await loadSemantic(); return s?.embedder ? s.embedder.embed(text) : null;
55
+ };
56
+
57
+ // cosine between a query vector and a stored row (rows are int8, scaled by 127, L2-normalised before scaling)
58
+ export function cosineTo(qvec, id) {
59
+ if (!state || !qvec) return null;
60
+ const r = state.ids.get(id);
61
+ if (r === undefined) return null;
62
+ let s = 0; const o = r * state.dim;
63
+ for (let i = 0; i < state.dim; i++) s += qvec[i] * state.vecs[o + i];
64
+ return s / 127;
65
+ }