specdx 0.4.0-alpha.8 → 0.4.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 +259 -0
  3. package/dist/{check-ULQYDDRD.js → check-PHXXA7VY.js} +70 -31
  4. package/dist/check-PHXXA7VY.js.map +1 -0
  5. package/dist/chunk-2BZIG7OE.js +185 -0
  6. package/dist/chunk-2BZIG7OE.js.map +1 -0
  7. package/dist/{chunk-OTDEP6WZ.js → chunk-3YXRWQGX.js} +251 -52
  8. package/dist/chunk-3YXRWQGX.js.map +1 -0
  9. package/dist/chunk-5WRI5ZAA.js +31 -0
  10. package/dist/chunk-DMGABJ6T.js +41 -0
  11. package/dist/chunk-DMGABJ6T.js.map +1 -0
  12. package/dist/{chunk-7JXW2GTJ.js → chunk-HCJDCS26.js} +9 -2
  13. package/dist/chunk-HCJDCS26.js.map +1 -0
  14. package/dist/chunk-LJTLNXGV.js +835 -0
  15. package/dist/chunk-LJTLNXGV.js.map +1 -0
  16. package/dist/chunk-NAWYG4VV.js +2846 -0
  17. package/dist/chunk-NAWYG4VV.js.map +1 -0
  18. package/dist/chunk-NHD44ZYN.js +20 -0
  19. package/dist/chunk-NHD44ZYN.js.map +1 -0
  20. package/dist/chunk-OVIKIIR4.js +103 -0
  21. package/dist/chunk-OVIKIIR4.js.map +1 -0
  22. package/dist/{chunk-IHTYAW7C.js → chunk-SNQNQ2MP.js} +111 -7
  23. package/dist/chunk-SNQNQ2MP.js.map +1 -0
  24. package/dist/{chunk-AKNPCB37.js → chunk-YRQPY5NF.js} +32 -12
  25. package/dist/chunk-YRQPY5NF.js.map +1 -0
  26. package/dist/diff-6C5LJ7SH.js +200 -0
  27. package/dist/diff-6C5LJ7SH.js.map +1 -0
  28. package/dist/{dist-HKVTEPU5.js → dist-PK52GA7M.js} +45 -20
  29. package/dist/dist-PK52GA7M.js.map +1 -0
  30. package/dist/{dist-4MXKMRHE.js → dist-ROHCFKYT.js} +3 -2
  31. package/dist/dist-ROHCFKYT.js.map +1 -0
  32. package/dist/generate-K72WD455.js +21 -0
  33. package/dist/generate-K72WD455.js.map +1 -0
  34. package/dist/{generate-story-EFHGINHA.js → generate-story-NUCNYL3I.js} +43 -19
  35. package/dist/generate-story-NUCNYL3I.js.map +1 -0
  36. package/dist/{generate-test-plan-BO7444RG.js → generate-test-plan-Z46W3N3B.js} +61 -11
  37. package/dist/generate-test-plan-Z46W3N3B.js.map +1 -0
  38. package/dist/{graph-5XINV7PT.js → graph-4RNURBNP.js} +49 -11
  39. package/dist/graph-4RNURBNP.js.map +1 -0
  40. package/dist/index.d.ts +275 -0
  41. package/dist/index.js +2651 -350
  42. package/dist/index.js.map +1 -1
  43. package/dist/{lint-PGA7JFKM.js → lint-2VZPNLE3.js} +51 -17
  44. package/dist/lint-2VZPNLE3.js.map +1 -0
  45. package/dist/main.js +10 -229
  46. package/dist/main.js.map +1 -1
  47. package/dist/mcp-E6PJWBDQ.js +35 -0
  48. package/dist/mcp-E6PJWBDQ.js.map +1 -0
  49. package/dist/{migrate-4KF6GHLO.js → migrate-FKFC7UAO.js} +21 -9
  50. package/dist/migrate-FKFC7UAO.js.map +1 -0
  51. package/dist/{pack-DSOODXAN.js → pack-DE4UBTCC.js} +41 -13
  52. package/dist/pack-DE4UBTCC.js.map +1 -0
  53. package/dist/{ready-GTCDQOIC.js → ready-K74SLQ24.js} +88 -24
  54. package/dist/ready-K74SLQ24.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} +8 -2
  67. package/dist/skills-36SRUEMR.js +121 -0
  68. package/dist/skills-36SRUEMR.js.map +1 -0
  69. package/dist/{status-C3YDBH2L.js → status-IAE3BB77.js} +69 -32
  70. package/dist/status-IAE3BB77.js.map +1 -0
  71. package/dist/{update-ULMSL5XZ.js → update-UFOHZEAK.js} +22 -12
  72. package/dist/update-UFOHZEAK.js.map +1 -0
  73. package/dist/validate-EZHUB5TW.js +105 -0
  74. package/dist/validate-EZHUB5TW.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-FJIQBEBB.js +0 -93
  79. package/dist/changelog-FJIQBEBB.js.map +0 -1
  80. package/dist/check-ULQYDDRD.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-OTDEP6WZ.js.map +0 -1
  89. package/dist/chunk-UZ2E6LX7.js +0 -1147
  90. package/dist/chunk-UZ2E6LX7.js.map +0 -1
  91. package/dist/diff-ZN2YTGE2.js +0 -107
  92. package/dist/diff-ZN2YTGE2.js.map +0 -1
  93. package/dist/dist-HKVTEPU5.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-PGA7JFKM.js.map +0 -1
  102. package/dist/mcp-QTIA76DS.js +0 -17
  103. package/dist/mcp-QTIA76DS.js.map +0 -1
  104. package/dist/migrate-4KF6GHLO.js.map +0 -1
  105. package/dist/pack-DSOODXAN.js.map +0 -1
  106. package/dist/ready-GTCDQOIC.js.map +0 -1
  107. package/dist/skills-3GBBWZW2.js +0 -93
  108. package/dist/skills-3GBBWZW2.js.map +0 -1
  109. package/dist/status-C3YDBH2L.js.map +0 -1
  110. package/dist/update-ULMSL5XZ.js.map +0 -1
  111. package/dist/validate-E7F3Q5BE.js +0 -49
  112. package/dist/validate-E7F3Q5BE.js.map +0 -1
  113. /package/dist/{dist-4MXKMRHE.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
package/dist/index.js CHANGED
@@ -1,7 +1,1551 @@
1
- // src/commands/init.ts
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js
28
+ var require_constants = __commonJS({
29
+ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/constants.js"(exports, module) {
30
+ "use strict";
31
+ var WIN_SLASH = "\\\\/";
32
+ var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
33
+ var DOT_LITERAL = "\\.";
34
+ var PLUS_LITERAL = "\\+";
35
+ var QMARK_LITERAL = "\\?";
36
+ var SLASH_LITERAL = "\\/";
37
+ var ONE_CHAR = "(?=.)";
38
+ var QMARK = "[^/]";
39
+ var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
40
+ var START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
41
+ var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
42
+ var NO_DOT = `(?!${DOT_LITERAL})`;
43
+ var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
44
+ var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
45
+ var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
46
+ var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
47
+ var STAR = `${QMARK}*?`;
48
+ var SEP = "/";
49
+ var POSIX_CHARS = {
50
+ DOT_LITERAL,
51
+ PLUS_LITERAL,
52
+ QMARK_LITERAL,
53
+ SLASH_LITERAL,
54
+ ONE_CHAR,
55
+ QMARK,
56
+ END_ANCHOR,
57
+ DOTS_SLASH,
58
+ NO_DOT,
59
+ NO_DOTS,
60
+ NO_DOT_SLASH,
61
+ NO_DOTS_SLASH,
62
+ QMARK_NO_DOT,
63
+ STAR,
64
+ START_ANCHOR,
65
+ SEP
66
+ };
67
+ var WINDOWS_CHARS = {
68
+ ...POSIX_CHARS,
69
+ SLASH_LITERAL: `[${WIN_SLASH}]`,
70
+ QMARK: WIN_NO_SLASH,
71
+ STAR: `${WIN_NO_SLASH}*?`,
72
+ DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
73
+ NO_DOT: `(?!${DOT_LITERAL})`,
74
+ NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
75
+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
76
+ NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
77
+ QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
78
+ START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
79
+ END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
80
+ SEP: "\\"
81
+ };
82
+ var POSIX_REGEX_SOURCE = {
83
+ alnum: "a-zA-Z0-9",
84
+ alpha: "a-zA-Z",
85
+ ascii: "\\x00-\\x7F",
86
+ blank: " \\t",
87
+ cntrl: "\\x00-\\x1F\\x7F",
88
+ digit: "0-9",
89
+ graph: "\\x21-\\x7E",
90
+ lower: "a-z",
91
+ print: "\\x20-\\x7E ",
92
+ punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
93
+ space: " \\t\\r\\n\\v\\f",
94
+ upper: "A-Z",
95
+ word: "A-Za-z0-9_",
96
+ xdigit: "A-Fa-f0-9"
97
+ };
98
+ module.exports = {
99
+ MAX_LENGTH: 1024 * 64,
100
+ POSIX_REGEX_SOURCE,
101
+ // regular expressions
102
+ REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
103
+ REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
104
+ REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
105
+ REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
106
+ REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
107
+ REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
108
+ // Replace globs with equivalent patterns to reduce parsing time.
109
+ REPLACEMENTS: {
110
+ __proto__: null,
111
+ "***": "*",
112
+ "**/**": "**",
113
+ "**/**/**": "**"
114
+ },
115
+ // Digits
116
+ CHAR_0: 48,
117
+ /* 0 */
118
+ CHAR_9: 57,
119
+ /* 9 */
120
+ // Alphabet chars.
121
+ CHAR_UPPERCASE_A: 65,
122
+ /* A */
123
+ CHAR_LOWERCASE_A: 97,
124
+ /* a */
125
+ CHAR_UPPERCASE_Z: 90,
126
+ /* Z */
127
+ CHAR_LOWERCASE_Z: 122,
128
+ /* z */
129
+ CHAR_LEFT_PARENTHESES: 40,
130
+ /* ( */
131
+ CHAR_RIGHT_PARENTHESES: 41,
132
+ /* ) */
133
+ CHAR_ASTERISK: 42,
134
+ /* * */
135
+ // Non-alphabetic chars.
136
+ CHAR_AMPERSAND: 38,
137
+ /* & */
138
+ CHAR_AT: 64,
139
+ /* @ */
140
+ CHAR_BACKWARD_SLASH: 92,
141
+ /* \ */
142
+ CHAR_CARRIAGE_RETURN: 13,
143
+ /* \r */
144
+ CHAR_CIRCUMFLEX_ACCENT: 94,
145
+ /* ^ */
146
+ CHAR_COLON: 58,
147
+ /* : */
148
+ CHAR_COMMA: 44,
149
+ /* , */
150
+ CHAR_DOT: 46,
151
+ /* . */
152
+ CHAR_DOUBLE_QUOTE: 34,
153
+ /* " */
154
+ CHAR_EQUAL: 61,
155
+ /* = */
156
+ CHAR_EXCLAMATION_MARK: 33,
157
+ /* ! */
158
+ CHAR_FORM_FEED: 12,
159
+ /* \f */
160
+ CHAR_FORWARD_SLASH: 47,
161
+ /* / */
162
+ CHAR_GRAVE_ACCENT: 96,
163
+ /* ` */
164
+ CHAR_HASH: 35,
165
+ /* # */
166
+ CHAR_HYPHEN_MINUS: 45,
167
+ /* - */
168
+ CHAR_LEFT_ANGLE_BRACKET: 60,
169
+ /* < */
170
+ CHAR_LEFT_CURLY_BRACE: 123,
171
+ /* { */
172
+ CHAR_LEFT_SQUARE_BRACKET: 91,
173
+ /* [ */
174
+ CHAR_LINE_FEED: 10,
175
+ /* \n */
176
+ CHAR_NO_BREAK_SPACE: 160,
177
+ /* \u00A0 */
178
+ CHAR_PERCENT: 37,
179
+ /* % */
180
+ CHAR_PLUS: 43,
181
+ /* + */
182
+ CHAR_QUESTION_MARK: 63,
183
+ /* ? */
184
+ CHAR_RIGHT_ANGLE_BRACKET: 62,
185
+ /* > */
186
+ CHAR_RIGHT_CURLY_BRACE: 125,
187
+ /* } */
188
+ CHAR_RIGHT_SQUARE_BRACKET: 93,
189
+ /* ] */
190
+ CHAR_SEMICOLON: 59,
191
+ /* ; */
192
+ CHAR_SINGLE_QUOTE: 39,
193
+ /* ' */
194
+ CHAR_SPACE: 32,
195
+ /* */
196
+ CHAR_TAB: 9,
197
+ /* \t */
198
+ CHAR_UNDERSCORE: 95,
199
+ /* _ */
200
+ CHAR_VERTICAL_LINE: 124,
201
+ /* | */
202
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
203
+ /* \uFEFF */
204
+ /**
205
+ * Create EXTGLOB_CHARS
206
+ */
207
+ extglobChars(chars) {
208
+ return {
209
+ "!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` },
210
+ "?": { type: "qmark", open: "(?:", close: ")?" },
211
+ "+": { type: "plus", open: "(?:", close: ")+" },
212
+ "*": { type: "star", open: "(?:", close: ")*" },
213
+ "@": { type: "at", open: "(?:", close: ")" }
214
+ };
215
+ },
216
+ /**
217
+ * Create GLOB_CHARS
218
+ */
219
+ globChars(win32) {
220
+ return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
221
+ }
222
+ };
223
+ }
224
+ });
225
+
226
+ // ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js
227
+ var require_utils = __commonJS({
228
+ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/utils.js"(exports) {
229
+ "use strict";
230
+ var {
231
+ REGEX_BACKSLASH,
232
+ REGEX_REMOVE_BACKSLASH,
233
+ REGEX_SPECIAL_CHARS,
234
+ REGEX_SPECIAL_CHARS_GLOBAL
235
+ } = require_constants();
236
+ exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
237
+ exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
238
+ exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
239
+ exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
240
+ exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
241
+ exports.isWindows = () => {
242
+ if (typeof navigator !== "undefined" && navigator.platform) {
243
+ const platform = navigator.platform.toLowerCase();
244
+ return platform === "win32" || platform === "windows";
245
+ }
246
+ if (typeof process !== "undefined" && process.platform) {
247
+ return process.platform === "win32";
248
+ }
249
+ return false;
250
+ };
251
+ exports.removeBackslashes = (str) => {
252
+ return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
253
+ return match === "\\" ? "" : match;
254
+ });
255
+ };
256
+ exports.escapeLast = (input, char, lastIdx) => {
257
+ const idx = input.lastIndexOf(char, lastIdx);
258
+ if (idx === -1) return input;
259
+ if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1);
260
+ return `${input.slice(0, idx)}\\${input.slice(idx)}`;
261
+ };
262
+ exports.removePrefix = (input, state = {}) => {
263
+ let output = input;
264
+ if (output.startsWith("./")) {
265
+ output = output.slice(2);
266
+ state.prefix = "./";
267
+ }
268
+ return output;
269
+ };
270
+ exports.wrapOutput = (input, state = {}, options = {}) => {
271
+ const prepend = options.contains ? "" : "^";
272
+ const append = options.contains ? "" : "$";
273
+ let output = `${prepend}(?:${input})${append}`;
274
+ if (state.negated === true) {
275
+ output = `(?:^(?!${output}).*$)`;
276
+ }
277
+ return output;
278
+ };
279
+ exports.basename = (path, { windows } = {}) => {
280
+ const segs = path.split(windows ? /[\\/]/ : "/");
281
+ const last = segs[segs.length - 1];
282
+ if (last === "") {
283
+ return segs[segs.length - 2];
284
+ }
285
+ return last;
286
+ };
287
+ }
288
+ });
289
+
290
+ // ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js
291
+ var require_scan = __commonJS({
292
+ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/scan.js"(exports, module) {
293
+ "use strict";
294
+ var utils = require_utils();
295
+ var {
296
+ CHAR_ASTERISK,
297
+ /* * */
298
+ CHAR_AT,
299
+ /* @ */
300
+ CHAR_BACKWARD_SLASH,
301
+ /* \ */
302
+ CHAR_COMMA,
303
+ /* , */
304
+ CHAR_DOT,
305
+ /* . */
306
+ CHAR_EXCLAMATION_MARK,
307
+ /* ! */
308
+ CHAR_FORWARD_SLASH,
309
+ /* / */
310
+ CHAR_LEFT_CURLY_BRACE,
311
+ /* { */
312
+ CHAR_LEFT_PARENTHESES,
313
+ /* ( */
314
+ CHAR_LEFT_SQUARE_BRACKET,
315
+ /* [ */
316
+ CHAR_PLUS,
317
+ /* + */
318
+ CHAR_QUESTION_MARK,
319
+ /* ? */
320
+ CHAR_RIGHT_CURLY_BRACE,
321
+ /* } */
322
+ CHAR_RIGHT_PARENTHESES,
323
+ /* ) */
324
+ CHAR_RIGHT_SQUARE_BRACKET
325
+ /* ] */
326
+ } = require_constants();
327
+ var isPathSeparator = (code) => {
328
+ return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
329
+ };
330
+ var depth = (token) => {
331
+ if (token.isPrefix !== true) {
332
+ token.depth = token.isGlobstar ? Infinity : 1;
333
+ }
334
+ };
335
+ var scan = (input, options) => {
336
+ const opts = options || {};
337
+ const length = input.length - 1;
338
+ const scanToEnd = opts.parts === true || opts.scanToEnd === true;
339
+ const slashes = [];
340
+ const tokens = [];
341
+ const parts = [];
342
+ let str = input;
343
+ let index = -1;
344
+ let start = 0;
345
+ let lastIndex = 0;
346
+ let isBrace = false;
347
+ let isBracket = false;
348
+ let isGlob = false;
349
+ let isExtglob = false;
350
+ let isGlobstar = false;
351
+ let braceEscaped = false;
352
+ let backslashes = false;
353
+ let negated = false;
354
+ let negatedExtglob = false;
355
+ let finished = false;
356
+ let braces = 0;
357
+ let prev;
358
+ let code;
359
+ let token = { value: "", depth: 0, isGlob: false };
360
+ const eos = () => index >= length;
361
+ const peek = () => str.charCodeAt(index + 1);
362
+ const advance = () => {
363
+ prev = code;
364
+ return str.charCodeAt(++index);
365
+ };
366
+ while (index < length) {
367
+ code = advance();
368
+ let next;
369
+ if (code === CHAR_BACKWARD_SLASH) {
370
+ backslashes = token.backslashes = true;
371
+ code = advance();
372
+ if (code === CHAR_LEFT_CURLY_BRACE) {
373
+ braceEscaped = true;
374
+ }
375
+ continue;
376
+ }
377
+ if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
378
+ braces++;
379
+ while (eos() !== true && (code = advance())) {
380
+ if (code === CHAR_BACKWARD_SLASH) {
381
+ backslashes = token.backslashes = true;
382
+ advance();
383
+ continue;
384
+ }
385
+ if (code === CHAR_LEFT_CURLY_BRACE) {
386
+ braces++;
387
+ continue;
388
+ }
389
+ if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
390
+ isBrace = token.isBrace = true;
391
+ isGlob = token.isGlob = true;
392
+ finished = true;
393
+ if (scanToEnd === true) {
394
+ continue;
395
+ }
396
+ break;
397
+ }
398
+ if (braceEscaped !== true && code === CHAR_COMMA) {
399
+ isBrace = token.isBrace = true;
400
+ isGlob = token.isGlob = true;
401
+ finished = true;
402
+ if (scanToEnd === true) {
403
+ continue;
404
+ }
405
+ break;
406
+ }
407
+ if (code === CHAR_RIGHT_CURLY_BRACE) {
408
+ braces--;
409
+ if (braces === 0) {
410
+ braceEscaped = false;
411
+ isBrace = token.isBrace = true;
412
+ finished = true;
413
+ break;
414
+ }
415
+ }
416
+ }
417
+ if (scanToEnd === true) {
418
+ continue;
419
+ }
420
+ break;
421
+ }
422
+ if (code === CHAR_FORWARD_SLASH) {
423
+ slashes.push(index);
424
+ tokens.push(token);
425
+ token = { value: "", depth: 0, isGlob: false };
426
+ if (finished === true) continue;
427
+ if (prev === CHAR_DOT && index === start + 1) {
428
+ start += 2;
429
+ continue;
430
+ }
431
+ lastIndex = index + 1;
432
+ continue;
433
+ }
434
+ if (opts.noext !== true) {
435
+ const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
436
+ if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
437
+ isGlob = token.isGlob = true;
438
+ isExtglob = token.isExtglob = true;
439
+ finished = true;
440
+ if (code === CHAR_EXCLAMATION_MARK && index === start) {
441
+ negatedExtglob = true;
442
+ }
443
+ if (scanToEnd === true) {
444
+ while (eos() !== true && (code = advance())) {
445
+ if (code === CHAR_BACKWARD_SLASH) {
446
+ backslashes = token.backslashes = true;
447
+ code = advance();
448
+ continue;
449
+ }
450
+ if (code === CHAR_RIGHT_PARENTHESES) {
451
+ isGlob = token.isGlob = true;
452
+ finished = true;
453
+ break;
454
+ }
455
+ }
456
+ continue;
457
+ }
458
+ break;
459
+ }
460
+ }
461
+ if (code === CHAR_ASTERISK) {
462
+ if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
463
+ isGlob = token.isGlob = true;
464
+ finished = true;
465
+ if (scanToEnd === true) {
466
+ continue;
467
+ }
468
+ break;
469
+ }
470
+ if (code === CHAR_QUESTION_MARK) {
471
+ isGlob = token.isGlob = true;
472
+ finished = true;
473
+ if (scanToEnd === true) {
474
+ continue;
475
+ }
476
+ break;
477
+ }
478
+ if (code === CHAR_LEFT_SQUARE_BRACKET) {
479
+ while (eos() !== true && (next = advance())) {
480
+ if (next === CHAR_BACKWARD_SLASH) {
481
+ backslashes = token.backslashes = true;
482
+ advance();
483
+ continue;
484
+ }
485
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
486
+ isBracket = token.isBracket = true;
487
+ isGlob = token.isGlob = true;
488
+ finished = true;
489
+ break;
490
+ }
491
+ }
492
+ if (scanToEnd === true) {
493
+ continue;
494
+ }
495
+ break;
496
+ }
497
+ if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
498
+ negated = token.negated = true;
499
+ start++;
500
+ continue;
501
+ }
502
+ if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
503
+ isGlob = token.isGlob = true;
504
+ if (scanToEnd === true) {
505
+ while (eos() !== true && (code = advance())) {
506
+ if (code === CHAR_LEFT_PARENTHESES) {
507
+ backslashes = token.backslashes = true;
508
+ code = advance();
509
+ continue;
510
+ }
511
+ if (code === CHAR_RIGHT_PARENTHESES) {
512
+ finished = true;
513
+ break;
514
+ }
515
+ }
516
+ continue;
517
+ }
518
+ break;
519
+ }
520
+ if (isGlob === true) {
521
+ finished = true;
522
+ if (scanToEnd === true) {
523
+ continue;
524
+ }
525
+ break;
526
+ }
527
+ }
528
+ if (opts.noext === true) {
529
+ isExtglob = false;
530
+ isGlob = false;
531
+ }
532
+ let base = str;
533
+ let prefix = "";
534
+ let glob2 = "";
535
+ if (start > 0) {
536
+ prefix = str.slice(0, start);
537
+ str = str.slice(start);
538
+ lastIndex -= start;
539
+ }
540
+ if (base && isGlob === true && lastIndex > 0) {
541
+ base = str.slice(0, lastIndex);
542
+ glob2 = str.slice(lastIndex);
543
+ } else if (isGlob === true) {
544
+ base = "";
545
+ glob2 = str;
546
+ } else {
547
+ base = str;
548
+ }
549
+ if (base && base !== "" && base !== "/" && base !== str) {
550
+ if (isPathSeparator(base.charCodeAt(base.length - 1))) {
551
+ base = base.slice(0, -1);
552
+ }
553
+ }
554
+ if (opts.unescape === true) {
555
+ if (glob2) glob2 = utils.removeBackslashes(glob2);
556
+ if (base && backslashes === true) {
557
+ base = utils.removeBackslashes(base);
558
+ }
559
+ }
560
+ const state = {
561
+ prefix,
562
+ input,
563
+ start,
564
+ base,
565
+ glob: glob2,
566
+ isBrace,
567
+ isBracket,
568
+ isGlob,
569
+ isExtglob,
570
+ isGlobstar,
571
+ negated,
572
+ negatedExtglob
573
+ };
574
+ if (opts.tokens === true) {
575
+ state.maxDepth = 0;
576
+ if (!isPathSeparator(code)) {
577
+ tokens.push(token);
578
+ }
579
+ state.tokens = tokens;
580
+ }
581
+ if (opts.parts === true || opts.tokens === true) {
582
+ let prevIndex;
583
+ for (let idx = 0; idx < slashes.length; idx++) {
584
+ const n = prevIndex ? prevIndex + 1 : start;
585
+ const i = slashes[idx];
586
+ const value = input.slice(n, i);
587
+ if (opts.tokens) {
588
+ if (idx === 0 && start !== 0) {
589
+ tokens[idx].isPrefix = true;
590
+ tokens[idx].value = prefix;
591
+ } else {
592
+ tokens[idx].value = value;
593
+ }
594
+ depth(tokens[idx]);
595
+ state.maxDepth += tokens[idx].depth;
596
+ }
597
+ if (idx !== 0 || value !== "") {
598
+ parts.push(value);
599
+ }
600
+ prevIndex = i;
601
+ }
602
+ if (prevIndex && prevIndex + 1 < input.length) {
603
+ const value = input.slice(prevIndex + 1);
604
+ parts.push(value);
605
+ if (opts.tokens) {
606
+ tokens[tokens.length - 1].value = value;
607
+ depth(tokens[tokens.length - 1]);
608
+ state.maxDepth += tokens[tokens.length - 1].depth;
609
+ }
610
+ }
611
+ state.slashes = slashes;
612
+ state.parts = parts;
613
+ }
614
+ return state;
615
+ };
616
+ module.exports = scan;
617
+ }
618
+ });
619
+
620
+ // ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js
621
+ var require_parse = __commonJS({
622
+ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/parse.js"(exports, module) {
623
+ "use strict";
624
+ var constants = require_constants();
625
+ var utils = require_utils();
626
+ var {
627
+ MAX_LENGTH,
628
+ POSIX_REGEX_SOURCE,
629
+ REGEX_NON_SPECIAL_CHARS,
630
+ REGEX_SPECIAL_CHARS_BACKREF,
631
+ REPLACEMENTS
632
+ } = constants;
633
+ var expandRange = (args, options) => {
634
+ if (typeof options.expandRange === "function") {
635
+ return options.expandRange(...args, options);
636
+ }
637
+ args.sort();
638
+ const value = `[${args.join("-")}]`;
639
+ try {
640
+ new RegExp(value);
641
+ } catch (ex) {
642
+ return args.map((v) => utils.escapeRegex(v)).join("..");
643
+ }
644
+ return value;
645
+ };
646
+ var syntaxError = (type, char) => {
647
+ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
648
+ };
649
+ var parse = (input, options) => {
650
+ if (typeof input !== "string") {
651
+ throw new TypeError("Expected a string");
652
+ }
653
+ input = REPLACEMENTS[input] || input;
654
+ const opts = { ...options };
655
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
656
+ let len = input.length;
657
+ if (len > max) {
658
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
659
+ }
660
+ const bos = { type: "bos", value: "", output: opts.prepend || "" };
661
+ const tokens = [bos];
662
+ const capture = opts.capture ? "" : "?:";
663
+ const PLATFORM_CHARS = constants.globChars(opts.windows);
664
+ const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
665
+ const {
666
+ DOT_LITERAL,
667
+ PLUS_LITERAL,
668
+ SLASH_LITERAL,
669
+ ONE_CHAR,
670
+ DOTS_SLASH,
671
+ NO_DOT,
672
+ NO_DOT_SLASH,
673
+ NO_DOTS_SLASH,
674
+ QMARK,
675
+ QMARK_NO_DOT,
676
+ STAR,
677
+ START_ANCHOR
678
+ } = PLATFORM_CHARS;
679
+ const globstar = (opts2) => {
680
+ return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
681
+ };
682
+ const nodot = opts.dot ? "" : NO_DOT;
683
+ const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
684
+ let star = opts.bash === true ? globstar(opts) : STAR;
685
+ if (opts.capture) {
686
+ star = `(${star})`;
687
+ }
688
+ if (typeof opts.noext === "boolean") {
689
+ opts.noextglob = opts.noext;
690
+ }
691
+ const state = {
692
+ input,
693
+ index: -1,
694
+ start: 0,
695
+ dot: opts.dot === true,
696
+ consumed: "",
697
+ output: "",
698
+ prefix: "",
699
+ backtrack: false,
700
+ negated: false,
701
+ brackets: 0,
702
+ braces: 0,
703
+ parens: 0,
704
+ quotes: 0,
705
+ globstar: false,
706
+ tokens
707
+ };
708
+ input = utils.removePrefix(input, state);
709
+ len = input.length;
710
+ const extglobs = [];
711
+ const braces = [];
712
+ const stack = [];
713
+ let prev = bos;
714
+ let value;
715
+ const eos = () => state.index === len - 1;
716
+ const peek = state.peek = (n = 1) => input[state.index + n];
717
+ const advance = state.advance = () => input[++state.index] || "";
718
+ const remaining = () => input.slice(state.index + 1);
719
+ const consume = (value2 = "", num = 0) => {
720
+ state.consumed += value2;
721
+ state.index += num;
722
+ };
723
+ const append = (token) => {
724
+ state.output += token.output != null ? token.output : token.value;
725
+ consume(token.value);
726
+ };
727
+ const negate = () => {
728
+ let count = 1;
729
+ while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
730
+ advance();
731
+ state.start++;
732
+ count++;
733
+ }
734
+ if (count % 2 === 0) {
735
+ return false;
736
+ }
737
+ state.negated = true;
738
+ state.start++;
739
+ return true;
740
+ };
741
+ const increment = (type) => {
742
+ state[type]++;
743
+ stack.push(type);
744
+ };
745
+ const decrement = (type) => {
746
+ state[type]--;
747
+ stack.pop();
748
+ };
749
+ const push = (tok) => {
750
+ if (prev.type === "globstar") {
751
+ const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
752
+ const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
753
+ if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
754
+ state.output = state.output.slice(0, -prev.output.length);
755
+ prev.type = "star";
756
+ prev.value = "*";
757
+ prev.output = star;
758
+ state.output += prev.output;
759
+ }
760
+ }
761
+ if (extglobs.length && tok.type !== "paren") {
762
+ extglobs[extglobs.length - 1].inner += tok.value;
763
+ }
764
+ if (tok.value || tok.output) append(tok);
765
+ if (prev && prev.type === "text" && tok.type === "text") {
766
+ prev.output = (prev.output || prev.value) + tok.value;
767
+ prev.value += tok.value;
768
+ return;
769
+ }
770
+ tok.prev = prev;
771
+ tokens.push(tok);
772
+ prev = tok;
773
+ };
774
+ const extglobOpen = (type, value2) => {
775
+ const token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" };
776
+ token.prev = prev;
777
+ token.parens = state.parens;
778
+ token.output = state.output;
779
+ const output = (opts.capture ? "(" : "") + token.open;
780
+ increment("parens");
781
+ push({ type, value: value2, output: state.output ? "" : ONE_CHAR });
782
+ push({ type: "paren", extglob: true, value: advance(), output });
783
+ extglobs.push(token);
784
+ };
785
+ const extglobClose = (token) => {
786
+ let output = token.close + (opts.capture ? ")" : "");
787
+ let rest;
788
+ if (token.type === "negate") {
789
+ let extglobStar = star;
790
+ if (token.inner && token.inner.length > 1 && token.inner.includes("/")) {
791
+ extglobStar = globstar(opts);
792
+ }
793
+ if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
794
+ output = token.close = `)$))${extglobStar}`;
795
+ }
796
+ if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
797
+ const expression = parse(rest, { ...options, fastpaths: false }).output;
798
+ output = token.close = `)${expression})${extglobStar})`;
799
+ }
800
+ if (token.prev.type === "bos") {
801
+ state.negatedExtglob = true;
802
+ }
803
+ }
804
+ push({ type: "paren", extglob: true, value, output });
805
+ decrement("parens");
806
+ };
807
+ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
808
+ let backslashes = false;
809
+ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
810
+ if (first === "\\") {
811
+ backslashes = true;
812
+ return m;
813
+ }
814
+ if (first === "?") {
815
+ if (esc) {
816
+ return esc + first + (rest ? QMARK.repeat(rest.length) : "");
817
+ }
818
+ if (index === 0) {
819
+ return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : "");
820
+ }
821
+ return QMARK.repeat(chars.length);
822
+ }
823
+ if (first === ".") {
824
+ return DOT_LITERAL.repeat(chars.length);
825
+ }
826
+ if (first === "*") {
827
+ if (esc) {
828
+ return esc + first + (rest ? star : "");
829
+ }
830
+ return star;
831
+ }
832
+ return esc ? m : `\\${m}`;
833
+ });
834
+ if (backslashes === true) {
835
+ if (opts.unescape === true) {
836
+ output = output.replace(/\\/g, "");
837
+ } else {
838
+ output = output.replace(/\\+/g, (m) => {
839
+ return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
840
+ });
841
+ }
842
+ }
843
+ if (output === input && opts.contains === true) {
844
+ state.output = input;
845
+ return state;
846
+ }
847
+ state.output = utils.wrapOutput(output, state, options);
848
+ return state;
849
+ }
850
+ while (!eos()) {
851
+ value = advance();
852
+ if (value === "\0") {
853
+ continue;
854
+ }
855
+ if (value === "\\") {
856
+ const next = peek();
857
+ if (next === "/" && opts.bash !== true) {
858
+ continue;
859
+ }
860
+ if (next === "." || next === ";") {
861
+ continue;
862
+ }
863
+ if (!next) {
864
+ value += "\\";
865
+ push({ type: "text", value });
866
+ continue;
867
+ }
868
+ const match = /^\\+/.exec(remaining());
869
+ let slashes = 0;
870
+ if (match && match[0].length > 2) {
871
+ slashes = match[0].length;
872
+ state.index += slashes;
873
+ if (slashes % 2 !== 0) {
874
+ value += "\\";
875
+ }
876
+ }
877
+ if (opts.unescape === true) {
878
+ value = advance();
879
+ } else {
880
+ value += advance();
881
+ }
882
+ if (state.brackets === 0) {
883
+ push({ type: "text", value });
884
+ continue;
885
+ }
886
+ }
887
+ if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
888
+ if (opts.posix !== false && value === ":") {
889
+ const inner = prev.value.slice(1);
890
+ if (inner.includes("[")) {
891
+ prev.posix = true;
892
+ if (inner.includes(":")) {
893
+ const idx = prev.value.lastIndexOf("[");
894
+ const pre = prev.value.slice(0, idx);
895
+ const rest2 = prev.value.slice(idx + 2);
896
+ const posix = POSIX_REGEX_SOURCE[rest2];
897
+ if (posix) {
898
+ prev.value = pre + posix;
899
+ state.backtrack = true;
900
+ advance();
901
+ if (!bos.output && tokens.indexOf(prev) === 1) {
902
+ bos.output = ONE_CHAR;
903
+ }
904
+ continue;
905
+ }
906
+ }
907
+ }
908
+ }
909
+ if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") {
910
+ value = `\\${value}`;
911
+ }
912
+ if (value === "]" && (prev.value === "[" || prev.value === "[^")) {
913
+ value = `\\${value}`;
914
+ }
915
+ if (opts.posix === true && value === "!" && prev.value === "[") {
916
+ value = "^";
917
+ }
918
+ prev.value += value;
919
+ append({ value });
920
+ continue;
921
+ }
922
+ if (state.quotes === 1 && value !== '"') {
923
+ value = utils.escapeRegex(value);
924
+ prev.value += value;
925
+ append({ value });
926
+ continue;
927
+ }
928
+ if (value === '"') {
929
+ state.quotes = state.quotes === 1 ? 0 : 1;
930
+ if (opts.keepQuotes === true) {
931
+ push({ type: "text", value });
932
+ }
933
+ continue;
934
+ }
935
+ if (value === "(") {
936
+ increment("parens");
937
+ push({ type: "paren", value });
938
+ continue;
939
+ }
940
+ if (value === ")") {
941
+ if (state.parens === 0 && opts.strictBrackets === true) {
942
+ throw new SyntaxError(syntaxError("opening", "("));
943
+ }
944
+ const extglob = extglobs[extglobs.length - 1];
945
+ if (extglob && state.parens === extglob.parens + 1) {
946
+ extglobClose(extglobs.pop());
947
+ continue;
948
+ }
949
+ push({ type: "paren", value, output: state.parens ? ")" : "\\)" });
950
+ decrement("parens");
951
+ continue;
952
+ }
953
+ if (value === "[") {
954
+ if (opts.nobracket === true || !remaining().includes("]")) {
955
+ if (opts.nobracket !== true && opts.strictBrackets === true) {
956
+ throw new SyntaxError(syntaxError("closing", "]"));
957
+ }
958
+ value = `\\${value}`;
959
+ } else {
960
+ increment("brackets");
961
+ }
962
+ push({ type: "bracket", value });
963
+ continue;
964
+ }
965
+ if (value === "]") {
966
+ if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
967
+ push({ type: "text", value, output: `\\${value}` });
968
+ continue;
969
+ }
970
+ if (state.brackets === 0) {
971
+ if (opts.strictBrackets === true) {
972
+ throw new SyntaxError(syntaxError("opening", "["));
973
+ }
974
+ push({ type: "text", value, output: `\\${value}` });
975
+ continue;
976
+ }
977
+ decrement("brackets");
978
+ const prevValue = prev.value.slice(1);
979
+ if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) {
980
+ value = `/${value}`;
981
+ }
982
+ prev.value += value;
983
+ append({ value });
984
+ if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
985
+ continue;
986
+ }
987
+ const escaped = utils.escapeRegex(prev.value);
988
+ state.output = state.output.slice(0, -prev.value.length);
989
+ if (opts.literalBrackets === true) {
990
+ state.output += escaped;
991
+ prev.value = escaped;
992
+ continue;
993
+ }
994
+ prev.value = `(${capture}${escaped}|${prev.value})`;
995
+ state.output += prev.value;
996
+ continue;
997
+ }
998
+ if (value === "{" && opts.nobrace !== true) {
999
+ increment("braces");
1000
+ const open = {
1001
+ type: "brace",
1002
+ value,
1003
+ output: "(",
1004
+ outputIndex: state.output.length,
1005
+ tokensIndex: state.tokens.length
1006
+ };
1007
+ braces.push(open);
1008
+ push(open);
1009
+ continue;
1010
+ }
1011
+ if (value === "}") {
1012
+ const brace = braces[braces.length - 1];
1013
+ if (opts.nobrace === true || !brace) {
1014
+ push({ type: "text", value, output: value });
1015
+ continue;
1016
+ }
1017
+ let output = ")";
1018
+ if (brace.dots === true) {
1019
+ const arr = tokens.slice();
1020
+ const range = [];
1021
+ for (let i = arr.length - 1; i >= 0; i--) {
1022
+ tokens.pop();
1023
+ if (arr[i].type === "brace") {
1024
+ break;
1025
+ }
1026
+ if (arr[i].type !== "dots") {
1027
+ range.unshift(arr[i].value);
1028
+ }
1029
+ }
1030
+ output = expandRange(range, opts);
1031
+ state.backtrack = true;
1032
+ }
1033
+ if (brace.comma !== true && brace.dots !== true) {
1034
+ const out = state.output.slice(0, brace.outputIndex);
1035
+ const toks = state.tokens.slice(brace.tokensIndex);
1036
+ brace.value = brace.output = "\\{";
1037
+ value = output = "\\}";
1038
+ state.output = out;
1039
+ for (const t of toks) {
1040
+ state.output += t.output || t.value;
1041
+ }
1042
+ }
1043
+ push({ type: "brace", value, output });
1044
+ decrement("braces");
1045
+ braces.pop();
1046
+ continue;
1047
+ }
1048
+ if (value === "|") {
1049
+ if (extglobs.length > 0) {
1050
+ extglobs[extglobs.length - 1].conditions++;
1051
+ }
1052
+ push({ type: "text", value });
1053
+ continue;
1054
+ }
1055
+ if (value === ",") {
1056
+ let output = value;
1057
+ const brace = braces[braces.length - 1];
1058
+ if (brace && stack[stack.length - 1] === "braces") {
1059
+ brace.comma = true;
1060
+ output = "|";
1061
+ }
1062
+ push({ type: "comma", value, output });
1063
+ continue;
1064
+ }
1065
+ if (value === "/") {
1066
+ if (prev.type === "dot" && state.index === state.start + 1) {
1067
+ state.start = state.index + 1;
1068
+ state.consumed = "";
1069
+ state.output = "";
1070
+ tokens.pop();
1071
+ prev = bos;
1072
+ continue;
1073
+ }
1074
+ push({ type: "slash", value, output: SLASH_LITERAL });
1075
+ continue;
1076
+ }
1077
+ if (value === ".") {
1078
+ if (state.braces > 0 && prev.type === "dot") {
1079
+ if (prev.value === ".") prev.output = DOT_LITERAL;
1080
+ const brace = braces[braces.length - 1];
1081
+ prev.type = "dots";
1082
+ prev.output += value;
1083
+ prev.value += value;
1084
+ brace.dots = true;
1085
+ continue;
1086
+ }
1087
+ if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
1088
+ push({ type: "text", value, output: DOT_LITERAL });
1089
+ continue;
1090
+ }
1091
+ push({ type: "dot", value, output: DOT_LITERAL });
1092
+ continue;
1093
+ }
1094
+ if (value === "?") {
1095
+ const isGroup = prev && prev.value === "(";
1096
+ if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1097
+ extglobOpen("qmark", value);
1098
+ continue;
1099
+ }
1100
+ if (prev && prev.type === "paren") {
1101
+ const next = peek();
1102
+ let output = value;
1103
+ if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
1104
+ output = `\\${value}`;
1105
+ }
1106
+ push({ type: "text", value, output });
1107
+ continue;
1108
+ }
1109
+ if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
1110
+ push({ type: "qmark", value, output: QMARK_NO_DOT });
1111
+ continue;
1112
+ }
1113
+ push({ type: "qmark", value, output: QMARK });
1114
+ continue;
1115
+ }
1116
+ if (value === "!") {
1117
+ if (opts.noextglob !== true && peek() === "(") {
1118
+ if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
1119
+ extglobOpen("negate", value);
1120
+ continue;
1121
+ }
1122
+ }
1123
+ if (opts.nonegate !== true && state.index === 0) {
1124
+ negate();
1125
+ continue;
1126
+ }
1127
+ }
1128
+ if (value === "+") {
1129
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1130
+ extglobOpen("plus", value);
1131
+ continue;
1132
+ }
1133
+ if (prev && prev.value === "(" || opts.regex === false) {
1134
+ push({ type: "plus", value, output: PLUS_LITERAL });
1135
+ continue;
1136
+ }
1137
+ if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
1138
+ push({ type: "plus", value });
1139
+ continue;
1140
+ }
1141
+ push({ type: "plus", value: PLUS_LITERAL });
1142
+ continue;
1143
+ }
1144
+ if (value === "@") {
1145
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1146
+ push({ type: "at", extglob: true, value, output: "" });
1147
+ continue;
1148
+ }
1149
+ push({ type: "text", value });
1150
+ continue;
1151
+ }
1152
+ if (value !== "*") {
1153
+ if (value === "$" || value === "^") {
1154
+ value = `\\${value}`;
1155
+ }
1156
+ const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
1157
+ if (match) {
1158
+ value += match[0];
1159
+ state.index += match[0].length;
1160
+ }
1161
+ push({ type: "text", value });
1162
+ continue;
1163
+ }
1164
+ if (prev && (prev.type === "globstar" || prev.star === true)) {
1165
+ prev.type = "star";
1166
+ prev.star = true;
1167
+ prev.value += value;
1168
+ prev.output = star;
1169
+ state.backtrack = true;
1170
+ state.globstar = true;
1171
+ consume(value);
1172
+ continue;
1173
+ }
1174
+ let rest = remaining();
1175
+ if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
1176
+ extglobOpen("star", value);
1177
+ continue;
1178
+ }
1179
+ if (prev.type === "star") {
1180
+ if (opts.noglobstar === true) {
1181
+ consume(value);
1182
+ continue;
1183
+ }
1184
+ const prior = prev.prev;
1185
+ const before = prior.prev;
1186
+ const isStart = prior.type === "slash" || prior.type === "bos";
1187
+ const afterStar = before && (before.type === "star" || before.type === "globstar");
1188
+ if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
1189
+ push({ type: "star", value, output: "" });
1190
+ continue;
1191
+ }
1192
+ const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
1193
+ const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
1194
+ if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
1195
+ push({ type: "star", value, output: "" });
1196
+ continue;
1197
+ }
1198
+ while (rest.slice(0, 3) === "/**") {
1199
+ const after = input[state.index + 4];
1200
+ if (after && after !== "/") {
1201
+ break;
1202
+ }
1203
+ rest = rest.slice(3);
1204
+ consume("/**", 3);
1205
+ }
1206
+ if (prior.type === "bos" && eos()) {
1207
+ prev.type = "globstar";
1208
+ prev.value += value;
1209
+ prev.output = globstar(opts);
1210
+ state.output = prev.output;
1211
+ state.globstar = true;
1212
+ consume(value);
1213
+ continue;
1214
+ }
1215
+ if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
1216
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
1217
+ prior.output = `(?:${prior.output}`;
1218
+ prev.type = "globstar";
1219
+ prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
1220
+ prev.value += value;
1221
+ state.globstar = true;
1222
+ state.output += prior.output + prev.output;
1223
+ consume(value);
1224
+ continue;
1225
+ }
1226
+ if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
1227
+ const end = rest[1] !== void 0 ? "|$" : "";
1228
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
1229
+ prior.output = `(?:${prior.output}`;
1230
+ prev.type = "globstar";
1231
+ prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
1232
+ prev.value += value;
1233
+ state.output += prior.output + prev.output;
1234
+ state.globstar = true;
1235
+ consume(value + advance());
1236
+ push({ type: "slash", value: "/", output: "" });
1237
+ continue;
1238
+ }
1239
+ if (prior.type === "bos" && rest[0] === "/") {
1240
+ prev.type = "globstar";
1241
+ prev.value += value;
1242
+ prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
1243
+ state.output = prev.output;
1244
+ state.globstar = true;
1245
+ consume(value + advance());
1246
+ push({ type: "slash", value: "/", output: "" });
1247
+ continue;
1248
+ }
1249
+ state.output = state.output.slice(0, -prev.output.length);
1250
+ prev.type = "globstar";
1251
+ prev.output = globstar(opts);
1252
+ prev.value += value;
1253
+ state.output += prev.output;
1254
+ state.globstar = true;
1255
+ consume(value);
1256
+ continue;
1257
+ }
1258
+ const token = { type: "star", value, output: star };
1259
+ if (opts.bash === true) {
1260
+ token.output = ".*?";
1261
+ if (prev.type === "bos" || prev.type === "slash") {
1262
+ token.output = nodot + token.output;
1263
+ }
1264
+ push(token);
1265
+ continue;
1266
+ }
1267
+ if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
1268
+ token.output = value;
1269
+ push(token);
1270
+ continue;
1271
+ }
1272
+ if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
1273
+ if (prev.type === "dot") {
1274
+ state.output += NO_DOT_SLASH;
1275
+ prev.output += NO_DOT_SLASH;
1276
+ } else if (opts.dot === true) {
1277
+ state.output += NO_DOTS_SLASH;
1278
+ prev.output += NO_DOTS_SLASH;
1279
+ } else {
1280
+ state.output += nodot;
1281
+ prev.output += nodot;
1282
+ }
1283
+ if (peek() !== "*") {
1284
+ state.output += ONE_CHAR;
1285
+ prev.output += ONE_CHAR;
1286
+ }
1287
+ }
1288
+ push(token);
1289
+ }
1290
+ while (state.brackets > 0) {
1291
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
1292
+ state.output = utils.escapeLast(state.output, "[");
1293
+ decrement("brackets");
1294
+ }
1295
+ while (state.parens > 0) {
1296
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")"));
1297
+ state.output = utils.escapeLast(state.output, "(");
1298
+ decrement("parens");
1299
+ }
1300
+ while (state.braces > 0) {
1301
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}"));
1302
+ state.output = utils.escapeLast(state.output, "{");
1303
+ decrement("braces");
1304
+ }
1305
+ if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) {
1306
+ push({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` });
1307
+ }
1308
+ if (state.backtrack === true) {
1309
+ state.output = "";
1310
+ for (const token of state.tokens) {
1311
+ state.output += token.output != null ? token.output : token.value;
1312
+ if (token.suffix) {
1313
+ state.output += token.suffix;
1314
+ }
1315
+ }
1316
+ }
1317
+ return state;
1318
+ };
1319
+ parse.fastpaths = (input, options) => {
1320
+ const opts = { ...options };
1321
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1322
+ const len = input.length;
1323
+ if (len > max) {
1324
+ throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1325
+ }
1326
+ input = REPLACEMENTS[input] || input;
1327
+ const {
1328
+ DOT_LITERAL,
1329
+ SLASH_LITERAL,
1330
+ ONE_CHAR,
1331
+ DOTS_SLASH,
1332
+ NO_DOT,
1333
+ NO_DOTS,
1334
+ NO_DOTS_SLASH,
1335
+ STAR,
1336
+ START_ANCHOR
1337
+ } = constants.globChars(opts.windows);
1338
+ const nodot = opts.dot ? NO_DOTS : NO_DOT;
1339
+ const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
1340
+ const capture = opts.capture ? "" : "?:";
1341
+ const state = { negated: false, prefix: "" };
1342
+ let star = opts.bash === true ? ".*?" : STAR;
1343
+ if (opts.capture) {
1344
+ star = `(${star})`;
1345
+ }
1346
+ const globstar = (opts2) => {
1347
+ if (opts2.noglobstar === true) return star;
1348
+ return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
1349
+ };
1350
+ const create = (str) => {
1351
+ switch (str) {
1352
+ case "*":
1353
+ return `${nodot}${ONE_CHAR}${star}`;
1354
+ case ".*":
1355
+ return `${DOT_LITERAL}${ONE_CHAR}${star}`;
1356
+ case "*.*":
1357
+ return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
1358
+ case "*/*":
1359
+ return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
1360
+ case "**":
1361
+ return nodot + globstar(opts);
1362
+ case "**/*":
1363
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
1364
+ case "**/*.*":
1365
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
1366
+ case "**/.*":
1367
+ return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
1368
+ default: {
1369
+ const match = /^(.*?)\.(\w+)$/.exec(str);
1370
+ if (!match) return;
1371
+ const source2 = create(match[1]);
1372
+ if (!source2) return;
1373
+ return source2 + DOT_LITERAL + match[2];
1374
+ }
1375
+ }
1376
+ };
1377
+ const output = utils.removePrefix(input, state);
1378
+ let source = create(output);
1379
+ if (source && opts.strictSlashes !== true) {
1380
+ source += `${SLASH_LITERAL}?`;
1381
+ }
1382
+ return source;
1383
+ };
1384
+ module.exports = parse;
1385
+ }
1386
+ });
1387
+
1388
+ // ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js
1389
+ var require_picomatch = __commonJS({
1390
+ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/lib/picomatch.js"(exports, module) {
1391
+ "use strict";
1392
+ var scan = require_scan();
1393
+ var parse = require_parse();
1394
+ var utils = require_utils();
1395
+ var constants = require_constants();
1396
+ var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
1397
+ var picomatch2 = (glob2, options, returnState = false) => {
1398
+ if (Array.isArray(glob2)) {
1399
+ const fns = glob2.map((input) => picomatch2(input, options, returnState));
1400
+ const arrayMatcher = (str) => {
1401
+ for (const isMatch of fns) {
1402
+ const state2 = isMatch(str);
1403
+ if (state2) return state2;
1404
+ }
1405
+ return false;
1406
+ };
1407
+ return arrayMatcher;
1408
+ }
1409
+ const isState = isObject(glob2) && glob2.tokens && glob2.input;
1410
+ if (glob2 === "" || typeof glob2 !== "string" && !isState) {
1411
+ throw new TypeError("Expected pattern to be a non-empty string");
1412
+ }
1413
+ const opts = options || {};
1414
+ const posix = opts.windows;
1415
+ const regex = isState ? picomatch2.compileRe(glob2, options) : picomatch2.makeRe(glob2, options, false, true);
1416
+ const state = regex.state;
1417
+ delete regex.state;
1418
+ let isIgnored = () => false;
1419
+ if (opts.ignore) {
1420
+ const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
1421
+ isIgnored = picomatch2(opts.ignore, ignoreOpts, returnState);
1422
+ }
1423
+ const matcher = (input, returnObject = false) => {
1424
+ const { isMatch, match, output } = picomatch2.test(input, regex, options, { glob: glob2, posix });
1425
+ const result = { glob: glob2, state, regex, posix, input, output, match, isMatch };
1426
+ if (typeof opts.onResult === "function") {
1427
+ opts.onResult(result);
1428
+ }
1429
+ if (isMatch === false) {
1430
+ result.isMatch = false;
1431
+ return returnObject ? result : false;
1432
+ }
1433
+ if (isIgnored(input)) {
1434
+ if (typeof opts.onIgnore === "function") {
1435
+ opts.onIgnore(result);
1436
+ }
1437
+ result.isMatch = false;
1438
+ return returnObject ? result : false;
1439
+ }
1440
+ if (typeof opts.onMatch === "function") {
1441
+ opts.onMatch(result);
1442
+ }
1443
+ return returnObject ? result : true;
1444
+ };
1445
+ if (returnState) {
1446
+ matcher.state = state;
1447
+ }
1448
+ return matcher;
1449
+ };
1450
+ picomatch2.test = (input, regex, options, { glob: glob2, posix } = {}) => {
1451
+ if (typeof input !== "string") {
1452
+ throw new TypeError("Expected input to be a string");
1453
+ }
1454
+ if (input === "") {
1455
+ return { isMatch: false, output: "" };
1456
+ }
1457
+ const opts = options || {};
1458
+ const format = opts.format || (posix ? utils.toPosixSlashes : null);
1459
+ let match = input === glob2;
1460
+ let output = match && format ? format(input) : input;
1461
+ if (match === false) {
1462
+ output = format ? format(input) : input;
1463
+ match = output === glob2;
1464
+ }
1465
+ if (match === false || opts.capture === true) {
1466
+ if (opts.matchBase === true || opts.basename === true) {
1467
+ match = picomatch2.matchBase(input, regex, options, posix);
1468
+ } else {
1469
+ match = regex.exec(output);
1470
+ }
1471
+ }
1472
+ return { isMatch: Boolean(match), match, output };
1473
+ };
1474
+ picomatch2.matchBase = (input, glob2, options) => {
1475
+ const regex = glob2 instanceof RegExp ? glob2 : picomatch2.makeRe(glob2, options);
1476
+ return regex.test(utils.basename(input));
1477
+ };
1478
+ picomatch2.isMatch = (str, patterns, options) => picomatch2(patterns, options)(str);
1479
+ picomatch2.parse = (pattern, options) => {
1480
+ if (Array.isArray(pattern)) return pattern.map((p) => picomatch2.parse(p, options));
1481
+ return parse(pattern, { ...options, fastpaths: false });
1482
+ };
1483
+ picomatch2.scan = (input, options) => scan(input, options);
1484
+ picomatch2.compileRe = (state, options, returnOutput = false, returnState = false) => {
1485
+ if (returnOutput === true) {
1486
+ return state.output;
1487
+ }
1488
+ const opts = options || {};
1489
+ const prepend = opts.contains ? "" : "^";
1490
+ const append = opts.contains ? "" : "$";
1491
+ let source = `${prepend}(?:${state.output})${append}`;
1492
+ if (state && state.negated === true) {
1493
+ source = `^(?!${source}).*$`;
1494
+ }
1495
+ const regex = picomatch2.toRegex(source, options);
1496
+ if (returnState === true) {
1497
+ regex.state = state;
1498
+ }
1499
+ return regex;
1500
+ };
1501
+ picomatch2.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
1502
+ if (!input || typeof input !== "string") {
1503
+ throw new TypeError("Expected a non-empty string");
1504
+ }
1505
+ let parsed = { negated: false, fastpaths: true };
1506
+ if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
1507
+ parsed.output = parse.fastpaths(input, options);
1508
+ }
1509
+ if (!parsed.output) {
1510
+ parsed = parse(input, options);
1511
+ }
1512
+ return picomatch2.compileRe(parsed, options, returnOutput, returnState);
1513
+ };
1514
+ picomatch2.toRegex = (source, options) => {
1515
+ try {
1516
+ const opts = options || {};
1517
+ return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
1518
+ } catch (err) {
1519
+ if (options && options.debug === true) throw err;
1520
+ return /$^/;
1521
+ }
1522
+ };
1523
+ picomatch2.constants = constants;
1524
+ module.exports = picomatch2;
1525
+ }
1526
+ });
1527
+
1528
+ // ../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js
1529
+ var require_picomatch2 = __commonJS({
1530
+ "../../node_modules/.pnpm/picomatch@4.0.3/node_modules/picomatch/index.js"(exports, module) {
1531
+ "use strict";
1532
+ var pico = require_picomatch();
1533
+ var utils = require_utils();
1534
+ function picomatch2(glob2, options, returnState = false) {
1535
+ if (options && (options.windows === null || options.windows === void 0)) {
1536
+ options = { ...options, windows: utils.isWindows() };
1537
+ }
1538
+ return pico(glob2, options, returnState);
1539
+ }
1540
+ Object.assign(picomatch2, pico);
1541
+ module.exports = picomatch2;
1542
+ }
1543
+ });
1544
+
1545
+ // src/commands/core/init.ts
2
1546
  import { defineCommand } from "citty";
3
1547
  import { mkdir, writeFile } from "fs/promises";
4
- import { join } from "path";
1548
+ import { join, basename, resolve } from "path";
5
1549
 
6
1550
  // ../schema/dist/types.js
7
1551
  var SPEC_TYPES = [
@@ -15,6 +1559,10 @@ var SPEC_TYPES = [
15
1559
  "quick-spec",
16
1560
  "project-context"
17
1561
  ];
1562
+ var DEPENDENCY_RELATIONSHIPS = {
1563
+ "depends-on": "self-requires-target",
1564
+ "implemented-by": "target-requires-self"
1565
+ };
18
1566
 
19
1567
  // ../schema/dist/sections.js
20
1568
  var REQUIRED_SECTIONS = {
@@ -168,7 +1716,7 @@ var base_spec_default = {
168
1716
 
169
1717
  // ../schema/dist/schemas/config.json
170
1718
  var config_default = {
171
- $id: "sdx-config",
1719
+ $id: "specdx-config",
172
1720
  $schema: "http://json-schema.org/draft-07/schema#",
173
1721
  type: "object",
174
1722
  properties: {
@@ -428,7 +1976,7 @@ function validateConfig(data) {
428
1976
  return { valid: !!valid, errors: valid ? null : configValidator.errors ?? null };
429
1977
  }
430
1978
 
431
- // src/commands/init.ts
1979
+ // src/commands/core/init.ts
432
1980
  var TEMPLATE_SPECS = {
433
1981
  lightweight: [
434
1982
  { filename: "prd.md", type: "prd" },
@@ -497,6 +2045,9 @@ async function scaffoldProject({
497
2045
  template,
498
2046
  targetDir
499
2047
  }) {
2048
+ if (!targetDir) {
2049
+ throw new TypeError("scaffoldProject requires `targetDir` \u2014 where to create the project.");
2050
+ }
500
2051
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
501
2052
  const specsDir = join(targetDir, "specs");
502
2053
  await mkdir(specsDir, { recursive: true });
@@ -511,6 +2062,10 @@ async function scaffoldProject({
511
2062
  const configContent = buildConfigYaml(projectName, specs);
512
2063
  await writeFile(join(targetDir, "spec.config.yaml"), configContent, "utf-8");
513
2064
  }
2065
+ function defaultProjectName(dir) {
2066
+ return basename(resolve(dir)) || "my-project";
2067
+ }
2068
+ var VALID_TEMPLATES = ["lightweight", "bmad", "api-first", "quick", "context"];
514
2069
  var init_default = defineCommand({
515
2070
  meta: {
516
2071
  name: "init",
@@ -519,12 +2074,11 @@ var init_default = defineCommand({
519
2074
  args: {
520
2075
  name: {
521
2076
  type: "string",
522
- description: "Project name",
523
- required: true
2077
+ description: "Project name (default: the target directory's name)"
524
2078
  },
525
2079
  template: {
526
2080
  type: "string",
527
- description: "Template to use (lightweight, bmad, api-first)",
2081
+ description: `Template to use (${VALID_TEMPLATES.join(", ")})`,
528
2082
  default: "lightweight"
529
2083
  },
530
2084
  dir: {
@@ -534,19 +2088,19 @@ var init_default = defineCommand({
534
2088
  }
535
2089
  },
536
2090
  async run({ args }) {
537
- const { name, template, dir } = args;
538
- const validTemplates = ["lightweight", "bmad", "api-first", "quick", "context"];
539
- if (!validTemplates.includes(template)) {
540
- console.error(`Unknown template: ${template}. Choose from: ${validTemplates.join(", ")}`);
2091
+ const { template, dir } = args;
2092
+ if (!VALID_TEMPLATES.includes(template)) {
2093
+ console.error(`Unknown template: ${template}. Choose from: ${VALID_TEMPLATES.join(", ")}`);
541
2094
  process.exit(1);
542
2095
  }
2096
+ const name = args.name || defaultProjectName(dir);
543
2097
  console.log(`Scaffolding "${name}" with template "${template}" in ${dir}...`);
544
2098
  await scaffoldProject({ projectName: name, template, targetDir: dir });
545
2099
  console.log(`Done! Project "${name}" scaffolded successfully.`);
546
2100
  }
547
2101
  });
548
2102
 
549
- // src/commands/lint.ts
2103
+ // src/commands/core/lint.ts
550
2104
  import { defineCommand as defineCommand2 } from "citty";
551
2105
 
552
2106
  // ../core/dist/config.js
@@ -565,7 +2119,7 @@ var CONFIG_FILENAME = "spec.config.yaml";
565
2119
  async function loadConfig(filePath, searchFrom) {
566
2120
  const resolvedPath = filePath ?? await findConfig(searchFrom ?? process.cwd());
567
2121
  if (!resolvedPath) {
568
- throw new ConfigError(`No ${CONFIG_FILENAME} found. Run 'sdx init' to create one.`);
2122
+ throw new ConfigError(`No ${CONFIG_FILENAME} found. Run 'specdx init' to create one.`);
569
2123
  }
570
2124
  let raw;
571
2125
  try {
@@ -809,6 +2363,112 @@ function buildGraph(config) {
809
2363
  };
810
2364
  }
811
2365
 
2366
+ // ../core/dist/relations.js
2367
+ function mapEntriesToIds(config, specsByEntry) {
2368
+ const entryIds = /* @__PURE__ */ new Map();
2369
+ for (const key of Object.keys(config.specs)) {
2370
+ const ids = [];
2371
+ for (const spec of specsByEntry.get(key) ?? []) {
2372
+ const id = spec.frontmatter.id;
2373
+ if (typeof id === "string")
2374
+ ids.push(id);
2375
+ }
2376
+ entryIds.set(key, ids);
2377
+ }
2378
+ return entryIds;
2379
+ }
2380
+ function collectKnownIds(specsByEntry) {
2381
+ const ids = /* @__PURE__ */ new Set();
2382
+ for (const specs of specsByEntry.values()) {
2383
+ for (const spec of specs) {
2384
+ const id = spec.frontmatter.id;
2385
+ if (typeof id === "string")
2386
+ ids.add(id);
2387
+ }
2388
+ }
2389
+ return ids;
2390
+ }
2391
+ function walk(specId, adjacency) {
2392
+ const visited = /* @__PURE__ */ new Set();
2393
+ const stack = [specId];
2394
+ while (stack.length > 0) {
2395
+ const current = stack.pop();
2396
+ for (const next of adjacency.get(current) ?? []) {
2397
+ if (!visited.has(next)) {
2398
+ visited.add(next);
2399
+ stack.push(next);
2400
+ }
2401
+ }
2402
+ }
2403
+ visited.delete(specId);
2404
+ return [...visited];
2405
+ }
2406
+ function buildRelationResolver(config, specsByEntry) {
2407
+ const entryIds = config ? mapEntriesToIds(config, specsByEntry) : /* @__PURE__ */ new Map();
2408
+ const knownIds = collectKnownIds(specsByEntry);
2409
+ const edgeSources = /* @__PURE__ */ new Map();
2410
+ const addEdge = (from, to, source) => {
2411
+ if (from === to)
2412
+ return;
2413
+ const key = `${from}\0${to}`;
2414
+ const existing = edgeSources.get(key);
2415
+ if (!existing) {
2416
+ edgeSources.set(key, source);
2417
+ } else if (existing !== source) {
2418
+ edgeSources.set(key, "both");
2419
+ }
2420
+ };
2421
+ for (const [key, entry] of Object.entries(config?.specs ?? {})) {
2422
+ const requires = entry.requires ?? [];
2423
+ for (const dep of requires) {
2424
+ for (const from of entryIds.get(dep) ?? []) {
2425
+ for (const to of entryIds.get(key) ?? []) {
2426
+ addEdge(from, to, "requires");
2427
+ }
2428
+ }
2429
+ }
2430
+ }
2431
+ for (const specs of specsByEntry.values()) {
2432
+ for (const spec of specs) {
2433
+ const selfId = spec.frontmatter.id;
2434
+ if (typeof selfId !== "string")
2435
+ continue;
2436
+ const refs = spec.frontmatter.references;
2437
+ if (!Array.isArray(refs))
2438
+ continue;
2439
+ for (const ref of refs) {
2440
+ if (!ref || typeof ref !== "object")
2441
+ continue;
2442
+ const { id: targetId, relationship } = ref;
2443
+ if (typeof targetId !== "string" || typeof relationship !== "string")
2444
+ continue;
2445
+ if (!knownIds.has(targetId))
2446
+ continue;
2447
+ const direction = DEPENDENCY_RELATIONSHIPS[relationship];
2448
+ if (direction === "self-requires-target") {
2449
+ addEdge(targetId, selfId, "references");
2450
+ } else if (direction === "target-requires-self") {
2451
+ addEdge(selfId, targetId, "references");
2452
+ }
2453
+ }
2454
+ }
2455
+ }
2456
+ const edges = [];
2457
+ const downstreamAdj = /* @__PURE__ */ new Map();
2458
+ const upstreamAdj = /* @__PURE__ */ new Map();
2459
+ for (const [key, source] of edgeSources) {
2460
+ const [from, to] = key.split("\0");
2461
+ edges.push({ from, to, source });
2462
+ downstreamAdj.set(from, [...downstreamAdj.get(from) ?? [], to]);
2463
+ upstreamAdj.set(to, [...upstreamAdj.get(to) ?? [], from]);
2464
+ }
2465
+ return {
2466
+ edges,
2467
+ getUpstream: (specId) => walk(specId, upstreamAdj),
2468
+ getDownstream: (specId) => walk(specId, downstreamAdj)
2469
+ };
2470
+ }
2471
+
812
2472
  // ../core/dist/glob.js
813
2473
  import { glob } from "tinyglobby";
814
2474
  import { join as join3, isAbsolute } from "path";
@@ -830,14 +2490,17 @@ function createLogger(options) {
830
2490
 
831
2491
  // ../core/dist/preset.js
832
2492
  import { readFile as readFile3 } from "fs/promises";
833
- import { resolve, isAbsolute as isAbsolute2 } from "path";
2493
+ import { resolve as resolve2, isAbsolute as isAbsolute2 } from "path";
834
2494
 
835
2495
  // ../lint/dist/engine.js
836
2496
  function createLintEngine(options) {
837
2497
  return {
838
2498
  lint(specs) {
839
2499
  const diagnostics = [];
2500
+ const ignored = new Set(options.ignore ?? []);
840
2501
  for (const spec of specs) {
2502
+ if (ignored.has(spec.filePath))
2503
+ continue;
841
2504
  for (const rule of options.rules) {
842
2505
  const results = rule.run({
843
2506
  spec,
@@ -845,7 +2508,11 @@ function createLintEngine(options) {
845
2508
  config: options.config,
846
2509
  graph: options.graph
847
2510
  });
848
- diagnostics.push(...results);
2511
+ for (const diagnostic of results) {
2512
+ if (ignored.has(diagnostic.filePath))
2513
+ continue;
2514
+ diagnostics.push({ ...diagnostic, severity: rule.severity });
2515
+ }
849
2516
  }
850
2517
  }
851
2518
  return {
@@ -858,6 +2525,18 @@ function createLintEngine(options) {
858
2525
  }
859
2526
 
860
2527
  // ../lint/dist/rules/valid-frontmatter.js
2528
+ function readablePath(instancePath) {
2529
+ return instancePath.split("/").filter(Boolean).map((segment) => /^\d+$/.test(segment) ? `[${segment}]` : `.${segment}`).join("").replace(/^\./, "");
2530
+ }
2531
+ function describeValidationError(err) {
2532
+ const path = readablePath(err.instancePath ?? "");
2533
+ const allowed = err.params?.allowedValues;
2534
+ let detail = err.message ?? JSON.stringify(err);
2535
+ if (Array.isArray(allowed) && allowed.length > 0) {
2536
+ detail += `: ${allowed.map((v) => JSON.stringify(v)).join(", ")}`;
2537
+ }
2538
+ return path ? `${path} ${detail}` : detail;
2539
+ }
861
2540
  var validFrontmatterRule = {
862
2541
  id: "structure/valid-frontmatter",
863
2542
  description: "Frontmatter matches the schema for the declared spec type",
@@ -869,7 +2548,7 @@ var validFrontmatterRule = {
869
2548
  return errors.map((err) => ({
870
2549
  ruleId: "structure/valid-frontmatter",
871
2550
  severity: "error",
872
- message: `Invalid frontmatter: ${err.message ?? JSON.stringify(err)}`,
2551
+ message: `Invalid frontmatter: ${describeValidationError(err)}`,
873
2552
  filePath: context.spec.filePath
874
2553
  }));
875
2554
  }
@@ -929,7 +2608,131 @@ var noCircularDepsRule = {
929
2608
  };
930
2609
 
931
2610
  // ../lint/dist/rules/story-coverage.js
932
- var FEATURE_PATTERN = /\*\*F\d+\*\*:\s*(.+)/g;
2611
+ var STOPWORDS = /* @__PURE__ */ new Set([
2612
+ "a",
2613
+ "an",
2614
+ "the",
2615
+ "and",
2616
+ "or",
2617
+ "of",
2618
+ "to",
2619
+ "for",
2620
+ "with",
2621
+ "its",
2622
+ "it",
2623
+ "in",
2624
+ "on",
2625
+ "at",
2626
+ "by",
2627
+ "from",
2628
+ "into",
2629
+ "every",
2630
+ "each",
2631
+ "that",
2632
+ "this",
2633
+ "be",
2634
+ "is",
2635
+ "are",
2636
+ "as",
2637
+ "can",
2638
+ "will",
2639
+ "must",
2640
+ "so",
2641
+ "their",
2642
+ "them",
2643
+ "when",
2644
+ "which",
2645
+ "who"
2646
+ ]);
2647
+ var OVERLAP_THRESHOLD = 0.5;
2648
+ var REFERENCED_THRESHOLD = 0.34;
2649
+ function tokenise(text) {
2650
+ 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);
2651
+ return new Set(words);
2652
+ }
2653
+ function extractFeatureSection(content) {
2654
+ const lines = content.split("\n");
2655
+ const start = lines.findIndex((l) => /^##\s+Features\s*$/.test(l.trim()));
2656
+ if (start === -1)
2657
+ return null;
2658
+ const body = [];
2659
+ for (let i = start + 1; i < lines.length; i++) {
2660
+ if (/^##\s/.test(lines[i]))
2661
+ break;
2662
+ body.push(lines[i]);
2663
+ }
2664
+ return body.join("\n");
2665
+ }
2666
+ function parseFeatures(content) {
2667
+ return parseFeatureEntries(content).map((f) => f.text);
2668
+ }
2669
+ function parseFeatureEntries(content) {
2670
+ const section = extractFeatureSection(content);
2671
+ if (section === null)
2672
+ return [];
2673
+ const ID_PREFIX = /^\*{0,2}F(\d+)\*{0,2}\s*[:.-]\s*/i;
2674
+ const features = [];
2675
+ for (const rawLine of section.split("\n")) {
2676
+ const line = rawLine.trim();
2677
+ if (!line)
2678
+ continue;
2679
+ const bullet = /^[-*]\s+(.*)$/.exec(line);
2680
+ const text = bullet ? (bullet[1] ?? "").trim() : ID_PREFIX.test(line) ? line : "";
2681
+ if (!text)
2682
+ continue;
2683
+ const idMatch = ID_PREFIX.exec(text);
2684
+ const stripped = text.replace(ID_PREFIX, "").trim();
2685
+ if (stripped)
2686
+ features.push({ text: stripped, num: idMatch?.[1] });
2687
+ }
2688
+ return features;
2689
+ }
2690
+ function overlap(featureTokens, storyTokens) {
2691
+ if (featureTokens.size === 0)
2692
+ return 0;
2693
+ let shared = 0;
2694
+ for (const token of featureTokens)
2695
+ if (storyTokens.has(token))
2696
+ shared++;
2697
+ return shared / featureTokens.size;
2698
+ }
2699
+ function referencesSpec(story, specId) {
2700
+ const refs = story.frontmatter.references;
2701
+ if (!Array.isArray(refs))
2702
+ return false;
2703
+ return refs.some((r) => r?.id === specId);
2704
+ }
2705
+ function uncoveredFeatures(features, stories, prdId) {
2706
+ const scored = stories.map((story) => ({
2707
+ tokens: tokenise(`${String(story.frontmatter.title ?? "")} ${story.content}`),
2708
+ threshold: referencesSpec(story, prdId) ? REFERENCED_THRESHOLD : OVERLAP_THRESHOLD
2709
+ }));
2710
+ const tokenised = features.map(tokenise);
2711
+ return features.filter((_feature, i) => {
2712
+ const featureTokens = tokenised[i];
2713
+ const distinctive = distinctiveTokens(featureTokens, tokenised, i);
2714
+ return !scored.some((s) => overlap(featureTokens, s.tokens) >= s.threshold && covers(distinctive, featureTokens, s.tokens));
2715
+ });
2716
+ }
2717
+ function covers(distinctive, featureTokens, storyTokens) {
2718
+ if (distinctive.size === 0 || distinctive.size === featureTokens.size)
2719
+ return true;
2720
+ let matched = 0;
2721
+ for (const token of distinctive)
2722
+ if (storyTokens.has(token))
2723
+ matched++;
2724
+ return matched > distinctive.size / 2;
2725
+ }
2726
+ function distinctiveTokens(featureTokens, allFeatureTokens, index) {
2727
+ const distinctive = new Set(featureTokens);
2728
+ for (let i = 0; i < allFeatureTokens.length; i++) {
2729
+ if (i === index)
2730
+ continue;
2731
+ for (const token of allFeatureTokens[i])
2732
+ distinctive.delete(token);
2733
+ }
2734
+ return distinctive;
2735
+ }
933
2736
  var storyCoverageRule = {
934
2737
  id: "completeness/story-coverage",
935
2738
  description: "Every feature listed in a PRD has at least one corresponding user story",
@@ -937,17 +2740,11 @@ var storyCoverageRule = {
937
2740
  run(context) {
938
2741
  if (context.spec.frontmatter.type !== "prd")
939
2742
  return [];
940
- const features = [];
941
- let match;
942
- const re = new RegExp(FEATURE_PATTERN.source, "g");
943
- while ((match = re.exec(context.spec.content)) !== null) {
944
- features.push(match[1].trim());
945
- }
2743
+ const features = parseFeatures(context.spec.content);
946
2744
  if (features.length === 0)
947
2745
  return [];
948
2746
  const stories = context.allSpecs.filter((s) => s.frontmatter.type === "user-story");
949
- const storyContent = stories.map((s) => s.content + " " + s.frontmatter.title).join(" ");
950
- return features.filter((feature) => !storyContent.toLowerCase().includes(feature.toLowerCase())).map((feature) => ({
2747
+ return uncoveredFeatures(features, stories, context.spec.frontmatter.id).map((feature) => ({
951
2748
  ruleId: "completeness/story-coverage",
952
2749
  severity: "warn",
953
2750
  message: `Feature "${feature}" has no corresponding user story`,
@@ -957,30 +2754,57 @@ var storyCoverageRule = {
957
2754
  };
958
2755
 
959
2756
  // ../lint/dist/rules/staleness-check.js
2757
+ function groupByEntry(config, specs) {
2758
+ const byEntry = /* @__PURE__ */ new Map();
2759
+ for (const key of Object.keys(config.specs))
2760
+ byEntry.set(key, []);
2761
+ for (const spec of specs) {
2762
+ let bestKey;
2763
+ let bestLen = -1;
2764
+ for (const [key, entry] of Object.entries(config.specs)) {
2765
+ const prefix = entry.path.split("*")[0] ?? "";
2766
+ const normalized = spec.filePath.replace(/\\/g, "/");
2767
+ if (normalized.includes(prefix) && prefix.length > bestLen) {
2768
+ bestKey = key;
2769
+ bestLen = prefix.length;
2770
+ }
2771
+ }
2772
+ if (bestKey)
2773
+ byEntry.get(bestKey).push(spec);
2774
+ }
2775
+ return byEntry;
2776
+ }
2777
+ function lastUpdated(spec) {
2778
+ return spec.frontmatter.updated ?? spec.frontmatter.created ?? "";
2779
+ }
960
2780
  var stalenessCheckRule = {
961
2781
  id: "freshness/staleness-check",
962
2782
  description: "Warns if a spec hasn't been updated since its upstream dependency changed",
963
2783
  severity: "warn",
964
2784
  run(context) {
965
- const refs = context.spec.frontmatter.references;
966
- if (!refs || refs.length === 0)
2785
+ const specId = context.spec.frontmatter.id;
2786
+ if (typeof specId !== "string")
2787
+ return [];
2788
+ const specUpdated = lastUpdated(context.spec);
2789
+ if (!specUpdated)
967
2790
  return [];
968
- const specUpdated = context.spec.frontmatter.updated ?? context.spec.frontmatter.created;
969
2791
  const specDate = new Date(specUpdated);
2792
+ const byEntry = context.config ? groupByEntry(context.config, context.allSpecs) : /* @__PURE__ */ new Map([["", context.allSpecs]]);
2793
+ const relations = buildRelationResolver(context.config, byEntry);
2794
+ const upstreamIds = relations.getUpstream(specId);
970
2795
  const diagnostics = [];
971
- for (const ref of refs) {
972
- if (ref.relationship !== "depends-on" && ref.relationship !== "implemented-by")
973
- continue;
974
- const upstream = context.allSpecs.find((s) => s.frontmatter.id === ref.id);
2796
+ for (const upstreamId of upstreamIds) {
2797
+ const upstream = context.allSpecs.find((s) => s.frontmatter.id === upstreamId);
975
2798
  if (!upstream)
976
2799
  continue;
977
- const upstreamUpdated = upstream.frontmatter.updated ?? upstream.frontmatter.created;
978
- const upstreamDate = new Date(upstreamUpdated);
979
- if (upstreamDate > specDate) {
2800
+ const upstreamUpdated = lastUpdated(upstream);
2801
+ if (!upstreamUpdated)
2802
+ continue;
2803
+ if (new Date(upstreamUpdated) > specDate) {
980
2804
  diagnostics.push({
981
2805
  ruleId: "freshness/staleness-check",
982
2806
  severity: "warn",
983
- message: `Potentially stale: upstream "${upstream.frontmatter.id}" was updated on ${upstreamUpdated}, but this spec was last updated on ${specUpdated}`,
2807
+ message: `Potentially stale: upstream "${upstreamId}" was updated on ${upstreamUpdated}, but this spec was last updated on ${specUpdated}`,
984
2808
  filePath: context.spec.filePath
985
2809
  });
986
2810
  }
@@ -1122,8 +2946,6 @@ var EDGE_CASE_KEYWORDS = [
1122
2946
  "reject",
1123
2947
  "unauthorized",
1124
2948
  "forbidden",
1125
- "404",
1126
- "500",
1127
2949
  "missing",
1128
2950
  "malformed",
1129
2951
  "overflow",
@@ -1133,8 +2955,24 @@ var EDGE_CASE_KEYWORDS = [
1133
2955
  "fallback",
1134
2956
  "crash",
1135
2957
  "nonexistent",
1136
- "corrupt"
2958
+ "corrupt",
2959
+ // Vocabulary that names a failure without using any of the words above.
2960
+ "conflict",
2961
+ "denied",
2962
+ "expired",
2963
+ "not found",
2964
+ "retry",
2965
+ "rate limit",
2966
+ "unavailable",
2967
+ "unprocessable"
1137
2968
  ];
2969
+ var ERROR_STATUS_CODE = /\b[45]\d{2}\b/;
2970
+ var EDGE_CASE_SECTION = "edge cases";
2971
+ var PLACEHOLDER_BODIES = /^(todo|tbd|fixme|n\/a|na|none|xxx|\.{2,}|-|\*)$/i;
2972
+ var DISCLAIMED_BODIES = /^(none|no|nothing|n\/a)\b[\s\S]{0,40}$/i;
2973
+ function meaningfulContent(content) {
2974
+ 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();
2975
+ }
1138
2976
  var edgeCaseCoverageRule = {
1139
2977
  id: "completeness/edge-case-coverage",
1140
2978
  description: "Flag user stories or test plans that don't mention error states or edge cases",
@@ -1143,8 +2981,24 @@ var edgeCaseCoverageRule = {
1143
2981
  const type = context.spec.frontmatter.type;
1144
2982
  if (type !== "user-story" && type !== "test-plan")
1145
2983
  return [];
2984
+ const section = context.spec.parsedSections.find((s) => s.heading.trim().toLowerCase() === EDGE_CASE_SECTION);
2985
+ if (type === "test-plan" && section) {
2986
+ const body = meaningfulContent(section.content);
2987
+ const written = body !== "" && !PLACEHOLDER_BODIES.test(body) && !DISCLAIMED_BODIES.test(body);
2988
+ if (written)
2989
+ return [];
2990
+ return [
2991
+ {
2992
+ ruleId: "completeness/edge-case-coverage",
2993
+ severity: "warn",
2994
+ 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.`,
2995
+ filePath: context.spec.filePath,
2996
+ section: section.heading
2997
+ }
2998
+ ];
2999
+ }
1146
3000
  const content = context.spec.content.toLowerCase();
