specdx 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +70 -22
- package/dist/{check-RH5SCXWW.js → check-5EA2MTNN.js} +120 -26
- package/dist/check-5EA2MTNN.js.map +1 -0
- package/dist/{chunk-3YXRWQGX.js → chunk-2UUQJ2ER.js} +242 -53
- package/dist/chunk-2UUQJ2ER.js.map +1 -0
- package/dist/{chunk-6WFNZH7F.js → chunk-5XOWCPP2.js} +2 -2
- package/dist/{chunk-CQETLJTZ.js → chunk-6S2OQMUH.js} +8 -4
- package/dist/chunk-6S2OQMUH.js.map +1 -0
- package/dist/{chunk-BP3SB35W.js → chunk-JGD3BOPH.js} +15 -5
- package/dist/chunk-JGD3BOPH.js.map +1 -0
- package/dist/{chunk-BMOOLUPG.js → chunk-MOYYF7Q6.js} +2 -2
- package/dist/{chunk-ZIODMXST.js → chunk-VVZUJ6H4.js} +52 -14
- package/dist/{chunk-ZIODMXST.js.map → chunk-VVZUJ6H4.js.map} +1 -1
- package/dist/{chunk-6EQIDZ4D.js → chunk-WSLIO2ZD.js} +13 -13
- package/dist/{diff-QO7HMAK3.js → diff-ZT6HXHK5.js} +3 -3
- package/dist/dist-6WDWUOCV.js +26 -0
- package/dist/{dist-JPWHWMV2.js → dist-A3CWALDC.js} +30 -9
- package/dist/dist-A3CWALDC.js.map +1 -0
- package/dist/{generate-MS4BM7RU.js → generate-PTDHGDR2.js} +4 -4
- package/dist/{generate-story-OMM322L7.js → generate-story-BXGNKWC6.js} +3 -3
- package/dist/{generate-test-plan-75W7SZIO.js → generate-test-plan-PZUNCNN3.js} +2 -2
- package/dist/{graph-QOTMXENE.js → graph-GKXD2IGW.js} +2 -2
- package/dist/index.d.ts +11 -0
- package/dist/index.js +109 -22
- package/dist/index.js.map +1 -1
- package/dist/{lint-LPFLHVO4.js → lint-GZX5C5EQ.js} +55 -10
- package/dist/lint-GZX5C5EQ.js.map +1 -0
- package/dist/main.js +2 -2
- package/dist/{mcp-OEC43SPF.js → mcp-PIVG3LEF.js} +3 -3
- package/dist/{migrate-CBP2AVLH.js → migrate-VASWPA3L.js} +2 -2
- package/dist/{pack-X6FSWORJ.js → pack-DFUCNWVR.js} +3 -3
- package/dist/{ready-7MJWRGLT.js → ready-5OFSV2OD.js} +4 -4
- package/dist/{status-UUPZYX3J.js → status-5MDODW4N.js} +4 -4
- package/dist/{update-EI7IJRHG.js → update-NFXC45UT.js} +3 -3
- package/dist/{validate-HTTZLQWI.js → validate-LWRLZR3H.js} +2 -2
- package/package.json +10 -6
- package/skills/core/specdx-author-spec/SKILL.md +33 -0
- package/skills/core/specdx-author-spec/references/spec-type-reference.md +57 -0
- package/skills/core/specdx-author-spec/references/step-01-frontmatter.md +66 -0
- package/skills/core/specdx-author-spec/references/step-02-sections.md +111 -0
- package/skills/core/specdx-author-spec/references/step-03-finalize.md +48 -0
- package/skills/core/specdx-onboard/SKILL.md +54 -0
- package/skills/core/specdx-plan-from-spec/SKILL.md +76 -0
- package/skills/core/specdx-pre-commit/SKILL.md +70 -0
- package/skills/core/specdx-review-spec/SKILL.md +81 -0
- package/skills/core/specdx-router/SKILL.md +67 -0
- package/skills/core/specdx-sprint-review/SKILL.md +73 -0
- package/skills/core/specdx-start-task/SKILL.md +62 -0
- package/skills/experimental/specdx-check-drift/SKILL.md +77 -0
- package/skills/experimental/specdx-verify/SKILL.md +85 -0
- package/dist/check-RH5SCXWW.js.map +0 -1
- package/dist/chunk-3YXRWQGX.js.map +0 -1
- package/dist/chunk-BP3SB35W.js.map +0 -1
- package/dist/chunk-CQETLJTZ.js.map +0 -1
- package/dist/dist-JPWHWMV2.js.map +0 -1
- package/dist/dist-ROHCFKYT.js +0 -16
- package/dist/lint-LPFLHVO4.js.map +0 -1
- /package/dist/{chunk-6WFNZH7F.js.map → chunk-5XOWCPP2.js.map} +0 -0
- /package/dist/{chunk-BMOOLUPG.js.map → chunk-MOYYF7Q6.js.map} +0 -0
- /package/dist/{chunk-6EQIDZ4D.js.map → chunk-WSLIO2ZD.js.map} +0 -0
- /package/dist/{diff-QO7HMAK3.js.map → diff-ZT6HXHK5.js.map} +0 -0
- /package/dist/{dist-ROHCFKYT.js.map → dist-6WDWUOCV.js.map} +0 -0
- /package/dist/{generate-MS4BM7RU.js.map → generate-PTDHGDR2.js.map} +0 -0
- /package/dist/{generate-story-OMM322L7.js.map → generate-story-BXGNKWC6.js.map} +0 -0
- /package/dist/{generate-test-plan-75W7SZIO.js.map → generate-test-plan-PZUNCNN3.js.map} +0 -0
- /package/dist/{graph-QOTMXENE.js.map → graph-GKXD2IGW.js.map} +0 -0
- /package/dist/{mcp-OEC43SPF.js.map → mcp-PIVG3LEF.js.map} +0 -0
- /package/dist/{migrate-CBP2AVLH.js.map → migrate-VASWPA3L.js.map} +0 -0
- /package/dist/{pack-X6FSWORJ.js.map → pack-DFUCNWVR.js.map} +0 -0
- /package/dist/{ready-7MJWRGLT.js.map → ready-5OFSV2OD.js.map} +0 -0
- /package/dist/{status-UUPZYX3J.js.map → status-5MDODW4N.js.map} +0 -0
- /package/dist/{update-EI7IJRHG.js.map → update-NFXC45UT.js.map} +0 -0
- /package/dist/{validate-HTTZLQWI.js.map → validate-LWRLZR3H.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../check/src/check.ts","../../check/src/spec-parsers.ts","../../check/src/extractors/express.ts","../../check/src/extractors/hono.ts","../../check/src/extractors/nextjs.ts","../../check/src/extractors/typescript.ts","../../check/src/extractors/zod.ts","../../check/src/extractors/prisma.ts","../../check/src/extractors/test-extractor.ts","../../check/src/matchers/routes.ts","../../check/src/status.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/baseline.ts","../../check/src/ai.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { CheckResult, CheckConfig, ExtractedRoute, Finding } from \"./types.js\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport {\n parseEndpoints,\n parseTypeDefinitions,\n parseTestCases,\n hasEndpointsSection,\n unreadableTypeBlocks,\n unattachedFieldLines,\n} from \"./spec-parsers.js\";\nimport { extractExpressRoutes } from \"./extractors/express.js\";\nimport { extractHonoRoutes } from \"./extractors/hono.js\";\nimport { extractNextjsRoutes } from \"./extractors/nextjs.js\";\nimport { extractTypeScriptTypes } from \"./extractors/typescript.js\";\nimport { extractZodSchemas } from \"./extractors/zod.js\";\nimport { extractPrismaModels, findPrismaSchemas } from \"./extractors/prisma.js\";\nimport { extractTestDescriptions } from \"./extractors/test-extractor.js\";\nimport { matchRoutes } from \"./matchers/routes.js\";\nimport { matchTypes } from \"./matchers/types.js\";\nimport { matchTests } from \"./matchers/tests.js\";\nimport { checkArtifacts } from \"./artifacts.js\";\nimport { computeScore } from \"./score.js\";\nimport { detectFramework } from \"./detect-framework.js\";\n\n/** True when the project declares a Prisma dependency, so a schema is expected. */\nasync function usesPrisma(projectDir: string): Promise<boolean> {\n try {\n const pkg = JSON.parse(await readFile(join(projectDir, \"package.json\"), \"utf-8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n return \"prisma\" in deps || \"@prisma/client\" in deps;\n } catch {\n return false;\n }\n}\n\n/**\n * Run implementation checks across all specs and return findings, score, and summary.\n *\n * - `api-contract` specs → route extraction + matching\n * - `technical-design` specs → type extraction + matching\n * - `test-plan` specs → test extraction + matching\n */\nexport async function runCheck(\n specs: ParsedSpec[],\n projectDir: string,\n config: CheckConfig = {},\n): Promise<CheckResult> {\n const findings: Finding[] = [];\n const notes: string[] = [];\n // Surfaces the author declared that could not be read. Distinct from `notes`,\n // which also carries purely advisory lines: an unreadable surface silently\n // leaves the score's denominator, which *raises* the percentage, so a caller\n // gating a build has to be able to tell the two apart.\n const unassessed: string[] = [];\n\n /** Note a declared surface that could not be assessed. */\n const noteUnassessed = (message: string): void => {\n notes.push(message);\n unassessed.push(message);\n };\n let routeTotal = 0;\n let typeTotal = 0;\n let testTotal = 0;\n let typesPending = 0;\n let codeRouteCount: number | null = null;\n let codeTypeCount: number | null = null;\n let codeTestCount: number | null = null;\n\n // ts-morph is an optional peer dependency; without it (e.g. under pnpm dlx,\n // where installing into the ephemeral cache is impossible) route, TS/Zod type\n // and test extraction degrade to skipped-with-a-note instead of throwing\n // (issue #7).\n //\n // All three, not two. Test extraction was left unguarded, so a suite holding a\n // single test-plan spec turned the intended note into an unhandled throw and a\n // stack trace — on exactly the ephemeral-runner path this note describes, and\n // on MCP's `sdx_check`, where the bare exception became the tool's only output.\n const tsMorphAvailable = await import(\"ts-morph\").then(\n () => true,\n () => false,\n );\n if (!tsMorphAvailable) {\n noteUnassessed(\n \"route, type and test extraction skipped: ts-morph is not installed. \" +\n \"Install specdx and ts-morph as devDependencies (pnpm add -D specdx ts-morph) — \" +\n \"an ephemeral runner like pnpm dlx cannot provide it.\",\n );\n }\n\n // Resolve the framework once so reporting can say what was scanned\n const framework =\n config.framework && config.framework !== \"auto\"\n ? config.framework\n : await detectFramework(projectDir);\n\n // 1. Route checking: find api-contract specs\n const apiContractSpecs = specs.filter((s) => s.frontmatter.type === \"api-contract\");\n if (apiContractSpecs.length > 0 && tsMorphAvailable) {\n const codeRoutes = await extractRoutes(projectDir, config, framework);\n codeRouteCount = codeRoutes.length;\n\n // No framework recognised *and* the fallback read nothing: we cannot tell an\n // unimplemented contract from a stack we cannot parse (NestJS, tRPC, Fastify\n // wrappers, anything not JS). Matching anyway reported every endpoint\n // missing at severity error — a maximally red first run for most of the\n // market, on a project that might be complete. Skip, like ts-morph does.\n const unreadableStack = framework === null && codeRoutes.length === 0;\n\n if (unreadableStack) {\n noteUnassessed(\n \"no supported framework detected (express, hono, nextjs) and no routes were readable, \" +\n \"so routes were not assessed. Set check.framework in spec.config.yaml, or pass --framework, \" +\n \"if this project does use one of them.\",\n );\n }\n\n for (const spec of unreadableStack ? [] : 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 noteUnassessed(\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 // Only when the fallback actually read something; the unreadable case is\n // already noted above, and saying both would contradict itself.\n if (framework === null && !unreadableStack) {\n notes.push(\n \"no supported framework detected (express, hono, nextjs) — route extraction ran in fallback mode across all extractors.\",\n );\n }\n }\n\n // 2. Type checking: find technical-design specs with Data Model sections.\n // Prisma extraction reads the schema as text, so types stay assessable\n // without ts-morph when a schema exists — but with neither, matching every\n // spec type against an empty extraction would report the whole model\n // unimplemented when it was simply never looked at. Skip, like tests do;\n // the ts-morph note above already says so.\n const designSpecs = specs.filter((s) => s.frontmatter.type === \"technical-design\");\n const prismaSchemaFound = (await findPrismaSchemas(projectDir)).length > 0;\n if (designSpecs.length > 0 && (tsMorphAvailable || prismaSchemaFound)) {\n const codeTypes = [\n ...(tsMorphAvailable ? await extractTypeScriptTypes(projectDir, config.types_dir) : []),\n ...(tsMorphAvailable ? await extractZodSchemas(projectDir, config.types_dir) : []),\n ...(await extractPrismaModels(projectDir)),\n ];\n codeTypeCount = codeTypes.length;\n\n // A project that depends on Prisma but whose schema we could not find is\n // worth saying out loud. Silence here read as \"these models are not\n // implemented\", which is the opposite of what happened.\n if ((await usesPrisma(projectDir)) && !prismaSchemaFound) {\n noteUnassessed(\n \"a prisma dependency is declared but no schema was found at prisma/schema.prisma, \" +\n \"schema.prisma or prisma/schema/*.prisma — Prisma models were not assessed.\",\n );\n }\n\n for (const spec of designSpecs) {\n const specId = spec.frontmatter.id as string;\n const specTypes = parseTypeDefinitions(spec.content);\n const fieldCount = specTypes.reduce((sum, t) => sum + t.fields.length, 0);\n const typeFindings = matchTypes(specTypes, codeTypes, specId, {\n status: spec.frontmatter.status,\n });\n findings.push(...typeFindings);\n\n // A type planned by a spec that is not yet approved leaves the score the\n // way a planned artifact does — fields and all, or a draft design would\n // drag coverage down for describing work before doing it (issue #52).\n const pendingTypes = typeFindings.filter((f) => f.type === \"pending\");\n typeTotal += fieldCount - pendingTypes.reduce((sum, f) => sum + (f.weight ?? 1), 0);\n typesPending += pendingTypes.length;\n\n // Field lines that no `### TypeName` heading claims are declarations the\n // author expects to be checked, and they are not being. A Data Model\n // written as prose declares nothing and draws no note: warning about it\n // every run, unclearable short of rewriting valid prose, taught people to\n // ignore the warnings that matter (issue #38).\n const unattached = unattachedFieldLines(spec.content);\n if (unattached.length > 0) {\n noteUnassessed(\n `${specId}: ${unattached.length} field line(s) in its Data Model sit under no \\`### TypeName\\` heading, ` +\n `so they were not assessed — the first is \\`${unattached[0]!}\\`.`,\n );\n }\n\n // The per-spec note is per spec, so one readable type used to silence\n // every unreadable one beside it — a table-shaped type left the\n // denominator with nothing said, and the percentage did not move.\n for (const name of unreadableTypeBlocks(spec.content)) {\n noteUnassessed(\n `${specId}: no fields recognised under \\`### ${name}\\`, so that type was not assessed. ` +\n \"A table needs a field column and a type column, or write fields as `- name: type`.\",\n );\n }\n }\n\n if (typesPending > 0) {\n notes.push(\n `${typesPending} declared type(s) pending: types planned by specs that are not yet approved. ` +\n \"They are excluded from the score and become enforceable when the spec status changes to approved.\",\n );\n }\n }\n\n // 3. Test checking: find test-plan specs\n const testPlanSpecs = specs.filter((s) => s.frontmatter.type === \"test-plan\");\n if (testPlanSpecs.length > 0 && tsMorphAvailable) {\n const codeTests = await extractTestDescriptions(projectDir, config.tests_dir);\n codeTestCount = codeTests.length;\n\n for (const spec of testPlanSpecs) {\n const specCases = parseTestCases(spec.content);\n testTotal += specCases.length;\n findings.push(...matchTests(specCases, codeTests, spec.frontmatter.id as string));\n }\n }\n\n // 4. Declared artifacts: framework-agnostic checkable surfaces (issue #15)\n const artifactResult = await checkArtifacts(specs, projectDir, tsMorphAvailable);\n findings.push(...artifactResult.findings);\n notes.push(...artifactResult.notes);\n\n // 5. Score\n const score = computeScore(findings, {\n routes: routeTotal,\n types: typeTotal,\n tests: testTotal,\n artifacts: artifactResult.total,\n });\n\n // 6. Summary — never present \"nothing was checkable\" as coverage (issue #6)\n const errors = findings.filter((f) => f.severity === \"error\").length;\n const warnings = findings.filter((f) => f.severity === \"warn\").length;\n const summary = score.assessed\n ? `${score.overall}% implementation coverage — ${errors} errors, ${warnings} warnings`\n : \"coverage not assessed — no checkable surfaces found (no spec'd routes, types, test cases, or declared artifacts)\";\n\n const scanned = {\n framework: framework ?? null,\n codeRoutes: codeRouteCount,\n codeTypes: codeTypeCount,\n codeTests: codeTestCount,\n artifacts: artifactResult.total > 0 ? artifactResult.checked : null,\n artifactsPending: artifactResult.pending,\n typesPending,\n };\n\n return { findings, score, summary, scanned, notes, unassessed };\n}\n\n/**\n * Extract routes from the project based on framework config.\n *\n * In \"auto\" mode, reads package.json to detect the framework first.\n * If a framework is detected, only that extractor is used.\n * If no framework is detected, falls back to trying all extractors and merging results.\n */\nasync function extractRoutes(\n projectDir: string,\n config: CheckConfig,\n framework: string | null,\n): Promise<ExtractedRoute[]> {\n if (framework === \"express\") {\n return extractExpressRoutes(projectDir, config.routes_dir);\n }\n if (framework === \"hono\") {\n return extractHonoRoutes(projectDir, config.routes_dir);\n }\n if (framework === \"nextjs\") {\n return extractNextjsRoutes(projectDir, config.app_dir);\n }\n\n // fallback: try all extractors and merge results\n const [express, hono, nextjs] = await Promise.all([\n extractExpressRoutes(projectDir, config.routes_dir),\n extractHonoRoutes(projectDir, config.routes_dir),\n extractNextjsRoutes(projectDir, config.app_dir),\n ]);\n\n return [...express, ...hono, ...nextjs];\n}\n","import type { HttpMethod, SpecEndpoint, SpecTypeDefinition, SpecTestCase } from \"./types.js\";\n\n/**\n * Extracts the content of a `## Heading` section from a markdown string.\n * Returns the text between that heading and the next `## ` heading (or end of string).\n */\nfunction extractSection(content: string, heading: string): string | null {\n // Match the heading line (case-insensitive, trimmed)\n const headingPattern = new RegExp(`^##\\\\s+${escapeRegex(heading)}\\\\s*$`, \"im\");\n const match = headingPattern.exec(content);\n if (!match) return null;\n\n const start = match.index + match[0].length;\n const rest = content.slice(start);\n\n // Find the next `## ` heading\n const nextSection = /^##\\s+/m.exec(rest);\n return nextSection ? rest.slice(0, nextSection.index) : rest;\n}\n\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nconst HTTP_METHODS: ReadonlySet<string> = new Set([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/**\n * Parses the `## Endpoints` section of a spec and returns structured endpoint data.\n */\n/** Path params are the `:name` segments of a route path. */\nfunction pathParams(path: string): string[] {\n return (path.match(/:([A-Za-z_][A-Za-z0-9_]*)/g) ?? []).map((p) => p.slice(1));\n}\n\n/**\n * True when `content` has an `## Endpoints` heading at all, regardless of what\n * it holds. Lets a caller tell \"no such section\" from \"a section we could not\n * read\" -- the second is worth a note, the first is not.\n */\nexport function hasEndpointsSection(content: string): boolean {\n return extractSection(content, \"Endpoints\") !== null;\n}\n\n/**\n * Parses the `## Endpoints` section of a spec and returns structured endpoint data.\n *\n * Two shapes are accepted, because both are what people write:\n *\n * ### GET /invoices (a sub-heading per endpoint, description beneath)\n * - `GET /invoices` — list (one bullet per endpoint, backticked or not)\n *\n * Accepting only the heading form meant an ordinary bulleted contract parsed to\n * zero endpoints. `check` then reported every real route as unspecified, missed\n * every genuinely absent one, and raised the coverage score because routes left\n * the denominator entirely.\n */\nexport function parseEndpoints(content: string): SpecEndpoint[] {\n const section = extractSection(content, \"Endpoints\");\n if (!section) return [];\n\n const results: SpecEndpoint[] = [];\n const seen = new Set<string>();\n\n const push = (rawMethod: string, path: string, description?: string): void => {\n const method = rawMethod.toUpperCase();\n if (!HTTP_METHODS.has(method)) return;\n // A contract listing an endpoint under a heading *and* in a summary bullet\n // describes one endpoint, not two.\n const key = `${method} ${path}`;\n if (seen.has(key)) return;\n seen.add(key);\n results.push({\n method: method as HttpMethod,\n path,\n params: pathParams(path),\n description: description && description.length > 0 ? description : undefined,\n });\n };\n\n // Shape 1: `### METHOD /path` sub-headings.\n const headingPattern = /^###\\s+(GET|POST|PUT|PATCH|DELETE)\\s+(\\S+)/im;\n for (const block of section.split(/^(?=###\\s)/m)) {\n const headingMatch = headingPattern.exec(block);\n if (!headingMatch) continue;\n\n // Description: first non-empty line after the heading line\n const afterHeading = block.slice(headingMatch.index + headingMatch[0].length);\n const descriptionLine = afterHeading\n .split(\"\\n\")\n .map((l) => l.trim())\n .find((l) => l.length > 0 && !l.startsWith(\"#\") && !l.startsWith(\"-\"));\n\n push(headingMatch[1]!, headingMatch[2]!, descriptionLine);\n }\n\n // Shape 2: one bullet per endpoint. The method and path may be wrapped in\n // backticks together (`GET /invoices`), separately (`GET` `/invoices`), or\n // not at all, and may carry bold emphasis. Anything after the path -- an\n // em-dash, a colon, a hyphen -- is the description.\n const bulletPattern = new RegExp(\n \"^\\\\s*[-*+]\\\\s+\" + // bullet marker\n \"[`*_]*\\\\s*\" + // opening backtick/emphasis\n \"(GET|POST|PUT|PATCH|DELETE)\" + // method\n \"[`*_]*\\\\s+[`*_]*\" + // separator, possibly re-opening a code span\n \"(/[^\\\\s`*_]*)\" + // path -- must start at the root, stops at a code span or emphasis\n \"[`*_]*\" + // closing backtick/emphasis\n \"\\\\s*(?:[—–:-]\\\\s*(.*))?$\", // optional description\n \"gim\",\n );\n let bulletMatch: RegExpExecArray | null;\n while ((bulletMatch = bulletPattern.exec(section)) !== null) {\n push(bulletMatch[1]!, bulletMatch[2]!, bulletMatch[3]?.trim());\n }\n\n return results;\n}\n\n/**\n * A bracketed group or quoted literal collapses to this single token, so a type\n * carrying one is still one atom. It is a character no spec contains, so it can\n * never be confused with something the author wrote.\n */\nconst GROUP = \"\\u00A7\";\n\n/**\n * A type annotation, as opposed to a sentence: identifiers, quoted literals and\n * numbers, joined by `|`, `&` or `=>`, each optionally carrying collapsed groups\n * (`Record<...>`, `Post[]`, `{ ... }`, `() => void`).\n *\n * The shape this replaced allowed only bare identifiers and their `.<>[]`\n * suffixes, so `\"light\" | \"dark\"` and `Record<string, number>` — ordinary\n * TypeScript — were read as prose and dropped (issue #51).\n */\nconst TYPE_ATOM = `(?:[A-Za-z_$][\\\\w$.]*|-?\\\\d+(?:\\\\.\\\\d+)?|${GROUP})${GROUP}*`;\nconst TYPE_SHAPE = new RegExp(`^${TYPE_ATOM}(?:\\\\s*(?:[|&]|=>)\\\\s*${TYPE_ATOM})*$`);\n\n/** Quoted literals and bracketed groups, innermost first, each reduced to one token. */\nfunction collapseGroups(type: string): string {\n let collapsed = type.replace(/\"[^\"]*\"|'[^']*'|`[^`]*`/g, GROUP);\n let previous = \"\";\n while (collapsed !== previous) {\n previous = collapsed;\n collapsed = collapsed.replace(/<[^<>]*>|\\{[^{}]*\\}|\\([^()]*\\)|\\[[^[\\]]*\\]/g, GROUP);\n }\n return collapsed;\n}\n\n/** True when a string reads as a type annotation rather than as prose. */\nfunction looksLikeType(type: string): boolean {\n return type.length > 0 && TYPE_SHAPE.test(collapseGroups(type));\n}\n\n/**\n * Index of the first ` — `, ` – ` or ` - ` separating a type from a description,\n * ignoring any inside brackets or quotes; -1 when there is none.\n *\n * `parseEndpoints` has always accepted those three after a path, so a spec that\n * described its endpoints and its fields in the same house style had one read\n * and the other silently dropped (issue #51).\n */\nfunction descriptionStart(raw: string): number {\n let depth = 0;\n let quote: string | null = null;\n\n for (let i = 0; i < raw.length; i++) {\n const ch = raw[i]!;\n if (quote !== null) {\n if (ch === quote) quote = null;\n continue;\n }\n if (ch === '\"' || ch === \"'\" || ch === \"`\") {\n quote = ch;\n continue;\n }\n if (ch === \"(\" || ch === \"[\" || ch === \"{\" || ch === \"<\") {\n depth += 1;\n continue;\n }\n if (ch === \")\" || ch === \"]\" || ch === \"}\" || ch === \">\") {\n depth = Math.max(0, depth - 1);\n continue;\n }\n if (depth > 0 || !/\\s/.test(ch)) continue;\n if (/^\\s+(?:—|–|-{1,2})\\s+/.test(raw.slice(i))) return i;\n }\n return -1;\n}\n\n/** The type a field declares, with any description or parenthetical note removed. */\nfunction normaliseFieldType(raw: string): string {\n const cut = descriptionStart(raw);\n const type = (cut === -1 ? raw : raw.slice(0, cut)).trim();\n\n // A trailing parenthetical is a note about the field (\"(UUID)\") -- unless\n // removing it leaves nothing, in which case it was the type: `(A | B)`.\n const withoutNote = type.replace(/\\s*\\(.*?\\)\\s*$/, \"\").trim();\n return withoutNote.length > 0 ? withoutNote : type;\n}\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 * A field declaration line, backticked or not -- `- \\`fieldName?\\`: type` or\n * `- fieldName?: type` -- under any of the three markdown bullet markers.\n */\nconst FIELD_LINE = /^[ \\t]*[-*+]\\s+(?:`([^`]+)`|([A-Za-z_$][\\w$]*\\??))\\s*:\\s*(.+)$/;\n\n/**\n * The field a line declares, or null when the line is prose.\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 -- the type has to look like a type\n * -- so \"- Note: this table is partitioned by tenant\" is not read as a field.\n * Backticks are the author saying \"this is a field\", so the type is then taken\n * as written.\n */\nfunction parseFieldLine(line: string): SpecTypeDefinition[\"fields\"][number] | null {\n const match = FIELD_LINE.exec(line);\n if (!match) return null;\n\n const backticked = match[1] !== undefined;\n const rawName = (match[1] ?? match[2])!;\n const optional = rawName.endsWith(\"?\");\n const type = normaliseFieldType(match[3]!);\n\n if (type.length === 0) return null;\n if (!backticked && !looksLikeType(type)) return null;\n\n return { name: optional ? rawName.slice(0, -1) : rawName, type, optional };\n}\n\n/** The `### TypeName` a block declares, or null when its heading is prose. */\nfunction typeHeading(block: string): string | null {\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) return null;\n\n const name = headingMatch[1]!.trim().replace(/^`|`$/g, \"\");\n return TYPE_NAME_SHAPE.test(name) ? name : null;\n}\n\n/** Every field a `### TypeName` block declares as bullets. */\nfunction parseFieldBullets(block: string): SpecTypeDefinition[\"fields\"] {\n const fields: SpecTypeDefinition[\"fields\"] = [];\n for (const line of block.split(\"\\n\")) {\n const field = parseFieldLine(line);\n if (field) fields.push(field);\n }\n return fields;\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 for (const block of section.split(/^(?=###\\s)/m)) {\n const name = typeHeading(block);\n if (name === null) continue;\n\n const fields = parseFieldBullets(block);\n\n // A table is the third way people write a data model, and reading only the\n // bullet forms meant a table-shaped type contributed nothing to the score\n // and drew no note -- the note fires per spec, so one readable type hid\n // every unreadable one beside it.\n if (fields.length === 0) fields.push(...parseFieldTable(block));\n\n // A heading with no fields beneath it asserts only that a name exists, and\n // in practice it is prose -- `### Indexes`, `### Migration notes`. Matching\n // it against code turns an explanatory sub-section into a check error, so a\n // block earns its place as a type only by declaring at least one field.\n if (fields.length === 0) continue;\n\n results.push({ name, fields });\n }\n\n return results;\n}\n\n/** A markdown table row split into trimmed cells, or null when the line is not one. */\nfunction tableCells(line: string): string[] | null {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"|\")) return null;\n return trimmed\n .replace(/^\\|/, \"\")\n .replace(/\\|$/, \"\")\n .split(\"|\")\n .map((cell) => cell.trim().replace(/^`|`$/g, \"\"));\n}\n\n/** True for the `|---|---|` rule under a table's header row. */\nfunction isTableRule(cells: string[]): boolean {\n return cells.every((cell) => /^:?-{2,}:?$/.test(cell));\n}\n\n/**\n * Fields from a markdown table inside a `### TypeName` block.\n *\n * Needs a header naming both a field column and a type column; anything else is\n * a table about something other than the shape of the type, and is left alone.\n */\nfunction parseFieldTable(block: string): SpecTypeDefinition[\"fields\"] {\n const rows = block.split(\"\\n\").map(tableCells);\n const headerIndex = rows.findIndex((r) => r !== null);\n if (headerIndex === -1) return [];\n\n const header = rows[headerIndex]!;\n const nameColumn = header.findIndex((h) => /^(field|name|property|attribute|key)s?$/i.test(h));\n const typeColumn = header.findIndex((h) => /^types?$/i.test(h));\n if (nameColumn === -1 || typeColumn === -1) return [];\n\n const fields: SpecTypeDefinition[\"fields\"] = [];\n for (const cells of rows.slice(headerIndex + 1)) {\n if (cells === null) continue;\n if (isTableRule(cells)) continue;\n\n const rawName = cells[nameColumn];\n const rawType = cells[typeColumn];\n if (!rawName || !rawType) continue;\n\n const optional = rawName.endsWith(\"?\");\n const name = optional ? rawName.slice(0, -1) : rawName;\n if (!/^[A-Za-z_$][\\w$]*$/.test(name)) continue;\n\n fields.push({ name, type: normaliseFieldType(rawType), optional });\n }\n return fields;\n}\n\n/**\n * Type-shaped `### Heading`s in a Data Model that declared a table we could not\n * read as fields.\n *\n * Prose blocks are deliberately absent: a heading with no field declarations at\n * all is an explanatory sub-section, and re-flagging it would undo the fix that\n * stopped `### Indexes` becoming a phantom type. A table, on the other hand, is\n * an author declaring a shape in a syntax the parser missed — worth saying,\n * because the alternative is dropping it from the score in silence.\n */\nexport function unreadableTypeBlocks(content: string): string[] {\n const section = extractSection(content, \"Data Model\");\n if (!section) return [];\n\n const unreadable: string[] = [];\n for (const block of section.split(/^(?=###\\s)/m)) {\n const name = typeHeading(block);\n if (name === null) continue;\n\n const hasTable = block.split(\"\\n\").some((line) => tableCells(line) !== null);\n if (!hasTable) continue;\n\n const parsed = parseTypeDefinitions(`## Data Model\\n\\n${block}`);\n if (parsed.length === 0) unreadable.push(name);\n }\n return unreadable;\n}\n\n/**\n * Field lines in a Data Model that no type claims, because no `### TypeName`\n * heading stands above them.\n *\n * This is the only unreadable-Data-Model case left worth a word. A Data Model\n * written as prose declares no fields and is not trying to: warning about it\n * once per spec on every run, with no edit short of restructuring valid prose\n * to clear it, taught people to ignore every warning `check` prints (issue\n * #38). A line that does parse as a field but belongs to nothing is different —\n * it is a declaration the author expects to be checked, and it is not being.\n */\nexport function unattachedFieldLines(content: string): string[] {\n const section = extractSection(content, \"Data Model\");\n if (!section) return [];\n\n const unattached: string[] = [];\n for (const block of section.split(/^(?=###\\s)/m)) {\n // Fields under a type heading are read; only orphans are of interest.\n if (typeHeading(block) !== null) continue;\n\n for (const line of block.split(\"\\n\")) {\n if (parseFieldLine(line) !== null) unattached.push(line.trim());\n }\n }\n return unattached;\n}\n\n/**\n * Parses the `## Test Cases` section of a spec and returns structured test case data.\n */\nexport function parseTestCases(content: string): SpecTestCase[] {\n const section = extractSection(content, \"Test Cases\");\n if (!section) return [];\n\n const results: SpecTestCase[] = [];\n let currentSection: string | undefined;\n\n for (const rawLine of section.split(\"\\n\")) {\n const line = rawLine.trim();\n\n // Track `### SubSection` headings\n const subHeading = /^###\\s+(.+)/.exec(line);\n if (subHeading) {\n currentSection = subHeading[1]!.trim();\n continue;\n }\n\n // Bullet points are test cases; each comma-separated item in the text is its own case\n const bulletMatch = /^-\\s+(.+)/.exec(line);\n if (!bulletMatch) continue;\n\n let bulletText = bulletMatch[1]!.trim();\n\n // A test-case ID names the case in the spec; it is not part of the test a\n // user is being asked to write. Leaving it in produced the suggestion\n // `Add a test matching: \"**TC5**: refuses to amend…\"`, markup and all, and\n // put `tc5` into the similarity comparison as if it were a word.\n let caseId: string | undefined;\n const idMatch = /^\\*{0,2}(TC\\d+)\\*{0,2}\\s*[:.-]\\s*/i.exec(bulletText);\n if (idMatch) {\n caseId = idMatch[1]!.toUpperCase();\n bulletText = bulletText.slice(idMatch[0].length).trim();\n if (!bulletText) continue;\n }\n\n // Split on `, ` only when it separates items after a label like \"label: item1, item2\"\n // Pattern: label: item1, item2, item3 → generate one entry per item\n const colonIdx = bulletText.indexOf(\":\");\n if (colonIdx !== -1) {\n const label = bulletText.slice(0, colonIdx).trim();\n const rest = bulletText.slice(colonIdx + 1).trim();\n const items = rest.split(/,\\s*/);\n for (const item of items) {\n const trimmed = item.trim();\n if (trimmed) {\n results.push({\n description: `${label}: ${trimmed}`,\n section: currentSection,\n id: caseId,\n });\n }\n }\n } else {\n results.push({ description: bulletText, section: currentSection, id: caseId });\n }\n }\n\n return results;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedRoute, HttpMethod } from \"../types.js\";\n\nconst HTTP_METHODS = new Set([\"get\", \"post\", \"put\", \"patch\", \"delete\"]);\n\n/**\n * Extract Express routes from TypeScript/JavaScript source files using ts-morph AST parsing.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param routesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractExpressRoutes(\n projectDir: string,\n routesDir?: string,\n): Promise<ExtractedRoute[]> {\n const scanDir = routesDir ? join(projectDir, routesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for route extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts and .js files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.test.js\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/*.spec.js\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const routes: ExtractedRoute[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Build a map of router variable name → mount prefix from app.use() calls.\n // e.g. app.use(\"/api\", router) → { router: \"/api\" }\n const mountPrefixes = new Map<string, string>();\n\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n\n // First pass: collect app.use(\"/prefix\", routerVar) mounts.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName();\n if (methodName !== \"use\") continue;\n\n const args = callExpr.getArguments();\n if (args.length < 2) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n const secondArg = args[1];\n if (!secondArg) continue;\n\n // First arg must be a string literal (the prefix).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const prefix = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Second arg should be an identifier (the router variable).\n if (secondArg.getKind() === SyntaxKind.Identifier) {\n const routerVarName = secondArg.asKindOrThrow(SyntaxKind.Identifier).getText();\n mountPrefixes.set(routerVarName, prefix);\n }\n }\n\n // Second pass: collect router.METHOD(\"/path\", handler) calls.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName().toLowerCase();\n if (!HTTP_METHODS.has(methodName)) continue;\n\n const args = callExpr.getArguments();\n if (args.length < 1) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n\n // First arg must be a string literal (the path).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const routePath = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Determine if the receiver is a known router variable, and look up its mount prefix.\n const receiverExpr = propAccess.getExpression();\n let prefix = \"\";\n if (receiverExpr.getKind() === SyntaxKind.Identifier) {\n const receiverName = receiverExpr.asKindOrThrow(SyntaxKind.Identifier).getText();\n prefix = mountPrefixes.get(receiverName) ?? \"\";\n }\n\n const fullPath = prefix + routePath;\n\n // Extract :param names from path segments.\n const params = (fullPath.match(/:([^/]+)/g) ?? []).map((p) => p.slice(1));\n\n const lineNumber = sourceFile.getLineAndColumnAtPos(callExpr.getStart()).line;\n\n routes.push({\n method: methodName.toUpperCase() as HttpMethod,\n path: fullPath,\n params,\n file: filePath,\n line: lineNumber,\n });\n }\n }\n\n return routes;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedRoute, HttpMethod } from \"../types.js\";\n\nconst HTTP_METHODS = new Set([\"get\", \"post\", \"put\", \"patch\", \"delete\"]);\n\n/**\n * Extract Hono routes from TypeScript/JavaScript source files using ts-morph AST parsing.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param routesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractHonoRoutes(\n projectDir: string,\n routesDir?: string,\n): Promise<ExtractedRoute[]> {\n const scanDir = routesDir ? join(projectDir, routesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for route extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts and .js files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.test.js\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/*.spec.js\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const routes: ExtractedRoute[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Build a map of sub-app variable name → mount prefix from app.route() calls.\n // e.g. app.route(\"/api/users\", users) → { users: \"/api/users\" }\n const mountPrefixes = new Map<string, string>();\n\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n\n // First pass: collect app.route(\"/prefix\", subAppVar) mounts.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName();\n if (methodName !== \"route\") continue;\n\n const args = callExpr.getArguments();\n if (args.length < 2) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n const secondArg = args[1];\n if (!secondArg) continue;\n\n // First arg must be a string literal (the prefix).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const prefix = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Second arg should be an identifier (the sub-app variable).\n if (secondArg.getKind() === SyntaxKind.Identifier) {\n const subAppVarName = secondArg.asKindOrThrow(SyntaxKind.Identifier).getText();\n mountPrefixes.set(subAppVarName, prefix);\n }\n }\n\n // Second pass: collect subApp.METHOD(\"/path\", handler) calls.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName().toLowerCase();\n if (!HTTP_METHODS.has(methodName)) continue;\n\n const args = callExpr.getArguments();\n if (args.length < 1) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n\n // First arg must be a string literal (the path).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const routePath = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Determine if the receiver is a known sub-app variable, and look up its mount prefix.\n const receiverExpr = propAccess.getExpression();\n let prefix = \"\";\n if (receiverExpr.getKind() === SyntaxKind.Identifier) {\n const receiverName = receiverExpr.asKindOrThrow(SyntaxKind.Identifier).getText();\n prefix = mountPrefixes.get(receiverName) ?? \"\";\n }\n\n // Hono sub-app routes with path \"/\" resolve to just the prefix (no trailing slash).\n const normalizedPath = routePath === \"/\" ? prefix : prefix + routePath;\n\n // Extract :param names from path segments.\n const params = (normalizedPath.match(/:([^/]+)/g) ?? []).map((p) => p.slice(1));\n\n const lineNumber = sourceFile.getLineAndColumnAtPos(callExpr.getStart()).line;\n\n routes.push({\n method: methodName.toUpperCase() as HttpMethod,\n path: normalizedPath,\n params,\n file: filePath,\n line: lineNumber,\n });\n }\n }\n\n return routes;\n}\n","import { existsSync } from \"node:fs\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { ExtractedRoute, HttpMethod } from \"../types.js\";\n\nconst HTTP_METHODS = new Set<string>([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/**\n * Convert a Next.js App Router directory segment to a route path segment.\n *\n * - Route groups `(group)` → empty string (omitted from path)\n * - Catch-all `[...slug]` → `:slug*`\n * - Dynamic `[param]` → `:param`\n * - Static `foo` → `foo`\n */\nfunction segmentToPath(segment: string): string {\n // Route group — skip in path\n if (segment.startsWith(\"(\") && segment.endsWith(\")\")) {\n return \"\";\n }\n // Catch-all segment: [...slug]\n const catchAll = segment.match(/^\\[\\.\\.\\.([^\\]]+)\\]$/);\n if (catchAll) {\n return `:${catchAll[1]}*`;\n }\n // Dynamic segment: [param]\n const dynamic = segment.match(/^\\[([^\\]]+)\\]$/);\n if (dynamic) {\n return `:${dynamic[1]}`;\n }\n return segment;\n}\n\n/**\n * Recursively walk a directory, yielding route files with their corresponding\n * URL path prefix.\n */\nasync function walkAppDir(\n dir: string,\n pathPrefix: string,\n results: Array<{ file: string; routePath: string }>,\n): Promise<void> {\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dir, entry);\n let entryStat;\n try {\n entryStat = await stat(fullPath);\n } catch {\n continue;\n }\n\n if (entryStat.isDirectory()) {\n const pathSegment = segmentToPath(entry);\n // Route groups are transparent — continue with the same prefix\n const childPrefix = pathSegment === \"\" ? pathPrefix : `${pathPrefix}/${pathSegment}`;\n await walkAppDir(fullPath, childPrefix, results);\n } else if (entry === \"route.ts\" || entry === \"route.js\") {\n results.push({ file: fullPath, routePath: pathPrefix || \"/\" });\n }\n }\n}\n\n/**\n * Extract routes from a Next.js App Router project by scanning the file system\n * and using ts-morph to detect exported HTTP method functions in route files.\n *\n * @param projectDir - Root directory (or fixtures dir in tests)\n * @param appDir - Sub-directory to scan, relative to projectDir. Defaults to \"app\"\n */\nexport async function extractNextjsRoutes(\n projectDir: string,\n appDir?: string,\n): Promise<ExtractedRoute[]> {\n // `src/app` is as official a layout as `app`, and defaulting to `app` alone\n // meant half of all App Router projects scanned an absent directory and\n // reported no routes — the same shape as reading only the project root for a\n // Prisma schema. An explicit `app_dir` is still honoured exactly as given.\n const candidates = appDir !== undefined ? [appDir] : [\"app\", \"src/app\"];\n const scanDir = candidates.map((dir) => join(projectDir, dir)).find((dir) => existsSync(dir));\n\n if (!scanDir) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for route extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n // Discover all route files and their URL paths\n const routeFiles: Array<{ file: string; routePath: string }> = [];\n await walkAppDir(scanDir, \"\", routeFiles);\n\n if (routeFiles.length === 0) {\n return [];\n }\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add only the discovered route files\n for (const { file } of routeFiles) {\n project.addSourceFileAtPath(file);\n }\n\n const routes: ExtractedRoute[] = [];\n\n for (const { file, routePath } of routeFiles) {\n const sourceFile = project.getSourceFile(file);\n if (!sourceFile) continue;\n\n // Extract params from route path segments (e.g. `:id` → \"id\", `:slug*` → \"slug\")\n const params = (routePath.match(/:[a-zA-Z_][a-zA-Z0-9_]*\\*?/g) ?? []).map((p) =>\n p.replace(/^:/, \"\").replace(/\\*$/, \"\"),\n );\n\n // Find all exported function declarations named after HTTP methods\n const exportedFunctions = sourceFile.getFunctions().filter((fn) => {\n const name = fn.getName();\n return name !== undefined && HTTP_METHODS.has(name) && fn.isExported();\n });\n\n for (const fn of exportedFunctions) {\n const name = fn.getName()!;\n const lineNumber = sourceFile.getLineAndColumnAtPos(fn.getStart()).line;\n\n routes.push({\n method: name as HttpMethod,\n path: routePath || \"/\",\n params,\n file,\n line: lineNumber,\n });\n }\n\n // Also handle variable exported functions: export const GET = async () => { ... }\n const exportedVarDecls = sourceFile\n .getDescendantsOfKind(SyntaxKind.VariableDeclaration)\n .filter((decl) => {\n const name = decl.getName();\n if (!HTTP_METHODS.has(name)) return false;\n // Check if the variable statement is exported\n const varStatement = decl.getVariableStatement();\n return varStatement !== undefined && varStatement.isExported();\n });\n\n for (const decl of exportedVarDecls) {\n const name = decl.getName();\n const lineNumber = sourceFile.getLineAndColumnAtPos(decl.getStart()).line;\n\n routes.push({\n method: name as HttpMethod,\n path: routePath || \"/\",\n params,\n file,\n line: lineNumber,\n });\n }\n }\n\n return routes;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedType } from \"../types.js\";\n\n/**\n * Extract TypeScript interface and type alias definitions from source files using ts-morph AST parsing.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param typesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractTypeScriptTypes(\n projectDir: string,\n typesDir?: string,\n): Promise<ExtractedType[]> {\n const scanDir = typesDir ? join(projectDir, typesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for type extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const types: ExtractedType[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Extract interfaces.\n for (const iface of sourceFile.getInterfaces()) {\n const name = iface.getName();\n const line = sourceFile.getLineAndColumnAtPos(iface.getStart()).line;\n const fields = extractProperties(iface.getProperties());\n types.push({ name, fields, file: filePath, line });\n }\n\n // Extract type aliases that define object types (with properties).\n for (const typeAlias of sourceFile.getTypeAliases()) {\n const typeNode = typeAlias.getTypeNode();\n if (!typeNode) continue;\n\n // Only process object type literals (skip simple aliases like `type X = string`).\n if (typeNode.getKind() !== SyntaxKind.TypeLiteral) continue;\n\n const typeLiteral = typeNode.asKindOrThrow(SyntaxKind.TypeLiteral);\n const properties = typeLiteral.getProperties();\n if (properties.length === 0) continue;\n\n const name = typeAlias.getName();\n const line = sourceFile.getLineAndColumnAtPos(typeAlias.getStart()).line;\n const fields = extractProperties(properties);\n types.push({ name, fields, file: filePath, line });\n }\n }\n\n return types;\n}\n\n/**\n * Convert a list of ts-morph property signatures into the ExtractedType fields format.\n */\nfunction extractProperties(\n properties: import(\"ts-morph\").PropertySignature[],\n): ExtractedType[\"fields\"] {\n return properties.map((prop) => {\n const name = prop.getName();\n const optional = prop.hasQuestionToken();\n\n // Prefer the type as written in source; fall back to the resolved type text.\n let type = prop.getTypeNode()?.getText() ?? prop.getType().getText();\n\n // Strip import() paths that ts-morph sometimes includes, e.g. `import(\"x\").Foo` → `Foo`.\n type = type.replace(/import\\([^)]+\\)\\./g, \"\");\n\n return { name, type, optional };\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedType } from \"../types.js\";\n\n/**\n * Extract Zod object schemas from TypeScript source files using ts-morph AST parsing.\n *\n * Scans for variable declarations of the form:\n * export const FooSchema = z.object({ ... });\n * and converts them to ExtractedType entries, stripping the `Schema` suffix from the name.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param typesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractZodSchemas(\n projectDir: string,\n typesDir?: string,\n): Promise<ExtractedType[]> {\n const scanDir = typesDir ? join(projectDir, typesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\n \"ts-morph is required for Zod schema extraction. Install it: pnpm add -D ts-morph\",\n );\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts and .js files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.test.js\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/*.spec.js\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const types: ExtractedType[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n const varDeclarations = sourceFile.getDescendantsOfKind(SyntaxKind.VariableDeclaration);\n\n for (const varDecl of varDeclarations) {\n const initializer = varDecl.getInitializer();\n if (!initializer) continue;\n if (initializer.getKind() !== SyntaxKind.CallExpression) continue;\n\n // Walk up the call chain looking for a z.object(...) call.\n // The pattern may be z.object({...}).strict() or similar — walk the chain.\n const zObjectCall = findZObjectCall(initializer, SyntaxKind);\n if (!zObjectCall) continue;\n\n // Get the argument to z.object() — must be an ObjectLiteralExpression.\n const args = zObjectCall.asKindOrThrow(SyntaxKind.CallExpression).getArguments();\n if (args.length === 0) continue;\n const firstArg = args[0];\n if (!firstArg) continue;\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) continue;\n\n const objLiteral = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Derive the type name: strip \"Schema\" suffix from the variable name.\n const rawName = varDecl.getName();\n const typeName = rawName.endsWith(\"Schema\") ? rawName.slice(0, -\"Schema\".length) : rawName;\n\n const fields: ExtractedType[\"fields\"] = [];\n\n for (const prop of objLiteral.getProperties()) {\n // Only handle PropertyAssignment (not shorthand, spread, etc.)\n if (prop.getKind() !== SyntaxKind.PropertyAssignment) continue;\n\n const propAssign = prop.asKindOrThrow(SyntaxKind.PropertyAssignment);\n const fieldName = propAssign.getName();\n const fieldInit = propAssign.getInitializer();\n if (!fieldInit) continue;\n\n const { type: fieldType, optional } = inferZodType(fieldInit, SyntaxKind);\n\n fields.push({ name: fieldName, type: fieldType, optional });\n }\n\n const lineNumber = sourceFile.getLineAndColumnAtPos(varDecl.getStart()).line;\n\n types.push({ name: typeName, fields, file: filePath, line: lineNumber });\n }\n }\n\n return types;\n}\n\n/**\n * Walk a call expression chain to find the `z.object(...)` call.\n * Handles chained calls like `z.object({...}).strict()`.\n */\nfunction findZObjectCall(\n node: import(\"ts-morph\").Node,\n SyntaxKind: typeof import(\"ts-morph\").SyntaxKind,\n): import(\"ts-morph\").Node | undefined {\n if (node.getKind() !== SyntaxKind.CallExpression) return undefined;\n\n const callExpr = node.asKindOrThrow(SyntaxKind.CallExpression);\n const expr = callExpr.getExpression();\n\n // Direct: z.object(...)\n if (isZObjectAccess(expr, SyntaxKind)) {\n return node;\n }\n\n // Chained: someCall(...).method(...) — recurse into the callee\n if (expr.getKind() === SyntaxKind.PropertyAccessExpression) {\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const innerExpr = propAccess.getExpression();\n if (innerExpr.getKind() === SyntaxKind.CallExpression) {\n return findZObjectCall(innerExpr, SyntaxKind);\n }\n }\n\n return undefined;\n}\n\n/**\n * Returns true if the given node is a `z.object` property access.\n */\nfunction isZObjectAccess(\n node: import(\"ts-morph\").Node,\n SyntaxKind: typeof import(\"ts-morph\").SyntaxKind,\n): boolean {\n if (node.getKind() !== SyntaxKind.PropertyAccessExpression) return false;\n const propAccess = node.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n if (propAccess.getName() !== \"object\") return false;\n const receiver = propAccess.getExpression();\n return receiver.getKind() === SyntaxKind.Identifier && receiver.getText() === \"z\";\n}\n\n/**\n * Infer the TypeScript type and optional flag from a Zod call chain.\n *\n * Examples:\n * z.string() → { type: \"string\", optional: false }\n * z.date().optional() → { type: \"Date\", optional: true }\n * z.enum([\"a\",\"b\"]) → { type: '\"a\" | \"b\"', optional: false }\n */\nfunction inferZodType(\n node: import(\"ts-morph\").Node,\n SyntaxKind: typeof import(\"ts-morph\").SyntaxKind,\n): { type: string; optional: boolean } {\n // Collect all method names in the chain and find the base z.<type>() call.\n const chainMethods: string[] = [];\n let baseCallNode: import(\"ts-morph\").Node | undefined;\n\n let current: import(\"ts-morph\").Node = node;\n\n // Walk from the outermost call inward, collecting method names.\n while (current.getKind() === SyntaxKind.CallExpression) {\n const callExpr = current.asKindOrThrow(SyntaxKind.CallExpression);\n const expr = callExpr.getExpression();\n\n if (expr.getKind() === SyntaxKind.PropertyAccessExpression) {\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName();\n const receiver = propAccess.getExpression();\n\n if (receiver.getKind() === SyntaxKind.Identifier && receiver.getText() === \"z\") {\n // This is the base z.<type>() call.\n baseCallNode = current;\n chainMethods.push(methodName);\n break;\n } else {\n // Intermediate method in the chain (e.g., .optional(), .email(), etc.)\n chainMethods.push(methodName);\n current = receiver;\n }\n } else {\n break;\n }\n }\n\n const optional = chainMethods.includes(\"optional\");\n\n // The last entry in chainMethods (from our walk) is the base Zod type method name.\n // Because we push inner methods last, the base type is the last element.\n const baseMethodName = chainMethods[chainMethods.length - 1];\n\n let type = \"unknown\";\n\n if (baseMethodName === \"string\") {\n type = \"string\";\n } else if (baseMethodName === \"number\") {\n type = \"number\";\n } else if (baseMethodName === \"boolean\") {\n type = \"boolean\";\n } else if (baseMethodName === \"date\") {\n type = \"Date\";\n } else if (baseMethodName === \"array\") {\n type = \"array\";\n } else if (baseMethodName === \"enum\" && baseCallNode) {\n // z.enum([\"a\", \"b\"]) → \"a\" | \"b\"\n const enumCall = baseCallNode.asKindOrThrow(SyntaxKind.CallExpression);\n const args = enumCall.getArguments();\n if (args.length > 0) {\n const firstArg = args[0];\n if (firstArg && firstArg.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arrayLiteral = firstArg.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const elements = arrayLiteral\n .getElements()\n .filter((el) => el.getKind() === SyntaxKind.StringLiteral)\n .map((el) => el.asKindOrThrow(SyntaxKind.StringLiteral).getText());\n if (elements.length > 0) {\n type = elements.join(\" | \");\n }\n }\n }\n }\n\n return { type, optional };\n}\n","import type { ExtractedType } from \"../types.js\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nconst PRISMA_TYPE_MAP: Record<string, string> = {\n String: \"string\",\n Int: \"number\",\n Float: \"number\",\n Decimal: \"number\",\n BigInt: \"number\",\n Boolean: \"boolean\",\n DateTime: \"Date\",\n Json: \"unknown\",\n Bytes: \"Buffer\",\n};\n\n/**\n * Every place Prisma keeps a schema, in the order Prisma itself prefers.\n *\n * Only the project root was read, and `prisma init` has never written there --\n * it writes `prisma/schema.prisma`. So a real Prisma project's models were\n * invisible, every one of them was reported as unimplemented, and the coverage\n * score dropped to match, with no note saying a schema had been looked for.\n *\n * `prisma/schema/` is the multi-file layout supported since Prisma 5.15.\n */\nexport async function findPrismaSchemas(projectDir: string): Promise<string[]> {\n const found: string[] = [];\n\n for (const relative of [\"prisma/schema.prisma\", \"schema.prisma\"]) {\n const path = join(projectDir, relative);\n try {\n await readFile(path, \"utf-8\");\n found.push(path);\n } catch {\n // not there; try the next layout\n }\n }\n\n const schemaDir = join(projectDir, \"prisma\", \"schema\");\n try {\n for (const entry of await readdir(schemaDir)) {\n if (entry.endsWith(\".prisma\")) found.push(join(schemaDir, entry));\n }\n } catch {\n // no multi-file schema directory\n }\n\n return found;\n}\n\nexport async function extractPrismaModels(projectDir: string): Promise<ExtractedType[]> {\n const schemaPaths = await findPrismaSchemas(projectDir);\n if (schemaPaths.length === 0) return [];\n\n const models: ExtractedType[] = [];\n for (const schemaPath of schemaPaths) {\n models.push(...parseSchema(await readFile(schemaPath, \"utf-8\"), schemaPath));\n }\n return models;\n}\n\nfunction parseSchema(content: string, schemaPath: string): ExtractedType[] {\n const models: ExtractedType[] = [];\n const modelRe = /^model\\s+(\\w+)\\s*\\{([^}]+)\\}/gm;\n let modelMatch;\n\n while ((modelMatch = modelRe.exec(content)) !== null) {\n const name = modelMatch[1]!;\n const body = modelMatch[2]!;\n const fields: ExtractedType[\"fields\"] = [];\n const lineOffset = content.slice(0, modelMatch.index).split(\"\\n\").length;\n\n for (const line of body.split(\"\\n\")) {\n const fieldMatch = /^\\s+(\\w+)\\s+(\\w+)(\\??)/.exec(line);\n if (!fieldMatch) continue;\n\n const fieldName = fieldMatch[1]!;\n const prismaType = fieldMatch[2]!;\n const optional = fieldMatch[3] === \"?\";\n\n // Skip relation fields (type references another model or is array)\n if (line.includes(\"@relation\") || prismaType.endsWith(\"[]\") || line.trim().endsWith(\"[]\"))\n continue;\n // Also skip if the type is not a known Prisma scalar (it's a relation)\n if (!PRISMA_TYPE_MAP[prismaType] && /^[A-Z]/.test(prismaType)) continue;\n\n const tsType = PRISMA_TYPE_MAP[prismaType] ?? prismaType.toLowerCase();\n fields.push({ name: fieldName, type: tsType, optional });\n }\n\n models.push({ name, fields, file: schemaPath, line: lineOffset });\n }\n\n return models;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedTest } from \"../types.js\";\n\n/**\n * Extract test descriptions from test files using ts-morph AST parsing.\n *\n * Scans all `.ts` and `.js` files in the given directory and extracts the first\n * string literal argument from `it()` and `test()` call expressions.\n *\n * @param projectDir - Root directory to scan (or fixtures dir in tests)\n * @param testsDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractTestDescriptions(\n projectDir: string,\n testsDir?: string,\n): Promise<ExtractedTest[]> {\n const scanDir = testsDir ? join(projectDir, testsDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for test extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Scan all .ts and .js files in the directory (caller is responsible for pointing\n // this at a tests directory, so all files are candidates).\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const tests: ExtractedTest[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n\n // We want bare `it(...)` and `test(...)` — identifiers only.\n if (expr.getKind() !== SyntaxKind.Identifier) continue;\n\n const calleeName = expr.asKindOrThrow(SyntaxKind.Identifier).getText();\n if (calleeName !== \"it\" && calleeName !== \"test\") continue;\n\n const args = callExpr.getArguments();\n if (args.length < 1) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n\n // First argument must be a string literal (the test description).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const description = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n const lineNumber = sourceFile.getLineAndColumnAtPos(callExpr.getStart()).line;\n\n tests.push({\n description,\n file: filePath,\n line: lineNumber,\n });\n }\n }\n\n return tests;\n}\n","import type { Finding, SpecEndpoint, ExtractedRoute } from \"../types.js\";\n\nfunction normalisePath(path: string): string {\n return \"/\" + path.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\").replace(/\\/+/g, \"/\");\n}\n\nexport function matchRoutes(\n specEndpoints: SpecEndpoint[],\n codeRoutes: ExtractedRoute[],\n specId: string,\n): Finding[] {\n const findings: Finding[] = [];\n\n const codeSet = new Set(codeRoutes.map((r) => `${r.method} ${normalisePath(r.path)}`));\n const specSet = new Set(specEndpoints.map((e) => `${e.method} ${normalisePath(e.path)}`));\n\n // Missing: in spec but not code\n for (const endpoint of specEndpoints) {\n const key = `${endpoint.method} ${normalisePath(endpoint.path)}`;\n if (!codeSet.has(key)) {\n findings.push({\n type: \"missing\",\n category: \"route\",\n specId,\n specSection: \"Endpoints\",\n expected: key,\n severity: \"error\",\n suggestion: `Implement ${key} in your route handler`,\n });\n }\n }\n\n // Extra: in code but not spec\n for (const route of codeRoutes) {\n const key = `${route.method} ${normalisePath(route.path)}`;\n if (!specSet.has(key)) {\n findings.push({\n type: \"extra\",\n category: \"route\",\n specId,\n codeLocation: { file: route.file, line: route.line },\n expected: \"(not in spec)\",\n actual: key,\n severity: \"info\",\n suggestion: `Route ${key} exists in code but not in spec — add to spec if intentional`,\n });\n }\n }\n\n return findings;\n}\n","/**\n * Spec statuses at which the surfaces a spec declares — its `artifacts` and the\n * types in its Data Model — must already exist in code.\n *\n * A spec is the plan for work that has not happened yet, so what it declares is\n * enforceable only once it is approved. Before then a declared-but-absent file,\n * export or type is the expected state, not a defect (issue #17) — otherwise\n * spec-first authoring would fail the very gate the declarations exist to feed.\n *\n * One rule, one place: artifacts had it and types did not, so the same draft\n * spec deferred its four planned files and hard-failed on its two planned types\n * (issue #52).\n */\nconst ENFORCED_STATUSES = new Set([\"approved\"]);\n\n/** True when what a spec declares must exist for the check to pass. */\nexport function enforcedByStatus(status: unknown): boolean {\n return typeof status === \"string\" && ENFORCED_STATUSES.has(status);\n}\n\n/**\n * The suggestion attached to a declaration that is planned rather than missing.\n * Shared so artifacts and types cannot drift into two wordings for one rule.\n */\nexport function plannedSuggestion(specId: string, status: unknown): string {\n return `planned by ${specId} (status: ${String(status)}) — not yet implemented; enforced once the spec is approved.`;\n}\n","import type { Finding, SpecTypeDefinition, ExtractedType } from \"../types.js\";\nimport { enforcedByStatus, plannedSuggestion } from \"../status.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\n/**\n * A type a spec declares but code does not define is only a defect once the\n * spec is approved. Before then it is planned work, reported the way a planned\n * artifact is (issue #52). The status is optional and defaults to enforcing:\n * a caller that cannot say what the status is gets the strict reading.\n */\nexport interface TypeMatchOptions {\n status?: unknown;\n}\n\nexport function matchTypes(\n specTypes: SpecTypeDefinition[],\n codeTypes: ExtractedType[],\n specId: string,\n options: TypeMatchOptions = {},\n): Finding[] {\n const findings: Finding[] = [];\n const enforced = \"status\" in options ? enforcedByStatus(options.status) : true;\n\n for (const specType of specTypes) {\n const codeType = findMatchingCodeType(specType, codeTypes);\n\n if (!codeType) {\n findings.push({\n type: enforced ? \"missing\" : \"pending\",\n category: \"type\",\n specId,\n specSection: \"Data Models\",\n expected: `Type: ${specType.name}`,\n severity: enforced ? \"error\" : \"info\",\n suggestion: enforced\n ? `Implement type \"${specType.name}\" in code`\n : plannedSuggestion(specId, options.status),\n // The score's types denominator counts fields; an absent type must\n // subtract all of its fields, not 1, or a project that implements\n // nothing of an N-field model scores (N-1)/N. A pending type carries\n // the same weight so its fields can leave the denominator entirely.\n weight: specType.fields.length,\n });\n continue;\n }\n\n // The type exists, so its fields are real assertions whatever the spec's\n // status -- the same rule artifacts apply to a file that exists.\n\n // Build a set of field names present in the code type\n const codeFieldNames = new Set(codeType.fields.map((f) => f.name));\n const specFieldNames = new Set(specType.fields.map((f) => f.name));\n\n // Missing fields: in spec but not in code\n for (const specField of specType.fields) {\n if (!codeFieldNames.has(specField.name)) {\n findings.push({\n type: \"missing\",\n category: \"type\",\n specId,\n specSection: \"Data Models\",\n codeLocation: { file: codeType.file, line: codeType.line },\n expected: `Field ${specType.name}.${specField.name} (${specField.type})`,\n severity: \"warn\",\n suggestion: `Add field \"${specField.name}: ${specField.type}\" to ${codeType.name}`,\n });\n }\n }\n\n // Extra fields: in code but not in spec\n for (const codeField of codeType.fields) {\n if (!specFieldNames.has(codeField.name)) {\n findings.push({\n type: \"extra\",\n category: \"type\",\n specId,\n specSection: \"Data Models\",\n codeLocation: { file: codeType.file, line: codeType.line },\n expected: \"(not in spec)\",\n actual: `Field ${codeType.name}.${codeField.name} (${codeField.type})`,\n severity: \"info\",\n suggestion: `Field \"${codeField.name}\" exists in code but not in spec — add to spec if intentional`,\n });\n }\n }\n }\n\n return findings;\n}\n","import type { Finding, SpecTestCase, ExtractedTest } from \"../types.js\";\n\n/** Jaccard similarity between two strings. Normalises to lowercase words. */\nfunction jaccard(a: string, b: string): number {\n const wordsA = new Set(\n a\n .toLowerCase()\n .replace(/[^\\w\\s]/g, \"\")\n .split(/\\s+/)\n .filter(Boolean),\n );\n const wordsB = new Set(\n b\n .toLowerCase()\n .replace(/[^\\w\\s]/g, \"\")\n .split(/\\s+/)\n .filter(Boolean),\n );\n const intersection = new Set([...wordsA].filter((w) => wordsB.has(w)));\n const union = new Set([...wordsA, ...wordsB]);\n if (union.size === 0) return 0;\n return intersection.size / union.size;\n}\n\nconst JACCARD_THRESHOLD = 0.4;\n\n/**\n * Match spec test cases against extracted code tests using Jaccard similarity.\n *\n * - Spec cases that have a code-test match above the threshold are considered covered.\n * - Unmatched spec cases produce a `missing` / `warn` Finding.\n * - Extra code tests (not matched to any spec case) are not reported.\n */\nexport function matchTests(\n specCases: SpecTestCase[],\n codeTests: ExtractedTest[],\n specId: string,\n): Finding[] {\n const findings: Finding[] = [];\n\n for (const specCase of specCases) {\n let bestScore = 0;\n let bestMatch: ExtractedTest | undefined;\n\n for (const codeTest of codeTests) {\n const score = jaccard(specCase.description, codeTest.description);\n if (score > bestScore) {\n bestScore = score;\n bestMatch = codeTest;\n }\n }\n\n if (bestScore < JACCARD_THRESHOLD || !bestMatch) {\n findings.push({\n type: \"missing\",\n category: \"test\",\n specId,\n specSection: specCase.section,\n // `expected` keeps the case ID so the finding can be traced back to a\n // line in the test plan; the suggestion is the test name to write, and\n // the spec's own label is no part of that.\n expected: specCase.id ? `${specCase.id}: ${specCase.description}` : specCase.description,\n severity: \"warn\",\n suggestion: `Add a test matching: \"${specCase.description}\"`,\n });\n }\n }\n\n return findings;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport type { Finding } from \"./types.js\";\nimport { enforcedByStatus, plannedSuggestion } from \"./status.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 * 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 = enforcedByStatus(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: plannedSuggestion(specId, status),\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: plannedSuggestion(specId, status),\n });\n }\n }\n }\n }\n\n if (skippedExports > 0) {\n notes.push(\n `artifact export checks skipped for ${skippedExports} export(s): ts-morph is not available or the file could not be parsed.`,\n );\n }\n\n if (pending > 0) {\n notes.push(\n `${pending} declared artifact assertion(s) pending: files or exports planned by specs that are not yet approved. They are excluded from the score and become enforceable when the spec status changes to approved.`,\n );\n }\n\n return { findings, total, checked: total, pending, notes };\n}\n","import type { Finding, ImplementationScore } from \"./types.js\";\n\ninterface SpecTotals {\n routes: number;\n types: number;\n tests: number;\n artifacts: number;\n}\n\nexport function computeScore(findings: Finding[], totals: SpecTotals): ImplementationScore {\n // Count missing findings per category (only \"missing\" and \"mismatch\" reduce the score, not \"extra\")\n const missingByCategory: Record<string, number> = { route: 0, type: 0, test: 0, artifact: 0 };\n\n for (const f of findings) {\n if (f.type === \"missing\" || f.type === \"mismatch\") {\n // A finding subtracts its weight in the category's own units (fields\n // for types); unweighted findings subtract 1.\n missingByCategory[f.category] = (missingByCategory[f.category] ?? 0) + (f.weight ?? 1);\n }\n }\n\n const categoryMap: Record<string, { total: number; categoryKey: string }> = {\n routes: { total: totals.routes, categoryKey: \"route\" },\n types: { total: totals.types, categoryKey: \"type\" },\n tests: { total: totals.tests, categoryKey: \"test\" },\n artifacts: { total: totals.artifacts, categoryKey: \"artifact\" },\n };\n\n const byCategory: Record<string, { matched: number; total: number }> = {};\n let totalItems = 0;\n let totalMatched = 0;\n\n for (const [name, { total, categoryKey }] of Object.entries(categoryMap)) {\n const missing = missingByCategory[categoryKey] ?? 0;\n const matched = Math.max(0, total - missing);\n byCategory[name] = { matched, total };\n // Test cases are reported but not scored. They are matched by Jaccard\n // similarity over prose, which measures shared vocabulary rather than\n // shared meaning: \"rejects a request with an expired token\" scores 0.167\n // against `returns 401 when the token has expired` and is called missing,\n // while \"creates an invoice\" scores 0.750 against `creates an invoice\n // draft` and is called covered. A signal that wrong cannot move a number\n // anyone acts on — and it is worst when the spec is written first, which\n // is the workflow specdx advocates.\n if (name === \"tests\") continue;\n totalItems += total;\n totalMatched += matched;\n }\n\n // Nothing checkable is \"not assessed\", never a vacuous 100% pass (issue #6)\n if (totalItems === 0) {\n return { overall: 0, assessed: false, byCategory };\n }\n\n const overall = Math.round((totalMatched / totalItems) * 100);\n return { overall, assessed: true, byCategory };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\ntype DetectedFramework = \"express\" | \"hono\" | \"nextjs\";\n\nconst FRAMEWORK_PACKAGES: [string, DetectedFramework][] = [\n [\"express\", \"express\"],\n [\"hono\", \"hono\"],\n [\"next\", \"nextjs\"],\n];\n\nexport async function detectFramework(projectDir: string): Promise<DetectedFramework | null> {\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n try {\n const content = await readFile(join(projectDir, \"package.json\"), \"utf-8\");\n pkg = JSON.parse(content);\n } catch {\n return null;\n }\n\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n\n for (const [pkgName, framework] of FRAMEWORK_PACKAGES) {\n if (pkgName in allDeps) {\n return framework;\n }\n }\n\n return null;\n}\n","import type { Finding } from \"./types.js\";\n\n/**\n * A finding the baseline accepts, recorded as the fields that identify it.\n *\n * Stored as fields rather than a joined string because a baseline is committed\n * and reviewed: the person approving the diff has to be able to read what is\n * being accepted.\n *\n * `count` is part of the record because a fingerprint is not unique — the same\n * drift can occur several times, and recording only presence would let a second\n * occurrence hide behind the first.\n */\nexport interface BaselineEntry {\n type: Finding[\"type\"];\n category: Finding[\"category\"];\n specId: string;\n expected: string;\n actual?: string;\n count: number;\n}\n\nexport interface Baseline {\n version: 1;\n entries: BaselineEntry[];\n}\n\n/** Field separator for the internal matching key: ASCII Unit Separator. */\nconst SEP = String.fromCharCode(31);\n\n/**\n * Internal identity of a finding, stable across code movement.\n *\n * Line numbers are deliberately absent: a baseline invalidated by an added\n * import is a baseline nobody keeps.\n *\n * `actual` is present because an `extra` finding's `expected` is the literal\n * string \"(not in spec)\" — without `actual`, every extra finding in a spec\n * would share one key and suppress its neighbours.\n *\n * The separator is not a space. Finding fields hold spaces, so a space-joined\n * key lets one finding's `expected` run into another's `actual`, and a\n * collision here suppresses a real finding under a baselined one.\n */\nexport function fingerprint(f: Finding | BaselineEntry): string {\n return [f.type, f.category, f.specId, f.expected, f.actual ?? \"\"].join(SEP);\n}\n\nfunction toEntry(f: Finding, count: number): BaselineEntry {\n return {\n type: f.type,\n category: f.category,\n specId: f.specId,\n expected: f.expected,\n // Omitted rather than written as undefined, so the JSON stays clean.\n ...(f.actual === undefined ? {} : { actual: f.actual }),\n count,\n };\n}\n\n/**\n * Record the current findings as accepted. Entries are sorted so the written\n * file diffs cleanly when only one finding changes.\n */\nexport function createBaseline(findings: Finding[]): Baseline {\n const counts = new Map<string, number>();\n const first = new Map<string, Finding>();\n for (const f of findings) {\n const key = fingerprint(f);\n counts.set(key, (counts.get(key) ?? 0) + 1);\n if (!first.has(key)) first.set(key, f);\n }\n\n const entries = [...counts]\n .map(([key, count]) => toEntry(first.get(key)!, count))\n .sort((a, b) => fingerprint(a).localeCompare(fingerprint(b)));\n\n return { version: 1, entries };\n}\n\n/** The baseline as it is written to disk: stable order, trailing newline. */\nexport function serializeBaseline(baseline: Baseline): string {\n return JSON.stringify(baseline, null, 2) + \"\\n\";\n}\n\n/**\n * Read a baseline, refusing anything it cannot vouch for.\n *\n * A baseline that degrades to \"no entries\" on a malformed file would gate every\n * pre-existing finding at once, and one that degrades to \"suppress everything\"\n * would hide real drift. Neither is recoverable by the reader, so both are\n * refused loudly instead.\n */\nexport function parseBaseline(source: string): Baseline {\n let raw: unknown;\n try {\n raw = JSON.parse(source);\n } catch {\n throw new Error(\"baseline file could not be parsed as JSON\");\n }\n\n if (typeof raw !== \"object\" || raw === null) {\n throw new Error(\"baseline file could not be parsed: expected a JSON object\");\n }\n\n const { version, entries } = raw as { version?: unknown; entries?: unknown };\n\n if (version !== 1) {\n throw new Error(\n `baseline file declares version ${String(version)}, which this version of specdx cannot read`,\n );\n }\n\n if (!Array.isArray(entries)) {\n throw new Error(\"baseline file has no entries array\");\n }\n\n for (const entry of entries) {\n const e = entry as Partial<BaselineEntry>;\n const ok =\n typeof entry === \"object\" &&\n entry !== null &&\n typeof e.type === \"string\" &&\n typeof e.category === \"string\" &&\n typeof e.specId === \"string\" &&\n typeof e.expected === \"string\" &&\n (e.actual === undefined || typeof e.actual === \"string\") &&\n Number.isInteger(e.count);\n if (!ok) {\n throw new Error(\n \"baseline file has entries missing type, category, specId, expected or count\",\n );\n }\n }\n\n return { version: 1, entries: entries as BaselineEntry[] };\n}\n\nexport interface BaselineApplication {\n /** Findings not covered by the baseline — these gate the build. */\n remaining: Finding[];\n /** Findings the baseline accepted. Still scored, never gating. */\n suppressed: Finding[];\n /** Recorded entries that no longer occur, so the baseline can be tightened. */\n obsolete: BaselineEntry[];\n}\n\n/**\n * Split findings into those the baseline already accepted and those it did not.\n *\n * Suppression governs the gate alone. The caller scores every finding, baselined\n * or not: a baseline that moved the coverage number would report an existing\n * project as complete on the day it was adopted.\n */\nexport function applyBaseline(findings: Finding[], baseline: Baseline): BaselineApplication {\n const budget = new Map<string, number>();\n for (const entry of baseline.entries) {\n const key = fingerprint(entry);\n budget.set(key, (budget.get(key) ?? 0) + entry.count);\n }\n\n const remaining: Finding[] = [];\n const suppressed: Finding[] = [];\n for (const f of findings) {\n const key = fingerprint(f);\n const left = budget.get(key) ?? 0;\n if (left > 0) {\n budget.set(key, left - 1);\n suppressed.push(f);\n } else {\n remaining.push(f);\n }\n }\n\n const obsolete = baseline.entries\n .filter((entry) => (budget.get(fingerprint(entry)) ?? 0) > 0)\n .sort((a, b) => fingerprint(a).localeCompare(fingerprint(b)));\n\n return { remaining, suppressed, obsolete };\n}\n","import type { Finding, AiAssessment, AiCheckResult } from \"./types.js\";\n\nexport async function analyzeWithAi(findings: Finding[], context: string): Promise<AiCheckResult> {\n const apiKey = process.env[\"ANTHROPIC_API_KEY\"];\n if (!apiKey) {\n throw new Error(\n \"ANTHROPIC_API_KEY environment variable is required for --ai mode. \" +\n \"Set it or use the specdx-verify skill instead (no API key needed).\",\n );\n }\n\n if (findings.length === 0) {\n return { findings, assessments: [], summary: \"No findings to analyze.\" };\n }\n\n let Anthropic: typeof import(\"@anthropic-ai/sdk\").default;\n try {\n const mod = await import(\"@anthropic-ai/sdk\");\n Anthropic = mod.default;\n } catch {\n throw new Error(\n \"@anthropic-ai/sdk is required for --ai mode. Install it: pnpm add -D @anthropic-ai/sdk\",\n );\n }\n\n const client = new Anthropic({ apiKey });\n\n const findingsSummary = findings\n .map(\n (f, i) =>\n `[${i}] ${f.type} (${f.severity}): ${f.expected}${f.actual ? ` — actual: ${f.actual}` : \"\"}${f.suggestion ? ` — suggestion: ${f.suggestion}` : \"\"}`,\n )\n .join(\"\\n\");\n\n const prompt = `You are reviewing static analysis findings from a spec-to-implementation check.\n\nContext: ${context}\n\nFindings:\n${findingsSummary}\n\nFor each finding (by index), assess:\n1. Is this a real issue or a false positive?\n2. How confident are you? (high/medium/low)\n3. Brief reasoning (1-2 sentences)\n4. Suggested fix if it's a real issue\n\nRespond with a JSON array of objects:\n[{ \"findingIndex\": 0, \"isRealIssue\": true, \"confidence\": \"high\", \"reasoning\": \"...\", \"suggestedFix\": \"...\" }]\n\nOnly output the JSON array, no other text.`;\n\n const response = await client.messages.create({\n model: \"claude-sonnet-4-20250514\",\n max_tokens: 4000,\n messages: [{ role: \"user\", content: prompt }],\n });\n\n const text = response.content[0]?.type === \"text\" ? response.content[0].text : \"\";\n\n let assessments: AiAssessment[];\n try {\n assessments = JSON.parse(text);\n } catch {\n assessments = [];\n }\n\n const realIssues = assessments.filter((a) => a.isRealIssue).length;\n const falsePositives = assessments.filter((a) => !a.isRealIssue).length;\n const summary = `AI analysis: ${realIssues} real issues, ${falsePositives} false positives out of ${findings.length} findings`;\n\n return { findings, assessments, summary };\n}\n"],"mappings":";AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,QAAAC,cAAY;;;ACKrB,SAAS,eAAe,SAAiB,SAAe;AAEtD,QAAM,iBAAiB,IAAI,OAAO,UAAU,YAAY,OAAO,CAAC,SAAS,IAAI;AAC7E,QAAM,QAAQ,eAAe,KAAK,OAAO;AACzC,MAAI,CAAC;AAAO,WAAO;AAEnB,QAAM,QAAQ,MAAM,QAAQ,MAAM,CAAC,EAAE;AACrC,QAAM,OAAO,QAAQ,MAAM,KAAK;AAGhC,QAAM,cAAc,UAAU,KAAK,IAAI;AACvC,SAAO,cAAc,KAAK,MAAM,GAAG,YAAY,KAAK,IAAI;AAC1D;AAEA,SAAS,YAAY,KAAW;AAC9B,SAAO,IAAI,QAAQ,uBAAuB,MAAM;AAClD;AAEA,IAAM,eAAoC,oBAAI,IAAI,CAAC,OAAO,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAM3F,SAAS,WAAW,MAAY;AAC9B,UAAQ,KAAK,MAAM,4BAA4B,KAAK,CAAA,GAAI,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC/E;AAOM,SAAU,oBAAoB,SAAe;AACjD,SAAO,eAAe,SAAS,WAAW,MAAM;AAClD;AAeM,SAAU,eAAe,SAAe;AAC5C,QAAM,UAAU,eAAe,SAAS,WAAW;AACnD,MAAI,CAAC;AAAS,WAAO,CAAA;AAErB,QAAM,UAA0B,CAAA;AAChC,QAAM,OAAO,oBAAI,IAAG;AAEpB,QAAM,OAAO,CAAC,WAAmB,MAAc,gBAA8B;AAC3E,UAAM,SAAS,UAAU,YAAW;AACpC,QAAI,CAAC,aAAa,IAAI,MAAM;AAAG;AAG/B,UAAM,MAAM,GAAG,MAAM,IAAI,IAAI;AAC7B,QAAI,KAAK,IAAI,GAA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I;AAEZ,QAAM,SAAS;;WAEN,OAAO;;;EAGhB,eAAe;;;;;;;;;;;;AAaf,QAAM,WAAW,MAAM,OAAO,SAAS,OAAO;IAC5C,OAAO;IACP,YAAY;IACZ,UAAU,CAAC,EAAE,MAAM,QAAQ,SAAS,OAAM,CAAE;GAC7C;AAED,QAAM,OAAO,SAAS,QAAQ,CAAC,GAAG,SAAS,SAAS,SAAS,QAAQ,CAAC,EAAE,OAAO;AAE/E,MAAI;AACJ,MAAI;AACF,kBAAc,KAAK,MAAM,IAAI;EAC/B,QAAQ;AACN,kBAAc,CAAA;EAChB;AAEA,QAAM,aAAa,YAAY,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE;AAC5D,QAAM,iBAAiB,YAAY,OAAO,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE;AACjE,QAAM,UAAU,gBAAgB,UAAU,iBAAiB,cAAc,2BAA2B,SAAS,MAAM;AAEnH,SAAO,EAAE,UAAU,aAAa,QAAO;AACzC;","names":["readFile","join","HTTP_METHODS","existsSync","join","HTTP_METHODS","existsSync","join","HTTP_METHODS","existsSync","join","existsSync","join","readdir","join","existsSync","join","existsSync","join","join","existsSync","readFile","join","readFile","join"]}
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
buildRelationResolver,
|
|
3
3
|
loadConfig,
|
|
4
4
|
parseSpecFromString
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-JGD3BOPH.js";
|
|
6
6
|
import {
|
|
7
7
|
__commonJS,
|
|
8
8
|
__toESM
|
|
@@ -2843,4 +2843,4 @@ export {
|
|
|
2843
2843
|
DiffError,
|
|
2844
2844
|
diffBetweenRefs
|
|
2845
2845
|
};
|
|
2846
|
-
//# sourceMappingURL=chunk-
|
|
2846
|
+
//# sourceMappingURL=chunk-5XOWCPP2.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// package.json
|
|
2
2
|
var package_default = {
|
|
3
3
|
name: "specdx",
|
|
4
|
-
version: "0.
|
|
5
|
-
description: "
|
|
4
|
+
version: "0.6.1",
|
|
5
|
+
description: "Lint the documents your coding agent reads: CLAUDE.md, AGENTS.md and specs. Deterministic, no LLM calls, no config needed.",
|
|
6
6
|
type: "module",
|
|
7
7
|
license: "MIT",
|
|
8
8
|
author: "Umar Gora (https://github.com/umxr)",
|
|
@@ -16,6 +16,9 @@ var package_default = {
|
|
|
16
16
|
url: "https://github.com/umxr/specdx/issues"
|
|
17
17
|
},
|
|
18
18
|
keywords: [
|
|
19
|
+
"claude-md",
|
|
20
|
+
"agents-md",
|
|
21
|
+
"linter",
|
|
19
22
|
"spec",
|
|
20
23
|
"specification",
|
|
21
24
|
"prd",
|
|
@@ -43,12 +46,13 @@ var package_default = {
|
|
|
43
46
|
},
|
|
44
47
|
files: [
|
|
45
48
|
"dist",
|
|
49
|
+
"skills",
|
|
46
50
|
".claude-plugin",
|
|
47
51
|
"hooks",
|
|
48
52
|
"README.md"
|
|
49
53
|
],
|
|
50
54
|
scripts: {
|
|
51
|
-
build: "tsup",
|
|
55
|
+
build: "node ../../scripts/sync-plugin-skills.mjs && tsup",
|
|
52
56
|
typecheck: "tsc --noEmit",
|
|
53
57
|
test: "vitest run",
|
|
54
58
|
clean: "rm -rf dist *.tsbuildinfo"
|
|
@@ -100,4 +104,4 @@ var package_default = {
|
|
|
100
104
|
export {
|
|
101
105
|
package_default
|
|
102
106
|
};
|
|
103
|
-
//# sourceMappingURL=chunk-
|
|
107
|
+
//# sourceMappingURL=chunk-6S2OQMUH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"specdx\",\n \"version\": \"0.6.1\",\n \"description\": \"Lint the documents your coding agent reads: CLAUDE.md, AGENTS.md and specs. Deterministic, no LLM calls, no config needed.\",\n \"type\": \"module\",\n \"license\": \"MIT\",\n \"author\": \"Umar Gora (https://github.com/umxr)\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/umxr/specdx.git\",\n \"directory\": \"packages/cli\"\n },\n \"homepage\": \"https://github.com/umxr/specdx#readme\",\n \"bugs\": {\n \"url\": \"https://github.com/umxr/specdx/issues\"\n },\n \"keywords\": [\n \"claude-md\",\n \"agents-md\",\n \"linter\",\n \"spec\",\n \"specification\",\n \"prd\",\n \"technical-design\",\n \"api-contract\",\n \"lint\",\n \"validation\",\n \"llm\",\n \"ai\",\n \"context-packing\",\n \"spec-driven-development\",\n \"claude-code\"\n ],\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"bin\": {\n \"specdx\": \"./dist/main.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"skills\",\n \".claude-plugin\",\n \"hooks\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"node ../../scripts/sync-plugin-skills.mjs && tsup\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"clean\": \"rm -rf dist *.tsbuildinfo\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.27.0\",\n \"ajv\": \"^8.18.0\",\n \"ajv-formats\": \"^3.0.1\",\n \"citty\": \"^0.2.1\",\n \"consola\": \"^3.4.0\",\n \"gray-matter\": \"^4.0.3\",\n \"js-tiktoken\": \"^1.0.18\",\n \"remark-parse\": \"^11.0.0\",\n \"tinyglobby\": \"^0.2.12\",\n \"unified\": \"^11.0.0\",\n \"unist-util-visit\": \"^5.0.0\",\n \"yaml\": \"^2.7.0\",\n \"zod\": \"^3.23.0\"\n },\n \"devDependencies\": {\n \"@specdx/check\": \"workspace:*\",\n \"@specdx/core\": \"workspace:*\",\n \"@specdx/diff\": \"workspace:*\",\n \"@specdx/lint\": \"workspace:*\",\n \"@specdx/mcp\": \"workspace:*\",\n \"@specdx/pack\": \"workspace:*\",\n \"@specdx/schema\": \"workspace:*\",\n \"@specdx/skills\": \"workspace:*\",\n \"tsup\": \"^8.5.1\",\n \"typescript\": \"^5.7.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"peerDependencies\": {\n \"ts-morph\": \">=20\",\n \"@anthropic-ai/sdk\": \">=0.30\"\n },\n \"peerDependenciesMeta\": {\n \"ts-morph\": {\n \"optional\": true\n },\n \"@anthropic-ai/sdk\": {\n \"optional\": true\n }\n }\n}\n"],"mappings":";AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,QAAU;AAAA,EACV,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,KAAO;AAAA,IACL,QAAU;AAAA,EACZ;AAAA,EACA,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,IACT,WAAa;AAAA,IACb,MAAQ;AAAA,IACR,OAAS;AAAA,EACX;AAAA,EACA,cAAgB;AAAA,IACd,6BAA6B;AAAA,IAC7B,KAAO;AAAA,IACP,eAAe;AAAA,IACf,OAAS;AAAA,IACT,SAAW;AAAA,IACX,eAAe;AAAA,IACf,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,YAAc;AAAA,IACd,SAAW;AAAA,IACX,oBAAoB;AAAA,IACpB,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,iBAAmB;AAAA,IACjB,iBAAiB;AAAA,IACjB,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,IAChB,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,kBAAkB;AAAA,IAClB,kBAAkB;AAAA,IAClB,MAAQ;AAAA,IACR,YAAc;AAAA,EAChB;AAAA,EACA,eAAiB;AAAA,IACf,QAAU;AAAA,EACZ;AAAA,EACA,kBAAoB;AAAA,IAClB,YAAY;AAAA,IACZ,qBAAqB;AAAA,EACvB;AAAA,EACA,sBAAwB;AAAA,IACtB,YAAY;AAAA,MACV,UAAY;AAAA,IACd;AAAA,IACA,qBAAqB;AAAA,MACnB,UAAY;AAAA,IACd;AAAA,EACF;AACF;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
} from "./chunk-XRWLPU24.js";
|
|
6
6
|
|
|
7
7
|
// ../core/dist/config.js
|
|
8
|
-
import { readFile } from "fs/promises";
|
|
8
|
+
import { readFile, stat } from "fs/promises";
|
|
9
9
|
import { join, dirname } from "path";
|
|
10
10
|
import { parse as parseYaml } from "yaml";
|
|
11
11
|
var ConfigError = class extends Error {
|
|
@@ -44,15 +44,24 @@ async function findConfig(from) {
|
|
|
44
44
|
let dir = from;
|
|
45
45
|
while (true) {
|
|
46
46
|
const candidate = join(dir, CONFIG_FILENAME);
|
|
47
|
+
let stats;
|
|
47
48
|
try {
|
|
48
|
-
await
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
stats = await stat(candidate);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
const code = err.code;
|
|
52
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
53
|
+
throw new ConfigError(`Cannot read config file: ${candidate} (${code}).`);
|
|
54
|
+
}
|
|
51
55
|
const parent = dirname(dir);
|
|
52
56
|
if (parent === dir)
|
|
53
57
|
return void 0;
|
|
54
58
|
dir = parent;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (!stats.isFile()) {
|
|
62
|
+
throw new ConfigError(`Cannot read config file: ${candidate} is not a regular file.`);
|
|
55
63
|
}
|
|
64
|
+
return candidate;
|
|
56
65
|
}
|
|
57
66
|
}
|
|
58
67
|
|
|
@@ -440,6 +449,7 @@ import { resolve, isAbsolute as isAbsolute2 } from "path";
|
|
|
440
449
|
export {
|
|
441
450
|
ConfigError,
|
|
442
451
|
loadConfig,
|
|
452
|
+
findConfig,
|
|
443
453
|
countTokens,
|
|
444
454
|
parseSpec,
|
|
445
455
|
parseSpecFromString,
|
|
@@ -451,4 +461,4 @@ export {
|
|
|
451
461
|
resolveGlob,
|
|
452
462
|
createLogger
|
|
453
463
|
};
|
|
454
|
-
//# sourceMappingURL=chunk-
|
|
464
|
+
//# sourceMappingURL=chunk-JGD3BOPH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../core/src/config.ts","../../core/src/parser.ts","../../core/src/tokens.ts","../../core/src/graph.ts","../../core/src/glob.ts","../../core/src/logger.ts","../../core/src/relations.ts","../../core/src/preset.ts"],"sourcesContent":["import { readFile, stat } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport { validateConfig, type SdxConfig } from \"@specdx/schema\";\n\nexport class ConfigError extends Error {\n constructor(\n message: string,\n public readonly errors?: unknown[],\n ) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\nconst CONFIG_FILENAME = \"spec.config.yaml\";\n\nexport async function loadConfig(filePath?: string, searchFrom?: string): Promise<SdxConfig> {\n const resolvedPath = filePath ?? (await findConfig(searchFrom ?? process.cwd()));\n if (!resolvedPath) {\n throw new ConfigError(`No ${CONFIG_FILENAME} found. Run 'specdx init' to create one.`);\n }\n\n let raw: string;\n try {\n raw = await readFile(resolvedPath, \"utf-8\");\n } catch {\n throw new ConfigError(`Cannot read config file: ${resolvedPath}`);\n }\n\n let data: Record<string, unknown>;\n try {\n data = parseYaml(raw) as Record<string, unknown>;\n } catch (err) {\n throw new ConfigError(`Invalid YAML in ${resolvedPath}: ${(err as Error).message}`);\n }\n\n const result = validateConfig(data);\n if (!result.valid) {\n throw new ConfigError(`Invalid config in ${resolvedPath}`, result.errors ?? undefined);\n }\n\n return data as unknown as SdxConfig;\n}\n\n/**\n * The nearest `spec.config.yaml` at or above `from`, or undefined.\n *\n * Exported so a caller can distinguish \"no spec suite here\" from \"the spec\n * suite is broken\" *before* loading. Both surface as a `ConfigError`, and a\n * caller that degrades gracefully on the first must not degrade on the second:\n * silently treating a YAML typo as \"no config\" would turn a spec lint into a\n * narrower check and report it as a pass.\n *\n * Only `ENOENT`/`ENOTDIR` mean absence. Every other errno — `EACCES` on a\n * root-owned checkout, `ELOOP`, `EMFILE` under a parallel run — means a config\n * may well be sitting there and we cannot tell, so it throws rather than\n * reporting the same `undefined` as an empty directory. A caller degrading on\n * that `undefined` would lint a narrower set and call it a pass, while telling\n * the user \"no spec.config.yaml here\" about a file they can see.\n *\n * A `spec.config.yaml` that is not a regular file is the same story: present,\n * unusable, never absent. A file that stats but cannot be read — mode `000` —\n * takes the other route: the path comes back, and `loadConfig` reports\n * \"Cannot read config file\". Neither ends in a degrade.\n */\nexport async function findConfig(from: string): Promise<string | undefined> {\n let dir = from;\n while (true) {\n const candidate = join(dir, CONFIG_FILENAME);\n let stats;\n try {\n stats = await stat(candidate);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\" && code !== \"ENOTDIR\") {\n throw new ConfigError(`Cannot read config file: ${candidate} (${code}).`);\n }\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n continue;\n }\n if (!stats.isFile()) {\n throw new ConfigError(`Cannot read config file: ${candidate} is not a regular file.`);\n }\n return candidate;\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport { extname } from \"node:path\";\nimport * as grayMatterNs from \"gray-matter\";\nimport { parse as parseYaml } from \"yaml\";\nimport { unified } from \"unified\";\nimport remarkParse from \"remark-parse\";\nimport { visit } from \"unist-util-visit\";\nimport { validateSpec, type ValidationResult } from \"@specdx/schema\";\nimport type { BaseSpec, SpecType } from \"@specdx/schema\";\nimport { countTokens } from \"./tokens.js\";\n\n// gray-matter is CJS — its callable default is exposed via .default in an ESM context\ntype GrayMatterFn = (input: string) => { data: Record<string, unknown>; content: string };\nconst matter = ((grayMatterNs as unknown as { default?: GrayMatterFn }).default ??\n (grayMatterNs as unknown as GrayMatterFn)) as GrayMatterFn;\n\nexport class ParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ParseError\";\n }\n}\n\nexport interface ParsedSection {\n heading: string;\n content: string;\n tokens: number;\n}\n\nexport interface ParsedSpec {\n filePath: string;\n frontmatter: BaseSpec & Record<string, unknown>;\n content: string;\n sections: string[];\n parsedSections: ParsedSection[];\n valid: boolean;\n validationErrors: ValidationResult[\"errors\"];\n}\n\nexport async function parseSpec(filePath: string): Promise<ParsedSpec> {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf-8\");\n } catch {\n throw new ParseError(`Cannot read spec file: ${filePath}`);\n }\n\n return parseSpecFromString(raw, filePath);\n}\n\nexport function parseSpecFromString(content: string, filePath: string): Promise<ParsedSpec> {\n const ext = extname(filePath).toLowerCase();\n if (ext === \".yaml\" || ext === \".yml\") {\n return Promise.resolve(parseYamlSpec(filePath, content));\n }\n return Promise.resolve(parseMarkdownSpec(filePath, content));\n}\n\nfunction parseMarkdownSpec(filePath: string, raw: string): ParsedSpec {\n const { data, content } = matter(raw);\n const parsedSections = extractParsedSections(content);\n const sections = parsedSections.map((s) => s.heading).filter(Boolean);\n const frontmatter = data as BaseSpec & Record<string, unknown>;\n const specType = frontmatter.type as SpecType | undefined;\n\n let valid = false;\n let validationErrors: ValidationResult[\"errors\"] = null;\n if (specType) {\n const result = validateSpec(specType, data);\n valid = result.valid;\n validationErrors = result.errors;\n }\n\n return { filePath, frontmatter, content, sections, parsedSections, valid, validationErrors };\n}\n\nfunction parseYamlSpec(filePath: string, raw: string): ParsedSpec {\n let data: Record<string, unknown>;\n try {\n data = parseYaml(raw) as Record<string, unknown>;\n } catch (err) {\n throw new ParseError(`Invalid YAML in ${filePath}: ${(err as Error).message}`);\n }\n\n const frontmatter = data as BaseSpec & Record<string, unknown>;\n const specType = frontmatter.type as SpecType | undefined;\n\n let valid = false;\n let validationErrors: ValidationResult[\"errors\"] = null;\n if (specType) {\n const result = validateSpec(specType, data);\n valid = result.valid;\n validationErrors = result.errors;\n }\n\n return {\n filePath,\n frontmatter,\n content: \"\",\n sections: [],\n parsedSections: [],\n valid,\n validationErrors,\n };\n}\n\nfunction extractParsedSections(markdown: string): ParsedSection[] {\n const tree = unified().use(remarkParse).parse(markdown);\n\n const h2s: { heading: string; startOffset: number; endOffset: number }[] = [];\n\n visit(tree, \"heading\", (node) => {\n if (node.depth === 2) {\n const text = (node.children as Array<{ type: string; value?: string }>)\n .filter((c) => c.type === \"text\")\n .map((c) => c.value ?? \"\")\n .join(\"\");\n h2s.push({\n heading: text,\n startOffset: node.position!.start.offset as number,\n endOffset: node.position!.end.offset as number,\n });\n }\n });\n\n const sections: ParsedSection[] = [];\n\n // Preamble: content before first H2\n const firstH2 = h2s[0];\n const firstOffset = firstH2 ? firstH2.startOffset : markdown.length;\n const preamble = markdown.slice(0, firstOffset).trim();\n if (preamble) {\n sections.push({ heading: \"\", content: preamble, tokens: countTokens(preamble) });\n }\n\n // Each H2 section: content AFTER the heading line, up to the next H2 (or end)\n for (let i = 0; i < h2s.length; i++) {\n const current = h2s[i]!;\n const next = h2s[i + 1];\n const end = next ? next.startOffset : markdown.length;\n const content = markdown.slice(current.endOffset, end).trim();\n sections.push({\n heading: current.heading,\n content,\n tokens: countTokens(content),\n });\n }\n\n return sections;\n}\n","import { encodingForModel } from \"js-tiktoken\";\n\nlet encoder: ReturnType<typeof encodingForModel> | undefined;\n\nfunction getEncoder() {\n if (!encoder) encoder = encodingForModel(\"gpt-4o\");\n return encoder;\n}\n\nexport function countTokens(text: string): number {\n if (!text) return 0;\n return getEncoder().encode(text).length;\n}\n","import type { SdxConfig } from \"@specdx/schema\";\nimport { DEPENDENCY_RELATIONSHIPS } from \"@specdx/schema\";\n\nexport class GraphError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GraphError\";\n }\n}\n\nexport interface Edge {\n from: string;\n to: string;\n}\n\nexport interface DependencyGraph {\n nodes: string[];\n edges: Edge[];\n topologicalSort(): string[];\n getDownstream(nodeId: string): string[];\n getUpstream(nodeId: string): string[];\n}\n\nexport function buildGraph(config: SdxConfig): DependencyGraph {\n const specNames = Object.keys(config.specs);\n const adjacency = new Map<string, string[]>();\n const reverseAdj = new Map<string, string[]>();\n const edges: Edge[] = [];\n\n for (const name of specNames) {\n adjacency.set(name, []);\n reverseAdj.set(name, []);\n }\n\n for (const [name, entry] of Object.entries(config.specs)) {\n if (!entry.requires) continue;\n for (const dep of entry.requires) {\n if (!adjacency.has(dep)) {\n throw new GraphError(\n `Spec \"${name}\" requires \"${dep}\", which does not exist in the config.`,\n );\n }\n adjacency.get(dep)!.push(name);\n reverseAdj.get(name)!.push(dep);\n edges.push({ from: dep, to: name });\n }\n }\n\n // Kahn's algorithm for cycle detection + topological sort\n const inDegree = new Map<string, number>();\n for (const name of specNames) inDegree.set(name, reverseAdj.get(name)!.length);\n\n const queue: string[] = [];\n for (const [name, degree] of inDegree) {\n if (degree === 0) queue.push(name);\n }\n\n const sorted: string[] = [];\n while (queue.length > 0) {\n const node = queue.shift()!;\n sorted.push(node);\n for (const neighbor of adjacency.get(node)!) {\n const newDegree = inDegree.get(neighbor)! - 1;\n inDegree.set(neighbor, newDegree);\n if (newDegree === 0) queue.push(neighbor);\n }\n }\n\n if (sorted.length !== specNames.length) {\n const remaining = specNames.filter((n) => !sorted.includes(n));\n throw new GraphError(`Circular dependency detected involving: ${remaining.join(\", \")}`);\n }\n\n return {\n nodes: specNames,\n edges,\n topologicalSort: () => [...sorted],\n getDownstream(nodeId: string): string[] {\n const visited = new Set<string>();\n const stack = [nodeId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const neighbor of adjacency.get(current) ?? []) {\n if (!visited.has(neighbor)) {\n visited.add(neighbor);\n stack.push(neighbor);\n }\n }\n }\n return [...visited];\n },\n getUpstream(nodeId: string): string[] {\n const visited = new Set<string>();\n const stack = [nodeId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const dep of reverseAdj.get(current) ?? []) {\n if (!visited.has(dep)) {\n visited.add(dep);\n stack.push(dep);\n }\n }\n }\n return [...visited];\n },\n };\n}\n\n/** A relationship edge declared in a spec's frontmatter `references`. */\nexport interface ReferenceEdge {\n fromId: string;\n toId: string;\n relationship: string;\n}\n\n// The dependency-implying taxonomy lives in @specdx/schema so it is versioned\n// with the schema it describes, rather than hardcoded here (ADR:\n// references/requires unification).\n\n/**\n * Collect relationship edges declared in spec frontmatter `references` fields.\n * Edges point from the declaring spec's id to the referenced spec's id.\n */\nexport function collectReferenceEdges(\n specs: { frontmatter: Record<string, unknown> }[],\n): ReferenceEdge[] {\n const edges: ReferenceEdge[] = [];\n for (const spec of specs) {\n const fromId = spec.frontmatter.id;\n if (typeof fromId !== \"string\") continue;\n const refs = spec.frontmatter.references;\n if (!Array.isArray(refs)) continue;\n for (const ref of refs) {\n if (ref && typeof ref === \"object\" && \"id\" in ref) {\n const r = ref as { id: unknown; relationship?: unknown };\n if (typeof r.id === \"string\") {\n edges.push({\n fromId,\n toId: r.id,\n relationship: typeof r.relationship === \"string\" ? r.relationship : \"related-to\",\n });\n }\n }\n }\n }\n return edges;\n}\n\n/**\n * Find dependency-implying frontmatter references that the config-level\n * `requires` graph does not reflect. `idToEntry` maps spec frontmatter ids to\n * config entry keys. References within the same entry (e.g. story-to-story\n * under one glob) and references to unmapped ids are skipped — reference\n * existence itself is the `structure/valid-references` lint rule's concern.\n */\nexport interface UnreflectedReference {\n edge: ReferenceEdge;\n requiringEntry: string;\n requiredEntry: string;\n /** True when adding the suggested requires edge would create a cycle. */\n createsCycle: boolean;\n}\n\nexport function findUnreflectedReferences(\n referenceEdges: ReferenceEdge[],\n idToEntry: Map<string, string>,\n graph: DependencyGraph,\n): UnreflectedReference[] {\n const configEdges = new Set(graph.edges.map((e) => `${e.from}→${e.to}`));\n const missing: UnreflectedReference[] = [];\n\n for (const edge of referenceEdges) {\n const direction = DEPENDENCY_RELATIONSHIPS[edge.relationship as never];\n if (!direction) continue;\n\n const selfEntry = idToEntry.get(edge.fromId);\n const targetEntry = idToEntry.get(edge.toId);\n if (!selfEntry || !targetEntry || selfEntry === targetEntry) continue;\n\n const requiringEntry = direction === \"self-requires-target\" ? selfEntry : targetEntry;\n const requiredEntry = direction === \"self-requires-target\" ? targetEntry : selfEntry;\n\n // Config edges point dependency → dependent\n if (!configEdges.has(`${requiredEntry}→${requiringEntry}`)) {\n // The suggested edge closes a cycle when the required entry is already\n // downstream of the requiring one (issue #13) — never recommend it.\n const createsCycle = graph.getDownstream(requiringEntry).includes(requiredEntry);\n missing.push({ edge, requiringEntry, requiredEntry, createsCycle });\n }\n }\n\n return missing;\n}\n","import { glob } from \"tinyglobby\";\nimport { join, isAbsolute } from \"node:path\";\n\nexport async function resolveGlob(pattern: string, baseDir: string): Promise<string[]> {\n const absolutePattern = isAbsolute(pattern) ? pattern : join(baseDir, pattern);\n return glob([absolutePattern], { absolute: true });\n}\n","import { createConsola, type ConsolaInstance } from \"consola\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LoggerOptions {\n quiet?: boolean;\n verbose?: boolean;\n}\n\nexport interface Logger extends ConsolaInstance {\n level: number;\n}\n\nexport function createLogger(options?: LoggerOptions): Logger {\n let level = 3; // info\n if (options?.quiet) level = 1; // only errors\n if (options?.verbose) level = 4; // debug\n return createConsola({ level }) as Logger;\n}\n","import type { SdxConfig } from \"@specdx/schema\";\nimport { DEPENDENCY_RELATIONSHIPS } from \"@specdx/schema\";\n\n/** Where a relation edge was declared. */\nexport type RelationSource = \"requires\" | \"references\" | \"both\";\n\n/** A dependency edge in **spec id** space, pointing upstream → downstream. */\nexport interface RelationEdge {\n /** Spec id of the dependency. */\n from: string;\n /** Spec id of the dependent. */\n to: string;\n /** Which declaration(s) produced this edge. */\n source: RelationSource;\n}\n\n/**\n * Answers \"what is upstream / downstream of this spec?\" in spec id space.\n *\n * specdx declares relationships two ways: config `requires` (keyed by config\n * entry, glob-aware, cheap) and frontmatter `references` (keyed by spec id,\n * typed). Consumers used to read one or the other, so the same question got\n * different answers — `freshness/staleness-check` saw only references, while\n * impact analysis saw only the config graph. This resolver unions both at\n * query time so every consumer agrees, without changing which source owns\n * graph topology (ADR: references/requires unification, Option B).\n */\nexport interface RelationResolver {\n /** All dependency edges, in spec id space, deduplicated. */\n edges: RelationEdge[];\n /** Spec ids this spec depends on, transitively. */\n getUpstream(specId: string): string[];\n /** Spec ids that depend on this spec, transitively. */\n getDownstream(specId: string): string[];\n}\n\ninterface SpecLike {\n frontmatter: Record<string, unknown>;\n}\n\n/** Map each config entry key to the spec ids its path resolved to. */\nfunction mapEntriesToIds(\n config: SdxConfig,\n specsByEntry: Map<string, SpecLike[]>,\n): Map<string, string[]> {\n const entryIds = new Map<string, string[]>();\n for (const key of Object.keys(config.specs)) {\n const ids: string[] = [];\n for (const spec of specsByEntry.get(key) ?? []) {\n const id = spec.frontmatter.id;\n if (typeof id === \"string\") ids.push(id);\n }\n entryIds.set(key, ids);\n }\n return entryIds;\n}\n\n/** Every spec id present, regardless of which entry it came from. */\nfunction collectKnownIds(specsByEntry: Map<string, SpecLike[]>): Set<string> {\n const ids = new Set<string>();\n for (const specs of specsByEntry.values()) {\n for (const spec of specs) {\n const id = spec.frontmatter.id;\n if (typeof id === \"string\") ids.add(id);\n }\n }\n return ids;\n}\n\nfunction walk(specId: string, adjacency: Map<string, string[]>): string[] {\n const visited = new Set<string>();\n const stack = [specId];\n while (stack.length > 0) {\n const current = stack.pop()!;\n for (const next of adjacency.get(current) ?? []) {\n if (!visited.has(next)) {\n visited.add(next);\n stack.push(next);\n }\n }\n }\n visited.delete(specId);\n return [...visited];\n}\n\n/**\n * Build a resolver from config `requires` and dependency-implying frontmatter\n * `references`.\n *\n * A glob entry is one config entry but many spec ids, so one `requires` edge\n * between entries expands to the cross-product of their spec ids. Structural\n * reference kinds (`decomposed-into`, `supersedes`, `related-to`) are not\n * dependency-implying and are excluded — see DEPENDENCY_RELATIONSHIPS.\n *\n * @param config - Spec config. When undefined, only frontmatter references\n * contribute edges — useful for callers that have specs but no config.\n * @param specsByEntry - Parsed specs grouped by the config entry key they resolved from.\n */\nexport function buildRelationResolver(\n config: SdxConfig | undefined,\n specsByEntry: Map<string, SpecLike[]>,\n): RelationResolver {\n const entryIds = config ? mapEntriesToIds(config, specsByEntry) : new Map<string, string[]>();\n const knownIds = collectKnownIds(specsByEntry);\n\n // key \"from→to\" -> source, so a relation declared both ways is one edge\n const edgeSources = new Map<string, RelationSource>();\n const addEdge = (from: string, to: string, source: \"requires\" | \"references\"): void => {\n if (from === to) return;\n const key = `${from}\u0000${to}`;\n const existing = edgeSources.get(key);\n if (!existing) {\n edgeSources.set(key, source);\n } else if (existing !== source) {\n edgeSources.set(key, \"both\");\n }\n };\n\n // 1. Config requires: entry-level edges expand across the entries' spec ids\n for (const [key, entry] of Object.entries(config?.specs ?? {})) {\n const requires = (entry as { requires?: string[] }).requires ?? [];\n for (const dep of requires) {\n for (const from of entryIds.get(dep) ?? []) {\n for (const to of entryIds.get(key) ?? []) {\n addEdge(from, to, \"requires\");\n }\n }\n }\n }\n\n // 2. Frontmatter references, already in spec id space\n for (const specs of specsByEntry.values()) {\n for (const spec of specs) {\n const selfId = spec.frontmatter.id;\n if (typeof selfId !== \"string\") continue;\n const refs = spec.frontmatter.references;\n if (!Array.isArray(refs)) continue;\n\n for (const ref of refs) {\n if (!ref || typeof ref !== \"object\") continue;\n const { id: targetId, relationship } = ref as { id?: unknown; relationship?: unknown };\n if (typeof targetId !== \"string\" || typeof relationship !== \"string\") continue;\n // Referencing a spec outside the suite is valid-references' concern.\n if (!knownIds.has(targetId)) continue;\n\n const direction = DEPENDENCY_RELATIONSHIPS[relationship as never];\n if (direction === \"self-requires-target\") {\n addEdge(targetId, selfId, \"references\");\n } else if (direction === \"target-requires-self\") {\n addEdge(selfId, targetId, \"references\");\n }\n }\n }\n }\n\n const edges: RelationEdge[] = [];\n const downstreamAdj = new Map<string, string[]>();\n const upstreamAdj = new Map<string, string[]>();\n\n for (const [key, source] of edgeSources) {\n const [from, to] = key.split(\"\u0000\") as [string, string];\n edges.push({ from, to, source });\n downstreamAdj.set(from, [...(downstreamAdj.get(from) ?? []), to]);\n upstreamAdj.set(to, [...(upstreamAdj.get(to) ?? []), from]);\n }\n\n return {\n edges,\n getUpstream: (specId) => walk(specId, upstreamAdj),\n getDownstream: (specId) => walk(specId, downstreamAdj),\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve, isAbsolute } from \"node:path\";\nimport { ConfigError } from \"./config.js\";\n\nconst BUILTINS = [\"minimal\", \"recommended\", \"strict\"];\n\n/**\n * Resolve a preset name to its config content.\n * Returns null for built-in presets (handled by @specdx/lint).\n * Resolves local file paths and npm package names.\n */\nexport async function resolvePreset(\n name: string,\n cwd = process.cwd(),\n): Promise<Record<string, unknown> | null> {\n if (BUILTINS.includes(name)) {\n return null;\n }\n\n // Try local file path\n const localPath = isAbsolute(name) ? name : resolve(cwd, name);\n try {\n const content = await readFile(localPath, \"utf-8\");\n const { default: yaml } = await import(\"yaml\");\n return yaml.parse(content) as Record<string, unknown>;\n } catch {\n // Not a local file, try npm\n }\n\n // Try npm package\n try {\n const mod = (await import(name)) as { default?: Record<string, unknown> };\n return (mod.default ?? mod) as Record<string, unknown>;\n } catch {\n throw new ConfigError(`Could not resolve preset \"${name}\" as a local file or npm package`);\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,UA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AAY,OAAO,iBAAiB;AAAU;AAEtE,YAAI,CAAC,SAAS,IAAI,QAAQ;AAAG;AAE7B,cAAM,YAAY,yBAAyB,YAAqB;AAChE,YAAI,cAAc,wBAAwB;AACxC,kBAAQ,UAAU,QAAQ,YAAY;QACxC,WAAW,cAAc,wBAAwB;AAC/C,kBAAQ,QAAQ,UAAU,YAAY;QACxC;MACF;IACF;EACF;AAEA,QAAM,QAAwB,CAAA;AAC9B,QAAM,gBAAgB,oBAAI,IAAG;AAC7B,QAAM,cAAc,oBAAI,IAAG;AAE3B,aAAW,CAAC,KAAK,MAAM,KAAK,aAAa;AACvC,UAAM,CAAC,MAAM,EAAE,IAAI,IAAI,MAAM,IAAG;AAChC,UAAM,KAAK,EAAE,MAAM,IAAI,OAAM,CAAE;AAC/B,kBAAc,IAAI,MAAM,CAAC,GAAI,cAAc,IAAI,IAAI,KAAK,CAAA,GAAK,EAAE,CAAC;AAChE,gBAAY,IAAI,IAAI,CAAC,GAAI,YAAY,IAAI,EAAE,KAAK,CAAA,GAAK,IAAI,CAAC;EAC5D;AAEA,SAAO;IACL;IACA,aAAa,CAAC,WAAW,KAAK,QAAQ,WAAW;IACjD,eAAe,CAAC,WAAW,KAAK,QAAQ,aAAa;;AAEzD;;;AC3KA,SAAS,YAAAC,iBAAgB;AACzB,SAAS,SAAS,cAAAC,mBAAkB;","names":["readFile","parseYaml","readFile","parseYaml","join","readFile","isAbsolute"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
countTokens
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-JGD3BOPH.js";
|
|
4
4
|
|
|
5
5
|
// ../pack/dist/resolver.js
|
|
6
6
|
var STOPWORDS = /* @__PURE__ */ new Set([
|
|
@@ -684,4 +684,4 @@ function pack(specs, options, packConfig, graph) {
|
|
|
684
684
|
export {
|
|
685
685
|
pack
|
|
686
686
|
};
|
|
687
|
-
//# sourceMappingURL=chunk-
|
|
687
|
+
//# sourceMappingURL=chunk-MOYYF7Q6.js.map
|