@kirill.konshin/lint 0.5.2 → 0.5.4

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