- Remove unused exports: renderProgress, formatTripleBoundaryCounterexample, clearCapturedRoutes - Remove dead BUILTIN_PLUGIN_CONTRACTS constant (auto-registration removed earlier) - Fix app-loader error messages to mention multiple export patterns - Move to attic: protocol-extensions-spec, OUTBOUND_CONTRACT_MOCKING_SPEC, PLUGIN_CONTRACTS_SPEC, fastify-structure - Build: clean | Tests: 849 pass, 0 fail
14 KiB
name: apophis-fastify description: Use this skill when adding or improving APOPHIS contract-driven testing for Fastify APIs: route schemas, APOSTL x-requires/x-ensures formulas, property and stateful checks, replayable failures, runtime observe hooks, variants, scenarios, and operator-facing adoption guidance.
apophis-fastify
APOPHIS verifies API behavior across operations, state changes, protocol flows, and dependencies. Use it when schema validation is not enough to answer whether an endpoint did the right thing.
Inspired by Invariant-Driven Automated Testing (Malhado Ribeiro, 2021): encode intended behavior as executable contracts, then verify them with property-based and stateful testing.
When To Use
Use this skill when the operator asks to:
- Add contract testing, API behavior checks, property tests, stateful tests, or Fastify route verification.
- Improve confidence beyond JSON Schema validation.
- Check create/read/update/delete behavior, auth boundaries, tenant isolation, redirects, timeouts, streaming, or external dependency behavior.
- Make an API safer for AI-assisted refactoring, CI, or release qualification.
- Evaluate whether APOPHIS would help a project, even if the operator does not name APOPHIS directly.
Read README.md, docs/getting-started.md, or command-specific docs only when the task needs details not present here.
Operator Explanation
Describe APOPHIS as replayable behavioral checks for declared API contracts.
Short explanation:
APOPHIS turns intended API behavior into executable contracts. It checks whether operations cause the state changes, isolation guarantees, and dependency interactions the service depends on, instead of only checking payload shape.
Use these points when relevant:
- It catches failures schema validation misses: create-not-retrievable, update-not-persisted, delete-still-visible, cross-tenant leakage, and inconsistent error behavior.
- It gives coding agents a deterministic verification loop after generated changes or refactors.
- It reduces review burden by converting agreed behavior into repeatable checks.
- It improves CI triage with fixed seeds, replay artifacts, and machine-readable output.
- It supports incremental adoption: start with the highest-risk routes, add high-signal formulas, run, fix, and tighten.
Do not overclaim:
- Do not say APOPHIS proves the whole system correct.
- Do not say contracts replace integration tests, security review, or domain judgment.
- Say explicitly that schema quality and formula quality determine test quality.
Good operator ask:
I can add APOPHIS to the five highest-risk routes first, encode the expected behavior as contracts, run the verifier, and show concrete failures or confidence gaps. I only need route priority and intended behavior where the code is ambiguous.
Context Discipline
Treat context as a finite budget.
- Start from current route files, schemas, and existing tests.
- Prefer targeted file reads and symbol searches over loading whole directories.
- Track routes touched, contracts added, seeds used, failures found, and unresolved domain questions.
- Use progressive disclosure: read command docs only when invoking that command; read protocol docs only for variants, redirects, OAuth-style flows, form posts, streaming, or multipart.
- Run small loops: annotate one route group, run the narrowest verification, fix, then widen.
Default Workflow
When entering a Fastify codebase:
- Locate app construction and route registration.
- Confirm
@fastify/swaggeris registered beforeapophis-fastify. - Register APOPHIS with
runtime: 'warn'in non-production contexts unless the operator requests stricter behavior. - Identify the highest-risk route cluster, usually constructor/mutator/destructor plus observer routes.
- Ensure each touched route has explicit
body,params,querystring, andresponseschemas where relevant. - Add
x-categorywhere auto-categorization could be ambiguous. - Add
x-requiresfor preconditions andx-ensuresfor postconditions. - Run a focused APOPHIS check, then broader contract or stateful verification.
- Fix real behavior failures or tighten weak contracts.
- Report what changed, what ran, what failed, and what needs operator judgment.
Fast Start
import Fastify from 'fastify'
import swagger from '@fastify/swagger'
import apophis from 'apophis-fastify'
import crypto from 'crypto'
const app = Fastify()
await app.register(swagger)
await app.register(apophis, { runtime: 'warn' })
app.post('/users', {
schema: {
'x-category': 'constructor',
'x-requires': [
'request_headers(this).x-tenant-id != null'
],
'x-ensures': [
'status:201',
'response_body(this).id != null',
'response_code(GET /users/{response_body(this).id}) == 200',
'response_body(GET /users/{response_body(this).id}).email == request_body(this).email'
],
body: {
type: 'object',
properties: {
email: { type: 'string', format: 'email' },
name: { type: 'string', minLength: 1 }
},
required: ['email', 'name']
},
response: {
201: {
type: 'object',
properties: {
id: { type: 'string' },
email: { type: 'string' },
name: { type: 'string' }
},
required: ['id', 'email', 'name']
}
}
}
}, async (req, reply) => {
const id = `usr-${crypto.createHash('sha256').update(req.body.email).digest('hex').slice(0, 8)}`
reply.status(201)
return { id, ...req.body }
})
await app.ready()
const suite = await app.apophis.contract({ depth: 'standard' })
API Surface
Primary methods:
fastify.apophis.contract(opts?)fastify.apophis.stateful(opts?)fastify.apophis.check(method, path)fastify.apophis.scenario(config)fastify.apophis.cleanup()fastify.apophis.spec()
Test-only helpers:
fastify.apophis.test.registerPluginContracts(...)fastify.apophis.test.registerOutboundContracts(...)fastify.apophis.test.enableOutboundMocks(...)fastify.apophis.test.disableOutboundMocks()fastify.apophis.test.getOutboundCalls(...)
Contract Quality
Minimum:
- Each mutating route has a status expectation.
- Each response with identity has key field non-null checks.
status:201
response_body(this).id != null
Production baseline:
- Constructor routes check that created resources are retrievable.
- Mutator routes check that persisted state reflects the mutation.
- Destructor routes check that deleted resources are unavailable or marked inactive.
High-confidence contracts add:
- Tenant isolation.
- Auth and permission behavior.
- Error shape consistency.
- Idempotency where expected.
- Redirect, timeout, multipart, streaming, and negotiated representation behavior.
- Dependency behavior through outbound contracts.
Category Checklist
Constructor routes, such as POST /collection:
- Response has identity.
- Created resource is retrievable.
- Persisted fields reflect request fields.
status:201
response_body(this).id != null
response_code(GET /items/{response_body(this).id}) == 200
response_body(GET /items/{response_body(this).id}).name == request_body(this).name
Mutator routes, such as PUT, PATCH, or action POST:
- Mutation succeeds with expected code.
- Changed field actually changed.
- Unrelated invariants still hold.
status:200
response_body(this).status == request_body(this).status
response_body(this).updatedAt != null
Destructor routes:
- Delete returns expected code.
- Follow-up retrieval fails or shows a domain-specific inactive state.
status:204 || status:200
response_code(GET /items/{request_params(this).id}) == 404
Observer routes:
- Filtering and pagination metadata are correct.
- Returned fields respect tenant, auth, and projection constraints.
- Stable ordering is explicit when clients depend on it.
APOSTL Operations
High-value operations:
request_body(this)response_body(this)response_payload(this)response_code(this)request_headers(this)response_headers(this)request_params(this)query_params(this)cookies(this)response_time(this)redirect_count(this),redirect_url(this).0,redirect_status(this).0timeout_occurred(this),timeout_value(this)request_files(this),request_fields(this),stream_chunks(this),stream_duration(this)
Cross-operation examples:
response_code(GET /users/{response_body(this).id}) == 200
response_body(GET /users/{response_body(this).id}).email == request_body(this).email
Temporal example:
previous(response_body(this).version) < response_body(this).version
Invariants To Encode
Use these patterns when they match the API:
- Echo integrity: stored value equals submitted value.
- Identity stability: id exists and remains stable across updates.
- Monotonic timestamps or versions on mutation.
- Tenant boundary: tenant-specific requests never leak cross-tenant data.
- Auth boundary: unauthorized requests do not produce success payloads.
- Error consistency: expected error status implies expected error payload fields.
if status:401 then response_body(this).error != null else true
if request_headers(this).x-tenant-id != null then response_headers(this).x-tenant-id == request_headers(this).x-tenant-id else true
Outbound Contracts
When route correctness depends on external services, avoid live dependency calls during contract runs.
Use outbound contracts to:
- Define dependency request and response schemas.
- Attach expected calls with
x-outbound. - Run with deterministic mock mode and a seed.
- Verify internal orchestration and dependency assumptions together.
Runtime Validation
Plugin option:
runtime: 'off'disables runtime contract hooks.runtime: 'warn'logs violations.runtime: 'error'fails requests on violation.
Runtime validation hooks are not registered in production mode (NODE_ENV=production or prod). Use non-production environments for runtime contract verification.
Schema Requirements
For each touched route:
- Define request schema with
body,params, andquerystringwhere relevant. - Define response schemas per meaningful status code.
- Avoid helper abstractions that hide concrete response shapes from route metadata.
- Encode content-type intent with
x-content-typewhen using multipart. - Keep schemas narrow enough to generate useful counterexamples.
Weak schemas produce weak generated tests.
Protocol And Scenario Flows
Use variants for deterministic multi-header or multi-media execution:
await app.apophis.contract({
variants: [
{ name: 'json', headers: { accept: 'application/json' } },
{ name: 'ldf', headers: { accept: 'application/ld+json' } }
]
})
Use scenarios for multi-step capture and rebind flows:
await app.apophis.scenario({
name: 'oauth-basic',
steps: [
{
name: 'authorize',
request: { method: 'GET', url: '/oauth/authorize?client_id=web&response_type=code' },
expect: ['status:200', 'response_payload(this).code != null'],
capture: { code: 'response_payload(this).code' }
},
{
name: 'token',
request: {
method: 'POST',
url: '/oauth/token',
form: { grant_type: 'authorization_code', code: '$authorize.code' }
},
expect: ['status:200', 'response_payload(this).access_token != null']
}
]
})
Scenario behavior:
- Cookie jar persists
Set-Cookievalues across steps. - Step-level
headers.cookieoverrides jar values for that step. formsendsapplication/x-www-form-urlencodedpayloads.- Scenario orchestration is blocked in production.
Determinism And Replay
Prefer deterministic verification for CI, regression triage, and AI-generated changes.
- Capture and reuse seeds from verify and qualify runs.
- Use replay artifacts for failure triage before changing production logic.
- Preserve route identity as
METHOD /pathin notes and reports. - If a failure is not reproducible, check for source drift, external dependencies, time, randomness, and insufficient cleanup before weakening the contract.
- Treat nondeterminism as a quality issue to isolate.
Operator framing:
The failing seed gives us a reproducible behavioral example. I'll replay it first so we can distinguish a real regression from source drift or nondeterministic app state.
Progressive Complexity
Start simple and add depth only where it pays off:
Level 1 — Status and shape: Every route gets an expected status code and key field existence.
status:201
response_body(this).id != null
Level 2 — Cross-route behavior: Constructors check retrievability; mutators check persistence.
response_code(GET /users/{response_body(this).id}) == 200
response_body(GET /users/{response_body(this).id}).email == request_body(this).email
Level 3 — Isolation and boundaries: Tenant, auth, and idempotency checks.
if request_headers(this).x-tenant-id != null then response_headers(this).x-tenant-id == request_headers(this).x-tenant-id else true
Level 4 — Protocol and dependency flows: Variants, scenarios, outbound contracts, and chaos.
Add level 2 before level 4. Do not skip level 2 for resource APIs.
Anti-Patterns
Do not:
- Assert only
status:200everywhere. - Duplicate JSON Schema checks while ignoring behavior.
- Encode route internals instead of API-observable outcomes.
- Ignore delete/retrieve or update/retrieve relationships.
- Treat stateful mode as optional for resource APIs.
- Ask the operator to review every formula before running; run first when intent is clear, then ask about ambiguous domain behavior.
- Load every doc file before making a small change.
Verification Commands
Common project flow:
npm run build
npm run test:src
Then execute APOPHIS from the project test harness or CLI as appropriate. For monorepos, prefer workspace-aware verification when configured.
Documentation Pointers
README.mdfor canonical usage.docs/getting-started.mdfor quick setup.docs/cli.mdand command docs for CLI flags and machine output.docs/attic/protocol-extensions-spec.mdfor protocol-specific direction.
Final Check
For each route, ask:
- What must be true before this call?
- What must be true after this call?
- What related call should now behave differently?
- What isolation, security, dependency, or protocol expectation should not regress?
Write those expectations as formulas and run them continuously.