content-md 1.0.8 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.9
4
+
5
+ - **Bare `npx content-md init` sets something up.** In a repo with no tool config, 1.0.8 wrote nothing. Now it asks which tools you use, sets up the agent that's running it (Claude Code, Cursor or Codex), or falls back to Claude Code, Cursor and Codex, and says which.
6
+ - **Anonymous usage stats, on by default.** Which tool ran, the kind of screen, the stakes, whether lint flagged anything and which rules fired, the agent, version, OS and a random install id. Never copy, code, paths, repo or product names. Announced on first run and in `init`. Off with `npx content-md telemetry off`, `DO_NOT_TRACK=1` or `CONTENT_MD_TELEMETRY=0`, and always off in CI. `CONTENT_MD_TELEMETRY_DEBUG=1` prints events instead of sending them.
7
+ - **Example sharing, off unless you say yes.** `init` asks once. With it on, `lint_copy` sends the copy it checked, before and after, scrubbed of emails, links, long numbers, paths and keys.
8
+ - **`npx content-md feedback`** opens a prefilled GitHub issue. You choose whether to paste an example.
9
+
3
10
  ## 1.0.8
4
11
 
5
12
  - **The product's own style.** `read_product` now reports the product's own style habits (contractions, "you", full stops, case, length, per moment) from its strings, and `lint_copy` flags departures from them in a repo. New clause-join warning (a colon or semicolon stitching two clauses in short UI copy) and a trailing-"yet" note.
package/README.md CHANGED
@@ -46,7 +46,7 @@ content-md lint '{"pattern":"error","units":[{"element":"headline","text":"Error
46
46
 
47
47
  ```sh
48
48
  cd your-app
49
- npx content-md init # uses the tools this repo already has config for; or name them: --cursor --claude --codex --vscode --windsurf, or --all
49
+ npx content-md init # uses the tools this repo already has config for, or asks; or name them: --cursor --claude --codex --vscode --windsurf, or --all
50
50
  ```
51
51
 
52
52
  Restart the editor or agent afterwards. `init` is safe to run again, and `--dry-run` shows what it would write.
@@ -57,7 +57,7 @@ What it does, and what it leaves alone:
57
57
  - **It pins the version.** The server entry is `npx -y content-md@<version>`, so your editor never picks up a new release on its own. Run `init` again to move to a newer one.
58
58
  - **Shared instruction files get a short pointer, not a rulebook.** `AGENTS.md`, `.github/copilot-instructions.md` and `.windsurfrules` get a few lines in a marked block: when to call the tools, and that your repo's own rules win. `--rules` puts the full method there instead. Cursor and Claude Code get the full method in their own files (`.cursor/rules/content-md.mdc`, `.claude/skills/content-md/SKILL.md`), which load only for copy work.
59
59
  - **Your repo's copy rules come first.** `init` looks for them (copy, voice, tone or glossary sections in `AGENTS.md` or `CLAUDE.md`, and files like `docs/glossary.md` or `content-style.md`) and names them in what it writes, so the agent reads them and follows them wherever content-md differs.
60
- - **It only sets up tools the repo already uses.** With no flags it looks for `.cursor`, `.claude`, `CLAUDE.md`, `AGENTS.md`, `.vscode` and `.windsurfrules` in the repo. If it finds none, it writes nothing and tells you which flag to pass.
60
+ - **It sets up the tools the repo already uses.** With no flags it looks for `.cursor`, `.claude`, `CLAUDE.md`, `AGENTS.md`, `.vscode` and `.windsurfrules` in the repo. If it finds none, it asks which tools you use. When an agent runs it, it sets up that agent (Claude Code, Cursor or Codex, from their environment). Otherwise it sets up Claude Code, Cursor and Codex, and says so.
61
61
  - **The product brief gets its own file.** `save_product_brief` writes `.content-md/product.md`, not your agent instructions.
62
62
  - **Claude Code defers MCP tools by default.** It keeps them behind tool search, and an agent that doesn't know they exist never loads them. So `init --claude` also adds a pointer to `CLAUDE.md` that names the tools and how to load them. To load every MCP tool up front instead, start Claude Code with `ENABLE_TOOL_SEARCH=false`.
63
63
  - **`npx content-md remove`** takes out everything `init` added. Add `--global` to clean the home-folder entries too.
