@kirill.konshin/lint 0.5.1 → 0.5.3

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.
Files changed (30) hide show
  1. package/README.md +6 -4
  2. package/dist/lintPrepare.d.ts +32 -31
  3. package/dist/lintPrepare.d.ts.map +1 -1
  4. package/dist/lintPrepare.js +261 -125
  5. package/package.json +5 -3
  6. package/rules/agent.md +42 -36
  7. package/rules/openspec.md +12 -0
  8. package/rules/testing.md +1 -0
  9. package/skills/lint-repo.md +2 -2
  10. package/skills/spec-steward/SKILL.md +76 -0
  11. package/skills/spec-steward/references/apply.md +18 -0
  12. package/skills/spec-steward/references/audit.md +57 -0
  13. package/skills/spec-steward/references/contract.md +186 -0
  14. package/skills/spec-steward/references/criteria.md +59 -0
  15. package/skills/spec-steward/references/model.md +71 -0
  16. package/skills/spec-steward/references/review-format.md +61 -0
  17. package/skills/spec-steward/references/wiring.md +19 -0
  18. package/skills/spec-steward/scripts/lib/align.mjs +126 -0
  19. package/skills/spec-steward/scripts/lib/checks.mjs +584 -0
  20. package/skills/spec-steward/scripts/lib/citations.mjs +156 -0
  21. package/skills/spec-steward/scripts/lib/corpus.mjs +259 -0
  22. package/skills/spec-steward/scripts/lib/coverage.mjs +124 -0
  23. package/skills/spec-steward/scripts/lib/evidence.mjs +335 -0
  24. package/skills/spec-steward/scripts/lib/git.mjs +138 -0
  25. package/skills/spec-steward/scripts/lib/review.mjs +347 -0
  26. package/skills/spec-steward/scripts/lib/scan.mjs +364 -0
  27. package/skills/spec-steward/scripts/lib/util.mjs +161 -0
  28. package/skills/spec-steward/scripts/lib/wire.mjs +331 -0
  29. package/skills/spec-steward/scripts/steward.mjs +350 -0
  30. package/skills/spec-steward/workflows/audit.js +539 -0
