@kirill.konshin/lint 0.6.0 → 0.6.2

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 (51) hide show
  1. package/README.md +8 -8
  2. package/dist/lib.js +2 -1
  3. package/package.json +4 -6
  4. package/skills/spec-steward/SKILL.md +2 -2
  5. package/skills/spec-steward/references/contract.md +7 -7
  6. package/skills/spec-tools/SKILL.md +3 -1
  7. package/skills/spec-tools/references/contract.md +5 -5
  8. package/skills/spec-tools/references/gitlab.md +26 -35
  9. package/skills/spec-tools/scripts/cli.js +8155 -0
  10. package/skills/spec-verify/SKILL.md +6 -6
  11. package/skills/spec-steward/scripts/lib/align.mjs +0 -127
  12. package/skills/spec-steward/scripts/lib/checks.mjs +0 -589
  13. package/skills/spec-steward/scripts/lib/citations.mjs +0 -156
  14. package/skills/spec-steward/scripts/lib/corpus.mjs +0 -256
  15. package/skills/spec-steward/scripts/lib/coverage.mjs +0 -123
  16. package/skills/spec-steward/scripts/lib/evidence.mjs +0 -189
  17. package/skills/spec-steward/scripts/lib/git.mjs +0 -138
  18. package/skills/spec-steward/scripts/lib/review.mjs +0 -347
  19. package/skills/spec-steward/scripts/lib/scan.mjs +0 -364
  20. package/skills/spec-steward/scripts/lib/util.mjs +0 -161
  21. package/skills/spec-steward/scripts/lib/wire.mjs +0 -333
  22. package/skills/spec-steward/scripts/steward.mjs +0 -289
  23. package/spec-tools/dist/audit-DkZZulq6.mjs +0 -130
  24. package/spec-tools/dist/auditChanged-CNGjlake.mjs +0 -1
  25. package/spec-tools/dist/auditChanged-CZCvMgyZ.mjs +0 -618
  26. package/spec-tools/dist/auditReport-xgq4wK2i.mjs +0 -458
  27. package/spec-tools/dist/auditScope-CBuBtfPG.mjs +0 -104
  28. package/spec-tools/dist/changeGates-DdeQKfle.mjs +0 -333
  29. package/spec-tools/dist/changeGates-uy4Ti8rK.mjs +0 -1
  30. package/spec-tools/dist/ci-BUewHJS3.mjs +0 -143
  31. package/spec-tools/dist/ci-CFBzn8Of.mjs +0 -1
  32. package/spec-tools/dist/cli.mjs +0 -93
  33. package/spec-tools/dist/comment-szasMMg2.mjs +0 -57
  34. package/spec-tools/dist/files-Bppsb34B.mjs +0 -1
  35. package/spec-tools/dist/files-QlzY687_.mjs +0 -38
  36. package/spec-tools/dist/html-BMTkpbUN.mjs +0 -1766
  37. package/spec-tools/dist/jsonrepair-Dlm5dEen.mjs +0 -742
  38. package/spec-tools/dist/repo-CjIoUPYl.mjs +0 -16
  39. package/spec-tools/dist/repo-DUcnJw3c.mjs +0 -1
  40. package/spec-tools/dist/run-BElA9du3.mjs +0 -67
  41. package/spec-tools/dist/specDiff-8G56jMYn.mjs +0 -123
  42. package/spec-tools/dist/steward-DeieyOcj.mjs +0 -34
  43. package/spec-tools/dist/stewardAudit-BRMM0lrD.mjs +0 -1
  44. package/spec-tools/dist/stewardAudit-v0vOMfLN.mjs +0 -271
  45. package/spec-tools/dist/tier-Cn0P7juM.mjs +0 -1
  46. package/spec-tools/dist/tier-c3s_mA_I.mjs +0 -65
  47. package/spec-tools/dist/util-wnxhsnWO.mjs +0 -49
  48. package/spec-tools/dist/verdict-BFfN9PO8.mjs +0 -58
  49. package/spec-tools/dist/workers-BcIgckeq.mjs +0 -417
  50. package/spec-tools/dist/workflowEvidence-DyBj8EdG.mjs +0 -1
  51. package/spec-tools/dist/workflowEvidence-oui6ghPI.mjs +0 -78
