specdx 0.4.0-alpha.9 → 0.5.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.
Files changed (115) hide show
  1. package/.claude-plugin/plugin.json +7 -2
  2. package/README.md +283 -0
  3. package/dist/{check-4FSSC6HN.js → check-RH5SCXWW.js} +68 -30
  4. package/dist/check-RH5SCXWW.js.map +1 -0
  5. package/dist/{chunk-N77RNV7J.js → chunk-3YXRWQGX.js} +217 -42
  6. package/dist/chunk-3YXRWQGX.js.map +1 -0
  7. package/dist/chunk-5WRI5ZAA.js +31 -0
  8. package/dist/chunk-6EQIDZ4D.js +185 -0
  9. package/dist/chunk-6EQIDZ4D.js.map +1 -0
  10. package/dist/chunk-6WFNZH7F.js +2846 -0
  11. package/dist/chunk-6WFNZH7F.js.map +1 -0
  12. package/dist/{chunk-AKNPCB37.js → chunk-BMOOLUPG.js} +32 -12
  13. package/dist/chunk-BMOOLUPG.js.map +1 -0
  14. package/dist/{chunk-IHTYAW7C.js → chunk-BP3SB35W.js} +111 -7
  15. package/dist/chunk-BP3SB35W.js.map +1 -0
  16. package/dist/chunk-CQETLJTZ.js +103 -0
  17. package/dist/chunk-CQETLJTZ.js.map +1 -0
  18. package/dist/chunk-DMGABJ6T.js +41 -0
  19. package/dist/chunk-DMGABJ6T.js.map +1 -0
  20. package/dist/chunk-NHD44ZYN.js +20 -0
  21. package/dist/chunk-NHD44ZYN.js.map +1 -0
  22. package/dist/{chunk-7JXW2GTJ.js → chunk-XRWLPU24.js} +18 -2
  23. package/dist/chunk-XRWLPU24.js.map +1 -0
  24. package/dist/chunk-ZIODMXST.js +1146 -0
  25. package/dist/chunk-ZIODMXST.js.map +1 -0
  26. package/dist/diff-QO7HMAK3.js +200 -0
  27. package/dist/diff-QO7HMAK3.js.map +1 -0
  28. package/dist/{dist-4DIRTBJH.js → dist-JPWHWMV2.js} +88 -26
  29. package/dist/dist-JPWHWMV2.js.map +1 -0
  30. package/dist/{dist-RL2DT3ZE.js → dist-ROHCFKYT.js} +3 -2
  31. package/dist/dist-ROHCFKYT.js.map +1 -0
  32. package/dist/generate-MS4BM7RU.js +21 -0
  33. package/dist/generate-MS4BM7RU.js.map +1 -0
  34. package/dist/{generate-story-EFHGINHA.js → generate-story-OMM322L7.js} +43 -19
  35. package/dist/generate-story-OMM322L7.js.map +1 -0
  36. package/dist/{generate-test-plan-BO7444RG.js → generate-test-plan-75W7SZIO.js} +61 -11
  37. package/dist/generate-test-plan-75W7SZIO.js.map +1 -0
  38. package/dist/{graph-5XINV7PT.js → graph-QOTMXENE.js} +49 -11
  39. package/dist/graph-QOTMXENE.js.map +1 -0
  40. package/dist/index.d.ts +302 -0
  41. package/dist/index.js +2996 -357
  42. package/dist/index.js.map +1 -1
  43. package/dist/lint-LPFLHVO4.js +184 -0
  44. package/dist/lint-LPFLHVO4.js.map +1 -0
  45. package/dist/main.js +10 -229
  46. package/dist/main.js.map +1 -1
  47. package/dist/mcp-OEC43SPF.js +35 -0
  48. package/dist/mcp-OEC43SPF.js.map +1 -0
  49. package/dist/{migrate-4KF6GHLO.js → migrate-CBP2AVLH.js} +21 -9
  50. package/dist/migrate-CBP2AVLH.js.map +1 -0
  51. package/dist/{pack-DSOODXAN.js → pack-X6FSWORJ.js} +41 -13
  52. package/dist/pack-X6FSWORJ.js.map +1 -0
  53. package/dist/{ready-6DNKIHP6.js → ready-7MJWRGLT.js} +55 -14
  54. package/dist/ready-7MJWRGLT.js.map +1 -0
  55. package/dist/skills/{specdx-author-spec.md → core/specdx-author-spec/SKILL.md} +10 -6
  56. package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-01-frontmatter.md +1 -1
  57. package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-02-sections.md +41 -0
  58. package/dist/skills/{specdx-onboard.md → core/specdx-onboard/SKILL.md} +8 -3
  59. package/dist/skills/{specdx-plan-from-spec.md → core/specdx-plan-from-spec/SKILL.md} +5 -1
  60. package/dist/skills/{specdx-pre-commit.md → core/specdx-pre-commit/SKILL.md} +16 -2
  61. package/dist/skills/{specdx-review-spec.md → core/specdx-review-spec/SKILL.md} +5 -1
  62. package/dist/skills/core/specdx-router/SKILL.md +67 -0
  63. package/dist/skills/{specdx-sprint-review.md → core/specdx-sprint-review/SKILL.md} +6 -2
  64. package/dist/skills/{specdx-start-task.md → core/specdx-start-task/SKILL.md} +5 -1
  65. package/dist/skills/{specdx-check-drift.md → experimental/specdx-check-drift/SKILL.md} +10 -4
  66. package/dist/skills/{specdx-verify.md → experimental/specdx-verify/SKILL.md} +6 -2
  67. package/dist/skills-36SRUEMR.js +121 -0
  68. package/dist/skills-36SRUEMR.js.map +1 -0
  69. package/dist/{status-WZK247CI.js → status-UUPZYX3J.js} +63 -32
  70. package/dist/status-UUPZYX3J.js.map +1 -0
  71. package/dist/{update-JTNSYX3B.js → update-EI7IJRHG.js} +22 -12
  72. package/dist/update-EI7IJRHG.js.map +1 -0
  73. package/dist/{validate-LBDYWUDX.js → validate-HTTZLQWI.js} +36 -17
  74. package/dist/validate-HTTZLQWI.js.map +1 -0
  75. package/hooks/hooks.json +12 -6
  76. package/hooks/session-start +35 -3
  77. package/package.json +28 -13
  78. package/dist/changelog-XUVHY3QK.js +0 -93
  79. package/dist/changelog-XUVHY3QK.js.map +0 -1
  80. package/dist/check-4FSSC6HN.js.map +0 -1
  81. package/dist/chunk-7JXW2GTJ.js.map +0 -1
  82. package/dist/chunk-AKNPCB37.js.map +0 -1
  83. package/dist/chunk-DAZCOUVK.js +0 -496
  84. package/dist/chunk-DAZCOUVK.js.map +0 -1
  85. package/dist/chunk-GAM4MXPC.js +0 -15
  86. package/dist/chunk-GAM4MXPC.js.map +0 -1
  87. package/dist/chunk-IHTYAW7C.js.map +0 -1
  88. package/dist/chunk-N77RNV7J.js.map +0 -1
  89. package/dist/chunk-SRZ33RJP.js +0 -1147
  90. package/dist/chunk-SRZ33RJP.js.map +0 -1
  91. package/dist/diff-OXZ34NU4.js +0 -107
  92. package/dist/diff-OXZ34NU4.js.map +0 -1
  93. package/dist/dist-4DIRTBJH.js.map +0 -1
  94. package/dist/explain-QBV3AESQ.js +0 -109
  95. package/dist/explain-QBV3AESQ.js.map +0 -1
  96. package/dist/generate-7GNPT2WJ.js +0 -13
  97. package/dist/generate-7GNPT2WJ.js.map +0 -1
  98. package/dist/generate-story-EFHGINHA.js.map +0 -1
  99. package/dist/generate-test-plan-BO7444RG.js.map +0 -1
  100. package/dist/graph-5XINV7PT.js.map +0 -1
  101. package/dist/lint-PTMWMLDQ.js +0 -122
  102. package/dist/lint-PTMWMLDQ.js.map +0 -1
  103. package/dist/mcp-BGFAPM6G.js +0 -17
  104. package/dist/mcp-BGFAPM6G.js.map +0 -1
  105. package/dist/migrate-4KF6GHLO.js.map +0 -1
  106. package/dist/pack-DSOODXAN.js.map +0 -1
  107. package/dist/ready-6DNKIHP6.js.map +0 -1
  108. package/dist/skills-3GBBWZW2.js +0 -93
  109. package/dist/skills-3GBBWZW2.js.map +0 -1
  110. package/dist/status-WZK247CI.js.map +0 -1
  111. package/dist/update-JTNSYX3B.js.map +0 -1
  112. package/dist/validate-LBDYWUDX.js.map +0 -1
  113. /package/dist/{dist-RL2DT3ZE.js.map → chunk-5WRI5ZAA.js.map} +0 -0
  114. /package/dist/skills/{spec-type-reference.md → core/specdx-author-spec/references/spec-type-reference.md} +0 -0
  115. /package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-03-finalize.md +0 -0
