factcheck-docs 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Avinash Gaurav
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,116 @@
1
- # Temporary Holding Version
1
+ # factcheck-docs
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Catch made-up numbers, fake sources and broken facts in AI-written docs, before your boss does.**
4
+
5
+ You give an AI your notes and it gives back a PRD, an exec update or a launch plan. Somewhere in there is a "23% lift" you never said, a "studies show" with no study, or a launch date that falls on the wrong weekday. `factcheck-docs` reads the draft against what you actually gave the AI and flags every line that needs a receipt.
6
+
7
+ It is a plain script, not another AI: fast, free, offline, and the same answer every time.
8
+
9
+ **Try it in your browser: [avinashgaurav.github.io/factcheck-docs](https://avinashgaurav.github.io/factcheck-docs/)** (runs locally in the page; nothing you paste is sent anywhere).
10
+
11
+ ```
12
+ $ npx factcheck-docs draft.md --source notes.md
13
+
14
+ draft.md against notes.md
15
+ Score 23/100 (F) 6 errors, 5 warnings, 2 notes
16
+
17
+ L4 error unsourced-number 68% is not in your input, not computed from it, and not labelled as an assumption or target.
18
+ L4 error fake-source Cites "Studies show" but your input gives no such source. Name it and link it, or cut it.
19
+ L5 warning invented-name "Globex" does not appear in your input. If it is a person, customer, tool or competitor, check it is real and relevant.
20
+ L8 error math-error Change from 42,000 to 51,000 is 21.4%, not 30%.
21
+ L9 error math-error 300 of 1,200 is 25.0%, not 40%.
22
+ L13 error date-error 31 April does not exist.
23
+ L14 warning contradiction "csat" is 85% here but 82% on line 14.
24
+ L15 note leftover Placeholder still to fill: [link]
25
+ ```
26
+
27
+ ## What it checks
28
+
29
+ | Check | Catches | Needs `--source` |
30
+ | --- | --- | --- |
31
+ | `unsourced-number` | Figures not in your input, not computed from it, and not labelled as an assumption or target | Yes |
32
+ | `math-error` | Percent changes, "X of Y (Z%)" and `a + b = c` that don't add up | No |
33
+ | `contradiction` | The same metric with two values in one doc | No |
34
+ | `fake-source` | "Studies show", "according to Gartner", norms stated as fact ("usually", "industry standard"), links not in your input | Partly |
35
+ | `invented-name` | People, customers, tools or competitors your input never mentions | Yes |
36
+ | `date-error` | Impossible dates, wrong weekdays, past dates written as plans, dates not in your input | Partly |
37
+ | `leftover` | `[TBD]`, `[link]`, "insert X here", `{{template}}` text | No |
38
+ | `vague-claim` | "Significantly", "industry-leading", "best-in-class" with no number behind them | No |
39
+
40
+ A number counts as sourced if it is in your input, or a reader could compute it from your input (sums, differences, ratios, percentages, percent changes, monthly to yearly), including step by step through numbers the doc already derived. A sentence that says "assumption", "estimate", "target", "TBD" or similar is treated as labelled.
41
+
42
+ **Severity:** `error` is very likely wrong. `warning` needs a look (an unsourced count or duration, a name, a link). `note` is tidying. The score starts at 100 and loses 10 per error, 3 per warning and 1 per note.
43
+
44
+ ## Usage
45
+
46
+ ```bash
47
+ npx factcheck-docs draft.md --source notes.md # check a draft against your notes
48
+ npx factcheck-docs draft.md -s thread.txt -s data.csv # several sources
49
+ cat draft.md | npx factcheck-docs - -s notes.md # from stdin
50
+ npx factcheck-docs draft.md # no source: maths, dates, sources, leftovers, vague claims only
51
+ npx factcheck-docs draft.md -s notes.md --json # machine-readable
52
+ npx factcheck-docs draft.md -s notes.md --fail-under 80 # exit 1 below 80, for CI
53
+ npx factcheck-docs draft.md -s notes.md --allow Acme,Northwind # names that are fine
54
+ ```
55
+
56
+ From code:
57
+
58
+ ```js
59
+ import { factcheck } from "factcheck-docs";
60
+ const { score, findings } = factcheck(draft, { source: notes });
61
+ ```
62
+
63
+ Node 18 or later. No dependencies.
64
+
65
+ ## Use it in Claude Code
66
+
67
+ The repo is also a Claude Code plugin with one skill. After Claude drafts a document from your notes, it runs the checker on its own draft, fixes every error (sources it, labels it or cuts it) and tells you what it changed. Ask it to fact-check someone else's doc and it reports the findings instead of rewriting.
68
+
69
+ ```
70
+ /plugin marketplace add avinashgaurav/factcheck-docs
71
+ /plugin install factcheck-docs@factcheck-docs
72
+ ```
73
+
74
+ Tested with `claude plugin eval` (`evals/`), 3 runs each, with and without the plugin, judged by Sonnet, on 1 December 2026:
75
+
76
+ | Case | With the skill | Without |
77
+ | --- | --- | --- |
78
+ | Draft a CFO update from notes; final draft has no figure that isn't in the notes, computed from them, or labelled | **3 / 3** | 1 / 3 |
79
+ | Fact-check a draft with 5 planted errors; all 5 found | 3 / 3 | 3 / 3 |
80
+
81
+ Read with care: 2 cases, written by me. The first run of the drafting case scored 0 / 3 with the skill, because Claude kept a header date that was not in the notes; I changed the skill to replace such dates with `[date]` and reran that case. Without the skill, Claude already finds obvious planted errors when asked; the skill's gain is in checking its own drafts.
82
+
83
+ ## How well does it agree with an AI judge?
84
+
85
+ I ran it on 96 real drafts from the [pm-os plugin evals](https://github.com/avinashgaurav/pm-os/tree/main/plugin): 8 kinds of PM document, written by Claude with and without a "don't invent figures" skill, each graded by a Sonnet judge on the same rule ("every figure comes from the prompt or is labelled; no outside benchmarks or invented links"). The prompt was used as `--source`.
86
+
87
+ | Counting as "flagged" | Judge failed, we flagged | Judge failed, we missed | Judge passed, we flagged | Judge passed, we didn't |
88
+ | --- | --- | --- | --- | --- |
89
+ | Errors and warnings | **19 / 25** | 6 | 32 / 71 | 39 |
90
+ | Errors only | 2 / 25 | 23 | 2 / 71 | 69 |
91
+
92
+ What that means:
93
+
94
+ - **Errors and warnings catch most of what the judge catches** (19 of 25), at the cost of flagging about 45% of drafts the judge passed. Most of those extra flags are durations and counts ("within 14 days", "25, 50 and 100 seats") that the judge sometimes accepts and sometimes rejects; the judge itself is not consistent on them.
95
+ - **Errors alone are rare and usually right**, but most judge failures are warning-level: an invented duration, a count, a norm stated as fact.
96
+ - **It is a reviewer's aid, not a verdict.** It cannot tell a reasonable planning choice from a made-up fact; it tells you where to look.
97
+ - Small, one-off comparison, and I tuned the rules while looking at these drafts. Reproduce it with `node scripts/validate-against-judge.js <eval-result.json ...>`.
98
+
99
+ ## Limits
100
+
101
+ - English, markdown or plain text.
102
+ - It matches numbers, not meaning: a sourced number used for the wrong thing passes.
103
+ - Name detection is a heuristic on capitalised words; use `--allow` for your own company and product names.
104
+ - Claims without numbers ("customers love it") need an AI judge. That is the next layer.
105
+
106
+ ## Roadmap
107
+
108
+ 1. ~~Script checks, scorecard, CLI~~
109
+ 2. ~~Paste-and-check web page~~ (`index.html`; runs in the browser, nothing is sent anywhere)
110
+ 3. ~~Claude Code skill: check drafts as they are written~~
111
+ 4. AI-judge layer: unsupported claims, hearsay written as fact, missing essentials by doc type, commitments with no owner
112
+ 5. Eval mode: test your own AI-writing prompts against cases, with and without a change
113
+
114
+ ## License
115
+
116
+ MIT
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { factcheck, CHECKS } from "../src/index.js";
4
+
5
+ const HELP = `factcheck-docs: catch made-up numbers, fake sources and broken facts in AI-written docs.
6
+
7
+ Usage:
8
+ factcheck-docs <draft.md> [--source notes.md ...] [options]
9
+ cat draft.md | factcheck-docs - --source notes.md
10
+
11
+ Options:
12
+ -s, --source <file> What you gave the AI (notes, data, thread). Repeatable.
13
+ Without it, only the checks that need no input run.
14
+ --today <YYYY-MM-DD> Date for past-date checks (default: today).
15
+ --only <a,b> Run only these checks: ${Object.keys(CHECKS).join(", ")}.
16
+ --allow <a,b> Names that are fine even if not in your input (your company, product).
17
+ --fail-under <score> Exit 1 if the score is below this (for CI).
18
+ --json Print the full result as JSON.
19
+ -h, --help Show this help.
20
+ `;
21
+
22
+ function parse(argv) {
23
+ const o = { sources: [], only: [], allow: [], json: false, failUnder: null, today: undefined, file: null };
24
+ for (let i = 0; i < argv.length; i++) {
25
+ const a = argv[i];
26
+ const next = () => {
27
+ if (i + 1 >= argv.length) die(`${a} needs a value`);
28
+ return argv[++i];
29
+ };
30
+ if (a === "-h" || a === "--help") o.help = true;
31
+ else if (a === "-s" || a === "--source") o.sources.push(next());
32
+ else if (a === "--today") o.today = next();
33
+ else if (a === "--only") o.only.push(...next().split(","));
34
+ else if (a === "--allow") o.allow.push(...next().split(","));
35
+ else if (a === "--fail-under") o.failUnder = Number(next());
36
+ else if (a === "--json") o.json = true;
37
+ else if (a.startsWith("-") && a !== "-") die(`Unknown option ${a}`);
38
+ else if (!o.file) o.file = a;
39
+ else die(`Unexpected argument ${a}`);
40
+ }
41
+ return o;
42
+ }
43
+
44
+ function die(msg) {
45
+ process.stderr.write(`factcheck-docs: ${msg}\n\n${HELP}`);
46
+ process.exit(2);
47
+ }
48
+
49
+ function read(path) {
50
+ try {
51
+ return readFileSync(path === "-" ? 0 : path, "utf8");
52
+ } catch (e) {
53
+ die(`cannot read ${path}: ${e.code ?? e.message}`);
54
+ }
55
+ }
56
+
57
+ const opts = parse(process.argv.slice(2));
58
+ if (opts.help || !opts.file) {
59
+ process.stdout.write(HELP);
60
+ process.exit(opts.help ? 0 : 2);
61
+ }
62
+
63
+ const doc = read(opts.file);
64
+ const source = opts.sources.map(read).join("\n\n");
65
+ let result;
66
+ try {
67
+ result = factcheck(doc, { source, today: opts.today, only: opts.only, allowNames: opts.allow });
68
+ } catch (e) {
69
+ die(e.message);
70
+ }
71
+
72
+ if (opts.json) {
73
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
74
+ } else {
75
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
76
+ const c = (code, s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : s);
77
+ const sev = { error: c(31, "error "), warning: c(33, "warning"), note: c(36, "note ") };
78
+ const src = opts.sources.length ? `against ${opts.sources.join(", ")}` : c(2, "(no --source: number, name and date-source checks skipped)");
79
+ const { error, warning, note } = result.counts;
80
+ process.stdout.write(`\n${c(1, opts.file === "-" ? "stdin" : opts.file)} ${src}\n`);
81
+ process.stdout.write(`${c(1, `Score ${result.score}/100 (${result.grade})`)} ${error} errors, ${warning} warnings, ${note} notes\n\n`);
82
+ for (const x of result.findings) {
83
+ process.stdout.write(` L${String(x.line).padEnd(4)} ${sev[x.severity]} ${c(2, x.check.padEnd(16))} ${x.message}\n`);
84
+ }
85
+ if (!result.findings.length) process.stdout.write(" No problems found.\n");
86
+ process.stdout.write("\n");
87
+ }
88
+
89
+ if (opts.failUnder != null && result.score < opts.failUnder) process.exit(1);
package/package.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "name": "factcheck-docs",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Catch made-up numbers, fake sources, wrong maths and broken dates in AI-written docs. Checks the draft against what you gave the AI.",
5
+ "type": "module",
6
+ "bin": { "factcheck-docs": "bin/factcheck-docs.js" },
7
+ "main": "src/index.js",
8
+ "exports": { ".": "./src/index.js" },
9
+ "files": ["bin", "src", "README.md", "LICENSE"],
10
+ "engines": { "node": ">=18" },
11
+ "scripts": { "test": "node --test test/*.test.js" },
12
+ "keywords": ["ai", "llm", "hallucination", "fact-check", "evals", "product-management", "prd", "claude", "chatgpt", "docs"],
13
+ "author": "Avinash Gaurav (https://github.com/avinashgaurav)",
14
+ "license": "MIT",
15
+ "repository": { "type": "git", "url": "git+https://github.com/avinashgaurav/factcheck-docs.git" }
16
+ }
package/src/checks.js ADDED
@@ -0,0 +1,277 @@
1
+ // The eight script checks. Each takes the document units and a context, and
2
+ // returns findings: { check, severity, line, text, message }.
3
+ //
4
+ // severity: "error" (very likely wrong), "warning" (check it), "note" (tidy up).
5
+
6
+ import { findNumbers, isLabelled, isSupported, derivedValues } from "./numbers.js";
7
+ import { findDates, daysInMonth, weekdayOf, dateKey } from "./dates.js";
8
+ import { URL_RE } from "./text.js";
9
+
10
+ const f = (check, severity, unit, text, message) => ({ check, severity, line: unit.line, text, message });
11
+
12
+ /** 1. Figures that are neither in the source nor labelled as assumptions. */
13
+ export function unsourcedNumbers(units, ctx) {
14
+ if (!ctx.hasSource) return [];
15
+ // Numbers the doc derives step by step (a rate, then a gap from that rate)
16
+ // are supported if each step is. Grow the pool of supported values over a
17
+ // few passes, and let each sentence or table row combine its own supported
18
+ // numbers (an ICE score is the product of the row's three inputs).
19
+ let pool = ctx.values.slice();
20
+ let derived = ctx.derived;
21
+ const supported = new Set();
22
+ for (let pass = 0; pass < 2; pass++) {
23
+ let grew = false;
24
+ for (const u of units) {
25
+ const nums = findNumbers(u.text);
26
+ const local = [];
27
+ for (const n of nums) {
28
+ if (supported.has(n) || isSupported(n, derived)) {
29
+ if (!supported.has(n)) { supported.add(n); grew = true; pool.push(n.value); }
30
+ local.push(n.value);
31
+ }
32
+ }
33
+ const combos = rowCombos(local);
34
+ for (const n of nums) {
35
+ if (!supported.has(n) && combos.some((d) => Math.abs(d - n.value) <= Math.max(Math.abs(n.value) * 0.005, 0.5 * 10 ** -n.decimals))) {
36
+ supported.add(n); grew = true; pool.push(n.value);
37
+ }
38
+ }
39
+ }
40
+ if (!grew) break;
41
+ derived = derivedValues([...new Set(pool)]);
42
+ }
43
+ const out = [];
44
+ for (const u of units) {
45
+ if (u.heading) continue;
46
+ for (const n of findNumbers(u.text)) {
47
+ if ([...supported].some((s) => s.raw === n.raw && s.start === n.start && s.value === n.value && units.indexOf(u) >= 0 && isSupported(n, derived))) continue;
48
+ if (isLabelled(u.text) || isSupported(n, derived)) continue;
49
+ const severity = n.kind === "count" || n.kind === "duration" ? "warning" : "error";
50
+ const what = n.kind === "duration" ? "This duration" : n.raw;
51
+ out.push(f("unsourced-number", severity, u, n.raw, n.kind === "duration" ? `${n.raw} (a duration or deadline) is not in your input. If you chose it, say so; if not, confirm it.` : `${what} is not in your input, not computed from it, and not labelled as an assumption or target.`));
52
+ }
53
+ }
54
+ return out;
55
+ }
56
+
57
+ function rowCombos(vals) {
58
+ const out = [];
59
+ const v = vals.slice(0, 8);
60
+ for (let i = 0; i < v.length; i++)
61
+ for (let j = i + 1; j < v.length; j++) {
62
+ out.push(v[i] * v[j], v[i] + v[j]);
63
+ for (let k = j + 1; k < v.length; k++) out.push(v[i] * v[j] * v[k], v[i] + v[j] + v[k], (v[i] * v[j]) / v[k]);
64
+ }
65
+ return out;
66
+ }
67
+
68
+ /** 2. Arithmetic the document states and gets wrong. */
69
+ export function mathErrors(units) {
70
+ const out = [];
71
+ const num = (s) => parseFloat(s.replace(/,/g, ""));
72
+ for (const u of units) {
73
+ const t = u.text;
74
+ // "from 42,000 to 51,000 (+21%)" or "from 10% to 6%, a 40% drop"
75
+ for (const m of t.matchAll(/from\s+[$€£₹]?([\d,.]+)\s*%?\s*(?:[a-zA-Z]+\s+){0,3}to\s+[$€£₹]?([\d,.]+)\s*%?[^.%\d]{0,40}?([+-]?\d+(?:\.\d+)?)\s*%\s*(increase|rise|growth|jump|up|drop|decrease|decline|fall|down|lift|more|less|higher|lower)?/gi)) {
76
+ const a = num(m[1]), b = num(m[2]), claimed = Math.abs(num(m[3]));
77
+ if (!a || isNaN(b) || isNaN(claimed)) continue;
78
+ const actual = Math.abs(((b - a) / a) * 100);
79
+ const tol = Math.max(1, actual * 0.05);
80
+ if (Math.abs(actual - claimed) > tol && Math.abs(Math.abs(b - a) - claimed) > 0.5) {
81
+ out.push(f("math-error", "error", u, m[0].trim(), `Change from ${m[1]} to ${m[2]} is ${actual.toFixed(1)}%, not ${m[3]}%.`));
82
+ }
83
+ }
84
+ // "300 of 1,200 (25%)" / "300 out of 1,200, or 25%"
85
+ for (const m of t.matchAll(/([\d,]+(?:\.\d+)?)\s+(?:out\s+)?of\s+(?:the\s+)?([\d,]+(?:\.\d+)?)\b[^.%\d]{0,25}?(\d+(?:\.\d+)?)\s*%/gi)) {
86
+ const a = num(m[1]), b = num(m[2]), claimed = num(m[3]);
87
+ if (!b) continue;
88
+ const actual = (a / b) * 100;
89
+ if (Math.abs(actual - claimed) > Math.max(0.6, actual * 0.02)) {
90
+ out.push(f("math-error", "error", u, m[0].trim(), `${m[1]} of ${m[2]} is ${actual.toFixed(1)}%, not ${m[3]}%.`));
91
+ }
92
+ }
93
+ // "a + b = c" and "a x b = c"
94
+ for (const m of t.matchAll(/([\d,]+(?:\.\d+)?)\s*([+\-x×*\/÷])\s*([\d,]+(?:\.\d+)?)\s*=\s*([\d,]+(?:\.\d+)?)/g)) {
95
+ const a = num(m[1]), b = num(m[3]), c = num(m[4]);
96
+ const op = m[2];
97
+ const r = op === "+" ? a + b : op === "-" ? a - b : /[x×*]/.test(op) ? a * b : a / b;
98
+ if (Math.abs(r - c) > Math.max(0.01, Math.abs(r) * 0.005)) {
99
+ out.push(f("math-error", "error", u, m[0].trim(), `${m[1]} ${op} ${m[3]} is ${+r.toFixed(2)}, not ${m[4]}.`));
100
+ }
101
+ }
102
+ }
103
+ return out;
104
+ }
105
+
106
+ const STOP = new Set("the a an of in on at to for and or our their its is was are be by with from this that per vs".split(" "));
107
+
108
+ /** 3. The same metric stated with two different values. */
109
+ export function contradictions(units) {
110
+ const seen = new Map();
111
+ const out = [];
112
+ for (const u of units) {
113
+ if (u.heading || isLabelled(u.text)) continue;
114
+ for (const n of findNumbers(u.text)) {
115
+ if (n.kind !== "percent" && n.kind !== "money") continue;
116
+ const words = u.text.slice(0, n.start).toLowerCase().match(/[a-z][a-z-]+/g) || [];
117
+ const key = words.filter((w) => !STOP.has(w) && w.length > 2).slice(-1).join(" ");
118
+ if (!key || /\b(from|to|was|now|today|before|after|week|month|quarter|year|target|goal)\b/.test(u.text.slice(Math.max(0, n.start - 30), n.start).toLowerCase())) continue;
119
+ const k = `${n.kind}:${key}`;
120
+ const prev = seen.get(k);
121
+ if (prev && Math.abs(prev.value - n.value) > 1e-9 && prev.unit !== u) {
122
+ out.push(f("contradiction", "warning", u, n.raw, `"${key}" is ${n.raw} here but ${prev.raw} on line ${prev.line}.`));
123
+ } else if (!prev) seen.set(k, { value: n.value, raw: n.raw, line: u.line, unit: u });
124
+ }
125
+ }
126
+ return out;
127
+ }
128
+
129
+ const SOURCE_PHRASES =
130
+ /\b(studies (?:show|suggest|find|found)|research (?:shows|suggests|finds|found)|a (?:recent )?(?:study|survey|report) (?:by|from|shows|found)|according to (?:a |the |recent )?(?:study|survey|report|research|data|gartner|forrester|mckinsey|idc|statista|harvard|hbr|deloitte|bcg|bain|pwc|accenture)|(?:gartner|forrester|mckinsey|idc|statista|deloitte|bcg|bain) (?:says|reports|found|estimates|predicts)|industry (?:average|benchmark|standard|norm)s?|(?:experts|analysts) (?:say|agree|estimate|predict)|on average,? (?:companies|teams|users|customers)|best practices? (?:say|show|suggest)s?)\b/i;
131
+
132
+ const NORM = /\b(usually|typically|tend(?:s)? to|as a rule|on average|most (?:companies|teams|businesses|startups|customers|users|buyers)|(?:is|are) (?:the )?(?:standard|norm|common practice)|industry[- ]standard|commonly|generally speaking)\b/i;
133
+
134
+ /** 4. Claimed sources the input never gave, and links that are not in the input. */
135
+ export function fakeSources(units, ctx) {
136
+ const out = [];
137
+ for (const u of units) {
138
+ const m = u.text.match(SOURCE_PHRASES);
139
+ if (m && !ctx.sourceLower.includes(m[0].toLowerCase())) {
140
+ out.push(f("fake-source", "error", u, m[0], `Cites "${m[0]}" but your input gives no such source. Name it and link it, or cut it.`));
141
+ }
142
+ const norm = u.text.match(NORM);
143
+ if (norm && !isLabelled(u.text) && !ctx.sourceLower.includes(norm[0].toLowerCase())) {
144
+ out.push(f("fake-source", "warning", u, norm[0], `"${norm[0]}" states a general norm as fact. Give the source, or say it is your assumption.`));
145
+ }
146
+ for (const url of u.raw.match(URL_RE) || []) {
147
+ if (ctx.hasSource && !ctx.sourceLower.includes(url.toLowerCase().replace(/[.,;]+$/, ""))) {
148
+ out.push(f("fake-source", "warning", u, url, `Link is not in your input. Open it and confirm it says what the doc claims.`));
149
+ }
150
+ }
151
+ }
152
+ return dedupe(out);
153
+ }
154
+
155
+ const COMMON = new Set(
156
+ ("I We You They He She It Our Their My Your This That These Those The A An If When While For And But Or So Then Also Next Now Today Tomorrow Yesterday " +
157
+ "Monday Tuesday Wednesday Thursday Friday Saturday Sunday January February March April May June July August September October November December " +
158
+ "Jan Feb Mar Apr Jun Jul Aug Sep Sept Oct Nov Dec Q1 Q2 Q3 Q4 H1 H2 Yes No Not None All Each Every Some Any One Two Three Four Five Six Seven Eight Nine Ten " +
159
+ "Assumption Assumptions Target Targets TBD Goal Goals Risk Risks Owner Owners Status Summary Context Background Problem Solution Scope Ask Why What How Who Where " +
160
+ "Notes Note Option Options Recommendation Decision Decisions Metric Metrics Success Timeline Milestone Milestones Dependencies Dependency Appendix Overview Objective Objectives Key Results Result " +
161
+ "Must Should Could Won't Will Can Need Needs Done Open Closed Blocked Ready Launch Product Engineering Design Marketing Sales Support Legal Finance Security Data Ops Customer Customers User Users Team Teams " +
162
+ "Before After During Phase Week Month Quarter Year Day Days Weeks Months Given Then And Story Stories Acceptance Criteria Epic Feature Features Out In Non Functional Requirements Requirement Open Questions Question " +
163
+ "Here There Please Thanks Hi Hello Dear Best Regards").split(" "),
164
+ );
165
+
166
+ /** 5. Proper names (people, customers, tools, competitors) that the input never mentions. */
167
+ export function inventedNames(units, ctx) {
168
+ if (!ctx.hasSource) return [];
169
+ const out = [];
170
+ const flagged = new Set();
171
+ for (const u of units) {
172
+ if (u.heading) continue;
173
+ const text = u.text.replace(URL_RE, " ");
174
+ for (const m of text.matchAll(/(?<![\w'])([A-Z][a-z]+[A-Za-z0-9]*|[A-Z][a-z]*[A-Z][A-Za-z0-9]+)(?:\s+([A-Z][a-z]+[A-Za-z0-9]*))?/g)) {
175
+ const name = m[0];
176
+ const first = m[1];
177
+ const prefix = text.slice(0, m.index);
178
+ const sentenceStart = /^[\s*_>#\-|"(\[]*(?:\d+[.)]\s*)?(?:\*\*)?$/.test(prefix) || /[:.!?]\s*(?:\*\*)?$/.test(prefix) || /\|\s*(?:\*\*)?$/.test(prefix);
179
+ if (sentenceStart && !m[2]) continue;
180
+ const candidate = sentenceStart ? m[2] : name;
181
+ if (!candidate) continue;
182
+ if (/^[A-Z0-9]+$/.test(candidate.replace(/\s+/g, ""))) continue; // acronyms: CSAT, API, ARR
183
+ if (candidate.split(/\s+/).every((w) => COMMON.has(w))) continue;
184
+ if (COMMON.has(sentenceStart ? candidate : first) && !m[2]) continue;
185
+ const key = candidate.toLowerCase();
186
+ if (flagged.has(key)) continue;
187
+ if (candidate.split(/\s+/).some((w) => ctx.sourceLower.includes(w.toLowerCase()))) continue;
188
+ if (ctx.allowNames.has(key)) continue;
189
+ flagged.add(key);
190
+ out.push(f("invented-name", "warning", u, candidate, `"${candidate}" does not appear in your input. If it is a person, customer, tool or competitor, check it is real and relevant.`));
191
+ }
192
+ }
193
+ return out;
194
+ }
195
+
196
+ /** 6. Impossible dates, wrong weekdays, past dates used as future plans, and dates not in the input. */
197
+ export function dateErrors(units, ctx) {
198
+ const out = [];
199
+ const today = ctx.today;
200
+ for (const u of units) {
201
+ for (const d of findDates(u.text)) {
202
+ if (d.day < 1 || d.day > daysInMonth(d.month, d.year)) {
203
+ out.push(f("date-error", "error", u, d.raw, `${d.raw} does not exist.`));
204
+ continue;
205
+ }
206
+ const year = d.year ?? (ctx.assumeYear || null);
207
+ if (d.weekday && year) {
208
+ const actual = weekdayOf(d.day, d.month, year);
209
+ if (actual !== d.weekday) out.push(f("date-error", "error", u, d.raw, `${d.raw}: that date is a ${fullDay(actual)}${d.year ? "" : ` in ${year}`}.`));
210
+ }
211
+ if (d.year && today) {
212
+ const when = Date.UTC(d.year, d.month - 1, d.day);
213
+ const future = /\b(will|launch\w*|ship\w*|go(?:es)? live|due|deadline|by|planned|scheduled|release\w*|start\w*)\b/i.test(u.text);
214
+ if (when < today && future && !/\b(was|were|did|launched|shipped|released|happened|ago|last)\b/i.test(u.text)) {
215
+ out.push(f("date-error", "warning", u, d.raw, `${d.raw} is in the past but reads as a future plan.`));
216
+ }
217
+ }
218
+ if (ctx.hasSource && !isLabelled(u.text) && !ctx.sourceDates.has(dateKey(d))) {
219
+ out.push(f("date-error", "warning", u, d.raw, `${d.raw} is not in your input. Confirm it or mark it as a target.`));
220
+ }
221
+ }
222
+ }
223
+ return dedupe(out);
224
+ }
225
+
226
+ const LEFTOVER = /\[(?:tbd|todo|tk|link|url|date|name|owner|insert[^\]]*|placeholder|x{2,}|\.\.\.)\]|\b(?:TODO|FIXME|TKTK|XXX)\b|lorem ipsum|\{\{[^}]+\}\}|<(?:insert|your|add)[^>]*>|\binsert (?:\w+ ){0,3}here\b|\[(?:your|company|product) [^\]]+\]/gi;
227
+
228
+ /** 7. Placeholders and template text left in the doc. */
229
+ export function leftovers(units) {
230
+ const out = [];
231
+ for (const u of units) {
232
+ for (const m of u.text.matchAll(LEFTOVER)) {
233
+ out.push(f("leftover", "note", u, m[0], `Placeholder still to fill: ${m[0]}`));
234
+ }
235
+ }
236
+ return out;
237
+ }
238
+
239
+ const VAGUE = /\b(significant(?:ly)?|substantial(?:ly)?|dramatic(?:ally)?|drastic(?:ally)?|exponential(?:ly)?|massive(?:ly)?|huge|tremendous(?:ly)?|industry[- ]leading|best[- ]in[- ]class|world[- ]class|cutting[- ]edge|state[- ]of[- ]the[- ]art|game[- ]chang(?:ing|er)|revolutionary|unprecedented|seamless(?:ly)?|robust|next[- ]gen(?:eration)?|many (?:customers|users|teams)|most (?:customers|users|teams)|a lot of|tons of|countless)\b/gi;
240
+
241
+ /** 8. Vague or hype words with nothing measurable behind them. */
242
+ export function vagueClaims(units) {
243
+ const out = [];
244
+ for (const u of units) {
245
+ if (u.heading) continue;
246
+ if (findNumbers(u.text).length) continue; // backed by a figure in the same sentence
247
+ for (const m of u.text.matchAll(VAGUE)) {
248
+ out.push(f("vague-claim", "note", u, m[0], `"${m[0]}" with nothing measurable behind it. Say how much, or cut it.`));
249
+ }
250
+ }
251
+ return out;
252
+ }
253
+
254
+ export const CHECKS = {
255
+ "unsourced-number": unsourcedNumbers,
256
+ "math-error": mathErrors,
257
+ contradiction: contradictions,
258
+ "fake-source": fakeSources,
259
+ "invented-name": inventedNames,
260
+ "date-error": dateErrors,
261
+ leftover: leftovers,
262
+ "vague-claim": vagueClaims,
263
+ };
264
+
265
+ function fullDay(abbr) {
266
+ return { sun: "Sunday", mon: "Monday", tue: "Tuesday", wed: "Wednesday", thu: "Thursday", fri: "Friday", sat: "Saturday" }[abbr];
267
+ }
268
+
269
+ function dedupe(findings) {
270
+ const seen = new Set();
271
+ return findings.filter((x) => {
272
+ const k = `${x.check}|${x.line}|${x.text}|${x.message}`;
273
+ if (seen.has(k)) return false;
274
+ seen.add(k);
275
+ return true;
276
+ });
277
+ }
package/src/dates.js ADDED
@@ -0,0 +1,60 @@
1
+ // Finding dates in text.
2
+
3
+ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
4
+ const MONTH_RE = "(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)";
5
+ const DAY_RE = "(mon|tue|wed|thu|fri|sat|sun)[a-z]*";
6
+ export const WEEKDAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
7
+
8
+ const PATTERNS = [
9
+ // Monday, 3 March 2026 / 3 March / 3rd March 2026
10
+ new RegExp(`(?:\\b${DAY_RE},?\\s+)?\\b(\\d{1,2})(?:st|nd|rd|th)?\\s+${MONTH_RE}\\b\\.?(?:,?\\s+(\\d{4}))?`, "gi"),
11
+ // Monday, March 3, 2026 / March 3rd
12
+ new RegExp(`(?:\\b${DAY_RE},?\\s+)?\\b${MONTH_RE}\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?\\b(?:,?\\s+(\\d{4}))?`, "gi"),
13
+ // 2026-03-03
14
+ /\b(\d{4})-(\d{2})-(\d{2})\b/g,
15
+ ];
16
+
17
+ /** Dates in a sentence: { raw, day, month (1-12), year|null, weekday|null, index }. */
18
+ export function findDates(sentence) {
19
+ const out = [];
20
+ const seen = new Set();
21
+ PATTERNS.forEach((re, p) => {
22
+ for (const m of sentence.matchAll(re)) {
23
+ let weekday = null, day, month, year;
24
+ if (p === 0) {
25
+ [, weekday, day, month, year] = m;
26
+ } else if (p === 1) {
27
+ [, weekday, month, day, year] = m;
28
+ } else {
29
+ [, year, month, day] = m;
30
+ month = MONTHS[+month - 1] ?? "x";
31
+ }
32
+ const mi = MONTHS.indexOf(String(month).slice(0, 3).toLowerCase());
33
+ if (mi < 0) continue;
34
+ // "may" is also a verb: only accept it next to a day number.
35
+ if (seen.has(m.index)) continue;
36
+ seen.add(m.index);
37
+ out.push({
38
+ raw: m[0].trim().replace(/[.,]$/, ""),
39
+ day: +day,
40
+ month: mi + 1,
41
+ year: year ? +year : null,
42
+ weekday: weekday ? weekday.slice(0, 3).toLowerCase() : null,
43
+ index: m.index,
44
+ });
45
+ }
46
+ });
47
+ return out;
48
+ }
49
+
50
+ export function daysInMonth(month, year) {
51
+ return new Date(Date.UTC(year ?? 2024, month, 0)).getUTCDate(); // 2024: leap year, so 29 Feb is allowed without a year
52
+ }
53
+
54
+ export function weekdayOf(day, month, year) {
55
+ return WEEKDAYS[new Date(Date.UTC(year, month - 1, day)).getUTCDay()].slice(0, 3);
56
+ }
57
+
58
+ export function dateKey(d) {
59
+ return `${d.month}-${d.day}`;
60
+ }
package/src/index.js ADDED
@@ -0,0 +1,65 @@
1
+ // factcheck-docs: check an AI-written document against the input it was written from.
2
+
3
+ import { toUnits } from "./text.js";
4
+ import { sourceValues, derivedValues } from "./numbers.js";
5
+ import { findDates, dateKey } from "./dates.js";
6
+ import { CHECKS } from "./checks.js";
7
+
8
+ const WEIGHT = { error: 10, warning: 3, note: 1 };
9
+
10
+ /**
11
+ * Check a markdown document.
12
+ * @param {string} doc The draft to check.
13
+ * @param {object} [opts]
14
+ * @param {string} [opts.source] What the author actually gave the AI (notes, data, thread). Enables source checks.
15
+ * @param {Date|string} [opts.today] Date used for past-date checks. Defaults to now.
16
+ * @param {string[]} [opts.only] Run only these checks.
17
+ * @param {string[]} [opts.allowNames] Names that are fine even if not in the source (your company, your product).
18
+ * @returns {{ score: number, grade: string, findings: object[], counts: object, checksRun: string[] }}
19
+ */
20
+ export function factcheck(doc, opts = {}) {
21
+ const source = opts.source ?? "";
22
+ const hasSource = source.trim().length > 0;
23
+ const values = hasSource ? sourceValues(source) : [];
24
+ const today = opts.today === null ? null : toUtcDay(opts.today ? new Date(opts.today) : new Date());
25
+ const sourceDates = new Set();
26
+ if (hasSource) for (const line of source.split("\n")) for (const d of findDates(line)) sourceDates.add(dateKey(d));
27
+
28
+ const ctx = {
29
+ hasSource,
30
+ sourceLower: source.toLowerCase(),
31
+ values,
32
+ derived: hasSource ? derivedValues(values) : [],
33
+ sourceDates,
34
+ today,
35
+ assumeYear: today ? new Date(today).getUTCFullYear() : null,
36
+ allowNames: new Set((opts.allowNames ?? []).map((n) => n.toLowerCase())),
37
+ };
38
+
39
+ const units = toUnits(doc);
40
+ const names = opts.only?.length ? opts.only : Object.keys(CHECKS);
41
+ const findings = [];
42
+ for (const name of names) {
43
+ const check = CHECKS[name];
44
+ if (!check) throw new Error(`Unknown check: ${name}. Known: ${Object.keys(CHECKS).join(", ")}`);
45
+ findings.push(...check(units, ctx));
46
+ }
47
+ findings.sort((a, b) => a.line - b.line || WEIGHT[b.severity] - WEIGHT[a.severity]);
48
+
49
+ const counts = { error: 0, warning: 0, note: 0 };
50
+ for (const x of findings) counts[x.severity]++;
51
+ const penalty = findings.reduce((s, x) => s + WEIGHT[x.severity], 0);
52
+ const score = Math.max(0, 100 - penalty);
53
+ return { score, grade: grade(score), findings, counts, checksRun: names, sourceChecks: hasSource };
54
+ }
55
+
56
+ export function grade(score) {
57
+ return score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
58
+ }
59
+
60
+ function toUtcDay(d) {
61
+ if (isNaN(d)) throw new Error("Invalid --today date");
62
+ return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
63
+ }
64
+
65
+ export { CHECKS };
package/src/numbers.js ADDED
@@ -0,0 +1,105 @@
1
+ // Finding numbers in text and deciding whether a source supports them.
2
+
3
+ import { stripUrls } from "./text.js";
4
+
5
+ const MONTHS = "jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec";
6
+ const MULT = { k: 1e3, thousand: 1e3, m: 1e6, mn: 1e6, million: 1e6, b: 1e9, bn: 1e9, billion: 1e9 };
7
+
8
+ // A number with optional currency, thousands separators, decimals, scale and unit.
9
+ const NUM_RE =
10
+ /(?<cur>[$€£₹¥]|\b(?:USD|EUR|GBP|INR|Rs\.?)\s?)?(?<n>\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)(?<scale>\s?(?:k|m|mn|bn|b|thousand|million|billion)\b)?(?<pct>\s?%|\s?percent\b|\s?pp\b)?(?<x>x\b)?/gi;
11
+
12
+ /**
13
+ * Every number in a sentence, with its value, kind and position. Dates,
14
+ * list markers, quarter names, versions and years are skipped: dates are
15
+ * handled by the date check.
16
+ */
17
+ export function findNumbers(sentence) {
18
+ const text = stripUrls(sentence);
19
+ const found = [];
20
+ for (const m of text.matchAll(NUM_RE)) {
21
+ const { cur, n, scale, pct, x } = m.groups;
22
+ const start = m.index;
23
+ const end = start + m[0].length;
24
+ const before = text.slice(Math.max(0, start - 12), start);
25
+ const after = text.slice(end, end + 14);
26
+ const raw = m[0].trim();
27
+
28
+ if (/^\s*$/.test(text.slice(0, start)) && /^[.)]\s/.test(after)) continue; // "1. item"
29
+ if (/[A-Za-z_]$/.test(before) && !cur) continue; // Q1, H2, P0, v2, OKR1
30
+ if (/^\.\d/.test(after) || /\d\.$/.test(before)) continue; // version strings 1.2.3
31
+ if (/^\s?(?:st|nd|rd|th)\b/i.test(after)) continue; // ordinals
32
+ if (new RegExp(`(?:${MONTHS})[a-z]*\\.?\\s*$`, "i").test(before)) continue; // May 15
33
+ if (new RegExp(`^\\s*(?:${MONTHS})[a-z]*\\b`, "i").test(after)) continue; // 15 May
34
+ if (/^[-/]\d/.test(after) && /^\d{4}$/.test(n)) continue; // 2026-05-15
35
+ if (/\d[-/]$/.test(before)) continue; // tail of an ISO date
36
+ if (/^\d{4}$/.test(n) && +n >= 1900 && +n <= 2100 && !cur && !pct && !scale) continue; // a year
37
+ if (/^:\d/.test(after) || /\d:$/.test(before)) continue; // times 10:30
38
+ if (/[A-Za-z][-–]$/.test(before)) continue; // L-14, T-3, D-7 countdown labels
39
+ // Section and key-result numbers: "KR 1.1", "Objective 2", "**3.2**", "Step 4.1"
40
+ if (/^\d{1,2}(\.\d{1,2})?$/.test(n) && !cur && !pct && /(?:\b(?:KR|O|Obj(?:ective)?|Key Result|Step|Phase|Section|Stage|Story|Epic)\s*|^[\s>*|#-]*\**)$/i.test(text.slice(Math.max(0, start - 16), start))) continue;
41
+
42
+ let value = parseFloat(n.replace(/,/g, ""));
43
+ if (scale) value *= MULT[scale.trim().toLowerCase()] ?? 1;
44
+ const kind = pct ? "percent" : cur ? "money" : x ? "multiple" : "count";
45
+ // Small bare counts ("3 moves", "2 options") are structure, not claims.
46
+ if (kind === "count" && !scale && value <= 10 && Number.isInteger(value)) continue;
47
+ const duration = !cur && !pct && /^\s?(?:business |working |calendar )?(?:days?|weeks?|wks?|months?|hours?|hrs?|minutes?|mins?|sprints?|quarters?)\b/i.test(after);
48
+ found.push({ raw, value, kind: duration ? "duration" : kind, start, end, decimals: (n.split(".")[1] || "").length });
49
+ }
50
+ return found;
51
+ }
52
+
53
+ /** All numeric values that appear in the source text. */
54
+ export function sourceValues(sourceText) {
55
+ const values = [];
56
+ for (const line of sourceText.split(/\n/)) {
57
+ for (const n of findNumbers(line)) values.push(n.value);
58
+ // Also accept small counts and years from the source, so they can be derived from.
59
+ for (const m of stripUrls(line).matchAll(/\d+(?:\.\d+)?/g)) values.push(parseFloat(m[0]));
60
+ }
61
+ return [...new Set(values)];
62
+ }
63
+
64
+ /**
65
+ * Values a reader can compute from the source: sums, differences, ratios,
66
+ * percentages and percent changes of any two source numbers, and simple
67
+ * time conversions of one.
68
+ */
69
+ export function derivedValues(values) {
70
+ const out = new Set(values);
71
+ for (const a of values) {
72
+ for (const f of [12, 4, 52, 365, 1 / 12, 1 / 4, 1 / 52, 1 / 365]) out.add(a * f);
73
+ if (Math.abs(a) <= 1) out.add(a * 100); // 0.25 -> 25%
74
+ if (Math.abs(a) >= 1) out.add(a / 100); // 25% -> 0.25
75
+ }
76
+ const vs = values.slice(0, 200);
77
+ for (const a of vs) {
78
+ for (const b of vs) {
79
+ if (a === b) continue;
80
+ out.add(a + b);
81
+ out.add(a - b);
82
+ if (b !== 0) {
83
+ out.add(a / b);
84
+ out.add((a / b) * 100);
85
+ out.add(((a - b) / b) * 100);
86
+ out.add(((b - a) / b) * 100);
87
+ }
88
+ out.add((a * b) / 100); // 50% of 3,050
89
+ }
90
+ }
91
+ return [...out];
92
+ }
93
+
94
+ /** True when the value matches a source or derived value, allowing rounding. */
95
+ export function isSupported(n, derived) {
96
+ const tol = Math.max(Math.abs(n.value) * 0.005, 0.5 * 10 ** -n.decimals);
97
+ return derived.some((d) => Math.abs(d - n.value) <= tol || Math.abs(Math.abs(d) - n.value) <= tol);
98
+ }
99
+
100
+ /** True when the sentence marks its figures as not-fact. */
101
+ export function isLabelled(sentence) {
102
+ return /\b(assum\w*|estimat\w*|target\w*|tbd|goal|hypothes\w*|projected|projection|forecast\w*|illustrative|example|e\.g\.|for instance|placeholder|to (?:be )?(?:confirm|validat|verif)\w*|unverified|guess)\b/i.test(
103
+ sentence,
104
+ );
105
+ }
package/src/text.js ADDED
@@ -0,0 +1,63 @@
1
+ // Splitting a markdown document into lines and sentences we can check.
2
+
3
+ const FENCE = /^\s*(```|~~~)/;
4
+
5
+ /**
6
+ * Turn markdown into checkable units. Each unit is one sentence (or one table
7
+ * row) with its 1-based line number. Code blocks, inline code and URLs are
8
+ * masked so their contents are never read as claims.
9
+ */
10
+ export function toUnits(markdown) {
11
+ const units = [];
12
+ let inFence = false;
13
+ const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
14
+ lines.forEach((raw, i) => {
15
+ if (FENCE.test(raw)) {
16
+ inFence = !inFence;
17
+ return;
18
+ }
19
+ if (inFence) return;
20
+ const line = i + 1;
21
+ const heading = /^\s*#{1,6}\s/.test(raw);
22
+ const text = maskCode(raw);
23
+ if (!text.trim()) return;
24
+ if (/^\s*\|/.test(text)) {
25
+ if (/^\s*\|?\s*:?-{3,}/.test(text)) return; // table divider
26
+ units.push({ line, text, raw, heading: false, table: true });
27
+ return;
28
+ }
29
+ for (const s of splitSentences(text)) {
30
+ units.push({ line, text: s, raw, heading, table: false });
31
+ }
32
+ });
33
+ return units;
34
+ }
35
+
36
+ /** Replace inline code with spaces of the same length. */
37
+ export function maskCode(s) {
38
+ return s.replace(/`[^`]*`/g, (m) => " ".repeat(m.length));
39
+ }
40
+
41
+ /** Split a line into sentences without breaking decimals or abbreviations. */
42
+ export function splitSentences(line) {
43
+ const out = [];
44
+ let start = 0;
45
+ const re = /[.!?](?=\s+[A-Z(*"\[]|\s*$)/g;
46
+ let m;
47
+ while ((m = re.exec(line))) {
48
+ const before = line.slice(Math.max(0, m.index - 4), m.index + 1);
49
+ if (/\b(e\.g|i\.e|vs|etc|approx|est|no|Inc|Ltd|Dr|Mr|Ms)\.$/i.test(before)) continue;
50
+ out.push(line.slice(start, m.index + 1).trim());
51
+ start = m.index + 1;
52
+ }
53
+ const rest = line.slice(start).trim();
54
+ if (rest) out.push(rest);
55
+ return out.filter((s) => /[A-Za-z0-9]/.test(s));
56
+ }
57
+
58
+ export const URL_RE = /\bhttps?:\/\/[^\s)\]>"']+/g;
59
+
60
+ /** Text with URLs replaced by spaces, so numbers inside links are ignored. */
61
+ export function stripUrls(s) {
62
+ return s.replace(URL_RE, (m) => " ".repeat(m.length));
63
+ }