Skip to content

About

Self-hosted, BYOK CI agent that syncs OpenAPI specs, fuzzes contracts with Schemathesis, and generates pytest coverage for PR diffs — without touching production code.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Use this GitHub action with your project
Add this Action to an existing workflow or create a new one
View on Marketplace

Repository files navigation

English | 한국어

diff-api-agent

CI Python 3.10+ License: MIT

A self-hosted, BYOK CI agent that verifies and strengthens backend PRs inside your own runner — without ever touching production code.

When a developer opens a PR, diff-api-agent reads only git diff base...HEAD, then:

  1. Syncs your OpenAPI spec with a minimal RFC 6902 JSON Patch (preserving YAML comments & formatting)
  2. Boots your real API server and fuzzes the contract with Schemathesis
  3. Generates and self-corrects pytest tests to close PR diff coverage gaps
  4. Commits one atomic commit to the PR only if every deterministic gate exits 0
git diff ──▶ ① DiffAnalyzer ──▶ ② SpecSyncEngine ──▶ ③ ContractFuzzer ──▶ ④ TestGenerator ──▶ ⑤ Gate + GitBot
            AST pinpoint        JSON Patch +          --setup-cmd +         pytest --cov gap      all exit 0 ?
            ≤100k tokens        openapi-spec-validator auth + schemathesis  Ralph loop (≤10x)     → 1 commit → PR

What It Looks Like on a Real PR

1. Minimal OpenAPI Drift Sync (Comments Preserved)

Instead of rewriting your entire openapi.yaml, the agent applies a targeted RFC 6902 JSON Patch via ruamel.yaml and validates with openapi-spec-validator:

 # Public Orders API specification
 openapi: '3.1.0'
 info:
   title: "Orders API"  # managed externally for gateway
   version: '1.0.0'
 paths:
   /orders:
     get:
       summary: List orders
+  /orders/{order_id}:
+    delete:
+      summary: Cancel an order
+      responses:
+        '204':
+          description: Order cancelled

2. Deterministic Gate Report (agent_report.md)

When every gate exits 0, diff-api-agent writes .agent_work/agent_report.md and stages only the spec update + newly generated tests/test_*.py:

| Gate | Status | Required | Detail |
|---|---|---|---|
| openapi | updated | yes | Added DELETE /orders/{order_id} |
| schemathesis | passed | yes | 43 generated, 43 passed (0 errors) |
| pytest_diff | passed | yes | Uncovered diff lines: 14 -> 0 (1 iteration) |

3. Production Bug Caught Before Merge (fix_plan.md)

If Schemathesis hits a 500 or your code fails under test, nothing is committed. The agent writes .agent_work/fix_plan.md with masked secrets (<REDACTED>) and exact cURL repro commands:

## Schemathesis contract fuzzing failed (exit 1)
- DELETE /orders/99999 -> 500 Internal Server Error (KeyError in app/orders.py)

### Reproduce
curl -X DELETE -H "Authorization: Bearer <REDACTED>" http://127.0.0.1:8000/orders/99999

Quickstart (GitHub Actions in 10 Lines)

Add this to .github/workflows/api-agent.yml in your backend repository:

- uses: actions/checkout@v4
  with:
    fetch-depth: 0
- uses: novoodi/diff-api-agent@v0
  env:
    ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}   # or OPENAI_API_KEY
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  with:
    base-branch: ${{ github.base_ref }}
    base-url: http://127.0.0.1:8000
    app-cmd: "python -m uvicorn app.main:app --port 8000"
    health-path: /health
    cov: app

Why diff-api-agent?

Built to fill the gap between generic AI PR bots and SaaS API testing platforms:

