Introducing a new way to review your PRs.

Read the announcement

greydgl / pentestgpt

Automated Penetration Testing Agentic Framework Powered by Large Language Models

View on GitHub

13 documents · Updated Nov 16, 2026

docs / pentestgpt-agent-execution-flow

PentestGPT Agent Execution Flow

Overview

The redesigned execution pipeline is a one-task-at-a-time trial runner centered on pentestgpt_agent/…/trial.py, pentestgpt_agent/…/loop.py, and pentestgpt_agent/…/execution.py. trial.py is the CLI/runtime entrypoint: TrialConfig captures the run identity, goal, authorized targets, provider backend/model, roots for durable state and agent workspaces, turn limits, and whether the run is an explicit resume. run_trial() validates that identity, writes or checks trial-config.json, opens runs/<run_id>/state.sqlite3 through MemoryKernel, creates a TraceStore under the runs root, builds the Supervisor and Executor roles, runs PentestLoop, and always writes summary.json with canonical state, trace/cost/usage totals, and any terminal error.

Role construction in trial.py keeps provider setup outside the deterministic loop. _build_roles() creates separate UnifiedAgent workspaces at <workspace_root>/<run_id>/supervisor and <workspace_root>/<run_id>/executor, wraps them in EpisodeRunner, and passes them to Supervisor and Executor. Both roles run with SandboxPolicy.FULL_ACCESS; for the Claude backend _provider_environment() disables Claude auto-memory, nonessential traffic, and the autoupdater so every episode is fresh and durable memory remains in SQLite/trace files rather than provider session state. _trial_identity() hashes the Supervisor/Executor instruction+schema contracts from pentestgpt_agent/…/agents.py and records backend, sandbox, turn-budget, and unified_agent version details; resume is rejected if the persisted identity differs.

PentestLoop.run() in loop.py owns the deterministic orchestration. It calls MemoryKernel.open_run() with the validated RunSpec, resumes an active lease if canonical state already has exactly one active task/attempt, and then repeats decision cycles while RunStatus.RUNNING. When no lease is active, _supervisor_plan() obtains a Supervisor decision, parses it, and validates it through compile_plan() from pentestgpt_agent/…/plan.py; only memory.commit_plan() mutates state and either finishes the run or creates a TaskLease for the selected ready task. When a lease exists, _drive_lease() runs or recovers the Executor episode and commits either a validated execution result or an operational failure.

The Supervisor side deliberately separates model output from state mutation. _supervisor_plan() gives each decision attempt a deterministic episode id (supervisor-r<revision> and supervisor-r<revision>-a<N>), reuses an existing persisted successful trace through TraceStore.recover_terminal_output() instead of replaying it, and checks trace identity (run_id, episode_id, role, and state revision) before parsing structured output. New Supervisor calls go through Supervisor.decide() in agents.py, whose prompt contains the bounded working set, recent/required observations, dependency context, recent diagnostics, and optional validation feedback. Contract or plan-validation failures are retried up to max_supervisor_attempts with the error text fed back; after that PentestLoop.run() records a run-level failure via MemoryKernel.commit_run_failure().

The Executor side is lease-bound. _drive_lease() derives the episode id from the lease/attempt (executor-<attempt_id>) and never replays an existing trace episode. If a trace directory exists, it is recovered and settled. If not, Executor.execute() in agents.py receives one active task envelope containing the run goal, task kind/target/objective/done_when, explicit basis observations, up to two prior same-task observations, one retry diagnostic from a previous attempt, and a task-kind-specific turn budget. After the provider returns, _drive_lease() loads the persisted trace and calls compile_execution() from execution.py; successful validation is committed through MemoryKernel.commit_execution().

execution.py is the evidence gate between an Executor proposal and canonical memory. The Executor proposes an ExecutionDelta with task_id, ExecutionOutcome (done, progress, blocked, or failed), a summary, and an optional evidence excerpt. compile_execution() verifies that the delta and EpisodeTrace match the TaskLease identity: run id, state revision, task id, attempt id, Executor role, and, when present, trace episode id. It rejects unsuccessful episodes unless structured-output transport recovery is explicitly allowed, enforces nonempty bounded summaries, and requires completed tasks to have grounded evidence.

