Skip to content
GuanghuiMinPublic

About

Code for paper "Prune the Summary, Not the History: Source-Judged Compaction for Long-Horizon Agents"

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Prune the Summary, Not the History: Source-Judged Compaction for Long-Horizon Agents

This repo contains the code for SJC (Source-Judged Compaction), a plug-in for the history compaction of a long-horizon tool-using agent. When the agent's history outgrows its context budget, a compressor LLM replaces the older turns by a summary. That summary mixes two kinds of entries: information the environment returned (values, IDs, results, how an API behaves) and the compressor's own plans, decisions and readings of the task. SJC keeps the first kind and removes the second: after the compressor writes the summary, a judge asks for every entry whether its information came from an environment output or from the previous summary, and the entries that did not are deleted before the agent sees the summary. The agent, its prompt, the compressor and its prompt stay unchanged.

🔗 Quick Links

Install Requirements

Step 1: Install the package and its dependencies (Python 3.10 or newer):

cd sjc
pip install -r requirements.txt
pip install -e .

Step 2: Copy the environment template and edit it:

cp env.example.sh env.sh

Put your OpenAI API key in env.sh as OPENAI_API_KEY; the agent and the compressor read it from there (ACON_VLLM_API_KEY and SJC_COMPRESSOR_API_KEY default to it). The judge, Jev (typesafe/jev-1.13), is reached through OpenRouter, so also set OPENROUTER_API_KEY. env.sh is git-ignored, so the keys never enter the repository. In the same file set the model names (SJC_AGENT_MODEL for the agent, SJC_COMPRESSOR_MODEL for the compressor), SJC_RUNS (where runs are written) and the paths of the benchmark harnesses. Then load it in every shell you work from:

source env.sh

Benchmark Setup

SJC does not ship an agent; the agents, environments and evaluators come from the benchmarks' own harnesses:

  • AppWorld and OfficeBench run through a patched checkout of ACON. Apply third_party/acon.patch, install AppWorld, and export OfficeBench's task tree to a read-only directory.
  • OfficeBench runs each task in a container built from docker/officebench/Dockerfile.

The exact commands are in third_party/README.md.

Repository Layout

