specdx 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/README.md +70 -22
  3. package/dist/{check-RH5SCXWW.js → check-5EA2MTNN.js} +120 -26
  4. package/dist/check-5EA2MTNN.js.map +1 -0
  5. package/dist/{chunk-3YXRWQGX.js → chunk-2UUQJ2ER.js} +242 -53
  6. package/dist/chunk-2UUQJ2ER.js.map +1 -0
  7. package/dist/{chunk-6WFNZH7F.js → chunk-5XOWCPP2.js} +2 -2
  8. package/dist/{chunk-CQETLJTZ.js → chunk-6S2OQMUH.js} +8 -4
  9. package/dist/chunk-6S2OQMUH.js.map +1 -0
  10. package/dist/{chunk-BP3SB35W.js → chunk-JGD3BOPH.js} +15 -5
  11. package/dist/chunk-JGD3BOPH.js.map +1 -0
  12. package/dist/{chunk-BMOOLUPG.js → chunk-MOYYF7Q6.js} +2 -2
  13. package/dist/{chunk-ZIODMXST.js → chunk-VVZUJ6H4.js} +52 -14
  14. package/dist/{chunk-ZIODMXST.js.map → chunk-VVZUJ6H4.js.map} +1 -1
  15. package/dist/{chunk-6EQIDZ4D.js → chunk-WSLIO2ZD.js} +13 -13
  16. package/dist/{diff-QO7HMAK3.js → diff-ZT6HXHK5.js} +3 -3
  17. package/dist/dist-6WDWUOCV.js +26 -0
  18. package/dist/{dist-JPWHWMV2.js → dist-A3CWALDC.js} +30 -9
  19. package/dist/dist-A3CWALDC.js.map +1 -0
  20. package/dist/{generate-MS4BM7RU.js → generate-PTDHGDR2.js} +4 -4
  21. package/dist/{generate-story-OMM322L7.js → generate-story-BXGNKWC6.js} +3 -3
  22. package/dist/{generate-test-plan-75W7SZIO.js → generate-test-plan-PZUNCNN3.js} +2 -2
  23. package/dist/{graph-QOTMXENE.js → graph-GKXD2IGW.js} +2 -2
  24. package/dist/index.d.ts +11 -0
  25. package/dist/index.js +109 -22
  26. package/dist/index.js.map +1 -1
  27. package/dist/{lint-LPFLHVO4.js → lint-GZX5C5EQ.js} +55 -10
  28. package/dist/lint-GZX5C5EQ.js.map +1 -0
  29. package/dist/main.js +2 -2
  30. package/dist/{mcp-OEC43SPF.js → mcp-PIVG3LEF.js} +3 -3
  31. package/dist/{migrate-CBP2AVLH.js → migrate-VASWPA3L.js} +2 -2
  32. package/dist/{pack-X6FSWORJ.js → pack-DFUCNWVR.js} +3 -3
  33. package/dist/{ready-7MJWRGLT.js → ready-5OFSV2OD.js} +4 -4
  34. package/dist/{status-UUPZYX3J.js → status-5MDODW4N.js} +4 -4
  35. package/dist/{update-EI7IJRHG.js → update-NFXC45UT.js} +3 -3
  36. package/dist/{validate-HTTZLQWI.js → validate-LWRLZR3H.js} +2 -2
  37. package/package.json +10 -6
  38. package/skills/core/specdx-author-spec/SKILL.md +33 -0
  39. package/skills/core/specdx-author-spec/references/spec-type-reference.md +57 -0
  40. package/skills/core/specdx-author-spec/references/step-01-frontmatter.md +66 -0
  41. package/skills/core/specdx-author-spec/references/step-02-sections.md +111 -0
  42. package/skills/core/specdx-author-spec/references/step-03-finalize.md +48 -0
  43. package/skills/core/specdx-onboard/SKILL.md +54 -0
  44. package/skills/core/specdx-plan-from-spec/SKILL.md +76 -0
  45. package/skills/core/specdx-pre-commit/SKILL.md +70 -0
  46. package/skills/core/specdx-review-spec/SKILL.md +81 -0
  47. package/skills/core/specdx-router/SKILL.md +67 -0
  48. package/skills/core/specdx-sprint-review/SKILL.md +73 -0
  49. package/skills/core/specdx-start-task/SKILL.md +62 -0
  50. package/skills/experimental/specdx-check-drift/SKILL.md +77 -0
  51. package/skills/experimental/specdx-verify/SKILL.md +85 -0
  52. package/dist/check-RH5SCXWW.js.map +0 -1
  53. package/dist/chunk-3YXRWQGX.js.map +0 -1
  54. package/dist/chunk-BP3SB35W.js.map +0 -1
  55. package/dist/chunk-CQETLJTZ.js.map +0 -1
  56. package/dist/dist-JPWHWMV2.js.map +0 -1
  57. package/dist/dist-ROHCFKYT.js +0 -16
  58. package/dist/lint-LPFLHVO4.js.map +0 -1
  59. /package/dist/{chunk-6WFNZH7F.js.map → chunk-5XOWCPP2.js.map} +0 -0
  60. /package/dist/{chunk-BMOOLUPG.js.map → chunk-MOYYF7Q6.js.map} +0 -0
  61. /package/dist/{chunk-6EQIDZ4D.js.map → chunk-WSLIO2ZD.js.map} +0 -0
  62. /package/dist/{diff-QO7HMAK3.js.map → diff-ZT6HXHK5.js.map} +0 -0
  63. /package/dist/{dist-ROHCFKYT.js.map → dist-6WDWUOCV.js.map} +0 -0
  64. /package/dist/{generate-MS4BM7RU.js.map → generate-PTDHGDR2.js.map} +0 -0
  65. /package/dist/{generate-story-OMM322L7.js.map → generate-story-BXGNKWC6.js.map} +0 -0
  66. /package/dist/{generate-test-plan-75W7SZIO.js.map → generate-test-plan-PZUNCNN3.js.map} +0 -0
  67. /package/dist/{graph-QOTMXENE.js.map → graph-GKXD2IGW.js.map} +0 -0
  68. /package/dist/{mcp-OEC43SPF.js.map → mcp-PIVG3LEF.js.map} +0 -0
  69. /package/dist/{migrate-CBP2AVLH.js.map → migrate-VASWPA3L.js.map} +0 -0
  70. /package/dist/{pack-X6FSWORJ.js.map → pack-DFUCNWVR.js.map} +0 -0
  71. /package/dist/{ready-7MJWRGLT.js.map → ready-5OFSV2OD.js.map} +0 -0
  72. /package/dist/{status-UUPZYX3J.js.map → status-5MDODW4N.js.map} +0 -0
  73. /package/dist/{update-EI7IJRHG.js.map → update-NFXC45UT.js.map} +0 -0
  74. /package/dist/{validate-HTTZLQWI.js.map → validate-LWRLZR3H.js.map} +0 -0
