@avinashgaurav/manti 0.0.0-stage → 0.3.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 +21 -0
- package/README.md +226 -2
- package/action/run.js +82 -0
- package/action.yml +46 -0
- package/bin/manti.js +123 -0
- package/package.json +50 -4
- package/src/ai.js +109 -0
- package/src/checks.js +534 -0
- package/src/dates.js +69 -0
- package/src/evalchecks.js +182 -0
- package/src/fix.js +137 -0
- package/src/index.js +99 -0
- package/src/morechecks.js +308 -0
- package/src/notecheck.js +130 -0
- package/src/numbers.js +141 -0
- package/src/text.js +64 -0
package/src/ai.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// Optional AI double-check, with the user's own Anthropic key. Off by default: Manti's checks never need it.
|
|
2
|
+
// It catches what rules can't: claims reworded so they no longer match the notes, and claims the notes contradict.
|
|
3
|
+
// Plain fetch (no SDK) so Manti stays zero-dependency and the website needs no build step.
|
|
4
|
+
// Every finding must quote the draft word for word; anything that doesn't is dropped, so the AI can't invent lines.
|
|
5
|
+
|
|
6
|
+
export const AI_MODEL = "claude-opus-5-5";
|
|
7
|
+
|
|
8
|
+
const SYSTEM = `You check a draft written by an AI against the notes its author gave it.
|
|
9
|
+
List every claim in the draft that the notes do not support, or that the notes contradict. Include claims that were reworded, merged, exaggerated, or given a cause, date, owner, or comparison the notes never state.
|
|
10
|
+
Do not list: wording or style; claims the notes support, even if phrased differently; claims marked as an assumption, estimate, target, or opinion.
|
|
11
|
+
For each claim, "quote" must be copied exactly, character for character, from one line of the draft (short: the claim only, not the whole paragraph). "problem" says in one plain sentence what the notes say instead, or that they say nothing about it. "fix" is a corrected version of the quote that the notes support, or an empty string if the claim should be cut. Use "error" when the notes contradict the claim and "warning" when the notes are silent.
|
|
12
|
+
If every claim is supported, return an empty list.`;
|
|
13
|
+
|
|
14
|
+
const SCHEMA = {
|
|
15
|
+
type: "object",
|
|
16
|
+
properties: {
|
|
17
|
+
findings: {
|
|
18
|
+
type: "array",
|
|
19
|
+
items: {
|
|
20
|
+
type: "object",
|
|
21
|
+
properties: {
|
|
22
|
+
quote: { type: "string" },
|
|
23
|
+
problem: { type: "string" },
|
|
24
|
+
severity: { type: "string", enum: ["error", "warning"] },
|
|
25
|
+
fix: { type: "string" },
|
|
26
|
+
},
|
|
27
|
+
required: ["quote", "problem", "severity", "fix"],
|
|
28
|
+
additionalProperties: false,
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
required: ["findings"],
|
|
33
|
+
additionalProperties: false,
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Ask Claude which claims in the draft the notes don't support.
|
|
38
|
+
* @param {string} draft
|
|
39
|
+
* @param {string} source the notes (required: without them there is nothing to check against)
|
|
40
|
+
* @param {object} opts
|
|
41
|
+
* @param {string} opts.apiKey the user's Anthropic API key
|
|
42
|
+
* @param {string} [opts.model] defaults to AI_MODEL
|
|
43
|
+
* @param {boolean} [opts.browser] true when called from a web page (adds the direct-browser-access header)
|
|
44
|
+
* @param {AbortSignal} [opts.signal]
|
|
45
|
+
* @returns {Promise<object[]>} findings in Manti's shape, check "ai-claim"
|
|
46
|
+
*/
|
|
47
|
+
export async function aiCheck(draft, source, { apiKey, model = AI_MODEL, browser = false, signal } = {}) {
|
|
48
|
+
if (!apiKey) throw new Error("No API key. The AI double-check uses your own Anthropic key.");
|
|
49
|
+
if (!source?.trim()) throw new Error("The AI double-check needs your notes to check against.");
|
|
50
|
+
const headers = {
|
|
51
|
+
"content-type": "application/json",
|
|
52
|
+
"x-api-key": apiKey,
|
|
53
|
+
"anthropic-version": "2026-10-21",
|
|
54
|
+
// if a safety classifier declines, the API retries on a fallback model in the same call
|
|
55
|
+
"anthropic-beta": "server-side-fallback-2026-07-01",
|
|
56
|
+
};
|
|
57
|
+
if (browser) headers["anthropic-dangerous-direct-browser-access"] = "true";
|
|
58
|
+
const res = await fetch("https://api.anthropic.com/v1/messages", {
|
|
59
|
+
method: "POST",
|
|
60
|
+
headers,
|
|
61
|
+
signal,
|
|
62
|
+
body: JSON.stringify({
|
|
63
|
+
model,
|
|
64
|
+
max_tokens: 16000,
|
|
65
|
+
fallbacks: "default",
|
|
66
|
+
output_config: { effort: "medium", format: { type: "json_schema", schema: SCHEMA } },
|
|
67
|
+
system: SYSTEM,
|
|
68
|
+
messages: [{ role: "user", content: `<notes>\n${source}\n</notes>\n\n<draft>\n${draft}\n</draft>` }],
|
|
69
|
+
}),
|
|
70
|
+
});
|
|
71
|
+
if (!res.ok) {
|
|
72
|
+
let detail = "";
|
|
73
|
+
try { detail = (await res.json())?.error?.message ?? ""; } catch {}
|
|
74
|
+
const why = res.status === 401 ? "The API key was not accepted." : res.status === 429 ? "Rate limited: try again in a minute." : res.status === 529 || res.status >= 500 ? "The API is busy: try again shortly." : `The API returned ${res.status}.`;
|
|
75
|
+
throw new Error(`${why}${detail ? ` (${detail})` : ""}`);
|
|
76
|
+
}
|
|
77
|
+
const msg = await res.json();
|
|
78
|
+
if (msg.stop_reason === "refusal") throw new Error("The AI declined to check this draft.");
|
|
79
|
+
if (msg.stop_reason === "max_tokens") throw new Error("The draft is too long for one AI pass. Check it in parts.");
|
|
80
|
+
const text = (msg.content ?? []).filter((b) => b.type === "text").map((b) => b.text).join("");
|
|
81
|
+
let parsed;
|
|
82
|
+
try { parsed = JSON.parse(text); } catch { throw new Error("The AI reply was not valid JSON."); }
|
|
83
|
+
return toFindings(draft, parsed.findings ?? []);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Keep only findings whose quote is really in the draft, and give each its line number. */
|
|
87
|
+
export function toFindings(draft, items) {
|
|
88
|
+
const lines = draft.replace(/\r\n?/g, "\n").split("\n");
|
|
89
|
+
const squash = (s) => s.replace(/[“”]/g, '"').replace(/[‘’]/g, "'").replace(/\s+/g, " ").trim();
|
|
90
|
+
const out = [];
|
|
91
|
+
const seen = new Set();
|
|
92
|
+
for (const it of items) {
|
|
93
|
+
const q = squash(it.quote ?? "");
|
|
94
|
+
if (q.length < 4) continue;
|
|
95
|
+
const i = lines.findIndex((l) => squash(l).includes(q));
|
|
96
|
+
if (i < 0 || seen.has(`${i}|${q}`)) continue;
|
|
97
|
+
seen.add(`${i}|${q}`);
|
|
98
|
+
const exact = lines[i].includes(it.quote) ? it.quote : null;
|
|
99
|
+
out.push({
|
|
100
|
+
check: "ai-claim",
|
|
101
|
+
severity: it.severity === "error" ? "error" : "warning",
|
|
102
|
+
line: i + 1,
|
|
103
|
+
text: exact ?? q,
|
|
104
|
+
message: `${it.problem}${it.fix ? ` Suggested: "${it.fix}"` : ""}`.trim(),
|
|
105
|
+
...(exact && it.fix ? { suggest: { from: exact, to: it.fix } } : {}),
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
package/src/checks.js
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
// The script checks (eight here, six in evalchecks.js, nine in morechecks.js). 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, sourceValues } from "./numbers.js";
|
|
7
|
+
import { findDates, daysInMonth, weekdayOf, dateKey } from "./dates.js";
|
|
8
|
+
import { URL_RE } from "./text.js";
|
|
9
|
+
import { inventedQuotes, periodMismatch, tableTotals, overclaims, missingOwners, missingSections } from "./evalchecks.js";
|
|
10
|
+
import { notesConflict, countMismatch } from "./notecheck.js";
|
|
11
|
+
import { topicWords } from "./morechecks.js";
|
|
12
|
+
import { scaleMismatch, roundingDrift, percentPoints, directionFlip, relativeDates, brokenLinks, roleChanges, readability, missingFacts } from "./morechecks.js";
|
|
13
|
+
|
|
14
|
+
const f = (check, severity, unit, text, message) => ({ check, severity, line: unit.line, text, message });
|
|
15
|
+
|
|
16
|
+
/** 1. Figures that are neither in the source nor labelled as assumptions. */
|
|
17
|
+
export function unsourcedNumbers(units, ctx) {
|
|
18
|
+
if (!ctx.hasSource) return [];
|
|
19
|
+
// Numbers the doc derives step by step (a rate, then a gap from that rate)
|
|
20
|
+
// are supported if each step is. Grow the pool of supported values over a
|
|
21
|
+
// few passes, and let each sentence or table row combine its own supported
|
|
22
|
+
// numbers (an ICE score is the product of the row's three inputs).
|
|
23
|
+
let pool = ctx.values.slice();
|
|
24
|
+
const figPool = (ctx.figures ?? ctx.values).slice();
|
|
25
|
+
let derived = ctx.derived;
|
|
26
|
+
const sortAbs = (arr) => Float64Array.from(arr.filter(Number.isFinite).map(Math.abs)).sort();
|
|
27
|
+
let derivedSorted = sortAbs(derived);
|
|
28
|
+
const supported = new Set();
|
|
29
|
+
const supKeys = new Set(); // line|start|raw of each supported figure, so later passes can look them up
|
|
30
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
31
|
+
ctx._topicPass = pass;
|
|
32
|
+
let grew = false;
|
|
33
|
+
for (const u of units) {
|
|
34
|
+
const nums = findNumbers(u.text);
|
|
35
|
+
const local = [];
|
|
36
|
+
const labelled = isLabelled(u.text); // "a target of 45% (my assumption)": figures computed from it are fine too
|
|
37
|
+
for (const n of nums) {
|
|
38
|
+
if (supported.has(n) || labelled || (inSorted(n, derivedSorted) && (isLiteral(n, ctx) || inSorted(n, topicDerived(u, units, supported, ctx))))) {
|
|
39
|
+
if (!supported.has(n)) { supported.add(n); supKeys.add(`${u.line}|${n.start}|${n.raw}`); grew = true; pool.push(n.value); figPool.push(n.value); }
|
|
40
|
+
local.push(n.value);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const combos = rowCombos(local);
|
|
44
|
+
for (const n of nums) {
|
|
45
|
+
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))) {
|
|
46
|
+
supported.add(n); supKeys.add(`${u.line}|${n.start}|${n.raw}`); grew = true; pool.push(n.value); figPool.push(n.value);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (!grew) break;
|
|
51
|
+
derived = derivedValues([...new Set(pool)], [...new Set(figPool)]);
|
|
52
|
+
derivedSorted = sortAbs(derived);
|
|
53
|
+
}
|
|
54
|
+
const out = [];
|
|
55
|
+
ctx._topicPass = "final";
|
|
56
|
+
for (const u of units) {
|
|
57
|
+
if (u.heading) continue;
|
|
58
|
+
for (const n of findNumbers(u.text)) {
|
|
59
|
+
if (supKeys.has(`${u.line}|${n.start}|${n.raw}`) && inSorted(n, derivedSorted)) continue;
|
|
60
|
+
if (isLabelled(u.text)) continue;
|
|
61
|
+
if (inSorted(n, derivedSorted)) {
|
|
62
|
+
// a figure that is only "computable" must be computable from notes about the same thing:
|
|
63
|
+
// two unrelated numbers in the notes can combine to almost anything
|
|
64
|
+
if (ctx.values.some((v) => Math.abs(v - n.value) <= Math.max(Math.abs(n.value) * 0.005, 0.5 * 10 ** -n.decimals))) continue;
|
|
65
|
+
if (inSorted(n, topicDerived(u, units, supported, ctx))) continue;
|
|
66
|
+
}
|
|
67
|
+
const severity = n.kind === "count" || n.kind === "duration" ? "warning" : "error";
|
|
68
|
+
const what = n.kind === "duration" ? "This duration" : n.raw;
|
|
69
|
+
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.`));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const isLiteral = (n, ctx) => ctx.values.some((v) => Math.abs(v - n.value) <= Math.max(Math.abs(n.value) * 0.005, 0.5 * 10 ** -n.decimals));
|
|
76
|
+
|
|
77
|
+
// Values a reader could combine for this sentence: figures from note lines that share a topic word with it,
|
|
78
|
+
// plus figures this draft already established nearby or about the same thing. Built once per sentence and cached:
|
|
79
|
+
// a naive version of this was quadratic to cubic on long docs.
|
|
80
|
+
function topicDerived(u, units, supported, ctx) {
|
|
81
|
+
const memo = (ctx._topic ??= { unitWords: new Map(), unitNums: new Map(), table: new Map(), cache: new Map(), notes: null, idx: new Map(units.map((x, k) => [x, k])) });
|
|
82
|
+
const tw = (v) => memo.unitWords.get(v) ?? memo.unitWords.set(v, topicWords(v.text)).get(v);
|
|
83
|
+
const nums = (v) => memo.unitNums.get(v) ?? memo.unitNums.set(v, findNumbers(v.text)).get(v);
|
|
84
|
+
memo.notes ??= (ctx.source ?? "").split("\n").filter((l) => l.trim()).map((l) => ({ words: topicWords(l), vals: sourceValues(l) }));
|
|
85
|
+
if (!memo.table.size) {
|
|
86
|
+
let b = 0;
|
|
87
|
+
units.forEach((x, k) => { if (x.table && !(k && units[k - 1].table)) b++; memo.table.set(x, x.table ? b : 0); });
|
|
88
|
+
}
|
|
89
|
+
// one build per sentence per pass of the caller (the supported pool only grows between passes that matter)
|
|
90
|
+
const hit = memo.cache.get(u);
|
|
91
|
+
if (hit && hit.pass === ctx._topicPass) return hit.out;
|
|
92
|
+
if (memo.supPass !== ctx._topicPass || memo.supSize !== supported.size) { memo.supVals = new Set([...supported].map((x) => x.value)); memo.supPass = ctx._topicPass; memo.supSize = supported.size; }
|
|
93
|
+
const supVals = memo.supVals;
|
|
94
|
+
const idx = memo.idx.get(u);
|
|
95
|
+
const near = units.slice(Math.max(0, idx - 2), idx + 1);
|
|
96
|
+
// the topic is this sentence plus the two before it ("...target (45%)... It's an 11-point gain, or 32% relative")
|
|
97
|
+
const words = new Set(near.flatMap((v) => [...tw(v)]));
|
|
98
|
+
const vals = [];
|
|
99
|
+
const shares = (set) => { for (const w of set) if (words.has(w)) return true; return false; };
|
|
100
|
+
for (const n of memo.notes) if (shares(n.words)) vals.push(...n.vals); // includes "2 roles", "12 months"
|
|
101
|
+
for (const m of u.text.matchAll(/(?<![\w.$€£₹])\d{1,2}(?![\d.,%])/g)) vals.push(+m[0]); // "2 | $185,000 | $370,000"
|
|
102
|
+
const block = memo.table.get(u);
|
|
103
|
+
for (let k = Math.max(0, idx - 200); k <= idx; k++) {
|
|
104
|
+
const v = units[k];
|
|
105
|
+
if (!(k >= idx - 2 || (block && memo.table.get(v) === block) || shares(tw(v)))) continue;
|
|
106
|
+
for (const n of nums(v)) if (supVals.has(n.value)) vals.push(n.value);
|
|
107
|
+
}
|
|
108
|
+
const uniq = [...new Set(vals)].slice(0, 40);
|
|
109
|
+
const out = derivedValues(uniq);
|
|
110
|
+
// a figure from the sentences just before may combine with any figure in the notes (34% today, 45% target -> 32% relative)
|
|
111
|
+
const nearVals = near.flatMap((v) => nums(v)).filter((n) => supVals.has(n.value)).map((n) => n.value);
|
|
112
|
+
// within one topic, products are fair: 2 roles x $185k, 312 accounts x 11 seats x $10 (triples on the first 12 only)
|
|
113
|
+
for (let i = 0; i < uniq.length; i++) for (let j = i + 1; j < uniq.length; j++) {
|
|
114
|
+
out.push(uniq[i] * uniq[j]);
|
|
115
|
+
if (j < 12) for (let k = j + 1; k < 12 && k < uniq.length; k++) out.push(uniq[i] * uniq[j] * uniq[k]);
|
|
116
|
+
}
|
|
117
|
+
const sorted = Float64Array.from(out.filter(Number.isFinite).map(Math.abs)).sort();
|
|
118
|
+
sorted.nearVals = nearVals; // checked lazily against the notes in inSorted (pairing them up front was millions of values)
|
|
119
|
+
sorted.noteVals = ctx.values;
|
|
120
|
+
memo.cache.set(u, { pass: ctx._topicPass, out: sorted });
|
|
121
|
+
return sorted;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// is n within rounding of a value in a sorted list? (binary search; the list can hold tens of thousands of values)
|
|
125
|
+
function inSorted(n, arr) {
|
|
126
|
+
const v = Math.abs(n.value), tol = Math.max(v * 0.005, 0.5 * 10 ** -n.decimals);
|
|
127
|
+
let lo = 0, hi = arr.length - 1;
|
|
128
|
+
while (lo <= hi) {
|
|
129
|
+
const mid = (lo + hi) >> 1;
|
|
130
|
+
if (arr[mid] < v - tol) lo = mid + 1;
|
|
131
|
+
else if (arr[mid] > v + tol) hi = mid - 1;
|
|
132
|
+
else return true;
|
|
133
|
+
}
|
|
134
|
+
// a figure from the sentences just before may combine with any figure in the notes (34% today, 45% target -> 32% relative)
|
|
135
|
+
if (arr.nearVals) for (const a of arr.nearVals) for (const b of arr.noteVals) {
|
|
136
|
+
const c = [a + b, a - b, b - a];
|
|
137
|
+
if (b) c.push((a / b) * 100, ((a - b) / b) * 100, ((b - a) / b) * 100);
|
|
138
|
+
if (a) c.push((b / a) * 100, ((b - a) / a) * 100, ((a - b) / a) * 100);
|
|
139
|
+
if (c.some((x) => Math.abs(Math.abs(x) - v) <= tol)) return true;
|
|
140
|
+
}
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function rowCombos(vals) {
|
|
145
|
+
const out = [];
|
|
146
|
+
const v = vals.slice(0, 8);
|
|
147
|
+
for (let i = 0; i < v.length; i++)
|
|
148
|
+
for (let j = i + 1; j < v.length; j++) {
|
|
149
|
+
out.push(v[i] * v[j], v[i] + v[j]);
|
|
150
|
+
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]);
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 2. Arithmetic the document states and gets wrong. */
|
|
156
|
+
// is "nearly 20%" a fair way to say 12.5%? (nearly: just below; over: below the actual; about: within 10%)
|
|
157
|
+
function approxOk(q, actual, claimed) {
|
|
158
|
+
if (/nearly|almost|just under/.test(q)) return claimed >= actual - 0.5 && claimed <= actual * 1.12 + 1;
|
|
159
|
+
if (/just over/.test(q)) return claimed <= actual && claimed >= actual * 0.88 - 1;
|
|
160
|
+
if (/over|more than/.test(q)) return claimed <= actual + 0.5;
|
|
161
|
+
if (/under|less than/.test(q)) return claimed >= actual - 0.5;
|
|
162
|
+
return Math.abs(actual - claimed) <= Math.max(1, actual * 0.1);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function mathErrors(units, ctx = {}) {
|
|
166
|
+
const out = [];
|
|
167
|
+
const num = (s) => parseFloat(s.replace(/,/g, ""));
|
|
168
|
+
for (const u of units) {
|
|
169
|
+
const t = u.text;
|
|
170
|
+
// "from 42,000 to 51,000 (+21%)" or "from 10% to 6%, a 40% drop"
|
|
171
|
+
for (const m of t.matchAll(/from\s+[$€£₹]?([\d,.]*\d)(?![\d,.]*\d)\s*%?\s*(?:[a-zA-Z]+\s+){0,3}to\s+[$€£₹]?([\d,.]*\d)(?![\d,.]*\d)\s*%?([^.%\d]{0,40}?)(?<![\d.])([+-]?\d+(?:\.\d+)?)\s*%\s*(increase|rise|growth|jump|up|drop|decrease|decline|fall|down|lift|more|less|higher|lower)?/gi)) {
|
|
172
|
+
// the % must read as the change: "(+21%)", ", up 21%", ", a 21% rise"; not "..., and CSAT was 91%"
|
|
173
|
+
// an approximation word before the % ("up nearly 20%", "(about 7% more)") is allowed and judged by its meaning
|
|
174
|
+
const q = (/(?:nearly|almost|just under|just over|about|around|roughly|approximately|over|more than|under|less than|~)\s*$/i.exec(m[3]) || [""])[0].trim().toLowerCase();
|
|
175
|
+
const lead = q ? m[3].trimEnd().slice(0, m[3].trimEnd().length - q.length) : m[3];
|
|
176
|
+
if (!m[5] && !/(?:^|[\s(])(?:up|down|by|an?|or)\s*$|[(,:;\u2013\u2014-]\s*$|^[\s\w]{0,3}$/i.test(q ? lead.replace(/\s+$/, "") + " " : m[3])) continue;
|
|
177
|
+
if (!m[5] && /\b(?:and|but|while|whereas|was|were|is|are)\b/i.test(m[3])) continue;
|
|
178
|
+
const a = num(m[1]), b = num(m[2]), claimed = Math.abs(num(m[4]));
|
|
179
|
+
if (!a || isNaN(b) || isNaN(claimed)) continue;
|
|
180
|
+
const actual = Math.abs(((b - a) / a) * 100);
|
|
181
|
+
const tol = Math.max(1, actual * 0.05);
|
|
182
|
+
const wrong = q ? !approxOk(q, actual, claimed) : Math.abs(actual - claimed) > tol;
|
|
183
|
+
if (wrong && Math.abs(Math.abs(b - a) - claimed) > 0.5) {
|
|
184
|
+
out.push(f("math-error", "error", u, m[0].trim(), `Change from ${m[1]} to ${m[2]} is ${actual.toFixed(1)}%, not ${m[4]}%.`));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
// "300 of 1,200 (25%)" / "300 out of 1,200, or 25%"
|
|
188
|
+
for (const m of t.matchAll(/([\d,]+(?:\.\d+)?)\s+(?:out\s+)?of\s+(?:the\s+)?([\d,]+(?:\.\d+)?)\b([^.%\d]{0,40}?)(\d+(?:\.\d+)?)\s*%/gi)) {
|
|
189
|
+
const a = num(m[1]), b = num(m[2]), claimed = num(m[4]);
|
|
190
|
+
const qq = (/(?:nearly|almost|just under|just over|about|around|roughly|approximately|over|more than|under|less than|~)\s*$/i.exec(m[3]) || [""])[0].trim().toLowerCase();
|
|
191
|
+
if (qq && b && !approxOk(qq, (a / b) * 100, claimed)) { out.push(f("math-error", "error", u, m[0].trim(), `${m[1]} of ${m[2]} is ${((a / b) * 100).toFixed(1)}%, so "${qq} ${m[4]}%" is wrong.`)); continue; }
|
|
192
|
+
if (qq) continue;
|
|
193
|
+
if (!b) continue;
|
|
194
|
+
const actual = (a / b) * 100;
|
|
195
|
+
if (Math.abs(actual - claimed) > Math.max(0.6, actual * 0.02)) {
|
|
196
|
+
out.push(f("math-error", "error", u, m[0].trim(), `${m[1]} of ${m[2]} is ${actual.toFixed(1)}%, not ${m[4]}%.`));
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
// "a + b = c" and "a x b = c"
|
|
200
|
+
for (const m of t.matchAll(/([\d,]+(?:\.\d+)?)\s*([+\-x×*\/÷])\s*([\d,]+(?:\.\d+)?)\s*=\s*([\d,]+(?:\.\d+)?)/g)) {
|
|
201
|
+
const a = num(m[1]), b = num(m[3]), c = num(m[4]);
|
|
202
|
+
const op = m[2];
|
|
203
|
+
const r = op === "+" ? a + b : op === "-" ? a - b : /[x×*]/.test(op) ? a * b : a / b;
|
|
204
|
+
if (Math.abs(r - c) > Math.max(0.01, Math.abs(r) * 0.005)) {
|
|
205
|
+
out.push(f("math-error", "error", u, m[0].trim(), `${m[1]} ${op} ${m[3]} is ${+r.toFixed(2)}, not ${m[4]}.`));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
// the claim before the pair ("grew 16%, from 35.1% to 38.6%") or in the next sentence ("... to 38.6%. That is a 16% increase.")
|
|
210
|
+
const pairOf = (t) => {
|
|
211
|
+
const m = t.match(/from\s+([$€£₹]?)([\d,.]*\d)\s*(%|[kmb]n?\b)?\s*(?:[a-zA-Z]+\s+){0,3}?to\s+([$€£₹]?)([\d,.]*\d)\s*(%|[kmb]n?\b)?/i);
|
|
212
|
+
if (!m) return null;
|
|
213
|
+
const a = num(m[2]), b = num(m[5]);
|
|
214
|
+
const isYear = (x, cur, suf) => !cur && !suf && Number.isInteger(x) && x >= 1900 && x <= 2100;
|
|
215
|
+
if (isYear(a, m[1], m[3]) || isYear(b, m[4], m[6])) return null; // "from 2025 to 2026" is a span of time
|
|
216
|
+
return { a, b, pct: m[3] === "%" && m[6] === "%" };
|
|
217
|
+
};
|
|
218
|
+
units.forEach((u, i) => {
|
|
219
|
+
const before = u.text.match(/\b(?:up|down|rose|fell|grew|increased|decreased|dropped|declined|climbed|jumped|went up|went down)\s+(?:by\s+)?(\d+(?:\.\d+)?)\s?%,?\s+from\s/i);
|
|
220
|
+
const next = /^(?:that|this|which)(?:'s|\s+is|\s+was|\s+means)\s+(?:an?\s+|about\s+|roughly\s+)?(\d+(?:\.\d+)?)\s?%\s+(?:increase|rise|growth|drop|decrease|decline|improvement|jump|fall|gain|lift|reduction|cut)/i.exec(u.text);
|
|
221
|
+
const claimed = before ? before[1] : next ? next[1] : null;
|
|
222
|
+
if (!claimed) return;
|
|
223
|
+
if (next && /\b(?:over|than|versus|vs\.?|against|compared (?:to|with)|relative to)\s+(?:the\s+)?(?:plan|target|budget|forecast|goal|last|prior|previous)/i.test(u.text)) return;
|
|
224
|
+
const p = pairOf(before ? u.text.slice(before.index) : (units[i - 1]?.text ?? ""));
|
|
225
|
+
if (!p || !p.a || isNaN(p.b)) return;
|
|
226
|
+
const actual = Math.abs(((p.b - p.a) / p.a) * 100), c = parseFloat(claimed);
|
|
227
|
+
if (Math.abs(actual - c) > Math.max(1, actual * 0.05) && !(p.pct && Math.abs(Math.abs(p.b - p.a) - c) < 0.05)) {
|
|
228
|
+
out.push(f("math-error", "error", u, `${claimed}%`, `From ${p.a} to ${p.b} is a ${actual.toFixed(1)}% change, not ${claimed}%.`));
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
// tables: a change column that doesn't match the two figures before it ("$99 | $115 | +18.2%")
|
|
232
|
+
const cellNum = (c) => { const m = c.replace(/\*\*/g, "").match(/^\s*[$€£₹]?\s*([\d,]+(?:\.\d+)?)\s*(k|m)?\b(?!\s*%)/i); return m ? parseFloat(m[1].replace(/,/g, "")) * ({ k: 1e3, m: 1e6 }[(m[2] || "").toLowerCase()] ?? 1) : null; };
|
|
233
|
+
let header = null, prevLine = -9;
|
|
234
|
+
for (const u of units) {
|
|
235
|
+
if (!u.table) { header = null; continue; }
|
|
236
|
+
const cells = u.text.split(/(?<!\\)\|/).slice(1, -1).map((c) => c.trim());
|
|
237
|
+
if (!header || u.line > prevLine + 2) { header = cells; prevLine = u.line; continue; }
|
|
238
|
+
prevLine = u.line;
|
|
239
|
+
for (let c = 2; c < cells.length; c++) {
|
|
240
|
+
const pm = cells[c].replace(/\*\*/g, "").match(/^([+\-−]?)(\d+(?:\.\d+)?)\s*%$/);
|
|
241
|
+
if (!pm || !(pm[1] || /change|delta|diff|growth|increase|decrease|uplift|%/i.test(header[c] || ""))) continue;
|
|
242
|
+
const a = cellNum(cells[c - 2]), b = cellNum(cells[c - 1]);
|
|
243
|
+
if (!a || b == null) continue;
|
|
244
|
+
const actual = ((b - a) / a) * 100, claimed = (pm[1] === "-" || pm[1] === "−" ? -1 : 1) * parseFloat(pm[2]);
|
|
245
|
+
if (Math.abs(actual - claimed) > Math.max(0.6, Math.abs(actual) * 0.02)) {
|
|
246
|
+
out.push(f("math-error", "error", u, cells[c], `${cells[c - 2]} to ${cells[c - 1]} is ${Math.abs(actual).toFixed(1)}%, not ${pm[2]}%.`));
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
// "the Enterprise plan will increase by approximately 15%" when its table row goes $1,499 -> $1,799 (20%)
|
|
251
|
+
const rows = units.filter((u) => u.table).map((u) => u.text.split(/(?<!\\)\|/).slice(1, -1).map((c) => c.trim()))
|
|
252
|
+
.filter((c) => c.length >= 3).map((c) => ({ label: c[0].replace(/\*\*/g, "").toLowerCase(), nums: c.slice(1).map(cellNum).filter((x) => x != null) }))
|
|
253
|
+
.filter((r) => r.nums.length >= 2 && /[a-z]{4,}/.test(r.label));
|
|
254
|
+
if (rows.length) for (const u of units) {
|
|
255
|
+
if (u.table || u.heading) continue;
|
|
256
|
+
for (const clause of u.text.split(/,\s*while\s+|;\s*|\s+while\s+|,\s*and\s+(?=the\s)/i)) {
|
|
257
|
+
const m = clause.match(/\b(?:increase|rise|grow|raise|reduce|cut|lower|decrease|drop|fall|decline)\w*\s+(?:\w+\s+){0,3}?by\s+(?:approximately\s+|about\s+|around\s+|roughly\s+|~)?(\d+(?:\.\d+)?)\s?%/i);
|
|
258
|
+
if (!m) continue;
|
|
259
|
+
const cw = clause.toLowerCase();
|
|
260
|
+
// the clause names the row: every label word, or all but one when the label has three or more
|
|
261
|
+
const row = rows.find((r) => { const lw = (r.label.match(/[a-z]{4,}/g) || []).filter((w) => !/^(?:monthly|current|proposed|total)$/.test(w)); const hit = lw.filter((w) => cw.includes(w)).length; return lw.length && (hit === lw.length || (lw.length >= 3 && hit >= lw.length - 1)); });
|
|
262
|
+
if (!row) continue;
|
|
263
|
+
const [a, b] = row.nums, actual = (Math.abs(b - a) / a) * 100, claimed = parseFloat(m[1]);
|
|
264
|
+
const loose = /approximately|about|around|roughly|~/i.test(m[0]);
|
|
265
|
+
if (a && Math.abs(actual - claimed) > Math.max(loose ? 2 : 0.6, actual * (loose ? 0.1 : 0.02))) {
|
|
266
|
+
out.push(f("math-error", "error", u, `${m[1]}%`, `${row.label[0].toUpperCase() + row.label.slice(1)} goes from ${a.toLocaleString("en-US")} to ${b.toLocaleString("en-US")}: that change is ${actual.toFixed(1)}%, not ${m[1]}%.`));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
// "31 accounts (82.5%)" when the notes say "31 accounts (77.5%)"
|
|
271
|
+
if (ctx.hasSource) {
|
|
272
|
+
const PAIR = /([\d,]+)\s+([a-z]+?)s?\s*\((\d+(?:\.\d+)?)%\)/gi;
|
|
273
|
+
const known = new Map();
|
|
274
|
+
for (const m of (ctx.source ?? "").matchAll(PAIR)) known.set(`${m[1]}|${m[2].toLowerCase()}`, m[3]);
|
|
275
|
+
for (const u of units) for (const m of u.text.matchAll(PAIR)) {
|
|
276
|
+
const want = known.get(`${m[1]}|${m[2].toLowerCase()}`);
|
|
277
|
+
if (want && Math.abs(parseFloat(want) - parseFloat(m[3])) > 0.05) out.push(f("math-error", "error", u, m[0], `In your notes, ${m[1]} ${m[2]}s is ${want}%, not ${m[3]}%.`));
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return out;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
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 were has have had about around roughly nearly almost " +
|
|
284
|
+
"says said say needed need costs cost paid pays pay only just also each every then than over under at least some all").split(" "));
|
|
285
|
+
|
|
286
|
+
/** 3. The same metric stated with two different values. */
|
|
287
|
+
export function contradictions(units) {
|
|
288
|
+
const seen = new Map();
|
|
289
|
+
const out = [];
|
|
290
|
+
for (const u of units) {
|
|
291
|
+
if (u.heading || u.table || isLabelled(u.text)) continue;
|
|
292
|
+
for (const n of findNumbers(u.text)) {
|
|
293
|
+
if (n.kind !== "percent" && n.kind !== "money" && n.kind !== "count") continue;
|
|
294
|
+
let key;
|
|
295
|
+
if (n.kind === "count") {
|
|
296
|
+
// "4 customers asked" vs "6 customers asked": the two words after the number name the metric
|
|
297
|
+
// only in prose, and only when the number is directly followed by the metric's words
|
|
298
|
+
const m = !u.table && u.text.slice(n.end).match(/^\s+([a-z][a-z-]+)\s+([a-z][a-z-]+)\b/);
|
|
299
|
+
key = m && !STOP.has(m[1]) && !STOP.has(m[2]) && !/^(?:hours?|days?|weeks?|months?|mins?|minutes?|people|times)$/.test(m[1]) ? `${m[1]} ${m[2]}` : "";
|
|
300
|
+
} else {
|
|
301
|
+
const words = u.text.slice(0, n.start).toLowerCase().match(/[a-z][a-z-]+/g) || [];
|
|
302
|
+
key = words.filter((w) => !STOP.has(w) && w.length > 2).slice(-1).join(" ");
|
|
303
|
+
}
|
|
304
|
+
if (MONTH_OR_DAY.test(key)) continue; // "7 January: 10%", "11 January: 50%" are a schedule, not one metric
|
|
305
|
+
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;
|
|
306
|
+
const k = `${n.kind}:${key}`;
|
|
307
|
+
const prev = seen.get(k);
|
|
308
|
+
if (prev && Math.abs(prev.value - n.value) > 1e-9 && prev.unit !== u) {
|
|
309
|
+
out.push(f("contradiction", "warning", u, n.raw, `"${key}" is ${n.raw} here but ${prev.raw} ${prev.line === u.line ? "earlier on this line" : `on line ${prev.line}`}.`));
|
|
310
|
+
} else if (!prev) seen.set(k, { value: n.value, raw: n.raw, line: u.line, unit: u });
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
// restatements: "Gross margin came in at 85% for the period.", "Recap: churn at 3%.", "Net revenue churn is 2.9%."
|
|
314
|
+
const RESTATE = /^(?:recap:\s*|in summary,?\s*|overall,?\s*)?(?:the\s+|our\s+)?([A-Za-z][\w -]{2,50}?)\s+(?:is|was|were|are|came in at|stood at|ended at|landed at|finished at|totall?ed|at)\s+(?:about\s+|around\s+)?([$€£₹]?\d[\d,]*(?:\.\d+)?\s?(?:%|k|m|bn)?)/i;
|
|
315
|
+
const stemW = (w) => w.toLowerCase().replace(/(?:ies|es|s)$/, "");
|
|
316
|
+
for (const u of units) {
|
|
317
|
+
if (u.heading || u.table || isLabelled(u.text)) continue;
|
|
318
|
+
const m = u.text.match(RESTATE);
|
|
319
|
+
if (!m) continue;
|
|
320
|
+
const n = findNumbers(m[2])[0];
|
|
321
|
+
if (!n) continue;
|
|
322
|
+
const subj = (m[1].toLowerCase().match(/[a-z][a-z-]+/g) || []).filter((w) => !STOP.has(w) && w.length > 2).map(stemW);
|
|
323
|
+
if (!subj.length) continue;
|
|
324
|
+
const QUAL = /\b(?:net|gross|adjusted|organic|total|annual|monthly|weekly|daily|average|median|new|existing)\b/gi;
|
|
325
|
+
const quals = (t) => new Set((t.toLowerCase().match(QUAL) || []));
|
|
326
|
+
const TIME = /\b(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?|q[1-4]|h[12]|20\d\d|last (?:week|month|quarter|year)|this (?:week|month|quarter|year)|next (?:week|month|quarter|year)|today|yesterday)\b/gi;
|
|
327
|
+
const times = (t) => [...new Set((t.toLowerCase().match(TIME) || []))].sort().join(",");
|
|
328
|
+
const subjQ = quals(m[1]);
|
|
329
|
+
for (const v of units) {
|
|
330
|
+
if (v === u || v.line >= u.line || v.heading) continue;
|
|
331
|
+
const vw = (v.text.toLowerCase().match(/[a-z][a-z-]+/g) || []).map(stemW);
|
|
332
|
+
if (!subj.every((w) => vw.includes(w))) continue;
|
|
333
|
+
// "Churn was 3% in January" vs "Churn was 5% in February" are two periods, not a contradiction
|
|
334
|
+
const tu = times(u.text), tv = times(v.text);
|
|
335
|
+
if (tu && tv && tu !== tv) continue;
|
|
336
|
+
// "Revenue was 9%" vs "Net revenue was 5%" are two measures
|
|
337
|
+
const vq = quals(v.text.slice(0, Math.max(0, v.text.toLowerCase().indexOf(subj[0])) + 40));
|
|
338
|
+
if ([...vq].some((q) => !subjQ.has(q)) || [...subjQ].some((q) => !vq.has(q))) continue;
|
|
339
|
+
const nums = findNumbers(v.text).filter((x) => x.kind === n.kind);
|
|
340
|
+
if (!nums.length || nums.some((x) => Math.abs(x.value - n.value) <= Math.abs(n.value) * 0.005)) continue;
|
|
341
|
+
const at = v.text.toLowerCase().indexOf(subj[subj.length - 1]);
|
|
342
|
+
const old = nums.sort((a, b) => Math.abs(a.start - at) - Math.abs(b.start - at))[0];
|
|
343
|
+
if (!out.some((x) => x.line === u.line && x.text === n.raw)) out.push(f("contradiction", "warning", u, n.raw, `"${m[1].trim()}" is ${n.raw} here but ${old.raw} on line ${v.line}.`));
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return out;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const MONTH_OR_DAY = /^(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sept?(?:ember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?|(?:mon|tues|wednes|thurs|fri|satur|sun)day)$/;
|
|
351
|
+
|
|
352
|
+
const SOURCE_PHRASES =
|
|
353
|
+
/\b(studies (?:show|suggest|find|found)|research (?:(?:from|by) (?!our |my |internal )(?:[\w&.']+ ){1,4})?(?:shows|suggests|finds|found|indicates|confirms|proves)|(?:industry|market|third-party|independent) (?:research|data|analysis|studies) (?:shows|suggests|indicates|finds|found|confirms)|an? (?:recent |(?:19|20)\d\d )?(?:(?:gartner|forrester|mckinsey|idc|deloitte|bcg|bain|pwc|accenture|harvard|stanford|mit) )?(?: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;
|
|
354
|
+
|
|
355
|
+
const NORM = /\b(usually|typically|tend(?:s)? to|as a rule|on average|most (?:companies|teams|businesses|startups|customers|users|buyers)|most (?!of\b)\w+ (?:companies|businesses|startups)|(?:is|are) (?:the )?(?:standard|norm|common practice)|industry[- ]standard|commonly|generally speaking)\b/i;
|
|
356
|
+
|
|
357
|
+
// "11 seats each on average", "it took 54 days on average": when the figure that "on average" qualifies
|
|
358
|
+
// is in your notes as written, it is an average you gave, not an outside norm.
|
|
359
|
+
function describesSourcedFigures(norm, text, ctx) {
|
|
360
|
+
if (!ctx.hasSource || !/^on average$/i.test(norm.match[0])) return false;
|
|
361
|
+
const n = findNumbers(text.slice(0, norm.index)).pop();
|
|
362
|
+
return !!n && ctx.values.includes(n.value);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** 4. Claimed sources the input never gave, and links that are not in the input. */
|
|
366
|
+
export function fakeSources(units, ctx) {
|
|
367
|
+
const out = [];
|
|
368
|
+
for (const u of units) {
|
|
369
|
+
const m = u.text.match(SOURCE_PHRASES);
|
|
370
|
+
if (m && !ctx.sourceLower.includes(m[0].toLowerCase())) {
|
|
371
|
+
out.push(f("fake-source", "error", u, m[0], ctx.hasSource ? `Cites "${m[0]}" but your input gives no such source. Name it and link it, or cut it.` : `Cites "${m[0]}" without naming the source. Name it and link it, or cut it.`));
|
|
372
|
+
}
|
|
373
|
+
const norm = u.text.match(NORM);
|
|
374
|
+
if (norm && !isLabelled(u.text) && !ctx.sourceLower.includes(norm[0].toLowerCase()) && !describesSourcedFigures({ match: norm, index: norm.index }, u.text, ctx)) {
|
|
375
|
+
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.`));
|
|
376
|
+
}
|
|
377
|
+
for (const url of u.raw.match(URL_RE) || []) {
|
|
378
|
+
if (ctx.hasSource && !ctx.sourceLower.includes(url.toLowerCase().replace(/[.,;]+$/, ""))) {
|
|
379
|
+
out.push(f("fake-source", "warning", u, url, `Link is not in your input. Open it and confirm it says what the doc claims.`));
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return dedupe(out);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const COMMON = new Set(
|
|
387
|
+
("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 " +
|
|
388
|
+
"Monday Tuesday Wednesday Thursday Friday Saturday Sunday January February March April May June July August September October November December " +
|
|
389
|
+
"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 " +
|
|
390
|
+
"Assumption Assumptions Target Targets TBD Goal Goals Risk Risks Owner Owners Status Summary Context Background Problem Solution Scope Ask Why What How Who Where " +
|
|
391
|
+
"Notes Note Option Options Recommendation Decision Decisions Metric Metrics Success Timeline Milestone Milestones Dependencies Dependency Appendix Overview Objective Objectives Key Results Result " +
|
|
392
|
+
"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 " +
|
|
393
|
+
"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 " +
|
|
394
|
+
"Here There Please Thanks Hi Hello Dear Best Regards Management Leadership Board Investors Partners Everyone Nobody Someone Most Many Several Both Neither Revenue Growth Churn Usage Adoption Pricing Billing Onboarding Procurement Recruiting Hiring Nothing Everything Feedback Each Every General Availability Beta Alpha Head Director Manager Lead Chief Officer President Principal Senior Staff").split(" "),
|
|
395
|
+
);
|
|
396
|
+
|
|
397
|
+
/** 5. Proper names (people, customers, tools, competitors) that the input never mentions. */
|
|
398
|
+
export function inventedNames(units, ctx) {
|
|
399
|
+
if (!ctx.hasSource) return [];
|
|
400
|
+
const out = [];
|
|
401
|
+
const flagged = new Set();
|
|
402
|
+
for (const u of units) {
|
|
403
|
+
if (u.heading) continue;
|
|
404
|
+
const text = u.text.replace(URL_RE, " ");
|
|
405
|
+
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)) {
|
|
406
|
+
const name = m[0];
|
|
407
|
+
const first = m[1];
|
|
408
|
+
const prefix = text.slice(0, m.index);
|
|
409
|
+
const sentenceStart = /^[\s*_>#\-|"(\[]*(?:\d+[.)]\s*)?(?:\*\*)?$/.test(prefix) || /[:.!?](?:\*\*|__)?\s*(?:\*\*)?$/.test(prefix) || /\|\s*(?:\*\*)?$/.test(prefix);
|
|
410
|
+
if (sentenceStart && !m[2] && !(m[1].length >= 4 && !/(?:ing|ion|ment|ness|ity)$/.test(m[1]) && /^\s+(?:has|have|had|is|was|asked|wants|signed|said|says|told|requested|reported|uses|used|will|plans|churned|renewed|joined|bought|chose|picked)\b/.test(text.slice(m.index + m[0].length)))) continue;
|
|
411
|
+
const candidate = sentenceStart ? (m[2] || m[1]) : name;
|
|
412
|
+
if (!candidate) continue;
|
|
413
|
+
if (/^\s*(?:\*\*|__)?\s*:|^:/.test(text.slice(m.index + m[0].length))) continue; // a label: "**Product Designer:**"
|
|
414
|
+
if (/^[A-Z0-9]+s?$/.test(candidate.replace(/\s+/g, ""))) continue; // acronyms: CSAT, API, ARR, and plurals: CFOs, APIs
|
|
415
|
+
if (candidate.split(/\s+/).every((w) => COMMON.has(w))) continue;
|
|
416
|
+
if (COMMON.has(sentenceStart ? candidate : first) && !m[2]) continue;
|
|
417
|
+
const key = candidate.toLowerCase();
|
|
418
|
+
if (flagged.has(key)) continue;
|
|
419
|
+
if (candidate.split(/\s+/).some((w) => ctx.sourceLower.includes(w.toLowerCase()))) continue;
|
|
420
|
+
if (ctx.allowNames.has(key)) continue;
|
|
421
|
+
flagged.add(key);
|
|
422
|
+
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.`));
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
return out;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** 6. Impossible dates, wrong weekdays, past dates used as future plans, and dates not in the input. */
|
|
429
|
+
export function dateErrors(units, ctx) {
|
|
430
|
+
const out = [];
|
|
431
|
+
const today = ctx.today;
|
|
432
|
+
for (const u of units) {
|
|
433
|
+
for (const d of findDates(u.text)) {
|
|
434
|
+
if (d.day < 1 || d.day > daysInMonth(d.month, d.year)) {
|
|
435
|
+
out.push(f("date-error", "error", u, d.raw, `${d.raw} does not exist.`));
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
const year = d.year ?? (ctx.assumeYear || null);
|
|
439
|
+
const lone = !d.weekday && findDates(u.text).length === 1 && /\((mon|tues|wednes|thurs|fri|satur|sun)day\)/i.exec(u.text);
|
|
440
|
+
if (lone && year && weekdayOf(d.day, d.month, year) !== lone[1].slice(0, 3).toLowerCase()) {
|
|
441
|
+
out.push(f("date-error", "error", u, lone[0].slice(1, -1), `${d.raw} is a ${fullDay(weekdayOf(d.day, d.month, year))}, not a ${lone[0].slice(1, -1)}.`));
|
|
442
|
+
}
|
|
443
|
+
if (d.weekday && year) {
|
|
444
|
+
const actual = weekdayOf(d.day, d.month, year);
|
|
445
|
+
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}`}.`));
|
|
446
|
+
}
|
|
447
|
+
if (d.year && today) {
|
|
448
|
+
const when = Date.UTC(d.year, d.month - 1, d.day);
|
|
449
|
+
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);
|
|
450
|
+
if (when < today && future && !/\b(was|were|did|ran|ended|finished|completed|closed|held|took place|occurred|launched|shipped|released|happened|ago|last)\b/i.test(u.text)) {
|
|
451
|
+
out.push(f("date-error", "warning", u, d.raw, `${d.raw} is in the past but reads as a future plan.`));
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
if (ctx.hasSource && !isLabelled(u.text) && !ctx.sourceDates.has(dateKey(d)) && !(d.alt && ctx.sourceDates.has(`${d.alt.month}-${d.alt.day}`))) {
|
|
455
|
+
out.push(f("date-error", "warning", u, d.raw, `${d.raw} is not in your input. Confirm it or mark it as a target.`));
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
return dedupe(out);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
const LEFTOVER = /\[(?:tbd|tbc|todo|tk|(?:link|url)(?: to [^\]]*)?|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;
|
|
463
|
+
|
|
464
|
+
// Case matters for these: "TBC" and "XX%" are placeholders, "Tbc Ltd" and "xx" may not be.
|
|
465
|
+
const LEFTOVER_CASED = /\bTBC\b|(?<![\w.])[$€£₹]?XX+(?:\.X+)?%?(?![\w])/g;
|
|
466
|
+
|
|
467
|
+
/** 7. Placeholders and template text left in the doc. */
|
|
468
|
+
export function leftovers(units) {
|
|
469
|
+
const out = [];
|
|
470
|
+
for (const u of units) {
|
|
471
|
+
if (u.table) for (const c of u.text.split("|").map((x) => x.trim())) if (/^(?:tbd|tba|tbc|todo|\?+|-{1,2})$/i.test(c) && c !== "---") out.push(f("leftover", "note", u, c, `A table cell still says "${c}". Fill it in.`));
|
|
472
|
+
for (const m of [...u.text.matchAll(LEFTOVER), ...u.text.matchAll(LEFTOVER_CASED)]) {
|
|
473
|
+
out.push(f("leftover", "note", u, m[0], `Placeholder still to fill: ${m[0]}`));
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return out;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const VAGUE = /\b(overwhelming(?:ly)?|(?:big|huge|massive|major) (?:jump|boost|win|leap|spike|increase|improvement|uptick)|skyrocket\w*|soar\w*|explosive|incredibl[ey]|amazing|phenomenal|(?:very|extremely|hugely|incredibly) (?:positive|successful|popular|strong)|loved by|rave reviews|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;
|
|
480
|
+
|
|
481
|
+
/** 8. Vague or hype words with nothing measurable behind them. */
|
|
482
|
+
export function vagueClaims(units) {
|
|
483
|
+
const out = [];
|
|
484
|
+
for (const u of units) {
|
|
485
|
+
if (u.heading) continue;
|
|
486
|
+
if (findNumbers(u.text).length) continue; // backed by a figure in the same sentence
|
|
487
|
+
for (const m of u.text.matchAll(VAGUE)) {
|
|
488
|
+
out.push(f("vague-claim", "note", u, m[0], `"${m[0]}" with nothing measurable behind it. Say how much, or cut it.`));
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
return out;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export const CHECKS = {
|
|
495
|
+
"unsourced-number": unsourcedNumbers,
|
|
496
|
+
"math-error": mathErrors,
|
|
497
|
+
contradiction: contradictions,
|
|
498
|
+
"fake-source": fakeSources,
|
|
499
|
+
"invented-name": inventedNames,
|
|
500
|
+
"date-error": dateErrors,
|
|
501
|
+
leftover: leftovers,
|
|
502
|
+
"vague-claim": vagueClaims,
|
|
503
|
+
"invented-quote": inventedQuotes,
|
|
504
|
+
"period-mismatch": periodMismatch,
|
|
505
|
+
"table-total": tableTotals,
|
|
506
|
+
overclaim: overclaims,
|
|
507
|
+
"missing-owner": missingOwners,
|
|
508
|
+
"missing-section": missingSections,
|
|
509
|
+
"scale-mismatch": scaleMismatch,
|
|
510
|
+
"rounding-drift": roundingDrift,
|
|
511
|
+
"percent-points": percentPoints,
|
|
512
|
+
"direction-flip": directionFlip,
|
|
513
|
+
"relative-date": relativeDates,
|
|
514
|
+
"broken-link": brokenLinks,
|
|
515
|
+
"role-change": roleChanges,
|
|
516
|
+
readability,
|
|
517
|
+
"missing-fact": missingFacts,
|
|
518
|
+
"notes-conflict": notesConflict,
|
|
519
|
+
"count-mismatch": countMismatch,
|
|
520
|
+
};
|
|
521
|
+
|
|
522
|
+
function fullDay(abbr) {
|
|
523
|
+
return { sun: "Sunday", mon: "Monday", tue: "Tuesday", wed: "Wednesday", thu: "Thursday", fri: "Friday", sat: "Saturday" }[abbr];
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function dedupe(findings) {
|
|
527
|
+
const seen = new Set();
|
|
528
|
+
return findings.filter((x) => {
|
|
529
|
+
const k = `${x.check}|${x.line}|${x.text}|${x.message}`;
|
|
530
|
+
if (seen.has(k)) return false;
|
|
531
|
+
seen.add(k);
|
|
532
|
+
return true;
|
|
533
|
+
});
|
|
534
|
+
}
|