Posts

Making Agents Work For You : First Goal Based Agent

Introductory Series In Making Agentic Workflows

Tags: harness , agent , llm , workflow

On This Page

Warning

This post is only partially complete, and I don’t intend to complete it further.

While writing this post, I was also writing the harness from scratch, and I kept updating the post as I built the harness, to some extent. Once the harness started giving good results, I focused more on it, and slowly the post drifted away from it. It still represents the base of the idea I started with.

Because of this, the post can feel very non linear. It’s a mix of the design I started with and the design I finished with, and the two are quite different in places. I tried my best to stitch it all together and keep it readable, but some effort from your side is expected.

I have no intention of keeping it up to date. I can only hope it helps.

As for the harness finding bugs, my conclusion for this pipeline is that this workflow is only useful for libraries that don’t have any fuzzing setup at all. A well written human (or centaur, human + AI) harness still beats this agentic harness.

Info

How to read this post. It follows the harness through three versions of its design :

Where something from Part 1 or Part 2 changed later, a note like this one tells you, and links to Part 3.

The biggest differences between the first build and the final harness, in one place :

The first buildThe final harness
Who picks the workthe harness hands out priming and deepening tasksthe agent picks, using the coverage tools
What the agent aims atone target branchthe frontier, which the fuzzers flip
A probea C program with main, run onceint probe(void) reading its values from the input, fuzzed for hours
write_probecompile, run once, reportcompile, fuzz for a short time, hand to the fuzzers
Builds of rizinone, with buzz-passthree : fuzz, trace and coverage
Contextcleared when fulltrimmed, compacted, and cleared only as a last resort
Tools715
Bug triagevalgrind and an agentsanitizer replay and a triage script

Disclaimer

I’m writing this post with good intent, and for educational purposes only. I do not intend to bring any individual, organization, or any other type of entity not included in the list any harm. If you use any information in this post for any malpractice, it is your own sole responsibility.

Software bugs are serious, and often lives depend on it. Follow resposible disclosure while reporting. Do not be an asshole!

This is a major step in the series because up until now we’ve only been dealing with primitives of writing a harness. Up until now, I have tried my best to introduce you to

  • basic terminologies/jargons associated with llm based agentic harnesses. I
  • how communication with an llm works and how we convert that llm into an agent
  • how we can run the agent in a loop to answer it the thing we want
  • how we can do a clear split on responsibilities of harnesses (clients) and inference (servers)

TL;DR: I’ve started a series of posts where I write an agentic harness from scratch and take you through the journey. I’ll tell you what challenges I faced and what things I tried in an attempt to solve those challenges.

In the series, we’ve covered

  • First post : Introduction to basic concepts that will be required for this series
  • Second post : Writing a basic harness and watching the agent work, studying the behavior
  • Third post : Get some tools in. Introducing problems and a goal to the agent and watching it use the tools to achieve the goal
  • Last post : Interacting with a remote inference. The original tentative idea was different.
  • This post : Writing tools for a specific task/workflow and watching agent work on it in the loop

This is supposed to be the very last post of this series, but I doubt the thrill will be over here. I’m expecting by the end of this post, I will have given you almost everything I learnt about writing harnesses and agentic workflows without any third party dependency… After this, if the post series continues, it will be mostly uncharted territory for me, and we both will be in experimentation mode.

I’m so glad that I’m able to reach the end of series because in the past, it has been very hard for me to follow a post series to the end. Something kept me going and I hope I have this level of enthisiasm always about writing and teaching.

Part 1 : The Plan

Agents Eat PEAS!

So, co-incidentally, I’ve just brushed up some theory for AI. At the time of writing this, there’s also another post in the brewings. It’ll be my Lecture Notes on Artifical Intelligence. I’m taking a class on Artificial Intelligence this fall semester, and at it’s showing it’s use here.

To design an agent we need it’s PEAS :

  • P erformance metric : Something to measure how good the agent is doing
  • E nvironment : A set of state variables, a transition function that defines viable actions
  • A ctuators : Actuators define what actions an agent can take and how it will take the action
  • S ensors : Sensors are what agent can perceive about the environment.

You know what yo mamma says! Always eat them greens. It’s good for your health. Same thing here.

An agent needs it’s PEAS, and it also needs a decision making model. Here we already have one! The LLM. We are making the LLM think and take actions. It’s actuators are the tool calls it will make (we’ve already covered this).

This post will be mostly about writing an environment, and sensors. I will use the word oracles over sensors throughout this article and series. Performance metrics will be for us and not for the agent to view so we won’t really consider that in the agent design.

Problem Definition

First get these facts :

  • Fuzzers are dumb but effective way to find bugs.
  • Fuzzers need a program to fuzz.
  • A library is not a program.

Therefore, Fuzzers can’t fuzz libraries directly.

Libraries still do get fuzzed however. There are user written programs (nowadays LLM written ones as well), that use these libraries and then fuzzer can fuzz these programs. How can we generate these programs agentically with the objective of maximizing coverage and the goal of complete coverage?

Well, I’ve seen gemma4 write quite good code, what if we give it the PEAS and ask it to write these programs using the libraries we wanna target and see if we can find some bugs in hiding?

Tip

If you’re not familiar with the basic jargons of fuzzing, I recommend reading this post by Trail of Bits as a good starting point. There’s also the fuzzingbook if you’re feeling a bit hungry today.

Talking about fuzzing is out-of-scope for this article, and maybe I can go in depth about it in a separate series of articles.

Workflow

So, here’s my idea

  • Take a library
  • Get list of functions that are callable by any program that links to it (functions installed in headers, published functions)
  • We ask the agent to write a program using the function, along with the inputs for it
  • We run the program on those inputs, get coverage
  • Then we do some magic and ask the agent to improve the results

I do not expect a single program to cover all of the library at once, so I intend to ask the agent to write multiple programs. Each program is run exactly once on the inputs the agent wrote for it, and the overall coverage of the library is just the union of coverage over all programs.

Many things can go wrong here, because there are many moving parts. First order of business is figuring out the interaction and a high level workflow.

Info

Because programs getting fuzzed are also called harnesses and we are also writing an AI harness here, in order to prevent collision of names, and prevent confusion, I will refer to the programs written by agents as probes.

So, an agent will write a probe that uses the library, along with inputs for it. A probe is a pair : probe.c and an inputs/ folder with files the probe reads. The harness will run the probe on its inputs, collect coverage, and decide how to drive the agent so we get more coverage.

Note

Later : There’s no inputs/ folder in the end. A probe defines int probe(void) and reads all its values from one input, and the fuzzers make the inputs. See The Prompts, Word For Word.

I refer to this whole process of agentic fuzzing as buzzing. No reason! Just is shorter than agentic fuzzing. Here the agent itself plays the role of the fuzzer, by writing the inputs.

There have been research in this direction, papers trying to achieve more coverage using agents. One that I recently read is called ConcoLLMic which is basically an agentic version of concolic fuzzing

Buzzing Target

I’ve decided to pick RizinOrg’s Rizin for buzzing. It’s a big and complex project with many moving parts. It’s also present as librz and programs can link with it and use some amazing rizin features.

Rizin is a reverse engineering framework, born as a fork of the radare2, with a focus on usability, features and cleanliness.
Rizin is portable and it can be used to analyze binaries, disassemble code, debug programs, as a forensic tool, as a scriptable command-line hexadecimal editor able to open disk files, and much more!

I’m picking it up because I already have some familiarity with this target.

Environment Setup

The very first thing we want to make sure is we run all the probes, and any command inside a sandboxed or containerized environment.

Info

When I was trying Qwen 3.8, I didn’t realize the containizer I launched for the agent was root by default. It was buzzing a target that wouldn’t run if it’s running inside root. The agent figured out on it’s own that it must create a less privileged user and then fork the program and run the program with that new user. It did all this in the probe itself.

At that point I realized I need to take the containerization more seriously!

I am not spending too much thought into whether I should sandbox this properly or not because that’s not the scope of this article. That’s for you to explore and figure out.

Sidecar

The harness has to know how to work with a target : how to get it and how to build it. That is different for every target, so I keep it out of the harness. Each target gets a sidecar file that describes its buzzing environment. It’s TOML, because python can read it with tomllib from the standard library.

To keep it simple, the harness and the sidecar just agree on a fixed layout inside the container :

/home/assistant/           home of the user the agent runs as, not root this time
    target/                $TARGET_DIR
        src/               target source, fetched from the sidecar's fetch_url
        build/             build files, written by the sidecar's build command
    install/               $INSTALL_DIR, the target gets installed here

The harness turns the sidecar into a docker image. The source is fetched, built and installed while the image is being built, so every container starts with a target that’s ready to use. Docker caches the image, so all of this only happens again when the sidecar changes. The paths are exported as environment variables ($TARGET_DIR, $INSTALL_DIR), so I don’t have to fill in any templates in the sidecar. It’s all just plain shell commands, which is nice because when something breaks (and it will), I can just copy the command and run it by hand to see what went wrong.

Every header installed into $INSTALL_DIR/include is considered public, and every function declared in them is a published function. Once probes come in, the target will be built twice, a coverage build and a trace build, and the sidecar will grow with it.

Note

Later : The final harness builds the target three times : a fuzz build, a trace build and a coverage build. See The Whole Thing.

This is the sidecar for rizin :

[desc]
name="rizin"
method="git" # git or wget only
fetch_url="https://github.com/rizinorg/rizin"

[build]
# build assumes that it's already in $TARGET_DIR/src when this command is being executed
# build command is supposed to write build files at $TARGET_DIR/build and install at $INSTALL_DIR
cmd="meson setup $TARGET_DIR/build --prefix=$INSTALL_DIR && meson compile -C $TARGET_DIR/build && meson install -C $TARGET_DIR/build"

[desc] says what the target is called and where to fetch it from, with git or wget. [build] runs once, inside src/, while the image is being built. I chain the steps with && so that if any step fails, the whole thing stops right there, and the error I get back is from the step that actually broke instead of something three steps later.

First Run

With the sidecar in place, the harness builds the rizin image, starts a container from it, and gives the agent a single tool : list_files, which lists files inside the source directory. I asked it to look at the top level of the source tree and tell me what the project is. Here’s the whole session, from the image build to the agent’s answer. The build is fast forwarded, everything after it plays at the pace it actually happened.

If you’d rather read it line by line, here’s the same session as plain text.

Homelander saying it was perfect
It was perfect (source : tenor)

Execution Feedback

An agent can have many oracles, but if I had to pick one that matters the most, it’s this one : the oracle that tells the agent what actually happened when its probe ran.

You can’t just tell the agent “increase coverage” and expect it to work. Coverage is the objective, and 100% coverage is the goal, but neither of these is something the agent can directly act on. It can’t see what’s blocking it, and a small llm like ours will just keep guessing forever. So the harness has to do most of the heavy lifting here.

Every time the agent works on something, the harness picks a branch somewhere in the library that it wants the agent to reach. I’ll call that the target branch (more on how the harness picks these later). So the question I want this oracle to answer is : the probe called the published function, but the target branch never executed. Where exactly did execution go the wrong way, and why?

Note

Later : The final harness doesn’t give the agent one target branch. It shows the agent the frontier, and the fuzzers do most of the flipping. The report below still exists, in trace_input. See The Prompts, Word For Word.

Say the target branch d sits inside C, and the path to it is A -> B -> C -> d, where A is the published function. I want the agent to see only the calls along that path, and not everything they call in turn :

flowchart LR
    A["A (published)"] --> a1["a1"]
    A --> a2["a2"]
    A ==> B
    B --> b1["b1"]
    B --> b2["b2"]
    B ==> C
    C --> c1["c1"]
    C -.->|"reached? if not, why?"| d(("d"))
    classDef collapsed stroke-dasharray: 4 4
    class a1,a2,b1,b2,c1 collapsed

Dashed boxes are shown as a single line, never expanded. And if d wasn’t reached : was it an early return? Was d sitting inside another branch that went the other way?

ConcoLLMic instruments source code to log what parts of the code were reached. We can do the same thing, with a compiler pass.

The Pieces

Tip

If you haven’t worked with compilers before : LLVM turns your C code into an intermediate representation (IR) before turning it into machine code, and a pass is a plugin that reads or changes that IR. A basic block is a run of instructions with no jumps in the middle, and the CFG (control flow graph) is how those blocks connect. The LLVM docs on writing a pass are a good place to start.
flowchart TB
    subgraph build ["once per library build"]
        src["library source"] --> pass["buzz-pass"]
        pass --> lib["instrumented library"]
        pass --> idx[("index")]
    end
    probe["probe.c + inputs/"] --> run["run probe"]
    lib --> run
    rt["libbuzzrt"] --> run
    run --> trace[("trace")]
    idx --> an["buzz-analyze"]
    trace --> an
    tgt["target branch"] --> an
    an --> rep["report"] --> agent["agent"]
    agent -->|"new probe / inputs"| probe
  • buzz-pass : an LLVM pass that instruments the library and writes the index, both from the same IR. This way every event in the trace is a basic block ID that the index knows about exactly, and I don’t have to go around guessing which event belongs to which line number.
  • libbuzzrt : a small C runtime the instrumented library calls into. It records the trace.
  • buzz-analyze : a python script that takes the index, the trace and the target, and turns them into plain english the agent can read.

The Index

One JSON file per source file, merged into one for the whole library (calls across files are resolved by name). Basically, it has all the information about the code that stays the same no matter what input the probe gives :

  • functions, with entry and return basic blocks
  • basic blocks, with source locations and successors (the CFG)
  • branches, with comparison predicate and source location
  • call sites, with direct callee, or the function type for indirect calls
  • loops, and struct layouts from debug info (field names, offsets, sizes)

Probes are not instrumented, so the index doesn’t change when the agent writes a new probe.

Info

Clang will load the pass with -fpass-plugin=buzz-pass.so, passed to the trace build through the sidecar. It works at -O0 the same way sanitizers do.

-O0 because inlining and branch merging at higher optimization levels make the mapping from trace to source unreliable.

The Trace

The pass inserts calls into libbuzzrt at :

  • every basic block entry
  • every call, so indirect calls record their actual target
  • every return, with the return value (and after calls into libc and friends too)
  • every conditional branch, with the values being compared
  • every function entry, with argument values

Arguments are read through debug info, so they come out with their source names. Structs are copied one level deep and decoded into named fields later. Probes pass garbage pointers all the time, and reading one directly would crash the tracer along with the probe. So memory is read with process_vm_readv on our own pid instead. It’s a syscall, so a bad pointer just makes it return an error, and the tracer prints <unreadable> and keeps going. The trace is flushed on every way a process can die, so even a crashing run leaves one behind.

The Report

buzz-analyze turns the index and the trace into plain english text using fixed templates. No llm is involved in generating this feedback. Everything in it comes straight from the compiler and from what actually happened when the probe ran. So for the agent, this report is god’s gospel. It doesn’t have to question it, double check it, or reason about whether it’s right. It only has to decide what to do about it. This is what I envision the final output to look like :

rz_bin_open_buf(bin=0x5020, buf=<RzBuffer size=512>, opt={.pluginname=NULL, .sz=512})
  └─ load_buffer(...)
       └─ rz_bin_elf_get_sections(bin={.ehdr.e_shnum=3, .ehdr.e_shoff=0x1c0, ...})
            ├─ init_shdr(bin) -> 1
            └─ STOPPED at elf.c:412: `bin->ehdr.e_shnum == 0` was false (e_shnum = 3)

This way the agent can see the values it passed into the API call, and how those values flowed all the way down to the condition that failed. With this, it can figure out whether it needs to change the probe or change the input.

Marking The Way

Here’s the idea. Before even looking at a trace, we mark all the code that could still lead to the target. Then we follow the trace, and the first time execution steps out of the marked code, we know that’s where things went wrong.

int A(buf) {             // published function
  a1();
  if (!hdr_ok(buf))
    return -1;
  B(buf);
}
int B(buf) {
  if (buf->kind == ELF)
    C(buf);
  b1();
}
int C(buf) {
  if (buf->e_shnum == 0)
    parse_phdrs(buf);    // target
}

There are two kinds of marks. fn_reach says which functions are worth looking inside :

flowchart LR
    A ==> B ==> C ==> T(("target"))
    A --> a1["a1"]
    A --> hdr_ok["hdr_ok"]
    B --> b1["b1"]
    classDef marked stroke-width: 3px
    classDef unmarked stroke-dasharray: 4 4
    class A,B,C marked
    class a1,hdr_ok,b1 unmarked

reach says which blocks inside a marked function still have a way forward to the target. Inside A :

flowchart LR
    e["a1()"] --> i{"!hdr_ok(buf)"}
    i -->|true| r["return -1"]
    i -->|false| b["B(buf)"]
    classDef marked stroke-width: 3px
    classDef unmarked stroke-dasharray: 4 4
    class e,i,b marked
    class r unmarked