Capability Generic AI PR Bots
(Copilot, CodeRabbit, Qodo)
Commercial API Tools
(Optic, Postman, Keploy)
diff-api-agent
OpenAPI drift repair Static review or risky full-file rewrites Detects only (manual fix) RFC 6902 JSON Patch + comment preservation + Validator
Contract fuzzing (500 / schema) None (static review) Strong (cloud/team tiers) Boots real server per PR → Schemathesis + cURL repro
Diff line coverage Disconnected from API contract None Closes Cobertura ∩ git diff gaps + blocks regressions
Production code safety Agent can edit application code N/A Physically blocked (tests/ only) + aborts on bugs
Data sovereignty / BYOK Vendor SaaS + GitHub App access SaaS-centric 100% inside your CI · Anthropic / OpenAI / local gateway

Where It Shines Most

  1. Flask / Django / Legacy Python Backends: Frameworks without automatic OpenAPI generation where openapi.yaml drifts from route handlers on every PR → examples/flask_orders_api/
  2. Spec-first / Public API FastAPI Teams: Teams maintaining an external gateway/public contract alongside app.openapi(), needing authenticated contract fuzzing and automatic diff coverage → examples/sample_api/

Local Installation

python -m venv .venv
source .venv/bin/activate && pip install -e .    # macOS / Linux
# .venv\Scripts\pip install -e .                  # Windows
cp .env.example .env                              # Configure Anthropic / OpenAI / local LLM

Or install directly into an isolated environment (recommended when running in the same repo as other tools):

pipx install "git+https://github.com/novoodi/diff-api-agent.git"

BYOK Multi-Provider Configuration

Set ANTHROPIC_API_KEY or OPENAI_API_KEY and --provider auto picks the right backend automatically. Any OpenAI-compatible endpoint works (OpenAI, Google Gemini, LiteLLM, vLLM, Ollama, or internal corporate gateways):

Provider Environment Variables --provider
Anthropic Claude ANTHROPIC_API_KEY=sk-ant-... (optional ANTHROPIC_BASE_URL) anthropic (default claude-opus-5-5)
OpenAI OPENAI_API_KEY=sk-... openai (default gpt-4.1)
Google Gemini (OpenAI-compat) OPENAI_API_KEY=..., OPENAI_BASE_URL=https://generativelanguage.googleapis.com/v1beta/openai, AGENT_MODEL=gemini-2.5-pro openai
Self-hosted / vLLM / Ollama OPENAI_BASE_URL=http://localhost:11434/v1, AGENT_MODEL=qwen2.5-coder (OPENAI_API_KEY optional) openai

CLI Usage

# 1) Inspect isolated diff context only (no LLM calls)
diff-api-agent analyze --repo path/to/backend --base main

# 2) Full pipeline with DB seeding + auth header + health check + fuzzing
export API_TOKEN=my-ci-token
diff-api-agent run --repo path/to/backend --base main \
    --setup-cmd "python seed.py" \
    --base-url http://127.0.0.1:8000 \
    --app-cmd "python -m flask --app app run --port 8000" \
    --health-path /health \
    --fuzz-header "Authorization: Bearer ${API_TOKEN}" \
    --cov app \
    --dry-run            # keep changes in checkout without committing

You can also invoke it as python -m diff_api_agent.

Key Options

Flag Default Description
--provider auto auto | anthropic | openai (AGENT_PROVIDER)
--model, --effort auto / high Also configurable via AGENT_MODEL, AGENT_EFFORT
--openapi PATH auto-detect openapi.yaml/json, docs/openapi.*, etc.
--setup-cmd CMD none Setup command run before server boot (migrations/seeding, --setup-timeout 300s)
--base-url, --app-cmd none Target server for Schemathesis. Required when API routes change
--health-path PATH none HTTP GET path polled (< 500) after TCP port opens (e.g. /health)
--fuzz-header HDR none Schemathesis -H header (Name: Value, supports ${ENV_VAR}, repeatable). Redacted in logs
--fuzz-arg ARG none Extra arg forwarded to schemathesis run (e.g. --fuzz-arg=--phases=examples, repeatable)
--fuzz-checks all Schemathesis --checks value (tip: start with not_a_server_error on legacy APIs)
--max-iterations 10 Self-correction loop circuit breaker
--iteration-timeout / --total-timeout 300 / 3600s Per-iteration and total pipeline timeouts
--docker-image IMG none Execute all commands inside a Docker container
--no-worktree off Isolated git worktree by default (composite action sets no-worktree: true in CI)
--lenient off Do not fail approval when optional/unconfigured gates are skipped
--dry-run, --no-push, --no-pr off Control git commit, push, and PR creation/commenting

