@sublang/spex 0.3.0 → 1.0.0

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.
package/dist/lint.js ADDED
@@ -0,0 +1,967 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, } from "node:fs";
4
+ import { join, posix, relative, sep } from "node:path";
5
+ import { baseHeadingSlugs, codeLineMap, headingSlugs, headingText, parseMarkdown, plainHeadingText, visit, } from "./markdown.js";
6
+ import { resolveBase } from "./resolve-base.js";
7
+ // Localized section names accepted alongside the English ones,
8
+ // matching the section names the bundled zh meta.md defines for
9
+ // package files (meta-30).
10
+ const SECTION_ALIASES = {
11
+ Intent: ["Intent", "意图"],
12
+ "External Behavior": ["External Behavior", "外部行为"],
13
+ "Internal Behavior": ["Internal Behavior", "内部行为"],
14
+ Verification: ["Verification", "验证"],
15
+ References: ["References", "参考资料"],
16
+ };
17
+ const PACKAGE_SECTION_ORDER = [
18
+ "Intent",
19
+ "External Behavior",
20
+ "Internal Behavior",
21
+ "Verification",
22
+ "References",
23
+ ];
24
+ // Required record sections per meta-4 / meta-5, with the zh names
25
+ // of the bundled templates. A DR's References section is listed by
26
+ // meta-4 but holds no uncited entry (meta-19), so a DR without
27
+ // external sources legitimately omits it — it is not required here.
28
+ const DR_SECTIONS = {
29
+ Status: ["Status", "状态"],
30
+ Context: ["Context", "背景"],
31
+ Decision: ["Decision", "决策"],
32
+ Consequences: ["Consequences", "影响"],
33
+ };
34
+ const IR_SECTIONS = {
35
+ Status: ["Status", "状态"],
36
+ Intent: ["Intent", "意图"],
37
+ Deliverables: ["Deliverables", "交付项"],
38
+ Tasks: ["Tasks", "任务"],
39
+ Verification: ["Verification", "验证"],
40
+ };
41
+ const KEBAB_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
42
+ const RECORD_NAME_RE = /^\d{3}-[a-z0-9]+(?:-[a-z0-9]+)*\.md$/;
43
+ // Package H1: `# <pack>: <Title>` with <pack> the lowercase
44
+ // kebab-case basename (meta-10).
45
+ const H1_RE = /^([a-z0-9]+(?:-[a-z0-9]+)*):\s+\S.*$/;
46
+ // Item headings: lowercase <pack>-<N> (meta-11). The loose form
47
+ // also catches case violations so they lint as items, not topics.
48
+ const ITEM_RE = /^([a-z0-9]+(?:-[a-z0-9]+)*)-([1-9][0-9]*)$/;
49
+ const ITEM_LOOSE_RE = /^([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*)-([1-9][0-9]*)$/;
50
+ const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
51
+ // Relationship-metadata lines prohibited by meta-14: citations in
52
+ // an item's statement are the single relationship source.
53
+ const METADATA_LINE_RE = /^(Verifies|Binds|Composes|Clients|Suppliers|Scope|Requires|Uses):(\s|$)/;
54
+ // A relationship-only sentence left by mechanical migration:
55
+ // "Verifies" plus citations and separators. meta-16 wants each
56
+ // citation woven into the assertion it supports.
57
+ const HAS_CITATION_RE = /\[[^\]]*\]\([^)]*\)/;
58
+ const CITATION_SCAN_RE = /\[[^\]]*\]\([^)]*\)/g;
59
+ const DETACHED_VERIFIES_RE = /^Verifies\b(?:[\s,.;]|and\b)*$/;
60
+ // Legacy directories of retired spec generations (lint-4); their
61
+ // structural migration is agent-skill work, not CLI code (DR-021).
62
+ const LEGACY_DIRS = [
63
+ "user",
64
+ "dev",
65
+ "test",
66
+ "items",
67
+ "interactions",
68
+ "compositions",
69
+ ];
70
+ const LEGACY_PATH_RE = /^specs\/(?:user|dev|test|items|interactions|compositions)\//;
71
+ const KNOWN_TOP_LEVEL = new Set([
72
+ "decisions",
73
+ "intents",
74
+ "packages",
75
+ "map.md",
76
+ "meta.md",
77
+ ]);
78
+ const BEHAVIOR_SECTIONS = new Set(["External Behavior", "Internal Behavior"]);
79
+ function report(ctx, path, line, severity, rule, message) {
80
+ ctx.findings.push({ path, line, severity, rule, message });
81
+ }
82
+ function listMarkdownFiles(dir, prefix) {
83
+ const files = [];
84
+ for (const entry of readdirSync(dir).sort()) {
85
+ if (entry === ".DS_Store")
86
+ continue;
87
+ const abs = join(dir, entry);
88
+ const rel = posix.join(prefix, entry);
89
+ if (statSync(abs).isDirectory()) {
90
+ files.push(...listMarkdownFiles(abs, rel));
91
+ }
92
+ else if (entry.endsWith(".md")) {
93
+ files.push(rel);
94
+ }
95
+ }
96
+ return files;
97
+ }
98
+ function plainInlineText(node) {
99
+ let plain = "";
100
+ visit(node, (child) => {
101
+ if (child.type === "text" || child.type === "inlineCode") {
102
+ plain += child.value;
103
+ }
104
+ });
105
+ return plain;
106
+ }
107
+ function loadFile(basePath, relPath) {
108
+ const text = readFileSync(join(basePath, relPath), "utf-8");
109
+ const tree = parseMarkdown(text);
110
+ const rawHeadings = [];
111
+ const links = [];
112
+ const texts = [];
113
+ const referenceLinks = [];
114
+ const referenceUses = [];
115
+ visit(tree, (node) => {
116
+ if (node.type === "heading") {
117
+ const heading = node;
118
+ rawHeadings.push({
119
+ depth: heading.depth,
120
+ text: headingText(text, heading),
121
+ plain: plainHeadingText(text, heading),
122
+ line: heading.position?.start.line ?? 1,
123
+ });
124
+ return;
125
+ }
126
+ if (node.type === "text") {
127
+ texts.push({
128
+ line: node.position?.start.line ?? 1,
129
+ value: node.value,
130
+ });
131
+ return;
132
+ }
133
+ if (node.type === "linkReference" || node.type === "imageReference") {
134
+ const reference = node;
135
+ const line = node.position?.start.line ?? 1;
136
+ referenceUses.push({ line });
137
+ // Only the literal [[N]] marker form of meta-19 is exempt: a
138
+ // numeric shortcut reference wrapped in the outer brackets.
139
+ // A bare [1], a collapsed [1][], and any full reference are
140
+ // disguised citations even with numeric labels (lint-8).
141
+ const start = node.position?.start.offset;
142
+ const end = node.position?.end.offset;
143
+ const wrapped = start !== undefined &&
144
+ end !== undefined &&
145
+ text.charAt(start - 1) === "[" &&
146
+ text.charAt(end) === "]";
147
+ const isMarker = /^\d+$/.test(reference.identifier) &&
148
+ reference.referenceType === "shortcut" &&
149
+ wrapped;
150
+ if (!isMarker) {
151
+ referenceLinks.push({ line });
152
+ }
153
+ return;
154
+ }
155
+ if (node.type === "link" ||
156
+ node.type === "image" ||
157
+ node.type === "definition") {
158
+ const start = node.position?.start.offset;
159
+ const end = node.position?.end.offset;
160
+ links.push({
161
+ url: node.url,
162
+ line: node.position?.start.line ?? 1,
163
+ kind: node.type,
164
+ text: node.type === "link" ? plainInlineText(node).trim() : "",
165
+ enclosed: start !== undefined &&
166
+ end !== undefined &&
167
+ text.charAt(start - 1) === "[" &&
168
+ text.charAt(end) === "]",
169
+ });
170
+ }
171
+ });
172
+ const slugList = headingSlugs(text, tree);
173
+ const rootHeadingLines = new Set();
174
+ for (const child of tree.children) {
175
+ if (child.type === "heading") {
176
+ rootHeadingLines.add(child.position?.start.line ?? 1);
177
+ }
178
+ }
179
+ const headings = rawHeadings.map((heading, index) => ({
180
+ ...heading,
181
+ slug: slugList[index] ?? "",
182
+ root: rootHeadingLines.has(heading.line),
183
+ }));
184
+ const lines = text.split("\n");
185
+ const h1 = headings.find((heading) => heading.depth === 1 && heading.root) ?? null;
186
+ return {
187
+ relPath,
188
+ text,
189
+ lines,
190
+ tree,
191
+ headings,
192
+ slugs: new Set(slugList),
193
+ links,
194
+ h1,
195
+ fenced: codeLineMap(tree, lines.length),
196
+ texts,
197
+ referenceLinks,
198
+ referenceUses,
199
+ };
200
+ }
201
+ function aliasSet(aliases) {
202
+ const map = new Map();
203
+ for (const [canonical, names] of Object.entries(aliases)) {
204
+ for (const name of names)
205
+ map.set(name, canonical);
206
+ }
207
+ return map;
208
+ }
209
+ const SECTION_BY_NAME = aliasSet(SECTION_ALIASES);
210
+ function isUnder(relPath, dir) {
211
+ return relPath.startsWith(`specs/${dir}/`);
212
+ }
213
+ // The meta-18 prohibition binds DRs and spec items — decisions/,
214
+ // packages/, and meta.md. Intent records themselves and map.md sit
215
+ // outside it, so an IR (or the map) referencing an IR is legal.
216
+ function boundByIrProhibition(relPath) {
217
+ return (isUnder(relPath, "decisions") ||
218
+ isUnder(relPath, "packages") ||
219
+ relPath === "specs/meta.md");
220
+ }
221
+ function basenameOf(relPath) {
222
+ return posix.basename(relPath, ".md");
223
+ }
224
+ // ---------------------------------------------------------------
225
+ // Structure rules (lint-4)
226
+ // ---------------------------------------------------------------
227
+ function lintStructure(ctx) {
228
+ const specsDir = join(ctx.basePath, "specs");
229
+ for (const dir of LEGACY_DIRS) {
230
+ if (existsSync(join(specsDir, dir))) {
231
+ report(ctx, `specs/${dir}`, 1, "error", "structure/legacy-layout", `legacy directory specs/${dir}/ found; run the spec-structure-migration skill to migrate to the current layout (DR-021)`);
232
+ }
233
+ }
234
+ for (const entry of readdirSync(specsDir).sort()) {
235
+ if (entry === ".DS_Store" || KNOWN_TOP_LEVEL.has(entry))
236
+ continue;
237
+ // Legacy directories carry their own findings; a lone legacy
238
+ // iterations/ still homes IRs (lint-4) and is not "unexpected".
239
+ if (LEGACY_DIRS.includes(entry))
240
+ continue;
241
+ if (entry === "iterations")
242
+ continue;
243
+ report(ctx, `specs/${entry}`, 1, "warning", "structure/unknown-entry", `unexpected entry under specs/ (expected decisions/, intents/, packages/, map.md, meta.md)`);
244
+ }
245
+ if (existsSync(join(specsDir, "intents")) &&
246
+ existsSync(join(specsDir, "iterations"))) {
247
+ report(ctx, "specs/iterations", 1, "warning", "structure/legacy-records", "legacy specs/iterations/ coexists with specs/intents/ (DR-017)");
248
+ }
249
+ for (const required of ["specs/meta.md", "specs/map.md"]) {
250
+ if (!existsSync(join(ctx.basePath, required))) {
251
+ report(ctx, required, 1, "error", "structure/missing-file", `${required} is missing`);
252
+ }
253
+ }
254
+ }
255
+ function lintNaming(ctx) {
256
+ for (const file of ctx.files.values()) {
257
+ const { relPath } = file;
258
+ if (isUnder(relPath, "packages")) {
259
+ const segments = relPath.split("/").slice(2);
260
+ const basename = segments.pop();
261
+ if (!KEBAB_RE.test(basename.replace(/\.md$/, ""))) {
262
+ report(ctx, relPath, 1, "error", "naming/kebab", `file name should be <kebab-case>.md (meta-1)`);
263
+ }
264
+ for (const segment of segments) {
265
+ if (!KEBAB_RE.test(segment)) {
266
+ report(ctx, relPath, 1, "error", "naming/kebab", `directory "${segment}" should be kebab-case (meta-1)`);
267
+ }
268
+ }
269
+ }
270
+ if (isUnder(relPath, "decisions") ||
271
+ isUnder(relPath, "intents") ||
272
+ isUnder(relPath, "iterations")) {
273
+ const basename = posix.basename(relPath);
274
+ if (!RECORD_NAME_RE.test(basename)) {
275
+ report(ctx, relPath, 1, "error", "naming/record", `record file name should be <NNN>-<kebab-case>.md (meta-1)`);
276
+ }
277
+ }
278
+ }
279
+ }
280
+ // ---------------------------------------------------------------
281
+ // Package file rules (lint-5)
282
+ // ---------------------------------------------------------------
283
+ function lintPackageFile(ctx, file) {
284
+ const basename = basenameOf(file.relPath);
285
+ if (file.h1 === null) {
286
+ report(ctx, file.relPath, 1, "error", "package/heading", "package file needs a `# <pack>: <Title>` heading (meta-30)");
287
+ }
288
+ else {
289
+ const match = file.h1.plain.trim().match(H1_RE);
290
+ if (match === null) {
291
+ report(ctx, file.relPath, file.h1.line, "error", "package/heading", "H1 should be `# <pack>: <Title>` with <pack> the lowercase kebab-case basename (meta-10)");
292
+ }
293
+ else if (match[1] !== basename) {
294
+ report(ctx, file.relPath, file.h1.line, "error", "package/heading", `H1 identifier "${match[1]}" does not match the file's basename "${basename}" (meta-10)`);
295
+ }
296
+ }
297
+ const h2s = file.headings.filter((heading) => heading.depth === 2 && heading.root);
298
+ const present = [];
299
+ for (const heading of h2s) {
300
+ const canonical = SECTION_BY_NAME.get(heading.plain.trim());
301
+ if (canonical === undefined) {
302
+ report(ctx, file.relPath, heading.line, "error", "package/sections", `unexpected section "## ${heading.plain}"; package files use ${PACKAGE_SECTION_ORDER.join(", ")} (meta-30)`);
303
+ continue;
304
+ }
305
+ if (present.includes(canonical)) {
306
+ report(ctx, file.relPath, heading.line, "error", "package/sections", `duplicate section "## ${heading.plain}" (meta-30)`);
307
+ continue;
308
+ }
309
+ if (present.length > 0 &&
310
+ PACKAGE_SECTION_ORDER.indexOf(canonical) <
311
+ PACKAGE_SECTION_ORDER.indexOf(present[present.length - 1])) {
312
+ report(ctx, file.relPath, heading.line, "error", "package/sections", `section "## ${heading.plain}" is out of order (expected ${PACKAGE_SECTION_ORDER.join(", ")}) (meta-30)`);
313
+ }
314
+ present.push(canonical);
315
+ }
316
+ for (const requiredSection of ["Intent", "External Behavior"]) {
317
+ if (!present.includes(requiredSection)) {
318
+ report(ctx, file.relPath, 1, "error", "package/sections", `missing required "## ${requiredSection}" section (meta-30)`);
319
+ }
320
+ }
321
+ if (!present.includes("Verification")) {
322
+ report(ctx, file.relPath, 1, "warning", "package/verification", 'missing "## Verification" section; verification is required unless irrelevant (meta-33)');
323
+ }
324
+ }
325
+ function collectItems(ctx) {
326
+ const items = [];
327
+ for (const file of ctx.files.values()) {
328
+ const eligible = isUnder(file.relPath, "packages") || file.relPath === "specs/meta.md";
329
+ if (!eligible)
330
+ continue;
331
+ for (const [index, heading] of file.headings.entries()) {
332
+ if (heading.depth < 2 || !heading.root)
333
+ continue;
334
+ const match = heading.plain.trim().match(ITEM_LOOSE_RE);
335
+ if (match === null)
336
+ continue;
337
+ // lint-10: the body runs to the next root-level heading of
338
+ // the same or shallower depth, so nested subsections stay in
339
+ // the item and a quoted heading never truncates its body.
340
+ let bodyEnd = file.lines.length + 1;
341
+ for (let after = index + 1; after < file.headings.length; after += 1) {
342
+ if (!file.headings[after].root)
343
+ continue;
344
+ if (file.headings[after].depth <= heading.depth) {
345
+ bodyEnd = file.headings[after].line;
346
+ break;
347
+ }
348
+ }
349
+ items.push({
350
+ file,
351
+ heading,
352
+ id: heading.plain.trim(),
353
+ prefix: match[1],
354
+ section: sectionOf(file, heading),
355
+ bodyStart: heading.line + 1,
356
+ bodyEnd,
357
+ });
358
+ }
359
+ }
360
+ return items;
361
+ }
362
+ function sectionOf(file, heading) {
363
+ let current = null;
364
+ for (const candidate of file.headings) {
365
+ if (candidate.line > heading.line)
366
+ break;
367
+ if (candidate.depth === 2 && candidate.root) {
368
+ current = SECTION_BY_NAME.get(candidate.plain.trim()) ?? candidate.plain;
369
+ }
370
+ }
371
+ return current;
372
+ }
373
+ function lintItems(ctx, items) {
374
+ const byId = new Map();
375
+ for (const item of items) {
376
+ const key = item.id.toLowerCase();
377
+ const list = byId.get(key) ?? [];
378
+ list.push(item);
379
+ byId.set(key, list);
380
+ if (!ITEM_RE.test(item.id)) {
381
+ report(ctx, item.file.relPath, item.heading.line, "error", "id/form", `item heading ${item.id} is not of the lowercase <pack>-<N> form (meta-11)`);
382
+ }
383
+ const basename = basenameOf(item.file.relPath);
384
+ if (item.prefix.toLowerCase() !== basename) {
385
+ report(ctx, item.file.relPath, item.heading.line, "error", "id/prefix", `item ${item.id} does not match the file's basename "${basename}" (meta-11)`);
386
+ }
387
+ if (isUnder(item.file.relPath, "packages") &&
388
+ (item.section === "Intent" || item.section === "References")) {
389
+ report(ctx, item.file.relPath, item.heading.line, "warning", "id/misplaced", `item ${item.id} sits inside the ${item.section} section; items belong in the Behavior and Verification sections (meta-30)`);
390
+ }
391
+ }
392
+ for (const list of byId.values()) {
393
+ if (list.length < 2)
394
+ continue;
395
+ for (const item of list) {
396
+ report(ctx, item.file.relPath, item.heading.line, "error", "id/duplicate", `item ID ${item.id} is defined ${list.length} times across specs/ (meta-11)`);
397
+ }
398
+ }
399
+ // A package's identity is its basename (meta-10); one basename
400
+ // used by two files collides even across subdirectories.
401
+ const byBasename = new Map();
402
+ for (const file of ctx.files.values()) {
403
+ if (!isUnder(file.relPath, "packages"))
404
+ continue;
405
+ const basename = basenameOf(file.relPath);
406
+ const list = byBasename.get(basename) ?? [];
407
+ list.push(file);
408
+ byBasename.set(basename, list);
409
+ }
410
+ for (const [basename, list] of byBasename) {
411
+ if (list.length < 2)
412
+ continue;
413
+ for (const file of list) {
414
+ report(ctx, file.relPath, 1, "error", "id/basename", `package basename "${basename}" is used by ${list
415
+ .map((other) => other.relPath)
416
+ .join(", ")} (meta-10)`);
417
+ }
418
+ }
419
+ }
420
+ // ---------------------------------------------------------------
421
+ // Item relationships (lint-7) and citation discipline (lint-13,
422
+ // lint-14)
423
+ // ---------------------------------------------------------------
424
+ /**
425
+ * Resolve a relative citation URL against its file, or null for
426
+ * scheme/absolute/empty URLs that cannot target a spec file.
427
+ */
428
+ function resolveCitation(file, url) {
429
+ const path = url.split("#")[0];
430
+ if (path === "" || SCHEME_RE.test(path))
431
+ return null;
432
+ if (path.startsWith("/") || path.startsWith("//"))
433
+ return null;
434
+ return posix.normalize(posix.join(posix.dirname(file.relPath), path));
435
+ }
436
+ /** Links whose source line falls inside the item's body. */
437
+ function bodyLinks(item) {
438
+ return item.file.links.filter((link) => link.kind === "link" &&
439
+ link.line >= item.bodyStart &&
440
+ link.line < item.bodyEnd);
441
+ }
442
+ /** The link's target file and fragment, self-links resolved. */
443
+ function linkTarget(file, link) {
444
+ const [path, ...fragmentParts] = link.url.split("#");
445
+ const fragment = fragmentParts.join("#");
446
+ if (path === "") {
447
+ return link.url.startsWith("#") ? { relPath: file.relPath, fragment } : null;
448
+ }
449
+ const resolved = resolveCitation(file, link.url);
450
+ if (resolved === null)
451
+ return null;
452
+ return { relPath: resolved, fragment };
453
+ }
454
+ function itemsBySlug(items) {
455
+ const bySlug = new Map();
456
+ for (const item of items) {
457
+ const map = bySlug.get(item.file.relPath) ?? new Map();
458
+ map.set(item.heading.slug, item);
459
+ bySlug.set(item.file.relPath, map);
460
+ }
461
+ return bySlug;
462
+ }
463
+ function lintItemRelationships(ctx, items) {
464
+ const bySlug = itemsBySlug(items);
465
+ for (const item of items) {
466
+ if (!isUnder(item.file.relPath, "packages"))
467
+ continue;
468
+ // Relationship-metadata lines are prohibited (lint-7): inline
469
+ // citations are the single relationship source (meta-14). A
470
+ // relationship-only "Verifies …" sentence is an error too
471
+ // (lint-13): weave each citation into the assertion it
472
+ // supports (meta-16).
473
+ for (let line = item.bodyStart; line < item.bodyEnd; line += 1) {
474
+ if (item.file.fenced[line - 1])
475
+ continue;
476
+ const content = item.file.lines[line - 1];
477
+ if (content === undefined)
478
+ continue;
479
+ const trimmed = content.trimStart();
480
+ if (METADATA_LINE_RE.test(trimmed)) {
481
+ report(ctx, item.file.relPath, line, "error", "item/metadata-line", `item ${item.id} carries a relationship-metadata line; inline citations are the single source of relationships (meta-14)`);
482
+ continue;
483
+ }
484
+ if (trimmed.startsWith("Verifies") &&
485
+ HAS_CITATION_RE.test(trimmed) &&
486
+ DETACHED_VERIFIES_RE.test(trimmed.replace(CITATION_SCAN_RE, ""))) {
487
+ report(ctx, item.file.relPath, line, "error", "cite/detached", `item ${item.id} carries a detached "Verifies …" sentence; weave each citation into the assertion it supports (meta-16)`);
488
+ }
489
+ }
490
+ // A Verification item cites every behavior it verifies inline
491
+ // (meta-20): at least one same-file behavior item anchor.
492
+ if (item.section === "Verification") {
493
+ let citesBehavior = false;
494
+ for (const link of bodyLinks(item)) {
495
+ const target = linkTarget(item.file, link);
496
+ if (target === null || target.relPath !== item.file.relPath)
497
+ continue;
498
+ const cited = bySlug.get(item.file.relPath)?.get(target.fragment);
499
+ if (cited !== undefined &&
500
+ cited !== item &&
501
+ cited.section !== null &&
502
+ BEHAVIOR_SECTIONS.has(cited.section)) {
503
+ citesBehavior = true;
504
+ break;
505
+ }
506
+ }
507
+ if (!citesBehavior) {
508
+ report(ctx, item.file.relPath, item.heading.line, "error", "verify/uncited", `Verification item ${item.id} cites no same-file behavior item; cite each behavior it verifies inline at the assertion (meta-20)`);
509
+ }
510
+ }
511
+ // Peer citations resolve against the peer's sections: a
512
+ // behavior item may rely on External Behavior alone (lint-7,
513
+ // meta-14); a Verification item cites behavior items (meta-20),
514
+ // and the law is silent on it reaching a peer's Internal
515
+ // Behavior, so lint tolerates that reach (lint-13).
516
+ const isBehavior = item.section !== null && BEHAVIOR_SECTIONS.has(item.section);
517
+ const isVerification = item.section === "Verification";
518
+ if (isBehavior || isVerification) {
519
+ for (const link of bodyLinks(item)) {
520
+ const target = linkTarget(item.file, link);
521
+ if (target === null ||
522
+ target.relPath === item.file.relPath ||
523
+ !target.relPath.startsWith("specs/packages/") ||
524
+ !ctx.files.has(target.relPath)) {
525
+ continue;
526
+ }
527
+ const cited = bySlug.get(target.relPath)?.get(target.fragment);
528
+ if (isBehavior) {
529
+ if (cited !== undefined && cited.section !== "External Behavior") {
530
+ report(ctx, item.file.relPath, link.line, "error", "cite/internal", `item ${item.id} cites ${cited.id} in ${target.relPath}'s ${cited.section ?? "front matter"}; a peer behavior is relied on through External Behavior alone (meta-14)`);
531
+ }
532
+ }
533
+ else if (target.fragment !== "") {
534
+ // Verification: the cited peer anchor must be an External
535
+ // or Internal Behavior item.
536
+ if (cited === undefined ||
537
+ cited.section === null ||
538
+ !BEHAVIOR_SECTIONS.has(cited.section)) {
539
+ report(ctx, item.file.relPath, link.line, "error", "cite/internal", `Verification item ${item.id} cites ${target.relPath}#${target.fragment} outside the peer's External and Internal Behavior items (meta-20)`);
540
+ }
541
+ }
542
+ }
543
+ }
544
+ }
545
+ // One governing statement per item (meta-29), sentence count as
546
+ // its advisory proxy (lint-14) — a conformant item may carry
547
+ // several sentences of one contract's cases, so this only
548
+ // prompts a read: prose outside fenced blocks, lists, tables,
549
+ // blockquotes, and headings carries at most one sentence.
550
+ // Terminators: ASCII before whitespace or line end, fullwidth
551
+ // anywhere, e.g./i.e. exempt.
552
+ for (const item of items) {
553
+ let terminators = 0;
554
+ let extraLine = -1;
555
+ for (let line = item.bodyStart; line < item.bodyEnd; line += 1) {
556
+ if (item.file.fenced[line - 1])
557
+ continue;
558
+ const content = item.file.lines[line - 1];
559
+ if (content === undefined)
560
+ continue;
561
+ const trimmed = content.trimStart();
562
+ if (trimmed === "" || /^(?:[-*+>|#]|\d+[.)]\s)/.test(trimmed)) {
563
+ continue;
564
+ }
565
+ const bare = trimmed.replace(/`[^`]*`/g, " ");
566
+ const spoken = bare.replace(/\b[ei]\.(?:g|e)\./gi, "eg");
567
+ const found = [...spoken.matchAll(/[.!?](?=\s|$)|[。!?]/g)].length;
568
+ if (found === 0)
569
+ continue;
570
+ if (terminators < 2 && terminators + found >= 2 && extraLine === -1) {
571
+ extraLine = line;
572
+ }
573
+ terminators += found;
574
+ }
575
+ if (terminators > 1) {
576
+ report(ctx, item.file.relPath, extraLine, "warning", "item/sentence", `item ${item.id} carries more than one sentence; review it for a second governing statement (meta-29)`);
577
+ }
578
+ }
579
+ }
580
+ function lintCitationDiscipline(ctx, items) {
581
+ for (const file of ctx.files.values()) {
582
+ if (!isUnder(file.relPath, "packages"))
583
+ continue;
584
+ // A package Intent is self-contained prose (meta-15): no
585
+ // citation links, no reference markers (lint-13).
586
+ const h2s = file.headings.filter((heading) => heading.depth === 2 && heading.root);
587
+ const intentRanges = [];
588
+ for (const [index, heading] of h2s.entries()) {
589
+ if (SECTION_BY_NAME.get(heading.plain.trim()) !== "Intent")
590
+ continue;
591
+ intentRanges.push({
592
+ start: heading.line,
593
+ end: h2s[index + 1]?.line ?? file.lines.length + 1,
594
+ });
595
+ }
596
+ for (const range of intentRanges) {
597
+ for (const link of file.links) {
598
+ if (link.kind !== "link")
599
+ continue;
600
+ if (link.line > range.start && link.line < range.end) {
601
+ report(ctx, file.relPath, link.line, "error", "intent/cited", "the Intent section carries a citation; a package reads standalone (meta-15)");
602
+ }
603
+ }
604
+ for (const use of file.referenceUses) {
605
+ if (use.line > range.start && use.line < range.end) {
606
+ report(ctx, file.relPath, use.line, "error", "intent/cited", "the Intent section carries a reference marker; a package reads standalone (meta-15)");
607
+ }
608
+ }
609
+ }
610
+ // Item statements are the single relationship source (meta-14):
611
+ // a peer-package link from section prose outside every item
612
+ // body declares no dependency (lint-13). Intent links are
613
+ // skipped here — they carry intent/cited already.
614
+ const itemRanges = items
615
+ .filter((item) => item.file === file)
616
+ .map((item) => ({ start: item.heading.line, end: item.bodyEnd }));
617
+ for (const link of file.links) {
618
+ if (link.kind !== "link")
619
+ continue;
620
+ const within = (range) => link.line >= range.start && link.line < range.end;
621
+ if (itemRanges.some(within) || intentRanges.some(within))
622
+ continue;
623
+ const resolved = resolveCitation(file, link.url);
624
+ if (resolved === null ||
625
+ resolved === file.relPath ||
626
+ !resolved.startsWith("specs/packages/")) {
627
+ continue;
628
+ }
629
+ report(ctx, file.relPath, link.line, "error", "cite/prose", "section prose cites a peer package; item statements are the single relationship source (meta-14)");
630
+ }
631
+ // Reference-style links dodge the citation rules, so package
632
+ // files use inline citations only (meta-16); literal [[N]]
633
+ // markers stay reserved for ## References (meta-19, lint-8).
634
+ for (const reference of file.referenceLinks) {
635
+ report(ctx, file.relPath, reference.line, "error", "cite/reference-style", "reference-style links are not citations; use an inline link (meta-16)");
636
+ }
637
+ }
638
+ }
639
+ // ---------------------------------------------------------------
640
+ // Citation rules (lint-8)
641
+ // ---------------------------------------------------------------
642
+ function lintCitations(ctx, items) {
643
+ const bySlug = itemsBySlug(items);
644
+ for (const file of ctx.files.values()) {
645
+ // Naming an IR in prose is citing it, and no DR or spec item
646
+ // does either (meta-18) — so the check binds decisions/,
647
+ // packages/, and meta.md alone; intent records and map.md sit
648
+ // outside the prohibition. Matched over parsed inline text, so
649
+ // inline code and code blocks cannot trip it (lint-10).
650
+ if (boundByIrProhibition(file.relPath)) {
651
+ for (const span of file.texts) {
652
+ for (const [offset, value] of span.value.split("\n").entries()) {
653
+ for (const match of value.matchAll(/\bIR-\d+\b/g)) {
654
+ report(ctx, file.relPath, span.line + offset, "error", "cite/intent", `no DR or spec item names an IR in prose (meta-18): ${match[0]}`);
655
+ }
656
+ }
657
+ }
658
+ }
659
+ const fileDir = posix.dirname(file.relPath);
660
+ for (const link of file.links) {
661
+ const url = link.url;
662
+ // Scheme, protocol-relative, and absolute URLs are unchecked.
663
+ if (url === "" || SCHEME_RE.test(url) || url.startsWith("//"))
664
+ continue;
665
+ if (url.startsWith("/"))
666
+ continue;
667
+ const [path, ...fragmentParts] = url.split("#");
668
+ const fragment = fragmentParts.join("#");
669
+ if (path === "") {
670
+ if (fragment !== "" && !file.slugs.has(fragment)) {
671
+ report(ctx, file.relPath, link.line, "error", "cite/broken-anchor", `anchor #${fragment} not found in this file`);
672
+ }
673
+ else {
674
+ lintItemCitationForm(ctx, file, link, file.relPath, fragment, bySlug);
675
+ }
676
+ continue;
677
+ }
678
+ const resolved = posix.normalize(posix.join(fileDir, path));
679
+ if (!resolved.startsWith("specs/")) {
680
+ // Links out of specs/ (e.g. ../README.md): existence only.
681
+ if (!existsSync(join(ctx.basePath, resolved))) {
682
+ report(ctx, file.relPath, link.line, "error", "cite/broken-link", `link target ${resolved} does not exist`);
683
+ }
684
+ continue;
685
+ }
686
+ if (LEGACY_PATH_RE.test(resolved)) {
687
+ report(ctx, file.relPath, link.line, "error", "cite/legacy-path", `link points into the legacy layout (${resolved}); cite the current layout of meta-1 instead`);
688
+ continue;
689
+ }
690
+ if ((resolved.startsWith("specs/intents/") ||
691
+ resolved.startsWith("specs/iterations/")) &&
692
+ boundByIrProhibition(file.relPath)) {
693
+ report(ctx, file.relPath, link.line, "error", "cite/intent", `no DR or spec item cites an IR (meta-18)`);
694
+ }
695
+ if (!existsSync(join(ctx.basePath, resolved))) {
696
+ report(ctx, file.relPath, link.line, "error", "cite/broken-link", `link target ${resolved} does not exist`);
697
+ continue;
698
+ }
699
+ if (fragment !== "" && resolved.endsWith(".md")) {
700
+ const target = ctx.files.get(resolved);
701
+ if (target !== undefined && !target.slugs.has(fragment)) {
702
+ report(ctx, file.relPath, link.line, "error", "cite/broken-anchor", `anchor #${fragment} not found in ${resolved}`);
703
+ continue;
704
+ }
705
+ lintItemCitationForm(ctx, file, link, resolved, fragment, bySlug);
706
+ }
707
+ }
708
+ }
709
+ }
710
+ /**
711
+ * An item citation is an enclosed inline link whose link text is
712
+ * the target item ID — `[[<pack>-<N>](<path>#<pack>-<N>)]`
713
+ * (meta-16, meta-11, lint-8).
714
+ */
715
+ function lintItemCitationForm(ctx, file, link, targetPath, fragment, bySlug) {
716
+ if (link.kind !== "link" || fragment === "")
717
+ return;
718
+ const target = bySlug.get(targetPath)?.get(fragment);
719
+ if (target === undefined)
720
+ return;
721
+ if (!link.enclosed) {
722
+ report(ctx, file.relPath, link.line, "error", "cite/item-link", `citation of ${target.id} is not an enclosed inline link; write it as [[${target.id}](<path>#${target.heading.slug})] (meta-16)`);
723
+ }
724
+ if (link.text !== target.id) {
725
+ report(ctx, file.relPath, link.line, "error", "cite/item-link", `citation text "${link.text}" is not the target item ID ${target.id} (meta-11)`);
726
+ }
727
+ }
728
+ // ---------------------------------------------------------------
729
+ // Reference-marker rules (lint-9, meta-19)
730
+ // ---------------------------------------------------------------
731
+ function lintReferences(ctx) {
732
+ for (const file of ctx.files.values()) {
733
+ // The ## References ranges: numbered definitions live there and
734
+ // nowhere else, pointing outward (meta-19).
735
+ const h2s = file.headings.filter((heading) => heading.depth === 2 && heading.root);
736
+ const referencesRanges = h2s
737
+ .map((heading, index) => ({ heading, next: h2s[index + 1] }))
738
+ .filter(({ heading }) => SECTION_BY_NAME.get(heading.plain.trim()) === "References")
739
+ .map(({ heading, next }) => ({
740
+ start: heading.line,
741
+ end: next?.line ?? file.lines.length + 1,
742
+ }));
743
+ const defined = new Set();
744
+ const used = new Set();
745
+ const definitionLines = new Map();
746
+ visit(file.tree, (node) => {
747
+ if (node.type === "definition") {
748
+ const definition = node;
749
+ if (/^\d+$/.test(definition.identifier)) {
750
+ const line = node.position?.start.line ?? 1;
751
+ defined.add(definition.identifier);
752
+ definitionLines.set(definition.identifier, line);
753
+ if (!referencesRanges.some((range) => line > range.start && line < range.end)) {
754
+ report(ctx, file.relPath, line, "error", "refs/definition", `numbered definition [${definition.identifier}] sits outside ## References (meta-19)`);
755
+ }
756
+ if (!SCHEME_RE.test(definition.url) &&
757
+ !definition.url.startsWith("//")) {
758
+ report(ctx, file.relPath, line, "error", "refs/definition", `numbered definition [${definition.identifier}] targets "${definition.url}"; reference markers point at external URLs — item citations are inline links (meta-19, meta-16)`);
759
+ }
760
+ }
761
+ }
762
+ if (node.type === "linkReference" || node.type === "imageReference") {
763
+ const identifier = node
764
+ .identifier;
765
+ if (/^\d+$/.test(identifier))
766
+ used.add(identifier);
767
+ }
768
+ });
769
+ // Undefined [[N]] markers stay literal text (no linkReference is
770
+ // materialized without a matching definition).
771
+ visit(file.tree, (node) => {
772
+ if (node.type !== "text")
773
+ return;
774
+ const value = node.value;
775
+ for (const match of value.matchAll(/\[\[(\d+)\]\]/g)) {
776
+ if (!defined.has(match[1])) {
777
+ report(ctx, file.relPath, node.position?.start.line ?? 1, "error", "refs/undefined", `reference marker [[${match[1]}]] has no definition in ## References (meta-19)`);
778
+ }
779
+ }
780
+ });
781
+ for (const identifier of defined) {
782
+ if (!used.has(identifier)) {
783
+ report(ctx, file.relPath, definitionLines.get(identifier) ?? 1, "warning", "refs/unused", `reference [${identifier}] is defined but never cited (meta-19)`);
784
+ }
785
+ }
786
+ }
787
+ }
788
+ // ---------------------------------------------------------------
789
+ // Record rules (lint-4, lint-9)
790
+ // ---------------------------------------------------------------
791
+ function lintRecords(ctx) {
792
+ // A record's ID is its filename's leading number (meta-22), so
793
+ // two differently named files on the same number are one ID —
794
+ // decisions/ for DRs, intents/ with legacy iterations/ for IRs.
795
+ const firstById = new Map();
796
+ for (const file of ctx.files.values()) {
797
+ const isDr = isUnder(file.relPath, "decisions");
798
+ const isIr = isUnder(file.relPath, "intents") || isUnder(file.relPath, "iterations");
799
+ if (!isDr && !isIr)
800
+ continue;
801
+ const digits = /^(\d+)/.exec(posix.basename(file.relPath))?.[1];
802
+ if (digits !== undefined) {
803
+ const id = `${isDr ? "DR" : "IR"}-${digits}`;
804
+ const first = firstById.get(id);
805
+ if (first === undefined) {
806
+ firstById.set(id, file.relPath);
807
+ }
808
+ else {
809
+ report(ctx, file.relPath, 1, "error", "record/duplicate-id", `record ID ${id} is already defined by ${first} (meta-22)`);
810
+ }
811
+ }
812
+ const sections = isDr ? DR_SECTIONS : IR_SECTIONS;
813
+ const h2s = new Set(file.headings
814
+ .filter((heading) => heading.depth === 2 && heading.root)
815
+ .map((heading) => heading.plain.trim()));
816
+ for (const [canonical, names] of Object.entries(sections)) {
817
+ if (!names.some((name) => h2s.has(name))) {
818
+ report(ctx, file.relPath, 1, "warning", "record/sections", `${isDr ? "DR" : "IR"} is missing a "## ${canonical}" section (${isDr ? "meta-4" : "meta-5"})`);
819
+ }
820
+ }
821
+ }
822
+ }
823
+ // ---------------------------------------------------------------
824
+ // Map + anchor rules (lint-8, lint-9)
825
+ // ---------------------------------------------------------------
826
+ function lintMap(ctx) {
827
+ const map = ctx.files.get("specs/map.md");
828
+ if (map === undefined)
829
+ return;
830
+ const listed = new Set();
831
+ for (const link of map.links) {
832
+ const url = link.url;
833
+ if (url === "" || SCHEME_RE.test(url) || url.startsWith("/"))
834
+ continue;
835
+ listed.add(posix.normalize(posix.join("specs", url.split("#")[0])));
836
+ }
837
+ for (const file of ctx.files.values()) {
838
+ if (!isUnder(file.relPath, "packages"))
839
+ continue;
840
+ if (!listed.has(file.relPath)) {
841
+ report(ctx, file.relPath, 1, "warning", "map/unlisted", `${file.relPath} is not linked from specs/map.md`);
842
+ }
843
+ }
844
+ }
845
+ function lintAnchors(ctx) {
846
+ for (const file of ctx.files.values()) {
847
+ // Base slugs are computed without -N dedupe counters, so a
848
+ // repeated value is a genuine heading collision (item IDs ending
849
+ // in -N cannot false-positive).
850
+ const counts = new Map();
851
+ for (const slug of baseHeadingSlugs(file.text, file.tree)) {
852
+ counts.set(slug, (counts.get(slug) ?? 0) + 1);
853
+ }
854
+ for (const [slug, count] of counts) {
855
+ if (count > 1) {
856
+ report(ctx, file.relPath, 1, "warning", "anchors/duplicate", `duplicate heading anchor #${slug}; citations to it are ambiguous`);
857
+ }
858
+ }
859
+ }
860
+ }
861
+ // ---------------------------------------------------------------
862
+ // Entry points
863
+ // ---------------------------------------------------------------
864
+ /** Lint the specs tree under basePath (lint-10). */
865
+ export function lintSpecs(basePath) {
866
+ const specsDir = join(basePath, "specs");
867
+ if (!existsSync(specsDir) || !statSync(specsDir).isDirectory()) {
868
+ return [
869
+ {
870
+ path: "specs",
871
+ line: 1,
872
+ severity: "error",
873
+ rule: "structure/missing-file",
874
+ message: `no specs/ directory found at ${basePath}`,
875
+ },
876
+ ];
877
+ }
878
+ const ctx = {
879
+ basePath,
880
+ files: new Map(),
881
+ findings: [],
882
+ };
883
+ for (const relPath of listMarkdownFiles(specsDir, "specs")) {
884
+ ctx.files.set(relPath, loadFile(basePath, relPath));
885
+ }
886
+ lintStructure(ctx);
887
+ lintNaming(ctx);
888
+ for (const file of ctx.files.values()) {
889
+ // specs/meta.md and specs/map.md live outside packages/ and are
890
+ // exempt from the package-file rules (lint-5).
891
+ if (isUnder(file.relPath, "packages"))
892
+ lintPackageFile(ctx, file);
893
+ }
894
+ const items = collectItems(ctx);
895
+ lintItems(ctx, items);
896
+ lintItemRelationships(ctx, items);
897
+ lintCitationDiscipline(ctx, items);
898
+ lintCitations(ctx, items);
899
+ lintReferences(ctx);
900
+ lintRecords(ctx);
901
+ lintMap(ctx);
902
+ lintAnchors(ctx);
903
+ ctx.findings.sort((a, b) => a.path.localeCompare(b.path) ||
904
+ a.line - b.line ||
905
+ a.rule.localeCompare(b.rule));
906
+ return ctx.findings;
907
+ }
908
+ /**
909
+ * The path prefix findings are printed under: the base path
910
+ * relative to the working directory, canonicalized on both sides
911
+ * so Windows 8.3 short names and symlinks cannot fake a
912
+ * difference, and always in forward slashes (lint-3).
913
+ */
914
+ function relativeToCwd(basePath) {
915
+ const canonical = (path) => {
916
+ try {
917
+ return realpathSync.native(path);
918
+ }
919
+ catch {
920
+ return path;
921
+ }
922
+ };
923
+ const rel = relative(canonical(process.cwd()), canonical(basePath));
924
+ if (rel === "")
925
+ return ".";
926
+ return rel.split(sep).join("/");
927
+ }
928
+ /**
929
+ * Entry point for the lint subcommand. Prints findings and exits
930
+ * non-zero when any error-severity finding exists (lint-1..3).
931
+ */
932
+ export function lint(args = []) {
933
+ try {
934
+ if (args.some((arg) => arg.startsWith("-"))) {
935
+ throw new Error(`Unknown option: ${args.find((a) => a.startsWith("-"))}`);
936
+ }
937
+ if (args.length > 1) {
938
+ throw new Error(`Unexpected arguments: ${args.slice(1).join(" ")}`);
939
+ }
940
+ // Same resolution as scaffold create: explicit path, else git
941
+ // root, else cwd.
942
+ const basePath = resolveBase(args[0]);
943
+ const findings = lintSpecs(basePath);
944
+ const prefix = relativeToCwd(basePath);
945
+ for (const finding of findings) {
946
+ const path = prefix === "." ? finding.path : posix.join(prefix, finding.path);
947
+ console.log(`${path}:${finding.line}: ${finding.severity} ${finding.rule}: ${finding.message}`);
948
+ }
949
+ const errors = findings.filter((f) => f.severity === "error").length;
950
+ const warnings = findings.length - errors;
951
+ if (findings.length === 0) {
952
+ console.log("spex lint: no problems found");
953
+ }
954
+ else {
955
+ console.log("");
956
+ console.log(`spex lint: ${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"}`);
957
+ }
958
+ if (errors > 0)
959
+ process.exit(1);
960
+ }
961
+ catch (err) {
962
+ const msg = err instanceof Error ? err.message : String(err);
963
+ console.error(`spex lint: ${msg}`);
964
+ process.exit(1);
965
+ }
966
+ }
967
+ //# sourceMappingURL=lint.js.map