sjc/gate.py               SJC: entries of the summary, the Jev request, the keep rule, the wrapper around a compressor
sjc/evidence.py           which parts of the environment outputs Jev sees (BM25 retrieval with parent chunks)
sjc/jev.py                Jev client (OpenRouter decisions endpoint)
sjc/safeguard.py          the host compressor: OpenClaw's safeguard-mode compaction
sjc/llm.py                the compressor's chat call
sjc/report.py             pass rate, Pass^k, Pass@k over evaluation runs
sjc/benchmarks/<name>/    agent.py (ACON's agent and environment), run.py (task runner)
data/tasklists            AppWorld test-normal and OfficeBench test task lists
scripts/eval_*.sh         full context, safeguard and SJC on one benchmark, three seeds, and the summary table

Every runner writes the same layout: <run>/run_records.jsonl with one line per task (task_id, success, num_steps, n_compressions, ...) and <run>/trajectories/<task_id>.json with the steps and the compaction events. Every command is resumable and skips tasks that are already recorded.

How SJC Works

After a compaction the agent sees its first prompt (system message, task and rules, always kept verbatim), the summary, and the most recent turn. SJC changes only what goes into the summary.

The host compressor

SJC works on top of any compressor whose summary is a list of entries under section headings. The compressor used here is OpenClaw's safeguard compaction mode (upstream commit d2f8755), ported in sjc/safeguard.py. It writes five sections (## Decisions, ## Open TODOs, ## Constraints/Rules, ## Pending user asks, ## Exact identifiers), re-distills the previous summary together with the new turns, and checks its own output: the five sections, the latest user request, and the opaque identifiers of the last ten compacted messages must be present. A failed check gets one corrective retry; if that also fails, the compaction is cancelled and the history is kept. In this port the task instruction plays the latest user request and one recent turn is kept verbatim. Run on its own (--method safeguard) it is the baseline.

Judging the summary entries

Every bullet of the five sections, with its continuation lines, is one entry. All entries of a compaction go to Jev in one request, one yes/no question per entry; Jev returns the probability of yes. The request state is:

field content
context a fixed paragraph explaining the fields (sjc/gate.py: CONTEXT)
visible.task the task instruction, the same view of the task the compressor has
visible.recent_interaction the turn that stays verbatim after the compaction
previous_checkpoint the previous committed summary; empty at the first compaction
span the compacted steps, each as {step, agent, action, executed, environment_output}
items b1..bn: {section, text} for every entry

The question asked for entry b{k}:

Does items.{k} contain information that came from an environment_output in span or from previous_checkpoint, such as a value, a name, a result, or how something in the environment behaves, rather than only plans, decisions, or readings of visible?

The question is about the source of an entry, not about whether it is correct. Whether a line's information can be found in what the environment returned can be checked against the material the judge sees; whether a plan or an inference is right usually cannot.

Evidence selection

A Jev request is limited to 32,000 tokens (30,000 estimated are used), and the environment outputs of a span are often longer. Jev therefore sees each output only through the passages retrieved for the entries it judges (sjc/evidence.py):

  1. Each output is split into lines; a line longer than 300 characters becomes 300-character windows overlapping by 50.
  2. For every entry, BM25 (k1 = 1.2, b = 0.75) ranks all passages and the top 3 are taken.
  3. A hit brings its parent chunk of at most 2,000 characters, built by the recursive splitter of the parent-document pattern (paragraphs, then the items of a pretty-printed JSON block, then lines; the default size of LangChain's RecursiveJsonSplitter).
  4. Hits are taken round-robin by rank until the budget is reached. Omitted parts are marked [... N lines omitted ...]; actions and agent text are always sent whole.

If the questions leave less than 8,000 tokens for evidence, they are split into batches, each with its own selection; in practice a compaction takes one request.

Committing the summary

An entry is kept if P(yes) >= 0.5 and deleted whole otherwise; section headings are never deleted and kept lines are byte-identical to what the compressor wrote. The pruned summary is what the agent sees, and it is also the previous summary the next compaction receives, so a deleted entry is not carried forward. If the compressor cancelled the compaction, the summary does not parse into the five sections, the request cannot fit the budget, or Jev fails, the raw summary is committed unchanged.

parameter value
keep threshold 0.5
passages retrieved per entry 3
parent chunk 2,000 characters
child passage / overlap 300 / 50 characters
BM25 k1 / b 1.2 / 0.75
request budget / minimum evidence room 30,000 / 8,000 estimated tokens
judge typesafe/jev-1.13

BM25 sums term scores in set order, so when two passages tie to the last bit their order can depend on Python's string hashing; set PYTHONHASHSEED to make the Jev requests reproducible across processes.

Running the Benchmarks

The agent runs with full context (no --method), with the safeguard compressor (--method safeguard), or with SJC (--method sjc). The context budget is 4096 tokens on AppWorld and 2048 on OfficeBench.

RUNS=$SJC_RUNS/appworld
python -m sjc.benchmarks.appworld.run --tasks data/tasklists/appworld_test_normal.jsonl --out $RUNS/full_s1 --seed 1 --workers 20
python -m sjc.benchmarks.appworld.run --tasks data/tasklists/appworld_test_normal.jsonl --out $RUNS/safeguard_w4096_s1 \
    --method safeguard --window 4096 --seed 1 --workers 20
python -m sjc.benchmarks.appworld.run --tasks data/tasklists/appworld_test_normal.jsonl --out $RUNS/sjc_w4096_s1 \
    --method sjc --window 4096 --seed 1 --workers 20

OfficeBench takes the same arguments plus a run tag, and runs every subtask in its own container:

python -m sjc.benchmarks.officebench.run --tasks data/tasklists/officebench_test.jsonl --out $SJC_RUNS/officebench/sjc_w2048_s1 \
    --tag sjc_w2048_s1 --method sjc --window 2048 --seed 1 --workers 20

Each compaction event in a trajectory holds the summary the agent saw (summary), the compressor's attempts and whether it cancelled (attempts, cancelled), and for SJC the judgement (gate: raw_summary, scores per entry, dropped, fail_open, Jev usage, and the token counts before and after pruning).

Evaluation

scripts/eval_appworld.sh and scripts/eval_officebench.sh run the three arms with seeds 1-3 and summarise them:

python -m sjc.report --arm full=$RUNS/full_s1,$RUNS/full_s2,$RUNS/full_s3 \
    --arm safeguard=$RUNS/safeguard_w4096_s1,$RUNS/safeguard_w4096_s2,$RUNS/safeguard_w4096_s3 \
    --arm sjc=$RUNS/sjc_w4096_s1,$RUNS/sjc_w4096_s2,$RUNS/sjc_w4096_s3 --out $RUNS/summary.md

sjc.report prints the pass rate over all runs, Pass^k (a task passes in every run), Pass@k (in at least one), and the mean numbers of steps and compactions.

Using SJC with Another Agent

SJC wraps a compressor with the interface ACON's memory manager uses (check_summarization_needed, process, events) and returns the pruned summary in place of the raw one:

from sjc.gate import SJC
from sjc.safeguard import SafeguardCompressor

compressor = SJC(SafeguardCompressor(window=4096, seed=1))
summary = compressor.process(task, history_text, prev_summary,
                             raw_history=messages,                       # chat messages, first two = system + first prompt
                             opt_args={"preserved_turns": last_turn})    # the messages kept verbatim

messages are OpenAI-style chat messages; the steps of the span are read from the assistant tool calls (the code argument, or the raw arguments) and the tool or user messages that follow them. To prune a summary from another compressor, call sjc.gate.prune(summary, task, preserved_turns, prev_summary, messages, Jev()) directly; it expects the five safeguard headings, and REQUIRED_SUMMARY_SECTIONS in sjc/safeguard.py names them.

About

Code for paper "Prune the Summary, Not the History: Source-Judged Compaction for Long-Horizon Agents"

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages