specdx 0.4.0-alpha.2 → 0.4.0-alpha.21

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 (112) hide show
  1. package/.claude-plugin/plugin.json +7 -2
  2. package/LICENSE +21 -0
  3. package/README.md +477 -0
  4. package/dist/{check-PZFBVQIP.js → check-GGGHTDTH.js} +37 -11
  5. package/dist/check-GGGHTDTH.js.map +1 -0
  6. package/dist/{chunk-QEUZJWBY.js → chunk-3YXRWQGX.js} +373 -63
  7. package/dist/chunk-3YXRWQGX.js.map +1 -0
  8. package/dist/chunk-5WRI5ZAA.js +31 -0
  9. package/dist/chunk-6IVWJKMQ.js +103 -0
  10. package/dist/chunk-6IVWJKMQ.js.map +1 -0
  11. package/dist/{chunk-YDU26YTH.js → chunk-HCJDCS26.js} +121 -17
  12. package/dist/chunk-HCJDCS26.js.map +1 -0
  13. package/dist/chunk-IEW62WR2.js +185 -0
  14. package/dist/chunk-IEW62WR2.js.map +1 -0
  15. package/dist/chunk-PXQML7NE.js +2846 -0
  16. package/dist/chunk-PXQML7NE.js.map +1 -0
  17. package/dist/{chunk-PHWUK7TH.js → chunk-QOP2KHW3.js} +290 -52
  18. package/dist/chunk-QOP2KHW3.js.map +1 -0
  19. package/dist/{chunk-FZWT4HVX.js → chunk-SNQNQ2MP.js} +157 -3
  20. package/dist/chunk-SNQNQ2MP.js.map +1 -0
  21. package/dist/{chunk-YRDOYUKF.js → chunk-YRQPY5NF.js} +124 -19
  22. package/dist/chunk-YRQPY5NF.js.map +1 -0
  23. package/dist/diff-VHVSXLKU.js +188 -0
  24. package/dist/diff-VHVSXLKU.js.map +1 -0
  25. package/dist/{dist-2B2MR5AM.js → dist-QRCEQ5WI.js} +53 -14
  26. package/dist/dist-QRCEQ5WI.js.map +1 -0
  27. package/dist/dist-ROHCFKYT.js +16 -0
  28. package/dist/dist-ROHCFKYT.js.map +1 -0
  29. package/dist/generate-WMJ37LCN.js +21 -0
  30. package/dist/generate-WMJ37LCN.js.map +1 -0
  31. package/dist/{generate-story-AOALIKSD.js → generate-story-ORJX24P7.js} +48 -20
  32. package/dist/generate-story-ORJX24P7.js.map +1 -0
  33. package/dist/{generate-test-plan-34L6RGOB.js → generate-test-plan-Z46W3N3B.js} +63 -10
  34. package/dist/generate-test-plan-Z46W3N3B.js.map +1 -0
  35. package/dist/graph-TG2CONHV.js +103 -0
  36. package/dist/graph-TG2CONHV.js.map +1 -0
  37. package/dist/index.d.ts +171 -0
  38. package/dist/index.js +2648 -390
  39. package/dist/index.js.map +1 -1
  40. package/dist/{lint-XGVQ6LCP.js → lint-ZFG6ALIT.js} +23 -8
  41. package/dist/lint-ZFG6ALIT.js.map +1 -0
  42. package/dist/main.js +11 -146
  43. package/dist/main.js.map +1 -1
  44. package/dist/mcp-WBHZANS5.js +35 -0
  45. package/dist/mcp-WBHZANS5.js.map +1 -0
  46. package/dist/{migrate-KDJZQKP7.js → migrate-FKFC7UAO.js} +20 -8
  47. package/dist/migrate-FKFC7UAO.js.map +1 -0
  48. package/dist/{pack-OJ3CDZHD.js → pack-VDEO7GRF.js} +39 -11
  49. package/dist/pack-VDEO7GRF.js.map +1 -0
  50. package/dist/ready-VDOH3XCV.js +257 -0
  51. package/dist/ready-VDOH3XCV.js.map +1 -0
  52. package/dist/skills/{specdx-author-spec.md → core/specdx-author-spec/SKILL.md} +10 -6
  53. package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-01-frontmatter.md +1 -1
  54. package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-02-sections.md +41 -0
  55. package/dist/skills/{specdx-onboard.md → core/specdx-onboard/SKILL.md} +8 -3
  56. package/dist/skills/{specdx-plan-from-spec.md → core/specdx-plan-from-spec/SKILL.md} +5 -1
  57. package/dist/skills/{specdx-pre-commit.md → core/specdx-pre-commit/SKILL.md} +16 -2
  58. package/dist/skills/{specdx-review-spec.md → core/specdx-review-spec/SKILL.md} +5 -1
  59. package/dist/skills/core/specdx-router/SKILL.md +67 -0
  60. package/dist/skills/{specdx-sprint-review.md → core/specdx-sprint-review/SKILL.md} +5 -1
  61. package/dist/skills/{specdx-start-task.md → core/specdx-start-task/SKILL.md} +5 -1
  62. package/dist/skills/{specdx-check-drift.md → experimental/specdx-check-drift/SKILL.md} +10 -4
  63. package/dist/skills/{specdx-verify.md → experimental/specdx-verify/SKILL.md} +17 -2
  64. package/dist/skills-36SRUEMR.js +121 -0
  65. package/dist/skills-36SRUEMR.js.map +1 -0
  66. package/dist/{status-JVIXK73H.js → status-JIQUF6MX.js} +48 -34
  67. package/dist/status-JIQUF6MX.js.map +1 -0
  68. package/dist/{update-HFLDULNJ.js → update-DNXF5Q64.js} +10 -9
  69. package/dist/update-DNXF5Q64.js.map +1 -0
  70. package/dist/validate-TSAMI65E.js +87 -0
  71. package/dist/validate-TSAMI65E.js.map +1 -0
  72. package/hooks/hooks.json +12 -6
  73. package/hooks/session-start +35 -3
  74. package/package.json +68 -21
  75. package/dist/changelog-G6XDIAZP.js +0 -86
  76. package/dist/changelog-G6XDIAZP.js.map +0 -1
  77. package/dist/check-PZFBVQIP.js.map +0 -1
  78. package/dist/chunk-7C3BAVCP.js +0 -1147
  79. package/dist/chunk-7C3BAVCP.js.map +0 -1
  80. package/dist/chunk-FZWT4HVX.js.map +0 -1
  81. package/dist/chunk-PHWUK7TH.js.map +0 -1
  82. package/dist/chunk-QEUZJWBY.js.map +0 -1
  83. package/dist/chunk-YDU26YTH.js.map +0 -1
  84. package/dist/chunk-YRDOYUKF.js.map +0 -1
  85. package/dist/diff-BEZARP53.js +0 -100
  86. package/dist/diff-BEZARP53.js.map +0 -1
  87. package/dist/dist-2B2MR5AM.js.map +0 -1
  88. package/dist/dist-WIK7F2PJ.js +0 -11
  89. package/dist/explain-PCZKDEM4.js +0 -102
  90. package/dist/explain-PCZKDEM4.js.map +0 -1
  91. package/dist/generate-OMEBJQFQ.js +0 -13
  92. package/dist/generate-OMEBJQFQ.js.map +0 -1
  93. package/dist/generate-story-AOALIKSD.js.map +0 -1
  94. package/dist/generate-test-plan-34L6RGOB.js.map +0 -1
  95. package/dist/graph-RR5UTY3R.js +0 -54
  96. package/dist/graph-RR5UTY3R.js.map +0 -1
  97. package/dist/lint-XGVQ6LCP.js.map +0 -1
  98. package/dist/mcp-GUFW37BE.js +0 -17
  99. package/dist/mcp-GUFW37BE.js.map +0 -1
  100. package/dist/migrate-KDJZQKP7.js.map +0 -1
  101. package/dist/pack-OJ3CDZHD.js.map +0 -1
  102. package/dist/ready-WTNO5W7C.js +0 -165
  103. package/dist/ready-WTNO5W7C.js.map +0 -1
  104. package/dist/skills-3GBBWZW2.js +0 -93
  105. package/dist/skills-3GBBWZW2.js.map +0 -1
  106. package/dist/status-JVIXK73H.js.map +0 -1
  107. package/dist/update-HFLDULNJ.js.map +0 -1
  108. package/dist/validate-O7W5YLR6.js +0 -34
  109. package/dist/validate-O7W5YLR6.js.map +0 -1
  110. /package/dist/{dist-WIK7F2PJ.js.map → chunk-5WRI5ZAA.js.map} +0 -0
  111. /package/dist/skills/{spec-type-reference.md → core/specdx-author-spec/references/spec-type-reference.md} +0 -0
  112. /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,1568 @@
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";
1549
+
1550
+ // ../schema/dist/types.js
1551
+ var SPEC_TYPES = [
1552
+ "prd",
1553
+ "technical-design",
1554
+ "user-story",
1555
+ "test-plan",
1556
+ "adr",
1557
+ "api-contract",
1558
+ "epic",
1559
+ "quick-spec",
1560
+ "project-context"
1561
+ ];
1562
+ var DEPENDENCY_RELATIONSHIPS = {
1563
+ "depends-on": "self-requires-target",
1564
+ "implemented-by": "target-requires-self"
1565
+ };
5
1566
 
6
1567
  // ../schema/dist/sections.js
