specdx 0.4.0-alpha.2 → 0.4.0-alpha.20

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-GGQB3SHI.js} +36 -10
  5. package/dist/check-GGQB3SHI.js.map +1 -0
  6. package/dist/chunk-5WRI5ZAA.js +31 -0
  7. package/dist/chunk-CI7KYTC7.js +103 -0
  8. package/dist/chunk-CI7KYTC7.js.map +1 -0
  9. package/dist/chunk-FBMYBYFB.js +182 -0
  10. package/dist/chunk-FBMYBYFB.js.map +1 -0
  11. package/dist/{chunk-FZWT4HVX.js → chunk-MM325DR6.js} +156 -2
  12. package/dist/chunk-MM325DR6.js.map +1 -0
  13. package/dist/chunk-RY5CDUNN.js +2846 -0
  14. package/dist/chunk-RY5CDUNN.js.map +1 -0
  15. package/dist/{chunk-YRDOYUKF.js → chunk-T232GZ2L.js} +124 -19
  16. package/dist/chunk-T232GZ2L.js.map +1 -0
  17. package/dist/{chunk-PHWUK7TH.js → chunk-UZKOJL2N.js} +288 -50
  18. package/dist/chunk-UZKOJL2N.js.map +1 -0
  19. package/dist/{chunk-QEUZJWBY.js → chunk-ZB5R5SK5.js} +364 -59
  20. package/dist/chunk-ZB5R5SK5.js.map +1 -0
  21. package/dist/{chunk-YDU26YTH.js → chunk-ZIPGRLYE.js} +120 -16
  22. package/dist/chunk-ZIPGRLYE.js.map +1 -0
  23. package/dist/diff-PHEX3HUT.js +188 -0
  24. package/dist/diff-PHEX3HUT.js.map +1 -0
  25. package/dist/{dist-2B2MR5AM.js → dist-DQ6NNKZO.js} +53 -14
  26. package/dist/dist-DQ6NNKZO.js.map +1 -0
  27. package/dist/dist-RT3MTIUW.js +16 -0
  28. package/dist/dist-RT3MTIUW.js.map +1 -0
  29. package/dist/generate-5VO6M4PB.js +21 -0
  30. package/dist/generate-5VO6M4PB.js.map +1 -0
  31. package/dist/{generate-story-AOALIKSD.js → generate-story-CJMV2F5K.js} +48 -20
  32. package/dist/generate-story-CJMV2F5K.js.map +1 -0
  33. package/dist/{generate-test-plan-34L6RGOB.js → generate-test-plan-XBAFJKJI.js} +63 -10
  34. package/dist/generate-test-plan-XBAFJKJI.js.map +1 -0
  35. package/dist/graph-UZJMLX4J.js +103 -0
  36. package/dist/graph-UZJMLX4J.js.map +1 -0
  37. package/dist/index.d.ts +171 -0
  38. package/dist/index.js +2635 -386
  39. package/dist/index.js.map +1 -1
  40. package/dist/{lint-XGVQ6LCP.js → lint-TVL2ILOQ.js} +20 -8
  41. package/dist/lint-TVL2ILOQ.js.map +1 -0
  42. package/dist/main.js +11 -146
  43. package/dist/main.js.map +1 -1
  44. package/dist/mcp-F7LJBZ4X.js +35 -0
  45. package/dist/mcp-F7LJBZ4X.js.map +1 -0
  46. package/dist/{migrate-KDJZQKP7.js → migrate-DEFCNOAH.js} +20 -8
  47. package/dist/migrate-DEFCNOAH.js.map +1 -0
  48. package/dist/{pack-OJ3CDZHD.js → pack-PNLD5AYW.js} +36 -11
  49. package/dist/pack-PNLD5AYW.js.map +1 -0
  50. package/dist/ready-2PHBPWJD.js +257 -0
  51. package/dist/ready-2PHBPWJD.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-LHFTTEJ7.js +121 -0
  65. package/dist/skills-LHFTTEJ7.js.map +1 -0
  66. package/dist/{status-JVIXK73H.js → status-UKLQV4AI.js} +48 -34
  67. package/dist/status-UKLQV4AI.js.map +1 -0
  68. package/dist/{update-HFLDULNJ.js → update-KLDLDQZM.js} +6 -5
  69. package/dist/update-KLDLDQZM.js.map +1 -0
  70. package/dist/validate-FXD5WS4C.js +87 -0
  71. package/dist/validate-FXD5WS4C.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
