Skip to content

Commit 97b950d

Browse files
authored
feat: validate reports against their schema before rendering (#42)
* feat: validate reports against their schema before rendering * fix: tighten report validation and its failure messages * fix: validate reports in the renderer so every render path is checked * fix: detect shop and aeo from content and let refusals finish writing
1 parent ceb40c6 commit 97b950d

13 files changed

Lines changed: 445 additions & 22 deletions

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,5 @@ jobs:
1616
- uses: actions/setup-node@v4
1717
with:
1818
node-version: 24
19+
- run: npm ci
1920
- run: node --test "tests/*.test.js"

‎CLAUDE.md‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@ kosh is a Claude Code plugin that runs functional, performance, accessibility, s
44

55
## Commands
66

7-
No build step and no root `package.json` — the scripts are plain `node` and `bash`. `evals/` has its own `package.json` for promptfoo.
7+
No build step — the scripts are plain `node` and `bash`. The root `package.json` has one dependency, `ajv`, for report validation; `evals/` has its own `package.json` for promptfoo. Install with `npm ci`, which never rewrites the committed lockfile — a rewritten one would block the user's next `git pull`. `npm install <pkg>` is only for adding a dependency.
88

99
```bash
10+
npm ci # once after cloning, and after any pull
1011
claude --plugin-dir . # launch Claude Code with the plugin loaded
1112
```
1213

@@ -24,13 +25,15 @@ Render a report to self-contained HTML:
2425

2526
```bash
2627
scripts/run-qa-report.sh reports/data/qa-report-functional.json # type from filename
27-
scripts/run-qa-report.sh reports/data/qa-report-aeo.json --aeo # aeo has no filename detection
28-
node scripts/generate-report.js reports/data/qa-report-aeo.json # renderer only, skips the stamp and the archive
28+
scripts/run-qa-report.sh reports/data/qa-report-aeo.json --aeo # aeo comes from the flag or mode: "aeo"
29+
node scripts/generate-report.js reports/data/qa-report-aeo.json # renderer only: validates, skips the stamp and the archive
2930
scripts/merge-qa-reports.sh # or /kosh:merge
30-
node --test "tests/*.test.js" # script, snippet, JSON-file and schema-drift tests, no dependencies
31+
node --test "tests/*.test.js" # script, snippet, JSON-file, schema-drift and validation tests
3132
```
3233

33-
`.github/workflows/ci.yml` runs that same `node --test` line on every PR and on pushes to `trunk` — no install, no API calls. The promptfoo evals stay manual because they cost money.
34+
`.github/workflows/ci.yml` runs `npm ci` and that same `node --test` line on every PR and on pushes to `trunk` — no API calls. The promptfoo evals stay manual because they cost money.
35+
36+
`generate-report.js` validates the report against its schema (`scripts/validate-report.js`, ajv) before rendering, so the check runs on every render path: `run-qa-report.sh`, the merge, and a direct call. A report that doesn't match is refused — nothing is rendered or archived, and ajv's errors name each field, so the skill that wrote the JSON can fix it and re-run. `run-qa-report.sh` stamps provenance first, so a refused report comes back stamped with its own fields untouched. The types checked are the flagged ones plus any the content shows — `mode: "aeo"` or a `shop` block — so leaving a flag out or passing the wrong one doesn't skip the check. Only a schema file that declares `$schema` is validated — shop and aeo today; functional, performance and accessibility, and so the merged report, are still example documents and pass through with a note. Schemas must compile in ajv strict mode. `node scripts/generate-report.js <json> --skip-validation` renders without the check, which is how to re-render an archived report in an older shape; it's a renderer flag, not a `run-qa-report.sh` one, since the wrapper would also re-stamp and re-archive.
3437

3538
`run-qa-report.sh` stamps a `provenance` block into the source JSON before rendering: the skill writes `provenance.model` (self-reported), and `scripts/stamp-provenance.js` adds `pluginVersion`, a SHA-256 of each skill directory (references included), and a `seal` over those plus the report's `timestamp`. A valid seal means the block is never restamped, so re-rendering an archived run keeps the provenance of the run that produced it; a model-invented or copied-forward block fails the seal and is restamped. The seal is an unkeyed hash, so it guards against accidents, not deliberate tampering — anything with a shell can recompute it. A report with no `provenance` block at all is left untouched with a warning — it predates the feature, or the skill skipped `provenance.model`. The renderer prints the block as one footer line, and nothing for reports that predate it. The merged report carries no provenance — its JSON is a temp file that is deleted after rendering.
3639

@@ -42,7 +45,7 @@ The renderer inlines each finding's screenshots as base64, because every run sha
4245

4346
Merging requires all three of functional, performance, and accessibility; shop and AEO reports are standalone. Prefer `/kosh:merge` over calling the script — it reports which JSON files are missing up front, where the script exits on the first one it can't find.
4447

45-
`run-qa-report.sh` has no aeo branch in its filename detection, so the AEO skill passes `--aeo` explicitly; without it the renderer's own dispatch routes on `mode: "aeo"` in the JSON. An AEO-shaped report missing that field is a hard error, not a fallback.
48+
With no flag, `run-qa-report.sh` takes the test type from the filename, and for AEO from `mode: "aeo"` in the JSON, so validation, the stamp and the renderer all get `--aeo` even when the skill forgets to pass it. A report with neither is rendered with a "not validated" note. An AEO-shaped report missing `mode` is a hard error in the renderer, not a fallback.
4649

4750
## How it works
4851

@@ -57,7 +60,7 @@ schemas/ → JSON schemas that define report structure
5760
scripts/ → report generation and merge scripts
5861
hooks/ → session hooks (e.g., create reports/data/ on startup)
5962
evals/ → promptfoo regression checks for skill decision rules (evals/README.md)
60-
tests/ → `node --test` checks for the scripts, skill-embedded snippets, tracked JSON files and skill ↔ schema drift, no dependencies
63+
tests/ → `node --test` checks for the scripts, skill-embedded snippets, tracked JSON files, skill ↔ schema drift and report validation
6164
docs/ → user-facing guides (getting-started.md)
6265
.github/ → the CI workflow (runs tests/ on every PR)
6366
.mcp.json → Playwright MCP server configuration

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Each test visits 4–6+ pages, simulates real user behavior, and outputs a struc
2121
```bash
2222
git clone https://github.com/a8cteam51/kosh.git
2323
cd kosh
24+
npm ci
2425
claude --plugin-dir .
2526
```
2627

‎docs/getting-started.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,16 @@ cd kosh
3434

3535
If you don't have it yet, you can install it with `brew install gh` and then run `gh auth login` to sign in.
3636

37+
### Install the report tools
38+
39+
Still inside the `kosh` folder, run:
40+
41+
```bash
42+
npm ci
43+
```
44+
45+
This installs the one library kosh uses to check each report's JSON before turning it into HTML. Run it again whenever you pull an update.
46+
3747
## Step 2: Start Claude Code with the plugin
3848

3949
From inside the `kosh` folder, run:

‎hooks/hooks.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
},
1010
{
1111
"type": "command",
12-
"command": "cd ${CLAUDE_PLUGIN_ROOT} && git fetch origin --quiet 2>/dev/null && BEHIND=$(git rev-list HEAD..@{u} --count 2>/dev/null) && [ \"${BEHIND:-0}\" -gt 0 ] && echo \"kosh has ${BEHIND} update(s) available — run: git pull\" || true"
12+
"command": "cd ${CLAUDE_PLUGIN_ROOT} && git fetch origin --quiet 2>/dev/null && BEHIND=$(git rev-list HEAD..@{u} --count 2>/dev/null) && [ \"${BEHIND:-0}\" -gt 0 ] && echo \"kosh has ${BEHIND} update(s) available — run: git pull && npm ci\" || true"
1313
}
1414
]
1515
}

