specdx 0.4.0-alpha.17 → 0.4.0-alpha.19

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 +1 -1
  2. package/README.md +477 -0
  3. package/dist/{check-Q3QKTN2D.js → check-PRQNMBOE.js} +5 -5
  4. package/dist/{chunk-PEC5LAVE.js → chunk-5MYELBKF.js} +56 -21
  5. package/dist/chunk-5MYELBKF.js.map +1 -0
  6. package/dist/{chunk-V7JOVK6D.js → chunk-BD6UDHYW.js} +194 -39
  7. package/dist/chunk-BD6UDHYW.js.map +1 -0
  8. package/dist/{chunk-TJPPBM24.js → chunk-ERRUYMZO.js} +21 -18
  9. package/dist/chunk-ERRUYMZO.js.map +1 -0
  10. package/dist/{chunk-Z77VQUZ3.js → chunk-MM325DR6.js} +2 -2
  11. package/dist/chunk-RDNEANZB.js +103 -0
  12. package/dist/chunk-RDNEANZB.js.map +1 -0
  13. package/dist/{chunk-4HPWTWBL.js → chunk-RY5CDUNN.js} +12 -7
  14. package/dist/chunk-RY5CDUNN.js.map +1 -0
  15. package/dist/{chunk-TF7WSPFV.js → chunk-T232GZ2L.js} +2 -2
  16. package/dist/{chunk-SJCIM4TC.js → chunk-ZIPGRLYE.js} +3 -1
  17. package/dist/chunk-ZIPGRLYE.js.map +1 -0
  18. package/dist/{diff-IEN6W4OG.js → diff-PHEX3HUT.js} +4 -4
  19. package/dist/{dist-DVROIZAO.js → dist-M7X5RJB3.js} +19 -11
  20. package/dist/dist-M7X5RJB3.js.map +1 -0
  21. package/dist/{dist-SWJSMLIP.js → dist-X4CSVKKR.js} +2 -2
  22. package/dist/{generate-GQPOLFP7.js → generate-FIMBI2NW.js} +5 -5
  23. package/dist/{generate-story-UJS37FHA.js → generate-story-5TPTJA7B.js} +41 -18
  24. package/dist/generate-story-5TPTJA7B.js.map +1 -0
  25. package/dist/{generate-test-plan-RQTSGQLR.js → generate-test-plan-XBAFJKJI.js} +58 -9
  26. package/dist/generate-test-plan-XBAFJKJI.js.map +1 -0
  27. package/dist/{graph-OKUMHR3Q.js → graph-UZJMLX4J.js} +3 -3
  28. package/dist/index.d.ts +171 -0
  29. package/dist/index.js +201 -41
  30. package/dist/index.js.map +1 -1
  31. package/dist/{lint-VB5PV32N.js → lint-PUAQ2UL6.js} +4 -4
  32. package/dist/main.js +5 -90
  33. package/dist/main.js.map +1 -1
  34. package/dist/{mcp-DADOVCEV.js → mcp-WTO5PDIS.js} +6 -3
  35. package/dist/mcp-WTO5PDIS.js.map +1 -0
  36. package/dist/{migrate-LAMRDT3V.js → migrate-DEFCNOAH.js} +18 -7
  37. package/dist/migrate-DEFCNOAH.js.map +1 -0
  38. package/dist/{pack-B3KYRKUR.js → pack-PNLD5AYW.js} +4 -4
  39. package/dist/{ready-C6YXJ47W.js → ready-XIO2IPRE.js} +15 -6
  40. package/dist/ready-XIO2IPRE.js.map +1 -0
  41. package/dist/skills/core/specdx-author-spec/SKILL.md +1 -1
  42. package/dist/skills/core/specdx-author-spec/references/step-02-sections.md +41 -0
  43. package/dist/skills/core/specdx-router/SKILL.md +2 -2
  44. package/dist/skills/experimental/specdx-check-drift/SKILL.md +1 -1
  45. package/dist/skills/experimental/specdx-verify/SKILL.md +1 -1
  46. package/dist/{status-BRLCD7NY.js → status-BXOYBOH6.js} +5 -5
  47. package/dist/{update-P6TQUI6H.js → update-ELXABLVS.js} +4 -4
  48. package/dist/{validate-WIB246IE.js → validate-FXD5WS4C.js} +3 -3
  49. package/hooks/hooks.json +1 -1
  50. package/hooks/session-start +35 -3
  51. package/package.json +19 -6
  52. package/dist/chunk-4HPWTWBL.js.map +0 -1
  53. package/dist/chunk-PEC5LAVE.js.map +0 -1
  54. package/dist/chunk-SJCIM4TC.js.map +0 -1
  55. package/dist/chunk-TJPPBM24.js.map +0 -1
  56. package/dist/chunk-V7JOVK6D.js.map +0 -1
  57. package/dist/dist-DVROIZAO.js.map +0 -1
  58. package/dist/generate-story-UJS37FHA.js.map +0 -1
  59. package/dist/generate-test-plan-RQTSGQLR.js.map +0 -1
  60. package/dist/mcp-DADOVCEV.js.map +0 -1
  61. package/dist/migrate-LAMRDT3V.js.map +0 -1
  62. package/dist/ready-C6YXJ47W.js.map +0 -1
  63. /package/dist/{check-Q3QKTN2D.js.map → check-PRQNMBOE.js.map} +0 -0
  64. /package/dist/{chunk-Z77VQUZ3.js.map → chunk-MM325DR6.js.map} +0 -0
  65. /package/dist/{chunk-TF7WSPFV.js.map → chunk-T232GZ2L.js.map} +0 -0
  66. /package/dist/{diff-IEN6W4OG.js.map → diff-PHEX3HUT.js.map} +0 -0
  67. /package/dist/{dist-SWJSMLIP.js.map → dist-X4CSVKKR.js.map} +0 -0
  68. /package/dist/{generate-GQPOLFP7.js.map → generate-FIMBI2NW.js.map} +0 -0
  69. /package/dist/{graph-OKUMHR3Q.js.map → graph-UZJMLX4J.js.map} +0 -0
  70. /package/dist/{lint-VB5PV32N.js.map → lint-PUAQ2UL6.js.map} +0 -0
  71. /package/dist/{pack-B3KYRKUR.js.map → pack-PNLD5AYW.js.map} +0 -0
  72. /package/dist/{status-BRLCD7NY.js.map → status-BXOYBOH6.js.map} +0 -0
  73. /package/dist/{update-P6TQUI6H.js.map → update-ELXABLVS.js.map} +0 -0
  74. /package/dist/{validate-WIB246IE.js.map → validate-FXD5WS4C.js.map} +0 -0
