@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,333 +0,0 @@
1
- // @ts-check
2
- /**
3
- * The guard's wiring into a repository — routing in AGENTS.md, the scoped rule, the edit hook, the OPSX operation
4
- * guidance — and the edit hook itself. Correctness never depends on the skill being discovered: the hook and the
5
- * scoped rule reach the agent whether or not it loads the skill.
6
- */
7
- import fs from 'node:fs';
8
- import path from 'node:path';
9
-
10
- import { baseIndex, checkCorpus, diffCorpus } from './checks.mjs';
11
- import { isTestFile, scanCitations } from './citations.mjs';
12
- import { capabilityOf, DEFAULT_SPECS_DIR, parseSpec } from './corpus.mjs';
13
- import { git, show, toplevel } from './git.mjs';
14
-
15
- /** The bin the package installs; the hook is a no-op until the repository's install provides it. */
16
- export const BIN = 'node_modules/.bin/spec-steward';
17
- export const HOOK_COMMAND = `f="$CLAUDE_PROJECT_DIR/${BIN}"; [ ! -x "$f" ] || "$f" hook`;
18
- export const AGENTS_LINE =
19
- 'Specifications: edits under `openspec/` are guarded by the scoped rule `.agents/rules/openspec.md` and the `spec-steward` edit hook; corpus-quality audits, review rounds and cross-repository alignment use the `spec-steward` skill, and code conformance is the `spec-verify` audit (`spec-tools`).';
20
- /** The OPSX guidance points at the repository's own spec gate; the gate runs spec-steward, so no second command. */
21
- export const GATE_POINTER = 'AGENTS.md → Checks';
22
- export const GUIDANCE = {
23
- apply: `Before handing back a spec change run the repository's spec gate (${GATE_POINTER}) and surface every \`weakened\` finding to the owner.`,
24
- archive: `Archive only after the repository's spec gate (${GATE_POINTER}) passes and every \`weakened\` finding has the owner's answer.`,
25
- };
26
- /** A guidance item from an earlier version that ran steward by path; `wire --fix` replaces it with the pointer. */
27
- const LEGACY_GUIDANCE = /steward\.mjs check|spec-steward check/;
28
- /**
29
- * Whether the operation's own section of `operations:` points at the gate.
30
- * @param {'apply' | 'archive'} op
31
- * @param {string} ops the config from its `operations:` key onwards
32
- */
33
- const hasPointer = (op, ops) => {
34
- const re = new RegExp(`^ {2}${op}:[^\\n]*\\n((?:(?: {3,}|[ \\t]*#)[^\\n]*\\n?|[ \\t]*\\n)*)`, 'm');
35
- const section = re.exec(ops)?.[1];
36
- return !!section && /AGENTS\.md\s*(?:→|->)\s*Checks/.test(section);
37
- };
38
-
39
- /** @param {string} root */
40
- const configPath = (root) =>
41
- ['openspec/config.yaml', 'openspec/config.yml'].map((p) => path.join(root, p)).find((p) => fs.existsSync(p));
42
-
43
- /**
44
- * Which steering points are in place.
45
- * @param {{ path: string, specsDir?: string }} root
46
- */
47
- export function wireStatus(root) {
48
- const has = (/** @type {string} */ p) => fs.existsSync(path.join(root.path, p));
49
- const read = (/** @type {string} */ p) => (has(p) ? fs.readFileSync(path.join(root.path, p), 'utf8') : '');
50
- const hook = (() => {
51
- try {
52
- const settings = JSON.parse(read('.claude/settings.json') || '{}');
53
- return (settings.hooks?.PostToolUse ?? []).some((/** @type {any} */ e) =>
54
- (e.hooks ?? []).some(
55
- (/** @type {any} */ h) =>
56
- typeof h.command === 'string' &&
57
- // the bin, or the script by path as earlier versions wired it
58
- /spec-steward|steward\.mjs/.test(h.command) &&
59
- h.command.includes('hook'),
60
- ),
61
- );
62
- } catch {
63
- return false;
64
- }
65
- })();
66
- const cfg = configPath(root.path);
67
- const config = cfg ? fs.readFileSync(cfg, 'utf8') : '';
68
- const ops = config.slice(Math.max(0, config.search(/^operations:/m)));
69
- return {
70
- applicable: has(root.specsDir ?? DEFAULT_SPECS_DIR),
71
- agents: /spec-steward/.test(read('AGENTS.md')),
72
- rule: ['.agents', '.claude'].some((d) => has(`${d}/rules/openspec.md`)),
73
- skill: ['.agents', '.claude'].some((d) => has(`${d}/skills/spec-steward/SKILL.md`)),
74
- hook,
75
- opsx: config.search(/^operations:/m) >= 0 && hasPointer('apply', ops) && hasPointer('archive', ops),
76
- };
77
- }
78
-
79
- /** One line when the guard is not fully wired, else empty. @param {{ path: string, specsDir?: string }} root */
80
- export function wireWarning(root) {
81
- const s = wireStatus(root);
82
- if (!s.applicable) return '';
83
- const missing = Object.entries(s)
84
- .filter(([k, v]) => k !== 'applicable' && !v)
85
- .map(([k]) => k);
86
- return missing.length
87
- ? `spec-steward: the guard is not fully wired (missing: ${missing.join(', ')}) — run \`steward wire --check\``
88
- : '';
89
- }
90
-
91
- /**
92
- * Add a line to a YAML list `operations.<op>.guidance`, creating the keys when absent, or replace the item an earlier
93
- * version wrote there. Text-level, so comments survive; handles OpenSpec's standard shape and refuses anything else.
94
- * @param {string} text
95
- * @param {'apply' | 'archive'} op
96
- * @param {string} line
97
- * @returns {string | null} the new text, or null when the shape is not recognised
98
- */
99
- export function addGuidance(text, op, line) {
100
- const item = `'${line.replace(/'/g, "''")}'`;
101
- const lines = text.split('\n');
102
- let ops = lines.findIndex((l) => /^operations:\s*$/.test(l));
103
- if (ops < 0) {
104
- const out = text.replace(/\s*$/, '');
105
- return `${out}\n\noperations:\n ${op}:\n guidance:\n - ${item}\n`;
106
- }
107
- const end = (/** @type {number} */ from, /** @type {number} */ indent) => {
108
- let i = from + 1;
109
- while (
110
- i < lines.length &&
111
- (!lines[i].trim() || /^\s*#/.test(lines[i]) || (/^(\s*)/.exec(lines[i])?.[1].length ?? 0) > indent)
112
- )
113
- i++;
114
- return i;
115
- };
116
- const opsEnd = end(ops, 0);
117
- let opLine = -1;
118
- for (let i = ops + 1; i < opsEnd; i++) if (new RegExp(`^\\s{2}${op}:\\s*$`).test(lines[i])) opLine = i;
119
- if (opLine < 0) {
120
- lines.splice(opsEnd, 0, ` ${op}:`, ` guidance:`, ` - ${item}`);
121
- return lines.join('\n');
122
- }
123
- const opEnd = end(opLine, 2);
124
- let g = -1;
125
- for (let i = opLine + 1; i < opEnd; i++) if (/^\s{4}guidance:\s*$/.test(lines[i])) g = i;
126
- if (g < 0) {
127
- lines.splice(opEnd, 0, ` guidance:`, ` - ${item}`);
128
- return lines.join('\n');
129
- }
130
- const gEnd = end(g, 4);
131
- for (let i = g + 1; i < gEnd; i++)
132
- if (/^\s{6}-\s/.test(lines[i]) && LEGACY_GUIDANCE.test(lines[i])) {
133
- lines[i] = ` - ${item}`;
134
- return lines.join('\n');
135
- }
136
- let last = g;
137
- for (let i = g + 1; i < gEnd; i++)
138
- if (/^\s{6}-\s/.test(lines[i]) || (/^\s{8,}\S/.test(lines[i]) && last > g)) last = i;
139
- if (!lines.slice(g + 1, gEnd).every((l) => !l.trim() || /^\s{6,}/.test(l) || /^\s*#/.test(l))) return null;
140
- lines.splice(last + 1, 0, ` - ${item}`);
141
- return lines.join('\n');
142
- }
143
-
144
- /**
145
- * @param {Record<string, any>} opts
146
- * @param {{ name: string, path: string, specsDir?: string }} root
147
- */
148
- export function wireCli(opts, root) {
149
- if (opts.fix) {
150
- const settingsFile = path.join(root.path, '.claude/settings.json');
151
- const settings = fs.existsSync(settingsFile) ? JSON.parse(fs.readFileSync(settingsFile, 'utf8')) : {};
152
- if (!wireStatus(root).hook) {
153
- settings.hooks ??= {};
154
- settings.hooks.PostToolUse ??= [];
155
- settings.hooks.PostToolUse.push({
156
- matcher: 'Edit|Write|MultiEdit',
157
- hooks: [{ type: 'command', command: HOOK_COMMAND, timeout: 30, statusMessage: 'spec-steward check' }],
158
- });
159
- fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
160
- fs.writeFileSync(settingsFile, JSON.stringify(settings, null, 4) + '\n');
161
- process.stdout.write(`wired the edit hook into .claude/settings.json\n`);
162
- }
163
- const cfg = configPath(root.path);
164
- if (cfg && !wireStatus(root).opsx) {
165
- let text = fs.readFileSync(cfg, 'utf8');
166
- for (const op of /** @type {const} */ (['apply', 'archive'])) {
167
- const ops = text.slice(Math.max(0, text.search(/^operations:/m)));
168
- if (hasPointer(op, ops) && text.search(/^operations:/m) >= 0) continue;
169
- const next = addGuidance(text, op, GUIDANCE[op]);
170
- if (next === null) {
171
- process.stdout.write(
172
- `could not place the ${op} guidance in ${path.relative(root.path, cfg)} — add it by hand: ${GUIDANCE[op]}\n`,
173
- );
174
- continue;
175
- }
176
- text = next;
177
- }
178
- fs.writeFileSync(cfg, text);
179
- process.stdout.write(`wired the apply/archive guidance into ${path.relative(root.path, cfg)}\n`);
180
- }
181
- if (!wireStatus(root).agents)
182
- process.stdout.write(`add to AGENTS.md, beside the specification-driven convention:\n ${AGENTS_LINE}\n`);
183
- }
184
- const s = wireStatus(root);
185
- const labels = {
186
- agents: 'AGENTS.md routes to spec-steward',
187
- rule: '.agents/rules/openspec.md (or .claude/rules) is linked by lint-prepare',
188
- skill: '.agents/skills/spec-steward (or .claude/skills) is linked by lint-prepare',
189
- hook: '.claude/settings.json runs the edit hook',
190
- opsx: `openspec/config apply/archive guidance points at the repository's spec gate (${GATE_POINTER})`,
191
- };
192
- if (!s.applicable) {
193
- process.stdout.write('no specifications here — nothing to wire\n');
194
- return 0;
195
- }
196
- for (const [k, label] of Object.entries(labels))
197
- process.stdout.write(`${s[/** @type {keyof typeof s} */ (k)] ? '✓' : '✗'} ${label}\n`);
198
- return Object.entries(s).every(([, v]) => v) ? 0 : 1;
199
- }
200
-
201
- /** Keys of findings already reported, per worktree, so an agent is told once per content. @param {string} root */
202
- function memory(root) {
203
- const dir = git(root, ['rev-parse', '--git-dir'])?.trim();
204
- const file = dir ? path.resolve(root, dir, 'spec-steward-hook.json') : null;
205
- /** @type {string[]} */
206
- let seen = [];
207
- try {
208
- if (file && fs.existsSync(file)) seen = JSON.parse(fs.readFileSync(file, 'utf8'));
209
- } catch {
210
- seen = [];
211
- }
212
- return {
213
- has: (/** @type {string} */ k) => seen.includes(k),
214
- save: (/** @type {string[]} */ keys) => {
215
- if (!file || !keys.length) return;
216
- try {
217
- fs.writeFileSync(file, JSON.stringify([...seen, ...keys].slice(-500)));
218
- } catch {
219
- // memory is a courtesy, never a failure
220
- }
221
- },
222
- };
223
- }
224
-
225
- /**
226
- * Findings for one edited file: on a spec, what the edit changed against HEAD; on a test or source file, its
227
- * citations. Never the backlog of findings an untouched requirement already had.
228
- * @param {string} root
229
- * @param {string} rel
230
- * @param {string} specsDir
231
- */
232
- export function hookFindings(root, rel, specsDir = DEFAULT_SPECS_DIR) {
233
- const abs = path.join(root, rel);
234
- if (!fs.existsSync(abs)) return [];
235
- const text = fs.readFileSync(abs, 'utf8');
236
- if (rel.startsWith(`${specsDir}/`) && rel.endsWith('/spec.md')) {
237
- const cap = capabilityOf(specsDir, rel);
238
- const head = { name: '', path: root, specsDir, capabilities: [parseSpec(text, rel, cap)] };
239
- const before = show(root, 'HEAD', rel);
240
- const base = {
241
- name: '',
242
- path: root,
243
- specsDir,
244
- capabilities: before === null ? [] : [parseSpec(before, rel, cap)],
245
- };
246
- const { findings } = diffCorpus(base, head);
247
- const old = new Map(base.capabilities.flatMap((c) => c.requirements).map((r) => [r.id, r.block]));
248
- const changed = new Set(
249
- head.capabilities[0].requirements.filter((r) => old.get(r.id) !== r.block).map((r) => r.id),
250
- );
251
- // The base enables the prompts that judge new text; the ratchet it would also enable is the gate's, not ours.
252
- const local = checkCorpus(head, [], { files: new Set([rel]), base: baseIndex(base) }).filter(
253
- (f) =>
254
- f.kind === 'duplicate-anchor' ||
255
- (f.id &&
256
- changed.has(f.id) &&
257
- [
258
- 'impl-detail',
259
- 'vague-obligation',
260
- 'restating-scenario',
261
- 'duplicate-scenario',
262
- 'non-ears',
263
- 'non-bdd',
264
- 'marker-hygiene',
265
- 'size',
266
- ].includes(f.kind)),
267
- );
268
- return [...findings, ...local];
269
- }
270
- if (!text.includes('openspec/')) return [];
271
- const anchorsOf = (/** @type {string} */ t) => parseSpec(t, '', '').slugs;
272
- const citations = scanCitations(root, anchorsOf, { files: [rel] });
273
- if (!citations.length) return [];
274
- const corpusFiles = [...new Set(citations.filter((c) => c.resolves).map((c) => c.target))];
275
- const corpus = {
276
- name: '',
277
- path: root,
278
- specsDir,
279
- capabilities: corpusFiles.map((f) =>
280
- parseSpec(fs.readFileSync(path.join(root, f), 'utf8'), f, capabilityOf(specsDir, f)),
281
- ),
282
- };
283
- return checkCorpus(corpus, citations, { files: new Set([rel]) }).filter((f) =>
284
- isTestFile(rel)
285
- ? ['dangling-citation', 'textual-test', 'unbound-test'].includes(f.kind)
286
- : f.kind === 'dangling-citation',
287
- );
288
- }
289
-
290
- /**
291
- * Claude Code PostToolUse entry: reads the hook JSON on stdin, prints a `decision: block` with the findings so they are
292
- * fed back to the agent at once, or nothing.
293
- * @param {Record<string, any>} opts
294
- */
295
- export async function hookCli(opts) {
296
- let input = '';
297
- for await (const chunk of process.stdin) input += chunk;
298
- let event;
299
- try {
300
- event = JSON.parse(input || '{}');
301
- } catch {
302
- return 0;
303
- }
304
- const file = event?.tool_input?.file_path ?? event?.tool_response?.filePath;
305
- if (!file || typeof file !== 'string') return 0;
306
- const resolved = path.resolve(event.cwd ?? process.cwd(), file);
307
- if (!fs.existsSync(resolved)) return 0;
308
- const absFile = fs.realpathSync(resolved);
309
- const top = toplevel(path.dirname(absFile));
310
- if (!top) return 0;
311
- const root = fs.realpathSync(top);
312
- const specsDir = opts.specs ?? DEFAULT_SPECS_DIR;
313
- if (!fs.existsSync(path.join(root, specsDir))) return 0;
314
- const rel = path.relative(root, absFile).split(path.sep).join('/');
315
- const findings = hookFindings(root, rel, specsDir);
316
- const mem = memory(root);
317
- const fresh = findings.filter((f) => !mem.has(`${f.file}|${f.kind}|${f.id ?? f.line}|${f.message}`));
318
- if (!fresh.length) return 0;
319
- mem.save(fresh.map((f) => `${f.file}|${f.kind}|${f.id ?? f.line}|${f.message}`));
320
- const reason = [
321
- `spec-steward found ${fresh.length} thing(s) in your edit of ${rel}:`,
322
- ...fresh.map((f) => `- ${f.file}:${f.line} ${f.kind}: ${f.message}`),
323
- 'Act on them per the Check table of the spec-steward skill: `weakened` means stop and ask the owner; `new-requirement` means name the failure it prevents and its cheapest evidence in your reply; an error (`size`, `duplicate-anchor`) fails the spec gate until fixed; the rest are prompts for judgement — never write a test just to silence one.',
324
- ].join('\n');
325
- process.stdout.write(
326
- JSON.stringify({
327
- decision: 'block',
328
- reason,
329
- hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: reason },
330
- }) + '\n',
331
- );
332
- return 0;
333
- }
@@ -1,289 +0,0 @@
1
- #!/usr/bin/env node
2
- // @ts-check
3
- /**
4
- * spec-steward CLI — deterministic support for writing, guarding and auditing an OpenSpec corpus. Installed as the
5
- * `spec-steward` bin of `@kirill.konshin/lint`; repositories call the CLI and read its JSON, never its modules.
6
- *
7
- * spec-steward check [--base auto|<ref>] [--binds <glob>]... [--file f] [--fix] [--strict] [--json]
8
- * [--max-words P,F] [--max-obligations P,F] the corpus gate (also local and the hook)
9
- * spec-steward coverage [--out file] [--binds <glob>]... the coverage report, MDX-safe Markdown
10
- * spec-steward evidence --json [--binds <glob>]... the audits' evidence model on stdout
11
- * spec-steward review render|status|verify|lint ... the review-file engine
12
- * spec-steward align --root A=path --root B=path [--json] wording drift of shared rules across repos
13
- * spec-steward wire [--check|--fix] the guard's steering points in a repository
14
- * spec-steward hook Claude Code PostToolUse entry (stdin JSON)
15
- *
16
- * Common flags: --root NAME=path (repeatable), --specs <dir> (default openspec/specs). A repository's own binds live in its
17
- * root package.json, `"spec-steward": { "binds": [...] }`, and add to every `--binds` given.
18
- * Exit: 0 clean; 1 an error finding (or a warning under --strict); 2 a usage or environment error — an unknown flag,
19
- * a base ref that does not exist, a git listing that fails or is empty, a missing specs directory.
20
- */
21
- import fs from 'node:fs';
22
- import path from 'node:path';
23
-
24
- import {
25
- applyFixes,
26
- baseIndex,
27
- checkCorpus,
28
- DIFF_KINDS,
29
- diffCorpus,
30
- renameFindings,
31
- scopePrompts,
32
- SIZE,
33
- } from './lib/checks.mjs';
34
- import { scanCitations } from './lib/citations.mjs';
35
- import { DEFAULT_SPECS_DIR, loadCorpus, loadCorpusAt, parseSpec } from './lib/corpus.mjs';
36
- import { coverageReport } from './lib/coverage.mjs';
37
- import { evidenceModel, sourceIndex } from './lib/evidence.mjs';
38
- import { changedFiles, forget, listFiles, resolveBase, toplevel } from './lib/git.mjs';
39
- import { parseArgs } from './lib/util.mjs';
40
-
41
- const anchorsOf = (/** @type {string} */ text) => parseSpec(text, '', '').slugs;
42
-
43
- /** Flags each command accepts; review, align, wire and hook read their own. */
44
- const FLAGS = {
45
- check: ['base', 'binds', 'file', 'fix', 'strict', 'json', 'max-words', 'max-obligations', 'all-citations'],
46
- coverage: ['out', 'binds'],
47
- evidence: ['json', 'binds'],
48
- };
49
- const COMMON = ['root', 'specs'];
50
- const BOOLEANS = ['fix', 'strict', 'json', 'all-citations', 'check'];
51
-
52
- /** A usage or environment error: reported on stderr, exit 2. */
53
- class UsageError extends Error {}
54
-
55
- /** @param {Record<string, any>} opts */
56
- export function rootsOf(opts) {
57
- const specsDir = opts.specs ?? DEFAULT_SPECS_DIR;
58
- const given = /** @type {string[]} */ (opts.root ?? []);
59
- if (!given.length) {
60
- const top = fs.realpathSync(toplevel(process.cwd()) ?? process.cwd());
61
- return [{ name: path.basename(top), path: top, specsDir }];
62
- }
63
- return given.map((r) => {
64
- const eq = r.indexOf('=');
65
- const p = fs.realpathSync(path.resolve(eq > 0 ? r.slice(eq + 1) : r));
66
- return { name: eq > 0 ? r.slice(0, eq) : path.basename(p), path: p, specsDir };
67
- });
68
- }
69
-
70
- /** A `P,F` pair of size lines, or the default. @param {unknown} value @param {[number, number]} fallback */
71
- function pair(value, fallback) {
72
- if (value === undefined) return fallback;
73
- const [p, f] = String(value).split(',').map(Number);
74
- if (!Number.isFinite(p) || (f !== undefined && !Number.isFinite(f)))
75
- throw new UsageError(`bad size line: ${value}`);
76
- return /** @type {[number, number]} */ ([p, f ?? fallback[1]]);
77
- }
78
-
79
- /**
80
- * The repository must hold a specs directory and a non-empty git listing; otherwise every scan would be vacuous.
81
- * @param {{ name: string, path: string, specsDir: string }} root
82
- */
83
- function assertScannable(root) {
84
- if (!fs.existsSync(path.join(root.path, root.specsDir)))
85
- throw new UsageError(`${root.name}: no specs directory ${root.specsDir}`);
86
- if (!listFiles(root.path)?.length)
87
- throw new UsageError(`${root.name}: git lists no files — is ${root.path} a repository?`);
88
- }
89
-
90
- /**
91
- * What binds beyond the defaults: the repository's own `binds` (`"spec-steward": { "binds": [...] }` in its root
92
- * `package.json`), then every `--binds` given.
93
- * @param {Record<string, any>} opts
94
- * @param {string} root
95
- */
96
- const bindsOf = (opts, root) => {
97
- let configured = [];
98
- try {
99
- configured = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))['spec-steward']?.binds ?? [];
100
- } catch {
101
- // no package.json, or not JSON: nothing configured
102
- }
103
- return /** @type {string[]} */ (
104
- [...[].concat(configured), ...[].concat(opts.binds ?? [])].filter((b) => typeof b === 'string')
105
- );
106
- };
107
-
108
- /**
109
- * Every finding for one repository, and the base it was judged against.
110
- * @param {{ name: string, path: string, specsDir: string }} root
111
- * @param {Record<string, any>} opts
112
- */
113
- export function runCheck(root, opts) {
114
- forget();
115
- assertScannable(root);
116
- let base = null;
117
- let how = 'none — no --base';
118
- if (opts.base !== undefined) {
119
- const resolved = resolveBase(root.path, opts.base);
120
- if ('error' in resolved) throw new UsageError(resolved.error);
121
- base = resolved.ref;
122
- how = resolved.how;
123
- }
124
- const corpus = loadCorpus(root.path, root);
125
- const binds = bindsOf(opts, root.path);
126
- if (opts.file && (typeof opts.file !== 'string' || !fs.existsSync(path.resolve(opts.file))))
127
- throw new UsageError(`--file ${opts.file}: no such file`);
128
- const relative = (/** @type {string} */ f) =>
129
- path
130
- .relative(root.path, fs.realpathSync(path.resolve(f)))
131
- .split(path.sep)
132
- .join('/');
133
- const only = opts.file ? new Set([relative(opts.file)]) : undefined;
134
- const all = scanCitations(root.path, anchorsOf, { binds });
135
- const citations = only && !opts['all-citations'] ? all.filter((c) => only.has(c.file)) : all;
136
- const baseCorpus = base ? loadCorpusAt(root.path, base, root) : null;
137
- const index = baseCorpus ? baseIndex(baseCorpus) : null;
138
- let findings = checkCorpus(corpus, all, {
139
- maxWords: pair(opts['max-words'], SIZE.words),
140
- maxObligations: pair(opts['max-obligations'], SIZE.obligations),
141
- files: only,
142
- base: index,
143
- });
144
- if (baseCorpus && index && base) {
145
- const { findings: diff, renames } = diffCorpus(baseCorpus, corpus);
146
- findings.push(...diff.filter((f) => !only || only.has(f.file)));
147
- const renamed = renameFindings(renames, citations);
148
- const covered = new Set(renamed.map((f) => `${f.file}:${f.line}`));
149
- findings = findings.filter((f) => f.kind !== 'dangling-citation' || !covered.has(`${f.file}:${f.line}`));
150
- findings.push(...renamed);
151
- findings = scopePrompts(findings, corpus, index, changedFiles(root.path, base));
152
- } else if (opts.base !== undefined) findings = findings.filter((f) => f.severity !== 'info');
153
- return { corpus, citations, findings, base, how };
154
- }
155
-
156
- const ORDER = { error: 0, warn: 1, info: 2 };
157
-
158
- /**
159
- * @param {string} cmd
160
- * @param {Record<string, any>} opts
161
- */
162
- function validateFlags(cmd, opts) {
163
- const known = /** @type {Record<string, string[]>} */ (FLAGS)[cmd];
164
- if (!known) return;
165
- const unknown = Object.keys(opts).filter((k) => k !== '_' && !known.includes(k) && !COMMON.includes(k));
166
- if (unknown.length) throw new UsageError(`${cmd}: unknown flag ${unknown.map((k) => `--${k}`).join(', ')}`);
167
- }
168
-
169
- /** @param {{ name: string }[]} roots @param {string} cmd */
170
- function oneRoot(roots, cmd) {
171
- if (roots.length !== 1) throw new UsageError(`${cmd} takes one --root`);
172
- return /** @type {{ name: string, path: string, specsDir: string }} */ (roots[0]);
173
- }
174
-
175
- /** @param {string[]} argv */
176
- async function main(argv) {
177
- const [cmd, ...rest] = argv;
178
- const opts = parseArgs(rest, ['root', 'lens', 'binds'], BOOLEANS);
179
- validateFlags(cmd, opts);
180
- const roots = rootsOf(opts);
181
-
182
- if (cmd === 'check') {
183
- let failed = false;
184
- const all = [];
185
- const prefix = roots.length > 1;
186
- for (const root of roots) {
187
- let { findings, how, base } = runCheck(root, opts);
188
- if (opts.fix) {
189
- const changed = applyFixes(root.path, findings);
190
- for (const f of changed) process.stderr.write(`fixed ${root.name} ${f}\n`);
191
- if (changed.length) findings = runCheck(root, { ...opts, fix: false }).findings;
192
- }
193
- process.stderr.write(`${prefix ? `${root.name} ` : ''}base: ${base ? `${base} (${how})` : how}\n`);
194
- if (!base && opts.base !== undefined)
195
- process.stderr.write(` skipped: ${DIFF_KINDS.join(', ')}; prompts not printed\n`);
196
- findings.sort(
197
- (a, b) => ORDER[a.severity] - ORDER[b.severity] || a.file.localeCompare(b.file) || a.line - b.line,
198
- );
199
- for (const f of findings)
200
- all.push({
201
- root: root.name,
202
- file: f.file,
203
- line: f.line,
204
- severity: f.severity,
205
- kind: f.kind,
206
- ...(f.id && { id: f.id }),
207
- message: f.message,
208
- });
209
- if (findings.some((f) => f.severity === 'error' || (opts.strict && f.severity === 'warn'))) failed = true;
210
- }
211
- if (opts.json) process.stdout.write(JSON.stringify(all, null, 2) + '\n');
212
- else
213
- for (const f of all)
214
- process.stdout.write(
215
- `${prefix ? `${f.root} ` : ''}${f.file}:${f.line} ${f.severity} ${f.kind} ${f.message}\n`,
216
- );
217
- const by = all.reduce(
218
- (m, f) => ((m[f.kind] = (m[f.kind] ?? 0) + 1), m),
219
- /** @type {Record<string, number>} */ ({}),
220
- );
221
- const n = (/** @type {string} */ s) => all.filter((f) => f.severity === s).length;
222
- process.stderr.write(
223
- `${all.length} finding(s): ${
224
- Object.entries(by)
225
- .map(([k, c]) => `${k} ${c}`)
226
- .join(', ') || 'none'
227
- }\n${failed ? 'FAIL' : 'PASS'} — ${n('error')} error(s), ${n('warn')} warning(s), ${n('info')} prompt(s)\n`,
228
- );
229
- return failed ? 1 : 0;
230
- }
231
-
232
- if (cmd === 'coverage') {
233
- const root = oneRoot(roots, cmd);
234
- assertScannable(root);
235
- const { markdown, totals } = coverageReport(
236
- loadCorpus(root.path, root),
237
- scanCitations(root.path, anchorsOf, { binds: bindsOf(opts, root.path) }),
238
- );
239
- if (typeof opts.out === 'string') {
240
- fs.writeFileSync(path.resolve(opts.out), markdown);
241
- process.stderr.write(
242
- `wrote ${opts.out} — ${totals.requirements} requirements, ${totals.unboundRequirements} REQUIRED unbound, ${totals.gaps} known gaps\n`,
243
- );
244
- } else process.stdout.write(markdown);
245
- return 0;
246
- }
247
-
248
- if (cmd === 'evidence') {
249
- if (!opts.json) throw new UsageError('evidence takes --json: the evidence model on stdout');
250
- const root = oneRoot(roots, cmd);
251
- assertScannable(root);
252
- const model = evidenceModel(
253
- loadCorpus(root.path, root),
254
- scanCitations(root.path, anchorsOf, { binds: bindsOf(opts, root.path) }),
255
- sourceIndex(root.path),
256
- );
257
- process.stdout.write(JSON.stringify(model) + '\n');
258
- return 0;
259
- }
260
-
261
- if (cmd === 'review') return (await import('./lib/review.mjs')).reviewCli(rest, roots);
262
- if (cmd === 'align') return (await import('./lib/align.mjs')).alignCli(opts, roots);
263
- if (cmd === 'wire') return (await import('./lib/wire.mjs')).wireCli(opts, roots[0]);
264
- if (cmd === 'hook') return (await import('./lib/wire.mjs')).hookCli(opts);
265
-
266
- throw new UsageError(
267
- 'usage: spec-steward check|coverage|evidence|review|align|wire|hook — see the header of steward.mjs',
268
- );
269
- }
270
-
271
- if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(new URL(import.meta.url).pathname)) {
272
- const cmd = process.argv[2];
273
- if (cmd && cmd !== 'hook' && cmd !== 'wire' && !process.env.CI) {
274
- try {
275
- const { wireWarning } = await import('./lib/wire.mjs');
276
- const warning = wireWarning(rootsOf(parseArgs(process.argv.slice(3), ['root']))[0]);
277
- if (warning) process.stderr.write(warning + '\n');
278
- } catch {
279
- // the wire check never blocks a command
280
- }
281
- }
282
- try {
283
- process.exitCode = await main(process.argv.slice(2));
284
- } catch (error) {
285
- if (!(error instanceof UsageError)) throw error;
286
- process.stderr.write(`spec-steward: ${error.message}\n`);
287
- process.exitCode = 2;
288
- }
289
- }