Shipping the PR flow: durable review rounds and an honest assessment
What this post covers#
This post ties together all of the work we did in the series and gives the agent an interface. In the previous post we
were validating the underlying agent’s ability to actually write code and made sure we can monitor it and investigate
any issue. Now it is @tfsmith-bot, which you address on an issue to plan a change or to start a PR and review it. The
workspace is now filled with a git clone and the changes of the run become a commit. In addition the agent result is
expanded so it can also respond to questions instead of just writing code. The lifetime of a PR can be hours or days and
we do want long running context. Lucky for us AWS and pydantic-ai did move quickly adding durable Lambdas and the
pydantic-ai integration for it. This allows us to pick up even after a lot of time has passed with minimal house-keeping
(storing state) on our side.
The agent is able to do this by defining a GitHub App. The app authenticates with its own private key, gets a
short-lived token for each installation and defines the permissions it needs. Adding it to an organization or a personal
account a user can “install” it and accept the permissions for all or selected repos. Importantly as opposed to a
personal access token a GitHub App can also receive events. Our GitHub App is private as it is just for this post and is
called tfsmith-bot. While the method we use to invoke looks like GitHub is smart about @tfsmith-bot, it really is not.
GitHub sends the app every comment and review on the events it subscribes to, and the receiver matches the handle in the
text itself. On the bright side this allows us to be generous about the exact form of invocation.
While the wait between posts (my daughter was born 😊) meant that I had to get back into it, it also offered the opportunity to upgrade the libraries. The world moves very quickly for AI libraries. There was obviously a price to pay in some minor code updates, but that is what we have tests for. Even on the model side we had to shift a little, as Fireworks retired GLM 5.2 from serverless. This means evals had to be re-run, which in itself gave some very interesting insights (more on that in Which model runs it).
Architecture#
The previous post did not make any additions to the architecture, but this one makes a major step. We switch our Lambda
to a durable version and give it the ability to interact with git in the review loop. You will notice that the review
loop also drives the agent, but that the agent does not know about git directly. It still just operates on a tmp file
system and reports a structured result. The only addition is that it can choose to respond with an Answer instead of
an implementation (TaskResult). Not using tools when traditional code works (no judgement needed) makes
the outcomes a lot more predictable and our previous evals still apply!
Another addition is the receiver Lambda, which is a very basic low dependency Lambda. It checks that the message comes from GitHub, drops untrusted authors, and either starts an execution for a mention or queues the event for the execution waiting on the thread (in DynamoDB) and wakes it.
Below you can see how the system behaves when it is notified by GitHub:
The result#
I think the result is best demonstrated with the video below. We can now comment on an issue on GitHub to give the bot
a task. For example to create a plan for a KMS encrypted S3 bucket. The bot can now reply with an Answer,
which means it does no implementation work, and code (not the agent) posts that answer on the issue. Once we have the plan we tell the agent to go ahead and now the agent provides a result describing
an implementation and the code it has done. This means a PR can be created. Now further comments can trigger answers or
work on the branch of this PR.
Work on the PR goes in rounds. Each round runs several tools, and validation afterwards checks the agent’s work. The whole request runs as one durable execution, so a failure mid-round resumes from its checkpoints instead of paying for the model calls again.
What a request costs#
For a single request the answer is easy, see the table below. The model is dominating the cost, which makes it also really difficult to answer the same question across different tasks. More complex tasks will eat a lot more tokens while the easier one here is quite quick. There is also optimisation potential in terms of memory, as the current code keeps the whole message history, which is certainly overkill. A pruned version would be more sensible, for example summarizing between rounds. That would need more evals and proof, which is out of scope for this post.
The table contains the cost of the PR in the video, with plan, approval, and PR comments. It comes in at a reasonable price at ~$0.07, but it was also a fairly restricted task with most of the cost being driven by the implementation steps with checkov making sure we enforce a basic level of infrastructure standards.
| Round | Model calls | Input tokens (cached) | Output tokens | Uncached input | Cached input | Output | Model cost | Lambda |
|---|---|---|---|---|---|---|---|---|
| 1: the plan, as an answer on the issue | 3 | 5.2k (64%) | 0.5k | $0.003 | $0.001 | $0.002 | $0.006 | 11s |
| 2: “go ahead”, the module and the PR | 16 | 58.1k (95%) | 2.1k | $0.004 | $0.014 | $0.009 | $0.028 | 100s |
| 3: a line comment, answered | 1 | 5.9k (79%) | 0.4k | $0.002 | $0.001 | $0.002 | $0.005 | 9s |
| 4: the review, the fix pushed | 12 | 97.5k (97%) | 1.3k | $0.004 | $0.025 | $0.006 | $0.034 | 74s |
| Request | 32 | 166.7k | 4.3k | $0.012 | $0.041 | $0.019 | $0.072 | 195s, ≈$0.008 |
Which model runs it#
We had to update our previous preference in this post, because GLM 5.2 was retired by Fireworks. This allowed us though to play with the new version and different settings. GLM 5.3 with a low effort came out best for our fairly simplistic tasks. GLM 5.3 on high effort did no better and cost more, and the default (max) effort was both worse and almost ten times the cost.
| Model | Pass rate | Cost / task | Avg duration | Tool-error |
|---|---|---|---|---|
| glm5p3-low | 100% | $0.015 | 56s | 0.84 |
| glm5p3-high | 100% | $0.022 | 62s | 0.81 |
| mistral-medium | 100% | $0.027 | 65s | 0.78 |
| glm5p3 | 93% | $0.143 | 201s | 0.85 |
The code#
Prerequisites (one-time setup for the series)
Tooling and AWS access common to every post in this series.
Tooling
- Terraform 1.x (install). Every post provisions infrastructure with Terraform.
- uv for Python project management (install). Each post ships a runnable script you can invoke with
uv run. - direnv (install) so
terraform,uv run, andawspick up AWS credentials automatically oncd. The project scaffold ships an.envrcthat sources a gitignored.envrc.local. - (Optional) A coding agent such as Claude Code, Cursor, Codex, or Gemini CLI to consume the
AgentPromptblocks throughout the series. Not required (each prompt has a manual equivalent shown alongside it), but it skips the boilerplate.
Agent prompt: Check and install missing tooling
You are helping set up tooling for a tutorial project.
For each of `terraform`, `uv`, and `direnv`, run `command -v` tocheck whether it is installed. If present, print the version andcontinue.
For missing tools, detect the system package manager in this order:`command -v brew`, `command -v dnf`, `command -v apt-get`. Use thefirst one available:
- Terraform: `brew tap hashicorp/tap && brew install hashicorp/tap/terraform`, dnf via the HashiCorp RPM repo, or apt via the HashiCorp deb repo. - uv: `brew install uv`, or the official installer `curl -LsSf https://astral.sh/uv/install.sh | sh`. - direnv: `brew install direnv`, `dnf install direnv`, or `apt-get install direnv`.
If no package manager is available or the install fails, stop andlink the manual install page so the developer can finish by hand:
- Terraform: https://developer.hashicorp.com/terraform/install - uv: https://docs.astral.sh/uv/getting-started/installation/ - direnv: https://direnv.net/docs/installation.html
After installing direnv, do not modify any shell rc files. Print thehook line for the developer's shell (bash, zsh, or fish) and the pathto the relevant rc file, then wait for them to apply it themselves.
Report which tools were already present, which you installed, andwhich need manual follow-up.AWS access
- A sandbox, test, or personal AWS account with permission to create, modify, and delete the resources discussed in each post. If you don’t have one, follow the official Create Your AWS Account walkthrough (about ten minutes; requires a credit card and a phone number for verification). Treat it as disposable - you can close it from the billing console after the series.
- AWS credentials available locally via
aws configure sso,aws configure, or whichever method matches your setup. You wire them into the project through.envrc.localin the next section, not your shell rc.
Anthropic First Time Use
Bedrock requires a one-time use-case form per account (or per AWS Organization management account) before Anthropic models can be invoked. Easiest path: open any Claude model in the Bedrock console playground and submit the form. Auto-subscription on first invoke can take up to 15 minutes to settle, so it is worth clearing this before post 1.
CLI alternative and verification
Programmatic equivalent (requires AWS CLI 2.27.42 or later):
aws bedrock put-use-case-for-model-access \ --form-data "$(printf '{"companyName":"...","companyWebsite":"...","intendedUsers":"1","industryOption":"...","otherIndustryOption":"","useCases":"..."}' | base64)"Verify:
aws bedrock get-foundation-model-availability \ --model-id anthropic.claude-haiku-4-5-20251001-v1:0 \ --region eu-west-1Look for agreementAvailability.status: AVAILABLE. Expected output:
{ "modelId": "anthropic.claude-haiku-4-5-20251001-v1", "agreementAvailability": { "status": "AVAILABLE" }, "authorizationStatus": "AUTHORIZED", "entitlementAvailability": "AVAILABLE", "regionAvailability": "AVAILABLE"}If the form has not been submitted, only agreementAvailability.status flips to NOT_AVAILABLE. The other three fields stay green even when invocation would fail, so do not rely on them.
The final tree. + is new in post 6, ~ extends a post 5 file, blank carries unchanged. Click any changed or new file
to read it; the download below fast-forwards to this state if you want to walk through the post against the finished
code.
The big changes in this post are:
- Addition of GitHub integration (receiver/writing back):
receiver/handler.py,agent/github.py,infra/receiver.tf,infra/github.tf,scripts/deploy-receiver.sh - Updates for new models and pydantic-ai upgrade:
agent/models.py,infra/models.tf,pyproject.toml,evals/ - Durable Lambda:
agent/lambda_entry.py,agent/core.py,infra/lambda.tf,scripts/build-lambda.sh - The review loop:
agent/pr_flow.py,infra/dynamodb.tf - Answers as well as code:
agent/core.py
# Hints the checkov tool puts before its report when one of these checks# fails. Each entry comes from a real run where a model went in circles.
[[hint]]checks = ["CKV_AWS_109", "CKV_AWS_111", "CKV_AWS_356"]text = """If the flagged policy document is a KMS key policy, resources = ["*"] meansthis key, so these IAM checks do not apply. Prefer no custom policy: withoutone, AWS applies the default key policy. If the request needs a custom keypolicy, add #checkov:skip=<check id>:<reason> inside the data block and listeach skip in known_limitations. For any other IAM policy, scope resources toARNs."""
[[hint]]checks = ["CKV_AWS_300"]text = """Add a rule that covers the whole bucket, with an empty filter: a rule with aprefix filter does not count. The block is nested, not an attribute: rule { id = "abort-incomplete-uploads" status = "Enabled" filter {} abort_incomplete_multipart_upload { days_after_initiation = 7 } }"""Fast-forward to the final code of this post
Download the cumulative checkpoint that matches the state at the end of this post. Useful for landing on the finished tree without working through every step.
mkdir -p ~/projectscd ~/projectscurl -fsSL https://andreaslang.dev/terraform-pr-agent/terraform-pr-agent-06.tar.gz | tar xzReceiving the trigger: the GitHub App#
The crux of the GitHub integration is the creation of a GitHub App. The app is an entity in GitHub that defines an integration, including permissions and what events it consumes. The app can then be installed in all or a subset of repos in an org. In our case it was only installed for a single repository to test and record the demos. The events get sent to a single receiver webhook: a small Lambda with a function URL, no API Gateway needed. The function URL has auth type NONE, which may seem odd at first, but the reason is that GitHub signs the payload with a secret, so the verification inherently needs the body. A function URL only offers IAM auth, which GitHub cannot sign, and an API Gateway authorizer never sees the body, so the receiver checks the signature itself. It is a separate Lambda because GitHub gives a webhook 10 seconds to answer and a run takes minutes. The receiver hands the event to the agent Lambda as an async invoke, and Lambda’s async invoke queue is the buffer, so we can skip a separate SQS queue.
Here are the permissions our app has configured and the events it subscribes to. One trap: PR conversation comments
arrive as issue_comment and are controlled by the Issues permission, not Pull requests.
| Repository permission | Access | Used for |
|---|---|---|
| Metadata | Read | Required by every app; repo lookups such as the default branch |
| Contents | Read and write | Fetch the start commit, compare commits, push the tfsmith/<request id> branch |
| Pull requests | Read and write | Find and open the PR, read each review and its diff comments, reply to them |
| Issues | Read and write | Read the issue, post answers and replies, add reactions |
| Event subscription | Action handled | What the receiver does |
|---|---|---|
| Issues | opened, closed | A mention in the body starts a request; close ends the thread |
| Issue comment | created | A mention starts a request; on a waiting thread it is feedback |
| Pull request | closed | Ends the thread |
| Pull request review | submitted | Feedback for the waiting execution, unless it is an approval |
Verification is standard and only needs Python’s standard library:
def verify_signature(secret: str, body: bytes, signature_header: str | None) -> bool: """Check X-Hub-Signature-256 against the raw request body.
HMAC-SHA256 keyed with the webhook secret, compared with hmac.compare_digest, never ==. Verify the raw bytes before any JSON parse; a parse and re-serialize round trip changes the bytes. """ if not signature_header: return False expected = "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature_header)We apply a few checks to see which comments and issues are meant for our bot:
@tfsmith-botneeds to be in the issue or comment to start a request. On a thread with a waiting request, any comment counts as feedback without it.- We only accept comments from people actually associated with the repo, and never from a bot, or the agent would answer itself.
# The mention is plain text. GitHub has no mention webhook event and apps# do not appear in @ autocomplete, so the receiver matches the handle in# the comment body itself. The lookarounds make it a whole handle, so# @tfsmith-bots or me@tfsmith-bot does not match.BOT_HANDLE = re.compile(r"(?<![\w-])@tfsmith-bot(?![\w-])", re.IGNORECASE)
# Anyone can comment on a public repo, and a comment becomes agent input,# so this is the prompt injection gate, not a courtesy filter. The field# arrives in every payload, so the check costs no API call.TRUSTED_AUTHOR_ASSOCIATIONS = frozenset({"OWNER", "MEMBER", "COLLABORATOR"})Unlike the rest of the code we do not use pydantic here, which means we lose type checks (a dataclass looks like it
checks types, but it does not). A missing key still fails, because from_payload reads every field directly. The
reason is to keep the Lambda light: the receiver only needs the standard library and boto3, which the runtime already
has, so the zip of one file is the whole build and the cold start stays short. A faster option would be a Rust or Go
Lambda. I had a lot of success with this in other projects, but a blog project does not need it.
@dataclass(frozen=True)class Post: """What a person wrote: an issue body, a comment or a review."""
id: int author: str association: str text: str
@classmethod def from_payload(cls, raw: dict) -> "Post": # A missing key fails here, at the trust boundary. An empty body is null. return cls(raw["id"], raw["user"]["login"], raw["author_association"], raw["body"] or "")
def trusted(self, sender: dict) -> bool: # A bot sender is dropped, or the agent would answer itself in a loop. return sender["type"] != "Bot" and self.association in TRUSTED_AUTHOR_ASSOCIATIONS
@dataclass(frozen=True)class Feedback: """A queue entry for the execution that waits on an issue or PR thread."""
thread: int entry: dict
@dataclass(frozen=True)class Mention: """The agent invoke payload for a new request."""
repo: str installation_id: int issue_number: int request_id: str comment_id: int | None author: str prompt: strRouting is one Python match statement: each case names a webhook and its action and takes the fields it needs,
and anything we do not expect falls through to case _.
def classify(kind: str, payload: dict) -> tuple[Feedback | None, Mention | None]: """Map a webhook to feedback for a waiting execution, a new request, or both.
A comment is both: feedback if an execution waits on its thread, else a mention. An approval is not feedback. A diff comment needs no case, because GitHub also sends its review as submitted. A ping has no action. """ match kind, payload: case "issues" | "pull_request", {"action": "closed"}: return Feedback(_number(payload), {"closed": True}), None case ( "pull_request_review", {"action": "submitted", "review": {"state": state} as review}, ) if state != "approved": post = Post.from_payload(review) if not post.trusted(payload["sender"]): return None, None entry = {"review_id": post.id, "author": post.author} return Feedback(_number(payload), entry), None case "issue_comment", {"action": "created", "comment": comment}: post = Post.from_payload(comment) if not post.trusted(payload["sender"]): return None, None entry = {"prompt": _prompt(post.text), "comment_id": post.id, "author": post.author} mention = _mention(payload, post, f"comment-{post.id}", post.id) return Feedback(_number(payload), entry), mention case "issues", {"action": "opened", "issue": issue}: post = Post.from_payload(issue) if not post.trusted(payload["sender"]): return None, None return None, _mention(payload, post, f"issue-{post.id}", None) case _: return None, None
def _mention(payload: dict, post: Post, request_id: str, comment_id: int | None) -> Mention | None: # issue.pull_request marks a PR thread, and a PR thread never starts a request. if payload["issue"].get("pull_request") or not BOT_HANDLE.search(post.text): return None return Mention( repo=payload["repository"]["full_name"], installation_id=payload["installation"]["id"], issue_number=payload["issue"]["number"], request_id=request_id, comment_id=comment_id, author=post.author, prompt=_prompt(post.text), )
def _prompt(text: str) -> str: return BOT_HANDLE.sub("", text).strip()
def _number(payload: dict) -> int: return (payload.get("pull_request") or payload["issue"])["number"]The handler reads like the request flow chart:
- Verify the signature
- Classify the event
- Deliver feedback if a request waits on the thread, otherwise start a new request for a mention
The DynamoDB queue routes feedback to the right durable execution: each issue or PR thread has its own item, which SQS cannot do without a queue per thread. One write queues the feedback and takes the callback id, so only one event can wake a waiting request. If that write finds no waiting request, the comment falls back to starting a new one.
GitHub can deliver the same webhook twice. A redelivered mention is harmless: the execution is named after the comment or issue id, so Lambda returns the running execution instead of starting a second one. A redelivered comment on a waiting thread is queued twice, though. Only reviews are deduplicated, by id, when the agent reads the queue.
def handler(event: dict, context: object) -> dict: """Function URL entry point: verify, filter, start or resume, answer fast.
Reads the webhook secret from SSM once per sandbox and verifies the signature (401 on mismatch). Feedback on a thread with a waiting execution goes to its queue. Otherwise a mention on an issue starts an execution. Anything else is 204. """ headers = event.get("headers") or {} body = event.get("body") or "" raw = base64.b64decode(body) if event.get("isBase64Encoded") else body.encode() if not verify_signature(_webhook_secret(), raw, headers.get("x-hub-signature-256")): return {"statusCode": 401} payload = json.loads(raw) feedback, mention = classify(headers.get("x-github-event", ""), payload) if feedback and _deliver(payload["repository"]["full_name"], feedback): return {"statusCode": 202} if mention: _start(mention) return {"statusCode": 202} return {"statusCode": 204}The PR flow#
At a high level the flow is simple:
- Fetch the start commit (the default branch, or the PR branch once it exists) at depth 1 into
/tmp - Run the agent on it
- Publish based on the result type (this is our code, not a tool the model calls):
- An
Answeris posted as a reply where each ask was made. - A
TaskResultis committed and pushed totfsmith/<request id>. The first push opens the PR, with its title and description taken from the result. Then the replies are posted.
- An
- Wait for feedback or more events
For git interactions we use the actual git CLI with a small wrapper class. The wrapper never force-pushes, and only
fetch, has_branch and push send the token. A commit pushed to the branch during the round makes our push fail
instead of being overwritten. A retry would hit the same moved branch, so the publish step returns the rejection
instead of raising it, and the round posts “Round n stopped: the push was rejected” and the execution ends.
def fetch(self, ref: str) -> str: self._run("fetch", "--quiet", "--depth", "1", "origin", ref, remote=True) return self._run("rev-parse", "FETCH_HEAD")
def has_branch(self, branch: str) -> bool: return bool(self._run("ls-remote", "--heads", "origin", branch, remote=True))
def push(self, branch: str) -> None: # Never a force push: a commit pushed meanwhile fails the push. try: self._run("push", "--quiet", "origin", f"HEAD:refs/heads/{branch}", remote=True) except RuntimeError as error: if "[rejected]" in str(error): raise PushRejected(str(error)) from error raise
def _run(self, *args: str, remote: bool = False, env: dict[str, str] | None = None) -> str: full_env = os.environ | (env or {}) | {"GIT_TERMINAL_PROMPT": "0"} if remote: # The token travels in an HTTP header set through GIT_CONFIG_* variables: # not in the remote URL, .git/config, argv, or a failed command's message. basic = base64.b64encode(f"x-access-token:{self.token}".encode()).decode() full_env |= { "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": f"http.{GIT_URL}/.extraheader", "GIT_CONFIG_VALUE_0": f"Authorization: Basic {basic}", } result = subprocess.run( ["git", *args], cwd=self.path, env=full_env, capture_output=True, text=True ) if result.returncode != 0: raise RuntimeError(f"git {args[0]} failed: {result.stderr.strip()}") return result.stdout.strip()With one method per git operation, push_branch reads as the retry argument: a durable step can run twice, so it
snapshots the tree, returns early if the branch already has it, and otherwise commits and pushes.
def push_branch(workspace: GitWorkspace, branch: str, message: str) -> str: """Commit the workspace to branch, push it, and return the commit SHA.
The workspace is a clone of the commit the round started on, so the push fast forwards. A retried step finds its own tree on the branch and returns. Never the default branch. """ tree = workspace.snapshot() if workspace.has_branch(branch): head = workspace.fetch(branch) if workspace.tree_of(head) == tree: return head sha = workspace.commit(message, _bot_identity(workspace.token)) workspace.push(branch) return shaDurable execution: one request, one execution#
Durable execution lets the Lambda resume where it left off. It is not a memory snapshot: the handler runs again from the top, and pydantic-ai skips the model calls and tool calls that already have a checkpoint. This means the agent does not have to repeat the expensive, slow LLM calls. A smaller saving, but worth mentioning: between rounds the execution waits for feedback from GitHub on a callback, and no compute is billed while it waits.
In the image you can see the durable execution for issue #22 and the PR it led to, #23. The agent runs are the
round-n entries, and in between are the steps of the review loop, the review wait and the pending and
feedback steps, which a replay also reads from their checkpoints. These rounds are child contexts and you can see
the LLM calls which we would not need to repeat on a replay.
Below you see the code that makes the agent durable. Key is AWSLambdaDurability in the capabilities, which
checkpoints every model request and tool call. You also see that we exclude some tools from checkpointing, by
wrapping them in _replayed. Their effect lives in the sandbox rather than in their result: writing files,
initializing terraform, and the record of which files were read, which edit_file checks. A resume can start on a
fresh sandbox, so these tools run again on replay, from the cached model responses. The others, like checkov,
only report on the workspace, so they stay checkpointed and a replay reads their stored result.
# The agent's own model id. Runs pass a registry key instead; this one only# lets the durable capability bind, and resolves to DEFAULT_MODEL._DEFAULT_MODEL_ID = "DEFAULT_MODEL"
def _registry_model(ctx: ModelResolutionContext[RoundDeps], model_id: str) -> Model: # A durable run carries only the model id across the step boundary, so # each request builds its model from the registry on the worker side. name = require_env("DEFAULT_MODEL") if model_id == _DEFAULT_MODEL_ID else model_id return _build_model(name)
def _replayed(tool: Callable[..., Any]) -> Tool: # A durable resume starts on an empty /tmp. These tools build the workspace # and the read-before-write record in deps, so a replay runs them again # instead of returning their checkpointed result. return Tool(tool, metadata={"aws_lambda": False})
# One Agent, reused across invocations; each run scopes the tools to its RoundDeps.# Only output tools end a run, so providers force tool use on every turn. Bedrock# rejects that once extended thinking is on; no registry entry enables it.agent = Agent( # Checkpoint step names derive from the agent and tool names, so a rename # needs a new Lambda version; waiting executions keep the old one. name="terraform-pr-agent", model=_DEFAULT_MODEL_ID, deps_type=RoundDeps, # One output tool per type: final_result_TaskResult, final_result_Answer. output_type=[TaskResult, Answer], system_prompt=SYSTEM_PROMPT, tools=[ _replayed(list_files), _replayed(read_file), _replayed(write_file), _replayed(edit_file), _replayed(delete_file), _replayed(terraform_init), terraform_validate, tflint, checkov, ], # A linter false positive can take several attempts to work around; at 3, # checkov alone ended a round that was still making progress. retries={"tools": 5, "output": 3}, # AWSLambdaDurability is inert outside run_durable, so execute() and the # evals run as before. capabilities=[ResolveModelId(_registry_model), AWSLambdaDurability()],)Besides making the agent durable, you can also use the durable context in your own code. Below we add our own steps and wrap each agent run in a child context. This goes in a loop, because every time we come back to the agent on the issue or the PR, it picks that up in a new round.
class RoundState(TypedDict): """What the next round needs from the last one; the history itself is in S3."""
pr: int | None sha: str | None history_key: str | None stopped: str | None
def run_review_loop(task: MentionTask, context: DurableContext) -> ReviewOutcome: """Run review rounds until the thread closes, a round fails, or time runs out.
Runs from the top on every invocation. The token is not a step: a checkpointed token is dead after a long wait. """ flow = Flow(task, github.installation_token(task.repo, task.installation_id), context) context.step( lambda _: github.add_reaction(flow.repo, flow.token, flow.subject, "eyes"), name="ack" ) deadline = context.step(lambda _: int(time.time()) + EXECUTION_TIMEOUT_SECONDS, name="deadline") background = context.step(lambda _: _background(flow), name="background")
ask, asks = _asks_prompt([(THREAD, task.prompt)], []) prompt = background + ask state: RoundState = {"pr": None, "sha": None, "history_key": None, "stopped": None} handled: set[int] = set() for n in count(1): state = context.run_in_child_context( lambda child: _round(child, flow, n, prompt, asks, state), # noqa: B023 name=f"round-{n}", ) if state["stopped"]: return _fail(flow, state["pr"], n, state["stopped"]) turn = _next_feedback(flow, flow.thread(state["pr"]), n, deadline, handled) if turn is None: logfire.info("thread closed after {rounds} rounds", rounds=n, pull_request=state["pr"]) return {"status": "done", "pull_request": state["pr"], "rounds": n} prompt, asks = turn["prompt"], turn["asks"]The handler still runs from the top on every invocation and goes through the loop again, so do not put very time-consuming elements in there that are not durable/stored (like LLM calls). Otherwise even if they are deterministic you pay a runtime price. The diagram after the next paragraph highlights this a bit more.
You also need to be deterministic. If you generate a uuid in your code and expect it to be the same across invocations, you will be disappointed! An execution stays on the Lambda version it started on, so a deploy does not change code mid-replay. Keep old versions until their executions drain.
The review loop#
Diving a bit more into the review loop itself, we opted for review rounds instead of giving the agent an
await_review tool. This makes rounds more predictable and results can be broken down and tested
much more easily. We can put request limits and max tokens on a round instead of the full agent run!
The Answer option was added after the first test runs as it was a real gap. The agent could only end a round with
code, so a plan question had no valid answer. It would just get stuck, burn through tokens and fail. Being able to choose between Answer
and TaskResult (description of the implementation) was the key to make the flow work.
The agent is notified by the receiver while it sleeps, but it also checks the queue itself before it goes to sleep. This avoids anything being stale and a continuous polling loop of a Lambda. Once woken, the Lambda keeps working the queue (new items can arrive while a round runs) and then goes to sleep. While it is asleep the receiver would wake it again. Both sides update the thread’s DynamoDB item atomically, and whoever removes the callback id sends the wake, so it is sent once.
def _record_callback(repo: str, thread: int, callback_id: str, deadline: int) -> None: """Wait for feedback on the thread, or wake at once if some queued meanwhile.
The receiver queues feedback that arrives during a round. Whichever side removes callback_id sends the wake, so it is sent exactly once. """ logfire.info("waiting for review on #{thread}", thread=thread) dynamodb = boto3.client("dynamodb") table = require_env("REVIEWS_TABLE") item = dynamodb.update_item( TableName=table, Key=_thread_key(repo, thread), UpdateExpression="SET callback_id = :id, expires_at = :deadline", ExpressionAttributeValues={":id": {"S": callback_id}, ":deadline": {"N": str(deadline)}}, ReturnValues="ALL_NEW", )["Attributes"] if "pending" not in item: return try: dynamodb.update_item( TableName=table, Key=_thread_key(repo, thread), UpdateExpression="REMOVE callback_id", ConditionExpression="callback_id = :id", ExpressionAttributeValues={":id": {"S": callback_id}}, ) except ClientError as error: if error.response["Error"]["Code"] == "ConditionalCheckFailedException": return raise boto3.client("lambda").send_durable_execution_callback_success( CallbackId=callback_id, Result=b"{}" )An honest assessment#
This post has been a demonstration on a toy problem that is close to a real one, but I think we have shown that the problem itself is certainly solvable (see all the software factory products out there). There is a fundamental catch, though. We reduced the problem space on purpose by aiming at a very narrow field (Terraform) and can get reliable results by hooking in a few deterministic barriers and limiting what the agent can do. Clear boundaries are what made this work (for our relatively simple problems) at a manageable price. It is not hard to extrapolate from the evals, though: the more you loosen the boundaries and give the agent more freedom, the harder it gets. This is why it surprises me when I see people building agent systems where they give the agent full freedom and a lot of tools. I would find that very hard to commercialize (at least if I were on the hook for the cost and could not pass token pricing on to customers).
That said, it is easy to see the potential for systems that interact with humans, have context about the task and capabilities specialized for the task at hand. How companies manage this complexity and fit LLMs into their products to improve customer journeys will separate the good from the bad. Good evals, deterministic guardrails and extensive monitoring to feed back into evals are key for this.
It was also interesting to come back to this project and keep up with what is happening in this space. pydantic-ai, Logfire and AWS have all moved fast, added new features and simplified things. Anyone building in this space has to adapt quickly.
This concludes the series. Thank you to everyone who stayed with me from the first Bedrock call to an agent that ships its own PRs.