buzz-analyze computes both from the index. A block is marked if it contains the target, calls a marked function, or can reach such a block through the CFG. A function is marked if its entry block is. The two depend on each other, so it repeats until nothing changes. Indirect calls may go to any address-taken function of matching type, plus any target already seen in traces. That matters for rizin, where everything goes through plugin function pointers.

Following The Trace

The marks are used in three places :

  1. Before running : only marked functions are traced in full. Everything else is recorded as just a call.
  2. At every call : marked callee, go inside. Otherwise, one line : called a1().
  3. At every step : the first step from a marked block to an unmarked one is the divergence.

If the trace inside A is :

flowchart LR
    e["a1()"] -->|"step 1"| i{"!hdr_ok(buf)"}
    i -->|"step 2: left the marked code"| r["return -1"]
    i -.- b["B(buf)"]
    linkStyle 1 stroke: #e5484d, stroke-width: 3px

the report says "A returned early because hdr_ok() returned 0". If instead it goes all the way into C and skips the target there, the report says “Reached C through A -> B -> C. buf->e_shnum == 0 was false, e_shnum was 3”.

The divergence is classified straight from the index : early return, loop exit (with iteration count), branch going the other way (with compared values), switch picking another case, indirect call going to the wrong function, or the process dying first.

Multiple Paths

Nothing here assumes a single path :

flowchart LR
    A ==> B ==> C ==> d(("d"))
    A ==> E ==> C
    A ==> C

The marks ask “is there any way forward?”, not “is this the right path?”. So B, E and C are all marked, and taking any of them is not a mistake. Returning from a failed call isn’t a divergence either, as long as the caller still has another marked call ahead. Each failed call is recorded as an attempt :

Attempt 1: A -> B -> C   diverged in C at line 12 (e_shnum = 3, needs 0)
Attempt 2: A -> C        diverged in C at line 12 (e_shnum = 3, needs 0)

Both failing at the same condition with the same value tells the agent the path doesn’t matter, the input does.

Part 2 : The First Build

Building It

Most of the design above held up when I actually built it, but not all of it. Here’s what changed along the way.

What Changed From The Plan

  • The sidecar is now a job file. A job names the environment it runs in (here buzzer, the environment that knows about probes), a prepare command that runs once while the image is built, and a build_probe template the environment fills in for every probe. The environment takes care of all the generic stuff (the container, the tools, the oracle), and the job only has to know about rizin.
  • The index is now a SQLite database. One JSON file per source file still comes out of the pass, but they all get merged into SQLite. For rizin that’s 43,443 functions, 251,866 branches and 573,051 edges. An edge is just one way a branch can go : an if has two (true and false), a switch has one per case. Fuzzers usually measure coverage in edges, so I’ll do the same. And I really didn’t want to load all that into memory every time I wanted to ask “who calls this?”.
  • buzz-analyze now lives inside the harness. Marks, divergence and the report all live in the same python file as the agent loop. It still uses templates, and there’s still no llm involved in the feedback.
  • The trace is now a memory mapped file, with fixed size 32 byte events (kind, successor, thread, id and two values). The nice thing about this is that whatever was written before a crash is already on disk, so I don’t have to worry about flushing anything. Branches get recorded everywhere, and that’s how we get coverage. Blocks, calls and compared values are recorded only inside marked functions, which the harness hands to the runtime as a sorted file of function ids.
  • There’s no inputs/ folder yet. Probes are plain C programs for now. Every probe has to finish within 10 seconds.
  • The target is now pinned to one commit. Before, the job cloned rizin’s master branch, so every rebuild silently picked up whatever rizin merged that day, and coverage measured on one commit was compared with probes run on another. Now it fetches one exact commit, and if I want to move to a newer one, I just change that one line.
environment = "buzzer"

prepare = """
git init -q $TARGET_DIR/src && \
cd $TARGET_DIR/src && \
git fetch -q --depth 1 https://github.com/rizinorg/rizin d78334182c2a69b4af798d8925d927396536d3a7 && \
git checkout -q FETCH_HEAD && \
CC=clang meson setup $TARGET_DIR/build --prefix=$INSTALL_DIR --libdir=lib --buildtype=debug \
    -Dc_args=-fpass-plugin=$BUZZ_PASS -Dc_link_args=-lbuzzrt && \
BUZZ_INDEX=$INDEX_DIR meson compile -C $TARGET_DIR/build && \
meson install -C $TARGET_DIR/build
"""

build_probe = '''
cd {probe_dir} && \
export PKG_CONFIG_PATH=$INSTALL_DIR/lib/pkgconfig && \
clang -O0 -g probe.c -o probe -I$INSTALL_DIR/include \
    $(pkg-config --cflags --libs $(ls $PKG_CONFIG_PATH | sed 's/[.]pc$//')) \
    -Wl,-rpath,$INSTALL_DIR/lib
'''

The Report, For Real

This is a real report, from a dry run. The task was to make ht_pp_update_key take the branch where the old key isn’t in the table. Here’s the function, so you can follow along. Rizin writes it once as a template, Ht_(update_key) in librz/util/ht/ht_inc.c, and every hash table type gets its own copy of it, ht_pp_update_key being one of them. The branch we want is the return false; inside the first if, the one on line 823 that the report below talks about :

RZ_API bool Ht_(update_key)(RZ_NONNULL HtName_(Ht) *ht, const KEY_TYPE old_key, const KEY_TYPE new_key) {
	rz_return_val_if_fail(ht, false);
	INDEX_TYPE idx;
	ut32 old_key_size = calcsize_key(ht, old_key);

	// First look for the value associated with old_key
	if ((idx = ctrl_table_lookup(ht, old_key, old_key_size)) == INVALID_INDEX) {
		return false;
	}

	// Associate the new key with the existing value
	if (insert_update(ht, new_key, HT_SLOT_AT(ht, idx)->value, false, NULL) <= 0) {
		return false;
	}

	// Second lookup of the element associated with `old_key`, since the previous index could be invalidated by a resize
	if ((idx = ctrl_table_lookup(ht, old_key, old_key_size)) == INVALID_INDEX) {
		return false;
	}

	// Do not free the value part if dupvalue is not set, because the old value will be
	// associated with the new key and it should not be freed
	if (!ht->opt.dupvalue) {
		HT_SLOT_AT(ht, idx)->value = HT_NULL_VALUE;
#ifdef VARIABLE_VALUE_LEN
		HT_SLOT_AT(ht, idx)->value_len = 0;
#endif
	}

	return internal_ht_delete(ht, idx);
}

And this is the report the harness gave back after the agent’s probe ran :

It called `ht_pp_update_key` 1 time.

call 1 :
ht_pp_update_key(ht={.capacity=16, .capacity_mask=15, .size=1, .growth_left=13, ...}, old_key=0x654ec2879021, new_key=0x654ec2879029)
├─ calcsize_key(ht=0x654ee804b2c0, k=0x654ec2879021) -> 0
├─ ctrl_table_lookup(ht=0x654ee804b2c0, key=0x654ec2879021, key_len=0) -> 15
└─ STOPPED at librz/util/ht/ht_inc.c:823: `if ((idx = ctrl_table_lookup(ht, old_key, old_key_size)) == INVALID_INDEX) {` : 15 == -1 was false

The table had one entry, the lookup found the key at slot 15, and that’s why it never got to return false. If you look at the report, the fix is right there : pass a key that isn’t in the table. This is pretty much exactly what I wanted the report to look like!

Driving The Agent

Note

Later : In the final harness, there are no tasks. The agent picks its own work with the coverage tools. See Where It Went From Here.

The agent doesn’t get to pick what it works on, the harness decides that for it. There are two kinds of tasks the harness hands out :

  1. Priming : every published function gets called at least once. Rizin has 5,187 of them. A priming task is done the moment the latest probe calls the function.
  2. Deepening : for every branch a published function reached, every edge of it that no probe has taken yet becomes a task, and the agent gets the report from above as feedback.

At first, deepening was supposed to start once everything was primed. At the speed the agent primes, that was a week away. Now the two go on side by side, the next task is either one, picked at random.

Only the latest probe counts. So if the agent wrote a good probe 10 turns ago and broke it since then, it’s not done yet. There’s also no limit on turns or failed builds, because this is meant to be a long horizon harness, and fuzzers are expected to run for days anyway. A task is given up on in two cases : the agent stops working on it 5 times, or 5 probes ran without getting it done. No priming task that got done ever needed more than 3 probes. The one task the agent never finished had it writing 35 probes over 2.5 hours, and it started looping in its thinking after its 5th.

