This post describes the threat hunting agent we run in our SOC. On a schedule it decides what is worth hunting, runs the hunt against our SIEM and EDR telemetry, records how the hunt closed, and drafts a detection rule from what it learned. Nobody approves a hunt before it runs. People review what comes out: findings, proposed rules and the telemetry gaps the hunts hit. The agent can't open a case, merge a rule or deploy anything itself.
I'll cover the architecture, the components with some alternatives to each, enough code to build a minimal version, and the problems we hit in production. Product names are mostly left out; the design doesn't depend on any particular vendor. It is the second agent built on the same platform as [the one that tunes our detections](https://tresscross.blog/building-an-agent-that-tunes-our-detections), and it reuses most of it.
The prompts, tool schemas and the rules described here are published, with our environment taken out, at [github.com/tresscross/autonomous-threat-hunting](https://github.com/tresscross/autonomous-threat-hunting).
## Prerequisites
The hunting agent did not start out autonomous. For its first few months it ran only when an analyst asked: they pasted a piece of threat intel, a link or a case into our hunt app, and the agent hunted it. That produced a little over a hundred hunts, each stored with its hypothesis, the techniques it covered and what it found.
That history is what made the autonomous version possible. The generator needs prior hunts to avoid repeating, follow-up suggestions to pick from, and a team that already trusts the format of a hunt write-up. You also need detections in Git with ATT&CK technique tags, a feed of threat intel that something has already scored for relevance, and programmatic access to your SIEM. If hunts in your team live in someone's notes, start there.
## Why in-house
A hunt is only as good as its knowledge of the estate: which log sources exist, which fields are actually populated, what normal looks like, what was hunted last month and what a rule already covers. All of that is internal.
Building it ourselves also meant the outputs land where the team already works. A finding goes to the hunt app for an analyst to agree or disagree with. A draft rule goes through the same merge request and CI path as every other detection change. There is no second route to production.
## Overview
```mermaid
flowchart TD
S[Schedule, every two hours] --> Q{Review queues<br/>under their limits?}
Q -->|no| P[Record why it paused]
Q -->|yes| G[Generator proposes hunts]
G --> H[Hunt agent runs one hunt at a time]
H --> C[Closure, queries and telemetry gaps stored]
C --> D[Detection builder drafts a rule]
C --> R{People review}
D --> R
R -->|reviewing keeps the queues short| Q
```
Three inputs feed the generator:
- Threat intel that our intel pipeline scored as relevant and nobody has sent to hunting yet.
- Earlier hunts: what they covered, how they closed and the follow-ups they suggested.
- Coverage gaps: techniques that recent intel names and that no detection rule and no recent hunt covers.
Analysts can still file a hunt by hand. It joins the same queue and is treated the same from then on.
## Components
Every component here is a commodity service. The right-hand column lists alternatives.
| Role | What it does | Options |
|---|---|---|
| Scheduler and glue | Runs the schedule, reads the queues, gathers context, stores results | Tines, Splunk SOAR, Cortex XSOAR, Torq, Shuffle, n8n, or cron and a small service |
| Front door | Validates the request, enqueues it, returns immediately | A serverless function (Cloud Functions, AWS Lambda, Azure Functions) or a small FastAPI/Flask service |
| Queue | Runs one hunt at a time, retries on infrastructure failure | Google Cloud Tasks, AWS SQS, Azure Service Bus, Celery or RQ on Redis |
| Worker | Runs the generator, the hunt and the detection builder | Cloud Run, ECS/Fargate, Azure Container Apps, Kubernetes jobs |
| Model | Tool-use LLM | Any frontier model with tool calling, through the vendor API or a cloud provider's managed endpoint (Bedrock, Vertex AI, Azure) |
| Hunt store | Hunts, queries, gaps, proposals, coverage snapshots | ClickHouse, Postgres, BigQuery, or your SIEM's own lookup tables |
| Review surface | Where people read findings, proposals and metrics | An internal web app, a case manager, or a dashboard on the store |
| Change control | Draft rules as merge requests | GitLab, GitHub, Bitbucket |
Some specifics on how ours is configured:
The worker has no database. Everything it knows about hunting history arrives in the request, and everything it produces leaves in one callback that the SOAR platform writes to the store. That kept the worker's credentials to read-only query access.
The queue runs one hunt at a time. A hunt sends 20 to 40 queries to the SIEM on a shared service login, and broad scans slow everyone else on that login while they run. Serialising hunts caps that load whatever the schedule says.
The model is called through the cloud provider's managed endpoint with the worker's identity, so there is no model API key to store.
## The pipeline
The hunt itself is a model session, but the decisions that matter for trust are made in code.
```mermaid
flowchart TD
A["Check the review queues<br/>(code)"] --> B["Find coverage gaps<br/>(code)"]
B --> C["Propose hunts<br/>(model)"]
C --> D["Drop repeats<br/>(code)"]
D --> E["Run the hunt<br/>(model)"]
E --> F["Run the positive control<br/>(code)"]
F --> G["Decide the closure<br/>(code)"]
G --> H["Store queries and gaps<br/>(code)"]
H --> I["Draft a detection<br/>(model, then code gates)"]
```
### Backpressure (code)
An always-on generator will fill whatever queue you give it, and the scarce resource is analyst attention, not compute. So every run starts by counting what is waiting for a person: findings nobody has agreed or disagreed with, proposed detections nobody has triaged, proposals held for review, and hunts still running. If any count is over its limit, the run records a row saying why and stops.
```sql
SELECT
(SELECT count() FROM hunts_latest
WHERE finding AND finding_decision = 'none') AS findings_waiting,
(SELECT count() FROM hunt_detections FINAL
WHERE decision = 'proposed' AND disposition = 'untriaged') AS detections_waiting,
(SELECT count() FROM hunt_hypotheses FINAL
WHERE state = 'proposed') AS hypotheses_waiting,
(SELECT count() FROM hunts_latest
WHERE agent_status = 'pending') AS hunts_running;
```
The hunt app shows the last run's reason, for example "52 proposed detections are waiting for triage (limit 25)". Reviewing the outputs is what restarts the loop. The limit on unreviewed findings is the lowest, because an unreviewed finding may be a real intrusion.
### Coverage gaps (code)
We have no curated list of in-scope techniques, only the rule repositories. So intel sets the scope. A technique is a gap when relevant intel from the last 30 days names it, no active rule is tagged with it, and no hunt tested it in the last 90 days.
```python
def gaps(articles, cover, recent_hunts, limit=25):
done = hunted(recent_hunts) # only hunts that actually tested the technique
out = []
for technique, seen in intel_techniques(articles).items():
if cover.get(technique) or technique in done:
continue
related = [r for t, rules in cover.items()
if t != technique and base(t) == base(technique) for r in rules]
out.append({"technique": technique, "articles": seen["articles"],
"examples": seen["examples"], "related_rules": names(related)[:3]})
return sorted(out, key=lambda g: -g["articles"])[:limit]
```
A rule on the same parent technique does not close the gap, but it is listed beside it. A rule tagged for PowerShell may already catch what the generator would hunt under the Unix shell sub-technique, and only something reading the rule names can tell.
### Proposing hunts (model)
The generator receives the gaps, a dozen intel summaries, 90 days of hunts with their follow-up suggestions, the backlog and the open telemetry gaps. It calls `submit_hypotheses` with at most three proposals. An empty list is a valid answer. Trimmed:
```json
{
"title": {"type": "string"},
"hypothesis": {"type": "string", "description": "One falsifiable sentence."},
"technique": {"type": "string", "description": "One ATT&CK id, e.g. T1543.002"},
"log_sources": {"type": "array", "items": {"enum": ["..."]}},
"lookback_days": {"type": "integer"},
"discriminator": {"type": "string",
"description": "The field condition that separates malicious from routine."},
"origin": {"enum": ["ti_article", "prior_hunt", "coverage_gap"]}
}
```
The `discriminator` is required. A proposal without one is a search for "anything unusual", and code drops it. Its one tool looks up deployed rules by name, so it can check whether a detection already exists before proposing a hunt for the same behaviour.
### Dropping repeats (code)
Proposals are compared with recent hunts and the backlog by text similarity. We set the thresholds from our own data: across the stored hunts, a hunt that had been filed twice scored 0.9 or higher against its twin, different hunts that shared a behaviour scored 0.5 to 0.72, and unrelated hunts sat under 0.5. A proposal at 0.8 or above is stored as a duplicate and never runs. One between 0.5 and 0.8 is kept, named as resembling the earlier work, and held for a person. Everything else starts as a hunt.
Running that measurement was its own finding. About a third of our analyst-filed hunts had a near-duplicate.
### The hunt (model)
The hunt agent gets the proposal as its brief and a belt of read-only tools: SIEM queries (single and batched, with slow ones handed back as a job to fetch later), a count-and-sweep query tool for our second EDR, our log-source documentation, a search over past hunts, and the investigation tools the triage agent uses. It works to a 24-minute wall clock: at 80% it is told to wrap up, at 90% every tool but the submission refuses.
It ends by calling `submit_hunt_findings`, and that call is where code takes over.
### The positive control (code)
Most hunts find nothing, and they should. But an empty result from a log source that is dark, or from a field that is never populated, reads exactly like a clean one. So a negative submission must name its control: the hunt query's telemetry selector with the discriminator removed.
```
hunt = telemetry selector AND discriminator
control = telemetry selector
```
The worker runs the control itself, as aggregates only. A timed one-day count sizes the window, then a per-day count over the window the hunt claims.
```python
def check(control, days, *, run, executed, budget_s):
if not control: return Result("missing")
if not has_source_anchor(control): return Result("invalid")
if not related(control, executed): return Result("unrelated") # a source the hunt never queried
probe, probe_s = timed(run, as_count(control), "1d")
if probe is None: return hour_fallback(control, run)
for window in windows_to_try(days, probe_s, budget_s):
buckets = run(as_daily_buckets(control), f"{window}d")
if buckets.timed_out: continue # try the next shorter window
share = buckets.days_with_events / window
if buckets.total == 0: return Result("zero", window)
if share < 0.8: return Result("sparse", window, share)
return Result("passed", window, share)
return Result("passed" if probe else "zero", days=1)
```
A missing, malformed or unrelated control is sent back to the model once. A feed that was dark for part of the window is not asked about twice, because asking cannot bring it back.
### The closure (code)
Every hunt ends in one of five closures, decided by code from the verdict, the control and the hunt's own statement of how much of its hypothesis the data could answer.
```python
def closure_for(finding, control, coverage):
if finding is True:
return "closed_findings"
if control and control.status in ("zero", "sparse"):
return "blocked_telemetry"
if control and control.passed:
if coverage == "tested":
return "closed_negative"
if coverage in ("partly_tested", "untested"):
return "blocked_telemetry"
return "negative_unverified" # the control could not be run, or no statement
```
The fifth, `unfeasible`, is set when a hunt runs out of turns or time. Only `closed_negative` and `closed_findings` count as having tested a technique. The reason `coverage` is in there is the first lesson below.
### Queries and gaps (code)
After the hunt, code reads the session's own audit trail and stores every query it sent, with its window, row count and outcome, plus the control as a row of its own. Each bullet the hunt wrote under telemetry gaps becomes a row in a gap register with a state, an owner and a ticket field. The model is not asked for any of this, so a query is recorded whether or not the write-up mentions it.
### Drafting a detection (model, then code gates)
Each finished hunt goes to a detection builder, including the negative ones: a technique we can see but do not alert on is the gap most worth closing. It reuses the validator, the live-data test, the control query and the volume gate described in the tuning post. A rule that would fire more than about five times a day is recorded as rejected for low fidelity, with the measured number, so nobody re-derives the same noisy rule.
## The loop
The generator and the hunt use the same loop as the tuning agent: run tools until the model calls the step's submit tool, validate the submission in code, and return any problem as a tool error in the same conversation. What is new here is that the submit tool can run queries of its own. Simplified:
```python
class FindingsCollector:
def execute(self, args):
findings = self.normalise(args)
missing = self.missing_fields(findings)
control = self.control_for(findings) # cached per (query, window)
hold = (control and control.fixable) or self.coverage_error(findings, control)
if missing or (hold and self.rejections < self.max_rejections):
self.rejections += 1
raise SubmissionRejected(self.explain(missing, control))
findings["closure"] = closure_for(findings["finding"], control,
findings["hypothesis_coverage"])
self.findings = findings
return {"recorded": True}
```
Notes on the loop:
- One rejection budget covers every reason to send a submission back. A hunt that is short on time is not held at all; the submission is stored with the weaker closure.
- The control's result is cached, so a resubmission with the same control costs nothing.
- The closure is never the model's to write. It supplies a verdict, a control and a coverage statement; code derives the rest.
### What it costs
From the worker's logs, at list prices: a hunt averages $2.47, the detection build after it $0.21, and a generation run $0.48 for three proposals. A hunt reads about 2.2 million input tokens across some 13 turns, and prompt caching roughly halves the bill. At our schedule's maximum of 36 hunts a day that is about $100 a day. Spend was never the constraint. Review time and query load were.
## Review controls
The agent has no write access to anything that matters. Its outputs are rows in the hunt store and, for a rule the builder is confident in, a merge request it cannot merge. What a person does with each:
- **A finding** is agreed or disagreed with in the hunt app. Agreement is what opens a case.
- **A proposed detection** is accepted or discarded, and an accepted one goes through normal MR review.
- **A telemetry gap** is accepted into a ticket, closed, or marked won't-fix.
- **A held proposal** is approved, edited, deferred or rejected.
Every one of those queues has a limit that pauses generation, which makes the review surface the control surface. There is no separate kill switch to remember: stop reviewing and the system stops.
## Measurement
Counting hunts or findings rewards volume, and an autonomous producer will supply as much volume as you count. The number we track is technique coverage over the scope intel sets:
| Over the techniques relevant intel named in 30 days | Share |
|---|---|
| Covered by an active rule | 54% |
| Tested by a hunt in the last 90 days | 2% |
| Neither | 45% |
The middle row is the honest one. Hunts had looked at about half of those techniques, but nearly all of them predate the closure rules, so they do not count as tests. A lazy hunt cannot move this number: it closes as blocked or unverified.
## Lessons from production
### A passing control is not a tested hypothesis
One of the first autonomous hunts looked for a new administrator account on our virtualisation management platform. The audit log that records account changes there is not collected, so the hunt queried a neighbouring log from the same product, which is healthy. Its control on that log passed across all 90 days, and the hunt closed as a tested negative. Its own summary said the behaviour could not be ruled out.
The control proves the data a hunt queried was there. It does not prove that data could answer the question. A negative now also states `hypothesis_coverage` (`tested`, `partly_tested` or `untested`), judged against the hypothesis and not the queries, and anything but `tested` closes as blocked by telemetry. A hunt that claims `tested` while listing telemetry gaps is asked once which it is. The next hunt on the same platform closed as blocked, with seven named gaps.
### The window you verify is not always the window you claim
The first version sized the control's window once, from a one-day probe measured against 60% of the query timeout. A probe that ran a few seconds slow dropped an identity-log control to a single day, and the hunt still closed as tested over 30. The real 30-day count took 12 seconds.
A one-day count is mostly fixed overhead, so its duration says little about a month. The control now attempts the claimed window whenever the projection fits the timeout, falls back to a week, and uses the week's own timing to decide whether the month deserves one attempt after all. Heavy endpoint streams still verify less than they claim, down to a single hour, and the stored record says so.
### How you count per day matters
The per-day count was first written as a formatted date field and a group-by. It did not finish 30 days of identity logs in 120 seconds. The query language's built-in time bucketing costs the same as a plain count: 51 seconds against 50 on the same data. Measure the control's own cost before blaming the source.
### Most failed queries were our own limit
Once every query was stored, we could see why they failed. Ten of the first fifteen failures were the worker's cap of four SIEM jobs in flight. A batch was all or nothing, so one slow scan still running got a batch of four refused whole. The error told the model to fetch a running job first, which returns its partial result and frees nothing, so the model fetched, resubmitted and was refused again.
A batch now runs as many queries as there are free slots, and the refusal says a slot frees only when a job ends. We would not have found this without the query table.
### The first autonomous run was paused, correctly
The first limit on untriaged detection proposals was 25. There were already 52 waiting when we turned the generator on, so the first run we asked for recorded a pause and proposed nothing. That was the system working, and it was also a clear statement of where the bottleneck is. The limit is higher now, and the queue is still the thing to watch.
### Test the scheduled path, not just the button
Every generation we had tested was started by hand. The first scheduled run failed at its opening step, because a formula in the SOAR platform treated a missing request body as an error where we had assumed it would read as empty. Nothing generated, and nothing alerted, because a run that fails before it records anything looks like a quiet morning. There was no way to trigger a scheduled run on demand, so the test was to add a one-off schedule entry a few minutes ahead, watch it, and remove it.
### Rules need technique tags on every platform
Coverage gaps depend on rules being tagged. Our SIEM rules carried an ATT&CK technique; the rules for our second EDR did not, and only a third of them named one anywhere in their description. We made the tactic and technique required fields there too, backfilled every rule, and found that the vendor's sync treats any byte change as a rule update. The deployment script now strips those two lines before upload, so tagging a rule does not redeploy it.
### Closed loop came last
The order we enabled things in: analysts trigger every hunt; the generator proposes and a person approves each one; then proposals start on their own. The approval stage was short, but it is where we saw what the generator actually proposes, including two tools it kept naming as log sources that are really ticket systems. Go straight to the closed loop and you find that out from the hunts.
## Building your own
The [autonomous-threat-hunting](https://github.com/tresscross/autonomous-threat-hunting) repository has both prompts, the two tool schemas, reference tables and a guide to wiring them into your own runtime. It ships no code: the parts that depend on your SIEM and your store are yours to write.
A suggested order:
1. Store hunts as structured records: hypothesis, techniques, data sources, what was found. Run them by hand or with an assistant until you have a few dozen.
2. Give the hunt a submit tool and make code decide the closure. Add the positive control and the coverage statement before anything else, and check both by hand on hunts you know the answer to.
3. Store every query the hunt sends, read from the session's own trail. Read the failures.
4. Turn telemetry gaps into rows with an owner.
5. Tag every detection rule with a technique, in every rule repository, and compute coverage in plain code.
6. Add the generator with a required discriminator and a duplicate check tuned on your own hunts. Let it propose into a backlog that people approve.
7. Add backpressure on every queue a person reads, and show the reason for a pause where analysts will see it.
8. Run it on a schedule, and test the scheduled path itself.
9. Let proposals start on their own, one hunt at a time, and hold the ones that resemble earlier work.
## Readiness checklist
- Hunts are recorded in a consistent structure, and there is a history of them.
- The SIEM and EDR can be queried programmatically with read-only credentials.
- Detection rules carry ATT&CK technique tags.
- Threat intel is collected and scored for relevance somewhere.
- Someone is assigned to review findings and proposed detections, and knows they are the brake.
- Hunt activity, queries and cost are logged.
Each of these is worth having without the agent.
## Next steps
The coverage statement still rests on the hunt's own judgement. The reconcile question and the prompt push it toward honesty, but a hunt can call a proxy a test. The next piece of work is tying the control to the hypothesis's discriminator field, so that code can check the field the hunt depends on is populated, not just that the source is alive.
The other gap is the oldest one. A proposed rule is still checked for format, execution, volume and data, but not for whether the technique triggers it. The detection lab from the tuning post is the answer to both agents' version of that problem, and it is still not wired in.