@@ -0,0 +1,156 @@
1
+ // @ts-check
2
+ /**
3
+ * Citations of the corpus in the repository's files. A citation is a mention of `openspec/specs/<path>/spec.md`, with
4
+ * or without `#<anchor>`, in a comment, a `{@link}` or `@see` tag, or a Markdown/MDX document. Most citations are
5
+ * optional pointers for a reader, never evidence; the only gate on them is that they resolve. A citation BINDS — is
6
+ * evidence for the scenario it names — only where it sits on a test: inside a `describe`/`it`/`test` call or in the
7
+ * comment run directly above one, on a type assertion of a test file, anywhere in a lint configuration, or anywhere in
8
+ * a file matching a repository `--binds` glob.
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+
13
+ import { listFiles } from './git.mjs';
14
+ import { blockAt, COMMENT, isCLike, isDoc, lex, testBlocks } from './scan.mjs';
15
+ import { globToRegExp } from './util.mjs';
16
+
17
+ /**
18
+ * @typedef {'test' | 'file'} BindingKind
19
+ * @typedef {{
20
+ * file: string, line: number, target: string, anchor: string | null, kind: 'test' | 'code' | 'doc',
21
+ * binding: BindingKind | null, resolves: boolean, reason?: string, testTitle?: string, window: [number, number]
22
+ * }} Citation
23
+ * @typedef {{ files?: string[], binds?: string[] }} ScanOptions
24
+ */
25
+
26
+ const CITE = /((?:\.{1,2}\/)*(?:[\w@.-]+\/)*?openspec\/specs\/[\w./-]*?spec\.md)(?:#([\w-]+))?/g;
27
+ /** Build outputs and vendored copies, the specs themselves, and every change folder (prose that quotes other trees). */
28
+ const SKIP =
29
+ /(?:^|\/)(?:node_modules|dist|build|coverage|\.git|\.nx|\.yarn|\.yalc|\.turbo|\.next|\.docusaurus|\.eve)(?:\/|$)|^openspec\/changes\/|(?:^|\/)spec\.md$/;
30
+ const TEST_FILE =
31
+ /(?:^|\/)(?:__tests__|e2e)\/|\.(?:test|spec|test-d)\.[cm]?[jt]sx?$|(?:^|\/)test_[^/]+\.py$|_test\.(?:py|go)$/;
32
+ /** Lint configurations: a citation anywhere in one binds (a lint rule is the cheapest evidence). */
33
+ const LINT_CONFIG = /(?:^|\/)(?:eslint\.config\.[cm]?[jt]s|yarn\.config\.cjs)$/;
34
+
35
+ /** @param {string} file */
36
+ export const isTestFile = (file) => TEST_FILE.test(file) && !isDoc(file);
37
+ /** @param {string} file */
38
+ export const isLintConfig = (file) => LINT_CONFIG.test(file);
39
+
40
+ /**
41
+ * A mention counts as a citation in a document, in a comment, or in a `{@link …}`/`@see` tag — never in code or a
42
+ * string, where a path is data (a fixture, a constant). C-family files are lexed; every other text file has `#`
43
+ * comments besides the common markers.
44
+ * @param {string} file
45
+ * @param {string} line
46
+ * @param {number} at index of the match in the line
47
+ * @param {Uint8Array | null} cls the file's lexer classes, for C-family files
48
+ * @param {number} offset the line's start offset in the file
49
+ */
50
+ function citesHere(file, line, at, cls, offset) {
51
+ if (isDoc(file)) return true;
52
+ const before = line.slice(0, at);
53
+ if (/\/\/$/.test(before)) return false; // a URL's path, not a repository path
54
+ if (cls) return cls[offset + at] === COMMENT;
55
+ if (/\{@link\s*$/.test(before) || /@see\s+\S*$/.test(before)) return true;
56
+ if (/^\s*(?:\*|\/\*|\/\/|#|<!--)/.test(line)) return true;
57
+ return /(?:^|[^:])\/\/|\/\*|<!--/.test(before) || /(?:^|\s)#/.test(before);
58
+ }
59
+
60
+ /** Anchors a spec file renders, cached per absolute path. */
61
+ const anchorCache = new Map();
62
+ /** @param {string} abs @param {(text: string) => Set<string>} anchorsOf */
63
+ function anchorsFor(abs, anchorsOf) {
64
+ if (!anchorCache.has(abs))
65
+ anchorCache.set(abs, fs.existsSync(abs) ? anchorsOf(fs.readFileSync(abs, 'utf8')) : null);
66
+ return anchorCache.get(abs);
67
+ }
68
+
69
+ /**
70
+ * The files a scan reads: every tracked or untracked-unignored file, or the given ones; null when git cannot list them.
71
+ * @param {string} root
72
+ * @param {ScanOptions} [opts]
73
+ */
74
+ export const scanUniverse = (root, { files } = {}) => (files ?? listFiles(root))?.filter((f) => !SKIP.test(f)) ?? null;
75
+
76
+ /**
77
+ * Every citation in the repository's text files (a NUL byte marks a binary file).
78
+ * @param {string} root
79
+ * @param {(text: string) => Set<string>} anchorsOf renders a spec's anchors
80
+ * @param {ScanOptions} [opts]
81
+ * @returns {Citation[]}
82
+ */
83
+ export function scanCitations(root, anchorsOf, opts = {}) {
84
+ anchorCache.clear();
85
+ const binds = (opts.binds ?? []).map(globToRegExp);
86
+ /** @type {Citation[]} */
87
+ const out = [];
88
+ for (const file of scanUniverse(root, opts) ?? []) {
89
+ let buf;
90
+ try {
91
+ buf = fs.readFileSync(path.join(root, file));
92
+ } catch {
93
+ continue;
94
+ }
95
+ if (buf.indexOf('openspec/specs/') < 0 || buf.includes(0)) continue;
96
+ const text = buf.toString('utf8');
97
+ const lines = text.split('\n');
98
+ const kind = isTestFile(file) ? 'test' : isDoc(file) ? 'doc' : 'code';
99
+ const cls = isCLike(file) ? lex(text) : null;
100
+ const blocks = kind === 'test' ? testBlocks(file, text) : [];
101
+ const wholeFile = isLintConfig(file) || binds.some((re) => re.test(file));
102
+ let offset = 0;
103
+ lines.forEach((line, i) => {
104
+ for (const m of line.matchAll(CITE)) {
105
+ if (!citesHere(file, line, m.index ?? 0, cls, offset)) continue;
106
+ const raw = m[1];
107
+ const rel = raw.startsWith('openspec/') ? raw : path.join(path.dirname(file), raw);
108
+ const target = path.normalize(rel).split(path.sep).join('/');
109
+ const anchors = anchorsFor(path.join(root, target), anchorsOf);
110
+ const anchor = m[2] ?? null;
111
+ let resolves = true;
112
+ let reason;
113
+ if (!anchors) {
114
+ resolves = false;
115
+ reason = 'file does not exist';
116
+ } else if (anchor && !anchors.has(anchor)) {
117
+ resolves = false;
118
+ reason = `anchor #${anchor} not found`;
119
+ }
120
+ const block = blockAt(blocks, i + 1);
121
+ /** @type {BindingKind | null} */
122
+ const binding = block ? 'test' : wholeFile ? 'file' : null;
123
+ out.push({
124
+ file,
125
+ line: i + 1,
126
+ target,
127
+ anchor,
128
+ kind,
129
+ binding,
130
+ resolves,
131
+ reason,
132
+ testTitle: block?.title ?? undefined,
133
+ window: block ? [block.attach, block.end] : [i + 1, Math.min(lines.length, i + 25)],
134
+ });
135
+ }
136
+ offset += line.length + 1;
137
+ });
138
+ }
139
+ return out;
140
+ }
141
+
142
+ /** Citations grouped by `<target>#<anchor>`. @param {Citation[]} citations */
143
+ export function byAnchor(citations) {
144
+ /** @type {Map<string, Citation[]>} */
145
+ const map = new Map();
146
+ for (const c of citations) {
147
+ if (!c.anchor) continue;
148
+ const key = `${c.target}#${c.anchor}`;
149
+ map.set(key, [...(map.get(key) ?? []), c]);
150
+ }
151
+ return map;
152
+ }
153
+
154
+ /** The anchors a binding citation proves, as `<spec file>#<anchor>`. @param {Citation[]} citations */
155
+ export const boundAnchors = (citations) =>
156
+ new Set(citations.filter((c) => c.binding && c.anchor && c.resolves).map((c) => `${c.target}#${c.anchor}`));
@@ -0,0 +1,259 @@
1
+ // @ts-check
2
+ /**
3
+ * The OpenSpec corpus as data: capabilities, requirements, scenarios, each with its line and anchor, and the two
4
+ * markers a requirement can carry — `**⚠️ Advisory:**` (its class) and `**⚠️ Known gap (<tracker>):**` (a gap,
5
+ * exempting the scenarios it names or whose block it sits in).
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ import { filesAt, showMany } from './git.mjs';
11
+ import { slugify, stripCode, strongCount, weakCount } from './util.mjs';
12
+
13
+ /**
14
+ * @typedef {{ kw: string, text: string, line: number }} Step
15
+ * @typedef {{ label: string, tracker: string | null, line: number, text: string, scenario: string | null,
16
+ * inline: boolean }} Marker
17
+ * @typedef {{ tracker: string, text: string, line: number, scenario: string | null, exempts: string[],
18
+ * named: boolean }} Gap
19
+ * @typedef {{ name: string, slug: string, line: number, end: number, block: string, steps: Step[],
20
+ * markers: Marker[] }} Scenario
21
+ * @typedef {{
22
+ * capability: string, file: string, name: string, slug: string, id: string, line: number, end: number,
23
+ * block: string, statement: string, statementLine: number, markers: Marker[], scenarios: Scenario[],
24
+ * strong: number, weak: number, advisory: boolean, gaps: Gap[]
25
+ * }} Requirement
26
+ * @typedef {{ line: number, slug: string, first: number }} DuplicateHeading
27
+ * @typedef {{ capability: string, file: string, purpose: string, slugs: Set<string>, requirements: Requirement[],
28
+ * duplicates: DuplicateHeading[] }} Capability
29
+ * @typedef {{ name: string, path: string, specsDir: string, capabilities: Capability[] }} Corpus
30
+ */
31
+
32
+ export const DEFAULT_SPECS_DIR = 'openspec/specs';
33
+
34
+ /** The two canonical markers; `<tracker>` is required text (a ticket key, a tickets-page id or a change folder). */
35
+ export const DEFAULT_MARKERS = ['**⚠️ Advisory:**', '**⚠️ Known gap (<tracker>):**'];
36
+ export const ADVISORY = 'Advisory';
37
+ export const KNOWN_GAP = 'Known gap';
38
+ export const RETIRED = 'Unenforced';
39
+
40
+ /** A marker on a line of its own: `**⚠️ Label (tracker):**`, tolerant of the spellings `marker-hygiene` repairs. */
41
+ const MARKER = /^\s*\*\*(?:⚠️?\s*)?([A-Z][\w -]{1,40}?)\s*(?:\(([^()\n]*)\))?\s*:?\s*\*\*\s*:?/u;
42
+ /** A marker spelling inside a line, where no tool reads it. */
43
+ const INLINE_MARKER =
44
+ /\S.*?\*\*(?:⚠️?\s*)?(Advisory|Known [Gg]ap|Unenforced)\s*(?:\([^()\n]*\))?\s*(?::\s*\*\*|\*\*\s*:)/u;
45
+ const STEP = /^\s*[-*]\s+\*\*(GIVEN|WHEN|THEN|AND|BUT)\*\*\s*(.*)$/i;
46
+ const LABELS = new Map([ADVISORY, KNOWN_GAP, RETIRED].map((l) => [l.toLowerCase(), l]));
47
+ const QUOTES = [`'…'`, `"…"`, `‘…’`, `“…”`, `_…_`, `*…*`];
48
+
49
+ /**
50
+ * The scenarios a Known gap names by title after "exempts" (quoted '…', "…", ‘…’, “…”, _…_ or *…*); null when it
51
+ * names none that way.
52
+ * @param {string} text
53
+ * @param {Scenario[]} scenarios
54
+ */
55
+ function namedIn(text, scenarios) {
56
+ const clause = /\bexempts?\b([\s\S]*)$/i.exec(text)?.[1].toLowerCase();
57
+ if (clause === undefined) return null;
58
+ const quoted = (/** @type {string} */ name) => QUOTES.map((q) => q.replace('…', name.toLowerCase()));
59
+ return scenarios.filter((s) => quoted(s.name).some((q) => clause.includes(q))).map((s) => s.slug);
60
+ }
61
+
62
+ /**
63
+ * Parse one capability specification.
64
+ * @param {string} text
65
+ * @param {string} file repository-relative path of the spec.md
66
+ * @param {string} capability
67
+ * @returns {Capability}
68
+ */
69
+ export function parseSpec(text, file, capability) {
70
+ const lines = text.split('\n');
71
+ const seen = new Map();
72
+ /** @type {Map<string, number>} */
73
+ const firstAt = new Map();
74
+ /** @type {DuplicateHeading[]} */
75
+ const duplicates = [];
76
+ /** @type {Requirement[]} */
77
+ const requirements = [];
78
+ /** @type {Set<string>} */
79
+ const slugs = new Set();
80
+ /** @type {Requirement | null} */
81
+ let req = null;
82
+ /** @type {Scenario | null} */
83
+ let scen = null;
84
+ let section = '';
85
+ const purpose = [];
86
+ const blockOf = (/** @type {number} */ from, /** @type {number} */ to) =>
87
+ lines
88
+ .slice(from - 1, to)
89
+ .join('\n')
90
+ .trimEnd();
91
+
92
+ const closeScenario = (/** @type {number} */ end) => {
93
+ if (!scen) return;
94
+ scen.end = end;
95
+ scen.block = blockOf(scen.line, end);
96
+ scen = null;
97
+ };
98
+
99
+ const close = (/** @type {number} */ end) => {
100
+ closeScenario(end);
101
+ if (!req) return;
102
+ const r = req;
103
+ r.end = end;
104
+ r.block = blockOf(r.line, end);
105
+ const statementEnd = r.scenarios[0] ? r.scenarios[0].line - 1 : end;
106
+ const markerLines = new Set(r.markers.filter((m) => !m.inline).map((m) => m.line));
107
+ r.statement = lines
108
+ .slice(r.line, statementEnd)
109
+ .filter((_, k) => !markerLines.has(r.line + 1 + k))
110
+ .join('\n')
111
+ .trim();
112
+ r.strong = strongCount(r.statement);
113
+ r.weak = weakCount(r.statement);
114
+ const own = r.markers.filter((m) => !m.inline);
115
+ r.advisory = own.some((m) => m.label === ADVISORY && !m.scenario);
116
+ r.gaps = own
117
+ .filter((m) => m.label === KNOWN_GAP && m.tracker)
118
+ .map((m) => {
119
+ const named = namedIn(m.text, r.scenarios);
120
+ const exempts = [...new Set([...(m.scenario ? [m.scenario] : []), ...(named ?? [])])];
121
+ return {
122
+ tracker: /** @type {string} */ (m.tracker),
123
+ text: m.text,
124
+ line: m.line,
125
+ scenario: m.scenario,
126
+ exempts,
127
+ named: named !== null,
128
+ };
129
+ });
130
+ requirements.push(r);
131
+ req = null;
132
+ };
133
+
134
+ lines.forEach((raw, i) => {
135
+ const n = i + 1;
136
+ const h = /^(#{1,6})\s+(.+?)\s*$/.exec(raw);
137
+ if (h) {
138
+ const level = h[1].length;
139
+ const title = h[2];
140
+ const base = slugify(title);
141
+ const first = firstAt.get(base);
142
+ if (first) duplicates.push({ line: n, slug: base, first });
143
+ else firstAt.set(base, n);
144
+ const slug = slugify(title, seen);
145
+ slugs.add(slug);
146
+ const r = level === 3 && /^Requirement:\s*(.+)$/.exec(title);
147
+ const s = level === 4 && /^Scenario:\s*(.+)$/.exec(title);
148
+ if (level <= 3) {
149
+ close(n - 1);
150
+ section = level === 2 ? title : section;
151
+ }
152
+ if (r) {
153
+ req = {
154
+ capability,
155
+ file,
156
+ name: r[1],
157
+ slug,
158
+ id: `${capability}#${slug}`,
159
+ line: n,
160
+ end: n,
161
+ block: '',
162
+ statement: '',
163
+ statementLine: n + 1,
164
+ markers: [],
165
+ scenarios: [],
166
+ strong: 0,
167
+ weak: 0,
168
+ advisory: false,
169
+ gaps: [],
170
+ };
171
+ } else if (s && req) {
172
+ closeScenario(n - 1);
173
+ scen = { name: s[1], slug, line: n, end: n, block: '', steps: [], markers: [] };
174
+ req.scenarios.push(scen);
175
+ } else if (level === 4) closeScenario(n - 1);
176
+ return;
177
+ }
178
+ if (section === 'Purpose' && !req) purpose.push(raw);
179
+ if (!req) return;
180
+ const atStart = MARKER.exec(raw);
181
+ const m = atStart && LABELS.has(atStart[1].trim().toLowerCase()) ? atStart : null;
182
+ const inline = !atStart && INLINE_MARKER.exec(stripCode(raw));
183
+ if (m || inline) {
184
+ const found = /** @type {RegExpExecArray} */ (m || inline);
185
+ const label = /** @type {string} */ (LABELS.get(found[1].trim().toLowerCase()));
186
+ /** @type {Marker} */
187
+ const marker = {
188
+ label,
189
+ tracker: m ? m[2]?.trim() || null : null,
190
+ line: n,
191
+ text: raw.trim(),
192
+ scenario: scen ? scen.slug : null,
193
+ inline: !m,
194
+ };
195
+ req.markers.push(marker);
196
+ scen?.markers.push(marker);
197
+ }
198
+ const st = scen && STEP.exec(raw);
199
+ if (st && scen) scen.steps.push({ kw: st[1].toUpperCase(), text: st[2].trim(), line: n });
200
+ });
201
+ close(lines.length);
202
+ return { capability, file, purpose: purpose.join('\n').trim(), slugs, requirements, duplicates };
203
+ }
204
+
205
+ /** Every spec.md under a directory on disk. @param {string} dir */
206
+ function walkSpecs(dir) {
207
+ /** @type {string[]} */
208
+ const out = [];
209
+ if (!fs.existsSync(dir)) return out;
210
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
211
+ const p = path.join(dir, entry.name);
212
+ if (entry.isDirectory()) out.push(...walkSpecs(p));
213
+ else if (entry.name === 'spec.md') out.push(p);
214
+ }
215
+ return out.sort();
216
+ }
217
+
218
+ /** `openspec/specs/apps/mastra/spec.md` → `apps/mastra`. @param {string} specsDir @param {string} file */
219
+ export const capabilityOf = (specsDir, file) => path.relative(specsDir, path.dirname(file)).split(path.sep).join('/');
220
+
221
+ /**
222
+ * The corpus as the working tree holds it.
223
+ * @param {string} root absolute repository root
224
+ * @param {{ name?: string, specsDir?: string }} [opts]
225
+ * @returns {Corpus}
226
+ */
227
+ export function loadCorpus(root, { name = path.basename(root), specsDir = DEFAULT_SPECS_DIR } = {}) {
228
+ const abs = path.join(root, specsDir);
229
+ const capabilities = walkSpecs(abs).map((p) => {
230
+ const file = path.relative(root, p).split(path.sep).join('/');
231
+ return parseSpec(fs.readFileSync(p, 'utf8'), file, capabilityOf(specsDir, file));
232
+ });
233
+ return { name, path: root, specsDir, capabilities };
234
+ }
235
+
236
+ /**
237
+ * The corpus as a git ref holds it.
238
+ * @param {string} root
239
+ * @param {string} ref
240
+ * @param {{ name?: string, specsDir?: string }} [opts]
241
+ * @returns {Corpus}
242
+ */
243
+ export function loadCorpusAt(root, ref, { name = path.basename(root), specsDir = DEFAULT_SPECS_DIR } = {}) {
244
+ const files = filesAt(root, ref, specsDir)
245
+ .filter((f) => f.endsWith('/spec.md'))
246
+ .sort();
247
+ const texts = showMany(root, ref, files);
248
+ const capabilities = files.map((file) => parseSpec(texts.get(file) ?? '', file, capabilityOf(specsDir, file)));
249
+ return { name, path: root, specsDir, capabilities };
250
+ }
251
+
252
+ /** Every requirement of a corpus. @param {Corpus} corpus */
253
+ export const allRequirements = (corpus) => corpus.capabilities.flatMap((c) => c.requirements);
254
+
255
+ /** Which corpus file a repository-relative path is, if any. @param {Corpus} corpus @param {string} file */
256
+ export const capabilityByFile = (corpus, file) => corpus.capabilities.find((c) => c.file === file);
257
+
258
+ /** Whether a scenario is exempt from the ratchet by a Known gap. @param {Requirement} r @param {Scenario} s */
259
+ export const gapExempts = (r, s) => r.gaps.some((g) => g.exempts.includes(s.slug));
@@ -0,0 +1,124 @@
1
+ // @ts-check
2
+ /**
3
+ * The coverage report: for every requirement and scenario, what binds it, which pointers name it, and its status —
4
+ * from bindings and markers only; a code or document citation never changes a status. Markdown, safe to publish as
5
+ * MDX. It fails nothing.
6
+ */
7
+ import { boundAnchors } from './citations.mjs';
8
+ import { KNOWN_GAP, RETIRED } from './corpus.mjs';
9
+
10
+ /**
11
+ * @typedef {import('./corpus.mjs').Corpus} Corpus
12
+ * @typedef {import('./citations.mjs').Citation} Citation
13
+ */
14
+
15
+ /** @type {Record<string, string>} */
16
+ const MDX_ESCAPES = { '<': '&lt;', '>': '&gt;', '{': '&#123;', '}': '&#125;', '|': '\\|' };
17
+ /** Text safe in an MDX table cell: angle brackets and braces would read as JSX, a pipe as a column. @param {string} s */
18
+ export const mdx = (s) => s.replace(/[<>{}|]/g, (c) => MDX_ESCAPES[c]);
19
+
20
+ /** @param {Citation[]} sites */
21
+ const show = (sites) => (sites.length ? sites.map((s) => `\`${s.file}:${s.line}\``).join('<br />') : '—');
22
+
23
+ /**
24
+ * @param {Corpus} corpus
25
+ * @param {Citation[]} citations
26
+ * @returns {{ markdown: string, totals: Record<string, number> }}
27
+ */
28
+ export function coverageReport(corpus, citations) {
29
+ const bound = boundAnchors(citations);
30
+ /** @type {Map<string, Citation[]>} */
31
+ const byAnchor = new Map();
32
+ for (const c of citations) {
33
+ if (!c.anchor || !c.resolves) continue;
34
+ const key = `${c.target}#${c.anchor}`;
35
+ byAnchor.set(key, [...(byAnchor.get(key) ?? []), c]);
36
+ }
37
+ const sites = (/** @type {string} */ key) => byAnchor.get(key) ?? [];
38
+ const totals = {
39
+ requirements: 0,
40
+ capabilities: corpus.capabilities.length,
41
+ advisory: 0,
42
+ gaps: 0,
43
+ unboundRequirements: 0,
44
+ unboundScenarios: 0,
45
+ retired: 0,
46
+ };
47
+ const body = [];
48
+ const gapRows = [];
49
+ const retiredRows = [];
50
+ for (const cap of [...corpus.capabilities].sort((a, b) => a.capability.localeCompare(b.capability))) {
51
+ body.push(
52
+ `## ${cap.capability}`,
53
+ '',
54
+ '| Requirement / Scenario | Spec | Bound by | Pointers | Status |',
55
+ '| --- | --- | --- | --- | --- |',
56
+ );
57
+ for (const r of cap.requirements) {
58
+ totals.requirements++;
59
+ const reqKey = `${r.file}#${r.slug}`;
60
+ const scenarioBound = (/** @type {import('./corpus.mjs').Scenario} */ s) =>
61
+ bound.has(`${r.file}#${s.slug}`) || (r.scenarios.length === 1 && bound.has(reqKey));
62
+ const anyBound = bound.has(reqKey) || r.scenarios.some(scenarioBound);
63
+ const requirementGaps = r.gaps.filter((g) => !g.scenario);
64
+ if (r.advisory) totals.advisory++;
65
+ totals.gaps += r.gaps.length;
66
+ if (!r.advisory && !anyBound) totals.unboundRequirements++;
67
+ const status = r.advisory
68
+ ? 'advisory'
69
+ : requirementGaps.length
70
+ ? `known gap (${requirementGaps.map((g) => mdx(g.tracker)).join(', ')})`
71
+ : anyBound
72
+ ? 'tested'
73
+ : 'no test';
74
+ const own = sites(reqKey);
75
+ body.push(
76
+ `| [${mdx(r.name)}](${r.file}#${r.slug}) | \`:${r.line}\` | ${show(own.filter((c) => c.binding))} | ${show(own.filter((c) => !c.binding))} | ${status} |`,
77
+ );
78
+ for (const s of r.scenarios) {
79
+ const key = `${r.file}#${s.slug}`;
80
+ const mine = [...sites(key), ...(r.scenarios.length === 1 ? own.filter((c) => c.binding) : [])];
81
+ const isBound = scenarioBound(s);
82
+ const gap = r.gaps.find((g) => g.exempts.includes(s.slug));
83
+ if (!r.advisory && !isBound) totals.unboundScenarios++;
84
+ const sStatus = r.advisory
85
+ ? '—'
86
+ : isBound
87
+ ? 'bound'
88
+ : gap
89
+ ? `known gap (${mdx(gap.tracker)})`
90
+ : 'no test';
91
+ body.push(
92
+ `| › [${mdx(s.name)}](${key}) | \`:${s.line}\` | ${show(mine.filter((c) => c.binding))} | ${show(mine.filter((c) => !c.binding))} | ${sStatus} |`,
93
+ );
94
+ }
95
+ for (const g of r.gaps)
96
+ gapRows.push(`| ${mdx(g.tracker)} | [${mdx(r.id)}](${r.file}#${r.slug}) | ${mdx(g.text)} |`);
97
+ for (const m of r.markers)
98
+ if (m.label === RETIRED || (m.label === KNOWN_GAP && !m.tracker)) {
99
+ totals.retired++;
100
+ retiredRows.push(`- \`${r.file}:${m.line}\` ${mdx(m.text)}`);
101
+ }
102
+ }
103
+ body.push('');
104
+ }
105
+ const header = [
106
+ '# Specification coverage',
107
+ '',
108
+ `${totals.requirements} requirements across ${totals.capabilities} capabilities. **${totals.advisory}** advisory; **${totals.gaps}** known gaps; **${totals.unboundRequirements}** REQUIRED requirements bound by no test; **${totals.unboundScenarios}** REQUIRED scenarios bound by no test; **${totals.retired}** retired markers.`,
109
+ '',
110
+ 'A status comes from bindings and markers only: a test block, type assertion, lint entry or declared check that cites a scenario binds it; a code or document citation is a pointer and changes nothing. Nothing here fails a build.',
111
+ '',
112
+ ];
113
+ const trailer = [
114
+ '## Known gaps',
115
+ '',
116
+ ...(gapRows.length ? ['| Tracker | Requirement | Gap |', '| --- | --- | --- |', ...gapRows] : ['_None._']),
117
+ '',
118
+ '## Retired markers',
119
+ '',
120
+ ...(retiredRows.length ? retiredRows : ['_None._']),
121
+ '',
122
+ ];
123
+ return { markdown: [...header, ...body, ...trailer].join('\n'), totals };
124
+ }