Everything that matters survives a restart : the probes, coverage, which functions were primed, how many tasks are done. When the target changes, every saved probe is run again to measure coverage on the new build. The agent’s context, on the other hand, doesn’t survive anything. Every task starts from a clean context, and if the context fills up in the middle of a task, I clear it and send the task again. Everything still gets saved in the transcript, so I can go back and see what happened, but the agent itself doesn’t remember any of it.

Note

Later : The final harness trims and compacts the context, and clears it only as a last resort. See … And A Whole Lotta Context Management.

I also locked down the container this time : no network, no capabilities, a quarter of the machine’s memory and CPU, and a limit on processes so a fork bomb in a probe takes down only itself. The agent runs as an unprivileged user, so no more creating users of its own like Qwen did last time!

Tools

Note

Later : The final harness has 15 tools. See The Tools, At The End.

These are the tools the agent ended up with in the first build :

  • find_file : files whose path matches a pattern, or a directory listing
  • search_text : grep
  • find_function : functions and macros by name, where each is defined, and whether a probe can call it
  • find_type : a type’s definition, public or private. Or the published functions that take it, return it, or whose prototype matches a pattern
  • find_calls : who calls a function, or what it calls
  • view_source : a function or macro by name, or a file from a line
  • write_probe : compile a probe, run it once, report

Tool Output Is The Prompt

