Switching Models Mid-Flight Without Losing Context: Cross-Harness Handoffs, Compaction, and SQLite Trajectory Forking
Subscription rate limits always hit at 90% completion, and exploratory architecture turns often need a clean rewind three prompts back. Because each CLI stores conversations in an incompatible format (tree-linked JSONL, append-only rollout logs, protobuf-in-SQLite trajectories, and WAL-mode relational tables), Rudder implements two complementary primitives: zero-LLM cross-harness handoffs and native trajectory forking.
Why a cross-harness handoff must not call an LLM first
When you switch an active agent's model picker from Claude Opus to Codex or Gemini (or trigger /handoff), the naive design asks the outgoing agent to summarize its work first. In practice, that fails in the exact scenario users care about most:
- Quota exhaustion: The #1 reason developers move a live session to another harness is that the current subscription just hit its 5-hour or weekly usage cap. The outgoing harness literally cannot generate another token.
- Latency tax: Waiting 20-45 seconds for a summarization turn before the new harness even spawns makes model switching feel sluggish.
cloud/worker/handoff.mjs and native/src/handoff.rs assemble the entire handoff deterministically in milliseconds from data Rudder already owns on disk: the initial goal, why and where the previous harness stopped (interrupted, permission, usage_limit, or mid-tool), live jj working-copy file diffs, the outgoing harness's own most recent compaction checkpoint summary, carried summaries from earlier handoffs in the same chain, compressed tool-call breadcrumbs, the outgoing assistant's final reply verbatim, and exact filesystem paths to prior transcripts in case the incoming agent wants to grep an old detail.
Budgeting 60,000 characters inside Linux's 128 KiB MAX_ARG_STRLEN
The handoff packet launches the new harness as its initial CLI prompt argument, and the Linux kernel enforces a hard per-argument ceiling of MAX_ARG_STRLEN = PAGE_SIZE * 32 = 131,072 bytes (execve fails with E2BIG if any single UTF-8 argv[i] exceeds 128 KiB - 1). Rather than truncating from the bottom and losing the user's latest instruction, handoffPrompt() allocates explicit section caps inside PROMPT_MAX = 60,000 characters:
const PROMPT_MAX = 60_000;
const ARG_BYTES_MAX = 128 * 1024 - 1;
const SUMMARY_MAX = 16_000; // Latest compaction summary from outgoing harness
const CONVERSATION_MAX = 14_000; // Sliding tail of recent turns (~4k tokens)
const CARRIED_MAX = 8_000; // Lineage from prior harness moves
const REPLY_MAX = 8_000; // Outgoing agent's final reply in full
const LIST_MAX = 3_000; // Modified files + secondary checkouts + log paths
Embedded markdown headings inside quoted user/assistant messages are demoted with quote() (/^#{1,2}(?= )/gm -> "###") so untrusted transcript text can never spoof top-level handoff sections like ## Goal or ## What to do now. As its first action, the incoming harness writes a crisp ≤8-line orientation card in chat confirming goal, touched files, and next step before resuming execution in the exact same workspace.
Multi-account rotation, 5-hour window priority auto-return, and spend tracking
Developers scaling parallel agents hit subscription caps in predictable waves: Claude Pro and Max enforce rolling 5-hour session windows alongside 7-day caps, Codex enforces rolling window and weekly limits, and Antigravity enforces per-family model pools. Many heavy teams hold two Claude subscriptions (for example, a work Max plan and a personal Pro/Max account) plus ChatGPT Plus/Pro and Google AI Pro.
Rudder's When usage runs out control (cloud/app/usage-fallback.js and cloud/worker/usage-fallback.mjs) treats your fallback list as an ordered priority stack across both accounts and harnesses:
- Multi-account selection on the same harness: Each entry is keyed by
<backend>/<model>@<account>. You can chainClaude Opus · Account 1toClaude Opus · Account 2toCodex GPT-5.4. Because extra accounts in~/.rudder/accounts/<backend>/<id>share conversation storage with the main directory while isolating credentials (src/accounts.ts), switching from Claude Account 1 to Claude Account 2 resumes the exact same Claude conversation natively with zero context loss. - Automatic priority return when a 5-hour window resets: Other wrappers leave a chat stranded on a backup model forever after a temporary 5-hour limit. When Rudder falls back from your prioritized model,
nextStep()recordspreferred: { backend, model, effort, account }. Every 4 seconds, the home checks live reset timestamps (resetsAt): as soon as the 5-hour window clears on your prioritized model (refusal(preferred) === ""), Rudder automatically switches a settled same-harness chat back to the prioritized model/account at idle (kind: "restore"), or moves a cross-harness chat back on your next message viatakeCrossHarnessRestore(). - Subscription ROI vs. API-equivalent spend in Settings: Because subscriptions are flat-rate while workloads vary wildly,
cloud/worker/spend-usage.mjsscans local session logs across Claude (multi-account), Codex, Antigravity, and OpenCode, joining flat monthly plan costs ($20/$100/$200) against published per-million-token API rates and prompt-cache read savings in Settings > Usage & Spend.
Editing and branching messages across four incompatible storage engines
When you click Edit on an earlier user message (or Branch from here to explore an alternative design in parallel), Rudder cannot merely hide UI bubbles; the underlying CLI's session state must rewind or fork cleanly so the model does not hallucinate tools from the discarded timeline. Each harness requires a distinct surgery in native/src/chat_edit.rs and cloud/worker/session-lineage.mjs:
| Harness | On-Disk Format | Edit / Rewind & Branch Mechanism |
|---|---|---|
| Claude Code | DAG of JSONL entries linked by uuid & parentUuid |
Active leaf walk prunes abandoned edit branches when reading transcripts; branching clones the JSONL prefix up to the cut point under a new session UUID. |
| OpenAI Codex | rollout-<ts>-<uuid>.jsonl |
Records history_base byte-offset chains across forked rollout files so UI scrollback stitches seamlessly while the forked session starts from the exact cut turn. |
| OpenCode | opencode.db (SQLite WAL: session, message, part) |
Passes RUDDER_OPENCODE_FORK_BEFORE=<msgId> to OpenCode's native session fork API via opencode_plugin.mjs, preserving relational part integrity under WAL concurrency. |
| Gemini Antigravity | conversations/<cid>.db + brain/<cid> |
Atomic SQLite VACUUM INTO clone, 36-byte UUID rewrite in metadata + protobuf blob, and idx >= cut_idx step truncation (detailed below). |
What if you catch a typo in a message before the busy agent has even finished its current tool call? Waiting for the turn to end just to rewind wastes minutes. Rudder's pending queue (cloud/app/pending.js + /api/app/withdraw) lets you click Edit on any queued, waiting, or sending message, atomically withdrawing it from the server queue (or recalling it out of the CLI's live input buffer via up,ctrl-u,ctrl-k) and restoring both your text and attached files straight back into the composer.
Inside Antigravity SQLite trajectory cloning
Google's Antigravity CLI (agy) does not expose a --fork-session flag. Each conversation lives in ~/.gemini/antigravity-cli/conversations/<cid>.db alongside brain/<cid>/.system_generated/logs/transcript.jsonl. Inspecting the SQLite schema reveals why simply copying the .db file to a new filename fails: internal foreign keys and serialized protobuf blobs embed both cascade_id (the conversation UUID) and trajectory_id.
fork_antigravity_session in native/src/antigravity.rs performs a crash-safe clone and optional step rewind without external native libraries:
-- 1. Consistent snapshot copy even if source DB was recently in WAL mode
VACUUM INTO '/.../conversations/<new_cid>.db';
-- 2. Truncate trajectory tables at cut_idx (when editing an earlier prompt)
DELETE FROM steps WHERE idx >= :cut_idx;
DELETE FROM gen_metadata WHERE idx >= :cut_idx;
DELETE FROM executor_metadata WHERE idx >= :cut_idx;
DELETE FROM parent_references WHERE idx >= :cut_idx;
DELETE FROM battle_mode_infos WHERE idx >= :cut_idx;
-- 3. Rewrite 36-byte ASCII UUIDs in both relational row & protobuf blob
UPDATE trajectory_meta
SET trajectory_id = :new_tid, cascade_id = :new_cid;
Because UUIDv4 strings have a fixed 36-byte wire length in protobuf length-delimited fields, replacing the exact 36 ASCII bytes of old_cid and old_tid inside trajectory_metadata_blob.data preserves every surrounding varint length prefix without pulling in generated protobuf schemas. Pairing that cloned .db with a matching slice of transcript.jsonl in brain/<new_cid> lets agy --conversation <new_cid> resume or branch with 100% recall of prior turns.
Asking side questions without polluting context: /btw
Sometimes you don't want to fork or steer the main agent at all: you just want to ask "Wait, why did we use O_NOFOLLOW here?" or "What port does the test server bind?" while the main agent keeps compiling. Sending that question into the main chat interrupts flow and permanently inflates prompt-cache tokens on every subsequent turn.
Rudder's /btw Side Question panel (cloud/worker/btw.mjs + cloud/app/btw-panel.js) runs an ephemeral, read-only query grounded in the workspace's recent transcript and repository root with --no-session-persistence, displaying the answer in a collapsible right-hand drawer. Your main agent's trajectory stays untouched, and if an insight from the side panel turns out to be actionable, one click on Send to chat promotes it into the composer.
Never get stranded by a single provider's rate limit.
Start a feature in Claude Opus, hand off mid-turn to Codex or Gemini in the same workspace when quota runs out, and branch or edit any prompt from Mac or iPhone.
$ npm install -g @exla/rudder@latest