specdx 0.3.0-alpha.3 → 0.4.0-alpha.10

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 (82) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/LICENSE +21 -0
  3. package/dist/{changelog-OUP2RXWN.js → changelog-GR53T6IG.js} +18 -11
  4. package/dist/{changelog-OUP2RXWN.js.map → changelog-GR53T6IG.js.map} +1 -1
  5. package/dist/{check-3XQYO3HU.js → check-OMWCIY5D.js} +37 -10
  6. package/dist/check-OMWCIY5D.js.map +1 -0
  7. package/dist/chunk-3GMYCATE.js +526 -0
  8. package/dist/chunk-3GMYCATE.js.map +1 -0
  9. package/dist/{chunk-6BWZEAST.js → chunk-N77RNV7J.js} +161 -26
  10. package/dist/chunk-N77RNV7J.js.map +1 -0
  11. package/dist/{pack-PI6V6OR2.js → chunk-SDDTD4R3.js} +97 -171
  12. package/dist/chunk-SDDTD4R3.js.map +1 -0
  13. package/dist/{chunk-ZX4HVL5M.js → chunk-SJCIM4TC.js} +119 -17
  14. package/dist/chunk-SJCIM4TC.js.map +1 -0
  15. package/dist/{chunk-DDFLMRPC.js → chunk-VMMTEGYN.js} +15 -11
  16. package/dist/chunk-VMMTEGYN.js.map +1 -0
  17. package/dist/{chunk-PHR7AV6I.js → chunk-Z77VQUZ3.js} +156 -2
  18. package/dist/chunk-Z77VQUZ3.js.map +1 -0
  19. package/dist/diff-AUBYOQWU.js +107 -0
  20. package/dist/diff-AUBYOQWU.js.map +1 -0
  21. package/dist/dist-BXYQB2UO.js +306 -0
  22. package/dist/dist-BXYQB2UO.js.map +1 -0
  23. package/dist/dist-RL2DT3ZE.js +15 -0
  24. package/dist/{explain-I7AQMEEH.js → explain-EUID6MZF.js} +35 -28
  25. package/dist/explain-EUID6MZF.js.map +1 -0
  26. package/dist/{generate-PC7BIB7G.js → generate-U3EFOCNS.js} +3 -3
  27. package/dist/{generate-story-7WHPPFHY.js → generate-story-U6FMQIYZ.js} +8 -4
  28. package/dist/generate-story-U6FMQIYZ.js.map +1 -0
  29. package/dist/{generate-test-plan-U5LMWGKX.js → generate-test-plan-HOCWDYKF.js} +11 -6
  30. package/dist/generate-test-plan-HOCWDYKF.js.map +1 -0
  31. package/dist/graph-TA54D4XA.js +102 -0
  32. package/dist/graph-TA54D4XA.js.map +1 -0
  33. package/dist/index.js +777 -158
  34. package/dist/index.js.map +1 -1
  35. package/dist/{lint-6Z2TVWAQ.js → lint-L5WOBD25.js} +17 -6
  36. package/dist/lint-L5WOBD25.js.map +1 -0
  37. package/dist/main.js +100 -15
  38. package/dist/main.js.map +1 -1
  39. package/dist/mcp-GNQQGD7X.js +17 -0
  40. package/dist/mcp-GNQQGD7X.js.map +1 -0
  41. package/dist/{migrate-L7W5RHSS.js → migrate-YEJQWIMX.js} +4 -4
  42. package/dist/migrate-YEJQWIMX.js.map +1 -0
  43. package/dist/pack-AQH5XQUF.js +168 -0
  44. package/dist/pack-AQH5XQUF.js.map +1 -0
  45. package/dist/ready-DB5ORK2E.js +229 -0
  46. package/dist/ready-DB5ORK2E.js.map +1 -0
  47. package/dist/skills/specdx-check-drift.md +1 -1
  48. package/dist/skills/specdx-verify.md +12 -1
  49. package/dist/{status-AV5GSWVI.js → status-3QUQMF4L.js} +46 -31
  50. package/dist/status-3QUQMF4L.js.map +1 -0
  51. package/dist/{update-HIWDDEZQ.js → update-PE2DPYDR.js} +5 -5
  52. package/dist/update-PE2DPYDR.js.map +1 -0
  53. package/dist/validate-YNZMV6KZ.js +86 -0
  54. package/dist/validate-YNZMV6KZ.js.map +1 -0
  55. package/hooks/session-start +0 -0
  56. package/package.json +49 -16
  57. package/dist/check-3XQYO3HU.js.map +0 -1
  58. package/dist/chunk-6BWZEAST.js.map +0 -1
  59. package/dist/chunk-DDFLMRPC.js.map +0 -1
  60. package/dist/chunk-PHR7AV6I.js.map +0 -1
  61. package/dist/chunk-WTFWNYJA.js +0 -261
  62. package/dist/chunk-WTFWNYJA.js.map +0 -1
  63. package/dist/chunk-ZX4HVL5M.js.map +0 -1
  64. package/dist/diff-275PLXYH.js +0 -100
  65. package/dist/diff-275PLXYH.js.map +0 -1
  66. package/dist/dist-PQCG2XXF.js +0 -11
  67. package/dist/explain-I7AQMEEH.js.map +0 -1
  68. package/dist/generate-story-7WHPPFHY.js.map +0 -1
  69. package/dist/generate-test-plan-U5LMWGKX.js.map +0 -1
  70. package/dist/graph-RCAPF55A.js +0 -54
  71. package/dist/graph-RCAPF55A.js.map +0 -1
  72. package/dist/lint-6Z2TVWAQ.js.map +0 -1
  73. package/dist/migrate-L7W5RHSS.js.map +0 -1
  74. package/dist/pack-PI6V6OR2.js.map +0 -1
  75. package/dist/ready-B7IFPL3S.js +0 -159
  76. package/dist/ready-B7IFPL3S.js.map +0 -1
  77. package/dist/status-AV5GSWVI.js.map +0 -1
  78. package/dist/update-HIWDDEZQ.js.map +0 -1
  79. package/dist/validate-N2WSG75W.js +0 -34
  80. package/dist/validate-N2WSG75W.js.map +0 -1
  81. /package/dist/{dist-PQCG2XXF.js.map → dist-RL2DT3ZE.js.map} +0 -0
  82. /package/dist/{generate-PC7BIB7G.js.map → generate-U3EFOCNS.js.map} +0 -0