Grounding is based on trace receipts, not model prose. _grounding_receipts() selects eligible action results using is_grounding_receipt() from trace.py: command receipts with integer exit codes, or non-error tool results that are not the StructuredOutput call. _matching_receipt() first searches for the Executor's exact excerpt, accepting CRLF/LF normalization via _exact_receipt_slice(). If the model quoted exact lines but not the exact contiguous block, _ordered_exact_line_span() and _exact_unique_line_envelope() may widen to a bounded contiguous receipt span; _supported_single_receipt_projection() can project a multi-receipt quote onto one rich source receipt only when all requested lines are uniquely supported. Oversized receipt slices are truncated to a 4,000-character suffix and cannot complete a task: compile_execution() demotes DONE to PROGRESS when evidence was fallback, truncated, or unresolved. If no current receipt matches, _matching_prior_observation() permits a no-action attempt to reuse an exact same-task prior observation; otherwise a last-receipt fallback may preserve progress but not completion.

Trace settlement in loop.py handles runtime failures without confusing them with task outcomes. _settle_trace() maps a truncated journal to trace_corrupt, missing durable output to interrupted, successful output to parse/validation/commit, and failed provider output through failure_detail() from trace.py. For max_structured_output_retries and max_turns, it tries recover_execution_deltas() from agents.py against captured StructuredOutput tool calls and calls compile_execution(..., recover_structured_transport=True) so a known malformed terminal transport failure can be committed without replaying actions. Operational failures are retryable only for provider/validation/interruption cases with no truncated tail and no action receipts (has_action_receipts()), which preserves the invariant that actionful attempts are never replayed.

Canonical state transitions live in MemoryKernel, which is outside this doc's owned files but is the state target for the flow. commit_plan() increments the revision, inserts at most one new task, activates exactly one ready task by inserting an active attempt and lease, or marks the run completed. commit_execution() maps execution outcomes to task status (DONE to done, PROGRESS back to ready unless the attempt budget is exhausted, BLOCKED/FAILED to failed), stores an observation only from validated evidence, unblocks dependent tasks whose dependencies are now done, and records an attempt_committed transition. commit_attempt_failure() records ERROR attempts and either creates a new active attempt/lease for a safe no-action retry or marks the task and run failed. Thus the loop, planning compiler, execution compiler, memory kernel, and trace store each have one authority boundary: agents propose, compilers validate, memory mutates, and traces preserve the raw episode record.

Coupling

  • If ExecutionDelta or ExecutionOutcome changes in pentestgpt_agent/…/execution.py, also update EXECUTOR_SCHEMA, parse_execution_delta(), and recover_execution_deltas() in pentestgpt_agent/…/agents.py; PentestLoop._settle_trace() depends on recovered candidates having the same fields and semantics as normal Executor output.
  • If EpisodeTrace.input fields written by EpisodeRunner in pentestgpt_agent/…/trace.py are renamed or omitted, update the identity checks in compile_execution() and _supervisor_plan(); those checks are what prevent stale or cross-run traces from mutating canonical state.
  • If receipt eligibility changes in pentestgpt_agent/src/pentestgpt_agent/trace.py:is_grounding_receipt(), re-check all evidence matching paths in pentestgpt_agent/…/execution.py; completed tasks rely on exact excerpts from eligible receipts, and fallback/truncation deliberately demote completion to progress.
  • If MemoryKernel.commit_attempt_failure() retry rules or has_action_receipts() in trace.py change, verify PentestLoop._settle_trace() still only retries no-action operational failures; replaying an actionful attempt can duplicate external side effects.
  • If trial resume identity in pentestgpt_agent/src/pentestgpt_agent/trial.py:_trial_identity() changes, keep it aligned with role construction in _build_roles() and agent contracts in agents.py; otherwise a resumed run could continue under different prompts, schemas, turn budgets, provider environment, or sandbox assumptions.

Risks

  • pentestgpt_agent/src/pentestgpt_agent/loop.py:_settle_trace() performs transport recovery for max_structured_output_retries and max_turns by scanning prior StructuredOutput tool calls. If that path accepts an ungrounded candidate or enables evidence fallback too broadly, a provider-format failure could be promoted into canonical state without the normal successful-output contract.
  • pentestgpt_agent/…/execution.py contains several quote-recovery paths (_ordered_exact_line_span(), _exact_unique_line_envelope(), and _supported_single_receipt_projection()). If these widen or project non-unique lines incorrectly, MemoryKernel.commit_execution() will persist an observation that the target did not produce as one exact contiguous receipt slice.
  • pentestgpt_agent/src/pentestgpt_agent/trial.py:run_trial() creates agents with SandboxPolicy.FULL_ACCESS. This is intentional for the pentest runtime, but changing workspace roots, resume checks, or provider environment handling can leak state between roles/runs or re-enable provider auto-memory that bypasses the SQLite/trace authority model.