I built an autonomous security-research agent that runs unattended: it picks a target, enumerates the attack surface, probes for vulnerabilities, validates its own findings, and files reports — in a loop, indefinitely, across several targets in parallel. It drives a coding-agent CLI as its execution engine.
This post is about the architecture, not the security work. Because the interesting part turned out to have almost nothing to do with hacking and everything to do with a harder, more general problem:
How do you run an LLM agent unattended for a long time without it (a) drowning in its own context, (b) trusting its own bad judgment, or (c) setting the building on fire?
Almost every design decision below is a scar. The agent did something dumb or expensive, and the fix became a structural rule. If you're building any kind of long-running autonomous agent, these patterns transfer directly.
The core inversion: memory lives outside the conversation
The naive way to build a long-running agent is one long session. You start a conversation, the agent works, and when the context window fills up you compact it and keep going.
This falls apart fast. Context grows without bound. Auto-compaction is lossy — the agent forgets what it decided three hours ago. And every token in the window is re-sent on every subsequent turn, so a big tool result you pulled at hour one is still being paid for at hour six.
So I inverted it. The central rule:
Every iteration is a completely fresh session. The conversation does not persist. The agent's memory lives in durable external stores.
Each iteration: the fresh session reads external memory first, does work, writes it back last. Nothing survives in the conversation.
Each iteration, the agent:
- Reads a working-memory file first — its bridge from the last iteration (current target, in-flight investigation, promising leads, the single next step).
- Does a bounded amount of work (the bounds enforced by code, as we'll see in Lesson 1).
- Rewrites the working-memory file last — and after each objective, because it can be killed at any moment.
Nothing important ever lives only in the conversation. Four external stores survive a session death:
- A task board (a database-backed kanban) — the queue and the record of what's done and why.
- A working-memory file — the cross-session bridge.
- A credential store — encrypted authenticated sessions.
- A knowledge vault — reports and reusable playbooks, indexed for semantic recall.
This is the single decision everything else hangs off. Because no state lives in the conversation, I can kill a session aggressively — mid-task, without warning — and lose almost nothing. The next fresh session picks up from the working-memory file.
That "kill it aggressively" freedom is what makes the rest of the design possible.
The driver loop: a dumb while around a smart agent
The agent's execution engine only loops on its own in interactive mode, not in the headless "run this prompt and exit" mode I needed. So the loop itself is a plain bash script:
while :; do
read STOP file → exit if present
replenish the board → if it's empty
run_one(prompt) → a FRESH agent session
handle rate-limit → exponential backoff
done
The bash layer is deliberately dumb. It knows nothing about hacking. It launches a fresh agent session, watches it, kills it when it exceeds a budget, and re-launches it. All the intelligence is in the prompt and the tools; all the discipline is in the loop.
This split — dumb deterministic orchestrator, smart non-deterministic worker — is worth internalizing. The things you want to be reliable (budgets, kill switches, isolation, retries) live in code. The things you want to be flexible (what to investigate, how to chain findings) live in the model. Don't mix them.
LESSON 1The prompt asks nicely. The handler enforces.
My first version had a prompt that said, politely, "do about 5 objectives per session, then stop."
The agent did 26.
This is the most important lesson in the whole system, so I'll state it plainly: you cannot trust an LLM to bound itself. Any budget that matters must be enforced by code that sits outside the model and can forcibly end the session.
So how is the work actually bounded? Two layers. The prompt suggests ~5 objectives (a soft hint the model may ignore). The handler — a background poller in the driver loop — queries the task board's completed-task count for this target, and when the bot has moved MAX_OBJECTIVES tasks to "done" this session, it kills the session's process group. The soft hint became a hard cap. That's the pattern, repeated everywhere.
Every soft limit the model ignored got promoted to a hard, externally-monitored cap:
| Cap | What it watches | Why |
|---|---|---|
| Objective cap | completed tasks on the board for this target | the model marathons past soft budgets |
| Context ceiling | re-sent-context token count in the output stream | the true "context got big, refresh now" signal |
| Turn backstop | number of assistant turns | coarse backstop if the above misses |
| Wall-clock | seconds elapsed | absolute ceiling regardless of everything |
The context ceiling is the clever one
Most people would cap "turns" or "time." But the thing I actually care about — cost, and context bloat — tracks the size of the re-sent conversation context, which the API exposes directly in its usage stream.
So the primary cap isn't turns or time. It's: when the accumulated context this session crosses a ceiling, end the session. The task isn't finished — it just gets picked back up by the next fresh session from working-memory, with a small clean context again.
Live Demo
Watch a session hit the context ceiling and get killed
Turn count was a terrible proxy for this, because per-turn size varies wildly: a session could be one enormous turn or forty tiny ones. Watching the context-token counter directly clips exactly the runaway sessions (dozens of turns, millions of re-sent tokens) that blew the budget, without touching normal ones.
But wait — how does memory survive the kill?
Here's the question that should bother you about the previous section: if the handler can kill the session at any moment, how do we know the working-memory file was updated before the kill landed? Couldn't we lose everything?
The honest answer: it's a soft guarantee, not a hard one, and it's worth understanding exactly how soft.
Three things make it survivable in practice:
- The bot rewrites working-memory after each objective, not just at the end. So at any kill moment, the file reflects at least the most recently completed objective. The worst case is losing the single in-flight objective — and that one is still
in_progresson the board (the next session sees it and resumes). - The board is durable. It's a database. Even if working-memory is stale, the board always knows what's queued, done, and in-progress. Working-memory is a convenience (a readable bridge); the board is the source of truth.
- Objective granularity is small. An "objective" is a single hunt (probe one endpoint, test one hypothesis). Losing one means re-doing minutes of work, not hours.
The real gap, stated plainly: if a kill lands during a write to the working-memory file, the file could end up half-written. The "rewrite after each objective" discipline narrows that window dramatically (there are few writes, each quick) but it doesn't atomically close it. A temp-file-then-rename would close it for real — write to working_memory.md.tmp, then rename() it over the original in a single atomic syscall. That's the proper fix. I'm calling it out because glossing over a gap like this in a blog post is how someone copies the design and silently loses data on day three.
LESSON 2Fail-direction is a per-component decision
The agent runs unattended with real capabilities: it can run shell commands and hit the network. That demands guardrails — implemented as hooks that fire before the agent uses a tool.
The subtle part isn't that there are guards. It's that each guard fails in a deliberately chosen direction, and getting the direction right per-component matters more than the checks themselves.
The safety guard fails safe (deny on any doubt)
A pre-execution hook inspects every shell command. On a parse error, an unreadable input, anything it can't confidently classify — it denies. In an unattended loop you never want a malformed call slipping through a broken check. Doubt means stop. It blocks destructive verbs (rm -rf, disk writes, reboots), destructive data operations, anything touching its own infrastructure or secrets, and out-of-scope network egress.
The assistive hooks fail open (never block the real work)
Other hooks help rather than guard — they inject useful context at key moments (more on this in Lesson 3). These fail in the opposite direction: if the helper breaks, it silently does nothing and lets the work proceed. A bug in a nice-to-have must never halt the mission.
Interactive
Toggle the simulated error and see how each guard reacts
Safety Guard FAIL-SAFE
Inspects every shell command. Blocks destructive/out-of-scope actions.
Retrieval Hook FAIL-OPEN
Injects relevant playbooks before a verdict. A nice-to-have.
LESSON 3You can't prompt an agent into good retrieval — so I built a RAG system and made it structural
I have a library of reusable playbooks — how to escalate a low-severity primitive into a real finding, what conditions kill each technique. The prompt told the agent to look them up before concluding.
It looked them up ~0% of the time. And when it did, it often picked the wrong one.
This matches what the research shows: frontier models are unreliable at both deciding a retrieval is needed and choosing the right target. You cannot prompt your way out of it. So I built a retrieval system and made using it structural, not instructional.
The RAG system: three sources, one local index
First, the retrieval itself. The knowledge base is a single vector index over three document sources, all embedded locally (no external API, no distillation LLM):
- Notes — technique write-ups, past reports, technology observations. The "what have I learned" layer.
- Tickets — every task-board row (thousands), each embedded with its tool + host set so the agent can ask "have I already run this scan on these hosts?"
- Scenario cards — one per program: a compact hunt-state card distilled from that program's tickets and filed reports.
The scenario cards are the interesting piece. Instead of the agent re-deriving "where am I on this target?" by paging through a thousand tickets, it reads one card. But here's the design choice I'm proudest of: the cards are extractive, not LLM-distilled. The signal is already in structured fields (ticket outcomes, filed-report IDs). I aggregate and rank those fields into a card with plain code. No LLM in the loop means the card cannot hallucinate a finding that isn't in the database. It's 100% local and hallucination-proof by construction.
Interactive
Progressive disclosure — click each layer to see what the agent reads, in order
Posture: HAS FILED / LIVE REPORTABLE
FILED (DO NOT re-file):
- CORS misconfig (H1 #12345, medium)
- Open redirect (H1 #12346, low)
Open reportable leads: 2 · Blocked: 1 (awaiting auth)
Next queued: test JWT alg-confusion on /api/v2/*
ESCALATION: reflected param → full ATO
KILL-CONDITIONS (rule out before calling dead):
- uses asymmetric RS256? (can't confuse to HS256)
- signature verified server-side?
[[cors-credentials]] (score 0.81)
KILL: SameSite=strict gates credentialed CORS
#1801 [dead] SSRF on webhook — no oracle
#1755 [primitive] IDOR reads foreign record
vault_check_dead_lead blocks #1801 re-investigation
This top-down read order — card → notes → tickets — is progressive disclosure. The agent reads the one-paragraph summary before paging through thousands of records. It's borrowed from agent-memory research (the "L2 scenario" idea), but with the distillation LLM stripped out so it stays local and can't fabricate.
There's also a dedicated dead-lead guard: a retrieval tool that searches only closed/investigated-and-dead notes. The agent must call it before chasing any lead, so it surfaces "you already proved this was a false positive last month" instead of re-investigating the same dead end.
Making retrieval structural, not instructional
So I had the RAG system. But the agent still wasn't using it — remember, prompting failed. The fix: retrieval became a hook, not an instruction.
At the exact moment the agent commits to a verdict — or spends a scarce resource on a lead — a pre-tool hook does the retrieval itself: it queries the index, pulls the top matching playbooks and their kill-conditions (the "don't call this dead until you've ruled out X" list), and prepends them into the agent's context before the tool call proceeds.
The model can no longer skip retrieval (the machinery ran it) or pick the wrong note (the machinery picked). It just receives the relevant knowledge at the moment it needs it, framed as a checklist to work through. And because this is an assistive hook, it fails open — if the index is down, the hunt continues unblocked.
LESSON 4An agent grading its own work is worthless
An audit of the agent's "this is a real, reportable finding" verdicts found that roughly half were false positives — plausible-looking results that didn't actually reproduce, benign behavior mis-framed as a vulnerability, duplicates of things already known-dead.
The agent had a validation step. It ran a validator in the same session. Same context, same model, same bias — it rubber-stamped its own findings. Self-validation inside one session is theater.
The fix: at the moment the agent tries to mark something as a confirmed finding, a hook spawns an independent adversarial verifier — a fresh session, a different model, reduced tools, and none of the original agent's reasoning trace. Its only job is to refute the finding using primary evidence.
- If the verifier confirms → the finding lands.
- If it challenges → the original agent gets the critique back as an error it must address this session, or concede.
The gating is cheap-to-expensive: mechanical checks first (is it even in reportable scope? is it a known duplicate? does the cited evidence exist?), and only if those pass does it spend money on the LLM verifier. A round counter prevents infinite argument — after a couple of rejections it escalates to a human instead of blocking forever. And it fails open: if the verifier crashes or times out, the finding proceeds and gets flagged for human review, rather than silently breaking the loop.
The parts that quietly worked
Not everything was a scar. A few things were right the first time:
Orient before acting. The agent's literal first move each iteration is a single "where am I on this target?" recall — the compact state card — before it pulls new work. Progressive disclosure: read the one-paragraph summary before paging through thousands of historical records. This alone prevents an enormous amount of repeated, already-done work.
Redundant result routing. Every concluded objective is recorded in two places: the structured board (the system of record) and a durable append-only log (with optional real-time notifications). Belt and suspenders — a notification failure never loses the record.
"Scan only when it pays." The prompt explicitly tells the agent it's often correct to do zero scanning this iteration and go straight to hands-on work on a known lead. Left unchecked, agents love to re-run expensive enumeration on a loop because it feels productive. A short cooldown dedup ("did I already run this exact scan in the last half hour? skip it") backs the instruction with a mechanism — because, per Lesson 1, the instruction alone isn't enough.
The mission never "completes." On a rich target there's always more surface. So finishing an objective — even a failed one — requires spawning follow-up tasks for every new piece of scope it exposed. The board is designed to grow faster than it drains. "Done" is a failure mode to be designed against, not a state to reach.
What transfers
Strip away the security domain and here's what's left — a checklist for any long-running autonomous agent:
- Put memory outside the conversation. Durable stores, not context. Then you can restart freely.
- Enforce budgets in code, not prose. The model will ignore soft limits. Cap it from the outside, and cap on the metric that actually costs you (usually re-sent context, not turns or time).
- Make durability survivable, not magical. Frequent checkpointing + a DB source-of-truth + small work units beat a fragile "hope the kill doesn't land mid-write." Use atomic rename if you need the hard guarantee.
- Choose each guard's fail-direction on purpose. Safety fails closed; assistance fails open. Write it down.
- Move unreliable steps out of the prompt and into hooks. If the model keeps skipping or botching a step, do it for it, deterministically, at the trigger moment.
- Build retrieval that's extractive where it matters. Aggregate structured fields into summaries with plain code — no hallucination, stays local. Reserve LLM distillation for the long-tail.
- Verify with genuine independence. A checker sharing the worker's session and model just confirms its mistakes. Fresh session, different model, prompted to refute.
- Design against "done." For open-ended work, make finishing a task generate more tasks.
The agent that hunts is the easy, flashy part. The scaffolding that keeps it alive, honest, and cheap for days on end — the dumb bash loop, the external memory, the fail-directional guards, the adversarial verifier — is where the real engineering is. Almost none of it is specific to security. It's just what "unattended and long-running" actually costs, paid one scar at a time.