@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/dates.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
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
|
+
// 12/22/2026 (US) or 22/12/2026: read as day/month only when the first part can't be a month
|
|
16
|
+
/\b(\d{1,2})\/(\d{1,2})\/(\d{4})\b/g,
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
/** Dates in a sentence: { raw, day, month (1-12), year|null, weekday|null, index }. */
|
|
20
|
+
export function findDates(sentence) {
|
|
21
|
+
const out = [];
|
|
22
|
+
const seen = new Set();
|
|
23
|
+
PATTERNS.forEach((re, p) => {
|
|
24
|
+
for (const m of sentence.matchAll(re)) {
|
|
25
|
+
let weekday = null, day, month, year, alt = null;
|
|
26
|
+
if (p === 0) {
|
|
27
|
+
[, weekday, day, month, year] = m;
|
|
28
|
+
} else if (p === 1) {
|
|
29
|
+
[, weekday, month, day, year] = m;
|
|
30
|
+
} else if (p === 2) {
|
|
31
|
+
[, year, month, day] = m;
|
|
32
|
+
month = MONTHS[+month - 1] ?? "x";
|
|
33
|
+
} else {
|
|
34
|
+
const [a, b] = [+m[1], +m[2]];
|
|
35
|
+
[month, day] = a > 12 ? [b, a] : [a, b];
|
|
36
|
+
if (a <= 12 && b <= 12 && a !== b) alt = { day: a, month: b }; // 3/4/2026: 4 March (US) or 3 April
|
|
37
|
+
year = m[3];
|
|
38
|
+
month = MONTHS[month - 1] ?? "x";
|
|
39
|
+
}
|
|
40
|
+
const mi = MONTHS.indexOf(String(month).slice(0, 3).toLowerCase());
|
|
41
|
+
if (mi < 0) continue;
|
|
42
|
+
// "may" is also a verb: only accept it next to a day number.
|
|
43
|
+
if (seen.has(m.index)) continue;
|
|
44
|
+
seen.add(m.index);
|
|
45
|
+
out.push({
|
|
46
|
+
raw: m[0].trim().replace(/[.,]$/, ""),
|
|
47
|
+
day: +day,
|
|
48
|
+
month: mi + 1,
|
|
49
|
+
year: year ? +year : null,
|
|
50
|
+
weekday: weekday ? weekday.slice(0, 3).toLowerCase() : null,
|
|
51
|
+
index: m.index,
|
|
52
|
+
...(alt ? { alt } : {}),
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function daysInMonth(month, year) {
|
|
60
|
+
return new Date(Date.UTC(year ?? 2024, month, 0)).getUTCDate(); // 2024: leap year, so 29 Feb is allowed without a year
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function weekdayOf(day, month, year) {
|
|
64
|
+
return WEEKDAYS[new Date(Date.UTC(year, month - 1, day)).getUTCDay()].slice(0, 3);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function dateKey(d) {
|
|
68
|
+
return `${d.month}-${d.day}`;
|
|
69
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Checks 9 to 14: quotes, periods, table totals, certainty, owners, and missing sections.
|
|
2
|
+
// Same contract as checks.js: (units, ctx) -> [{ check, severity, line, text, message }].
|
|
3
|
+
|
|
4
|
+
import { findNumbers } from "./numbers.js";
|
|
5
|
+
import { findDates } from "./dates.js";
|
|
6
|
+
|
|
7
|
+
const f = (check, severity, unit, text, message) => ({ check, severity, line: unit.line, text, message });
|
|
8
|
+
const norm = (s) => s.toLowerCase().replace(/[“”"'‘’]/g, "").replace(/[^a-z0-9%$., ]+/g, " ").replace(/\s+/g, " ").trim();
|
|
9
|
+
|
|
10
|
+
/** 9. Quoted words that nobody in your notes said. */
|
|
11
|
+
const QUOTE = /(?<![\w\d])[“"]([^“”"\n]{12,280})[”"](?!\w)|(?<=^|[\s(:])[‘']([^‘’'\n]{12,280})[’'](?=[\s.,;:!?)]|$)/g;
|
|
12
|
+
export function inventedQuotes(units, ctx) {
|
|
13
|
+
if (!ctx.hasSource) return [];
|
|
14
|
+
const src = norm(ctx.sourceLower);
|
|
15
|
+
const out = [];
|
|
16
|
+
for (const u of units) {
|
|
17
|
+
for (const m of u.text.matchAll(QUOTE)) {
|
|
18
|
+
const q = (m[1] ?? m[2]).trim();
|
|
19
|
+
if (q.split(/\s+/).length < 4) continue;
|
|
20
|
+
if (src.includes(norm(q))) {
|
|
21
|
+
// right words, wrong person: "As Jordan noted, '...'" when the notes have Hannah saying it
|
|
22
|
+
const srcLine = (ctx.source ?? "").split("\n").find((l) => norm(l).includes(norm(q)));
|
|
23
|
+
const speaker = srcLine && /^\s*[-*]?\s*([A-Z][a-z]+)(?:\s+[A-Z][a-z]+)?(?:\s*\([^)]*\))?\s*:/.exec(srcLine)?.[1];
|
|
24
|
+
const said = /\b(?:as\s+)?([A-Z][a-z]+)(?:\s+[A-Z][a-z]+)?\s+(?:noted|said|says|added|explained|mentioned|put it|told)/.exec(u.text)?.[1];
|
|
25
|
+
if (speaker && said && speaker !== said && ctx.sourceLower.includes(said.toLowerCase())) {
|
|
26
|
+
out.push(f("invented-quote", "error", u, m[0], `In your notes ${speaker} said this, not ${said}.`));
|
|
27
|
+
}
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
out.push(f("invented-quote", "error", u, m[0], `This quote isn't in your notes. Quote what was actually said, or paraphrase without quote marks.`));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 10. A figure given per month in your notes but per year here (or the other way round). */
|
|
37
|
+
const PERIOD = [
|
|
38
|
+
["day", /^\s*(?:\/(?:user|seat|member|account|workspace|org)s?)?(?:[\w-]+\s+){0,2}?(?:per day|a day|\/day|daily|each day)\b/i],
|
|
39
|
+
["week", /^\s*(?:\/(?:user|seat|member|account|workspace|org)s?)?(?:[\w-]+\s+){0,2}?(?:per week|a week|\/wk|\/week|weekly|each week)\b/i],
|
|
40
|
+
["month", /^\s*(?:\/(?:user|seat|member|account|workspace|org)s?)?(?:[\w-]+\s+){0,2}?(?:per month|a month|\/mo|\/month|monthly|each month|MRR)\b/i],
|
|
41
|
+
["quarter", /^\s*(?:\/(?:user|seat|member|account|workspace|org)s?)?(?:[\w-]+\s+){0,2}?(?:per quarter|a quarter|quarterly|each quarter)\b/i],
|
|
42
|
+
["year", /^\s*(?:\/(?:user|seat|member|account|workspace|org)s?)?(?:[\w-]+\s+){0,2}?(?:per year|a year|\/yr|\/year|annually|annual|yearly|each year|ARR)\b/i],
|
|
43
|
+
];
|
|
44
|
+
const STOP = new Set("the a an and or of for on in to is are was were be we our it its this that with per each about around roughly usd eur gbp inr dollars".split(" "));
|
|
45
|
+
const topic = (s) => new Set(s.toLowerCase().match(/[a-z]{4,}/g)?.filter((w) => !STOP.has(w)) ?? []);
|
|
46
|
+
function periodsIn(text) {
|
|
47
|
+
const out = [];
|
|
48
|
+
for (const n of findNumbers(text)) {
|
|
49
|
+
if (n.kind === "duration") continue;
|
|
50
|
+
const after = text.slice(n.end, n.end + 40);
|
|
51
|
+
const hit = PERIOD.find(([, re]) => re.test(after));
|
|
52
|
+
if (hit) { out.push({ ...n, period: hit[0], words: topic(text) }); continue; }
|
|
53
|
+
// or a period word earlier in the same clause, with no other figure in between
|
|
54
|
+
const before = text.slice(Math.max(0, n.start - 80), n.start);
|
|
55
|
+
const adj = [...before.matchAll(/\b(daily|weekly|monthly|quarterly|annual|annually|yearly)\b/gi)].pop();
|
|
56
|
+
if (adj && !/\d/.test(before.slice(adj.index)) && !/[.;]/.test(before.slice(adj.index))) {
|
|
57
|
+
const p = { daily: "day", weekly: "week", monthly: "month", quarterly: "quarter", annual: "year", annually: "year", yearly: "year" }[adj[1].toLowerCase()];
|
|
58
|
+
out.push({ ...n, period: p, words: topic(text) });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
export function periodMismatch(units, ctx) {
|
|
64
|
+
if (!ctx.hasSource) return [];
|
|
65
|
+
const seen = []; // { value, period, words } from the source
|
|
66
|
+
for (const line of ctx.sourceLower.split("\n")) seen.push(...periodsIn(line));
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const u of units) {
|
|
69
|
+
for (const n of periodsIn(u.text.toLowerCase())) {
|
|
70
|
+
// same value, different period, and the sentences share a topic word ("infra", "licence", "hosting")
|
|
71
|
+
const hit = seen.find((s) => s.value === n.value && s.period !== n.period && [...n.words].some((w) => s.words.has(w)));
|
|
72
|
+
const p = hit?.period;
|
|
73
|
+
if (p) {
|
|
74
|
+
out.push(f("period-mismatch", "error", u, n.raw, `${n.raw} is per ${p} in your notes, but per ${n.period} here.`));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 11. Table totals that don't match the rows above them. */
|
|
82
|
+
const cellNum = (c) => {
|
|
83
|
+
const m = c.replace(/[$€£₹,\s*_]/g, "").match(/^\(?(-?\d+(?:\.\d+)?)\)?(%|k|m)?$/i);
|
|
84
|
+
if (!m) return null;
|
|
85
|
+
let v = parseFloat(m[1]);
|
|
86
|
+
if (/^k$/i.test(m[2] || "")) v *= 1e3;
|
|
87
|
+
if (/^m$/i.test(m[2] || "")) v *= 1e6;
|
|
88
|
+
return { v, d: (m[1].split(".")[1] || "").length };
|
|
89
|
+
};
|
|
90
|
+
export function tableTotals(units) {
|
|
91
|
+
const out = [];
|
|
92
|
+
const tables = [];
|
|
93
|
+
let cur = null, lastLine = -2;
|
|
94
|
+
for (const u of units) {
|
|
95
|
+
if (!u.table) { cur = null; continue; }
|
|
96
|
+
if (!cur || u.line !== lastLine + 1 && u.line !== lastLine + 2) { cur = []; tables.push(cur); }
|
|
97
|
+
cur.push(u); lastLine = u.line;
|
|
98
|
+
}
|
|
99
|
+
for (const t of tables) {
|
|
100
|
+
const rows = t.map((u) => ({ u, cells: u.text.split(/(?<!\\)\|/).slice(1, -1).map((c) => c.trim()) }));
|
|
101
|
+
if (rows.length < 3) continue;
|
|
102
|
+
const body = rows.slice(1);
|
|
103
|
+
const ti = body.findIndex((r) => /^[*_]*\s*(?:(?:grand\s+)?total|sum|all \w+|overall|combined)\b/i.test(r.cells[0] || ""));
|
|
104
|
+
if (ti < 1) continue;
|
|
105
|
+
const above = body.slice(0, ti), total = body[ti];
|
|
106
|
+
for (let c = 1; c < total.cells.length; c++) {
|
|
107
|
+
const tv = cellNum(total.cells[c]);
|
|
108
|
+
if (!tv) continue;
|
|
109
|
+
const vals = above.map((r) => cellNum(r.cells[c] || ""));
|
|
110
|
+
if (vals.some((x) => !x) || !vals.length) continue;
|
|
111
|
+
const sum = vals.reduce((s, x) => s + x.v, 0);
|
|
112
|
+
const dec = Math.max(tv.d, ...vals.map((x) => x.d));
|
|
113
|
+
const tol = Math.max(0.5 * 10 ** -dec * vals.length, Math.abs(tv.v) * 0.001);
|
|
114
|
+
if (Math.abs(sum - tv.v) > tol) {
|
|
115
|
+
const header = rows[0].cells[c] || `column ${c + 1}`;
|
|
116
|
+
const shown = sum.toLocaleString("en-US", { maximumFractionDigits: dec });
|
|
117
|
+
out.push(f("table-total", "error", total.u, total.cells[c], `"${header}" rows add up to ${shown}, but the total says ${total.cells[c]}.`));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 12. Things stated as certain that no plan can promise. */
|
|
125
|
+
const CERTAIN = /\b(guarantee[sd]?|guaranteeing|will not change|won't change|cannot change|will never (?:change|fail|happen)|eliminat(?:e|es|ing) (?:the )?(?:possibility|chance) of|definitely|undoubtedly|will certainly|certainly will|cannot fail|can't fail|can not fail|proven to|zero risk|zero (?:\w+ ){0,2}(?:risk|downtime|outages?|errors?|defects?|bugs?|churn)|ensur(?:e|es|ing) (?:zero|no) (?:downtime|outages?|errors?|risk)|eliminat(?:e|es|ing) (?:the |all )?risks?|risk[- ]free|no risk|will (?:double|triple|eliminate|fix all)|100% (?:sure|certain|guaranteed|accurate|of (?:customers|users|teams)))\b/gi;
|
|
126
|
+
export function overclaims(units) {
|
|
127
|
+
const out = [];
|
|
128
|
+
for (const u of units) {
|
|
129
|
+
if (u.heading) continue;
|
|
130
|
+
for (const m of u.text.matchAll(CERTAIN)) {
|
|
131
|
+
if (/^100%/.test(m[0]) && /\bto\s*$/i.test(u.text.slice(0, m.index))) continue; // "ship to 100% of users" is a rollout, not a promise
|
|
132
|
+
out.push(f("overclaim", "warning", u, m[0], `"${m[0]}" states a forecast as a certainty. Soften it, or show the evidence.`));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** 13. Action items with no owner and no date. */
|
|
139
|
+
const ACTION_HEAD = /^\s*#{1,6}\s*(?:\d+[.)]\s*)?(next steps?|action items?|actions|(?:corrective|preventive|preventative|remediation|follow-up) actions?|to-?dos?|follow[- ]?ups?|owners?)\b/i;
|
|
140
|
+
const HAS_OWNER = /@\w+|\bowner\s*:|\b(?:dri|assignee)\b|\((?:[A-Z][a-z]+)\)|(?:^|[-*]\s+|:\s*)[A-Z][a-z]+(?:\s[A-Z][a-z]+)?(?:\s*\([^)]{1,40}\))?\s*(?:to|will|owns|:|-|–)\s|^[A-Z][a-z]+\s+(?:[a-z]+s|is|has)\s/;
|
|
141
|
+
const HAS_WHEN = /\bby\s+\w+|\b(?:eod|eow|eom|eoq|today|tomorrow|this week|next week|asap)\b|\bQ[1-4]\b|\b(?:mon|tues?|wed(?:nes)?|thu(?:rs)?|fri|sat(?:ur)?|sun)(?:day)?\b/i;
|
|
142
|
+
export function missingOwners(units) {
|
|
143
|
+
const out = [];
|
|
144
|
+
let inActions = false;
|
|
145
|
+
let ownersOnly = false; // an "Owners" section says who owns what; it is not a list of dated tasks
|
|
146
|
+
let lastLine = 0;
|
|
147
|
+
for (const u of units) {
|
|
148
|
+
if (u.line === lastLine) continue; // one finding per line
|
|
149
|
+
if (/^\s*#{1,6}\s/.test(u.raw)) { inActions = ACTION_HEAD.test(u.raw); ownersOnly = /^\s*#{1,6}\s*owners?\s*$/i.test(u.raw); continue; }
|
|
150
|
+
if (!inActions) continue;
|
|
151
|
+
if (!/^\s*(?:[-*+]|\d+[.)])\s+/.test(u.raw)) continue;
|
|
152
|
+
lastLine = u.line;
|
|
153
|
+
const item = u.raw.replace(/^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ x]\]\s*)?/i, "");
|
|
154
|
+
const owner = HAS_OWNER.test(item) || HAS_OWNER.test(u.raw);
|
|
155
|
+
const when = HAS_WHEN.test(item) || findDates(item).length > 0;
|
|
156
|
+
if (!owner || (!when && !ownersOnly)) {
|
|
157
|
+
const what = !owner && !when ? "owner or date" : !owner ? "owner" : "date";
|
|
158
|
+
out.push(f("missing-owner", "note", u, item.slice(0, 60), `This action item has no ${what}. Say who does it and by when.`));
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 14. Sections a reader expects for this kind of document. */
|
|
165
|
+
const DOC_TYPES = [
|
|
166
|
+
{ type: "PRD", match: /\b(prd|product requirements?|requirements doc)\b/i, need: [["the problem", /problem|why|background|context/i], ["goals or success metrics", /goal|objective|success|metric|kpi/i], ["scope or non-goals", /scope|non-?goals?|requirement|out of scope/i], ["risks", /risk|open question|concern|dependenc/i]] },
|
|
167
|
+
{ type: "launch plan", match: /\blaunch\b/i, need: [["the launch date or timeline", /date|timeline|schedule|when|milestone/i], ["owners", /owner|team|dri|who|raci/i], ["risks or rollback", /risk|rollback|roll back|contingenc/i], ["how you'll measure it", /metric|success|kpi|measure/i]] },
|
|
168
|
+
{ type: "update", match: /\b(update|status|weekly|monthly|report)\b/i, need: [["a summary", /summary|tl;?dr|highlights?|overview/i], ["risks or blockers", /risk|blocker|issue|concern/i], ["asks or next steps", /ask|decision|next|need/i]] },
|
|
169
|
+
];
|
|
170
|
+
export function missingSections(units) {
|
|
171
|
+
const headings = units.filter((u) => u.heading);
|
|
172
|
+
if (!headings.length) return [];
|
|
173
|
+
const title = headings.find((h) => /^\s*#\s/.test(h.raw)) ?? headings[0];
|
|
174
|
+
const dt = DOC_TYPES.find((d) => d.match.test(title.text));
|
|
175
|
+
if (!dt) return [];
|
|
176
|
+
const rest = headings.filter((h) => h !== title).map((h) => h.text).join(" \n ");
|
|
177
|
+
const out = [];
|
|
178
|
+
for (const [label, re] of dt.need) {
|
|
179
|
+
if (!re.test(rest)) out.push(f("missing-section", "note", title, title.text.replace(/^#+\s*/, ""), `This looks like ${/^[aeiou]/i.test(dt.type) ? "an" : "a"} ${dt.type} but has no section on ${label}.`));
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
package/src/fix.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Fix my draft: rewrite what the checker can fix on its own, and leave the rest for you.
|
|
2
|
+
// fixDraft(draft, findings) -> { text, changes: [{ line, check, before, after }], left: findings it could not fix }
|
|
3
|
+
//
|
|
4
|
+
// Fixed: wrong maths, wrong weekdays (when the date is in your notes), per-month vs per-year mix-ups, table totals,
|
|
5
|
+
// generic "studies show" style sources (dropped, and the claim behind them marked as an estimate; named ones are left),
|
|
6
|
+
// unsourced figures (labelled as estimates), certainty words (softened), hype adverbs (cut).
|
|
7
|
+
// Impossible dates become [date] so they can't be missed.
|
|
8
|
+
// Also from a check's own `suggest`: wrong scale or unit, percent vs points, rounding that drifted, changed job titles, jargon.
|
|
9
|
+
// Left for you: invented quotes (only you know what was said), names, owners, missing sections, placeholders, links, contradictions, direction flips, relative dates.
|
|
10
|
+
|
|
11
|
+
import { findNumbers } from "./numbers.js";
|
|
12
|
+
|
|
13
|
+
const ORDER = { "math-error": 0, "table-total": 1, "scale-mismatch": 1.2, "percent-points": 1.4, "rounding-drift": 1.6, "role-change": 1.8, readability: 1.9, "period-mismatch": 2, "date-error": 3, "fake-source": 4, "overclaim": 6, "vague-claim": 7, "unsourced-number": 8 };
|
|
14
|
+
const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
15
|
+
const WEEKDAY = /\b(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\b/;
|
|
16
|
+
const SOFTEN = { "will certainly": "should", "certainly will": "should", "cannot fail": "is likely to work", "can't fail": "is likely to work", "can not fail": "is likely to work", definitely: "likely", undoubtedly: "likely", guaranteed: "expected", guarantees: "is expected to give", guarantee: "expect", "proven to": "expected to", "zero risk": "low risk", "risk-free": "low-risk", "risk free": "low-risk", "no risk": "low risk" };
|
|
17
|
+
const PERIOD_WORD = /(per (?:day|week|month|quarter|year)|a (?:day|week|month|quarter|year)|\/(?:day|wk|week|mo|month|yr|year)|daily|weekly|monthly|quarterly|yearly|annually|annual)/i;
|
|
18
|
+
const PERIOD_TO = { day: "per day", week: "per week", month: "per month", quarter: "per quarter", year: "per year" };
|
|
19
|
+
|
|
20
|
+
function capFirst(s) { return s.replace(/^(\s*(?:[-*+]\s+|\d+[.)]\s+|#+\s+)?)([a-z])/, (m, p, c) => p + c.toUpperCase()); }
|
|
21
|
+
|
|
22
|
+
const GENERIC_SOURCE = /^(studies|research|data|surveys?|experts?|reports?|evidence|statistics|analysts?|science|it is (?:well )?known|everyone knows|industry (?:data|research|benchmarks?))\b/i;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {string} draft
|
|
26
|
+
* @param {object[]} findings from factcheck()
|
|
27
|
+
* @param {object} [opts]
|
|
28
|
+
* @param {string} [opts.source] the notes; a wrong weekday is only corrected when the date itself is in them
|
|
29
|
+
* @param {Map<number, Set<string>>} [opts.protect] values per line that fixes produced (never labelled as estimates)
|
|
30
|
+
*/
|
|
31
|
+
export function fixDraft(draft, findings, opts = {}) {
|
|
32
|
+
const srcLower = (opts.source ?? "").toLowerCase();
|
|
33
|
+
const lines = draft.replace(/\r\n?/g, "\n").split("\n");
|
|
34
|
+
const changes = [];
|
|
35
|
+
const left = [];
|
|
36
|
+
const touched = opts.protect ?? new Map(); // line index -> Set of values a fix wrote or replaced
|
|
37
|
+
const mark = (i, v) => (touched.get(i) ?? touched.set(i, new Set()).get(i)).add(v);
|
|
38
|
+
const sorted = findings.slice().sort((a, b) => a.line - b.line || (ORDER[a.check] ?? 99) - (ORDER[b.check] ?? 99));
|
|
39
|
+
|
|
40
|
+
for (const x of sorted) {
|
|
41
|
+
const i = x.line - 1;
|
|
42
|
+
const before = lines[i];
|
|
43
|
+
if (before == null || !(x.check in ORDER)) { left.push(x); continue; }
|
|
44
|
+
let after = before;
|
|
45
|
+
let m;
|
|
46
|
+
const exact = x.suggest && new RegExp("(?<![\\w.])" + reEsc(x.suggest.from) + "(?!\\w)");
|
|
47
|
+
if (exact && exact.test(after)) {
|
|
48
|
+
after = after.replace(exact, () => x.suggest.to);
|
|
49
|
+
mark(i, x.text); mark(i, x.suggest.to.trim());
|
|
50
|
+
}
|
|
51
|
+
else switch (x.check) {
|
|
52
|
+
case "math-error": {
|
|
53
|
+
if ((m = x.message.match(/ is (-?[\d.,]+%?), not (-?[\d.,]+%?)\.$/))) {
|
|
54
|
+
const at = after.indexOf(x.text), k = x.text.lastIndexOf(m[2]);
|
|
55
|
+
if (at >= 0 && k >= 0) { after = after.slice(0, at) + x.text.slice(0, k) + m[1] + x.text.slice(k + m[2].length) + after.slice(at + x.text.length); mark(i, m[2]); mark(i, m[1]); }
|
|
56
|
+
}
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
case "table-total": {
|
|
60
|
+
// a total that is in your notes is right; the wrong figure is one of the rows, so leave it for you
|
|
61
|
+
const totalInNotes = srcLower && new RegExp("(?<![\\d.,])" + reEsc(x.text.replace(/[^\d.,-]/g, "")) + "(?![\\d,]|\\.\\d)").test(srcLower);
|
|
62
|
+
if (!totalInNotes && (m = x.message.match(/add up to ([\d.,-]+), but/))) {
|
|
63
|
+
const cell = x.text.replace(/-?\d[\d,]*(?:\.\d+)?/, m[1]); // keep "$", "**" and suffixes around the number
|
|
64
|
+
after = after.replace(new RegExp("(\\|\\s*)" + reEsc(x.text) + "(\\s*\\|)"), (all, a, b) => a + cell + b);
|
|
65
|
+
mark(i, x.text); mark(i, m[1]); mark(i, cell);
|
|
66
|
+
}
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
case "period-mismatch": {
|
|
70
|
+
if ((m = x.message.match(/is per (\w+) in your notes/))) {
|
|
71
|
+
const at = after.indexOf(x.text);
|
|
72
|
+
if (at >= 0) { const tail = after.slice(at + x.text.length).replace(PERIOD_WORD, PERIOD_TO[m[1]]); after = after.slice(0, at + x.text.length) + tail; }
|
|
73
|
+
}
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
case "date-error": {
|
|
77
|
+
// only when the date itself came from your notes; otherwise the date may be the wrong part
|
|
78
|
+
if ((m = x.message.match(/that date is a (\w+)/))) { const date = x.text.replace(WEEKDAY, "").replace(/^[\s,]+/, "").toLowerCase(); if (date && srcLower.includes(date)) after = after.replace(x.text, x.text.replace(WEEKDAY, m[1])); }
|
|
79
|
+
else if (/does not exist/.test(x.message)) after = after.replace(x.text, "[date]");
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
case "fake-source": {
|
|
83
|
+
if (x.severity === "error" && GENERIC_SOURCE.test(x.text)) { // named sources ("according to Gartner") are left for you
|
|
84
|
+
// drop the made-up attribution: "Studies show 68% of teams..." -> "68% of teams..."
|
|
85
|
+
const at = Math.max(0, after.search(new RegExp(reEsc(x.text), "i")));
|
|
86
|
+
after = after.replace(new RegExp(reEsc(x.text) + "(?:\\s+that)?[,:]?\\s*", "i"), "");
|
|
87
|
+
// the claim behind the dropped source still has no source: say so, never let it pass silently
|
|
88
|
+
const n = findNumbers(after.slice(at)).find((k) => k.kind !== "duration");
|
|
89
|
+
if (n && !/^\s*\((?:estimate|unverified)\)/.test(after.slice(at + n.end))) {
|
|
90
|
+
after = after.slice(0, at + n.end) + " (estimate)" + after.slice(at + n.end);
|
|
91
|
+
mark(i, n.raw);
|
|
92
|
+
}
|
|
93
|
+
after = capFirst(after).replace(/([.!?]\s+)([a-z])/g, (mm, p, c) => p + c.toUpperCase());
|
|
94
|
+
}
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
case "overclaim": {
|
|
98
|
+
const rep = SOFTEN[x.text.toLowerCase()] ?? (/^will (\w+)/i.test(x.text) ? x.text.replace(/^will/i, "could") : null);
|
|
99
|
+
if (rep) after = after.replace(x.text, x.text[0] === x.text[0].toUpperCase() ? rep[0].toUpperCase() + rep.slice(1) : rep);
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
case "vague-claim": {
|
|
103
|
+
if (/ly$/i.test(x.text)) after = after.replace(new RegExp("\\s+" + reEsc(x.text) + "\\b"), "");
|
|
104
|
+
break;
|
|
105
|
+
}
|
|
106
|
+
case "unsourced-number": {
|
|
107
|
+
if (x.severity !== "error" || touched.get(i)?.has(x.text) || /^\d+(\.\d+)?%?$/.test(x.text) && [...(touched.get(i) ?? [])].some((v) => v === x.text)) break;
|
|
108
|
+
after = after.replace(new RegExp(reEsc(x.text) + "(?! \\(estimate\\))"), x.text + " (estimate)");
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (after !== before) { lines[i] = after; changes.push({ line: x.line, check: x.check, before, after }); }
|
|
113
|
+
else if (!touched.get(i)?.has(x.text)) left.push(x);
|
|
114
|
+
}
|
|
115
|
+
return { text: lines.join("\n"), changes, left };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Fix, re-check and fix again until nothing more changes (at most `passes` rounds).
|
|
120
|
+
* Some problems only show once others are fixed, e.g. a figure that was hidden by a fake source.
|
|
121
|
+
* @param {string} draft
|
|
122
|
+
* @param {(text: string) => object[]} recheck returns findings for a text
|
|
123
|
+
*/
|
|
124
|
+
export function fixAll(draft, recheck, passes = 3, opts = {}) {
|
|
125
|
+
let text = draft;
|
|
126
|
+
const protect = new Map();
|
|
127
|
+
const changes = [];
|
|
128
|
+
let left = [];
|
|
129
|
+
for (let p = 0; p < passes; p++) {
|
|
130
|
+
const res = fixDraft(text, recheck(text), { ...opts, protect });
|
|
131
|
+
left = res.left;
|
|
132
|
+
if (!res.changes.length) break;
|
|
133
|
+
changes.push(...res.changes);
|
|
134
|
+
text = res.text;
|
|
135
|
+
}
|
|
136
|
+
return { text, changes, left: recheck(text) };
|
|
137
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Manti (factcheck-docs): check an AI-written document against the input it was written from.
|
|
2
|
+
|
|
3
|
+
import { toUnits } from "./text.js";
|
|
4
|
+
import { sourceValues, sourceFigures, derivedValues, findNumbers } 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
|
+
/** How findings roll up into a scorecard. Each dimension starts at 100. */
|
|
11
|
+
export const DIMENSIONS = [
|
|
12
|
+
{ key: "accuracy", label: "Accuracy", checks: ["unsourced-number", "invented-name", "invented-quote", "period-mismatch", "contradiction", "scale-mismatch", "rounding-drift", "direction-flip", "role-change", "notes-conflict", "count-mismatch", "ai-claim"] },
|
|
13
|
+
{ key: "maths", label: "Maths", checks: ["math-error", "table-total", "percent-points"] },
|
|
14
|
+
{ key: "sources", label: "Sources", checks: ["fake-source", "overclaim", "broken-link"] },
|
|
15
|
+
{ key: "dates", label: "Dates", checks: ["date-error", "relative-date"] },
|
|
16
|
+
{ key: "completeness", label: "Completeness", checks: ["missing-section", "missing-owner", "leftover", "missing-fact"] },
|
|
17
|
+
{ key: "clarity", label: "Clarity", checks: ["vague-claim", "readability"] },
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Check a markdown document.
|
|
22
|
+
* @param {string} doc The draft to check.
|
|
23
|
+
* @param {object} [opts]
|
|
24
|
+
* @param {string} [opts.source] What the author actually gave the AI (notes, data, thread). Enables source checks.
|
|
25
|
+
* @param {Date|string} [opts.today] Date used for past-date checks. Defaults to now.
|
|
26
|
+
* @param {string[]} [opts.only] Run only these checks.
|
|
27
|
+
* @param {string[]} [opts.allowNames] Names that are fine even if not in the source (your company, your product).
|
|
28
|
+
* @param {object[]} [opts.extra] Findings from elsewhere (the optional AI double-check) to score alongside.
|
|
29
|
+
* @returns {{ score: number, grade: string, findings: object[], counts: object, dimensions: {key,label,score,lost,count,ran}[], checksRun: string[] }}
|
|
30
|
+
*/
|
|
31
|
+
export function factcheck(doc, opts = {}) {
|
|
32
|
+
const source = opts.source ?? "";
|
|
33
|
+
const hasSource = source.trim().length > 0;
|
|
34
|
+
const values = hasSource ? sourceValues(source) : [];
|
|
35
|
+
const figures = hasSource ? sourceFigures(source) : [];
|
|
36
|
+
const today = opts.today === null ? null : toUtcDay(opts.today ? new Date(opts.today) : new Date());
|
|
37
|
+
const sourceDates = new Set();
|
|
38
|
+
if (hasSource) for (const line of source.split("\n")) for (const d of findDates(line)) sourceDates.add(dateKey(d));
|
|
39
|
+
|
|
40
|
+
const ctx = {
|
|
41
|
+
hasSource,
|
|
42
|
+
source,
|
|
43
|
+
sourceLower: source.toLowerCase(),
|
|
44
|
+
values,
|
|
45
|
+
figures,
|
|
46
|
+
derived: hasSource ? derivedValues(values, figures) : [],
|
|
47
|
+
sourceDates,
|
|
48
|
+
today,
|
|
49
|
+
assumeYear: today ? new Date(today).getUTCFullYear() : null,
|
|
50
|
+
allowNames: new Set((opts.allowNames ?? []).map((n) => n.toLowerCase())),
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const units = toUnits(doc);
|
|
54
|
+
const names = opts.only?.length ? opts.only : Object.keys(CHECKS);
|
|
55
|
+
const findings = [];
|
|
56
|
+
for (const name of names) {
|
|
57
|
+
const check = CHECKS[name];
|
|
58
|
+
if (!check) throw new Error(`Unknown check: ${name}. Known: ${Object.keys(CHECKS).join(", ")}`);
|
|
59
|
+
findings.push(...check(units, ctx));
|
|
60
|
+
}
|
|
61
|
+
// one wrong number, one finding: when a specific check explains a figure (wrong maths, a total, a 10x slip),
|
|
62
|
+
// drop the generic "not in your notes" flag for that same figure on that line
|
|
63
|
+
const SPECIFIC = new Set(["math-error", "table-total", "scale-mismatch", "percent-points", "period-mismatch", "rounding-drift", "count-mismatch"]);
|
|
64
|
+
for (let k = findings.length - 1; k >= 0; k--) {
|
|
65
|
+
const x = findings[k];
|
|
66
|
+
if (x.check !== "unsourced-number") continue;
|
|
67
|
+
const v = findNumbers(x.text)[0]?.value;
|
|
68
|
+
if (v == null) continue;
|
|
69
|
+
if (findings.some((y) => SPECIFIC.has(y.check) && y.line === x.line && findNumbers(y.text).some((n) => n.value === v))) findings.splice(k, 1);
|
|
70
|
+
}
|
|
71
|
+
const extra = opts.extra ?? [];
|
|
72
|
+
findings.push(...extra);
|
|
73
|
+
findings.sort((a, b) => a.line - b.line || WEIGHT[b.severity] - WEIGHT[a.severity]);
|
|
74
|
+
|
|
75
|
+
const counts = { error: 0, warning: 0, note: 0 };
|
|
76
|
+
for (const x of findings) counts[x.severity]++;
|
|
77
|
+
const penalty = findings.reduce((s, x) => s + WEIGHT[x.severity], 0);
|
|
78
|
+
const score = Math.max(0, 100 - penalty);
|
|
79
|
+
const dimensions = DIMENSIONS.map((d) => {
|
|
80
|
+
const hits = findings.filter((x) => d.checks.includes(x.check));
|
|
81
|
+
const ran = d.checks.some((c) => names.includes(c) || extra.some((x) => x.check === c));
|
|
82
|
+
const lost = hits.reduce((s, x) => s + WEIGHT[x.severity], 0); // the areas' lost points add up to 100 - score (floored at 0)
|
|
83
|
+
return { key: d.key, label: d.label, score: Math.max(0, 100 - lost), lost, count: hits.length, ran };
|
|
84
|
+
});
|
|
85
|
+
return { score, grade: grade(score), findings, counts, dimensions, checksRun: names, sourceChecks: hasSource };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function grade(score) {
|
|
89
|
+
return score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : score >= 60 ? "D" : "F";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function toUtcDay(d) {
|
|
93
|
+
if (isNaN(d)) throw new Error("Invalid --today date");
|
|
94
|
+
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export { CHECKS };
|
|
98
|
+
export { fixDraft, fixAll } from "./fix.js";
|
|
99
|
+
export { aiCheck, AI_MODEL } from "./ai.js";
|