Context-Handoff Protocol & Infrastructure Middleware for Long-Running AI Coding Agents
Quick Start โข Architecture โข Features โข Benchmark v2 โข CLI & API Reference โข Docker Deployment
Long-running autonomous AI coding agents (Claude Code, OpenHands, Codex CLI, Aider, Devin-style systems) hit a fundamental physical limit: context window exhaustion. As an agent reads multi-file repositories, runs tests, inspects tracebacks, and executes tool calls, its context window fills rapidly.
Existing systems resort to two crude recovery strategies when context limit is approached:
- Truncation: Blindly dropping early chat messages, destroying architectural decisions, variable definitions, and file context.
- Unstructured Paragraph Summarization: Prompting an LLM to "summarize history", which loses precise line numbers, AST symbol signatures, exact git diffs, and failing tracebacks.
Both methods lead to severe failure modes โ most notably Dead-End Loops, where a fresh agent instance forgets previously rejected hypotheses and endlessly retries the exact same broken patches.
Relay is open-source infrastructure middleware that replaces conversational summarization with Structured Knowledge Checkpointing, Why-NOT Memory, and Multi-Signal Hybrid Retrieval.
When context usage reaches a configurable threshold (e.g., 85%), Relay interceptors checkpoint the active session into an immutable KnowledgeCheckpoint containing:
- Narrative Progress: Structured task goal and step summary.
- Decision Log: Key architectural choices made and their rationales.
- Why-NOT Store: Explicit memory of failed hypotheses, rejected patches, and runtime tracebacks.
- AST Symbol Deltas: Class/function definitions modified or created.
- JIT Context Retrieval: Hybrid vector (Qdrant) + graph (AST proximity) retrieval of relevant workspace chunks.
Fresh agent instances resume from a synthesized, highly token-efficient system prompt โ allowing tasks to continue seamlessly across context boundaries without repeating work or retrying dead ends.
# 1. Clone repository & enter directory
git clone https://github.com/neo0007777/relay.git
cd relay
# 2. Install package in editable mode
pip install -e .
# 3. Run complete unit & integration test suite (50/50 passing)
python3 -m pytest tests/ -v
# 4. Run quickstart handoff demo script
python3 scripts/demo_1_context_handoff.py
# 5. Run RelayBench Benchmark v2 suite
python3 scripts/run_benchmark_v2.py --iterations 3 โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Active Agent Session โ
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโ
โ
(Token Usage โฅ 85%)
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Context Monitor Interceptor โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Knowledge Checkpoint Engine โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โข Task Goal & Narrative โ
โ โข Architectural Decision Tree โ
โ โข "Why-NOT" Dead-End Memory โ
โ โข Git Diffs & AST Deltas โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Hybrid Graph & Vector Reranker โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โข Qdrant Dense Vector Store โ
โ โข AST Topological Proximity โ
โ โข Edit Recency Scoring โ
โโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LangGraph Handoff Orchestrator โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Synthesizes System Prompt & โ
โ Resumes Fresh Agent Session โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ContextMonitor continuously evaluates 5 distinct signals to trigger handoffs before catastrophic context overflow:
- Token Ratio: Usage vs maximum provider token limit.
- Edit Velocity: High frequency of rapid file modifications.
- Repeated Tool Failures: Consecutive command exit-code failures.
- Reasoning Loop Detection: Long chains of reasoning without state progress.
- Explicit Trigger: Programmatic or manual checkpoint boundary.
Relay serializes task state into an atomic, SHA-256 verified KnowledgeCheckpoint JSON schema:
{
"checkpoint_id": "chk-7f3a9012",
"task_goal": "Refactor authentication module into standalone TokenService",
"narrative_progress": "Extracted TokenService.py, updated JWT verification signature.",
"decision_log": [
{
"decision_id": "dec-1",
"choice_made": "Atomic Redis key swap for refresh token queue",
"justification": "Prevents async thread deadlocks under concurrent load"
}
],
"why_not_store": [
{
"approach_id": "wn-1",
"attempted_idea": "Mutex lock around refresh queue",
"rationale_rejected": "Caused deadlock in async execution loop",
"error_traceback": "DeadlockError: lock timeout after 5.0s"
}
],
"ast_changes": [
{
"file_path": "src/auth/tokens.py",
"symbol_name": "verify_jwt",
"symbol_type": "async_function",
"change_type": "modified",
"signature": "async def verify_jwt(token, secret=None)"
}
]
}One of Relay's primary design ideas is the "Why-NOT" store, which explicitly records rejected approaches, failed hypotheses, and runtime tracebacks. When a fresh agent resumes execution after handoff, the prompt builder injects negative constraints so the agent avoids repeating known dead ends:
โ DO NOT RETRY PREVIOUSLY FAILED APPROACHES:
Mutex lock around refresh queue: Failed due toDeadlockError: lock timeout after 5.0s.
Retrieves relevant code context for the resumed session by scoring chunks across 4 orthogonal dimensions:
RelayBench v2 is an autonomous, live agent evaluation suite spanning 288 independent runs across 32 tasks and 3 experimental conditions with zero expected solution injection:
| Strategy / Scenario | Completion Rate | 95% Confidence Interval | Dead-End Retries (mean) | Handoff Latency (ms) | Welch's |
|---|---|---|---|---|---|
| Relay (Full Knowledge Checkpoint) | 100.0% | 0.00 | 2.60 ms | Baseline | |
| Naive Truncation (Baseline) | 92.7% | 0.28 | 0.00 ms |
|
|
| Unlimited Context (Upper Bound) | 100.0% | 0.00 | 0.00 ms |
Operational Definition โ Dead-End Retry: A tool step where the agent attempts a patch or code edit matching an approach previously listed in the
WhyNotStorewithout introducing new information.Statistical Significance: Computed via Welch's two-sample
$t$ -test across 288 runs. Raw trace datasets are exported toartifacts/v2/benchmark_v2_results.csv.
- Task Scope: Currently evaluated on Python repository tasks; multi-language tasks (TypeScript, Go) remain in development.
- Agent Coverage: Claude Code CLI adapter currently has the highest test coverage.
- Context Horizon: Evaluated up to 128k context budgets; ultra-long horizon sessions (>200k tokens) remain future work.
- SWE-bench Integration: Evaluate Relay on real SWE-bench Lite repository issues.
- OpenHands & Aider Adapter Expansion: Deepen integration hooks with OpenHands and Aider agent runners.
- Multi-Agent Cross-Session Memory: Persist knowledge checkpoints across distinct agent team roles.
- Distributed Checkpoint Storage: S3/Postgres backends for enterprise cluster agent handoffs.
# Run an agent task through Relay middleware
relay run claude --project . --goal "Refactor database connection pool"
# Execute Benchmark v2 evaluation suite
python3 scripts/run_benchmark_v2.py --iterations 3
# List persisted checkpoints
relay checkpoint list
# Replay an execution trace in sandbox environment
relay replay .relay/traces/trace_sample.jsonlRelay exposes REST APIs for remote agent orchestration:
๐ Live Deployed API Server:
https://relay-api-pjuv.onrender.com
๐ Interactive Swagger Docs:https://relay-api-pjuv.onrender.com/docs
# Health Check (Live Server)
curl https://relay-api-pjuv.onrender.com/health
# Trigger Manual Checkpoint
curl -X POST https://relay-api-pjuv.onrender.com/api/v1/checkpoint \
-H "Content-Type: application/json" \
-d '{"session_id": "sess-123", "task_goal": "Optimize query"}'
# Execute Handoff
curl -X POST https://relay-api-pjuv.onrender.com/api/v1/handoff \
-H "Content-Type: application/json" \
-d '{"session_id": "sess-123"}'# Start Relay API server & Qdrant vector database
docker-compose up --build -d
# Check service container status
docker-compose psRelay includes a modern Next.js + Tailwind visualization web app:
cd frontend
npm install
npm run dev
# Open http://localhost:3000 to view handoff timeline & Qdrant retrieval visualizer- ๐ Claim Verification Matrix
- ๐๏ธ Architecture & Security Audit
- ๐ป Developer & Contributor Guide
- โก Empirical Performance Report
- ๐ Scalability Report
- ๐ก๏ธ Fault Injection Resilience Report
- ๐ v1.0.0 Release Notes
- ๐ Open Source Final Guide
- GitHub: @neo0007777
- Repository: https://github.com/neo0007777/relay
This project is licensed under the MIT License. See LICENSE for details.