gadievron/raptor
Claude Code-driven framework that chains Semgrep, CodeQL, fuzzing and binary analysis with LLM validation, exploit and patch generation.
Overview
RAPTOR is a security research framework for source code and compiled binaries. It chains static analysis (Semgrep, CodeQL, Coccinelle), binary analysis, fuzzing and LLM review into pipelines that end with validated findings, proof-of-concept code and patches. It is not a network pentest bot. Apart from an optional /web scanner, it reads repositories and binaries that the operator points it at.
The project has two layers. The interactive layer is Claude Code: the raptor launcher starts a Claude Code session in the repo, and CLAUDE.md plus .claude/commands, .claude/agents and .claude/skills turn slash commands such as /scan, /agentic, /validate and /crash-analysis into fixed command lines or multi-step skill scripts. The second layer is a large Python code base (core/, packages/, libexec/) that does the actual work and also runs standalone without Claude Code. The CLAUDE.md rules are explicit that “Python orchestrates everything” and that the model must run the documented command verbatim (CLAUDE.md).
At this commit the Python side is about 1,800 non-test modules. The code style is very defensive. Many functions carry long “pre-fix” comments that explain a bug and its fix. The authors say in the README that most of the code is AI-written under human review. Expect a lot of mechanism and a steep learning curve.
Architecture
flowchart LR
OP["Operator"] --> CC["Claude Code session (CLAUDE.md, commands, skills)"]
OP --> CLI["raptor.py / libexec CLIs"]
CC --> CLI
CLI --> AG["raptor_agentic.py phases"]
AG --> SCAN["Scanners: Semgrep, CodeQL, Coccinelle"]
AG --> VAL["Exploitability validation + dedup"]
AG --> ORCH["llm_analysis orchestrator"]
ORCH --> TASKS["Analysis / consensus / judge / exploit / patch tasks"]
TASKS --> LLM["LLM client (Anthropic, OpenAI, Gemini, Mistral, Ollama)"]
TASKS --> CCP["claude -p sub-agents (Read, Grep, Glob)"]
SCAN --> SB["core.sandbox (namespaces, Landlock, seccomp)"]
AG --> FUZZ["Fuzzing / binary oracle"]
FUZZ --> SB
ORCH --> OUT["findings.json, SARIF, reports"]
| Component | Path | Role |
|---|---|---|
| Claude Code layer | CLAUDE.md, .claude/commands/, .claude/agents/, .claude/skills/ |
Slash-command dispatch, skill workflows, sub-agents for crash analysis and OSS forensics |
| Mode dispatcher | raptor.py |
scan, agentic, codeql, fuzz, web and other modes with run-lifecycle tracking |
| Agentic pipeline | raptor_agentic.py |
Phases 0-5: mitigation check, scanning, validation, prep, LLM orchestration, fuzzing |
| LLM analysis | packages/llm_analysis/ |
orchestrate(), task classes, Claude Code dispatch, dataflow validation |
| LLM client | core/llm/ |
Providers, model defaults, cost tracking, concurrency caps, multi-model |
| Sandbox | core/sandbox/ |
Profiles, namespaces, Landlock, seccomp, egress proxy, consent gates |
| Prompt defences | core/security/ |
Prompt envelope, envelope probe, repo trust checks, env sanitisation |
| Evidence | core/evidence/ |
Evidence tiers from runtime observation down to LLM heuristic |
| Engagement | core/engagement/ |
Ledger, depth governor and supervisor for long, budgeted binary engagements |
| Web scanner | packages/web/ |
Crawl, fuzz and verify a live web app under a scope receipt |
How a request flows
Take /agentic /path/to/repo from the interactive shell:
- Dispatch. Claude Code reads
.claude/commands/agentic.mdand runslibexec/raptor-agentic --repo <path>with the operator’s flags unchanged (CLAUDE.md). - Scan.
raptor_agentic.pybuilds an inventory checklist, optionally runs an/understandpre-pass, and then startspackages/static-analysis/scanner.pyfor Semgrep (and CodeQL when requested) as subprocesses with the sandbox flags passed through (raptor_agentic.py, L3531-L3543). - Validate and dedup. Phase 2 merges SARIF, SCA, OpenAnt and taint inputs, removes duplicates and runs mechanical enrichment before any LLM call (raptor_agentic.py).
- Prepare. Phase 3 runs
packages/llm_analysis/agent.py. When Claude Code or an external model is available, it runs with--prep-onlyand only writesautonomous_analysis_report.json. If the analysis subprocess reports that the sandbox could not engage, the run aborts instead of continuing unsandboxed (raptor_agentic.py). - Orchestrate. Phase 4 builds an
LLMConfigfrom the flags, applies the cost, time, call and token caps, and callsorchestrate(). The repo trust check is re-run at dispatch time, because scanning may have executed target code (raptor_agentic.py). - Per-finding tasks.
orchestrate()sends findings to external models in parallel or, without one, toclaude -psub-agents. The task chain is analysis (stages A-D), dataflow validation, cross-family check, a self-contradiction retry (stage F), optional consensus and judge, then exploit and patch generation only for findings with a final “exploitable” verdict, and finally cross-finding grouping (orchestrator.py, L1444-L1454). - Fuzz (optional). With
--fuzzand--binary, Phase 5 runs a short fuzzing campaign and merges reproduced crashes into the report (raptor_agentic.py).
Key components
Agent loop
There is no single free-running agent loop. /agentic is a fixed phase pipeline, and inside Phase 4 every finding is an independent structured LLM call (or one claude -p child per finding). Claude Code sub-agents are used in some skills, for example /crash-analysis and /oss-forensics, where the agent files in .claude/agents/ split the work into fetcher, analyzer and checker roles. For long, unattended work on binary installations there is a separate engagement supervisor. It sequences a per-artifact chain over a ledger, runs at most 8 passes, parks an artifact after repeated failures, and refuses to start an LLM-capable engagement without --max-cost, --envelope or an explicit --uncapped (supervise.py). Parks are sticky until the operator acknowledges them.
Tool execution and sandbox
Tools are external programs started with list-based subprocess arguments and a sanitised environment. The core.sandbox package wraps them with user, network, PID, IPC and mount namespaces, Landlock filesystem rules, seccomp-bpf and rlimits, plus an optional HTTPS-CONNECT egress proxy with a hostname allowlist (sandbox/init.py). Profiles set the strictness. The default full profile warns and degrades when the host lacks a backend (for example, Ubuntu 24.04 blocks unprivileged user namespaces by default). Only strict fails closed (profiles.py). If the sandbox module cannot be imported at all, tool runners refuse to run unless RAPTOR_ALLOW_UNSANDBOXED_TOOLS=1 is set (sandbox_policy.py). Turning the sandbox off with --no-sandbox needs a minted nonce that matches a mode-0600 file in the user’s home. A TTY or a boolean env var is not accepted, so an LLM that writes a command line cannot simply disable isolation (disable_consent.py).
Scope and safety controls
Scope is mostly structural. Code analysis only touches the target path the operator gives, and default target resolution refuses scratch or empty directories. The live /web scanner is the one component that sends traffic to a remote system. It builds a ScopeReceipt from the target URL, and WebExecutionPolicy.authorize rejects any action whose origin is not in the receipt, or whose risk class (passive, active, intrusive) is above the approved level, unless that tool was approved explicitly. Every decision is logged into the run report (execution_policy.py). The default approval level is active.
Other controls target the operator’s own machine rather than third parties: prompt-injection envelopes around target-derived text, a canary probe that checks each model handles the envelope before real findings are sent, a refusal to spawn claude -p when the target repo ships its own Claude credential helpers, and CLAUDE.md rules that tell the model to ask before applying patches, deleting or pushing.
LLM analysis and Claude Code dispatch
AnalysisTask builds a prompt bundle per finding with a random nonce and a model defence profile. It asks for a schema-checked verdict and adds a CVSS score to the result (tasks.py). When the work goes to Claude Code, each child runs with a read-only Read,Grep,Glob tool allowlist, the target added as a directory, a JSON schema, and a --max-budget-usd of 1.00 per finding (cc_dispatch.py).
Findings and evidence
Every observation carries an evidence tier, from OBSERVED_RUNTIME and REPLAYED_CRASH through SMT_PROVED and XREF_BACKED down to HEURISTIC for LLM inference (evidence/init.py). Mechanical filters run before the LLM: Z3 reachability on CodeQL paths, a binary oracle that drops findings in functions the compiler removed, and dead-code marking. Generated exploit code for C/C++ is compile-checked with gcc inside the sandbox with networking blocked. Findings are written to findings.json, SARIF and Markdown reports.
Models
core/llm speaks to Anthropic, OpenAI, Gemini and Mistral through their own SDKs, and to Ollama through an OpenAI-compatible endpoint. Defaults are claude-opus-4-6, gpt-5.4, gemini-2.5-pro and mistral-large-latest (model_data.py). ~/.config/raptor/models.json assigns models to roles (analysis, code, consensus, aggregate, fallback). Concurrency is capped at 32 workers, and at 4 for the Claude Code transport (concurrency.py).
State and memory
State lives on disk in the run or project directory: SARIF, findings.json, the agentic report, coverage records and, for engagements, ledger.json plus per-artifact chain-state.json files that let an interrupted chain resume. SAGE is an optional persistent-memory sidecar (Docker plus a sentence-transformers embedding model) for cross-run recall of findings, false positives and methodology.
Extending it
- Rules. Add Semgrep rules under
engine/semgrep/rules/, Coccinelle rules underengine/coccinelle/rules/or CodeQL queries underengine/codeql/queries/. - Commands and skills. A new slash command is a
.claude/commands/<name>.mdfile with adispatch:field. CI checks that the field parses and that its target exists on disk. - Models. Add providers or role assignments in
models.json. Unsupported models can be reached through the Ollama/OpenAI-compatible path. - Personas and guidance.
tiers/holds guidance files thatCLAUDE.mdloads only when their trigger fires.
Running it
- Interactive.
uv sync --locked, putbin/onPATH, install Semgrep, then runraptor. The launcher runs pre-flight trust checks and environment stripping before it starts Claude Code. - Container. The devcontainer image adds static analysis, fuzzing and browser automation tooling plus Z3, and installs the pinned CodeQL bundle on first use. The README recommends the container to limit blast radius.
- Standalone.
python3 raptor.py agentic --repo <path>runs without Claude Code if an API key or Ollama is configured. Without any LLM, Phase 3 is skipped and findings are prepared for manual review. - Required. Python 3.12+, uv, Node.js 18+ for Claude Code, Linux for the full sandbox.
Strengths and caveats
- Strength: mechanical evidence first. Tiers, Z3 pre-screening, binary oracles and compile checks keep LLM verdicts from being the only proof.
- Strength: serious host safety. Namespaces, Landlock, seccomp, egress allowlists, nonce-gated sandbox disable and prompt envelopes are far beyond what most tools in this category ship.
- Strength: cost governance. Per-run USD, call, time and token caps, a $1 per-finding cap for Claude Code children, and a spend gate on engagements.
- Caveat: sandbox strength depends on the host. The default profile degrades silently on hosts without unprivileged user namespaces or Landlock. Use
strictif you need a guarantee. - Caveat: scope is local by design. Except for
/web, there is no target allowlist because the target is a path. The web scope receipt has one origin and defaults toactiveactions. - Caveat: size and churn. The code base is huge, fast-moving and heavy with defensive comments. Reading it, or changing it safely, takes time.
- Caveat: Claude Code coupling. The best-supported workflow assumes a Claude Code subscription. The standalone CLI covers the pipelines but not the skill-driven commands.
Sources: code at 265236f, verified Q&A.
How it answers the Open-source AI pentest and offensive-security agents questions
Each answer was drafted by a code-reading agent at commit 265236f. Its citations were checked mechanically. Compare with the other open-source ai pentest and offensive-security agents →
How is the agent loop and planning implemented?
answeredRAPTOR does not use multi-agent or role-based crews. It is a single-agent system orchestrated by a mechanical supervisor loop (core/engagement/supervise.py). The workflow is artifact-centric: an engagement ledger (core/engagement/ledger.py) inventories all files in a target directory into artifact rows with content hashes, DT_NEEDED links, and exposure features. The depth governor (core/engagement/governor.py) mechanically assigns each artifact a tier (T0–T3) based purely on deterministic exposure signals — no LLM ever assigns depth (M3a doctrine). The supervisor (supervise()) runs scheduling passes: each pass iterates the governor's priority-ordered artifact list (deepest tier first), and for each artifact calls chain_elf.run_chain() which invokes the per-class analysis chain: investigate → import → study → checklist → audit → siblings → seed re-review → validate. Tasks are not dynamically planned by an LLM; they are statically sequenced by the chain module, which is resumable — per-artifact state is durable in chain-state.json, so an interrupted run continues from the first unsettled stage. Stop conditions include the _MAX_PASSES cap (8 passes), the PARK_AFTER_DEATHS bound (3 consecutive unreconciled segment deaths park the artifact), operator envelope exhaustion (reservations over budget park the engagement), and wall-clock bounds from core.run.supervisor.supervisor_wall_bound. The supervisor also respects fleet drain requests and operator acknowledgment parks (M5: parks are sticky until acknowledged).
claude -p children), and /crash-analysis and /oss-forensics use Claude Code sub-agents defined in .claude/agents/.How are security tools integrated and executed?
answeredSecurity tools are integrated as external subprocesses invoked through a sandbox layer, never as in-process MCP servers or browser automations. The runner path is: CLI argparse → raptor.py <mode> dispatches to scripts in packages/ (e.g. packages/codeql/, packages/semgrep/, packages/fuzzing/) which construct list-based subprocess arguments with RaptorConfig.get_safe_env() sanitised environment — no file-path interpolation into shell strings. The sandbox (core/sandbox/__init__.py) provides six independent isolation layers: user namespaces, network namespaces (blocks all network), PID namespaces, IPC namespaces, mount namespaces (pivot_root onto fresh tmpfs with read-only /usr//lib), Landlock filesystem rules, and seccomp-bpf syscall filtering with egress proxy. Profile names (full, strict, target_run, debug, frida, network-only, none) govern which layers are active. Sandbox profiles are the ONLY way to downgrade isolation — controlled by --sandbox <profile> CLI flags parsed at startup, never from env vars or target content (prompt-injection safety). Tool output is captured as JSON or SARIF and fed back through the evidence system (core/evidence/__init__.py) which grades observations from OBSERVED_RUNTIME (strongest) down to HEURISTIC (weakest). Commands like Semgrep, CodeQL, AFL++, and Ghidra are run as shell commands through the sandboxed subprocess runner, with core/sandbox/exec_stage.py staging env-built artifacts as executable copies in private temp dirs before the sandboxed child execve.
How are scope, authorization and dangerous actions controlled?
answeredScope and safety are enforced through multiple independent layers with a fail-closed posture. Target scope: the engagement ledger is CLOSED over an operator-given install directory — core/engagement/ledger.py enumerates only files under target_root and records provenance with derived_from_target field lists for every target-derived value. The ledger explicitly binds content by SHA-256: the chain module's content-binding refuses to analyse bytes that differ from the ledger's recorded hash, and stale chain state is archived, not reused. Sandbox isolation: every subprocess runs through core/sandbox/ which layers network namespaces (no interfaces), mount namespaces (pivot_root to private tmpfs with RO system dirs), Landlock filesystem rules, and seccomp syscall filtering. The egress proxy enforces a hostname allowlist and rejects CONNECT targets with non-printable bytes or non-globally-routable resolved IPs. Disable consent: turning off sandbox (--no-sandbox or --sandbox none) requires explicit consent via core/sandbox/disable_consent.py — validated minted nonces, not just terminal presence. Sandbox-unavailability is fail-closed: core/run/sandbox_policy.py raises SandboxUnavailableError unless the operator has set RAPTOR_ALLOW_UNSANDBOXED_TOOLS=1. Budget governor: the engagement supervisor (core/engagement/supervise.py) enforces budget gates — no LLM-capable launch starts without --max-cost, --envelope, or --uncapped opt-out. The feasibility enforcer (governor.enforce_feasibility) compares policy cost estimates against the envelope; an unattended conflict parks the engagement before any segment spends. Human-in-the-loop: parks are sticky — segment-death parks, code-drift parks, and envelope-exhaustion parks all require an operator to --acknowledge <park-id> before resuming. Rate limits: LLM concurrency is capped at MAX_WORKERS_CAP=32 with provider-specific RPM awareness and a CC_MAX_WORKERS_DEFAULT=4 for the Claude Code transport.
strict sandbox profile fails closed; the default full profile warns and degrades when namespaces or Landlock are unavailable. Live web testing is scoped by a ScopeReceipt in packages/web/execution_policy.py that rejects off-origin actions and actions above the approved risk level (default active).How are findings validated and reported?
answeredFindings flow through a multi-stage validation pipeline with evidence-tier grading, not a single LLM prompt. Static analysis tools (Semgrep, CodeQL) produce SARIF findings. The /agentic pipeline then runs exploitability validation (packages/exploitability_validation/) that filters false positives and unreachable code before LLM analysis. The evidence system (core/evidence/__init__.py) assigns every observation a tier: OBSERVED_RUNTIME (Frida instrumentation), REPLAYED_CRASH (ASan/fuzz witness), SMT_PROVED (Z3 solver), CORPUS_CORROBORATED (two independent witnesses), DECODED_INSTRUCTION (concrete address), XREF_BACKED (call-graph/dataflow), HEADER_BACKED (ELF/Mach-O headers), DECOMPILER_INFERRED, and HEURISTIC (LLM inference). The orchestration driver (core/orchestration/driver.py) implements a generate-and-verify loop with pluggable oracles: propose candidate → build artifact → test against mechanical oracle → refine → stop. The oracle has a reliability_class field (decisive for deterministic checks, judgement for LLM-based). For CodeQL findings specifically, packages/codeql/ includes a dataflow_validator that checks reachability and sanitization guards by re-reading source context. Duplicates are handled via the engagement ledger's content-identity system (core/engagement/ledger.py): every artifact is keyed by content SHA-256, and the router (core/engagement/router.py) collects hypotheses from four producer classes (sibling runs, binary sink edges, ABI facts, corpus facts), ranks them by evidence strength, applies per-artifact quota allocation against a maximum seed cap, and writes per-artifact seed files — overflow beyond quota is escalated as a routing_saturated event rather than dropped silently. Findings are persisted as findings.json with provenance_refs back-linking to the producing run (core/run/findings.py). The reporting layer (core/reporting/findings.py) builds tables with columns: index, type, CWE, file:line, status, severity, CVSS.
How is engagement state and knowledge kept across a long run?
answeredEngagement state is stored durably on disk in the run output directory, not in RAM or a graph database. The engagement ledger (core/engagement/ledger.py) is a ledger.json document with every artifact row, its content identity, exposure features, policy slots (tier assignments), reservation slots (budget charges), and an append-only policy_amendments trail. Per-artifact chain state is in <output_dir>/chains/<artifact-id>/chain-state.json — an interrupted chain resumes from the first unsettled stage, judged by artifact existence plus recorded state, never wall-clock. The engagement supervisor (core/engagement/supervise.py) persists a engagement-state.json with a code pin (framework source-control SHA + models config hash), segment counter, and budget figures. Parks are recorded durably in engagement-parks.json with a PARKED marker file surfaced by the project status view. The SAGE persistent memory system (core/sage/) provides consensus-validated cross-run persistence across domains like raptor-findings-{repo_key}, raptor-fuzzing, raptor-methodology, raptor-fp-{repo_key} (false positive suppression), raptor-rule-library, and raptor-audit-{repo_key}. SAGE stores are accessed through mechanical hooks (core/sage/hooks.py) that make hard skip/suppress decisions — no prompt injection from recalled text. Rows are MAC-stamped (core/sage/rowmac.py); recall verifies the MAC over decision fields before any mechanical effect, and unverified rows degrade to hints only. Session summarisation is achieved through the phase/pass structure of the supervisor: after each pass, an interim report (engagement-interim-report.md) is written with policy, feasibility, committed spend, per-row status, and park summaries. Compaction of long sessions is handled by the _MAX_PASSES cap and the per-pass boundary checks (drain requests, wall bounds) that pause cleanly rather than accumulating infinite churn.
Which models are supported and how are cost and context managed?
answeredRAPTOR supports five LLM provider families via native SDKs: Anthropic (Claude models via anthropic SDK), OpenAI (GPT models via openai SDK), Google Gemini (via google-genai SDK with OpenAI shim fallback), Mistral (via mistralai SDK), and Ollama (local models via OpenAI-compatible endpoint). Provider defaults are defined in core/llm/model_data.py: Anthropic defaults to claude-opus-4-6, OpenAI to gpt-5.4, Gemini to gemini-2.5-pro, Mistral to mistral-large-latest. Fast/cheap model mappings exist per provider (e.g., claude-haiku-4-5, gpt-4o-mini, gemini-2.5-flash-lite) for lightweight classification tasks. Per-role model selection is configured via models.json (at ~/.config/raptor/models.json) which maps provider, model name, optional role, and API key. The configuration system (core/llm/config.py) reads this file, detects SDK availability, and auto-discovers Ollama models. The client (core/llm/client.py) provides automatic fallback across providers, retry logic with exponential backoff, cost tracking with per-call budget reservation (_BUDGET_RESERVATION=0.10), response caching, and task-specific model selection. The multi-model subsystem (core/llm/multi_model/) runs N models against the same task with dispatch, merge, review, and optional LLM aggregation — used by /agentic's consensus mode. Cost management includes a core/llm/cost.py sanitisation layer (sanitizes NaN/inf negative floats to 0.0), per-call cost estimates from scorecard history (core/llm/client.py defines a _DEFAULT_CALL_COST_ESTIMATE=2.00), and budget caps per client. Context window management (core/llm/context_window.py) defines line-window limits for per-finding classifier context (default: 50 lines before/after a finding, 5 lines per dataflow step). The core/llm/prompt_budget.py module provides fit_to_budget() for priority-based prompt section shedding when approaching budget limits. The core/llm/concurrency.py module caps LLM parallelism at 32 workers with provider-specific RPM awareness.