@@ -0,0 +1,85 @@
1
+ ---
2
+ name: specdx-verify
3
+ description: "[experimental — built on specdx check, whose static analysis can be noisy] Use when the user says 'verify', 'check against spec', 'does this match the spec', 'review implementation', or after completing a feature. Runs spec-to-implementation analysis and reviews findings."
4
+ allowed-tools: Bash(npx specdx:*) Read
5
+ ---
6
+
7
+ # Verify Implementation Against Specs
8
+
9
+ Run static analysis to check if the implementation matches the specs, then review each finding.
10
+
11
+ ## Workflow
12
+
13
+ ### Step 1: Run spec-to-implementation check
14
+
15
+ ```bash
16
+ npx specdx check --format json
17
+ ```
18
+
19
+ If the command fails with "ts-morph is required", tell the user to install it: `pnpm add -D ts-morph`.
20
+
21
+ If it fails with "No spec.config.yaml found", the project isn't set up with specdx. Stop and inform the user.
22
+
23
+ If it exits 3 ("coverage not assessed — no checkable surfaces"), the project has no extractable routes/types/tests — common outside Express/Hono/Next.js. Suggest declaring checkable artifacts in the relevant spec's frontmatter so check has something real to verify:
24
+
25
+ ```yaml
26
+ artifacts:
27
+ - path: "middleware.ts"
28
+ - path: "src/lib/bots.ts"
29
+ exports: ["BOT_SIGNATURES"]
30
+ ```
31
+
32
+ Declaring artifacts for work that is not built yet is safe: while the spec is `draft` or `review`, absent files report as *pending* (info, exit 0). They become enforceable errors when the spec status is `approved`. So write the declaration when you write the spec — do not wait for the implementation.
33
+
34
+ ### Step 2: Load spec context
35
+
36
+ ```bash
37
+ npx specdx pack --task "$ARGUMENTS" --format xml
38
+ ```
39
+
40
+ This gives you the spec content to compare findings against.
41
+
42
+ ### Step 3: Review each finding
43
+
44
+ For each finding in the check output:
45
+
46
+ | Finding Type | Action |
47
+ |---|---|
48
+ | `missing` (error) | Check if the spec requirement is genuinely unimplemented, or if the static analysis missed it (different naming, different file location). Report your assessment. |
49
+ | `extra` (info) | Check if the code addition is intentional (feature beyond spec) or accidental scope creep. Note it but don't flag as an issue unless it contradicts a Non-Goal. |
50
+ | `mismatch` (warn) | Compare the spec expectation against the code. Determine if the deviation is intentional (spec needs updating) or a bug (code needs fixing). |
51
+
52
+ ### Step 4: Present structured report
53
+
54
+ ```
55
+ ## Verification Report
56
+
57
+ **Score:** X% implementation coverage
58
+
59
+ ### Real Issues
60
+ - [finding] — [why it's a real issue] — [suggested fix]
61
+
62
+ ### False Positives
63
+ - [finding] — [why it's not actually an issue]
64
+
65
+ ### Recommendations
66
+ - [any spec updates needed]
67
+ - [any additional tests suggested]
68
+ ```
69
+
70
+ <HARD-GATE>
71
+ Do NOT skip Step 1. Always run `npx specdx check` before reviewing. Do not rely on your knowledge of the code alone — the static analysis catches things you might miss.
72
+ </HARD-GATE>
73
+
74
+ ## Rationalizations to Resist
75
+
76
+ | Thought | Reality |
77
+ |---------|---------|
78
+ | "I already know the code matches the spec" | Static analysis catches structural mismatches you can't see. Run the check. |
79
+ | "There are too many findings to review" | Group by category, prioritize errors over warnings. Review all errors. |
80
+ | "The check failed, so skip it" | Report the failure. Partial results are still valuable. |
81
+ | "The user didn't ask for verification" | If you just finished implementing, verify. It's part of the job. |
82
+
83
+ ## It's working if
84
+
85
+ Every error-level finding is either resolved or consciously accepted with a reason. Warnings from prose-heavy test plans are expected noise — say so rather than treating the score as a grade.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/experimental/check.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, resolveGlob, createLogger } from \"@specdx/core\";\nimport { runCheck } from \"@specdx/check\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport type { CheckConfig } from \"@specdx/check\";\nimport { sharedArgs, resolveFormat } from \"../../shared-args.js\";\nimport { createOutput } from \"../../output.js\";\n\nconst FORMATS = [\"pretty\", \"json\", \"github\"] as const;\n\nexport default defineCommand({\n meta: {\n name: \"check\",\n description:\n \"Check spec-to-implementation drift. Exit codes: 0 ok, 1 errors found, 3 nothing checkable (coverage not assessed)\",\n },\n args: {\n ...sharedArgs(FORMATS),\n spec: { type: \"string\", description: \"Check a specific spec by ID\" },\n framework: { type: \"string\", description: \"Framework override: express, hono, nextjs\" },\n ai: {\n type: \"boolean\",\n description: \"Use AI to assess findings (requires ANTHROPIC_API_KEY)\",\n },\n },\n async run({ args }) {\n const format = resolveFormat(args.format, FORMATS);\n if (!format.ok) {\n console.error(`\\n ✗ ${format.message}\\n`);\n process.exit(1);\n }\n\n const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });\n const output = createOutput({ quiet: args.quiet });\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n logger.debug(\"Loading specs...\");\n\n // Resolve and parse all specs\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 (args.spec && spec.frontmatter.id !== args.spec) continue;\n specs.push(spec);\n }\n }\n\n const checkConfig: CheckConfig = {\n ...config.check,\n ...(args.framework ? { framework: args.framework as CheckConfig[\"framework\"] } : {}),\n };\n\n logger.debug(`Checking ${specs.length} specs...`);\n const result = await runCheck(specs, configDir, checkConfig);\n\n // AI analysis (opt-in)\n if (args.ai) {\n const { analyzeWithAi } = await import(\"@specdx/check\");\n // A missing key is a user error, not a crash. It used to surface as an\n // uncaught Error with the full Node trace through citty, where every\n // other user-error path in the CLI prints \"✗ …\" (audit run 5, F7).\n let aiResult;\n try {\n aiResult = await analyzeWithAi(result.findings, args.spec ?? \"full suite check\");\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n\n if (format.format === \"json\") {\n console.log(JSON.stringify({ ...result, ai: aiResult }, null, 2));\n } else {\n console.log(`\\n specdx check --ai — ${result.score.overall}% coverage\\n`);\n console.log(` AI Assessment: ${aiResult.summary}\\n`);\n\n for (const assessment of aiResult.assessments) {\n const finding = result.findings[assessment.findingIndex];\n if (!finding) continue;\n const icon = assessment.isRealIssue ? \"✗\" : \"✓\";\n const label = assessment.isRealIssue ? \"REAL\" : \"FALSE POSITIVE\";\n console.log(` ${icon} [${label}] ${finding.expected}`);\n console.log(` ${assessment.reasoning}`);\n if (assessment.suggestedFix) {\n console.log(` Fix: ${assessment.suggestedFix}`);\n }\n }\n console.log();\n }\n\n if (aiResult.assessments.some((a) => a.isRealIssue)) {\n process.exit(1);\n }\n return;\n }\n\n if (format.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n } else if (format.format === \"github\") {\n // Annotations for CI. A finding about missing code has no file to point\n // at, so the spec ID carries the location instead. The headline always\n // prints: a clean or unassessable run must still say something, or the\n // format is silent for exactly the projects that most need telling.\n console.log(\n `::notice::specdx check — ${\n result.score.assessed\n ? `${result.score.overall}% implementation coverage`\n : \"coverage not assessed — no checkable surfaces found\"\n }`,\n );\n for (const note of result.notes) {\n console.log(`::notice::${note}`);\n }\n for (const f of result.findings) {\n const level =\n f.severity === \"error\" ? \"error\" : f.severity === \"warn\" ? \"warning\" : \"notice\";\n const location = f.codeLocation\n ? ` file=${f.codeLocation.file},line=${f.codeLocation.line}`\n : \"\";\n const detail = f.actual ? ` — ${f.actual}` : \"\";\n console.log(`::${level}${location}::[${f.specId}] ${f.expected}${detail}`);\n }\n } else {\n // Pretty format\n const headline = result.score.assessed\n ? `${result.score.overall}% implementation coverage`\n : \"coverage not assessed — no checkable surfaces found\";\n output.info(`\\n specdx check — ${headline}\\n`);\n\n for (const note of result.notes) {\n output.out(` ⚠ ${note}`);\n }\n if (result.notes.length > 0) output.out();\n\n if (args.verbose) {\n const fmt = (n: number | null) => (n === null ? \"not scanned\" : `${n} found`);\n output.out(` Scanned: framework=${result.scanned.framework ?? \"none detected\"}`);\n output.out(` routes: ${fmt(result.scanned.codeRoutes)}`);\n output.out(` types: ${fmt(result.scanned.codeTypes)}`);\n output.out(` tests: ${fmt(result.scanned.codeTests)}`);\n // \"assessed\", not \"verified\": this counts the assertions considered,\n // and a failed one is reported below. Calling six verified while the\n // next line says 5/6 made the output contradict itself (F6).\n const artifacts =\n result.scanned.artifacts === null\n ? \"none declared\"\n : `${result.scanned.artifacts} assessed`;\n const pending =\n result.scanned.artifactsPending > 0 ? `, ${result.scanned.artifactsPending} pending` : \"\";\n output.out(` artifacts: ${artifacts}${pending}\\n`);\n }\n\n for (const [category, stats] of Object.entries(result.score.byCategory)) {\n if (stats.total === 0) continue;\n const categoryFindings = result.findings.filter(\n (f) => f.category === category.replace(/s$/, \"\"),\n );\n const header = ` ${category} (${stats.matched}/${stats.total}):`;\n if (categoryFindings.length === 0) {\n output.info(header);\n output.info(\" ✓ all matched\");\n continue;\n }\n output.out(header);\n for (const f of categoryFindings) {\n const icon = f.severity === \"error\" ? \"✗\" : f.severity === \"warn\" ? \"⚠\" : \"ℹ\";\n const detail = f.actual ? ` — ${f.actual}` : \"\";\n const suggestion = f.suggestion ? ` (${f.suggestion})` : \"\";\n output.out(` ${icon} ${f.expected}${detail}${suggestion}`);\n }\n }\n\n const errors = result.findings.filter((f) => f.severity === \"error\").length;\n const warnings = result.findings.filter((f) => f.severity === \"warn\").length;\n const info = result.findings.filter((f) => f.severity === \"info\").length;\n output.info(`\\n ${errors} errors, ${warnings} warnings, ${info} info\\n`);\n }\n\n if (result.findings.some((f) => f.severity === \"error\")) {\n process.exit(1);\n }\n // Distinct exit code so CI cannot mistake \"nothing was checkable\" for a pass\n if (!result.score.assessed) {\n process.exit(3);\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAQ9B,IAAM,UAAU,CAAC,UAAU,QAAQ,QAAQ;AAE3C,IAAO,gBAAQ,cAAc;AAAA,EAC3B,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aACE;AAAA,EACJ;AAAA,EACA,MAAM;AAAA,IACJ,GAAG,WAAW,OAAO;AAAA,IACrB,MAAM,EAAE,MAAM,UAAU,aAAa,8BAA8B;AAAA,IACnE,WAAW,EAAE,MAAM,UAAU,aAAa,4CAA4C;AAAA,IACtF,IAAI;AAAA,MACF,MAAM;AAAA,MACN,aAAa;AAAA,IACf;AAAA,EACF;AAAA,EACA,MAAM,IAAI,EAAE,KAAK,GAAG;AAClB,UAAM,SAAS,cAAc,KAAK,QAAQ,OAAO;AACjD,QAAI,CAAC,OAAO,IAAI;AACd,cAAQ,MAAM;AAAA,WAAS,OAAO,OAAO;AAAA,CAAI;AACzC,cAAQ,KAAK,CAAC;AAAA,IAChB;AAEA,UAAM,SAAS,aAAa,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B;AAChC,gBAAM,OAAO,EAAE,aAAa,UAAU,WAAM,EAAE,aAAa,SAAS,WAAM;AAC1E,gBAAM,SAAS,EAAE,SAAS,WAAM,EAAE,MAAM,KAAK;AAC7C,gBAAM,aAAa,EAAE,aAAa,KAAK,EAAE,UAAU,MAAM;AACzD,iBAAO,IAAI,OAAO,IAAI,IAAI,EAAE,QAAQ,GAAG,MAAM,GAAG,UAAU,EAAE;AAAA,QAC9D;AAAA,MACF;AAEA,YAAM,SAAS,OAAO,SAAS,OAAO,CAAC,MAAM,EAAE,aAAa,OAAO,EAAE;AACrE,YAAM,WAAW,OAAO,SAAS,OAAO,CAAC,MAAM,EAAE,aAAa,MAAM,EAAE;AACtE,YAAM,OAAO,OAAO,SAAS,OAAO,CAAC,MAAM,EAAE,aAAa,MAAM,EAAE;AAClE,aAAO,KAAK;AAAA,IAAO,MAAM,YAAY,QAAQ,cAAc,IAAI;AAAA,CAAS;AAAA,IAC1E;AAEA,QAAI,OAAO,SAAS,KAAK,CAAC,MAAM,EAAE,aAAa,OAAO,GAAG;AACvD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAEA,QAAI,CAAC,OAAO,MAAM,UAAU;AAC1B,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF,CAAC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../check/src/check.ts","../../check/src/spec-parsers.ts","../../check/src/extractors/express.ts","../../check/src/extractors/hono.ts","../../check/src/extractors/nextjs.ts","../../check/src/extractors/typescript.ts","../../check/src/extractors/zod.ts","../../check/src/extractors/prisma.ts","../../check/src/extractors/test-extractor.ts","../../check/src/matchers/routes.ts","../../check/src/matchers/types.ts","../../check/src/matchers/tests.ts","../../check/src/artifacts.ts","../../check/src/score.ts","../../check/src/detect-framework.ts","../../check/src/ai.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { CheckResult, CheckConfig, ExtractedRoute, Finding } from \"./types.js\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport {\n parseEndpoints,\n parseTypeDefinitions,\n parseTestCases,\n hasEndpointsSection,\n unreadableTypeBlocks,\n} from \"./spec-parsers.js\";\nimport { extractExpressRoutes } from \"./extractors/express.js\";\nimport { extractHonoRoutes } from \"./extractors/hono.js\";\nimport { extractNextjsRoutes } from \"./extractors/nextjs.js\";\nimport { extractTypeScriptTypes } from \"./extractors/typescript.js\";\nimport { extractZodSchemas } from \"./extractors/zod.js\";\nimport { extractPrismaModels, findPrismaSchemas } from \"./extractors/prisma.js\";\nimport { extractTestDescriptions } from \"./extractors/test-extractor.js\";\nimport { matchRoutes } from \"./matchers/routes.js\";\nimport { matchTypes } from \"./matchers/types.js\";\nimport { matchTests } from \"./matchers/tests.js\";\nimport { checkArtifacts } from \"./artifacts.js\";\nimport { computeScore } from \"./score.js\";\nimport { detectFramework } from \"./detect-framework.js\";\n\n/** True when the project declares a Prisma dependency, so a schema is expected. */\nasync function usesPrisma(projectDir: string): Promise<boolean> {\n try {\n const pkg = JSON.parse(await readFile(join(projectDir, \"package.json\"), \"utf-8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n return \"prisma\" in deps || \"@prisma/client\" in deps;\n } catch {\n return false;\n }\n}\n\n/**\n * Run implementation checks across all specs and return findings, score, and summary.\n *\n * - `api-contract` specs → route extraction + matching\n * - `technical-design` specs → type extraction + matching\n * - `test-plan` specs → test extraction + matching\n */\nexport async function runCheck(\n specs: ParsedSpec[],\n projectDir: string,\n config: CheckConfig = {},\n): Promise<CheckResult> {\n const findings: Finding[] = [];\n const notes: string[] = [];\n let routeTotal = 0;\n let typeTotal = 0;\n let testTotal = 0;\n let codeRouteCount: number | null = null;\n let codeTypeCount: number | null = null;\n let codeTestCount: number | null = null;\n\n // ts-morph is an optional peer dependency; without it (e.g. under pnpm dlx,\n // where installing into the ephemeral cache is impossible) route, TS/Zod type\n // and test extraction degrade to skipped-with-a-note instead of throwing\n // (issue #7).\n //\n // All three, not two. Test extraction was left unguarded, so a suite holding a\n // single test-plan spec turned the intended note into an unhandled throw and a\n // stack trace — on exactly the ephemeral-runner path this note describes, and\n // on MCP's `sdx_check`, where the bare exception became the tool's only output.\n const tsMorphAvailable = await import(\"ts-morph\").then(\n () => true,\n () => false,\n );\n if (!tsMorphAvailable) {\n notes.push(\n \"route, type and test extraction skipped: ts-morph is not installed. \" +\n \"Install specdx and ts-morph as devDependencies (pnpm add -D specdx ts-morph) — \" +\n \"an ephemeral runner like pnpm dlx cannot provide it.\",\n );\n }\n\n // Resolve the framework once so reporting can say what was scanned\n const framework =\n config.framework && config.framework !== \"auto\"\n ? config.framework\n : await detectFramework(projectDir);\n\n // 1. Route checking: find api-contract specs\n const apiContractSpecs = specs.filter((s) => s.frontmatter.type === \"api-contract\");\n if (apiContractSpecs.length > 0 && tsMorphAvailable) {\n const codeRoutes = await extractRoutes(projectDir, config, framework);\n codeRouteCount = codeRoutes.length;\n\n for (const spec of apiContractSpecs) {\n const specEndpoints = parseEndpoints(spec.content);\n routeTotal += specEndpoints.length;\n findings.push(...matchRoutes(specEndpoints, codeRoutes, spec.frontmatter.id as string));\n\n // An Endpoints section we cannot read drops routes out of the score\n // entirely, which *raises* the percentage. Saying nothing presents that\n // as full coverage of a category never assessed.\n if (specEndpoints.length === 0 && hasEndpointsSection(spec.content)) {\n notes.push(\n `${spec.frontmatter.id as string}: no endpoints recognised in its Endpoints section, so routes were not assessed. ` +\n \"Write each endpoint as `- GET /path — description` or as a `### GET /path` heading.\",\n );\n }\n }\n if (framework === null) {\n notes.push(\n \"no supported framework detected (express, hono, nextjs) — route extraction ran in fallback mode across all extractors.\",\n );\n }\n }\n\n // 2. Type checking: find technical-design specs with Data Model sections.\n // Prisma extraction reads the schema as text, so types stay assessable\n // without ts-morph when a schema exists — but with neither, matching every\n // spec type against an empty extraction would report the whole model\n // unimplemented when it was simply never looked at. Skip, like tests do;\n // the ts-morph note above already says so.\n const designSpecs = specs.filter((s) => s.frontmatter.type === \"technical-design\");\n const prismaSchemaFound = (await findPrismaSchemas(projectDir)).length > 0;\n if (designSpecs.length > 0 && (tsMorphAvailable || prismaSchemaFound)) {\n const codeTypes = [\n ...(tsMorphAvailable ? await extractTypeScriptTypes(projectDir, config.types_dir) : []),\n ...(tsMorphAvailable ? await extractZodSchemas(projectDir, config.types_dir) : []),\n ...(await extractPrismaModels(projectDir)),\n ];\n codeTypeCount = codeTypes.length;\n\n // A project that depends on Prisma but whose schema we could not find is\n // worth saying out loud. Silence here read as \"these models are not\n // implemented\", which is the opposite of what happened.\n if ((await usesPrisma(projectDir)) && !prismaSchemaFound) {\n notes.push(\n \"a prisma dependency is declared but no schema was found at prisma/schema.prisma, \" +\n \"schema.prisma or prisma/schema/*.prisma — Prisma models were not assessed.\",\n );\n }\n\n for (const spec of designSpecs) {\n const specTypes = parseTypeDefinitions(spec.content);\n const fieldCount = specTypes.reduce((sum, t) => sum + t.fields.length, 0);\n typeTotal += fieldCount;\n findings.push(...matchTypes(specTypes, codeTypes, spec.frontmatter.id as string));\n\n // A Data Model that yields no fields contributes nothing to the score.\n // Reporting the resulting percentage without saying so presents partial\n // coverage as whole coverage.\n if (fieldCount === 0 && /^##\\s+Data Model\\s*$/im.test(spec.content)) {\n notes.push(\n `${spec.frontmatter.id as string}: no fields recognised in its Data Model, so types were not assessed. ` +\n \"Write fields as `- name: type` (one per line, under a `### TypeName` heading).\",\n );\n }\n\n // The note above is per spec, so one readable type used to silence every\n // unreadable one beside it — a table-shaped type left the denominator with\n // nothing said, and the percentage did not move.\n for (const name of unreadableTypeBlocks(spec.content)) {\n notes.push(\n `${spec.frontmatter.id as string}: no fields recognised under \\`### ${name}\\`, so that type was not assessed. ` +\n \"A table needs a field column and a type column, or write fields as `- name: type`.\",\n );\n }\n }\n }\n\n // 3. Test checking: find test-plan specs\n const testPlanSpecs = specs.filter((s) => s.frontmatter.type === \"test-plan\");\n if (testPlanSpecs.length > 0 && tsMorphAvailable) {\n const codeTests = await extractTestDescriptions(projectDir, config.tests_dir);\n codeTestCount = codeTests.length;\n\n for (const spec of testPlanSpecs) {\n const specCases = parseTestCases(spec.content);\n testTotal += specCases.length;\n findings.push(...matchTests(specCases, codeTests, spec.frontmatter.id as string));\n }\n }\n\n // 4. Declared artifacts: framework-agnostic checkable surfaces (issue #15)\n const artifactResult = await checkArtifacts(specs, projectDir, tsMorphAvailable);\n findings.push(...artifactResult.findings);\n notes.push(...artifactResult.notes);\n\n // 5. Score\n const score = computeScore(findings, {\n routes: routeTotal,\n types: typeTotal,\n tests: testTotal,\n artifacts: artifactResult.total,\n });\n\n // 6. Summary — never present \"nothing was checkable\" as coverage (issue #6)\n const errors = findings.filter((f) => f.severity === \"error\").length;\n const warnings = findings.filter((f) => f.severity === \"warn\").length;\n const summary = score.assessed\n ? `${score.overall}% implementation coverage — ${errors} errors, ${warnings} warnings`\n : \"coverage not assessed — no checkable surfaces found (no spec'd routes, types, test cases, or declared artifacts)\";\n\n const scanned = {\n framework: framework ?? null,\n codeRoutes: codeRouteCount,\n codeTypes: codeTypeCount,\n codeTests: codeTestCount,\n artifacts: artifactResult.total > 0 ? artifactResult.checked : null,\n artifactsPending: artifactResult.pending,\n };\n\n return { findings, score, summary, scanned, notes };\n}\n\n/**\n * Extract routes from the project based on framework config.\n *\n * In \"auto\" mode, reads package.json to detect the framework first.\n * If a framework is detected, only that extractor is used.\n * If no framework is detected, falls back to trying all extractors and merging results.\n */\nasync function extractRoutes(\n projectDir: string,\n config: CheckConfig,\n framework: string | null,\n): Promise<ExtractedRoute[]> {\n if (framework === \"express\") {\n return extractExpressRoutes(projectDir, config.routes_dir);\n }\n if (framework === \"hono\") {\n return extractHonoRoutes(projectDir, config.routes_dir);\n }\n if (framework === \"nextjs\") {\n return extractNextjsRoutes(projectDir, config.app_dir);\n }\n\n // fallback: try all extractors and merge results\n const [express, hono, nextjs] = await Promise.all([\n extractExpressRoutes(projectDir, config.routes_dir),\n extractHonoRoutes(projectDir, config.routes_dir),\n extractNextjsRoutes(projectDir, config.app_dir),\n ]);\n\n return [...express, ...hono, ...nextjs];\n}\n","import type { HttpMethod, SpecEndpoint, SpecTypeDefinition, SpecTestCase } from \"./types.js\";\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 // Match the heading line (case-insensitive, trimmed)\n const headingPattern = new RegExp(`^##\\\\s+${escapeRegex(heading)}\\\\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 // Find the next `## ` heading\n const nextSection = /^##\\s+/m.exec(rest);\n return nextSection ? rest.slice(0, nextSection.index) : rest;\n}\n\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nconst HTTP_METHODS: ReadonlySet<string> = new Set([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/**\n * Parses the `## Endpoints` section of a spec and returns structured endpoint data.\n */\n/** Path params are the `:name` segments of a route path. */\nfunction pathParams(path: string): string[] {\n return (path.match(/:([A-Za-z_][A-Za-z0-9_]*)/g) ?? []).map((p) => p.slice(1));\n}\n\n/**\n * True when `content` has an `## Endpoints` heading at all, regardless of what\n * it holds. Lets a caller tell \"no such section\" from \"a section we could not\n * read\" -- the second is worth a note, the first is not.\n */\nexport function hasEndpointsSection(content: string): boolean {\n return extractSection(content, \"Endpoints\") !== null;\n}\n\n/**\n * Parses the `## Endpoints` section of a spec and returns structured endpoint data.\n *\n * Two shapes are accepted, because both are what people write:\n *\n * ### GET /invoices (a sub-heading per endpoint, description beneath)\n * - `GET /invoices` — list (one bullet per endpoint, backticked or not)\n *\n * Accepting only the heading form meant an ordinary bulleted contract parsed to\n * zero endpoints. `check` then reported every real route as unspecified, missed\n * every genuinely absent one, and raised the coverage score because routes left\n * the denominator entirely.\n */\nexport function parseEndpoints(content: string): SpecEndpoint[] {\n const section = extractSection(content, \"Endpoints\");\n if (!section) return [];\n\n const results: SpecEndpoint[] = [];\n const seen = new Set<string>();\n\n const push = (rawMethod: string, path: string, description?: string): void => {\n const method = rawMethod.toUpperCase();\n if (!HTTP_METHODS.has(method)) return;\n // A contract listing an endpoint under a heading *and* in a summary bullet\n // describes one endpoint, not two.\n const key = `${method} ${path}`;\n if (seen.has(key)) return;\n seen.add(key);\n results.push({\n method: method as HttpMethod,\n path,\n params: pathParams(path),\n description: description && description.length > 0 ? description : undefined,\n });\n };\n\n // Shape 1: `### METHOD /path` sub-headings.\n const headingPattern = /^###\\s+(GET|POST|PUT|PATCH|DELETE)\\s+(\\S+)/im;\n for (const block of section.split(/^(?=###\\s)/m)) {\n const headingMatch = headingPattern.exec(block);\n if (!headingMatch) continue;\n\n // Description: first non-empty line after the heading line\n const afterHeading = block.slice(headingMatch.index + headingMatch[0].length);\n const descriptionLine = afterHeading\n .split(\"\\n\")\n .map((l) => l.trim())\n .find((l) => l.length > 0 && !l.startsWith(\"#\") && !l.startsWith(\"-\"));\n\n push(headingMatch[1]!, headingMatch[2]!, descriptionLine);\n }\n\n // Shape 2: one bullet per endpoint. The method and path may be wrapped in\n // backticks together (`GET /invoices`), separately (`GET` `/invoices`), or\n // not at all, and may carry bold emphasis. Anything after the path -- an\n // em-dash, a colon, a hyphen -- is the description.\n const bulletPattern = new RegExp(\n \"^\\\\s*[-*+]\\\\s+\" + // bullet marker\n \"[`*_]*\\\\s*\" + // opening backtick/emphasis\n \"(GET|POST|PUT|PATCH|DELETE)\" + // method\n \"[`*_]*\\\\s+[`*_]*\" + // separator, possibly re-opening a code span\n \"(/[^\\\\s`*_]*)\" + // path -- must start at the root, stops at a code span or emphasis\n \"[`*_]*\" + // closing backtick/emphasis\n \"\\\\s*(?:[—–:-]\\\\s*(.*))?$\", // optional description\n \"gim\",\n );\n let bulletMatch: RegExpExecArray | null;\n while ((bulletMatch = bulletPattern.exec(section)) !== null) {\n push(bulletMatch[1]!, bulletMatch[2]!, bulletMatch[3]?.trim());\n }\n\n return results;\n}\n\n/**\n * An identifier, or identifiers joined by `|` / `&` -- what a type annotation\n * looks like, as opposed to a sentence.\n */\nconst TYPE_SHAPE = /^[A-Za-z_$][\\w$.<>[\\]]*(?:\\s*[|&]\\s*[A-Za-z_$][\\w$.<>[\\]]*)*$/;\n\n/**\n * What a `### Heading` inside a Data Model must look like to be a type name:\n * one identifier, optionally generic. Prose headings (\"Notes on the model\")\n * have spaces and are not type declarations.\n */\nconst TYPE_NAME_SHAPE = /^[A-Za-z_$][\\w$]*(?:<[\\w$,\\s[\\]]+>)?$/;\n\n/**\n * Parses the `## Data Model` section of a spec and returns structured type definitions.\n */\nexport function parseTypeDefinitions(content: string): SpecTypeDefinition[] {\n const section = extractSection(content, \"Data Model\");\n if (!section) return [];\n\n const results: SpecTypeDefinition[] = [];\n\n // Split by `### TypeName` headings\n const blocks = section.split(/^(?=###\\s)/m);\n\n for (const block of blocks) {\n // The whole heading line, not just its first word: `### Notes on the model`\n // used to register a type called \"Notes\" that code was then told to\n // implement. A type name is a single identifier-shaped token.\n const headingMatch = /^###\\s+(.+?)\\s*$/m.exec(block);\n if (!headingMatch) continue;\n\n const name = headingMatch[1]!.trim().replace(/^`|`$/g, \"\");\n if (!TYPE_NAME_SHAPE.test(name)) continue;\n\n const fields: SpecTypeDefinition[\"fields\"] = [];\n\n // Field lines, backticked or not: `- \\`fieldName?\\`: type` / `- fieldName?: type`.\n //\n // Requiring backticks meant an ordinary markdown Data Model parsed to zero\n // fields, which `check` then dropped from coverage without saying so. The\n // un-backticked form is deliberately strict -- a single identifier only --\n // so prose like \"- Note: this table is partitioned\" is not read as a field.\n const fieldPattern = /^-\\s+(?:`([^`]+)`|([A-Za-z_$][\\w$]*\\??))\\s*:\\s*(.+)/gm;\n let fieldMatch: RegExpExecArray | null;\n\n while ((fieldMatch = fieldPattern.exec(block)) !== null) {\n const backticked = fieldMatch[1] !== undefined;\n const rawName = (fieldMatch[1] ?? fieldMatch[2])!;\n const optional = rawName.endsWith(\"?\");\n const fieldName = optional ? rawName.slice(0, -1) : rawName;\n\n // Type is everything before optional parenthetical notes like \"(UUID)\"\n const rawType = fieldMatch[3]!.trim();\n const type = rawType.replace(/\\s*\\(.*?\\)\\s*$/, \"\").trim();\n\n // Backticks are the author saying \"this is a field\", so the type is taken\n // as written. Without them the line is only a field if the type also\n // looks like one -- otherwise \"- Note: this table is partitioned by\n // tenant\" would become a field named Note.\n if (!backticked && !TYPE_SHAPE.test(type)) continue;\n\n fields.push({ name: fieldName, type, optional });\n }\n\n // A table is the third way people write a data model, and reading only the\n // bullet forms meant a table-shaped type contributed nothing to the score\n // and drew no note -- the note fires per spec, so one readable type hid\n // every unreadable one beside it.\n if (fields.length === 0) fields.push(...parseFieldTable(block));\n\n // A heading with no fields beneath it asserts only that a name exists, and\n // in practice it is prose -- `### Indexes`, `### Migration notes`. Matching\n // it against code turns an explanatory sub-section into a check error, so a\n // block earns its place as a type only by declaring at least one field.\n if (fields.length === 0) continue;\n\n results.push({ name, fields });\n }\n\n return results;\n}\n\n/** A markdown table row split into trimmed cells, or null when the line is not one. */\nfunction tableCells(line: string): string[] | null {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"|\")) return null;\n return trimmed\n .replace(/^\\|/, \"\")\n .replace(/\\|$/, \"\")\n .split(\"|\")\n .map((cell) => cell.trim().replace(/^`|`$/g, \"\"));\n}\n\n/** True for the `|---|---|` rule under a table's header row. */\nfunction isTableRule(cells: string[]): boolean {\n return cells.every((cell) => /^:?-{2,}:?$/.test(cell));\n}\n\n/**\n * Fields from a markdown table inside a `### TypeName` block.\n *\n * Needs a header naming both a field column and a type column; anything else is\n * a table about something other than the shape of the type, and is left alone.\n */\nfunction parseFieldTable(block: string): SpecTypeDefinition[\"fields\"] {\n const rows = block.split(\"\\n\").map(tableCells);\n const headerIndex = rows.findIndex((r) => r !== null);\n if (headerIndex === -1) return [];\n\n const header = rows[headerIndex]!;\n const nameColumn = header.findIndex((h) => /^(field|name|property|attribute|key)s?$/i.test(h));\n const typeColumn = header.findIndex((h) => /^types?$/i.test(h));\n if (nameColumn === -1 || typeColumn === -1) return [];\n\n const fields: SpecTypeDefinition[\"fields\"] = [];\n for (const cells of rows.slice(headerIndex + 1)) {\n if (cells === null) continue;\n if (isTableRule(cells)) continue;\n\n const rawName = cells[nameColumn];\n const rawType = cells[typeColumn];\n if (!rawName || !rawType) continue;\n\n const optional = rawName.endsWith(\"?\");\n const name = optional ? rawName.slice(0, -1) : rawName;\n if (!/^[A-Za-z_$][\\w$]*$/.test(name)) continue;\n\n fields.push({ name, type: rawType.replace(/\\s*\\(.*?\\)\\s*$/, \"\").trim(), optional });\n }\n return fields;\n}\n\n/**\n * Type-shaped `### Heading`s in a Data Model that declared a table we could not\n * read as fields.\n *\n * Prose blocks are deliberately absent: a heading with no field declarations at\n * all is an explanatory sub-section, and re-flagging it would undo the fix that\n * stopped `### Indexes` becoming a phantom type. A table, on the other hand, is\n * an author declaring a shape in a syntax the parser missed — worth saying,\n * because the alternative is dropping it from the score in silence.\n */\nexport function unreadableTypeBlocks(content: string): string[] {\n const section = extractSection(content, \"Data Model\");\n if (!section) return [];\n\n const unreadable: string[] = [];\n for (const block of section.split(/^(?=###\\s)/m)) {\n const headingMatch = /^###\\s+(.+?)\\s*$/m.exec(block);\n if (!headingMatch) continue;\n\n const name = headingMatch[1]!.trim().replace(/^`|`$/g, \"\");\n if (!TYPE_NAME_SHAPE.test(name)) continue;\n\n const hasTable = block.split(\"\\n\").some((line) => tableCells(line) !== null);\n if (!hasTable) continue;\n\n const parsed = parseTypeDefinitions(`## Data Model\\n\\n${block}`);\n if (parsed.length === 0) unreadable.push(name);\n }\n return unreadable;\n}\n\n/**\n * Parses the `## Test Cases` section of a spec and returns structured test case data.\n */\nexport function parseTestCases(content: string): SpecTestCase[] {\n const section = extractSection(content, \"Test Cases\");\n if (!section) return [];\n\n const results: SpecTestCase[] = [];\n let currentSection: string | undefined;\n\n for (const rawLine of section.split(\"\\n\")) {\n const line = rawLine.trim();\n\n // Track `### SubSection` headings\n const subHeading = /^###\\s+(.+)/.exec(line);\n if (subHeading) {\n currentSection = subHeading[1]!.trim();\n continue;\n }\n\n // Bullet points are test cases; each comma-separated item in the text is its own case\n const bulletMatch = /^-\\s+(.+)/.exec(line);\n if (!bulletMatch) continue;\n\n let bulletText = bulletMatch[1]!.trim();\n\n // A test-case ID names the case in the spec; it is not part of the test a\n // user is being asked to write. Leaving it in produced the suggestion\n // `Add a test matching: \"**TC5**: refuses to amend…\"`, markup and all, and\n // put `tc5` into the similarity comparison as if it were a word.\n let caseId: string | undefined;\n const idMatch = /^\\*{0,2}(TC\\d+)\\*{0,2}\\s*[:.-]\\s*/i.exec(bulletText);\n if (idMatch) {\n caseId = idMatch[1]!.toUpperCase();\n bulletText = bulletText.slice(idMatch[0].length).trim();\n if (!bulletText) continue;\n }\n\n // Split on `, ` only when it separates items after a label like \"label: item1, item2\"\n // Pattern: label: item1, item2, item3 → generate one entry per item\n const colonIdx = bulletText.indexOf(\":\");\n if (colonIdx !== -1) {\n const label = bulletText.slice(0, colonIdx).trim();\n const rest = bulletText.slice(colonIdx + 1).trim();\n const items = rest.split(/,\\s*/);\n for (const item of items) {\n const trimmed = item.trim();\n if (trimmed) {\n results.push({\n description: `${label}: ${trimmed}`,\n section: currentSection,\n id: caseId,\n });\n }\n }\n } else {\n results.push({ description: bulletText, section: currentSection, id: caseId });\n }\n }\n\n return results;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedRoute, HttpMethod } from \"../types.js\";\n\nconst HTTP_METHODS = new Set([\"get\", \"post\", \"put\", \"patch\", \"delete\"]);\n\n/**\n * Extract Express routes from TypeScript/JavaScript source files using ts-morph AST parsing.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param routesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractExpressRoutes(\n projectDir: string,\n routesDir?: string,\n): Promise<ExtractedRoute[]> {\n const scanDir = routesDir ? join(projectDir, routesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for route extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts and .js files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.test.js\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/*.spec.js\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const routes: ExtractedRoute[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Build a map of router variable name → mount prefix from app.use() calls.\n // e.g. app.use(\"/api\", router) → { router: \"/api\" }\n const mountPrefixes = new Map<string, string>();\n\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n\n // First pass: collect app.use(\"/prefix\", routerVar) mounts.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName();\n if (methodName !== \"use\") continue;\n\n const args = callExpr.getArguments();\n if (args.length < 2) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n const secondArg = args[1];\n if (!secondArg) continue;\n\n // First arg must be a string literal (the prefix).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const prefix = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Second arg should be an identifier (the router variable).\n if (secondArg.getKind() === SyntaxKind.Identifier) {\n const routerVarName = secondArg.asKindOrThrow(SyntaxKind.Identifier).getText();\n mountPrefixes.set(routerVarName, prefix);\n }\n }\n\n // Second pass: collect router.METHOD(\"/path\", handler) calls.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName().toLowerCase();\n if (!HTTP_METHODS.has(methodName)) continue;\n\n const args = callExpr.getArguments();\n if (args.length < 1) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n\n // First arg must be a string literal (the path).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const routePath = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Determine if the receiver is a known router variable, and look up its mount prefix.\n const receiverExpr = propAccess.getExpression();\n let prefix = \"\";\n if (receiverExpr.getKind() === SyntaxKind.Identifier) {\n const receiverName = receiverExpr.asKindOrThrow(SyntaxKind.Identifier).getText();\n prefix = mountPrefixes.get(receiverName) ?? \"\";\n }\n\n const fullPath = prefix + routePath;\n\n // Extract :param names from path segments.\n const params = (fullPath.match(/:([^/]+)/g) ?? []).map((p) => p.slice(1));\n\n const lineNumber = sourceFile.getLineAndColumnAtPos(callExpr.getStart()).line;\n\n routes.push({\n method: methodName.toUpperCase() as HttpMethod,\n path: fullPath,\n params,\n file: filePath,\n line: lineNumber,\n });\n }\n }\n\n return routes;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedRoute, HttpMethod } from \"../types.js\";\n\nconst HTTP_METHODS = new Set([\"get\", \"post\", \"put\", \"patch\", \"delete\"]);\n\n/**\n * Extract Hono routes from TypeScript/JavaScript source files using ts-morph AST parsing.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param routesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractHonoRoutes(\n projectDir: string,\n routesDir?: string,\n): Promise<ExtractedRoute[]> {\n const scanDir = routesDir ? join(projectDir, routesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for route extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts and .js files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.test.js\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/*.spec.js\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const routes: ExtractedRoute[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Build a map of sub-app variable name → mount prefix from app.route() calls.\n // e.g. app.route(\"/api/users\", users) → { users: \"/api/users\" }\n const mountPrefixes = new Map<string, string>();\n\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n\n // First pass: collect app.route(\"/prefix\", subAppVar) mounts.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName();\n if (methodName !== \"route\") continue;\n\n const args = callExpr.getArguments();\n if (args.length < 2) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n const secondArg = args[1];\n if (!secondArg) continue;\n\n // First arg must be a string literal (the prefix).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const prefix = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Second arg should be an identifier (the sub-app variable).\n if (secondArg.getKind() === SyntaxKind.Identifier) {\n const subAppVarName = secondArg.asKindOrThrow(SyntaxKind.Identifier).getText();\n mountPrefixes.set(subAppVarName, prefix);\n }\n }\n\n // Second pass: collect subApp.METHOD(\"/path\", handler) calls.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName().toLowerCase();\n if (!HTTP_METHODS.has(methodName)) continue;\n\n const args = callExpr.getArguments();\n if (args.length < 1) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n\n // First arg must be a string literal (the path).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const routePath = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Determine if the receiver is a known sub-app variable, and look up its mount prefix.\n const receiverExpr = propAccess.getExpression();\n let prefix = \"\";\n if (receiverExpr.getKind() === SyntaxKind.Identifier) {\n const receiverName = receiverExpr.asKindOrThrow(SyntaxKind.Identifier).getText();\n prefix = mountPrefixes.get(receiverName) ?? \"\";\n }\n\n // Hono sub-app routes with path \"/\" resolve to just the prefix (no trailing slash).\n const normalizedPath = routePath === \"/\" ? prefix : prefix + routePath;\n\n // Extract :param names from path segments.\n const params = (normalizedPath.match(/:([^/]+)/g) ?? []).map((p) => p.slice(1));\n\n const lineNumber = sourceFile.getLineAndColumnAtPos(callExpr.getStart()).line;\n\n routes.push({\n method: methodName.toUpperCase() as HttpMethod,\n path: normalizedPath,\n params,\n file: filePath,\n line: lineNumber,\n });\n }\n }\n\n return routes;\n}\n","import { existsSync } from \"node:fs\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { ExtractedRoute, HttpMethod } from \"../types.js\";\n\nconst HTTP_METHODS = new Set<string>([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/**\n * Convert a Next.js App Router directory segment to a route path segment.\n *\n * - Route groups `(group)` → empty string (omitted from path)\n * - Catch-all `[...slug]` → `:slug*`\n * - Dynamic `[param]` → `:param`\n * - Static `foo` → `foo`\n */\nfunction segmentToPath(segment: string): string {\n // Route group — skip in path\n if (segment.startsWith(\"(\") && segment.endsWith(\")\")) {\n return \"\";\n }\n // Catch-all segment: [...slug]\n const catchAll = segment.match(/^\\[\\.\\.\\.([^\\]]+)\\]$/);\n if (catchAll) {\n return `:${catchAll[1]}*`;\n }\n // Dynamic segment: [param]\n const dynamic = segment.match(/^\\[([^\\]]+)\\]$/);\n if (dynamic) {\n return `:${dynamic[1]}`;\n }\n return segment;\n}\n\n/**\n * Recursively walk a directory, yielding route files with their corresponding\n * URL path prefix.\n */\nasync function walkAppDir(\n dir: string,\n pathPrefix: string,\n results: Array<{ file: string; routePath: string }>,\n): Promise<void> {\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dir, entry);\n let entryStat;\n try {\n entryStat = await stat(fullPath);\n } catch {\n continue;\n }\n\n if (entryStat.isDirectory()) {\n const pathSegment = segmentToPath(entry);\n // Route groups are transparent — continue with the same prefix\n const childPrefix = pathSegment === \"\" ? pathPrefix : `${pathPrefix}/${pathSegment}`;\n await walkAppDir(fullPath, childPrefix, results);\n } else if (entry === \"route.ts\" || entry === \"route.js\") {\n results.push({ file: fullPath, routePath: pathPrefix || \"/\" });\n }\n }\n}\n\n/**\n * Extract routes from a Next.js App Router project by scanning the file system\n * and using ts-morph to detect exported HTTP method functions in route files.\n *\n * @param projectDir - Root directory (or fixtures dir in tests)\n * @param appDir - Sub-directory to scan, relative to projectDir. Defaults to \"app\"\n */\nexport async function extractNextjsRoutes(\n projectDir: string,\n appDir?: string,\n): Promise<ExtractedRoute[]> {\n // `src/app` is as official a layout as `app`, and defaulting to `app` alone\n // meant half of all App Router projects scanned an absent directory and\n // reported no routes — the same shape as reading only the project root for a\n // Prisma schema. An explicit `app_dir` is still honoured exactly as given.\n const candidates = appDir !== undefined ? [appDir] : [\"app\", \"src/app\"];\n const scanDir = candidates.map((dir) => join(projectDir, dir)).find((dir) => existsSync(dir));\n\n if (!scanDir) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for route extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n // Discover all route files and their URL paths\n const routeFiles: Array<{ file: string; routePath: string }> = [];\n await walkAppDir(scanDir, \"\", routeFiles);\n\n if (routeFiles.length === 0) {\n return [];\n }\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add only the discovered route files\n for (const { file } of routeFiles) {\n project.addSourceFileAtPath(file);\n }\n\n const routes: ExtractedRoute[] = [];\n\n for (const { file, routePath } of routeFiles) {\n const sourceFile = project.getSourceFile(file);\n if (!sourceFile) continue;\n\n // Extract params from route path segments (e.g. `:id` → \"id\", `:slug*` → \"slug\")\n const params = (routePath.match(/:[a-zA-Z_][a-zA-Z0-9_]*\\*?/g) ?? []).map((p) =>\n p.replace(/^:/, \"\").replace(/\\*$/, \"\"),\n );\n\n // Find all exported function declarations named after HTTP methods\n const exportedFunctions = sourceFile.getFunctions().filter((fn) => {\n const name = fn.getName();\n return name !== undefined && HTTP_METHODS.has(name) && fn.isExported();\n });\n\n for (const fn of exportedFunctions) {\n const name = fn.getName()!;\n const lineNumber = sourceFile.getLineAndColumnAtPos(fn.getStart()).line;\n\n routes.push({\n method: name as HttpMethod,\n path: routePath || \"/\",\n params,\n file,\n line: lineNumber,\n });\n }\n\n // Also handle variable exported functions: export const GET = async () => { ... }\n const exportedVarDecls = sourceFile\n .getDescendantsOfKind(SyntaxKind.VariableDeclaration)\n .filter((decl) => {\n const name = decl.getName();\n if (!HTTP_METHODS.has(name)) return false;\n // Check if the variable statement is exported\n const varStatement = decl.getVariableStatement();\n return varStatement !== undefined && varStatement.isExported();\n });\n\n for (const decl of exportedVarDecls) {\n const name = decl.getName();\n const lineNumber = sourceFile.getLineAndColumnAtPos(decl.getStart()).line;\n\n routes.push({\n method: name as HttpMethod,\n path: routePath || \"/\",\n params,\n file,\n line: lineNumber,\n });\n }\n }\n\n return routes;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedType } from \"../types.js\";\n\n/**\n * Extract TypeScript interface and type alias definitions from source files using ts-morph AST parsing.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param typesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractTypeScriptTypes(\n projectDir: string,\n typesDir?: string,\n): Promise<ExtractedType[]> {\n const scanDir = typesDir ? join(projectDir, typesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for type extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const types: ExtractedType[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Extract interfaces.\n for (const iface of sourceFile.getInterfaces()) {\n const name = iface.getName();\n const line = sourceFile.getLineAndColumnAtPos(iface.getStart()).line;\n const fields = extractProperties(iface.getProperties());\n types.push({ name, fields, file: filePath, line });\n }\n\n // Extract type aliases that define object types (with properties).\n for (const typeAlias of sourceFile.getTypeAliases()) {\n const typeNode = typeAlias.getTypeNode();\n if (!typeNode) continue;\n\n // Only process object type literals (skip simple aliases like `type X = string`).\n if (typeNode.getKind() !== SyntaxKind.TypeLiteral) continue;\n\n const typeLiteral = typeNode.asKindOrThrow(SyntaxKind.TypeLiteral);\n const properties = typeLiteral.getProperties();\n if (properties.length === 0) continue;\n\n const name = typeAlias.getName();\n const line = sourceFile.getLineAndColumnAtPos(typeAlias.getStart()).line;\n const fields = extractProperties(properties);\n types.push({ name, fields, file: filePath, line });\n }\n }\n\n return types;\n}\n\n/**\n * Convert a list of ts-morph property signatures into the ExtractedType fields format.\n */\nfunction extractProperties(\n properties: import(\"ts-morph\").PropertySignature[],\n): ExtractedType[\"fields\"] {\n return properties.map((prop) => {\n const name = prop.getName();\n const optional = prop.hasQuestionToken();\n\n // Prefer the type as written in source; fall back to the resolved type text.\n let type = prop.getTypeNode()?.getText() ?? prop.getType().getText();\n\n // Strip import() paths that ts-morph sometimes includes, e.g. `import(\"x\").Foo` → `Foo`.\n type = type.replace(/import\\([^)]+\\)\\./g, \"\");\n\n return { name, type, optional };\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedType } from \"../types.js\";\n\n/**\n * Extract Zod object schemas from TypeScript source files using ts-morph AST parsing.\n *\n * Scans for variable declarations of the form:\n * export const FooSchema = z.object({ ... });\n * and converts them to ExtractedType entries, stripping the `Schema` suffix from the name.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param typesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractZodSchemas(\n projectDir: string,\n typesDir?: string,\n): Promise<ExtractedType[]> {\n const scanDir = typesDir ? join(projectDir, typesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\n \"ts-morph is required for Zod schema extraction. Install it: pnpm add -D ts-morph\",\n );\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts and .js files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.test.js\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/*.spec.js\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const types: ExtractedType[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n const varDeclarations = sourceFile.getDescendantsOfKind(SyntaxKind.VariableDeclaration);\n\n for (const varDecl of varDeclarations) {\n const initializer = varDecl.getInitializer();\n if (!initializer) continue;\n if (initializer.getKind() !== SyntaxKind.CallExpression) continue;\n\n // Walk up the call chain looking for a z.object(...) call.\n // The pattern may be z.object({...}).strict() or similar — walk the chain.\n const zObjectCall = findZObjectCall(initializer, SyntaxKind);\n if (!zObjectCall) continue;\n\n // Get the argument to z.object() — must be an ObjectLiteralExpression.\n const args = zObjectCall.asKindOrThrow(SyntaxKind.CallExpression).getArguments();\n if (args.length === 0) continue;\n const firstArg = args[0];\n if (!firstArg) continue;\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) continue;\n\n const objLiteral = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Derive the type name: strip \"Schema\" suffix from the variable name.\n const rawName = varDecl.getName();\n const typeName = rawName.endsWith(\"Schema\") ? rawName.slice(0, -\"Schema\".length) : rawName;\n\n const fields: ExtractedType[\"fields\"] = [];\n\n for (const prop of objLiteral.getProperties()) {\n // Only handle PropertyAssignment (not shorthand, spread, etc.)\n if (prop.getKind() !== SyntaxKind.PropertyAssignment) continue;\n\n const propAssign = prop.asKindOrThrow(SyntaxKind.PropertyAssignment);\n const fieldName = propAssign.getName();\n const fieldInit = propAssign.getInitializer();\n if (!fieldInit) continue;\n\n const { type: fieldType, optional } = inferZodType(fieldInit, SyntaxKind);\n\n fields.push({ name: fieldName, type: fieldType, optional });\n }\n\n const lineNumber = sourceFile.getLineAndColumnAtPos(varDecl.getStart()).line;\n\n types.push({ name: typeName, fields, file: filePath, line: lineNumber });\n }\n }\n\n return types;\n}\n\n/**\n * Walk a call expression chain to find the `z.object(...)` call.\n * Handles chained calls like `z.object({...}).strict()`.\n */\nfunction findZObjectCall(\n node: import(\"ts-morph\").Node,\n SyntaxKind: typeof import(\"ts-morph\").SyntaxKind,\n): import(\"ts-morph\").Node | undefined {\n if (node.getKind() !== SyntaxKind.CallExpression) return undefined;\n\n const callExpr = node.asKindOrThrow(SyntaxKind.CallExpression);\n const expr = callExpr.getExpression();\n\n // Direct: z.object(...)\n if (isZObjectAccess(expr, SyntaxKind)) {\n return node;\n }\n\n // Chained: someCall(...).method(...) — recurse into the callee\n if (expr.getKind() === SyntaxKind.PropertyAccessExpression) {\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const innerExpr = propAccess.getExpression();\n if (innerExpr.getKind() === SyntaxKind.CallExpression) {\n return findZObjectCall(innerExpr, SyntaxKind);\n }\n }\n\n return undefined;\n}\n\n/**\n * Returns true if the given node is a `z.object` property access.\n */\nfunction isZObjectAccess(\n node: import(\"ts-morph\").Node,\n SyntaxKind: typeof import(\"ts-morph\").SyntaxKind,\n): boolean {\n if (node.getKind() !== SyntaxKind.PropertyAccessExpression) return false;\n const propAccess = node.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n if (propAccess.getName() !== \"object\") return false;\n const receiver = propAccess.getExpression();\n return receiver.getKind() === SyntaxKind.Identifier && receiver.getText() === \"z\";\n}\n\n/**\n * Infer the TypeScript type and optional flag from a Zod call chain.\n *\n * Examples:\n * z.string() → { type: \"string\", optional: false }\n * z.date().optional() → { type: \"Date\", optional: true }\n * z.enum([\"a\",\"b\"]) → { type: '\"a\" | \"b\"', optional: false }\n */\nfunction inferZodType(\n node: import(\"ts-morph\").Node,\n SyntaxKind: typeof import(\"ts-morph\").SyntaxKind,\n): { type: string; optional: boolean } {\n // Collect all method names in the chain and find the base z.<type>() call.\n const chainMethods: string[] = [];\n let baseCallNode: import(\"ts-morph\").Node | undefined;\n\n let current: import(\"ts-morph\").Node = node;\n\n // Walk from the outermost call inward, collecting method names.\n while (current.getKind() === SyntaxKind.CallExpression) {\n const callExpr = current.asKindOrThrow(SyntaxKind.CallExpression);\n const expr = callExpr.getExpression();\n\n if (expr.getKind() === SyntaxKind.PropertyAccessExpression) {\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName();\n const receiver = propAccess.getExpression();\n\n if (receiver.getKind() === SyntaxKind.Identifier && receiver.getText() === \"z\") {\n // This is the base z.<type>() call.\n baseCallNode = current;\n chainMethods.push(methodName);\n break;\n } else {\n // Intermediate method in the chain (e.g., .optional(), .email(), etc.)\n chainMethods.push(methodName);\n current = receiver;\n }\n } else {\n break;\n }\n }\n\n const optional = chainMethods.includes(\"optional\");\n\n // The last entry in chainMethods (from our walk) is the base Zod type method name.\n // Because we push inner methods last, the base type is the last element.\n const baseMethodName = chainMethods[chainMethods.length - 1];\n\n let type = \"unknown\";\n\n if (baseMethodName === \"string\") {\n type = \"string\";\n } else if (baseMethodName === \"number\") {\n type = \"number\";\n } else if (baseMethodName === \"boolean\") {\n type = \"boolean\";\n } else if (baseMethodName === \"date\") {\n type = \"Date\";\n } else if (baseMethodName === \"array\") {\n type = \"array\";\n } else if (baseMethodName === \"enum\" && baseCallNode) {\n // z.enum([\"a\", \"b\"]) → \"a\" | \"b\"\n const enumCall = baseCallNode.asKindOrThrow(SyntaxKind.CallExpression);\n const args = enumCall.getArguments();\n if (args.length > 0) {\n const firstArg = args[0];\n if (firstArg && firstArg.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arrayLiteral = firstArg.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const elements = arrayLiteral\n .getElements()\n .filter((el) => el.getKind() === SyntaxKind.StringLiteral)\n .map((el) => el.asKindOrThrow(SyntaxKind.StringLiteral).getText());\n if (elements.length > 0) {\n type = elements.join(\" | \");\n }\n }\n }\n }\n\n return { type, optional };\n}\n","import type { ExtractedType } from \"../types.js\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nconst PRISMA_TYPE_MAP: Record<string, string> = {\n String: \"string\",\n Int: \"number\",\n Float: \"number\",\n Decimal: \"number\",\n BigInt: \"number\",\n Boolean: \"boolean\",\n DateTime: \"Date\",\n Json: \"unknown\",\n Bytes: \"Buffer\",\n};\n\n/**\n * Every place Prisma keeps a schema, in the order Prisma itself prefers.\n *\n * Only the project root was read, and `prisma init` has never written there --\n * it writes `prisma/schema.prisma`. So a real Prisma project's models were\n * invisible, every one of them was reported as unimplemented, and the coverage\n * score dropped to match, with no note saying a schema had been looked for.\n *\n * `prisma/schema/` is the multi-file layout supported since Prisma 5.15.\n */\nexport async function findPrismaSchemas(projectDir: string): Promise<string[]> {\n const found: string[] = [];\n\n for (const relative of [\"prisma/schema.prisma\", \"schema.prisma\"]) {\n const path = join(projectDir, relative);\n try {\n await readFile(path, \"utf-8\");\n found.push(path);\n } catch {\n // not there; try the next layout\n }\n }\n\n const schemaDir = join(projectDir, \"prisma\", \"schema\");\n try {\n for (const entry of await readdir(schemaDir)) {\n if (entry.endsWith(\".prisma\")) found.push(join(schemaDir, entry));\n }\n } catch {\n // no multi-file schema directory\n }\n\n return found;\n}\n\nexport async function extractPrismaModels(projectDir: string): Promise<ExtractedType[]> {\n const schemaPaths = await findPrismaSchemas(projectDir);\n if (schemaPaths.length === 0) return [];\n\n const models: ExtractedType[] = [];\n for (const schemaPath of schemaPaths) {\n models.push(...parseSchema(await readFile(schemaPath, \"utf-8\"), schemaPath));\n }\n return models;\n}\n\nfunction parseSchema(content: string, schemaPath: string): ExtractedType[] {\n const models: ExtractedType[] = [];\n const modelRe = /^model\\s+(\\w+)\\s*\\{([^}]+)\\}/gm;\n let modelMatch;\n\n while ((modelMatch = modelRe.exec(content)) !== null) {\n const name = modelMatch[1]!;\n const body = modelMatch[2]!;\n const fields: ExtractedType[\"fields\"] = [];\n const lineOffset = content.slice(0, modelMatch.index).split(\"\\n\").length;\n\n for (const line of body.split(\"\\n\")) {\n const fieldMatch = /^\\s+(\\w+)\\s+(\\w+)(\\??)/.exec(line);\n if (!fieldMatch) continue;\n\n const fieldName = fieldMatch[1]!;\n const prismaType = fieldMatch[2]!;\n const optional = fieldMatch[3] === \"?\";\n\n // Skip relation fields (type references another model or is array)\n if (line.includes(\"@relation\") || prismaType.endsWith(\"[]\") || line.trim().endsWith(\"[]\"))\n continue;\n // Also skip if the type is not a known Prisma scalar (it's a relation)\n if (!PRISMA_TYPE_MAP[prismaType] && /^[A-Z]/.test(prismaType)) continue;\n\n const tsType = PRISMA_TYPE_MAP[prismaType] ?? prismaType.toLowerCase();\n fields.push({ name: fieldName, type: tsType, optional });\n }\n\n models.push({ name, fields, file: schemaPath, line: lineOffset });\n }\n\n return models;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedTest } from \"../types.js\";\n\n/**\n * Extract test descriptions from test files using ts-morph AST parsing.\n *\n * Scans all `.ts` and `.js` files in the given directory and extracts the first\n * string literal argument from `it()` and `test()` call expressions.\n *\n * @param projectDir - Root directory to scan (or fixtures dir in tests)\n * @param testsDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractTestDescriptions(\n projectDir: string,\n testsDir?: string,\n): Promise<ExtractedTest[]> {\n const scanDir = testsDir ? join(projectDir, testsDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for test extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Scan all .ts and .js files in the directory (caller is responsible for pointing\n // this at a tests directory, so all files are candidates).\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const tests: ExtractedTest[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n\n // We want bare `it(...)` and `test(...)` — identifiers only.\n if (expr.getKind() !== SyntaxKind.Identifier) continue;\n\n const calleeName = expr.asKindOrThrow(SyntaxKind.Identifier).getText();\n if (calleeName !== \"it\" && calleeName !== \"test\") continue;\n\n const args = callExpr.getArguments();\n if (args.length < 1) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n\n // First argument must be a string literal (the test description).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const description = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n const lineNumber = sourceFile.getLineAndColumnAtPos(callExpr.getStart()).line;\n\n tests.push({\n description,\n file: filePath,\n line: lineNumber,\n });\n }\n }\n\n return tests;\n}\n","import type { Finding, SpecEndpoint, ExtractedRoute } from \"../types.js\";\n\nfunction normalisePath(path: string): string {\n return \"/\" + path.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\").replace(/\\/+/g, \"/\");\n}\n\nexport function matchRoutes(\n specEndpoints: SpecEndpoint[],\n codeRoutes: ExtractedRoute[],\n specId: string,\n): Finding[] {\n const findings: Finding[] = [];\n\n const codeSet = new Set(codeRoutes.map((r) => `${r.method} ${normalisePath(r.path)}`));\n const specSet = new Set(specEndpoints.map((e) => `${e.method} ${normalisePath(e.path)}`));\n\n // Missing: in spec but not code\n for (const endpoint of specEndpoints) {\n const key = `${endpoint.method} ${normalisePath(endpoint.path)}`;\n if (!codeSet.has(key)) {\n findings.push({\n type: \"missing\",\n category: \"route\",\n specId,\n specSection: \"Endpoints\",\n expected: key,\n severity: \"error\",\n suggestion: `Implement ${key} in your route handler`,\n });\n }\n }\n\n // Extra: in code but not spec\n for (const route of codeRoutes) {\n const key = `${route.method} ${normalisePath(route.path)}`;\n if (!specSet.has(key)) {\n findings.push({\n type: \"extra\",\n category: \"route\",\n specId,\n codeLocation: { file: route.file, line: route.line },\n expected: \"(not in spec)\",\n actual: key,\n severity: \"info\",\n suggestion: `Route ${key} exists in code but not in spec — add to spec if intentional`,\n });\n }\n }\n\n return findings;\n}\n","import type { Finding, SpecTypeDefinition, ExtractedType } from \"../types.js\";\n\nconst STRIP_SUFFIXES = [\"Schema\", \"Model\", \"Type\", \"Interface\", \"Entity\"];\n\nfunction normaliseTypeName(name: string): string {\n let normalised = name;\n for (const suffix of STRIP_SUFFIXES) {\n if (normalised.endsWith(suffix) && normalised.length > suffix.length) {\n normalised = normalised.slice(0, -suffix.length);\n break;\n }\n }\n return normalised.toLowerCase();\n}\n\nfunction findMatchingCodeType(\n specType: SpecTypeDefinition,\n codeTypes: ExtractedType[],\n): ExtractedType | undefined {\n const specNorm = normaliseTypeName(specType.name);\n return codeTypes.find((ct) => normaliseTypeName(ct.name) === specNorm);\n}\n\nexport function matchTypes(\n specTypes: SpecTypeDefinition[],\n codeTypes: ExtractedType[],\n specId: string,\n): Finding[] {\n const findings: Finding[] = [];\n\n for (const specType of specTypes) {\n const codeType = findMatchingCodeType(specType, codeTypes);\n\n if (!codeType) {\n findings.push({\n type: \"missing\",\n category: \"type\",\n specId,\n specSection: \"Data Models\",\n expected: `Type: ${specType.name}`,\n severity: \"error\",\n suggestion: `Implement type \"${specType.name}\" in code`,\n // The score's types denominator counts fields; an absent type must\n // subtract all of its fields, not 1, or a project that implements\n // nothing of an N-field model scores (N-1)/N.\n weight: specType.fields.length,\n });\n continue;\n }\n\n // Build a set of field names present in the code type\n const codeFieldNames = new Set(codeType.fields.map((f) => f.name));\n const specFieldNames = new Set(specType.fields.map((f) => f.name));\n\n // Missing fields: in spec but not in code\n for (const specField of specType.fields) {\n if (!codeFieldNames.has(specField.name)) {\n findings.push({\n type: \"missing\",\n category: \"type\",\n specId,\n specSection: \"Data Models\",\n codeLocation: { file: codeType.file, line: codeType.line },\n expected: `Field ${specType.name}.${specField.name} (${specField.type})`,\n severity: \"warn\",\n suggestion: `Add field \"${specField.name}: ${specField.type}\" to ${codeType.name}`,\n });\n }\n }\n\n // Extra fields: in code but not in spec\n for (const codeField of codeType.fields) {\n if (!specFieldNames.has(codeField.name)) {\n findings.push({\n type: \"extra\",\n category: \"type\",\n specId,\n specSection: \"Data Models\",\n codeLocation: { file: codeType.file, line: codeType.line },\n expected: \"(not in spec)\",\n actual: `Field ${codeType.name}.${codeField.name} (${codeField.type})`,\n severity: \"info\",\n suggestion: `Field \"${codeField.name}\" exists in code but not in spec — add to spec if intentional`,\n });\n }\n }\n }\n\n return findings;\n}\n","import type { Finding, SpecTestCase, ExtractedTest } from \"../types.js\";\n\n/** Jaccard similarity between two strings. Normalises to lowercase words. */\nfunction jaccard(a: string, b: string): number {\n const wordsA = new Set(\n a\n .toLowerCase()\n .replace(/[^\\w\\s]/g, \"\")\n .split(/\\s+/)\n .filter(Boolean),\n );\n const wordsB = new Set(\n b\n .toLowerCase()\n .replace(/[^\\w\\s]/g, \"\")\n .split(/\\s+/)\n .filter(Boolean),\n );\n const intersection = new Set([...wordsA].filter((w) => wordsB.has(w)));\n const union = new Set([...wordsA, ...wordsB]);\n if (union.size === 0) return 0;\n return intersection.size / union.size;\n}\n\nconst JACCARD_THRESHOLD = 0.4;\n\n/**\n * Match spec test cases against extracted code tests using Jaccard similarity.\n *\n * - Spec cases that have a code-test match above the threshold are considered covered.\n * - Unmatched spec cases produce a `missing` / `warn` Finding.\n * - Extra code tests (not matched to any spec case) are not reported.\n */\nexport function matchTests(\n specCases: SpecTestCase[],\n codeTests: ExtractedTest[],\n specId: string,\n): Finding[] {\n const findings: Finding[] = [];\n\n for (const specCase of specCases) {\n let bestScore = 0;\n let bestMatch: ExtractedTest | undefined;\n\n for (const codeTest of codeTests) {\n const score = jaccard(specCase.description, codeTest.description);\n if (score > bestScore) {\n bestScore = score;\n bestMatch = codeTest;\n }\n }\n\n if (bestScore < JACCARD_THRESHOLD || !bestMatch) {\n findings.push({\n type: \"missing\",\n category: \"test\",\n specId,\n specSection: specCase.section,\n // `expected` keeps the case ID so the finding can be traced back to a\n // line in the test plan; the suggestion is the test name to write, and\n // the spec's own label is no part of that.\n expected: specCase.id ? `${specCase.id}: ${specCase.description}` : specCase.description,\n severity: \"warn\",\n suggestion: `Add a test matching: \"${specCase.description}\"`,\n });\n }\n }\n\n return findings;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport type { Finding } from \"./types.js\";\n\n/** A checkable artifact declared in a spec's `artifacts` frontmatter (issue #15). */\nexport interface ArtifactDecl {\n /** Project-root-relative file path that must exist. */\n path: string;\n /** Names that must be exported from the file. */\n exports?: string[];\n}\n\n/** Result of verifying declared artifacts against the project. */\nexport interface ArtifactCheckResult {\n findings: Finding[];\n /** Total artifact assertions considered (each path, plus each checkable export). */\n total: number;\n /** Assertions actually verified — equals `total`; skipped assertions are excluded, not passed. */\n checked: number;\n /** Declared-but-absent artifacts of specs not yet approved — planned, not missing (issue #17). */\n pending: number;\n notes: string[];\n}\n\n/**\n * Spec statuses at which declared artifacts must already exist.\n *\n * A spec is the plan for work that has not happened yet, so its artifacts are\n * enforceable only once it is approved. Before then a declared-but-absent file\n * is the expected state, not a defect (issue #17) — otherwise spec-first\n * authoring would fail the very gate the artifacts exist to feed.\n */\nconst ENFORCED_STATUSES = new Set([\"approved\"]);\n\n/** True when a spec's declared artifacts must exist for the check to pass. */\nexport function artifactsEnforced(status: unknown): boolean {\n return typeof status === \"string\" && ENFORCED_STATUSES.has(status);\n}\n\n/**\n * Read the `artifacts` frontmatter field defensively. Schema validation\n * reports malformed entries; here we simply skip anything unusable.\n */\nexport function parseArtifacts(spec: ParsedSpec): ArtifactDecl[] {\n const raw = spec.frontmatter.artifacts;\n if (!Array.isArray(raw)) return [];\n\n const out: ArtifactDecl[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\") continue;\n const decl = item as { path?: unknown; exports?: unknown };\n if (typeof decl.path !== \"string\" || decl.path.length === 0) continue;\n const exports = Array.isArray(decl.exports)\n ? decl.exports.filter((e): e is string => typeof e === \"string\" && e.length > 0)\n : undefined;\n out.push({ path: decl.path, exports });\n }\n return out;\n}\n\n/** Return the set of exported names from a source file, or null when ts-morph fails to parse. */\nasync function getExportedNames(filePath: string): Promise<Set<string> | null> {\n try {\n const { Project } = await import(\"ts-morph\");\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n const sourceFile = project.addSourceFileAtPath(filePath);\n return new Set(sourceFile.getExportedDeclarations().keys());\n } catch {\n return null;\n }\n}\n\n/**\n * Verify each spec's declared artifacts: files must exist, and named exports\n * must be present. Export checks need ts-morph; without it they are skipped\n * with a note and excluded from the totals — never counted as passed.\n */\nexport async function checkArtifacts(\n specs: ParsedSpec[],\n projectDir: string,\n tsMorphAvailable: boolean,\n): Promise<ArtifactCheckResult> {\n const findings: Finding[] = [];\n const notes: string[] = [];\n let total = 0;\n let pending = 0;\n let skippedExports = 0;\n\n for (const spec of specs) {\n const specId = String(spec.frontmatter.id);\n const status = spec.frontmatter.status;\n const enforced = artifactsEnforced(status);\n\n for (const artifact of parseArtifacts(spec)) {\n const absolute = join(projectDir, artifact.path);\n\n if (!existsSync(absolute)) {\n if (enforced) {\n total += 1;\n findings.push({\n type: \"missing\",\n category: \"artifact\",\n specId,\n expected: `file \"${artifact.path}\"`,\n severity: \"error\",\n suggestion: `Create ${artifact.path} or update the artifacts list in ${specId}.`,\n });\n } else {\n // Planned, not missing: excluded from the score rather than passed.\n pending += 1;\n findings.push({\n type: \"pending\",\n category: \"artifact\",\n specId,\n expected: `file \"${artifact.path}\"`,\n severity: \"info\",\n suggestion: `planned by ${specId} (status: ${String(status)}) — not yet implemented; enforced once the spec is approved.`,\n });\n }\n // Export assertions for an absent file are not separately counted.\n continue;\n }\n\n // The file exists, so it is a real assertion regardless of spec status.\n total += 1;\n\n if (!artifact.exports || artifact.exports.length === 0) continue;\n\n if (!tsMorphAvailable) {\n skippedExports += artifact.exports.length;\n continue;\n }\n\n const exported = await getExportedNames(absolute);\n if (exported === null) {\n skippedExports += artifact.exports.length;\n continue;\n }\n\n for (const name of artifact.exports) {\n // An export that exists is a verified assertion whatever the status.\n if (exported.has(name)) {\n total += 1;\n continue;\n }\n\n // An absent export follows the same status rule as an absent file: a\n // spec that is not yet approved is planning it, not missing it (#19).\n if (enforced) {\n total += 1;\n findings.push({\n type: \"missing\",\n category: \"artifact\",\n specId,\n codeLocation: { file: artifact.path, line: 1 },\n expected: `export \"${name}\" from ${artifact.path}`,\n severity: \"error\",\n suggestion: `Export ${name} from ${artifact.path} or update the artifacts list in ${specId}.`,\n });\n } else {\n pending += 1;\n findings.push({\n type: \"pending\",\n category: \"artifact\",\n specId,\n codeLocation: { file: artifact.path, line: 1 },\n expected: `export \"${name}\" from ${artifact.path}`,\n severity: \"info\",\n suggestion: `planned by ${specId} (status: ${String(status)}) — not yet implemented; enforced once the spec is approved.`,\n });\n }\n }\n }\n }\n\n if (skippedExports > 0) {\n notes.push(\n `artifact export checks skipped for ${skippedExports} export(s): ts-morph is not available or the file could not be parsed.`,\n );\n }\n\n if (pending > 0) {\n notes.push(\n `${pending} declared artifact assertion(s) pending: files or exports planned by specs that are not yet approved. They are excluded from the score and become enforceable when the spec status changes to approved.`,\n );\n }\n\n return { findings, total, checked: total, pending, notes };\n}\n","import type { Finding, ImplementationScore } from \"./types.js\";\n\ninterface SpecTotals {\n routes: number;\n types: number;\n tests: number;\n artifacts: number;\n}\n\nexport function computeScore(findings: Finding[], totals: SpecTotals): ImplementationScore {\n // Count missing findings per category (only \"missing\" and \"mismatch\" reduce the score, not \"extra\")\n const missingByCategory: Record<string, number> = { route: 0, type: 0, test: 0, artifact: 0 };\n\n for (const f of findings) {\n if (f.type === \"missing\" || f.type === \"mismatch\") {\n // A finding subtracts its weight in the category's own units (fields\n // for types); unweighted findings subtract 1.\n missingByCategory[f.category] = (missingByCategory[f.category] ?? 0) + (f.weight ?? 1);\n }\n }\n\n const categoryMap: Record<string, { total: number; categoryKey: string }> = {\n routes: { total: totals.routes, categoryKey: \"route\" },\n types: { total: totals.types, categoryKey: \"type\" },\n tests: { total: totals.tests, categoryKey: \"test\" },\n artifacts: { total: totals.artifacts, categoryKey: \"artifact\" },\n };\n\n const byCategory: Record<string, { matched: number; total: number }> = {};\n let totalItems = 0;\n let totalMatched = 0;\n\n for (const [name, { total, categoryKey }] of Object.entries(categoryMap)) {\n const missing = missingByCategory[categoryKey] ?? 0;\n const matched = Math.max(0, total - missing);\n byCategory[name] = { matched, total };\n totalItems += total;\n totalMatched += matched;\n }\n\n // Nothing checkable is \"not assessed\", never a vacuous 100% pass (issue #6)\n if (totalItems === 0) {\n return { overall: 0, assessed: false, byCategory };\n }\n\n const overall = Math.round((totalMatched / totalItems) * 100);\n return { overall, assessed: true, byCategory };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\ntype DetectedFramework = \"express\" | \"hono\" | \"nextjs\";\n\nconst FRAMEWORK_PACKAGES: [string, DetectedFramework][] = [\n [\"express\", \"express\"],\n [\"hono\", \"hono\"],\n [\"next\", \"nextjs\"],\n];\n\nexport async function detectFramework(projectDir: string): Promise<DetectedFramework | null> {\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n try {\n const content = await readFile(join(projectDir, \"package.json\"), \"utf-8\");\n pkg = JSON.parse(content);\n } catch {\n return null;\n }\n\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n\n for (const [pkgName, framework] of FRAMEWORK_PACKAGES) {\n if (pkgName in allDeps) {\n return framework;\n }\n }\n\n return null;\n}\n","import type { Finding, AiAssessment, AiCheckResult } from \"./types.js\";\n\nexport async function analyzeWithAi(findings: Finding[], context: string): Promise<AiCheckResult> {\n const apiKey = process.env[\"ANTHROPIC_API_KEY\"];\n if (!apiKey) {\n throw new Error(\n \"ANTHROPIC_API_KEY environment variable is required for --ai mode. \" +\n \"Set it or use the specdx-verify skill instead (no API key needed).\",\n );\n }\n\n if (findings.length === 0) {\n return { findings, assessments: [], summary: \"No findings to analyze.\" };\n }\n\n let Anthropic: typeof import(\"@anthropic-ai/sdk\").default;\n try {\n const mod = await import(\"@anthropic-ai/sdk\");\n Anthropic = mod.default;\n } catch {\n throw new Error(\n \"@anthropic-ai/sdk is required for --ai mode. Install it: pnpm add -D @anthropic-ai/sdk\",\n );\n }\n\n const client = new Anthropic({ apiKey });\n\n const findingsSummary = findings\n .map(\n (f, i) =>\n `[${i}] ${f.type} (${f.severity}): ${f.expected}${f.actual ? ` — actual: ${f.actual}` : \"\"}${f.suggestion ? ` — suggestion: ${f.suggestion}` : \"\"}`,\n )\n .join(\"\\n\");\n\n const prompt = `You are reviewing static analysis findings from a spec-to-implementation check.\n\nContext: ${context}\n\nFindings:\n${findingsSummary}\n\nFor each finding (by index), assess:\n1. Is this a real issue or a false positive?\n2. How confident are you? (high/medium/low)\n3. Brief reasoning (1-2 sentences)\n4. Suggested fix if it's a real issue\n\nRespond with a JSON array of objects:\n[{ \"findingIndex\": 0, \"isRealIssue\": true, \"confidence\": \"high\", \"reasoning\": \"...\", \"suggestedFix\": \"...\" }]\n\nOnly output the JSON array, no other text.`;\n\n const response = await client.messages.create({\n model: \"claude-sonnet-4-20250514\",\n max_tokens: 4000,\n messages: [{ role: \"user\", content: prompt }],\n });\n\n const text = response.content[0]?.type === \"text\" ? response.content[0].text : \"\";\n\n let assessments: AiAssessment[];\n try {\n assessments = JSON.parse(text);\n } catch {\n assessments = [];\n }\n\n const realIssues = assessments.filter((a) => a.isRealIssue).length;\n const falsePositives = assessments.filter((a) => !a.isRealIssue).length;\n const summary = `AI analysis: ${realIssues} real issues, ${falsePositives} false positives out of ${findings.length} findings`;\n\n return { findings, assessments, summary };\n}\n"],"mappings":";AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,QAAAC,cAAY;;;ACKrB,SAAS,eAAe,SAAiB,SAAe;AAEtD,QAAM,iBAAiB,IAAI,OAAO,UAAU,YAAY,OAAO,CAAC,SAAS,IAAI;AAC7E,QAAM,QAAQ,eAAe,KAAK,OAAO;AACzC,MAAI,CAAC;AAAO,WAAO;AAEnB,QAAM,QAAQ,MAAM,QAAQ,MAAM,CAAC,EAAE;AACrC,QAAM,OAAO,QAAQ,MAAM,KAAK;AAGhC,QAAM,cAAc,UAAU,KAAK,IAAI;AACvC,SAAO,cAAc,KAAK,MAAM,GAAG,YAAY,KAAK,IAAI;AAC1D;AAEA,SAAS,YAAY,KAAW;AAC9B,SAAO,IAAI,QAAQ,uBAAuB,MAAM;AAClD;AAEA,IAAM,eAAoC,oBAAI,IAAI,CAAC,OAAO,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAM3F,SAAS,WAAW,MAAY;AAC9B,UAAQ,KAAK,MAAM,4BAA4B,KAAK,CAAA,GAAI,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC/E;AAOM,SAAU,oBAAoB,SAAe;AACjD,SAAO,eAAe,SAAS,WAAW,MAAM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AM,IAAI,MACR,wFAAwF;EAE5F;AAEA,QAAM,SAAS,IAAI,UAAU,EAAE,OAAM,CAAE;AAEvC,QAAM,kBAAkB,SACrB,IACC,CAAC,GAAG,MACF,IAAI,CAAC,KAAK,EAAE,IAAI,KAAK,EAAE,QAAQ,MAAM,EAAE,QAAQ,GAAG,EAAE,SAAS,mBAAc,EAAE,MAAM,KAAK,EAAE,GAAG,EAAE,aAAa,uBAAkB,EAAE,UAAU,KAAK,EAAE,EAAE,EAEtJ,KAAK,IAAI;AAEZ,QAAM,SAAS;;WAEN,OAAO;;;EAGhB,eAAe;;;;;;;;;;;;AAaf,QAAM,WAAW,MAAM,OAAO,SAAS,OAAO;IAC5C,OAAO;IACP,YAAY;IACZ,UAAU,CAAC,EAAE,MAAM,QAAQ,SAAS,OAAM,CAAE;GAC7C;AAED,QAAM,OAAO,SAAS,QAAQ,CAAC,GAAG,SAAS,SAAS,SAAS,QAAQ,CAAC,EAAE,OAAO;AAE/E,MAAI;AACJ,MAAI;AACF,kBAAc,KAAK,MAAM,IAAI;EAC/B,QAAQ;AACN,kBAAc,CAAA;EAChB;AAEA,QAAM,aAAa,YAAY,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE;AAC5D,QAAM,iBAAiB,YAAY,OAAO,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE;AACjE,QAAM,UAAU,gBAAgB,UAAU,iBAAiB,cAAc,2BAA2B,SAAS,MAAM;AAEnH,SAAO,EAAE,UAAU,aAAa,QAAO;AACzC;","names":["readFile","join","HTTP_METHODS","existsSync","join","HTTP_METHODS","existsSync","join","HTTP_METHODS","existsSync","join","existsSync","join","readdir","join","existsSync","join","existsSync","join","readFile","join","readFile","join"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../core/src/config.ts","../../core/src/parser.ts","../../core/src/tokens.ts","../../core/src/graph.ts","../../core/src/glob.ts","../../core/src/logger.ts","../../core/src/relations.ts","../../core/src/preset.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport { validateConfig, type SdxConfig } from \"@specdx/schema\";\n\nexport class ConfigError extends Error {\n constructor(\n message: string,\n public readonly errors?: unknown[],\n ) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\nconst CONFIG_FILENAME = \"spec.config.yaml\";\n\nexport async function loadConfig(filePath?: string, searchFrom?: string): Promise<SdxConfig> {\n const resolvedPath = filePath ?? (await findConfig(searchFrom ?? process.cwd()));\n if (!resolvedPath) {\n throw new ConfigError(`No ${CONFIG_FILENAME} found. Run 'specdx init' to create one.`);\n }\n\n let raw: string;\n try {\n raw = await readFile(resolvedPath, \"utf-8\");\n } catch {\n throw new ConfigError(`Cannot read config file: ${resolvedPath}`);\n }\n\n let data: Record<string, unknown>;\n try {\n data = parseYaml(raw) as Record<string, unknown>;\n } catch (err) {\n throw new ConfigError(`Invalid YAML in ${resolvedPath}: ${(err as Error).message}`);\n }\n\n const result = validateConfig(data);\n if (!result.valid) {\n throw new ConfigError(`Invalid config in ${resolvedPath}`, result.errors ?? undefined);\n }\n\n return data as unknown as SdxConfig;\n}\n\nasync function findConfig(from: string): Promise<string | undefined> {\n let dir = from;\n while (true) {\n const candidate = join(dir, CONFIG_FILENAME);\n try {\n await readFile(candidate, \"utf-8\");\n return candidate;\n } catch {\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\nimport * as grayMatterNs from \"gray-matter\";\nimport { parse as parseYaml } from \"yaml\";\nimport { unified } from \"unified\";\nimport remarkParse from \"remark-parse\";\nimport { visit } from \"unist-util-visit\";\nimport { validateSpec, type ValidationResult } from \"@specdx/schema\";\nimport type { BaseSpec, SpecType } from \"@specdx/schema\";\nimport { countTokens } from \"./tokens.js\";\n\n// gray-matter is CJS — its callable default is exposed via .default in an ESM context\ntype GrayMatterFn = (input: string) => { data: Record<string, unknown>; content: string };\nconst matter = ((grayMatterNs as unknown as { default?: GrayMatterFn }).default ??\n (grayMatterNs as unknown as GrayMatterFn)) as GrayMatterFn;\n\nexport class ParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ParseError\";\n }\n}\n\nexport interface ParsedSection {\n heading: string;\n content: string;\n tokens: number;\n}\n\nexport interface ParsedSpec {\n filePath: string;\n frontmatter: BaseSpec & Record<string, unknown>;\n content: string;\n sections: string[];\n parsedSections: ParsedSection[];\n valid: boolean;\n validationErrors: ValidationResult[\"errors\"];\n}\n\nexport async function parseSpec(filePath: string): Promise<ParsedSpec> {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf-8\");\n } catch {\n throw new ParseError(`Cannot read spec file: ${filePath}`);\n }\n\n return parseSpecFromString(raw, filePath);\n}\n\nexport function parseSpecFromString(content: string, filePath: string): Promise<ParsedSpec> {\n const ext = extname(filePath).toLowerCase();\n if (ext === \".yaml\" || ext === \".yml\") {\n return Promise.resolve(parseYamlSpec(filePath, content));\n }\n return Promise.resolve(parseMarkdownSpec(filePath, content));\n}\n\nfunction parseMarkdownSpec(filePath: string, raw: string): ParsedSpec {\n const { data, content } = matter(raw);\n const parsedSections = extractParsedSections(content);\n const sections = parsedSections.map((s) => s.heading).filter(Boolean);\n const frontmatter = data as BaseSpec & Record<string, unknown>;\n const specType = frontmatter.type as SpecType | undefined;\n\n let valid = false;\n let validationErrors: ValidationResult[\"errors\"] = null;\n if (specType) {\n const result = validateSpec(specType, data);\n valid = result.valid;\n validationErrors = result.errors;\n }\n\n return { filePath, frontmatter, content, sections, parsedSections, valid, validationErrors };\n}\n\nfunction parseYamlSpec(filePath: string, raw: string): ParsedSpec {\n let data: Record<string, unknown>;\n try {\n data = parseYaml(raw) as Record<string, unknown>;\n } catch (err) {\n throw new ParseError(`Invalid YAML in ${filePath}: ${(err as Error).message}`);\n }\n\n const frontmatter = data as BaseSpec & Record<string, unknown>;\n const specType = frontmatter.type as SpecType | undefined;\n\n let valid = false;\n let validationErrors: ValidationResult[\"errors\"] = null;\n if (specType) {\n const result = validateSpec(specType, data);\n valid = result.valid;\n validationErrors = result.errors;\n }\n\n return {\n filePath,\n frontmatter,\n content: \"\",\n sections: [],\n parsedSections: [],\n valid,\n validationErrors,\n };\n}\n\nfunction extractParsedSections(markdown: string): ParsedSection[] {\n const tree = unified().use(remarkParse).parse(markdown);\n\n const h2s: { heading: string; startOffset: number; endOffset: number }[] = [];\n\n visit(tree, \"heading\", (node) => {\n if (node.depth === 2) {\n const text = (node.children as Array<{ type: string; value?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.value ?? \"\")\n .join(\"\");\n h2s.push({\n heading: text,\n startOffset: node.position!.start.offset as number,\n endOffset: node.position!.end.offset as number,\n });\n }\n });\n\n const sections: ParsedSection[] = [];\n\n // Preamble: content before first H2\n const firstH2 = h2s[0];\n const firstOffset = firstH2 ? firstH2.startOffset : markdown.length;\n const preamble = markdown.slice(0, firstOffset).trim();\n if (preamble) {\n sections.push({ heading: \"\", content: preamble, tokens: countTokens(preamble) });\n }\n\n // Each H2 section: content AFTER the heading line, up to the next H2 (or end)\n for (let i = 0; i < h2s.length; i++) {\n const current = h2s[i]!;\n const next = h2s[i + 1];\n const end = next ? next.startOffset : markdown.length;\n const content = markdown.slice(current.endOffset, end).trim();\n sections.push({\n heading: current.heading,\n content,\n tokens: countTokens(content),\n });\n }\n\n return sections;\n}\n","import { encodingForModel } from \"js-tiktoken\";\n\nlet encoder: ReturnType<typeof encodingForModel> | undefined;\n\nfunction getEncoder() {\n if (!encoder) encoder = encodingForModel(\"gpt-4o\");\n return encoder;\n}\n\nexport function countTokens(text: string): number {\n if (!text) return 0;\n return getEncoder().encode(text).length;\n}\n","import type { SdxConfig } from \"@specdx/schema\";\nimport { DEPENDENCY_RELATIONSHIPS } from \"@specdx/schema\";\n\nexport class GraphError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GraphError\";\n }\n}\n\nexport interface Edge {\n from: string;\n to: string;\n}\n\nexport interface DependencyGraph {\n nodes: string[];\n edges: Edge[];\n topologicalSort(): string[];\n getDownstream(nodeId: string): string[];\n getUpstream(nodeId: string): string[];\n}\n\nexport function buildGraph(config: SdxConfig): DependencyGraph {\n const specNames = Object.keys(config.specs);\n const adjacency = new Map<string, string[]>();\n const reverseAdj = new Map<string, string[]>();\n const edges: Edge[] = [];\n\n for (const name of specNames) {\n adjacency.set(name, []);\n reverseAdj.set(name, []);\n }\n\n for (const [name, entry] of Object.entries(config.specs)) {\n if (!entry.requires) continue;\n for (const dep of entry.requires) {\n if (!adjacency.has(dep)) {\n throw new GraphError(\n `Spec \"${name}\" requires \"${dep}\", which does not exist in the config.`,\n );\n }\n adjacency.get(dep)!.push(name);\n reverseAdj.get(name)!.push(dep);\n edges.push({ from: dep, to: name });\n }\n }\n\n // Kahn's algorithm for cycle detection + topological sort\n const inDegree = new Map<string, number>();\n for (const name of specNames) inDegree.set(name, reverseAdj.get(name)!.length);\n\n const queue: string[] = [];\n for (const [name, degree] of inDegree) {\n if (degree === 0) queue.push(name);\n }\n\n const sorted: string[] = [];\n while (queue.length > 0) {\n const node = queue.shift()!;\n sorted.push(node);\n for (const neighbor of adjacency.get(node)!) {\n const newDegree = inDegree.get(neighbor)! - 1;\n inDegree.set(neighbor, newDegree);\n if (newDegree === 0) queue.push(neighbor);\n }\n }\n\n if (sorted.length !== specNames.length) {\n const remaining = specNames.filter((n) => !sorted.includes(n));\n throw new GraphError(`Circular dependency detected involving: ${remaining.join(\", \")}`);\n }\n\n return {\n nodes: specNames,\n edges,\n topologicalSort: () => [...sorted],\n getDownstream(nodeId: string): string[] {\n const visited = new Set<string>();\n const stack = [nodeId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const neighbor of adjacency.get(current) ?? []) {\n if (!visited.has(neighbor)) {\n visited.add(neighbor);\n stack.push(neighbor);\n }\n }\n }\n return [...visited];\n },\n getUpstream(nodeId: string): string[] {\n const visited = new Set<string>();\n const stack = [nodeId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const dep of reverseAdj.get(current) ?? []) {\n if (!visited.has(dep)) {\n visited.add(dep);\n stack.push(dep);\n }\n }\n }\n return [...visited];\n },\n };\n}\n\n/** A relationship edge declared in a spec's frontmatter `references`. */\nexport interface ReferenceEdge {\n fromId: string;\n toId: string;\n relationship: string;\n}\n\n// The dependency-implying taxonomy lives in @specdx/schema so it is versioned\n// with the schema it describes, rather than hardcoded here (ADR:\n// references/requires unification).\n\n/**\n * Collect relationship edges declared in spec frontmatter `references` fields.\n * Edges point from the declaring spec's id to the referenced spec's id.\n */\nexport function collectReferenceEdges(\n specs: { frontmatter: Record<string, unknown> }[],\n): ReferenceEdge[] {\n const edges: ReferenceEdge[] = [];\n for (const spec of specs) {\n const fromId = spec.frontmatter.id;\n if (typeof fromId !== \"string\") continue;\n const refs = spec.frontmatter.references;\n if (!Array.isArray(refs)) continue;\n for (const ref of refs) {\n if (ref && typeof ref === \"object\" && \"id\" in ref) {\n const r = ref as { id: unknown; relationship?: unknown };\n if (typeof r.id === \"string\") {\n edges.push({\n fromId,\n toId: r.id,\n relationship: typeof r.relationship === \"string\" ? r.relationship : \"related-to\",\n });\n }\n }\n }\n }\n return edges;\n}\n\n/**\n * Find dependency-implying frontmatter references that the config-level\n * `requires` graph does not reflect. `idToEntry` maps spec frontmatter ids to\n * config entry keys. References within the same entry (e.g. story-to-story\n * under one glob) and references to unmapped ids are skipped — reference\n * existence itself is the `structure/valid-references` lint rule's concern.\n */\nexport interface UnreflectedReference {\n edge: ReferenceEdge;\n requiringEntry: string;\n requiredEntry: string;\n /** True when adding the suggested requires edge would create a cycle. */\n createsCycle: boolean;\n}\n\nexport function findUnreflectedReferences(\n referenceEdges: ReferenceEdge[],\n idToEntry: Map<string, string>,\n graph: DependencyGraph,\n): UnreflectedReference[] {\n const configEdges = new Set(graph.edges.map((e) => `${e.from}→${e.to}`));\n const missing: UnreflectedReference[] = [];\n\n for (const edge of referenceEdges) {\n const direction = DEPENDENCY_RELATIONSHIPS[edge.relationship as never];\n if (!direction) continue;\n\n const selfEntry = idToEntry.get(edge.fromId);\n const targetEntry = idToEntry.get(edge.toId);\n if (!selfEntry || !targetEntry || selfEntry === targetEntry) continue;\n\n const requiringEntry = direction === \"self-requires-target\" ? selfEntry : targetEntry;\n const requiredEntry = direction === \"self-requires-target\" ? targetEntry : selfEntry;\n\n // Config edges point dependency → dependent\n if (!configEdges.has(`${requiredEntry}→${requiringEntry}`)) {\n // The suggested edge closes a cycle when the required entry is already\n // downstream of the requiring one (issue #13) — never recommend it.\n const createsCycle = graph.getDownstream(requiringEntry).includes(requiredEntry);\n missing.push({ edge, requiringEntry, requiredEntry, createsCycle });\n }\n }\n\n return missing;\n}\n","import { glob } from \"tinyglobby\";\nimport { join, isAbsolute } from \"node:path\";\n\nexport async function resolveGlob(pattern: string, baseDir: string): Promise<string[]> {\n const absolutePattern = isAbsolute(pattern) ? pattern : join(baseDir, pattern);\n return glob([absolutePattern], { absolute: true });\n}\n","import { createConsola, type ConsolaInstance } from \"consola\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LoggerOptions {\n quiet?: boolean;\n verbose?: boolean;\n}\n\nexport interface Logger extends ConsolaInstance {\n level: number;\n}\n\nexport function createLogger(options?: LoggerOptions): Logger {\n let level = 3; // info\n if (options?.quiet) level = 1; // only errors\n if (options?.verbose) level = 4; // debug\n return createConsola({ level }) as Logger;\n}\n","import type { SdxConfig } from \"@specdx/schema\";\nimport { DEPENDENCY_RELATIONSHIPS } from \"@specdx/schema\";\n\n/** Where a relation edge was declared. */\nexport type RelationSource = \"requires\" | \"references\" | \"both\";\n\n/** A dependency edge in **spec id** space, pointing upstream → downstream. */\nexport interface RelationEdge {\n /** Spec id of the dependency. */\n from: string;\n /** Spec id of the dependent. */\n to: string;\n /** Which declaration(s) produced this edge. */\n source: RelationSource;\n}\n\n/**\n * Answers \"what is upstream / downstream of this spec?\" in spec id space.\n *\n * specdx declares relationships two ways: config `requires` (keyed by config\n * entry, glob-aware, cheap) and frontmatter `references` (keyed by spec id,\n * typed). Consumers used to read one or the other, so the same question got\n * different answers — `freshness/staleness-check` saw only references, while\n * impact analysis saw only the config graph. This resolver unions both at\n * query time so every consumer agrees, without changing which source owns\n * graph topology (ADR: references/requires unification, Option B).\n */\nexport interface RelationResolver {\n /** All dependency edges, in spec id space, deduplicated. */\n edges: RelationEdge[];\n /** Spec ids this spec depends on, transitively. */\n getUpstream(specId: string): string[];\n /** Spec ids that depend on this spec, transitively. */\n getDownstream(specId: string): string[];\n}\n\ninterface SpecLike {\n frontmatter: Record<string, unknown>;\n}\n\n/** Map each config entry key to the spec ids its path resolved to. */\nfunction mapEntriesToIds(\n config: SdxConfig,\n specsByEntry: Map<string, SpecLike[]>,\n): Map<string, string[]> {\n const entryIds = new Map<string, string[]>();\n for (const key of Object.keys(config.specs)) {\n const ids: string[] = [];\n for (const spec of specsByEntry.get(key) ?? []) {\n const id = spec.frontmatter.id;\n if (typeof id === \"string\") ids.push(id);\n }\n entryIds.set(key, ids);\n }\n return entryIds;\n}\n\n/** Every spec id present, regardless of which entry it came from. */\nfunction collectKnownIds(specsByEntry: Map<string, SpecLike[]>): Set<string> {\n const ids = new Set<string>();\n for (const specs of specsByEntry.values()) {\n for (const spec of specs) {\n const id = spec.frontmatter.id;\n if (typeof id === \"string\") ids.add(id);\n }\n }\n return ids;\n}\n\nfunction walk(specId: string, adjacency: Map<string, string[]>): string[] {\n const visited = new Set<string>();\n const stack = [specId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const next of adjacency.get(current) ?? []) {\n if (!visited.has(next)) {\n visited.add(next);\n stack.push(next);\n }\n }\n }\n visited.delete(specId);\n return [...visited];\n}\n\n/**\n * Build a resolver from config `requires` and dependency-implying frontmatter\n * `references`.\n *\n * A glob entry is one config entry but many spec ids, so one `requires` edge\n * between entries expands to the cross-product of their spec ids. Structural\n * reference kinds (`decomposed-into`, `supersedes`, `related-to`) are not\n * dependency-implying and are excluded — see DEPENDENCY_RELATIONSHIPS.\n *\n * @param config - Spec config. When undefined, only frontmatter references\n * contribute edges — useful for callers that have specs but no config.\n * @param specsByEntry - Parsed specs grouped by the config entry key they resolved from.\n */\nexport function buildRelationResolver(\n config: SdxConfig | undefined,\n specsByEntry: Map<string, SpecLike[]>,\n): RelationResolver {\n const entryIds = config ? mapEntriesToIds(config, specsByEntry) : new Map<string, string[]>();\n const knownIds = collectKnownIds(specsByEntry);\n\n // key \"from→to\" -> source, so a relation declared both ways is one edge\n const edgeSources = new Map<string, RelationSource>();\n const addEdge = (from: string, to: string, source: \"requires\" | \"references\"): void => {\n if (from === to) return;\n const key = `${from}\u0000${to}`;\n const existing = edgeSources.get(key);\n if (!existing) {\n edgeSources.set(key, source);\n } else if (existing !== source) {\n edgeSources.set(key, \"both\");\n }\n };\n\n // 1. Config requires: entry-level edges expand across the entries' spec ids\n for (const [key, entry] of Object.entries(config?.specs ?? {})) {\n const requires = (entry as { requires?: string[] }).requires ?? [];\n for (const dep of requires) {\n for (const from of entryIds.get(dep) ?? []) {\n for (const to of entryIds.get(key) ?? []) {\n addEdge(from, to, \"requires\");\n }\n }\n }\n }\n\n // 2. Frontmatter references, already in spec id space\n for (const specs of specsByEntry.values()) {\n for (const spec of specs) {\n const selfId = spec.frontmatter.id;\n if (typeof selfId !== \"string\") continue;\n const refs = spec.frontmatter.references;\n if (!Array.isArray(refs)) continue;\n\n for (const ref of refs) {\n if (!ref || typeof ref !== \"object\") continue;\n const { id: targetId, relationship } = ref as { id?: unknown; relationship?: unknown };\n if (typeof targetId !== \"string\" || typeof relationship !== \"string\") continue;\n // Referencing a spec outside the suite is valid-references' concern.\n if (!knownIds.has(targetId)) continue;\n\n const direction = DEPENDENCY_RELATIONSHIPS[relationship as never];\n if (direction === \"self-requires-target\") {\n addEdge(targetId, selfId, \"references\");\n } else if (direction === \"target-requires-self\") {\n addEdge(selfId, targetId, \"references\");\n }\n }\n }\n }\n\n const edges: RelationEdge[] = [];\n const downstreamAdj = new Map<string, string[]>();\n const upstreamAdj = new Map<string, string[]>();\n\n for (const [key, source] of edgeSources) {\n const [from, to] = key.split(\"\u0000\") as [string, string];\n edges.push({ from, to, source });\n downstreamAdj.set(from, [...(downstreamAdj.get(from) ?? []), to]);\n upstreamAdj.set(to, [...(upstreamAdj.get(to) ?? []), from]);\n }\n\n return {\n edges,\n getUpstream: (specId) => walk(specId, upstreamAdj),\n getDownstream: (specId) => walk(specId, downstreamAdj),\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve, isAbsolute } from \"node:path\";\nimport { ConfigError } from \"./config.js\";\n\nconst BUILTINS = [\"minimal\", \"recommended\", \"strict\"];\n\n/**\n * Resolve a preset name to its config content.\n * Returns null for built-in presets (handled by @specdx/lint).\n * Resolves local file paths and npm package names.\n */\nexport async function resolvePreset(\n name: string,\n cwd = process.cwd(),\n): Promise<Record<string, unknown> | null> {\n if (BUILTINS.includes(name)) {\n return null;\n }\n\n // Try local file path\n const localPath = isAbsolute(name) ? name : resolve(cwd, name);\n try {\n const content = await readFile(localPath, \"utf-8\");\n const { default: yaml } = await import(\"yaml\");\n return yaml.parse(content) as Record<string, unknown>;\n } catch {\n // Not a local file, try npm\n }\n\n // Try npm package\n try {\n const mod = (await import(name)) as { default?: Record<string, unknown> };\n return (mod.default ?? mod) as Record<string, unknown>;\n } catch {\n throw new ConfigError(`Could not resolve preset \"${name}\" as a local file or npm package`);\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,MAAM,eAAe;AAC9B,SAAS,SAAS,iBAAiB;AAG7B,IAAO,cAAP,cAA2B,MAAK;EAGlB;EAFlB,YACE,SACgB,QAAkB;AAElC,UAAM,OAAO;AAFG,SAAA,SAAA;AAGhB,SAAK,OAAO;EACd;;AAGF,IAAM,kBAAkB;AAExB,eAAsB,WAAW,UAAmB,YAAmB;AACrE,QAAM,eAAe,YAAa,MAAM,WAAW,cAAc,QAAQ,IAAG,CAAE;AAC9E,M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K,EAAE,CAAC;AAChE,gBAAY,IAAI,IAAI,CAAC,GAAI,YAAY,IAAI,EAAE,KAAK,CAAA,GAAK,IAAI,CAAC;EAC5D;AAEA,SAAO;IACL;IACA,aAAa,CAAC,WAAW,KAAK,QAAQ,WAAW;IACjD,eAAe,CAAC,WAAW,KAAK,QAAQ,aAAa;;AAEzD;;;AC3KA,SAAS,YAAAC,iBAAgB;AACzB,SAAS,SAAS,cAAAC,mBAAkB;","names":["readFile","parseYaml","readFile","parseYaml","join","readFile","isAbsolute"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"specdx\",\n \"version\": \"0.5.0\",\n \"description\": \"Spec-driven development toolchain. Validate, lint, pack, and ship specs for LLM-assisted workflows.\",\n \"type\": \"module\",\n \"license\": \"MIT\",\n \"author\": \"Umar Gora (https://github.com/umxr)\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/umxr/specdx.git\",\n \"directory\": \"packages/cli\"\n },\n \"homepage\": \"https://github.com/umxr/specdx#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/umxr/specdx/issues\"\n },\n \"keywords\": [\n \"spec\",\n \"specification\",\n \"prd\",\n \"technical-design\",\n \"api-contract\",\n \"lint\",\n \"validation\",\n \"llm\",\n \"ai\",\n \"context-packing\",\n \"spec-driven-development\",\n \"claude-code\"\n ],\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"bin\": {\n \"specdx\": \"./dist/main.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"files\": [\n \"dist\",\n \".claude-plugin\",\n \"hooks\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"clean\": \"rm -rf dist *.tsbuildinfo\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.27.0\",\n \"ajv\": \"^8.18.0\",\n \"ajv-formats\": \"^3.0.1\",\n \"citty\": \"^0.2.1\",\n \"consola\": \"^3.4.0\",\n \"gray-matter\": \"^4.0.3\",\n \"js-tiktoken\": \"^1.0.18\",\n \"remark-parse\": \"^11.0.0\",\n \"tinyglobby\": \"^0.2.12\",\n \"unified\": \"^11.0.0\",\n \"unist-util-visit\": \"^5.0.0\",\n \"yaml\": \"^2.7.0\",\n \"zod\": \"^3.23.0\"\n },\n \"devDependencies\": {\n \"@specdx/check\": \"workspace:*\",\n \"@specdx/core\": \"workspace:*\",\n \"@specdx/diff\": \"workspace:*\",\n \"@specdx/lint\": \"workspace:*\",\n \"@specdx/mcp\": \"workspace:*\",\n \"@specdx/pack\": \"workspace:*\",\n \"@specdx/schema\": \"workspace:*\",\n \"@specdx/skills\": \"workspace:*\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"^5.7.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"peerDependencies\": {\n \"ts-morph\": \">=20\",\n \"@anthropic-ai/sdk\": \">=0.30\"\n },\n \"peerDependenciesMeta\": {\n \"ts-morph\": {\n \"optional\": true\n },\n \"@anthropic-ai/sdk\": {\n \"optional\": true\n }\n }\n}\n"],"mappings":";AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,QAAU;AAAA,EACV,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,KAAO;AAAA,IACL,QAAU;AAAA,EACZ;AAAA,EACA,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,OAAS;AAAA,EACX;AAAA,EACA,cAAgB;AAAA,IACd,6BAA6B;AAAA,IAC7B,KAAO;AAAA,IACP,eAAe;AAAA,IACf,OAAS;AAAA,IACT,SAAW;AAAA,IACX,eAAe;AAAA,IACf,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,YAAc;AAAA,IACd,SAAW;AAAA,IACX,oBAAoB;AAAA,IACpB,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,iBAAmB;AAAA,IACjB,iBAAiB;AAAA,IACjB,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB,MAAQ;AAAA,IACR,YAAc;AAAA,EAChB;AAAA,EACA,eAAiB;AAAA,IACf,QAAU;AAAA,EACZ;AAAA,EACA,kBAAoB;AAAA,IAClB,YAAY;AAAA,IACZ,qBAAqB;AAAA,EACvB;AAAA,EACA,sBAAwB;AAAA,IACtB,YAAY;AAAA,MACV,UAAY;AAAA,IACd;AAAA,IACA,qBAAqB;AAAA,MACnB,UAAY;AAAA,IACd;AAAA,EACF;AACF;","names":[]}
@@ -1 +0,0 @@
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;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;;;ACZA,eAAsB,WAAW,QAA8C;AAC7E,QAAM,YAAY,QAAQ,IAAG;AAC7B,QAAM,SAAS,MAAM,WAAW,QAAW,SAAS;AACpD,QAAM,SAAS,OAAO,UAAU,OAAO,MAAM,WAAW;AACxD,QAAM,EAAE,OAAO,OAAM,IAAK,MAAM,kBAAkB;IAChD;IACA;IACA;GACD;AAID,QAAM,QAAsB,CAAA;AAC5B,aAAW,CAAC,EAAE,KAAK,KAAK,OAAO,QAAQ,OAAO,KAAK,GA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A6B;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":[]}
@@ -1,16 +0,0 @@
1
- import {
2
- analyzeWithAi,
3
- checkArtifacts,
4
- detectFramework,
5
- parseArtifacts,
6
- runCheck
7
- } from "./chunk-3YXRWQGX.js";
8
- import "./chunk-5WRI5ZAA.js";
9
- export {
10
- analyzeWithAi,
11
- checkArtifacts,
12
- detectFramework,
13
- parseArtifacts,
14
- runCheck
15
- };
16
- //# sourceMappingURL=dist-ROHCFKYT.js.map