@@ -0,0 +1,1146 @@
1
+ import {
2
+ buildRelationResolver,
3
+ countTokens,
4
+ resolveGlob
5
+ } from "./chunk-BP3SB35W.js";
6
+ import {
7
+ REQUIRED_SECTIONS
8
+ } from "./chunk-XRWLPU24.js";
9
+
10
+ // ../lint/dist/engine.js
11
+ function createLintEngine(options) {
12
+ return {
13
+ lint(specs) {
14
+ const diagnostics = [];
15
+ const ignored = new Set(options.ignore ?? []);
16
+ for (const spec of specs) {
17
+ if (ignored.has(spec.filePath))
18
+ continue;
19
+ for (const rule of options.rules) {
20
+ const results = rule.run({
21
+ spec,
22
+ allSpecs: specs,
23
+ config: options.config,
24
+ graph: options.graph
25
+ });
26
+ for (const diagnostic of results) {
27
+ if (ignored.has(diagnostic.filePath))
28
+ continue;
29
+ diagnostics.push({ ...diagnostic, severity: rule.severity });
30
+ }
31
+ }
32
+ }
33
+ return {
34
+ diagnostics,
35
+ hasErrors: diagnostics.some((d) => d.severity === "error"),
36
+ hasWarnings: diagnostics.some((d) => d.severity === "warn")
37
+ };
38
+ }
39
+ };
40
+ }
41
+
42
+ // ../lint/dist/rules/story-coverage.js
43
+ var STOPWORDS = /* @__PURE__ */ new Set([
44
+ "a",
45
+ "an",
46
+ "the",
47
+ "and",
48
+ "or",
49
+ "of",
50
+ "to",
51
+ "for",
52
+ "with",
53
+ "its",
54
+ "it",
55
+ "in",
56
+ "on",
57
+ "at",
58
+ "by",
59
+ "from",
60
+ "into",
61
+ "every",
62
+ "each",
63
+ "that",
64
+ "this",
65
+ "be",
66
+ "is",
67
+ "are",
68
+ "as",
69
+ "can",
70
+ "will",
71
+ "must",
72
+ "so",
73
+ "their",
74
+ "them",
75
+ "when",
76
+ "which",
77
+ "who"
78
+ ]);
79
+ var OVERLAP_THRESHOLD = 0.5;
80
+ var REFERENCED_THRESHOLD = 0.34;
81
+ function tokenise(text) {
82
+ const words = text.toLowerCase().replace(/[^a-z0-9\s-]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !STOPWORDS.has(w)).map((w) => w.length > 3 && w.endsWith("s") && !w.endsWith("ss") ? w.slice(0, -1) : w);
83
+ return new Set(words);
84
+ }
85
+ function extractFeatureSection(content) {
86
+ const lines = content.split("\n");
87
+ const start = lines.findIndex((l) => /^##\s+Features\s*$/.test(l.trim()));
88
+ if (start === -1)
89
+ return null;
90
+ const body = [];
91
+ for (let i = start + 1; i < lines.length; i++) {
92
+ if (/^##\s/.test(lines[i]))
93
+ break;
94
+ body.push(lines[i]);
95
+ }
96
+ return body.join("\n");
97
+ }
98
+ function parseFeatures(content) {
99
+ return parseFeatureEntries(content).map((f) => f.text);
100
+ }
101
+ function parseFeatureEntries(content) {
102
+ const section = extractFeatureSection(content);
103
+ if (section === null)
104
+ return [];
105
+ const ID_PREFIX = /^\*{0,2}F(\d+)\*{0,2}\s*[:.-]\s*/i;
106
+ const features = [];
107
+ for (const rawLine of section.split("\n")) {
108
+ const line = rawLine.trim();
109
+ if (!line)
110
+ continue;
111
+ const bullet = /^[-*]\s+(.*)$/.exec(line);
112
+ const text = bullet ? (bullet[1] ?? "").trim() : ID_PREFIX.test(line) ? line : "";
113
+ if (!text)
114
+ continue;
115
+ const idMatch = ID_PREFIX.exec(text);
116
+ const stripped = text.replace(ID_PREFIX, "").trim();
117
+ if (stripped)
118
+ features.push({ text: stripped, num: idMatch?.[1] });
119
+ }
120
+ return features;
121
+ }
122
+ function overlap(featureTokens, storyTokens) {
123
+ if (featureTokens.size === 0)
124
+ return 0;
125
+ let shared = 0;
126
+ for (const token of featureTokens)
127
+ if (storyTokens.has(token))
128
+ shared++;
129
+ return shared / featureTokens.size;
130
+ }
131
+ function referencesSpec(story, specId) {
132
+ const refs = story.frontmatter.references;
133
+ if (!Array.isArray(refs))
134
+ return false;
135
+ return refs.some((r) => r?.id === specId);
136
+ }
137
+ function uncoveredFeatures(features, stories, prdId) {
138
+ const scored = stories.map((story) => ({
139
+ tokens: tokenise(`${String(story.frontmatter.title ?? "")} ${story.content}`),
140
+ threshold: referencesSpec(story, prdId) ? REFERENCED_THRESHOLD : OVERLAP_THRESHOLD
141
+ }));
142
+ const tokenised = features.map(tokenise);
143
+ return features.filter((_feature, i) => {
144
+ const featureTokens = tokenised[i];
145
+ const distinctive = distinctiveTokens(featureTokens, tokenised, i);
146
+ return !scored.some((s) => overlap(featureTokens, s.tokens) >= s.threshold && covers(distinctive, featureTokens, s.tokens));
147
+ });
148
+ }
149
+ function covers(distinctive, featureTokens, storyTokens) {
150
+ if (distinctive.size === 0 || distinctive.size === featureTokens.size)
151
+ return true;
152
+ let matched = 0;
153
+ for (const token of distinctive)
154
+ if (storyTokens.has(token))
155
+ matched++;
156
+ return matched > distinctive.size / 2;
157
+ }
158
+ function distinctiveTokens(featureTokens, allFeatureTokens, index) {
159
+ const distinctive = new Set(featureTokens);
160
+ for (let i = 0; i < allFeatureTokens.length; i++) {
161
+ if (i === index)
162
+ continue;
163
+ for (const token of allFeatureTokens[i])
164
+ distinctive.delete(token);
165
+ }
166
+ return distinctive;
167
+ }
168
+ var storyCoverageRule = {
169
+ id: "completeness/story-coverage",
170
+ description: "Every feature listed in a PRD has at least one corresponding user story",
171
+ severity: "warn",
172
+ run(context) {
173
+ if (context.spec.frontmatter.type !== "prd")
174
+ return [];
175
+ const features = parseFeatures(context.spec.content);
176
+ if (features.length === 0)
177
+ return [];
178
+ const stories = context.allSpecs.filter((s) => s.frontmatter.type === "user-story");
179
+ return uncoveredFeatures(features, stories, context.spec.frontmatter.id).map((feature) => ({
180
+ ruleId: "completeness/story-coverage",
181
+ severity: "warn",
182
+ message: `Feature "${feature}" has no corresponding user story`,
183
+ filePath: context.spec.filePath
184
+ }));
185
+ }
186
+ };
187
+
188
+ // ../lint/dist/resolve-lint-config.js
189
+ import { isAbsolute, resolve } from "path";
190
+
191
+ // ../lint/dist/rules/valid-frontmatter.js
192
+ function readablePath(instancePath) {
193
+ return instancePath.split("/").filter(Boolean).map((segment) => /^\d+$/.test(segment) ? `[${segment}]` : `.${segment}`).join("").replace(/^\./, "");
194
+ }
195
+ function describeValidationError(err) {
196
+ const path = readablePath(err.instancePath ?? "");
197
+ const allowed = err.params?.allowedValues;
198
+ let detail = err.message ?? JSON.stringify(err);
199
+ if (Array.isArray(allowed) && allowed.length > 0) {
200
+ detail += `: ${allowed.map((v) => JSON.stringify(v)).join(", ")}`;
201
+ }
202
+ return path ? `${path} ${detail}` : detail;
203
+ }
204
+ var validFrontmatterRule = {
205
+ id: "structure/valid-frontmatter",
206
+ description: "Frontmatter matches the schema for the declared spec type",
207
+ severity: "error",
208
+ run(context) {
209
+ if (context.spec.valid)
210
+ return [];
211
+ const errors = context.spec.validationErrors ?? [];
212
+ return errors.map((err) => ({
213
+ ruleId: "structure/valid-frontmatter",
214
+ severity: "error",
215
+ message: `Invalid frontmatter: ${describeValidationError(err)}`,
216
+ filePath: context.spec.filePath
217
+ }));
218
+ }
219
+ };
220
+
221
+ // ../lint/dist/rules/required-sections.js
222
+ var requiredSectionsRule = {
223
+ id: "structure/required-sections",
224
+ description: "Spec body contains all required sections for its type",
225
+ severity: "error",
226
+ run(context) {
227
+ const ext = context.spec.filePath.split(".").pop()?.toLowerCase();
228
+ if (ext === "yaml" || ext === "yml")
229
+ return [];
230
+ const specType = context.spec.frontmatter.type;
231
+ const required = REQUIRED_SECTIONS[specType];
232
+ if (!required)
233
+ return [];
234
+ const missing = required.filter((s) => !context.spec.sections.includes(s));
235
+ return missing.map((section) => ({
236
+ ruleId: "structure/required-sections",
237
+ severity: "error",
238
+ message: `Missing required section: "${section}"`,
239
+ filePath: context.spec.filePath,
240
+ section
241
+ }));
242
+ }
243
+ };
244
+
245
+ // ../lint/dist/rules/valid-references.js
246
+ var validReferencesRule = {
247
+ id: "structure/valid-references",
248
+ description: "All references in frontmatter point to specs that exist in the suite",
249
+ severity: "error",
250
+ run(context) {
251
+ const refs = context.spec.frontmatter.references;
252
+ if (!refs || refs.length === 0)
253
+ return [];
254
+ const allIds = new Set(context.allSpecs.map((s) => s.frontmatter.id));
255
+ return refs.filter((ref) => !allIds.has(ref.id)).map((ref) => ({
256
+ ruleId: "structure/valid-references",
257
+ severity: "error",
258
+ message: `Reference "${ref.id}" does not match any spec in the suite`,
259
+ filePath: context.spec.filePath
260
+ }));
261
+ }
262
+ };
263
+
264
+ // ../lint/dist/rules/no-circular-deps.js
265
+ var noCircularDepsRule = {
266
+ id: "structure/no-circular-deps",
267
+ description: "The dependency graph has no cycles",
268
+ severity: "error",
269
+ run() {
270
+ return [];
271
+ }
272
+ };
273
+
274
+ // ../lint/dist/rules/staleness-check.js
275
+ function groupByEntry(config, specs) {
276
+ const byEntry = /* @__PURE__ */ new Map();
277
+ for (const key of Object.keys(config.specs))
278
+ byEntry.set(key, []);
279
+ for (const spec of specs) {
280
+ let bestKey;
281
+ let bestLen = -1;
282
+ for (const [key, entry] of Object.entries(config.specs)) {
283
+ const prefix = entry.path.split("*")[0] ?? "";
284
+ const normalized = spec.filePath.replace(/\\/g, "/");
285
+ if (normalized.includes(prefix) && prefix.length > bestLen) {
286
+ bestKey = key;
287
+ bestLen = prefix.length;
288
+ }
289
+ }
290
+ if (bestKey)
291
+ byEntry.get(bestKey).push(spec);
292
+ }
293
+ return byEntry;
294
+ }
295
+ function lastUpdated(spec) {
296
+ return spec.frontmatter.updated ?? spec.frontmatter.created ?? "";
297
+ }
298
+ var stalenessCheckRule = {
299
+ id: "freshness/staleness-check",
300
+ description: "Warns if a spec hasn't been updated since its upstream dependency changed",
301
+ severity: "warn",
302
+ run(context) {
303
+ const specId = context.spec.frontmatter.id;
304
+ if (typeof specId !== "string")
305
+ return [];
306
+ const specUpdated = lastUpdated(context.spec);
307
+ if (!specUpdated)
308
+ return [];
309
+ const specDate = new Date(specUpdated);
310
+ const byEntry = context.config ? groupByEntry(context.config, context.allSpecs) : /* @__PURE__ */ new Map([["", context.allSpecs]]);
311
+ const relations = buildRelationResolver(context.config, byEntry);
312
+ const upstreamIds = relations.getUpstream(specId);
313
+ const diagnostics = [];
314
+ for (const upstreamId of upstreamIds) {
315
+ const upstream = context.allSpecs.find((s) => s.frontmatter.id === upstreamId);
316
+ if (!upstream)
317
+ continue;
318
+ const upstreamUpdated = lastUpdated(upstream);
319
+ if (!upstreamUpdated)
320
+ continue;
321
+ if (new Date(upstreamUpdated) > specDate) {
322
+ diagnostics.push({
323
+ ruleId: "freshness/staleness-check",
324
+ severity: "warn",
325
+ message: `Potentially stale: upstream "${upstreamId}" was updated on ${upstreamUpdated}, but this spec was last updated on ${specUpdated}`,
326
+ filePath: context.spec.filePath
327
+ });
328
+ }
329
+ }
330
+ return diagnostics;
331
+ }
332
+ };
333
+
334
+ // ../lint/dist/rules/no-vague-language.js
335
+ var DEFAULT_VAGUE_PATTERNS = [
336
+ "as appropriate",
337
+ "handle edge cases",
338
+ "as needed",
339
+ "etc\\.",
340
+ "TBD",
341
+ "TODO",
342
+ "and so on",
343
+ "various",
344
+ "somehow",
345
+ "straightforward",
346
+ "obviously",
347
+ "simply",
348
+ "just need to"
349
+ ];
350
+ var noVagueLanguageRule = {
351
+ id: "clarity/no-vague-language",
352
+ description: "Flags known ambiguous phrases",
353
+ severity: "warn",
354
+ run(context) {
355
+ if (!context.spec.content)
356
+ return [];
357
+ const diagnostics = [];
358
+ for (const pattern of DEFAULT_VAGUE_PATTERNS) {
359
+ const regex = new RegExp(`\\b${pattern}`, "gi");
360
+ let match;
361
+ while ((match = regex.exec(context.spec.content)) !== null) {
362
+ diagnostics.push({
363
+ ruleId: "clarity/no-vague-language",
364
+ severity: "warn",
365
+ message: `Vague language: "${match[0]}"`,
366
+ filePath: context.spec.filePath
367
+ });
368
+ }
369
+ }
370
+ return diagnostics;
371
+ }
372
+ };
373
+
374
+ // ../lint/dist/rules/single-project-context.js
375
+ var singleProjectContextRule = {
376
+ id: "structure/single-project-context",
377
+ description: "Only one project-context spec should exist per suite",
378
+ severity: "warn",
379
+ run(context) {
380
+ if (context.spec.frontmatter.type !== "project-context")
381
+ return [];
382
+ const contextSpecs = context.allSpecs.filter((s) => s.frontmatter.type === "project-context");
383
+ if (contextSpecs.length > 1) {
384
+ return [
385
+ {
386
+ ruleId: "structure/single-project-context",
387
+ severity: "warn",
388
+ message: `Multiple project-context specs found (${contextSpecs.length}). Only one should exist per suite.`,
389
+ filePath: context.spec.filePath
390
+ }
391
+ ];
392
+ }
393
+ return [];
394
+ }
395
+ };
396
+
397
+ // ../lint/dist/rules/terminology.js
398
+ function normalizeCompound(term) {
399
+ return term.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").toLowerCase().trim();
400
+ }
401
+ function extractCompoundTerms(content) {
402
+ const terms = [];
403
+ const camelCaseRegex = /\b[a-zA-Z]*[a-z][A-Z][a-zA-Z]*\b/g;
404
+ let match;
405
+ while ((match = camelCaseRegex.exec(content)) !== null) {
406
+ terms.push(match[0]);
407
+ }
408
+ const hyphenatedRegex = /\b[a-z][a-z0-9]*(?:-[a-z][a-z0-9]*)+\b/g;
409
+ while ((match = hyphenatedRegex.exec(content)) !== null) {
410
+ terms.push(match[0]);
411
+ }
412
+ return terms;
413
+ }
414
+ var terminologyRule = {
415
+ id: "consistency/terminology",
416
+ description: "Detects terminology drift (e.g., user-profile vs UserProfile vs user profile) across specs",
417
+ severity: "warn",
418
+ run(context) {
419
+ if (context.spec !== context.allSpecs[0])
420
+ return [];
421
+ const termMap = /* @__PURE__ */ new Map();
422
+ for (const spec of context.allSpecs) {
423
+ if (!spec.content)
424
+ continue;
425
+ const terms = extractCompoundTerms(spec.content);
426
+ for (const term of terms) {
427
+ const normalized = normalizeCompound(term);
428
+ if (!normalized.includes(" "))
429
+ continue;
430
+ if (!termMap.has(normalized)) {
431
+ termMap.set(normalized, /* @__PURE__ */ new Set());
432
+ }
433
+ termMap.get(normalized).add(term);
434
+ }
435
+ }
436
+ const diagnostics = [];
437
+ for (const [normalized, variants] of termMap) {
438
+ if (variants.size >= 2) {
439
+ const variantList = [...variants].join(", ");
440
+ diagnostics.push({
441
+ ruleId: "consistency/terminology",
442
+ severity: "warn",
443
+ message: `Inconsistent terminology for "${normalized}": found variants [${variantList}]. Standardize terminology across specs.`,
444
+ filePath: context.spec.filePath
445
+ });
446
+ }
447
+ }
448
+ return diagnostics;
449
+ }
450
+ };
451
+
452
+ // ../lint/dist/rules/edge-case-coverage.js
453
+ var EDGE_CASE_KEYWORDS = [
454
+ "error",
455
+ "invalid",
456
+ "empty",
457
+ "timeout",
458
+ "fails",
459
+ "failure",
460
+ "boundary",
461
+ "edge case",
462
+ "null",
463
+ "undefined",
464
+ "reject",
465
+ "unauthorized",
466
+ "forbidden",
467
+ "missing",
468
+ "malformed",
469
+ "overflow",
470
+ "duplicate",
471
+ "graceful",
472
+ "fall back",
473
+ "fallback",
474
+ "crash",
475
+ "nonexistent",
476
+ "corrupt",
477
+ // Vocabulary that names a failure without using any of the words above.
478
+ "conflict",
479
+ "denied",
480
+ "expired",
481
+ "not found",
482
+ "retry",
483
+ "rate limit",
484
+ "unavailable",
485
+ "unprocessable"
486
+ ];
487
+ var ERROR_STATUS_CODE = /\b[45]\d{2}\b/;
488
+ var EDGE_CASE_SECTION = "edge cases";
489
+ var PLACEHOLDER_BODIES = /^(todo|tbd|fixme|n\/a|na|none|xxx|\.{2,}|-|\*)$/i;
490
+ var DISCLAIMED_BODIES = /^(none|no|nothing|n\/a)\b[\s\S]{0,40}$/i;
491
+ function meaningfulContent(content) {
492
+ return content.replace(/<!--[\s\S]*?-->/g, "").split("\n").map((line) => line.replace(/^\s*[-*+]\s+/, "").trim()).filter((line) => line.length > 0 && !/^-{3,}$/.test(line)).join("\n").trim();
493
+ }
494
+ var edgeCaseCoverageRule = {
495
+ id: "completeness/edge-case-coverage",
496
+ description: "Flag user stories or test plans that don't mention error states or edge cases",
497
+ severity: "warn",
498
+ run(context) {
499
+ const type = context.spec.frontmatter.type;
500
+ if (type !== "user-story" && type !== "test-plan")
501
+ return [];
502
+ const section = context.spec.parsedSections.find((s) => s.heading.trim().toLowerCase() === EDGE_CASE_SECTION);
503
+ if (type === "test-plan" && section) {
504
+ const body = meaningfulContent(section.content);
505
+ const written = body !== "" && !PLACEHOLDER_BODIES.test(body) && !DISCLAIMED_BODIES.test(body);
506
+ if (written)
507
+ return [];
508
+ return [
509
+ {
510
+ ruleId: "completeness/edge-case-coverage",
511
+ severity: "warn",
512
+ message: `The "${section.heading}" section lists no cases \u2014 describe the boundary conditions and failure modes this plan covers, or the plan asserts only the happy path.`,
513
+ filePath: context.spec.filePath,
514
+ section: section.heading
515
+ }
516
+ ];
517
+ }
518
+ const content = context.spec.content.toLowerCase();
519
+ const hasEdgeCases = EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw)) || ERROR_STATUS_CODE.test(content);
520
+ if (hasEdgeCases)
521
+ return [];
522
+ return [
523
+ {
524
+ ruleId: "completeness/edge-case-coverage",
525
+ severity: "warn",
526
+ message: "No error states or edge cases mentioned. Consider adding error handling, boundary conditions, or failure mode scenarios.",
527
+ filePath: context.spec.filePath
528
+ }
529
+ ];
530
+ }
531
+ };
532
+
533
+ // ../lint/dist/rules/naming-conventions.js
534
+ var namingConventionsRule = {
535
+ id: "consistency/naming-conventions",
536
+ description: "Enforce consistent naming conventions across specs",
537
+ severity: "warn",
538
+ run(context) {
539
+ const { spec } = context;
540
+ const type = spec.frontmatter.type;
541
+ const diagnostics = [];
542
+ if (type === "prd") {
543
+ const sectionParts = spec.content.split(/^(?=## )/m);
544
+ const featuresSection = sectionParts.find((p) => /^## Features\b/.test(p));
545
+ if (featuresSection) {
546
+ const bullets = featuresSection.match(/^- .+$/gm) ?? [];
547
+ for (const bullet of bullets) {
548
+ if (bullet.match(/^- \*\*F\d+\*\*:/) === null && bullet.trim().length > 2) {
549
+ diagnostics.push({
550
+ ruleId: "consistency/naming-conventions",
551
+ severity: "warn",
552
+ message: `PRD feature missing feature ID pattern (**F<N>**:): "${bullet.slice(0, 60)}"`,
553
+ filePath: spec.filePath
554
+ });
555
+ }
556
+ }
557
+ }
558
+ }
559
+ if (type === "user-story") {
560
+ const id = spec.frontmatter.id;
561
+ if (!id.startsWith("story-")) {
562
+ diagnostics.push({
563
+ ruleId: "consistency/naming-conventions",
564
+ severity: "warn",
565
+ message: `User story ID "${id}" should start with "story-" (e.g., "story-${id}")`,
566
+ filePath: spec.filePath
567
+ });
568
+ }
569
+ }
570
+ if (type === "api-contract") {
571
+ const endpointRe = /^###\s+(GET|POST|PUT|PATCH|DELETE)\s+(\S+)/gm;
572
+ let match;
573
+ while ((match = endpointRe.exec(spec.content)) !== null) {
574
+ const path = match[2];
575
+ if (/\/[a-z]+[A-Z]/.test(path)) {
576
+ diagnostics.push({
577
+ ruleId: "consistency/naming-conventions",
578
+ severity: "warn",
579
+ message: `Endpoint path "${path}" uses camelCase \u2014 use kebab-case instead (e.g., "${path.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()}")`,
580
+ filePath: spec.filePath
581
+ });
582
+ }
583
+ }
584
+ }
585
+ return diagnostics;
586
+ }
587
+ };
588
+
589
+ // ../lint/dist/rules/threat-coverage.js
590
+ var STOPWORDS2 = /* @__PURE__ */ new Set(["the", "and", "for", "with", "from", "that", "this", "into", "via"]);
591
+ function extractThreats(content) {
592
+ const parts = content.split(/^(?=## )/m);
593
+ const threats = [];
594
+ for (const part of parts) {
595
+ if (!/^##\s+(Threats|Security)\b/i.test(part))
596
+ continue;
597
+ const bullets = part.match(/^- .+$/gm) ?? [];
598
+ threats.push(...bullets.map((b) => b.slice(2).trim()));
599
+ }
600
+ return threats;
601
+ }
602
+ function extractKeyTerms(text) {
603
+ return text.toLowerCase().split(/\W+/).filter((w) => w.length > 3).filter((w) => !STOPWORDS2.has(w));
604
+ }
605
+ var threatCoverageRule = {
606
+ id: "security/threat-coverage",
607
+ description: "Technical design specs must address threats identified in other specs",
608
+ severity: "warn",
609
+ run(context) {
610
+ if (context.spec.frontmatter.type !== "technical-design")
611
+ return [];
612
+ const allThreats = [];
613
+ for (const spec of context.allSpecs) {
614
+ if (spec.filePath === context.spec.filePath)
615
+ continue;
616
+ allThreats.push(...extractThreats(spec.content));
617
+ }
618
+ if (allThreats.length === 0)
619
+ return [];
620
+ const techContent = context.spec.content.toLowerCase();
621
+ const diagnostics = [];
622
+ for (const threat of allThreats) {
623
+ const keyTerms = extractKeyTerms(threat);
624
+ const covered = keyTerms.some((term) => techContent.includes(term));
625
+ if (!covered) {
626
+ diagnostics.push({
627
+ ruleId: "security/threat-coverage",
628
+ severity: "warn",
629
+ message: `Threat not addressed in technical design: "${threat}". Ensure the design covers this threat.`,
630
+ filePath: context.spec.filePath
631
+ });
632
+ }
633
+ }
634
+ return diagnostics;
635
+ }
636
+ };
637
+
638
+ // ../lint/dist/rules/ambiguity-score-ai.js
639
+ var ambiguityScoreAiRule = {
640
+ id: "clarity/ambiguity-score-ai",
641
+ description: "AI-powered ambiguity detection (requires ANTHROPIC_API_KEY)",
642
+ severity: "info",
643
+ run(context) {
644
+ if (!process.env["ANTHROPIC_API_KEY"])
645
+ return [];
646
+ return [
647
+ {
648
+ ruleId: "clarity/ambiguity-score-ai",
649
+ severity: "info",
650
+ message: "AI ambiguity analysis available \u2014 run `specdx check --ai` for LLM-powered ambiguity detection",
651
+ filePath: context.spec.filePath
652
+ }
653
+ ];
654
+ }
655
+ };
656
+
657
+ // ../lint/dist/rules/no-placeholder-sections.js
658
+ var PLACEHOLDER_BODIES2 = /^(todo|tbd|fixme|n\/a|na|none|xxx|\.{2,}|-|\*)$/i;
659
+ function meaningfulContent2(content) {
660
+ return content.replace(/<!--[\s\S]*?-->/g, "").split("\n").map((line) => line.replace(/^\s*[-*+]\s+/, "").trim()).filter((line) => line.length > 0 && !/^-{3,}$/.test(line)).join("\n").trim();
661
+ }
662
+ var noPlaceholderSectionsRule = {
663
+ id: "completeness/no-placeholder-sections",
664
+ description: "Spec sections contain content, not scaffolding placeholders",
665
+ severity: "warn",
666
+ run(context) {
667
+ return context.spec.parsedSections.filter((section) => section.heading !== "").filter((section) => {
668
+ const body = meaningfulContent2(section.content);
669
+ return body === "" || PLACEHOLDER_BODIES2.test(body);
670
+ }).map((section) => ({
671
+ ruleId: "completeness/no-placeholder-sections",
672
+ severity: "warn",
673
+ message: `Section "${section.heading}" is still a placeholder \u2014 write its content or remove the section`,
674
+ filePath: context.spec.filePath,
675
+ section: section.heading
676
+ }));
677
+ }
678
+ };
679
+
680
+ // ../lint/dist/rules/id-matches-config-key.js
681
+ import { basename } from "path";
682
+ var idMatchesConfigKeyRule = {
683
+ id: "structure/id-matches-config-key",
684
+ description: "A spec's frontmatter id should match the key it is registered under in the config",
685
+ severity: "warn",
686
+ run(context) {
687
+ const { spec, config } = context;
688
+ if (!config)
689
+ return [];
690
+ const id = spec.frontmatter.id;
691
+ if (typeof id !== "string" || id.length === 0)
692
+ return [];
693
+ const specFile = basename(spec.filePath);
694
+ const candidates = Object.entries(config.specs).filter(([, entry]) => {
695
+ const target = basename(entry.path);
696
+ return !target.includes("*") && target === specFile;
697
+ });
698
+ if (candidates.length !== 1)
699
+ return [];
700
+ const key = candidates[0][0];
701
+ if (key === id)
702
+ return [];
703
+ return [
704
+ {
705
+ ruleId: "structure/id-matches-config-key",
706
+ severity: "warn",
707
+ message: `Spec declares id "${id}" but is registered in spec.config.yaml as "${key}". Frontmatter references resolve against "${id}" and config requires against "${key}", so the dependency graph shows them as two things. Rename one so they agree.`,
708
+ filePath: spec.filePath
709
+ }
710
+ ];
711
+ }
712
+ };
713
+
714
+ // ../lint/dist/rules/index.js
715
+ var structureRules = [
716
+ validFrontmatterRule,
717
+ requiredSectionsRule,
718
+ validReferencesRule,
719
+ noCircularDepsRule,
720
+ singleProjectContextRule,
721
+ idMatchesConfigKeyRule
722
+ ];
723
+ var contentRules = [
724
+ storyCoverageRule,
725
+ stalenessCheckRule,
726
+ noVagueLanguageRule,
727
+ terminologyRule,
728
+ edgeCaseCoverageRule,
729
+ namingConventionsRule,
730
+ threatCoverageRule,
731
+ ambiguityScoreAiRule,
732
+ noPlaceholderSectionsRule
733
+ ];
734
+ var allBuiltinRules = [...structureRules, ...contentRules];
735
+
736
+ // ../lint/dist/presets.js
737
+ function getPreset(name) {
738
+ switch (name) {
739
+ case "minimal":
740
+ return structureRules;
741
+ case "recommended":
742
+ return allBuiltinRules;
743
+ case "strict":
744
+ return allBuiltinRules.map((rule) => rule.severity === "warn" ? { ...rule, severity: "error" } : rule);
745
+ default:
746
+ throw new Error(`Unknown preset: "${name}". Use "minimal", "recommended", or "strict", or resolve external presets via resolvePreset() from @specdx/core.`);
747
+ }
748
+ }
749
+
750
+ // ../lint/dist/custom-rule-loader.js
751
+ import { pathToFileURL } from "url";
752
+ async function loadCustomRule(filePath) {
753
+ const module = await import(pathToFileURL(filePath).href);
754
+ const rule = module.default ?? module.rule;
755
+ if (!rule || !rule.id || !rule.run) {
756
+ throw new Error(`Custom rule at ${filePath} must export a default LintRule with id and run function`);
757
+ }
758
+ return rule;
759
+ }
760
+
761
+ // ../lint/dist/resolve-lint-config.js
762
+ var SEVERITIES = /* @__PURE__ */ new Set(["error", "warn", "info"]);
763
+ function isOff(value) {
764
+ return value === false || value === null || value === "off";
765
+ }
766
+ function severityOf(value) {
767
+ return typeof value === "string" && SEVERITIES.has(value) ? value : void 0;
768
+ }
769
+ function describe(value) {
770
+ return typeof value === "string" ? `"${value}"` : JSON.stringify(value);
771
+ }
772
+ async function resolveLintConfig({ config, preset, configDir }) {
773
+ const presetName = preset ?? config?.lint?.extends ?? "recommended";
774
+ const byId = new Map(getPreset(presetName).map((rule) => [rule.id, rule]));
775
+ const builtins = new Map(allBuiltinRules.map((rule) => [rule.id, rule]));
776
+ for (const [id, value] of Object.entries(config?.lint?.rules ?? {})) {
777
+ if (isOff(value)) {
778
+ if (!builtins.has(id)) {
779
+ throw new Error(`lint.rules["${id}"]: cannot turn off "${id}" \u2014 no built-in rule has that id. Check the spelling.`);
780
+ }
781
+ byId.delete(id);
782
+ continue;
783
+ }
784
+ let severity;
785
+ let rulePath;
786
+ if (Array.isArray(value)) {
787
+ severity = severityOf(value[0]);
788
+ if (severity === void 0) {
789
+ throw new Error(`lint.rules["${id}"]: ${describe(value[0])} is not a severity. Use "error", "warn", "info", or "off".`);
790
+ }
791
+ const options = value[1];
792
+ if (options !== void 0) {
793
+ if (typeof options !== "object" || options === null || Array.isArray(options)) {
794
+ throw new Error(`lint.rules["${id}"]: expected options like { path: "./rule.js" }, got ${describe(options)}.`);
795
+ }
796
+ const declared = options.path;
797
+ if (declared !== void 0) {
798
+ if (typeof declared !== "string" || declared.length === 0) {
799
+ throw new Error(`lint.rules["${id}"]: \`path\` must be a non-empty string.`);
800
+ }
801
+ rulePath = declared;
802
+ }
803
+ }
804
+ } else {
805
+ severity = severityOf(value);
806
+ if (severity === void 0) {
807
+ throw new Error(`lint.rules["${id}"]: ${describe(value)} is not a severity. Use "error", "warn", "info", or "off".`);
808
+ }
809
+ }
810
+ if (rulePath !== void 0) {
811
+ const absolute = isAbsolute(rulePath) ? rulePath : resolve(configDir, rulePath);
812
+ const custom = await loadCustomRule(absolute);
813
+ byId.set(id, { ...custom, id, severity });
814
+ continue;
815
+ }
816
+ const existing = byId.get(id) ?? builtins.get(id);
817
+ if (!existing) {
818
+ throw new Error(`lint.rules["${id}"]: no built-in rule with that id. For a custom rule, give it a file: ["${severity}", { path: "./rules/my-rule.js" }].`);
819
+ }
820
+ byId.set(id, { ...existing, severity });
821
+ }
822
+ const ignore = [];
823
+ for (const pattern of config?.lint?.ignore ?? []) {
824
+ ignore.push(...await resolveGlob(pattern, configDir));
825
+ }
826
+ return { rules: [...byId.values()], ignore };
827
+ }
828
+
829
+ // ../lint/dist/agents/discover.js
830
+ import { readFile } from "fs/promises";
831
+ import { relative } from "path";
832
+ var DEFAULT_AGENT_PATHS = ["AGENTS.md", "CLAUDE.md"];
833
+ var DEFAULT_MAX_TOKENS = 8e3;
834
+ async function discoverAgentFiles(patterns, configDir) {
835
+ const seen = /* @__PURE__ */ new Set();
836
+ const files = [];
837
+ for (const pattern of patterns) {
838
+ for (const filePath of await resolveGlob(pattern, configDir)) {
839
+ if (seen.has(filePath))
840
+ continue;
841
+ seen.add(filePath);
842
+ const content = await readFile(filePath, "utf8");
843
+ files.push({
844
+ filePath,
845
+ relativePath: relative(configDir, filePath),
846
+ content,
847
+ lines: content.split("\n"),
848
+ tokens: countTokens(content)
849
+ });
850
+ }
851
+ }
852
+ return files.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
853
+ }
854
+
855
+ // ../lint/dist/agents/rules/structure.js
856
+ var structureRule = {
857
+ id: "agents/structure",
858
+ description: "Agent instruction files should have content and be organised under headings",
859
+ severity: "warn",
860
+ run(context) {
861
+ const { file } = context;
862
+ const diagnostics = [];
863
+ if (file.content.trim() === "") {
864
+ diagnostics.push({
865
+ ruleId: "agents/structure",
866
+ severity: "warn",
867
+ message: `${file.relativePath} is empty. An empty instruction file steers nothing \u2014 delete it or write it.`,
868
+ filePath: file.filePath
869
+ });
870
+ return { diagnostics };
871
+ }
872
+ const headings = file.lines.filter((line) => /^#{1,6}\s+\S/.test(line));
873
+ if (headings.length === 0) {
874
+ diagnostics.push({
875
+ ruleId: "agents/structure",
876
+ severity: "warn",
877
+ message: `${file.relativePath} has no headings, so it is one undifferentiated block. Nothing can be referenced, revised, or removed in isolation.`,
878
+ filePath: file.filePath
879
+ });
880
+ }
881
+ return { diagnostics };
882
+ }
883
+ };
884
+
885
+ // ../lint/dist/agents/rules/stale-references.js
886
+ var PATH_SHAPED = /^(?:[\w.@-]+\/)+[\w.-]+$|^[\w.-]+\.(?:ts|tsx|js|jsx|mjs|cjs|json|md|ya?ml|toml|sh|py|rb|rs|go|java|css|html)$/;
887
+ function isNotAFileClaim(candidate) {
888
+ return candidate.includes("*") || // a glob describes a set, not a file
889
+ candidate.includes("://") || // a URL
890
+ candidate.startsWith("http") || candidate.startsWith("@") || // an npm scope: @specdx/core
891
+ candidate.startsWith("~") || // a home-relative path outside the repo
892
+ candidate.startsWith("/") || // an absolute path outside the repo
893
+ /^[A-Z_]+=/.test(candidate);
894
+ }
895
+ function normalise(candidate) {
896
+ return candidate.replace(/^\.\//, "").replace(/[.,;:)]+$/, "");
897
+ }
898
+ function fencedLines(lines) {
899
+ const fenced = /* @__PURE__ */ new Set();
900
+ let fence;
901
+ lines.forEach((line, index) => {
902
+ const match = /^\s*(`{3,}|~{3,})/.exec(line);
903
+ if (match) {
904
+ if (fence === void 0) {
905
+ fence = match[1];
906
+ fenced.add(index);
907
+ return;
908
+ }
909
+ if (match[1][0] === fence[0])
910
+ fence = void 0;
911
+ fenced.add(index);
912
+ return;
913
+ }
914
+ if (fence !== void 0)
915
+ fenced.add(index);
916
+ });
917
+ return fenced;
918
+ }
919
+ function extractReferences(lines) {
920
+ const skip = fencedLines(lines);
921
+ const found = [];
922
+ const seen = /* @__PURE__ */ new Set();
923
+ lines.forEach((line, index) => {
924
+ if (skip.has(index))
925
+ return;
926
+ const candidates = [];
927
+ for (const match of line.matchAll(/`([^`\n]+)`/g))
928
+ candidates.push(match[1]);
929
+ for (const match of line.matchAll(/\]\((?!https?:|#)([^)\s]+)\)/g))
930
+ candidates.push(match[1]);
931
+ for (const raw of candidates) {
932
+ const candidate = normalise(raw.trim());
933
+ if (!candidate || isNotAFileClaim(candidate))
934
+ continue;
935
+ if (!PATH_SHAPED.test(candidate))
936
+ continue;
937
+ if (seen.has(candidate))
938
+ continue;
939
+ seen.add(candidate);
940
+ found.push({ path: candidate, line: index + 1 });
941
+ }
942
+ });
943
+ return found;
944
+ }
945
+ var staleReferencesRule = {
946
+ id: "agents/stale-references",
947
+ description: "Paths named by an agent instruction file must exist",
948
+ severity: "warn",
949
+ run(context) {
950
+ const { file, exists } = context;
951
+ const references = extractReferences(file.lines);
952
+ if (references.length === 0) {
953
+ return {
954
+ diagnostics: [],
955
+ assessed: false,
956
+ notAssessedReason: `${file.relativePath} names no file paths, so none were checked for staleness.`
957
+ };
958
+ }
959
+ return {
960
+ diagnostics: references.filter((reference) => !exists(reference.path)).map((reference) => ({
961
+ ruleId: "agents/stale-references",
962
+ severity: this.severity,
963
+ message: `${file.relativePath} refers to "${reference.path}", which does not exist. An agent told to look there will not find it.`,
964
+ filePath: file.filePath,
965
+ line: reference.line
966
+ }))
967
+ };
968
+ }
969
+ };
970
+
971
+ // ../lint/dist/agents/rules/size-budget.js
972
+ var sizeBudgetRule = {
973
+ id: "agents/size-budget",
974
+ description: "Agent instruction files should fit a token budget",
975
+ severity: "warn",
976
+ run(context) {
977
+ const { file, maxTokens } = context;
978
+ if (file.tokens <= maxTokens)
979
+ return { diagnostics: [] };
980
+ const over = file.tokens - maxTokens;
981
+ const percent = Math.round(over / maxTokens * 100);
982
+ return {
983
+ diagnostics: [
984
+ {
985
+ ruleId: "agents/size-budget",
986
+ severity: this.severity,
987
+ message: `${file.relativePath} is ${file.tokens} tokens, ${over} over the ${maxTokens} budget (${percent}% over). It is spending the context window it exists to protect.`,
988
+ filePath: file.filePath
989
+ }
990
+ ]
991
+ };
992
+ }
993
+ };
994
+
995
+ // ../lint/dist/agents/resolve-reference.js
996
+ import { readdirSync } from "fs";
997
+ import { join, sep } from "path";
998
+ var SKIP_DIRECTORIES = /* @__PURE__ */ new Set([
999
+ "node_modules",
1000
+ ".git",
1001
+ "dist",
1002
+ "build",
1003
+ "coverage",
1004
+ ".next",
1005
+ ".turbo",
1006
+ ".cache",
1007
+ "out"
1008
+ ]);
1009
+ var MAX_INDEXED_FILES = 2e4;
1010
+ function indexProjectFiles(configDir) {
1011
+ const found = [];
1012
+ const walk = (dir, prefix) => {
1013
+ if (found.length >= MAX_INDEXED_FILES)
1014
+ return;
1015
+ let entries;
1016
+ try {
1017
+ entries = readdirSync(dir, { withFileTypes: true });
1018
+ } catch {
1019
+ return;
1020
+ }
1021
+ for (const entry of entries) {
1022
+ if (found.length >= MAX_INDEXED_FILES)
1023
+ return;
1024
+ const relative2 = prefix ? `${prefix}/${entry.name}` : entry.name;
1025
+ if (entry.isDirectory()) {
1026
+ if (SKIP_DIRECTORIES.has(entry.name))
1027
+ continue;
1028
+ found.push(relative2);
1029
+ walk(join(dir, entry.name), relative2);
1030
+ } else {
1031
+ found.push(relative2);
1032
+ }
1033
+ }
1034
+ };
1035
+ walk(configDir, "");
1036
+ return found;
1037
+ }
1038
+ var PLACEHOLDER_STEMS = /* @__PURE__ */ new Set([
1039
+ "foo",
1040
+ "bar",
1041
+ "baz",
1042
+ "qux",
1043
+ "example",
1044
+ "your-app",
1045
+ "my-app",
1046
+ "some-file",
1047
+ "path"
1048
+ ]);
1049
+ function isPlaceholder(reference) {
1050
+ const base = reference.split("/").pop() ?? reference;
1051
+ const stem = base.split(".")[0] ?? base;
1052
+ return PLACEHOLDER_STEMS.has(stem.toLowerCase());
1053
+ }
1054
+ function createReferenceResolver(files) {
1055
+ const exact = new Set(files);
1056
+ const byLastSegment = /* @__PURE__ */ new Map();
1057
+ for (const file of files) {
1058
+ const last = file.split("/").pop();
1059
+ const bucket = byLastSegment.get(last);
1060
+ if (bucket)
1061
+ bucket.push(file);
1062
+ else
1063
+ byLastSegment.set(last, [file]);
1064
+ }
1065
+ return (reference) => {
1066
+ const normalised = reference.split(sep).join("/");
1067
+ if (exact.has(normalised))
1068
+ return true;
1069
+ if (isPlaceholder(normalised))
1070
+ return true;
1071
+ const last = normalised.split("/").pop();
1072
+ if (!last)
1073
+ return false;
1074
+ const candidates = byLastSegment.get(last);
1075
+ if (!candidates)
1076
+ return false;
1077
+ return candidates.some((candidate) => candidate === normalised || candidate.endsWith(`/${normalised}`));
1078
+ };
1079
+ }
1080
+
1081
+ // ../lint/dist/agents/index.js
1082
+ var AGENT_RULES = [structureRule, staleReferencesRule, sizeBudgetRule];
1083
+ var VALID_SEVERITIES = /* @__PURE__ */ new Set(["error", "warn", "info"]);
1084
+ var AgentConfigError = class extends Error {
1085
+ };
1086
+ function resolveAgentRules(overrides = {}) {
1087
+ const known = new Map(AGENT_RULES.map((rule) => [rule.id, rule]));
1088
+ for (const id of Object.keys(overrides)) {
1089
+ if (!known.has(id)) {
1090
+ throw new AgentConfigError(`Unknown agent rule "${id}" in agents.rules. Known rules: ${[...known.keys()].join(", ")}.`);
1091
+ }
1092
+ }
1093
+ const resolved = [];
1094
+ for (const rule of AGENT_RULES) {
1095
+ const override = overrides[rule.id];
1096
+ if (override === void 0) {
1097
+ resolved.push(rule);
1098
+ continue;
1099
+ }
1100
+ if (override === false || override === "off")
1101
+ continue;
1102
+ if (typeof override === "string" && VALID_SEVERITIES.has(override)) {
1103
+ resolved.push({ ...rule, severity: override });
1104
+ continue;
1105
+ }
1106
+ throw new AgentConfigError(`Invalid severity ${JSON.stringify(override)} for "${rule.id}". Use "error", "warn", "info", "off", or false.`);
1107
+ }
1108
+ return resolved;
1109
+ }
1110
+ async function lintAgentFiles(options) {
1111
+ const { config, configDir } = options;
1112
+ const agents = config.agents ?? {};
1113
+ const patterns = agents.paths ?? DEFAULT_AGENT_PATHS;
1114
+ const maxTokens = agents.max_tokens ?? DEFAULT_MAX_TOKENS;
1115
+ const rules = resolveAgentRules(agents.rules);
1116
+ const files = await discoverAgentFiles(patterns, configDir);
1117
+ const exists = options.exists ?? (files.length > 0 ? createReferenceResolver(indexProjectFiles(configDir)) : () => true);
1118
+ const diagnostics = [];
1119
+ for (const file of files) {
1120
+ for (const rule of rules) {
1121
+ const result = rule.run({ file, configDir, exists, maxTokens });
1122
+ for (const diagnostic of result.diagnostics) {
1123
+ diagnostics.push({ ...diagnostic, severity: rule.severity });
1124
+ }
1125
+ if (result.assessed === false) {
1126
+ diagnostics.push({
1127
+ ruleId: rule.id,
1128
+ severity: "info",
1129
+ message: result.notAssessedReason ?? `${rule.id} assessed nothing in ${file.relativePath}.`,
1130
+ filePath: file.filePath
1131
+ });
1132
+ }
1133
+ }
1134
+ }
1135
+ return { diagnostics, filesLinted: files.length, assessed: files.length > 0 };
1136
+ }
1137
+
1138
+ export {
1139
+ createLintEngine,
1140
+ parseFeatures,
1141
+ parseFeatureEntries,
1142
+ uncoveredFeatures,
1143
+ resolveLintConfig,
1144
+ lintAgentFiles
1145
+ };
1146
+ //# sourceMappingURL=chunk-ZIODMXST.js.map