@@ -70,6 +70,35 @@ What it does, and what it leaves alone:
70
70
  | VS Code (Copilot) | `.vscode/mcp.json` | `.github/copilot-instructions.md` (marked block) |
71
71
  | Windsurf | `~/.codeium/windsurf/mcp_config.json` (with `--global`) | `.windsurfrules` (marked block) |
72
72
 
73
+ ## Usage stats
74
+
75
+ content-md sends anonymous usage stats, the way Next.js and Astro do, so it's possible to see which tools people use and where the checks get in the way. It tells you the first time it runs.
76
+
77
+ What it sends: which tool ran, how long it took and whether it worked; the kind of screen and the stakes, from content-md's own lists; for `lint_copy`, how many pieces of copy, whether it flagged anything and which content-md rules fired; the content-md version, the agent (Claude Code, Cursor, Codex...), your OS and Node version; and a random install id made on your machine.
78
+
79
+ What it never sends: your copy, your code, file names or paths, repo or product names, or anything from your product brief. The collector at agarau.dev doesn't pass on or store your IP address. Details: https://agarau.dev/content-md#usage-stats
80
+
81
+ Turn it off with any of these. It's always off in CI.
82
+
83
+ ```sh
84
+ npx content-md telemetry off # stored in ~/.config/content-md/telemetry.json
85
+ export DO_NOT_TRACK=1
86
+ export CONTENT_MD_TELEMETRY=0
87
+ ```
88
+
89
+ `npx content-md telemetry` shows the current setting. `CONTENT_MD_TELEMETRY_DEBUG=1` prints each event to stderr instead of sending it, so you can see exactly what would go.
90
+
91
+ **Example sharing** is separate and off unless you say yes. `init` asks once. With it on, `lint_copy` also sends the copy it checked, before and after, with emails, links, long numbers, paths and keys removed. Turn it on or off with `npx content-md telemetry examples on` / `off`.
92
+
93
+ ## Feedback
94
+
95
+ ```sh
96
+ npx content-md feedback "lint flagged a button that was fine"
97
+ npx content-md feedback "..." --example "Save changes"
98
+ ```
99
+
100
+ It opens a GitHub issue with your content-md version, Node version and OS filled in. Run it with no message to be asked for one, and for an example you can paste if you want to. Nothing is sent until you submit the issue, and issues are public.
101
+
73
102
  ### Tuning it to your repo
74
103
 
75
104
  Put a `.content-md.json` at the repo root to tell the tools what your product has already decided:
package/bin/content-md.js CHANGED
@@ -1,9 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  const [cmd, ...rest] = process.argv.slice(2);
3
3
 