@@ -1,156 +0,0 @@
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}`));
@@ -1,256 +0,0 @@
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 by title).
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, exempts: string[], named: boolean }} Gap
18
- * @typedef {{ name: string, slug: string, line: number, end: number, block: string, steps: Step[],
19
- * markers: Marker[] }} Scenario
20
- * @typedef {{
21
- * capability: string, file: string, name: string, slug: string, id: string, line: number, end: number,
22
- * block: string, statement: string, statementLine: number, markers: Marker[], scenarios: Scenario[],
23
- * strong: number, weak: number, advisory: boolean, gaps: Gap[]
24
- * }} Requirement
25
- * @typedef {{ line: number, slug: string, first: number }} DuplicateHeading
26
- * @typedef {{ capability: string, file: string, purpose: string, slugs: Set<string>, requirements: Requirement[],
27
- * duplicates: DuplicateHeading[] }} Capability
28
- * @typedef {{ name: string, path: string, specsDir: string, capabilities: Capability[] }} Corpus
29
- */
30
-
31
- export const DEFAULT_SPECS_DIR = 'openspec/specs';
32
-
33
- /** The two canonical markers; `<tracker>` is required text (a ticket key, a tickets-page id or a change folder). */
34
- export const DEFAULT_MARKERS = ['**⚠️ Advisory:**', '**⚠️ Known gap (<tracker>):**'];
35
- export const ADVISORY = 'Advisory';
36
- export const KNOWN_GAP = 'Known gap';
37
- export const RETIRED = 'Unenforced';
38
-
39
- /** A marker on a line of its own: `**⚠️ Label (tracker):**`, tolerant of the spellings `marker-hygiene` repairs. */
40
- const MARKER = /^\s*\*\*(?:⚠️?\s*)?([A-Z][\w -]{1,40}?)\s*(?:\(([^()\n]*)\))?\s*:?\s*\*\*\s*:?/u;
41
- /** A marker spelling inside a line, where no tool reads it. */
42
- const INLINE_MARKER =
43
- /\S.*?\*\*(?:⚠️?\s*)?(Advisory|Known [Gg]ap|Unenforced)\s*(?:\([^()\n]*\))?\s*(?::\s*\*\*|\*\*\s*:)/u;
44
- const STEP = /^\s*[-*]\s+\*\*(GIVEN|WHEN|THEN|AND|BUT)\*\*\s*(.*)$/i;
45
- const LABELS = new Map([ADVISORY, KNOWN_GAP, RETIRED].map((l) => [l.toLowerCase(), l]));
46
- const QUOTES = [`'…'`, `"…"`, `‘…’`, `“…”`, `_…_`, `*…*`];
47
-
48
- /**
49
- * The scenarios a Known gap names by title after "exempts" (quoted '…', "…", ‘…’, “…”, _…_ or *…*); null when it
50
- * names none that way.
51
- * @param {string} text
52
- * @param {Scenario[]} scenarios
53
- */
54
- function namedIn(text, scenarios) {
55
- const clause = /\bexempts?\b([\s\S]*)$/i.exec(text)?.[1].toLowerCase();
56
- if (clause === undefined) return null;
57
- const quoted = (/** @type {string} */ name) => QUOTES.map((q) => q.replace('…', name.toLowerCase()));
58
- return scenarios.filter((s) => quoted(s.name).some((q) => clause.includes(q))).map((s) => s.slug);
59
- }
60
-
61
- /**
62
- * Parse one capability specification.
63
- * @param {string} text
64
- * @param {string} file repository-relative path of the spec.md
65
- * @param {string} capability
66
- * @returns {Capability}
67
- */
68
- export function parseSpec(text, file, capability) {
69
- const lines = text.split('\n');
70
- const seen = new Map();
71
- /** @type {Map<string, number>} */
72
- const firstAt = new Map();
73
- /** @type {DuplicateHeading[]} */
74
- const duplicates = [];
75
- /** @type {Requirement[]} */
76
- const requirements = [];
77
- /** @type {Set<string>} */
78
- const slugs = new Set();
79
- /** @type {Requirement | null} */
80
- let req = null;
81
- /** @type {Scenario | null} */
82
- let scen = null;
83
- let section = '';
84
- const purpose = [];
85
- const blockOf = (/** @type {number} */ from, /** @type {number} */ to) =>
86
- lines
87
- .slice(from - 1, to)
88
- .join('\n')
89
- .trimEnd();
90
-
91
- const closeScenario = (/** @type {number} */ end) => {
92
- if (!scen) return;
93
- scen.end = end;
94
- scen.block = blockOf(scen.line, end);
95
- scen = null;
96
- };
97
-
98
- const close = (/** @type {number} */ end) => {
99
- closeScenario(end);
100
- if (!req) return;
101
- const r = req;
102
- r.end = end;
103
- r.block = blockOf(r.line, end);
104
- const statementEnd = r.scenarios[0] ? r.scenarios[0].line - 1 : end;
105
- const markerLines = new Set(r.markers.filter((m) => !m.inline).map((m) => m.line));
106
- r.statement = lines
107
- .slice(r.line, statementEnd)
108
- .filter((_, k) => !markerLines.has(r.line + 1 + k))
109
- .join('\n')
110
- .trim();
111
- r.strong = strongCount(r.statement);
112
- r.weak = weakCount(r.statement);
113
- const own = r.markers.filter((m) => !m.inline);
114
- r.advisory = own.some((m) => m.label === ADVISORY && !m.scenario);
115
- r.gaps = own
116
- .filter((m) => m.label === KNOWN_GAP && m.tracker && !m.scenario)
117
- .map((m) => {
118
- const named = namedIn(m.text, r.scenarios);
119
- return {
120
- tracker: /** @type {string} */ (m.tracker),
121
- text: m.text,
122
- line: m.line,
123
- exempts: named ?? [],
124
- named: named !== null,
125
- };
126
- });
127
- requirements.push(r);
128
- req = null;
129
- };
130
-
131
- lines.forEach((raw, i) => {
132
- const n = i + 1;
133
- const h = /^(#{1,6})\s+(.+?)\s*$/.exec(raw);
134
- if (h) {
135
- const level = h[1].length;
136
- const title = h[2];
137
- const base = slugify(title);
138
- const first = firstAt.get(base);
139
- if (first) duplicates.push({ line: n, slug: base, first });
140
- else firstAt.set(base, n);
141
- const slug = slugify(title, seen);
142
- slugs.add(slug);
143
- const r = level === 3 && /^Requirement:\s*(.+)$/.exec(title);
144
- const s = level === 4 && /^Scenario:\s*(.+)$/.exec(title);
145
- if (level <= 3) {
146
- close(n - 1);
147
- section = level === 2 ? title : section;
148
- }
149
- if (r) {
150
- req = {
151
- capability,
152
- file,
153
- name: r[1],
154
- slug,
155
- id: `${capability}#${slug}`,
156
- line: n,
157
- end: n,
158
- block: '',
159
- statement: '',
160
- statementLine: n + 1,
161
- markers: [],
162
- scenarios: [],
163
- strong: 0,
164
- weak: 0,
165
- advisory: false,
166
- gaps: [],
167
- };
168
- } else if (s && req) {
169
- closeScenario(n - 1);
170
- scen = { name: s[1], slug, line: n, end: n, block: '', steps: [], markers: [] };
171
- req.scenarios.push(scen);
172
- } else if (level === 4) closeScenario(n - 1);
173
- return;
174
- }
175
- if (section === 'Purpose' && !req) purpose.push(raw);
176
- if (!req) return;
177
- const atStart = MARKER.exec(raw);
178
- const m = atStart && LABELS.has(atStart[1].trim().toLowerCase()) ? atStart : null;
179
- const inline = !atStart && INLINE_MARKER.exec(stripCode(raw));
180
- if (m || inline) {
181
- const found = /** @type {RegExpExecArray} */ (m || inline);
182
- const label = /** @type {string} */ (LABELS.get(found[1].trim().toLowerCase()));
183
- /** @type {Marker} */
184
- const marker = {
185
- label,
186
- tracker: m ? m[2]?.trim() || null : null,
187
- line: n,
188
- text: raw.trim(),
189
- scenario: scen ? scen.slug : null,
190
- inline: !m,
191
- };
192
- req.markers.push(marker);
193
- scen?.markers.push(marker);
194
- }
195
- const st = scen && STEP.exec(raw);
196
- if (st && scen) scen.steps.push({ kw: st[1].toUpperCase(), text: st[2].trim(), line: n });
197
- });
198
- close(lines.length);
199
- return { capability, file, purpose: purpose.join('\n').trim(), slugs, requirements, duplicates };
200
- }
201
-
202
- /** Every spec.md under a directory on disk. @param {string} dir */
203
- function walkSpecs(dir) {
204
- /** @type {string[]} */
205
- const out = [];
206
- if (!fs.existsSync(dir)) return out;
207
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
208
- const p = path.join(dir, entry.name);
209
- if (entry.isDirectory()) out.push(...walkSpecs(p));
210
- else if (entry.name === 'spec.md') out.push(p);
211
- }
212
- return out.sort();
213
- }
214
-
215
- /** `openspec/specs/billing/refunds/spec.md` → `billing/refunds`. @param {string} specsDir @param {string} file */
216
- export const capabilityOf = (specsDir, file) => path.relative(specsDir, path.dirname(file)).split(path.sep).join('/');
217
-
218
- /**
219
- * The corpus as the working tree holds it.
220
- * @param {string} root absolute repository root
221
- * @param {{ name?: string, specsDir?: string }} [opts]
222
- * @returns {Corpus}
223
- */
224
- export function loadCorpus(root, { name = path.basename(root), specsDir = DEFAULT_SPECS_DIR } = {}) {
225
- const abs = path.join(root, specsDir);
226
- const capabilities = walkSpecs(abs).map((p) => {
227
- const file = path.relative(root, p).split(path.sep).join('/');
228
- return parseSpec(fs.readFileSync(p, 'utf8'), file, capabilityOf(specsDir, file));
229
- });
230
- return { name, path: root, specsDir, capabilities };
231
- }
232
-
233
- /**
234
- * The corpus as a git ref holds it.
235
- * @param {string} root
236
- * @param {string} ref
237
- * @param {{ name?: string, specsDir?: string }} [opts]
238
- * @returns {Corpus}
239
- */
240
- export function loadCorpusAt(root, ref, { name = path.basename(root), specsDir = DEFAULT_SPECS_DIR } = {}) {
241
- const files = filesAt(root, ref, specsDir)
242
- .filter((f) => f.endsWith('/spec.md'))
243
- .sort();
244
- const texts = showMany(root, ref, files);
245
- const capabilities = files.map((file) => parseSpec(texts.get(file) ?? '', file, capabilityOf(specsDir, file)));
246
- return { name, path: root, specsDir, capabilities };
247
- }
248
-
249
- /** Every requirement of a corpus. @param {Corpus} corpus */
250
- export const allRequirements = (corpus) => corpus.capabilities.flatMap((c) => c.requirements);
251
-
252
- /** Which corpus file a repository-relative path is, if any. @param {Corpus} corpus @param {string} file */
253
- export const capabilityByFile = (corpus, file) => corpus.capabilities.find((c) => c.file === file);
254
-
255
- /** Whether a scenario is exempt from the ratchet by a Known gap. @param {Requirement} r @param {Scenario} s */
256
- export const gapExempts = (r, s) => r.gaps.some((g) => g.exempts.includes(s.slug));
@@ -1,123 +0,0 @@
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
- if (r.advisory) totals.advisory++;
64
- totals.gaps += r.gaps.length;
65
- if (!r.advisory && !anyBound) totals.unboundRequirements++;
66
- const status = r.advisory
67
- ? 'advisory'
68
- : r.gaps.length
69
- ? `known gap (${r.gaps.map((g) => mdx(g.tracker)).join(', ')})`
70
- : anyBound
71
- ? 'tested'
72
- : 'no test';
73
- const own = sites(reqKey);
74
- body.push(
75
- `| [${mdx(r.name)}](${r.file}#${r.slug}) | \`:${r.line}\` | ${show(own.filter((c) => c.binding))} | ${show(own.filter((c) => !c.binding))} | ${status} |`,
76
- );
77
- for (const s of r.scenarios) {
78
- const key = `${r.file}#${s.slug}`;
79
- const mine = [...sites(key), ...(r.scenarios.length === 1 ? own.filter((c) => c.binding) : [])];
80
- const isBound = scenarioBound(s);
81
- const gap = r.gaps.find((g) => g.exempts.includes(s.slug));
82
- if (!r.advisory && !isBound) totals.unboundScenarios++;
83
- const sStatus = r.advisory
84
- ? '—'
85
- : isBound
86
- ? 'bound'
87
- : gap
88
- ? `known gap (${mdx(gap.tracker)})`
89
- : 'no test';
90
- body.push(
91
- `| › [${mdx(s.name)}](${key}) | \`:${s.line}\` | ${show(mine.filter((c) => c.binding))} | ${show(mine.filter((c) => !c.binding))} | ${sStatus} |`,
92
- );
93
- }
94
- for (const g of r.gaps)
95
- gapRows.push(`| ${mdx(g.tracker)} | [${mdx(r.id)}](${r.file}#${r.slug}) | ${mdx(g.text)} |`);
96
- for (const m of r.markers)
97
- if (m.label === RETIRED || (m.label === KNOWN_GAP && !m.tracker)) {
98
- totals.retired++;
99
- retiredRows.push(`- \`${r.file}:${m.line}\` ${mdx(m.text)}`);
100
- }
101
- }
102
- body.push('');
103
- }
104
- const header = [
105
- '# Specification coverage',
106
- '',
107
- `${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.`,
108
- '',
109
- '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.',
110
- '',
111
- ];
112
- const trailer = [
113
- '## Known gaps',
114
- '',
115
- ...(gapRows.length ? ['| Tracker | Requirement | Gap |', '| --- | --- | --- |', ...gapRows] : ['_None._']),
116
- '',
117
- '## Retired markers',
118
- '',
119
- ...(retiredRows.length ? retiredRows : ['_None._']),
120
- '',
121
- ];
122
- return { markdown: [...header, ...body, ...trailer].join('\n'), totals };
123
- }