diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cc604a..9fb7bcf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- **AI step on by default** (docs/GUIDE.md §5b): `generate` uses a console AI tool when one is found (`API_AI` / `--ai-runner`, else `claude`, else `codex`); none found, a failing tool or `--no-ai` → generated without it. + - new: read-only sources of path values: the AI says which list operation and field hold existing ids (`brandId ← GET /brands #/0/id`); after the spec check (safe list operation, a pointer through a list element, a fitting identifier type) a positive test reads the list and then the record, skipped with the reason when there is no record or the list is refused; marked `ai-proposed` (pytest `ai_proposed`), listed in the report section "AI participation"; + - answers cached in the suite (`_support/ai-sources.json`): regeneration, `maintain` (which never calls the AI) and runs without AI reproduce the same tests; a reviewed form in the deps file: `"sources": [...]`; + - unconfirmed write dependencies stay proposals (`ai-deps.proposed.json`); `--ai-max-calls` default 25. + - On Toolshop: 8 sources found (brands, category tree, related / specs of a product, invoices, users): 8 more tests passed, 8 skipped with the reason (no invoices on a fresh account, `GET /users` needs an admin), `MISSING_RESOURCE_SOURCE` 22 → 15. - **Query parameters and GET collections** (docs/SUPPORT_MATRIX.md): - confirmed: a decimal case for integer parameters (inside the documented bounds, so only the type is broken); every query case checks that the value really went over HTTP; accepted values also check the response contract; values over the limits are `CASE_LIMIT_REACHED` gaps instead of being dropped silently; Python sends query booleans as `true` / `false`; - exploratory probes for scalar query parameters of GET / HEAD operations (empty, text, decimal, zero, negative, large, special characters, another spelling of a boolean or enum value, a missing required parameter): deduplicated against confirmed cases and the documented range, never failing on the API's behavior, recorded in the report (`exploratory.jsonl`, "Exploratory query probes"); diff --git a/README.md b/README.md index 1f4cf7c..a4597a4 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ OpenAPI spec ──► lint + catalogue ──► safe probe ──► Schemathe ## Principles -- **Deterministic first, no AI in this version.** Parsing, lint, catalogue, payloads, templates, CI: all rule-based. AI is planned only for ambiguous dependencies, with a token budget. +- **Deterministic first, AI where rules cannot decide.** Parsing, lint, catalogue, payloads, templates, CI: rule-based. When a console AI tool is found, `generate` also asks it where an existing id can be read (read-only tests, marked AI-proposed, cached for reproducibility) and proposes unconfirmed dependencies for review; without a tool it runs exactly as before. - **The spec is the requirement.** An observed response that differs from the spec is a `CONTRACT_MISMATCH` for a human to decide on. The tool never treats the implementation as the source of truth. - **Stop with a precise blocker instead of inventing.** No example for a required parameter, a pattern it cannot satisfy, a dependency that is only implied by path names: each becomes `BLOCKED` with the exact question to answer. - **Never make a test green by editing it.** Generated tests run once; assertions are not touched. @@ -49,7 +49,7 @@ npx @testomut/api-test-agent diff --head openapi.yaml # what changed in the sp **Test language:** TypeScript (Playwright Test) or Python (pytest + requests), chosen in `init` or with `API_TESTS_LANG` / `generate --lang`. Same layout, cases and safety rules in both. -**Optional AI (`--ai`):** runs through a console tool you are logged in to (Claude Code `claude -p`, Codex `codex exec`, or your own orchestrator command): no API keys. It proposes answers for unconfirmed dependencies from a minimal spec excerpt; every answer is schema-validated, checked against the spec and written as a proposal you review, never applied automatically. Without `--ai` the tool is fully deterministic. +**AI step (on by default, `--no-ai` to switch off):** runs through a console tool you are logged in to (Claude Code `claude -p`, Codex `codex exec`, or your own orchestrator command), no API keys; none found → generated without it. From a minimal spec excerpt it finds where existing ids can be read, which unblocks read-only tests of `GET /x/{id}` (marked `ai-proposed`; copy them into the deps file `sources` to keep them reviewed), and proposes unconfirmed dependencies, which are never applied without your review. Every answer is schema-validated and checked against the spec. **Full guide: [docs/GUIDE.md](docs/GUIDE.md)** (configuration, every check, what each command changes). Legacy projects to try it on: [Playwright](examples/legacy-project), [pytest](examples/legacy-pytest-project). diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 6acdaa6..4363968 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -202,9 +202,16 @@ Not yet: three-way `registry merge`, `--id-aliases` / `--apply-registry`, `plan` - Assertions: the statuses from `pm.test`; if the request had none and the operation is in the spec, the documented success status (marked as such in the test). Other `pm.test` lines are copied as comments for review. - Output in the configured language: `//positive.postman.spec.ts` or `test_positive_postman.py`. -## 5b. Optional AI (`--ai`), through console tools +## 5b. AI step (on by default), through console tools -Everything above is deterministic. `--ai` adds an AI step in **one** place where rules cannot decide: **unconfirmed dependencies** (`POST /x` + `/x/{param}` with no OpenAPI `links` and no deps file, normally BLOCKED with a question). +`generate` asks an AI where rules cannot decide, **when a console tool is found** (`API_AI` / `--ai-runner`, else `claude`, else `codex` on PATH). No tool, or not logged in: the run says so and goes on without AI, exactly as before. `--no-ai` switches it off. + +1. **Read-only sources of path values (used right away, marked AI-proposed).** A safe operation such as `GET /brands/{brandId}` is normally blocked (`MISSING_RESOURCE_SOURCE`): no real id to call it with. The AI picks the list operation and field that hold existing ids (`brandId ← GET /brands #/0/id`). After the spec check (below) the test reads the list, takes an existing value and reads that record; no record, or the list refused (e.g. another role needed) → skipped with the reason. These tests only read, carry the `ai-proposed` annotation (pytest marker `ai_proposed`) and are listed in the report section "AI participation". To make one reviewed, copy it into the deps file: + ```json + "sources": [{ "operationId": "getBrand", "param": "brandId", "from": "getBrands", "pointer": "/0/id" }] + ``` + The answers are cached in the suite (`_support/ai-sources.json`, in the generation manifest): a regeneration, `maintain` and a run without AI reuse them, so the suite stays reproducible. +2. **Unconfirmed dependencies (proposals, never applied).** `POST /x` + `/x/{param}` with no OpenAPI `links` and no deps file: these would create and delete data, so the answer is only a proposal (`ai-deps.proposed.json`) until you pass it with `--deps`. The AI runs through a **console tool you are already logged in to**: no API keys, usage counts against your subscription. @@ -222,11 +229,12 @@ npx @testomut/api-test-agent generate --deps reports/api-agent/generate/ai-deps. **Contract for `command` (orchestrators):** the request is written to stdin as JSON `{"system": "...", "prompt": "...", "schema": {JSON Schema}}`; the tool prints the answer object (matching the schema) as JSON on stdout and exits 0. The tool runs in an empty temporary folder. -- **Opt-in only.** Without `--ai` no tool is called. -- **Minimal context.** For each candidate: operation keys and ids, the create response's property names and types, the path parameter's type. Never example values, request data, test results or `.env` contents. -- **Validated twice.** The answer must match the JSON Schema (checked here, not only by the tool), then the spec: the identifier pointer must exist in the create response and its type/format must match the path parameter; low confidence is rejected. +- **On by default, never required.** No tool found, a tool that fails, or `--no-ai`: generated without AI; `maintain` never calls the AI (cached answers and reviewed sources only). +- **Minimal context.** Operation keys, ids and summaries, response field names and types, the path parameter's type. Never example values, request data, test results or `.env` contents. +- **Validated twice.** The answer must match the JSON Schema (checked here, not only by the tool), then the spec. A source: a safe list operation of the spec callable as is, a pointer through a list element of its response, a field type that fits the parameter (an integer id may fill a string parameter, a decimal never). A dependency: the identifier pointer must exist in the create response and its type/format must match. Low confidence is rejected. +- **Writes only after review.** AI answers never create or delete data: sources only read, dependencies stay proposals. - **Proposals, never applied.** Accepted answers go to `ai-deps.proposed.json` (deps-file format); every answer with its reason to `ai-proposals.json`. Tests use them only after you pass the file with `--deps`, and running the tests then confirms the link against the real API. -- **Budget:** `--ai-max-calls` (default 10). The run ends with answers, failures, time and, for `claude`, the cost Claude Code reports (only billed per call when you use an API key instead of a subscription). +- **Budget:** `--ai-max-calls` (default 25). The run ends with answers, failures, time and, for `claude`, the cost Claude Code reports (only billed per call when you use an API key instead of a subscription). - **Tool missing or not logged in:** the AI step is skipped with a message; the rest of the run is unaffected. ## 6. Checks catalogue @@ -368,7 +376,7 @@ Python folders use underscores and contain `__init__.py`, so `test_functional.py **Postman cloud or file?** Both. A path ending in `.json` is read from disk; anything else is treated as a cloud collection id and needs `POSTMAN_API_KEY`. -**Does it use AI?** Only with `--ai`, through a console tool you are logged in to (Claude Code, Codex, or your own orchestrator), and only to propose answers for unconfirmed dependencies, which you review (§5b). No API keys. Everything else (spec analysis, cases, payloads, test analysis, generation) is rule-based and reproducible. +**Does it use AI?** By default `generate` does, when a console tool you are logged in to is found (Claude Code, Codex, or your own orchestrator), and only where rules cannot decide (§5b): read-only sources of path values (used, marked AI-proposed, cached for reproducibility) and unconfirmed dependencies (proposals you review). No API keys. Without a tool, or with `--no-ai`, everything is rule-based. **Which languages can tests be generated in?** TypeScript (Playwright Test) and Python (pytest + requests), chosen in `init` or with `API_TESTS_LANG` / `--lang`. The analysis, cases and safety rules are shared; only the output templates differ, so more languages can be added. diff --git a/docs/SUPPORT_MATRIX.md b/docs/SUPPORT_MATRIX.md index 5eb5916..e6e387f 100644 --- a/docs/SUPPORT_MATRIX.md +++ b/docs/SUPPORT_MATRIX.md @@ -83,6 +83,14 @@ Inputs a real client sends by mistake, for scalar query parameters of GET / HEAD Write operations are never probed (`UNSAFE_LIVE_CHECK`); an operation with an unknown path value is not probed (`MISSING_RESOURCE_SOURCE`); more than 24 probes per operation → `CASE_LIMIT_REACHED`. +### Path values from existing data (`src/ai/sources.ts`) + +| Source | State | How / limits | +|---|---|---| +| deps `sources` (reviewed) | ✅ | `{ operationId, param, from, pointer }`, checked against the spec; a mismatch → `INVALID_REVIEWED_CONFIG` | +| AI step (on by default) | ✅ | for safe operations blocked by one unknown path value; spec check: a safe list operation callable as is, a pointer through a list element, a fitting identifier type; low confidence rejected; tests only read, marked `ai-proposed`; answers cached in `_support/ai-sources.json` | +| no record / the list refused | ✅ | the test is skipped with the reason, never failed | + ## Functional (`functional.spec.ts`) | Check | State | Limits | Stage | diff --git a/src/ai/sources.ts b/src/ai/sources.ts new file mode 100644 index 0000000..30eb906 --- /dev/null +++ b/src/ai/sources.ts @@ -0,0 +1,225 @@ +import type { Operation } from '../types.js'; +import { resolvePointer, type OpenApiDoc } from '../spec/loader.js'; +import { operationPointer } from '../spec/catalog.js'; +import { AiRunner, describeAiError } from './runner.js'; + +/** + * AI step for READ-ONLY resource sources: where an existing value of a path parameter can be read, e.g. + * "brandId of GET /brands/{brandId} is /0/id of GET /brands". Asked only for safe operations whose positive test is + * blocked by an unknown path value. The model sees operation keys, summaries, field names and types - never data. + * Every answer is checked against the spec (the source is a safe operation of the spec, the pointer exists in its + * response schema, the field type fits the parameter) before it is used; a test built from it only reads + * (list → read by id) and is marked "AI-proposed, unreviewed". Reviewed sources live in the deps file: + * "sources": [{ "operationId": "getBrand", "param": "brandId", "from": "getBrands", "pointer": "/0/id" }] + */ + +export interface SourceConfig { + operationId: string; + param: string; + from: string; + pointer: string; +} + +export interface ResolvedSource { + op: Operation; + param: string; + from: Operation; + pointer: string; + /** Proposed by the AI step this run (not reviewed); false for a deps-file entry. */ + ai: boolean; + reason: string; +} + +export interface SourceAnswerT { + from: string | null; + pointer: string | null; + confidence: 'high' | 'medium' | 'low'; + reasoning: string; +} + +export const SOURCE_SCHEMA = { + type: 'object', + properties: { + from: { type: ['string', 'null'], description: 'operationId of the candidate list operation whose response holds existing values of the parameter; null if none fits' }, + pointer: { type: ['string', 'null'], description: 'JSON pointer to one value in that response, with 0 for the first array element, e.g. "/data/0/id"; null if none fits' }, + confidence: { type: 'string', enum: ['high', 'medium', 'low'] }, + reasoning: { type: 'string', description: 'one or two sentences, citing only names from the excerpt' }, + }, + required: ['from', 'pointer', 'confidence', 'reasoning'], + additionalProperties: false, +}; + +export const SOURCE_PROMPT = `You review REST API specifications for an API test generator. +You get one read operation with a path parameter and candidate list operations with the fields of their response elements. +Pick the candidate whose elements are the resources the path parameter identifies, and the field that holds the identifier. +Rules: +- Use only names and types that appear in the excerpt. Never invent operations or fields. +- If no candidate clearly lists those resources, or the identifier field is not clear, answer from=null or confidence "low". +- pointer is a JSON pointer into the candidate's response body, using 0 for the first array element, e.g. "/0/id" or "/data/0/id".`; + +const deref = (doc: OpenApiDoc, s: any, depth = 0): any => (s?.$ref && depth < 20 ? deref(doc, resolvePointer(doc, s.$ref.slice(1)).node, depth + 1) : s); +const typeOf = (s: any): string | undefined => (Array.isArray(s?.type) ? s.type.find((t: string) => t !== 'null') : s?.type ?? (s?.properties ? 'object' : s?.items ? 'array' : undefined)); + +function successSchema(doc: OpenApiDoc, op: Operation): any { + const responses = resolvePointer(doc, `${operationPointer(op)}/responses`).node ?? {}; + for (const [status, r] of Object.entries(responses)) { + if (!/^2\d\d$/.test(status)) continue; + const resp = deref(doc, r); + const media = Object.keys(resp?.content ?? {}).find((k) => k.includes('json')); + if (media) return deref(doc, resp.content[media].schema); + } + return undefined; +} + +/** Arrays of objects in a response: pointer to the array ("" = the body) and the element's field names / types. */ +function listings(doc: OpenApiDoc, schema: any): { items: string; fields: Record }[] { + const out: { items: string; fields: Record }[] = []; + const fieldsOf = (el: any) => Object.fromEntries(Object.entries(deref(doc, el)?.properties ?? {}).map(([k, v]) => [k, [typeOf(deref(doc, v)) ?? 'any', deref(doc, v)?.format].filter(Boolean).join(':')])); + const s = deref(doc, schema); + if (typeOf(s) === 'array' && typeOf(deref(doc, s.items)) === 'object') out.push({ items: '', fields: fieldsOf(s.items) }); + for (const [k, v] of Object.entries(s?.properties ?? {})) { + const p = deref(doc, v); + if (typeOf(p) === 'array' && typeOf(deref(doc, p.items)) === 'object') out.push({ items: `/${k}`, fields: fieldsOf(p.items) }); + } + return out; +} + +/** Safe operations without unknown path / required query values whose response lists objects: possible sources. */ +export function sourceCandidates(doc: OpenApiDoc, ops: Operation[]): { op: Operation; listings: { items: string; fields: Record }[] }[] { + return ops + .filter((o) => o.method === 'get' && o.operationId && !o.deprecated) + .filter((o) => !o.params.some((p) => (p.in === 'path' || p.required) && p.knownValue === undefined)) + .map((o) => ({ op: o, listings: listings(doc, successSchema(doc, o)) })) + .filter((c) => c.listings.length); +} + +/** Deterministic check of a source (AI answer or deps entry) against the spec. */ +export function verifySource(doc: OpenApiDoc, ops: Operation[], target: Operation, param: string, from: string | null, pointer: string | null): { from?: Operation; problem?: string } { + const p = target.params.find((x) => x.in === 'path' && x.name === param); + if (!p) return { problem: `${target.key} has no path parameter "${param}"` }; + const src = ops.find((o) => o.operationId === from); + if (!src) return { problem: `operation "${from}" is not in the spec` }; + if (!sourceCandidates(doc, ops).some((c) => c.op === src)) return { problem: `${src.key} is not a safe list operation that can be called as is` }; + if (typeof pointer !== 'string' || !pointer.startsWith('/')) return { problem: 'the pointer is not a JSON pointer such as "/0/id"' }; + let node = successSchema(doc, src); + let throughElement = false; + for (const raw of pointer.split('/').slice(1)) { + const seg = raw.replace(/~1/g, '/').replace(/~0/g, '~'); + node = deref(doc, node); + if (/^\d+$/.test(seg) && typeOf(node) === 'array') { + node = node.items; + throughElement = true; + } else node = node?.properties?.[seg]; + if (!node) return { problem: `${pointer} does not exist in the ${src.key} response schema` }; + } + // A value of an existing record: the pointer goes through a list element, not to a field of the response itself. + if (!throughElement) return { problem: `${pointer} is not inside a list element of the ${src.key} response` }; + const field = deref(doc, node); + const ft = typeOf(field); + const pt = typeOf(p.schema); + // An identifier: the same type, or an integer id in a string path parameter (never a decimal number). + const compatible = !pt || !ft || ft === pt || (pt === 'string' && ft === 'integer'); + if (!compatible) return { problem: `type mismatch: ${pointer} is ${ft}, the path parameter is ${pt}` }; + const pf = (p.schema as any)?.format; + if (pf && field?.format && pf !== field.format) return { problem: `format mismatch: ${field.format} vs ${pf}` }; + return { from: src }; +} + +/** Reviewed deps-file sources, checked against the spec; problems are returned, never used. */ +export function reviewedSources(doc: OpenApiDoc, ops: Operation[], configs: SourceConfig[] | undefined): { sources: ResolvedSource[]; errors: { operationId: string; reason: string }[] } { + const sources: ResolvedSource[] = []; + const errors: { operationId: string; reason: string }[] = []; + for (const c of configs ?? []) { + const op = ops.find((o) => o.operationId === c?.operationId); + if (!op) { + errors.push({ operationId: String(c?.operationId), reason: `sources: operation "${c?.operationId}" is not in the spec` }); + continue; + } + const v = verifySource(doc, ops, op, c.param, c.from, c.pointer); + if (v.problem) errors.push({ operationId: c.operationId, reason: `sources: ${v.problem}` }); + else sources.push({ op, param: c.param, from: v.from!, pointer: c.pointer, ai: false, reason: 'deps file (reviewed)' }); + } + return { sources, errors }; +} + +/** Operations a source would unblock: safe, not deprecated, exactly one path parameter without a real value. */ +export function sourceTargets(ops: Operation[], covered: (op: Operation) => boolean): { op: Operation; param: string }[] { + const out: { op: Operation; param: string }[] = []; + for (const op of ops.filter((o) => o.method === 'get' && o.operationId && !o.deprecated && !covered(o))) { + const unknown = op.params.filter((p) => p.in === 'path' && (p.knownValue === undefined || p.knownSource === 'example')); + if (unknown.length === 1 && !op.params.some((p) => p.in !== 'path' && p.required && p.knownValue === undefined)) out.push({ op, param: unknown[0].name }); + } + return out; +} + +export interface SourceProposal { + operation: string; + param: string; + answer?: SourceAnswerT; + status: 'used' | 'rejected' | 'not-asked' | 'cached'; + reason: string; +} + +/** Cache of AI answers in the suite (regeneration stays deterministic): key = operation, parameter and candidates. */ +export type SourceCache = Record; + +export async function proposeSources( + doc: OpenApiDoc, + ops: Operation[], + targets: { op: Operation; param: string }[], + advisor: AiRunner | undefined, + cache: SourceCache, + log: (m: string) => void, +): Promise<{ sources: ResolvedSource[]; proposals: SourceProposal[]; cache: SourceCache; deps: SourceConfig[] }> { + const candidates = sourceCandidates(doc, ops); + const sources: ResolvedSource[] = []; + const proposals: SourceProposal[] = []; + const deps: SourceConfig[] = []; + const next: SourceCache = {}; + let aiDown = !advisor; + for (const t of targets) { + const param = t.op.params.find((p) => p.in === 'path' && p.name === t.param)!; + const usable = candidates.filter((c) => c.op !== t.op); + const key = `${t.op.operationId}#${t.param}#${usable.map((c) => c.op.operationId).sort().join(',')}`; + let answer: SourceAnswerT | null | undefined = cache[key]; + let status: SourceProposal['status'] = 'cached'; + if (!answer) { + if (aiDown || !usable.length) { + proposals.push({ operation: t.op.key, param: t.param, status: 'not-asked', reason: !usable.length ? 'no safe list operation to read existing values from' : 'AI not available' }); + continue; + } + const excerpt = { + read_operation: { key: t.op.key, operationId: t.op.operationId, summary: t.op.summary ?? null, path_parameter: { name: t.param, type: [typeOf(param.schema) ?? 'any', (param.schema as any)?.format].filter(Boolean).join(':') } }, + candidates: usable.map((c) => ({ operationId: c.op.operationId, key: c.op.key, summary: c.op.summary ?? null, listings: c.listings.map((l) => ({ array_at: l.items || '(the body)', element_fields: l.fields })) })), + }; + try { + answer = await advisor!.ask(SOURCE_PROMPT, `Excerpt (JSON):\n${JSON.stringify(excerpt, null, 2)}\n\nAnswer with the JSON object only.`, SOURCE_SCHEMA); + status = 'used'; + } catch (e) { + log(` AI: ${describeAiError(e)}: the remaining operations are generated without AI`); + aiDown = true; + proposals.push({ operation: t.op.key, param: t.param, status: 'not-asked', reason: describeAiError(e) }); + continue; + } + if (!answer) { + proposals.push({ operation: t.op.key, param: t.param, status: 'rejected', reason: 'no usable answer (declined or unparseable)' }); + continue; + } + } + next[key] = answer; + if (!answer.from || !answer.pointer || answer.confidence === 'low') { + proposals.push({ operation: t.op.key, param: t.param, answer, status: 'rejected', reason: answer.confidence === 'low' ? 'model confidence is low' : 'model found no source' }); + continue; + } + const v = verifySource(doc, ops, t.op, t.param, answer.from, answer.pointer); + if (v.problem) { + proposals.push({ operation: t.op.key, param: t.param, answer, status: 'rejected', reason: `rejected by the spec check: ${v.problem}` }); + continue; + } + sources.push({ op: t.op, param: t.param, from: v.from!, pointer: answer.pointer, ai: true, reason: `${answer.confidence} confidence: ${answer.reasoning}` }); + deps.push({ operationId: t.op.operationId!, param: t.param, from: answer.from, pointer: answer.pointer }); + proposals.push({ operation: t.op.key, param: t.param, answer, status, reason: `${answer.confidence} confidence, verified against the spec: ${answer.reasoning}` }); + log(` AI source: ${t.op.key} ${t.param} ← ${v.from!.key} #${answer.pointer} (${answer.confidence}${status === 'cached' ? ', cached' : ''})`); + } + return { sources, proposals, cache: next, deps }; +} diff --git a/src/cli.ts b/src/cli.ts index f2aa55e..5307773 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -27,12 +27,14 @@ import { validateManifest, validateRegistry } from './cases/validate.js'; import { validateScenarios, type ResolvedScenario } from './scenarios/dsl.js'; import { isUrl } from './change/network.js'; import { accountNotice, ACCOUNT_MODES, checkRegisterConfig, missingLoginVars, parseAccountMode, registerAccount, type AccountMode } from './audit/account.js'; -import { AiRunner, describeAiError, RUNNERS, type RunnerKind } from './ai/runner.js'; +import { AiRunner, describeAiError, resolveCli, RUNNERS, type RunnerKind } from './ai/runner.js'; import { proposeDependencies } from './ai/dependencies.js'; import { analyzeProject } from './discover/analyze.js'; import { loadApproved, type LoadedFixture } from './fixtures/fixtures.js'; import { candidateSummary, captureFixture } from './fixtures/capture.js'; import { maintain } from './maintain.js'; +import { proposeSources, reviewedSources, sourceTargets } from './ai/sources.js'; +import { findChains } from './generate/graph.js'; import { upsertDraftPr } from './pr.js'; const VERSION = '0.1.3'; @@ -255,9 +257,9 @@ common(program.command('generate').description('audit, then generate Playwright .addOption(new Option('--lang ', 'language of generated tests (default: API_TESTS_LANG or typescript)').choices(['typescript', 'python'])) .option('--run', 'run the generated tests once against --base-url (needs --allow-write)', false) .option('--draft-pr', 'commit to a new branch and open a GitHub Draft PR for review', false) - .option('--ai', 'ask an AI console tool (your subscription, no API key) about unconfirmed dependencies; writes a PROPOSAL file, never applies it', false) - .addOption(new Option('--ai-runner ', 'console tool: claude, codex, or command (API_AI_COMMAND). Default: API_AI or claude').choices(RUNNERS)) - .option('--ai-max-calls ', 'AI call budget per run', '10') + .option('--no-ai', 'generate without the AI step (default: on when a console tool is found: API_AI, else claude, else codex)') + .addOption(new Option('--ai-runner ', 'console tool: claude, codex, or command (API_AI_COMMAND). Default: API_AI, else the first of claude / codex found').choices(RUNNERS)) + .option('--ai-max-calls ', 'AI call budget per run', '25') .option('--ai-model ', 'model name passed to the console tool (default: its own default)') .action(async (specArg: string | undefined, o: CommonOpts & { testsDir?: string; deps?: string; run: boolean; draftPr: boolean; lang?: 'typescript' | 'python'; ai: boolean; aiMaxCalls: string; maxCases: string; scenarios?: string; aiModel?: string; aiRunner?: RunnerKind; fixtures?: string }) => { const location = await resolveInputs(specArg, o); @@ -268,7 +270,9 @@ common(program.command('generate').description('audit, then generate Playwright await prepareAccount(o, o.probe || o.schemathesis, o.run); const r = await runAudit(location, o); const deps = o.deps ? JSON.parse(await readFile(o.deps, 'utf8')) : undefined; - if (o.ai) await aiProposals(r.spec.doc, r.ops, o.out, { maxCalls: Number(o.aiMaxCalls), model: o.aiModel, runner: o.aiRunner }, deps); + // AI step, on by default: proposals for review, and read-only sources of path values used right away + // (marked AI-proposed). Without a console tool everything is generated without it. + const ai = await aiStep(r.spec.doc, r.ops, o.out, o.testsDir!, { enabled: o.ai, maxCalls: Number(o.aiMaxCalls), model: o.aiModel, runner: o.aiRunner }, deps); log('Generating test suites (functional / contract / scenarios)…'); const maxCases = Number(o.maxCases); if (!Number.isInteger(maxCases) || maxCases < 1) throw new Error(`--max-cases must be a positive integer, got "${o.maxCases}".`); @@ -280,7 +284,7 @@ common(program.command('generate').description('audit, then generate Playwright log(`Scenarios: ${scenarios.length} reviewed business scenario(s) from ${o.scenarios}`); } const fx = o.fixtures ? await approvedFixtures(o.fixtures, r.spec, r.ops) : undefined; - const gen = await generate(r.spec, r.ops, { outDir: o.testsDir!, deps, version: VERSION, lang: o.lang, maxCases, scenarios, ...(fx ?? {}) }); + const gen = await generate(r.spec, r.ops, { outDir: o.testsDir!, deps, version: VERSION, lang: o.lang, maxCases, scenarios, ...(fx ?? {}), sources: ai.sources, sourceErrors: ai.sourceErrors, aiCache: ai.cache }); for (const s of gen.scenarios) log(` ${s.status.padEnd(9)} ${s.name}`); for (const f of gen.removed) log(` REMOVED ${relative(process.cwd(), f).replace(/\\/g, '/')} (generated earlier, no longer produced)`); if (o.run) { @@ -316,6 +320,7 @@ common(program.command('generate').description('audit, then generate Playwright files: gen.files.map((f) => resolve(f).replace(process.cwd() + (process.platform === 'win32' ? '\\' : '/'), '').replace(/\\/g, '/')), scenarios: gen.scenarios.map(({ name, status, reason, operations }) => ({ name, status, reason, operations })), cleanupFailures: gen.cleanupFailures, + ai: ai.report, ...(gen.exploratory?.length ? { exploratory: gen.exploratory } : {}), ...(gen.caseIdCheck ? { caseIdCheck: gen.caseIdCheck } : {}), }, @@ -412,7 +417,9 @@ program if (!specRef) log('AI: skipped, no spec.'); else { const spec = await loadSpec(/^https?:/i.test(specRef) ? specRef : resolve(process.cwd(), specRef)); - await aiProposals(spec.doc, buildCatalog(spec.doc), o.out, { maxCalls: Number(o.aiMaxCalls), model: o.aiModel, runner: o.aiRunner }); + const found = findAdvisor({ maxCalls: Number(o.aiMaxCalls), model: o.aiModel, runner: o.aiRunner }); + if (found.advisor) await aiProposals(spec.doc, buildCatalog(spec.doc), o.out, found.advisor); + else log(`AI: ${found.reason}.`); } } const a = r.analysis; @@ -560,15 +567,64 @@ program }); /** --ai: proposals for unconfirmed dependencies, written for review; never applied automatically. */ -async function aiProposals(doc: any, ops: Operation[], outDir: string, opts: { maxCalls: number; model?: string; runner?: RunnerKind }, deps?: any) { - let advisor: AiRunner; +/** + * The AI console tool to use: --ai-runner / API_AI when set, else the first of claude / codex installed. + * None found (or a broken setting) → undefined with the reason: the run goes on without AI. + */ +function findAdvisor(opts: { maxCalls: number; model?: string; runner?: RunnerKind }): { advisor?: AiRunner; reason: string } { + const explicit = opts.runner ?? ((process.env.API_AI as RunnerKind | undefined) || undefined); + const kind = explicit ?? (resolveCli('claude') ? 'claude' : resolveCli('codex') ? 'codex' : undefined); + if (!kind) return { reason: 'no AI console tool found (claude or codex on PATH, or API_AI=command with API_AI_COMMAND)' }; + if (!explicit || kind !== 'command') { + if (kind !== 'command' && !resolveCli(kind)) return { reason: `${kind} is not installed (API_AI / --ai-runner)` }; + } try { - advisor = new AiRunner(opts); - log(`\nAI proposals (opt-in --ai, via ${advisor.kind}): only operation names, field names and types of each candidate are sent.`); + return { advisor: new AiRunner({ ...opts, runner: kind }), reason: `via ${kind}` }; } catch (e) { - log(` ${describeAiError(e)}`); - return; + return { reason: describeAiError(e) }; + } +} + +/** AI step of generate: dependency proposals (for review) and read-only sources of path values (used, marked). */ +async function aiStep(doc: any, ops: Operation[], outDir: string, testsDir: string, opts: { enabled: boolean; cacheOnly?: boolean; maxCalls: number; model?: string; runner?: RunnerKind }, deps?: any) { + const reviewed = reviewedSources(doc, ops, deps?.sources); + for (const e of reviewed.errors) log(` INVALID ${e.reason}`); + const none = { sources: reviewed.sources, sourceErrors: reviewed.errors, cache: undefined as Record | undefined, report: { enabled: false, runner: null as string | null, reason: 'switched off (--no-ai)', usage: null as unknown, sources: [] as unknown[], dependencies: [] as unknown[] } }; + if (!opts.enabled) { + log('AI: off (--no-ai): generated without the AI step.'); + return none; + } + const found: { advisor?: AiRunner; reason: string } = opts.cacheOnly ? { reason: 'cached answers only (no AI calls here)' } : findAdvisor(opts); + log(found.advisor ? `AI: on ${found.reason} (only operation names, summaries, field names and types are sent; no data, no examples).` : `AI: ${found.reason}: generating without the AI step.`); + const dependencies = found.advisor ? await aiProposals(doc, ops, outDir, found.advisor, deps) : []; + // Read-only sources: the AI answers are cached in the suite, so a regeneration (even without AI) gives the same tests. + const cacheFile = join(testsDir, '_support', 'ai-sources.json'); + let cache: Record = {}; + try { + cache = JSON.parse(await readFile(cacheFile, 'utf8')).answers ?? {}; + } catch { + /* no cache yet */ } + const { chains } = findChains(doc, ops, deps); + const covered = (op: Operation) => reviewed.sources.some((x) => x.op === op) || chains.some((c) => c.read === op && !!c.delete); + const targets = sourceTargets(ops, covered); + const r = await proposeSources(doc, ops, targets, found.advisor, cache, log); + await mkdir(outDir, { recursive: true }); + if (r.deps.length) { + const file = join(outDir, 'ai-sources.proposed.json'); + await writeFile(file, JSON.stringify({ sources: r.deps }, null, 2) + '\n'); + log(` ${r.deps.length} AI source(s) used for read-only tests (marked AI-proposed). To review and keep them, copy "sources" from ${file.replace(/\\/g, '/')} into the deps file.`); + } + if (found.advisor) log(` ${found.advisor.summary()}`); + return { + sources: [...reviewed.sources, ...r.sources], + sourceErrors: reviewed.errors, + cache: r.cache, + report: { enabled: true, runner: found.advisor?.kind ?? null, reason: found.reason, usage: found.advisor?.usage ?? null, sources: r.proposals, dependencies }, + }; +} + +async function aiProposals(doc: any, ops: Operation[], outDir: string, advisor: AiRunner, deps?: any): Promise { const { proposals, depsFile } = await proposeDependencies(doc, ops, advisor, log, deps); await mkdir(outDir, { recursive: true }); await writeFile(join(outDir, 'ai-proposals.json'), JSON.stringify({ runner: advisor.kind, model: advisor.model ?? null, usage: advisor.usage, proposals }, null, 2) + '\n'); @@ -580,7 +636,7 @@ async function aiProposals(doc: any, ops: Operation[], outDir: string, opts: { m log(` ${depsFile.scenarios.length} proposal(s) passed the spec check: ${file}`); log(` Review it, then use it: generate --deps ${file.replace(/\\/g, '/')}`); } - log(` ${advisor.summary()}`); + return proposals; } /** Approved fixtures of a directory; invalid ones are logged and become INVALID_REVIEWED_CONFIG gaps. */ @@ -622,9 +678,11 @@ program if (!location) throw new Error('No spec found: pass it as an argument or set API_SPEC_URL.'); const { spec, ops } = await load(location); const inputs = await reviewedInputs(o, spec, ops); + // No new AI calls in maintenance (deterministic, unattended): reviewed sources and the AI answers cached in the suite. + const ai = await aiStep(spec.doc, ops, o.out, o.testsDir, { enabled: true, cacheOnly: true, maxCalls: 0 }, inputs.deps); const r = await maintain({ location, spec, ops, testsDir: o.testsDir, base: o.base, out: o.out, draftPr: o.draftPr, allowNetwork: o.allowNetwork, log, - generate: { version: VERSION, lang: o.lang ?? cfg.testsLang, maxCases: Number(o.maxCases), ...inputs }, + generate: { version: VERSION, lang: o.lang ?? cfg.testsLang, maxCases: Number(o.maxCases), ...inputs, sources: ai.sources, sourceErrors: ai.sourceErrors, aiCache: ai.cache }, }); log(`Summary: ${r.summaryFile}`); if (!r.valid) process.exitCode = 1; diff --git a/src/generate/generate.ts b/src/generate/generate.ts index 1e8e526..053b7e4 100644 --- a/src/generate/generate.ts +++ b/src/generate/generate.ts @@ -18,6 +18,7 @@ import { checkAuthConfig, errorPlan } from './error-cases.js'; import { collectionGaps, resolveCollection } from './collection.js'; import { bodyVariants as variantsOf, type BodyVariant } from './variants.js'; import { paramProbes } from './probes.js'; +import type { ResolvedSource } from '../ai/sources.js'; import { encodeSegment, location } from '../cases/ids.js'; import { collectionStrategy, planCollectionTests } from './collection-tests.js'; import { tsFixtureModule, fixtureModule, type CollectionInput } from './collection-render.js'; @@ -48,6 +49,12 @@ export interface GenerateOptions { maxCases?: number; /** Reviewed business scenarios (validated with validateScenarios against the same operations). */ scenarios?: ResolvedScenario[]; + /** Read-only sources of path values (deps "sources", reviewed, and AI-proposed this run), checked against the spec. */ + sources?: ResolvedSource[]; + /** Problems of the deps "sources" (INVALID_REVIEWED_CONFIG gaps of the operations named). */ + sourceErrors?: { operationId: string; reason: string }[]; + /** AI answers to keep with the suite (_support/ai-sources.json), so regeneration stays deterministic. */ + aiCache?: Record; /** Approved fixtures (strategy B), already validated against the spec; invalid ones arrive as fixtureErrors. */ fixtures?: LoadedFixture[]; fixtureErrors?: { file: string; operationId?: string; errors: string[] }[]; @@ -115,6 +122,8 @@ export interface Coverage { uncheckedRequestContentTypes: string[]; /** Security alternatives beyond the one the suite uses. */ uncheckedSecurityAlternatives: string[][]; + /** What the AI step contributed to this operation (unreviewed), e.g. the source of a path value. */ + aiProposed?: { kind: 'source'; from: string; pointer: string; reason: string }[]; /** List operations: how the collection is tested (create-verify / read-only / contract-only) and why. */ collection?: { strategy: string; reasons: string[]; tests: { kind: string; mode: string }[] }; } @@ -316,7 +325,9 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const helpers = helperPlan ? posix(relative(dir, helperFile(helperPlan))).replace(/\.ts$/, '.js') : undefined; const safe = SAFE_METHODS.includes(op.method); const pathParams = op.params.filter((p) => p.in === 'path'); - const unresolvedPath = pathParams.filter((p) => p.knownValue === undefined && p.name !== plan?.chain.param); + // A read-only source (deps "sources" or the AI step) gives a real value of one path parameter: list → read by id. + const source = !plan && op.method === 'get' ? o.sources?.find((x) => x.op === op) : undefined; + const unresolvedPath = pathParams.filter((p) => p.knownValue === undefined && p.name !== plan?.chain.param && p.name !== source?.param); // Required query / header / cookie parameters need a documented value, or no valid request exists. const unresolvedQuery = op.params.filter((p) => p.in !== 'path' && p.required && p.knownValue === undefined && sendable(p)); @@ -330,7 +341,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const miss = [...unresolvedPath, ...unresolvedQuery].map((p) => `${p.in} "${p.name}"`).join(', '); posReason = chainBlock.get(op) ?? `No value for ${miss}: add an example to the spec, or link the operation that creates it.`; } else if (!op.responses.some((r) => /^2\d\d$/.test(r.status))) posReason = 'No concrete 2xx response is documented.'; - else if (pathParams.some((p) => p.knownSource === 'example')) { + else if (pathParams.some((p) => p.knownSource === 'example' && p.name !== source?.param)) { // An example id ("1") is an illustration, not a record that exists on the test environment. const ex = pathParams.filter((p) => p.knownSource === 'example').map((p) => `"${p.name}"`).join(', '); posReason = chainBlock.get(op) ?? `Path ${ex} would come from a spec example, not from a real record: link the operation that creates it (OpenAPI links / --deps), or provide test data.`; @@ -390,7 +401,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp const firstWith405 = op.responses.some((r) => r.status === '405') && !paths405.has(op.path); if (firstWith405) paths405.add(op.path); const errors = op.deprecated ? { gaps: [] } : errorPlan({ doc: spec.doc, op, ops, chain: plan?.chain, role: errRole, hasUpdatePayload: plan?.updatePayload !== undefined, reachable, firstWith405, auth: authOk ? o.deps?.auth : undefined }); - const input: SuiteInput = { op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, errors, business: (o.scenarios ?? []).filter((b) => b.primaryOp === op) }; + const input: SuiteInput = { ...(source && !posReason ? { source } : {}), op, refs, plan, helpers, positive: !posReason, validation: rej.validation, bodyCases: bCases, paramCases: qCases, notFound, unauthorized, errors, business: (o.scenarios ?? []).filter((b) => b.primaryOp === op) }; let collPlan: ReturnType | undefined; if (coll && input.positive && !op.deprecated) { const ch = coll.plan.chain; @@ -401,7 +412,8 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp if (fixture) input.fixture = fixture; const fixtureGaps: CoverageGap[] = (o.fixtureErrors ?? []).filter((e) => e.operationId && e.operationId === op.operationId).flatMap((e) => e.errors.map((reason) => ({ code: 'INVALID_REVIEWED_CONFIG', location: 'operation', reason: `${e.file}: ${reason}` }))); const authGaps: CoverageGap[] = authErrors.filter((e) => !!op.operationId && e.includes(`"${op.operationId}"`) || (op === ops[0] && !/operation "/.test(e))).map((reason) => ({ code: 'INVALID_REVIEWED_CONFIG', location: 'request.security', reason })); - const collGaps: CoverageGap[] = [...authGaps, ...fixtureGaps, ...(collectionErrors.get(op.key) ?? []), ...(collPlan?.gaps ?? []), ...(coll ? [] : collectionGaps(spec.doc, op, false))]; + const sourceGaps: CoverageGap[] = (o.sourceErrors ?? []).filter((e) => e.operationId === op.operationId).map((e) => ({ code: 'INVALID_REVIEWED_CONFIG', location: 'operation', reason: e.reason })); + const collGaps: CoverageGap[] = [...sourceGaps, ...authGaps, ...fixtureGaps, ...(collectionErrors.get(op.key) ?? []), ...(collPlan?.gaps ?? []), ...(coll ? [] : collectionGaps(spec.doc, op, false))]; // Positive body variants of a create / update with a confirmed chain (written with cleanup only). let variantResult: { variants: BodyVariant[]; gaps: CoverageGap[] } | undefined; if (plan && input.positive && !op.deprecated && (plan.chain.create === op || (plan.chain.update === op && plan.updatePayload !== undefined))) { @@ -452,6 +464,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp negativeGaps: why, lifecycle: plan ? plan.chain.name : null, gaps: [...bodyGaps, ...errors.gaps, ...variantGaps, ...responseGaps, ...collGaps, ...probed.gaps], + ...(input.source?.ai ? { aiProposed: [{ kind: 'source' as const, from: input.source.from.key, pointer: input.source.pointer, reason: input.source.reason }] } : {}), ...(coll || fixture || collGaps.length ? { collection: { ...collectionStrategy(collPlan, collGaps.map((g) => g.reason), !!fixture), tests: [...(collPlan?.tests ?? []).map((t) => ({ kind: t.kind, mode: t.mode })), ...(fixture ? [{ kind: 'fixture', mode: 'approved' }] : [])] } } : {}), ...(bodyStats ? { bodyCases: bodyStats } : {}), suites: { @@ -510,6 +523,7 @@ export async function generate(spec: LoadedSpec, ops: Operation[], o: GenerateOp if (!coverage.some((c) => c.operation === f.op.key && c.collection?.tests.some((t) => t.kind === 'fixture'))) continue; await write(join(support, 'approved', py ? `${fixtureModule(f)}.json` : `${fixtureModule(f)}.fixture.ts`), py ? JSON.stringify(f.fixture, null, 2) + '\n' : tsFixtureModule(f, o.version)); } + if (files.length && o.aiCache && Object.keys(o.aiCache).length) await write(join(support, 'ai-sources.json'), canonicalJson({ note: 'AI answers (unreviewed) for read-only path-value sources; reused on regeneration. Move an entry into the deps file "sources" to make it reviewed.', answers: o.aiCache })); if (files.length && py) { // Self-contained support code: the generated suite runs without the agent installed. await write(join(support, 'contract.py'), await readFile(fileURLToPath(new URL('../../src/contract/contract.py', import.meta.url)), 'utf8')); diff --git a/src/generate/graph.ts b/src/generate/graph.ts index b6fb821..7d93c30 100644 --- a/src/generate/graph.ts +++ b/src/generate/graph.ts @@ -44,6 +44,8 @@ export interface Candidate { } export interface DepsFile { + /** Reviewed read-only sources of path values: { operationId, param, from, pointer } (src/ai/sources.ts). */ + sources?: import('../ai/sources.js').SourceConfig[]; /** Reviewed credentials for 401 / 403 cases, by environment variable name (never the values). */ auth?: import('./error-cases.js').AuthConfig; scenarios: { diff --git a/src/generate/python.ts b/src/generate/python.ts index ed23390..ee6fc0f 100644 --- a/src/generate/python.ts +++ b/src/generate/python.ts @@ -256,6 +256,7 @@ def pytest_configure(config): "positive": "the request is expected to succeed / the response to conform", "negative": "the request is expected to be rejected", "exploratory": "a probe that records the API's answer and never fails on it", + "ai_proposed": "built from an AI proposal that no human has reviewed yet (read-only)", }.items(): config.addinivalue_line("markers", f"{name}: {text}") config.addinivalue_line("markers", "api_case_id(id): stable case ID from _support/cases.json") @@ -442,6 +443,28 @@ function pyPositive(s: SuiteInput, name: string, assert: (indent: string) => str const chain = plan?.chain; const role = roleOf(op, plan); const res = plan ? resourceModule(plan).replace(/_resource$/, '') : ''; + if (!role && s.source) { + // List → read by id: the path value is an existing record's, never invented; no record → skipped with the reason. + const src = s.source; + const why = `${src.param} from ${src.from.key} #${src.pointer}`; + return [ + ...(src.ai ? ['@pytest.mark.ai_proposed'] : []), + POS, + `def ${name}(api, contract):`, + ` # ${src.ai ? 'AI-proposed, unreviewed' : 'Source: deps file (reviewed)'}: ${why}.`, + ` source = api.${src.from.method}(${pathExpr(src.from)}${pyRequired(src.from)})`, + ' # The source is a precondition, not the operation under test: refused (e.g. needs another role) -> skipped.', + ' if not source.ok:', + ` pytest.skip(f"${src.from.key} answered {source.status_code}: no existing record to read (read-only)")`, + ` value = read_pointer(source.json(), ${str(src.pointer)})`, + ' if value is None:', + ` pytest.skip(${str(`no existing record in ${src.from.key} to read (read-only)`)})`, + ` res = api.${op.method}(${pathExpr(op, src.param, 'value')}${pyRequired(op)})`, + ...assert(' '), + '', + '', + ]; + } if (!role) { return [POS, `def ${name}(api, contract):`, ` res = api.${op.method}(${pathExpr(op)}${pyRequired(op)})`, ...assert(' '), '', '']; } diff --git a/src/generate/templates.ts b/src/generate/templates.ts index 46e8eb0..9bbfa9d 100644 --- a/src/generate/templates.ts +++ b/src/generate/templates.ts @@ -11,6 +11,7 @@ import { tsCollectionImports, tsCollectionPrelude, tsCollectionTests, tsFixtureI import type { LoadedFixture } from '../fixtures/fixtures.js'; import type { BodyVariant } from './variants.js'; import type { Probe } from './probes.js'; +import type { ResolvedSource } from '../ai/sources.js'; import { tsVariantImports, tsVariantTests } from './variant-render.js'; /** Payloads and assumptions for one confirmed resource chain. */ @@ -253,6 +254,8 @@ export interface SuiteInput { bodyVariants?: BodyVariant[]; /** Exploratory query probes (record the API's answer, never fail on it). */ probes?: Probe[]; + /** A path value read from existing data first (deps "sources" or AI-proposed). */ + source?: ResolvedSource; } export type Role = 'create' | 'read' | 'update' | 'delete'; @@ -318,6 +321,26 @@ function positiveTest(s: SuiteInput, title: string, assert: (indent: string) => const role = roleOf(op, plan); const ref = refs.get(op)!; const call = (idVar?: string, options?: string) => apiCall(ref, 'api', pathArgs(op, ref, chain?.param, idVar), optionsWith(op, options)); + if (!role && s.source) { + // List → read by id: the path value is an existing record's, never invented; no record → skipped with the reason. + const src = s.source; + const fref = refs.get(src.from)!; + const fx = isPublic(op) && isPublic(src.from) ? 'publicApi' : 'api'; + const why = `${src.param} from ${src.from.key} #${src.pointer}`; + return [ + ` test(${q(title)}, ${POS}, async ({ ${fx} }) => {`, + ` // ${src.ai ? `AI-proposed, unreviewed (${src.reason.replace(/\s+/g, ' ').slice(0, 160)})` : 'Source: deps file (reviewed)'}: ${why}.`, + ...(src.ai ? [` test.info().annotations.push({ type: 'ai-proposed', description: ${q(`unreviewed source: ${why}`)} });`] : []), + ` const source = await ${apiCall(fref, fx, pathArgs(src.from, fref), optionsWith(src.from))};`, + ` // The source is a precondition, not the operation under test: refused (e.g. needs another role) → skipped.`, + ` test.skip(!source.ok(), ${q(`${src.from.key} answered `)} + source.status() + ': no existing record to read (read-only)');`, + ` const value = readPointer(await source.json(), ${q(src.pointer)});`, + ` test.skip(value === undefined || value === null, ${q(`no existing record in ${src.from.key} to read (read-only)`)});`, + ` const res = await ${apiCall(ref, fx, pathArgs(op, ref, src.param, 'String(value)'), optionsWith(op))};`, + ...assert(' '), + ` });`, + ]; + } if (!role) { const opts = optionsWith(op); const fx = apiFixture(op); @@ -388,7 +411,7 @@ export function renderFunctional(s: SuiteInput, meta: Meta): string { const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || !!(s.errors?.preconditionFailed && plan) || !!s.collection?.plan.tests.length || !!s.bodyVariants?.length; const errorStatus = !!(s.errors?.invalidCredentials || s.errors?.envCredentials?.length || s.errors?.methodNotAllowed || s.errors?.preconditionFailed); const coll = s.collection?.plan.tests.length ? s.collection : undefined; - const names = [...new Set(['expect', ...(s.positive && (role === 'create' || role === 'read') ? ['readPointer'] : []), ...(s.notFound || s.unauthorized || errorStatus ? ['expectStatus'] : []), ...(coll ? tsCollectionImports('functional') : []), ...(s.fixture ? ['itemsOf', 'expectMatchesFixture'] : []), ...tsVariantImports(s), ...(s.positive && !plan && op.method === 'get' && queryVariants(op).length ? ['expectContract'] : [])])]; + const names = [...new Set(['expect', ...(s.positive && (role === 'create' || role === 'read') ? ['readPointer'] : []), ...(s.notFound || s.unauthorized || errorStatus ? ['expectStatus'] : []), ...(coll ? tsCollectionImports('functional') : []), ...(s.fixture ? ['itemsOf', 'expectMatchesFixture'] : []), ...tsVariantImports(s), ...(s.positive && !plan && op.method === 'get' && queryVariants(op).length ? ['expectContract'] : []), ...(s.source ? ['readPointer'] : [])])]; const L = suiteHeader('functional', s, meta, ['Checks the behavior of the endpoint: status and result. The response schema is checked in contract.spec.ts.', ...(coll ? ['Collection checks run on records the tests create (controlled datasets) or, where marked read-only, on existing data.'] : [])]); L.push(...imports(s, names, usesHelpers), ...(s.fixture ? [tsFixtureImport(s.fixture)] : []), ...(coll ? ['', ...tsCollectionPrelude(s, coll)] : ['']), `test.describe('${op.key} · functional', { tag: '@functional' }, () => {`); @@ -580,7 +603,7 @@ export function renderContract(s: SuiteInput, meta: Meta): string { const usesHelpers = (s.positive && !!role) || notFoundNeedsHelpers(s) || (s.bodyCases.length > 0 && !!chain && (isCreate || needsExisting)) || wrongMedia; // Validation cases go through the same fixture as the positive test (anonymous for public operations). const fx = chain ? 'api' : apiFixture(op); - const names = [...(s.positive || s.notFound || s.unauthorized ? ['expectContract'] : []), ...(invalid ? ['expectRejected'] : []), ...(s.paramCases.some((c) => c.sent) || s.probes?.length ? ['expectSentQuery'] : []), ...(s.probes?.length ? ['recordProbe'] : [])]; + const names = [...(s.source ? ['expect', 'readPointer'] : []), ...(s.positive || s.notFound || s.unauthorized ? ['expectContract'] : []), ...(invalid ? ['expectRejected'] : []), ...(s.paramCases.some((c) => c.sent) || s.probes?.length ? ['expectSentQuery'] : []), ...(s.probes?.length ? ['recordProbe'] : [])]; const L = suiteHeader('contract', s, meta, ['Checks conformance to the OpenAPI document: the status actually returned is documented and the body matches its schema.', 'Invalid requests break one documented constraint each and must get a documented rejection.']); L.push(...imports(s, names, usesHelpers)); if (s.bodyCases.length + s.paramCases.length > 0) L.push('', `const rejection = ${JSON.stringify(s.validation)}; // documented in the spec`); diff --git a/src/report/report.ts b/src/report/report.ts index 7d1583e..6204930 100644 --- a/src/report/report.ts +++ b/src/report/report.ts @@ -34,6 +34,8 @@ export interface AuditReport { scenarios: { name: string; status: Status; reason: string; operations: string[] }[]; /** Test data cleanup could not remove during the run: it stays on the target. */ cleanupFailures?: { operation: string; id: string; status: number | string }[]; + /** The AI step: whether it ran, through which tool, and what it proposed (dependencies) or contributed (sources). */ + ai?: { enabled: boolean; runner: string | null; reason: string; usage: unknown; sources: unknown[]; dependencies: unknown[] }; /** Exploratory probe outcomes: observations for a human, never confirmed defects. */ exploratory?: { operation: string; parameter: string; probe: string; value: string | null; status: number; documented: boolean; contract: string; serverError: boolean }[]; /** After a run: every physical test has its own case ID registered in cases.json. */ @@ -132,6 +134,18 @@ export function toMarkdown(r: AuditReport): string { L.push('## ⚠️ Test data left on the target', '', `Cleanup could not remove ${left.length} record(s) created by the run. Remove them by hand, or fix the cleanup (e.g. an account allowed to delete) before running again.`, ''); L.push('| Cleanup operation | Status | Id |', '|---|---|---|', ...left.map((f) => `| \`${f.operation}\` | ${f.status} | \`${f.id}\` |`), ''); } + const ai = r.generated?.ai; + if (ai) { + const rows = ai.sources as { operation: string; param: string; status: string; reason: string; answer?: { from: string | null; pointer: string | null } }[]; + const used = rows.filter((x) => x.status === 'used' || x.status === 'cached'); + L.push('## AI participation', '', !ai.enabled ? 'Off (`--no-ai`): generated without the AI step.' : ai.runner ? `On, via ${ai.runner}. Only operation names, summaries, field names and types were sent; no data, no examples.` : `On, but ${ai.reason}: generated without the AI step${used.length ? ' (cached answers of an earlier run were reused)' : ''}.`, ''); + if (used.length) { + L.push(`${used.length} read-only test(s) take a path value from existing data where the AI found it (marked \`ai-proposed\`, unreviewed). To keep one, copy it into the deps file \`sources\`.`, ''); + L.push('| Operation | Parameter | From | Pointer | |', '|---|---|---|---|---|', ...used.map((x) => `| \`${x.operation}\` | \`${x.param}\` | \`${x.answer?.from}\` | \`${x.answer?.pointer}\` | ${x.status} |`), ''); + } + const rejected = rows.filter((x) => x.status === 'rejected'); + if (rejected.length) L.push(`Rejected (not used): ${rejected.map((x) => `\`${x.operation}\` (${x.reason})`).join('; ')}.`, ''); + } const probes = r.generated?.exploratory ?? []; if (probes.length) { const notable = probes.filter((p) => p.serverError || !p.documented || p.contract !== 'matches'); diff --git a/tests/unit/ai-sources.test.ts b/tests/unit/ai-sources.test.ts new file mode 100644 index 0000000..08a75ce --- /dev/null +++ b/tests/unit/ai-sources.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'vitest'; +import { mkdtemp, readFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { loadSpec } from '../../src/spec/loader.js'; +import { buildCatalog } from '../../src/spec/catalog.js'; +import { generate } from '../../src/generate/generate.js'; +import { AiRunner, type Exec } from '../../src/ai/runner.js'; +import { proposeSources, reviewedSources, sourceTargets, verifySource } from '../../src/ai/sources.js'; + +/** AI step on by default: read-only sources of path values, verified against the spec, cached, marked AI-proposed. */ + +const demo = await loadSpec('demo-api/openapi.yaml'); +const ops = buildCatalog(demo.doc); +const op = (k: string) => ops.find((o) => o.key === k)!; +const report = op('GET /reports/{reportId}'); + +/** A console tool that always gives this answer (runner "command", no real AI). */ +const fake = (answer: unknown) => { + const exec: Exec = async () => ({ code: 0, stdout: JSON.stringify(answer), stderr: '' }); + return new AiRunner({ runner: 'command', command: 'fake-ai', maxCalls: 5 }, exec); +}; +const log = () => {}; + +describe('spec check of a source (AI answer or deps entry)', () => { + it('accepts a safe list operation, an existing pointer and a fitting type', () => { + expect(verifySource(demo.doc, ops, report, 'reportId', 'listItems', '/items/0/id').problem).toBeUndefined(); + }); + + it('rejects what the spec does not support, never guessing', () => { + expect(verifySource(demo.doc, ops, report, 'reportId', 'nope', '/items/0/id').problem).toContain('is not in the spec'); + expect(verifySource(demo.doc, ops, report, 'reportId', 'createItem', '/id').problem).toContain('not a safe list operation'); + expect(verifySource(demo.doc, ops, report, 'reportId', 'listItems', '/items/0/missing').problem).toContain('does not exist'); + expect(verifySource(demo.doc, ops, report, 'reportId', 'listItems', '/items/0/price').problem).toContain('type mismatch'); + expect(verifySource(demo.doc, ops, report, 'other', 'listItems', '/items/0/id').problem).toContain('no path parameter'); + }); + + it('a deps-file source with a problem is reported, never used', () => { + const r = reviewedSources(demo.doc, ops, [{ operationId: 'getReport', param: 'reportId', from: 'listItems', pointer: '/nope' }]); + expect(r.sources).toEqual([]); + expect(r.errors[0].reason).toContain('does not exist'); + }); +}); + +describe('the AI step', () => { + const targets = sourceTargets(ops, () => false); + + it('targets only safe operations blocked by one unknown path value', () => { + expect(targets.map((t) => `${t.op.key} ${t.param}`)).toEqual(['GET /items/{itemId} itemId', 'GET /reports/{reportId} reportId']); + }); + + it('uses a verified answer, rejects a low-confidence one, and replays the cache without AI', async () => { + const one = [{ op: report, param: 'reportId' }]; + const good = await proposeSources(demo.doc, ops, one, fake({ from: 'listItems', pointer: '/items/0/id', confidence: 'high', reasoning: 'r' }), {}, log); + expect(good.sources.map((s) => [s.from.key, s.pointer, s.ai])).toEqual([['GET /items', '/items/0/id', true]]); + expect(good.proposals[0].status).toBe('used'); + const low = await proposeSources(demo.doc, ops, one, fake({ from: 'listItems', pointer: '/items/0/id', confidence: 'low', reasoning: 'r' }), {}, log); + expect(low.sources).toEqual([]); + expect(low.proposals[0].reason).toBe('model confidence is low'); + const bad = await proposeSources(demo.doc, ops, one, fake({ from: 'listItems', pointer: '/total', confidence: 'high', reasoning: 'r' }), {}, log); + expect(bad.proposals[0].reason).toContain('rejected by the spec check'); + // No AI available: the cached answer gives the same source; an uncached target is simply not asked. + const replay = await proposeSources(demo.doc, ops, one, undefined, good.cache, log); + expect(replay.sources.map((s) => s.pointer)).toEqual(['/items/0/id']); + expect(replay.proposals[0].status).toBe('cached'); + const without = await proposeSources(demo.doc, ops, one, undefined, {}, log); + expect(without.sources).toEqual([]); + expect(without.proposals[0]).toEqual(expect.objectContaining({ status: 'not-asked', reason: 'AI not available' })); + }); + + it('a broken tool stops the AI step, not the run', async () => { + const exec: Exec = async () => ({ code: 1, stdout: '', stderr: 'not logged in' }); + const r = await proposeSources(demo.doc, ops, targets, new AiRunner({ runner: 'command', command: 'x' }, exec), {}, log); + expect(r.sources).toEqual([]); + expect(r.proposals.every((p) => p.status === 'not-asked')).toBe(true); + }); +}); + +describe('generated read-only tests from a source', () => { + it('list → read by id, skipped without data or when the source is refused, marked AI-proposed, same cases in TS and Python', async () => { + const r = await proposeSources(demo.doc, ops, [{ op: report, param: 'reportId' }], fake({ from: 'listItems', pointer: '/items/0/id', confidence: 'high', reasoning: 'r' }), {}, log); + const gen = async (lang: 'typescript' | 'python') => { + const dir = await mkdtemp(join(tmpdir(), 'ata-ai-')); + const res = await generate(demo, ops, { outDir: dir, version: 'test', lang, sources: r.sources, aiCache: r.cache }); + return { dir, res, read: (f: string) => readFile(join(dir, f), 'utf8') }; + }; + const ts = await gen('typescript'); + const py = await gen('python'); + const fn = await ts.read('reports/get-by-id/functional.spec.ts'); + expect(fn).toContain("const value = readPointer(await source.json(), '/items/0/id');"); + expect(fn).toContain("test.skip(!source.ok(),"); + expect(fn).toContain("type: 'ai-proposed'"); + expect(fn).toContain('String(value)'); + expect(await py.read('reports/get_by_id/test_functional.py')).toContain('@pytest.mark.ai_proposed'); + const cov = ts.res.coverage.find((c) => c.operation === 'GET /reports/{reportId}')!; + expect(cov.positiveBlocked).toBeNull(); + expect(cov.aiProposed).toEqual([expect.objectContaining({ kind: 'source', from: 'GET /items', pointer: '/items/0/id' })]); + const active = async (g: typeof ts) => Object.entries(JSON.parse(await g.read('_support/cases.json')).cases).filter(([, c]) => c.status !== 'retired').map(([id]) => id).sort(); + expect(await active(py)).toEqual(await active(ts)); + expect(JSON.parse(await ts.read('_support/ai-sources.json')).answers).toEqual(r.cache); + }); +});