specdx 0.4.0-alpha.9 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +7 -2
- package/README.md +283 -0
- package/dist/{check-4FSSC6HN.js → check-RH5SCXWW.js} +68 -30
- package/dist/check-RH5SCXWW.js.map +1 -0
- package/dist/{chunk-N77RNV7J.js → chunk-3YXRWQGX.js} +217 -42
- package/dist/chunk-3YXRWQGX.js.map +1 -0
- package/dist/chunk-5WRI5ZAA.js +31 -0
- package/dist/chunk-6EQIDZ4D.js +185 -0
- package/dist/chunk-6EQIDZ4D.js.map +1 -0
- package/dist/chunk-6WFNZH7F.js +2846 -0
- package/dist/chunk-6WFNZH7F.js.map +1 -0
- package/dist/{chunk-AKNPCB37.js → chunk-BMOOLUPG.js} +32 -12
- package/dist/chunk-BMOOLUPG.js.map +1 -0
- package/dist/{chunk-IHTYAW7C.js → chunk-BP3SB35W.js} +111 -7
- package/dist/chunk-BP3SB35W.js.map +1 -0
- package/dist/chunk-CQETLJTZ.js +103 -0
- package/dist/chunk-CQETLJTZ.js.map +1 -0
- package/dist/chunk-DMGABJ6T.js +41 -0
- package/dist/chunk-DMGABJ6T.js.map +1 -0
- package/dist/chunk-NHD44ZYN.js +20 -0
- package/dist/chunk-NHD44ZYN.js.map +1 -0
- package/dist/{chunk-7JXW2GTJ.js → chunk-XRWLPU24.js} +18 -2
- package/dist/chunk-XRWLPU24.js.map +1 -0
- package/dist/chunk-ZIODMXST.js +1146 -0
- package/dist/chunk-ZIODMXST.js.map +1 -0
- package/dist/diff-QO7HMAK3.js +200 -0
- package/dist/diff-QO7HMAK3.js.map +1 -0
- package/dist/{dist-4DIRTBJH.js → dist-JPWHWMV2.js} +88 -26
- package/dist/dist-JPWHWMV2.js.map +1 -0
- package/dist/{dist-RL2DT3ZE.js → dist-ROHCFKYT.js} +3 -2
- package/dist/dist-ROHCFKYT.js.map +1 -0
- package/dist/generate-MS4BM7RU.js +21 -0
- package/dist/generate-MS4BM7RU.js.map +1 -0
- package/dist/{generate-story-EFHGINHA.js → generate-story-OMM322L7.js} +43 -19
- package/dist/generate-story-OMM322L7.js.map +1 -0
- package/dist/{generate-test-plan-BO7444RG.js → generate-test-plan-75W7SZIO.js} +61 -11
- package/dist/generate-test-plan-75W7SZIO.js.map +1 -0
- package/dist/{graph-5XINV7PT.js → graph-QOTMXENE.js} +49 -11
- package/dist/graph-QOTMXENE.js.map +1 -0
- package/dist/index.d.ts +302 -0
- package/dist/index.js +2996 -357
- package/dist/index.js.map +1 -1
- package/dist/lint-LPFLHVO4.js +184 -0
- package/dist/lint-LPFLHVO4.js.map +1 -0
- package/dist/main.js +10 -229
- package/dist/main.js.map +1 -1
- package/dist/mcp-OEC43SPF.js +35 -0
- package/dist/mcp-OEC43SPF.js.map +1 -0
- package/dist/{migrate-4KF6GHLO.js → migrate-CBP2AVLH.js} +21 -9
- package/dist/migrate-CBP2AVLH.js.map +1 -0
- package/dist/{pack-DSOODXAN.js → pack-X6FSWORJ.js} +41 -13
- package/dist/pack-X6FSWORJ.js.map +1 -0
- package/dist/{ready-6DNKIHP6.js → ready-7MJWRGLT.js} +55 -14
- package/dist/ready-7MJWRGLT.js.map +1 -0
- package/dist/skills/{specdx-author-spec.md → core/specdx-author-spec/SKILL.md} +10 -6
- package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-01-frontmatter.md +1 -1
- package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-02-sections.md +41 -0
- package/dist/skills/{specdx-onboard.md → core/specdx-onboard/SKILL.md} +8 -3
- package/dist/skills/{specdx-plan-from-spec.md → core/specdx-plan-from-spec/SKILL.md} +5 -1
- package/dist/skills/{specdx-pre-commit.md → core/specdx-pre-commit/SKILL.md} +16 -2
- package/dist/skills/{specdx-review-spec.md → core/specdx-review-spec/SKILL.md} +5 -1
- package/dist/skills/core/specdx-router/SKILL.md +67 -0
- package/dist/skills/{specdx-sprint-review.md → core/specdx-sprint-review/SKILL.md} +6 -2
- package/dist/skills/{specdx-start-task.md → core/specdx-start-task/SKILL.md} +5 -1
- package/dist/skills/{specdx-check-drift.md → experimental/specdx-check-drift/SKILL.md} +10 -4
- package/dist/skills/{specdx-verify.md → experimental/specdx-verify/SKILL.md} +6 -2
- package/dist/skills-36SRUEMR.js +121 -0
- package/dist/skills-36SRUEMR.js.map +1 -0
- package/dist/{status-WZK247CI.js → status-UUPZYX3J.js} +63 -32
- package/dist/status-UUPZYX3J.js.map +1 -0
- package/dist/{update-JTNSYX3B.js → update-EI7IJRHG.js} +22 -12
- package/dist/update-EI7IJRHG.js.map +1 -0
- package/dist/{validate-LBDYWUDX.js → validate-HTTZLQWI.js} +36 -17
- package/dist/validate-HTTZLQWI.js.map +1 -0
- package/hooks/hooks.json +12 -6
- package/hooks/session-start +35 -3
- package/package.json +28 -13
- package/dist/changelog-XUVHY3QK.js +0 -93
- package/dist/changelog-XUVHY3QK.js.map +0 -1
- package/dist/check-4FSSC6HN.js.map +0 -1
- package/dist/chunk-7JXW2GTJ.js.map +0 -1
- package/dist/chunk-AKNPCB37.js.map +0 -1
- package/dist/chunk-DAZCOUVK.js +0 -496
- package/dist/chunk-DAZCOUVK.js.map +0 -1
- package/dist/chunk-GAM4MXPC.js +0 -15
- package/dist/chunk-GAM4MXPC.js.map +0 -1
- package/dist/chunk-IHTYAW7C.js.map +0 -1
- package/dist/chunk-N77RNV7J.js.map +0 -1
- package/dist/chunk-SRZ33RJP.js +0 -1147
- package/dist/chunk-SRZ33RJP.js.map +0 -1
- package/dist/diff-OXZ34NU4.js +0 -107
- package/dist/diff-OXZ34NU4.js.map +0 -1
- package/dist/dist-4DIRTBJH.js.map +0 -1
- package/dist/explain-QBV3AESQ.js +0 -109
- package/dist/explain-QBV3AESQ.js.map +0 -1
- package/dist/generate-7GNPT2WJ.js +0 -13
- package/dist/generate-7GNPT2WJ.js.map +0 -1
- package/dist/generate-story-EFHGINHA.js.map +0 -1
- package/dist/generate-test-plan-BO7444RG.js.map +0 -1
- package/dist/graph-5XINV7PT.js.map +0 -1
- package/dist/lint-PTMWMLDQ.js +0 -122
- package/dist/lint-PTMWMLDQ.js.map +0 -1
- package/dist/mcp-BGFAPM6G.js +0 -17
- package/dist/mcp-BGFAPM6G.js.map +0 -1
- package/dist/migrate-4KF6GHLO.js.map +0 -1
- package/dist/pack-DSOODXAN.js.map +0 -1
- package/dist/ready-6DNKIHP6.js.map +0 -1
- package/dist/skills-3GBBWZW2.js +0 -93
- package/dist/skills-3GBBWZW2.js.map +0 -1
- package/dist/status-WZK247CI.js.map +0 -1
- package/dist/update-JTNSYX3B.js.map +0 -1
- package/dist/validate-LBDYWUDX.js.map +0 -1
- /package/dist/{dist-RL2DT3ZE.js.map → chunk-5WRI5ZAA.js.map} +0 -0
- /package/dist/skills/{spec-type-reference.md → core/specdx-author-spec/references/spec-type-reference.md} +0 -0
- /package/dist/skills/{specdx-author-spec → core/specdx-author-spec/references}/step-03-finalize.md +0 -0
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
import {
|
|
2
2
|
runCheck
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-3YXRWQGX.js";
|
|
4
4
|
import {
|
|
5
5
|
pack
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-BMOOLUPG.js";
|
|
7
7
|
import {
|
|
8
8
|
createLintEngine,
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
lintAgentFiles,
|
|
10
|
+
resolveLintConfig
|
|
11
|
+
} from "./chunk-ZIODMXST.js";
|
|
11
12
|
import {
|
|
12
13
|
DEFAULT_DIFF_CONFIG,
|
|
13
14
|
DiffError,
|
|
14
15
|
diffBetweenRefs
|
|
15
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-6WFNZH7F.js";
|
|
16
17
|
import {
|
|
17
18
|
ConfigError,
|
|
18
19
|
GraphError,
|
|
@@ -22,8 +23,9 @@ import {
|
|
|
22
23
|
loadConfig,
|
|
23
24
|
parseSpec,
|
|
24
25
|
resolveGlob
|
|
25
|
-
} from "./chunk-
|
|
26
|
-
import "./chunk-
|
|
26
|
+
} from "./chunk-BP3SB35W.js";
|
|
27
|
+
import "./chunk-XRWLPU24.js";
|
|
28
|
+
import "./chunk-5WRI5ZAA.js";
|
|
27
29
|
|
|
28
30
|
// ../mcp/dist/server.js
|
|
29
31
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
@@ -35,9 +37,14 @@ async function handleValidate(params) {
|
|
|
35
37
|
const configDir = params.configPath ?? process.cwd();
|
|
36
38
|
const config = await loadConfig(void 0, configDir);
|
|
37
39
|
buildGraph(config);
|
|
40
|
+
let specFiles = 0;
|
|
41
|
+
for (const entry of Object.values(config.specs)) {
|
|
42
|
+
specFiles += (await resolveGlob(entry.path, configDir)).length;
|
|
43
|
+
}
|
|
38
44
|
return JSON.stringify({
|
|
39
45
|
valid: true,
|
|
40
|
-
|
|
46
|
+
specEntries: Object.keys(config.specs).length,
|
|
47
|
+
specFiles,
|
|
41
48
|
project: config.project?.name ?? "unknown"
|
|
42
49
|
});
|
|
43
50
|
} catch (err) {
|
|
@@ -56,13 +63,15 @@ async function handleLint(params) {
|
|
|
56
63
|
const configDir = process.cwd();
|
|
57
64
|
const config = await loadConfig(void 0, configDir);
|
|
58
65
|
const preset = params.preset ?? config.lint?.extends ?? "recommended";
|
|
59
|
-
const rules =
|
|
66
|
+
const { rules, ignore } = await resolveLintConfig({
|
|
67
|
+
config,
|
|
68
|
+
preset,
|
|
69
|
+
configDir
|
|
70
|
+
});
|
|
60
71
|
const specs = [];
|
|
61
72
|
for (const [, entry] of Object.entries(config.specs)) {
|
|
62
73
|
const files = await resolveGlob(entry.path, configDir);
|
|
63
74
|
for (const file of files) {
|
|
64
|
-
if (params.specPath && !file.includes(params.specPath))
|
|
65
|
-
continue;
|
|
66
75
|
specs.push(await parseSpec(file));
|
|
67
76
|
}
|
|
68
77
|
}
|
|
@@ -71,13 +80,52 @@ async function handleLint(params) {
|
|
|
71
80
|
graph = buildGraph(config);
|
|
72
81
|
} catch {
|
|
73
82
|
}
|
|
74
|
-
const engine = createLintEngine({ rules, config, graph });
|
|
83
|
+
const engine = createLintEngine({ rules, config, graph, ignore });
|
|
75
84
|
const results = engine.lint(specs);
|
|
85
|
+
const { specPath } = params;
|
|
86
|
+
const selects = (filePath) => specPath === void 0 || filePath.includes(specPath);
|
|
87
|
+
let diagnostics = results.diagnostics;
|
|
88
|
+
let { hasErrors, hasWarnings } = results;
|
|
89
|
+
if (specPath !== void 0) {
|
|
90
|
+
diagnostics = diagnostics.filter((d) => selects(d.filePath));
|
|
91
|
+
hasErrors = diagnostics.some((d) => d.severity === "error");
|
|
92
|
+
hasWarnings = diagnostics.some((d) => d.severity === "warn");
|
|
93
|
+
}
|
|
94
|
+
let agentFiles = 0;
|
|
95
|
+
if (config.agents) {
|
|
96
|
+
const agentResults = await lintAgentFiles({ config, configDir });
|
|
97
|
+
agentFiles = agentResults.filesLinted;
|
|
98
|
+
diagnostics = [...diagnostics];
|
|
99
|
+
if (!agentResults.assessed) {
|
|
100
|
+
const patterns = config.agents.paths ?? ["AGENTS.md", "CLAUDE.md"];
|
|
101
|
+
diagnostics.push({
|
|
102
|
+
ruleId: "agents/paths-match-nothing",
|
|
103
|
+
severity: "error",
|
|
104
|
+
message: `agents.paths matched no files (${patterns.join(", ")}), so no agent instruction file was linted. Remove the \`agents\` key or fix the paths.`,
|
|
105
|
+
filePath: "spec.config.yaml"
|
|
106
|
+
});
|
|
107
|
+
hasErrors = true;
|
|
108
|
+
}
|
|
109
|
+
for (const diagnostic of agentResults.diagnostics) {
|
|
110
|
+
if (!selects(diagnostic.filePath))
|
|
111
|
+
continue;
|
|
112
|
+
diagnostics.push(diagnostic);
|
|
113
|
+
if (diagnostic.severity === "error")
|
|
114
|
+
hasErrors = true;
|
|
115
|
+
if (diagnostic.severity === "warn")
|
|
116
|
+
hasWarnings = true;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const ignored = new Set(ignore);
|
|
120
|
+
const linted = specs.filter((spec) => !ignored.has(spec.filePath) && selects(spec.filePath));
|
|
76
121
|
return JSON.stringify({
|
|
77
|
-
diagnostics
|
|
78
|
-
hasErrors
|
|
79
|
-
hasWarnings
|
|
80
|
-
specsChecked:
|
|
122
|
+
diagnostics,
|
|
123
|
+
hasErrors,
|
|
124
|
+
hasWarnings,
|
|
125
|
+
specsChecked: linted.length,
|
|
126
|
+
// False when nothing was selected — "no diagnostics" is then not a pass.
|
|
127
|
+
assessed: linted.length > 0,
|
|
128
|
+
agentFilesChecked: agentFiles
|
|
81
129
|
});
|
|
82
130
|
}
|
|
83
131
|
|
|
@@ -123,7 +171,11 @@ async function handleStatus() {
|
|
|
123
171
|
byStatus[status] = (byStatus[status] ?? 0) + 1;
|
|
124
172
|
}
|
|
125
173
|
const presetName = config.lint?.extends ?? "recommended";
|
|
126
|
-
const rules =
|
|
174
|
+
const { rules, ignore } = await resolveLintConfig({
|
|
175
|
+
config,
|
|
176
|
+
preset: presetName,
|
|
177
|
+
configDir
|
|
178
|
+
});
|
|
127
179
|
let graph;
|
|
128
180
|
let graphError;
|
|
129
181
|
try {
|
|
@@ -131,10 +183,12 @@ async function handleStatus() {
|
|
|
131
183
|
} catch (err) {
|
|
132
184
|
graphError = err.message;
|
|
133
185
|
}
|
|
134
|
-
const engine = createLintEngine({ rules, config, graph });
|
|
186
|
+
const engine = createLintEngine({ rules, config, graph, ignore });
|
|
135
187
|
const lintResults = engine.lint(specs.map((s) => s.spec));
|
|
136
188
|
const errors = lintResults.diagnostics.filter((d) => d.severity === "error").length;
|
|
137
189
|
const warnings = lintResults.diagnostics.filter((d) => d.severity === "warn").length;
|
|
190
|
+
const specsWithErrors = new Set(lintResults.diagnostics.filter((d) => d.severity === "error").map((d) => d.filePath));
|
|
191
|
+
const passing = specs.filter(({ spec }) => !specsWithErrors.has(spec.filePath)).length;
|
|
138
192
|
const thresholdDays = config.diff?.staleness_threshold_days ?? DEFAULT_DIFF_CONFIG.staleness_threshold_days;
|
|
139
193
|
const now = Date.now();
|
|
140
194
|
const staleSpecs = [];
|
|
@@ -160,9 +214,12 @@ async function handleStatus() {
|
|
|
160
214
|
verdict = "unassessed";
|
|
161
215
|
return JSON.stringify({
|
|
162
216
|
project: config.project?.name ?? "unknown",
|
|
163
|
-
specCount
|
|
217
|
+
// `specFiles` only. A second field named `specCount` gives a consumer no
|
|
218
|
+
// way to know whether it counts config entries or resolved files -- the
|
|
219
|
+
// ambiguity `sdx_validate` was already cleaned up to avoid.
|
|
220
|
+
specFiles: specs.length,
|
|
164
221
|
byStatus,
|
|
165
|
-
lintHealth: { errors, warnings, passing
|
|
222
|
+
lintHealth: { errors, warnings, passing },
|
|
166
223
|
staleSpecs,
|
|
167
224
|
integrityIssues: graphError ? [graphError] : [],
|
|
168
225
|
verdict
|
|
@@ -200,7 +257,9 @@ async function handleDiff(params) {
|
|
|
200
257
|
const headRef = params.head ?? "HEAD";
|
|
201
258
|
const configPath = join(configDir, "spec.config.yaml");
|
|
202
259
|
try {
|
|
203
|
-
const result = await diffBetweenRefs(configPath, baseRef, headRef
|
|
260
|
+
const result = await diffBetweenRefs(configPath, baseRef, headRef, {
|
|
261
|
+
working: params.working ?? false
|
|
262
|
+
});
|
|
204
263
|
return JSON.stringify(result);
|
|
205
264
|
} catch (err) {
|
|
206
265
|
if (err instanceof DiffError) {
|
|
@@ -257,10 +316,10 @@ async function handleGraph(params) {
|
|
|
257
316
|
}
|
|
258
317
|
|
|
259
318
|
// ../mcp/dist/server.js
|
|
260
|
-
function createMcpServer() {
|
|
319
|
+
function createMcpServer(version = "0.0.0-unknown") {
|
|
261
320
|
const server = new McpServer({
|
|
262
321
|
name: "specdx",
|
|
263
|
-
version
|
|
322
|
+
version
|
|
264
323
|
});
|
|
265
324
|
server.tool("sdx_validate", "Validate the spec.config.yaml configuration file", { configPath: z.string().optional().describe("Path to config directory") }, async (params) => ({
|
|
266
325
|
content: [{ type: "text", text: await handleValidate(params) }]
|
|
@@ -289,7 +348,8 @@ function createMcpServer() {
|
|
|
289
348
|
}));
|
|
290
349
|
server.tool("sdx_diff", "Show spec changes and downstream impact between git refs", {
|
|
291
350
|
base: z.string().optional().describe("Base git ref (default: main)"),
|
|
292
|
-
head: z.string().optional().describe("Head git ref (default: HEAD)")
|
|
351
|
+
head: z.string().optional().describe("Head git ref (default: HEAD)"),
|
|
352
|
+
working: z.boolean().optional().describe("Compare the base ref against the working tree, including uncommitted and untracked specs (default: false)")
|
|
293
353
|
}, async (params) => ({
|
|
294
354
|
content: [{ type: "text", text: await handleDiff(params) }]
|
|
295
355
|
}));
|
|
@@ -301,6 +361,8 @@ function createMcpServer() {
|
|
|
301
361
|
return server;
|
|
302
362
|
}
|
|
303
363
|
export {
|
|
304
|
-
createMcpServer
|
|
364
|
+
createMcpServer,
|
|
365
|
+
handleLint,
|
|
366
|
+
handleStatus
|
|
305
367
|
};
|
|
306
|
-
//# sourceMappingURL=dist-
|
|
368
|
+
//# sourceMappingURL=dist-JPWHWMV2.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, resolveLintConfig, lintAgentFiles } from \"@specdx/lint\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport type { Diagnostic } from \"@specdx/lint\";\n\n/**\n * `sdx_lint` is a near-copy of `runLint`, not a caller of it — the CLI depends\n * on this package, so the dependency cannot run the other way. See\n * `packages/cli/src/lint-parity.test.ts`, which pins the two together.\n *\n * Two divergences were fixed here, both found while dogfooding on 2026-08-11:\n *\n * 1. `specPath` filtered the specs *before* linting, so a single-file lint had\n * no sight of the rest of the suite and cross-reference rules could not\n * fire. The CLI has always linted the whole suite and filtered the\n * resulting diagnostics; that is the correct behaviour and this now matches.\n * 2. A `specPath` matching no spec returned `hasErrors: false` with no signal\n * that nothing had been assessed, which reads to a caller as a clean pass.\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, ignore } = await resolveLintConfig({\n config,\n preset: preset,\n configDir,\n });\n\n // Always parse the full suite so cross-reference rules have complete\n // context; a single-file lint filters the *diagnostics*, not the suite.\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 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, ignore });\n const results = engine.lint(specs);\n\n // One definition of \"does specPath select this file\", shared by the\n // diagnostic filter, the agent diagnostics below, and the assessed count, so\n // none of the three can disagree.\n const { specPath } = params;\n const selects = (filePath: string) => specPath === undefined || filePath.includes(specPath);\n\n let diagnostics: Diagnostic[] = results.diagnostics;\n let { hasErrors, hasWarnings } = results;\n if (specPath !== undefined) {\n diagnostics = diagnostics.filter((d) => selects(d.filePath));\n hasErrors = diagnostics.some((d) => d.severity === \"error\");\n hasWarnings = diagnostics.some((d) => d.severity === \"warn\");\n }\n\n // Agent instruction files, opt-in via the `agents` key. Kept in step with the\n // CLI deliberately: this tool duplicates `runLint` rather than calling it, and\n // that duplication has already shipped a divergence twice.\n //\n // Runs after the spec filter above, because it appends to the already-filtered\n // diagnostics — appending first and filtering after would drop agent findings\n // whenever `specPath` names a spec.\n let agentFiles = 0;\n if (config.agents) {\n const agentResults = await lintAgentFiles({ config, configDir });\n agentFiles = agentResults.filesLinted;\n diagnostics = [...diagnostics];\n\n if (!agentResults.assessed) {\n const patterns = config.agents.paths ?? [\"AGENTS.md\", \"CLAUDE.md\"];\n diagnostics.push({\n ruleId: \"agents/paths-match-nothing\",\n severity: \"error\",\n message: `agents.paths matched no files (${patterns.join(\", \")}), so no agent instruction file was linted. Remove the \\`agents\\` key or fix the paths.`,\n filePath: \"spec.config.yaml\",\n });\n hasErrors = true;\n }\n\n for (const diagnostic of agentResults.diagnostics) {\n if (!selects(diagnostic.filePath)) continue;\n diagnostics.push(diagnostic);\n if (diagnostic.severity === \"error\") hasErrors = true;\n if (diagnostic.severity === \"warn\") hasWarnings = true;\n }\n }\n\n const ignored = new Set(ignore);\n const linted = specs.filter((spec) => !ignored.has(spec.filePath) && selects(spec.filePath));\n\n return JSON.stringify({\n diagnostics,\n hasErrors,\n hasWarnings,\n specsChecked: linted.length,\n // False when nothing was selected — \"no diagnostics\" is then not a pass.\n assessed: linted.length > 0,\n agentFilesChecked: agentFiles,\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, resolveLintConfig } 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, ignore } = await resolveLintConfig({\n config,\n preset: presetName,\n configDir,\n });\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, ignore });\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 // Specs carrying no error-severity diagnostic.\n //\n // This was `specs.length - errors` here too, and the CLI-side fix did not\n // reach it: this handler is a near-copy of `runStatus`, so a repair to one\n // leaves the other reporting a negative number of passing specs. Kept in step\n // by the parity test in the CLI package (audit run 6, G2).\n const specsWithErrors = new Set(\n lintResults.diagnostics.filter((d) => d.severity === \"error\").map((d) => d.filePath),\n );\n const passing = specs.filter(({ spec }) => !specsWithErrors.has(spec.filePath)).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 },\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;AACl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,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":[]}
|
|
@@ -4,7 +4,8 @@ import {
|
|
|
4
4
|
detectFramework,
|
|
5
5
|
parseArtifacts,
|
|
6
6
|
runCheck
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-3YXRWQGX.js";
|
|
8
|
+
import "./chunk-5WRI5ZAA.js";
|
|
8
9
|
export {
|
|
9
10
|
analyzeWithAi,
|
|
10
11
|
checkArtifacts,
|
|
@@ -12,4 +13,4 @@ export {
|
|
|
12
13
|
parseArtifacts,
|
|
13
14
|
runCheck
|
|
14
15
|
};
|
|
15
|
-
//# sourceMappingURL=dist-
|
|
16
|
+
//# sourceMappingURL=dist-ROHCFKYT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {
|
|
2
|
+
labelled
|
|
3
|
+
} from "./chunk-6EQIDZ4D.js";
|
|
4
|
+
import "./chunk-XRWLPU24.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-OMM322L7.js").then((m) => labelled("generate story", m.default)),
|
|
13
|
+
"test-plan": () => import("./generate-test-plan-75W7SZIO.js").then(
|
|
14
|
+
(m) => labelled("generate test-plan", m.default)
|
|
15
|
+
)
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
export {
|
|
19
|
+
generate_default as default
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=generate-MS4BM7RU.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,14 +1,19 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseFeatureEntries,
|
|
3
|
+
uncoveredFeatures
|
|
4
|
+
} from "./chunk-ZIODMXST.js";
|
|
1
5
|
import {
|
|
2
6
|
createLogger,
|
|
3
7
|
loadConfig,
|
|
4
8
|
parseSpec,
|
|
5
9
|
resolveGlob
|
|
6
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-BP3SB35W.js";
|
|
7
11
|
import {
|
|
8
12
|
REQUIRED_SECTIONS
|
|
9
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-XRWLPU24.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";
|
|
@@ -101,26 +106,38 @@ async function generateStories(options) {
|
|
|
101
106
|
throw new Error(`No spec with id "${from}" found in config.`);
|
|
102
107
|
}
|
|
103
108
|
const prd = await parseSpec(prdFilePath);
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
while ((match = featureRegex.exec(featuresSection.content)) !== null) {
|
|
112
|
-
features.push({ num: match[1], text: match[2] });
|
|
113
|
-
}
|
|
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
|
+
}));
|
|
114
116
|
if (features.length === 0) {
|
|
115
|
-
return { generated: [] };
|
|
117
|
+
return { generated: [], skipped: [] };
|
|
116
118
|
}
|
|
117
119
|
const storiesDir = outDir ?? detectStoriesDir(configDir, config);
|
|
118
120
|
await mkdir(storiesDir, { recursive: true });
|
|
119
121
|
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
120
122
|
const prdAuthors = prd.frontmatter.authors ?? [];
|
|
121
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);
|
|
122
139
|
const generated = [];
|
|
123
|
-
for (const feature of features) {
|
|
140
|
+
for (const feature of features.filter((f) => uncovered.has(f.text))) {
|
|
124
141
|
const slug = slugify(feature.text);
|
|
125
142
|
const filename = `story-f${feature.num}-${slug}.md`;
|
|
126
143
|
const filePath = join(storiesDir, filename);
|
|
@@ -135,11 +152,11 @@ async function generateStories(options) {
|
|
|
135
152
|
await writeFile(filePath, content, "utf-8");
|
|
136
153
|
generated.push(filePath);
|
|
137
154
|
}
|
|
138
|
-
return { generated };
|
|
155
|
+
return { generated, skipped };
|
|
139
156
|
}
|
|
140
157
|
var defineCommandExport = defineCommand({
|
|
141
158
|
meta: {
|
|
142
|
-
name: "
|
|
159
|
+
name: "story",
|
|
143
160
|
description: "Generate user story stub files from a PRD's Features section"
|
|
144
161
|
},
|
|
145
162
|
args: {
|
|
@@ -171,13 +188,20 @@ var defineCommandExport = defineCommand({
|
|
|
171
188
|
from: args.from,
|
|
172
189
|
outDir: args.out
|
|
173
190
|
});
|
|
174
|
-
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) {
|
|
175
196
|
logger.info("No features found in PRD \u2014 no story stubs generated.");
|
|
176
197
|
} else {
|
|
177
198
|
logger.info(`Generated ${result.generated.length} story stub(s):`);
|
|
178
199
|
for (const filePath of result.generated) {
|
|
179
200
|
logger.info(` ${filePath}`);
|
|
180
201
|
}
|
|
202
|
+
if (result.skipped.length > 0) {
|
|
203
|
+
logger.info(`Skipped ${result.skipped.length} feature(s) an existing story covers.`);
|
|
204
|
+
}
|
|
181
205
|
}
|
|
182
206
|
} catch (err) {
|
|
183
207
|
console.error(`
|
|
@@ -193,4 +217,4 @@ export {
|
|
|
193
217
|
defineCommandExport,
|
|
194
218
|
generateStories
|
|
195
219
|
};
|
|
196
|
-
//# sourceMappingURL=generate-story-
|
|
220
|
+
//# sourceMappingURL=generate-story-OMM322L7.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;AAC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AAG;AAC9D,eAAO;AAAA,UACL,4CAAuC,OAAO,QAAQ,MAAM;AAAA,QAC9D;AAAA,MACF,WAAW,OAAO,UAAU,WAAW,GAAG;AACxC,eAAO,KAAK,2DAAsD;AAAA,MACpE,OAAO;AACL,eAAO,KAAK,aAAa,OAAO,UAAU,MAAM,iBAAiB;AACjE,mBAAW,YAAY,OAAO,WAAW;AACvC,iBAAO,KAAK,KAAK,QAAQ,EAAE;AAAA,QAC7B;AACA,YAAI,OAAO,QAAQ,SAAS,GAAG;AAC7B,iBAAO,KAAK,WAAW,OAAO,QAAQ,MAAM,uCAAuC;AAAA,QACrF;AAAA,MACF;AAAA,IACF,SAAS,KAAK;AACZ,cAAQ,MAAM;AAAA,WAAU,IAAc,OAAO;AAAA,CAAI;AACjD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF,CAAC;AAED,IAAO,yBAAQ;","names":[]}
|
|
@@ -3,13 +3,15 @@ import {
|
|
|
3
3
|
loadConfig,
|
|
4
4
|
parseSpec,
|
|
5
5
|
resolveGlob
|
|
6
|
-
} from "./chunk-
|
|
7
|
-
import "./chunk-
|
|
6
|
+
} from "./chunk-BP3SB35W.js";
|
|
7
|
+
import "./chunk-XRWLPU24.js";
|
|
8
|
+
import "./chunk-5WRI5ZAA.js";
|
|
8
9
|
|
|
9
|
-
// src/commands/generate-test-plan.ts
|
|
10
|
+
// src/commands/experimental/generate-test-plan.ts
|
|
10
11
|
import { defineCommand } from "citty";
|
|
11
12
|
import { writeFile } from "fs/promises";
|
|
12
|
-
import {
|
|
13
|
+
import { existsSync } from "fs";
|
|
14
|
+
import { join, relative, resolve } from "path";
|
|
13
15
|
function extractSection(content, heading) {
|
|
14
16
|
const escapedHeading = heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
15
17
|
const headingPattern = new RegExp(`^##\\s+${escapedHeading}\\s*$`, "im");
|
|
@@ -35,7 +37,7 @@ function parseAcceptanceCriteria(section) {
|
|
|
35
37
|
return cases;
|
|
36
38
|
}
|
|
37
39
|
async function generateTestPlan(options) {
|
|
38
|
-
const { configDir, outPath } = options;
|
|
40
|
+
const { configDir, outPath, force = false } = options;
|
|
39
41
|
const config = await loadConfig(void 0, configDir);
|
|
40
42
|
const storiesBySpec = [];
|
|
41
43
|
for (const [, entry] of Object.entries(config.specs)) {
|
|
@@ -110,14 +112,29 @@ ${caseBullets}`;
|
|
|
110
112
|
const fileContent = `${frontmatter}
|
|
111
113
|
|
|
112
114
|
${body}`;
|
|
115
|
+
if (storiesBySpec.length === 0) {
|
|
116
|
+
return { testCases: 0 };
|
|
117
|
+
}
|
|
113
118
|
const targetPath = outPath ?? join(configDir, "specs", "test-plan.md");
|
|
119
|
+
if (!force && existsSync(targetPath)) {
|
|
120
|
+
return { testCases: totalTestCases, blockedBy: targetPath };
|
|
121
|
+
}
|
|
114
122
|
await writeFile(targetPath, fileContent, "utf-8");
|
|
115
123
|
return { filePath: targetPath, testCases: totalTestCases };
|
|
116
124
|
}
|
|
125
|
+
async function registeredKeyFor(configDir, filePath) {
|
|
126
|
+
const config = await loadConfig(void 0, configDir);
|
|
127
|
+
for (const [key, entry] of Object.entries(config.specs)) {
|
|
128
|
+
for (const resolved of await resolveGlob(entry.path, configDir)) {
|
|
129
|
+
if (resolve(resolved) === resolve(filePath)) return key;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return void 0;
|
|
133
|
+
}
|
|
117
134
|
var generate_test_plan_default = defineCommand({
|
|
118
135
|
meta: {
|
|
119
|
-
name: "
|
|
120
|
-
description: "
|
|
136
|
+
name: "test-plan",
|
|
137
|
+
description: "Generate a test plan stub from user stories"
|
|
121
138
|
},
|
|
122
139
|
args: {
|
|
123
140
|
from: {
|
|
@@ -128,6 +145,11 @@ var generate_test_plan_default = defineCommand({
|
|
|
128
145
|
out: {
|
|
129
146
|
type: "string",
|
|
130
147
|
description: "Output file path (default: specs/test-plan.md)"
|
|
148
|
+
},
|
|
149
|
+
force: {
|
|
150
|
+
type: "boolean",
|
|
151
|
+
description: "Overwrite the file if it already exists",
|
|
152
|
+
default: false
|
|
131
153
|
}
|
|
132
154
|
},
|
|
133
155
|
async run({ args }) {
|
|
@@ -139,11 +161,38 @@ var generate_test_plan_default = defineCommand({
|
|
|
139
161
|
process.exit(1);
|
|
140
162
|
}
|
|
141
163
|
try {
|
|
164
|
+
const configDir = process.cwd();
|
|
142
165
|
const result = await generateTestPlan({
|
|
143
|
-
configDir
|
|
144
|
-
outPath: args.out
|
|
166
|
+
configDir,
|
|
167
|
+
outPath: args.out,
|
|
168
|
+
force: args.force
|
|
145
169
|
});
|
|
170
|
+
if (result.blockedBy) {
|
|
171
|
+
console.error(
|
|
172
|
+
`
|
|
173
|
+
\u2717 ${result.blockedBy} already exists \u2014 not overwriting it.
|
|
174
|
+
Pass --force to replace it, or --out <path> to write elsewhere.
|
|
175
|
+
`
|
|
176
|
+
);
|
|
177
|
+
process.exit(1);
|
|
178
|
+
}
|
|
179
|
+
if (!result.filePath) {
|
|
180
|
+
logger.info("No user stories found \u2014 no test plan generated.");
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
146
183
|
logger.info(`Generated test plan with ${result.testCases} test cases \u2192 ${result.filePath}`);
|
|
184
|
+
const existingKey = await registeredKeyFor(configDir, result.filePath);
|
|
185
|
+
if (existingKey) {
|
|
186
|
+
logger.info(`Already registered in spec.config.yaml as "${existingKey}".`);
|
|
187
|
+
} else {
|
|
188
|
+
const rel = relative(configDir, result.filePath) || result.filePath;
|
|
189
|
+
logger.info(
|
|
190
|
+
`Add it to spec.config.yaml so lint, status and pack can see it:
|
|
191
|
+
test-plan:
|
|
192
|
+
path: ${rel}
|
|
193
|
+
type: test-plan`
|
|
194
|
+
);
|
|
195
|
+
}
|
|
147
196
|
} catch (err) {
|
|
148
197
|
console.error(`
|
|
149
198
|
\u2717 ${err.message}
|
|
@@ -154,6 +203,7 @@ var generate_test_plan_default = defineCommand({
|
|
|
154
203
|
});
|
|
155
204
|
export {
|
|
156
205
|
generate_test_plan_default as default,
|
|
157
|
-
generateTestPlan
|
|
206
|
+
generateTestPlan,
|
|
207
|
+
registeredKeyFor
|
|
158
208
|
};
|
|
159
|
-
//# sourceMappingURL=generate-test-plan-
|
|
209
|
+
//# sourceMappingURL=generate-test-plan-75W7SZIO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/experimental/generate-test-plan.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, resolveGlob, createLogger } from \"@specdx/core\";\nimport { writeFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join, relative, resolve } from \"node:path\";\n\nexport interface GenerateTestPlanOptions {\n configDir: string;\n outPath?: string;\n /** Overwrite an existing file. Off by default -- the file may be hand-written. */\n force?: boolean;\n}\n\nexport interface GenerateTestPlanResult {\n /** Undefined when there was nothing to generate, so no file was written. */\n filePath?: string;\n testCases: number;\n /** Set when a file exists at the target path and `force` was not given. */\n blockedBy?: string;\n}\n\ninterface StoryTestCases {\n storyId: string;\n title: string;\n authors: string[];\n cases: string[];\n}\n\n/**\n * Extracts the content of a `## Heading` section from a markdown string.\n * Returns the text between that heading and the next `## ` heading (or end of string).\n */\nfunction extractSection(content: string, heading: string): string | null {\n const escapedHeading = heading.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const headingPattern = new RegExp(`^##\\\\s+${escapedHeading}\\\\s*$`, \"im\");\n const match = headingPattern.exec(content);\n if (!match) return null;\n\n const start = match.index + match[0].length;\n const rest = content.slice(start);\n\n const nextSection = /^##\\s+/m.exec(rest);\n return nextSection ? rest.slice(0, nextSection.index) : rest;\n}\n\n/**\n * Parses acceptance criteria bullet points from a section string.\n * Handles `- [ ] text`, `- [x] text`, and plain `- text` formats.\n */\nfunction parseAcceptanceCriteria(section: string): string[] {\n const cases: string[] = [];\n for (const rawLine of section.split(\"\\n\")) {\n const line = rawLine.trim();\n // Match bullet lines: `- [ ] text`, `- [x] text`, `- text`\n const bulletMatch = /^-\\s+(?:\\[[ xX]\\]\\s+)?(.+)/.exec(line);\n if (bulletMatch) {\n const text = bulletMatch[1]!.trim();\n if (text) {\n cases.push(text);\n }\n }\n }\n return cases;\n}\n\nexport async function generateTestPlan(\n options: GenerateTestPlanOptions,\n): Promise<GenerateTestPlanResult> {\n const { configDir, outPath, force = false } = options;\n const config = await loadConfig(undefined, configDir);\n\n const storiesBySpec: StoryTestCases[] = [];\n\n for (const [, entry] of Object.entries(config.specs)) {\n if (entry.type !== \"user-story\") continue;\n\n const files = await resolveGlob(entry.path, configDir);\n for (const file of files) {\n const parsed = await parseSpec(file);\n const frontmatter = parsed.frontmatter;\n const storyId = (frontmatter[\"id\"] as string | undefined) ?? file;\n const title = (frontmatter[\"title\"] as string | undefined) ?? storyId;\n const authors = (frontmatter[\"authors\"] as string[] | undefined) ?? [];\n\n const acSection = extractSection(parsed.content, \"Acceptance Criteria\");\n const cases = acSection ? parseAcceptanceCriteria(acSection) : [];\n\n storiesBySpec.push({ storyId, title, authors, cases });\n }\n }\n\n // Sort stories by ID for deterministic output\n storiesBySpec.sort((a, b) => a.storyId.localeCompare(b.storyId));\n\n const today = new Date().toISOString().slice(0, 10);\n\n // Aggregate authors from all stories (deduplicated)\n const allAuthors = Array.from(new Set(storiesBySpec.flatMap((s) => s.authors)));\n\n // Build references to all stories\n const storyRefs = storiesBySpec.map(\n (s) => ` - id: \"${s.storyId}\"\\n relationship: \"related-to\"`,\n );\n\n const totalTestCases = storiesBySpec.reduce((sum, s) => sum + s.cases.length, 0);\n\n // Build frontmatter\n const authorsYaml =\n allAuthors.length > 0 ? `[${allAuthors.map((a) => `\"${a}\"`).join(\", \")}]` : '[\"generated\"]';\n\n const refsYaml = storyRefs.length > 0 ? `\\nreferences:\\n${storyRefs.join(\"\\n\")}` : \"\";\n\n const frontmatter = [\n \"---\",\n 'id: \"generated-test-plan\"',\n 'type: \"test-plan\"',\n 'title: \"Generated Test Plan\"',\n 'status: \"draft\"',\n 'version: \"0.1\"',\n `created: \"${today}\"`,\n `authors: ${authorsYaml}`,\n refsYaml.length > 0 ? refsYaml.trimStart() : null,\n \"---\",\n ]\n .filter((line) => line !== null)\n .join(\"\\n\");\n\n // ## Scope\n const scopeLines =\n storiesBySpec.length > 0\n ? storiesBySpec.map((s) => `- ${s.storyId}: ${s.title}`).join(\"\\n\")\n : \"_No user stories found._\";\n\n // ## Test Cases — grouped by story\n const testCaseBlocks = storiesBySpec\n .map((s) => {\n const caseBullets =\n s.cases.length > 0\n ? s.cases.map((c) => `- [ ] ${c}`).join(\"\\n\")\n : \"_No acceptance criteria found._\";\n return `### ${s.storyId}\\n\\n${caseBullets}`;\n })\n .join(\"\\n\\n\");\n\n const testCasesBody = storiesBySpec.length > 0 ? testCaseBlocks : \"_No user stories found._\";\n\n // ## Coverage Matrix\n const matrixHeader = \"| Story | Test Cases |\";\n const matrixSep = \"| ----- | ---------- |\";\n const matrixRows = storiesBySpec.map((s) => `| ${s.storyId} | ${s.cases.length} |`);\n const coverageMatrix = [matrixHeader, matrixSep, ...matrixRows].join(\"\\n\");\n\n // ## Edge Cases\n const edgeCasesPlaceholder = \"<!-- Add edge cases and boundary conditions here -->\";\n\n const body = [\n `## Scope`,\n \"\",\n scopeLines,\n \"\",\n `## Test Cases`,\n \"\",\n testCasesBody,\n \"\",\n `## Coverage Matrix`,\n \"\",\n coverageMatrix,\n \"\",\n `## Edge Cases`,\n \"\",\n edgeCasesPlaceholder,\n \"\",\n ].join(\"\\n\");\n\n const fileContent = `${frontmatter}\\n\\n${body}`;\n\n // Nothing to build a plan from. Writing a spec whose every section reads\n // \"_No user stories found._\" would add a file the linter then flags and the\n // suite has to carry -- `generate story` already declines in this case.\n if (storiesBySpec.length === 0) {\n return { testCases: 0 };\n }\n\n const targetPath = outPath ?? join(configDir, \"specs\", \"test-plan.md\");\n\n // A generator must not destroy hand-written work. This overwrote an approved\n // spec -- registered in the config, with a filled-in coverage matrix -- and\n // replaced it with a draft stub, silently and with exit 0. The only reason it\n // was recoverable was that the project happened to use git.\n if (!force && existsSync(targetPath)) {\n return { testCases: totalTestCases, blockedBy: targetPath };\n }\n\n await writeFile(targetPath, fileContent, \"utf-8\");\n\n return { filePath: targetPath, testCases: totalTestCases };\n}\n\n/**\n * The config key, if any, already pointing at `filePath`.\n *\n * Telling an author to register a file the config already knows about invites a\n * duplicate entry for one path -- which is how a frontmatter id and its key\n * come to disagree.\n */\nexport async function registeredKeyFor(\n configDir: string,\n filePath: string,\n): Promise<string | undefined> {\n const config = await loadConfig(undefined, configDir);\n for (const [key, entry] of Object.entries(config.specs)) {\n for (const resolved of await resolveGlob(entry.path, configDir)) {\n if (resolve(resolved) === resolve(filePath)) return key;\n }\n }\n return undefined;\n}\n\nexport default defineCommand({\n meta: {\n name: \"test-plan\",\n description: \"Generate a test plan stub from user stories\",\n },\n args: {\n from: {\n type: \"string\",\n description: \"Source to generate from (currently only 'stories' is supported)\",\n default: \"stories\",\n },\n out: {\n type: \"string\",\n description: \"Output file path (default: specs/test-plan.md)\",\n },\n force: {\n type: \"boolean\",\n description: \"Overwrite the file if it already exists\",\n default: false,\n },\n },\n async run({ args }) {\n const logger = createLogger({ quiet: false, verbose: false });\n\n if (args.from !== \"stories\") {\n console.error(`\\n ✗ --from must be 'stories' (got: ${args.from})\\n`);\n process.exit(1);\n }\n\n try {\n const configDir = process.cwd();\n const result = await generateTestPlan({\n configDir,\n outPath: args.out,\n force: args.force,\n });\n\n if (result.blockedBy) {\n console.error(\n `\\n ✗ ${result.blockedBy} already exists — not overwriting it.\\n` +\n \" Pass --force to replace it, or --out <path> to write elsewhere.\\n\",\n );\n process.exit(1);\n }\n\n if (!result.filePath) {\n logger.info(\"No user stories found — no test plan generated.\");\n return;\n }\n\n logger.info(`Generated test plan with ${result.testCases} test cases → ${result.filePath}`);\n\n // Only worth saying when it is actually unregistered. Advising a key for\n // a path the config already maps produces two entries for one file.\n const existingKey = await registeredKeyFor(configDir, result.filePath);\n if (existingKey) {\n logger.info(`Already registered in spec.config.yaml as \"${existingKey}\".`);\n } else {\n const rel = relative(configDir, result.filePath) || result.filePath;\n logger.info(\n \"Add it to spec.config.yaml so lint, status and pack can see it:\\n\" +\n ` test-plan:\\n path: ${rel}\\n type: test-plan`,\n );\n }\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n});\n"],"mappings":";;;;;;;;;;AAAA,SAAS,qBAAqB;AAE9B,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B,SAAS,MAAM,UAAU,eAAe;AA4BxC,SAAS,eAAe,SAAiB,SAAgC;AACvE,QAAM,iBAAiB,QAAQ,QAAQ,uBAAuB,MAAM;AACpE,QAAM,iBAAiB,IAAI,OAAO,UAAU,cAAc,SAAS,IAAI;AACvE,QAAM,QAAQ,eAAe,KAAK,OAAO;AACzC,MAAI,CAAC,MAAO,QAAO;AAEnB,QAAM,QAAQ,MAAM,QAAQ,MAAM,CAAC,EAAE;AACrC,QAAM,OAAO,QAAQ,MAAM,KAAK;AAEhC,QAAM,cAAc,UAAU,KAAK,IAAI;AACvC,SAAO,cAAc,KAAK,MAAM,GAAG,YAAY,KAAK,IAAI;AAC1D;AAMA,SAAS,wBAAwB,SAA2B;AAC1D,QAAM,QAAkB,CAAC;AACzB,aAAW,WAAW,QAAQ,MAAM,IAAI,GAAG;AACzC,UAAM,OAAO,QAAQ,KAAK;AAE1B,UAAM,cAAc,6BAA6B,KAAK,IAAI;AAC1D,QAAI,aAAa;AACf,YAAM,OAAO,YAAY,CAAC,EAAG,KAAK;AAClC,UAAI,MAAM;AACR,cAAM,KAAK,IAAI;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAsB,iBACpB,SACiC;AACjC,QAAM,EAAE,WAAW,SAAS,QAAQ,MAAM,IAAI;AAC9C,QAAM,SAAS,MAAM,WAAW,QAAW,SAAS;AAEpD,QAAM,gBAAkC,CAAC;AAEzC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