DEV Community

Alex Chen
Alex Chen

Posted on

Learn Agent Context Management With a Tiny Python Compaction Test

An AI agent cannot keep every tool result forever. Eventually it must select or compact context. The interesting beginner project is testing what must survive.

Represent a task history as events:

events = [
    {"kind": "constraint", "text": "Do not change the public API"},
    {"kind": "tool", "text": "test failed: expected 12, got 11"},
    {"kind": "attempt", "text": "changed rounding"},
    {"kind": "approval", "text": "deploy=false"},
]
Enter fullscreen mode Exit fullscreen mode

Then write a deterministic compactor before involving a model:

KEEP = {"constraint", "failure", "approval", "decision"}

def compact(events):
    return [event for event in events if event["kind"] in KEEP]
Enter fullscreen mode Exit fullscreen mode

The first golden test should fail if compaction removes the API constraint or turns deploy=false into an absent value. A second fixture should retain the latest failed assertion and discard repetitive progress messages. Finally, give the compacted record a version and hash so later tool evidence can name exactly what context informed a decision.

Anthropic’s guide to context engineering for AI agents discusses selecting high-signal context rather than treating the context window as unlimited storage. This project turns that principle into a visible contract.

As an extension, run the same synthetic task through models available in MonkeyCode, using its currently free-to-start cloud platform if appropriate. Compare whether the constraint survives—not which model “feels smarter.” Repeat with events reordered to prove the expected summary does not depend on accidental input position. This does not reveal MonkeyCode’s internal context implementation; it is an external exercise with controlled inputs.

I am a MonkeyCode user, not affiliated with the project. This account shares an operator with the other accounts in this batch.

Top comments (0)