7
1568
  var REQUIRED_SECTIONS = {
@@ -33,36 +1594,129 @@ var base_spec_default = {
33
1594
  $schema: "http://json-schema.org/draft-07/schema#",
34
1595
  type: "object",
35
1596
  properties: {
36
- id: { type: "string", minLength: 1 },
37
- type: { type: "string", enum: ["prd", "technical-design", "user-story", "test-plan", "adr", "api-contract", "epic", "quick-spec", "project-context"] },
38
- title: { type: "string", minLength: 1 },
39
- status: { type: "string", enum: ["draft", "review", "approved", "superseded"] },
40
- version: { type: "string" },
41
- created: { type: "string", format: "date" },
42
- updated: { type: "string", format: "date" },
43
- authors: { type: "array", items: { type: "string" }, minItems: 1 },
44
- tags: { type: "array", items: { type: "string" }, default: [] },
1597
+ id: {
1598
+ type: "string",
1599
+ minLength: 1
1600
+ },
1601
+ type: {
1602
+ type: "string",
1603
+ enum: [
1604
+ "prd",
1605
+ "technical-design",
1606
+ "user-story",
1607
+ "test-plan",
1608
+ "adr",
1609
+ "api-contract",
1610
+ "epic",
1611
+ "quick-spec",
1612
+ "project-context"
1613
+ ]
1614
+ },
1615
+ title: {
1616
+ type: "string",
1617
+ minLength: 1
1618
+ },
1619
+ status: {
1620
+ type: "string",
1621
+ enum: [
1622
+ "draft",
1623
+ "review",
1624
+ "approved",
1625
+ "superseded"
1626
+ ]
1627
+ },
1628
+ version: {
1629
+ type: "string"
1630
+ },
1631
+ created: {
1632
+ type: "string",
1633
+ format: "date"
1634
+ },
1635
+ updated: {
1636
+ type: "string",
1637
+ format: "date"
1638
+ },
1639
+ authors: {
1640
+ type: "array",
1641
+ items: {
1642
+ type: "string"
1643
+ },
1644
+ minItems: 1
1645
+ },
1646
+ tags: {
1647
+ type: "array",
1648
+ items: {
1649
+ type: "string"
1650
+ },
1651
+ default: []
1652
+ },
45
1653
  references: {
46
1654
  type: "array",
47
1655
  items: {
48
1656
  type: "object",
49
1657
  properties: {
50
- id: { type: "string" },
51
- relationship: { type: "string", enum: ["implemented-by", "decomposed-into", "depends-on", "supersedes", "related-to"] }
1658
+ id: {
1659
+ type: "string"
1660
+ },
1661
+ relationship: {
1662
+ type: "string",
1663
+ enum: [
1664
+ "implemented-by",
1665
+ "decomposed-into",
1666
+ "depends-on",
1667
+ "supersedes",
1668
+ "related-to"
1669
+ ]
1670
+ }
1671
+ },
1672
+ required: [
1673
+ "id",
1674
+ "relationship"
1675
+ ],
1676
+ additionalProperties: false
1677
+ },
1678
+ default: []
1679
+ },
1680
+ artifacts: {
1681
+ type: "array",
1682
+ items: {
1683
+ type: "object",
1684
+ properties: {
1685
+ path: {
1686
+ type: "string",
1687
+ minLength: 1
1688
+ },
1689
+ exports: {
1690
+ type: "array",
1691
+ items: {
1692
+ type: "string",
1693
+ minLength: 1
1694
+ }
1695
+ }
52
1696
  },
53
- required: ["id", "relationship"],
1697
+ required: [
1698
+ "path"
1699
+ ],
54
1700
  additionalProperties: false
55
1701
  },
56
1702
  default: []
57
1703
  }
58
1704
  },
59
- required: ["id", "type", "title", "status", "version", "created", "authors"],
1705
+ required: [
1706
+ "id",
1707
+ "type",
1708
+ "title",
1709
+ "status",
1710
+ "version",
1711
+ "created",
1712
+ "authors"
1713
+ ],
60
1714
  additionalProperties: true
61
1715
  };
62
1716
 
63
1717
  // ../schema/dist/schemas/config.json
64
1718
  var config_default = {
65
- $id: "sdx-config",
1719
+ $id: "specdx-config",
66
1720
  $schema: "http://json-schema.org/draft-07/schema#",
67
1721
  type: "object",
68
1722
  properties: {
@@ -290,9 +1944,13 @@ var project_context_default = {
290
1944
  // ../schema/dist/validator.js
291
1945
  import * as addFormatsNs from "ajv-formats";
292
1946
  var addFormats = addFormatsNs.default ?? addFormatsNs;
1947
+ var runtimeBaseSpecSchema = structuredClone(base_spec_default);
1948
+ runtimeBaseSpecSchema.properties.type.enum = [...SPEC_TYPES];
1949
+ var runtimeConfigSchema = structuredClone(config_default);
1950
+ runtimeConfigSchema.properties.specs.additionalProperties.properties.type.enum = [...SPEC_TYPES];
293
1951
  var ajv = new AjvClass({ allErrors: true, strict: true });
294
1952
  addFormats(ajv, ["date"]);
295
- ajv.addSchema(base_spec_default);
1953
+ ajv.addSchema(runtimeBaseSpecSchema);
296
1954
  var specValidators = {
297
1955
  prd: ajv.compile(prd_default),
298
1956
  "technical-design": ajv.compile(technical_design_default),
@@ -304,7 +1962,7 @@ var specValidators = {
304
1962
  "quick-spec": ajv.compile(quick_spec_default),
305
1963
  "project-context": ajv.compile(project_context_default)
306
1964
  };
307
- var configValidator = ajv.compile(config_default);
1965
+ var configValidator = ajv.compile(runtimeConfigSchema);
308
1966
  function validateSpec(type, data) {
309
1967
  const validate = specValidators[type];
310
1968
  if (!validate) {
@@ -318,7 +1976,7 @@ function validateConfig(data) {
318
1976
  return { valid: !!valid, errors: valid ? null : configValidator.errors ?? null };
319
1977
  }
320
1978
 
321
- // src/commands/init.ts
1979
+ // src/commands/core/init.ts
322
1980
  var TEMPLATE_SPECS = {
323
1981
  lightweight: [
324
1982
  { filename: "prd.md", type: "prd" },
@@ -387,6 +2045,9 @@ async function scaffoldProject({
387
2045
  template,
388
2046
  targetDir
389
2047
  }) {
2048
+ if (!targetDir) {
2049
+ throw new TypeError("scaffoldProject requires `targetDir` \u2014 where to create the project.");
2050
+ }
390
2051
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
391
2052
  const specsDir = join(targetDir, "specs");
392
2053
  await mkdir(specsDir, { recursive: true });
@@ -401,6 +2062,9 @@ async function scaffoldProject({
401
2062
  const configContent = buildConfigYaml(projectName, specs);
402
2063
  await writeFile(join(targetDir, "spec.config.yaml"), configContent, "utf-8");
403
2064
  }
2065
+ function defaultProjectName(dir) {
2066
+ return basename(resolve(dir)) || "my-project";
2067
+ }
404
2068
  var init_default = defineCommand({
405
2069
  meta: {
406
2070
  name: "init",
@@ -409,8 +2073,7 @@ var init_default = defineCommand({
409
2073
  args: {
410
2074
  name: {
411
2075
  type: "string",
412
- description: "Project name",
413
- required: true
2076
+ description: "Project name (default: the target directory's name)"
414
2077
  },
415
2078
  template: {
416
2079
  type: "string",
@@ -424,19 +2087,20 @@ var init_default = defineCommand({
424
2087
  }
425
2088
  },
426
2089
  async run({ args }) {
427
- const { name, template, dir } = args;
2090
+ const { template, dir } = args;
428
2091
  const validTemplates = ["lightweight", "bmad", "api-first", "quick", "context"];
429
2092
  if (!validTemplates.includes(template)) {
430
2093
  console.error(`Unknown template: ${template}. Choose from: ${validTemplates.join(", ")}`);
431
2094
  process.exit(1);
432
2095
  }
2096
+ const name = args.name || defaultProjectName(dir);
433
2097
  console.log(`Scaffolding "${name}" with template "${template}" in ${dir}...`);
434
2098
  await scaffoldProject({ projectName: name, template, targetDir: dir });
435
2099
  console.log(`Done! Project "${name}" scaffolded successfully.`);
436
2100
  }
437
2101
  });
438
2102
 
439
- // src/commands/lint.ts
2103
+ // src/commands/core/lint.ts
440
2104
  import { defineCommand as defineCommand2 } from "citty";
441
2105
 
442
2106
  // ../core/dist/config.js
@@ -455,7 +2119,7 @@ var CONFIG_FILENAME = "spec.config.yaml";
455
2119
  async function loadConfig(filePath, searchFrom) {
456
2120
  const resolvedPath = filePath ?? await findConfig(searchFrom ?? process.cwd());
457
2121
  if (!resolvedPath) {
458
- 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.`);
459
2123
  }
460
2124
  let raw;
461
2125
  try {
@@ -699,6 +2363,112 @@ function buildGraph(config) {
699
2363
  };
700
2364
  }
701
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
+
702
2472
  // ../core/dist/glob.js
703
2473
  import { glob } from "tinyglobby";
704
2474
  import { join as join3, isAbsolute } from "path";
@@ -720,7 +2490,7 @@ function createLogger(options) {
720
2490
 
721
2491
  // ../core/dist/preset.js
722
2492
  import { readFile as readFile3 } from "fs/promises";
723
- import { resolve, isAbsolute as isAbsolute2 } from "path";
2493
+ import { resolve as resolve2, isAbsolute as isAbsolute2 } from "path";
724
2494
 
725
2495
  // ../lint/dist/engine.js
726
2496
  function createLintEngine(options) {
@@ -735,7 +2505,9 @@ function createLintEngine(options) {
735
2505
  config: options.config,
736
2506
  graph: options.graph
737
2507
  });
738
- diagnostics.push(...results);
2508
+ for (const diagnostic of results) {
2509
+ diagnostics.push({ ...diagnostic, severity: rule.severity });
2510
+ }
739
2511
  }
740
2512
  }
741
2513
  return {
@@ -748,6 +2520,18 @@ function createLintEngine(options) {
748
2520
  }
749
2521
 
750
2522
  // ../lint/dist/rules/valid-frontmatter.js
2523
+ function readablePath(instancePath) {
2524
+ return instancePath.split("/").filter(Boolean).map((segment) => /^\d+$/.test(segment) ? `[${segment}]` : `.${segment}`).join("").replace(/^\./, "");
2525
+ }
2526
+ function describeValidationError(err) {
2527
+ const path = readablePath(err.instancePath ?? "");
2528
+ const allowed = err.params?.allowedValues;
2529
+ let detail = err.message ?? JSON.stringify(err);
2530
+ if (Array.isArray(allowed) && allowed.length > 0) {
2531
+ detail += `: ${allowed.map((v) => JSON.stringify(v)).join(", ")}`;
2532
+ }
2533
+ return path ? `${path} ${detail}` : detail;
2534
+ }
751
2535
  var validFrontmatterRule = {
752
2536
  id: "structure/valid-frontmatter",
753
2537
  description: "Frontmatter matches the schema for the declared spec type",
@@ -759,7 +2543,7 @@ var validFrontmatterRule = {
759
2543
  return errors.map((err) => ({
760
2544
  ruleId: "structure/valid-frontmatter",
761
2545
  severity: "error",
762
- message: `Invalid frontmatter: ${err.message ?? JSON.stringify(err)}`,
2546
+ message: `Invalid frontmatter: ${describeValidationError(err)}`,
763
2547
  filePath: context.spec.filePath
764
2548
  }));
765
2549
  }
@@ -819,7 +2603,131 @@ var noCircularDepsRule = {
819
2603
  };
820
2604
 
821
2605
  // ../lint/dist/rules/story-coverage.js
822
- var FEATURE_PATTERN = /\*\*F\d+\*\*:\s*(.+)/g;
2606
+ var STOPWORDS = /* @__PURE__ */ new Set([
2607
+ "a",
2608
+ "an",
2609
+ "the",
2610
+ "and",
2611
+ "or",
2612
+ "of",
2613
+ "to",
2614
+ "for",
2615
+ "with",
2616
+ "its",
2617
+ "it",
2618
+ "in",
2619
+ "on",
2620
+ "at",
2621
+ "by",
2622
+ "from",
2623
+ "into",
2624
+ "every",
2625
+ "each",
2626
+ "that",
2627
+ "this",
2628
+ "be",
2629
+ "is",
2630
+ "are",
2631
+ "as",
2632
+ "can",
2633
+ "will",
2634
+ "must",
2635
+ "so",
2636
+ "their",
2637
+ "them",
2638
+ "when",
2639
+ "which",
2640
+ "who"
2641
+ ]);
2642
+ var OVERLAP_THRESHOLD = 0.5;
2643
+ var REFERENCED_THRESHOLD = 0.34;
2644
+ function tokenise(text) {
2645
+ 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);
2646
+ return new Set(words);
2647
+ }
2648
+ function extractFeatureSection(content) {
2649
+ const lines = content.split("\n");
2650
+ const start = lines.findIndex((l) => /^##\s+Features\s*$/.test(l.trim()));
2651
+ if (start === -1)
2652
+ return null;
2653
+ const body = [];
2654
+ for (let i = start + 1; i < lines.length; i++) {
2655
+ if (/^##\s/.test(lines[i]))
2656
+ break;
2657
+ body.push(lines[i]);
2658
+ }
2659
+ return body.join("\n");
2660
+ }
2661
+ function parseFeatures(content) {
2662
+ return parseFeatureEntries(content).map((f) => f.text);
2663
+ }
2664
+ function parseFeatureEntries(content) {
2665
+ const section = extractFeatureSection(content);
2666
+ if (section === null)
2667
+ return [];
2668
+ const ID_PREFIX = /^\*{0,2}F(\d+)\*{0,2}\s*[:.-]\s*/i;
2669
+ const features = [];
2670
+ for (const rawLine of section.split("\n")) {
2671
+ const line = rawLine.trim();
2672
+ if (!line)
2673
+ continue;
2674
+ const bullet = /^[-*]\s+(.*)$/.exec(line);
2675
+ const text = bullet ? (bullet[1] ?? "").trim() : ID_PREFIX.test(line) ? line : "";
2676
+ if (!text)
2677
+ continue;
2678
+ const idMatch = ID_PREFIX.exec(text);
2679
+ const stripped = text.replace(ID_PREFIX, "").trim();
2680
+ if (stripped)
2681
+ features.push({ text: stripped, num: idMatch?.[1] });
2682
+ }
2683
+ return features;
2684
+ }
2685
+ function overlap(featureTokens, storyTokens) {
2686
+ if (featureTokens.size === 0)
2687
+ return 0;
2688
+ let shared = 0;
2689
+ for (const token of featureTokens)
2690
+ if (storyTokens.has(token))
2691
+ shared++;
2692
+ return shared / featureTokens.size;
2693
+ }
2694
+ function referencesSpec(story, specId) {
2695
+ const refs = story.frontmatter.references;
2696
+ if (!Array.isArray(refs))
2697
+ return false;
2698
+ return refs.some((r) => r?.id === specId);
2699
+ }
2700
+ function uncoveredFeatures(features, stories, prdId) {
2701
+ const scored = stories.map((story) => ({
2702
+ tokens: tokenise(`${String(story.frontmatter.title ?? "")} ${story.content}`),
2703
+ threshold: referencesSpec(story, prdId) ? REFERENCED_THRESHOLD : OVERLAP_THRESHOLD
2704
+ }));
2705
+ const tokenised = features.map(tokenise);
2706
+ return features.filter((_feature, i) => {
2707
+ const featureTokens = tokenised[i];
2708
+ const distinctive = distinctiveTokens(featureTokens, tokenised, i);
2709
+ return !scored.some((s) => overlap(featureTokens, s.tokens) >= s.threshold && covers(distinctive, featureTokens, s.tokens));
2710
+ });
2711
+ }
2712
+ function covers(distinctive, featureTokens, storyTokens) {
2713
+ if (distinctive.size === 0 || distinctive.size === featureTokens.size)
2714
+ return true;
2715
+ let matched = 0;
2716
+ for (const token of distinctive)
2717
+ if (storyTokens.has(token))
2718
+ matched++;
2719
+ return matched > distinctive.size / 2;
2720
+ }
2721
+ function distinctiveTokens(featureTokens, allFeatureTokens, index) {
2722
+ const distinctive = new Set(featureTokens);
2723
+ for (let i = 0; i < allFeatureTokens.length; i++) {
2724
+ if (i === index)
2725
+ continue;
2726
+ for (const token of allFeatureTokens[i])
2727
+ distinctive.delete(token);
2728
+ }
2729
+ return distinctive;
2730
+ }
823
2731
  var storyCoverageRule = {
824
2732
  id: "completeness/story-coverage",
825
2733
  description: "Every feature listed in a PRD has at least one corresponding user story",
@@ -827,17 +2735,11 @@ var storyCoverageRule = {
827
2735
  run(context) {
828
2736
  if (context.spec.frontmatter.type !== "prd")
829
2737
  return [];
830
- const features = [];
831
- let match;
832
- const re = new RegExp(FEATURE_PATTERN.source, "g");
833
- while ((match = re.exec(context.spec.content)) !== null) {
834
- features.push(match[1].trim());
835
- }
2738
+ const features = parseFeatures(context.spec.content);
836
2739
  if (features.length === 0)
837
2740
  return [];
838
2741
  const stories = context.allSpecs.filter((s) => s.frontmatter.type === "user-story");
839
- const storyContent = stories.map((s) => s.content + " " + s.frontmatter.title).join(" ");
840
- return features.filter((feature) => !storyContent.toLowerCase().includes(feature.toLowerCase())).map((feature) => ({
2742
+ return uncoveredFeatures(features, stories, context.spec.frontmatter.id).map((feature) => ({
841
2743
  ruleId: "completeness/story-coverage",
842
2744
  severity: "warn",
843
2745
  message: `Feature "${feature}" has no corresponding user story`,
@@ -847,30 +2749,57 @@ var storyCoverageRule = {
847
2749
  };
848
2750
 
849
2751
  // ../lint/dist/rules/staleness-check.js
2752
+ function groupByEntry(config, specs) {
2753
+ const byEntry = /* @__PURE__ */ new Map();
2754
+ for (const key of Object.keys(config.specs))
2755
+ byEntry.set(key, []);
2756
+ for (const spec of specs) {
2757
+ let bestKey;
2758
+ let bestLen = -1;
2759
+ for (const [key, entry] of Object.entries(config.specs)) {
2760
+ const prefix = entry.path.split("*")[0] ?? "";
2761
+ const normalized = spec.filePath.replace(/\\/g, "/");
2762
+ if (normalized.includes(prefix) && prefix.length > bestLen) {
2763
+ bestKey = key;
2764
+ bestLen = prefix.length;
2765
+ }
2766
+ }
2767
+ if (bestKey)
2768
+ byEntry.get(bestKey).push(spec);
2769
+ }
2770
+ return byEntry;
2771
+ }
2772
+ function lastUpdated(spec) {
2773
+ return spec.frontmatter.updated ?? spec.frontmatter.created ?? "";
2774
+ }
850
2775
  var stalenessCheckRule = {
851
2776
  id: "freshness/staleness-check",
852
2777
  description: "Warns if a spec hasn't been updated since its upstream dependency changed",
853
2778
  severity: "warn",
854
2779
  run(context) {
855
- const refs = context.spec.frontmatter.references;
856
- if (!refs || refs.length === 0)
2780
+ const specId = context.spec.frontmatter.id;
2781
+ if (typeof specId !== "string")
2782
+ return [];
2783
+ const specUpdated = lastUpdated(context.spec);
2784
+ if (!specUpdated)
857
2785
  return [];
858
- const specUpdated = context.spec.frontmatter.updated ?? context.spec.frontmatter.created;
859
2786
  const specDate = new Date(specUpdated);
2787
+ const byEntry = context.config ? groupByEntry(context.config, context.allSpecs) : /* @__PURE__ */ new Map([["", context.allSpecs]]);
2788
+ const relations = buildRelationResolver(context.config, byEntry);
2789
+ const upstreamIds = relations.getUpstream(specId);
860
2790
  const diagnostics = [];
861
- for (const ref of refs) {
862
- if (ref.relationship !== "depends-on" && ref.relationship !== "implemented-by")
863
- continue;
864
- const upstream = context.allSpecs.find((s) => s.frontmatter.id === ref.id);
2791
+ for (const upstreamId of upstreamIds) {
2792
+ const upstream = context.allSpecs.find((s) => s.frontmatter.id === upstreamId);
865
2793
  if (!upstream)
866
2794
  continue;
867
- const upstreamUpdated = upstream.frontmatter.updated ?? upstream.frontmatter.created;
868
- const upstreamDate = new Date(upstreamUpdated);
869
- if (upstreamDate > specDate) {
2795
+ const upstreamUpdated = lastUpdated(upstream);
2796
+ if (!upstreamUpdated)
2797
+ continue;
2798
+ if (new Date(upstreamUpdated) > specDate) {
870
2799
  diagnostics.push({
871
2800
  ruleId: "freshness/staleness-check",
872
2801
  severity: "warn",
873
- message: `Potentially stale: upstream "${upstream.frontmatter.id}" was updated on ${upstreamUpdated}, but this spec was last updated on ${specUpdated}`,
2802
+ message: `Potentially stale: upstream "${upstreamId}" was updated on ${upstreamUpdated}, but this spec was last updated on ${specUpdated}`,
874
2803
  filePath: context.spec.filePath
875
2804
  });
876
2805
  }
@@ -1012,13 +2941,27 @@ var EDGE_CASE_KEYWORDS = [
1012
2941
  "reject",
1013
2942
  "unauthorized",
1014
2943
  "forbidden",
1015
- "404",
1016
- "500",
1017
2944
  "missing",
1018
2945
  "malformed",
1019
2946
  "overflow",
1020
- "duplicate"
2947
+ "duplicate",
2948
+ "graceful",
2949
+ "fall back",
2950
+ "fallback",
2951
+ "crash",
2952
+ "nonexistent",
2953
+ "corrupt",
2954
+ // Vocabulary that names a failure without using any of the words above.
2955
+ "conflict",
2956
+ "denied",
2957
+ "expired",
2958
+ "not found",
2959
+ "retry",
2960
+ "rate limit",
2961
+ "unavailable",
2962
+ "unprocessable"
1021
2963
  ];
2964
+ var ERROR_STATUS_CODE = /\b[45]\d{2}\b/;
1022
2965
  var edgeCaseCoverageRule = {
1023
2966
  id: "completeness/edge-case-coverage",
1024
2967
  description: "Flag user stories or test plans that don't mention error states or edge cases",
@@ -1028,7 +2971,7 @@ var edgeCaseCoverageRule = {
1028
2971
  if (type !== "user-story" && type !== "test-plan")
1029
2972
  return [];
1030
2973
  const content = context.spec.content.toLowerCase();
1031
- const hasEdgeCases = EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw));
2974
+ const hasEdgeCases = EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw)) || ERROR_STATUS_CODE.test(content);
1032
2975
  if (hasEdgeCases)
1033
2976
  return [];
1034
2977
  return [
@@ -1099,7 +3042,7 @@ var namingConventionsRule = {
1099
3042
  };
1100
3043
 
1101
3044
  // ../lint/dist/rules/threat-coverage.js
1102
- var STOPWORDS = /* @__PURE__ */ new Set(["the", "and", "for", "with", "from", "that", "this", "into", "via"]);
3045
+ var STOPWORDS2 = /* @__PURE__ */ new Set(["the", "and", "for", "with", "from", "that", "this", "into", "via"]);
1103
3046
  function extractThreats(content) {
1104
3047
  const parts = content.split(/^(?=## )/m);
1105
3048
  const threats = [];
@@ -1112,7 +3055,7 @@ function extractThreats(content) {
1112
3055
  return threats;
1113
3056
  }
1114
3057
  function extractKeyTerms(text) {
1115
- return text.toLowerCase().split(/\W+/).filter((w) => w.length > 3).filter((w) => !STOPWORDS.has(w));
3058
+ return text.toLowerCase().split(/\W+/).filter((w) => w.length > 3).filter((w) => !STOPWORDS2.has(w));
1116
3059
  }
1117
3060
  var threatCoverageRule = {
1118
3061
  id: "security/threat-coverage",
@@ -1159,20 +3102,78 @@ var ambiguityScoreAiRule = {
1159
3102
  {
1160
3103
  ruleId: "clarity/ambiguity-score-ai",
1161
3104
  severity: "info",
1162
- message: "AI ambiguity analysis available \u2014 run `sdx check --ai` for LLM-powered ambiguity detection",
3105
+ message: "AI ambiguity analysis available \u2014 run `specdx check --ai` for LLM-powered ambiguity detection",
1163
3106
  filePath: context.spec.filePath
1164
3107
  }
1165
3108
  ];
1166
3109
  }
1167
3110
  };
1168
3111
 
3112
+ // ../lint/dist/rules/no-placeholder-sections.js
3113
+ var PLACEHOLDER_BODIES = /^(todo|tbd|fixme|n\/a|na|none|xxx|\.{2,}|-|\*)$/i;
3114
+ function meaningfulContent(content) {
3115
+ 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();
3116
+ }
3117
+ var noPlaceholderSectionsRule = {
3118
+ id: "completeness/no-placeholder-sections",
3119
+ description: "Spec sections contain content, not scaffolding placeholders",
3120
+ severity: "warn",
3121
+ run(context) {
3122
+ return context.spec.parsedSections.filter((section) => section.heading !== "").filter((section) => {
3123
+ const body = meaningfulContent(section.content);
3124
+ return body === "" || PLACEHOLDER_BODIES.test(body);
3125
+ }).map((section) => ({
3126
+ ruleId: "completeness/no-placeholder-sections",
3127
+ severity: "warn",
3128
+ message: `Section "${section.heading}" is still a placeholder \u2014 write its content or remove the section`,
3129
+ filePath: context.spec.filePath,
3130
+ section: section.heading
3131
+ }));
3132
+ }
3133
+ };
3134
+
3135
+ // ../lint/dist/rules/id-matches-config-key.js
3136
+ import { basename as basename2 } from "path";
3137
+ var idMatchesConfigKeyRule = {
3138
+ id: "structure/id-matches-config-key",
3139
+ description: "A spec's frontmatter id should match the key it is registered under in the config",
3140
+ severity: "warn",
3141
+ run(context) {
3142
+ const { spec, config } = context;
3143
+ if (!config)
3144
+ return [];
3145
+ const id = spec.frontmatter.id;
3146
+ if (typeof id !== "string" || id.length === 0)
3147
+ return [];
3148
+ const specFile = basename2(spec.filePath);
3149
+ const candidates = Object.entries(config.specs).filter(([, entry]) => {
3150
+ const target = basename2(entry.path);
3151
+ return !target.includes("*") && target === specFile;
3152
+ });
3153
+ if (candidates.length !== 1)
3154
+ return [];
3155
+ const key = candidates[0][0];
3156
+ if (key === id)
3157
+ return [];
3158
+ return [
3159
+ {
3160
+ ruleId: "structure/id-matches-config-key",
3161
+ severity: "warn",
3162
+ 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.`,
3163
+ filePath: spec.filePath
3164
+ }
3165
+ ];
3166
+ }
3167
+ };
3168
+
1169
3169
  // ../lint/dist/rules/index.js
1170
3170
  var structureRules = [
1171
3171
  validFrontmatterRule,
1172
3172
  requiredSectionsRule,
1173
3173
  validReferencesRule,
1174
3174
  noCircularDepsRule,
1175
- singleProjectContextRule
3175
+ singleProjectContextRule,
3176
+ idMatchesConfigKeyRule
1176
3177
  ];
1177
3178
  var contentRules = [
1178
3179
  storyCoverageRule,
@@ -1182,7 +3183,8 @@ var contentRules = [
1182
3183
  edgeCaseCoverageRule,
1183
3184
  namingConventionsRule,
1184
3185
  threatCoverageRule,
1185
- ambiguityScoreAiRule
3186
+ ambiguityScoreAiRule,
3187
+ noPlaceholderSectionsRule
1186
3188
  ];
1187
3189
  var allBuiltinRules = [...structureRules, ...contentRules];
1188
3190
 
@@ -1194,7 +3196,7 @@ function getPreset(name) {
1194
3196
  case "recommended":
1195
3197
  return allBuiltinRules;
1196
3198
  case "strict":
1197
- return allBuiltinRules.map((rule) => ({ ...rule, severity: "error" }));
3199
+ return allBuiltinRules.map((rule) => rule.severity === "warn" ? { ...rule, severity: "error" } : rule);
1198
3200
  default:
1199
3201
  throw new Error(`Unknown preset: "${name}". Use "minimal", "recommended", or "strict", or resolve external presets via resolvePreset() from @specdx/core.`);
1200
3202
  }
@@ -1238,8 +3240,11 @@ function formatGithub(diagnostics) {
1238
3240
  }).join("\n");
1239
3241
  }
1240
3242
 
1241
- // src/commands/lint.ts
3243
+ // src/commands/core/lint.ts
1242
3244
  async function runLint(options) {
3245
+ if (!options.configDir) {
3246
+ throw new TypeError("runLint requires `configDir` \u2014 the directory holding spec.config.yaml.");
3247
+ }
1243
3248
  const config = await loadConfig(void 0, options.configDir);
1244
3249
  const preset = options.preset ?? config.lint?.extends ?? "recommended";
1245
3250
  const rules = getPreset(preset);
@@ -1247,7 +3252,6 @@ async function runLint(options) {
1247
3252
  for (const [, entry] of Object.entries(config.specs)) {
1248
3253
  const files = await resolveGlob(entry.path, options.configDir);
1249
3254
  for (const file of files) {
1250
- if (options.specPath && !file.includes(options.specPath)) continue;
1251
3255
  specs.push(await parseSpec(file));
1252
3256
  }
1253
3257
  }
@@ -1260,6 +3264,12 @@ async function runLint(options) {
1260
3264
  }
1261
3265
  const engine = createLintEngine({ rules, config, graph });
1262
3266
  const results = engine.lint(specs);
3267
+ if (options.specPath) {
3268
+ const specPath = options.specPath;
3269
+ results.diagnostics = results.diagnostics.filter((d) => d.filePath.includes(specPath));
3270
+ results.hasErrors = results.diagnostics.some((d) => d.severity === "error");
3271
+ results.hasWarnings = results.diagnostics.some((d) => d.severity === "warn");
3272
+ }
1263
3273
  if (graphError) {
1264
3274
  results.diagnostics.push({
1265
3275
  ruleId: "structure/no-circular-deps",
@@ -1269,7 +3279,7 @@ async function runLint(options) {
1269
3279
  });
1270
3280
  results.hasErrors = true;
1271
3281
  }
1272
- return results;
3282
+ return { ...results, specCount: specs.length, assessed: specs.length > 0 };
1273
3283
  }
1274
3284
  var lint_default = defineCommand2({
1275
3285
  meta: { name: "lint", description: "Lint all specs in the suite" },
@@ -1291,6 +3301,12 @@ var lint_default = defineCommand2({
1291
3301
  preset: args.preset
1292
3302
  });
1293
3303
  const formatter = args.format === "json" ? formatJson : args.format === "github" ? formatGithub : formatPretty;
3304
+ if (!results.assessed) {
3305
+ console.error(
3306
+ "\n \u26A0 No specs found \u2014 nothing was linted. Check the spec paths in spec.config.yaml.\n"
3307
+ );
3308
+ process.exit(3);
3309
+ }
1294
3310
  console.log(formatter(results.diagnostics));
1295
3311
  if (results.hasErrors) process.exit(1);
1296
3312
  } catch (err) {
@@ -1302,11 +3318,11 @@ var lint_default = defineCommand2({
1302
3318
  }
1303
3319
  });
1304
3320
 
1305
- // src/commands/pack.ts
3321
+ // src/commands/core/pack.ts
1306
3322
  import { defineCommand as defineCommand3 } from "citty";
1307
3323
 
1308
3324
  // ../pack/dist/resolver.js
1309
- var STOPWORDS2 = /* @__PURE__ */ new Set([
3325
+ var STOPWORDS3 = /* @__PURE__ */ new Set([
1310
3326
  "a",
1311
3327
  "an",
1312
3328
  "and",
@@ -1383,12 +3399,13 @@ var STOPWORDS2 = /* @__PURE__ */ new Set([
1383
3399
  "your"
1384
3400
  ]);
1385
3401
  function tokenize(task) {
1386
- return task.split(/[\s\-_/.,;:!?()[\]{}'"]+/).map((t) => t.toLowerCase()).filter((t) => t.length > 1 && !STOPWORDS2.has(t));
3402
+ return task.split(/[\s\-_/.,;:!?()[\]{}'"]+/).map((t) => t.toLowerCase()).filter((t) => t.length > 1 && !STOPWORDS3.has(t));
1387
3403
  }
1388
3404
  var WEIGHT_TAGS = 3;
1389
3405
  var WEIGHT_TITLE = 3;
1390
3406
  var WEIGHT_SECTIONS = 2;
1391
3407
  var WEIGHT_BODY = 1;
3408
+ var ID_MATCH_MIN_LENGTH = 3;
1392
3409
  var GRAPH_BOOST_FACTOR = 0.5;
1393
3410
  var SCORE_THRESHOLD = 0.1;
1394
3411
  function scoreSpecs(specs, task, graph) {
@@ -1408,9 +3425,15 @@ function scoreSpecs(specs, task, graph) {
1408
3425
  }
1409
3426
  const rawScores = /* @__PURE__ */ new Map();
1410
3427
  const matchedMap = /* @__PURE__ */ new Map();
3428
+ const idMatchedSet = /* @__PURE__ */ new Set();
3429
+ const taskLower = (task ?? "").toLowerCase();
1411
3430
  for (const [specId, spec] of specs) {
1412
3431
  let weightedHits = 0;
1413
3432
  const matched = /* @__PURE__ */ new Set();
3433
+ const idLower = specId.toLowerCase();
3434
+ if (idLower.length >= ID_MATCH_MIN_LENGTH && taskLower.includes(idLower)) {
3435
+ idMatchedSet.add(specId);
3436
+ }
1414
3437
  for (const keyword of keywords) {
1415
3438
  let hit = false;
1416
3439
  const tags = spec.frontmatter.tags ?? [];
@@ -1482,7 +3505,8 @@ function scoreSpecs(specs, task, graph) {
1482
3505
  const results = [];
1483
3506
  for (const [specId] of specs) {
1484
3507
  const combined = finalRawScores.get(specId) ?? 0;
1485
- const normalized = maxScore > 0 ? combined / maxScore : 0;
3508
+ const idMatched = idMatchedSet.has(specId);
3509
+ const normalized = idMatched ? 1 : maxScore > 0 ? combined / maxScore : 0;
1486
3510
  if (normalized < SCORE_THRESHOLD)
1487
3511
  continue;
1488
3512
  results.push({
@@ -1490,10 +3514,11 @@ function scoreSpecs(specs, task, graph) {
1490
3514
  score: normalized,
1491
3515
  rawScore: rawScores.get(specId) ?? 0,
1492
3516
  matchedKeywords: [...matchedMap.get(specId) ?? []],
1493
- graphBoosted: boostedSet.has(specId)
3517
+ graphBoosted: boostedSet.has(specId),
3518
+ idMatched
1494
3519
  });
1495
3520
  }
1496
- results.sort((a, b) => b.score - a.score);
3521
+ results.sort((a, b) => b.score - a.score || Number(b.idMatched ?? false) - Number(a.idMatched ?? false));
1497
3522
  return results;
1498
3523
  }
1499
3524
  function scoreSpecsByIds(specs, specIds, graph) {
@@ -1586,17 +3611,86 @@ function compressSpec(specId, type, title, status, updatedDate, parsedSections,
1586
3611
  }
1587
3612
 
1588
3613
  // ../pack/dist/allocator.js
3614
+ var HIGH_RELEVANCE = 0.75;
3615
+ var MIN_TRIM_BUDGET = 150;
3616
+ function omissionMarker(sections) {
3617
+ const names = sections.map((s) => s.heading || "(untitled)");
3618
+ const noun = names.length === 1 ? "section" : "sections";
3619
+ return `[${names.length} ${noun} omitted to fit token budget: ${names.join(", ")}]`;
3620
+ }
3621
+ function trimToBudget(compressed, budget) {
3622
+ const sections = compressed.sections;
3623
+ let reserve = 0;
3624
+ for (; ; ) {
3625
+ const effective = budget - reserve;
3626
+ const keep = new Array(sections.length).fill(false);
3627
+ let used = 0;
3628
+ let keptReal = false;
3629
+ for (let i = 0; i < sections.length; i++) {
3630
+ if (used + sections[i].tokens <= effective) {
3631
+ keep[i] = true;
3632
+ used += sections[i].tokens;
3633
+ keptReal = true;
3634
+ }
3635
+ }
3636
+ if (!keptReal)
3637
+ return null;
3638
+ const runs = [];
3639
+ for (let i = 0; i < sections.length; i++) {
3640
+ if (keep[i])
3641
+ continue;
3642
+ const start = i;
3643
+ const run = [];
3644
+ while (i < sections.length && !keep[i]) {
3645
+ run.push(sections[i]);
3646
+ i++;
3647
+ }
3648
+ i--;
3649
+ const marker = omissionMarker(run);
3650
+ runs.push({ start, sections: run, marker, markerTokens: countTokens(marker) });
3651
+ }
3652
+ const markerTokens = runs.reduce((sum, r) => sum + r.markerTokens, 0);
3653
+ if (markerTokens > reserve) {
3654
+ reserve = markerTokens;
3655
+ continue;
3656
+ }
3657
+ const out = [];
3658
+ for (let i = 0; i < sections.length; i++) {
3659
+ const run = runs.find((r) => r.start === i);
3660
+ if (run) {
3661
+ out.push({
3662
+ heading: "",
3663
+ content: run.marker,
3664
+ tokens: run.markerTokens,
3665
+ compressed: true,
3666
+ originalTokens: run.sections.reduce((sum, s) => sum + s.tokens, 0),
3667
+ omittedSections: run.sections.length
3668
+ });
3669
+ i += run.sections.length - 1;
3670
+ continue;
3671
+ }
3672
+ out.push(sections[i]);
3673
+ }
3674
+ return { spec: { ...compressed, sections: out }, tokens: used + markerTokens };
3675
+ }
3676
+ }
1589
3677
  function allocate(specs, scores, options) {
1590
3678
  const specMap = /* @__PURE__ */ new Map();
1591
3679
  for (const spec of specs) {
1592
3680
  specMap.set(spec.frontmatter.id, spec);
1593
3681
  }
3682
+ function tokensOf(compressed) {
3683
+ if (compressed.collapsed)
3684
+ return countTokens(compressed.collapsedSummary ?? "");
3685
+ return compressed.sections.reduce((sum, section) => sum + section.tokens, 0);
3686
+ }
1594
3687
  const items = [];
1595
3688
  for (const score of scores) {
1596
3689
  const spec = specMap.get(score.specId);
1597
3690
  if (!spec)
1598
3691
  continue;
1599
3692
  let compressed;
3693
+ let stale;
1600
3694
  if (options.full) {
1601
3695
  compressed = {
1602
3696
  specId: score.specId,
@@ -1612,20 +3706,34 @@ function allocate(specs, scores, options) {
1612
3706
  collapsed: false
1613
3707
  };
1614
3708
  } else {
1615
- compressed = compressSpec(score.specId, String(spec.frontmatter.type), String(spec.frontmatter.title), spec.frontmatter.status, spec.frontmatter.updated, spec.parsedSections, options.compression);
1616
- }
1617
- let tokens;
1618
- if (compressed.collapsed) {
1619
- tokens = countTokens(compressed.collapsedSummary ?? "");
1620
- } else {
1621
- tokens = 0;
1622
- for (const section of compressed.sections) {
1623
- tokens += section.tokens;
3709
+ const compress = (compression) => compressSpec(score.specId, String(spec.frontmatter.type), String(spec.frontmatter.title), spec.frontmatter.status, spec.frontmatter.updated, spec.parsedSections, compression);
3710
+ compressed = compress({ ...options.compression, stableDays: 0 });
3711
+ if (options.compression.stableDays > 0) {
3712
+ const collapsed = compress(options.compression);
3713
+ const collapsedTokens = tokensOf(collapsed);
3714
+ if (collapsedTokens < tokensOf(compressed)) {
3715
+ stale = { spec: collapsed, tokens: collapsedTokens };
3716
+ }
1624
3717
  }
1625
3718
  }
1626
- items.push({ compressed, relevance: score.score, tokens });
3719
+ items.push({
3720
+ compressed,
3721
+ relevance: score.score,
3722
+ tokens: tokensOf(compressed),
3723
+ idMatched: score.idMatched ?? false,
3724
+ stale
3725
+ });
3726
+ }
3727
+ items.sort((a, b) => b.relevance - a.relevance || Number(b.idMatched) - Number(a.idMatched));
3728
+ let projected = items.reduce((sum, item) => sum + item.tokens, 0);
3729
+ for (let i = items.length - 1; i >= 0 && projected > options.budget; i--) {
3730
+ const item = items[i];
3731
+ if (!item.stale)
3732
+ continue;
3733
+ projected -= item.tokens - item.stale.tokens;
3734
+ item.compressed = item.stale.spec;
3735
+ item.tokens = item.stale.tokens;
1627
3736
  }
1628
- items.sort((a, b) => b.relevance - a.relevance);
1629
3737
  const totalTokens = items.reduce((sum, item) => sum + item.tokens, 0);
1630
3738
  const withinBudget = totalTokens <= options.budget;
1631
3739
  const included = [];
@@ -1641,17 +3749,28 @@ function allocate(specs, scores, options) {
1641
3749
  if (usedTokens + item.tokens <= options.budget) {
1642
3750
  included.push(item);
1643
3751
  usedTokens += item.tokens;
1644
- } else {
1645
- excluded.push(item);
3752
+ continue;
3753
+ }
3754
+ const remaining = options.budget - usedTokens;
3755
+ if ((item.idMatched || item.relevance >= HIGH_RELEVANCE) && remaining >= MIN_TRIM_BUDGET && !item.compressed.collapsed) {
3756
+ const trimmed = trimToBudget(item.compressed, remaining);
3757
+ if (trimmed) {
3758
+ included.push({ ...item, compressed: trimmed.spec, tokens: trimmed.tokens });
3759
+ usedTokens += trimmed.tokens;
3760
+ continue;
3761
+ }
1646
3762
  }
3763
+ excluded.push(item);
1647
3764
  }
1648
3765
  }
1649
3766
  let sectionsCompressed = 0;
3767
+ let sectionsOmitted = 0;
1650
3768
  for (const item of included) {
1651
3769
  for (const section of item.compressed.sections) {
1652
3770
  if (section.compressed) {
1653
3771
  sectionsCompressed++;
1654
3772
  }
3773
+ sectionsOmitted += section.omittedSections ?? 0;
1655
3774
  }
1656
3775
  }
1657
3776
  const allocations = [];
@@ -1681,6 +3800,7 @@ function allocate(specs, scores, options) {
1681
3800
  specsIncluded: included.length,
1682
3801
  specsExcluded: excluded.length,
1683
3802
  sectionsCompressed,
3803
+ sectionsOmitted,
1684
3804
  allocations
1685
3805
  };
1686
3806
  return {
@@ -1695,7 +3815,7 @@ function escapeXml(text) {
1695
3815
  }
1696
3816
  function formatXml(specs, stats) {
1697
3817
  const lines = [];
1698
- lines.push(`<context budget="${stats.budget}" used="${stats.used}" specs="${stats.specsIncluded}" compressed="${stats.sectionsCompressed}">`);
3818
+ lines.push(`<context budget="${stats.budget}" used="${stats.used}" specs="${stats.specsIncluded}" compressed="${stats.sectionsCompressed}" omitted="${stats.sectionsOmitted}">`);
1699
3819
  for (const spec of specs) {
1700
3820
  const alloc = stats.allocations.find((a) => a.specId === spec.specId);
1701
3821
  const relevance = alloc?.relevance ?? 0;
@@ -1754,6 +3874,7 @@ function formatJson2(specs, stats) {
1754
3874
  const output = {
1755
3875
  budget: stats.budget,
1756
3876
  used: stats.used,
3877
+ sectionsOmitted: stats.sectionsOmitted,
1757
3878
  specs: specs.map((spec) => {
1758
3879
  const alloc = stats.allocations.find((a) => a.specId === spec.specId);
1759
3880
  const relevance = alloc?.relevance ?? 0;
@@ -1879,7 +4000,7 @@ function pack(specs, options, packConfig, graph) {
1879
4000
  return { output, stats };
1880
4001
  }
1881
4002
 
1882
- // src/commands/pack.ts
4003
+ // src/commands/core/pack.ts
1883
4004
  import { writeFile as writeFile2 } from "fs/promises";
1884
4005
  import { execSync } from "child_process";
1885
4006
  function copyToClipboard(text) {
@@ -1896,7 +4017,20 @@ function copyToClipboard(text) {
1896
4017
  }
1897
4018
  execSync(cmd, { input: text, stdio: ["pipe", "ignore", "ignore"] });
1898
4019
  }
4020
+ function emptyPackReason(stats, specsResolved) {
4021
+ if (stats.specsIncluded > 0) return void 0;
4022
+ if (specsResolved === 0) {
4023
+ return "no specs resolved from spec.config.yaml \u2014 check the paths in your config";
4024
+ }
4025
+ if (stats.specsExcluded === 0) {
4026
+ 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`;
4027
+ }
4028
+ return `all ${stats.specsExcluded} candidate spec(s) were excluded \u2014 widen --specs or raise --budget`;
4029
+ }
1899
4030
  async function runPack(options) {
4031
+ if (!options.configDir) {
4032
+ throw new TypeError("runPack requires `configDir` \u2014 the directory holding spec.config.yaml.");
4033
+ }
1900
4034
  const config = await loadConfig(void 0, options.configDir);
1901
4035
  const allSpecs = [];
1902
4036
  for (const [, entry] of Object.entries(config.specs)) {
@@ -1923,7 +4057,7 @@ async function runPack(options) {
1923
4057
  config.pack,
1924
4058
  graph
1925
4059
  );
1926
- return result;
4060
+ return { ...result, specsResolved: allSpecs.length };
1927
4061
  }
1928
4062
  var pack_default = defineCommand3({
1929
4063
  meta: { name: "pack", description: "Pack specs into AI-ready context" },
@@ -1994,11 +4128,16 @@ var pack_default = defineCommand3({
1994
4128
  }
1995
4129
  console.log(`
1996
4130
  Budget: ${stats.used} / ${stats.budget} tokens`);
1997
- console.log(
1998
- ` Included: ${stats.specsIncluded} / ${stats.specsIncluded + stats.specsExcluded} specs`
1999
- );
2000
- console.log(` Sections compressed: ${stats.sectionsCompressed}
4131
+ console.log(` Included: ${stats.specsIncluded} / ${result.specsResolved} specs`);
4132
+ console.log(` Sections compressed: ${stats.sectionsCompressed}`);
4133
+ console.log(` Sections omitted: ${stats.sectionsOmitted}
2001
4134
  `);
4135
+ const dryReason = emptyPackReason(stats, result.specsResolved);
4136
+ if (dryReason) {
4137
+ console.log(` \u26A0 Nothing would be packed: ${dryReason}
4138
+ `);
4139
+ process.exit(3);
4140
+ }
2002
4141
  return;
2003
4142
  }
2004
4143
  if (args.out) {
@@ -2014,9 +4153,17 @@ var pack_default = defineCommand3({
2014
4153
  }
2015
4154
  const total = stats.specsIncluded + stats.specsExcluded;
2016
4155
  process.stderr.write(
2017
- `Packed ${stats.specsIncluded}/${total} specs \u2022 ${stats.used} / ${stats.budget} tokens \u2022 ${stats.sectionsCompressed} sections compressed
4156
+ `Packed ${stats.specsIncluded}/${total} specs \u2022 ${stats.used} / ${stats.budget} tokens \u2022 ${stats.sectionsCompressed} sections compressed \u2022 ${stats.sectionsOmitted} sections omitted
2018
4157
  `
2019
4158
  );
4159
+ const emptyReason = emptyPackReason(stats, result.specsResolved);
4160
+ if (emptyReason) {
4161
+ process.stderr.write(`
4162
+ \u26A0 No context packed: ${emptyReason}
4163
+
4164
+ `);
4165
+ process.exit(3);
4166
+ }
2020
4167
  } catch (err) {
2021
4168
  console.error(`
2022
4169
  \u2717 ${err.message}
@@ -2026,7 +4173,7 @@ var pack_default = defineCommand3({
2026
4173
  }
2027
4174
  });
2028
4175
 
2029
- // src/commands/diff.ts
4176
+ // src/commands/core/diff.ts
2030
4177
  import { defineCommand as defineCommand4 } from "citty";
2031
4178
  import { join as join5 } from "path";
2032
4179
 
@@ -2456,8 +4603,8 @@ function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep
2456
4603
  } else if (endKeep) {
2457
4604
  var endKeepWsPrefix = endKeep.value.match(/^\s*/)[0];
2458
4605
  var deletionWsSuffix = deletion.value.match(/\s*$/)[0];
2459
- var overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
2460
- deletion.value = removeSuffix(deletion.value, overlap);
4606
+ var overlap2 = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
4607
+ deletion.value = removeSuffix(deletion.value, overlap2);
2461
4608
  } else if (startKeep) {
2462
4609
  var startKeepWsSuffix = startKeep.value.match(/\s*$/)[0];
2463
4610
  var deletionWsPrefix = deletion.value.match(/^\s*/)[0];
@@ -2917,10 +5064,10 @@ var STRUCTURAL_SECTIONS = /* @__PURE__ */ new Set([
2917
5064
  "API Design",
2918
5065
  "Problem Statement"
2919
5066
  ]);
2920
- function bfsDistances(startId, graph) {
5067
+ function bfsDistances(startId, relations) {
2921
5068
  const distances = /* @__PURE__ */ new Map();
2922
5069
  const queue = [];
2923
- for (const edge of graph.edges) {
5070
+ for (const edge of relations.edges) {
2924
5071
  if (edge.from === startId) {
2925
5072
  if (!distances.has(edge.to)) {
2926
5073
  distances.set(edge.to, 1);
@@ -2931,7 +5078,7 @@ function bfsDistances(startId, graph) {
2931
5078
  while (queue.length > 0) {
2932
5079
  const item = queue.shift();
2933
5080
  const currentDist = item.distance;
2934
- for (const edge of graph.edges) {
5081
+ for (const edge of relations.edges) {
2935
5082
  if (edge.from === item.id && !distances.has(edge.to)) {
2936
5083
  distances.set(edge.to, currentDist + 1);
2937
5084
  queue.push({ id: edge.to, distance: currentDist + 1 });
@@ -2948,8 +5095,8 @@ function daysBetween(dateStr) {
2948
5095
  function clamp(min, max, value) {
2949
5096
  return Math.min(max, Math.max(min, value));
2950
5097
  }
2951
- function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14) {
2952
- const distanceMap = bfsDistances(changedSpecId, graph);
5098
+ function analyzeImpact(changedSpecId, diff2, relations, allSpecs, thresholdDays = 14) {
5099
+ const distanceMap = bfsDistances(changedSpecId, relations);
2953
5100
  if (distanceMap.size === 0) {
2954
5101
  return {
2955
5102
  changedSpec: changedSpecId,
@@ -2968,11 +5115,11 @@ function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14
2968
5115
  const downstream = [];
2969
5116
  for (const [specId, distance] of distanceMap) {
2970
5117
  const spec = specById.get(specId);
2971
- const lastUpdated = spec?.frontmatter.updated ?? spec?.frontmatter.created ?? null;
5118
+ const lastUpdated2 = spec?.frontmatter.updated ?? spec?.frontmatter.created ?? null;
2972
5119
  const filePath = spec?.filePath ?? `specs/${specId}.md`;
2973
5120
  let staleness;
2974
- if (lastUpdated) {
2975
- const daysSinceUpdate = daysBetween(lastUpdated);
5121
+ if (lastUpdated2) {
5122
+ const daysSinceUpdate = daysBetween(lastUpdated2);
2976
5123
  staleness = clamp(0, 1, daysSinceUpdate / thresholdDays * 0.5 + structuralSectionsChanged / totalSections * 0.3 + 1 / distance * 0.2);
2977
5124
  } else {
2978
5125
  staleness = clamp(0, 1, structuralSectionsChanged / totalSections * 0.3 + 1 / distance * 0.2);
@@ -2982,8 +5129,8 @@ function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14
2982
5129
  if (structuralSectionsChanged > 0) {
2983
5130
  parts.push(`${structuralSectionsChanged} structural section(s) changed`);
2984
5131
  }
2985
- if (lastUpdated) {
2986
- const days = Math.round(daysBetween(lastUpdated));
5132
+ if (lastUpdated2) {
5133
+ const days = Math.round(daysBetween(lastUpdated2));
2987
5134
  parts.push(`last updated ${days} day(s) ago`);
2988
5135
  }
2989
5136
  const reason = parts.join("; ");
@@ -2991,7 +5138,7 @@ function analyzeImpact(changedSpecId, diff2, graph, allSpecs, thresholdDays = 14
2991
5138
  specId,
2992
5139
  filePath,
2993
5140
  distance,
2994
- lastUpdated,
5141
+ lastUpdated: lastUpdated2,
2995
5142
  staleness,
2996
5143
  reason
2997
5144
  });
@@ -3031,15 +5178,21 @@ function checkCrossReferences(allSpecs, removedIds) {
3031
5178
  }
3032
5179
 
3033
5180
  // ../diff/dist/git.js
5181
+ var import_picomatch = __toESM(require_picomatch2(), 1);
3034
5182
  import { execSync as execSync2 } from "child_process";
3035
- import { realpathSync } from "fs";
3036
- import { dirname as dirname2, relative, resolve as resolve2 } from "path";
5183
+ import { readFileSync, realpathSync } from "fs";
5184
+ import { dirname as dirname2, relative, resolve as resolve3, sep } from "path";
3037
5185
  function getRepoRoot(cwd) {
3038
- const root = execSync2("git rev-parse --show-toplevel", {
3039
- cwd,
3040
- encoding: "utf-8",
3041
- stdio: "pipe"
3042
- }).trim();
5186
+ let root;
5187
+ try {
5188
+ root = execSync2("git rev-parse --show-toplevel", {
5189
+ cwd,
5190
+ encoding: "utf-8",
5191
+ stdio: "pipe"
5192
+ }).trim();
5193
+ } catch {
5194
+ 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.");
5195
+ }
3043
5196
  return realpathSync(root);
3044
5197
  }
3045
5198
  function validateRef(ref, cwd) {
@@ -3049,35 +5202,157 @@ function validateRef(ref, cwd) {
3049
5202
  throw new DiffError(`Invalid git ref: "${ref}"`);
3050
5203
  }
3051
5204
  }
3052
- function gitShow(ref, filePath, projectRoot, repoRoot) {
3053
- const relPath = relative(repoRoot, resolve2(projectRoot, filePath));
5205
+ function gitShow(ref, filePath, projectRoot, repoRoot) {
5206
+ const relPath = relative(repoRoot, resolve3(projectRoot, filePath));
5207
+ try {
5208
+ return execSync2(`git show ${ref}:${relPath}`, {
5209
+ cwd: repoRoot,
5210
+ encoding: "utf-8",
5211
+ stdio: "pipe"
5212
+ });
5213
+ } catch {
5214
+ throw new DiffError(`Cannot read "${filePath}" at ref "${ref}"`);
5215
+ }
5216
+ }
5217
+ function toPosix(p) {
5218
+ return sep === "/" ? p : p.split(sep).join("/");
5219
+ }
5220
+ function buildEntryMatchers(specPathsByKey, projectRoot, repoRoot) {
5221
+ return [...specPathsByKey].map(([key, specPath]) => ({
5222
+ key,
5223
+ isMatch: (0, import_picomatch.default)(toPosix(relative(repoRoot, resolve3(projectRoot, specPath))))
5224
+ }));
5225
+ }
5226
+ function getChangedSpecFiles(baseRef, headRef, matchers, projectRoot, repoRoot) {
5227
+ let diffOutput;
5228
+ try {
5229
+ diffOutput = execSync2(`git diff --name-status ${baseRef} ${headRef}`, {
5230
+ cwd: repoRoot,
5231
+ encoding: "utf-8",
5232
+ stdio: "pipe"
5233
+ });
5234
+ } catch {
5235
+ throw new DiffError(`Failed to run git diff between "${baseRef}" and "${headRef}"`);
5236
+ }
5237
+ const result = { modified: [], added: [], deleted: [] };
5238
+ for (const line of diffOutput.trim().split("\n")) {
5239
+ if (!line)
5240
+ continue;
5241
+ const parts = line.split(" ");
5242
+ const status = parts[0];
5243
+ const filePath = parts[1];
5244
+ if (!status || !filePath)
5245
+ continue;
5246
+ const entry = matchers.find((m) => m.isMatch(filePath));
5247
+ if (!entry)
5248
+ continue;
5249
+ const changed = {
5250
+ path: relative(projectRoot, resolve3(repoRoot, filePath)),
5251
+ entryKey: entry.key
5252
+ };
5253
+ if (status === "M") {
5254
+ result.modified.push(changed);
5255
+ } else if (status === "A") {
5256
+ result.added.push(changed);
5257
+ } else if (status === "D") {
5258
+ result.deleted.push(changed);
5259
+ }
5260
+ }
5261
+ return result;
5262
+ }
5263
+ function listSpecFilesAtRef(ref, matchers, projectRoot, repoRoot) {
5264
+ const byEntry = new Map(matchers.map((m) => [m.key, []]));
5265
+ let listing;
5266
+ try {
5267
+ listing = execSync2(`git ls-tree -r --name-only ${ref}`, {
5268
+ cwd: repoRoot,
5269
+ encoding: "utf-8",
5270
+ stdio: "pipe"
5271
+ });
5272
+ } catch {
5273
+ throw new DiffError(`Failed to list files at ref "${ref}"`);
5274
+ }
5275
+ for (const filePath of listing.trim().split("\n")) {
5276
+ if (!filePath)
5277
+ continue;
5278
+ const entry = matchers.find((m) => m.isMatch(filePath));
5279
+ if (!entry)
5280
+ continue;
5281
+ byEntry.get(entry.key)?.push(relative(projectRoot, resolve3(repoRoot, filePath)));
5282
+ }
5283
+ return byEntry;
5284
+ }
5285
+ function listSpecFilesInWorktree(matchers, projectRoot, repoRoot) {
5286
+ const byEntry = new Map(matchers.map((m) => [m.key, []]));
5287
+ let listing;
3054
5288
  try {
3055
- return execSync2(`git show ${ref}:${relPath}`, {
5289
+ listing = execSync2("git ls-files --cached --others --exclude-standard", {
3056
5290
  cwd: repoRoot,
3057
5291
  encoding: "utf-8",
3058
5292
  stdio: "pipe"
3059
5293
  });
3060
5294
  } catch {
3061
- throw new DiffError(`Cannot read "${filePath}" at ref "${ref}"`);
5295
+ throw new DiffError("Failed to list files in the working tree");
3062
5296
  }
3063
- }
3064
- function getChangedSpecFiles(baseRef, headRef, specPaths, projectRoot, repoRoot) {
3065
- const repoRelToProjectRel = /* @__PURE__ */ new Map();
3066
- for (const p of specPaths) {
3067
- const repoRel = relative(repoRoot, resolve2(projectRoot, p));
3068
- repoRelToProjectRel.set(repoRel, p);
5297
+ for (const filePath of listing.trim().split("\n")) {
5298
+ if (!filePath)
5299
+ continue;
5300
+ const entry = matchers.find((m) => m.isMatch(filePath));
5301
+ if (!entry)
5302
+ continue;
5303
+ byEntry.get(entry.key)?.push(relative(projectRoot, resolve3(repoRoot, filePath)));
3069
5304
  }
5305
+ return byEntry;
5306
+ }
5307
+ function refSide(ref, matchers, projectRoot, repoRoot) {
5308
+ return {
5309
+ read: (path) => gitShow(ref, path, projectRoot, repoRoot),
5310
+ list: () => listSpecFilesAtRef(ref, matchers, projectRoot, repoRoot)
5311
+ };
5312
+ }
5313
+ function worktreeSide(matchers, projectRoot, repoRoot) {
5314
+ return {
5315
+ read: (path) => {
5316
+ try {
5317
+ return readFileSync(resolve3(projectRoot, path), "utf-8");
5318
+ } catch {
5319
+ throw new DiffError(`Cannot read "${path}" in the working tree`);
5320
+ }
5321
+ },
5322
+ list: () => listSpecFilesInWorktree(matchers, projectRoot, repoRoot)
5323
+ };
5324
+ }
5325
+ function getChangedSpecFilesInWorktree(baseRef, matchers, projectRoot, repoRoot) {
3070
5326
  let diffOutput;
3071
5327
  try {
3072
- diffOutput = execSync2(`git diff --name-status ${baseRef} ${headRef}`, {
5328
+ diffOutput = execSync2(`git diff --name-status ${baseRef}`, {
3073
5329
  cwd: repoRoot,
3074
5330
  encoding: "utf-8",
3075
5331
  stdio: "pipe"
3076
5332
  });
3077
5333
  } catch {
3078
- throw new DiffError(`Failed to run git diff between "${baseRef}" and "${headRef}"`);
5334
+ throw new DiffError(`Failed to diff "${baseRef}" against the working tree`);
3079
5335
  }
3080
5336
  const result = { modified: [], added: [], deleted: [] };
5337
+ const seen = /* @__PURE__ */ new Set();
5338
+ const record = (status, filePath) => {
5339
+ const entry = matchers.find((m) => m.isMatch(filePath));
5340
+ if (!entry)
5341
+ return;
5342
+ if (seen.has(filePath))
5343
+ return;
5344
+ seen.add(filePath);
5345
+ const changed = {
5346
+ path: relative(projectRoot, resolve3(repoRoot, filePath)),
5347
+ entryKey: entry.key
5348
+ };
5349
+ if (status === "M")
5350
+ result.modified.push(changed);
5351
+ else if (status === "A")
5352
+ result.added.push(changed);
5353
+ else if (status === "D")
5354
+ result.deleted.push(changed);
5355
+ };
3081
5356
  for (const line of diffOutput.trim().split("\n")) {
3082
5357
  if (!line)
3083
5358
  continue;
@@ -3086,57 +5361,105 @@ function getChangedSpecFiles(baseRef, headRef, specPaths, projectRoot, repoRoot)
3086
5361
  const filePath = parts[1];
3087
5362
  if (!status || !filePath)
3088
5363
  continue;
3089
- const projectRelPath = repoRelToProjectRel.get(filePath);
3090
- if (projectRelPath === void 0)
5364
+ record(status, filePath);
5365
+ }
5366
+ let untracked;
5367
+ try {
5368
+ untracked = execSync2("git ls-files --others --exclude-standard", {
5369
+ cwd: repoRoot,
5370
+ encoding: "utf-8",
5371
+ stdio: "pipe"
5372
+ });
5373
+ } catch {
5374
+ throw new DiffError("Failed to list untracked files");
5375
+ }
5376
+ for (const filePath of untracked.trim().split("\n")) {
5377
+ if (!filePath)
5378
+ continue;
5379
+ record("A", filePath);
5380
+ }
5381
+ return result;
5382
+ }
5383
+ function listUncommittedSpecFiles(matchers, projectRoot, repoRoot) {
5384
+ let statusOutput;
5385
+ try {
5386
+ statusOutput = execSync2("git status --porcelain", {
5387
+ cwd: repoRoot,
5388
+ encoding: "utf-8",
5389
+ stdio: "pipe"
5390
+ });
5391
+ } catch {
5392
+ return [];
5393
+ }
5394
+ const files = [];
5395
+ for (const line of statusOutput.split("\n")) {
5396
+ if (!line.trim())
5397
+ continue;
5398
+ const rawPath = line.slice(3);
5399
+ const renamed = rawPath.includes(" -> ") ? rawPath.split(" -> ")[1] : void 0;
5400
+ const filePath = (renamed ?? rawPath).replace(/^"|"$/g, "");
5401
+ if (!matchers.some((m) => m.isMatch(filePath)))
3091
5402
  continue;
3092
- if (status === "M") {
3093
- result.modified.push(projectRelPath);
3094
- } else if (status === "A") {
3095
- result.added.push(projectRelPath);
3096
- } else if (status === "D") {
3097
- result.deleted.push(projectRelPath);
5403
+ files.push(relative(projectRoot, resolve3(repoRoot, filePath)));
5404
+ }
5405
+ return files;
5406
+ }
5407
+ async function specIdsFrom(files, read) {
5408
+ const ids = [];
5409
+ for (const file of files) {
5410
+ try {
5411
+ const parsed = await parseSpecFromString(read(file.path), file.path);
5412
+ ids.push(parsed.frontmatter.id);
5413
+ } catch {
5414
+ ids.push(file.entryKey);
3098
5415
  }
3099
5416
  }
3100
- return result;
5417
+ return ids;
3101
5418
  }
3102
- async function diffBetweenRefs(configPath, baseRef, headRef) {
3103
- const projectRoot = realpathSync(dirname2(resolve2(configPath)));
5419
+ async function diffBetweenRefs(configPath, baseRef, headRef, options = {}) {
5420
+ const projectRoot = realpathSync(dirname2(resolve3(configPath)));
3104
5421
  const repoRoot = getRepoRoot(projectRoot);
3105
5422
  validateRef(baseRef, projectRoot);
3106
- validateRef(headRef, projectRoot);
5423
+ if (!options.working)
5424
+ validateRef(headRef, projectRoot);
3107
5425
  const config = await loadConfig(configPath);
3108
- const specPaths = [];
3109
- const specIdByPath = /* @__PURE__ */ new Map();
3110
- for (const [specId, entry] of Object.entries(config.specs)) {
3111
- specPaths.push(entry.path);
3112
- specIdByPath.set(entry.path, specId);
3113
- }
3114
- const changed = getChangedSpecFiles(baseRef, headRef, specPaths, projectRoot, repoRoot);
5426
+ const specPathsByKey = /* @__PURE__ */ new Map();
5427
+ for (const [key, entry] of Object.entries(config.specs)) {
5428
+ specPathsByKey.set(key, entry.path);
5429
+ }
5430
+ const matchers = buildEntryMatchers(specPathsByKey, projectRoot, repoRoot);
5431
+ const base = refSide(baseRef, matchers, projectRoot, repoRoot);
5432
+ const head = options.working ? worktreeSide(matchers, projectRoot, repoRoot) : refSide(headRef, matchers, projectRoot, repoRoot);
5433
+ const changed = options.working ? getChangedSpecFilesInWorktree(baseRef, matchers, projectRoot, repoRoot) : getChangedSpecFiles(baseRef, headRef, matchers, projectRoot, repoRoot);
3115
5434
  const diffs = [];
3116
- for (const filePath of changed.modified) {
3117
- const beforeContent = gitShow(baseRef, filePath, projectRoot, repoRoot);
3118
- const afterContent = gitShow(headRef, filePath, projectRoot, repoRoot);
3119
- const beforeSpec = await parseSpecFromString(beforeContent, filePath);
3120
- const afterSpec = await parseSpecFromString(afterContent, filePath);
5435
+ for (const file of changed.modified) {
5436
+ const beforeSpec = await parseSpecFromString(base.read(file.path), file.path);
5437
+ const afterSpec = await parseSpecFromString(head.read(file.path), file.path);
3121
5438
  const diff2 = diffSpecs(beforeSpec, afterSpec);
3122
5439
  diffs.push(diff2);
3123
5440
  }
3124
- const added = changed.added.map((p) => specIdByPath.get(p)).filter((id) => id !== void 0);
3125
- const removed = changed.deleted.map((p) => specIdByPath.get(p)).filter((id) => id !== void 0);
3126
- const graph = buildGraph(config);
5441
+ const added = await specIdsFrom(changed.added, head.read);
5442
+ const removed = await specIdsFrom(changed.deleted, base.read);
3127
5443
  const impact = [];
3128
5444
  const allSpecs = [];
3129
- for (const entry of Object.values(config.specs)) {
3130
- try {
3131
- const content = gitShow(headRef, entry.path, projectRoot, repoRoot);
3132
- const parsed = await parseSpecFromString(content, entry.path);
3133
- allSpecs.push(parsed);
3134
- } catch {
5445
+ const specsByEntry = /* @__PURE__ */ new Map();
5446
+ const filesAtHead = head.list();
5447
+ for (const [key, paths] of filesAtHead) {
5448
+ const forEntry = [];
5449
+ for (const path of paths) {
5450
+ try {
5451
+ const parsed = await parseSpecFromString(head.read(path), path);
5452
+ forEntry.push(parsed);
5453
+ allSpecs.push(parsed);
5454
+ } catch {
5455
+ }
3135
5456
  }
5457
+ specsByEntry.set(key, forEntry);
3136
5458
  }
5459
+ const relations = buildRelationResolver(config, specsByEntry);
3137
5460
  const thresholdDays = config.diff?.staleness_threshold_days ?? 14;
3138
5461
  for (const diff2 of diffs) {
3139
- const analysis = analyzeImpact(diff2.specId, diff2, graph, allSpecs, thresholdDays);
5462
+ const analysis = analyzeImpact(diff2.specId, diff2, relations, allSpecs, thresholdDays);
3140
5463
  if (analysis.totalAffected > 0) {
3141
5464
  impact.push(analysis);
3142
5465
  }
@@ -3160,17 +5483,69 @@ async function diffBetweenRefs(configPath, baseRef, headRef) {
3160
5483
  summaryParts.push(`${_brokenRefs.length} broken reference(s)`);
3161
5484
  }
3162
5485
  const summary = summaryParts.length > 0 ? summaryParts.join("; ") : "No changes detected";
3163
- return { diffs, added, removed, impact, summary };
5486
+ const uncommittedSpecFiles = options.working ? [] : listUncommittedSpecFiles(matchers, projectRoot, repoRoot);
5487
+ return { diffs, added, removed, impact, summary, uncommittedSpecFiles };
5488
+ }
5489
+
5490
+ // src/formatters/changelog.ts
5491
+ function formatChangelog(result, baseRef, headRef) {
5492
+ const lines = [];
5493
+ lines.push(`## Spec Changes (${baseRef}..${headRef})
5494
+ `);
5495
+ if (result.diffs.length > 0) {
5496
+ lines.push("### Modified");
5497
+ for (const diff2 of result.diffs) {
5498
+ const sections = diff2.sections.map((s) => s.heading).join(", ");
5499
+ const versionChange = diff2.frontmatter.find((f) => f.field === "version");
5500
+ const versionStr = versionChange ? ` (${String(versionChange.before)} \u2192 ${String(versionChange.after)})` : "";
5501
+ lines.push(`- **${diff2.specId}**${versionStr} \u2014 ${sections || "frontmatter only"}`);
5502
+ }
5503
+ lines.push("");
5504
+ }
5505
+ if (result.added.length > 0) {
5506
+ lines.push("### Added");
5507
+ for (const id of result.added) {
5508
+ lines.push(`- **${id}**`);
5509
+ }
5510
+ lines.push("");
5511
+ }
5512
+ if (result.removed.length > 0) {
5513
+ lines.push("### Removed");
5514
+ for (const id of result.removed) {
5515
+ lines.push(`- **${id}**`);
5516
+ }
5517
+ lines.push("");
5518
+ }
5519
+ const allDownstream = result.impact.flatMap((i) => i.downstream);
5520
+ if (allDownstream.length > 0) {
5521
+ lines.push("### Downstream Impact");
5522
+ for (const d of allDownstream) {
5523
+ lines.push(`- ${d.specId} may be stale (${d.reason})`);
5524
+ }
5525
+ lines.push("");
5526
+ }
5527
+ if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
5528
+ lines.push("No spec changes detected.\n");
5529
+ }
5530
+ if (result.uncommittedSpecFiles.length > 0) {
5531
+ lines.push(
5532
+ `> \u26A0 ${result.uncommittedSpecFiles.length} spec file(s) changed in the working tree are not covered by this range.
5533
+ `
5534
+ );
5535
+ }
5536
+ return lines.join("\n");
3164
5537
  }
3165
5538
 
3166
- // src/commands/diff.ts
5539
+ // src/commands/core/diff.ts
3167
5540
  async function runDiff(options) {
3168
5541
  const configDir = process.cwd();
3169
5542
  const config = await loadConfig(void 0, configDir);
3170
5543
  const baseRef = options.base ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;
3171
5544
  const headRef = options.head ?? "HEAD";
3172
5545
  const configPath = join5(configDir, "spec.config.yaml");
3173
- const result = await diffBetweenRefs(configPath, baseRef, headRef);
5546
+ const result = await diffBetweenRefs(configPath, baseRef, headRef, {
5547
+ working: options.working ?? false
5548
+ });
3174
5549
  if (options.spec) {
3175
5550
  result.diffs = result.diffs.filter((d) => d.specId === options.spec);
3176
5551
  result.impact = result.impact.filter((i) => i.changedSpec === options.spec);
@@ -3182,72 +5557,106 @@ var diff_default = defineCommand4({
3182
5557
  args: {
3183
5558
  base: { type: "string", description: "Base git ref (default: from config or 'main')" },
3184
5559
  head: { type: "string", description: "Head git ref (default: HEAD)" },
5560
+ working: {
5561
+ type: "boolean",
5562
+ description: "Compare the base ref against the working tree (includes uncommitted specs)",
5563
+ default: false
5564
+ },
3185
5565
  spec: { type: "string", description: "Scope to a single spec ID" },
3186
5566
  format: {
3187
5567
  type: "string",
3188
- description: "Output format: pretty, json",
5568
+ description: "Output format: pretty, json, changelog",
3189
5569
  default: "pretty"
3190
5570
  }
3191
5571
  },
3192
5572
  async run({ args }) {
3193
5573
  try {
3194
- const result = await runDiff({
3195
- base: args.base,
3196
- head: args.head,
3197
- spec: args.spec,
3198
- format: args.format
3199
- });
3200
- if (args.format === "json") {
3201
- console.log(JSON.stringify(result, null, 2));
3202
- return;
3203
- }
3204
- if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
3205
- console.log(" \u2713 No spec changes detected.");
3206
- return;
3207
- }
3208
- console.log(result.summary);
3209
- console.log();
3210
- for (const diff2 of result.diffs) {
3211
- console.log(` ${diff2.specId}:`);
3212
- for (const fc of diff2.frontmatter) {
3213
- const detail = fc.before !== void 0 || fc.after !== void 0 ? ` (${String(fc.before)} \u2192 ${String(fc.after)})` : "";
3214
- console.log(` ${fc.type}: ${fc.field}${detail}`);
5574
+ try {
5575
+ const result = await runDiff({
5576
+ base: args.base,
5577
+ head: args.head,
5578
+ spec: args.spec,
5579
+ format: args.format,
5580
+ working: args.working
5581
+ });
5582
+ if (args.format === "json") {
5583
+ console.log(JSON.stringify(result, null, 2));
5584
+ return;
3215
5585
  }
3216
- for (const sc of diff2.sections) {
3217
- console.log(` ${sc.type}: ${sc.heading}`);
5586
+ if (args.format === "changelog") {
5587
+ const baseRef = args.base ?? (await loadConfig(void 0, process.cwd())).diff?.baseline_ref ?? "main";
5588
+ console.log(
5589
+ formatChangelog(result, baseRef, args.working ? "working tree" : args.head ?? "HEAD")
5590
+ );
5591
+ return;
3218
5592
  }
3219
- }
3220
- if (result.added.length > 0) {
3221
- console.log(`
5593
+ const printUncommittedWarning = () => {
5594
+ if (result.uncommittedSpecFiles.length === 0) return;
5595
+ const count = result.uncommittedSpecFiles.length;
5596
+ console.log(
5597
+ `
5598
+ \u26A0 ${count} spec file(s) changed in the working tree are not covered by this comparison:`
5599
+ );
5600
+ for (const file of result.uncommittedSpecFiles) {
5601
+ console.log(` ${file}`);
5602
+ }
5603
+ console.log(" Run with --working to include them.");
5604
+ };
5605
+ if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
5606
+ console.log(" \u2713 No spec changes detected.");
5607
+ printUncommittedWarning();
5608
+ return;
5609
+ }
5610
+ console.log(result.summary);
5611
+ console.log();
5612
+ for (const diff2 of result.diffs) {
5613
+ console.log(` ${diff2.specId}:`);
5614
+ for (const fc of diff2.frontmatter) {
5615
+ const detail = fc.before !== void 0 || fc.after !== void 0 ? ` (${String(fc.before)} \u2192 ${String(fc.after)})` : "";
5616
+ console.log(` ${fc.type}: ${fc.field}${detail}`);
5617
+ }
5618
+ for (const sc of diff2.sections) {
5619
+ console.log(` ${sc.type}: ${sc.heading}`);
5620
+ }
5621
+ }
5622
+ if (result.added.length > 0) {
5623
+ console.log(`
3222
5624
  Added: ${result.added.join(", ")}`);
3223
- }
3224
- if (result.removed.length > 0) {
3225
- console.log(`
5625
+ }
5626
+ if (result.removed.length > 0) {
5627
+ console.log(`
3226
5628
  Removed: ${result.removed.join(", ")}`);
3227
- }
3228
- if (result.impact.length > 0) {
3229
- console.log("\n Downstream Impact:");
3230
- for (const impact of result.impact) {
3231
- for (const d of impact.downstream) {
3232
- console.log(
3233
- ` ${d.specId} \u2014 staleness: ${d.staleness.toFixed(2)} \u2014 ${d.reason}`
3234
- );
5629
+ }
5630
+ if (result.impact.length > 0) {
5631
+ console.log("\n Downstream Impact:");
5632
+ for (const impact of result.impact) {
5633
+ for (const d of impact.downstream) {
5634
+ console.log(
5635
+ ` ${d.specId} \u2014 staleness: ${d.staleness.toFixed(2)} \u2014 ${d.reason}`
5636
+ );
5637
+ }
3235
5638
  }
3236
5639
  }
5640
+ printUncommittedWarning();
5641
+ } catch (err) {
5642
+ if (err instanceof DiffError) {
5643
+ console.error(`
5644
+ \u2717 ${err.message}
5645
+ `);
5646
+ process.exit(1);
5647
+ }
5648
+ throw err;
3237
5649
  }
3238
5650
  } catch (err) {
3239
- if (err instanceof DiffError) {
3240
- console.error(`
5651
+ console.error(`
3241
5652
  \u2717 ${err.message}
3242
5653
  `);
3243
- process.exit(1);
3244
- }
3245
- throw err;
5654
+ process.exit(1);
3246
5655
  }
3247
5656
  }
3248
5657
  });
3249
5658
 
3250
- // src/commands/status.ts
5659
+ // src/commands/core/status.ts
3251
5660
  import { defineCommand as defineCommand5 } from "citty";
3252
5661
  async function runStatus(_options = {}) {
3253
5662
  const configDir = process.cwd();
@@ -3318,6 +5727,7 @@ async function runStatus(_options = {}) {
3318
5727
  let verdict = "healthy";
3319
5728
  if (errors > 0) verdict = "errors";
3320
5729
  else if (warnings > 0 || staleSpecs.length > 0) verdict = "warnings";
5730
+ else if (specs.length === 0) verdict = "unassessed";
3321
5731
  return {
3322
5732
  project: config.project?.name ?? "unknown",
3323
5733
  specCount: specs.length,
@@ -3338,208 +5748,56 @@ var status_default = defineCommand5({
3338
5748
  }
3339
5749
  },
3340
5750
  async run({ args }) {
3341
- const result = await runStatus({ format: args.format });
3342
- if (args.format === "json") {
3343
- console.log(JSON.stringify(result, null, 2));
3344
- return;
3345
- }
3346
- if (args.format === "github") {
3347
- for (const s of result.staleSpecs) {
3348
- console.log(
3349
- `::warning::Spec "${s.specId}" is stale (${s.daysSinceUpdate} days since update)`
3350
- );
5751
+ try {
5752
+ const result = await runStatus({ format: args.format });
5753
+ if (args.format === "json") {
5754
+ console.log(JSON.stringify(result, null, 2));
5755
+ return;
3351
5756
  }
3352
- for (const issue of result.integrityIssues) {
3353
- console.log(`::error::${issue}`);
5757
+ if (args.format === "github") {
5758
+ for (const s of result.staleSpecs) {
5759
+ console.log(
5760
+ `::warning::Spec "${s.specId}" is stale (${s.daysSinceUpdate} days since update)`
5761
+ );
5762
+ }
5763
+ for (const issue of result.integrityIssues) {
5764
+ console.log(`::error::${issue}`);
5765
+ }
5766
+ return;
3354
5767
  }
3355
- return;
3356
- }
3357
- const icon = result.verdict === "healthy" ? "\u2713" : result.verdict === "warnings" ? "\u26A0" : "\u2717";
3358
- console.log(`
5768
+ const icon = result.verdict === "healthy" ? "\u2713" : result.verdict === "warnings" || result.verdict === "unassessed" ? "\u26A0" : "\u2717";
5769
+ console.log(`
3359
5770
  ${icon} ${result.project} \u2014 ${result.verdict}`);
3360
- console.log(
3361
- ` ${result.specCount} specs: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
3362
- );
3363
- console.log(
3364
- ` Lint: ${result.lintHealth.errors} errors, ${result.lintHealth.warnings} warnings`
3365
- );
3366
- if (result.staleSpecs.length > 0) {
5771
+ if (result.verdict === "unassessed") {
5772
+ console.log(
5773
+ " No specs resolved \u2014 nothing was assessed. Check the spec paths in spec.config.yaml."
5774
+ );
5775
+ }
3367
5776
  console.log(
3368
- ` Stale: ${result.staleSpecs.map((s) => `${s.specId} (${s.daysSinceUpdate}d)`).join(", ")}`
5777
+ ` ${result.specCount} specs: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
3369
5778
  );
3370
- }
3371
- if (result.integrityIssues.length > 0) {
3372
- console.log(` Issues: ${result.integrityIssues.join("; ")}`);
3373
- }
3374
- console.log();
3375
- }
3376
- });
3377
-
3378
- // src/commands/changelog.ts
3379
- import { defineCommand as defineCommand6 } from "citty";
3380
- import { join as join6 } from "path";
3381
- async function runChangelog(options) {
3382
- const configDir = process.cwd();
3383
- const config = await loadConfig(void 0, configDir);
3384
- const fromRef = options.from ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;
3385
- const toRef = options.to ?? "HEAD";
3386
- const configPath = join6(configDir, "spec.config.yaml");
3387
- const result = await diffBetweenRefs(configPath, fromRef, toRef);
3388
- const lines = [];
3389
- lines.push(`## Spec Changes (${fromRef}..${toRef})
3390
- `);
3391
- if (result.diffs.length > 0) {
3392
- lines.push("### Modified");
3393
- for (const diff2 of result.diffs) {
3394
- const sections = diff2.sections.map((s) => s.heading).join(", ");
3395
- const versionChange = diff2.frontmatter.find((f) => f.field === "version");
3396
- const versionStr = versionChange ? ` (${String(versionChange.before)} \u2192 ${String(versionChange.after)})` : "";
3397
- lines.push(`- **${diff2.specId}**${versionStr} \u2014 ${sections || "frontmatter only"}`);
3398
- }
3399
- lines.push("");
3400
- }
3401
- if (result.added.length > 0) {
3402
- lines.push("### Added");
3403
- for (const id of result.added) {
3404
- lines.push(`- **${id}**`);
3405
- }
3406
- lines.push("");
3407
- }
3408
- if (result.removed.length > 0) {
3409
- lines.push("### Removed");
3410
- for (const id of result.removed) {
3411
- lines.push(`- **${id}**`);
3412
- }
3413
- lines.push("");
3414
- }
3415
- const allDownstream = result.impact.flatMap((i) => i.downstream);
3416
- if (allDownstream.length > 0) {
3417
- lines.push("### Downstream Impact");
3418
- for (const d of allDownstream) {
3419
- lines.push(`- ${d.specId} may be stale (${d.reason})`);
3420
- }
3421
- lines.push("");
3422
- }
3423
- if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
3424
- lines.push("No spec changes detected.\n");
3425
- }
3426
- return lines.join("\n");
3427
- }
3428
- var changelog_default = defineCommand6({
3429
- meta: { name: "changelog", description: "Generate changelog of spec changes between git refs" },
3430
- args: {
3431
- from: { type: "string", description: "Start git ref (default: from config or 'main')" },
3432
- to: { type: "string", description: "End git ref (default: HEAD)" }
3433
- },
3434
- async run({ args }) {
3435
- try {
3436
- const output = await runChangelog(args);
3437
- console.log(output);
5779
+ console.log(
5780
+ ` Lint: ${result.lintHealth.errors} errors, ${result.lintHealth.warnings} warnings`
5781
+ );
5782
+ if (result.staleSpecs.length > 0) {
5783
+ console.log(
5784
+ ` Stale: ${result.staleSpecs.map((s) => `${s.specId} (${s.daysSinceUpdate}d)`).join(", ")}`
5785
+ );
5786
+ }
5787
+ if (result.integrityIssues.length > 0) {
5788
+ console.log(` Issues: ${result.integrityIssues.join("; ")}`);
5789
+ }
5790
+ console.log();
3438
5791
  } catch (err) {
3439
- if (err instanceof DiffError) {
3440
- console.error(`
5792
+ console.error(`
3441
5793
  \u2717 ${err.message}
3442
5794
  `);
3443
- process.exit(1);
3444
- }
3445
- throw err;
3446
- }
3447
- }
3448
- });
3449
-
3450
- // src/commands/explain.ts
3451
- import { defineCommand as defineCommand7 } from "citty";
3452
- async function runExplain(_options = {}) {
3453
- const configDir = process.cwd();
3454
- const config = await loadConfig(void 0, configDir);
3455
- const specs = [];
3456
- for (const [, entry] of Object.entries(config.specs)) {
3457
- const paths = await resolveGlob(entry.path, configDir);
3458
- for (const p of paths) {
3459
- specs.push(await parseSpec(p));
3460
- }
3461
- }
3462
- const byType = {};
3463
- const byStatus = {};
3464
- for (const spec of specs) {
3465
- const type = spec.frontmatter.type || "unknown";
3466
- const status = spec.frontmatter.status || "unknown";
3467
- byType[type] = (byType[type] ?? 0) + 1;
3468
- byStatus[status] = (byStatus[status] ?? 0) + 1;
3469
- }
3470
- const specSummaries = specs.map((spec) => {
3471
- const firstSection = spec.parsedSections[0];
3472
- const firstLine = firstSection?.content?.split("\n").find((l) => l.trim().length > 0)?.trim() ?? "";
3473
- const truncated = firstLine.slice(0, 120) + (firstLine.length > 120 ? "..." : "");
3474
- return {
3475
- id: spec.frontmatter.id,
3476
- type: spec.frontmatter.type,
3477
- title: spec.frontmatter.title,
3478
- status: spec.frontmatter.status,
3479
- firstLine: truncated
3480
- };
3481
- });
3482
- const graph = buildGraph(config);
3483
- const graphLines = [];
3484
- for (const node of graph.nodes) {
3485
- const downstream = graph.edges.filter((e) => e.from === node).map((e) => e.to);
3486
- if (downstream.length > 0) {
3487
- graphLines.push(`${node} \u2192 ${downstream.join(", ")}`);
3488
- } else {
3489
- graphLines.push(node);
3490
- }
3491
- }
3492
- return {
3493
- project: config.project?.name ?? "unknown",
3494
- description: config.project?.description,
3495
- specCount: specs.length,
3496
- byType,
3497
- byStatus,
3498
- specs: specSummaries,
3499
- graph: graphLines
3500
- };
3501
- }
3502
- var explain_default = defineCommand7({
3503
- meta: { name: "explain", description: "Explain the spec suite for onboarding" },
3504
- args: {
3505
- format: { type: "string", description: "Output format: pretty, json", default: "pretty" }
3506
- },
3507
- async run({ args }) {
3508
- const result = await runExplain({ format: args.format });
3509
- if (args.format === "json") {
3510
- console.log(JSON.stringify(result, null, 2));
3511
- return;
3512
- }
3513
- console.log(`
3514
- ${result.project}`);
3515
- if (result.description) {
3516
- console.log(` ${result.description}`);
3517
- }
3518
- console.log(
3519
- `
3520
- ${result.specCount} specs: ${Object.entries(result.byType).map(([k, v]) => `${v} ${k}`).join(", ")}`
3521
- );
3522
- console.log(
3523
- ` Status: ${Object.entries(result.byStatus).map(([k, v]) => `${v} ${k}`).join(", ")}`
3524
- );
3525
- console.log("\n Specs:");
3526
- for (const spec of result.specs) {
3527
- console.log(` ${spec.id} (${spec.type}, ${spec.status}) \u2014 ${spec.title}`);
3528
- if (spec.firstLine) {
3529
- console.log(` ${spec.firstLine}`);
3530
- }
3531
- }
3532
- console.log("\n Dependencies:");
3533
- for (const line of result.graph) {
3534
- console.log(` ${line}`);
5795
+ process.exit(1);
3535
5796
  }
3536
- console.log();
3537
5797
  }
3538
5798
  });
3539
5799
  export {
3540
- runChangelog,
3541
5800
  runDiff,
3542
- runExplain,
3543
5801
  runLint,
3544
5802
  runPack,
3545
5803
  runStatus,