1147
- const hasEdgeCases = EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw));
3001
+ const hasEdgeCases = EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw)) || ERROR_STATUS_CODE.test(content);
1148
3002
  if (hasEdgeCases)
1149
3003
  return [];
1150
3004
  return [
@@ -1215,7 +3069,7 @@ var namingConventionsRule = {
1215
3069
  };
1216
3070
 
1217
3071
  // ../lint/dist/rules/threat-coverage.js
1218
- var STOPWORDS = /* @__PURE__ */ new Set(["the", "and", "for", "with", "from", "that", "this", "into", "via"]);
3072
+ var STOPWORDS2 = /* @__PURE__ */ new Set(["the", "and", "for", "with", "from", "that", "this", "into", "via"]);
1219
3073
  function extractThreats(content) {
1220
3074
  const parts = content.split(/^(?=## )/m);
1221
3075
  const threats = [];
@@ -1228,7 +3082,7 @@ function extractThreats(content) {
1228
3082
  return threats;
1229
3083
  }
1230
3084
  function extractKeyTerms(text) {
1231
- return text.toLowerCase().split(/\W+/).filter((w) => w.length > 3).filter((w) => !STOPWORDS.has(w));
3085
+ return text.toLowerCase().split(/\W+/).filter((w) => w.length > 3).filter((w) => !STOPWORDS2.has(w));
1232
3086
  }
1233
3087
  var threatCoverageRule = {
1234
3088
  id: "security/threat-coverage",
@@ -1275,20 +3129,78 @@ var ambiguityScoreAiRule = {
1275
3129
  {
1276
3130
  ruleId: "clarity/ambiguity-score-ai",
1277
3131
  severity: "info",
1278
- message: "AI ambiguity analysis available \u2014 run `sdx check --ai` for LLM-powered ambiguity detection",
3132
+ message: "AI ambiguity analysis available \u2014 run `specdx check --ai` for LLM-powered ambiguity detection",
1279
3133
  filePath: context.spec.filePath
1280
3134
  }
1281
3135
  ];
1282
3136
  }
1283
3137
  };
1284
3138
 
3139
+ // ../lint/dist/rules/no-placeholder-sections.js
3140
+ var PLACEHOLDER_BODIES2 = /^(todo|tbd|fixme|n\/a|na|none|xxx|\.{2,}|-|\*)$/i;
3141
+ function meaningfulContent2(content) {
3142
+ 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();
3143
+ }
3144
+ var noPlaceholderSectionsRule = {
3145
+ id: "completeness/no-placeholder-sections",
3146
+ description: "Spec sections contain content, not scaffolding placeholders",
3147
+ severity: "warn",
3148
+ run(context) {
3149
+ return context.spec.parsedSections.filter((section) => section.heading !== "").filter((section) => {
3150
+ const body = meaningfulContent2(section.content);
3151
+ return body === "" || PLACEHOLDER_BODIES2.test(body);
3152
+ }).map((section) => ({
3153
+ ruleId: "completeness/no-placeholder-sections",
3154
+ severity: "warn",
3155
+ message: `Section "${section.heading}" is still a placeholder \u2014 write its content or remove the section`,
3156
+ filePath: context.spec.filePath,
3157
+ section: section.heading
3158
+ }));
3159
+ }
3160
+ };
3161
+
3162
+ // ../lint/dist/rules/id-matches-config-key.js
3163
+ import { basename as basename2 } from "path";
3164
+ var idMatchesConfigKeyRule = {
3165
+ id: "structure/id-matches-config-key",
3166
+ description: "A spec's frontmatter id should match the key it is registered under in the config",
3167
+ severity: "warn",
3168
+ run(context) {
3169
+ const { spec, config } = context;
3170
+ if (!config)
3171
+ return [];
3172
+ const id = spec.frontmatter.id;
3173
+ if (typeof id !== "string" || id.length === 0)
3174
+ return [];
3175
+ const specFile = basename2(spec.filePath);
3176
+ const candidates = Object.entries(config.specs).filter(([, entry]) => {
3177
+ const target = basename2(entry.path);
3178
+ return !target.includes("*") && target === specFile;
3179
+ });
3180
+ if (candidates.length !== 1)
3181
+ return [];
3182
+ const key = candidates[0][0];
3183
+ if (key === id)
3184
+ return [];
3185
+ return [
3186
+ {
3187
+ ruleId: "structure/id-matches-config-key",
3188
+ severity: "warn",
3189
+ 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.`,
3190
+ filePath: spec.filePath
3191
+ }
3192
+ ];
3193
+ }
3194
+ };
3195
+
1285
3196
  // ../lint/dist/rules/index.js
1286
3197
  var structureRules = [
1287
3198
  validFrontmatterRule,
1288
3199
  requiredSectionsRule,
1289
3200
  validReferencesRule,
1290
3201
  noCircularDepsRule,
1291
- singleProjectContextRule
3202
+ singleProjectContextRule,
3203
+ idMatchesConfigKeyRule
1292
3204
  ];
1293
3205
  var contentRules = [
1294
3206
  storyCoverageRule,
@@ -1298,7 +3210,8 @@ var contentRules = [
1298
3210
  edgeCaseCoverageRule,
1299
3211
  namingConventionsRule,
1300
3212
  threatCoverageRule,
1301
- ambiguityScoreAiRule
3213
+ ambiguityScoreAiRule,
3214
+ noPlaceholderSectionsRule
1302
3215
  ];
1303
3216
  var allBuiltinRules = [...structureRules, ...contentRules];
1304
3217
 
@@ -1310,25 +3223,143 @@ function getPreset(name) {
1310
3223
  case "recommended":
1311
3224
  return allBuiltinRules;
1312
3225
  case "strict":
1313
- return allBuiltinRules.map((rule) => ({ ...rule, severity: "error" }));
3226
+ return allBuiltinRules.map((rule) => rule.severity === "warn" ? { ...rule, severity: "error" } : rule);
1314
3227
  default:
1315
3228
  throw new Error(`Unknown preset: "${name}". Use "minimal", "recommended", or "strict", or resolve external presets via resolvePreset() from @specdx/core.`);
1316
3229
  }
1317
3230
  }
1318
3231
 
3232
+ // ../lint/dist/resolve-lint-config.js
3233
+ import { isAbsolute as isAbsolute3, resolve as resolve3 } from "path";
3234
+
1319
3235
  // ../lint/dist/custom-rule-loader.js
1320
3236
  import { pathToFileURL } from "url";
3237
+ async function loadCustomRule(filePath) {
3238
+ const module = await import(pathToFileURL(filePath).href);
3239
+ const rule = module.default ?? module.rule;
3240
+ if (!rule || !rule.id || !rule.run) {
3241
+ throw new Error(`Custom rule at ${filePath} must export a default LintRule with id and run function`);
3242
+ }
3243
+ return rule;
3244
+ }
1321
3245
 
1322
- // src/shared-args.ts
1323
- var sharedArgs = {
1324
- quiet: { type: "boolean", description: "Suppress info output", alias: ["q"] },
1325
- verbose: { type: "boolean", description: "Enable debug output", alias: ["V"] },
1326
- format: {
1327
- type: "string",
1328
- description: "Output format (pretty, json, github)",
1329
- default: "pretty"
3246
+ // ../lint/dist/resolve-lint-config.js
3247
+ var SEVERITIES = /* @__PURE__ */ new Set(["error", "warn", "info"]);
3248
+ function isOff(value) {
3249
+ return value === false || value === null || value === "off";
3250
+ }
3251
+ function severityOf(value) {
3252
+ return typeof value === "string" && SEVERITIES.has(value) ? value : void 0;
3253
+ }
3254
+ function describe(value) {
3255
+ return typeof value === "string" ? `"${value}"` : JSON.stringify(value);
3256
+ }
3257
+ async function resolveLintConfig({ config, preset, configDir }) {
3258
+ const presetName = preset ?? config?.lint?.extends ?? "recommended";
3259
+ const byId = new Map(getPreset(presetName).map((rule) => [rule.id, rule]));
3260
+ const builtins = new Map(allBuiltinRules.map((rule) => [rule.id, rule]));
3261
+ for (const [id, value] of Object.entries(config?.lint?.rules ?? {})) {
3262
+ if (isOff(value)) {
3263
+ if (!builtins.has(id)) {
3264
+ throw new Error(`lint.rules["${id}"]: cannot turn off "${id}" \u2014 no built-in rule has that id. Check the spelling.`);
3265
+ }
3266
+ byId.delete(id);
3267
+ continue;
3268
+ }
3269
+ let severity;
3270
+ let rulePath;
3271
+ if (Array.isArray(value)) {
3272
+ severity = severityOf(value[0]);
3273
+ if (severity === void 0) {
3274
+ throw new Error(`lint.rules["${id}"]: ${describe(value[0])} is not a severity. Use "error", "warn", "info", or "off".`);
3275
+ }
3276
+ const options = value[1];
3277
+ if (options !== void 0) {
3278
+ if (typeof options !== "object" || options === null || Array.isArray(options)) {
3279
+ throw new Error(`lint.rules["${id}"]: expected options like { path: "./rule.js" }, got ${describe(options)}.`);
3280
+ }
3281
+ const declared = options.path;
3282
+ if (declared !== void 0) {
3283
+ if (typeof declared !== "string" || declared.length === 0) {
3284
+ throw new Error(`lint.rules["${id}"]: \`path\` must be a non-empty string.`);
3285
+ }
3286
+ rulePath = declared;
3287
+ }
3288
+ }
3289
+ } else {
3290
+ severity = severityOf(value);
3291
+ if (severity === void 0) {
3292
+ throw new Error(`lint.rules["${id}"]: ${describe(value)} is not a severity. Use "error", "warn", "info", or "off".`);
3293
+ }
3294
+ }
3295
+ if (rulePath !== void 0) {
3296
+ const absolute = isAbsolute3(rulePath) ? rulePath : resolve3(configDir, rulePath);
3297
+ const custom = await loadCustomRule(absolute);
3298
+ byId.set(id, { ...custom, id, severity });
3299
+ continue;
3300
+ }
3301
+ const existing = byId.get(id) ?? builtins.get(id);
3302
+ if (!existing) {
3303
+ 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" }].`);
3304
+ }
3305
+ byId.set(id, { ...existing, severity });
3306
+ }
3307
+ const ignore = [];
3308
+ for (const pattern of config?.lint?.ignore ?? []) {
3309
+ ignore.push(...await resolveGlob(pattern, configDir));
1330
3310
  }
3311
+ return { rules: [...byId.values()], ignore };
3312
+ }
3313
+
3314
+ // src/shared-args.ts
3315
+ var quietArg = {
3316
+ type: "boolean",
3317
+ description: "Suppress success and summary output; problems still print",
3318
+ alias: ["q"]
3319
+ };
3320
+ var verboseArg = {
3321
+ type: "boolean",
3322
+ description: "Enable debug output",
3323
+ alias: ["V"]
1331
3324
  };
