Cross-Provider Context Handoff and Unified Session Lineage
Architecture and implementation details for Context Handoff, Worktree Forking, and Unified Session Lineage.
1. Goals and Overall Architecture
Section titled “1. Goals and Overall Architecture”This design implements the highest-leverage 20% of T3 Code Orchestration V2 across herdr2 (herdr-core + herdr-app):
- Cross-Provider Context Handoff (
Handoff/Fork/Side Chat/Merge Back): Supports transferring context between any combination of headless ACP agents (a*) and interactive PTY terminal agents (t*), coveringa* / t* -> new a* / new t* / --into existing a*|t*. - Lightweight Unified Session Lineage: Records parent/branch/merge origins directly inside
Agent,Terminal, DroveWorker/Assign, and transcript entries (Entry::Handoff)—reusing existing file-backed state and worktree models without introducing a heavyweight event-sourcing database. - Drove Automatic Fallback Retry Handover: When a Drove DAG task retries (
retry_of) or falls back to a different provider, Core automatically extracts the prior attempt’s trajectory, failure reason, and change summary into the new worker’s prompt, while preserving manual triggers and UI handoff entry points.
2. Core Design and Phased Implementation
Section titled “2. Core Design and Phased Implementation”Step 1: Data Model, Transcript Enhancements, and Deterministic Context Packager (herdr-core)
Section titled “Step 1: Data Model, Transcript Enhancements, and Deterministic Context Packager (herdr-core)”api/types.rsandpty_transcript.rs- Added
provider: Option<String>andsession_id: Option<String>toReadSessionMeta, and updated the Claude / Codex / Gemini / Pi / Agy CLI transcript parsers to extract the actual provider and underlyingsession_id. - Added
--from-turnand--to-turntoReadParamsso receiving agents can slice and lazily re-read omitted earlier turns on demand.
- Added
transcript.rs- Added
Entry::Handoff { kind, from_address, from_provider, from_session_id, from_turns, artifact_path, ts_ms }along withturn(),approx_bytes(), andrender_line()implementations. - Extended
strip_h2_envelopeto filter internal<herdr2-handoff ...>...</herdr2-handoff>envelope tags. - Added the
slice_turn_rangehelper for slicing transcript entries by turn range.
- Added
src/handoff.rs(new module exported insrc/lib.rs)- Defined
LineageKind(Handoff/Fork/SideChat),Lineage, andHandoffPackage. - Implemented the bounded deterministic context packager
build_handoff_package(default 24 KiB budget):- Preserves the Turn 1 original objective + current
git status --short+ plan/latest summary; - Backfills recent turns and key artifacts in reverse chronological order;
- Generates self-service lookup hints (
h2 read <source> --from-turn X --to-turn Y) for middle turns collapsed due to budget limits.
- Preserves the Turn 1 original objective + current
- Implemented
default_pty_argvand unit tests.
- Defined
agents.rs,terminals.rs,api.rs,mcp.rs- Added
lineage: Option<Lineage>toAgent,NewAgent,Terminal, andNewTerminal. - Implemented
--from-turn/--to-turnfiltered reading in bothagent_readand theh2_readMCP tool (supporting botha*andt*).
- Added
Step 2: Unified agent.handoff RPC, CLI, MCP, and Hybrid Delivery Paths
Section titled “Step 2: Unified agent.handoff RPC, CLI, MCP, and Hybrid Delivery Paths”api/handoff.rs+api/types.rs+api.rs- Added
HandoffParamsandHandoffResult(avoiding any field namedfirst_messageto satisfy them0OpenRPC contract test) and registered the"agent.handoff"RPC method. - Implemented dual-track delivery based on the target runtime:
- Headless ACP Target (
a*): Writes the full handoff package intoTargetCheckpoints.pending_handoff(automatically prepended on Turn 1 byacp/mod.rs::prepare_acp_promptwithout polluting the user-visible first message) and appendsEntry::Handoff(Turn 0); ifpromptis supplied, immediately starts the first turn. - Interactive PTY Target (
t*): Never usestc.pending_handoff(avoiding conflicts with Agy rollback prompts) and never overwrites an already-running PTY pane:- Same-provider CLI native
Fork(e.g., Claude or Codex with a resolvedsession_id): Reusespty_adapters::{fork_claude_jsonl, fork_codex_jsonl}to copy the session file up to the requested turn and launches with--resume <fork_uuid>/codex resume <fork_uuid>. - Cross-provider or general handoff: Stages the complete
handoff.mdinto the target terminal’s staging directory viaput::stage_terminal, then injects a brief two-line file-path pointer instructing the agent to read it.
- Same-provider CLI native
--into <target>Merge-Back Mode (includingmerge_back): Extracts conclusions from the source node’s recent turns (or the incremental turns since the last fork), builds a lightweight delta handoff, and delivers it safely into an existinga*or as a file pointer into an existingt*(without clearing or restarting a PTY target).
- Headless ACP Target (
- Added
remote.rs,cli.rs,cli/output.rs,mcp.rs,help.txt,SKILL.md- Wired
"agent.handoff"into the remote forwarding allowlist, theh2 handoffCLI subcommand, theh2_handoffMCP tool,lineagestatus display, and help/skill documentation. - Updated the OpenRPC schema (
schema/h2.openrpc.json), CLI command docs (docs/commands.md), andtests/handoff.rsintegration tests.
- Wired
Step 3: Drove DAG Automatic Fallback Retry Handover
Section titled “Step 3: Drove DAG Automatic Fallback Retry Handover”drove/protocol.rsanddrove/pool.rs- Added
PriorAttemptHandoverandbuild_task_prompt_with_handover. - When a DAG task retries (
retry_of) and is scheduled onto a new worker (or falls back to an alternate provider),build_attempt_handoverextracts the failure reason, executed trajectory, and trailing output summary from the previous attempt’sWorkerItemlogs and injects them into the prompt, while recording lineage inWorker.forked_fromandAssign.fork.
- Added
Step 4: Desktop UI Integration (herdr-app)
Section titled “Step 4: Desktop UI Integration (herdr-app)”src/commands.rs,src/hc.rs,src/window.rs,defaults/AGENTS.md- Registered and forwarded the
agent.handoffcommand, and updatedAGENTS.mdcommand documentation to pass doc validation tests.
- Registered and forwarded the
- New
defaults/mods/handoff/{mod.json,main.js}(bilingualen/zh-CN)- Provides the Handoff modal with mode selection (
Handoff/Fork/Side Chat/Merge back), target runtime (CLI/ACP), Preset, and placement layout (Split Right/New Tab/Peek).
- Provides the Handoff modal with mode selection (
- Existing Module Integration
defaults/mods/menu/main.js: Adds Handoff / Fork / Side Chat / Merge back entries to context and action menus.defaults/mods/pane/main.js: Displays a clickable↳ <source>lineage badge and hover quick actions in the pane header.defaults/mods/peek/{acp_model.js,main.js}: Parses and rendersEntry::Handoffbanner cards along with header lineage jump andMerge backactions.
3. Verification Plan
Section titled “3. Verification Plan”herdr-coreverification:H2_UPDATE_SCHEMA=1 cargo test --locked -p herdr2 --test m0sh scripts/docs.sh --writecargo clippy --locked --all-targets -- -D warningscargo test --locked -p herdr2 --libcargo test --locked -p herdr2 --test m0 --test cli_docs --test skill --test handoff --test checkpoints --test acp_mcp --test drove
herdr-appverification:cargo build --lockedbun scripts/docs.ts generatebun test scripts/docs.test.ts scripts/peek.test.ts scripts/changes.test.ts scripts/agents.test.ts scripts/tabs.test.ts scripts/palette.test.tscargo test --locked