Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

chore(eval): a cross-session memory eval, and the OptMem evaluation it settled

Rach Pradhandaeb1d4a5a88
diff --git a/scripts/eval/longhorizon/.gitignore b/scripts/eval/longhorizon/.gitignore
new file mode 100644
index 00000000..2eb1fee4
--- /dev/null
+++ b/scripts/eval/longhorizon/.gitignore
@@ -0,0 +1,3 @@
+runs/
+results.json
+__pycache__/
diff --git a/scripts/eval/longhorizon/README.md b/scripts/eval/longhorizon/README.md
new file mode 100644
index 00000000..c1d72d3c
--- /dev/null
+++ b/scripts/eval/longhorizon/README.md
@@ -0,0 +1,70 @@
+# Long-horizon memory eval
+
+Answers one question the other harnesses cannot: **after a session ends, can a
+fresh one recover what the first one learned?**
+
+`scripts/eval/live-ab/` measures token economics within a run and
+`scripts/eval/golden/` proves byte-identity of rendering. Neither crosses a
+session boundary, and neither exercises compaction more than incidentally. This
+one does both by construction.
+
+## Running it
+
+```sh
+export GRAFF_BIN=/path/to/zig-out/bin/graff
+python3 run_longhorizon.py base 1 # 1 run of the base arm
+python3 run_longhorizon.py base 3 # 3 runs
+LH_MEMO_BIN=/path/to/memo python3 run_longhorizon.py base,optmem 1 # comparison arm
+```
+
+Knobs: `LH_STEPS` (12), `LH_COMPACT_PCT` (4), `LH_FILLER` (26 lines/step),
+`LH_TIMEOUT` (900s), `LH_SEED`, `GRAFF_EVAL_MODEL`.
+
+## The two phases
+
+**Phase 1** walks a chain of steps, each printing a one-time TOKEN, and is told
+that a later session will need them. **Phase 2** is a *fresh process with no
+shared history* in the same directory, asked to recover those tokens from
+whatever durable record survived. Only phase 2 is scored; phase 1's number is a
+sanity check that the chain completed.
+
+## Four design properties, each of which had to be there
+
+1. **Tokens are unrecoverable from disk.** `probe.py` prints a token once, then
+ erases it from its own state file. `grep -r` over the fixture afterwards
+ finds nothing. Without this the eval measures re-reading, not memory: a fact
+ still on disk is one a competent agent simply reads again, and every arm
+ scores full marks.
+2. **The steps are chained, not numbered 1..N.** Each step reveals only the id
+ of the next, so they cannot be batched. This is measured, not assumed: with a
+ predictable sequence the model ran several probes per turn and 14 steps
+ produced **9 api calls and 3 compactions**. Chained, the same 14 steps
+ produced **45 calls and 15 compactions**.
+3. **Compaction is forced with `GRAFF_COMPACT_PCT`, not `GRAFF_CONTEXT`.**
+ `GRAFF_CONTEXT` only applies to models whose window graff cannot look up, so
+ against a model with a known window it is silently ignored and the run
+ compacts zero times while appearing to work.
+4. **Filler stays under the #440 handle threshold** so it accumulates in context
+ and drives compaction, rather than spilling to a handle.
+
+## Scoring
+
+- `correct` — token matched against its own step label. The real score.
+- `loose` — token present anywhere in the output. Separates "forgot it" from
+ "mislabelled it", and caught a run that scored 0/14 exact while having
+ actually retained all 14.
+- `fabricated` — a label carrying the *wrong* value. On a cold recall an agent
+ that invents plausible tokens is worse than one that admits it cannot recover
+ them, and a hits-only score hides that completely.
+
+## Reading a result honestly
+
+Runs are live-model and n is small; treat single-run deltas as directional. The
+call cap (`--max-model-calls 60`) is a parameter, and an arm that exhausts it
+has not "forgotten" anything — it failed to arrive. Check `p1_correct` before
+concluding anything about recall: a low phase-2 score with a low phase-1 score
+is an incompleteness result, not a memory result.
+
+The phase-1 prompt tells both arms that a later session will need the data. That
+does real work — in an earlier un-hinted variant the agent persisted nothing at
+all — so this measures "can it persist when told to", not "does it think to".
diff --git a/scripts/eval/longhorizon/RESULTS-2026-08-06-optmem.md b/scripts/eval/longhorizon/RESULTS-2026-08-06-optmem.md
new file mode 100644
index 00000000..e3552146
--- /dev/null
+++ b/scripts/eval/longhorizon/RESULTS-2026-08-06-optmem.md
@@ -0,0 +1,97 @@
+# Cross-session memory: graff v0.0.242 vs graff + OptMem
+
+**Verdict: not adopting OptMem.** Its retention was flawless; its cost model is
+the wrong shape for a harness whose agent already has bash and a filesystem.
+
+Evaluated because [OptMem](https://github.com/VictorTaelin/OptMem) solves a real
+gap — a hierarchical, navigable index over an append-only log — that #441's flat
+transcript does not. The design is sound. The integration is not.
+
+**Setup.** `gpt-5.6-sol`, 12 chained steps, `GRAFF_COMPACT_PCT=3`, 36 filler
+lines/step, `--max-model-calls 60`, one run per arm, identical tokens across
+arms (paired). Base is v0.0.242 as shipped, which already carries the
+append-only transcript (#441), pre-compaction notes-to-self (#391) and the
+post-compaction durable-state note (#411) — so this is not "OptMem vs nothing",
+it is "does OptMem add anything on top of what we ship".
+
+## Results
+
+| | base (v0.0.242) | + OptMem |
+|---|---|---|
+| **cold recall** | **12/12** | 8/12 |
+| fabricated tokens | 0 | 0 |
+| steps completed | 12/12 | **8/12 — call budget exhausted** |
+| api calls per completed step | **3.2** | 7.5 |
+| input tokens | 198,864 | 332,925 (**+67%**) |
+| compactions | 13 | 21 |
+| wall | 296s | 580s |
+
+## What actually happened
+
+**OptMem retained everything it stored: 8 of 8, across a genuine session
+boundary.** It did not forget. It ran out of budget at step 8 of 12, and its
+final message honestly enumerated what remained undone, including a `memo nap`
+compression it had been asked to perform mid-task.
+
+**The mechanism is the whole result.** The base agent persisted with:
+
+```sh
+python3 probe.py step 9 | tee -a .probe-token-chain
+```
+
+Persistence folded into a tool call it was **already making** — zero marginal
+cost. OptMem requires a separate `memo note` call per fact, plus `wake` at
+startup, plus compressions it prompts for mid-task. That is 2.3× the calls per
+step, and the extra output inflated context enough to force 21 compactions
+against 13.
+
+This is the #440 doctrine ("filesystem as the namespace, bash as the REPL")
+arriving at the same destination without a subsystem — reached by the model on
+its own, unprompted.
+
+## An earlier round that was invalid, and why it is recorded
+
+The first attempt was a single session. Both arms scored 18/18 through ~20
+compactions and OptMem appeared to cost +10.7% for no benefit — a tidy,
+plausible, **entirely unfounded** conclusion. `memo note` had been called **zero
+times** and `LOG.txt` was empty. The arm never used the tool; it only paid to
+carry instructions it ignored.
+
+Two findings survive from that failure:
+
+1. **The model ignored instructions marked "mandatory."** The AGENTS.md was
+ correct and complete and `memo` was executable at the documented path. Given
+ a concrete task, the agent went straight at it. That is an adoption risk for
+ *any* always-on memory layer that depends on the model volunteering to write,
+ and it is not specific to OptMem.
+2. **A single-session test cannot evaluate a cross-session tool.** Within one
+ session the agent has no reason to note anything: its context holds
+ everything, and #391 covers the rollover.
+
+The lesson for this harness generally: **always check the mechanism was
+exercised before believing the score.** `memo_notes` and `memo_log_lines` are in
+the record for exactly that reason.
+
+## What is worth taking
+
+Not the tool. The **idea**: a hierarchical index over the append-only
+transcript, so a large `.transcript.jsonl` is navigable rather than only
+greppable. Built from the compaction summaries graff *already generates*, its
+leaves cost nothing extra and land on precisely the right boundary — which is
+the one thing OptMem cannot do, since it must schedule merges explicitly and
+interrupt the agent to run them.
+
+Two costs to avoid importing along with it: OptMem's `wake` loads ~8k tokens
+into every session by default, several times what #416 and #445 clawed back this
+same release; and a per-fact API call is expensive in exactly the regime that
+matters.
+
+## Caveats
+
+n=1 per arm — treat the deltas as directional, not measured. The 60-call cap is
+a chosen parameter and OptMem would likely have finished without it, though the
+2.3×-per-step cost ratio is cap-independent and is the real signal. Both arms
+were told a later session would need the data, which does real work: in the
+un-hinted round the agent persisted nothing at all. And OptMem is built for
+accumulating identity across projects over weeks, which this fixture does not
+test at all.
diff --git a/scripts/eval/longhorizon/fixture/probe.py b/scripts/eval/longhorizon/fixture/probe.py
new file mode 100644
index 00000000..b8101ff1
--- /dev/null
+++ b/scripts/eval/longhorizon/fixture/probe.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+"""Long-horizon memory probe.
+
+Each `step N` emits a one-time TOKEN and then DESTROYS it on disk. After that
+the token exists nowhere except the conversation, so recovering it later is a
+pure memory question: no re-reading, no re-deriving. That property is the whole
+point — a fact still readable from the filesystem tests nothing, because a
+competent agent just reads it again and both arms score full marks.
+
+Each step also emits filler kept deliberately under the #440 handle threshold,
+so it accumulates in context rather than spilling to a handle, and drives real
+compaction.
+"""
+import json, os, pathlib, sys
+
+ROOT = pathlib.Path(__file__).resolve().parent
+STATE = ROOT / ".state.json"
+
+
+def load():
+ return json.loads(STATE.read_text())
+
+
+def save(s):
+ tmp = STATE.with_suffix(".tmp")
+ tmp.write_text(json.dumps(s))
+ tmp.replace(STATE)
+
+
+def main():
+ if len(sys.argv) < 3 or sys.argv[1] != "step":
+ print("usage: probe.py step <N>")
+ sys.exit(2)
+ n = sys.argv[2]
+ s = load()
+ if n not in s["steps"]:
+ print(f"no such step {n}; valid: {' '.join(sorted(s['steps'], key=int))}")
+ sys.exit(2)
+
+ entry = s["steps"][n]
+ if entry["consumed"]:
+ # The load-bearing behaviour: a consumed token is gone for good.
+ print(f"step {n}: ALREADY CONSUMED — this token was emitted once and "
+ f"erased. It cannot be recovered from disk. If you did not "
+ f"record it, it is lost.")
+ sys.exit(0)
+
+ token = entry["token"]
+ entry["consumed"] = True
+ entry["token"] = None # erased from disk, forever
+ save(s)
+
+ print(f"=== step {n} of {len(s['steps'])} ===")
+ print(f"TOKEN-{n}: {token}")
+ print(f"NOTE: that token has now been erased from disk. It will never be "
+ f"printed again. You must carry it yourself to the end of this task.")
+ nxt = entry.get("next")
+ # The chain is what forces one model call per step. With a predictable
+ # 1..N sequence the model simply batches every probe into a single turn,
+ # context never accumulates and no compaction fires — measured, not
+ # assumed: 14 predictable steps produced 9 api calls and 3 compactions.
+ print(f"NEXT: run `python3 probe.py step {nxt}`" if nxt else
+ "NEXT: none — this was the last step. Now report every token.")
+ print()
+ # Filler: bulk that fills context without tripping the handle threshold.
+ for i in range(int(s["filler_lines"])):
+ print(f" [step {n}] scan {i:04d} module=pkg/mod-{i:04d} "
+ f"status=OK checksum={(hash((n, i)) & 0xffffff):06x}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/eval/longhorizon/run_longhorizon.py b/scripts/eval/longhorizon/run_longhorizon.py
new file mode 100644
index 00000000..b8e2afc0
--- /dev/null
+++ b/scripts/eval/longhorizon/run_longhorizon.py
@@ -0,0 +1,210 @@
+#!/usr/bin/env python3
+"""Long-horizon memory A/B: graff as shipped vs graff + OptMem.
+
+The question: after several real compactions, can the agent still produce facts
+it saw ONCE, early, that no longer exist on disk?
+
+Arm `base` is v0.0.242 as shipped, which already carries the append-only
+transcript (#441), pre-compaction notes-to-self (#391) and the post-compaction
+durable-state note (#411). So this is not "OptMem vs nothing" — it is "does
+OptMem add anything on top of what we just shipped", which is the actual
+decision.
+"""
+import json, os, pathlib, random, re, shutil, string, subprocess, sys, time
+
+ROOT = pathlib.Path(__file__).resolve().parent
+FIX = ROOT / "fixture"
+RUNS = ROOT / "runs"
+MEMO = pathlib.Path(os.environ.get("LH_MEMO_BIN", "")) # optional comparison arm; not vendored
+
+GRAFF = os.environ.get("GRAFF_BIN", "/Users/blackfloofie/codegraff/zig-out/bin/graff")
+MODEL = os.environ.get("GRAFF_EVAL_MODEL", "gpt-5.6-sol")
+STEPS = int(os.environ.get("LH_STEPS", "12"))
+FILLER = int(os.environ.get("LH_FILLER", "26")) # lines/step, under the 4096B handle threshold
+COMPACT_PCT = os.environ.get("LH_COMPACT_PCT", "4") # % of the window at which compaction fires.
+# GRAFF_CONTEXT is NOT the knob here: it only applies to models whose window
+# graff cannot look up, and gpt-5.6-sol has a known 270k one, so it is ignored.
+# Forcing a low compaction PERCENT is what makes a short run cross the boundary
+# several times, which is the whole point of the fixture.
+TIMEOUT = int(os.environ.get("LH_TIMEOUT", "900"))
+
+RECALL_TASK = (
+ "A previous session in this same directory worked through probe.py and saw "
+ "{n} one-time TOKEN values. That session is over and its conversation is "
+ "gone. The tokens were erased from probe.py's state when they were printed, "
+ "so re-running it will not reveal them.\n\n"
+ "Recover as many of those tokens as you can from whatever durable record "
+ "the previous session left behind, and report them. Reply with EXACTLY one "
+ "line per token you recover and nothing else, labelled by the step number "
+ "that printed it:\nTOKEN-<step>=<value>\n"
+ "If you genuinely cannot recover a token, omit its line rather than guessing."
+)
+
+TASK = (
+ "Work through probe.py one step at a time, starting with "
+ "`python3 probe.py step {start}`. Each step prints a TOKEN and then tells "
+ "you which step to run NEXT — you cannot know the order in advance, so run "
+ "exactly one step per turn and follow the chain until a step says there is "
+ "no next one. Each TOKEN is ERASED from disk the moment it is printed; it "
+ "is never printed again, so you cannot go back for it.\n\n"
+ "IMPORTANT: a LATER, SEPARATE session — with none of this conversation "
+ "available — will be asked to recover these tokens. Whatever durable record "
+ "you rely on, make sure they survive this session ending.\n\n"
+ "When the chain ends, reply with EXACTLY one line per token and nothing "
+ "else. Label each token with the STEP NUMBER that printed it — the N in "
+ "that step's `TOKEN-N:` line — NOT the order you visited them in. Sort by "
+ "step number:\n"
+ "TOKEN-1=<value>\nTOKEN-2=<value>\n...\nTOKEN-{n}=<value>"
+)
+
+
+def make_tokens(rng):
+ al = string.ascii_uppercase + string.digits
+ ids = [str(i) for i in range(1, STEPS + 1)]
+ order = ids[:]
+ rng.shuffle(order) # traversal order is scrambled so it cannot be guessed
+ toks = {i: "".join(rng.choice(al) for _ in range(8)) for i in ids}
+ return toks, order
+
+
+def setup(dest, arm, tokens):
+ if dest.exists():
+ shutil.rmtree(dest)
+ dest.mkdir(parents=True)
+ shutil.copy2(FIX / "probe.py", dest / "probe.py")
+ toks, order = tokens
+ nxt = {order[i]: (order[i + 1] if i + 1 < len(order) else None) for i in range(len(order))}
+ (dest / ".state.json").write_text(json.dumps({
+ "filler_lines": FILLER,
+ "start": order[0],
+ "steps": {k: {"token": v, "consumed": False, "next": nxt[k]} for k, v in toks.items()},
+ }))
+
+ home = dest / "_home"
+ home.mkdir()
+ # graff resolves credentials out of HOME (~/.codex/auth.json and friends),
+ # and OptMem keys its store on HOME too. So the per-run HOME symlinks the
+ # credential dirs back to the real one — auth keeps working while .optmem
+ # stays isolated per run. Both arms get the identical shape, so the only
+ # difference between them is the memory instructions.
+ real = pathlib.Path(os.environ.get("REAL_HOME", os.path.expanduser("~")))
+ for cred in (".codex", ".codegraff", ".config"):
+ src = real / cred
+ if src.exists():
+ try:
+ (home / cred).symlink_to(src)
+ except OSError:
+ pass
+ agents = ["# Project", "", "Follow the task exactly. Be concise."]
+
+ if arm == "optmem":
+ if not MEMO.exists():
+ sys.exit("the optmem arm needs LH_MEMO_BIN pointing at a `memo` "
+ "binary; see RESULTS-2026-08-06-optmem.md for why this "
+ "arm exists and what it measured")
+ shutil.copy2(MEMO, home / "memo")
+ os.chmod(home / "memo", 0o755)
+ init = subprocess.run([str(home / "memo"), "init"], capture_output=True,
+ text=True, env={**os.environ, "HOME": str(home)})
+ # Use OptMem's OWN prescribed instructions, not a paraphrase of them.
+ block = init.stdout.split("Paste this at the top", 1)
+ agents += ["", (block[1].split("\n", 1)[1] if len(block) > 1 else init.stdout).strip()]
+ (dest / "AGENTS.md").write_text("\n".join(agents) + "\n")
+ return home
+
+
+def graff_cmd(task, calls="60"):
+ return [GRAFF, "--model", MODEL, "--no-telemetry", "--new", "--yolo", "-p",
+ "--max-model-calls", calls, task]
+
+
+def one_run(arm, idx, tokens):
+ dest = RUNS / arm / str(idx)
+ home = setup(dest, arm, tokens)
+ env = {**os.environ, "HOME": str(home), "GRAFF_NO_TELEMETRY": "1",
+ "GRAFF_COMPACT_PCT": COMPACT_PCT}
+ start = json.loads((dest / ".state.json").read_text())["start"]
+ cmd = graff_cmd(TASK.format(n=STEPS, start=start))
+ t0 = time.time()
+ try:
+ p = subprocess.run(cmd, cwd=dest, capture_output=True, text=True,
+ timeout=TIMEOUT, env=env)
+ out, err, rc, killed = p.stdout, p.stderr, p.returncode, False
+ except subprocess.TimeoutExpired as e:
+ out = (e.stdout or b"").decode(errors="replace") if isinstance(e.stdout, bytes) else (e.stdout or "")
+ err = (e.stderr or b"").decode(errors="replace") if isinstance(e.stderr, bytes) else (e.stderr or "")
+ rc, killed = -1, True
+ wall = time.time() - t0
+
+ (dest / "_stdout.txt").write_text(out)
+ (dest / "_stderr.txt").write_text(err)
+
+ # ── phase 2: a cold session. Same cwd, no shared history. ───────────────
+ p2out = p2err = ""
+ if not killed:
+ try:
+ p2 = subprocess.run(graff_cmd(RECALL_TASK.format(n=STEPS), "40"),
+ cwd=dest, capture_output=True, text=True,
+ timeout=TIMEOUT, env=env)
+ p2out, p2err = p2.stdout, p2.stderr
+ except subprocess.TimeoutExpired:
+ p2out, p2err = "", "(phase 2 timed out)"
+ (dest / "_p2_stdout.txt").write_text(p2out)
+ (dest / "_p2_stderr.txt").write_text(p2err)
+
+ # Phase 1 recall is trivial (the tokens are in-context), so it is recorded
+ # only as a sanity check that the chain completed. The REAL score is phase
+ # 2: a cold session that must recover them from a durable store.
+ toks = tokens[0]
+ pat = r"TOKEN-(\d+)\s*=\s*([A-Z0-9]{8})"
+ got1 = dict(re.findall(pat, out))
+ p1_correct = sum(1 for k, v in toks.items() if got1.get(k) == v)
+
+ got2 = dict(re.findall(pat, p2out))
+ correct = sum(1 for k, v in toks.items() if got2.get(k) == v)
+ # Anywhere-in-output credit separates "forgot it" from "mislabelled it".
+ loose = sum(1 for v in toks.values() if v in p2out)
+ # An agent that INVENTS plausible tokens is worse than one that admits it
+ # cannot recover them, and a hits-only score would hide that entirely.
+ wrong = sum(1 for k, v in got2.items() if toks.get(k) and toks[k] != v)
+
+ u = re.search(r"\[usage\]\s+(\d+)\s+api call\(s\)\s+.\s+(\d+)\s+in\s+\((\d+)\s+cached\)\s*\+\s*(\d+)\s+out", err)
+ rec = {
+ "arm": arm, "run": idx, "rc": rc, "timed_out": killed, "wall_s": round(wall, 1),
+ "p1_correct": p1_correct, "correct": correct, "loose": loose,
+ "fabricated": wrong, "of": STEPS,
+ "compactions": err.count("[history compacted"),
+ "api_calls": int(u.group(1)) if u else None,
+ "input_tokens": int(u.group(2)) if u else None,
+ "output_tokens": int(u.group(4)) if u else None,
+ "memo_notes": (err + out).count("memo note"),
+ "memo_log_lines": len([l for l in (home / ".optmem/memory/LOG.txt").read_text().splitlines() if l.strip()]) if (home / ".optmem/memory/LOG.txt").exists() else 0,
+ }
+ (dest / "meta.json").write_text(json.dumps(rec, indent=2))
+ return rec
+
+
+def main():
+ arms = sys.argv[1].split(",") if len(sys.argv) > 1 else ["base", "optmem"]
+ n = int(sys.argv[2]) if len(sys.argv) > 2 else 2
+ RUNS.mkdir(exist_ok=True)
+ seed = int(os.environ.get("LH_SEED", "20260806"))
+ allrecs = []
+ for i in range(1, n + 1):
+ # Same tokens across arms within a run index: a paired comparison.
+ tokens = make_tokens(random.Random(seed + i))
+ for arm in arms:
+ r = one_run(arm, i, tokens)
+ allrecs.append(r)
+ print(f"{arm:8s} #{i} phase1={r['p1_correct']}/{r['of']} "
+ f"COLD-RECALL={r['correct']}/{r['of']} exact ({r['loose']} anywhere, "
+ f"{r['fabricated']} wrong) memo_notes={r['memo_notes']} "
+ f"log_lines={r['memo_log_lines']} compactions={r['compactions']} "
+ f"in={r['input_tokens']} {r['wall_s']}s")
+ sys.stdout.flush()
+ (ROOT / "results.json").write_text(json.dumps(allrecs, indent=2))
+ print(f"\nwrote {ROOT/'results.json'}")
+
+
+if __name__ == "__main__":
+ main()