@@ -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 */\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 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/**\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 // 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 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 {\n parseEndpoints,\n parseTypeDefinitions,\n parseTestCases,\n hasEndpointsSection,\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 } 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 // 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 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 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 }\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,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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":["HTTP_METHODS","existsSync","join","HTTP_METHODS","existsSync","join","HTTP_METHODS","existsSync","join","existsSync","join","join","existsSync","join","existsSync","join","readFile","join"]}
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  buildRelationResolver
3
- } from "./chunk-Z77VQUZ3.js";
3
+ } from "./chunk-MM325DR6.js";
4
4
  import {
5
5
  REQUIRED_SECTIONS
6
- } from "./chunk-SJCIM4TC.js";
6
+ } from "./chunk-ZIPGRLYE.js";
7
7
 
8
8
  // ../lint/dist/engine.js
9
9
  function createLintEngine(options) {
@@ -30,7 +30,144 @@ function createLintEngine(options) {
30
30
  };
31
31
  }
32
32
 
33
+ // ../lint/dist/rules/story-coverage.js
34
+ var STOPWORDS = /* @__PURE__ */ new Set([
35
+ "a",
36
+ "an",
37
+ "the",
38
+ "and",
39
+ "or",
40
+ "of",
41
+ "to",
42
+ "for",
43
+ "with",
44
+ "its",
45
+ "it",
46
+ "in",
47
+ "on",
48
+ "at",
49
+ "by",
50
+ "from",
51
+ "into",
52
+ "every",
53
+ "each",
54
+ "that",
55
+ "this",
56
+ "be",
57
+ "is",
58
+ "are",
59
+ "as",
60
+ "can",
61
+ "will",
62
+ "must",
63
+ "so",
64
+ "their",
65
+ "them",
66
+ "when",
67
+ "which",
68
+ "who"
69
+ ]);
70
+ var OVERLAP_THRESHOLD = 0.5;
71
+ var REFERENCED_THRESHOLD = 0.34;
72
+ function tokenise(text) {
73
+ const words = text.toLowerCase().replace(/[^a-z0-9\s-]/g, " ").split(/\s+/).filter((w) => w.length > 2 && !STOPWORDS.has(w)).map((w) => w.length > 3 && w.endsWith("s") && !w.endsWith("ss") ? w.slice(0, -1) : w);
74
+ return new Set(words);
75
+ }
76
+ function extractFeatureSection(content) {
77
+ const lines = content.split("\n");
78
+ const start = lines.findIndex((l) => /^##\s+Features\s*$/.test(l.trim()));
79
+ if (start === -1)
80
+ return null;
81
+ const body = [];
82
+ for (let i = start + 1; i < lines.length; i++) {
83
+ if (/^##\s/.test(lines[i]))
84
+ break;
85
+ body.push(lines[i]);
86
+ }
87
+ return body.join("\n");
88
+ }
89
+ function parseFeatures(content) {
90
+ return parseFeatureEntries(content).map((f) => f.text);
91
+ }
92
+ function parseFeatureEntries(content) {
93
+ const section = extractFeatureSection(content);
94
+ if (section === null)
95
+ return [];
96
+ const ID_PREFIX = /^\*{0,2}F(\d+)\*{0,2}\s*[:.-]\s*/i;
97
+ const features = [];
98
+ for (const rawLine of section.split("\n")) {
99
+ const line = rawLine.trim();
100
+ if (!line)
101
+ continue;
102
+ const bullet = /^[-*]\s+(.*)$/.exec(line);
103
+ const text = bullet ? (bullet[1] ?? "").trim() : ID_PREFIX.test(line) ? line : "";
104
+ if (!text)
105
+ continue;
106
+ const idMatch = ID_PREFIX.exec(text);
107
+ const stripped = text.replace(ID_PREFIX, "").trim();
108
+ if (stripped)
109
+ features.push({ text: stripped, num: idMatch?.[1] });
110
+ }
111
+ return features;
112
+ }
113
+ function overlap(featureTokens, storyTokens) {
114
+ if (featureTokens.size === 0)
115
+ return 0;
116
+ let shared = 0;
117
+ for (const token of featureTokens)
118
+ if (storyTokens.has(token))
119
+ shared++;
120
+ return shared / featureTokens.size;
121
+ }
122
+ function referencesSpec(story, specId) {
123
+ const refs = story.frontmatter.references;
124
+ if (!Array.isArray(refs))
125
+ return false;
126
+ return refs.some((r) => r?.id === specId);
127
+ }
128
+ function uncoveredFeatures(features, stories, prdId) {
129
+ const scored = stories.map((story) => ({
130
+ tokens: tokenise(`${String(story.frontmatter.title ?? "")} ${story.content}`),
131
+ threshold: referencesSpec(story, prdId) ? REFERENCED_THRESHOLD : OVERLAP_THRESHOLD
132
+ }));
133
+ return features.filter((feature) => {
134
+ const featureTokens = tokenise(feature);
135
+ return !scored.some((s) => overlap(featureTokens, s.tokens) >= s.threshold);
136
+ });
137
+ }
138
+ var storyCoverageRule = {
139
+ id: "completeness/story-coverage",
140
+ description: "Every feature listed in a PRD has at least one corresponding user story",
141
+ severity: "warn",
142
+ run(context) {
143
+ if (context.spec.frontmatter.type !== "prd")
144
+ return [];
145
+ const features = parseFeatures(context.spec.content);
146
+ if (features.length === 0)
147
+ return [];
148
+ const stories = context.allSpecs.filter((s) => s.frontmatter.type === "user-story");
149
+ return uncoveredFeatures(features, stories, context.spec.frontmatter.id).map((feature) => ({
150
+ ruleId: "completeness/story-coverage",
151
+ severity: "warn",
152
+ message: `Feature "${feature}" has no corresponding user story`,
153
+ filePath: context.spec.filePath
154
+ }));
155
+ }
156
+ };
157
+
33
158
  // ../lint/dist/rules/valid-frontmatter.js
159
+ function readablePath(instancePath) {
160
+ return instancePath.split("/").filter(Boolean).map((segment) => /^\d+$/.test(segment) ? `[${segment}]` : `.${segment}`).join("").replace(/^\./, "");
161
+ }
162
+ function describeValidationError(err) {
163
+ const path = readablePath(err.instancePath ?? "");
164
+ const allowed = err.params?.allowedValues;
165
+ let detail = err.message ?? JSON.stringify(err);
166
+ if (Array.isArray(allowed) && allowed.length > 0) {
167
+ detail += `: ${allowed.map((v) => JSON.stringify(v)).join(", ")}`;
168
+ }
169
+ return path ? `${path} ${detail}` : detail;
170
+ }
34
171
  var validFrontmatterRule = {
35
172
  id: "structure/valid-frontmatter",
36
173
  description: "Frontmatter matches the schema for the declared spec type",
@@ -42,7 +179,7 @@ var validFrontmatterRule = {
42
179
  return errors.map((err) => ({
43
180
  ruleId: "structure/valid-frontmatter",
44
181
  severity: "error",
45
- message: `Invalid frontmatter: ${err.message ?? JSON.stringify(err)}`,
182
+ message: `Invalid frontmatter: ${describeValidationError(err)}`,
46
183
  filePath: context.spec.filePath
47
184
  }));
48
185
  }
@@ -101,34 +238,6 @@ var noCircularDepsRule = {
101
238
  }
102
239
  };
103
240
 
104
- // ../lint/dist/rules/story-coverage.js
105
- var FEATURE_PATTERN = /\*\*F\d+\*\*:\s*(.+)/g;
106
- var storyCoverageRule = {
107
- id: "completeness/story-coverage",
108
- description: "Every feature listed in a PRD has at least one corresponding user story",
109
- severity: "warn",
110
- run(context) {
111
- if (context.spec.frontmatter.type !== "prd")
112
- return [];
113
- const features = [];
114
- let match;
115
- const re = new RegExp(FEATURE_PATTERN.source, "g");
116
- while ((match = re.exec(context.spec.content)) !== null) {
117
- features.push(match[1].trim());
118
- }
119
- if (features.length === 0)
120
- return [];
121
- const stories = context.allSpecs.filter((s) => s.frontmatter.type === "user-story");
122
- const storyContent = stories.map((s) => s.content + " " + s.frontmatter.title).join(" ");
123
- return features.filter((feature) => !storyContent.toLowerCase().includes(feature.toLowerCase())).map((feature) => ({
124
- ruleId: "completeness/story-coverage",
125
- severity: "warn",
126
- message: `Feature "${feature}" has no corresponding user story`,
127
- filePath: context.spec.filePath
128
- }));
129
- }
130
- };
131
-
132
241
  // ../lint/dist/rules/staleness-check.js
133
242
  function groupByEntry(config, specs) {
134
243
  const byEntry = /* @__PURE__ */ new Map();
@@ -322,8 +431,6 @@ var EDGE_CASE_KEYWORDS = [
322
431
  "reject",
323
432
  "unauthorized",
324
433
  "forbidden",
325
- "404",
326
- "500",
327
434
  "missing",
328
435
  "malformed",
329
436
  "overflow",
@@ -333,8 +440,18 @@ var EDGE_CASE_KEYWORDS = [
333
440
  "fallback",
334
441
  "crash",
335
442
  "nonexistent",
336
- "corrupt"
443
+ "corrupt",
444
+ // Vocabulary that names a failure without using any of the words above.
445
+ "conflict",
446
+ "denied",
447
+ "expired",
448
+ "not found",
449
+ "retry",
450
+ "rate limit",
451
+ "unavailable",
452
+ "unprocessable"
337
453
  ];
454
+ var ERROR_STATUS_CODE = /\b[45]\d{2}\b/;
338
455
  var edgeCaseCoverageRule = {
339
456
  id: "completeness/edge-case-coverage",
340
457
  description: "Flag user stories or test plans that don't mention error states or edge cases",
@@ -344,7 +461,7 @@ var edgeCaseCoverageRule = {
344
461
  if (type !== "user-story" && type !== "test-plan")
345
462
  return [];
346
463
  const content = context.spec.content.toLowerCase();
347
- const hasEdgeCases = EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw));
464
+ const hasEdgeCases = EDGE_CASE_KEYWORDS.some((kw) => content.includes(kw)) || ERROR_STATUS_CODE.test(content);
348
465
  if (hasEdgeCases)
349
466
  return [];
350
467
  return [
@@ -415,7 +532,7 @@ var namingConventionsRule = {
415
532
  };
416
533
 
417
534
  // ../lint/dist/rules/threat-coverage.js
418
- var STOPWORDS = /* @__PURE__ */ new Set(["the", "and", "for", "with", "from", "that", "this", "into", "via"]);
535
+ var STOPWORDS2 = /* @__PURE__ */ new Set(["the", "and", "for", "with", "from", "that", "this", "into", "via"]);
419
536
  function extractThreats(content) {
420
537
  const parts = content.split(/^(?=## )/m);
421
538
  const threats = [];
@@ -428,7 +545,7 @@ function extractThreats(content) {
428
545
  return threats;
429
546
  }
430
547
  function extractKeyTerms(text) {
431
- return text.toLowerCase().split(/\W+/).filter((w) => w.length > 3).filter((w) => !STOPWORDS.has(w));
548
+ return text.toLowerCase().split(/\W+/).filter((w) => w.length > 3).filter((w) => !STOPWORDS2.has(w));
432
549
  }
433
550
  var threatCoverageRule = {
434
551
  id: "security/threat-coverage",
@@ -505,13 +622,48 @@ var noPlaceholderSectionsRule = {
505
622
  }
506
623
  };
507
624
 
625
+ // ../lint/dist/rules/id-matches-config-key.js
626
+ import { basename } from "path";
627
+ var idMatchesConfigKeyRule = {
628
+ id: "structure/id-matches-config-key",
629
+ description: "A spec's frontmatter id should match the key it is registered under in the config",
630
+ severity: "warn",
631
+ run(context) {
632
+ const { spec, config } = context;
633
+ if (!config)
634
+ return [];
635
+ const id = spec.frontmatter.id;
636
+ if (typeof id !== "string" || id.length === 0)
637
+ return [];
638
+ const specFile = basename(spec.filePath);
639
+ const candidates = Object.entries(config.specs).filter(([, entry]) => {
640
+ const target = basename(entry.path);
641
+ return !target.includes("*") && target === specFile;
642
+ });
643
+ if (candidates.length !== 1)
644
+ return [];
645
+ const key = candidates[0][0];
646
+ if (key === id)
647
+ return [];
648
+ return [
649
+ {
650
+ ruleId: "structure/id-matches-config-key",
651
+ severity: "warn",
652
+ message: `Spec declares id "${id}" but is registered in spec.config.yaml as "${key}". Frontmatter references resolve against "${id}" and config requires against "${key}", so the dependency graph shows them as two things. Rename one so they agree.`,
653
+ filePath: spec.filePath
654
+ }
655
+ ];
656
+ }
657
+ };
658
+
508
659
  // ../lint/dist/rules/index.js
509
660
  var structureRules = [
510
661
  validFrontmatterRule,
511
662
  requiredSectionsRule,
512
663
  validReferencesRule,
513
664
  noCircularDepsRule,
514
- singleProjectContextRule
665
+ singleProjectContextRule,
666
+ idMatchesConfigKeyRule
515
667
  ];
516
668
  var contentRules = [
517
669
  storyCoverageRule,
@@ -545,6 +697,9 @@ import { pathToFileURL } from "url";
545
697
 
546
698
  export {
547
699
  createLintEngine,
700
+ parseFeatures,
701
+ parseFeatureEntries,
702
+ uncoveredFeatures,
548
703
  getPreset
549
704
  };
550
- //# sourceMappingURL=chunk-V7JOVK6D.js.map
705
+ //# sourceMappingURL=chunk-BD6UDHYW.js.map