Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ jobs:
'

- name: Generate tests (resource/method/functional|contract|scenarios) and run them once
run: npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --scenarios demo-api/scenarios.json --allow-write --run -o reports/generate --fail-on never
run: npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --deps demo-api/deps.json --fixtures demo-api/fixtures/approved --scenarios demo-api/scenarios.json --allow-write --run -o reports/generate --fail-on never

- name: Self-check - generated suite fails only on the known defect
run: |
Expand Down Expand Up @@ -103,7 +103,7 @@ jobs:
- name: Generate Python tests (pytest + requests) and run them once
run: |
pip install pytest requests jsonschema
npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --scenarios demo-api/scenarios.json --allow-write --run --lang python --tests-dir tests/api-python -o reports/generate-python --fail-on never
npx tsx src/cli.ts generate demo-api/openapi.yaml -u http://localhost:3100 --deps demo-api/deps.json --fixtures demo-api/fixtures/approved --scenarios demo-api/scenarios.json --allow-write --run --lang python --tests-dir tests/api-python -o reports/generate-python --fail-on never
node -e '
const r = require("./reports/generate-python/report.json");
const bad = r.generated.scenarios.filter(s => s.status === "CONTRACT_MISMATCH" || s.status === "TEST_FAILURE").map(s => s.name);
Expand All @@ -122,6 +122,22 @@ jobs:
npx tsx src/cli.ts registry validate tests/api-python/_support/cases.json --spec demo-api/openapi.yaml --require-spec > /dev/null
npx tsx src/cli.ts manifest validate --tests-dir tests/api-python

- name: Fault injection - the collection tests must catch every injected defect (TS and Python)
# The demo API runs once per DEMO_FAULT (ignored filter, wrong sort, hidden record, duplicates, wrong field,
# overlapping pages) on its own port: clean without a fault, at least one failure with each.
run: |
npx tsx scripts/mutation-check.ts --lang typescript --port 3200 tests/api/items/get
npx tsx scripts/mutation-check.ts --lang python --port 3300 tests/api-python/items/get
node -e '
for (const l of ["typescript", "python"]) { const r = require("./reports/mutation-" + l + ".json"); console.log(l, r.detected + "/" + r.injected); if (r.detected !== r.injected) process.exit(1); }
'

- name: Maintenance - a spec change is regenerated, validated and summarized (no PR in CI)
run: |
sed 's/enum: \[name, -name, price, -price\]/enum: [name, -name, price]/' demo-api/openapi.yaml > reports/openapi.changed.yaml
npx tsx src/cli.ts maintain reports/openapi.changed.yaml --base demo-api/openapi.yaml --deps demo-api/deps.json --tests-dir tests/api -o reports/maintain
grep -q 'sort value "-price" is not documented' reports/maintain/maintenance-summary.md

- name: Analyse the legacy example project (init + run)
working-directory: examples/legacy-project
run: |
Expand Down
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@

## Unreleased

- **Collection testing** (docs/SUPPORT_MATRIX.md, "Collections"):
- reviewed deps `collection` mapping, checked strictly against the spec (`INVALID_REVIEWED_CONFIG` gap on a mismatch);
- strategy A (create & verify): controlled datasets with a unique marker in an isolating filter, cleanup in `finally`; strategy C (read-only) with explicit skips; strategy recorded per list operation in `coverage-gaps.json`;
- assertions in TypeScript and Python alike: contains / not contains, persisted fields by policy (exact, tolerance, schema, ignore), all match a filter, unique by, sorted by, page size, no duplicates across pages; offset and page/size paging; bounded polling for documented eventual consistency;
- create → list → update → list → delete → list scenario on the list operation;
- case ID vocabulary v3: `collection-contains`, `filter`, `sort`, `pagination`, `unique`, `fixture`.
- **Approved fixtures (strategy B):** `generate --fixtures <dir>` compares a list with `<operationId>.json` approved by a person; `fixtures capture` writes candidates only; `fixtures refresh --draft-pr` proposes a changed candidate in one Draft PR per operation (updated, never duplicated). Approved files are never written by the agent.
- **`maintain`:** spec diff → deterministic regeneration → registry and manifest validation → one Draft PR per suite with a summary (changed operations, files and cases, expectations old → new, fixtures, stale reviewed configuration, gaps before → after). Never merges; no PR when validation fails or nothing changed.
- **Fault injection:** the demo API simulates six list defects (`DEMO_FAULT`); `scripts/mutation-check.ts` runs a generated suite against each, and CI requires 6/6 detected in TypeScript and Python. The previous generator detected 0/6.
- Demo API: `offset`, `tag` and `sort` on `GET /items`; two reference items tagged `catalog` (the approved demo fixture).
- **Shared environments (found on Toolshop):** `"strategy": "read-only"` in a collection mapping; page-number paging with a fixed page size; read-only checks of a public list go through `publicApi` (no login); read-only filter tests take up to 5 values from the list and require the filtered result to be a subset of the unfiltered list, which catches the rental leak of Toolshop's defective build; a `sort` case ID may carry a reviewed value the spec does not enumerate.
- **Test account `auto`:** `API_TEST_ACCOUNT=auto` / `--test-account auto` uses the `.env` account and registers a new one only when it is missing or refused (401 / 403 / 422), e.g. after Toolshop reset its data; the agent registers once before `--run` and the generated tests reuse that account; with the generated `_support/global-setup.ts` as Playwright's `globalSetup` (added by `init`), a standalone run decides once in the main process, so a run registers at most one account even when Playwright restarts workers after failures; without it, at most one per worker. `.env` is never changed. Python suites (conftest) support `new` and `auto` too, with at most one registration per pytest session.
- Fixes: a GET of a single resource with an array field is no longer reported as an unconfigured collection; hand-written `_support/api/*Api.ts` stay in the generation manifest after the first run.

