specdx 0.4.0-alpha.17 → 0.4.0-alpha.18
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 +1 -1
- package/README.md +435 -0
- package/dist/{check-Q3QKTN2D.js → check-PQQGR4KP.js} +3 -3
- package/dist/{chunk-TJPPBM24.js → chunk-33FELECG.js} +9 -9
- package/dist/{chunk-4HPWTWBL.js → chunk-AXCGMUU7.js} +11 -6
- package/dist/chunk-AXCGMUU7.js.map +1 -0
- package/dist/{chunk-V7JOVK6D.js → chunk-FX4NRQHE.js} +139 -32
- package/dist/chunk-FX4NRQHE.js.map +1 -0
- package/dist/{chunk-PEC5LAVE.js → chunk-RI2SFGMR.js} +13 -5
- package/dist/chunk-RI2SFGMR.js.map +1 -0
- package/dist/{diff-IEN6W4OG.js → diff-IOBAJMKU.js} +2 -2
- package/dist/{dist-DVROIZAO.js → dist-HRY2V5MO.js} +11 -5
- package/dist/dist-HRY2V5MO.js.map +1 -0
- package/dist/{dist-SWJSMLIP.js → dist-WXT4UJ55.js} +2 -2
- package/dist/{generate-GQPOLFP7.js → generate-NSTYQOAV.js} +4 -4
- package/dist/{generate-story-UJS37FHA.js → generate-story-RFAPULQY.js} +31 -6
- package/dist/generate-story-RFAPULQY.js.map +1 -0
- package/dist/{generate-test-plan-RQTSGQLR.js → generate-test-plan-M22PCW73.js} +11 -1
- package/dist/generate-test-plan-M22PCW73.js.map +1 -0
- package/dist/index.js +131 -21
- package/dist/index.js.map +1 -1
- package/dist/{lint-VB5PV32N.js → lint-ADR7L6AP.js} +2 -2
- package/dist/main.js +16 -3
- package/dist/main.js.map +1 -1
- package/dist/{mcp-DADOVCEV.js → mcp-A6CCWSS2.js} +2 -2
- package/dist/{ready-C6YXJ47W.js → ready-GH4YKVOX.js} +13 -4
- package/dist/ready-GH4YKVOX.js.map +1 -0
- package/dist/{status-BRLCD7NY.js → status-PQKPTDP5.js} +3 -3
- package/dist/{update-P6TQUI6H.js → update-VAC6XV5E.js} +2 -2
- package/hooks/hooks.json +1 -1
- package/package.json +19 -6
- package/dist/chunk-4HPWTWBL.js.map +0 -1
- package/dist/chunk-PEC5LAVE.js.map +0 -1
- package/dist/chunk-V7JOVK6D.js.map +0 -1
- package/dist/dist-DVROIZAO.js.map +0 -1
- package/dist/generate-story-UJS37FHA.js.map +0 -1
- package/dist/generate-test-plan-RQTSGQLR.js.map +0 -1
- package/dist/ready-C6YXJ47W.js.map +0 -1
- /package/dist/{check-Q3QKTN2D.js.map → check-PQQGR4KP.js.map} +0 -0
- /package/dist/{chunk-TJPPBM24.js.map → chunk-33FELECG.js.map} +0 -0
- /package/dist/{diff-IEN6W4OG.js.map → diff-IOBAJMKU.js.map} +0 -0
- /package/dist/{dist-SWJSMLIP.js.map → dist-WXT4UJ55.js.map} +0 -0
- /package/dist/{generate-GQPOLFP7.js.map → generate-NSTYQOAV.js.map} +0 -0
- /package/dist/{lint-VB5PV32N.js.map → lint-ADR7L6AP.js.map} +0 -0
- /package/dist/{mcp-DADOVCEV.js.map → mcp-A6CCWSS2.js.map} +0 -0
- /package/dist/{status-BRLCD7NY.js.map → status-PQKPTDP5.js.map} +0 -0
- /package/dist/{update-P6TQUI6H.js.map → update-VAC6XV5E.js.map} +0 -0
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
2
|
runCheck
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-RI2SFGMR.js";
|
|
4
4
|
import {
|
|
5
5
|
pack
|
|
6
6
|
} from "./chunk-TF7WSPFV.js";
|
|
7
7
|
import {
|
|
8
8
|
createLintEngine,
|
|
9
9
|
getPreset
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-FX4NRQHE.js";
|
|
11
11
|
import {
|
|
12
12
|
DEFAULT_DIFF_CONFIG,
|
|
13
13
|
DiffError,
|
|
14
14
|
diffBetweenRefs
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-AXCGMUU7.js";
|
|
16
16
|
import {
|
|
17
17
|
ConfigError,
|
|
18
18
|
GraphError,
|
|
@@ -36,9 +36,14 @@ async function handleValidate(params) {
|
|
|
36
36
|
const configDir = params.configPath ?? process.cwd();
|
|
37
37
|
const config = await loadConfig(void 0, configDir);
|
|
38
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
|
+
}
|
|
39
43
|
return JSON.stringify({
|
|
40
44
|
valid: true,
|
|
41
|
-
|
|
45
|
+
specEntries: Object.keys(config.specs).length,
|
|
46
|
+
specFiles,
|
|
42
47
|
project: config.project?.name ?? "unknown"
|
|
43
48
|
});
|
|
44
49
|
} catch (err) {
|
|
@@ -161,6 +166,7 @@ async function handleStatus() {
|
|
|
161
166
|
verdict = "unassessed";
|
|
162
167
|
return JSON.stringify({
|
|
163
168
|
project: config.project?.name ?? "unknown",
|
|
169
|
+
specFiles: specs.length,
|
|
164
170
|
specCount: specs.length,
|
|
165
171
|
byStatus,
|
|
166
172
|
lintHealth: { errors, warnings, passing: specs.length - errors },
|
|
@@ -307,4 +313,4 @@ function createMcpServer() {
|
|
|
307
313
|
export {
|
|
308
314
|
createMcpServer
|
|
309
315
|
};
|
|
310
|
-
//# sourceMappingURL=dist-
|
|
316
|
+
//# sourceMappingURL=dist-HRY2V5MO.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\nexport function createMcpServer(): McpServer {\n const server = new McpServer({\n name: \"specdx\",\n version: \"0.4.0\",\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: specs.length,\n specCount: 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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,EAAE,MAAM,QAAiB,MAAM,MAAM,aAAY,EAAE,CAAE;IAC/D;AAGJ,SAAO,KACL,aACA,6CACA;IACE,WAAW,EAAE,OAAM,EAAG,SAAQ,EAAG,SAAS,kCAAkC;IAC5E,QAAQ,EAAE,OAAM,EAAG,SAAQ,EAAG,SAAS,6BAA6B;KAEtE,OAAO,YAAY;IACjB,SAAS,CAAC,EAAE,MAAM,QAAiB,MAAM,MAAM,YAAY,MAAM,EAAC,CAAE;IACpE;AAGJ,SAAO,KACL,YACA,4DACA;IACE,MAAM,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":[]}
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
detectFramework,
|
|
5
5
|
parseArtifacts,
|
|
6
6
|
runCheck
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-RI2SFGMR.js";
|
|
8
8
|
import "./chunk-5WRI5ZAA.js";
|
|
9
9
|
export {
|
|
10
10
|
analyzeWithAi,
|
|
@@ -13,4 +13,4 @@ export {
|
|
|
13
13
|
parseArtifacts,
|
|
14
14
|
runCheck
|
|
15
15
|
};
|
|
16
|
-
//# sourceMappingURL=dist-
|
|
16
|
+
//# sourceMappingURL=dist-WXT4UJ55.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
labelled
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-33FELECG.js";
|
|
4
4
|
import "./chunk-SJCIM4TC.js";
|
|
5
5
|
import "./chunk-5WRI5ZAA.js";
|
|
6
6
|
|
|
@@ -9,8 +9,8 @@ import { defineCommand } from "citty";
|
|
|
9
9
|
var generate_default = defineCommand({
|
|
10
10
|
meta: { name: "generate", description: "Generate spec stubs from existing specs" },
|
|
11
11
|
subCommands: {
|
|
12
|
-
story: () => import("./generate-story-
|
|
13
|
-
"test-plan": () => import("./generate-test-plan-
|
|
12
|
+
story: () => import("./generate-story-RFAPULQY.js").then((m) => labelled("generate story", m.default)),
|
|
13
|
+
"test-plan": () => import("./generate-test-plan-M22PCW73.js").then(
|
|
14
14
|
(m) => labelled("generate test-plan", m.default)
|
|
15
15
|
)
|
|
16
16
|
}
|
|
@@ -18,4 +18,4 @@ var generate_default = defineCommand({
|
|
|
18
18
|
export {
|
|
19
19
|
generate_default as default
|
|
20
20
|
};
|
|
21
|
-
//# sourceMappingURL=generate-
|
|
21
|
+
//# sourceMappingURL=generate-NSTYQOAV.js.map
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
uncoveredFeatures
|
|
3
|
+
} from "./chunk-FX4NRQHE.js";
|
|
1
4
|
import {
|
|
2
5
|
createLogger,
|
|
3
6
|
loadConfig,
|
|
@@ -104,7 +107,7 @@ async function generateStories(options) {
|
|
|
104
107
|
const prd = await parseSpec(prdFilePath);
|
|
105
108
|
const featuresSection = prd.parsedSections.find((s) => s.heading === "Features");
|
|
106
109
|
if (!featuresSection) {
|
|
107
|
-
return { generated: [] };
|
|
110
|
+
return { generated: [], skipped: [] };
|
|
108
111
|
}
|
|
109
112
|
const featureRegex = /\*\*F(\d+)\*\*:\s*(.+)/g;
|
|
110
113
|
const features = [];
|
|
@@ -113,15 +116,30 @@ async function generateStories(options) {
|
|
|
113
116
|
features.push({ num: match[1], text: match[2] });
|
|
114
117
|
}
|
|
115
118
|
if (features.length === 0) {
|
|
116
|
-
return { generated: [] };
|
|
119
|
+
return { generated: [], skipped: [] };
|
|
117
120
|
}
|
|
118
121
|
const storiesDir = outDir ?? detectStoriesDir(configDir, config);
|
|
119
122
|
await mkdir(storiesDir, { recursive: true });
|
|
120
123
|
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
121
124
|
const prdAuthors = prd.frontmatter.authors ?? [];
|
|
122
125
|
const sections = REQUIRED_SECTIONS["user-story"];
|
|
126
|
+
const existingStories = [];
|
|
127
|
+
for (const entry of Object.values(config.specs)) {
|
|
128
|
+
if (entry.type !== "user-story") continue;
|
|
129
|
+
for (const p of await resolveGlob(entry.path, configDir)) {
|
|
130
|
+
existingStories.push(await parseSpec(p));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const uncovered = new Set(
|
|
134
|
+
uncoveredFeatures(
|
|
135
|
+
features.map((f) => f.text),
|
|
136
|
+
existingStories,
|
|
137
|
+
from
|
|
138
|
+
)
|
|
139
|
+
);
|
|
140
|
+
const skipped = features.filter((f) => !uncovered.has(f.text)).map((f) => f.text);
|
|
123
141
|
const generated = [];
|
|
124
|
-
for (const feature of features) {
|
|
142
|
+
for (const feature of features.filter((f) => uncovered.has(f.text))) {
|
|
125
143
|
const slug = slugify(feature.text);
|
|
126
144
|
const filename = `story-f${feature.num}-${slug}.md`;
|
|
127
145
|
const filePath = join(storiesDir, filename);
|
|
@@ -136,7 +154,7 @@ async function generateStories(options) {
|
|
|
136
154
|
await writeFile(filePath, content, "utf-8");
|
|
137
155
|
generated.push(filePath);
|
|
138
156
|
}
|
|
139
|
-
return { generated };
|
|
157
|
+
return { generated, skipped };
|
|
140
158
|
}
|
|
141
159
|
var defineCommandExport = defineCommand({
|
|
142
160
|
meta: {
|
|
@@ -172,13 +190,20 @@ var defineCommandExport = defineCommand({
|
|
|
172
190
|
from: args.from,
|
|
173
191
|
outDir: args.out
|
|
174
192
|
});
|
|
175
|
-
if (result.generated.length === 0) {
|
|
193
|
+
if (result.generated.length === 0 && result.skipped.length > 0) {
|
|
194
|
+
logger.info(
|
|
195
|
+
`Every feature already has a story \u2014 ${result.skipped.length} feature(s) skipped, nothing generated.`
|
|
196
|
+
);
|
|
197
|
+
} else if (result.generated.length === 0) {
|
|
176
198
|
logger.info("No features found in PRD \u2014 no story stubs generated.");
|
|
177
199
|
} else {
|
|
178
200
|
logger.info(`Generated ${result.generated.length} story stub(s):`);
|
|
179
201
|
for (const filePath of result.generated) {
|
|
180
202
|
logger.info(` ${filePath}`);
|
|
181
203
|
}
|
|
204
|
+
if (result.skipped.length > 0) {
|
|
205
|
+
logger.info(`Skipped ${result.skipped.length} feature(s) an existing story covers.`);
|
|
206
|
+
}
|
|
182
207
|
}
|
|
183
208
|
} catch (err) {
|
|
184
209
|
console.error(`
|
|
@@ -194,4 +219,4 @@ export {
|
|
|
194
219
|
defineCommandExport,
|
|
195
220
|
generateStories
|
|
196
221
|
};
|
|
197
|
-
//# sourceMappingURL=generate-story-
|
|
222
|
+
//# sourceMappingURL=generate-story-RFAPULQY.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 } 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 // Find the Features section content\n const featuresSection = prd.parsedSections.find((s) => s.heading === \"Features\");\n if (!featuresSection) {\n return { generated: [], skipped: [] };\n }\n\n // Parse features using the required regex pattern\n const featureRegex = /\\*\\*F(\\d+)\\*\\*:\\s*(.+)/g;\n const features: Array<{ num: string; text: string }> = [];\n let match: RegExpExecArray | null;\n while ((match = featureRegex.exec(featuresSection.content)) !== null) {\n features.push({ num: match[1]!, text: match[2]! });\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: \"generate 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,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|
@@ -111,6 +111,9 @@ ${caseBullets}`;
|
|
|
111
111
|
const fileContent = `${frontmatter}
|
|
112
112
|
|
|
113
113
|
${body}`;
|
|
114
|
+
if (storiesBySpec.length === 0) {
|
|
115
|
+
return { testCases: 0 };
|
|
116
|
+
}
|
|
114
117
|
const targetPath = outPath ?? join(configDir, "specs", "test-plan.md");
|
|
115
118
|
await writeFile(targetPath, fileContent, "utf-8");
|
|
116
119
|
return { filePath: targetPath, testCases: totalTestCases };
|
|
@@ -144,7 +147,14 @@ var generate_test_plan_default = defineCommand({
|
|
|
144
147
|
configDir: process.cwd(),
|
|
145
148
|
outPath: args.out
|
|
146
149
|
});
|
|
150
|
+
if (!result.filePath) {
|
|
151
|
+
logger.info("No user stories found \u2014 no test plan generated.");
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
147
154
|
logger.info(`Generated test plan with ${result.testCases} test cases \u2192 ${result.filePath}`);
|
|
155
|
+
logger.info(
|
|
156
|
+
"Add it to spec.config.yaml so lint, status and pack can see it:\n test-plan:\n path: specs/test-plan.md\n type: test-plan"
|
|
157
|
+
);
|
|
148
158
|
} catch (err) {
|
|
149
159
|
console.error(`
|
|
150
160
|
\u2717 ${err.message}
|
|
@@ -157,4 +167,4 @@ export {
|
|
|
157
167
|
generate_test_plan_default as default,
|
|
158
168
|
generateTestPlan
|
|
159
169
|
};
|
|
160
|
-
//# sourceMappingURL=generate-test-plan-
|
|
170
|
+
//# sourceMappingURL=generate-test-plan-M22PCW73.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 { join } from \"node:path\";\n\nexport interface GenerateTestPlanOptions {\n configDir: string;\n outPath?: string;\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}\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 } = 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 await writeFile(targetPath, fileContent, \"utf-8\");\n\n return { filePath: targetPath, testCases: totalTestCases };\n}\n\nexport default defineCommand({\n meta: {\n name: \"generate-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 },\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 result = await generateTestPlan({\n configDir: process.cwd(),\n outPath: args.out,\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 logger.info(\n \"Add it to spec.config.yaml so lint, status and pack can see it:\\n\" +\n \" test-plan:\\n path: specs/test-plan.md\\n type: test-plan\",\n );\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n },\n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AAa;AAAA,IACf;AAAA,EACF;AAAA,EACA,MAAM,IAAI,EAAE,KAAK,GAAG;AAClB,UAAM,SAAS,aAAa,EAAE,OAAO,OAAO,SAAS,MAAM,CAAC;AAE5D,QAAI,KAAK,SAAS,WAAW;AAC3B,cAAQ,MAAM;AAAA,0CAAwC,KAAK,IAAI;AAAA,CAAK;AACpE,cAAQ,KAAK,CAAC;AAAA,IAChB;AAEA,QAAI;AACF,YAAM,SAAS,MAAM,iBAAiB;AAAA,QACpC,WAAW,QAAQ,IAAI;AAAA,QACvB,SAAS,KAAK;AAAA,MAChB,CAAC;AAED,UAAI,CAAC,OAAO,UAAU;AACpB,eAAO,KAAK,sDAAiD;AAC7D;AAAA,MACF;AAEA,aAAO,KAAK,4BAA4B,OAAO,SAAS,sBAAiB,OAAO,QAAQ,EAAE;AAC1F,aAAO;AAAA,QACL;AAAA,MAEF;AAAA,IACF,SAAS,KAAK;AACZ,cAAQ,MAAM;AAAA,WAAU,IAAc,OAAO;AAAA,CAAI;AACjD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF,CAAC;","names":["frontmatter"]}
|
package/dist/index.js
CHANGED
|
@@ -2512,6 +2512,18 @@ function createLintEngine(options) {
|
|
|
2512
2512
|
}
|
|
2513
2513
|
|
|
2514
2514
|
// ../lint/dist/rules/valid-frontmatter.js
|
|
2515
|
+
function readablePath(instancePath) {
|
|
2516
|
+
return instancePath.split("/").filter(Boolean).map((segment) => /^\d+$/.test(segment) ? `[${segment}]` : `.${segment}`).join("").replace(/^\./, "");
|
|
2517
|
+
}
|
|
2518
|
+
function describeValidationError(err) {
|
|
2519
|
+
const path = readablePath(err.instancePath ?? "");
|
|
2520
|
+
const allowed = err.params?.allowedValues;
|
|
2521
|
+
let detail = err.message ?? JSON.stringify(err);
|
|
2522
|
+
if (Array.isArray(allowed) && allowed.length > 0) {
|
|
2523
|
+
detail += `: ${allowed.map((v) => JSON.stringify(v)).join(", ")}`;
|
|
2524
|
+
}
|
|
2525
|
+
return path ? `${path} ${detail}` : detail;
|
|
2526
|
+
}
|
|
2515
2527
|
var validFrontmatterRule = {
|
|
2516
2528
|
id: "structure/valid-frontmatter",
|
|
2517
2529
|
description: "Frontmatter matches the schema for the declared spec type",
|
|
@@ -2523,7 +2535,7 @@ var validFrontmatterRule = {
|
|
|
2523
2535
|
return errors.map((err) => ({
|
|
2524
2536
|
ruleId: "structure/valid-frontmatter",
|
|
2525
2537
|
severity: "error",
|
|
2526
|
-
message: `Invalid frontmatter: ${
|
|
2538
|
+
message: `Invalid frontmatter: ${describeValidationError(err)}`,
|
|
2527
2539
|
filePath: context.spec.filePath
|
|
2528
2540
|
}));
|
|
2529
2541
|
}
|
|
@@ -2583,7 +2595,106 @@ var noCircularDepsRule = {
|
|
|
2583
2595
|
};
|
|
2584
2596
|
|
|
2585
2597
|
// ../lint/dist/rules/story-coverage.js
|
|
2586
|
-
var
|
|
2598
|
+
var STOPWORDS = /* @__PURE__ */ new Set([
|
|
2599
|
+
"a",
|
|
2600
|
+
"an",
|
|
2601
|
+
"the",
|
|
2602
|
+
"and",
|
|
2603
|
+
"or",
|
|
2604
|
+
"of",
|
|
2605
|
+
"to",
|
|
2606
|
+
"for",
|
|
2607
|
+
"with",
|
|
2608
|
+
"its",
|
|
2609
|
+
"it",
|
|
2610
|
+
"in",
|
|
2611
|
+
"on",
|
|
2612
|
+
"at",
|
|
2613
|
+
"by",
|
|
2614
|
+
"from",
|
|
2615
|
+
"into",
|
|
2616
|
+
"every",
|
|
2617
|
+
"each",
|
|
2618
|
+
"that",
|
|
2619
|
+
"this",
|
|
2620
|
+
"be",
|
|
2621
|
+
"is",
|
|
2622
|
+
"are",
|
|
2623
|
+
"as",
|
|
2624
|
+
"can",
|
|
2625
|
+
"will",
|
|
2626
|
+
"must",
|
|
2627
|
+
"so",
|
|
2628
|
+
"their",
|
|
2629
|
+
"them",
|
|
2630
|
+
"when",
|
|
2631
|
+
"which",
|
|
2632
|
+
"who"
|
|
2633
|
+
]);
|
|
2634
|
+
var OVERLAP_THRESHOLD = 0.5;
|
|
2635
|
+
var REFERENCED_THRESHOLD = 0.34;
|
|
2636
|
+
function tokenise(text) {
|
|
2637
|
+
const words = text.toLowerCase().replace(/[^a-z0-9\s-]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !STOPWORDS.has(w)).map((w) => w.length > 3 && w.endsWith("s") && !w.endsWith("ss") ? w.slice(0, -1) : w);
|
|
2638
|
+
return new Set(words);
|
|
2639
|
+
}
|
|
2640
|
+
function extractFeatureSection(content) {
|
|
2641
|
+
const lines = content.split("\n");
|
|
2642
|
+
const start = lines.findIndex((l) => /^##\s+Features\s*$/.test(l.trim()));
|
|
2643
|
+
if (start === -1)
|
|
2644
|
+
return null;
|
|
2645
|
+
const body = [];
|
|
2646
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
2647
|
+
if (/^##\s/.test(lines[i]))
|
|
2648
|
+
break;
|
|
2649
|
+
body.push(lines[i]);
|
|
2650
|
+
}
|
|
2651
|
+
return body.join("\n");
|
|
2652
|
+
}
|
|
2653
|
+
function parseFeatures(content) {
|
|
2654
|
+
const section = extractFeatureSection(content);
|
|
2655
|
+
if (section === null)
|
|
2656
|
+
return [];
|
|
2657
|
+
const ID_PREFIX = /^\*{0,2}F\d+\*{0,2}\s*[:.-]\s*/i;
|
|
2658
|
+
const features = [];
|
|
2659
|
+
for (const rawLine of section.split("\n")) {
|
|
2660
|
+
const line = rawLine.trim();
|
|
2661
|
+
if (!line)
|
|
2662
|
+
continue;
|
|
2663
|
+
const bullet = /^[-*]\s+(.*)$/.exec(line);
|
|
2664
|
+
const text = bullet ? (bullet[1] ?? "").trim() : ID_PREFIX.test(line) ? line : "";
|
|
2665
|
+
if (!text)
|
|
2666
|
+
continue;
|
|
2667
|
+
const stripped = text.replace(ID_PREFIX, "").trim();
|
|
2668
|
+
if (stripped)
|
|
2669
|
+
features.push(stripped);
|
|
2670
|
+
}
|
|
2671
|
+
return features;
|
|
2672
|
+
}
|
|
2673
|
+
function overlap(featureTokens, storyTokens) {
|
|
2674
|
+
if (featureTokens.size === 0)
|
|
2675
|
+
return 0;
|
|
2676
|
+
let shared = 0;
|
|
2677
|
+
for (const token of featureTokens)
|
|
2678
|
+
if (storyTokens.has(token))
|
|
2679
|
+
shared++;
|
|
2680
|
+
return shared / featureTokens.size;
|
|
2681
|
+
}
|
|
2682
|
+
function referencesSpec(story, specId) {
|
|
2683
|
+
const refs = story.frontmatter.references;
|
|
2684
|
+
if (!Array.isArray(refs))
|
|
2685
|
+
return false;
|
|
2686
|
+
return refs.some((r) => r?.id === specId);
|
|
2687
|
+
}
|
|
2688
|
+
function uncoveredFeatures(features, stories, prdId) {
|
|
2689
|
+
const scored = stories.map((story) => ({
|
|
2690
|
+
tokens: tokenise(`${String(story.frontmatter.title ?? "")} ${story.content}`),
|
|
2691
|
+
threshold: referencesSpec(story, prdId) ? REFERENCED_THRESHOLD : OVERLAP_THRESHOLD
|
|
2692
|
+
}));
|
|
2693
|
+
return features.filter((feature) => {
|
|
2694
|
+
const featureTokens = tokenise(feature);
|
|
2695
|
+
return !scored.some((s) => overlap(featureTokens, s.tokens) >= s.threshold);
|
|
2696
|
+
});
|
|
2697
|
+
}
|
|
2587
2698
|
var storyCoverageRule = {
|
|
2588
2699
|
id: "completeness/story-coverage",
|
|
2589
2700
|
description: "Every feature listed in a PRD has at least one corresponding user story",
|
|
@@ -2591,17 +2702,11 @@ var storyCoverageRule = {
|
|
|
2591
2702
|
run(context) {
|
|
2592
2703
|
if (context.spec.frontmatter.type !== "prd")
|
|
2593
2704
|
return [];
|
|
2594
|
-
const features =
|
|
2595
|
-
let match;
|
|
2596
|
-
const re = new RegExp(FEATURE_PATTERN.source, "g");
|
|
2597
|
-
while ((match = re.exec(context.spec.content)) !== null) {
|
|
2598
|
-
features.push(match[1].trim());
|
|
2599
|
-
}
|
|
2705
|
+
const features = parseFeatures(context.spec.content);
|
|
2600
2706
|
if (features.length === 0)
|
|
2601
2707
|
return [];
|
|
2602
2708
|
const stories = context.allSpecs.filter((s) => s.frontmatter.type === "user-story");
|
|
2603
|
-
|
|
2604
|
-
return features.filter((feature) => !storyContent.toLowerCase().includes(feature.toLowerCase())).map((feature) => ({
|
|
2709
|
+
return uncoveredFeatures(features, stories, context.spec.frontmatter.id).map((feature) => ({
|
|
2605
2710
|
ruleId: "completeness/story-coverage",
|
|
2606
2711
|
severity: "warn",
|
|
2607
2712
|
message: `Feature "${feature}" has no corresponding user story`,
|
|
@@ -2896,7 +3001,7 @@ var namingConventionsRule = {
|
|
|
2896
3001
|
};
|
|
2897
3002
|
|
|
2898
3003
|
// ../lint/dist/rules/threat-coverage.js
|
|
2899
|
-
var
|
|
3004
|
+
var STOPWORDS2 = /* @__PURE__ */ new Set(["the", "and", "for", "with", "from", "that", "this", "into", "via"]);
|
|
2900
3005
|
function extractThreats(content) {
|
|
2901
3006
|
const parts = content.split(/^(?=## )/m);
|
|
2902
3007
|
const threats = [];
|
|
@@ -2909,7 +3014,7 @@ function extractThreats(content) {
|
|
|
2909
3014
|
return threats;
|
|
2910
3015
|
}
|
|
2911
3016
|
function extractKeyTerms(text) {
|
|
2912
|
-
return text.toLowerCase().split(/\W+/).filter((w) => w.length > 3).filter((w) => !
|
|
3017
|
+
return text.toLowerCase().split(/\W+/).filter((w) => w.length > 3).filter((w) => !STOPWORDS2.has(w));
|
|
2913
3018
|
}
|
|
2914
3019
|
var threatCoverageRule = {
|
|
2915
3020
|
id: "security/threat-coverage",
|
|
@@ -3138,7 +3243,7 @@ var lint_default = defineCommand2({
|
|
|
3138
3243
|
import { defineCommand as defineCommand3 } from "citty";
|
|
3139
3244
|
|
|
3140
3245
|
// ../pack/dist/resolver.js
|
|
3141
|
-
var
|
|
3246
|
+
var STOPWORDS3 = /* @__PURE__ */ new Set([
|
|
3142
3247
|
"a",
|
|
3143
3248
|
"an",
|
|
3144
3249
|
"and",
|
|
@@ -3215,7 +3320,7 @@ var STOPWORDS2 = /* @__PURE__ */ new Set([
|
|
|
3215
3320
|
"your"
|
|
3216
3321
|
]);
|
|
3217
3322
|
function tokenize(task) {
|
|
3218
|
-
return task.split(/[\s\-_/.,;:!?()[\]{}'"]+/).map((t) => t.toLowerCase()).filter((t) => t.length > 1 && !
|
|
3323
|
+
return task.split(/[\s\-_/.,;:!?()[\]{}'"]+/).map((t) => t.toLowerCase()).filter((t) => t.length > 1 && !STOPWORDS3.has(t));
|
|
3219
3324
|
}
|
|
3220
3325
|
var WEIGHT_TAGS = 3;
|
|
3221
3326
|
var WEIGHT_TITLE = 3;
|
|
@@ -4416,8 +4521,8 @@ function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep
|
|
|
4416
4521
|
} else if (endKeep) {
|
|
4417
4522
|
var endKeepWsPrefix = endKeep.value.match(/^\s*/)[0];
|
|
4418
4523
|
var deletionWsSuffix = deletion.value.match(/\s*$/)[0];
|
|
4419
|
-
var
|
|
4420
|
-
deletion.value = removeSuffix(deletion.value,
|
|
4524
|
+
var overlap2 = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
|
|
4525
|
+
deletion.value = removeSuffix(deletion.value, overlap2);
|
|
4421
4526
|
} else if (startKeep) {
|
|
4422
4527
|
var startKeepWsSuffix = startKeep.value.match(/\s*$/)[0];
|
|
4423
4528
|
var deletionWsPrefix = deletion.value.match(/^\s*/)[0];
|
|
@@ -4996,11 +5101,16 @@ import { execSync as execSync2 } from "child_process";
|
|
|
4996
5101
|
import { readFileSync, realpathSync } from "fs";
|
|
4997
5102
|
import { dirname as dirname2, relative, resolve as resolve2, sep } from "path";
|
|
4998
5103
|
function getRepoRoot(cwd) {
|
|
4999
|
-
|
|
5000
|
-
|
|
5001
|
-
|
|
5002
|
-
|
|
5003
|
-
|
|
5104
|
+
let root;
|
|
5105
|
+
try {
|
|
5106
|
+
root = execSync2("git rev-parse --show-toplevel", {
|
|
5107
|
+
cwd,
|
|
5108
|
+
encoding: "utf-8",
|
|
5109
|
+
stdio: "pipe"
|
|
5110
|
+
}).trim();
|
|
5111
|
+
} catch {
|
|
5112
|
+
throw new DiffError("diff compares specs across git history, and this directory is not inside a git repository. Run `git init` first, or run diff from a checked-out project.");
|
|
5113
|
+
}
|
|
5004
5114
|
return realpathSync(root);
|
|
5005
5115
|
}
|
|
5006
5116
|
function validateRef(ref, cwd) {
|