4
+ const cli = async (event, props) => { const t = await import("../src/telemetry.js"); t.noticeOnce(process.stderr); t.track(event, props); await t.flush(); };
5
+
4
6
  if (cmd === "init") {
5
- const { init } = await import("../src/init.js");
6
- init(rest);
7
+ const { initCli } = await import("../src/init.js");
8
+ await initCli(rest);
9
+ } else if (cmd === "telemetry") {
10
+ const { telemetryCommand } = await import("../src/telemetry.js");
11
+ telemetryCommand(rest);
12
+ } else if (cmd === "feedback") {
13
+ const { feedback } = await import("../src/feedback.js");
14
+ await feedback(rest);
15
+ await cli("cli", { command: "feedback" });
7
16
  } else if (cmd === "remove" || cmd === "uninstall") {
8
17
  const { remove } = await import("../src/init.js");
9
18
  remove(rest);
@@ -11,15 +20,18 @@ if (cmd === "init") {
11
20
  // npx content-md audit [path_filter] : the worst user-facing lines in this repo
12
21
  const { auditCopy } = await import("../src/product.js");
13
22
  console.log(JSON.stringify(auditCopy({ path_filter: rest[0] }), null, 1));
23
+ await cli("cli", { command: "audit" });
14
24
  } else if (cmd === "lint") {
15
25
  // npx content-md lint '{"pattern":"error","units":[{"element":"headline","text":"Error"}]}'
16
26
  const { lintCopy } = await import("../src/tools.js");
17
27
  console.log(JSON.stringify(lintCopy(JSON.parse(rest.join(" "))), null, 1));
28
+ await cli("cli", { command: "lint" });
18
29
  } else if (cmd === "--help" || cmd === "-h" || cmd === "help") {
19
30
  console.log(`content-md: UX writing tools for coding agents, a tone decider, pattern playbooks, style-guide rules and a copy linter.
20
31
 
21
32
  npx content-md init [--cursor --claude --codex --vscode --windsurf | --all] [--rules] [--global] [--dry-run]
22
- register the MCP server with your tools and add a short pointer (with no flag, it uses the tools this repo already has config for, and writes nothing if it finds none).
33
+ register the MCP server with your tools and add a short pointer. With no flag it uses the tools this repo
34
+ already has config for; if there are none, it asks (or sets up Claude Code, Cursor and Codex).
23
35
  Writes only inside this repo unless you pass --global. --rules puts the full method
24
36
  in AGENTS.md and the other shared files instead of the pointer.
25
37
  npx content-md remove [--global] [--dry-run]
@@ -29,7 +41,12 @@ if (cmd === "init") {
29
41
  npx content-md
30
42
  run the MCP server over stdio (this is what your editor calls)
31
43
  npx content-md lint '<json>'
32
- lint one screen: {"pattern":"error","units":[{"element":"headline","text":"..."}]}`);
44
+ lint one screen: {"pattern":"error","units":[{"element":"headline","text":"..."}]}
45
+ npx content-md feedback ["message"] [--example "the copy"]
46
+ open a GitHub issue with your version filled in; attach an example only if you want to
47
+ npx content-md telemetry [status | off | on | examples on | examples off]
48
+ anonymous usage stats are on by default and never include your copy or code.
49
+ Also off with DO_NOT_TRACK=1 or CONTENT_MD_TELEMETRY=0, and always off in CI.`);
33
50
  } else {
34
51
  const { serve } = await import("../src/server.js");
35
52
  await serve();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "content-md",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
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
5
  "type": "module",
6
6
  "bin": {
@@ -31,6 +31,6 @@
31
31
  "zod": "^3.25.0"
32
32
  },
33
33
  "scripts": {
34
- "test": "node --test test/*.test.mjs"
34
+ "test": "CONTENT_MD_TELEMETRY=0 node --test test/*.test.mjs"
35
35
  }
36
36
  }
@@ -0,0 +1,52 @@
1
+ // `npx content-md feedback`: opens a GitHub issue with the version and platform filled in. The person writes the
2
+ // message, and attaches one example of copy only if they choose to. Nothing is sent until they press Submit on GitHub.
3
+ import { readFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { spawn } from "node:child_process";
7
+ import { createInterface } from "node:readline/promises";
8
+
9
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
10
+ const PKG = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
11
+ export const ISSUES = "https://github.com/adedayoagarau/content.md/issues/new";
12
+
13
+ const flag = (argv, name) => { const i = argv.indexOf(name); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[i + 1] : undefined; };
14
+
15
+ export function issueUrl({ message = "", example = "" }) {
16
+ const msg = message.trim();
17
+ const ex = example.trim().slice(0, 2000);
18
+ const title = msg ? `Feedback: ${msg.split("\n")[0].slice(0, 70)}` : "Feedback";
19
+ const body = [
20
+ "## What happened",
21
+ msg || "<!-- What did content-md do, and what did you expect? -->",
22
+ "",
23
+ "## Example",
24
+ ex ? "```\n" + ex + "\n```" : "<!-- Optional: paste the copy (before and after) if you're happy to share it. This issue is public. -->",
25
+ "",
26
+ "## Setup",
27
+ `- content-md ${PKG.version}`,
28
+ `- Node ${process.versions.node}, ${process.platform}`,
29
+ "- Agent: <!-- Claude Code, Cursor, Codex, VS Code, Windsurf... -->",
30
+ ].join("\n");
31
+ return `${ISSUES}?${new URLSearchParams({ title, body, labels: "feedback" })}`;
32
+ }
33
+
34
+ function openUrl(url) {
35
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
36
+ try { const p = spawn(cmd, args, { stdio: "ignore", detached: true }); p.on("error", () => {}); p.unref(); return true; } catch { return false; }
37
+ }
38
+
39
+ export async function feedback(argv) {
40
+ let message = flag(argv, "--message") ?? argv.filter((a, i) => !a.startsWith("--") && !["--message", "--example"].includes(argv[i - 1])).join(" ");
41
+ let example = flag(argv, "--example") || "";
42
+ if (!message && process.stdin.isTTY && process.stdout.isTTY) {
43
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
44
+ message = await rl.question("What should we know? ");
45
+ if (!example) example = await rl.question("Paste one example of the copy, if you want to share it (it will be public). Press Enter to skip: ");
46
+ rl.close();
47
+ }
48
+ const url = issueUrl({ message, example });
49
+ const opened = !argv.includes("--no-open") && openUrl(url);
50
+ console.log(`${opened ? "Opening a GitHub issue in your browser." : "Open this link to send feedback:"} Nothing is sent until you submit it there.\n\n${url}`);
51
+ return url;
52
+ }
package/src/init.js CHANGED
@@ -6,6 +6,8 @@ import { homedir } from "node:os";
6
6
  import { dirname, join, relative, sep } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { findRepoRules } from "./repo.js";
9
+ import { createInterface } from "node:readline/promises";
10
+ import { enabled, noticeOnce, readConfig, writeConfig, track, flush, PRIVACY_URL } from "./telemetry.js";
9
11
 
10
12
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
11
13
  const PKG = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
@@ -140,6 +142,60 @@ export function init(argv, cwd = process.cwd()) {
140
142
  if (!dry) console.log("Restart your editor or agent so it picks up the new MCP server.");
141
143
  }
142
144
 
145
+ // The agent running this command, from its environment, when there is no config in the repo to go on.
146
+ export function agentFromEnv(env = process.env) {
147
+ if (env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT) return "claude";
148
+ if (env.CURSOR_TRACE_ID || env.CURSOR_AGENT) return "cursor";
149
+ if (env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED || env.CODEX_THREAD_ID) return "codex";
150
+ if (/windsurf/i.test(env.TERM_PROGRAM || "")) return "windsurf";
151
+ return null;
152
+ }
153
+ export const DEFAULT_TARGETS = ["claude", "cursor", "codex"];
154
+ const LABELS = { claude: "Claude Code", cursor: "Cursor", codex: "Codex", vscode: "VS Code", windsurf: "Windsurf" };
155
+
156
+ // What bare `npx content-md init` sets up when the repo has no tool config yet. 1.0.8 wrote nothing here,
157
+ // which left people who followed the one-line install with no setup at all.
158
+ export function pickTargets(argv, cwd = process.cwd(), env = process.env) {
159
+ const asked = argv.includes("--all") ? TARGETS : TARGETS.filter((t) => argv.includes("--" + t));
160
+ if (asked.length) return { targets: asked, how: "flags" };
161
+ const found = detect(cwd);
162
+ if (found.length) return { targets: found, how: "detected" };
163
+ const agent = agentFromEnv(env);
164
+ if (agent) return { targets: [agent], how: "agent" };
165
+ return { targets: DEFAULT_TARGETS, how: "default" };
166
+ }
167
+
168
+ async function ask(question) {
169
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
170
+ try { return (await rl.question(question)).trim(); } finally { rl.close(); }
171
+ }
172
+
173
+ // The command-line entry: picks the tools (asking when a person is at the keyboard), runs init, and asks once
174
+ // whether to share examples of copy.
175
+ export async function initCli(argv, cwd = process.cwd()) {
176
+ const interactive = process.stdin.isTTY && process.stdout.isTTY && !argv.includes("--yes") && !argv.includes("-y");
177
+ let { targets, how } = pickTargets(argv, cwd);
178
+ if (how === "default" && interactive) {
179
+ const names = TARGETS.map((t, i) => ` ${i + 1}. ${LABELS[t]}`).join("\n");
180
+ const a = await ask(`No coding-tool setup found in this repo. Which tools do you use?\n${names}\nType the numbers (e.g. 1 3), or press Enter for Claude Code, Cursor and Codex: `);
181
+ const picked = [...new Set((a.match(/[1-5]/g) || []).map((n) => TARGETS[+n - 1]))];
182
+ if (picked.length) { targets = picked; how = "prompt"; }
183
+ } else if (how === "agent") console.log(`No coding-tool setup found in this repo. You're running this from ${LABELS[targets[0]]}, so it's set up for that. Add --cursor, --codex and so on for other tools.\n`);
184
+ else if (how === "default") console.log(`No coding-tool setup found in this repo, so it's set up for Claude Code, Cursor and Codex. Name the tools you use to change that: --claude --cursor --codex --vscode --windsurf.\n`);
185
+ const rest = argv.filter((a) => !TARGETS.includes(a.slice(2)) && a !== "--all");
186
+ init([...rest, ...targets.map((t) => "--" + t)], cwd);
187
+
188
+ if (!noticeOnce() && enabled()) console.log(`Anonymous usage stats are on (never your copy or code). Turn them off with \`npx content-md telemetry off\`. ${PRIVACY_URL}`);
189
+ if (enabled() && interactive && readConfig().examples === undefined) {
190
+ const a = await ask("\nShare examples of copy to help improve content-md? lint_copy would send the text it checks, before and after, with emails, links, numbers, paths and keys removed. [y/N] ");
191
+ const yes = /^y(es)?$/i.test(a);
192
+ writeConfig({ examples: yes });
193
+ console.log(yes ? "Thanks. Example sharing is on. Turn it off with `npx content-md telemetry examples off`." : "No copy will be shared. You can turn this on later with `npx content-md telemetry examples on`.");
194
+ }
195
+ track("init", { targets, how, dry: argv.includes("--dry-run"), global: argv.includes("--global"), rules: argv.includes("--rules") });
196
+ await flush();
197
+ }
198
+
143
199
  // Take out everything init added: marked blocks, our server entries, our rule and skill files.
144
200
  export function remove(argv, cwd = process.cwd()) {
145
201
  const dry = argv.includes("--dry-run");
package/src/server.js CHANGED
@@ -11,6 +11,7 @@ import { readConfig } from "./repo.js";
11
11
  import { checkClaims } from "./claims.js";
12
12
  import { positionFor, checkPosition } from "./position.js";
13
13
  import { existsSync as exists } from "node:fs";
14
+ import { track, trackExample, setClient, noticeOnce, flush } from "./telemetry.js";
14
15
  import { join as pjoin } from "node:path";
15
16
  import { normElement, META, PATTERNS, ELEMENTS, HAS_EXAMPLES, findExamples, findRules, getGuide, lintCopy, findReference, compareToReference } from "./tools.js";
16
17
  let productRead = false; // get_guide reminds the agent to read the product first
@@ -52,6 +53,7 @@ const element = z.string().transform((e, ctx) => {
52
53
 
53
54
  export async function serve() {
54
55
  const server = new McpServer({ name: "content-md", version: pkg.version }, { instructions: INSTRUCTIONS });
56
+ instrument(server);
55
57
 
56
58
  server.registerTool("get_guide", {
57
59
  title: "UX writing guide",
@@ -254,4 +256,49 @@ export async function serve() {
254
256
  }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/markdown", text: getGuide({ full: true }) }] }));
255
257
 
256
258
  await server.connect(new StdioServerTransport());
259
+ noticeOnce(process.stderr);
260
+ // a stdio server ends when the client closes stdin: send what is queued first
261
+ process.stdin.on("end", () => { flush().finally(() => process.exit(0)); });
262
+ }
263
+
264
+ // Usage stats: wrap every tool so each call records its name, our own enum values from its arguments and the
265
+ // shape of its result. Nothing the agent wrote (copy, situations, paths, briefs) is read here.
266
+ const ENUM_ARGS = ["stakes", "screen_state", "reversibility", "journey_stage", "trigger", "audience", "cause", "user_mindset", "platform", "quality"];
267
+ function instrument(server) {
268
+ const register = server.registerTool.bind(server);
269
+ server.registerTool = (name, config, handler) => register(name, config, async (args, extra) => {
270
+ const t0 = Date.now();
271
+ let result, ok = true;
272
+ try { result = await handler(args, extra); return result; }
273
+ catch (e) { ok = false; throw e; }
274
+ finally { try { record(server, name, args || {}, result, ok, Date.now() - t0); } catch { /* stats never break a tool */ } }
275
+ });
276
+ }
277
+ function record(server, tool, args, result, ok, ms) {
278
+ setClient(server.server.getClientVersion?.()?.name);
279
+ const props = { tool, ok, duration_ms: ms };
280
+ if (PATTERNS.includes(args.pattern)) props.pattern = args.pattern;
281
+ for (const k of ENUM_ARGS) if (typeof args[k] === "string") props[k] = args[k];
282
+ if (Array.isArray(args.risk)) props.risk = args.risk;
283
+ if (ELEMENTS.includes(args.element)) props.element = args.element;
284
+ let out; try { out = JSON.parse(result?.content?.[0]?.text); } catch { out = undefined; }
285
+ if (tool === "lint_copy") {
286
+ const findings = Array.isArray(out?.findings) ? out.findings : [];
287
+ Object.assign(props, {
288
+ n_units: args.units?.length || 0, elements: [...new Set((args.units || []).map((u) => normElement(u.element)).filter((e) => ELEMENTS.includes(e)))],
289
+ rewrite: !!args.original?.length, n_evidence: args.evidence?.length || 0, has_state: !!args.state,
290
+ pass: !!out?.pass, flagged: findings.some((f) => f.severity === "block" || f.severity === "warn"),
291
+ blocks: findings.filter((f) => f.severity === "block").length, warns: findings.filter((f) => f.severity === "warn").length,
292
+ notes: findings.filter((f) => f.severity === "note").length, rules: [...new Set(findings.map((f) => f.rule))], n_claims: out?.claims?.length || 0,
293
+ });
294
+ if (out) trackExample({ pattern: props.pattern, stakes: args.stakes, units: args.units, original: args.original, rules: props.rules, pass: props.pass });
295
+ }
296
+ if (["find_reference", "find_examples", "find_rules", "audit_copy"].includes(tool)) {
297
+ const list = Array.isArray(out) ? out : out?.results || out?.references || out?.strings || out?.lines;
298
+ if (Array.isArray(list)) props.n_results = list.length;
299
+ if (tool === "audit_copy") { props.passed_strings = !!args.strings; props.filtered = !!args.path_filter; }
300
+ }
301
+ if (tool === "ask_person") props.n_questions = args.questions?.length || 0;
302
+ if (tool === "decide_tone" && Array.isArray(out?.tones)) props.n_tones = out.tones.length;
303
+ track("tool", props);
257
304
  }
@@ -0,0 +1,167 @@
1
+ // Anonymous usage stats, on by default, the way Next.js and Astro do it: announced on first run, off with one
2
+ // command, and never on in CI or when DO_NOT_TRACK is set. Only event names and our own enum values are sent:
3
+ // which tool ran, the UI pattern, the stakes, whether lint flagged anything and which of our rules fired.
4
+ // Never copy, code, file paths, repo names or product details. Sharing examples of copy is a separate opt-in.
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { homedir, platform } from "node:os";
7
+ import { dirname, join } from "node:path";
8
+ import { randomUUID } from "node:crypto";
9
+ import { fileURLToPath } from "node:url";
10
+
11
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
12
+ const PKG = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
13
+ export const ENDPOINT = process.env.CONTENT_MD_TELEMETRY_URL || "https://agarau.dev/api/content-md/events";
14
+ export const PRIVACY_URL = "https://agarau.dev/content-md#usage-stats";
15
+ const SESSION = randomUUID();
16
+
17
+ export const NOTICE = `content-md collects anonymous usage stats: which tools run, the kind of screen, and whether lint flagged anything.
18
+ It never sends your copy, code, file paths or repo names. Details: ${PRIVACY_URL}
19
+ Turn it off with \`npx content-md telemetry off\`, or set DO_NOT_TRACK=1.`;
20
+
21
+ export function configDir() {
22
+ if (process.env.CONTENT_MD_CONFIG_DIR) return process.env.CONTENT_MD_CONFIG_DIR;
23
+ if (process.platform === "win32" && process.env.APPDATA) return join(process.env.APPDATA, "content-md");
24
+ return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "content-md");
25
+ }
26
+ const file = () => join(configDir(), "telemetry.json");
27
+
28
+ export function readConfig() {
29
+ try { return JSON.parse(readFileSync(file(), "utf8")); } catch { return {}; }
30
+ }
31
+ export function writeConfig(patch) {
32
+ const next = { ...readConfig(), ...patch };
33
+ try { mkdirSync(configDir(), { recursive: true }); writeFileSync(file(), JSON.stringify(next, null, 2) + "\n"); } catch { /* read-only home: stay quiet */ }
34
+ return next;
35
+ }
36
+
37
+ const CI_VARS = ["CI", "CONTINUOUS_INTEGRATION", "BUILD_NUMBER", "RUN_ID", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "CIRCLECI", "TRAVIS", "JENKINS_URL", "TEAMCITY_VERSION", "TF_BUILD", "CODEBUILD_BUILD_ID", "BITBUCKET_BUILD_NUMBER"];
38
+ const off = (v) => v != null && /^(0|false|off|no)$/i.test(String(v).trim());
39
+ const on = (v) => v != null && /^(1|true|on|yes)$/i.test(String(v).trim());
40
+
41
+ // Why stats are off, or null when they are on.
42
+ export function disabledReason(env = process.env, cfg = readConfig()) {
43
+ if (on(env.DO_NOT_TRACK)) return "DO_NOT_TRACK is set";
44
+ if (off(env.CONTENT_MD_TELEMETRY) || on(env.CONTENT_MD_TELEMETRY_DISABLED)) return "CONTENT_MD_TELEMETRY is off";
45
+ if (cfg.enabled === false) return "turned off with `content-md telemetry off`";
46
+ if (CI_VARS.some((k) => env[k] && !off(env[k]))) return "running in CI";
47
+ if (env.NODE_ENV === "test") return "NODE_ENV is test";
48
+ return null;
49
+ }
50
+ export const enabled = () => !disabledReason();
51
+ export const examplesEnabled = () => enabled() && readConfig().examples === true;
52
+ const debug = () => on(process.env.CONTENT_MD_TELEMETRY_DEBUG);
53
+
54
+ function installId() {
55
+ const cfg = readConfig();
56
+ if (/^[0-9a-f-]{36}$/.test(cfg.installId || "")) return cfg.installId;
57
+ return writeConfig({ installId: randomUUID() }).installId;
58
+ }
59
+
60
+ // Show the notice once per machine. `stream` is stderr for the MCP server, whose stdout is the protocol.
61
+ export function noticeOnce(stream = process.stdout) {
62
+ if (!enabled()) return false;
63
+ const cfg = readConfig();
64
+ if (cfg.notifiedAt) return false;
65
+ stream.write(`\n${NOTICE}\n\n`);
66
+ writeConfig({ notifiedAt: new Date().toISOString() });
67
+ return true;
68
+ }
69
+
70
+ // The calling agent's client, reduced to a short known name.
71
+ const CLIENTS = [[/claude/i, "claude-code"], [/cursor/i, "cursor"], [/codex/i, "codex"], [/windsurf|codeium|cascade/i, "windsurf"], [/copilot|vscode|visual studio code/i, "vscode"], [/zed/i, "zed"], [/gemini/i, "gemini"], [/cline/i, "cline"], [/goose/i, "goose"]];
72
+ export function clientName(raw) {
73
+ if (!raw) return "unknown";
74
+ const hit = CLIENTS.find(([re]) => re.test(raw));
75
+ return hit ? hit[1] : "other";
76
+ }
77
+
78
+ const SAFE = /^[a-z0-9][a-z0-9._-]{0,47}$/i;
79
+ const safe = (v) => (typeof v === "string" && SAFE.test(v) ? v : undefined);
80
+
81
+ let queue = [], timer = null, client = "cli";
82
+ export const setClient = (raw) => { client = clientName(raw); };
83
+
84
+ function base() {
85
+ return { install_id: installId(), session_id: SESSION, version: PKG.version, client, os: platform(), node: process.versions.node.split(".")[0] };
86
+ }
87
+
88
+ export function track(event, props = {}) {
89
+ if (!enabled()) return;
90
+ const clean = {};
91
+ for (const [k, v] of Object.entries(props)) {
92
+ if (typeof v === "number" && Number.isFinite(v)) clean[k] = Math.round(v);
93
+ else if (typeof v === "boolean") clean[k] = v;
94
+ else if (Array.isArray(v)) { const a = v.map(safe).filter(Boolean).slice(0, 40); if (a.length) clean[k] = a; }
95
+ else if (safe(v)) clean[k] = v;
96
+ }
97
+ push({ kind: "event", event: safe(event) || "unknown", props: clean });
98
+ }
99
+
100
+ // Opt-in only: the before/after text of one lint_copy check, scrubbed of anything that looks private.
101
+ export function trackExample(example) {
102
+ if (!examplesEnabled()) return;
103
+ const units = (list) => (list || []).slice(0, 12).map((u) => ({ element: safe(u.element) || "other", text: scrub(u.text) })).filter((u) => u.text);
104
+ push({ kind: "example", pattern: safe(example.pattern), stakes: safe(example.stakes), units: units(example.units), original: units(example.original), rules: (example.rules || []).map(safe).filter(Boolean).slice(0, 40), pass: !!example.pass });
105
+ }
106
+
107
+ export function scrub(text) {
108
+ if (typeof text !== "string") return "";
109
+ return text
110
+ .replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g, "[email]")
111
+ .replace(/\bhttps?:\/\/\S+|\bwww\.\S+/gi, "[link]")
112
+ .replace(/\b(sk|pk|rk|ghp|gho|ghs|github_pat|xox[abpr]|AKIA|AIza)[-_A-Za-z0-9]{10,}/g, "[key]")
113
+ .replace(/\b[A-Za-z0-9_-]{32,}\b/g, "[key]")
114
+ .replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g, "[key]")
115
+ .replace(/(?:~|\.{1,2})?\/(?:[\w.-]+\/)+[\w.-]+/g, "[path]")
116
+ .replace(/\b[A-Z]:\\[^\s]+/g, "[path]")
117
+ .replace(/\+?\d[\d ()-]{7,}\d/g, "[number]")
118
+ .slice(0, 300);
119
+ }
120
+
121
+ function push(item) {
122
+ const full = { ...base(), ...item, at: new Date().toISOString() };
123
+ if (debug()) { process.stderr.write(`[content-md telemetry] ${JSON.stringify(full)}\n`); return; }
124
+ queue.push(full);
125
+ if (queue.length >= 20) { flush(); return; }
126
+ if (!timer) { timer = setTimeout(() => { timer = null; flush(); }, 5000); timer.unref?.(); }
127
+ }
128
+
129
+ // Send what is queued. Never throws, never waits more than 1.5 seconds.
130
+ export async function flush() {
131
+ if (timer) { clearTimeout(timer); timer = null; }
132
+ if (!queue.length) return;
133
+ const batch = queue; queue = [];
134
+ try {
135
+ await fetch(ENDPOINT, {
136
+ method: "POST",
137
+ headers: { "content-type": "application/json", "user-agent": `content-md/${PKG.version}` },
138
+ body: JSON.stringify({ items: batch }),
139
+ signal: AbortSignal.timeout(1500),
140
+ });
141
+ } catch { /* offline or blocked: drop it */ }
142
+ }
143
+
144
+ // `npx content-md telemetry [status|on|off|examples on|examples off]`
145
+ export function telemetryCommand(argv) {
146
+ const [a, b] = argv;
147
+ if (a === "off" || a === "disable") { writeConfig({ enabled: false, examples: false }); console.log("Usage stats are off on this machine. Nothing more will be sent."); return; }
148
+ if (a === "on" || a === "enable") { writeConfig({ enabled: true }); console.log("Usage stats are on. Only anonymous events are sent, never your copy or code."); return; }
149
+ if (a === "examples" && (b === "on" || b === "off")) {
150
+ writeConfig({ examples: b === "on", ...(b === "on" ? { enabled: true } : {}) });
151
+ console.log(b === "on"
152
+ ? "Example sharing is on. lint_copy checks now send the copy they checked (before and after), with emails, links, numbers, paths and keys removed. Turn it off with `npx content-md telemetry examples off`."
153
+ : "Example sharing is off. Only anonymous usage stats are sent.");
154
+ return;
155
+ }
156
+ const reason = disabledReason();
157
+ const cfg = readConfig();
158
+ console.log(`Usage stats: ${reason ? `off (${reason})` : "on"}
159
+ Example sharing: ${!reason && cfg.examples === true ? "on" : "off"}
160
+ Config: ${file()}
161
+ ${NOTICE.split("\n").slice(0, 2).join("\n")}
162
+
163
+ npx content-md telemetry off stop sending usage stats
164
+ npx content-md telemetry on start again
165
+ npx content-md telemetry examples on also share the copy lint_copy checks (scrubbed)
166
+ npx content-md telemetry examples off stop sharing copy`);
167
+ }