- **Coverage completeness** (see docs/SUPPORT_MATRIX.md):
- one physical test → one stable case ID (vocabulary v2: `accepted-value`, `invalid-credentials`, `method-not-allowed`, `precondition-failed`), checked on the real run (Playwright report, pytest collection); cases no longer generated become tombstones;
- recursive request-body negative cases at any depth, exactly one broken rule each (verified with ajv), configurable limit `--max-cases` with dropped cases reported;
Expand Down
30 changes: 26 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,29 @@ Coverage is reported, never implied. The full keyword-by-keyword table is in [do
- responses: status, Content-Type, headers, JSON / text schema, no body where none is documented, writeOnly;
- documented errors with a safe trigger: 400 / 422, 401 (missing and invalid credentials), 404, 405 (GET only), 412, 415.

**Needs your confirmation (deps or scenarios file):** CRUD chains and cleanup, 409 conflicts (`conflictOn`), fields a create returns as sent (`echoes`), values taken from existing data (`fill`), and every business flow (`--scenarios`): state transitions, parent → child, login / refresh, list / search / pagination.
**Needs your confirmation (deps or scenarios file):** CRUD chains and cleanup, 409 conflicts (`conflictOn`), fields a create returns as sent (`echoes`), values taken from existing data (`fill`), collection semantics (`collection`: identifier, persisted fields and their comparison policy, filters, sorts, paging, uniqueness, eventual consistency), approved fixtures (`--fixtures`), and every other business flow (`--scenarios`): state transitions, parent → child, login / refresh.

**Never generated (reported as gaps):** 403 without a reviewed role setup, 429, a 405 that would need an unsafe method, oneOf / anyOf branches other than the one sent, rules that cannot be broken without breaking another, media types other than JSON / text, and anything the spec does not state.

## Collections, fixtures and maintenance

The number of tests is not the goal; catching defects is. On the demo API the previous generator's 65 tests miss all six injected list defects (ignored filter, wrong sort, hidden record, duplicates, wrong field value, overlapping pages); the collection tests catch all six, in TypeScript and Python (`npx tsx scripts/mutation-check.ts tests/api/items/get`).

```bash
# Deep list tests from a reviewed "collection" mapping (demo-api/deps.json) and approved fixtures
npx tsx src/cli.ts generate demo-api/openapi.yaml --deps demo-api/deps.json --fixtures demo-api/fixtures/approved

# Fixtures are never trusted automatically: capture writes a candidate, refresh proposes it in a Draft PR
npx tsx src/cli.ts fixtures capture demo-api/openapi.yaml --operation listItems -u http://localhost:3100 --query tag=catalog
npx tsx src/cli.ts fixtures refresh demo-api/openapi.yaml --operation listItems -u http://localhost:3100 --draft-pr

# After a spec change: diff → regenerate → validate → one Draft PR per suite (updated, never duplicated, never merged)
npx tsx src/cli.ts maintain openapi.yaml --base <old spec> --deps deps.json --draft-pr
```

Collection tests create their own records with a unique marker, read them through an isolating filter, and remove them in `finally`; without a confirmed create they run read-only on existing data and skip with the reason when there is not enough. Strategy and reasons per list operation are in `coverage-gaps.json`. Details: [docs/SUPPORT_MATRIX.md](docs/SUPPORT_MATRIX.md#collections-srcgeneratecollectionts-srcfixtures).


## Options

| Option | Default | |
Expand All @@ -158,7 +177,7 @@ Coverage is reported, never implied. The full keyword-by-keyword table is in [do
| `--max-requests`, `--rps`, `--timeout` | 100, 5, 10s | probe budget and limits |
| `--max-examples`, `--max-time`, `--seed` | 25, 120s, 42 | Schemathesis budget, reproducible seed |
| `--fail-on` | `mismatch` | `mismatch` / `blocked` / `never` |
| `--deps`, `--tests-dir`, `--run`, `--draft-pr` | | `generate` only |
| `--deps`, `--fixtures`, `--tests-dir`, `--run`, `--draft-pr` | | `generate` only |

Credentials: `API_TOKEN` (bearer / OAuth2 / OIDC), `API_USER` + `API_PASSWORD` (basic), `API_KEY` (apiKey header or query).

Expand All @@ -168,15 +187,18 @@ Credentials: `API_TOKEN` (bearer / OAuth2 / OIDC), `API_USER` + `API_PASSWORD` (
src/spec/ load, bundle, validate (swagger-parser), lint (Redocly), operation catalogue
src/audit/ SafeClient, probe, Schemathesis runner + JUnit/JSON parsing, auth + redaction
src/contract/ response validator (Ajv), copied verbatim into generated suites
src/generate/ dependency graph, deterministic payloads, Playwright templates, runner
src/generate/ dependency graph, deterministic payloads, Playwright / pytest templates, collection tests, runner
src/fixtures/ approved fixtures: validation, policies, capture of candidates
src/maintain.ts spec change → regenerate → validate → one Draft PR
scripts/ fault injection (mutation-check.ts)
src/report/ JSON + Markdown report
demo-api/ in-memory target API and its OpenAPI spec
tests/unit/ Vitest unit tests
```

## Roadmap

- **Stage 2:** more scenario shapes (list-after-create, PUT, nested resources), Schemathesis config export for CI, re-analyse only operations changed since the last spec hash.
- **Stage 2:** more scenario shapes (PUT, nested resources), cursor pagination, Schemathesis config export for CI, re-analyse only operations changed since the last spec hash.
- **Stage 3:** optional AI adapter for unconfirmed dependencies, given only the operation, nearby schemas and the open question, with per-task token limits; `BLOCKED` when confidence is low.
- **Stage 4:** Jira / GitHub / Telegram triggers and notifications.

Expand Down
28 changes: 28 additions & 0 deletions demo-api/deps.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"scenarios": [
{
"create": "createItem",
"idFrom": "/id",
"param": "itemId",
"read": "getItem",
"update": "updateItem",
"delete": "deleteItem",
"collection": {
"operationId": "listItems",
"items": "/items",
"id": "/id",
"fields": { "/name": "exact", "/price": "tolerance:0.001", "/tags": "exact", "/createdAt": "ignore" },
"unique": ["/id"],
"filters": [{ "param": "tag", "field": "/tags", "match": "contains" }],
"sorts": [
{ "param": "sort", "value": "name", "field": "/name", "order": "asc" },
{ "param": "sort", "value": "-name", "field": "/name", "order": "desc" },
{ "param": "sort", "value": "price", "field": "/price", "order": "asc" },
{ "param": "sort", "value": "-price", "field": "/price", "order": "desc" }
],
"page": { "style": "offset", "offsetParam": "offset", "limitParam": "limit", "maxPages": 20 },
"deletedDisappears": true
}
}
]
}
1 change: 1 addition & 0 deletions demo-api/expected-gaps.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"CANNOT_ISOLATE_RULE": 1,
"MISSING_CLEANUP": 2,
"MISSING_RESOURCE_SOURCE": 1,
"MISSING_RESPONSE_SCHEMA": 1
Expand Down
41 changes: 41 additions & 0 deletions demo-api/fixtures/approved/listItems.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"schemaVersion": 1,
"operationId": "listItems",
"query": {
"tag": "catalog"
},
"items": "/items",
"id": "/id",
"policies": {
"/price": "tolerance:0.001",
"/createdAt": "ignore"
},
"default": "exact",
"exhaustive": true,
"page": {
"style": "offset",
"offsetParam": "offset",
"limitParam": "limit",
"maxPages": 20
},
"expected": [
{
"id": "00000000-0000-4000-8000-000000000001",
"name": "Catalog hammer",
"price": 12.5,
"tags": [
"catalog"
],
"createdAt": "2026-11-09T21:13:16.636Z"
},
{
"id": "00000000-0000-4000-8000-000000000002",
"name": "Catalog screwdriver",
"price": 4.25,
"tags": [
"catalog"
],
"createdAt": "2026-11-09T21:13:16.637Z"
}
]
}
23 changes: 23 additions & 0 deletions demo-api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,29 @@ paths:
minimum: 1
maximum: 100
default: 20
- name: offset
in: query
required: false
description: Items to skip (offset pagination).
schema:
type: integer
minimum: 0
default: 0
- name: tag
in: query
required: false
description: Only items carrying this tag.
schema:
type: string
minLength: 1
maxLength: 30
- name: sort
in: query
required: false
description: Order of the items; a leading "-" is descending.
schema:
type: string
enum: [name, -name, price, -price]
responses:
'200':
description: Items page
Expand Down
31 changes: 29 additions & 2 deletions demo-api/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ interface Item {
}

const items = new Map<string, Item>();
// Reference data present from the start (tag "catalog"): what demo-api/fixtures/approved/listItems.json approves.
for (const seed of [
{ id: '00000000-0000-4000-8000-000000000001', name: 'Catalog hammer', price: 12.5, tags: ['catalog'] },
{ id: '00000000-0000-4000-8000-000000000002', name: 'Catalog screwdriver', price: 4.25, tags: ['catalog'] },
]) items.set(seed.id, { ...seed, createdAt: new Date().toISOString() });
let lastCreated: string | undefined; // DEMO_FAULT=hide-created hides it from the list
const ADMIN_TOKEN = process.env.DEMO_ADMIN_TOKEN ?? 'demo-admin-token';
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

Expand Down Expand Up @@ -78,8 +84,28 @@ route('/items', {
const raw = url.searchParams.get('limit');
const limit = raw === null ? 20 : Number(raw);
if (!Number.isInteger(limit) || limit < 1 || limit > 100) return error(res, 400, 'limit must be an integer 1-100');
const all = [...items.values()];
send(res, 200, { items: all.slice(0, limit), total: all.length });
const rawOffset = url.searchParams.get('offset');
const offset = rawOffset === null ? 0 : Number(rawOffset);
if (!Number.isInteger(offset) || offset < 0) return error(res, 400, 'offset must be an integer >= 0');
const sort = url.searchParams.get('sort');
if (sort !== null && !['name', '-name', 'price', '-price'].includes(sort)) return error(res, 400, 'sort must be name, -name, price or -price');
const tag = url.searchParams.get('tag');
if (tag !== null && (tag.length < 1 || tag.length > 30)) return error(res, 400, 'tag must be 1-30 characters');
// DEMO_FAULT simulates one collection defect at a time (mutation tests: the generated suite must catch each).
const fault = process.env.DEMO_FAULT;
let all = [...items.values()];
if (tag !== null && fault !== 'ignore-filter') all = all.filter((i) => i.tags.includes(tag));
if (fault === 'hide-created') all = all.filter((i) => i.id !== lastCreated);
if (sort) {
const key = sort.replace(/^-/, '') as 'name' | 'price';
const dir = sort.startsWith('-') ? -1 : 1;
all = [...all].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0) * dir * (fault === 'wrong-sort' ? -1 : 1));
}
if (fault === 'duplicate') all = all.flatMap((i) => [i, i]);
const start = fault === 'bad-pagination' ? Math.max(0, offset - 1) : offset;
let page = all.slice(start, start + limit);
if (fault === 'wrong-field') page = page.map((i) => ({ ...i, price: i.price + 1 }));
send(res, 200, { items: page, total: all.length });
},
POST: async (req, res) => {
const body = await readJson(req);
Expand All @@ -88,6 +114,7 @@ route('/items', {
if (typeof v === 'string') return error(res, 400, v);
const item: Item = { id: randomUUID(), name: v.name!, price: v.price!, tags: v.tags ?? [], createdAt: new Date().toISOString() };
items.set(item.id, item);
lastCreated = item.id;
// DEMO_BREAK=create-price simulates a regression so the agent's CONTRACT_MISMATCH path can be demonstrated.
const out = process.env.DEMO_BREAK === 'create-price' ? { ...item, price: String(item.price) } : item;
send(res, 201, out, { location: `/items/${item.id}` });
Expand Down
Loading
Loading