File size: 6,147 Bytes
26228ef cb00361 26228ef cb00361 26228ef 89076a2 26228ef eb60226 26228ef 89076a2 26228ef 89076a2 26228ef cb00361 26228ef cb00361 26228ef cb00361 26228ef cb00361 26228ef cb00361 26228ef eb60226 26228ef cb00361 eb60226 26228ef | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | """Agent state schema: Pydantic v2 models + the LangGraph ``AgentState`` TypedDict.
Nested objects are Pydantic models (validated, JSON-serializable for checkpointers);
the top-level state is a TypedDict because LangGraph needs per-key reducers.
See SPEC.md section 2.
"""
from __future__ import annotations
from datetime import UTC, datetime
from enum import StrEnum
from pathlib import Path
from typing import Annotated, Literal, TypedDict
from langchain_core.messages import AnyMessage
from langgraph.graph.message import add_messages
from pydantic import BaseModel, ConfigDict, Field, model_validator
from sandbox.base import SandboxResult
__all__ = [
"AgentState",
"AgentStatus",
"ApprovalDecision",
"FileEdit",
"FilePatch",
"FixAttempt",
"IssueInput",
"RepoContext",
"RepoFinding",
"ReproTest",
"RunBudget",
"SandboxResult",
"initial_state",
"merge_attempts",
]
class AgentStatus(StrEnum):
INGESTED = "ingested"
INSPECTED = "inspected"
REPRO_WRITTEN = "repro_written"
REPRO_CONFIRMED = "repro_confirmed"
FIXING = "fixing"
TESTS_PASSING = "tests_passing"
AWAITING_APPROVAL = "awaiting_approval"
APPROVED = "approved"
COMMITTED = "committed"
ESCALATED = "escalated"
REJECTED = "rejected"
class _Model(BaseModel):
"""Base: reject unknown fields so LLM/node typos fail loudly."""
model_config = ConfigDict(extra="forbid")
class IssueInput(_Model):
title: str = Field(min_length=1)
body: str = ""
url: str | None = None
number: int | None = Field(default=None, ge=1)
repo_path: Path
class RepoFinding(_Model):
"""A single bug, defect, or vulnerability discovered during a repository scan."""
severity: Literal["Critical", "High", "Medium", "Low"] = "High"
file_path: str = Field(min_length=1)
title: str = Field(min_length=1)
description: str = ""
suggested_fix: str = ""
class RepoContext(_Model):
tree: str = "" # truncated directory listing
relevant_files: dict[str, str] = Field(default_factory=dict) # path -> snippet
findings: list[RepoFinding] = Field(default_factory=list) # all issues discovered in repo
test_command: str = "pytest -x -q"
language: str = "python"
class ReproTest(_Model):
path: str = Field(min_length=1) # repo-relative
content: str
framework: Literal["pytest"] = "pytest"
confirmed_failing: bool = False
class FileEdit(_Model):
"""One search/replace edit proposed by the LLM (far more reliable than raw diffs)."""
path: str = Field(min_length=1) # repo-relative
search: str = Field(min_length=1) # must match exactly once in the file
replace: str
class FilePatch(_Model):
"""A unified diff (relative to the pristine baseline) computed from applied edits."""
path: str = Field(min_length=1) # repo-relative
unified_diff: str = Field(min_length=1)
class FixAttempt(_Model):
iteration: int = Field(ge=1)
rationale: str = ""
edits: list[FileEdit] = Field(default_factory=list) # proposed by the LLM
patches: list[FilePatch] = Field(default_factory=list) # set by apply_fix
patch_error: str | None = None # set by apply_fix when an edit does not apply
result: SandboxResult | None = None # set by run_tests
class ApprovalDecision(_Model):
approved: bool
feedback: str | None = None
reviewer: str | None = None
decided_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
class RunBudget(_Model):
"""Hard limits that keep a run inside Groq's free tier (8K tokens/min)."""
max_iterations: int = Field(default=8, ge=1, le=8)
max_repro_attempts: int = Field(default=2, ge=1)
max_context_tokens: int = Field(default=3500, ge=500) # prompt budget per LLM call
max_tool_output_chars: int = Field(default=2500, ge=200)
@model_validator(mode="after")
def _output_fits_context(self) -> RunBudget:
# ~4 chars/token: a single tool output must not eat the whole window.
if self.max_tool_output_chars // 4 >= self.max_context_tokens:
raise ValueError("max_tool_output_chars is too large for max_context_tokens")
return self
def merge_attempts(existing: list[FixAttempt] | None, new: list[FixAttempt] | None) -> list[FixAttempt]:
"""Reducer for ``attempts``: upsert by ``iteration``, ordered by iteration.
Lets a later node (e.g. ``run_tests``) return an updated copy of an attempt
with its sandbox result attached, while earlier attempts stay in the history.
"""
merged = {a.iteration: a for a in existing or []}
merged.update({a.iteration: a for a in new or []})
return [merged[k] for k in sorted(merged)]
class AgentState(TypedDict, total=False):
"""Graph state. Nodes return partial updates and never mutate their input."""
issue: IssueInput
repo: RepoContext
repro_test: ReproTest
repro_result: SandboxResult | None # last run of the repro test
workspace_root: str # temp dir holding the baseline + working copies
diagnosis: str | None # failure summary / reviewer feedback fed into the next attempt
attempts: Annotated[list[FixAttempt], merge_attempts] # audit trail, upserted by iteration
messages: Annotated[list[AnyMessage], add_messages] # LLM conversation (pruned)
iteration: int # fix iterations consumed, 0..budget.max_iterations
repro_attempts: int # repro-test generations consumed
budget: RunBudget
status: AgentStatus
approval: ApprovalDecision | None
branch: str | None
commit_sha: str | None
pr_url: str | None
error: str | None # terminal failure reason, set by escalate
def initial_state(issue: IssueInput, budget: RunBudget | None = None) -> AgentState:
"""Build the starting state for a run."""
return AgentState(
issue=issue,
attempts=[],
messages=[],
iteration=0,
repro_attempts=0,
budget=budget or RunBudget(),
status=AgentStatus.INGESTED,
approval=None,
branch=None,
commit_sha=None,
pr_url=None,
error=None,
)
|