PentestGPT Agent Domain Model
Overview
The redesigned pentestgpt_agent domain separates model-authored proposals from deterministic state mutation. The package marker in pentestgpt_agent/…/__init__.py only exposes the package version; the domain model lives in the agent contract, planning, memory, trace, identifier, and audit modules.
pentestgpt_agent/…/agents.py is the LLM contract boundary. Supervisor and Executor wrap a trace.EpisodeRunner, require the runner's configured instructions to exactly match SUPERVISOR_INSTRUCTIONS or EXECUTOR_INSTRUCTIONS, invoke the provider with JSON schemas, and parse the returned structured objects. The Supervisor sees a bounded prompt built by _supervisor_prompt: the run goal, allowed targets, open tasks, recent closed tasks, required dependency/basis context, recent observations, and recent diagnostic attempts. It returns a plan.SupervisorDecision with at most one new task, a selected next task or finish flag, and finish basis IDs. The Executor receives one leased active task plus its basis observations, up to two prior same-task observations, a retry diagnostic from the prior attempt if present, and a kind-specific turn budget. It returns an execution.ExecutionDelta containing task ID, outcome, summary, and a single evidence excerpt candidate. recover_execution_deltas() can reconstruct malformed terminal StructuredOutput calls from an EpisodeTrace, but still returns only parsed ExecutionDelta candidates for deterministic validation elsewhere.
pentestgpt_agent/…/plan.py defines the small planning language. TaskKind is ordered by penetration-test intent (discover, enumerate, test, exploit, verify, recover), while TaskStatus is the durable scheduler state (blocked, ready, active, done, failed). TaskProposal, TaskRecord, SupervisorDecision, and ValidPlan are frozen dataclasses used to move from model output to a commit-ready plan. compile_plan() validates a SupervisorDecision against a memory.RunSnapshot without mutating state: the run must be running, the decision revision must match, exactly one of next_task_id or finish must be chosen, at most one new task may be proposed, and a new task must be selected immediately. It also enforces task limits, allowed-target scope, dependency existence and acyclicity, basis observation existence, basis-producing task dependencies for non-RECOVER tasks, TEST/EXPLOIT separation, and the rule that EXPLOIT cites the newest completed same-target TEST observation.
Allowed-target matching in plan.py is deliberately conservative. _canonical_url_target() accepts only clean http/https URLs without credentials, fragments, control characters, unresolved percent escapes, backslashes, or path traversal segments, normalizes default ports and host case, and compares path-prefix containment in _url_contains(). Non-URL targets must match an allowed target byte-for-byte in _target_is_allowed(). This is why agents.py prompts tell the Supervisor to copy one supplied allowed target exactly and put ports, paths, and vhosts in task prose instead of the task target field.
pentestgpt_agent/…/memory.py is the authoritative SQLite-backed memory kernel. Its frozen records model the durable run: RunSpec, RunSnapshot, ObservationRecord, AttemptRecord, TransitionRecord, TaskLease, PlanCommit, and AttemptCommit. validate_run_spec() applies the shared opaque run ID contract from identifiers.py, bounds the goal, requires one to sixteen unique allowed targets, and caps max_attempts_per_task. MemoryKernel.__init__() creates or migrates runs, transitions, attempts, observations, and tasks tables, then all state changes go through revisioned commits. create_run() inserts revision 0 and a run_created transition; open_run() reuses an existing run only when goal, allowed targets, and attempt budget match; snapshot() reconstructs a full immutable RunSnapshot ordered by revisions.
MemoryKernel.commit_plan() consumes a plan.ValidPlan and advances the run by one revision under BEGIN IMMEDIATE. New tasks are inserted as ready only if dependencies are already done, otherwise blocked; a selected ready task becomes active, gets a UUID attempt, and returns a TaskLease whose trace_episode_id is executor-{attempt_id}. The same transition records the summary, new task IDs, selected task, and finish basis IDs. MemoryKernel.commit_execution() consumes a validated execution object, maps executor outcomes to task status (done, ready for progress, or failed for blocked/failed), fails a progress task when its attempt budget is exhausted, writes one observation as {attempt_id}:observation when evidence was validated from a trace, unblocks dependent tasks whose dependencies are now all done, increments the run revision, and appends an attempt_committed transition with evidence recovery flags. Operational failures do not create observations: commit_attempt_failure() closes the active attempt as error, optionally creates a fresh retry attempt and lease when the failure is retryable and the attempt budget permits, or otherwise fails the task and run. commit_run_failure() settles supervisor/run-level failures only when no attempt is active.
pentestgpt_agent/…/trace.py is the diagnostic episode journal and provider seam. EpisodeInput binds a provider episode to run_id, episode_id, AgentRole, state revision, rendered task, optional output schema, optional task/attempt IDs, and turn budget. EpisodeRunner.run() renders the prompt, writes input.json through TraceStore._begin(), streams a fresh UnifiedAgent episode with resume=None, appends normalized event records to events.jsonl with a monotonically increasing sequence, collects a UnifiedResult, and writes output.json. The persisted input includes provider metadata and SHA-256 signatures for the rendered prompt, instructions, schema, and provider config, so a trace can later be tied back to the exact contract that produced it. TraceStore.load() returns an EpisodeTrace and marks a malformed final JSONL line as truncated_tail; recover_terminal_output() can write a missing output.json when the last durable event is a terminal turn_completed event.
Trace helpers define which runtime facts can become memory. has_action_receipts() treats commands, file changes, and non-StructuredOutput tool calls as side-effect receipts, which is used to decide whether retrying an attempt could duplicate an action. is_grounding_receipt() allows completed command_run events with integer exit codes, including nonzero exits, and successful non-structured tool_result events as eligible evidence sources; structured output calls are excluded. failure_detail() prefers provider terminal failure details from the trace and detects Claude safety-rejection text before falling back to output.json errors. These helpers are used by execution validation and audit code to keep traces diagnostic while memory remains canonical.
pentestgpt_agent/…/identifiers.py supplies the shared path-safety contract for opaque external IDs. validate_opaque_id() allows one to 128 ASCII letters, digits, dots, underscores, or hyphens, requires an alphanumeric first character, and rejects . and ... memory.py applies it to run_id; trace.py applies it to both run_id and episode_id before constructing filesystem paths under the trace root.
pentestgpt_agent/…/audit.py reads completed trial artifacts back from state.sqlite3 and immutable trace directories. audit_run() loads one run row plus tasks, attempts, observations, transitions, and per-episode trace records. It checks that observations point to executor traces with matching run/task/attempt/revision identity, that each observation statement is a direct substring of exactly one grounding receipt sequence, that task basis IDs exist and their producers are dependencies, that EXPLOIT tasks cite the newest same-target completed TEST observation, that completed runs cite valid finish basis observations, that every revision from zero through the current revision has a transition, and that failed/incomplete episodes are settled by canonical transitions or attempt failure metadata. It also counts provider cost, token usage, supervisor actions, and hidden Claude memory writes, then returns a schema-versioned audit object whose passed field is the conjunction of the checks.
End-to-end, an execution/trial flow moves through these domain objects in one direction: agents.Supervisor.decide() produces a SupervisorDecision; plan.compile_plan() validates it into ValidPlan; memory.MemoryKernel.commit_plan() records tasks/transitions and optionally leases exactly one active attempt; agents.Executor.execute() runs that lease through trace.EpisodeRunner; execution validation (outside this doc's owned files) uses trace.is_grounding_receipt() and the trace identity to produce a commit-ready execution; memory.MemoryKernel.commit_execution() writes canonical observations and revisions; and audit.audit_run() later reconciles the SQLite memory with trace files.
Coupling
- If the structured Supervisor or Executor schemas in pentestgpt_agent/…/agents.py change, update the corresponding parsers in the same file and the plan/execution dataclasses they instantiate.
_require_exact_keys()rejects both missing and extra fields, so schema drift fails at the agent contract boundary. - If task kinds or statuses change in pentestgpt_agent/…/plan.py, update agents.py schemas and prompts, memory.py outcome/status transitions, and audit.py basis/exploit checks. These modules compare enum
.valuestrings persisted in SQLite and trace JSON. - If trace event shapes or eligible evidence rules change in pentestgpt_agent/…/trace.py, verify both execution validation and pentestgpt_agent/…/audit.py. Audit reuses
is_grounding_receipt()and expects observations to cite exactly one sequence whose output contains the canonical statement. - If the
TaskLease.trace_episode_idconvention in pentestgpt_agent/…/memory.py changes fromexecutor-{attempt_id}, updateagents.Executor.execute()inputs and audit identity checks. Observations and attempts are tied back to trace directories by that episode ID. - If the opaque ID validator in pentestgpt_agent/…/identifiers.py is loosened, check both
MemoryKernel.snapshot()andTraceStore._episode_dir(). The same validator protects SQLite run lookup inputs and filesystem trace paths.
Risks
- pentestgpt_agent/…/memory.py records observations as
{attempt_id}:observation, while pentestgpt_agent/…/identifiers.py does not allow colons. That is safe only because observation IDs are stored in SQLite and are not passed throughvalidate_opaque_id(); if observation IDs become path components or externally reopened opaque IDs, existing IDs would fail validation or create a path-safety gap. - pentestgpt_agent/…/audit.py checks direct quotes with
statement in event["output"], while execution validation accepts CRLF/LF normalization and bounded widening/projection before committing observations. Runs that are valid under execution's normalization rules can fail audit if the persisted statement no longer appears byte-for-byte in the raw event output.