3325
+ function formatArg(formats) {
3326
+ const [fallback] = formats;
3327
+ if (!fallback) throw new Error("formatArg requires at least one format");
3328
+ return {
3329
+ type: "string",
3330
+ description: `Output format (${formats.join(", ")})`,
3331
+ default: fallback
3332
+ };
3333
+ }
3334
+ function sharedArgs(formats) {
3335
+ return { quiet: quietArg, verbose: verboseArg, format: formatArg(formats) };
3336
+ }
3337
+ function resolveFormat(value, formats) {
3338
+ const [fallback] = formats;
3339
+ if (!fallback) throw new Error("resolveFormat requires at least one format");
3340
+ if (value === void 0) return { ok: true, format: fallback };
3341
+ if (formats.includes(value)) return { ok: true, format: value };
3342
+ return {
3343
+ ok: false,
3344
+ message: `unknown --format "${value}". This command renders: ${formats.join(", ")}.`
3345
+ };
3346
+ }
3347
+
3348
+ // src/output.ts
3349
+ function createOutput(options = {}) {
3350
+ const quiet = options.quiet === true;
3351
+ return {
3352
+ info(line = "") {
3353
+ if (!quiet) console.log(line);
3354
+ },
3355
+ out(line = "") {
3356
+ console.log(line);
3357
+ },
3358
+ error(line = "") {
3359
+ console.error(line);
3360
+ }
3361
+ };
3362
+ }
1332
3363
 