@@ -0,0 +1,188 @@
1
+ import {
2
+ DEFAULT_DIFF_CONFIG,
3
+ DiffError,
4
+ diffBetweenRefs
5
+ } from "./chunk-RY5CDUNN.js";
6
+ import {
7
+ loadConfig
8
+ } from "./chunk-MM325DR6.js";
9
+ import "./chunk-ZIPGRLYE.js";
10
+ import "./chunk-5WRI5ZAA.js";
11
+
12
+ // src/commands/core/diff.ts
13
+ import { defineCommand } from "citty";
14
+ import { join } from "path";
15
+
16
+ // src/formatters/changelog.ts
17
+ function formatChangelog(result, baseRef, headRef) {
18
+ const lines = [];
19
+ lines.push(`## Spec Changes (${baseRef}..${headRef})
20
+ `);
21
+ if (result.diffs.length > 0) {
22
+ lines.push("### Modified");
23
+ for (const diff of result.diffs) {
24
+ const sections = diff.sections.map((s) => s.heading).join(", ");
25
+ const versionChange = diff.frontmatter.find((f) => f.field === "version");
26
+ const versionStr = versionChange ? ` (${String(versionChange.before)} \u2192 ${String(versionChange.after)})` : "";
27
+ lines.push(`- **${diff.specId}**${versionStr} \u2014 ${sections || "frontmatter only"}`);
28
+ }
29
+ lines.push("");
30
+ }
31
+ if (result.added.length > 0) {
32
+ lines.push("### Added");
33
+ for (const id of result.added) {
34
+ lines.push(`- **${id}**`);
35
+ }
36
+ lines.push("");
37
+ }
38
+ if (result.removed.length > 0) {
39
+ lines.push("### Removed");
40
+ for (const id of result.removed) {
41
+ lines.push(`- **${id}**`);
42
+ }
43
+ lines.push("");
44
+ }
45
+ const allDownstream = result.impact.flatMap((i) => i.downstream);
46
+ if (allDownstream.length > 0) {
47
+ lines.push("### Downstream Impact");
48
+ for (const d of allDownstream) {
49
+ lines.push(`- ${d.specId} may be stale (${d.reason})`);
50
+ }
51
+ lines.push("");
52
+ }
53
+ if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
54
+ lines.push("No spec changes detected.\n");
55
+ }
56
+ if (result.uncommittedSpecFiles.length > 0) {
57
+ lines.push(
58
+ `> \u26A0 ${result.uncommittedSpecFiles.length} spec file(s) changed in the working tree are not covered by this range.
59
+ `
60
+ );
61
+ }
62
+ return lines.join("\n");
63
+ }
64
+
65
+ // src/commands/core/diff.ts
66
+ async function runDiff(options) {
67
+ const configDir = process.cwd();
68
+ const config = await loadConfig(void 0, configDir);
69
+ const baseRef = options.base ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;
70
+ const headRef = options.head ?? "HEAD";
71
+ const configPath = join(configDir, "spec.config.yaml");
72
+ const result = await diffBetweenRefs(configPath, baseRef, headRef, {
73
+ working: options.working ?? false
74
+ });
75
+ if (options.spec) {
76
+ result.diffs = result.diffs.filter((d) => d.specId === options.spec);
77
+ result.impact = result.impact.filter((i) => i.changedSpec === options.spec);
78
+ }
79
+ return result;
80
+ }
81
+ var diff_default = defineCommand({
82
+ meta: { name: "diff", description: "Show spec changes and downstream impact" },
83
+ args: {
84
+ base: { type: "string", description: "Base git ref (default: from config or 'main')" },
85
+ head: { type: "string", description: "Head git ref (default: HEAD)" },
86
+ working: {
87
+ type: "boolean",
88
+ description: "Compare the base ref against the working tree (includes uncommitted specs)",
89
+ default: false
90
+ },
91
+ spec: { type: "string", description: "Scope to a single spec ID" },
92
+ format: {
93
+ type: "string",
94
+ description: "Output format: pretty, json, changelog",
95
+ default: "pretty"
96
+ }
97
+ },
98
+ async run({ args }) {
99
+ try {
100
+ try {
101
+ const result = await runDiff({
102
+ base: args.base,
103
+ head: args.head,
104
+ spec: args.spec,
105
+ format: args.format,
106
+ working: args.working
107
+ });
108
+ if (args.format === "json") {
109
+ console.log(JSON.stringify(result, null, 2));
110
+ return;
111
+ }
112
+ if (args.format === "changelog") {
113
+ const baseRef = args.base ?? (await loadConfig(void 0, process.cwd())).diff?.baseline_ref ?? "main";
114
+ console.log(
115
+ formatChangelog(result, baseRef, args.working ? "working tree" : args.head ?? "HEAD")
116
+ );
117
+ return;
118
+ }
119
+ const printUncommittedWarning = () => {
120
+ if (result.uncommittedSpecFiles.length === 0) return;
121
+ const count = result.uncommittedSpecFiles.length;
122
+ console.log(
123
+ `
124
+ \u26A0 ${count} spec file(s) changed in the working tree are not covered by this comparison:`
125
+ );
126
+ for (const file of result.uncommittedSpecFiles) {
127
+ console.log(` ${file}`);
128
+ }
129
+ console.log(" Run with --working to include them.");
130
+ };
131
+ if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {
132
+ console.log(" \u2713 No spec changes detected.");
133
+ printUncommittedWarning();
134
+ return;
135
+ }
136
+ console.log(result.summary);
137
+ console.log();
138
+ for (const diff of result.diffs) {
139
+ console.log(` ${diff.specId}:`);
140
+ for (const fc of diff.frontmatter) {
141
+ const detail = fc.before !== void 0 || fc.after !== void 0 ? ` (${String(fc.before)} \u2192 ${String(fc.after)})` : "";
142
+ console.log(` ${fc.type}: ${fc.field}${detail}`);
143
+ }
144
+ for (const sc of diff.sections) {
145
+ console.log(` ${sc.type}: ${sc.heading}`);
146
+ }
147
+ }
148
+ if (result.added.length > 0) {
149
+ console.log(`
150
+ Added: ${result.added.join(", ")}`);
151
+ }
152
+ if (result.removed.length > 0) {
153
+ console.log(`
154
+ Removed: ${result.removed.join(", ")}`);
155
+ }
156
+ if (result.impact.length > 0) {
157
+ console.log("\n Downstream Impact:");
158
+ for (const impact of result.impact) {
159
+ for (const d of impact.downstream) {
160
+ console.log(
161
+ ` ${d.specId} \u2014 staleness: ${d.staleness.toFixed(2)} \u2014 ${d.reason}`
162
+ );
163
+ }
164
+ }
165
+ }
166
+ printUncommittedWarning();
167
+ } catch (err) {
168
+ if (err instanceof DiffError) {
169
+ console.error(`
170
+ \u2717 ${err.message}
171
+ `);
172
+ process.exit(1);
173
+ }
174
+ throw err;
175
+ }
176
+ } catch (err) {
177
+ console.error(`
178
+ \u2717 ${err.message}
179
+ `);
180
+ process.exit(1);
181
+ }
182
+ }
183
+ });
184
+ export {
185
+ diff_default as default,
186
+ runDiff
187
+ };
188
+ //# sourceMappingURL=diff-PHEX3HUT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/core/diff.ts","../src/formatters/changelog.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { join } from \"node:path\";\nimport { diffBetweenRefs, DEFAULT_DIFF_CONFIG, DiffError } from \"@specdx/diff\";\nimport { loadConfig } from \"@specdx/core\";\nimport { formatChangelog } from \"../../formatters/changelog.js\";\nimport type { DiffResult } from \"@specdx/diff\";\n\nexport interface RunDiffOptions {\n base?: string;\n head?: string;\n spec?: string;\n format?: string;\n /** Compare the base ref against the working tree instead of a head ref. */\n working?: boolean;\n}\n\nexport async function runDiff(options: RunDiffOptions): Promise<DiffResult> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n const baseRef = options.base ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;\n const headRef = options.head ?? \"HEAD\";\n\n const configPath = join(configDir, \"spec.config.yaml\");\n\n const result = await diffBetweenRefs(configPath, baseRef, headRef, {\n working: options.working ?? false,\n });\n\n if (options.spec) {\n result.diffs = result.diffs.filter((d) => d.specId === options.spec);\n result.impact = result.impact.filter((i) => i.changedSpec === options.spec);\n }\n\n return result;\n}\n\nexport default defineCommand({\n meta: { name: \"diff\", description: \"Show spec changes and downstream impact\" },\n args: {\n base: { type: \"string\", description: \"Base git ref (default: from config or 'main')\" },\n head: { type: \"string\", description: \"Head git ref (default: HEAD)\" },\n working: {\n type: \"boolean\",\n description: \"Compare the base ref against the working tree (includes uncommitted specs)\",\n default: false,\n },\n spec: { type: \"string\", description: \"Scope to a single spec ID\" },\n format: {\n type: \"string\",\n description: \"Output format: pretty, json, changelog\",\n default: \"pretty\",\n },\n },\n async run({ args }) {\n try {\n try {\n const result = await runDiff({\n base: args.base,\n head: args.head,\n spec: args.spec,\n format: args.format,\n working: args.working,\n });\n\n if (args.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n\n if (args.format === \"changelog\") {\n const baseRef =\n args.base ?? (await loadConfig(undefined, process.cwd())).diff?.baseline_ref ?? \"main\";\n console.log(\n formatChangelog(result, baseRef, args.working ? \"working tree\" : (args.head ?? \"HEAD\")),\n );\n return;\n }\n\n // A ref-to-ref comparison cannot see the working tree, so an unqualified\n // \"no changes\" would be a false all-clear for anyone about to commit.\n const printUncommittedWarning = (): void => {\n if (result.uncommittedSpecFiles.length === 0) return;\n const count = result.uncommittedSpecFiles.length;\n console.log(\n `\\n \\u26a0 ${count} spec file(s) changed in the working tree are not covered by this comparison:`,\n );\n for (const file of result.uncommittedSpecFiles) {\n console.log(` ${file}`);\n }\n console.log(\" Run with --working to include them.\");\n };\n\n // Pretty format\n if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {\n console.log(\" \\u2713 No spec changes detected.\");\n printUncommittedWarning();\n return;\n }\n\n console.log(result.summary);\n console.log();\n\n for (const diff of result.diffs) {\n console.log(` ${diff.specId}:`);\n for (const fc of diff.frontmatter) {\n const detail =\n fc.before !== undefined || fc.after !== undefined\n ? ` (${String(fc.before)} \\u2192 ${String(fc.after)})`\n : \"\";\n console.log(` ${fc.type}: ${fc.field}${detail}`);\n }\n for (const sc of diff.sections) {\n console.log(` ${sc.type}: ${sc.heading}`);\n }\n }\n\n if (result.added.length > 0) {\n console.log(`\\n Added: ${result.added.join(\", \")}`);\n }\n if (result.removed.length > 0) {\n console.log(`\\n Removed: ${result.removed.join(\", \")}`);\n }\n\n if (result.impact.length > 0) {\n console.log(\"\\n Downstream Impact:\");\n for (const impact of result.impact) {\n for (const d of impact.downstream) {\n console.log(\n ` ${d.specId} \\u2014 staleness: ${d.staleness.toFixed(2)} \\u2014 ${d.reason}`,\n );\n }\n }\n }\n\n printUncommittedWarning();\n } catch (err) {\n if (err instanceof DiffError) {\n console.error(`\\n \\u2717 ${err.message}\\n`);\n process.exit(1);\n }\n throw err;\n }\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n","import type { DiffResult } from \"@specdx/diff\";\n\n/**\n * Render a diff as a markdown changelog.\n *\n * Formerly the `specdx changelog` command, which ran the same comparison as\n * `diff` and differed only in presentation. It is a format, not a second\n * question, so it lives as `diff --format changelog`.\n */\nexport function formatChangelog(result: DiffResult, baseRef: string, headRef: string): string {\n const lines: string[] = [];\n lines.push(`## Spec Changes (${baseRef}..${headRef})\\n`);\n\n if (result.diffs.length > 0) {\n lines.push(\"### Modified\");\n for (const diff of result.diffs) {\n const sections = diff.sections.map((s) => s.heading).join(\", \");\n const versionChange = diff.frontmatter.find((f) => f.field === \"version\");\n const versionStr = versionChange\n ? ` (${String(versionChange.before)} → ${String(versionChange.after)})`\n : \"\";\n lines.push(`- **${diff.specId}**${versionStr} — ${sections || \"frontmatter only\"}`);\n }\n lines.push(\"\");\n }\n\n if (result.added.length > 0) {\n lines.push(\"### Added\");\n for (const id of result.added) {\n lines.push(`- **${id}**`);\n }\n lines.push(\"\");\n }\n\n if (result.removed.length > 0) {\n lines.push(\"### Removed\");\n for (const id of result.removed) {\n lines.push(`- **${id}**`);\n }\n lines.push(\"\");\n }\n\n const allDownstream = result.impact.flatMap((i) => i.downstream);\n if (allDownstream.length > 0) {\n lines.push(\"### Downstream Impact\");\n for (const d of allDownstream) {\n lines.push(`- ${d.specId} may be stale (${d.reason})`);\n }\n lines.push(\"\");\n }\n\n if (result.diffs.length === 0 && result.added.length === 0 && result.removed.length === 0) {\n lines.push(\"No spec changes detected.\\n\");\n }\n\n // The uncommitted warning matters most here: a changelog is usually written\n // at release time, when unstaged spec edits are easy to miss.\n if (result.uncommittedSpecFiles.length > 0) {\n lines.push(\n `> ⚠ ${result.uncommittedSpecFiles.length} spec file(s) changed in the working tree are not covered by this range.\\n`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,YAAY;;;ACQd,SAAS,gBAAgB,QAAoB,SAAiB,SAAyB;AAC5F,QAAM,QAAkB,CAAC;AACzB,QAAM,KAAK,oBAAoB,OAAO,KAAK,OAAO;AAAA,CAAK;AAEvD,MAAI,OAAO,MAAM,SAAS,GAAG;AAC3B,UAAM,KAAK,cAAc;AACzB,eAAW,QAAQ,OAAO,OAAO;AAC/B,YAAM,WAAW,KAAK,SAAS,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,IAAI;AAC9D,YAAM,gBAAgB,KAAK,YAAY,KAAK,CAAC,MAAM,EAAE,UAAU,SAAS;AACxE,YAAM,aAAa,gBACf,KAAK,OAAO,cAAc,MAAM,CAAC,WAAM,OAAO,cAAc,KAAK,CAAC,MAClE;AACJ,YAAM,KAAK,OAAO,KAAK,MAAM,KAAK,UAAU,WAAM,YAAY,kBAAkB,EAAE;AAAA,IACpF;AACA,UAAM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,OAAO,QAAQ;AAClC,uBAAW,KAAK,OAAO,YAAY;AACjC,sBAAQ;AAAA,gBACN,OAAO,EAAE,MAAM,sBAAsB,EAAE,UAAU,QAAQ,CAAC,CAAC,WAAW,EAAE,MAAM;AAAA,cAChF;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAEA,gCAAwB;AAAA,MAC1B,SAAS,KAAK;AACZ,YAAI,eAAe,WAAW;AAC5B,kBAAQ,MAAM;AAAA,WAAc,IAAI,OAAO;AAAA,CAAI;AAC3C,kBAAQ,KAAK,CAAC;AAAA,QAChB;AACA,cAAM;AAAA,MACR;AAAA,IACF,SAAS,KAAK;AACZ,cAAQ,MAAM;AAAA,WAAU,IAAc,OAAO;AAAA,CAAI;AACjD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF,CAAC;","names":[]}
@@ -1,27 +1,30 @@
1
1
  import {
2
2
  runCheck
3
- } from "./chunk-QEUZJWBY.js";
3
+ } from "./chunk-ZB5R5SK5.js";
4
4
  import {
5
5
  pack
6
- } from "./chunk-YRDOYUKF.js";
6
+ } from "./chunk-T232GZ2L.js";
7
7
  import {
8
8
  createLintEngine,
9
9
  getPreset
10
- } from "./chunk-PHWUK7TH.js";
10
+ } from "./chunk-UZKOJL2N.js";
11
11
  import {
12
12
  DEFAULT_DIFF_CONFIG,
13
13
  DiffError,
14
14
  diffBetweenRefs
15
- } from "./chunk-7C3BAVCP.js";
15
+ } from "./chunk-RY5CDUNN.js";
16
16
  import {
17
17
  ConfigError,
18
18
  GraphError,
19
19
  buildGraph,
20
+ collectReferenceEdges,
21
+ findUnreflectedReferences,
20
22
  loadConfig,
21
23
  parseSpec,
22
24
  resolveGlob
23
- } from "./chunk-FZWT4HVX.js";
24
- import "./chunk-YDU26YTH.js";
25
+ } from "./chunk-MM325DR6.js";
26
+ import "./chunk-ZIPGRLYE.js";
27
+ import "./chunk-5WRI5ZAA.js";
25
28
 