‎package-lock.json‎

Lines changed: 66 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"name": "kosh",
3+
"private": true,
4+
"dependencies": {
5+
"ajv": "^8.20.0"
6+
}
7+
}

‎schemas/qa-report-aeo-schema.json‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -371,35 +371,35 @@
371371
"criterionSignalPairing": {
372372
"description": "Discriminated union enforcing that the criterion + signal pair belongs together. Each variant fixes the criterion key and restricts the signal to that criterion's canonical subset, so `{ criterion: 'llmsTxt', signal: 'canonicalUrls' }` fails validation instead of rendering as a nonsense finding. Used by both `issue` and `actionablePrompt` via `allOf`.",
373373
"oneOf": [
374-
{ "properties": {
374+
{ "type": "object", "properties": {
375375
"criterion": { "const": "technicalHealth" },
376376
"signal": { "enum": ["robotsAndCrawlerAccess", "noNoindex", "httpsNoMixedContent", "sitemapLastmod", "nojsAccessible", "canonicalUrls"] }
377377
} },
378-
{ "properties": {
378+
{ "type": "object", "properties": {
379379
"criterion": { "const": "structuredData" },
380380
"signal": { "enum": ["organizationSchema", "primaryEntitySchema", "faqSchema", "relevantSchemasApplied", "jsonLdFormat", "openGraphTags", "reviewSchema"] }
381381
} },
382-
{ "properties": {
382+
{ "type": "object", "properties": {
383383
"criterion": { "const": "aeoReadiness" },
384384
"signal": { "enum": ["directAnswers", "whoWhatWho", "featuredSnippetStructure", "answerCapsules", "faqSectionPresent", "faqSchemaApplied", "questionFramedHeadings", "titleAndMetaQuestionMatch"] }
385385
} },
386-
{ "properties": {
386+
{ "type": "object", "properties": {
387387
"criterion": { "const": "eeatSignals" },
388388
"signal": { "enum": ["namedTeamMembers", "authorCredentials", "authorBylines", "demonstratedExpertise", "externalCitations", "certificationBadges", "namedExternalRelationships", "tenureIndicators"] }
389389
} },
390-
{ "properties": {
390+
{ "type": "object", "properties": {
391391
"criterion": { "const": "contentFreshness" },
392392
"signal": { "enum": ["copyrightYearCurrent", "blogNewsRecent", "dateStampsOnContent", "contentUpdateRecency", "sitemapLastmodRecent", "recentFeaturedWork", "currentDomainReferences"] }
393393
} },
394-
{ "properties": {
394+
{ "type": "object", "properties": {
395395
"criterion": { "const": "entityClarity" },
396396
"signal": { "enum": ["entityIdentifiable", "primaryFocusSpecificity", "socialProfileLinks", "geographicMarketClarity", "consistentIdentity"] }
397397
} },
398-
{ "properties": {
398+
{ "type": "object", "properties": {
399399
"criterion": { "const": "contentSpecificity" },
400400
"signal": { "enum": ["primaryOfferingDetail", "namedSpecificEntities", "namedSubjectAreas", "specificOutcomes", "passageExtractionQuality"] }
401401
} },
402-
{ "properties": {
402+
{ "type": "object", "properties": {
403403
"criterion": { "const": "llmsTxt" },
404404
"signal": { "enum": ["llmsTxtPresent", "llmsFullTxtPresent", "llmsTxtContent"] }
405405
} }

‎scripts/generate-report.js‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
* severity, collapsible sections, and inline screenshots when findings reference them.
99
*
1010
* Usage:
11-
* node generate-report.js <json-file> [--functional|--performance|--accessibility|--shop|--aeo]
11+
* node generate-report.js <json-file> [--functional|--performance|--accessibility|--shop|--aeo] [--skip-validation]
1212
*
1313
* AEO reports are auto-detected from `report.mode === "aeo"`; --aeo forces the
1414
* AEO branch explicitly. The test-type flag affects the output filename.
@@ -19,12 +19,13 @@
1919
const fs = require('fs');
2020
const path = require('path');
2121
const { describeProvenance } = require('./stamp-provenance.js');
22+
const { checkReport, typesFor } = require('./validate-report.js');
2223

2324
const inputFile = process.argv[2];
2425
const args = process.argv.slice(3);
2526

2627
if (!inputFile) {
27-
console.error('Usage: node generate-report.js <report.json> [--functional|--performance|--accessibility|--shop|--aeo]');
28+
console.error('Usage: node generate-report.js <report.json> [--functional|--performance|--accessibility|--shop|--aeo] [--skip-validation]');
2829
process.exit(1);
2930
}
3031

@@ -140,9 +141,14 @@ if (looksLikeAeo && qaFlagSet) {
140141
process.exit(1);
141142
}
142143
if (looksLikeAeo && !modeIsAeo) {
143-
console.error('Error: report has AEO-shaped `criteria` but is missing `mode: "aeo"`. Add the field or pass --aeo to force.');
144+
console.error('Error: report has AEO-shaped `criteria` but is missing `mode: "aeo"`. Add the field and re-run.');
144145
process.exit(1);
145146
}
147+
// process.exit would cut off a long refusal still being written to a pipe; a top-level return lets it drain.
148+
if (!args.includes('--skip-validation') && !checkReport(report, inputFile, typesFor(args, report))) {
149+
process.exitCode = 1;
150+
return;
151+
}
146152
if (modeIsAeo || aeoFlagSet) {
147153
renderAeoReport(report, inputFile, testTypeLabel);
148154
process.exit(0);

‎scripts/run-qa-report.sh‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
# ./run-qa-report.sh qa-report-shop.json --shop
1212
# ./run-qa-report.sh qa-report.json --performance
1313
# ./run-qa-report.sh qa-report.json --functional --performance --accessibility
14-
# ./run-qa-report.sh qa-report.json (auto-detects test type from filename)
14+
# ./run-qa-report.sh qa-report.json (auto-detects test type from filename, or aeo from "mode": "aeo")
1515

1616
set -e # Exit on any error
1717

@@ -55,8 +55,8 @@ fi
5555

5656
# Step 2: Extract metadata from JSON
5757
echo -e "${BLUE}Step 2: Extracting metadata from JSON...${NC}"
58-
WEBSITE_NAME=$(node -e "console.log(require('fs').readFileSync('$QA_REPORT_JSON', 'utf8').split('\"websiteName\": \"')[1].split('\"')[0])")
59-
TIMESTAMP=$(node -e "console.log(require('fs').readFileSync('$QA_REPORT_JSON', 'utf8').split('\"timestamp\": \"')[1].split('\"')[0])")
58+
WEBSITE_NAME=$(node -p "JSON.parse(require('fs').readFileSync('$QA_REPORT_JSON', 'utf8')).websiteName ?? ''")
59+
TIMESTAMP=$(node -p "JSON.parse(require('fs').readFileSync('$QA_REPORT_JSON', 'utf8')).timestamp ?? ''")
6060
echo -e "${GREEN} Website: $WEBSITE_NAME${NC}"
6161
echo -e "${GREEN} Timestamp: $TIMESTAMP${NC}"
6262

@@ -74,6 +74,8 @@ if [ -z "$TEST_TYPE_FLAGS" ]; then
7474
TEST_TYPE_FLAGS="--accessibility"
7575
elif [[ "$BASENAME" == *"shop"* ]]; then
7676
TEST_TYPE_FLAGS="--shop"
77+
elif [ "$(node -p "JSON.parse(require('fs').readFileSync('$QA_REPORT_JSON', 'utf8')).mode")" = "aeo" ]; then
78+
TEST_TYPE_FLAGS="--aeo"
7779
fi
7880
fi
7981

0 commit comments

Comments
 (0)