@@ -866,9 +866,118 @@ function matchTests(specCases, codeTests, specId) {
866
866
  return findings;
867
867
  }
868
868
 
869
+ // ../check/dist/artifacts.js
870
+ import { existsSync as existsSync7 } from "fs";
871
+ import { join as join8 } from "path";
872
+ var ENFORCED_STATUSES = /* @__PURE__ */ new Set(["approved"]);
873
+ function artifactsEnforced(status) {
874
+ return typeof status === "string" && ENFORCED_STATUSES.has(status);
875
+ }
876
+ function parseArtifacts(spec) {
877
+ const raw = spec.frontmatter.artifacts;
878
+ if (!Array.isArray(raw))
879
+ return [];
880
+ const out = [];
881
+ for (const item of raw) {
882
+ if (!item || typeof item !== "object")
883
+ continue;
884
+ const decl = item;
885
+ if (typeof decl.path !== "string" || decl.path.length === 0)
886
+ continue;
887
+ const exports = Array.isArray(decl.exports) ? decl.exports.filter((e) => typeof e === "string" && e.length > 0) : void 0;
888
+ out.push({ path: decl.path, exports });
889
+ }
890
+ return out;
891
+ }
892
+ async function getExportedNames(filePath) {
893
+ try {
894
+ const { Project } = await import("ts-morph");
895
+ const project = new Project({
896
+ skipAddingFilesFromTsConfig: true,
897
+ compilerOptions: { allowJs: true }
898
+ });
899
+ const sourceFile = project.addSourceFileAtPath(filePath);
900
+ return new Set(sourceFile.getExportedDeclarations().keys());
901
+ } catch {
902
+ return null;
903
+ }
904
+ }
905
+ async function checkArtifacts(specs, projectDir, tsMorphAvailable) {
906
+ const findings = [];
907
+ const notes = [];
908
+ let total = 0;
909
+ let pending = 0;
910
+ let skippedExports = 0;
911
+ for (const spec of specs) {
912
+ const specId = String(spec.frontmatter.id);
913
+ const status = spec.frontmatter.status;
914
+ const enforced = artifactsEnforced(status);
915
+ for (const artifact of parseArtifacts(spec)) {
916
+ const absolute = join8(projectDir, artifact.path);
917
+ if (!existsSync7(absolute)) {
918
+ if (enforced) {
919
+ total += 1;
920
+ findings.push({
921
+ type: "missing",
922
+ category: "artifact",
923
+ specId,
924
+ expected: `file "${artifact.path}"`,
925
+ severity: "error",
926
+ suggestion: `Create ${artifact.path} or update the artifacts list in ${specId}.`
927
+ });
928
+ } else {
929
+ pending += 1;
930
+ findings.push({
931
+ type: "pending",
932
+ category: "artifact",
933
+ specId,
934
+ expected: `file "${artifact.path}"`,
935
+ severity: "info",
936
+ suggestion: `planned by ${specId} (status: ${String(status)}) \u2014 not yet implemented; enforced once the spec is approved.`
937
+ });
938
+ }
939
+ continue;
940
+ }
941
+ total += 1;
942
+ if (!artifact.exports || artifact.exports.length === 0)
943
+ continue;
944
+ if (!tsMorphAvailable) {
945
+ skippedExports += artifact.exports.length;
946
+ continue;
947
+ }
948
+ const exported = await getExportedNames(absolute);
949
+ if (exported === null) {
950
+ skippedExports += artifact.exports.length;
951
+ continue;
952
+ }
953
+ for (const name of artifact.exports) {
954
+ total += 1;
955
+ if (!exported.has(name)) {
956
+ findings.push({
957
+ type: "missing",
958
+ category: "artifact",
959
+ specId,
960
+ codeLocation: { file: artifact.path, line: 1 },
961
+ expected: `export "${name}" from ${artifact.path}`,
962
+ severity: "error",
963
+ suggestion: `Export ${name} from ${artifact.path} or update the artifacts list in ${specId}.`
964
+ });
965
+ }
966
+ }
967
+ }
968
+ }
969
+ if (skippedExports > 0) {
970
+ notes.push(`artifact export checks skipped for ${skippedExports} export(s): ts-morph is not available or the file could not be parsed.`);
971
+ }
972
+ if (pending > 0) {
973
+ notes.push(`${pending} declared artifact(s) pending: planned by specs that are not yet approved. They are excluded from the score and become enforceable when the spec status changes to approved.`);
974
+ }
975
+ return { findings, total, checked: total, pending, notes };
976
+ }
977
+
869
978
  // ../check/dist/score.js