26
29
  // ../mcp/dist/server.js
27
30
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
@@ -32,15 +35,24 @@ async function handleValidate(params) {
32
35
  try {
33
36
  const configDir = params.configPath ?? process.cwd();
34
37
  const config = await loadConfig(void 0, configDir);
38
+ buildGraph(config);
39
+ let specFiles = 0;
40
+ for (const entry of Object.values(config.specs)) {
41
+ specFiles += (await resolveGlob(entry.path, configDir)).length;
42
+ }
35
43
  return JSON.stringify({
36
44
  valid: true,
37
- specCount: Object.keys(config.specs).length,
45
+ specEntries: Object.keys(config.specs).length,
46
+ specFiles,
38
47
  project: config.project?.name ?? "unknown"
39
48
  });
40
49
  } catch (err) {
41
50
  if (err instanceof ConfigError) {
42
51
  return JSON.stringify({ valid: false, error: err.message, details: err.errors });
43
52
  }
53
+ if (err instanceof GraphError) {
54
+ return JSON.stringify({ valid: false, error: err.message });
55
+ }
44
56
  throw err;
45
57
  }
46
58
  }
@@ -150,9 +162,14 @@ async function handleStatus() {
150
162
  verdict = "errors";
151
163
  else if (warnings > 0 || staleSpecs.length > 0)
152
164
  verdict = "warnings";
165
+ else if (specs.length === 0)
166
+ verdict = "unassessed";
153
167
  return JSON.stringify({
154
168
  project: config.project?.name ?? "unknown",
155
- specCount: specs.length,
169
+ // `specFiles` only. A second field named `specCount` gives a consumer no
170
+ // way to know whether it counts config entries or resolved files -- the
171
+ // ambiguity `sdx_validate` was already cleaned up to avoid.
172
+ specFiles: specs.length,
156
173
  byStatus,
157
174
  lintHealth: { errors, warnings, passing: specs.length - errors },
158
175
  staleSpecs,
@@ -192,7 +209,9 @@ async function handleDiff(params) {
192
209
  const headRef = params.head ?? "HEAD";
193
210
  const configPath = join(configDir, "spec.config.yaml");
194
211
  try {
195
- const result = await diffBetweenRefs(configPath, baseRef, headRef);
212
+ const result = await diffBetweenRefs(configPath, baseRef, headRef, {
213
+ working: params.working ?? false
214
+ });
196
215
  return JSON.stringify(result);
197
216
  } catch (err) {
198
217
  if (err instanceof DiffError) {
@@ -209,17 +228,36 @@ async function handleGraph(params) {
209
228
  try {
210
229
  const graph = buildGraph(config);
211
230
  const sorted = graph.topologicalSort();
231
+ const idToEntry = /* @__PURE__ */ new Map();
232
+ const specs = [];
233
+ for (const [key, entry] of Object.entries(config.specs)) {
234
+ const paths = await resolveGlob(entry.path, configDir);
235
+ for (const p of paths) {
236
+ const spec = await parseSpec(p);
237
+ specs.push(spec);
238
+ if (typeof spec.frontmatter.id === "string") {
239
+ idToEntry.set(spec.frontmatter.id, key);
240
+ }
241
+ }
242
+ }
243
+ const referenceEdges = collectReferenceEdges(specs);
244
+ const unreflectedReferences = findUnreflectedReferences(referenceEdges, idToEntry, graph);
212
245
  if (params.format === "dot") {
213
246
  const lines = ["digraph specs {"];
214
247
  for (const edge of graph.edges)
215
248
  lines.push(` "${edge.from}" -> "${edge.to}";`);
249
+ for (const ref of referenceEdges) {
250
+ lines.push(` "${ref.fromId}" -> "${ref.toId}" [style=dashed, label="${ref.relationship}"];`);
251
+ }
216
252
  lines.push("}");
217
253
  return lines.join("\n");
218
254
  }
219
255
  return JSON.stringify({
220
256
  nodes: sorted,
221
257
  edges: graph.edges,
222
- downstream: Object.fromEntries(sorted.map((n) => [n, graph.getDownstream(n)]))
258
+ downstream: Object.fromEntries(sorted.map((n) => [n, graph.getDownstream(n)])),
259
+ referenceEdges,
260
+ unreflectedReferences
223
261
  });
224
262
  } catch (err) {
225
263
  if (err instanceof GraphError) {
@@ -230,10 +268,10 @@ async function handleGraph(params) {
230
268
  }
231
269
 
232
270
  // ../mcp/dist/server.js
233
- function createMcpServer() {
271
+ function createMcpServer(version = "0.0.0-unknown") {
234
272
  const server = new McpServer({
235
273
  name: "specdx",
236
- version: "0.3.0"
274
+ version
237
275
  });
238
276
  server.tool("sdx_validate", "Validate the spec.config.yaml configuration file", { configPath: z.string().optional().describe("Path to config directory") }, async (params) => ({
239
277
  content: [{ type: "text", text: await handleValidate(params) }]
@@ -262,7 +300,8 @@ function createMcpServer() {
262
300
  }));
263
301
  server.tool("sdx_diff", "Show spec changes and downstream impact between git refs", {
264
302
  base: z.string().optional().describe("Base git ref (default: main)"),
265
- head: z.string().optional().describe("Head git ref (default: HEAD)")
303
+ head: z.string().optional().describe("Head git ref (default: HEAD)"),
304
+ working: z.boolean().optional().describe("Compare the base ref against the working tree, including uncommitted and untracked specs (default: false)")
266
305
  }, async (params) => ({
267
306
  content: [{ type: "text", text: await handleDiff(params) }]
268
307
  }));
@@ -276,4 +315,4 @@ function createMcpServer() {
276
315
  export {
277
316
  createMcpServer
278
317
  };
279
- //# sourceMappingURL=dist-2B2MR5AM.js.map
318
+ //# sourceMappingURL=dist-DQ6NNKZO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../mcp/src/server.ts","../../mcp/src/tools/validate.ts","../../mcp/src/tools/lint.ts","../../mcp/src/tools/pack.ts","../../mcp/src/tools/status.ts","../../mcp/src/tools/check.ts","../../mcp/src/tools/diff.ts","../../mcp/src/tools/graph.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { handleValidate } from \"./tools/validate.js\";\nimport { handleLint } from \"./tools/lint.js\";\nimport { handlePack } from \"./tools/pack.js\";\nimport { handleStatus } from \"./tools/status.js\";\nimport { handleCheck } from \"./tools/check.js\";\nimport { handleDiff } from \"./tools/diff.js\";\nimport { handleGraph } from \"./tools/graph.js\";\n\n/**\n * Build the MCP server.\n *\n * `version` is passed in rather than hardcoded: a literal here advertised\n * `0.4.0` from every prerelease build, so every MCP client logged a version\n * that was never published. The CLI owns the real number and hands it over.\n */\nexport function createMcpServer(version = \"0.0.0-unknown\"): McpServer {\n const server = new McpServer({\n name: \"specdx\",\n version,\n });\n\n server.tool(\n \"sdx_validate\",\n \"Validate the spec.config.yaml configuration file\",\n { configPath: z.string().optional().describe(\"Path to config directory\") },\n async (params) => ({\n content: [{ type: \"text\" as const, text: await handleValidate(params) }],\n }),\n );\n\n server.tool(\n \"sdx_lint\",\n \"Run lint rules against the spec suite\",\n {\n preset: z.string().optional().describe(\"Lint preset: minimal, recommended, strict\"),\n specPath: z.string().optional().describe(\"Lint a specific spec file\"),\n },\n async (params) => ({\n content: [{ type: \"text\" as const, text: await handleLint(params) }],\n }),\n );\n\n server.tool(\n \"sdx_pack\",\n \"Pack spec context for LLM consumption within a token budget\",\n {\n task: z.string().optional().describe(\"Task description for relevance scoring\"),\n format: z.string().optional().describe(\"Output format: xml, markdown, json\"),\n budget: z.number().optional().describe(\"Token budget (default: 12000)\"),\n },\n async (params) => ({\n content: [{ type: \"text\" as const, text: await handlePack(params) }],\n }),\n );\n\n server.tool(\n \"sdx_status\",\n \"Get spec suite health overview (lint health, staleness, integrity)\",\n {},\n async () => ({\n content: [{ type: \"text\" as const, text: await handleStatus() }],\n }),\n );\n\n server.tool(\n \"sdx_check\",\n \"Run spec-to-implementation drift analysis\",\n {\n framework: z.string().optional().describe(\"Framework: express, hono, nextjs\"),\n specId: z.string().optional().describe(\"Check a specific spec by ID\"),\n },\n async (params) => ({\n content: [{ type: \"text\" as const, text: await handleCheck(params) }],\n }),\n );\n\n server.tool(\n \"sdx_diff\",\n \"Show spec changes and downstream impact between git refs\",\n {\n base: z.string().optional().describe(\"Base git ref (default: main)\"),\n head: z.string().optional().describe(\"Head git ref (default: HEAD)\"),\n working: z\n .boolean()\n .optional()\n .describe(\n \"Compare the base ref against the working tree, including uncommitted and untracked specs (default: false)\",\n ),\n },\n async (params) => ({\n content: [{ type: \"text\" as const, text: await handleDiff(params) }],\n }),\n );\n\n server.tool(\n \"sdx_graph\",\n \"Get the spec dependency graph\",\n {\n format: z.string().optional().describe(\"Output format: json (default) or dot\"),\n },\n async (params) => ({\n content: [{ type: \"text\" as const, text: await handleGraph(params) }],\n }),\n );\n\n return server;\n}\n","import { loadConfig, buildGraph, resolveGlob, ConfigError, GraphError } from \"@specdx/core\";\n\nexport async function handleValidate(params: { configPath?: string }): Promise<string> {\n try {\n const configDir = params.configPath ?? process.cwd();\n const config = await loadConfig(undefined, configDir);\n // A cyclic or dangling requires chain is an invalid config (issue #13).\n buildGraph(config);\n // `specEntries` and `specFiles` are distinct: one glob entry can resolve to\n // many files. Reporting either as a bare `specCount` put this tool and\n // sdx_status in direct contradiction for the same project.\n let specFiles = 0;\n for (const entry of Object.values(config.specs)) {\n specFiles += (await resolveGlob(entry.path, configDir)).length;\n }\n\n return JSON.stringify({\n valid: true,\n specEntries: Object.keys(config.specs).length,\n specFiles,\n project: config.project?.name ?? \"unknown\",\n });\n } catch (err) {\n if (err instanceof ConfigError) {\n return JSON.stringify({ valid: false, error: err.message, details: err.errors });\n }\n if (err instanceof GraphError) {\n return JSON.stringify({ valid: false, error: err.message });\n }\n throw err;\n }\n}\n","import { loadConfig, parseSpec, resolveGlob, buildGraph } from \"@specdx/core\";\nimport { createLintEngine, getPreset } from \"@specdx/lint\";\nimport type { ParsedSpec } from \"@specdx/core\";\n\nexport async function handleLint(params: { preset?: string; specPath?: string }): Promise<string> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n const preset = params.preset ?? config.lint?.extends ?? \"recommended\";\n const rules = getPreset(preset);\n\n const specs: ParsedSpec[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const files = await resolveGlob(entry.path, configDir);\n for (const file of files) {\n if (params.specPath && !file.includes(params.specPath)) continue;\n specs.push(await parseSpec(file));\n }\n }\n\n let graph;\n try {\n graph = buildGraph(config);\n } catch {\n // non-fatal\n }\n\n const engine = createLintEngine({ rules, config, graph });\n const results = engine.lint(specs);\n\n return JSON.stringify({\n diagnostics: results.diagnostics,\n hasErrors: results.hasErrors,\n hasWarnings: results.hasWarnings,\n specsChecked: specs.length,\n });\n}\n","import { loadConfig, parseSpec, resolveGlob, buildGraph } from \"@specdx/core\";\nimport { pack } from \"@specdx/pack\";\nimport type { ParsedSpec } from \"@specdx/core\";\n\nexport async function handlePack(params: {\n task?: string;\n format?: string;\n budget?: number;\n}): Promise<string> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n const allSpecs: ParsedSpec[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const files = await resolveGlob(entry.path, configDir);\n for (const file of files) {\n allSpecs.push(await parseSpec(file));\n }\n }\n\n let graph;\n try {\n graph = buildGraph(config);\n } catch {\n // non-fatal\n }\n\n const result = pack(\n allSpecs,\n {\n task: params.task,\n budget: params.budget,\n format: (params.format as \"xml\" | \"markdown\" | \"json\") ?? undefined,\n },\n config.pack,\n graph,\n );\n\n return result.output;\n}\n","import { loadConfig, parseSpec, resolveGlob, buildGraph } from \"@specdx/core\";\nimport { createLintEngine, getPreset } from \"@specdx/lint\";\nimport { DEFAULT_DIFF_CONFIG } from \"@specdx/diff\";\nimport type { ParsedSpec } from \"@specdx/core\";\n\nexport async function handleStatus(): Promise<string> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n const specs: { spec: ParsedSpec; entry: { path: string; owner?: string } }[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const paths = await resolveGlob(entry.path, configDir);\n for (const p of paths) {\n const spec = await parseSpec(p);\n specs.push({ spec, entry: entry as { path: string; owner?: string } });\n }\n }\n\n const byStatus: Record<string, number> = {};\n for (const { spec } of specs) {\n const status = (spec.frontmatter.status as string) || \"unknown\";\n byStatus[status] = (byStatus[status] ?? 0) + 1;\n }\n\n const presetName = config.lint?.extends ?? \"recommended\";\n const rules = getPreset(presetName);\n\n let graph;\n let graphError: string | undefined;\n try {\n graph = buildGraph(config);\n } catch (err) {\n graphError = (err as Error).message;\n }\n\n const engine = createLintEngine({ rules, config, graph });\n const lintResults = engine.lint(specs.map((s) => s.spec));\n\n const errors = lintResults.diagnostics.filter((d) => d.severity === \"error\").length;\n const warnings = lintResults.diagnostics.filter((d) => d.severity === \"warn\").length;\n\n const thresholdDays =\n config.diff?.staleness_threshold_days ?? DEFAULT_DIFF_CONFIG.staleness_threshold_days;\n const now = Date.now();\n const staleSpecs: { specId: string; daysSinceUpdate: number; owner?: string }[] = [];\n for (const { spec, entry } of specs) {\n const dateStr =\n (spec.frontmatter.updated as string | undefined) ||\n (spec.frontmatter.created as string | undefined);\n if (dateStr) {\n const days = Math.floor((now - new Date(dateStr).getTime()) / (1000 * 60 * 60 * 24));\n if (days > thresholdDays) {\n staleSpecs.push({\n specId: spec.frontmatter.id as string,\n daysSinceUpdate: days,\n owner: entry.owner,\n });\n }\n }\n }\n\n // An empty suite is unassessed, never a vacuous \"healthy\" (vacuous-pass audit)\n let verdict: \"healthy\" | \"warnings\" | \"errors\" | \"unassessed\" = \"healthy\";\n if (errors > 0 || graphError) verdict = \"errors\";\n else if (warnings > 0 || staleSpecs.length > 0) verdict = \"warnings\";\n else if (specs.length === 0) verdict = \"unassessed\";\n\n return JSON.stringify({\n project: config.project?.name ?? \"unknown\",\n // `specFiles` only. A second field named `specCount` gives a consumer no\n // way to know whether it counts config entries or resolved files -- the\n // ambiguity `sdx_validate` was already cleaned up to avoid.\n specFiles: specs.length,\n byStatus,\n lintHealth: { errors, warnings, passing: specs.length - errors },\n staleSpecs,\n integrityIssues: graphError ? [graphError] : [],\n verdict,\n });\n}\n","import { loadConfig, parseSpec, resolveGlob } from \"@specdx/core\";\nimport { runCheck } from \"@specdx/check\";\nimport type { ParsedSpec } from \"@specdx/core\";\n\nexport async function handleCheck(params: {\n framework?: string;\n specId?: string;\n}): Promise<string> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n const specs: ParsedSpec[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const paths = await resolveGlob(entry.path, configDir);\n for (const p of paths) {\n const spec = await parseSpec(p);\n if (params.specId && spec.frontmatter.id !== params.specId) continue;\n specs.push(spec);\n }\n }\n\n const checkConfig = {\n ...config.check,\n ...(params.framework ? { framework: params.framework as \"express\" | \"hono\" | \"nextjs\" } : {}),\n };\n\n const result = await runCheck(specs, configDir, checkConfig);\n return JSON.stringify(result);\n}\n","import { join } from \"node:path\";\nimport { loadConfig } from \"@specdx/core\";\nimport { diffBetweenRefs, DEFAULT_DIFF_CONFIG, DiffError } from \"@specdx/diff\";\n\nexport async function handleDiff(params: {\n base?: string;\n head?: string;\n working?: boolean;\n}): Promise<string> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n const baseRef = params.base ?? config.diff?.baseline_ref ?? DEFAULT_DIFF_CONFIG.baseline_ref;\n const headRef = params.head ?? \"HEAD\";\n const configPath = join(configDir, \"spec.config.yaml\");\n\n try {\n const result = await diffBetweenRefs(configPath, baseRef, headRef, {\n working: params.working ?? false,\n });\n return JSON.stringify(result);\n } catch (err) {\n if (err instanceof DiffError) {\n return JSON.stringify({ error: err.message });\n }\n throw err;\n }\n}\n","import {\n loadConfig,\n buildGraph,\n GraphError,\n parseSpec,\n resolveGlob,\n collectReferenceEdges,\n findUnreflectedReferences,\n} from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\n\nexport async function handleGraph(params: { format?: string }): Promise<string> {\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n try {\n const graph = buildGraph(config);\n const sorted = graph.topologicalSort();\n\n const idToEntry = new Map<string, string>();\n const specs: ParsedSpec[] = [];\n for (const [key, entry] of Object.entries(config.specs)) {\n const paths = await resolveGlob(entry.path, configDir);\n for (const p of paths) {\n const spec = await parseSpec(p);\n specs.push(spec);\n if (typeof spec.frontmatter.id === \"string\") {\n idToEntry.set(spec.frontmatter.id, key);\n }\n }\n }\n const referenceEdges = collectReferenceEdges(specs);\n const unreflectedReferences = findUnreflectedReferences(referenceEdges, idToEntry, graph);\n\n if (params.format === \"dot\") {\n const lines = [\"digraph specs {\"];\n for (const edge of graph.edges) lines.push(` \"${edge.from}\" -> \"${edge.to}\";`);\n for (const ref of referenceEdges) {\n lines.push(\n ` \"${ref.fromId}\" -> \"${ref.toId}\" [style=dashed, label=\"${ref.relationship}\"];`,\n );\n }\n lines.push(\"}\");\n return lines.join(\"\\n\");\n }\n\n return JSON.stringify({\n nodes: sorted,\n edges: graph.edges,\n downstream: Object.fromEntries(sorted.map((n) => [n, graph.getDownstream(n)])),\n referenceEdges,\n unreflectedReferences,\n });\n } catch (err) {\n if (err instanceof GraphError) {\n return JSON.stringify({ error: err.message });\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,SAAS;;;ACClB,eAAsB,eAAe,QAA+B;AAClE,MAAI;AACF,UAAM,YAAY,OAAO,cAAc,QAAQ,IAAG;AAClD,UAAM,SAAS,MAAM,WAAW,QAAW,SAAS;AAEpD,eAAW,MAAM;AAIjB,QAAI,YAAY;AAChB,eAAW,SAAS,OAAO,OAAO,OAAO,KAAK,GAAG;AAC/C,oBAAc,MAAM,YAAY,MAAM,MAAM,SAAS,GAAG;IAC1D;AAEA,WAAO,KAAK,UAAU;MACpB,OAAO;MACP,aAAa,OAAO,KAAK,OAAO,KAAK,EAAE;MACvC;MACA,SAAS,OAAO,SAAS,QAAQ;KAClC;EACH,SAAS,KAAK;AACZ,QAAI,eAAe,aAAa;AAC9B,aAAO,KAAK,UAAU,EAAE,OAAO,OAAO,OAAO,IAAI,SAAS,SAAS,IAAI,OAAM,CAAE;IACjF;AACA,QAAI,eAAe,YAAY;AAC7B,aAAO,KAAK,UAAU,EAAE,OAAO,OAAO,OAAO,IAAI,QAAO,CAAE;IAC5D;AACA,UAAM;EACR;AACF;;;AC3BA,eAAsB,WAAW,QAA8C;AAC7E,QAAM,YAAY,QAAQ,IAAG;AAC7B,QAAM,SAAS,MAAM,WAAW,QAAW,SAAS;AACpD,QAAM,SAAS,OAAO,UAAU,OAAO,MAAM,WAAW;AACxD,QAAM,QAAQ,UAAU,MAAM;AAE9B,QAAM,QAAsB,CAAA;AAC5B,aAAW,CAAC,EAAE,KAAK,KAAK,OAAO,QAAQ,OAAO,KAAK,GAAG;AACpD,UAAM,QAAQ,MAAM,YAAY,MAAM,MAAM,SAAS;AACrD,eAAW,QAAQ,OAAO;AACxB,UAAI,OAAO,YAAY,CAAC,KA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AM,EAAE,OAAM,EAAG,SAAQ,EAAG,SAAS,8BAA8B;IACnE,MAAM,EAAE,OAAM,EAAG,SAAQ,EAAG,SAAS,8BAA8B;IACnE,SAAS,EACN,QAAO,EACP,SAAQ,EACR,SACC,2GAA2G;KAGjH,OAAO,YAAY;IACjB,SAAS,CAAC,EAAE,MAAM,QAAiB,MAAM,MAAM,WAAW,MAAM,EAAC,CAAE;IACnE;AAGJ,SAAO,KACL,aACA,iCACA;IACE,QAAQ,EAAE,OAAM,EAAG,SAAQ,EAAG,SAAS,sCAAsC;KAE/E,OAAO,YAAY;IACjB,SAAS,CAAC,EAAE,MAAM,QAAiB,MAAM,MAAM,YAAY,MAAM,EAAC,CAAE;IACpE;AAGJ,SAAO;AACT;","names":[]}
@@ -0,0 +1,16 @@
1
+ import {
2
+ analyzeWithAi,
3
+ checkArtifacts,
4
+ detectFramework,
5
+ parseArtifacts,
6
+ runCheck
7
+ } from "./chunk-ZB5R5SK5.js";
8
+ import "./chunk-5WRI5ZAA.js";
9
+ export {
10
+ analyzeWithAi,
11
+ checkArtifacts,
12
+ detectFramework,
13
+ parseArtifacts,
14
+ runCheck
15
+ };
16
+ //# sourceMappingURL=dist-RT3MTIUW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,21 @@
1
+ import {
2
+ labelled
3
+ } from "./chunk-FBMYBYFB.js";
4
+ import "./chunk-ZIPGRLYE.js";
5
+ import "./chunk-5WRI5ZAA.js";
6
+
7
+ // src/commands/core/generate.ts
8
+ import { defineCommand } from "citty";
9
+ var generate_default = defineCommand({
10
+ meta: { name: "generate", description: "Generate spec stubs from existing specs" },
11
+ subCommands: {
12
+ story: () => import("./generate-story-CJMV2F5K.js").then((m) => labelled("generate story", m.default)),
13
+ "test-plan": () => import("./generate-test-plan-XBAFJKJI.js").then(
14
+ (m) => labelled("generate test-plan", m.default)
15
+ )
16
+ }
17
+ });
18
+ export {
19
+ generate_default as default
20
+ };
21
+ //# sourceMappingURL=generate-5VO6M4PB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/core/generate.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { labelled } from \"../registry.js\";\n\nexport default defineCommand({\n meta: { name: \"generate\", description: \"Generate spec stubs from existing specs\" },\n subCommands: {\n story: () => import(\"./generate-story.js\").then((m) => labelled(\"generate story\", m.default)),\n \"test-plan\": () =>\n import(\"../experimental/generate-test-plan.js\").then((m) =>\n labelled(\"generate test-plan\", m.default),\n ),\n },\n});\n"],"mappings":";;;;;;;AAAA,SAAS,qBAAqB;AAG9B,IAAO,mBAAQ,cAAc;AAAA,EAC3B,MAAM,EAAE,MAAM,YAAY,aAAa,0CAA0C;AAAA,EACjF,aAAa;AAAA,IACX,OAAO,MAAM,OAAO,8BAAqB,EAAE,KAAK,CAAC,MAAM,SAAS,kBAAkB,EAAE,OAAO,CAAC;AAAA,IAC5F,aAAa,MACX,OAAO,kCAAuC,EAAE;AAAA,MAAK,CAAC,MACpD,SAAS,sBAAsB,EAAE,OAAO;AAAA,IAC1C;AAAA,EACJ;AACF,CAAC;","names":[]}
@@ -1,19 +1,28 @@
1
+ import {
2
+ parseFeatureEntries,
3
+ uncoveredFeatures
4
+ } from "./chunk-UZKOJL2N.js";
1
5
  import {
2
6
  createLogger,
3
7
  loadConfig,
4
8
  parseSpec,
5
9
  resolveGlob
6
- } from "./chunk-FZWT4HVX.js";
10
+ } from "./chunk-MM325DR6.js";
7
11
  import {
8
12
  REQUIRED_SECTIONS
9
- } from "./chunk-YDU26YTH.js";
13
+ } from "./chunk-ZIPGRLYE.js";
14
+ import "./chunk-5WRI5ZAA.js";
10
15
 
11
- // src/commands/generate-story.ts
16
+ // src/commands/core/generate-story.ts
12
17
  import { defineCommand } from "citty";
13
18
  import { writeFile, mkdir } from "fs/promises";
14
19
  import { join } from "path";
15
20
  function slugify(text) {
16
- return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
21
+ const slug = text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
22
+ if (slug.length <= 40) return slug;
23
+ const cut = slug.slice(0, 40);
24
+ const lastHyphen = cut.lastIndexOf("-");
25
+ return lastHyphen > 0 ? cut.slice(0, lastHyphen) : cut;
17
26
  }
18
27
  function detectStoriesDir(configDir, config) {
19
28
  for (const entry of Object.values(config.specs)) {
@@ -97,26 +106,38 @@ async function generateStories(options) {
97
106
  throw new Error(`No spec with id "${from}" found in config.`);
98
107
  }
99
108
  const prd = await parseSpec(prdFilePath);
100
- const featuresSection = prd.parsedSections.find((s) => s.heading === "Features");
101
- if (!featuresSection) {
102
- return { generated: [] };
103
- }
104
- const featureRegex = /\*\*F(\d+)\*\*:\s*(.+)/g;
105
- const features = [];
106
- let match;
107
- while ((match = featureRegex.exec(featuresSection.content)) !== null) {
108
- features.push({ num: match[1], text: match[2] });
109
- }
109
+ const entries = parseFeatureEntries(prd.content);
110
+ const features = entries.map((entry, i) => ({
111
+ // Un-numbered features still need a stable filename, so fall back to
112
+ // position. Authors who do use `**F<N>**:` keep their numbering.
113
+ num: entry.num ?? String(i + 1),
114
+ text: entry.text
115
+ }));
110
116
  if (features.length === 0) {
111
- return { generated: [] };
117
+ return { generated: [], skipped: [] };
112
118
  }
113
119
  const storiesDir = outDir ?? detectStoriesDir(configDir, config);
114
120
  await mkdir(storiesDir, { recursive: true });
115
121
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
116
122
  const prdAuthors = prd.frontmatter.authors ?? [];
117
123
  const sections = REQUIRED_SECTIONS["user-story"];
124
+ const existingStories = [];
125
+ for (const entry of Object.values(config.specs)) {
126
+ if (entry.type !== "user-story") continue;
127
+ for (const p of await resolveGlob(entry.path, configDir)) {
128
+ existingStories.push(await parseSpec(p));
129
+ }
130
+ }
131
+ const uncovered = new Set(
132
+ uncoveredFeatures(
133
+ features.map((f) => f.text),
134
+ existingStories,
135
+ from
136
+ )
137
+ );
138
+ const skipped = features.filter((f) => !uncovered.has(f.text)).map((f) => f.text);
118
139
  const generated = [];
119
- for (const feature of features) {
140
+ for (const feature of features.filter((f) => uncovered.has(f.text))) {
120
141
  const slug = slugify(feature.text);
121
142
  const filename = `story-f${feature.num}-${slug}.md`;
122
143
  const filePath = join(storiesDir, filename);
@@ -131,11 +152,11 @@ async function generateStories(options) {
131
152
  await writeFile(filePath, content, "utf-8");
132
153
  generated.push(filePath);
133
154
  }
134
- return { generated };
155
+ return { generated, skipped };
135
156
  }
136
157
  var defineCommandExport = defineCommand({
137
158
  meta: {
138
- name: "generate story",
159
+ name: "story",
139
160
  description: "Generate user story stub files from a PRD's Features section"
140
161
  },
141
162
  args: {
@@ -167,13 +188,20 @@ var defineCommandExport = defineCommand({
167
188
  from: args.from,
168
189
  outDir: args.out
169
190
  });
170
- if (result.generated.length === 0) {
191
+ if (result.generated.length === 0 && result.skipped.length > 0) {
192
+ logger.info(
193
+ `Every feature already has a story \u2014 ${result.skipped.length} feature(s) skipped, nothing generated.`
194
+ );
195
+ } else if (result.generated.length === 0) {
171
196
  logger.info("No features found in PRD \u2014 no story stubs generated.");
172
197
  } else {
173
198
  logger.info(`Generated ${result.generated.length} story stub(s):`);
174
199
  for (const filePath of result.generated) {
175
200
  logger.info(` ${filePath}`);
176
201
  }
202
+ if (result.skipped.length > 0) {
203
+ logger.info(`Skipped ${result.skipped.length} feature(s) an existing story covers.`);
204
+ }
177
205
  }
178
206
  } catch (err) {
179
207
  console.error(`
@@ -189,4 +217,4 @@ export {
189
217
  defineCommandExport,
190
218
  generateStories
191
219
  };
192
- //# sourceMappingURL=generate-story-AOALIKSD.js.map
220
+ //# sourceMappingURL=generate-story-CJMV2F5K.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/core/generate-story.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { writeFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { loadConfig, parseSpec, resolveGlob, createLogger } from \"@specdx/core\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { REQUIRED_SECTIONS } from \"@specdx/schema\";\nimport { uncoveredFeatures, parseFeatureEntries } from \"@specdx/lint\";\n\nexport interface GenerateStoriesOptions {\n configDir: string;\n from: string;\n outDir?: string;\n}\n\nexport interface GenerateStoriesResult {\n generated: string[];\n /** Features left alone because an existing story already covers them. */\n skipped: string[];\n}\n\nfunction slugify(text: string): string {\n const slug = text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n if (slug.length <= 40) return slug;\n // Truncate on a word boundary so filenames don't end mid-word\n const cut = slug.slice(0, 40);\n const lastHyphen = cut.lastIndexOf(\"-\");\n return lastHyphen > 0 ? cut.slice(0, lastHyphen) : cut;\n}\n\nfunction detectStoriesDir(\n configDir: string,\n config: Awaited<ReturnType<typeof loadConfig>>,\n): string {\n for (const entry of Object.values(config.specs)) {\n if (entry.type === \"user-story\") {\n // Use the directory portion of the glob path\n const dirPart = entry.path.replace(/\\/[^/]*\\*.*$/, \"\").replace(/\\/[^/]*$/, \"\");\n // If path ends with *.md at a directory level, take that dir\n const match = entry.path.match(/^(.+?)\\/\\*/);\n if (match) {\n return join(configDir, match[1]!);\n }\n return join(configDir, dirPart);\n }\n }\n return join(configDir, \"specs/stories\");\n}\n\nfunction buildStoryFile(options: {\n featureNum: string;\n featureText: string;\n prdId: string;\n prdAuthors: string[];\n today: string;\n sections: string[];\n}): string {\n const { featureNum, featureText, prdId, prdAuthors, today, sections } = options;\n const storyId = `story-f${featureNum}`;\n const title = featureText.trim();\n const authorsYaml = JSON.stringify(prdAuthors);\n\n const frontmatter = [\n \"---\",\n `id: \"${storyId}\"`,\n `type: \"user-story\"`,\n `title: \"${title}\"`,\n `status: \"draft\"`,\n `version: \"0.1\"`,\n `created: \"${today}\"`,\n `authors: ${authorsYaml}`,\n `story_id: \"${storyId}\"`,\n `priority: \"medium\"`,\n `estimate: \"TBD\"`,\n `references:`,\n ` - id: \"${prdId}\"`,\n ` relationship: \"decomposed-into\"`,\n \"---\",\n ].join(\"\\n\");\n\n const bodyParts = sections.map((section) => {\n if (section === \"Description\") {\n return `\\n## ${section}\\n\\n${featureText.trim()}`;\n }\n if (section === \"Acceptance Criteria\") {\n return `\\n## ${section}\\n\\n- [ ] <!-- acceptance criterion -->`;\n }\n if (section === \"Dependencies\") {\n return `\\n## ${section}\\n\\nF${featureNum} from ${prdId}`;\n }\n return `\\n## ${section}\\n\\n<!-- placeholder -->`;\n });\n\n return `${frontmatter}\\n${bodyParts.join(\"\\n\")}\\n`;\n}\n\nexport async function generateStories(\n options: GenerateStoriesOptions,\n): Promise<GenerateStoriesResult> {\n const { configDir, from, outDir } = options;\n const config = await loadConfig(undefined, configDir);\n\n // Find the PRD spec file by ID\n let prdFilePath: string | undefined;\n for (const entry of Object.values(config.specs)) {\n const files = await resolveGlob(entry.path, configDir);\n for (const file of files) {\n const parsed = await parseSpec(file);\n if (parsed.frontmatter.id === from) {\n prdFilePath = file;\n break;\n }\n }\n if (prdFilePath) break;\n }\n\n if (!prdFilePath) {\n throw new Error(`No spec with id \"${from}\" found in config.`);\n }\n\n const prd = await parseSpec(prdFilePath);\n\n // The same parser the lint rule and `ready` use. Carrying a second one here\n // meant this command reported \"no features found\" for a PRD that lint was\n // simultaneously reporting three features in.\n const entries = parseFeatureEntries(prd.content);\n const features = entries.map((entry, i) => ({\n // Un-numbered features still need a stable filename, so fall back to\n // position. Authors who do use `**F<N>**:` keep their numbering.\n num: entry.num ?? String(i + 1),\n text: entry.text,\n }));\n\n if (features.length === 0) {\n return { generated: [], skipped: [] };\n }\n\n const storiesDir = outDir ?? detectStoriesDir(configDir, config);\n await mkdir(storiesDir, { recursive: true });\n\n const today = new Date().toISOString().slice(0, 10);\n const prdAuthors = (prd.frontmatter.authors as string[] | undefined) ?? [];\n const sections = REQUIRED_SECTIONS[\"user-story\"];\n\n // Features an existing story already covers are left alone -- regenerating\n // them produces a second stub for the same feature to reconcile by hand.\n const existingStories: ParsedSpec[] = [];\n for (const entry of Object.values(config.specs)) {\n if (entry.type !== \"user-story\") continue;\n for (const p of await resolveGlob(entry.path, configDir)) {\n existingStories.push(await parseSpec(p));\n }\n }\n const uncovered = new Set(\n uncoveredFeatures(\n features.map((f) => f.text),\n existingStories,\n from,\n ),\n );\n const skipped = features.filter((f) => !uncovered.has(f.text)).map((f) => f.text);\n\n const generated: string[] = [];\n\n for (const feature of features.filter((f) => uncovered.has(f.text))) {\n const slug = slugify(feature.text);\n const filename = `story-f${feature.num}-${slug}.md`;\n const filePath = join(storiesDir, filename);\n\n const content = buildStoryFile({\n featureNum: feature.num,\n featureText: feature.text,\n prdId: from,\n prdAuthors,\n today,\n sections,\n });\n\n await writeFile(filePath, content, \"utf-8\");\n generated.push(filePath);\n }\n\n return { generated, skipped };\n}\n\nexport const defineCommandExport = defineCommand({\n meta: {\n name: \"story\",\n description: \"Generate user story stub files from a PRD's Features section\",\n },\n args: {\n from: {\n type: \"string\",\n description: \"Spec ID of the PRD to generate stories from\",\n required: true,\n },\n out: {\n type: \"string\",\n description: \"Output directory for story files (default: auto-detected from config)\",\n },\n quiet: {\n type: \"boolean\",\n description: \"Suppress output\",\n default: false,\n },\n verbose: {\n type: \"boolean\",\n description: \"Verbose output\",\n default: false,\n },\n },\n async run({ args }) {\n const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });\n\n try {\n const result = await generateStories({\n configDir: process.cwd(),\n from: args.from,\n outDir: args.out,\n });\n\n if (result.generated.length === 0 && result.skipped.length > 0) {\n logger.info(\n `Every feature already has a story — ${result.skipped.length} feature(s) skipped, nothing generated.`,\n );\n } else if (result.generated.length === 0) {\n logger.info(\"No features found in PRD — no story stubs generated.\");\n } else {\n logger.info(`Generated ${result.generated.length} story stub(s):`);\n for (const filePath of result.generated) {\n logger.info(` ${filePath}`);\n }\n if (result.skipped.length > 0) {\n logger.info(`Skipped ${result.skipped.length} feature(s) an existing story covers.`);\n }\n }\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n\nexport default defineCommandExport;\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,WAAW,aAAa;AACjC,SAAS,YAAY;AAkBrB,SAAS,QAAQ,MAAsB;AACrC,QAAM,OAAO,KACV,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,EAAE;AACzB,MAAI,KAAK,UAAU,GAAI,QAAO;AAE9B,QAAM,MAAM,KAAK,MAAM,GAAG,EAAE;AAC5B,QAAM,aAAa,IAAI,YAAY,GAAG;AACtC,SAAO,aAAa,IAAI,IAAI,MAAM,GAAG,UAAU,IAAI;AACrD;AAEA,SAAS,iBACP,WACA,QACQ;AACR,aAAW,SAAS,OAAO,OAAO,OAAO,KAAK,GAAG;AAC/C,QAAI,MAAM,SAAS,cAAc;AAE/B,YAAM,UAAU,MAAM,KAAK,QAAQ,gBAAgB,EAAE,EAAE,QAAQ,YAAY,EAAE;AAE7E,YAAM,QAAQ,MAAM,KAAK,MAAM,YAAY;AAC3C,UAAI,OAAO;AACT,eAAO,KAAK,WAAW,MAAM,CAAC,CAAE;AAAA,MAClC;AACA,aAAO,KAAK,WAAW,OAAO;AAAA,IAChC;AAAA,EACF;AACA,SAAO,KAAK,WAAW,eAAe;AACxC;AAEA,SAAS,eAAe,SAOb;AACT,QAAM,EAAE,YAAY,aAAa,OAAO,YAAY,OAAO,SAAS,IAAI;AACxE,QAAM,UAAU,UAAU,UAAU;AACpC,QAAM,QAAQ,YAAY,KAAK;AAC/B,QAAM,cAAc,KAAK,UAAU,UAAU;AAE7C,QAAM,cAAc;AAAA,IAClB;AAAA,IACA,QAAQ,OAAO;AAAA,IACf;AAAA,IACA,WAAW,KAAK;AAAA,IAChB;AAAA,IACA;AAAA,IACA,aAAa,KAAK;AAAA,IAClB,YAAY,WAAW;AAAA,IACvB,cAAc,O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