1333
3364
  // src/formatters/pretty.ts
1334
3365
  function formatPretty(diagnostics) {
@@ -1348,17 +3379,25 @@ function formatJson(diagnostics) {
1348
3379
  // src/formatters/github.ts
1349
3380
  function formatGithub(diagnostics) {
1350
3381
  return diagnostics.map((d) => {
1351
- const level = d.severity === "error" ? "error" : "warning";
3382
+ const level = d.severity === "error" ? "error" : d.severity === "warn" ? "warning" : "notice";
1352
3383
  const line = d.line ? `,line=${d.line}` : "";
1353
3384
  return `::${level} file=${d.filePath}${line}::${d.message} (${d.ruleId})`;
1354
3385
  }).join("\n");
1355
3386
  }
1356
3387
 
1357
- // src/commands/lint.ts
3388
+ // src/commands/core/lint.ts
3389
+ var FORMATS = ["pretty", "json", "github"];
1358
3390
  async function runLint(options) {
3391
+ if (!options.configDir) {
3392
+ throw new TypeError("runLint requires `configDir` \u2014 the directory holding spec.config.yaml.");
3393
+ }
1359
3394
  const config = await loadConfig(void 0, options.configDir);
1360
3395
  const preset = options.preset ?? config.lint?.extends ?? "recommended";
1361
- const rules = getPreset(preset);
3396
+ const { rules, ignore } = await resolveLintConfig({
3397
+ config,
3398
+ preset,
3399
+ configDir: options.configDir
3400
+ });
1362
3401
  const specs = [];
1363
3402
  for (const [, entry] of Object.entries(config.specs)) {
1364
3403
  const files = await resolveGlob(entry.path, options.configDir);
@@ -1373,7 +3412,7 @@ async function runLint(options) {
1373
3412
  } catch (err) {
1374
3413
  graphError = err.message;
1375
3414
  }
1376
- const engine = createLintEngine({ rules, config, graph });
3415
+ const engine = createLintEngine({ rules, config, graph, ignore });
1377
3416
  const results = engine.lint(specs);
1378
3417
  if (options.specPath) {
1379
3418
  const specPath = options.specPath;
@@ -1390,18 +3429,28 @@ async function runLint(options) {
1390
3429
  });
1391
3430
  results.hasErrors = true;
1392
3431
  }
1393
- return results;
3432
+ const ignored = new Set(ignore);
3433
+ const linted = specs.filter((spec) => !ignored.has(spec.filePath));
3434
+ return { ...results, specFiles: linted.length, assessed: linted.length > 0 };
1394
3435
  }
1395
3436
  var lint_default = defineCommand2({
1396
3437
  meta: { name: "lint", description: "Lint all specs in the suite" },
1397
3438
  args: {
1398
- ...sharedArgs,
3439
+ ...sharedArgs(FORMATS),
1399
3440
  fix: { type: "boolean", description: "Auto-fix issues where possible" },
1400
3441
  path: { type: "positional", description: "Lint a specific spec file", required: false },
1401
3442
  preset: { type: "string", description: "Lint preset (minimal, recommended, strict)" }
1402
3443
  },
1403
3444
  async run({ args }) {
1404
3445
  const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });
3446
+ const output = createOutput({ quiet: args.quiet });
3447
+ const format = resolveFormat(args.format, FORMATS);
3448
+ if (!format.ok) {
3449
+ console.error(`
3450
+ \u2717 ${format.message}
3451
+ `);
3452
+ process.exit(1);
3453
+ }
1405
3454
  if (args.fix) {
1406
3455
  logger.info("No auto-fixable issues supported yet.");
1407
3456
  }
@@ -1411,8 +3460,19 @@ var lint_default = defineCommand2({
1411
3460
  specPath: args.path,
1412
3461
  preset: args.preset
1413
3462
  });
1414
- const formatter = args.format === "json" ? formatJson : args.format === "github" ? formatGithub : formatPretty;
1415
- console.log(formatter(results.diagnostics));
3463
+ const formatter = format.format === "json" ? formatJson : format.format === "github" ? formatGithub : formatPretty;
3464
+ if (!results.assessed) {
3465
+ console.error(
3466
+ "\n \u26A0 No specs were linted. Check the spec paths in spec.config.yaml, and whether `lint.ignore` excludes them all.\n"
3467
+ );
3468
+ process.exit(3);
3469
+ }
3470
+ const rendered = formatter(results.diagnostics);
3471
+ if (format.format === "pretty" && results.diagnostics.length === 0) {
3472
+ output.info(rendered);
3473
+ } else {
3474
+ output.out(rendered);
3475
+ }
1416
3476
  if (results.hasErrors) process.exit(1);
1417
3477
  } catch (err) {
1418
3478
  console.error(`
@@ -1423,11 +3483,11 @@ var lint_default = defineCommand2({
1423
3483
  }
1424
3484
  });
1425
3485
 
1426
- // src/commands/pack.ts
3486
+ // src/commands/core/pack.ts
1427
3487
  import { defineCommand as defineCommand3 } from "citty";
1428
3488
 
1429
3489
  // ../pack/dist/resolver.js
1430
- var STOPWORDS2 = /* @__PURE__ */ new Set([
3490
+ var STOPWORDS3 = /* @__PURE__ */ new Set([
1431
3491
  "a",
1432
3492
  "an",
1433
3493
  "and",
@@ -1504,7 +3564,7 @@ var STOPWORDS2 = /* @__PURE__ */ new Set([
1504
3564
  "your"
1505
3565
  ]);
1506
3566
  function tokenize(task) {
1507
- return task.split(/[\s\-_/.,;:!?()[\]{}'"]+/).map((t) => t.toLowerCase()).filter((t) => t.length > 1 && !STOPWORDS2.has(t));
3567
+ return task.split(/[\s\-_/.,;:!?()[\]{}'"]+/).map((t) => t.toLowerCase()).filter((t) => t.length > 1 && !STOPWORDS3.has(t));
1508
3568
  }
1509
3569
  var WEIGHT_TAGS = 3;
1510
3570
  var WEIGHT_TITLE = 3;
@@ -1784,12 +3844,18 @@ function allocate(specs, scores, options) {
1784
3844
  for (const spec of specs) {
1785
3845
  specMap.set(spec.frontmatter.id, spec);
1786
3846
  }
3847
+ function tokensOf(compressed) {
3848
+ if (compressed.collapsed)
3849
+ return countTokens(compressed.collapsedSummary ?? "");
3850
+ return compressed.sections.reduce((sum, section) => sum + section.tokens, 0);
3851
+ }
1787
3852
  const items = [];
1788
3853
  for (const score of scores) {
1789
3854
  const spec = specMap.get(score.specId);
1790
3855
  if (!spec)
1791
3856
  continue;
1792
3857
  let compressed;
3858
+ let stale;
1793
3859
  if (options.full) {
1794
3860
  compressed = {
1795
3861
  specId: score.specId,
@@ -1805,20 +3871,34 @@ function allocate(specs, scores, options) {
1805
3871
  collapsed: false
1806
3872
  };
1807
3873
  } else {
1808
- compressed = compressSpec(score.specId, String(spec.frontmatter.type), String(spec.frontmatter.title), spec.frontmatter.status, spec.frontmatter.updated, spec.parsedSections, options.compression);
1809
- }
1810
- let tokens;
1811
- if (compressed.collapsed) {
1812
- tokens = countTokens(compressed.collapsedSummary ?? "");
1813
- } else {
1814
- tokens = 0;
1815
- for (const section of compressed.sections) {
1816
- tokens += section.tokens;
3874
+ const compress = (compression) => compressSpec(score.specId, String(spec.frontmatter.type), String(spec.frontmatter.title), spec.frontmatter.status, spec.frontmatter.updated, spec.parsedSections, compression);
3875
+ compressed = compress({ ...options.compression, stableDays: 0 });
3876
+ if (options.compression.stableDays > 0) {
3877
+ const collapsed = compress(options.compression);
3878
+ const collapsedTokens = tokensOf(collapsed);
3879
+ if (collapsedTokens < tokensOf(compressed)) {
3880
+ stale = { spec: collapsed, tokens: collapsedTokens };
3881
+ }
1817
3882
  }
1818
3883
  }
1819
- items.push({ compressed, relevance: score.score, tokens, idMatched: score.idMatched ?? false });
3884
+ items.push({
3885
+ compressed,
3886
+ relevance: score.score,
3887
+ tokens: tokensOf(compressed),
3888
+ idMatched: score.idMatched ?? false,
3889
+ stale
3890
+ });
1820
3891
  }
1821
3892
  items.sort((a, b) => b.relevance - a.relevance || Number(b.idMatched) - Number(a.idMatched));
3893
+ let projected = items.reduce((sum, item) => sum + item.tokens, 0);
3894
+ for (let i = items.length - 1; i >= 0 && projected > options.budget; i--) {
3895
+ const item = items[i];
3896
+ if (!item.stale)
3897
+ continue;
3898
+ projected -= item.tokens - item.stale.tokens;
3899
+ item.compressed = item.stale.spec;
3900
+ item.tokens = item.stale.tokens;
3901
+ }
1822
3902
  const totalTokens = items.reduce((sum, item) => sum + item.tokens, 0);
1823
3903
  const withinBudget = totalTokens <= options.budget;
1824
3904
  const included = [];
@@ -2085,7 +4165,7 @@ function pack(specs, options, packConfig, graph) {
2085
4165
  return { output, stats };
2086
4166
  }
2087
4167
 
2088
- // src/commands/pack.ts
4168
+ // src/commands/core/pack.ts
2089
4169
  import { writeFile as writeFile2 } from "fs/promises";
2090
4170
  import { execSync } from "child_process";
2091
4171
  function copyToClipboard(text) {
@@ -2102,7 +4182,20 @@ function copyToClipboard(text) {
2102
4182
  }
2103
4183
  execSync(cmd, { input: text, stdio: ["pipe", "ignore", "ignore"] });
2104
4184
  }
4185
+ function emptyPackReason(stats, specsResolved) {
4186
+ if (stats.specsIncluded > 0) return void 0;
4187
+ if (specsResolved === 0) {
4188
+ return "no specs resolved from spec.config.yaml \u2014 check the paths in your config";
4189
+ }
4190
+ if (stats.specsExcluded === 0) {
4191
+ return `none of the ${specsResolved} resolved spec(s) scored above the relevance threshold for this task \u2014 try different --task wording, name specs with --specs, or use --full`;
4192
+ }
4193
+ return `all ${stats.specsExcluded} candidate spec(s) were excluded \u2014 widen --specs or raise --budget`;
4194
+ }
2105
4195
  async function runPack(options) {
4196
+ if (!options.configDir) {
4197
+ throw new TypeError("runPack requires `configDir` \u2014 the directory holding spec.config.yaml.");
4198
+ }
2106
4199
  const config = await loadConfig(void 0, options.configDir);
2107
4200
  const allSpecs = [];
2108
4201
  for (const [, entry] of Object.entries(config.specs)) {
@@ -2129,13 +4222,13 @@ async function runPack(options) {
2129
4222
  config.pack,
2130
4223
  graph
2131
4224
  );
2132
- return result;
4225
+ return { ...result, specsResolved: allSpecs.length };
2133
4226
  }
2134
4227
  var pack_default = defineCommand3({
2135
4228
  meta: { name: "pack", description: "Pack specs into AI-ready context" },
2136
4229
  args: {
2137
- quiet: sharedArgs.quiet,
2138
- verbose: sharedArgs.verbose,
4230
+ quiet: quietArg,
4231
+ verbose: verboseArg,
2139
4232
  task: { type: "string", description: "Task or context to optimise relevance for" },
2140
4233
  specs: { type: "string", description: "Comma-separated spec IDs or glob patterns to include" },
2141
4234
  budget: { type: "string", description: "Maximum token budget for the output" },
@@ -2200,12 +4293,16 @@ var pack_default = defineCommand3({
2200
4293
  }
2201
4294
  console.log(`
2202
4295
  Budget: ${stats.used} / ${stats.budget} tokens`);
2203
- console.log(
2204
- ` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`
2205
- );
4296
+ console.log(` Included: ${stats.specsIncluded} / ${result.specsResolved} specs`);
2206
4297
  console.log(` Sections compressed: ${stats.sectionsCompressed}`);
2207
4298
  console.log(` Sections omitted: ${stats.sectionsOmitted}
2208
4299
  `);
4300
+ const dryReason = emptyPackReason(stats, result.specsResolved);
4301
+ if (dryReason) {
4302
+ console.log(` \u26A0 Nothing would be packed: ${dryReason}
4303
+ `);
4304
+ process.exit(3);
4305
+ }
2209
4306
  return;
2210
4307
  }
2211
4308
  if (args.out) {
@@ -2224,6 +4321,14 @@ var pack_default = defineCommand3({
2224
4321
  `Packed ${stats.specsIncluded}/${total} specs \u2022 ${stats.used} / ${stats.budget} tokens \u2022 ${stats.sectionsCompressed} sections compressed \u2022 ${stats.sectionsOmitted} sections omitted
2225
4322
  `
2226
4323
  );
4324
+ const emptyReason = emptyPackReason(stats, result.specsResolved);
4325
+ if (emptyReason) {
4326
+ process.stderr.write(`
4327
+ \u26A0 No context packed: ${emptyReason}
4328
+
4329
+ `);
4330
+ process.exit(3);
4331
+ }
2227
4332
  } catch (err) {
2228
4333
  console.error(`
2229
4334
  \u2717 ${err.message}
@@ -2233,7 +4338,7 @@ var pack_default = defineCommand3({
2233
4338
  }
2234
4339
  });
2235
4340
 
2236
- // src/commands/diff.ts
4341
+ // src/commands/core/diff.ts
2237
4342
  import { defineCommand as defineCommand4 } from "citty";
2238
4343
  import { join as join5 } from "path";
2239
4344
 
@@ -2663,8 +4768,8 @@ function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep
2663
4768
  } else if (endKeep) {
2664
4769
  var endKeepWsPrefix = endKeep.value.match(/^\s*/)[0];
2665
4770
  var deletionWsSuffix = deletion.value.match(/\s*$/)[0];
2666
- var overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
2667
- deletion.value = removeSuffix(deletion.value, overlap);
4771
+ var overlap2 = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
4772
+ deletion.value = removeSuffix(deletion.value, overlap2);
2668
4773
  } else if (startKeep) {
2669
4774
  var startKeepWsSuffix = startKeep.value.match(/\s*$/)[0];
2670
4775
  var deletionWsPrefix = deletion.value.match(/^\s*/)[0];
@@ -3124,10 +5229,10 @@ var STRUCTURAL_SECTIONS = /* @__PURE__ */ new Set([
3124
5229
  "API Design",
3125
5230
  "Problem Statement"
3126
5231
  ]);
3127
- function bfsDistances(startId, graph) {
5232
+ function bfsDistances(startId, relations) {
3128
5233
  const distances = /* @__PURE__ */ new Map();
3129
5234
  const queue = [];
3130
- for (const edge of graph.edges) {
5235
+ for (const edge of relations.edges) {
3131
5236
  if (edge.from === startId) {
3132
5237
  if (!distances.has(edge.to)) {
3133
5238
  distances.set(edge.to, 1);
@@ -3138,7 +5243,7 @@ function bfsDistances(startId, graph) {
3138
5243
  while (queue.length > 0) {
3139
5244
  const item = queue.shift();
3140
5245
  const currentDist = item.distance;
3141
- for (const edge of graph.edges) {
5246
+ for (const edge of relations.edges) {
3142
5247
  if (edge.from === item.id && !distances.has(edge.to)) {
3143
5248
  distances.set(edge.to, currentDist + 1);
3144
5249
  queue.push({ id: edge.to, distance: currentDist + 1 });
@@ -3155,8 +5260,8 @@ function daysBetween(dateStr) {
3155
5260
  function clamp(min, max, value) {
3156
5261
  return Math.min(max, Math.max(min, value));
3157
5262
  }
3158
- function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14) {
3159
- const distanceMap = bfsDistances(changedSpecId, graph);
5263
+ function analyzeImpact(changedSpecId, diff2, relations, allSpecs, thresholdDays = 14) {
5264
+ const distanceMap = bfsDistances(changedSpecId, relations);
3160
5265
  if (distanceMap.size === 0) {
3161
5266
  return {
3162
5267
  changedSpec: changedSpecId,
@@ -3175,11 +5280,11 @@ function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14
3175
5280
  const downstream = [];
3176
5281
  for (const [specId, distance] of distanceMap) {
3177
5282
  const spec = specById.get(specId);
3178
- const lastUpdated = spec?.frontmatter.updated ?? spec?.frontmatter.created ?? null;
5283
+ const lastUpdated2 = spec?.frontmatter.updated ?? spec?.frontmatter.created ?? null;
3179
5284
  const filePath = spec?.filePath ?? `specs/${specId}.md`;
3180
5285
  let staleness;
3181
- if (lastUpdated) {
3182
- const daysSinceUpdate = daysBetween(lastUpdated);
5286
+ if (lastUpdated2) {
5287
+ const daysSinceUpdate = daysBetween(lastUpdated2);
3183
5288
  staleness = clamp(0, 1, daysSinceUpdate / thresholdDays * 0.5 + structuralSectionsChanged / totalSections * 0.3 + 1 / distance * 0.2);
3184
5289
  } else {
3185
5290
  staleness = clamp(0, 1, structuralSectionsChanged / totalSections * 0.3 + 1 / distance * 0.2);
@@ -3189,8 +5294,8 @@ function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14
3189
5294
  if (structuralSectionsChanged > 0) {
3190
5295
  parts.push(`${structuralSectionsChanged} structural section(s) changed`);
3191
5296
  }
3192
- if (lastUpdated) {
3193
- const days = Math.round(daysBetween(lastUpdated));
5297
+ if (lastUpdated2) {
5298
+ const days = Math.round(daysBetween(lastUpdated2));
3194
5299
  parts.push(`last updated ${days} day(s) ago`);
3195
5300
  }
3196
5301
  const reason = parts.join("; ");
@@ -3198,7 +5303,7 @@ function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14
3198
5303
  specId,
3199
5304
  filePath,
3200
5305
  distance,
3201
- lastUpdated,
5306
+ lastUpdated: lastUpdated2,
3202
5307
  staleness,
3203
5308
  reason
3204
5309
  });
@@ -3238,53 +5343,181 @@ function checkCrossReferences(allSpecs, removedIds) {
3238
5343
  }
3239
5344
 
3240
5345
  // ../diff/dist/git.js
5346
+ var import_picomatch = __toESM(require_picomatch2(), 1);
3241
5347
  import { execSync as execSync2 } from "child_process";
3242
- import { realpathSync } from "fs";
3243
- import { dirname as dirname2, relative, resolve as resolve2 } from "path";
5348
+ import { readFileSync, realpathSync } from "fs";
5349
+ import { dirname as dirname2, relative, resolve as resolve4, sep } from "path";
3244
5350
  function getRepoRoot(cwd) {
3245
- const root = execSync2("git rev-parse --show-toplevel", {
3246
- cwd,
3247
- encoding: "utf-8",
3248
- stdio: "pipe"
3249
- }).trim();
5351
+ let root;
5352
+ try {
5353
+ root = execSync2("git rev-parse --show-toplevel", {
5354
+ cwd,
5355
+ encoding: "utf-8",
5356
+ stdio: "pipe"
5357
+ }).trim();
5358
+ } catch {
5359
+ throw new DiffError("diff compares specs across git history, and this directory is not inside a git repository. Run `git init` first, or run diff from a checked-out project.");
5360
+ }
3250
5361
  return realpathSync(root);
3251
5362
  }
3252
- function validateRef(ref, cwd) {
5363
+ function validateRef(ref, cwd) {
5364
+ try {
5365
+ execSync2(`git rev-parse --verify ${ref}`, { cwd, encoding: "utf-8", stdio: "pipe" });
5366
+ } catch {
5367
+ throw new DiffError(`Invalid git ref: "${ref}"`);
5368
+ }
5369
+ }
5370
+ function gitShow(ref, filePath, projectRoot, repoRoot) {
5371
+ const relPath = relative(repoRoot, resolve4(projectRoot, filePath));
5372
+ try {
5373
+ return execSync2(`git show ${ref}:${relPath}`, {
5374
+ cwd: repoRoot,
5375
+ encoding: "utf-8",
5376
+ stdio: "pipe"
5377
+ });
5378
+ } catch {
5379
+ throw new DiffError(`Cannot read "${filePath}" at ref "${ref}"`);
5380
+ }
5381
+ }
5382
+ function toPosix(p) {
5383
+ return sep === "/" ? p : p.split(sep).join("/");
5384
+ }
5385
+ function buildEntryMatchers(specPathsByKey, projectRoot, repoRoot) {
5386
+ return [...specPathsByKey].map(([key, specPath]) => ({
5387
+ key,
5388
+ isMatch: (0, import_picomatch.default)(toPosix(relative(repoRoot, resolve4(projectRoot, specPath))))
5389
+ }));
5390
+ }
5391
+ function getChangedSpecFiles(baseRef, headRef, matchers, projectRoot, repoRoot) {
5392
+ let diffOutput;
5393
+ try {
5394
+ diffOutput = execSync2(`git diff --name-status ${baseRef} ${headRef}`, {
5395
+ cwd: repoRoot,
5396
+ encoding: "utf-8",
5397
+ stdio: "pipe"
5398
+ });
5399
+ } catch {
5400
+ throw new DiffError(`Failed to run git diff between "${baseRef}" and "${headRef}"`);
5401
+ }
5402
+ const result = { modified: [], added: [], deleted: [] };
5403
+ for (const line of diffOutput.trim().split("\n")) {
5404
+ if (!line)
5405
+ continue;
5406
+ const parts = line.split(" ");
5407
+ const status = parts[0];
5408
+ const filePath = parts[1];
5409
+ if (!status || !filePath)
5410
+ continue;
5411
+ const entry = matchers.find((m) => m.isMatch(filePath));
5412
+ if (!entry)
5413
+ continue;
5414
+ const changed = {
5415
+ path: relative(projectRoot, resolve4(repoRoot, filePath)),
5416
+ entryKey: entry.key
5417
+ };
5418
+ if (status === "M") {
5419
+ result.modified.push(changed);
5420
+ } else if (status === "A") {
5421
+ result.added.push(changed);
5422
+ } else if (status === "D") {
5423
+ result.deleted.push(changed);
5424
+ }
5425
+ }
5426
+ return result;
5427
+ }
5428
+ function listSpecFilesAtRef(ref, matchers, projectRoot, repoRoot) {
5429
+ const byEntry = new Map(matchers.map((m) => [m.key, []]));
5430
+ let listing;
3253
5431
  try {
3254
- execSync2(`git rev-parse --verify ${ref}`, { cwd, encoding: "utf-8", stdio: "pipe" });
5432
+ listing = execSync2(`git ls-tree -r --name-only ${ref}`, {
5433
+ cwd: repoRoot,
5434
+ encoding: "utf-8",
5435
+ stdio: "pipe"
5436
+ });
3255
5437
  } catch {
3256
- throw new DiffError(`Invalid git ref: "${ref}"`);
5438
+ throw new DiffError(`Failed to list files at ref "${ref}"`);
5439
+ }
5440
+ for (const filePath of listing.trim().split("\n")) {
5441
+ if (!filePath)
5442
+ continue;
5443
+ const entry = matchers.find((m) => m.isMatch(filePath));
5444
+ if (!entry)
5445
+ continue;
5446
+ byEntry.get(entry.key)?.push(relative(projectRoot, resolve4(repoRoot, filePath)));
3257
5447
  }
5448
+ return byEntry;
3258
5449
  }
3259
- function gitShow(ref, filePath, projectRoot, repoRoot) {
3260
- const relPath = relative(repoRoot, resolve2(projectRoot, filePath));
5450
+ function listSpecFilesInWorktree(matchers, projectRoot, repoRoot) {
5451
+ const byEntry = new Map(matchers.map((m) => [m.key, []]));
5452
+ let listing;
3261
5453
  try {
3262
- return execSync2(`git show ${ref}:${relPath}`, {
5454
+ listing = execSync2("git ls-files --cached --others --exclude-standard", {
3263
5455
  cwd: repoRoot,
3264
5456
  encoding: "utf-8",
3265
5457
  stdio: "pipe"
3266
5458
  });
3267
5459
  } catch {
3268
- throw new DiffError(`Cannot read "${filePath}" at ref "${ref}"`);
5460
+ throw new DiffError("Failed to list files in the working tree");
3269
5461
  }
3270
- }
3271
- function getChangedSpecFiles(baseRef, headRef, specPaths, projectRoot, repoRoot) {
3272
- const repoRelToProjectRel = /* @__PURE__ */ new Map();
3273
- for (const p of specPaths) {
3274
- const repoRel = relative(repoRoot, resolve2(projectRoot, p));
3275
- repoRelToProjectRel.set(repoRel, p);
5462
+ for (const filePath of listing.trim().split("\n")) {
5463
+ if (!filePath)
5464
+ continue;
5465
+ const entry = matchers.find((m) => m.isMatch(filePath));
5466
+ if (!entry)
5467
+ continue;
5468
+ byEntry.get(entry.key)?.push(relative(projectRoot, resolve4(repoRoot, filePath)));
3276
5469
  }
5470
+ return byEntry;
5471
+ }
5472
+ function refSide(ref, matchers, projectRoot, repoRoot) {
5473
+ return {
5474
+ read: (path) => gitShow(ref, path, projectRoot, repoRoot),
5475
+ list: () => listSpecFilesAtRef(ref, matchers, projectRoot, repoRoot)
5476
+ };
5477
+ }
5478
+ function worktreeSide(matchers, projectRoot, repoRoot) {
5479
+ return {
5480
+ read: (path) => {
5481
+ try {
5482
+ return readFileSync(resolve4(projectRoot, path), "utf-8");
5483
+ } catch {
5484
+ throw new DiffError(`Cannot read "${path}" in the working tree`);
5485
+ }
5486
+ },
5487
+ list: () => listSpecFilesInWorktree(matchers, projectRoot, repoRoot)
5488
+ };
5489
+ }
5490
+ function getChangedSpecFilesInWorktree(baseRef, matchers, projectRoot, repoRoot) {
3277
5491
  let diffOutput;
3278
5492
  try {
3279
- diffOutput = execSync2(`git diff --name-status ${baseRef} ${headRef}`, {
5493
+ diffOutput = execSync2(`git diff --name-status ${baseRef}`, {
3280
5494
  cwd: repoRoot,
3281
5495
  encoding: "utf-8",
3282
5496
  stdio: "pipe"
3283
5497
  });
3284
5498
  } catch {
3285
- throw new DiffError(`Failed to run git diff between "${baseRef}" and "${headRef}"`);
5499
+ throw new DiffError(`Failed to diff "${baseRef}" against the working tree`);
3286
5500
  }
3287
5501
  const result = { modified: [], added: [], deleted: [] };
5502
+ const seen = /* @__PURE__ */ new Set();
5503
+ const record = (status, filePath) => {
5504
+ const entry = matchers.find((m) => m.isMatch(filePath));
5505
+ if (!entry)
5506
+ return;
5507
+ if (seen.has(filePath))
5508
+ return;
5509
+ seen.add(filePath);
5510
+ const changed = {
5511
+ path: relative(projectRoot, resolve4(repoRoot, filePath)),
5512
+ entryKey: entry.key
5513
+ };
5514
+ if (status === "M")
5515
+ result.modified.push(changed);
5516
+ else if (status === "A")
5517
+ result.added.push(changed);
5518
+ else if (status === "D")
5519
+ result.deleted.push(changed);
5520
+ };
3288
5521
  for (const line of diffOutput.trim().split("\n")) {
3289
5522
  if (!line)
3290
5523
  continue;
@@ -3293,57 +5526,105 @@ function getChangedSpecFiles(baseRef, headRef, specPaths, projectRoot, repoRoot)
3293
5526
  const filePath = parts[1];
3294
5527
  if (!status || !filePath)
3295
5528
  continue;
3296
- const projectRelPath = repoRelToProjectRel.get(filePath);
3297
- if (projectRelPath === void 0)
5529
+ record(status, filePath);
5530
+ }
5531
+ let untracked;
5532
+ try {
5533
+ untracked = execSync2("git ls-files --others --exclude-standard", {
5534
+ cwd: repoRoot,
5535
+ encoding: "utf-8",
5536
+ stdio: "pipe"
5537
+ });
5538
+ } catch {
5539
+ throw new DiffError("Failed to list untracked files");
5540
+ }
5541
+ for (const filePath of untracked.trim().split("\n")) {
5542
+ if (!filePath)
3298
5543
  continue;
3299
- if (status === "M") {
3300
- result.modified.push(projectRelPath);
3301
- } else if (status === "A") {
3302
- result.added.push(projectRelPath);
3303
- } else if (status === "D") {
3304
- result.deleted.push(projectRelPath);
3305
- }
5544
+ record("A", filePath);
3306
5545
  }
3307
5546
  return result;
3308
5547
  }
3309
- async function diffBetweenRefs(configPath, baseRef, headRef) {
3310
- const projectRoot = realpathSync(dirname2(resolve2(configPath)));
5548
+ function listUncommittedSpecFiles(matchers, projectRoot, repoRoot) {
5549
+ let statusOutput;
5550
+ try {
5551
+ statusOutput = execSync2("git status --porcelain", {
5552
+ cwd: repoRoot,
5553
+ encoding: "utf-8",
5554
+ stdio: "pipe"
5555
+ });
5556
+ } catch {
5557
+ return [];
5558
+ }
5559
+ const files = [];
5560
+ for (const line of statusOutput.split("\n")) {
5561
+ if (!line.trim())
5562
+ continue;
5563
+ const rawPath = line.slice(3);
5564
+ const renamed = rawPath.includes(" -> ") ? rawPath.split(" -> ")[1] : void 0;
5565
+ const filePath = (renamed ?? rawPath).replace(/^"|"$/g, "");
5566
+ if (!matchers.some((m) => m.isMatch(filePath)))
5567
+ continue;
5568
+ files.push(relative(projectRoot, resolve4(repoRoot, filePath)));
5569
+ }
5570
+ return files;
5571
+ }
5572
+ async function specIdsFrom(files, read) {
5573
+ const ids = [];
5574
+ for (const file of files) {
5575
+ try {
5576
+ const parsed = await parseSpecFromString(read(file.path), file.path);
5577
+ ids.push(parsed.frontmatter.id);
5578
+ } catch {
5579
+ ids.push(file.entryKey);
5580
+ }
5581
+ }
5582
+ return ids;
5583
+ }
5584
+ async function diffBetweenRefs(configPath, baseRef, headRef, options = {}) {
5585
+ const projectRoot = realpathSync(dirname2(resolve4(configPath)));
3311
5586
  const repoRoot = getRepoRoot(projectRoot);
3312
5587
  validateRef(baseRef, projectRoot);
3313
- validateRef(headRef, projectRoot);
5588
+ if (!options.working)
5589
+ validateRef(headRef, projectRoot);
3314
5590
  const config = await loadConfig(configPath);
3315
- const specPaths = [];
3316
- const specIdByPath = /* @__PURE__ */ new Map();
3317
- for (const [specId, entry] of Object.entries(config.specs)) {
3318
- specPaths.push(entry.path);
3319
- specIdByPath.set(entry.path, specId);
3320
- }
3321
- const changed = getChangedSpecFiles(baseRef, headRef, specPaths, projectRoot, repoRoot);
5591
+ const specPathsByKey = /* @__PURE__ */ new Map();
5592
+ for (const [key, entry] of Object.entries(config.specs)) {
5593
+ specPathsByKey.set(key, entry.path);
5594
+ }
5595
+ const matchers = buildEntryMatchers(specPathsByKey, projectRoot, repoRoot);
5596
+ const base = refSide(baseRef, matchers, projectRoot, repoRoot);
5597
+ const head = options.working ? worktreeSide(matchers, projectRoot, repoRoot) : refSide(headRef, matchers, projectRoot, repoRoot);
5598
+ const changed = options.working ? getChangedSpecFilesInWorktree(baseRef, matchers, projectRoot, repoRoot) : getChangedSpecFiles(baseRef, headRef, matchers, projectRoot, repoRoot);
3322
5599
  const diffs = [];
3323
- for (const filePath of changed.modified) {
3324
- const beforeContent = gitShow(baseRef, filePath, projectRoot, repoRoot);
3325
- const afterContent = gitShow(headRef, filePath, projectRoot, repoRoot);
3326
- const beforeSpec = await parseSpecFromString(beforeContent, filePath);
3327
- const afterSpec = await parseSpecFromString(afterContent, filePath);
5600
+ for (const file of changed.modified) {
5601
+ const beforeSpec = await parseSpecFromString(base.read(file.path), file.path);
5602
+ const afterSpec = await parseSpecFromString(head.read(file.path), file.path);
3328
5603
  const diff2 = diffSpecs(beforeSpec, afterSpec);
3329
5604
  diffs.push(diff2);
3330
5605
  }
3331
- const added = changed.added.map((p) => specIdByPath.get(p)).filter((id) => id !== void 0);
3332
- const removed = changed.deleted.map((p) => specIdByPath.get(p)).filter((id) => id !== void 0);
3333
- const graph = buildGraph(config);
5606
+ const added = await specIdsFrom(changed.added, head.read);
5607
+ const removed = await specIdsFrom(changed.deleted, base.read);
3334
5608
  const impact = [];
3335
5609
  const allSpecs = [];
3336
- for (const entry of Object.values(config.specs)) {
3337
- try {
3338
- const content = gitShow(headRef, entry.path, projectRoot, repoRoot);
3339
- const parsed = await parseSpecFromString(content, entry.path);
3340
- allSpecs.push(parsed);
3341
- } catch {
5610
+ const specsByEntry = /* @__PURE__ */ new Map();
5611
+ const filesAtHead = head.list();
5612
+ for (const [key, paths] of filesAtHead) {
5613
+ const forEntry = [];
5614
+ for (const path of paths) {
5615
+ try {
5616
+ const parsed = await parseSpecFromString(head.read(path), path);
5617
+ forEntry.push(parsed);
5618
+ allSpecs.push(parsed);
5619
+ } catch {
5620
+ }
3342
5621
  }
5622
+ specsByEntry.set(key, forEntry);
3343
5623
  }
5624
+ const relations = buildRelationResolver(config, specsByEntry);
3344
5625
  const thresholdDays = config.diff?.staleness_threshold_days ?? 14;
3345
5626
  for (const diff2 of diffs) {
3346
- const analysis = analyzeImpact(diff2.specId, diff2, graph, allSpecs, thresholdDays);
5627
+ const analysis = analyzeImpact(diff2.specId, diff2, relations, allSpecs, thresholdDays);
3347
5628
  if (analysis.totalAffected > 0) {
3348
5629
  impact.push(analysis);
3349
5630
  }
@@ -3367,17 +5648,70 @@ async function diffBetweenRefs(configPath, baseRef, headRef) {
3367
5648
  summaryParts.push(`${_brokenRefs.length} broken reference(s)`);
3368
5649
  }
3369
5650
  const summary = summaryParts.length > 0 ? summaryParts.join("; ") : "No changes detected";
3370
- return { diffs, added, removed, impact, summary };
5651
+ const uncommittedSpecFiles = options.working ? [] : listUncommittedSpecFiles(matchers, projectRoot, repoRoot);
5652
+ return { diffs, added, removed, impact, summary, uncommittedSpecFiles };
5653
+ }
5654
+
5655
+ // src/formatters/changelog.ts
5656
+ function formatChangelog(result, baseRef, headRef) {
5657
+ const lines = [];
5658
+ lines.push(`## Spec Changes (${baseRef}..${headRef})
5659
+ `);
5660
+ if (result.diffs.length > 0) {
5661
+ lines.push("### Modified");
5662
+ for (const diff2 of result.diffs) {
5663
+ const sections = diff2.sections.map((s) => s.heading).join(", ");
5664
+ const versionChange = diff2.frontmatter.find((f) => f.field === "version");
5665
+ const versionStr = versionChange ? ` (${String(versionChange.before)} \u2192 ${String(versionChange.after)})` : "";
5666
+ lines.push(`- **${diff2.specId}**${versionStr} \u2014 ${sections || "frontmatter only"}`);
5667
+ }
5668
+ lines.push("");
5669
+ }
5670
+ if (result.added.length > 0) {
5671
+ lines.push("### Added");
5672
+ for (const id of result.added) {
5673
+ lines.push(`- **${id}**`);
5674
+ }
5675
+ lines.push("");
5676
+ }
5677
+ if (result.removed.length > 0) {
5678
+ lines.push("### Removed");
5679
+ for (const id of result.removed) {
5680
+ lines.push(`- **${id}**`);
5681
+ }
5682
+ lines.push("");
5683
+ }
5684
+ const allDownstream = result.impact.flatMap((i) => i.downstream);
5685
+ if (allDownstream.length > 0) {
5686
+ lines.push("### Downstream Impact");
5687
+ for (const d of allDownstream) {
5688
+ lines.push(`- ${d.specId} may be stale (${d.reason})`);
5689
+ }
5690
+ lines.push("");
5691
+ }
5692
+ if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
5693
+ lines.push("No spec changes detected.\n");
5694
+ }
5695
+ if (result.uncommittedSpecFiles.length > 0) {
5696
+ lines.push(
5697
+ `> \u26A0 ${result.uncommittedSpecFiles.length} spec file(s) changed in the working tree are not covered by this range.
5698
+ `
5699
+ );
5700
+ }
5701
+ return lines.join("\n");
3371
5702
  }
3372
5703
 
3373
- // src/commands/diff.ts
5704
+ // src/commands/core/diff.ts
5705
+ var FORMATS2 = ["pretty", "json", "changelog"];
3374
5706
  async function runDiff(options) {
3375
- const configDir = process.cwd();
5707
+ const configDir = options.configDir ?? process.cwd();
3376
5708
  const config = await loadConfig(void 0, configDir);
3377
5709
  const baseRef = options.base ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;
3378
5710
  const headRef = options.head ?? "HEAD";
3379
5711
  const configPath = join5(configDir, "spec.config.yaml");
3380
- const result = await diffBetweenRefs(configPath, baseRef, headRef);
5712
+ const result = await diffBetweenRefs(configPath, baseRef, headRef, {
5713
+ working: options.working ?? false
5714
+ });
3381
5715
  if (options.spec) {
3382
5716
  result.diffs = result.diffs.filter((d) => d.specId === options.spec);
3383
5717
  result.impact = result.impact.filter((i) => i.changedSpec === options.spec);
@@ -3389,28 +5723,58 @@ var diff_default = defineCommand4({
3389
5723
  args: {
3390
5724
  base: { type: "string", description: "Base git ref (default: from config or 'main')" },
3391
5725
  head: { type: "string", description: "Head git ref (default: HEAD)" },
5726
+ working: {
5727
+ type: "boolean",
5728
+ description: "Compare the base ref against the working tree (includes uncommitted specs)",
5729
+ default: false
5730
+ },
3392
5731
  spec: { type: "string", description: "Scope to a single spec ID" },
3393
- format: {
3394
- type: "string",
3395
- description: "Output format: pretty, json",
3396
- default: "pretty"
3397
- }
5732
+ ...sharedArgs(FORMATS2)
3398
5733
  },
3399
5734
  async run({ args }) {
5735
+ const format = resolveFormat(args.format, FORMATS2);
5736
+ if (!format.ok) {
5737
+ console.error(`
5738
+ \u2717 ${format.message}
5739
+ `);
5740
+ process.exit(1);
5741
+ }
5742
+ const output = createOutput({ quiet: args.quiet });
3400
5743
  try {
3401
5744
  try {
3402
5745
  const result = await runDiff({
3403
5746
  base: args.base,
3404
5747
  head: args.head,
3405
5748
  spec: args.spec,
3406
- format: args.format
5749
+ format: args.format,
5750
+ working: args.working
3407
5751
  });
3408
- if (args.format === "json") {
5752
+ if (format.format === "json") {
3409
5753
  console.log(JSON.stringify(result, null, 2));
3410
5754
  return;
3411
5755
  }
5756
+ if (format.format === "changelog") {
5757
+ const baseRef = args.base ?? (await loadConfig(void 0, process.cwd())).diff?.baseline_ref ?? "main";
5758
+ console.log(
5759
+ formatChangelog(result, baseRef, args.working ? "working tree" : args.head ?? "HEAD")
5760
+ );
5761
+ return;
5762
+ }
5763
+ const printUncommittedWarning = () => {
5764
+ if (result.uncommittedSpecFiles.length === 0) return;
5765
+ const count = result.uncommittedSpecFiles.length;
5766
+ console.log(
5767
+ `
5768
+ \u26A0 ${count} spec file(s) changed in the working tree are not covered by this comparison:`
5769
+ );
5770
+ for (const file of result.uncommittedSpecFiles) {
5771
+ console.log(` ${file}`);
5772
+ }
5773
+ console.log(" Run with --working to include them.");
5774
+ };
3412
5775
  if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
3413
- console.log(" \u2713 No spec changes detected.");
5776
+ output.info(" \u2713 No spec changes detected.");
5777
+ printUncommittedWarning();
3414
5778
  return;
3415
5779
  }
3416
5780
  console.log(result.summary);
@@ -3443,6 +5807,7 @@ var diff_default = defineCommand4({
3443
5807
  }
3444
5808
  }
3445
5809
  }
5810
+ printUncommittedWarning();
3446
5811
  } catch (err) {
3447
5812
  if (err instanceof DiffError) {
3448
5813
  console.error(`
@@ -3461,10 +5826,11 @@ var diff_default = defineCommand4({
3461
5826
  }
3462
5827
  });
3463
5828
 
3464
- // src/commands/status.ts
5829
+ // src/commands/core/status.ts
3465
5830
  import { defineCommand as defineCommand5 } from "citty";
3466
- async function runStatus(_options = {}) {
3467
- const configDir = process.cwd();
5831
+ var FORMATS3 = ["pretty", "json", "github"];
5832
+ async function runStatus(options = {}) {
5833
+ const configDir = options.configDir ?? process.cwd();
3468
5834
  const config = await loadConfig(void 0, configDir);
3469
5835
  const specs = [];
3470
5836
  for (const [, entry] of Object.entries(config.specs)) {
@@ -3480,7 +5846,11 @@ async function runStatus(_options = {}) {
3480
5846
  byStatus[status] = (byStatus[status] ?? 0) + 1;
3481
5847
  }
3482
5848
  const presetName = config.lint?.extends ?? "recommended";
3483
- const rules = getPreset(presetName);
5849
+ const { rules, ignore } = await resolveLintConfig({
5850
+ config,
5851
+ preset: presetName,
5852
+ configDir
5853
+ });
3484
5854
  let graph;
3485
5855
  let graphError;
3486
5856
  try {
@@ -3488,7 +5858,7 @@ async function runStatus(_options = {}) {
3488
5858
  } catch (err) {
3489
5859
  graphError = err.message;
3490
5860
  }
3491
- const engine = createLintEngine({ rules, config, graph });
5861
+ const engine = createLintEngine({ rules, config, graph, ignore });
3492
5862
  const lintResults = engine.lint(specs.map((s) => s.spec));
3493
5863
  if (graphError) {
3494
5864
  lintResults.diagnostics.push({
@@ -3501,6 +5871,10 @@ async function runStatus(_options = {}) {
3501
5871
  }
3502
5872
  const errors = lintResults.diagnostics.filter((d) => d.severity === "error").length;
3503
5873
  const warnings = lintResults.diagnostics.filter((d) => d.severity === "warn").length;
5874
+ const specsWithErrors = new Set(
5875
+ lintResults.diagnostics.filter((d) => d.severity === "error").map((d) => d.filePath)
5876
+ );
5877
+ const passing = specs.filter(({ spec }) => !specsWithErrors.has(spec.filePath)).length;
3504
5878
  const thresholdDays = config.diff?.staleness_threshold_days ?? DEFAULT_DIFF_CONFIG.staleness_threshold_days;
3505
5879
  const now = Date.now();
3506
5880
  const staleSpecs = [];
@@ -3532,11 +5906,12 @@ async function runStatus(_options = {}) {
3532
5906
  let verdict = "healthy";
3533
5907
  if (errors > 0) verdict = "errors";
3534
5908
  else if (warnings > 0 || staleSpecs.length > 0) verdict = "warnings";
5909
+ else if (specs.length === 0) verdict = "unassessed";
3535
5910
  return {
3536
5911
  project: config.project?.name ?? "unknown",
3537
- specCount: specs.length,
5912
+ specFiles: specs.length,
3538
5913
  byStatus,
3539
- lintHealth: { errors, warnings, passing: specs.length - errors },
5914
+ lintHealth: { errors, warnings, passing },
3540
5915
  staleSpecs,
3541
5916
  integrityIssues,
3542
5917
  verdict
@@ -3544,21 +5919,32 @@ async function runStatus(_options = {}) {
3544
5919
  }
3545
5920
  var status_default = defineCommand5({
3546
5921
  meta: { name: "status", description: "Show spec suite health overview" },
3547
- args: {
3548
- format: {
3549
- type: "string",
3550
- description: "Output format: pretty, json, github",
3551
- default: "pretty"
3552
- }
3553
- },
5922
+ args: { ...sharedArgs(FORMATS3) },
3554
5923
  async run({ args }) {
5924
+ const format = resolveFormat(args.format, FORMATS3);
5925
+ if (!format.ok) {
5926
+ console.error(`
5927
+ \u2717 ${format.message}
5928
+ `);
5929
+ process.exit(1);
5930
+ }
5931
+ const output = createOutput({ quiet: args.quiet });
3555
5932
  try {
3556
- const result = await runStatus({ format: args.format });
3557
- if (args.format === "json") {
5933
+ const result = await runStatus();
5934
+ if (format.format === "json") {
3558
5935
  console.log(JSON.stringify(result, null, 2));
3559
5936
  return;
3560
5937
  }
3561
- if (args.format === "github") {
5938
+ if (format.format === "github") {
5939
+ const level = result.verdict === "errors" ? "error" : result.verdict === "healthy" ? "notice" : "warning";
5940
+ console.log(
5941
+ `::${level}::specdx status \u2014 ${result.project} \u2014 ${result.verdict}: ${result.specFiles} spec file(s), ${result.lintHealth.errors} error(s), ${result.lintHealth.warnings} warning(s)`
5942
+ );
5943
+ if (result.verdict === "unassessed") {
5944
+ console.log(
5945
+ "::warning::No specs resolved \u2014 nothing was assessed. Check the spec paths in spec.config.yaml."
5946
+ );
5947
+ }
3562
5948
  for (const s of result.staleSpecs) {
3563
5949
  console.log(
3564
5950
  `::warning::Spec "${s.specId}" is stale (${s.daysSinceUpdate} days since update)`
@@ -3569,24 +5955,32 @@ var status_default = defineCommand5({
3569
5955
  }
3570
5956
  return;
3571
5957
  }
3572
- const icon = result.verdict === "healthy" ? "\u2713" : result.verdict === "warnings" ? "\u26A0" : "\u2717";
3573
- console.log(`
3574
- ${icon} ${result.project} \u2014 ${result.verdict}`);
3575
- console.log(
3576
- ` ${result.specCount} specs: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
5958
+ const icon = result.verdict === "healthy" ? "\u2713" : result.verdict === "warnings" || result.verdict === "unassessed" ? "\u26A0" : "\u2717";
5959
+ const healthy = result.verdict === "healthy";
5960
+ const headline = `
5961
+ ${icon} ${result.project} \u2014 ${result.verdict}`;
5962
+ if (healthy) output.info(headline);
5963
+ else output.out(headline);
5964
+ if (result.verdict === "unassessed") {
5965
+ output.out(
5966
+ " No specs resolved \u2014 nothing was assessed. Check the spec paths in spec.config.yaml."
5967
+ );
5968
+ }
5969
+ output.info(
5970
+ ` ${result.specFiles} specs: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
3577
5971
  );
3578
- console.log(
5972
+ output.info(
3579
5973
  ` Lint: ${result.lintHealth.errors} errors, ${result.lintHealth.warnings} warnings`
3580
5974
  );
3581
5975
  if (result.staleSpecs.length > 0) {
3582
- console.log(
5976
+ output.out(
3583
5977
  ` Stale: ${result.staleSpecs.map((s) => `${s.specId} (${s.daysSinceUpdate}d)`).join(", ")}`
3584
5978
  );
3585
5979
  }
3586
5980
  if (result.integrityIssues.length > 0) {
3587
- console.log(` Issues: ${result.integrityIssues.join("; ")}`);
5981
+ output.out(` Issues: ${result.integrityIssues.join("; ")}`);
3588
5982
  }
3589
- console.log();
5983
+ output.info();
3590
5984
  } catch (err) {
3591
5985
  console.error(`
3592
5986
  \u2717 ${err.message}
@@ -3596,188 +5990,95 @@ var status_default = defineCommand5({
3596
5990
  }
3597
5991
  });
3598
5992
 
3599
- // src/commands/changelog.ts
5993
+ // src/commands/core/validate.ts
3600
5994
  import { defineCommand as defineCommand6 } from "citty";
3601
- import { join as join6 } from "path";
3602
- async function runChangelog(options) {
3603
- const configDir = process.cwd();
3604
- const config = await loadConfig(void 0, configDir);
3605
- const fromRef = options.from ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;
3606
- const toRef = options.to ?? "HEAD";
3607
- const configPath = join6(configDir, "spec.config.yaml");
3608
- const result = await diffBetweenRefs(configPath, fromRef, toRef);
3609
- const lines = [];
3610
- lines.push(`## Spec Changes (${fromRef}..${toRef})
3611
- `);
3612
- if (result.diffs.length > 0) {
3613
- lines.push("### Modified");
3614
- for (const diff2 of result.diffs) {
3615
- const sections = diff2.sections.map((s) => s.heading).join(", ");
3616
- const versionChange = diff2.frontmatter.find((f) => f.field === "version");
3617
- const versionStr = versionChange ? ` (${String(versionChange.before)} \u2192 ${String(versionChange.after)})` : "";
3618
- lines.push(`- **${diff2.specId}**${versionStr} \u2014 ${sections || "frontmatter only"}`);
5995
+ var FORMATS4 = ["pretty", "json"];
5996
+ async function runValidate(configDir) {
5997
+ const warnings = [];
5998
+ try {
5999
+ const config = await loadConfig(void 0, configDir);
6000
+ buildGraph(config);
6001
+ let specFiles = 0;
6002
+ const missingRequired = [];
6003
+ for (const [key, entry] of Object.entries(config.specs)) {
6004
+ const files = await resolveGlob(entry.path, configDir);
6005
+ specFiles += files.length;
6006
+ if (files.length > 0) continue;
6007
+ if (entry.required) {
6008
+ missingRequired.push(`"${key}" (${entry.path})`);
6009
+ } else {
6010
+ warnings.push(`spec entry "${key}" resolves to no files: ${entry.path}`);
6011
+ }
3619
6012
  }
3620
- lines.push("");
3621
- }
3622
- if (result.added.length > 0) {
3623
- lines.push("### Added");
3624
- for (const id of result.added) {
3625
- lines.push(`- **${id}**`);
6013
+ if (missingRequired.length > 0) {
6014
+ return {
6015
+ valid: false,
6016
+ specEntries: Object.keys(config.specs).length,
6017
+ specFiles,
6018
+ warnings,
6019
+ error: `required spec entry resolves to no files: ${missingRequired.join(", ")}`
6020
+ };
3626
6021
  }
3627
- lines.push("");
3628
- }
3629
- if (result.removed.length > 0) {
3630
- lines.push("### Removed");
3631
- for (const id of result.removed) {
3632
- lines.push(`- **${id}**`);
6022
+ if (specFiles === 0) {
6023
+ warnings.push(
6024
+ "no spec files found \u2014 every downstream check (lint, status, ready) would pass vacuously"
6025
+ );
3633
6026
  }
3634
- lines.push("");
3635
- }
3636
- const allDownstream = result.impact.flatMap((i) => i.downstream);
3637
- if (allDownstream.length > 0) {
3638
- lines.push("### Downstream Impact");
3639
- for (const d of allDownstream) {
3640
- lines.push(`- ${d.specId} may be stale (${d.reason})`);
6027
+ return {
6028
+ valid: true,
6029
+ specEntries: Object.keys(config.specs).length,
6030
+ specFiles,
6031
+ warnings
6032
+ };
6033
+ } catch (err) {
6034
+ if (err instanceof ConfigError) {
6035
+ return { valid: false, warnings, error: err.message, details: err.errors ?? void 0 };
3641
6036
  }
3642
- lines.push("");
3643
- }
3644
- if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
3645
- lines.push("No spec changes detected.\n");
6037
+ if (err instanceof GraphError) {
6038
+ return { valid: false, warnings, error: err.message };
6039
+ }
6040
+ throw err;
3646
6041
  }
3647
- return lines.join("\n");
3648
6042
  }
3649
- var changelog_default = defineCommand6({
3650
- meta: { name: "changelog", description: "Generate changelog of spec changes between git refs" },
3651
- args: {
3652
- from: { type: "string", description: "Start git ref (default: from config or 'main')" },
3653
- to: { type: "string", description: "End git ref (default: HEAD)" }
3654
- },
6043
+ var validate_default = defineCommand6({
6044
+ meta: { name: "validate", description: "Validate spec.config.yaml" },
6045
+ args: { ...sharedArgs(FORMATS4) },
3655
6046
  async run({ args }) {
3656
- try {
3657
- try {
3658
- const output = await runChangelog(args);
3659
- console.log(output);
3660
- } catch (err) {
3661
- if (err instanceof DiffError) {
3662
- console.error(`
3663
- \u2717 ${err.message}
3664
- `);
3665
- process.exit(1);
3666
- }
3667
- throw err;
3668
- }
3669
- } catch (err) {
6047
+ const format = resolveFormat(args.format, FORMATS4);
6048
+ if (!format.ok) {
3670
6049
  console.error(`
3671
- \u2717 ${err.message}
6050
+ \u2717 ${format.message}
3672
6051
  `);
3673
6052
  process.exit(1);
3674
6053
  }
3675
- }
3676
- });
3677
-
3678
- // src/commands/explain.ts
3679
- import { defineCommand as defineCommand7 } from "citty";
3680
- async function runExplain(_options = {}) {
3681
- const configDir = process.cwd();
3682
- const config = await loadConfig(void 0, configDir);
3683
- const specs = [];
3684
- for (const [, entry] of Object.entries(config.specs)) {
3685
- const paths = await resolveGlob(entry.path, configDir);
3686
- for (const p of paths) {
3687
- specs.push(await parseSpec(p));
3688
- }
3689
- }
3690
- const byType = {};
3691
- const byStatus = {};
3692
- for (const spec of specs) {
3693
- const type = spec.frontmatter.type || "unknown";
3694
- const status = spec.frontmatter.status || "unknown";
3695
- byType[type] = (byType[type] ?? 0) + 1;
3696
- byStatus[status] = (byStatus[status] ?? 0) + 1;
3697
- }
3698
- const specSummaries = specs.map((spec) => {
3699
- const firstSection = spec.parsedSections[0];
3700
- const firstLine = firstSection?.content?.split("\n").find((l) => l.trim().length > 0)?.trim() ?? "";
3701
- const truncated = firstLine.slice(0, 120) + (firstLine.length > 120 ? "..." : "");
3702
- return {
3703
- id: spec.frontmatter.id,
3704
- type: spec.frontmatter.type,
3705
- title: spec.frontmatter.title,
3706
- status: spec.frontmatter.status,
3707
- firstLine: truncated
3708
- };
3709
- });
3710
- const graph = buildGraph(config);
3711
- const graphLines = [];
3712
- for (const node of graph.nodes) {
3713
- const downstream = graph.edges.filter((e) => e.from === node).map((e) => e.to);
3714
- if (downstream.length > 0) {
3715
- graphLines.push(`${node} \u2192 ${downstream.join(", ")}`);
3716
- } else {
3717
- graphLines.push(node);
6054
+ const output = createOutput({ quiet: args.quiet });
6055
+ const result = await runValidate(process.cwd());
6056
+ if (format.format === "json") {
6057
+ console.log(JSON.stringify(result, null, 2));
6058
+ if (!result.valid) process.exit(1);
6059
+ return;
3718
6060
  }
3719
- }
3720
- return {
3721
- project: config.project?.name ?? "unknown",
3722
- description: config.project?.description,
3723
- specCount: specs.length,
3724
- byType,
3725
- byStatus,
3726
- specs: specSummaries,
3727
- graph: graphLines
3728
- };
3729
- }
3730
- var explain_default = defineCommand7({
3731
- meta: { name: "explain", description: "Explain the spec suite for onboarding" },
3732
- args: {
3733
- format: { type: "string", description: "Output format: pretty, json", default: "pretty" }
3734
- },
3735
- async run({ args }) {
3736
- try {
3737
- const result = await runExplain({ format: args.format });
3738
- if (args.format === "json") {
3739
- console.log(JSON.stringify(result, null, 2));
3740
- return;
3741
- }
3742
- console.log(`
3743
- ${result.project}`);
3744
- if (result.description) {
3745
- console.log(` ${result.description}`);
3746
- }
3747
- console.log(
3748
- `
3749
- ${result.specCount} specs: ${Object.entries(result.byType).map(([k, v]) => `${v} ${k}`).join(", ")}`
3750
- );
3751
- console.log(
3752
- ` Status: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
6061
+ if (result.valid) {
6062
+ output.info(
6063
+ ` \u2713 Config valid. ${result.specEntries} spec entries, ${result.specFiles} spec files.`
3753
6064
  );
3754
- console.log("\n Specs:");
3755
- for (const spec of result.specs) {
3756
- console.log(` ${spec.id} (${spec.type}, ${spec.status}) \u2014 ${spec.title}`);
3757
- if (spec.firstLine) {
3758
- console.log(` ${spec.firstLine}`);
3759
- }
3760
- }
3761
- console.log("\n Dependencies:");
3762
- for (const line of result.graph) {
3763
- console.log(` ${line}`);
3764
- }
3765
- console.log();
3766
- } catch (err) {
3767
- console.error(`
3768
- \u2717 ${err.message}
3769
- `);
3770
- process.exit(1);
6065
+ for (const w of result.warnings) output.out(` \u26A0 ${w}`);
6066
+ return;
6067
+ }
6068
+ console.error(` \u2717 Config invalid: ${result.error}`);
6069
+ for (const w of result.warnings) console.error(` \u26A0 ${w}`);
6070
+ if (result.details) {
6071
+ for (const e of result.details) console.error(` - ${JSON.stringify(e)}`);
3771
6072
  }
6073
+ process.exit(1);
3772
6074
  }
3773
6075
  });
3774
6076
  export {
3775
- runChangelog,
3776
6077
  runDiff,
3777
- runExplain,
3778
6078
  runLint,
3779
6079
  runPack,
3780
6080
  runStatus,
6081
+ runValidate,
3781
6082
  scaffoldProject
3782
6083
  };
3783
6084
  //# sourceMappingURL=index.js.map