@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,589 +0,0 @@
1
- // @ts-check
2
- /**
3
- * Deterministic checks over the corpus, a diff of it, and the citations of it. Every kind is cheap and mechanical;
4
- * judgement stays with the reader. Severity: `error` fails the run, `warn` fails it under --strict, `info` is a prompt
5
- * that never fails. Under a base, prompts are limited to what the diff added or edited.
6
- */
7
- import fs from 'node:fs';
8
- import path from 'node:path';
9
-
10
- import { boundAnchors } from './citations.mjs';
11
- import { ADVISORY, allRequirements, DEFAULT_MARKERS, gapExempts, KNOWN_GAP, RETIRED } from './corpus.mjs';
12
- import {
13
- absolutesIn,
14
- codeTokens,
15
- containment,
16
- exceptionsIn,
17
- jaccard,
18
- normalize,
19
- sentences,
20
- wordCount,
21
- words,
22
- } from './util.mjs';
23
-
24
- export { DEFAULT_MARKERS };
25
-
26
- /**
27
- * @typedef {import('./corpus.mjs').Corpus} Corpus
28
- * @typedef {import('./corpus.mjs').Requirement} Requirement
29
- * @typedef {import('./corpus.mjs').Scenario} Scenario
30
- * @typedef {import('./citations.mjs').Citation} Citation
31
- * @typedef {'error' | 'warn' | 'info'} Severity
32
- * @typedef {{
33
- * kind: string, severity: Severity, file: string, line: number, id?: string, scenario?: string, message: string,
34
- * fix?: { file: string, from: string, to: string, all?: boolean }[]
35
- * }} Finding
36
- * @typedef {{ reqBlocks: Set<string>, scenarioBlocks: Set<string> }} BaseIndex
37
- * @typedef {{
38
- * maxWords?: [number, number], maxObligations?: [number, number], files?: Set<string>, base?: BaseIndex | null
39
- * }} CheckOptions
40
- */
41
-
42
- /** The size lines: [prompt, failing] for a block's words and a statement's obligations. */
43
- export const SIZE = {
44
- words: /** @type {[number, number]} */ ([300, 500]),
45
- obligations: /** @type {[number, number]} */ ([5, 8]),
46
- };
47
- /** The kinds that need a base, skipped when there is none. */
48
- export const DIFF_KINDS = ['weakened', 'new-requirement', 'renamed-anchor', 'scenario-unproven', 'non-ears', 'non-bdd'];
49
-
50
- const VAGUE =
51
- /\b(appropriate(?:ly)?|reasonabl[ey]|sensibl[ey]|cleanly|lean|simplest|properly|efficient(?:ly)?|minimal(?:ly)?|best|prefer(?:s|ably|red)?|as needed|where possible|if possible|generally|typically|ideally|robust(?:ly)?|gracefully|user-friendly|well-defined|readable|maintainable|elegant(?:ly)?|badly|good)\b/i;
52
- const FILE_PATH = /(?<![\w/:])(?:[\w@.-]+\/)+[\w.-]+\.(?:[cm]?[jt]sx?|json|ya?ml|sh|py|go|sql|toml|conf)\b/g;
53
- const CALL_SYMBOL = /^(?:[a-z][\w$]*\.)*[a-z][\w$]*\(\)$/;
54
- const CLASS_SYMBOL =
55
- /^[A-Z][a-zA-Z0-9]+(?:Service|Controller|Module|Provider|Factory|Middleware|Repository|Helper|Manager|Adapter|Handler|Builder|Utils?)$/;
56
- const READS =
57
- /\b(?:readFileSync|readFile|readdirSync|readJson(?:Sync)?|globSync|fs\.promises\.readFile|Bun\.file)\s*\(/;
58
- const READ_TARGET =
59
- /['"`][^'"`\n]*(?:\.(?:[cm]?[jt]sx?|mdx?|ya?ml|json)|package\.json|AGENTS\.md|SKILL\.md|\/src|src\/)['"`]/;
60
- const FIXTURE = /fixture|__fixtures__|testdata|test-data/i;
61
- const TEXT_ASSERT =
62
- /\.(?:toContain|toMatch|toMatchInlineSnapshot|toMatchSnapshot|toInclude)\(|\.includes\(|\.match\(|new RegExp\(|\/[^/\n]{2,}\/[gimsuy]*\.test\(/;
63
- const OBLIGATION = /\b(?:MUST|SHALL|REQUIRED|SHOULD|RECOMMENDED|MAY|OPTIONAL)\b/;
64
- const EARS = /^(?:When|While|Where)\b|^If\b[\s\S]*\bthen\b|\bSHALL\b/;
65
- const EARS_FORMS =
66
- 'When <trigger>, the <system> SHALL <response>; While <state>, …; If <condition>, then …; Where <feature>, …; or The <system> SHALL …';
67
-
68
- /** @param {Corpus} corpus */
69
- const reqIndex = (corpus) => new Map(allRequirements(corpus).map((r) => [r.id, r]));
70
- /** Body without its heading, normalized: identity apart from name. @param {string} block */
71
- const bodyKey = (block) => normalize(block.split('\n').slice(1).join('\n'));
72
-
73
- /**
74
- * What the base corpus holds, for telling added or edited text from text it already had (a verbatim move is neither).
75
- * @param {Corpus} base
76
- * @returns {BaseIndex}
77
- */
78
- export function baseIndex(base) {
79
- const reqs = allRequirements(base);
80
- return {
81
- reqBlocks: new Set(reqs.map((r) => normalize(r.block))),
82
- scenarioBlocks: new Set(reqs.flatMap((r) => r.scenarios.map((s) => normalize(s.block)))),
83
- };
84
- }
85
-
86
- /**
87
- * Compare a base corpus with the head: removals, weaker obligations, dropped absolutes, added exceptions, new advisory
88
- * markers — and renames (same body, new heading or file), which are not weakening but move every anchor citing them.
89
- * @param {Corpus} base
90
- * @param {Corpus} head
91
- * @returns {{ findings: Finding[], renames: { from: string, to: string }[] }}
92
- */
93
- export function diffCorpus(base, head) {
94
- /** @type {Finding[]} */
95
- const findings = [];
96
- const renames = [];
97
- const b = reqIndex(base);
98
- const h = reqIndex(head);
99
- const headByBody = new Map([...h.values()].map((r) => [bodyKey(r.block), r]));
100
- const renamedTo = new Set();
101
-
102
- for (const [id, old] of b) {
103
- const now = h.get(id);
104
- if (!now) {
105
- const moved = headByBody.get(bodyKey(old.block));
106
- if (moved && !b.has(moved.id)) {
107
- renamedTo.add(moved.id);
108
- renames.push({ from: `${old.file}#${old.slug}`, to: `${moved.file}#${moved.slug}` });
109
- continue;
110
- }
111
- findings.push({
112
- kind: 'weakened',
113
- severity: 'warn',
114
- file: old.file,
115
- line: old.line,
116
- id,
117
- message: `requirement removed: "${old.name}" — never delete a rule to make code pass; the owner decides`,
118
- });
119
- continue;
120
- }
121
- const nowScen = new Map(now.scenarios.map((s) => [s.slug, s]));
122
- const nowScenBody = new Map(now.scenarios.map((s) => [bodyKey(s.block), s]));
123
- for (const s of old.scenarios) {
124
- if (nowScen.has(s.slug)) continue;
125
- const moved = nowScenBody.get(bodyKey(s.block));
126
- if (moved) {
127
- renames.push({ from: `${old.file}#${s.slug}`, to: `${now.file}#${moved.slug}` });
128
- continue;
129
- }
130
- findings.push({
131
- kind: 'weakened',
132
- severity: 'warn',
133
- file: now.file,
134
- line: now.line,
135
- id,
136
- message: `scenario removed: "${s.name}"`,
137
- });
138
- }
139
- /** @type {string[]} */
140
- const why = [];
141
- if (now.strong < old.strong) why.push(`MUST/SHALL ${old.strong} → ${now.strong}`);
142
- const absOld = absolutesIn(old.statement).length;
143
- const absNow = absolutesIn(now.statement).length;
144
- if (absNow < absOld) why.push(`absolutes ${absOld} → ${absNow}`);
145
- const exOld = exceptionsIn(old.block).length;
146
- const exNow = exceptionsIn(now.block).length;
147
- if (exNow > exOld) why.push(`exceptions ${exOld} → ${exNow}`);
148
- if (now.advisory && !old.advisory) why.push('newly marked advisory');
149
- if (why.length)
150
- findings.push({
151
- kind: 'weakened',
152
- severity: 'warn',
153
- file: now.file,
154
- line: now.line,
155
- id,
156
- message: `"${now.name}": ${why.join(', ')} — weakening a rule needs the owner's word, never done to make code pass`,
157
- });
158
- }
159
- for (const [id, r] of h) {
160
- if (b.has(id) || renamedTo.has(id)) continue;
161
- findings.push({
162
- kind: 'new-requirement',
163
- severity: 'info',
164
- file: r.file,
165
- line: r.line,
166
- id,
167
- message: `new requirement "${r.name}": name the observable failure it prevents and the cheapest evidence that catches it (types > lint/static > behavioural test > integration > review); if there is none it is advisory or belongs elsewhere (see the steward model)`,
168
- });
169
- }
170
- return { findings, renames };
171
- }
172
-
173
- /**
174
- * The marker findings of one requirement: retired, tracker-less, misplaced or misspelled markers grant nothing until
175
- * they are fixed, and say so.
176
- * @param {Requirement} r
177
- * @returns {Finding[]}
178
- */
179
- function markerFindings(r) {
180
- /** @type {Finding[]} */
181
- const out = [];
182
- const warn = (/** @type {number} */ line, /** @type {string} */ message, /** @type {any} */ fix) =>
183
- out.push({
184
- kind: 'marker-hygiene',
185
- severity: 'warn',
186
- file: r.file,
187
- line,
188
- id: r.id,
189
- message,
190
- ...(fix && { fix }),
191
- });
192
- for (const m of r.markers) {
193
- if (m.inline) warn(m.line, `a ${m.label} marker inside a line is not read — put it on a line of its own`);
194
- else if (m.label === RETIRED)
195
- warn(
196
- m.line,
197
- `**⚠️ Unenforced:** is retired and grants nothing — reclassify it: ${DEFAULT_MARKERS[0]} (review is its evidence), ${DEFAULT_MARKERS[1]} (behaviour or its evidence is missing), or no marker (a test, lint or build proves it)`,
198
- );
199
- else if (m.label === KNOWN_GAP && !m.tracker)
200
- warn(m.line, `a Known gap names its tracker — ${DEFAULT_MARKERS[1]}; without one it grants nothing`);
201
- else if (m.label === ADVISORY && m.scenario)
202
- warn(
203
- m.line,
204
- "Advisory is the requirement's class — put it directly under the requirement heading; in a scenario it grants nothing",
205
- );
206
- else if (m.label === KNOWN_GAP && m.scenario)
207
- warn(
208
- m.line,
209
- 'a Known gap goes under the requirement statement and names the scenarios it exempts by title; inside a scenario it grants nothing',
210
- );
211
- else {
212
- const canon = m.label === ADVISORY ? DEFAULT_MARKERS[0] : `**⚠️ Known gap (${m.tracker}):**`;
213
- if (!m.text.startsWith(canon)) {
214
- const fixed = m.text.replace(/^\s*\*\*[^*]*\*\*(?:\s*:)?/u, canon);
215
- warn(m.line, `marker should read ${canon}`, [{ file: r.file, from: m.text, to: fixed }]);
216
- }
217
- }
218
- }
219
- for (const g of r.gaps)
220
- if (g.named && !g.exempts.length)
221
- warn(
222
- g.line,
223
- 'names no scenario of this requirement by its title — a Known gap exempts only the scenarios it names',
224
- );
225
- return out;
226
- }
227
-
228
- /**
229
- * Checks over one corpus and its citations.
230
- * @param {Corpus} corpus
231
- * @param {Citation[]} citations
232
- * @param {CheckOptions} opts
233
- * @returns {Finding[]}
234
- */
235
- export function checkCorpus(corpus, citations, opts = {}) {
236
- /** @type {Finding[]} */
237
- const out = [];
238
- const [wordsInfo, wordsFail] = opts.maxWords ?? SIZE.words;
239
- const [obligationsInfo, obligationsFail] = opts.maxObligations ?? SIZE.obligations;
240
- const bound = boundAnchors(citations);
241
- const inScope = (/** @type {string} */ f) => !opts.files || opts.files.has(f);
242
- const base = opts.base ?? null;
243
-
244
- for (const cap of corpus.capabilities) {
245
- if (!inScope(cap.file)) continue;
246
- for (const d of cap.duplicates)
247
- out.push({
248
- kind: 'duplicate-anchor',
249
- severity: 'error',
250
- file: cap.file,
251
- line: d.line,
252
- message: `renders #${d.slug} as line ${d.first} does — a citation reaches only the first; rename one`,
253
- });
254
- for (const r of cap.requirements) {
255
- const at = (/** @type {number} */ line, /** @type {Scenario | undefined} */ s = undefined) => ({
256
- file: r.file,
257
- line,
258
- id: r.id,
259
- ...(s && { scenario: s.slug }),
260
- });
261
- const stmtWords = words(r.statement);
262
- const binds = (/** @type {Scenario} */ s) =>
263
- bound.has(`${r.file}#${s.slug}`) || (r.scenarios.length === 1 && bound.has(`${r.file}#${r.slug}`));
264
-
265
- const paths = [...r.block.matchAll(FILE_PATH)].map((m) => m[0]).filter((p) => !p.includes('openspec/'));
266
- const symbols = codeTokens(r.block).filter((t) => CALL_SYMBOL.test(t) || CLASS_SYMBOL.test(t));
267
- if (paths.length || symbols.length)
268
- out.push({
269
- kind: 'impl-detail',
270
- severity: 'info',
271
- ...at(r.line),
272
- message: `names ${[...new Set([...paths, ...symbols])].slice(0, 6).join(', ')} — would it survive a rewrite that keeps the contract? If not, it is not spec text`,
273
- });
274
-
275
- const obligationSentences = sentences(r.statement).filter((s) => OBLIGATION.test(s));
276
- for (const s of obligationSentences) {
277
- if (!/\b(MUST|SHALL|REQUIRED)\b/.test(s)) continue;
278
- const v = VAGUE.exec(s);
279
- if (v)
280
- out.push({
281
- kind: 'vague-obligation',
282
- severity: 'info',
283
- ...at(r.statementLine),
284
- message: `"${v[0]}" inside an obligation — no test can fail on it; a candidate for advisory`,
285
- });
286
- }
287
-
288
- const abs = absolutesIn(r.statement);
289
- const anyBound =
290
- bound.has(`${r.file}#${r.slug}`) || r.scenarios.some((s) => bound.has(`${r.file}#${s.slug}`));
291
- if (!r.advisory && abs.length && !exceptionsIn(r.statement).length && !anyBound)
292
- out.push({
293
- kind: 'absolute-unproven',
294
- severity: 'info',
295
- ...at(r.line),
296
- message: `absolute (${[...new Set(abs)].join(', ')}) with no named exception and nothing binding it — name its exceptions, or say there are none, for the owner's review`,
297
- });
298
-
299
- for (const s of r.scenarios) {
300
- const sw = words(s.steps.map((x) => x.text).join(' '));
301
- if (sw.length >= 3 && containment(sw, stmtWords) >= 0.85)
302
- out.push({
303
- kind: 'restating-scenario',
304
- severity: 'info',
305
- ...at(s.line, s),
306
- message: `scenario "${s.name}" restates the requirement — it adds no precision`,
307
- });
308
- if (base && (!s.steps.some((x) => x.kw === 'WHEN') || !s.steps.some((x) => x.kw === 'THEN')))
309
- out.push({
310
- kind: 'non-bdd',
311
- severity: 'info',
312
- ...at(s.line, s),
313
- message: `scenario "${s.name}" lacks WHEN/THEN steps — Given/When/Then, Given only where a precondition matters`,
314
- });
315
- if (
316
- base &&
317
- !r.advisory &&
318
- !base.scenarioBlocks.has(normalize(s.block)) &&
319
- !binds(s) &&
320
- !gapExempts(r, s)
321
- )
322
- out.push({
323
- kind: 'scenario-unproven',
324
- severity: 'error',
325
- ...at(s.line, s),
326
- message: `scenario "${s.name}" is new or changed in a REQUIRED requirement and nothing binds it — cite #${s.slug} on the test block, type assertion or lint entry that proves it, or name it in a ${DEFAULT_MARKERS[1]} line`,
327
- });
328
- }
329
- for (let i = 0; i < r.scenarios.length; i++)
330
- for (let j = i + 1; j < r.scenarios.length; j++) {
331
- const a = words(r.scenarios[i].block.split('\n').slice(1).join(' '));
332
- const bb = words(r.scenarios[j].block.split('\n').slice(1).join(' '));
333
- if (a.length >= 4 && jaccard(a, bb) >= 0.9)
334
- out.push({
335
- kind: 'duplicate-scenario',
336
- severity: 'info',
337
- ...at(r.scenarios[j].line, r.scenarios[j]),
338
- message: `"${r.scenarios[j].name}" repeats "${r.scenarios[i].name}"`,
339
- });
340
- }
341
-
342
- const w = wordCount(r.block);
343
- const o = r.strong + r.weak;
344
- if (w > wordsInfo)
345
- out.push({
346
- kind: 'size',
347
- severity: w > wordsFail ? 'error' : 'info',
348
- ...at(r.line),
349
- message:
350
- w > wordsFail
351
- ? `${w} words (> ${wordsFail}) — over the failing line: split it into coherent areas that fit under it`
352
- : `${w} words (> ${wordsInfo})`,
353
- });
354
- if (o > obligationsInfo)
355
- out.push({
356
- kind: 'size',
357
- severity: o > obligationsFail ? 'error' : 'info',
358
- ...at(r.line),
359
- message:
360
- o > obligationsFail
361
- ? `${o} obligations in the statement (> ${obligationsFail}) — over the failing line: move the detail into scenarios`
362
- : `${o} obligations in the statement (> ${obligationsInfo})`,
363
- });
364
- if (base && !obligationSentences.length)
365
- out.push({
366
- kind: 'non-ears',
367
- severity: 'info',
368
- ...at(r.line),
369
- message: `the statement issues no obligation — EARS: ${EARS_FORMS}`,
370
- });
371
- else if (base && !EARS.test(obligationSentences[0]))
372
- out.push({
373
- kind: 'non-ears',
374
- severity: 'info',
375
- ...at(r.line),
376
- message: `its first obligation matches no EARS template — ${EARS_FORMS}`,
377
- });
378
-
379
- out.push(...markerFindings(r));
380
- }
381
- }
382
-
383
- out.push(...duplicateRequirements(corpus).filter((f) => inScope(f.file)));
384
- out.push(...citationFindings(corpus, citations, inScope));
385
- return out;
386
- }
387
-
388
- /**
389
- * The same requirement name in two capabilities, or two requirements with the same body up to whitespace.
390
- * @param {Corpus} corpus
391
- * @returns {Finding[]}
392
- */
393
- function duplicateRequirements(corpus) {
394
- /** @type {Finding[]} */
395
- const out = [];
396
- /** @type {Map<string, Requirement[]>} */
397
- const byName = new Map();
398
- /** @type {Map<string, Requirement[]>} */
399
- const byBody = new Map();
400
- for (const r of allRequirements(corpus)) {
401
- const name = r.name.toLowerCase();
402
- byName.set(name, [...(byName.get(name) ?? []), r]);
403
- const body = bodyKey(r.block);
404
- if (body) byBody.set(body, [...(byBody.get(body) ?? []), r]);
405
- }
406
- for (const group of byName.values()) {
407
- if (new Set(group.map((r) => r.capability)).size < 2) continue;
408
- for (const r of group.slice(1))
409
- out.push({
410
- kind: 'duplicate-requirement',
411
- severity: 'error',
412
- file: r.file,
413
- line: r.line,
414
- id: r.id,
415
- message: `"${r.name}" is also a requirement of ${group[0].capability} — one rule, one home`,
416
- });
417
- }
418
- for (const group of byBody.values())
419
- for (const r of group.slice(1))
420
- out.push({
421
- kind: 'duplicate-requirement',
422
- severity: 'error',
423
- file: r.file,
424
- line: r.line,
425
- id: r.id,
426
- message: `same text as ${group[0].id} (${group[0].file}:${group[0].line})`,
427
- });
428
- return out;
429
- }
430
-
431
- /**
432
- * Citations that do not resolve, tests that assert on text, and bindings that do not seem to prove what they cite.
433
- * @param {Corpus} corpus
434
- * @param {Citation[]} citations
435
- * @param {(file: string) => boolean} inScope
436
- * @returns {Finding[]}
437
- */
438
- function citationFindings(corpus, citations, inScope) {
439
- /** @type {Finding[]} */
440
- const out = [];
441
- const reqs = allRequirements(corpus);
442
- /** @type {Map<string, Requirement>} */
443
- const byScenario = new Map();
444
- for (const r of reqs) for (const s of r.scenarios) byScenario.set(`${r.file}#${s.slug}`, r);
445
- const reqByAnchor = new Map(reqs.map((r) => [`${r.file}#${r.slug}`, r]));
446
-
447
- /** @type {Map<string, Citation[]>} */
448
- const testsByFile = new Map();
449
- for (const c of citations) {
450
- if (!inScope(c.file)) continue;
451
- if (!c.resolves)
452
- out.push({
453
- kind: 'dangling-citation',
454
- severity: 'error',
455
- file: c.file,
456
- line: c.line,
457
- message: `${c.target}${c.anchor ? `#${c.anchor}` : ''}: ${c.reason}`,
458
- });
459
- if (c.kind === 'test') testsByFile.set(c.file, [...(testsByFile.get(c.file) ?? []), c]);
460
- }
461
-
462
- for (const [file, cites] of testsByFile) {
463
- const abs = path.join(corpus.path, file);
464
- if (!fs.existsSync(abs)) continue;
465
- const text = fs.readFileSync(abs, 'utf8');
466
- if (READS.test(text) && READ_TARGET.test(text) && TEXT_ASSERT.test(text)) {
467
- const targets = [...text.matchAll(new RegExp(READ_TARGET.source, 'g'))]
468
- .map((m) => m[0])
469
- .filter((t) => !FIXTURE.test(t));
470
- if (targets.length)
471
- out.push({
472
- kind: 'textual-test',
473
- severity: 'warn',
474
- file,
475
- line: cites[0].line,
476
- message: `reads ${[...new Set(targets)].slice(0, 4).join(', ')} and asserts on text — that proves text is present, not behaviour; prefer a behavioural test, or a lint/dependency rule for structure`,
477
- });
478
- }
479
- }
480
-
481
- const linesOf = new Map();
482
- for (const c of citations) {
483
- if (!inScope(c.file) || !c.binding || !c.resolves || !c.anchor) continue;
484
- const key = `${c.target}#${c.anchor}`;
485
- const req = reqByAnchor.get(key);
486
- if (req && req.scenarios.length > 1) {
487
- out.push({
488
- kind: 'unbound-test',
489
- severity: 'info',
490
- file: c.file,
491
- line: c.line,
492
- message: `cites the requirement "${req.name}", not the scenario it proves — a requirement anchor binds only a requirement's one scenario`,
493
- });
494
- continue;
495
- }
496
- if (c.binding !== 'test') continue;
497
- const owner = byScenario.get(key);
498
- const scen = owner?.scenarios.find((s) => `${owner.file}#${s.slug}` === key);
499
- if (!scen) continue;
500
- const terms = codeTokens(scen.block).filter((t) => t.length >= 3 && !/\s/.test(t));
501
- if (!terms.length) continue;
502
- if (!linesOf.has(c.file))
503
- linesOf.set(c.file, fs.readFileSync(path.join(corpus.path, c.file), 'utf8').split('\n'));
504
- const body = linesOf
505
- .get(c.file)
506
- .slice(c.window[0] - 1, c.window[1])
507
- .join('\n');
508
- if (!terms.some((t) => body.includes(t)))
509
- out.push({
510
- kind: 'unbound-test',
511
- severity: 'info',
512
- file: c.file,
513
- line: c.line,
514
- message: `cites "${scen.name}" but mentions none of its terms (${terms.slice(0, 4).join(', ')}) — does it exercise it?`,
515
- });
516
- }
517
- return out;
518
- }
519
-
520
- /**
521
- * Prompts limited to what the diff added or edited: a requirement or scenario whose text the base holds nowhere, and
522
- * citations in changed files. Errors and warnings stay corpus-wide.
523
- * @param {Finding[]} findings
524
- * @param {Corpus} head
525
- * @param {BaseIndex} base
526
- * @param {Set<string>} changed files the working tree changes against the base
527
- */
528
- export function scopePrompts(findings, head, base, changed) {
529
- const edited = new Set();
530
- for (const r of allRequirements(head)) {
531
- if (!base.reqBlocks.has(normalize(r.block))) edited.add(r.id);
532
- for (const s of r.scenarios) if (!base.scenarioBlocks.has(normalize(s.block))) edited.add(`${r.id}|${s.slug}`);
533
- }
534
- return findings.filter(
535
- (f) =>
536
- f.severity !== 'info' ||
537
- (f.id ? edited.has(f.scenario ? `${f.id}|${f.scenario}` : f.id) : changed.has(f.file)),
538
- );
539
- }
540
-
541
- /**
542
- * Fixes for anchors a diff renamed: every citation of the old anchor is rewritten to the new one.
543
- * @param {{ from: string, to: string }[]} renames
544
- * @param {Citation[]} citations
545
- * @returns {Finding[]}
546
- */
547
- export function renameFindings(renames, citations) {
548
- /** @type {Finding[]} */
549
- const out = [];
550
- for (const { from, to } of renames) {
551
- const hits = citations.filter((c) => c.anchor && `${c.target}#${c.anchor}` === from);
552
- for (const c of hits)
553
- out.push({
554
- kind: 'renamed-anchor',
555
- severity: 'error',
556
- file: c.file,
557
- line: c.line,
558
- message: `cites ${from}, renamed to ${to}`,
559
- fix: [{ file: c.file, from, to, all: true }],
560
- });
561
- }
562
- return out;
563
- }
564
-
565
- /**
566
- * Apply every finding's fix; each file is rewritten once. A rename replaces whole anchors only (`#x` never `#x-y`).
567
- * @param {string} root
568
- * @param {Finding[]} findings
569
- * @returns {string[]} files changed
570
- */
571
- export function applyFixes(root, findings) {
572
- /** @type {Map<string, string>} */
573
- const texts = new Map();
574
- for (const f of findings)
575
- for (const fix of f.fix ?? []) {
576
- const abs = path.join(root, fix.file);
577
- const text = texts.get(abs) ?? fs.readFileSync(abs, 'utf8');
578
- const whole = new RegExp(`${fix.from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w-])`, 'g');
579
- texts.set(abs, fix.all ? text.replace(whole, () => fix.to) : text.replace(fix.from, () => fix.to));
580
- }
581
- const changed = [];
582
- for (const [abs, text] of texts) {
583
- if (fs.readFileSync(abs, 'utf8') !== text) {
584
- fs.writeFileSync(abs, text);
585
- changed.push(path.relative(root, abs));
586
- }
587
- }
588
- return changed;
589
- }