870
979
  function computeScore(findings, totals) {
871
- const missingByCategory = { route: 0, type: 0, test: 0 };
980
+ const missingByCategory = { route: 0, type: 0, test: 0, artifact: 0 };
872
981
  for (const f of findings) {
873
982
  if (f.type === "missing" || f.type === "mismatch") {
874
983
  missingByCategory[f.category] = (missingByCategory[f.category] ?? 0) + 1;
@@ -877,7 +986,8 @@ function computeScore(findings, totals) {
877
986
  const categoryMap = {
878
987
  routes: { total: totals.routes, categoryKey: "route" },
879
988
  types: { total: totals.types, categoryKey: "type" },
880
- tests: { total: totals.tests, categoryKey: "test" }
989
+ tests: { total: totals.tests, categoryKey: "test" },
990
+ artifacts: { total: totals.artifacts, categoryKey: "artifact" }
881
991
  };
882
992
  const byCategory = {};
883
993
  let totalItems = 0;
@@ -889,13 +999,16 @@ function computeScore(findings, totals) {
889
999
  totalItems += total;
890
1000
  totalMatched += matched;
891
1001
  }
892
- const overall = totalItems === 0 ? 100 : Math.round(totalMatched / totalItems * 100);
893
- return { overall, byCategory };
1002
+ if (totalItems === 0) {
1003
+ return { overall: 0, assessed: false, byCategory };
1004
+ }
1005
+ const overall = Math.round(totalMatched / totalItems * 100);
1006
+ return { overall, assessed: true, byCategory };
894
1007
  }
895
1008
 
896
1009
  // ../check/dist/detect-framework.js
897
1010
  import { readFile as readFile2 } from "fs/promises";
898
- import { join as join8 } from "path";
1011
+ import { join as join9 } from "path";
899
1012
  var FRAMEWORK_PACKAGES = [
900
1013
  ["express", "express"],
901
1014
  ["hono", "hono"],
@@ -904,7 +1017,7 @@ var FRAMEWORK_PACKAGES = [
904
1017
  async function detectFramework(projectDir) {
905
1018
  let pkg;
906
1019
  try {
907
- const content = await readFile2(join8(projectDir, "package.json"), "utf-8");
1020
+ const content = await readFile2(join9(projectDir, "package.json"), "utf-8");
908
1021
  pkg = JSON.parse(content);
909
1022
  } catch {
910
1023
  return null;
@@ -921,25 +1034,39 @@ async function detectFramework(projectDir) {
921
1034
  // ../check/dist/check.js
922
1035
  async function runCheck(specs, projectDir, config = {}) {
923
1036
  const findings = [];
1037
+ const notes = [];
924
1038
  let routeTotal = 0;
925
1039
  let typeTotal = 0;
926
1040
  let testTotal = 0;
1041
+ let codeRouteCount = null;
1042
+ let codeTypeCount = null;
1043
+ let codeTestCount = null;
1044
+ const tsMorphAvailable = await import("ts-morph").then(() => true, () => false);
1045
+ if (!tsMorphAvailable) {
1046
+ notes.push("route and type extraction skipped: ts-morph is not installed. Install specdx and ts-morph as devDependencies (pnpm add -D specdx ts-morph) \u2014 an ephemeral runner like pnpm dlx cannot provide it.");
1047
+ }
1048
+ const framework = config.framework && config.framework !== "auto" ? config.framework : await detectFramework(projectDir);
927
1049
  const apiContractSpecs = specs.filter((s) => s.frontmatter.type === "api-contract");
928
- if (apiContractSpecs.length > 0) {
929
- const codeRoutes = await extractRoutes(projectDir, config);
1050
+ if (apiContractSpecs.length > 0 && tsMorphAvailable) {
1051
+ const codeRoutes = await extractRoutes(projectDir, config, framework);
1052
+ codeRouteCount = codeRoutes.length;
930
1053
  for (const spec of apiContractSpecs) {
931
1054
  const specEndpoints = parseEndpoints(spec.content);
932
1055
  routeTotal += specEndpoints.length;
933
1056
  findings.push(...matchRoutes(specEndpoints, codeRoutes, spec.frontmatter.id));
934
1057
  }
1058
+ if (framework === null) {
1059
+ notes.push("no supported framework detected (express, hono, nextjs) \u2014 route extraction ran in fallback mode across all extractors.");
1060
+ }
935
1061
  }
936
1062
  const designSpecs = specs.filter((s) => s.frontmatter.type === "technical-design");
937
1063
  if (designSpecs.length > 0) {
938
1064
  const codeTypes = [
939
- ...await extractTypeScriptTypes(projectDir, config.types_dir),
940
- ...await extractZodSchemas(projectDir, config.types_dir),
1065
+ ...tsMorphAvailable ? await extractTypeScriptTypes(projectDir, config.types_dir) : [],
1066
+ ...tsMorphAvailable ? await extractZodSchemas(projectDir, config.types_dir) : [],
941
1067
  ...await extractPrismaModels(projectDir)
942
1068
  ];
1069
+ codeTypeCount = codeTypes.length;
943
1070
  for (const spec of designSpecs) {
944
1071
  const specTypes = parseTypeDefinitions(spec.content);
945
1072
  typeTotal += specTypes.reduce((sum, t) => sum + t.fields.length, 0);
@@ -949,20 +1076,36 @@ async function runCheck(specs, projectDir, config = {}) {
949
1076
  const testPlanSpecs = specs.filter((s) => s.frontmatter.type === "test-plan");
950
1077
  if (testPlanSpecs.length > 0) {
951
1078
  const codeTests = await extractTestDescriptions(projectDir, config.tests_dir);
1079
+ codeTestCount = codeTests.length;
952
1080
  for (const spec of testPlanSpecs) {
953
1081
  const specCases = parseTestCases(spec.content);
954
1082
  testTotal += specCases.length;
955
1083
  findings.push(...matchTests(specCases, codeTests, spec.frontmatter.id));
956
1084
  }
957
1085
  }
958
- const score = computeScore(findings, { routes: routeTotal, types: typeTotal, tests: testTotal });
1086
+ const artifactResult = await checkArtifacts(specs, projectDir, tsMorphAvailable);
1087
+ findings.push(...artifactResult.findings);
1088
+ notes.push(...artifactResult.notes);
1089
+ const score = computeScore(findings, {
1090
+ routes: routeTotal,
1091
+ types: typeTotal,
1092
+ tests: testTotal,
1093
+ artifacts: artifactResult.total
1094
+ });
959
1095
  const errors = findings.filter((f) => f.severity === "error").length;
960
1096
  const warnings = findings.filter((f) => f.severity === "warn").length;
961
- const summary = `${score.overall}% implementation coverage \u2014 ${errors} errors, ${warnings} warnings`;
962
- return { findings, score, summary };
1097
+ const summary = score.assessed ? `${score.overall}% implementation coverage \u2014 ${errors} errors, ${warnings} warnings` : "coverage not assessed \u2014 no checkable surfaces found (no spec'd routes, types, test cases, or declared artifacts)";
1098
+ const scanned = {
1099
+ framework: framework ?? null,
1100
+ codeRoutes: codeRouteCount,
1101
+ codeTypes: codeTypeCount,
1102
+ codeTests: codeTestCount,
1103
+ artifacts: artifactResult.total > 0 ? artifactResult.checked : null,
1104
+ artifactsPending: artifactResult.pending
1105
+ };
1106
+ return { findings, score, summary, scanned, notes };
963
1107
  }
964
- async function extractRoutes(projectDir, config) {
965
- const framework = config.framework ?? "auto";
1108
+ async function extractRoutes(projectDir, config, framework) {
966
1109
  if (framework === "express") {
967
1110
  return extractExpressRoutes(projectDir, config.routes_dir);
968
1111
  }
@@ -972,16 +1115,6 @@ async function extractRoutes(projectDir, config) {
972
1115
  if (framework === "nextjs") {
973
1116
  return extractNextjsRoutes(projectDir, config.app_dir);
974
1117
  }
975
- const detected = await detectFramework(projectDir);
976
- if (detected === "express") {
977
- return extractExpressRoutes(projectDir, config.routes_dir);
978
- }
979
- if (detected === "hono") {
980
- return extractHonoRoutes(projectDir, config.routes_dir);
981
- }
982
- if (detected === "nextjs") {
983
- return extractNextjsRoutes(projectDir, config.app_dir);
984
- }
985
1118
  const [express, hono, nextjs] = await Promise.all([
986
1119
  extractExpressRoutes(projectDir, config.routes_dir),
987
1120
  extractHonoRoutes(projectDir, config.routes_dir),
@@ -1044,8 +1177,10 @@ Only output the JSON array, no other text.`;
1044
1177
  }
1045
1178
 
1046
1179
  export {
1180
+ parseArtifacts,
1181
+ checkArtifacts,
1047
1182
  detectFramework,
1048
1183
  runCheck,
1049
1184
  analyzeWithAi
1050
1185
  };
1051
- //# sourceMappingURL=chunk-6BWZEAST.js.map
1186
+ //# sourceMappingURL=chunk-N77RNV7J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../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/check.ts","../../check/src/ai.ts"],"sourcesContent":["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 */\nexport function parseEndpoints(content: string): SpecEndpoint[] {\n const section = extractSection(content, \"Endpoints\");\n if (!section) return [];\n\n const results: SpecEndpoint[] = [];\n\n // Split by `### METHOD /path` headings\n const headingPattern = /^###\\s+(GET|POST|PUT|PATCH|DELETE)\\s+(\\S+)/im;\n // Split section into blocks starting at each `### ` heading\n const blocks = section.split(/^(?=###\\s)/m);\n\n for (const block of blocks) {\n const headingMatch = headingPattern.exec(block);\n if (!headingMatch) continue;\n\n const rawMethod = headingMatch[1]!.toUpperCase();\n if (!HTTP_METHODS.has(rawMethod)) continue;\n const method = rawMethod as HttpMethod;\n const path = headingMatch[2]!;\n\n // Extract path params: segments starting with `:`\n const params = (path.match(/:([A-Za-z_][A-Za-z0-9_]*)/g) ?? []).map((p) => p.slice(1));\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 results.push({\n method,\n path,\n params,\n description: descriptionLine,\n });\n }\n\n return results;\n}\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 const headingMatch = /^###\\s+(\\S+)/m.exec(block);\n if (!headingMatch) continue;\n\n const name = headingMatch[1]!;\n const fields: SpecTypeDefinition[\"fields\"] = [];\n\n // Field lines: `- \\`fieldName?\\`: type description`\n const fieldPattern = /^-\\s+`([^`]+)`\\s*:\\s*(.+)/gm;\n let fieldMatch: RegExpExecArray | null;\n\n while ((fieldMatch = fieldPattern.exec(block)) !== null) {\n const rawName = fieldMatch[1]!;\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[2]!.trim();\n const type = rawType.replace(/\\s*\\(.*?\\)\\s*$/, \"\").trim();\n\n fields.push({ name: fieldName, type, optional });\n }\n\n results.push({ name, fields });\n }\n\n return results;\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 const bulletText = bulletMatch[1]!.trim();\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({ description: `${label}: ${trimmed}`, section: currentSection });\n }\n }\n } else {\n results.push({ description: bulletText, section: currentSection });\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 = \"app\",\n): Promise<ExtractedRoute[]> {\n const scanDir = join(projectDir, appDir);\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 // 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 } 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\nexport async function extractPrismaModels(projectDir: string): Promise<ExtractedType[]> {\n const schemaPath = join(projectDir, \"schema.prisma\");\n let content: string;\n try {\n content = await readFile(schemaPath, \"utf-8\");\n } catch {\n return [];\n }\n\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 });\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: 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 total += 1;\n if (!exported.has(name)) {\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 }\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(s) pending: 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 missingByCategory[f.category] = (missingByCategory[f.category] ?? 0) + 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 { CheckResult, CheckConfig, ExtractedRoute, Finding } from \"./types.js\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport { parseEndpoints, parseTypeDefinitions, parseTestCases } 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 } 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/**\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 and TS/Zod\n // type extraction degrade to skipped-with-a-note instead of throwing (issue #7).\n const tsMorphAvailable = await import(\"ts-morph\").then(\n () => true,\n () => false,\n );\n if (!tsMorphAvailable) {\n notes.push(\n \"route and type 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 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 const designSpecs = specs.filter((s) => s.frontmatter.type === \"technical-design\");\n if (designSpecs.length > 0) {\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 for (const spec of designSpecs) {\n const specTypes = parseTypeDefinitions(spec.content);\n typeTotal += specTypes.reduce((sum, t) => sum + t.fields.length, 0);\n findings.push(...matchTypes(specTypes, codeTypes, spec.frontmatter.id as string));\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) {\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 { 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 sdx: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":";AAMA,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;AAG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,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":["HTTP_METHODS","existsSync","join","HTTP_METHODS","existsSync","join","HTTP_METHODS","existsSync","join","existsSync","join","join","existsSync","join","existsSync","join","readFile","join"]}