If there’s one thing you take away from this post, let it be this one. Everything a tool sends back goes straight into the agent’s context. A small model won’t just skip over a confusing line the way you or I would, it’ll take it seriously, try to make sense of it, and then act on it. Pretty much every problem I had with the agent, I could trace back to something it read in a tool’s output.

  • Early on, it kept saying “I don’t know what the working directory is”. Now every tool description says what relative paths are relative to, and a wrong path says how it was resolved.
  • Errors used to mention JSON. But the model never writes JSON, the server is the one turning its calls into JSON, so the agent was basically seeing the internals of my system leak through. Errors now talk about the agent’s mistake, in plain english.
  • Search results got huge, one grep was 8,000 tokens. So I showed 10 at a time with a page argument. But the agent never used it, not even once in 35 searches. It just kept repeating the same search instead, 17 times in a row for stack_addr =, getting the same 1 of 10 lines every time. It even wrote “Let’s check page 2.” in its thinking, and then made the same call again without page. What fixed it was ranking results by how close they are to the task, with a page holding whole groups of equally close results, up to 50, and no page argument anymore. Now calling the same tool again the same way just shows the next ones. Turns out that’s what the agent was trying to do the whole time.
  • rz_io_bind_init and rz_analysis_value_free are macros. The index only knows compiled functions, so find_function said they don’t exist, and the agent kept hunting for them, search after search. Now every compiled file is run through just the preprocessor again with its own flags (-E stops after preprocessing, and -dD keeps every #define in the output), and every macro the build actually used goes into the index. That’s 24,239 of them for rizin.
  • RzAnalysis is a typedef of struct rz_analysis_t, which is only defined in a private header. The installed headers can’t tell you that, debug info can. The pass now records every named type in every file.
  • rz_pvector_len is static inline in a header, so every file including the header has its own copy. find_function showed 192 identical lines saying it’s “static, only callable from inside its own file”, which is also wrong, a probe can call it by including the header. Now a definition shows once, and says how to use it.
  • A probe that crashed lost everything it printed, the output was still sitting in a buffer. The agent then made the output up, quoted lines its probe never printed, and concluded “then it did reach that line!”. Probes now run with unbuffered output.

Handing It What It Needs

Since every task starts from nothing, the prompt has to carry everything the agent needs. So I mined the transcript for how the agent actually used its tools.

  • It almost always makes just one tool call per turn (1,498 out of 1,502 turns), which means every single lookup costs a whole model turn.
  • On a new task, it mostly opens the same way : read the function’s source, look up the types in its prototype, then write the probe. 152 of its 225 type lookups were for a type in the task function’s own prototype.
  • The function’s source is small. Half of them are 12 lines or fewer.

The harness knows all of that before the task starts. So a priming task now comes with the function’s whole source, and a line for every type of the library in its prototype : what it is, whether it’s private, and the published functions that return one. That last part fixed the worst task of the whole run, where the agent spent 3.7 hours and 28 calls looking for a way to get an RzAnalysisBlock. Now the prompt says rz_analysis_create_block(RzAnalysis *analysis, uint64_t addr, uint64_t size) returns one.

A deepening task gets all of that too, plus the source of the function the branch is in, and a probe to start from. The harness remembers which probe first reached every branch, so the prompt can say : this probe already gets to the branch, base yours on it and get further.

Inference Troubles

Honestly, this is where most of my time went, and none of it had anything to do with the agent itself.

I started with vllm-mlx on a Mac, serving gemma-4-26B-A4B. The first problem : the agent got stuck writing [Calling tool: ...] as plain text, again and again. The server’s Gemma 4 tool parser was missing a flag saying it supports the model’s native tool call format. So earlier tool calls were turned into text when the history was sent back. So the model saw plain text where its tool calls used to be, and just copied that text. Adding one flag fixed it.

The second problem : every turn got slower. Normally, the server keeps a prefix cache : the part of the prompt it already processed last turn is saved, so it only has to read the new part. But this cache never stored a single entry, so every turn the whole prompt was read again from scratch. 29 seconds before the first token at 6,400 tokens of context, and growing. Gemma 4 uses sliding window attention in most of its layers, which means those layers only keep the last few thousand tokens around and throw away the older ones. The server’s cache could only save a prompt by rewinding it after the response, and you can’t rewind something that’s already thrown away its old tokens, so the server just skipped saving it, without telling anyone.

I moved to LM Studio’s headless server, still on MLX. Its cache handles sliding windows : on the second turn, 15,872 of 16,124 tokens came from the cache, and the first token came after 3.6 seconds. Two more surprises :

  • Thinking was off. Gemma 4 needs a flag in its chat template, and LM Studio only sets it for models it ships itself. A small model.yaml fixed that.
  • I loaded the model with 80,000 tokens of context. LM Studio gave it 22,016 without saying anything, because it estimated that’s what fits in memory. Prompts longer than that got their middle cut out, silently. Turns went to 60 seconds, and the agent lost most of its recent history without anyone noticing. A newer runtime respects the size you ask for, and 48k fits fine.

What I learnt from all this is that the harness can’t trust the server. It sets the context size itself, and leaves explicit room for tool results and the response, so nothing gets cut. If the server throws an error, we lose one turn, not the whole run. And if a response hits the output limit, the harness now tells the agent what actually happened : “Your last response reached its length limit while you were still thinking, before you called any tool”. Before, it got told “No probe has run for this task yet”, which it read as “you already wrote one”.

Watching It Work

Here are two tasks from the run, at the speed they actually happened. The first one reads the source and writes a probe :

The second one looks up a type before writing its probe :

Most priming tasks look like this. Over about a day of running :

  • 406 priming tasks done, none given up
  • 445 probes
  • 5,718 of 573,051 edges taken, that’s 1% of all of rizin
  • speed stayed flat at 13 to 14 tokens a second, whether the context had 2,000 tokens or 16,000

Deepening

And then deepening started. This is the second deepening task the agent ever got, at the speed it happened. The target is the return 0; at the top of buffer_putalign, from librz/util/sdb/src/buffer.c :

int buffer_putalign(buffer *s, const char *buf, ut32 len) {
	ut32 n;
	if (!s || !s->x || !buf) {
		return 0;
	}
	...

Here’s the first probe it wrote. It sets up a 10 byte buffer and then passes NULL as buf :

int main() {
    buffer buf;
    char mem[10];
    BufferOp op = test_op;
    int fd = 1;
    unsigned int len = 10;

    buffer_init(&buf, op, fd, mem, len);

    // 1. Put 5 bytes in buffer
    // To reach line 75, we pass NULL as the second argument.
    buffer_putalign(&buf, NULL, 5);

    return 0;
}

and the report came back with :

buffer_putalign(s={.x=0x7ffdcb1fb1be, .p=0, .n=10, .fd=1, .op=0x604f27a17160}, buf=NULL, len=5)
└─ STOPPED at librz/util/sdb/src/buffer.c:74: `if (!s || !s->x || !buf) {` : 0x7ffdcb1fb1be != 0x0 was true (s->x = 0x7ffdcb1fb1be)

Now, !s || !s->x || !buf looks like one branch, but after compiling it’s actually three. || stops checking as soon as one condition is true, so the compiler puts a separate jump after each condition, all three on line 74. This task was for the middle one, !s->x. Its thinking was confused by the wording, “maybe it means the execution reached line 74 and then… what?”, and it spent a while second guessing the report. But the value was right there : s->x = 0x7ffdcb1fb1be, and the report was right. The answer was to believe it. So the next probe passed NULL as the memory to buffer_init, which makes s->x NULL :

    // Initialize with NULL buffer to make s->x == NULL
    buffer_init(&buf, op, fd, NULL, len);

    // 1. Put 5 bytes in buffer
    buffer_putalign(&buf, "ABCDE", 5);

and this time :

buffer_putalign(s={.x=NULL, .p=0, .n=10, .fd=1, .op=0x648ca7080160}, buf="ABCDE", len=5)
└─ REACHED the target

And that’s the whole idea of this post, working on a real target! In the first two hours, the agent reached 3 of the 6 deepening targets it got, in 1 or 2 probes each. Two it gave up on, both inside cdb_findnext. I think that’s pretty good for a model that only uses 4 billion parameters per token.

And then there are the tasks that don’t go well.

  • Every few hours, the agent gets stuck in a loop where it drafts its probe in its thinking, doubts it, and drafts it again. 20,000 characters later it hits the output limit. In one of them it wrote 10 tool calls as code blocks inside its thinking, and called none of them.

  • Sometimes it overthinks. rz_analysis_esil_get_instruction_trace took 2.5 hours. The agent decided it needed a fully working trace, which needs a working IO layer, which crashed probe after probe. But if you look at the function, it returns right at the top for any negative index :

    	if (idx < 0 || idx >= rz_pvector_len(etrace->instructions)) {
    		return NULL;
    	}
    

    So all it had to do was pass a zeroed trace and -1, and it would’ve been done in one probe. I’m keeping that probe though, because probes that use the API properly will be more useful later on.

  • Right after a context clear, it forgets rz_analysis_new exists. That’s the function that creates the RzAnalysis object pretty much every analysis function needs, so without it the agent goes back to searching from scratch. That’s part of why every task starts with everything it needs in the prompt, and later, a big part of why I started caring about context management.

I didn’t find these by looking at numbers. I had four agents read the transcript of the run, word by word, each looking for a list of behaviours I was suspicious of. That’s how I found most of the tool output problems above.

Looking back at all this, there’s only so much the harness can do. It can hand the agent the source, the types, a probe to start from, and a report that points at the exact condition that failed. But it can’t do the reasoning for the agent. All the failures above (the thinking loops, the overthinking, the amnesia) basically come down to the model not reasoning well about code that’s right in front of it. So if you give it the code and the right tools, the most useful agent for this harness is the one that can actually reason about the library’s code and write a good probe that uses it. The harness can make up for a lot of things, but not for that.

Part 3 : The Final Harness

Where It Went From Here

This was supposed to be the last post of the series, and it’s the last one where I knew where I was going. The harness kept going after the post stopped though, and a few things changed that are worth mentioning :

  • Probes don’t have a main anymore. A probe defines int probe(void) and reads its values from the input, through the functions in probe_input.h. This means a fuzzer (afl-fuzz) can keep running the probe with new inputs long after the agent wrote it. That’s the inputs/ idea from the start of this post, just done differently.
  • Crashes get replayed under sanitizers in a fresh throwaway container, and a script sorts them into not a crash, flaky, the probe’s fault and candidate. Only the candidates need someone to read the code.
  • The context management, in the next section.
  • It’s not just rizin anymore. The harness has jobs for a lot more targets now.
  • The harness doesn’t hand out priming and deepening tasks anymore. The agent gets one message at the start, “Write many probes. Each probe that compiles gives the fuzzers new work for many hours. A short probe now gives more coverage than a complete probe later.”, and then picks its own work using the coverage tools below. Every time it stops, it’s told “Continue the work. Write a probe that increases the coverage.”

As the warning at the top says, I won’t be keeping this post up to date with any of that. But since the tools and the workflow changed so much, the rest of this part is about how the final harness works : its context management, the prompts, the tools, and how it all chains together.

… And A Whole Lotta Context Management

In the first build, my context management was basically : when the context fills up, throw all of it away and send the task again. That works, but it also means that every time the context filled up, the agent started from nothing, and every time it got stuck in a loop, the only way out was to wait for the context to fill up. Once I started caring about what’s actually sitting in the context, things got a lot better. The agent started recovering from its thinking loops, it started recovering from bad conclusions it came to earlier, and the whole thing stayed quite continuous, instead of starting over every time the context filled up.

Here’s how it works in the latest version of the harness. The harness keeps track of how full the context is, using the token count the server gives back for the last response, plus an estimate for everything added since. Then it does three different things, at three different levels :

  • At 50% of the context window, it starts trimming.
  • At 85%, it compacts.
  • At 95%, it clears, like before. This is now the last resort, for when the first two didn’t work.

All of this happens between turns, never in the middle of one. In pseudo code, the loop that drives the agent looks roughly like this :

before every turn :
    if the agent made the same calls again and again :
        remove the repeats, trim, compact, tell the agent to do a different thing
    if context >= 50% of the window and it grew by 20% since the last trim :
        trim
    if context >= 85% of the window :
        compact
    if context >= 95% of the window :
        clear, and give the work again

    run one turn

    if the thinking went in circles :
        throw the response away
        quiet = quiet + 1, the next `quiet` turns run without thinking
        call a tool for the agent that shows the state of its work
        if quiet reaches 4 : clear
    if 2 * quiet turns went by without circles :
        quiet = quiet / 2

Trimming

Most of the context is tool results, about three quarters of it. And most of those results the agent read once, a long time ago, and doesn’t need anymore. So when the harness trims, every tool result older than the last 10 turns gets replaced with a single line :

This result is old. The harness removed it to make space. If you still need it, call the tool again.

The call itself stays, so the agent still knows what it did, it just doesn’t have the full result anymore. This is called observation masking, and there’s a paper by JetBrains Research that found it solves as many tasks as having an llm summarize the old turns, at half the cost of keeping everything. Not all results age the same way though. The coverage tools give a different answer every time a probe runs, so only the latest answer of each one stays once it’s a few turns old. The source of a function from view_source stays true, so it stays, unless the same call came again later, or the kept sources take up more than a quarter of the window.

The trim also cleans up a few more things :

  • The thinking from older turns, except for the last 3. The chat template puts all of the old thinking back into the prompt, and the model reads it again every turn.
  • Calls that only repeated an earlier call with the same result. The first one stays, the repeats go.
  • Chains of calls that all failed, once a later call worked. The model copies the wrong names from those failed calls again, so they go away, and only one line stays before the call that worked, like “3 calls failed. The last cause : …”. This way the lesson stays, but the noise goes.
  • Repeated sentences in the agent’s thinking and answers. Only the first time a sentence appears stays. I learnt this one the hard way : a sentence that the model reads again, it writes again. That’s how a lot of the doom loops start.

Every trim changes old messages, so the server has to process the whole history again from there. So the harness only trims when the context grew by 20% of the window since the last trim, and only if the trim frees at least 20% of the window. Otherwise it waits for the compaction. Put together, a trim goes like this :

trim :
    repeat until nothing changes :
        remove the calls that only repeated an earlier call
        remove the chains of failed calls, put a one line lesson before the call that worked
        remove the sentences in thinking and answers that already appeared before
    remove the thinking of every turn except the last 3
    replace with one line :
        the results older than the last 10 turns
        the coverage results older than the last 3 turns, except the latest of each tool
        the view_source results that the same call got again later
        the oldest view_source results, while they take more than 25% of the window
    remove completely the calls whose result was replaced with a line 2 trims ago
    if all this frees less than 20% of the window :
        undo it, and wait for the compaction

Compaction

At 85%, the harness asks the agent to write notes for itself, because all the messages are about to go away. The notes have to be in four parts, and the agent has to fill every part or write “None” :

THE WORK AT THIS TIME : the work that you did last, and your next step.
RESULTS : the procedures that you tried, and the results.
PROCEDURES THAT DID NOT WORK : these procedures, and the cause for each.
FACTS : the important facts about the library. ...

The separate parts are from an evaluation of context compression by Factory. If you just ask for a summary, a whole kind of fact can get lost without anyone noticing. With a part for each kind, the agent has to at least think about each one. And the notes are written in ASD-STE100 Simplified Technical English : short sentences, one fact in each, active voice, easy words. Everything the harness tells the agent is written that way, and the model writes it well enough too.

Then the whole history goes away, and what replaces it is the facts from the harness (the coverage at this time, and the probes the agent wrote) first, and then the agent’s notes. The facts come first on purpose. The notes come from the model’s memory, and that can be wrong. The harness’s facts can’t be.

This is also how the agent gets out of bad conclusions. Before, a wrong conclusion the agent came to early on just sat in the context, and it kept reading it and acting on it, turn after turn. Now, between the trims removing old thinking and repeated sentences, and the compaction keeping only the notes next to the harness’s facts, a wrong conclusion doesn’t get to stick around for long.

One small trick : the compaction request is sent with the exact same history and the same tools as a normal turn, just with the request for notes at the end. That way the server already has all of it in its cache, and doesn’t have to read the whole history again just to write the notes.

compact :
    send the same history and the same tools, plus the request for notes, without thinking
    if the notes are missing, cut off, or in circles :
        the compaction failed, keep the history as it is
    else :
        history = system prompt + facts from the harness + the notes

Doom Loops

There are two kinds of loops, and the harness handles them differently.

The first is thinking in circles. The harness watches the agent’s thinking as it streams in, and if a passage of 600 characters shows up word for word 3 times in one response, it stops the response right there and throws it away. In the transcripts, every response with a repeat like that went all the way to the output limit, and no response that ended normally had one. In place of the thrown away turn, the harness makes a tool call on the agent’s behalf that tells it the state of its work. So the agent gets facts in place of the circles. Then the next turn runs without thinking. If it happens again soon after, the next 2 turns run without thinking, and so on. After enough calm turns, thinking comes back. If it happens 4 times in a short time, the harness gives up on the context and clears it, because at that point the circles are coming from what’s in the context itself. The check itself is simple :

while the response streams in, every 500 characters :
    if any passage of 600 characters appears 3 times, word for word :
        stop the response, it's thinking in circles

The second is calling the same tool again and again, with the same result. The harness removes all the repeats from the history, trims, compacts, and tells the agent :

You made the same calls again and again, and the results did not change.
The harness removed the repeated calls from the messages.
The same call gives the same result again. Do a different thing.

Once the repeats are gone from the context, the model doesn’t have them to copy anymore.

The Prompts, Word For Word

A lot of what changed is easier to see in what the agent actually reads than in anything I can describe. So here are the prompts, word for word. Everything the harness says to the agent is written in ASD-STE100 Simplified Technical English, the same way the compaction notes are.

There’s one exception, and it’s the first line of the system prompt : “You are a helpful assistant.”, with no change. The agent’s wish to help is what gets it to read its values from the input, so the system prompt, and the feedback about reading values, talk to it as me, with “I” and “me”.

This is the whole system prompt for the rizin job, with the paths and numbers filled in. It’s long, so it’s folded :

The system prompt (click to expand)
You are a helpful assistant.

YOUR WORK
I fuzz a C library. I must get more coverage of its code. Your work is to write probes for
the fuzzers.
A probe is a fuzz harness. It is a small C++ program. It calls functions of the library
with values from an input.
The fuzzers make the inputs. They change the inputs many times each second. They keep each
input that reaches a new position in the code. The fuzzers keep these inputs for the
probe.
The harness compiles each probe that you write, links it with the library and gives it to
the fuzzers. The fuzzers then run it for many hours. It is not necessary for you to do
this work.
The values that the probe reads from the input must control the branches of the library
that the probe covers. Probes of this type help me the most. Then the fuzzers can find the
values that get execution far into the code. A constant value has only one value. The
fuzzers cannot change it. But a constant can open a branch that the fuzzers do not find.
Then the fuzzers explore the code after that branch. VALUES TO READ FROM THE INPUT, step
6, tells you how.
You and the fuzzers do this work together. Your probe gets execution into a part of the
library. Then the fuzzers change the values from the input, and they cover more branches
of this part. They flip its frontier conditions for you. The fuzzers cannot get coverage
of code that no probe reaches.

FILES
1. The source code of the library is in /home/assistant/target/src. This is your working
   directory.
2. A path that does not start with / starts from the working directory.
3. Reports give files as full paths, and modules from the source directory, for example
   `lib/util`. You can give both to the tools as they are.
4. The installed headers of the library are in /home/assistant/install/include.
5. The probes and their inputs are in /home/assistant/probes.

THE SHAPE OF A PROBE
A probe contains the function `int probe(void)`. It does not contain a main function. All
probes have this shape. The probe reads its values from the input with the functions that
follow.
  #include <probe_input.h>

  int probe(void) {
      uint32_t count = read_u32();
      char *name = read_string(64);
      ... call the library with these values ...
      free(name);
      return 0;
  }
These functions read a value from the input. The file
/home/assistant/buzz/include/probe_input.h contains them.
  read_u8(), read_u16(), read_u32(), read_u64(), read_bool() : a number.
  read_range(lo, hi) : a number from lo to hi.
  read_bytes(out, n) : n bytes into out.
  read_buffer(&len, most) : a new buffer of a maximum of most bytes. Its length goes into
  len.
  read_string(most) : a new string of a maximum of most symbols, with a NUL at the end.
  read_rest(&len) : all the bytes of the input that the probe did not read. The function
  does not make a copy of these bytes.
  read_file(most) : a new file with a maximum of most bytes from the input. The function
  gives its path.
  read_file_stream(most) : a new file, as read_file makes it. The function gives a FILE
  pointer, open for the read operation. Close it with fclose.
  read_file_fd(most) : a new file, as read_file makes it. The function gives a file
  descriptor, open for the read operation. Close it with close.
  Each call makes a different file from the next bytes of the input. For 10 files, call
  the function 10 times. A probe can make a maximum of 64 files.
The network is a fake network. When the library uses the network, the input gives the
bytes that the network sends to the library. probe_input.h tells how.

INSTRUCTIONS FOR VALUES
1. The values come from the start of the input, in the sequence that the probe reads them.
2. The computer is little endian. The lowest byte of a number comes first. The u32 value 1
   is the bytes 01 00 00 00.
3. After the end of the input, each number is 0, and read_range gives lo. Each buffer and
   each string is empty. Because of this, all of the probe runs on each input, also on an
   empty input.
4. The fuzzers run the probe many times in one process. Release all the memory that the
   probe gets.
5. A probe must stop in less than 10 seconds on all inputs.

VALUES TO READ FROM THE INPUT
Read as many values as possible from the input. A value from the input can have all
possible values.
1. Read numbers, lengths, flags and contents from the input. Also read the values that
   select between options.
2. You can also read a pointer from the input. Read if it is NULL, or which object it
   points to.
3. The fuzzers find most of the special values that the library looks for in its input.
   Read these values from the input first. Do not calculate them. If uncovered_branches
   shows that the fuzzers did not find a special value, write a new probe. In it, write
   this value into the bytes of the input, as step 6 tells. Write only these bytes. Read
   all the other bytes from the input.
4. Use a constant value where 2 values must agree. Example: a buffer and the length that
   you give with it.
5. Do not use the clock time, or values that change from run to run. Read these values
   from the input. On the same input, the probe must do the same operations each time.
6. Sometimes a branch opens only when one bit of a flag is set, when one field of a struct
   has a specific value, or when some bytes of a buffer or a file have specific values.
   The fuzzers do not always find these values. uncovered_branches shows these conditions.
   Then the probe can set this bit, this value or these bytes itself, after it reads them
   from the input. This is correct, and it helps me. Set only the bits, the fields and the
   bytes that open the branch. Read all the others from the input. Example:
     int flags = read_u32() | FLAG_READ;           // this bit is always set, the input
     gives all the other bits
     opt.load_all = true;                          // the parser reads the rest of the
     file only with this value
     uint8_t *buf = read_buffer(&len, 4096);
     if (len >= 4) memcpy(buf, "FMT1", 4);         // these 4 bytes are always set, the
     input gives all the other bytes
   The probe opens the branch. Then the fuzzers explore the code after the branch with the
   values from the input.
   The fuzzers change some bytes of an input at a time. A check that needs many bytes with
   specific values at the same time almost never passes. Then the fuzzers do not get past
   this check. When the probe sets these bytes, each run passes the check. Then the
   fuzzers use all their runs on the code after the check. But the fuzzers cannot change
   the bytes that the probe sets. The code for the other values of these bytes gets no
   coverage from this probe. Because of this, set bytes only for a check that the fuzzers
   did not pass.
   If the code for the other value of the bit is also important, write a second probe, or
   read this bit from the input in that probe.
7. Some checks accept only a small number of correct values. Example: the type of a
   format. Put these values in a list in the probe. Read the index of the value from the
   input. Then write this value into the bytes of the input. The fuzzers then select
   between the correct values, and they change all the other bytes. Example:
     static const uint16_t types[] = { 3, 8, 40, 62 };
     uint16_t type = types[read_range(0, 3)];  // the input selects one of the 4 correct
     values
8. Some parsers read a file only when it contains some structs, and when these structs
   agree with each other. Example: the header gives the number of entries and the position
   of the first entry, and the entries are at this position. The parser stops if these
   parts do not agree. The fuzzers almost never make a file where all these parts agree.
   Do these steps:
   a. In the probe, write these structs into the bytes of the input.
   b. Make sure that the positions and the sizes in the structs are correct for the file.
   c. Read all the other bytes from the input. Also read from the input the values that
      can change, for example the number of entries.
   Example: a file starts with the 4 bytes "FMT1". Bytes 4 to 7 give the number of
   entries. Bytes 8 to 11 give the position of the first entry.
     uint8_t *buf = read_buffer(&len, 4096);
     if (len >= 16) {
         uint32_t count = read_range(1, 8), at = 16;
         memcpy(buf, "FMT1", 4);          // the parser looks for these bytes
         memcpy(buf + 4, &count, 4);      // the number of entries : from the input
         memcpy(buf + 8, &at, 4);         // the position of the entries : it agrees with
         the file
     }
   These bytes are only an example. Read the real format in the source code of the parser.
   If the library reads a file, use read_file. Then open the file again with fopen(path,
   "r+b"), and write the bytes at their positions.
You select which functions the probe calls, and in which sequence. You select how the
probe makes its objects. You select which values come from the input.

HOW TO INCREASE THE COVERAGE
1. A condition is one branch condition in the code of the library that compares 2 values.
   Example: `!s` in `if (!s || !s->x)`. A condition has 2 branches: one for the value
   `true` and one for the value `false`. A switch has one branch for each case.
2. The coverage is the set of branches that the probes covered, on one or more inputs.
3. The frontier is the set of conditions where the probes covered one branch, but not the
   other branch. The fuzzers try to flip these conditions. uncovered_branches shows them.
   First are the conditions with the most uncovered branches after their other value. Each
   call shows conditions from different modules, if possible. For each condition, the tool
   shows the value that the condition always had. It also shows a probe and an input that
   reach the condition.
4. To increase the coverage, do one of these steps :
   a. Select a file of the library that has no coverage. show_coverage shows these files,
      the largest first. uncovered_functions shows the API functions that are defined in a
      file. Write a probe that calls the functions of this file with values from the
      input. Then the fuzzers cover more branches of the file and flip its conditions for
      you. Your one probe gives the start, and the fuzzers do the work after that.
   b. Select an API function that no probe calls. API functions are the functions that the
      installed headers declare. The uncovered_functions tool shows these functions first.
      Write a probe that calls it with values from the input. The fuzzers then do the same
      work on its code.
   c. Select a condition from the frontier. Write a new probe that reaches the condition
      and gives it the other value. Start from the probe that uncovered_branches shows.
      Use view_source to read it. Write its code again in the new probe. Then add or
      change the objects, the flags or the calls that control the value of the condition.
      Read from the input the values that the condition compares.
5. A sequence of calls on the same objects reaches more code than one call. Write a short
   sequence first. Then write the next probe with a different sequence.
6. You cannot change a probe after you write it. To read a probe that you wrote before,
   use view_source. In a new probe, you can write the same code again.
7. You can call all functions of the library. A probe can call one function with all your
   work on it, or it can call many functions. These two types of probe are good.

REPORTS
1. write_probe compiles the probe, then fuzzes it for a short time. The harness runs the
   probe many times, each time on a different input. It uses 8 processes at the same time
   for 15 seconds.
   The report is short. It tells you the number of branches that the probe covered for the
   first time. It tells you the number of new frontier conditions that the probe added. It
   tells you the API functions that the probe called for the first time. For more
   information, use trace_input.
2. After this short time, the fuzzers continue to fuzz the probe for many hours. When they
   find more coverage, write_probe and the messages of the harness tell you.
3. write_probe does not accept a probe that reads no values from the input. But
   write_probe keeps this type of probe if each parameter of each function that the probe
   calls is an object. Another function in the probe must make this object.

TOOLS
1. To find code, use find_file, search_text, find_function, find_type and find_calls. To
   read code, use view_source.
2. uncovered_branches shows the frontier conditions. uncovered_functions shows the API
   functions. First, it shows the functions that no probe calls. Give it a module or a
   file from show_coverage to see the functions that are defined in it.
3. write_probe compiles a probe, fuzzes it for a short time and gives it to the fuzzers.
4. trace_input runs a probe on one of its inputs. It shows which bytes became which value,
   and the tree of the functions that the run entered. Give it from_function to see one
   function of the run as a tree : its conditions with the values that they compared and
   the sides that the run did not enter, and its calls with their arguments and results.
   Call it again with other functions to examine the same run. Give it a condition to see
   only the path to this condition. It does not run new code.
5. change_input_byte makes a new input from an input of a probe. It changes one byte. Then
   it runs the probe on the new input. The fuzzers also use the new input.
   For a library whose inputs start with a setup part (for example the mount options and
   the image of a file system), understand_input shows this part as text. change_input
   takes new text for these sections, runs the probe on the new input, and tells what the
   setup did. The fuzzers also use the new input.
6. show_input_byte shows the bytes of an input of a probe.
7. show_coverage shows the files of the library that have no coverage, the largest first.
   It also shows the coverage of each module : how many of its branches the probes
   covered. Use it to find the code where a new probe gets the most new coverage.
8. The tools that find code show first the results nearest to the first function that your
   last probe called.
9. A tool shows one part of its results. If you make the same call again, it shows the
   next part.

THE FUZZERS AND YOU DO DIFFERENT WORK
1. The fuzzers find the values : numbers, strings, and the contents of files in all file
   formats. They change the bytes of the input many times each second. They can find the
   correct bytes for file formats.
2. Your work is to call the functions of the library in a sequence that works. Make the
   objects. Then call the functions with values and files from the input. The fuzzers
   cannot do this work.
3. For a file, a path or a FILE pointer, use `read_file`, `read_file_stream` or
   `read_file_fd`. Do not try to make the contents of the file correct. An empty or an
   incorrect file is a good start. The fuzzers find the correct bytes.
4. A probe that calls a function for the first time gets more coverage than no probe. One
   call is a good start, also when the objects of the function are not easy to make.
5. The files of the library that have no coverage contain the most code. show_coverage
   shows them. Some steps can be necessary to make an object there. These steps are usual.
   Do these steps.
6. When a probe adds new frontier conditions, the fuzzers try to flip them. Thus the
   frontier increases the coverage without more work from you. Write a different probe
   only for the conditions that must have different objects or calls.
7. Do not stop work on a function only because its objects are not easy to make. First,
   find how the library makes them. Do these steps for each type that the function must
   have :
   a. Find the functions that give an object of the type. Example: for the type `Type *`,
      use search_text with the pattern `Type \*\w+\(` in the headers.
   b. Find the code that calls these functions. Use find_calls, or search_text in the
      tests and the programs of the library. They make many objects.
   c. Read how this code makes the object. Then write the same steps in the probe.
   If the library can make an object, a probe can make it.

WORK
1. Write probes, one after the other.
2. Get a condition from uncovered_branches. Or get the first function from the
   uncovered_functions tool, or a file from show_coverage that has no coverage. Read the
   code of the file, the function or the condition. Then write a probe for it.
3. Each probe that compiles and calls the library is good. The fuzzers make it better.
4. A probe is good also if it does not do all the work.
5. When you know which functions to call and how to make their objects, write the probe.
   Then go to the next condition, function or module.
6. Think in a few sentences. Then make a tool call.
7. When you know one call that gets execution into the code, write the probe. It is not
   necessary to know all of the code first.
8. Make a decision one time. Do not examine the same question again. If a probe gives no
   coverage, write a different probe.
9. If you are not sure, write the probe. Its result tells you more than more reading.

Right after the system prompt, the agent gets its one message to start the work :

Write many probes. Each probe that compiles gives the fuzzers new work for many hours. A
short probe now gives more coverage than a complete probe later.

And every time it stops making tool calls, it gets :

Continue the work. Write a probe that increases the coverage.

When it makes the same call again and gets the same result, the result starts with :

You made this same call before, and the result is the same. The same call gives the same
result again. Do a different thing.

And when it keeps doing that, the harness removes the repeats, compacts, and sends :

You made the same calls again and again, and the results did not change. The harness
removed the repeated calls from the messages. The same call gives the same result again.
Do a different thing.

When a response is lost, the agent gets one of these, depending on what happened :

Your last response stopped before you called a tool. The harness did not keep it.
Continue.

Your last response had no tool call and no answer. The harness did not keep it. Continue.

The harness did not get all of your last response. The harness did not use this response.
Continue.

When a trim removes an old tool result, this line takes its place :

This result is old. The harness removed it to make space. If you still need it, call the
tool again.

At 85% of the context window, the compaction request :

The compaction request (click to expand)
The space for messages is almost full. I will remove the messages from before. Before
this, write notes for yourself. The notes will replace these messages.
Write the notes in ASD-STE100 Simplified Technical English :
- Write short sentences, with a maximum of 20 words.
- Write one fact or one instruction in each sentence.
- Use the active voice. Use easy words.
- Write the names of functions, types, files, probes and inputs as they are, in backticks.
If the messages contain notes that you wrote before, keep all their facts. Add the new
facts to them.
Write these 4 parts. Write each part. If a part has no text, write "None".
THE WORK AT THIS TIME : the work that you did last, and your next step.
RESULTS : the procedures that you tried, and the results.
PROCEDURES THAT DID NOT WORK : these procedures, and the cause for each.
FACTS : the important facts about the library. Write its functions, types and headers, how
to make its objects, and the values that its conditions must have.
Do not write the list of your probes or the coverage. The harness gives them to you. Do
not call tools.

And after the compaction, the message that replaces the whole history. The parts in <...> are filled in by the harness :

The space for messages became full. The harness removed the messages from before. These
are the facts from the harness, and the notes that you wrote.

THE COVERAGE AT THIS TIME
<the branches covered, the frontier, and the API functions that probes call>

YOUR PROBES AFTER THE HARNESS STARTED, AND THE API FUNCTIONS THAT EACH ONE CALLS
<the last 40 probes>

YOUR NOTES
<the notes>

Continue the work.

The Tools, At The End

Remember the Tools section from earlier? That was the design I started with : 7 tools, where the harness picked a task, the agent read the code, wrote a probe, and write_probe ran it exactly once and sent back the report. The design I finished with is quite different, and the tools changed with it :

  • The 6 tools for reading the library stayed, mostly the same.
  • Since the harness doesn’t hand out tasks anymore, the agent needs to find its own work. So it got 3 tools that show what isn’t covered yet.
  • Since probes read their values from an input now, and the fuzzers keep running them, the agent also got tools to look at those inputs, trace a probe on one of them, and change them by hand.
  • And write_probe doesn’t run a probe once anymore. It compiles it, fuzzes it for a short time, and hands it to the fuzzers.

So the agent ends up with 15 tools. They fall into three groups.

Reading the library :

find_file(pattern, path)          files whose path matches a regex, or a directory listing
search_text(pattern, path)        grep over everything the agent can read, definitions first
view_source(function | path+line) one definition at a time : a function by name, the definition
                                  that contains a line, or the list of functions in a file
find_function(pattern)            functions and macros by name, with their file and line
find_type(name, search)           a type's definition, or the API functions that take it,
                                  return it, or have a prototype that matches
find_calls(function, direction)   who calls a function, or what it calls

Seeing what’s not covered yet :

show_coverage(module)             the conditions that lead to the most uncovered branches, the files
                                  with no coverage, and the coverage of each module
uncovered_functions(area)         the API functions no probe calls, then the ones probes rarely call,
                                  each with its prototype, header and the uncovered branches it reaches
uncovered_branches()              5 frontier conditions at a time : conditions that had the same value
                                  on every input so far, with that value, the line for the other value,
                                  and a probe and an input that reach it

Writing probes and working with their inputs :

write_probe(source)
    refuse it if it isn't a probe : `int probe(void)`, reading its values through probe_input.h
    compile it, and refuse it if it doesn't compile, or if it still has a main
    run afl-fuzz on it, in many parallel instances, for a short time
    replay the inputs afl-fuzz kept on the trace build, and merge their coverage
    refuse it if it never read a value from its input
    report the API functions it called and the new coverage, and hand it to the fuzzers

trace_input(probe, input, condition, from_function)
    run the probe once on one input, on the trace build
    report which bytes of the input became which values, and the library calls
    with from_function : zoom into one function of that run
    with condition : the path to one condition, and the values it compared

show_input_byte(path)             the bytes of an input, in hex and as text
change_input_byte(probe, input, position, value)
    change one byte, trace again, report if the condition flipped,
    then let afl-fuzz continue from the new input for a short time
understand_input / change_input   for targets where the start of every input is a setup step (like a
                                  file system image and its mount options) : show it as text, and
                                  change it the same way change_input_byte changes a byte

And this is what a probe looks like now. The values come from the start of the input, in the order the probe reads them, and after the end of the input every number is 0 and every buffer is empty, so a probe runs on any input, even an empty one :

#include <probe_input.h>

int probe(void) {
    uint32_t flags = read_u32();
    size_t len;
    uint8_t *buf = read_buffer(&len, 4096);
    char *name = read_string(64);
    // ... call the library with these values ...
    free(buf);
    free(name);
    return 0;
}

The Whole Thing

Here’s how all of it chains together, in three parts. First, what happens when I start harness.py with a job file. Before the agent sees anything, the job’s image is built, and rizin gets built three times inside it :

flowchart TB
    start["harness.py jobs/rizin.toml"] --> job["job file : prepare, three builds, build_probe"]
    job --> src["prepare : fetch rizin at one pinned commit"]
    src --> fuzzb["fuzz build : afl-fuzz coverage + sanitizers"]
    src --> traceb["trace build : buzz-pass + buzzrt"]
    src --> covb["coverage build : llvm-cov"]
    traceb --> idx[("index.db : functions, branches, types, macros")]
    src --> pub[("published.json : the API functions")]

Then the agent loop starts. The agent gets one message, and from there it’s model, tools, results, again and again, with the context management from earlier sitting between the results and the next turn :

flowchart TB
    prompt["system prompt + 'Write many probes...'"] --> model["model on the inference server"]
    model -->|"tool calls"| tools["the 15 tools"]
    data[("index.db, published.json, coverage")] --> tools
    tools -->|"results"| ctx["context management : trim, compact, clear, thought loop check"]
    ctx --> model
    model -->|"stopped"| cont["'Continue the work. Write a probe that increases the coverage.'"]
    cont --> model

And last, what happens to a probe once the agent calls write_probe. The agent gets a report right away, and the fuzzers keep working on the probe in the background for as long as the harness runs :

flowchart TB
    probec["probe.c : int probe(void), reads values through probe_input.h"] --> compile["compiled three times : probe, probe.trace, probe.cov"]
    compile --> burst["short afl-fuzz run"]
    burst --> replay["replay the kept inputs on probe.trace"]
    replay --> state[("coverage, frontier, probes")]
    state -->|"report"| agent["the agent"]

    compile --> fuzzers["afl-fuzz on every probe, in the background"]
    fuzzers --> newin["new inputs"]
    newin -->|"replay on probe.trace, llvm-cov on probe.cov"| state
    state -.->|"news in the next message"| agent

    fuzzers --> crashes["crashes/"]
    crashes -.->|"run by hand, outside harness.py"| triage["triage_crashes.py : replay under the sanitizers"]
    triage --> verdict["not a crash / flaky / the probe's fault / candidate"]

Did We Find Any Bugs?

Buzzing found lots of crashes. But buzzing is prone to false positives : a probe that misuses the API, by freeing memory rizin owns, reading internal structs wrong, or passing garbage, crashes rizin just as well, and rizin is allowed to crash on those. So, to find out how many of the crashes were true bugs, I had another agent decide for every crash and memory error whether it’s the probe’s fault or rizin’s, and it had to argue it from rizin’s source.

After throwing out all the crashes that were the probe’s fault, I was left with enough real bugs to write 32 patches for rizin : heap out-of-bounds reads and writes, undefined behaviour, divisions by zero, and a few endless loops. Every one reproduces on rizin’s development branch, and almost every one comes with a regression test. I won’t be listing them here until they’re fixed upstream.

Info

Probes crash because they misuse the API a lot more often than because the library is broken, so a crash alone doesn’t tell you much. You need a sanitizer report that says who freed what, and where, and then someone has to read the code.

Resources

AI Disclosure

Parts of this post were written with the help of an AI, with clear instructions and review from me (the author).

If you wanna talk about any of this, or say hi, reach me at hi@brightprogrammer.in, I’ll try my best to reach back.