Outputs (add .agent_work/ to your target repo .gitignore)

  • .agent_work/agent_report.md — Gate table, provider/model, AST pinpoints, before/after diff coverage, LLM token usage
  • .agent_work/fix_plan.md — Failure logs, secret-redacted Schemathesis cURL repros, suspected source bugs
  • Exit code 0 = all required gates passed & committed; 1 = any failure (ready as a CI merge gate)

Architecture

Module Responsibility
diff_api_agent/diff_analyzer.py git diff --name-status + hunk parsing, AST enclosing function/class pinpoints, route detection, token budget guard
diff_api_agent/spec_sync.py Requests RFC 6902 JSON Patch → applies via ruamel.yaml (preserving comments/quotes) → validates with openapi-spec-validator (up to 3 retries)
diff_api_agent/contract_fuzzer.py Runs --setup-cmd → boots server & polls --health-path → runs schemathesis with auth headers → redacts secrets & extracts cURL repros
diff_api_agent/test_generator.py Parses Cobertura XML → finds changed_lines ∩ uncovered_lines → generates new test_*.py → runs full suite regression & coverage loop
diff_api_agent/orchestrator.py Enforces deterministic gates, writes agent_report.md / fix_plan.md, copies approved files back from worktree
diff_api_agent/git_bot.py Stages only generated/synced files, creates 1 atomic commit, pushes, and opens/comments on PR via gh or REST
diff_api_agent/sandbox.py Subprocess runner with timeouts, git worktree isolation, nested COV_CORE_* isolation, process-tree cleanup
diff_api_agent/llm.py Multi-provider LLM client (Anthropic SDK + OpenAI-compatible httpx), strict JSON schema + Pydantic retry + json_object fallback

Safety Guardrails

  • Worktree Isolation: Runs inside a detached git worktree by default; failed runs never touch your working tree.
  • Production Code & Existing Tests Immutable: Only new test_*.py files inside tests/ can be written (existing tests cannot be overwritten). Suspected source bugs stop the loop with bug_found and document details in fix_plan.md.
  • Secret Redaction: --fuzz-header expands ${ENV_VAR} at runtime and masks values as <REDACTED> in fix_plan.md and logs.
  • Circuit Breakers: Hard caps on max iterations (10), per-iteration/total timeouts, and diff context token budget (100k).
  • Atomic Commits: Never commits directly to base_branch, stages only pipeline outputs, creates at most 1 commit.

Known Limitations

  • YAML formatting uses ruamel.yaml round-trip mode to preserve comments, key order, and quotes, while JSON Patch operations on newly inserted blocks serialize with default ruamel.yaml indentation.
  • AST pinpoint and Cobertura diff coverage gap detection target Python source files; non-Python route changes pass diff hunks directly to the LLM.
  • Schemathesis requires a running HTTP server; provide --app-cmd (and optionally --setup-cmd, --health-path) so the agent manages server startup and teardown automatically.

Development & Testing

.venv/Scripts/pip install -e ".[dev]"                  # Windows (includes fastapi/uvicorn/flask)
.venv/Scripts/python -m pytest tests -m "not e2e" -q   # Fast unit/integration suite (no LLM/server)
.venv/Scripts/python -m pytest tests -q                # Full suite incl. real validator/uvicorn/schemathesis/pytest-cov E2E

Examples:

Contributing & License

About

Self-hosted, BYOK CI agent that syncs OpenAPI specs, fuzzes contracts with Schemathesis, and generates pytest coverage for PR diffs — without touching production code.

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages