@kirill.konshin/lint 0.6.0 → 0.6.1

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 +7 -7
  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 +1 -1
  8. package/skills/spec-tools/references/gitlab.md +20 -22
  9. package/skills/spec-tools/scripts/cli.js +8129 -0
  10. package/skills/spec-verify/SKILL.md +2 -2
  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,618 +0,0 @@
1
- import { a as PARTS_DIR, l as UNITS_FILE, r as EVIDENCE_FILE } from "./files-QlzY687_.mjs";
2
- import { n as root, t as git } from "./repo-CjIoUPYl.mjs";
3
- import { t as diffBase } from "./ci-BUewHJS3.mjs";
4
- import { f as syncedUnarchivedChanges, p as touchedOpenChanges } from "./changeGates-DdeQKfle.mjs";
5
- import * as fs from "node:fs";
6
- import * as path from "node:path";
7
- import ts from "typescript";
8
- //#region spec-tools/src/auditParts.ts
9
- /**
10
- * The evidence each audit worker judges, assembled here before the audit starts from spec-steward's evidence model
11
- * (`spec-evidence.json`, which `spec-steward evidence --json` writes): one file per capability under `audit-parts/`
12
- * carrying every requirement verbatim and, under each, the tests bound to it quoted at their real `file:line`, the
13
- * source lines where its own terms occur with comments stripped, and the other requirements that share its terms; the
14
- * code and documents that cite it are not evidence, and are left out. A capability larger than one reader holds is
15
- * cut between its requirements into several such files. A worker reads its part's files and
16
- * judges; it opens a source only where an excerpt is cut. That is what lets the audit cover its whole scope in minutes
17
- * rather than rediscover the corpus one search at a time.
18
- */
19
- /**
20
- * The evidence one cheap reader holds in full — an evidence file and a part are never larger, unless one requirement
21
- * alone is. Lowered from 96 KB on 2026-09-12: over six local corpus runs on the cheap tier, parts of ~150 KB left a
22
- * reader short (a mislabelled or genuine `sampled`) in 4 of 64 cases and parts of ~75 KB in 0 of 64.
23
- */
24
- const PART_BYTES = 73728;
25
- /** The evidence model at a path; a missing file is the operator's to fix — the scope never guesses its evidence. */
26
- function loadEvidence(file = path.join(root(), EVIDENCE_FILE)) {
27
- if (!fs.existsSync(file)) throw new Error(`${EVIDENCE_FILE} is missing — \`spec-tools scope\` writes it with \`spec-steward evidence --json\``);
28
- const model = JSON.parse(fs.readFileSync(file, "utf8"));
29
- if (model.version !== 1 || !Array.isArray(model.requirements)) throw new Error(`${EVIDENCE_FILE} is not spec-steward's evidence model, version 1`);
30
- return model;
31
- }
32
- /** A marker line — `**⚠️ Advisory:**`, `**⚠️ Known gap (…):**` — is not the rule's statement. */
33
- const isMarker = (line) => /^\*\*⚠️ /.test(line.trim());
34
- /** Every requirement of the evidence model, in the model's order. */
35
- function requirementsOf(model) {
36
- return model.requirements.map((r) => {
37
- const lines = r.block.split("\n");
38
- const heading = lines[0].replace(/^### Requirement: /, "");
39
- const statement = lines.slice(1).find((l) => l.trim() !== "" && !l.startsWith("#") && !isMarker(l)) ?? "";
40
- return {
41
- capability: r.capability,
42
- file: r.file,
43
- name: heading,
44
- slug: r.id.slice(r.id.indexOf("#") + 1),
45
- line: r.line,
46
- endLine: r.end,
47
- block: r.block,
48
- statement: statement.trim(),
49
- scenarioSlugs: r.scenarios.map((s) => s.slug),
50
- advisory: r.class === "advisory",
51
- gaps: r.gaps,
52
- bindings: r.bindings,
53
- pointers: r.pointers,
54
- terms: r.terms,
55
- related: r.related
56
- };
57
- });
58
- }
59
- const idOf = (r) => `${r.capability}#${r.slug}`;
60
- /**
61
- * Which terms say something about the files they occur in: named by at most `COMMON_TOKEN_LIMIT` requirements, and
62
- * found in at least one and at most `MAX_CANDIDATE_FILES` files. A term every second file carries (`path`, `get`)
63
- * places no requirement anywhere.
64
- */
65
- function distinctiveTerms(all) {
66
- const named = /* @__PURE__ */ new Map();
67
- const files = /* @__PURE__ */ new Map();
68
- for (const r of all) for (const t of r.terms) {
69
- named.set(t.term, (named.get(t.term) ?? 0) + 1);
70
- files.set(t.term, new Set(t.hits.map((h) => h.file)).size);
71
- }
72
- const inFiles = (t) => files.get(t) ?? 0;
73
- return new Set([...named].filter(([t, n]) => n <= 12 && inFiles(t) > 0 && inFiles(t) <= 8).map(([t]) => t));
74
- }
75
- function sourceReader() {
76
- const cache = /* @__PURE__ */ new Map();
77
- return (file) => {
78
- if (!cache.has(file)) try {
79
- cache.set(file, fs.readFileSync(path.join(root(), file), "utf8").split("\n"));
80
- } catch {
81
- cache.set(file, void 0);
82
- }
83
- return cache.get(file);
84
- };
85
- }
86
- /**
87
- * Where a requirement's terms occur, as the reader is shown it: the files ranked by how many distinctive terms they
88
- * share with it, then by how many terms, at most `MAX_CANDIDATE_FILES` files and `MAX_CANDIDATE_LINES_PER_FILE`
89
- * lines each — the lines of distinctive terms first. spec-steward found the hits in the comment-stripped sources; the
90
- * line shown is the source's own.
91
- */
92
- function occurrences(terms, distinctive, read) {
93
- const byFile = /* @__PURE__ */ new Map();
94
- for (const { term, hits } of terms) for (const h of hits) {
95
- const entry = byFile.get(h.file) ?? {
96
- terms: /* @__PURE__ */ new Set(),
97
- hits: []
98
- };
99
- entry.terms.add(term);
100
- entry.hits.push({
101
- line: h.line,
102
- term
103
- });
104
- byFile.set(h.file, entry);
105
- }
106
- const rare = (shared) => [...shared].filter((t) => distinctive.has(t)).length;
107
- return [...byFile].sort(([a, x], [b, y]) => rare(y.terms) - rare(x.terms) || y.terms.size - x.terms.size || a.localeCompare(b)).slice(0, 8).map(([file, { terms: shared, hits }]) => {
108
- const seen = /* @__PURE__ */ new Set();
109
- const chosen = [...hits].sort((a, b) => Number(distinctive.has(b.term)) - Number(distinctive.has(a.term)) || a.line - b.line).filter((h) => !seen.has(h.line) && seen.add(h.line)).slice(0, 3).sort((a, b) => a.line - b.line);
110
- return {
111
- file,
112
- terms: [...shared],
113
- hits: chosen.map((h) => ({
114
- file,
115
- line: h.line,
116
- term: h.term,
117
- text: (read(file)?.[h.line - 1] ?? "").trim().slice(0, 160)
118
- }))
119
- };
120
- });
121
- }
122
- /** A quotable unit: a statement, a class member, a callback, or an object literal's entry. */
123
- const isBoundary = (node) => ts.isStatement(node) && !ts.isBlock(node) || ts.isClassElement(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isPropertyAssignment(node);
124
- /** `describe(…)`, `it(…)`, `test(…)`: a call whose callback is the unit a reader wants whole. */
125
- const isCallbackStatement = (node) => ts.isExpressionStatement(node) && ts.isCallExpression(node.expression) && node.expression.arguments.some((a) => ts.isArrowFunction(a) || ts.isFunctionExpression(a));
126
- /**
127
- * What an inline citation quotes: the top-level statement, the test block, the class member or the
128
- * object entry around it — never a lone statement inside a body, which would quote one line.
129
- */
130
- const isUnit = (node) => ts.isStatement(node) && (ts.isSourceFile(node.parent) || isCallbackStatement(node)) || ts.isClassElement(node) || ts.isPropertyAssignment(node);
131
- const lineOf = (sf, pos) => sf.getLineAndCharacterOfPosition(pos).line + 1;
132
- /** The quotable units holding `pos`, outermost first. */
133
- function enclosing(sf, pos) {
134
- const path = [];
135
- const visit = (node) => {
136
- if (pos < node.getFullStart() || pos >= node.getEnd()) return;
137
- if (isBoundary(node)) path.push(node);
138
- ts.forEachChild(node, visit);
139
- };
140
- ts.forEachChild(sf, visit);
141
- return path;
142
- }
143
- /**
144
- * The first line of a node including the comments above it. Its full start is the end of the previous
145
- * token, often mid-line, so the comment block begins on the next non-blank line.
146
- */
147
- function firstLine(sf, lines, node) {
148
- const { line, character } = sf.getLineAndCharacterOfPosition(node.getFullStart());
149
- let start = line + 1 + (character > 0 ? 1 : 0);
150
- const last = lineOf(sf, node.getStart(sf, true));
151
- while (start < last && lines[start - 1].trim() === "") start++;
152
- return start;
153
- }
154
- const numbered = (lines, startLine) => lines.map((line, i) => `${String(startLine + i).padStart(4)}│ ${line}`).join("\n");
155
- const window = (lines, line) => {
156
- const start = Math.max(1, line - 30);
157
- const end = Math.min(lines.length, line + 30);
158
- return {
159
- startLine: start,
160
- text: numbered(lines.slice(start - 1, end), start),
161
- cut: true
162
- };
163
- };
164
- const TEST_CALLS = /* @__PURE__ */ new Set([
165
- "describe",
166
- "it",
167
- "test"
168
- ]);
169
- /** A file-level citation's excerpt: the header comment, then one line per top-level declaration and test title. */
170
- function outline(sf, lines, line) {
171
- const rows = [];
172
- const name = (node) => {
173
- if (ts.isVariableStatement(node)) return node.declarationList.declarations.map((d) => d.name.getText(sf)).join(", ");
174
- if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node)) return node.name?.getText(sf);
175
- if (ts.isTypeAliasDeclaration(node) || ts.isEnumDeclaration(node)) return node.name.getText(sf);
176
- };
177
- const visit = (node) => {
178
- if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && TEST_CALLS.has(node.expression.text)) {
179
- const title = node.arguments[0];
180
- if (title && ts.isStringLiteralLike(title)) rows.push(`${String(lineOf(sf, node.getStart(sf))).padStart(4)}│ ${node.expression.text}('${title.text}')`);
181
- }
182
- ts.forEachChild(node, visit);
183
- };
184
- for (const statement of sf.statements) {
185
- if (ts.isImportDeclaration(statement)) continue;
186
- const label = name(statement);
187
- if (label) rows.push(`${String(lineOf(sf, statement.getStart(sf))).padStart(4)}│ ${ts.SyntaxKind[statement.kind].replace("Declaration", "").replace("Statement", "")} ${label}`);
188
- visit(statement);
189
- }
190
- const header = lines.slice(0, Math.min(lines.length, line + 3));
191
- const end = header.findIndex((l, i) => i >= line - 1 && /\*\//.test(l));
192
- return {
193
- startLine: 1,
194
- text: `${numbered(header.slice(0, end === -1 ? line : end + 1), 1)}\n …│ outline of the file — open it to judge an assertion:\n${rows.join("\n")}`,
195
- cut: true
196
- };
197
- }
198
- /**
199
- * The code a citation at `line` annotates. In TypeScript a citation in a unit's own doc comment quotes
200
- * that unit — the function, the class member, the one test — from its comment to its end; a citation
201
- * inline in a body quotes the outermost enclosing unit that fits the budget. Anything else — a unit
202
- * past the budget, or a file that is not TypeScript — is a window around the line. Every line carries
203
- * its number.
204
- */
205
- function excerpt(file, code, line) {
206
- const lines = code.split("\n");
207
- if (!/\.(ts|tsx|mts|cts)$/.test(file)) {
208
- if (lines.length <= 150) return {
209
- startLine: 1,
210
- text: numbered(lines, 1),
211
- cut: false
212
- };
213
- return window(lines, line);
214
- }
215
- const sf = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, file.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
216
- const text = lines[line - 1] ?? "";
217
- const column = Math.max(0, text.indexOf("@link") === -1 ? text.search(/\S/) : text.indexOf("@link"));
218
- const pos = sf.getPositionOfLineAndCharacter(line - 1, column);
219
- const path = enclosing(sf, pos);
220
- const inner = path[path.length - 1];
221
- if (!inner) return window(lines, line);
222
- const span = (node) => ({
223
- start: firstLine(sf, lines, node),
224
- end: lineOf(sf, node.getEnd())
225
- });
226
- const fits = (node) => {
227
- const { start, end } = span(node);
228
- return end - start + 1 <= 80;
229
- };
230
- const documented = inner.getStart(sf, true) <= pos && pos < inner.getStart(sf, false);
231
- if (documented && (ts.isImportDeclaration(inner) || /\.(test|spec)\.tsx?$/.test(file) && ts.isSourceFile(inner.parent) && !isCallbackStatement(inner))) {
232
- if (lines.length <= 150) return {
233
- startLine: 1,
234
- text: numbered(lines, 1),
235
- cut: false
236
- };
237
- return outline(sf, lines, line);
238
- }
239
- const chosen = documented ? fits(inner) ? inner : void 0 : path.filter(isUnit).find(fits);
240
- if (!chosen) return window(lines, line);
241
- const { start, end } = span(chosen);
242
- if (line < start || line > end) return window(lines, line);
243
- return {
244
- startLine: start,
245
- text: numbered(lines.slice(start - 1, end), start),
246
- cut: false
247
- };
248
- }
249
- const fence = (file, e) => {
250
- return [
251
- "```" + (/\.(ts|tsx|mts|cts)$/.test(file) ? "ts" : /\.ya?ml$/.test(file) ? "yaml" : ""),
252
- e.text,
253
- "```"
254
- ].join("\n");
255
- };
256
- function contextOf(all, read = sourceReader()) {
257
- const excerpts = /* @__PURE__ */ new Map();
258
- const excerptAt = (file, line) => {
259
- const key = `${file}:${line}`;
260
- if (!excerpts.has(key)) {
261
- const lines = read(file);
262
- excerpts.set(key, lines ? excerpt(file, lines.join("\n"), line) : void 0);
263
- }
264
- return excerpts.get(key);
265
- };
266
- return {
267
- all,
268
- byId: new Map(all.map((r) => [idOf(r), r])),
269
- distinctive: distinctiveTerms(all),
270
- read,
271
- excerptAt
272
- };
273
- }
274
- const gapNote = (r) => r.gaps.length ? ` — records a known gap (${r.gaps.map((g) => g.tracker ?? "no tracker").join(", ")})` : "";
275
- /**
276
- * One requirement's evidence, as its reader is shown it: its block; the tests bound to it, each excerpt once with the
277
- * anchors it binds; where its terms occur; its related requirements.
278
- * `quoted` lets a capability quote a shared excerpt once.
279
- */
280
- function renderRequirement(r, ctx, relatedInFull = false, quoted) {
281
- const out = [
282
- "",
283
- "---",
284
- "",
285
- `\`${idOf(r)}\` — \`${r.file}:${r.line}\`${r.advisory ? " — ⚠️ Advisory: a finding against it is at most WARN" : ""}${gapNote(r)}`,
286
- "",
287
- r.block,
288
- "",
289
- "### Bound tests"
290
- ];
291
- const span = (e) => [e.startLine, e.startLine + e.text.split("\n").length - 1];
292
- const quotedHere = [];
293
- const found = r.bindings.flatMap((b) => {
294
- const e = ctx.excerptAt(b.file, b.line);
295
- return e ? [{
296
- b,
297
- e
298
- }] : [];
299
- });
300
- for (const { b, e } of found.sort((x, y) => span(y.e)[1] - span(y.e)[0] - (span(x.e)[1] - span(x.e)[0]))) {
301
- const bind = `#${b.anchor} (:${b.line})`;
302
- const holder = quotedHere.find((q) => q.file === b.file && span(q.e)[0] <= span(e)[0] && span(e)[1] <= span(q.e)[1]);
303
- if (holder) {
304
- if (!holder.binds.includes(bind)) holder.binds.push(bind);
305
- continue;
306
- }
307
- quotedHere.push({
308
- file: b.file,
309
- line: b.line,
310
- e,
311
- binds: [bind],
312
- title: b.title
313
- });
314
- }
315
- quotedHere.sort((a, b) => a.file.localeCompare(b.file) || a.e.startLine - b.e.startLine);
316
- if (quotedHere.length === 0) out.push("", "No test, type assertion, lint entry or check binds it.");
317
- for (const { file, line, e, binds, title } of quotedHere) {
318
- const key = `${file}:${e.startLine}:${e.text}`;
319
- const [from, to] = span(e);
320
- const heading = `\`${file}:${line}\`${title ? ` — \`${title.replace(/`/g, "'")}\`` : ""} — binds ${binds.join(", ")}${e.cut ? ` — window, lines ${from}–${to}` : ""}`;
321
- const first = quoted?.get(key);
322
- if (first) {
323
- out.push("", `${heading} — the same excerpt as quoted under \`${first}\` above`);
324
- continue;
325
- }
326
- quoted?.set(key, idOf(r));
327
- out.push("", heading, "", fence(file, e));
328
- }
329
- out.push("", "### Where its terms occur");
330
- if (r.terms.length === 0) out.push("", "The requirement names no term. Decide first whether it describes code behaviour at all — a process or documentation rule has nothing to implement; only if it does, search by hand.");
331
- else {
332
- out.push("", `Terms: ${r.terms.map((t) => `\`${t.term}\`${ctx.distinctive.has(t.term) ? "" : " (common)"}`).join(", ")}`);
333
- const found = occurrences(r.terms, ctx.distinctive, ctx.read);
334
- if (found.length === 0) out.push("", "None of them occurs in the sources, comments stripped.");
335
- for (const c of found) {
336
- out.push("", `- \`${c.file}\` shares ${c.terms.map((t) => `\`${t}\``).join(", ")}`);
337
- for (const h of c.hits) out.push(` - \`${h.file}:${h.line}\` — \`${h.text.replace(/`/g, "'")}\``);
338
- }
339
- }
340
- const rel = r.related.flatMap((x) => {
341
- const other = ctx.byId.get(x.id);
342
- return other ? [{
343
- other,
344
- shared: x.shared
345
- }] : [];
346
- });
347
- if (rel.length > 0) {
348
- out.push("", "### Related requirements — judge for conflict and duplication");
349
- for (const { other, shared } of rel.slice(0, 8)) {
350
- const terms = shared.length ? ` (${shared.map((t) => `\`${t}\``).join(", ")})` : " (similar wording)";
351
- if (relatedInFull) out.push("", `#### \`${idOf(other)}\`${terms}`, "", other.block);
352
- else out.push(`- \`${idOf(other)}\`${terms} — ${other.statement.slice(0, 240)}${other.statement.length > 240 ? "…" : ""}`);
353
- }
354
- }
355
- return out;
356
- }
357
- /** A capability's evidence file opens with this: what it is, and the capability's Purpose. */
358
- function capabilityHeader(capability, ctx, sliced) {
359
- const file = ctx.all.find((r) => r.capability === capability)?.file ?? `openspec/specs/${capability}/spec.md`;
360
- const specLines = ctx.read(file) ?? [];
361
- const purposeStart = specLines.findIndex((l) => l.startsWith("## Purpose"));
362
- const purposeEnd = specLines.findIndex((l, i) => i > purposeStart && l.startsWith("## "));
363
- const purpose = purposeStart === -1 ? [] : specLines.slice(purposeStart + 1, purposeEnd === -1 ? void 0 : purposeEnd);
364
- return [
365
- `# \`${capability}\` — evidence for the specification audit`,
366
- "",
367
- `Generated by \`spec-tools scope\` from \`${file}\` and spec-steward's evidence model; line numbers are the files' own. Every requirement is here verbatim with the tests bound to it, where its own terms occur in the sources with comments stripped, and its related requirements — so judge from this file and open a source only where an excerpt is marked as a window or a term occurrence must be confirmed.`,
368
- ...sliced ? ["", "This capability is larger than one reader holds, so its evidence is cut between its requirements: this file carries some of them, and its other files the rest."] : [],
369
- "",
370
- ...purpose.length ? ["## Purpose", ...purpose] : []
371
- ];
372
- }
373
- const textOf = (lines) => lines.join("\n") + "\n";
374
- /**
375
- * A capability's evidence, as the files a reader holds in full: the whole capability when it fits in `PART_BYTES`,
376
- * otherwise cut between its requirements in their spec order — a file closes before the requirement that would take
377
- * it past `PART_BYTES`, so none is larger unless one requirement alone is, and each repeats the header and Purpose and
378
- * quotes its own excerpts. A function of the evidence alone: every job that reads the scope sees the same cut.
379
- */
380
- function renderCapability(capability, ctx) {
381
- const own = ctx.all.filter((r) => r.capability === capability);
382
- const cut = (sliced) => {
383
- const slices = [];
384
- let lines = capabilityHeader(capability, ctx, sliced);
385
- let taken = [];
386
- let quoted = /* @__PURE__ */ new Map();
387
- for (const r of own) {
388
- const trial = new Map(quoted);
389
- const block = renderRequirement(r, ctx, false, trial);
390
- if (taken.length && Buffer.byteLength(textOf([...lines, ...block])) > 73728) {
391
- slices.push({
392
- requirements: taken,
393
- text: textOf(lines)
394
- });
395
- quoted = /* @__PURE__ */ new Map();
396
- lines = [...capabilityHeader(capability, ctx, sliced), ...renderRequirement(r, ctx, false, quoted)];
397
- taken = [r];
398
- } else {
399
- lines.push(...block);
400
- taken.push(r);
401
- quoted = trial;
402
- }
403
- }
404
- slices.push({
405
- requirements: taken,
406
- text: textOf(lines)
407
- });
408
- return slices;
409
- };
410
- const whole = cut(false);
411
- return whole.length === 1 ? whole : cut(true);
412
- }
413
- /**
414
- * The focused evidence for the requirements a change touched: each with its bound tests, where its terms occur, and
415
- * its related requirements quoted IN FULL, so one reader can judge the edit against the rest before it
416
- * is handed back — the file `spec-tools changed` writes and the audit's focused mode judges.
417
- */
418
- function renderChanged(touched, ctx, base = "HEAD") {
419
- const out = [
420
- "# Changed requirements — evidence for the focused check",
421
- "",
422
- touched.length ? `Generated by \`spec-tools changed\` from the diff against ${base}: ${touched.length} requirement(s) in scope — the ones the diff changed or a touched delta names, the ones whose bound tests or whose own terms the changed files contain, the ones the changed code cites, and the requirements related to these. Judge each against its bound tests, where its terms occur, and the requirements related to it, quoted below.` : `Generated by \`spec-tools changed\`: nothing in scope against ${base}.`
423
- ];
424
- for (const r of touched) out.push(...renderRequirement(r, ctx, true));
425
- return out.join("\n") + "\n";
426
- }
427
- /**
428
- * Writes each capability's evidence files and `units.json`; returns each file with its weight — `<capability>.md` for a
429
- * capability whole, `<capability>.<k>.md` for its k-th slice.
430
- */
431
- function writeParts(capabilities, all = requirementsOf(loadEvidence())) {
432
- const ctx = contextOf(all);
433
- const dir = path.join(root(), PARTS_DIR);
434
- if (fs.existsSync(dir)) {
435
- for (const entry of fs.readdirSync(dir)) if (entry !== "findings" && entry !== "steward") fs.rmSync(path.join(dir, entry), { recursive: true });
436
- }
437
- fs.mkdirSync(path.join(dir, "findings"), { recursive: true });
438
- const units = {};
439
- for (const r of all) if (capabilities.includes(r.capability)) units[idOf(r)] = r.advisory ? { advisory: true } : {};
440
- fs.writeFileSync(path.join(root(), UNITS_FILE), JSON.stringify(units, null, 1) + "\n");
441
- return capabilities.flatMap((capability) => {
442
- const slices = renderCapability(capability, ctx);
443
- return slices.map(({ requirements, text }, k) => {
444
- const file = `${PARTS_DIR}/${capability}${slices.length > 1 ? `.${k + 1}` : ""}.md`;
445
- fs.mkdirSync(path.dirname(path.join(root(), file)), { recursive: true });
446
- fs.writeFileSync(path.join(root(), file), text);
447
- return {
448
- capability,
449
- file,
450
- bytes: Buffer.byteLength(text),
451
- requirements: requirements.length,
452
- requirementIds: requirements.map(idOf)
453
- };
454
- });
455
- });
456
- }
457
- //#endregion
458
- //#region spec-tools/src/auditChanged.ts
459
- /**
460
- * The focused check an editor runs before handing a specification change back, and the affected set of a merge
461
- * request or a push in CI: which requirements the diff changed or a touched delta names, which ones the changed
462
- * files bind or name the terms of, which ones the changed code cites, and the requirements related to
463
- * these — with the evidence to validate each against the rest, quoted in full — so a sentence that
464
- * contradicts a sibling is caught by the author, not by the next audit. Deterministic; the judging is the
465
- * audit skill's focused mode over the one file this writes. The diff base is `diffBase`'s.
466
- */
467
- const CHANGED_FILE = `${PARTS_DIR}/changed.md`;
468
- /** The `+c,d` side of every hunk in a unified diff, per file — the new lines a change touched. */
469
- function hunksOf(diff) {
470
- const hunks = [];
471
- let file = "";
472
- for (const line of diff.split("\n")) {
473
- const f = /^\+\+\+ b\/(.+)$/.exec(line);
474
- if (f) {
475
- file = f[1];
476
- continue;
477
- }
478
- const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
479
- if (h && file) hunks.push({
480
- file,
481
- start: Number(h[1]),
482
- count: h[2] === void 0 ? 1 : Number(h[2])
483
- });
484
- }
485
- return hunks;
486
- }
487
- /** The requirements whose blocks a hunk overlaps; a deleted-only hunk (count 0) touches the block at its line. */
488
- function requirementsTouched(hunks, all) {
489
- const touched = [];
490
- for (const r of all) if (hunks.some((h) => h.file === r.file && h.start <= r.endLine && h.start + Math.max(h.count, 1) - 1 >= r.line) && !touched.includes(r)) touched.push(r);
491
- return touched;
492
- }
493
- /** A delta file's requirement blocks by operation; a RENAMED entry is named by its FROM heading and has no block. */
494
- function deltaBlocks(text) {
495
- const out = [];
496
- let op = "";
497
- const lines = text.split("\n");
498
- lines.forEach((line, i) => {
499
- const s = /^## (ADDED|MODIFIED|REMOVED|RENAMED) Requirements/.exec(line);
500
- if (s) {
501
- op = s[1];
502
- return;
503
- }
504
- if (op === "RENAMED") {
505
- const from = /^- FROM: `### Requirement: (.+)`\s*$/.exec(line);
506
- if (from) out.push({
507
- op,
508
- name: from[1].trim(),
509
- block: ""
510
- });
511
- return;
512
- }
513
- const h = /^### Requirement: (.+)$/.exec(line);
514
- if (op && h) {
515
- let end = lines.findIndex((l, j) => j > i && /^##/.test(l) && !l.startsWith("####"));
516
- if (end < 0) end = lines.length;
517
- out.push({
518
- op,
519
- name: h[1].trim(),
520
- block: lines.slice(i, end).join("\n")
521
- });
522
- }
523
- });
524
- return out;
525
- }
526
- /** The backticked spans of a text — the form a requirement names its terms in. */
527
- const codeSpans = (text) => new Set([...text.matchAll(/`([^`\n]+)`/g)].map((m) => m[1].trim()));
528
- /**
529
- * Before sync a request's claim on the corpus is its deltas: a MODIFIED, REMOVED or RENAMED-FROM heading
530
- * maps to the standing requirement it names; an ADDED one has no standing counterpart yet and maps to
531
- * its lexical neighbours — the standing requirements of its capability sharing the most terms with it.
532
- */
533
- function deltaRequirements(deltaText, capability, all) {
534
- const own = all.filter((r) => r.capability === capability);
535
- const out = /* @__PURE__ */ new Set();
536
- for (const { op, name, block } of deltaBlocks(deltaText)) {
537
- if (op !== "ADDED") {
538
- const r = own.find((x) => x.name === name);
539
- if (r) out.add(r);
540
- continue;
541
- }
542
- const spans = codeSpans(block);
543
- own.map((r) => ({
544
- r,
545
- shared: r.terms.filter((t) => spans.has(t.term)).length
546
- })).filter(({ shared }) => shared > 0).sort((a, b) => b.shared - a.shared || a.r.line - b.r.line).slice(0, 2).forEach(({ r }) => out.add(r));
547
- }
548
- return [...out];
549
- }
550
- /**
551
- * The requirements a set of changed files reaches: those a test, type assertion, lint entry or check in a changed
552
- * file binds; those a changed file cites; and those whose distinctive terms occur in a changed file, so a change to
553
- * code no citation names still has its requirements judged.
554
- */
555
- function reachedBy(changed, all) {
556
- const distinctive = distinctiveTerms(all);
557
- return all.filter((r) => r.bindings.some((b) => changed.has(b.file)) || r.pointers.some((p) => changed.has(p.file)) || r.terms.some((t) => distinctive.has(t.term) && t.hits.some((h) => changed.has(h.file))));
558
- }
559
- /**
560
- * The affected set against a base: the standing requirements the diff changed, the ones a touched unsynced change's
561
- * deltas name, the ones the changed files bind, cite or name the terms of, and the requirements related to these.
562
- */
563
- function affectedScope(base, all = requirementsOf(loadEvidence())) {
564
- const byId = new Map(all.map((r) => [idOf(r), r]));
565
- const set = /* @__PURE__ */ new Map();
566
- const add = (r) => set.set(idOf(r), r);
567
- for (const r of requirementsTouched(hunksOf(git([
568
- "diff",
569
- "-M",
570
- "--unified=0",
571
- base,
572
- "--",
573
- "openspec/specs"
574
- ])), all)) add(r);
575
- const synced = new Set(syncedUnarchivedChanges().map((s) => s.split(" — ")[0]));
576
- for (const change of touchedOpenChanges(base).filter((c) => !synced.has(c))) {
577
- const specs = path.join(root(), "openspec/changes", change, "specs");
578
- if (!fs.existsSync(specs)) continue;
579
- const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
580
- const full = path.join(dir, entry.name);
581
- return entry.isDirectory() ? walk(full) : entry.name === "spec.md" ? [full] : [];
582
- });
583
- for (const delta of walk(specs)) {
584
- const capability = path.relative(specs, path.dirname(delta));
585
- for (const r of deltaRequirements(fs.readFileSync(delta, "utf8"), capability, all)) add(r);
586
- }
587
- }
588
- const changed = new Set([...git([
589
- "diff",
590
- "--name-only",
591
- base
592
- ]).split("\n"), ...git([
593
- "ls-files",
594
- "--others",
595
- "--exclude-standard"
596
- ]).split("\n")].filter(Boolean));
597
- for (const r of reachedBy(changed, all)) add(r);
598
- for (const r of [...set.values()]) for (const { id } of r.related) {
599
- const other = byId.get(id);
600
- if (other) add(other);
601
- }
602
- return {
603
- base,
604
- requirements: [...set.values()],
605
- capabilities: [...new Set([...set.values()].map((r) => r.capability))].sort()
606
- };
607
- }
608
- function main(env = process.env) {
609
- const base = diffBase(env);
610
- const all = requirementsOf(loadEvidence());
611
- const scope = affectedScope(base, all);
612
- const text = renderChanged(scope.requirements, contextOf(all), base);
613
- fs.mkdirSync(path.join(root(), PARTS_DIR), { recursive: true });
614
- fs.writeFileSync(path.join(root(), CHANGED_FILE), text);
615
- return scope.requirements.length ? `${scope.requirements.length} requirement(s) in scope against ${base} → ${CHANGED_FILE}:\n${scope.requirements.map((r) => `- ${idOf(r)}`).join("\n")}\n` : `Nothing in scope against ${base}; ${CHANGED_FILE} says so.\n`;
616
- }
617
- //#endregion
618
- export { hunksOf as a, requirementsTouched as c, requirementsOf as d, writeParts as f, deltaRequirements as i, PART_BYTES as l, affectedScope as n, main as o, deltaBlocks as r, reachedBy as s, CHANGED_FILE as t, loadEvidence as u };