liarliar 0.0.0 → 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/dist/config.js ADDED
@@ -0,0 +1,33 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { createJiti } from 'jiti';
4
+ export const CONFIG_FILES = ['liarliar.config.ts', 'liarliar.config.mts', 'liarliar.config.js', 'liarliar.config.mjs'];
5
+ /** The tsconfig "paths" as jiti aliases, so a config can import the project's own code by "@/lib/x". */
6
+ function aliases(root) {
7
+ const file = join(root, 'tsconfig.json');
8
+ if (!existsSync(file))
9
+ return {};
10
+ try {
11
+ // tsconfig allows comments and trailing commas.
12
+ const json = JSON.parse(readFileSync(file, 'utf8').replace(/\/\*[\s\S]*?\*\/|(?<![:"])\/\/.*$/gm, '').replace(/,(\s*[}\]])/g, '$1'));
13
+ const base = join(root, json.compilerOptions?.baseUrl ?? '.');
14
+ const out = {};
15
+ for (const [from, [to]] of Object.entries(json.compilerOptions?.paths ?? {}))
16
+ if (to)
17
+ out[from.replace(/\/\*$/, '')] = join(base, to.replace(/\/\*$/, ''));
18
+ return out;
19
+ }
20
+ catch {
21
+ return {};
22
+ }
23
+ }
24
+ /** Finds and loads the config from the working directory or a path; its folder is the root unless it says otherwise. */
25
+ export async function loadConfig(path) {
26
+ const file = path ? resolve(path) : CONFIG_FILES.map((f) => resolve(f)).find((f) => existsSync(f));
27
+ if (!file || !existsSync(file))
28
+ throw new Error(`No liarliar config found (looked for ${CONFIG_FILES.join(', ')}). Run \`liarliar init\` to write one.`);
29
+ const root = dirname(file);
30
+ const jiti = createJiti(import.meta.url, { alias: aliases(root), interopDefault: true });
31
+ const config = (await jiti.import(file, { default: true }));
32
+ return { ...config, root: config.root ? resolve(root, config.root) : root };
33
+ }
@@ -0,0 +1,3 @@
1
+ /** Files under root matching any of the globs and none of the ignores, as sorted paths relative to root. */
2
+ export declare function list(root: string, globs: string[], ignore?: string[]): string[];
3
+ export declare const matches: (file: string, globs: string[]) => boolean;
package/dist/files.js ADDED
@@ -0,0 +1,13 @@
1
+ import { globSync } from 'node:fs';
2
+ import { matchesGlob } from 'node:path';
3
+ /** Files under root matching any of the globs and none of the ignores, as sorted paths relative to root. */
4
+ export function list(root, globs, ignore = []) {
5
+ const skip = ['**/node_modules/**', ...ignore];
6
+ const found = new Set();
7
+ for (const g of globs)
8
+ for (const f of globSync(g, { cwd: root }))
9
+ if (!skip.some((s) => matchesGlob(f, s)))
10
+ found.add(f.split('\\').join('/'));
11
+ return [...found].sort();
12
+ }
13
+ export const matches = (file, globs) => globs.some((g) => matchesGlob(file, g));
@@ -0,0 +1,12 @@
1
+ import type { Config, Context, Finding } from './types.js';
2
+ export declare function checkGenerated(context: Context, config: Config, docFiles: string[], write: boolean): Promise<Finding[]>;
3
+ /**
4
+ * A generator for .env.example: every environment variable the code reads, one per line, no values.
5
+ * `extra` names variables a library reads for you; `exclude` those the platform sets.
6
+ */
7
+ export declare function envExample(options?: {
8
+ header?: string;
9
+ extra?: string[];
10
+ exclude?: string[];
11
+ from?: string[];
12
+ }): ({ index }: Context) => string;
@@ -0,0 +1,63 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { matches } from './files.js';
3
+ /**
4
+ * Text written from the code, so it can't drift: a region inside a doc
5
+ * (<!-- liarliar:generate NAME --> … <!-- liarliar:end -->) or a whole file.
6
+ * `liarliar check` fails when the text and the code disagree; `liarliar write` writes it again.
7
+ */
8
+ const REGION = /(<!--\s*liarliar:generate\s+([\w-]+)\s*-->\n)([\s\S]*?)(<!--\s*liarliar:end\s*-->)/g;
9
+ const withNewline = (s) => (s.endsWith('\n') ? s : `${s}\n`);
10
+ export async function checkGenerated(context, config, docFiles, write) {
11
+ const findings = [];
12
+ const { root } = context;
13
+ for (const file of docFiles) {
14
+ const text = readFileSync(`${root}/${file}`, 'utf8');
15
+ const parts = [];
16
+ for (const m of text.matchAll(REGION)) {
17
+ const name = m[2];
18
+ const generator = config.generate?.[name];
19
+ const line = text.slice(0, m.index).split('\n').length;
20
+ if (!generator) {
21
+ findings.push({ check: 'generated', severity: 'error', file, line, message: `No generator called "${name}".`, fix: `Add generate["${name}"] to the liarliar config, or fix the region's name.` });
22
+ continue;
23
+ }
24
+ const next = withNewline(await generator(context));
25
+ if (next === m[3])
26
+ continue;
27
+ const start = m.index + m[1].length;
28
+ parts.push({ start, end: start + m[3].length, next, name });
29
+ if (!write)
30
+ findings.push({ check: 'generated', severity: 'error', file, line, message: `The "${name}" region no longer matches the code.`, fix: 'Run `liarliar write` and commit the result.' });
31
+ }
32
+ if (write && parts.length) {
33
+ let out = text;
34
+ for (const p of [...parts].reverse())
35
+ out = out.slice(0, p.start) + p.next + out.slice(p.end);
36
+ writeFileSync(`${root}/${file}`, out);
37
+ }
38
+ }
39
+ for (const [file, generator] of Object.entries(config.files ?? {})) {
40
+ const next = withNewline(await generator(context));
41
+ const now = existsSync(`${root}/${file}`) ? readFileSync(`${root}/${file}`, 'utf8') : undefined;
42
+ if (now === next)
43
+ continue;
44
+ if (write)
45
+ writeFileSync(`${root}/${file}`, next);
46
+ else
47
+ findings.push({ check: 'generated', severity: 'error', file, line: 1, message: now === undefined ? `${file} is missing.` : `${file} no longer matches the code.`, fix: 'Run `liarliar write` and commit the result.' });
48
+ }
49
+ return findings;
50
+ }
51
+ /**
52
+ * A generator for .env.example: every environment variable the code reads, one per line, no values.
53
+ * `extra` names variables a library reads for you; `exclude` those the platform sets.
54
+ */
55
+ export function envExample(options = {}) {
56
+ const exclude = new Set(['NODE_ENV', ...(options.exclude ?? [])]);
57
+ return ({ index }) => {
58
+ // `from` limits it to variables read in those files (the app's own code, say, not its scripts).
59
+ const read = [...index.env.entries()].filter(([, defs]) => !options.from || defs.some((d) => matches(d.file, options.from))).map(([name]) => name);
60
+ const names = [...new Set([...read, ...(options.extra ?? [])])].filter((n) => !exclude.has(n)).sort();
61
+ return `${options.header ? withNewline(options.header) : ''}${names.map((n) => `${n}=`).join('\n')}\n`;
62
+ };
63
+ }
@@ -0,0 +1,9 @@
1
+ export { check } from './check.js';
2
+ export { loadConfig } from './config.js';
3
+ export { envExample } from './generated.js';
4
+ export { format, failed } from './report.js';
5
+ export type { Config, Context, Finding, Generator, Report } from './types.js';
6
+ export type { CodeIndex, Definition, Value } from './code.js';
7
+ import type { Config } from './types.js';
8
+ /** Types a config file: `export default defineConfig({ docs: [...], code: [...] })`. */
9
+ export declare const defineConfig: (config: Config) => Config;
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { check } from './check.js';
2
+ export { loadConfig } from './config.js';
3
+ export { envExample } from './generated.js';
4
+ export { format, failed } from './report.js';
5
+ /** Types a config file: `export default defineConfig({ docs: [...], code: [...] })`. */
6
+ export const defineConfig = (config) => config;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A Markdown file as liarliar reads it: the text, a copy with everything that isn't prose blanked out
3
+ * (code, comments, link targets, dates) so numbers in it aren't mistaken for claims, and the inline-code
4
+ * spans, which is where code names live.
5
+ */
6
+ export interface Doc {
7
+ file: string;
8
+ text: string;
9
+ /** Same length as text, newlines kept; code, comments, URLs and dates are spaces. */
10
+ prose: string;
11
+ /** Inline code spans: their content and where they sit in text. */
12
+ spans: {
13
+ code: string;
14
+ start: number;
15
+ end: number;
16
+ }[];
17
+ line: (offset: number) => number;
18
+ }
19
+ export declare function readDoc(file: string, root: string): Doc;
20
+ export declare function parseDoc(file: string, text: string): Doc;
@@ -0,0 +1,44 @@
1
+ import { readFileSync } from 'node:fs';
2
+ const blank = (s) => s.replace(/[^\n]/g, ' ');
3
+ const MONTHS = 'Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?';
4
+ const DATES = new RegExp(String.raw `\b\d{4}-\d{2}-\d{2}(?:[T ][\d:.]+Z?)?\b|\b\d{1,2}\s+(?:${MONTHS})\b(?:\s+\d{4})?|\b(?:${MONTHS})\s+\d{1,2}\b(?:,?\s+\d{4})?|\b20[12]\d\b(?!\s*(?:ms|s|min|minutes?|hours?|days?|%|characters?|rows?|items?))`, 'g');
5
+ export function readDoc(file, root) {
6
+ return parseDoc(file, readFileSync(`${root}/${file}`, 'utf8'));
7
+ }
8
+ export function parseDoc(file, text) {
9
+ let prose = text;
10
+ const keep = (pattern) => {
11
+ prose = prose.replace(pattern, (m) => blank(m));
12
+ };
13
+ // Fenced blocks (``` or ~~~), then HTML comments, before inline code so fences aren't read as spans.
14
+ keep(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm);
15
+ keep(/<!--[\s\S]*?-->/g);
16
+ const spans = [];
17
+ prose = prose.replace(/(`+)([^`\n]+?)\1/g, (m, _ticks, code, offset) => {
18
+ spans.push({ code: code.trim(), start: offset, end: offset + m.length });
19
+ return blank(m);
20
+ });
21
+ keep(/\]\([^)\s]*\)/g); // link targets
22
+ keep(/https?:\/\/\S+/g);
23
+ keep(DATES);
24
+ keep(/^\s*\d+\.(?=\s)/gm); // numbered list markers
25
+ keep(/\b[\w-]+\/[\w./-]+/g); // paths: src/lib/x.ts, docs/a.md
26
+ keep(/\b[vV]?\d+\.\d+\.\d+\b/g); // versions
27
+ const starts = [0];
28
+ for (let i = 0; i < text.length; i++)
29
+ if (text[i] === '\n')
30
+ starts.push(i + 1);
31
+ const line = (offset) => {
32
+ let lo = 0;
33
+ let hi = starts.length - 1;
34
+ while (lo < hi) {
35
+ const mid = (lo + hi + 1) >> 1;
36
+ if (starts[mid] <= offset)
37
+ lo = mid;
38
+ else
39
+ hi = mid - 1;
40
+ }
41
+ return lo + 1;
42
+ };
43
+ return { file, text, prose, spans, line };
44
+ }
@@ -0,0 +1,10 @@
1
+ import type { CodeIndex } from './code.js';
2
+ import type { Doc } from './markdown.js';
3
+ import type { Finding } from './types.js';
4
+ /**
5
+ * Names a doc gives in backticks that the code no longer has: `MATCH_WINDOW` after the code dropped it.
6
+ * A name counts when it is SCREAMING_CASE with an underscore (a constant or an env variable). A doc may name
7
+ * a dropped one if it says so close by ("removed", "renamed", "was", …).
8
+ */
9
+ export declare const DEFAULT_GONE: RegExp;
10
+ export declare function checkNames(doc: Doc, index: CodeIndex, allow: Set<string>, gone: RegExp): Finding[];
package/dist/names.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Names a doc gives in backticks that the code no longer has: `MATCH_WINDOW` after the code dropped it.
3
+ * A name counts when it is SCREAMING_CASE with an underscore (a constant or an env variable). A doc may name
4
+ * a dropped one if it says so close by ("removed", "renamed", "was", …).
5
+ */
6
+ export const DEFAULT_GONE = /\b(deleted|removed|killed|retired|gone|dropped|deprecated|not built|was renamed|renamed|replaced|used to|no longer|formerly)\b/i;
7
+ /** The sentence holding a span: from the last sentence end before it to the next after it. */
8
+ function sentence(text, start, end) {
9
+ const before = text.slice(Math.max(0, start - 400), start);
10
+ const cut = Math.max(...[...before.matchAll(/[.!?](?=\s)|\n\s*\n/g)].map((m) => m.index + m[0].length), 0);
11
+ const after = text.slice(end, end + 400);
12
+ const stop = /[.!?](?=\s|$)|\n\s*\n/.exec(after);
13
+ return before.slice(cut) + text.slice(start, end) + after.slice(0, stop ? stop.index : after.length);
14
+ }
15
+ export function checkNames(doc, index, allow, gone) {
16
+ const findings = [];
17
+ const seen = new Set();
18
+ for (const span of doc.spans) {
19
+ const m = /^([A-Z][A-Z0-9]*_[A-Z0-9_]+)(?:\.[\w.]+)?$/.exec(span.code);
20
+ if (!m)
21
+ continue;
22
+ const name = m[1];
23
+ if (seen.has(name) || allow.has(name) || index.words.has(name))
24
+ continue;
25
+ if (gone.test(sentence(doc.text, span.start, span.end)))
26
+ continue;
27
+ seen.add(name);
28
+ findings.push({
29
+ check: 'name',
30
+ severity: 'error',
31
+ file: doc.file,
32
+ line: doc.line(span.start),
33
+ message: `\`${name}\` is not in the code any more.`,
34
+ fix: `Rename it in ${doc.file} as the code did, or say close by that it was removed; if a platform sets it, add it to names.allow.`,
35
+ });
36
+ }
37
+ return findings;
38
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Numbers as people write them in prose: "15", "1,000", "0.05", "fifteen", "six weeks",
3
+ * "$5", "£250k", "$10M", "70%", "21:00", "8 million", "a 15-minute window", "within an hour".
4
+ */
5
+ export type TimeUnit = 'ms' | 's' | 'min' | 'h' | 'day' | 'week';
6
+ export type Unit = TimeUnit | 'percent' | 'money' | 'clock' | 'bytes' | null;
7
+ export interface Quantity {
8
+ value: number;
9
+ unit: Unit;
10
+ /** "about 960", "~5", "roughly a day": stated loosely, so never held to the code. */
11
+ approx: boolean;
12
+ /** Offsets in the text the quantity was read from. */
13
+ start: number;
14
+ end: number;
15
+ text: string;
16
+ }
17
+ export declare const MS: Record<TimeUnit, number>;
18
+ /** Sizes in bytes (or characters, which is how code usually counts a body). */
19
+ export declare const BYTES: Record<string, number>;
20
+ export declare function timeUnit(word: string): TimeUnit | null;
21
+ /** Every quantity in a stretch of text, in order. Masked spans (code, dates) should already be blanked out. */
22
+ export declare function quantities(text: string): Quantity[];
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Numbers as people write them in prose: "15", "1,000", "0.05", "fifteen", "six weeks",
3
+ * "$5", "£250k", "$10M", "70%", "21:00", "8 million", "a 15-minute window", "within an hour".
4
+ */
5
+ export const MS = { ms: 1, s: 1000, min: 60_000, h: 3_600_000, day: 86_400_000, week: 604_800_000 };
6
+ const WORDS = {
7
+ zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10,
8
+ eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18,
9
+ nineteen: 19, twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, ninety: 90, hundred: 100, twice: 2,
10
+ };
11
+ const SCALE = { thousand: 1e3, million: 1e6, billion: 1e9 };
12
+ const SUFFIX = { k: 1e3, m: 1e6, bn: 1e9, b: 1e9 };
13
+ /** Sizes in bytes (or characters, which is how code usually counts a body). */
14
+ export const BYTES = { KB: 1e3, kB: 1e3, MB: 1e6, GB: 1e9, KiB: 1024, MiB: 1024 ** 2, GiB: 1024 ** 3 };
15
+ const TIME_WORDS = [
16
+ [/^(?:ms|milliseconds?)$/i, 'ms'],
17
+ [/^(?:s|secs?|seconds?)$/i, 's'],
18
+ [/^(?:mins?|minutes?)$/i, 'min'],
19
+ [/^(?:h|hrs?|hours?)$/i, 'h'],
20
+ [/^days?$/i, 'day'],
21
+ [/^weeks?$/i, 'week'],
22
+ ];
23
+ export function timeUnit(word) {
24
+ for (const [pattern, unit] of TIME_WORDS)
25
+ if (pattern.test(word))
26
+ return unit;
27
+ return null;
28
+ }
29
+ const APPROX = /(?:\babout|\baround|\broughly|\bsome|\bnearly|\balmost|~|≈|\bapprox\.?|\bapproximately)\s*$/i;
30
+ const NEGATED = /(?:\bnot|\bnever|\brather than|\binstead of|\bno longer)\s*$/i;
31
+ const WORD_NUMBER = Object.keys(WORDS).join('|');
32
+ const UNIT_WORD = 'ms|milliseconds?|secs?|seconds?|mins?|minutes?|hrs?|hours?|days?|weeks?|s|h';
33
+ /** One pattern for every way a quantity is written. Order matters: clock times and money before bare numbers. */
34
+ const QUANTITY = new RegExp([
35
+ String.raw `\b(?<ch>[01]?\d|2[0-3]):(?<cm>[0-5]\d)\b`,
36
+ String.raw `(?<cur>[$£€])\s?(?<amt>\d[\d,]*(?:\.\d+)?)(?:(?<msfx>k|K|M|bn|B)\b|\s+(?<mscale>thousand|million|billion)\b)?`,
37
+ String.raw `(?:(?<![\w.$£€])(?<num>\d[\d,_]*(?:\.\d+)?)(?<nsfx>k|M|bn)?\b|\b(?<word>${WORD_NUMBER})\b)(?:\s+(?<scale>thousand|million|billion)\b)?(?:\s*(?<pct>%)|\s?(?<size>KB|kB|MB|GB|KiB|MiB|GiB)\b|[\s-]+(?<unit>${UNIT_WORD})\b)?`,
38
+ String.raw `(?<=\b(?:within|after|for|in|than|over|under|past|about|every|once|per)\s+)\b(?:an?)\s+(?<aunit>ms|millisecond|sec|second|min|minute|hour|day|week)\b`,
39
+ ].join('|'), 'gi');
40
+ /** Every quantity in a stretch of text, in order. Masked spans (code, dates) should already be blanked out. */
41
+ export function quantities(text) {
42
+ const found = [];
43
+ for (const m of text.matchAll(QUANTITY)) {
44
+ const g = m.groups;
45
+ const start = m.index;
46
+ const end = start + m[0].length;
47
+ const approx = APPROX.test(text.slice(Math.max(0, start - 16), start));
48
+ // "At 08:30, not 08:00": a number ruled out is no claim.
49
+ if (NEGATED.test(text.slice(Math.max(0, start - 16), start)))
50
+ continue;
51
+ const push = (value, unit) => {
52
+ if (Number.isFinite(value))
53
+ found.push({ value, unit, approx, start, end, text: m[0] });
54
+ };
55
+ if (g.ch !== undefined)
56
+ push(Number(g.ch) + Number(g.cm) / 60, 'clock');
57
+ else if (g.amt !== undefined) {
58
+ const scale = g.msfx ? SUFFIX[g.msfx.toLowerCase()] : g.mscale ? SCALE[g.mscale.toLowerCase()] : 1;
59
+ push(Number(g.amt.replace(/,/g, '')) * scale, 'money');
60
+ }
61
+ else if (g.num !== undefined || g.word !== undefined) {
62
+ const unit = g.pct ? 'percent' : g.size ? 'bytes' : g.unit ? timeUnit(g.unit) : null;
63
+ // "one" is mostly a pronoun ("one whose notes…"); it counts only with a unit or a scale.
64
+ if (g.word?.toLowerCase() === 'one' && unit === null && !g.scale)
65
+ continue;
66
+ let value = g.num !== undefined ? Number(g.num.replace(/[,_]/g, '')) : WORDS[g.word.toLowerCase()];
67
+ if (g.nsfx)
68
+ value *= SUFFIX[g.nsfx.toLowerCase()];
69
+ if (g.scale)
70
+ value *= SCALE[g.scale.toLowerCase()];
71
+ if (g.size)
72
+ value *= BYTES[g.size];
73
+ push(value, unit);
74
+ }
75
+ else if (g.aunit !== undefined)
76
+ push(1, timeUnit(g.aunit));
77
+ }
78
+ return found;
79
+ }
@@ -0,0 +1,8 @@
1
+ import type { Config, Finding } from './types.js';
2
+ /** The ways a doc names a file: its path, any tail of it two parts or longer, its bare name unless generic, and any aliases. */
3
+ export declare function namesOf(file: string, aliases?: (file: string) => string[]): string[];
4
+ export declare function docsOf(file: string, root: string, docs: {
5
+ path: string;
6
+ text: string;
7
+ }[], aliases?: (file: string) => string[]): string[];
8
+ export declare function checkOwners(root: string, config: Config, docFiles: string[]): Finding[];
package/dist/owners.js ADDED
@@ -0,0 +1,82 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { basename } from 'node:path';
4
+ import { list, matches } from './files.js';
5
+ /**
6
+ * Which doc owns which code, inferred: a doc owns a file it names (its path, its last two parts, or its bare
7
+ * name when that isn't generic) and a file owns up to a doc it points to in a comment. Then:
8
+ * - every owned file has a doc (requireDoc);
9
+ * - a branch that changes an owned file changes one of its docs too, unless every commit that changed the file
10
+ * says why not in a trailer: `Docs-unchanged: <reason>`.
11
+ */
12
+ const GENERIC = /^(index|route|page|types|layout|main|mod|__init__)\.\w+$/;
13
+ const TESTS = ['**/*.test.*', '**/*.spec.*', '**/__tests__/**', 'test/**', 'tests/**'];
14
+ /** The ways a doc names a file: its path, any tail of it two parts or longer, its bare name unless generic, and any aliases. */
15
+ export function namesOf(file, aliases) {
16
+ const parts = file.split('/');
17
+ const bare = basename(file);
18
+ const tails = parts.slice(0, -1).map((_, i) => parts.slice(i).join('/'));
19
+ return [...new Set([...tails, ...(GENERIC.test(bare) ? [] : [bare]), ...(aliases?.(file) ?? [])].filter((n) => n.length > 0))];
20
+ }
21
+ /** Does a doc's text name this file? As code, a link, or a path in a list. */
22
+ function names(text, name) {
23
+ const e = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
24
+ return new RegExp(`(?:\`|\\(|/|\\s)${e}(?:\`|\\)|,|:|\\s|$)`, 'm').test(text) || text.includes(`\`${name}`);
25
+ }
26
+ export function docsOf(file, root, docs, aliases) {
27
+ const own = existsSync(`${root}/${file}`) ? readFileSync(`${root}/${file}`, 'utf8') : '';
28
+ const pointed = docs.filter((d) => own.includes(d.path)).map((d) => d.path);
29
+ const named = docs.filter((d) => namesOf(file, aliases).some((n) => names(d.text, n))).map((d) => d.path);
30
+ return [...new Set([...pointed, ...named])];
31
+ }
32
+ export function checkOwners(root, config, docFiles) {
33
+ const o = config.owners;
34
+ if (!o)
35
+ return [];
36
+ const except = [...(o.except ?? []), ...TESTS];
37
+ const trailer = o.trailer ?? 'Docs-unchanged';
38
+ const docs = (o.docs ? list(root, o.docs, config.ignore) : docFiles).map((path) => ({ path, text: readFileSync(`${root}/${path}`, 'utf8') }));
39
+ const owned = list(root, o.code, config.ignore).filter((f) => !matches(f, except));
40
+ const findings = [];
41
+ if (o.requireDoc !== false) {
42
+ for (const f of owned) {
43
+ if (docsOf(f, root, docs, o.aliases).length)
44
+ continue;
45
+ findings.push({ check: 'owner', severity: 'error', file: f, line: 1, message: `${f} has no doc that names it.`, fix: `Name it in the doc for its area (\`${basename(f)}\`), or point to that doc in its header comment; if no doc would say anything about it, add it to owners.except.` });
46
+ }
47
+ }
48
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
49
+ let base;
50
+ try {
51
+ base = git('merge-base', 'HEAD', o.base ?? 'origin/main');
52
+ }
53
+ catch {
54
+ return findings; // no base branch here (a shallow checkout): nothing to compare
55
+ }
56
+ if (!base)
57
+ return findings;
58
+ const changed = git('diff', '--name-only', '--diff-filter=AMR', base).split('\n').filter(Boolean);
59
+ const touched = new Set(changed);
60
+ // A trailer speaks for its own commit; a file is excused only when every commit that changed it says why.
61
+ const unexcused = new Set();
62
+ const pattern = new RegExp(`^${trailer}:\\s*\\S`, 'm');
63
+ for (const sha of git('rev-list', `${base}..HEAD`).split('\n').filter(Boolean)) {
64
+ if (pattern.test(git('log', '-1', '--format=%B', sha)))
65
+ continue;
66
+ for (const f of git('diff-tree', '--no-commit-id', '--name-only', '-r', sha).split('\n').filter(Boolean))
67
+ unexcused.add(f);
68
+ }
69
+ // Uncommitted changes have no trailer yet.
70
+ for (const f of git('diff', '--name-only', 'HEAD').split('\n').filter(Boolean)) {
71
+ unexcused.add(f);
72
+ touched.add(f);
73
+ }
74
+ const ownedSet = new Set(owned);
75
+ for (const f of [...touched].filter((f) => ownedSet.has(f) && unexcused.has(f))) {
76
+ const own = docsOf(f, root, docs, o.aliases);
77
+ if (!own.length || own.some((d) => touched.has(d)))
78
+ continue;
79
+ findings.push({ check: 'owner', severity: 'error', file: f, line: 1, message: `${f} changed but ${own.join(' or ')} did not.`, fix: `Update ${own.join(' or ')} in this branch, or end each commit that changed ${f} with a trailer "${trailer}: <why>".` });
80
+ }
81
+ return findings;
82
+ }
@@ -0,0 +1,6 @@
1
+ import type { Report } from './types.js';
2
+ /** The report as people and agents read it: every failure with its fix, grouped, then one line of totals. */
3
+ export declare function format(report: Report, options?: {
4
+ all?: boolean;
5
+ }): string;
6
+ export declare const failed: (report: Report) => boolean;
package/dist/report.js ADDED
@@ -0,0 +1,27 @@
1
+ const TITLES = {
2
+ claim: 'Numbers the docs state',
3
+ name: 'Names the docs give',
4
+ owner: 'Docs that own the code',
5
+ generated: 'Text written from the code',
6
+ };
7
+ /** The report as people and agents read it: every failure with its fix, grouped, then one line of totals. */
8
+ export function format(report, options = {}) {
9
+ const shown = report.findings.filter((f) => f.severity !== 'info' || options.all);
10
+ const lines = [];
11
+ for (const check of Object.keys(TITLES)) {
12
+ const of = shown.filter((f) => f.check === check);
13
+ if (!of.length)
14
+ continue;
15
+ lines.push(`\n${TITLES[check]}`);
16
+ for (const f of of) {
17
+ const mark = f.severity === 'error' ? '✗' : f.severity === 'warning' ? '!' : '·';
18
+ lines.push(` ${mark} ${f.file}:${f.line} ${f.message}`, ` → ${f.fix}`);
19
+ }
20
+ }
21
+ const errors = report.findings.filter((f) => f.severity === 'error').length;
22
+ const warnings = report.findings.filter((f) => f.severity === 'warning').length;
23
+ const { bound, passed, unbound } = report.claims;
24
+ lines.push('', `${errors ? '✗' : '✓'} liarliar: ${errors} error${errors === 1 ? '' : 's'}, ${warnings} warning${warnings === 1 ? '' : 's'}. ${passed} of ${bound} stated numbers match the code; ${unbound} more name a constant without a number liarliar can check${options.all ? '' : ' (--all lists them)'}.`);
25
+ return lines.join('\n').trimStart();
26
+ }
27
+ export const failed = (report) => report.findings.some((f) => f.severity === 'error');
@@ -0,0 +1,20 @@
1
+ import type { CodeIndex, Definition, Value } from './code.js';
2
+ /** What a doc's code name stands for in the code, if exactly one thing. */
3
+ export type Resolved = {
4
+ kind: 'value';
5
+ value: Value;
6
+ where: Definition;
7
+ } | {
8
+ kind: 'ambiguous';
9
+ where: Definition[];
10
+ } | {
11
+ kind: 'unknown';
12
+ where: Definition[];
13
+ } | {
14
+ kind: 'missing';
15
+ };
16
+ /**
17
+ * `LEDGER_DAYS`, `STORY_RULE.days`, or an env var's default. A name defined in several files is settled by the
18
+ * file paths the doc names (`hints`, closest first), then by which definitions are exported.
19
+ */
20
+ export declare function resolve(index: CodeIndex, name: string, hints?: string[][]): Resolved;
@@ -0,0 +1,42 @@
1
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
2
+ function pick(defs, path) {
3
+ const values = defs.map((d) => {
4
+ let v = d.value;
5
+ for (const key of path)
6
+ v = v !== null && typeof v === 'object' && !Array.isArray(v) ? v[key] : Array.isArray(v) && /^\d+$/.test(key) ? v[Number(key)] : undefined;
7
+ return v;
8
+ });
9
+ const known = defs.map((d, i) => ({ d, v: values[i] })).filter((x) => x.v !== undefined);
10
+ if (known.length === 0)
11
+ return { kind: 'unknown', where: defs };
12
+ if (!known.every((x) => same(x.v, known[0].v)))
13
+ return { kind: 'ambiguous', where: known.map((x) => x.d) };
14
+ return { kind: 'value', value: known[0].v, where: known[0].d };
15
+ }
16
+ /**
17
+ * `LEDGER_DAYS`, `STORY_RULE.days`, or an env var's default. A name defined in several files is settled by the
18
+ * file paths the doc names (`hints`, closest first), then by which definitions are exported.
19
+ */
20
+ export function resolve(index, name, hints = []) {
21
+ const [head, ...path] = name.split('.');
22
+ let defs = index.constants.get(head) ?? [];
23
+ for (const hint of hints) {
24
+ if (defs.length < 2)
25
+ break;
26
+ const named = defs.filter((d) => hint.some((h) => d.file.endsWith(h) || h.endsWith(d.file)));
27
+ if (named.length)
28
+ defs = named;
29
+ }
30
+ if (defs.length > 1 && defs.some((d) => d.exported))
31
+ defs = defs.filter((d) => d.exported);
32
+ if (defs.length)
33
+ return pick(defs, path);
34
+ if (path.length === 0) {
35
+ const env = (index.env.get(head) ?? []).filter((d) => d.value !== undefined);
36
+ if (env.length)
37
+ return pick(env, []);
38
+ if (index.env.has(head))
39
+ return { kind: 'unknown', where: index.env.get(head) };
40
+ }
41
+ return { kind: 'missing' };
42
+ }
@@ -0,0 +1,20 @@
1
+ import type { CodeIndex } from './code.js';
2
+ import type { Doc } from './markdown.js';
3
+ import type { Finding } from './types.js';
4
+ /**
5
+ * Claims in Markdown tables: a row that names code in its first cell and gives a value in a column headed
6
+ * "Default", "Without it" or "Value", as quoted code and nothing else (bar a note in brackets):
7
+ *
8
+ * | Variable | What | Default |
9
+ * | `MODEL_JUDGE` | The judge | `auto` |
10
+ * | `MIN_A`, `MIN_B` | Two floors | `2`, `5` |
11
+ *
12
+ * One value for the row, or one per name in order. An env variable is held to the defaults the code gives it;
13
+ * a constant to its value. A name the code doesn't know is left to the names check.
14
+ */
15
+ export declare const VALUE_COLUMN: RegExp;
16
+ export declare function checkTables(doc: Doc, index: CodeIndex, column?: RegExp): {
17
+ findings: Finding[];
18
+ bound: number;
19
+ passed: number;
20
+ };