specdx 0.4.0-alpha.20 → 0.4.0-alpha.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +24 -6
- package/dist/{check-GGQB3SHI.js → check-PHXXA7VY.js} +64 -27
- package/dist/check-PHXXA7VY.js.map +1 -0
- package/dist/{chunk-ZB5R5SK5.js → chunk-3YXRWQGX.js} +11 -6
- package/dist/chunk-3YXRWQGX.js.map +1 -0
- package/dist/{chunk-FBMYBYFB.js → chunk-AQZQIURH.js} +18 -15
- package/dist/chunk-AQZQIURH.js.map +1 -0
- package/dist/chunk-DMGABJ6T.js +41 -0
- package/dist/chunk-DMGABJ6T.js.map +1 -0
- package/dist/{chunk-ZIPGRLYE.js → chunk-HCJDCS26.js} +2 -2
- package/dist/chunk-HCJDCS26.js.map +1 -0
- package/dist/{chunk-CI7KYTC7.js → chunk-KVLFW5MI.js} +2 -2
- package/dist/{chunk-CI7KYTC7.js.map → chunk-KVLFW5MI.js.map} +1 -1
- package/dist/{chunk-RY5CDUNN.js → chunk-NAWYG4VV.js} +2 -2
- package/dist/chunk-NAWYG4VV.js.map +1 -0
- package/dist/chunk-NHD44ZYN.js +20 -0
- package/dist/chunk-NHD44ZYN.js.map +1 -0
- package/dist/{chunk-MM325DR6.js → chunk-SNQNQ2MP.js} +3 -3
- package/dist/chunk-SNQNQ2MP.js.map +1 -0
- package/dist/{chunk-UZKOJL2N.js → chunk-UFTEMDPU.js} +31 -9
- package/dist/chunk-UFTEMDPU.js.map +1 -0
- package/dist/{chunk-T232GZ2L.js → chunk-YRQPY5NF.js} +2 -2
- package/dist/{diff-PHEX3HUT.js → diff-6C5LJ7SH.js} +25 -13
- package/dist/diff-6C5LJ7SH.js.map +1 -0
- package/dist/{dist-RT3MTIUW.js → dist-ROHCFKYT.js} +2 -2
- package/dist/{dist-DQ6NNKZO.js → dist-SOZ3I4RP.js} +7 -7
- package/dist/{generate-5VO6M4PB.js → generate-AVXZHH76.js} +5 -5
- package/dist/{generate-story-CJMV2F5K.js → generate-story-3O4T4CEV.js} +4 -4
- package/dist/{generate-test-plan-XBAFJKJI.js → generate-test-plan-Z46W3N3B.js} +3 -3
- package/dist/{graph-UZJMLX4J.js → graph-4RNURBNP.js} +47 -10
- package/dist/graph-4RNURBNP.js.map +1 -0
- package/dist/index.d.ts +111 -7
- package/dist/index.js +234 -54
- package/dist/index.js.map +1 -1
- package/dist/{lint-TVL2ILOQ.js → lint-PKWAK4CO.js} +33 -12
- package/dist/lint-PKWAK4CO.js.map +1 -0
- package/dist/main.js +3 -3
- package/dist/{mcp-F7LJBZ4X.js → mcp-VMHFWM3O.js} +3 -3
- package/dist/{migrate-DEFCNOAH.js → migrate-FKFC7UAO.js} +3 -3
- package/dist/{pack-PNLD5AYW.js → pack-DE4UBTCC.js} +12 -8
- package/dist/pack-DE4UBTCC.js.map +1 -0
- package/dist/{ready-2PHBPWJD.js → ready-IKVESKEB.js} +19 -10
- package/dist/ready-IKVESKEB.js.map +1 -0
- package/dist/skills/core/specdx-sprint-review/SKILL.md +1 -1
- package/dist/{skills-LHFTTEJ7.js → skills-36SRUEMR.js} +1 -1
- package/dist/skills-36SRUEMR.js.map +1 -0
- package/dist/{status-UKLQV4AI.js → status-NWMX2KJZ.js} +40 -27
- package/dist/status-NWMX2KJZ.js.map +1 -0
- package/dist/{update-KLDLDQZM.js → update-UFOHZEAK.js} +20 -11
- package/dist/update-UFOHZEAK.js.map +1 -0
- package/dist/{validate-FXD5WS4C.js → validate-EZHUB5TW.js} +34 -16
- package/dist/validate-EZHUB5TW.js.map +1 -0
- package/package.json +9 -9
- package/dist/check-GGQB3SHI.js.map +0 -1
- package/dist/chunk-FBMYBYFB.js.map +0 -1
- package/dist/chunk-GAM4MXPC.js +0 -15
- package/dist/chunk-GAM4MXPC.js.map +0 -1
- package/dist/chunk-MM325DR6.js.map +0 -1
- package/dist/chunk-RY5CDUNN.js.map +0 -1
- package/dist/chunk-UZKOJL2N.js.map +0 -1
- package/dist/chunk-ZB5R5SK5.js.map +0 -1
- package/dist/chunk-ZIPGRLYE.js.map +0 -1
- package/dist/diff-PHEX3HUT.js.map +0 -1
- package/dist/graph-UZJMLX4J.js.map +0 -1
- package/dist/lint-TVL2ILOQ.js.map +0 -1
- package/dist/pack-PNLD5AYW.js.map +0 -1
- package/dist/ready-2PHBPWJD.js.map +0 -1
- package/dist/skills-LHFTTEJ7.js.map +0 -1
- package/dist/status-UKLQV4AI.js.map +0 -1
- package/dist/update-KLDLDQZM.js.map +0 -1
- package/dist/validate-FXD5WS4C.js.map +0 -1
- /package/dist/{chunk-T232GZ2L.js.map → chunk-YRQPY5NF.js.map} +0 -0
- /package/dist/{dist-RT3MTIUW.js.map → dist-ROHCFKYT.js.map} +0 -0
- /package/dist/{dist-DQ6NNKZO.js.map → dist-SOZ3I4RP.js.map} +0 -0
- /package/dist/{generate-5VO6M4PB.js.map → generate-AVXZHH76.js.map} +0 -0
- /package/dist/{generate-story-CJMV2F5K.js.map → generate-story-3O4T4CEV.js.map} +0 -0
- /package/dist/{generate-test-plan-XBAFJKJI.js.map → generate-test-plan-Z46W3N3B.js.map} +0 -0
- /package/dist/{mcp-F7LJBZ4X.js.map → mcp-VMHFWM3O.js.map} +0 -0
- /package/dist/{migrate-DEFCNOAH.js.map → migrate-FKFC7UAO.js.map} +0 -0
package/README.md
CHANGED
|
@@ -146,13 +146,21 @@ Add spec health checks to your CI pipeline with the GitHub Action:
|
|
|
146
146
|
|
|
147
147
|
```yaml
|
|
148
148
|
# .github/workflows/specs.yml
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
149
|
+
permissions:
|
|
150
|
+
pull-requests: write
|
|
151
|
+
steps:
|
|
152
|
+
- uses: umxr/specdx/packages/github-action@v0.4.0
|
|
153
|
+
with:
|
|
154
|
+
working-directory: .
|
|
155
|
+
preset: recommended
|
|
156
|
+
github-token: ${{ secrets.GITHUB_TOKEN }}
|
|
153
157
|
```
|
|
154
158
|
|
|
155
|
-
The action runs lint + diff on every PR
|
|
159
|
+
The action runs lint + diff on every PR and can block merges on spec health failures. It fails the job when the spec paths resolve to no files — zero specs checked is not a pass.
|
|
160
|
+
|
|
161
|
+
Pass `github-token` and grant the workflow `permissions: pull-requests: write` to have it post a spec health comment, which it updates in place on each push rather than stacking a new one. Without the token it skips commenting and logs why; a missing permission is a warning, never a failed job. Set `badge-path` to write an SVG health badge.
|
|
162
|
+
|
|
163
|
+
Configure severity thresholds in `spec.config.yaml`:
|
|
156
164
|
|
|
157
165
|
```yaml
|
|
158
166
|
ci:
|
|
@@ -450,7 +458,17 @@ ci:
|
|
|
450
458
|
| `specdx skills install` | Install Claude Code skills (`--experimental` also installs the unpromoted ones) |
|
|
451
459
|
| `specdx mcp` | Start the MCP server |
|
|
452
460
|
|
|
453
|
-
Global flags: `--
|
|
461
|
+
Global flags: `--quiet` (suppress success and summary output; problems still print) and `--verbose`.
|
|
462
|
+
|
|
463
|
+
`--format` is per command, because not every command renders every format. Run `specdx <command> --help` for the list it supports — asking for one it does not render is an error, not a silent fallback to pretty output.
|
|
464
|
+
|
|
465
|
+
| Formats | Commands |
|
|
466
|
+
|---|---|
|
|
467
|
+
| `pretty`, `json`, `github` | `lint`, `status`, `check` |
|
|
468
|
+
| `pretty`, `json` | `validate`, `ready`, `update` |
|
|
469
|
+
| `pretty`, `json`, `dot` | `graph` |
|
|
470
|
+
| `pretty`, `json`, `changelog` | `diff` |
|
|
471
|
+
| `xml`, `markdown`, `json` | `pack` |
|
|
454
472
|
|
|
455
473
|
---
|
|
456
474
|
|
|
@@ -1,27 +1,32 @@
|
|
|
1
1
|
import {
|
|
2
2
|
runCheck
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-3YXRWQGX.js";
|
|
4
4
|
import {
|
|
5
|
+
createOutput
|
|
6
|
+
} from "./chunk-NHD44ZYN.js";
|
|
7
|
+
import {
|
|
8
|
+
resolveFormat,
|
|
5
9
|
sharedArgs
|
|
6
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-DMGABJ6T.js";
|
|
7
11
|
import {
|
|
8
12
|
createLogger,
|
|
9
13
|
loadConfig,
|
|
10
14
|
parseSpec,
|
|
11
15
|
resolveGlob
|
|
12
|
-
} from "./chunk-
|
|
13
|
-
import "./chunk-
|
|
16
|
+
} from "./chunk-SNQNQ2MP.js";
|
|
17
|
+
import "./chunk-HCJDCS26.js";
|
|
14
18
|
import "./chunk-5WRI5ZAA.js";
|
|
15
19
|
|
|
16
20
|
// src/commands/experimental/check.ts
|
|
17
21
|
import { defineCommand } from "citty";
|
|
22
|
+
var FORMATS = ["pretty", "json", "github"];
|
|
18
23
|
var check_default = defineCommand({
|
|
19
24
|
meta: {
|
|
20
25
|
name: "check",
|
|
21
26
|
description: "Check spec-to-implementation drift. Exit codes: 0 ok, 1 errors found, 3 nothing checkable (coverage not assessed)"
|
|
22
27
|
},
|
|
23
28
|
args: {
|
|
24
|
-
...sharedArgs,
|
|
29
|
+
...sharedArgs(FORMATS),
|
|
25
30
|
spec: { type: "string", description: "Check a specific spec by ID" },
|
|
26
31
|
framework: { type: "string", description: "Framework override: express, hono, nextjs" },
|
|
27
32
|
ai: {
|
|
@@ -30,7 +35,15 @@ var check_default = defineCommand({
|
|
|
30
35
|
}
|
|
31
36
|
},
|
|
32
37
|
async run({ args }) {
|
|
38
|
+
const format = resolveFormat(args.format, FORMATS);
|
|
39
|
+
if (!format.ok) {
|
|
40
|
+
console.error(`
|
|
41
|
+
\u2717 ${format.message}
|
|
42
|
+
`);
|
|
43
|
+
process.exit(1);
|
|
44
|
+
}
|
|
33
45
|
const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });
|
|
46
|
+
const output = createOutput({ quiet: args.quiet });
|
|
34
47
|
const configDir = process.cwd();
|
|
35
48
|
const config = await loadConfig(void 0, configDir);
|
|
36
49
|
logger.debug("Loading specs...");
|
|
@@ -50,13 +63,21 @@ var check_default = defineCommand({
|
|
|
50
63
|
logger.debug(`Checking ${specs.length} specs...`);
|
|
51
64
|
const result = await runCheck(specs, configDir, checkConfig);
|
|
52
65
|
if (args.ai) {
|
|
53
|
-
const { analyzeWithAi } = await import("./dist-
|
|
54
|
-
|
|
55
|
-
|
|
66
|
+
const { analyzeWithAi } = await import("./dist-ROHCFKYT.js");
|
|
67
|
+
let aiResult;
|
|
68
|
+
try {
|
|
69
|
+
aiResult = await analyzeWithAi(result.findings, args.spec ?? "full suite check");
|
|
70
|
+
} catch (err) {
|
|
71
|
+
console.error(`
|
|
72
|
+
\u2717 ${err.message}
|
|
73
|
+
`);
|
|
74
|
+
process.exit(1);
|
|
75
|
+
}
|
|
76
|
+
if (format.format === "json") {
|
|
56
77
|
console.log(JSON.stringify({ ...result, ai: aiResult }, null, 2));
|
|
57
78
|
} else {
|
|
58
79
|
console.log(`
|
|
59
|
-
|
|
80
|
+
specdx check --ai \u2014 ${result.score.overall}% coverage
|
|
60
81
|
`);
|
|
61
82
|
console.log(` AI Assessment: ${aiResult.summary}
|
|
62
83
|
`);
|
|
@@ -78,48 +99,64 @@ var check_default = defineCommand({
|
|
|
78
99
|
}
|
|
79
100
|
return;
|
|
80
101
|
}
|
|
81
|
-
if (
|
|
102
|
+
if (format.format === "json") {
|
|
82
103
|
console.log(JSON.stringify(result, null, 2));
|
|
104
|
+
} else if (format.format === "github") {
|
|
105
|
+
console.log(
|
|
106
|
+
`::notice::specdx check \u2014 ${result.score.assessed ? `${result.score.overall}% implementation coverage` : "coverage not assessed \u2014 no checkable surfaces found"}`
|
|
107
|
+
);
|
|
108
|
+
for (const note of result.notes) {
|
|
109
|
+
console.log(`::notice::${note}`);
|
|
110
|
+
}
|
|
111
|
+
for (const f of result.findings) {
|
|
112
|
+
const level = f.severity === "error" ? "error" : f.severity === "warn" ? "warning" : "notice";
|
|
113
|
+
const location = f.codeLocation ? ` file=${f.codeLocation.file},line=${f.codeLocation.line}` : "";
|
|
114
|
+
const detail = f.actual ? ` \u2014 ${f.actual}` : "";
|
|
115
|
+
console.log(`::${level}${location}::[${f.specId}] ${f.expected}${detail}`);
|
|
116
|
+
}
|
|
83
117
|
} else {
|
|
84
118
|
const headline = result.score.assessed ? `${result.score.overall}% implementation coverage` : "coverage not assessed \u2014 no checkable surfaces found";
|
|
85
|
-
|
|
86
|
-
|
|
119
|
+
output.info(`
|
|
120
|
+
specdx check \u2014 ${headline}
|
|
87
121
|
`);
|
|
88
122
|
for (const note of result.notes) {
|
|
89
|
-
|
|
123
|
+
output.out(` \u26A0 ${note}`);
|
|
90
124
|
}
|
|
91
|
-
if (result.notes.length > 0)
|
|
125
|
+
if (result.notes.length > 0) output.out();
|
|
92
126
|
if (args.verbose) {
|
|
93
127
|
const fmt = (n) => n === null ? "not scanned" : `${n} found`;
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
const artifacts = result.scanned.artifacts === null ? "none declared" : `${result.scanned.artifacts}
|
|
128
|
+
output.out(` Scanned: framework=${result.scanned.framework ?? "none detected"}`);
|
|
129
|
+
output.out(` routes: ${fmt(result.scanned.codeRoutes)}`);
|
|
130
|
+
output.out(` types: ${fmt(result.scanned.codeTypes)}`);
|
|
131
|
+
output.out(` tests: ${fmt(result.scanned.codeTests)}`);
|
|
132
|
+
const artifacts = result.scanned.artifacts === null ? "none declared" : `${result.scanned.artifacts} assessed`;
|
|
99
133
|
const pending = result.scanned.artifactsPending > 0 ? `, ${result.scanned.artifactsPending} pending` : "";
|
|
100
|
-
|
|
134
|
+
output.out(` artifacts: ${artifacts}${pending}
|
|
101
135
|
`);
|
|
102
136
|
}
|
|
103
137
|
for (const [category, stats] of Object.entries(result.score.byCategory)) {
|
|
104
138
|
if (stats.total === 0) continue;
|
|
105
|
-
console.log(` ${category} (${stats.matched}/${stats.total}):`);
|
|
106
139
|
const categoryFindings = result.findings.filter(
|
|
107
140
|
(f) => f.category === category.replace(/s$/, "")
|
|
108
141
|
);
|
|
142
|
+
const header = ` ${category} (${stats.matched}/${stats.total}):`;
|
|
143
|
+
if (categoryFindings.length === 0) {
|
|
144
|
+
output.info(header);
|
|
145
|
+
output.info(" \u2713 all matched");
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
output.out(header);
|
|
109
149
|
for (const f of categoryFindings) {
|
|
110
150
|
const icon = f.severity === "error" ? "\u2717" : f.severity === "warn" ? "\u26A0" : "\u2139";
|
|
111
151
|
const detail = f.actual ? ` \u2014 ${f.actual}` : "";
|
|
112
152
|
const suggestion = f.suggestion ? ` (${f.suggestion})` : "";
|
|
113
|
-
|
|
114
|
-
}
|
|
115
|
-
if (categoryFindings.length === 0) {
|
|
116
|
-
console.log(" \u2713 all matched");
|
|
153
|
+
output.out(` ${icon} ${f.expected}${detail}${suggestion}`);
|
|
117
154
|
}
|
|
118
155
|
}
|
|
119
156
|
const errors = result.findings.filter((f) => f.severity === "error").length;
|
|
120
157
|
const warnings = result.findings.filter((f) => f.severity === "warn").length;
|
|
121
158
|
const info = result.findings.filter((f) => f.severity === "info").length;
|
|
122
|
-
|
|
159
|
+
output.info(`
|
|
123
160
|
${errors} errors, ${warnings} warnings, ${info} info
|
|
124
161
|
`);
|
|
125
162
|
}
|
|
@@ -134,4 +171,4 @@ var check_default = defineCommand({
|
|
|
134
171
|
export {
|
|
135
172
|
check_default as default
|
|
136
173
|
};
|
|
137
|
-
//# sourceMappingURL=check-
|
|
174
|
+
//# sourceMappingURL=check-PHXXA7VY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/experimental/check.ts"],"sourcesContent":["import { defineCommand } from \"citty\";\nimport { loadConfig, parseSpec, resolveGlob, createLogger } from \"@specdx/core\";\nimport { runCheck } from \"@specdx/check\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport type { CheckConfig } from \"@specdx/check\";\nimport { sharedArgs, resolveFormat } from \"../../shared-args.js\";\nimport { createOutput } from \"../../output.js\";\n\nconst FORMATS = [\"pretty\", \"json\", \"github\"] as const;\n\nexport default defineCommand({\n meta: {\n name: \"check\",\n description:\n \"Check spec-to-implementation drift. Exit codes: 0 ok, 1 errors found, 3 nothing checkable (coverage not assessed)\",\n },\n args: {\n ...sharedArgs(FORMATS),\n spec: { type: \"string\", description: \"Check a specific spec by ID\" },\n framework: { type: \"string\", description: \"Framework override: express, hono, nextjs\" },\n ai: {\n type: \"boolean\",\n description: \"Use AI to assess findings (requires ANTHROPIC_API_KEY)\",\n },\n },\n async run({ args }) {\n const format = resolveFormat(args.format, FORMATS);\n if (!format.ok) {\n console.error(`\\n ✗ ${format.message}\\n`);\n process.exit(1);\n }\n\n const logger = createLogger({ quiet: args.quiet, verbose: args.verbose });\n const output = createOutput({ quiet: args.quiet });\n const configDir = process.cwd();\n const config = await loadConfig(undefined, configDir);\n\n logger.debug(\"Loading specs...\");\n\n // Resolve and parse all specs\n const specs: ParsedSpec[] = [];\n for (const [, entry] of Object.entries(config.specs)) {\n const paths = await resolveGlob(entry.path, configDir);\n for (const p of paths) {\n const spec = await parseSpec(p);\n if (args.spec && spec.frontmatter.id !== args.spec) continue;\n specs.push(spec);\n }\n }\n\n const checkConfig: CheckConfig = {\n ...config.check,\n ...(args.framework ? { framework: args.framework as CheckConfig[\"framework\"] } : {}),\n };\n\n logger.debug(`Checking ${specs.length} specs...`);\n const result = await runCheck(specs, configDir, checkConfig);\n\n // AI analysis (opt-in)\n if (args.ai) {\n const { analyzeWithAi } = await import(\"@specdx/check\");\n // A missing key is a user error, not a crash. It used to surface as an\n // uncaught Error with the full Node trace through citty, where every\n // other user-error path in the CLI prints \"✗ …\" (audit run 5, F7).\n let aiResult;\n try {\n aiResult = await analyzeWithAi(result.findings, args.spec ?? \"full suite check\");\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`);\n process.exit(1);\n }\n\n if (format.format === \"json\") {\n console.log(JSON.stringify({ ...result, ai: aiResult }, null, 2));\n } else {\n console.log(`\\n specdx check --ai — ${result.score.overall}% coverage\\n`);\n console.log(` AI Assessment: ${aiResult.summary}\\n`);\n\n for (const assessment of aiResult.assessments) {\n const finding = result.findings[assessment.findingIndex];\n if (!finding) continue;\n const icon = assessment.isRealIssue ? \"✗\" : \"✓\";\n const label = assessment.isRealIssue ? \"REAL\" : \"FALSE POSITIVE\";\n console.log(` ${icon} [${label}] ${finding.expected}`);\n console.log(` ${assessment.reasoning}`);\n if (assessment.suggestedFix) {\n console.log(` Fix: ${assessment.suggestedFix}`);\n }\n }\n console.log();\n }\n\n if (aiResult.assessments.some((a) => a.isRealIssue)) {\n process.exit(1);\n }\n return;\n }\n\n if (format.format === \"json\") {\n console.log(JSON.stringify(result, null, 2));\n } else if (format.format === \"github\") {\n // Annotations for CI. A finding about missing code has no file to point\n // at, so the spec ID carries the location instead. The headline always\n // prints: a clean or unassessable run must still say something, or the\n // format is silent for exactly the projects that most need telling.\n console.log(\n `::notice::specdx check — ${\n result.score.assessed\n ? `${result.score.overall}% implementation coverage`\n : \"coverage not assessed — no checkable surfaces found\"\n }`,\n );\n for (const note of result.notes) {\n console.log(`::notice::${note}`);\n }\n for (const f of result.findings) {\n const level =\n f.severity === \"error\" ? \"error\" : f.severity === \"warn\" ? \"warning\" : \"notice\";\n const location = f.codeLocation\n ? ` file=${f.codeLocation.file},line=${f.codeLocation.line}`\n : \"\";\n const detail = f.actual ? ` — ${f.actual}` : \"\";\n console.log(`::${level}${location}::[${f.specId}] ${f.expected}${detail}`);\n }\n } else {\n // Pretty format\n const headline = result.score.assessed\n ? `${result.score.overall}% implementation coverage`\n : \"coverage not assessed — no checkable surfaces found\";\n output.info(`\\n specdx check — ${headline}\\n`);\n\n for (const note of result.notes) {\n output.out(` ⚠ ${note}`);\n }\n if (result.notes.length > 0) output.out();\n\n if (args.verbose) {\n const fmt = (n: number | null) => (n === null ? \"not scanned\" : `${n} found`);\n output.out(` Scanned: framework=${result.scanned.framework ?? \"none detected\"}`);\n output.out(` routes: ${fmt(result.scanned.codeRoutes)}`);\n output.out(` types: ${fmt(result.scanned.codeTypes)}`);\n output.out(` tests: ${fmt(result.scanned.codeTests)}`);\n // \"assessed\", not \"verified\": this counts the assertions considered,\n // and a failed one is reported below. Calling six verified while the\n // next line says 5/6 made the output contradict itself (F6).\n const artifacts =\n result.scanned.artifacts === null\n ? \"none declared\"\n : `${result.scanned.artifacts} assessed`;\n const pending =\n result.scanned.artifactsPending > 0 ? `, ${result.scanned.artifactsPending} pending` : \"\";\n output.out(` artifacts: ${artifacts}${pending}\\n`);\n }\n\n for (const [category, stats] of Object.entries(result.score.byCategory)) {\n if (stats.total === 0) continue;\n const categoryFindings = result.findings.filter(\n (f) => f.category === category.replace(/s$/, \"\"),\n );\n const header = ` ${category} (${stats.matched}/${stats.total}):`;\n if (categoryFindings.length === 0) {\n output.info(header);\n output.info(\" ✓ all matched\");\n continue;\n }\n output.out(header);\n for (const f of categoryFindings) {\n const icon = f.severity === \"error\" ? \"✗\" : f.severity === \"warn\" ? \"⚠\" : \"ℹ\";\n const detail = f.actual ? ` — ${f.actual}` : \"\";\n const suggestion = f.suggestion ? ` (${f.suggestion})` : \"\";\n output.out(` ${icon} ${f.expected}${detail}${suggestion}`);\n }\n }\n\n const errors = result.findings.filter((f) => f.severity === \"error\").length;\n const warnings = result.findings.filter((f) => f.severity === \"warn\").length;\n const info = result.findings.filter((f) => f.severity === \"info\").length;\n output.info(`\\n ${errors} errors, ${warnings} warnings, ${info} info\\n`);\n }\n\n if (result.findings.some((f) => f.severity === \"error\")) {\n process.exit(1);\n }\n // Distinct exit code so CI cannot mistake \"nothing was checkable\" for a pass\n if (!result.score.assessed) {\n process.exit(3);\n }\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAQ9B,IAAM,UAAU,CAAC,UAAU,QAAQ,QAAQ;AAE3C,IAAO,gBAAQ,cAAc;AAAA,EAC3B,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,aACE;AAAA,EACJ;AAAA,EACA,MAAM;AAAA,IACJ,G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7 +919,11 @@ function matchTypes(specTypes, codeTypes, specId) {
|
|
|
919
919
|
specSection: "Data Models",
|
|
920
920
|
expected: `Type: ${specType.name}`,
|
|
921
921
|
severity: "error",
|
|
922
|
-
suggestion: `Implement type "${specType.name}" in code
|
|
922
|
+
suggestion: `Implement type "${specType.name}" in code`,
|
|
923
|
+
// The score's types denominator counts fields; an absent type must
|
|
924
|
+
// subtract all of its fields, not 1, or a project that implements
|
|
925
|
+
// nothing of an N-field model scores (N-1)/N.
|
|
926
|
+
weight: specType.fields.length
|
|
923
927
|
});
|
|
924
928
|
continue;
|
|
925
929
|
}
|
|
@@ -1128,7 +1132,7 @@ function computeScore(findings, totals) {
|
|
|
1128
1132
|
const missingByCategory = { route: 0, type: 0, test: 0, artifact: 0 };
|
|
1129
1133
|
for (const f of findings) {
|
|
1130
1134
|
if (f.type === "missing" || f.type === "mismatch") {
|
|
1131
|
-
missingByCategory[f.category] = (missingByCategory[f.category] ?? 0) + 1;
|
|
1135
|
+
missingByCategory[f.category] = (missingByCategory[f.category] ?? 0) + (f.weight ?? 1);
|
|
1132
1136
|
}
|
|
1133
1137
|
}
|
|
1134
1138
|
const categoryMap = {
|
|
@@ -1220,14 +1224,15 @@ async function runCheck(specs, projectDir, config = {}) {
|
|
|
1220
1224
|
}
|
|
1221
1225
|
}
|
|
1222
1226
|
const designSpecs = specs.filter((s) => s.frontmatter.type === "technical-design");
|
|
1223
|
-
|
|
1227
|
+
const prismaSchemaFound = (await findPrismaSchemas(projectDir)).length > 0;
|
|
1228
|
+
if (designSpecs.length > 0 && (tsMorphAvailable || prismaSchemaFound)) {
|
|
1224
1229
|
const codeTypes = [
|
|
1225
1230
|
...tsMorphAvailable ? await extractTypeScriptTypes(projectDir, config.types_dir) : [],
|
|
1226
1231
|
...tsMorphAvailable ? await extractZodSchemas(projectDir, config.types_dir) : [],
|
|
1227
1232
|
...await extractPrismaModels(projectDir)
|
|
1228
1233
|
];
|
|
1229
1234
|
codeTypeCount = codeTypes.length;
|
|
1230
|
-
if (await usesPrisma(projectDir) &&
|
|
1235
|
+
if (await usesPrisma(projectDir) && !prismaSchemaFound) {
|
|
1231
1236
|
notes.push("a prisma dependency is declared but no schema was found at prisma/schema.prisma, schema.prisma or prisma/schema/*.prisma \u2014 Prisma models were not assessed.");
|
|
1232
1237
|
}
|
|
1233
1238
|
for (const spec of designSpecs) {
|
|
@@ -1297,7 +1302,7 @@ async function extractRoutes(projectDir, config, framework) {
|
|
|
1297
1302
|
async function analyzeWithAi(findings, context) {
|
|
1298
1303
|
const apiKey = process.env["ANTHROPIC_API_KEY"];
|
|
1299
1304
|
if (!apiKey) {
|
|
1300
|
-
throw new Error("ANTHROPIC_API_KEY environment variable is required for --ai mode. Set it or use the
|
|
1305
|
+
throw new Error("ANTHROPIC_API_KEY environment variable is required for --ai mode. Set it or use the specdx-verify skill instead (no API key needed).");
|
|
1301
1306
|
}
|
|
1302
1307
|
if (findings.length === 0) {
|
|
1303
1308
|
return { findings, assessments: [], summary: "No findings to analyze." };
|
|
@@ -1353,4 +1358,4 @@ export {
|
|
|
1353
1358
|
runCheck,
|
|
1354
1359
|
analyzeWithAi
|
|
1355
1360
|
};
|
|
1356
|
-
//# sourceMappingURL=chunk-
|
|
1361
|
+
//# sourceMappingURL=chunk-3YXRWQGX.js.map
|
|
@@ -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/matchers/types.ts","../../check/src/matchers/tests.ts","../../check/src/artifacts.ts","../../check/src/score.ts","../../check/src/detect-framework.ts","../../check/src/ai.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { CheckResult, CheckConfig, ExtractedRoute, Finding } from \"./types.js\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport {\n parseEndpoints,\n parseTypeDefinitions,\n parseTestCases,\n hasEndpointsSection,\n unreadableTypeBlocks,\n} from \"./spec-parsers.js\";\nimport { extractExpressRoutes } from \"./extractors/express.js\";\nimport { extractHonoRoutes } from \"./extractors/hono.js\";\nimport { extractNextjsRoutes } from \"./extractors/nextjs.js\";\nimport { extractTypeScriptTypes } from \"./extractors/typescript.js\";\nimport { extractZodSchemas } from \"./extractors/zod.js\";\nimport { extractPrismaModels, findPrismaSchemas } from \"./extractors/prisma.js\";\nimport { extractTestDescriptions } from \"./extractors/test-extractor.js\";\nimport { matchRoutes } from \"./matchers/routes.js\";\nimport { matchTypes } from \"./matchers/types.js\";\nimport { matchTests } from \"./matchers/tests.js\";\nimport { checkArtifacts } from \"./artifacts.js\";\nimport { computeScore } from \"./score.js\";\nimport { detectFramework } from \"./detect-framework.js\";\n\n/** True when the project declares a Prisma dependency, so a schema is expected. */\nasync function usesPrisma(projectDir: string): Promise<boolean> {\n try {\n const pkg = JSON.parse(await readFile(join(projectDir, \"package.json\"), \"utf-8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n return \"prisma\" in deps || \"@prisma/client\" in deps;\n } catch {\n return false;\n }\n}\n\n/**\n * Run implementation checks across all specs and return findings, score, and summary.\n *\n * - `api-contract` specs → route extraction + matching\n * - `technical-design` specs → type extraction + matching\n * - `test-plan` specs → test extraction + matching\n */\nexport async function runCheck(\n specs: ParsedSpec[],\n projectDir: string,\n config: CheckConfig = {},\n): Promise<CheckResult> {\n const findings: Finding[] = [];\n const notes: string[] = [];\n let routeTotal = 0;\n let typeTotal = 0;\n let testTotal = 0;\n let codeRouteCount: number | null = null;\n let codeTypeCount: number | null = null;\n let codeTestCount: number | null = null;\n\n // ts-morph is an optional peer dependency; without it (e.g. under pnpm dlx,\n // where installing into the ephemeral cache is impossible) route, TS/Zod type\n // and test extraction degrade to skipped-with-a-note instead of throwing\n // (issue #7).\n //\n // All three, not two. Test extraction was left unguarded, so a suite holding a\n // single test-plan spec turned the intended note into an unhandled throw and a\n // stack trace — on exactly the ephemeral-runner path this note describes, and\n // on MCP's `sdx_check`, where the bare exception became the tool's only output.\n const tsMorphAvailable = await import(\"ts-morph\").then(\n () => true,\n () => false,\n );\n if (!tsMorphAvailable) {\n notes.push(\n \"route, type and test extraction skipped: ts-morph is not installed. \" +\n \"Install specdx and ts-morph as devDependencies (pnpm add -D specdx ts-morph) — \" +\n \"an ephemeral runner like pnpm dlx cannot provide it.\",\n );\n }\n\n // Resolve the framework once so reporting can say what was scanned\n const framework =\n config.framework && config.framework !== \"auto\"\n ? config.framework\n : await detectFramework(projectDir);\n\n // 1. Route checking: find api-contract specs\n const apiContractSpecs = specs.filter((s) => s.frontmatter.type === \"api-contract\");\n if (apiContractSpecs.length > 0 && tsMorphAvailable) {\n const codeRoutes = await extractRoutes(projectDir, config, framework);\n codeRouteCount = codeRoutes.length;\n\n for (const spec of apiContractSpecs) {\n const specEndpoints = parseEndpoints(spec.content);\n routeTotal += specEndpoints.length;\n findings.push(...matchRoutes(specEndpoints, codeRoutes, spec.frontmatter.id as string));\n\n // An Endpoints section we cannot read drops routes out of the score\n // entirely, which *raises* the percentage. Saying nothing presents that\n // as full coverage of a category never assessed.\n if (specEndpoints.length === 0 && hasEndpointsSection(spec.content)) {\n notes.push(\n `${spec.frontmatter.id as string}: no endpoints recognised in its Endpoints section, so routes were not assessed. ` +\n \"Write each endpoint as `- GET /path — description` or as a `### GET /path` heading.\",\n );\n }\n }\n if (framework === null) {\n notes.push(\n \"no supported framework detected (express, hono, nextjs) — route extraction ran in fallback mode across all extractors.\",\n );\n }\n }\n\n // 2. Type checking: find technical-design specs with Data Model sections.\n // Prisma extraction reads the schema as text, so types stay assessable\n // without ts-morph when a schema exists — but with neither, matching every\n // spec type against an empty extraction would report the whole model\n // unimplemented when it was simply never looked at. Skip, like tests do;\n // the ts-morph note above already says so.\n const designSpecs = specs.filter((s) => s.frontmatter.type === \"technical-design\");\n const prismaSchemaFound = (await findPrismaSchemas(projectDir)).length > 0;\n if (designSpecs.length > 0 && (tsMorphAvailable || prismaSchemaFound)) {\n const codeTypes = [\n ...(tsMorphAvailable ? await extractTypeScriptTypes(projectDir, config.types_dir) : []),\n ...(tsMorphAvailable ? await extractZodSchemas(projectDir, config.types_dir) : []),\n ...(await extractPrismaModels(projectDir)),\n ];\n codeTypeCount = codeTypes.length;\n\n // A project that depends on Prisma but whose schema we could not find is\n // worth saying out loud. Silence here read as \"these models are not\n // implemented\", which is the opposite of what happened.\n if ((await usesPrisma(projectDir)) && !prismaSchemaFound) {\n notes.push(\n \"a prisma dependency is declared but no schema was found at prisma/schema.prisma, \" +\n \"schema.prisma or prisma/schema/*.prisma — Prisma models were not assessed.\",\n );\n }\n\n for (const spec of designSpecs) {\n const specTypes = parseTypeDefinitions(spec.content);\n const fieldCount = specTypes.reduce((sum, t) => sum + t.fields.length, 0);\n typeTotal += fieldCount;\n findings.push(...matchTypes(specTypes, codeTypes, spec.frontmatter.id as string));\n\n // A Data Model that yields no fields contributes nothing to the score.\n // Reporting the resulting percentage without saying so presents partial\n // coverage as whole coverage.\n if (fieldCount === 0 && /^##\\s+Data Model\\s*$/im.test(spec.content)) {\n notes.push(\n `${spec.frontmatter.id as string}: no fields recognised in its Data Model, so types were not assessed. ` +\n \"Write fields as `- name: type` (one per line, under a `### TypeName` heading).\",\n );\n }\n\n // The note above is per spec, so one readable type used to silence every\n // unreadable one beside it — a table-shaped type left the denominator with\n // nothing said, and the percentage did not move.\n for (const name of unreadableTypeBlocks(spec.content)) {\n notes.push(\n `${spec.frontmatter.id as string}: no fields recognised under \\`### ${name}\\`, so that type was not assessed. ` +\n \"A table needs a field column and a type column, or write fields as `- name: type`.\",\n );\n }\n }\n }\n\n // 3. Test checking: find test-plan specs\n const testPlanSpecs = specs.filter((s) => s.frontmatter.type === \"test-plan\");\n if (testPlanSpecs.length > 0 && tsMorphAvailable) {\n const codeTests = await extractTestDescriptions(projectDir, config.tests_dir);\n codeTestCount = codeTests.length;\n\n for (const spec of testPlanSpecs) {\n const specCases = parseTestCases(spec.content);\n testTotal += specCases.length;\n findings.push(...matchTests(specCases, codeTests, spec.frontmatter.id as string));\n }\n }\n\n // 4. Declared artifacts: framework-agnostic checkable surfaces (issue #15)\n const artifactResult = await checkArtifacts(specs, projectDir, tsMorphAvailable);\n findings.push(...artifactResult.findings);\n notes.push(...artifactResult.notes);\n\n // 5. Score\n const score = computeScore(findings, {\n routes: routeTotal,\n types: typeTotal,\n tests: testTotal,\n artifacts: artifactResult.total,\n });\n\n // 6. Summary — never present \"nothing was checkable\" as coverage (issue #6)\n const errors = findings.filter((f) => f.severity === \"error\").length;\n const warnings = findings.filter((f) => f.severity === \"warn\").length;\n const summary = score.assessed\n ? `${score.overall}% implementation coverage — ${errors} errors, ${warnings} warnings`\n : \"coverage not assessed — no checkable surfaces found (no spec'd routes, types, test cases, or declared artifacts)\";\n\n const scanned = {\n framework: framework ?? null,\n codeRoutes: codeRouteCount,\n codeTypes: codeTypeCount,\n codeTests: codeTestCount,\n artifacts: artifactResult.total > 0 ? artifactResult.checked : null,\n artifactsPending: artifactResult.pending,\n };\n\n return { findings, score, summary, scanned, notes };\n}\n\n/**\n * Extract routes from the project based on framework config.\n *\n * In \"auto\" mode, reads package.json to detect the framework first.\n * If a framework is detected, only that extractor is used.\n * If no framework is detected, falls back to trying all extractors and merging results.\n */\nasync function extractRoutes(\n projectDir: string,\n config: CheckConfig,\n framework: string | null,\n): Promise<ExtractedRoute[]> {\n if (framework === \"express\") {\n return extractExpressRoutes(projectDir, config.routes_dir);\n }\n if (framework === \"hono\") {\n return extractHonoRoutes(projectDir, config.routes_dir);\n }\n if (framework === \"nextjs\") {\n return extractNextjsRoutes(projectDir, config.app_dir);\n }\n\n // fallback: try all extractors and merge results\n const [express, hono, nextjs] = await Promise.all([\n extractExpressRoutes(projectDir, config.routes_dir),\n extractHonoRoutes(projectDir, config.routes_dir),\n extractNextjsRoutes(projectDir, config.app_dir),\n ]);\n\n return [...express, ...hono, ...nextjs];\n}\n","import type { HttpMethod, SpecEndpoint, SpecTypeDefinition, SpecTestCase } from \"./types.js\";\n\n/**\n * Extracts the content of a `## Heading` section from a markdown string.\n * Returns the text between that heading and the next `## ` heading (or end of string).\n */\nfunction extractSection(content: string, heading: string): string | null {\n // Match the heading line (case-insensitive, trimmed)\n const headingPattern = new RegExp(`^##\\\\s+${escapeRegex(heading)}\\\\s*$`, \"im\");\n const match = headingPattern.exec(content);\n if (!match) return null;\n\n const start = match.index + match[0].length;\n const rest = content.slice(start);\n\n // Find the next `## ` heading\n const nextSection = /^##\\s+/m.exec(rest);\n return nextSection ? rest.slice(0, nextSection.index) : rest;\n}\n\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nconst HTTP_METHODS: ReadonlySet<string> = new Set([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/**\n * Parses the `## Endpoints` section of a spec and returns structured endpoint data.\n */\n/** Path params are the `:name` segments of a route path. */\nfunction pathParams(path: string): string[] {\n return (path.match(/:([A-Za-z_][A-Za-z0-9_]*)/g) ?? []).map((p) => p.slice(1));\n}\n\n/**\n * True when `content` has an `## Endpoints` heading at all, regardless of what\n * it holds. Lets a caller tell \"no such section\" from \"a section we could not\n * read\" -- the second is worth a note, the first is not.\n */\nexport function hasEndpointsSection(content: string): boolean {\n return extractSection(content, \"Endpoints\") !== null;\n}\n\n/**\n * Parses the `## Endpoints` section of a spec and returns structured endpoint data.\n *\n * Two shapes are accepted, because both are what people write:\n *\n * ### GET /invoices (a sub-heading per endpoint, description beneath)\n * - `GET /invoices` — list (one bullet per endpoint, backticked or not)\n *\n * Accepting only the heading form meant an ordinary bulleted contract parsed to\n * zero endpoints. `check` then reported every real route as unspecified, missed\n * every genuinely absent one, and raised the coverage score because routes left\n * the denominator entirely.\n */\nexport function parseEndpoints(content: string): SpecEndpoint[] {\n const section = extractSection(content, \"Endpoints\");\n if (!section) return [];\n\n const results: SpecEndpoint[] = [];\n const seen = new Set<string>();\n\n const push = (rawMethod: string, path: string, description?: string): void => {\n const method = rawMethod.toUpperCase();\n if (!HTTP_METHODS.has(method)) return;\n // A contract listing an endpoint under a heading *and* in a summary bullet\n // describes one endpoint, not two.\n const key = `${method} ${path}`;\n if (seen.has(key)) return;\n seen.add(key);\n results.push({\n method: method as HttpMethod,\n path,\n params: pathParams(path),\n description: description && description.length > 0 ? description : undefined,\n });\n };\n\n // Shape 1: `### METHOD /path` sub-headings.\n const headingPattern = /^###\\s+(GET|POST|PUT|PATCH|DELETE)\\s+(\\S+)/im;\n for (const block of section.split(/^(?=###\\s)/m)) {\n const headingMatch = headingPattern.exec(block);\n if (!headingMatch) continue;\n\n // Description: first non-empty line after the heading line\n const afterHeading = block.slice(headingMatch.index + headingMatch[0].length);\n const descriptionLine = afterHeading\n .split(\"\\n\")\n .map((l) => l.trim())\n .find((l) => l.length > 0 && !l.startsWith(\"#\") && !l.startsWith(\"-\"));\n\n push(headingMatch[1]!, headingMatch[2]!, descriptionLine);\n }\n\n // Shape 2: one bullet per endpoint. The method and path may be wrapped in\n // backticks together (`GET /invoices`), separately (`GET` `/invoices`), or\n // not at all, and may carry bold emphasis. Anything after the path -- an\n // em-dash, a colon, a hyphen -- is the description.\n const bulletPattern = new RegExp(\n \"^\\\\s*[-*+]\\\\s+\" + // bullet marker\n \"[`*_]*\\\\s*\" + // opening backtick/emphasis\n \"(GET|POST|PUT|PATCH|DELETE)\" + // method\n \"[`*_]*\\\\s+[`*_]*\" + // separator, possibly re-opening a code span\n \"(/[^\\\\s`*_]*)\" + // path -- must start at the root, stops at a code span or emphasis\n \"[`*_]*\" + // closing backtick/emphasis\n \"\\\\s*(?:[—–:-]\\\\s*(.*))?$\", // optional description\n \"gim\",\n );\n let bulletMatch: RegExpExecArray | null;\n while ((bulletMatch = bulletPattern.exec(section)) !== null) {\n push(bulletMatch[1]!, bulletMatch[2]!, bulletMatch[3]?.trim());\n }\n\n return results;\n}\n\n/**\n * An identifier, or identifiers joined by `|` / `&` -- what a type annotation\n * looks like, as opposed to a sentence.\n */\nconst TYPE_SHAPE = /^[A-Za-z_$][\\w$.<>[\\]]*(?:\\s*[|&]\\s*[A-Za-z_$][\\w$.<>[\\]]*)*$/;\n\n/**\n * What a `### Heading` inside a Data Model must look like to be a type name:\n * one identifier, optionally generic. Prose headings (\"Notes on the model\")\n * have spaces and are not type declarations.\n */\nconst TYPE_NAME_SHAPE = /^[A-Za-z_$][\\w$]*(?:<[\\w$,\\s[\\]]+>)?$/;\n\n/**\n * Parses the `## Data Model` section of a spec and returns structured type definitions.\n */\nexport function parseTypeDefinitions(content: string): SpecTypeDefinition[] {\n const section = extractSection(content, \"Data Model\");\n if (!section) return [];\n\n const results: SpecTypeDefinition[] = [];\n\n // Split by `### TypeName` headings\n const blocks = section.split(/^(?=###\\s)/m);\n\n for (const block of blocks) {\n // The whole heading line, not just its first word: `### Notes on the model`\n // used to register a type called \"Notes\" that code was then told to\n // implement. A type name is a single identifier-shaped token.\n const headingMatch = /^###\\s+(.+?)\\s*$/m.exec(block);\n if (!headingMatch) continue;\n\n const name = headingMatch[1]!.trim().replace(/^`|`$/g, \"\");\n if (!TYPE_NAME_SHAPE.test(name)) continue;\n\n const fields: SpecTypeDefinition[\"fields\"] = [];\n\n // Field lines, backticked or not: `- \\`fieldName?\\`: type` / `- fieldName?: type`.\n //\n // Requiring backticks meant an ordinary markdown Data Model parsed to zero\n // fields, which `check` then dropped from coverage without saying so. The\n // un-backticked form is deliberately strict -- a single identifier only --\n // so prose like \"- Note: this table is partitioned\" is not read as a field.\n const fieldPattern = /^-\\s+(?:`([^`]+)`|([A-Za-z_$][\\w$]*\\??))\\s*:\\s*(.+)/gm;\n let fieldMatch: RegExpExecArray | null;\n\n while ((fieldMatch = fieldPattern.exec(block)) !== null) {\n const backticked = fieldMatch[1] !== undefined;\n const rawName = (fieldMatch[1] ?? fieldMatch[2])!;\n const optional = rawName.endsWith(\"?\");\n const fieldName = optional ? rawName.slice(0, -1) : rawName;\n\n // Type is everything before optional parenthetical notes like \"(UUID)\"\n const rawType = fieldMatch[3]!.trim();\n const type = rawType.replace(/\\s*\\(.*?\\)\\s*$/, \"\").trim();\n\n // Backticks are the author saying \"this is a field\", so the type is taken\n // as written. Without them the line is only a field if the type also\n // looks like one -- otherwise \"- Note: this table is partitioned by\n // tenant\" would become a field named Note.\n if (!backticked && !TYPE_SHAPE.test(type)) continue;\n\n fields.push({ name: fieldName, type, optional });\n }\n\n // A table is the third way people write a data model, and reading only the\n // bullet forms meant a table-shaped type contributed nothing to the score\n // and drew no note -- the note fires per spec, so one readable type hid\n // every unreadable one beside it.\n if (fields.length === 0) fields.push(...parseFieldTable(block));\n\n // A heading with no fields beneath it asserts only that a name exists, and\n // in practice it is prose -- `### Indexes`, `### Migration notes`. Matching\n // it against code turns an explanatory sub-section into a check error, so a\n // block earns its place as a type only by declaring at least one field.\n if (fields.length === 0) continue;\n\n results.push({ name, fields });\n }\n\n return results;\n}\n\n/** A markdown table row split into trimmed cells, or null when the line is not one. */\nfunction tableCells(line: string): string[] | null {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"|\")) return null;\n return trimmed\n .replace(/^\\|/, \"\")\n .replace(/\\|$/, \"\")\n .split(\"|\")\n .map((cell) => cell.trim().replace(/^`|`$/g, \"\"));\n}\n\n/** True for the `|---|---|` rule under a table's header row. */\nfunction isTableRule(cells: string[]): boolean {\n return cells.every((cell) => /^:?-{2,}:?$/.test(cell));\n}\n\n/**\n * Fields from a markdown table inside a `### TypeName` block.\n *\n * Needs a header naming both a field column and a type column; anything else is\n * a table about something other than the shape of the type, and is left alone.\n */\nfunction parseFieldTable(block: string): SpecTypeDefinition[\"fields\"] {\n const rows = block.split(\"\\n\").map(tableCells);\n const headerIndex = rows.findIndex((r) => r !== null);\n if (headerIndex === -1) return [];\n\n const header = rows[headerIndex]!;\n const nameColumn = header.findIndex((h) => /^(field|name|property|attribute|key)s?$/i.test(h));\n const typeColumn = header.findIndex((h) => /^types?$/i.test(h));\n if (nameColumn === -1 || typeColumn === -1) return [];\n\n const fields: SpecTypeDefinition[\"fields\"] = [];\n for (const cells of rows.slice(headerIndex + 1)) {\n if (cells === null) continue;\n if (isTableRule(cells)) continue;\n\n const rawName = cells[nameColumn];\n const rawType = cells[typeColumn];\n if (!rawName || !rawType) continue;\n\n const optional = rawName.endsWith(\"?\");\n const name = optional ? rawName.slice(0, -1) : rawName;\n if (!/^[A-Za-z_$][\\w$]*$/.test(name)) continue;\n\n fields.push({ name, type: rawType.replace(/\\s*\\(.*?\\)\\s*$/, \"\").trim(), optional });\n }\n return fields;\n}\n\n/**\n * Type-shaped `### Heading`s in a Data Model that declared a table we could not\n * read as fields.\n *\n * Prose blocks are deliberately absent: a heading with no field declarations at\n * all is an explanatory sub-section, and re-flagging it would undo the fix that\n * stopped `### Indexes` becoming a phantom type. A table, on the other hand, is\n * an author declaring a shape in a syntax the parser missed — worth saying,\n * because the alternative is dropping it from the score in silence.\n */\nexport function unreadableTypeBlocks(content: string): string[] {\n const section = extractSection(content, \"Data Model\");\n if (!section) return [];\n\n const unreadable: string[] = [];\n for (const block of section.split(/^(?=###\\s)/m)) {\n const headingMatch = /^###\\s+(.+?)\\s*$/m.exec(block);\n if (!headingMatch) continue;\n\n const name = headingMatch[1]!.trim().replace(/^`|`$/g, \"\");\n if (!TYPE_NAME_SHAPE.test(name)) continue;\n\n const hasTable = block.split(\"\\n\").some((line) => tableCells(line) !== null);\n if (!hasTable) continue;\n\n const parsed = parseTypeDefinitions(`## Data Model\\n\\n${block}`);\n if (parsed.length === 0) unreadable.push(name);\n }\n return unreadable;\n}\n\n/**\n * Parses the `## Test Cases` section of a spec and returns structured test case data.\n */\nexport function parseTestCases(content: string): SpecTestCase[] {\n const section = extractSection(content, \"Test Cases\");\n if (!section) return [];\n\n const results: SpecTestCase[] = [];\n let currentSection: string | undefined;\n\n for (const rawLine of section.split(\"\\n\")) {\n const line = rawLine.trim();\n\n // Track `### SubSection` headings\n const subHeading = /^###\\s+(.+)/.exec(line);\n if (subHeading) {\n currentSection = subHeading[1]!.trim();\n continue;\n }\n\n // Bullet points are test cases; each comma-separated item in the text is its own case\n const bulletMatch = /^-\\s+(.+)/.exec(line);\n if (!bulletMatch) continue;\n\n let bulletText = bulletMatch[1]!.trim();\n\n // A test-case ID names the case in the spec; it is not part of the test a\n // user is being asked to write. Leaving it in produced the suggestion\n // `Add a test matching: \"**TC5**: refuses to amend…\"`, markup and all, and\n // put `tc5` into the similarity comparison as if it were a word.\n let caseId: string | undefined;\n const idMatch = /^\\*{0,2}(TC\\d+)\\*{0,2}\\s*[:.-]\\s*/i.exec(bulletText);\n if (idMatch) {\n caseId = idMatch[1]!.toUpperCase();\n bulletText = bulletText.slice(idMatch[0].length).trim();\n if (!bulletText) continue;\n }\n\n // Split on `, ` only when it separates items after a label like \"label: item1, item2\"\n // Pattern: label: item1, item2, item3 → generate one entry per item\n const colonIdx = bulletText.indexOf(\":\");\n if (colonIdx !== -1) {\n const label = bulletText.slice(0, colonIdx).trim();\n const rest = bulletText.slice(colonIdx + 1).trim();\n const items = rest.split(/,\\s*/);\n for (const item of items) {\n const trimmed = item.trim();\n if (trimmed) {\n results.push({\n description: `${label}: ${trimmed}`,\n section: currentSection,\n id: caseId,\n });\n }\n }\n } else {\n results.push({ description: bulletText, section: currentSection, id: caseId });\n }\n }\n\n return results;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedRoute, HttpMethod } from \"../types.js\";\n\nconst HTTP_METHODS = new Set([\"get\", \"post\", \"put\", \"patch\", \"delete\"]);\n\n/**\n * Extract Express routes from TypeScript/JavaScript source files using ts-morph AST parsing.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param routesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractExpressRoutes(\n projectDir: string,\n routesDir?: string,\n): Promise<ExtractedRoute[]> {\n const scanDir = routesDir ? join(projectDir, routesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for route extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts and .js files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.test.js\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/*.spec.js\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const routes: ExtractedRoute[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Build a map of router variable name → mount prefix from app.use() calls.\n // e.g. app.use(\"/api\", router) → { router: \"/api\" }\n const mountPrefixes = new Map<string, string>();\n\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n\n // First pass: collect app.use(\"/prefix\", routerVar) mounts.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName();\n if (methodName !== \"use\") continue;\n\n const args = callExpr.getArguments();\n if (args.length < 2) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n const secondArg = args[1];\n if (!secondArg) continue;\n\n // First arg must be a string literal (the prefix).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const prefix = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Second arg should be an identifier (the router variable).\n if (secondArg.getKind() === SyntaxKind.Identifier) {\n const routerVarName = secondArg.asKindOrThrow(SyntaxKind.Identifier).getText();\n mountPrefixes.set(routerVarName, prefix);\n }\n }\n\n // Second pass: collect router.METHOD(\"/path\", handler) calls.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName().toLowerCase();\n if (!HTTP_METHODS.has(methodName)) continue;\n\n const args = callExpr.getArguments();\n if (args.length < 1) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n\n // First arg must be a string literal (the path).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const routePath = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Determine if the receiver is a known router variable, and look up its mount prefix.\n const receiverExpr = propAccess.getExpression();\n let prefix = \"\";\n if (receiverExpr.getKind() === SyntaxKind.Identifier) {\n const receiverName = receiverExpr.asKindOrThrow(SyntaxKind.Identifier).getText();\n prefix = mountPrefixes.get(receiverName) ?? \"\";\n }\n\n const fullPath = prefix + routePath;\n\n // Extract :param names from path segments.\n const params = (fullPath.match(/:([^/]+)/g) ?? []).map((p) => p.slice(1));\n\n const lineNumber = sourceFile.getLineAndColumnAtPos(callExpr.getStart()).line;\n\n routes.push({\n method: methodName.toUpperCase() as HttpMethod,\n path: fullPath,\n params,\n file: filePath,\n line: lineNumber,\n });\n }\n }\n\n return routes;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedRoute, HttpMethod } from \"../types.js\";\n\nconst HTTP_METHODS = new Set([\"get\", \"post\", \"put\", \"patch\", \"delete\"]);\n\n/**\n * Extract Hono routes from TypeScript/JavaScript source files using ts-morph AST parsing.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param routesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractHonoRoutes(\n projectDir: string,\n routesDir?: string,\n): Promise<ExtractedRoute[]> {\n const scanDir = routesDir ? join(projectDir, routesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for route extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts and .js files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.test.js\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/*.spec.js\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const routes: ExtractedRoute[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Build a map of sub-app variable name → mount prefix from app.route() calls.\n // e.g. app.route(\"/api/users\", users) → { users: \"/api/users\" }\n const mountPrefixes = new Map<string, string>();\n\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n\n // First pass: collect app.route(\"/prefix\", subAppVar) mounts.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName();\n if (methodName !== \"route\") continue;\n\n const args = callExpr.getArguments();\n if (args.length < 2) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n const secondArg = args[1];\n if (!secondArg) continue;\n\n // First arg must be a string literal (the prefix).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const prefix = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Second arg should be an identifier (the sub-app variable).\n if (secondArg.getKind() === SyntaxKind.Identifier) {\n const subAppVarName = secondArg.asKindOrThrow(SyntaxKind.Identifier).getText();\n mountPrefixes.set(subAppVarName, prefix);\n }\n }\n\n // Second pass: collect subApp.METHOD(\"/path\", handler) calls.\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n if (expr.getKind() !== SyntaxKind.PropertyAccessExpression) continue;\n\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName().toLowerCase();\n if (!HTTP_METHODS.has(methodName)) continue;\n\n const args = callExpr.getArguments();\n if (args.length < 1) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n\n // First arg must be a string literal (the path).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const routePath = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n\n // Determine if the receiver is a known sub-app variable, and look up its mount prefix.\n const receiverExpr = propAccess.getExpression();\n let prefix = \"\";\n if (receiverExpr.getKind() === SyntaxKind.Identifier) {\n const receiverName = receiverExpr.asKindOrThrow(SyntaxKind.Identifier).getText();\n prefix = mountPrefixes.get(receiverName) ?? \"\";\n }\n\n // Hono sub-app routes with path \"/\" resolve to just the prefix (no trailing slash).\n const normalizedPath = routePath === \"/\" ? prefix : prefix + routePath;\n\n // Extract :param names from path segments.\n const params = (normalizedPath.match(/:([^/]+)/g) ?? []).map((p) => p.slice(1));\n\n const lineNumber = sourceFile.getLineAndColumnAtPos(callExpr.getStart()).line;\n\n routes.push({\n method: methodName.toUpperCase() as HttpMethod,\n path: normalizedPath,\n params,\n file: filePath,\n line: lineNumber,\n });\n }\n }\n\n return routes;\n}\n","import { existsSync } from \"node:fs\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { ExtractedRoute, HttpMethod } from \"../types.js\";\n\nconst HTTP_METHODS = new Set<string>([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/**\n * Convert a Next.js App Router directory segment to a route path segment.\n *\n * - Route groups `(group)` → empty string (omitted from path)\n * - Catch-all `[...slug]` → `:slug*`\n * - Dynamic `[param]` → `:param`\n * - Static `foo` → `foo`\n */\nfunction segmentToPath(segment: string): string {\n // Route group — skip in path\n if (segment.startsWith(\"(\") && segment.endsWith(\")\")) {\n return \"\";\n }\n // Catch-all segment: [...slug]\n const catchAll = segment.match(/^\\[\\.\\.\\.([^\\]]+)\\]$/);\n if (catchAll) {\n return `:${catchAll[1]}*`;\n }\n // Dynamic segment: [param]\n const dynamic = segment.match(/^\\[([^\\]]+)\\]$/);\n if (dynamic) {\n return `:${dynamic[1]}`;\n }\n return segment;\n}\n\n/**\n * Recursively walk a directory, yielding route files with their corresponding\n * URL path prefix.\n */\nasync function walkAppDir(\n dir: string,\n pathPrefix: string,\n results: Array<{ file: string; routePath: string }>,\n): Promise<void> {\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dir, entry);\n let entryStat;\n try {\n entryStat = await stat(fullPath);\n } catch {\n continue;\n }\n\n if (entryStat.isDirectory()) {\n const pathSegment = segmentToPath(entry);\n // Route groups are transparent — continue with the same prefix\n const childPrefix = pathSegment === \"\" ? pathPrefix : `${pathPrefix}/${pathSegment}`;\n await walkAppDir(fullPath, childPrefix, results);\n } else if (entry === \"route.ts\" || entry === \"route.js\") {\n results.push({ file: fullPath, routePath: pathPrefix || \"/\" });\n }\n }\n}\n\n/**\n * Extract routes from a Next.js App Router project by scanning the file system\n * and using ts-morph to detect exported HTTP method functions in route files.\n *\n * @param projectDir - Root directory (or fixtures dir in tests)\n * @param appDir - Sub-directory to scan, relative to projectDir. Defaults to \"app\"\n */\nexport async function extractNextjsRoutes(\n projectDir: string,\n appDir?: string,\n): Promise<ExtractedRoute[]> {\n // `src/app` is as official a layout as `app`, and defaulting to `app` alone\n // meant half of all App Router projects scanned an absent directory and\n // reported no routes — the same shape as reading only the project root for a\n // Prisma schema. An explicit `app_dir` is still honoured exactly as given.\n const candidates = appDir !== undefined ? [appDir] : [\"app\", \"src/app\"];\n const scanDir = candidates.map((dir) => join(projectDir, dir)).find((dir) => existsSync(dir));\n\n if (!scanDir) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for route extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n // Discover all route files and their URL paths\n const routeFiles: Array<{ file: string; routePath: string }> = [];\n await walkAppDir(scanDir, \"\", routeFiles);\n\n if (routeFiles.length === 0) {\n return [];\n }\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add only the discovered route files\n for (const { file } of routeFiles) {\n project.addSourceFileAtPath(file);\n }\n\n const routes: ExtractedRoute[] = [];\n\n for (const { file, routePath } of routeFiles) {\n const sourceFile = project.getSourceFile(file);\n if (!sourceFile) continue;\n\n // Extract params from route path segments (e.g. `:id` → \"id\", `:slug*` → \"slug\")\n const params = (routePath.match(/:[a-zA-Z_][a-zA-Z0-9_]*\\*?/g) ?? []).map((p) =>\n p.replace(/^:/, \"\").replace(/\\*$/, \"\"),\n );\n\n // Find all exported function declarations named after HTTP methods\n const exportedFunctions = sourceFile.getFunctions().filter((fn) => {\n const name = fn.getName();\n return name !== undefined && HTTP_METHODS.has(name) && fn.isExported();\n });\n\n for (const fn of exportedFunctions) {\n const name = fn.getName()!;\n const lineNumber = sourceFile.getLineAndColumnAtPos(fn.getStart()).line;\n\n routes.push({\n method: name as HttpMethod,\n path: routePath || \"/\",\n params,\n file,\n line: lineNumber,\n });\n }\n\n // Also handle variable exported functions: export const GET = async () => { ... }\n const exportedVarDecls = sourceFile\n .getDescendantsOfKind(SyntaxKind.VariableDeclaration)\n .filter((decl) => {\n const name = decl.getName();\n if (!HTTP_METHODS.has(name)) return false;\n // Check if the variable statement is exported\n const varStatement = decl.getVariableStatement();\n return varStatement !== undefined && varStatement.isExported();\n });\n\n for (const decl of exportedVarDecls) {\n const name = decl.getName();\n const lineNumber = sourceFile.getLineAndColumnAtPos(decl.getStart()).line;\n\n routes.push({\n method: name as HttpMethod,\n path: routePath || \"/\",\n params,\n file,\n line: lineNumber,\n });\n }\n }\n\n return routes;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedType } from \"../types.js\";\n\n/**\n * Extract TypeScript interface and type alias definitions from source files using ts-morph AST parsing.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param typesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractTypeScriptTypes(\n projectDir: string,\n typesDir?: string,\n): Promise<ExtractedType[]> {\n const scanDir = typesDir ? join(projectDir, typesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for type extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const types: ExtractedType[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n // Extract interfaces.\n for (const iface of sourceFile.getInterfaces()) {\n const name = iface.getName();\n const line = sourceFile.getLineAndColumnAtPos(iface.getStart()).line;\n const fields = extractProperties(iface.getProperties());\n types.push({ name, fields, file: filePath, line });\n }\n\n // Extract type aliases that define object types (with properties).\n for (const typeAlias of sourceFile.getTypeAliases()) {\n const typeNode = typeAlias.getTypeNode();\n if (!typeNode) continue;\n\n // Only process object type literals (skip simple aliases like `type X = string`).\n if (typeNode.getKind() !== SyntaxKind.TypeLiteral) continue;\n\n const typeLiteral = typeNode.asKindOrThrow(SyntaxKind.TypeLiteral);\n const properties = typeLiteral.getProperties();\n if (properties.length === 0) continue;\n\n const name = typeAlias.getName();\n const line = sourceFile.getLineAndColumnAtPos(typeAlias.getStart()).line;\n const fields = extractProperties(properties);\n types.push({ name, fields, file: filePath, line });\n }\n }\n\n return types;\n}\n\n/**\n * Convert a list of ts-morph property signatures into the ExtractedType fields format.\n */\nfunction extractProperties(\n properties: import(\"ts-morph\").PropertySignature[],\n): ExtractedType[\"fields\"] {\n return properties.map((prop) => {\n const name = prop.getName();\n const optional = prop.hasQuestionToken();\n\n // Prefer the type as written in source; fall back to the resolved type text.\n let type = prop.getTypeNode()?.getText() ?? prop.getType().getText();\n\n // Strip import() paths that ts-morph sometimes includes, e.g. `import(\"x\").Foo` → `Foo`.\n type = type.replace(/import\\([^)]+\\)\\./g, \"\");\n\n return { name, type, optional };\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedType } from \"../types.js\";\n\n/**\n * Extract Zod object schemas from TypeScript source files using ts-morph AST parsing.\n *\n * Scans for variable declarations of the form:\n * export const FooSchema = z.object({ ... });\n * and converts them to ExtractedType entries, stripping the `Schema` suffix from the name.\n *\n * @param projectDir - Root directory of the project (or fixtures dir in tests)\n * @param typesDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractZodSchemas(\n projectDir: string,\n typesDir?: string,\n): Promise<ExtractedType[]> {\n const scanDir = typesDir ? join(projectDir, typesDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\n \"ts-morph is required for Zod schema extraction. Install it: pnpm add -D ts-morph\",\n );\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Add all .ts and .js files from the scan directory, excluding tests and node_modules.\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/*.test.ts\")}`,\n `!${join(scanDir, \"**/*.test.js\")}`,\n `!${join(scanDir, \"**/*.spec.ts\")}`,\n `!${join(scanDir, \"**/*.spec.js\")}`,\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const types: ExtractedType[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n const varDeclarations = sourceFile.getDescendantsOfKind(SyntaxKind.VariableDeclaration);\n\n for (const varDecl of varDeclarations) {\n const initializer = varDecl.getInitializer();\n if (!initializer) continue;\n if (initializer.getKind() !== SyntaxKind.CallExpression) continue;\n\n // Walk up the call chain looking for a z.object(...) call.\n // The pattern may be z.object({...}).strict() or similar — walk the chain.\n const zObjectCall = findZObjectCall(initializer, SyntaxKind);\n if (!zObjectCall) continue;\n\n // Get the argument to z.object() — must be an ObjectLiteralExpression.\n const args = zObjectCall.asKindOrThrow(SyntaxKind.CallExpression).getArguments();\n if (args.length === 0) continue;\n const firstArg = args[0];\n if (!firstArg) continue;\n if (firstArg.getKind() !== SyntaxKind.ObjectLiteralExpression) continue;\n\n const objLiteral = firstArg.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n // Derive the type name: strip \"Schema\" suffix from the variable name.\n const rawName = varDecl.getName();\n const typeName = rawName.endsWith(\"Schema\") ? rawName.slice(0, -\"Schema\".length) : rawName;\n\n const fields: ExtractedType[\"fields\"] = [];\n\n for (const prop of objLiteral.getProperties()) {\n // Only handle PropertyAssignment (not shorthand, spread, etc.)\n if (prop.getKind() !== SyntaxKind.PropertyAssignment) continue;\n\n const propAssign = prop.asKindOrThrow(SyntaxKind.PropertyAssignment);\n const fieldName = propAssign.getName();\n const fieldInit = propAssign.getInitializer();\n if (!fieldInit) continue;\n\n const { type: fieldType, optional } = inferZodType(fieldInit, SyntaxKind);\n\n fields.push({ name: fieldName, type: fieldType, optional });\n }\n\n const lineNumber = sourceFile.getLineAndColumnAtPos(varDecl.getStart()).line;\n\n types.push({ name: typeName, fields, file: filePath, line: lineNumber });\n }\n }\n\n return types;\n}\n\n/**\n * Walk a call expression chain to find the `z.object(...)` call.\n * Handles chained calls like `z.object({...}).strict()`.\n */\nfunction findZObjectCall(\n node: import(\"ts-morph\").Node,\n SyntaxKind: typeof import(\"ts-morph\").SyntaxKind,\n): import(\"ts-morph\").Node | undefined {\n if (node.getKind() !== SyntaxKind.CallExpression) return undefined;\n\n const callExpr = node.asKindOrThrow(SyntaxKind.CallExpression);\n const expr = callExpr.getExpression();\n\n // Direct: z.object(...)\n if (isZObjectAccess(expr, SyntaxKind)) {\n return node;\n }\n\n // Chained: someCall(...).method(...) — recurse into the callee\n if (expr.getKind() === SyntaxKind.PropertyAccessExpression) {\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const innerExpr = propAccess.getExpression();\n if (innerExpr.getKind() === SyntaxKind.CallExpression) {\n return findZObjectCall(innerExpr, SyntaxKind);\n }\n }\n\n return undefined;\n}\n\n/**\n * Returns true if the given node is a `z.object` property access.\n */\nfunction isZObjectAccess(\n node: import(\"ts-morph\").Node,\n SyntaxKind: typeof import(\"ts-morph\").SyntaxKind,\n): boolean {\n if (node.getKind() !== SyntaxKind.PropertyAccessExpression) return false;\n const propAccess = node.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n if (propAccess.getName() !== \"object\") return false;\n const receiver = propAccess.getExpression();\n return receiver.getKind() === SyntaxKind.Identifier && receiver.getText() === \"z\";\n}\n\n/**\n * Infer the TypeScript type and optional flag from a Zod call chain.\n *\n * Examples:\n * z.string() → { type: \"string\", optional: false }\n * z.date().optional() → { type: \"Date\", optional: true }\n * z.enum([\"a\",\"b\"]) → { type: '\"a\" | \"b\"', optional: false }\n */\nfunction inferZodType(\n node: import(\"ts-morph\").Node,\n SyntaxKind: typeof import(\"ts-morph\").SyntaxKind,\n): { type: string; optional: boolean } {\n // Collect all method names in the chain and find the base z.<type>() call.\n const chainMethods: string[] = [];\n let baseCallNode: import(\"ts-morph\").Node | undefined;\n\n let current: import(\"ts-morph\").Node = node;\n\n // Walk from the outermost call inward, collecting method names.\n while (current.getKind() === SyntaxKind.CallExpression) {\n const callExpr = current.asKindOrThrow(SyntaxKind.CallExpression);\n const expr = callExpr.getExpression();\n\n if (expr.getKind() === SyntaxKind.PropertyAccessExpression) {\n const propAccess = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression);\n const methodName = propAccess.getName();\n const receiver = propAccess.getExpression();\n\n if (receiver.getKind() === SyntaxKind.Identifier && receiver.getText() === \"z\") {\n // This is the base z.<type>() call.\n baseCallNode = current;\n chainMethods.push(methodName);\n break;\n } else {\n // Intermediate method in the chain (e.g., .optional(), .email(), etc.)\n chainMethods.push(methodName);\n current = receiver;\n }\n } else {\n break;\n }\n }\n\n const optional = chainMethods.includes(\"optional\");\n\n // The last entry in chainMethods (from our walk) is the base Zod type method name.\n // Because we push inner methods last, the base type is the last element.\n const baseMethodName = chainMethods[chainMethods.length - 1];\n\n let type = \"unknown\";\n\n if (baseMethodName === \"string\") {\n type = \"string\";\n } else if (baseMethodName === \"number\") {\n type = \"number\";\n } else if (baseMethodName === \"boolean\") {\n type = \"boolean\";\n } else if (baseMethodName === \"date\") {\n type = \"Date\";\n } else if (baseMethodName === \"array\") {\n type = \"array\";\n } else if (baseMethodName === \"enum\" && baseCallNode) {\n // z.enum([\"a\", \"b\"]) → \"a\" | \"b\"\n const enumCall = baseCallNode.asKindOrThrow(SyntaxKind.CallExpression);\n const args = enumCall.getArguments();\n if (args.length > 0) {\n const firstArg = args[0];\n if (firstArg && firstArg.getKind() === SyntaxKind.ArrayLiteralExpression) {\n const arrayLiteral = firstArg.asKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n const elements = arrayLiteral\n .getElements()\n .filter((el) => el.getKind() === SyntaxKind.StringLiteral)\n .map((el) => el.asKindOrThrow(SyntaxKind.StringLiteral).getText());\n if (elements.length > 0) {\n type = elements.join(\" | \");\n }\n }\n }\n }\n\n return { type, optional };\n}\n","import type { ExtractedType } from \"../types.js\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nconst PRISMA_TYPE_MAP: Record<string, string> = {\n String: \"string\",\n Int: \"number\",\n Float: \"number\",\n Decimal: \"number\",\n BigInt: \"number\",\n Boolean: \"boolean\",\n DateTime: \"Date\",\n Json: \"unknown\",\n Bytes: \"Buffer\",\n};\n\n/**\n * Every place Prisma keeps a schema, in the order Prisma itself prefers.\n *\n * Only the project root was read, and `prisma init` has never written there --\n * it writes `prisma/schema.prisma`. So a real Prisma project's models were\n * invisible, every one of them was reported as unimplemented, and the coverage\n * score dropped to match, with no note saying a schema had been looked for.\n *\n * `prisma/schema/` is the multi-file layout supported since Prisma 5.15.\n */\nexport async function findPrismaSchemas(projectDir: string): Promise<string[]> {\n const found: string[] = [];\n\n for (const relative of [\"prisma/schema.prisma\", \"schema.prisma\"]) {\n const path = join(projectDir, relative);\n try {\n await readFile(path, \"utf-8\");\n found.push(path);\n } catch {\n // not there; try the next layout\n }\n }\n\n const schemaDir = join(projectDir, \"prisma\", \"schema\");\n try {\n for (const entry of await readdir(schemaDir)) {\n if (entry.endsWith(\".prisma\")) found.push(join(schemaDir, entry));\n }\n } catch {\n // no multi-file schema directory\n }\n\n return found;\n}\n\nexport async function extractPrismaModels(projectDir: string): Promise<ExtractedType[]> {\n const schemaPaths = await findPrismaSchemas(projectDir);\n if (schemaPaths.length === 0) return [];\n\n const models: ExtractedType[] = [];\n for (const schemaPath of schemaPaths) {\n models.push(...parseSchema(await readFile(schemaPath, \"utf-8\"), schemaPath));\n }\n return models;\n}\n\nfunction parseSchema(content: string, schemaPath: string): ExtractedType[] {\n const models: ExtractedType[] = [];\n const modelRe = /^model\\s+(\\w+)\\s*\\{([^}]+)\\}/gm;\n let modelMatch;\n\n while ((modelMatch = modelRe.exec(content)) !== null) {\n const name = modelMatch[1]!;\n const body = modelMatch[2]!;\n const fields: ExtractedType[\"fields\"] = [];\n const lineOffset = content.slice(0, modelMatch.index).split(\"\\n\").length;\n\n for (const line of body.split(\"\\n\")) {\n const fieldMatch = /^\\s+(\\w+)\\s+(\\w+)(\\??)/.exec(line);\n if (!fieldMatch) continue;\n\n const fieldName = fieldMatch[1]!;\n const prismaType = fieldMatch[2]!;\n const optional = fieldMatch[3] === \"?\";\n\n // Skip relation fields (type references another model or is array)\n if (line.includes(\"@relation\") || prismaType.endsWith(\"[]\") || line.trim().endsWith(\"[]\"))\n continue;\n // Also skip if the type is not a known Prisma scalar (it's a relation)\n if (!PRISMA_TYPE_MAP[prismaType] && /^[A-Z]/.test(prismaType)) continue;\n\n const tsType = PRISMA_TYPE_MAP[prismaType] ?? prismaType.toLowerCase();\n fields.push({ name: fieldName, type: tsType, optional });\n }\n\n models.push({ name, fields, file: schemaPath, line: lineOffset });\n }\n\n return models;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ExtractedTest } from \"../types.js\";\n\n/**\n * Extract test descriptions from test files using ts-morph AST parsing.\n *\n * Scans all `.ts` and `.js` files in the given directory and extracts the first\n * string literal argument from `it()` and `test()` call expressions.\n *\n * @param projectDir - Root directory to scan (or fixtures dir in tests)\n * @param testsDir - Sub-directory to scan, relative to projectDir. Defaults to \".\"\n */\nexport async function extractTestDescriptions(\n projectDir: string,\n testsDir?: string,\n): Promise<ExtractedTest[]> {\n const scanDir = testsDir ? join(projectDir, testsDir) : projectDir;\n\n if (!existsSync(scanDir)) {\n return [];\n }\n\n // Lazy-load ts-morph so the package works without it installed.\n let tsMorph: typeof import(\"ts-morph\");\n try {\n tsMorph = await import(\"ts-morph\");\n } catch {\n throw new Error(\"ts-morph is required for test extraction. Install it: pnpm add -D ts-morph\");\n }\n\n const { Project, SyntaxKind } = tsMorph;\n\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n\n // Scan all .ts and .js files in the directory (caller is responsible for pointing\n // this at a tests directory, so all files are candidates).\n project.addSourceFilesAtPaths([\n join(scanDir, \"**/*.ts\"),\n join(scanDir, \"**/*.js\"),\n `!${join(scanDir, \"**/node_modules/**\")}`,\n ]);\n\n const tests: ExtractedTest[] = [];\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);\n\n for (const callExpr of callExpressions) {\n const expr = callExpr.getExpression();\n\n // We want bare `it(...)` and `test(...)` — identifiers only.\n if (expr.getKind() !== SyntaxKind.Identifier) continue;\n\n const calleeName = expr.asKindOrThrow(SyntaxKind.Identifier).getText();\n if (calleeName !== \"it\" && calleeName !== \"test\") continue;\n\n const args = callExpr.getArguments();\n if (args.length < 1) continue;\n\n const firstArg = args[0];\n if (!firstArg) continue;\n\n // First argument must be a string literal (the test description).\n if (firstArg.getKind() !== SyntaxKind.StringLiteral) continue;\n\n const description = firstArg.asKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();\n const lineNumber = sourceFile.getLineAndColumnAtPos(callExpr.getStart()).line;\n\n tests.push({\n description,\n file: filePath,\n line: lineNumber,\n });\n }\n }\n\n return tests;\n}\n","import type { Finding, SpecEndpoint, ExtractedRoute } from \"../types.js\";\n\nfunction normalisePath(path: string): string {\n return \"/\" + path.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\").replace(/\\/+/g, \"/\");\n}\n\nexport function matchRoutes(\n specEndpoints: SpecEndpoint[],\n codeRoutes: ExtractedRoute[],\n specId: string,\n): Finding[] {\n const findings: Finding[] = [];\n\n const codeSet = new Set(codeRoutes.map((r) => `${r.method} ${normalisePath(r.path)}`));\n const specSet = new Set(specEndpoints.map((e) => `${e.method} ${normalisePath(e.path)}`));\n\n // Missing: in spec but not code\n for (const endpoint of specEndpoints) {\n const key = `${endpoint.method} ${normalisePath(endpoint.path)}`;\n if (!codeSet.has(key)) {\n findings.push({\n type: \"missing\",\n category: \"route\",\n specId,\n specSection: \"Endpoints\",\n expected: key,\n severity: \"error\",\n suggestion: `Implement ${key} in your route handler`,\n });\n }\n }\n\n // Extra: in code but not spec\n for (const route of codeRoutes) {\n const key = `${route.method} ${normalisePath(route.path)}`;\n if (!specSet.has(key)) {\n findings.push({\n type: \"extra\",\n category: \"route\",\n specId,\n codeLocation: { file: route.file, line: route.line },\n expected: \"(not in spec)\",\n actual: key,\n severity: \"info\",\n suggestion: `Route ${key} exists in code but not in spec — add to spec if intentional`,\n });\n }\n }\n\n return findings;\n}\n","import type { Finding, SpecTypeDefinition, ExtractedType } from \"../types.js\";\n\nconst STRIP_SUFFIXES = [\"Schema\", \"Model\", \"Type\", \"Interface\", \"Entity\"];\n\nfunction normaliseTypeName(name: string): string {\n let normalised = name;\n for (const suffix of STRIP_SUFFIXES) {\n if (normalised.endsWith(suffix) && normalised.length > suffix.length) {\n normalised = normalised.slice(0, -suffix.length);\n break;\n }\n }\n return normalised.toLowerCase();\n}\n\nfunction findMatchingCodeType(\n specType: SpecTypeDefinition,\n codeTypes: ExtractedType[],\n): ExtractedType | undefined {\n const specNorm = normaliseTypeName(specType.name);\n return codeTypes.find((ct) => normaliseTypeName(ct.name) === specNorm);\n}\n\nexport function matchTypes(\n specTypes: SpecTypeDefinition[],\n codeTypes: ExtractedType[],\n specId: string,\n): Finding[] {\n const findings: Finding[] = [];\n\n for (const specType of specTypes) {\n const codeType = findMatchingCodeType(specType, codeTypes);\n\n if (!codeType) {\n findings.push({\n type: \"missing\",\n category: \"type\",\n specId,\n specSection: \"Data Models\",\n expected: `Type: ${specType.name}`,\n severity: \"error\",\n suggestion: `Implement type \"${specType.name}\" in code`,\n // The score's types denominator counts fields; an absent type must\n // subtract all of its fields, not 1, or a project that implements\n // nothing of an N-field model scores (N-1)/N.\n weight: specType.fields.length,\n });\n continue;\n }\n\n // Build a set of field names present in the code type\n const codeFieldNames = new Set(codeType.fields.map((f) => f.name));\n const specFieldNames = new Set(specType.fields.map((f) => f.name));\n\n // Missing fields: in spec but not in code\n for (const specField of specType.fields) {\n if (!codeFieldNames.has(specField.name)) {\n findings.push({\n type: \"missing\",\n category: \"type\",\n specId,\n specSection: \"Data Models\",\n codeLocation: { file: codeType.file, line: codeType.line },\n expected: `Field ${specType.name}.${specField.name} (${specField.type})`,\n severity: \"warn\",\n suggestion: `Add field \"${specField.name}: ${specField.type}\" to ${codeType.name}`,\n });\n }\n }\n\n // Extra fields: in code but not in spec\n for (const codeField of codeType.fields) {\n if (!specFieldNames.has(codeField.name)) {\n findings.push({\n type: \"extra\",\n category: \"type\",\n specId,\n specSection: \"Data Models\",\n codeLocation: { file: codeType.file, line: codeType.line },\n expected: \"(not in spec)\",\n actual: `Field ${codeType.name}.${codeField.name} (${codeField.type})`,\n severity: \"info\",\n suggestion: `Field \"${codeField.name}\" exists in code but not in spec — add to spec if intentional`,\n });\n }\n }\n }\n\n return findings;\n}\n","import type { Finding, SpecTestCase, ExtractedTest } from \"../types.js\";\n\n/** Jaccard similarity between two strings. Normalises to lowercase words. */\nfunction jaccard(a: string, b: string): number {\n const wordsA = new Set(\n a\n .toLowerCase()\n .replace(/[^\\w\\s]/g, \"\")\n .split(/\\s+/)\n .filter(Boolean),\n );\n const wordsB = new Set(\n b\n .toLowerCase()\n .replace(/[^\\w\\s]/g, \"\")\n .split(/\\s+/)\n .filter(Boolean),\n );\n const intersection = new Set([...wordsA].filter((w) => wordsB.has(w)));\n const union = new Set([...wordsA, ...wordsB]);\n if (union.size === 0) return 0;\n return intersection.size / union.size;\n}\n\nconst JACCARD_THRESHOLD = 0.4;\n\n/**\n * Match spec test cases against extracted code tests using Jaccard similarity.\n *\n * - Spec cases that have a code-test match above the threshold are considered covered.\n * - Unmatched spec cases produce a `missing` / `warn` Finding.\n * - Extra code tests (not matched to any spec case) are not reported.\n */\nexport function matchTests(\n specCases: SpecTestCase[],\n codeTests: ExtractedTest[],\n specId: string,\n): Finding[] {\n const findings: Finding[] = [];\n\n for (const specCase of specCases) {\n let bestScore = 0;\n let bestMatch: ExtractedTest | undefined;\n\n for (const codeTest of codeTests) {\n const score = jaccard(specCase.description, codeTest.description);\n if (score > bestScore) {\n bestScore = score;\n bestMatch = codeTest;\n }\n }\n\n if (bestScore < JACCARD_THRESHOLD || !bestMatch) {\n findings.push({\n type: \"missing\",\n category: \"test\",\n specId,\n specSection: specCase.section,\n // `expected` keeps the case ID so the finding can be traced back to a\n // line in the test plan; the suggestion is the test name to write, and\n // the spec's own label is no part of that.\n expected: specCase.id ? `${specCase.id}: ${specCase.description}` : specCase.description,\n severity: \"warn\",\n suggestion: `Add a test matching: \"${specCase.description}\"`,\n });\n }\n }\n\n return findings;\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ParsedSpec } from \"@specdx/core\";\nimport type { Finding } from \"./types.js\";\n\n/** A checkable artifact declared in a spec's `artifacts` frontmatter (issue #15). */\nexport interface ArtifactDecl {\n /** Project-root-relative file path that must exist. */\n path: string;\n /** Names that must be exported from the file. */\n exports?: string[];\n}\n\n/** Result of verifying declared artifacts against the project. */\nexport interface ArtifactCheckResult {\n findings: Finding[];\n /** Total artifact assertions considered (each path, plus each checkable export). */\n total: number;\n /** Assertions actually verified — equals `total`; skipped assertions are excluded, not passed. */\n checked: number;\n /** Declared-but-absent artifacts of specs not yet approved — planned, not missing (issue #17). */\n pending: number;\n notes: string[];\n}\n\n/**\n * Spec statuses at which declared artifacts must already exist.\n *\n * A spec is the plan for work that has not happened yet, so its artifacts are\n * enforceable only once it is approved. Before then a declared-but-absent file\n * is the expected state, not a defect (issue #17) — otherwise spec-first\n * authoring would fail the very gate the artifacts exist to feed.\n */\nconst ENFORCED_STATUSES = new Set([\"approved\"]);\n\n/** True when a spec's declared artifacts must exist for the check to pass. */\nexport function artifactsEnforced(status: unknown): boolean {\n return typeof status === \"string\" && ENFORCED_STATUSES.has(status);\n}\n\n/**\n * Read the `artifacts` frontmatter field defensively. Schema validation\n * reports malformed entries; here we simply skip anything unusable.\n */\nexport function parseArtifacts(spec: ParsedSpec): ArtifactDecl[] {\n const raw = spec.frontmatter.artifacts;\n if (!Array.isArray(raw)) return [];\n\n const out: ArtifactDecl[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\") continue;\n const decl = item as { path?: unknown; exports?: unknown };\n if (typeof decl.path !== \"string\" || decl.path.length === 0) continue;\n const exports = Array.isArray(decl.exports)\n ? decl.exports.filter((e): e is string => typeof e === \"string\" && e.length > 0)\n : undefined;\n out.push({ path: decl.path, exports });\n }\n return out;\n}\n\n/** Return the set of exported names from a source file, or null when ts-morph fails to parse. */\nasync function getExportedNames(filePath: string): Promise<Set<string> | null> {\n try {\n const { Project } = await import(\"ts-morph\");\n const project = new Project({\n skipAddingFilesFromTsConfig: true,\n compilerOptions: { allowJs: true },\n });\n const sourceFile = project.addSourceFileAtPath(filePath);\n return new Set(sourceFile.getExportedDeclarations().keys());\n } catch {\n return null;\n }\n}\n\n/**\n * Verify each spec's declared artifacts: files must exist, and named exports\n * must be present. Export checks need ts-morph; without it they are skipped\n * with a note and excluded from the totals — never counted as passed.\n */\nexport async function checkArtifacts(\n specs: ParsedSpec[],\n projectDir: string,\n tsMorphAvailable: boolean,\n): Promise<ArtifactCheckResult> {\n const findings: Finding[] = [];\n const notes: string[] = [];\n let total = 0;\n let pending = 0;\n let skippedExports = 0;\n\n for (const spec of specs) {\n const specId = String(spec.frontmatter.id);\n const status = spec.frontmatter.status;\n const enforced = artifactsEnforced(status);\n\n for (const artifact of parseArtifacts(spec)) {\n const absolute = join(projectDir, artifact.path);\n\n if (!existsSync(absolute)) {\n if (enforced) {\n total += 1;\n findings.push({\n type: \"missing\",\n category: \"artifact\",\n specId,\n expected: `file \"${artifact.path}\"`,\n severity: \"error\",\n suggestion: `Create ${artifact.path} or update the artifacts list in ${specId}.`,\n });\n } else {\n // Planned, not missing: excluded from the score rather than passed.\n pending += 1;\n findings.push({\n type: \"pending\",\n category: \"artifact\",\n specId,\n expected: `file \"${artifact.path}\"`,\n severity: \"info\",\n suggestion: `planned by ${specId} (status: ${String(status)}) — not yet implemented; enforced once the spec is approved.`,\n });\n }\n // Export assertions for an absent file are not separately counted.\n continue;\n }\n\n // The file exists, so it is a real assertion regardless of spec status.\n total += 1;\n\n if (!artifact.exports || artifact.exports.length === 0) continue;\n\n if (!tsMorphAvailable) {\n skippedExports += artifact.exports.length;\n continue;\n }\n\n const exported = await getExportedNames(absolute);\n if (exported === null) {\n skippedExports += artifact.exports.length;\n continue;\n }\n\n for (const name of artifact.exports) {\n // An export that exists is a verified assertion whatever the status.\n if (exported.has(name)) {\n total += 1;\n continue;\n }\n\n // An absent export follows the same status rule as an absent file: a\n // spec that is not yet approved is planning it, not missing it (#19).\n if (enforced) {\n total += 1;\n findings.push({\n type: \"missing\",\n category: \"artifact\",\n specId,\n codeLocation: { file: artifact.path, line: 1 },\n expected: `export \"${name}\" from ${artifact.path}`,\n severity: \"error\",\n suggestion: `Export ${name} from ${artifact.path} or update the artifacts list in ${specId}.`,\n });\n } else {\n pending += 1;\n findings.push({\n type: \"pending\",\n category: \"artifact\",\n specId,\n codeLocation: { file: artifact.path, line: 1 },\n expected: `export \"${name}\" from ${artifact.path}`,\n severity: \"info\",\n suggestion: `planned by ${specId} (status: ${String(status)}) — not yet implemented; enforced once the spec is approved.`,\n });\n }\n }\n }\n }\n\n if (skippedExports > 0) {\n notes.push(\n `artifact export checks skipped for ${skippedExports} export(s): ts-morph is not available or the file could not be parsed.`,\n );\n }\n\n if (pending > 0) {\n notes.push(\n `${pending} declared artifact assertion(s) pending: files or exports planned by specs that are not yet approved. They are excluded from the score and become enforceable when the spec status changes to approved.`,\n );\n }\n\n return { findings, total, checked: total, pending, notes };\n}\n","import type { Finding, ImplementationScore } from \"./types.js\";\n\ninterface SpecTotals {\n routes: number;\n types: number;\n tests: number;\n artifacts: number;\n}\n\nexport function computeScore(findings: Finding[], totals: SpecTotals): ImplementationScore {\n // Count missing findings per category (only \"missing\" and \"mismatch\" reduce the score, not \"extra\")\n const missingByCategory: Record<string, number> = { route: 0, type: 0, test: 0, artifact: 0 };\n\n for (const f of findings) {\n if (f.type === \"missing\" || f.type === \"mismatch\") {\n // A finding subtracts its weight in the category's own units (fields\n // for types); unweighted findings subtract 1.\n missingByCategory[f.category] = (missingByCategory[f.category] ?? 0) + (f.weight ?? 1);\n }\n }\n\n const categoryMap: Record<string, { total: number; categoryKey: string }> = {\n routes: { total: totals.routes, categoryKey: \"route\" },\n types: { total: totals.types, categoryKey: \"type\" },\n tests: { total: totals.tests, categoryKey: \"test\" },\n artifacts: { total: totals.artifacts, categoryKey: \"artifact\" },\n };\n\n const byCategory: Record<string, { matched: number; total: number }> = {};\n let totalItems = 0;\n let totalMatched = 0;\n\n for (const [name, { total, categoryKey }] of Object.entries(categoryMap)) {\n const missing = missingByCategory[categoryKey] ?? 0;\n const matched = Math.max(0, total - missing);\n byCategory[name] = { matched, total };\n totalItems += total;\n totalMatched += matched;\n }\n\n // Nothing checkable is \"not assessed\", never a vacuous 100% pass (issue #6)\n if (totalItems === 0) {\n return { overall: 0, assessed: false, byCategory };\n }\n\n const overall = Math.round((totalMatched / totalItems) * 100);\n return { overall, assessed: true, byCategory };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\ntype DetectedFramework = \"express\" | \"hono\" | \"nextjs\";\n\nconst FRAMEWORK_PACKAGES: [string, DetectedFramework][] = [\n [\"express\", \"express\"],\n [\"hono\", \"hono\"],\n [\"next\", \"nextjs\"],\n];\n\nexport async function detectFramework(projectDir: string): Promise<DetectedFramework | null> {\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n try {\n const content = await readFile(join(projectDir, \"package.json\"), \"utf-8\");\n pkg = JSON.parse(content);\n } catch {\n return null;\n }\n\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n\n for (const [pkgName, framework] of FRAMEWORK_PACKAGES) {\n if (pkgName in allDeps) {\n return framework;\n }\n }\n\n return null;\n}\n","import type { Finding, AiAssessment, AiCheckResult } from \"./types.js\";\n\nexport async function analyzeWithAi(findings: Finding[], context: string): Promise<AiCheckResult> {\n const apiKey = process.env[\"ANTHROPIC_API_KEY\"];\n if (!apiKey) {\n throw new Error(\n \"ANTHROPIC_API_KEY environment variable is required for --ai mode. \" +\n \"Set it or use the specdx-verify skill instead (no API key needed).\",\n );\n }\n\n if (findings.length === 0) {\n return { findings, assessments: [], summary: \"No findings to analyze.\" };\n }\n\n let Anthropic: typeof import(\"@anthropic-ai/sdk\").default;\n try {\n const mod = await import(\"@anthropic-ai/sdk\");\n Anthropic = mod.default;\n } catch {\n throw new Error(\n \"@anthropic-ai/sdk is required for --ai mode. Install it: pnpm add -D @anthropic-ai/sdk\",\n );\n }\n\n const client = new Anthropic({ apiKey });\n\n const findingsSummary = findings\n .map(\n (f, i) =>\n `[${i}] ${f.type} (${f.severity}): ${f.expected}${f.actual ? ` — actual: ${f.actual}` : \"\"}${f.suggestion ? ` — suggestion: ${f.suggestion}` : \"\"}`,\n )\n .join(\"\\n\");\n\n const prompt = `You are reviewing static analysis findings from a spec-to-implementation check.\n\nContext: ${context}\n\nFindings:\n${findingsSummary}\n\nFor each finding (by index), assess:\n1. Is this a real issue or a false positive?\n2. How confident are you? (high/medium/low)\n3. Brief reasoning (1-2 sentences)\n4. Suggested fix if it's a real issue\n\nRespond with a JSON array of objects:\n[{ \"findingIndex\": 0, \"isRealIssue\": true, \"confidence\": \"high\", \"reasoning\": \"...\", \"suggestedFix\": \"...\" }]\n\nOnly output the JSON array, no other text.`;\n\n const response = await client.messages.create({\n model: \"claude-sonnet-4-20250514\",\n max_tokens: 4000,\n messages: [{ role: \"user\", content: prompt }],\n });\n\n const text = response.content[0]?.type === \"text\" ? response.content[0].text : \"\";\n\n let assessments: AiAssessment[];\n try {\n assessments = JSON.parse(text);\n } catch {\n assessments = [];\n }\n\n const realIssues = assessments.filter((a) => a.isRealIssue).length;\n const falsePositives = assessments.filter((a) => !a.isRealIssue).length;\n const summary = `AI analysis: ${realIssues} real issues, ${falsePositives} false positives out of ${findings.length} findings`;\n\n return { findings, assessments, summary };\n}\n"],"mappings":";AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,QAAAC,cAAY;;;ACKrB,SAAS,eAAe,SAAiB,SAAe;AAEtD,QAAM,iBAAiB,IAAI,OAAO,UAAU,YAAY,OAAO,CAAC,SAAS,IAAI;AAC7E,QAAM,QAAQ,eAAe,KAAK,OAAO;AACzC,MAAI,CAAC;AAAO,WAAO;AAEnB,QAAM,QAAQ,MAAM,QAAQ,MAAM,CAAC,EAAE;AACrC,QAAM,OAAO,QAAQ,MAAM,KAAK;AAGhC,QAAM,cAAc,UAAU,KAAK,IAAI;AACvC,SAAO,cAAc,KAAK,MAAM,GAAG,YAAY,KAAK,IAAI;AAC1D;AAEA,SAAS,YAAY,KAAW;AAC9B,SAAO,IAAI,QAAQ,uBAAuB,MAAM;AAClD;AAEA,IAAM,eAAoC,oBAAI,IAAI,CAAC,OAAO,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAM3F,SAAS,WAAW,MAAY;AAC9B,UAAQ,KAAK,MAAM,4BAA4B,KAAK,CAAA,GAAI,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC/E;AAOM,SAAU,oBAAoB,SAAe;AACjD,SAAO,eA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EAClB,QAAQ;AACN,UAAM,IAAI,MACR,wFAAwF;EAE5F;AAEA,QAAM,SAAS,IAAI,UAAU,EAAE,OAAM,CAAE;AAEvC,QAAM,kBAAkB,SACrB,IACC,CAAC,GAAG,MACF,IAAI,CAAC,KAAK,EAAE,IAAI,KAAK,EAAE,QAAQ,MAAM,EAAE,QAAQ,GAAG,EAAE,SAAS,mBAAc,EAAE,MAAM,KAAK,EAAE,GAAG,EAAE,aAAa,uBAAkB,EAAE,UAAU,KAAK,EAAE,EAAE,EAEtJ,KAAK,IAAI;AAEZ,QAAM,SAAS;;WAEN,OAAO;;;EAGhB,eAAe;;;;;;;;;;;;AAaf,QAAM,WAAW,MAAM,OAAO,SAAS,OAAO;IAC5C,OAAO;IACP,YAAY;IACZ,UAAU,CAAC,EAAE,MAAM,QAAQ,SAAS,OAAM,CAAE;GAC7C;AAED,QAAM,OAAO,SAAS,QAAQ,CAAC,GAAG,SAAS,SAAS,SAAS,QAAQ,CAAC,EAAE,OAAO;AAE/E,MAAI;AACJ,MAAI;AACF,kBAAc,KAAK,MAAM,IAAI;EAC/B,QAAQ;AACN,kBAAc,CAAA;EAChB;AAEA,QAAM,aAAa,YAAY,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE;AAC5D,QAAM,iBAAiB,YAAY,OAAO,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE;AACjE,QAAM,UAAU,gBAAgB,UAAU,iBAAiB,cAAc,2BAA2B,SAAS,MAAM;AAEnH,SAAO,EAAE,UAAU,aAAa,QAAO;AACzC;","names":["readFile","join","HTTP_METHODS","existsSync","join","HTTP_METHODS","existsSync","join","HTTP_METHODS","existsSync","join","existsSync","join","readdir","join","existsSync","join","existsSync","join","readFile","join","readFile","join"]}
|