[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-92463":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":8,"htmlUrl":8,"language":9,"languages":8,"totalLinesOfCode":8,"stars":10,"forks":11,"watchers":12,"openIssues":13,"contributorsCount":14,"subscribersCount":14,"size":14,"stars1d":14,"stars7d":14,"stars30d":15,"stars90d":14,"forks30d":14,"starsTrendScore":14,"compositeScore":16,"rankGlobal":8,"rankLanguage":8,"license":17,"archived":18,"fork":18,"defaultBranch":19,"hasWiki":20,"hasPages":18,"topics":21,"createdAt":8,"pushedAt":8,"updatedAt":22,"readmeContent":23,"aiSummary":24,"trendingCount":14,"starSnapshotCount":14,"syncStatus":25,"lastSyncTime":26,"discoverSource":27},92463,"context-warp-drive","dogtorjonah\u002Fcontext-warp-drive","dogtorjonah",null,"TypeScript",62,8,51,1,0,4,40.26,"MIT License",false,"main",true,[],"2026-07-22 04:02:06","# Context Warp Drive\n\n[![CI](https:\u002F\u002Fgithub.com\u002Fdogtorjonah\u002Fcontext-warp-drive\u002Factions\u002Fworkflows\u002Fci.yml\u002Fbadge.svg)](https:\u002F\u002Fgithub.com\u002Fdogtorjonah\u002Fcontext-warp-drive\u002Factions\u002Fworkflows\u002Fci.yml) [![license: MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Flicense-MIT-blue.svg)](.\u002FLICENSE) [![GitHub stars](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Fstars\u002Fdogtorjonah\u002Fcontext-warp-drive?style=social)](https:\u002F\u002Fgithub.com\u002Fdogtorjonah\u002Fcontext-warp-drive)\n\n**Stop summarizing your agent's memory.** Every compaction call burns a model round-trip, rewrites your prefix so the provider prompt cache goes cold, and quietly drops the exact identifiers your agent needs. Fold it deterministically instead.\n\n> **92.6% cache-read hit rate** across 954 tool calls in a 1h49m agent marathon. **−60% cost vs truncation, −70% vs summarization.** Zero extra LLM calls. Every number measured from the provider's own usage ledger — not estimated.\n\n**The Infinite Context Warp Engine.** Keep long function-calling agent sessions under the context window **without LLM summarization calls** and **without ending the session** — while keeping provider prompt caches **hot** — and page folded content back in the moment the agent touches it again.\n\nDeterministic. Zero-LLM. Pure CPU, zero I\u002FO, byte-identical output for identical inputs. Provider-agnostic: **Anthropic** content blocks, **OpenAI** `tool_calls`, and **Gemini** `parts`.\n\nExtracted from a production multi-agent system, where it folds context continuously across every model and long-running agent workloads.\n\n- The core engine passes **380+ deterministic tests** across rolling fold, recall, freeze, and integration.\n- Every number below is **measured, not estimated** — production cache rates from the Claude provider usage ledger, reproducible live against Claude (`ANTHROPIC_API_KEY=… npx tsx examples\u002Fbenchmark-live.ts`, real model + real summarizer) and offline with exact `o200k_base` BPE token counts (`npx tsx examples\u002Fbenchmark.ts`, deterministic, no key).\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Provenance note\u003C\u002Fstrong> (click to expand)\u003C\u002Fsummary>\n\nThis public package is production-derived. It is the portable distribution of an engine that runs live inside a private multi-agent system, so it deliberately uses generic `WARP_*` environment names, package-neutral examples, raw-history recovery wording, and tool-agnostic voice mining. The byte-identical invariant is local to this package — identical inputs produce identical folded views — and is not a claim of bit-for-bit parity with any private integration layer.\n\u003C\u002Fdetails>\n\n---\n\n## Performance & Economics\n\n### Measured in production — real Claude workloads, provider cache telemetry\n\nThe numbers that matter are from the production multi-agent system this engine powers — real Claude workloads running the fold\u002Ffreeze engine continuously across **hundreds of turns**, measured from the provider's own usage ledger (cache-read tokens ÷ total input tokens):\n\n| Production Claude workload | Measured turns | Cache-read hit | Fresh input | Cache-read input |\n| :--- | :---: | :---: | :---: | :---: |\n| Opus 4.8 agent | 691 | **89.6%** | 32.9M tok | 292.6M tok |\n| Opus agent | 510 | **93.2%** | 32.6M tok | 602.5M tok |\n\n**~90% of all input tokens are served from cache** across these high-turn Claude workloads — that is the byte-identical frozen-fold prefix doing its job, turn after turn, at $0.30\u002FMTok cache reads instead of $3.00\u002FMTok fresh input (Sonnet rates). A re-summarizing compactor rewrites the prefix and can never sustain this; truncation slides the window and breaks it. This is the entire economic argument, measured live.\n\n**Note on scope:** the table above is live single-deployment production telemetry, not a controlled A\u002FB study — there is no held-out arm running truncation or summarization against the same real workload for a head-to-head comparison. The offline\u002Flive benchmarks below fill that gap deterministically on a small session; a larger-scale controlled long-horizon comparison across strategies is future work, gated on compute budget, not on the mechanism being unproven.\n\n### Reproduce it yourself — live, against Claude\n\n```bash\nANTHROPIC_API_KEY=sk-ant-... npx tsx examples\u002Fbenchmark-live.ts   # default claude-sonnet-4-6\n```\n\nReal Claude calls every turn with Anthropic `cache_control` breakpoints, a **real Claude summarizer** (told to preserve every identifier — a fair fight), and the provider's own `cache_read_input_tokens` \u002F `cache_creation_input_tokens`. A short 16-turn demo *understates* the production cache rate (caching needs a ≥1024-token prefix and CWD's advantage compounds over long sessions) — but it shows the mechanism on real telemetry, with CWD reading from cache while truncation and summarization rebuild their prefix.\n\n### Offline deterministic demo (no API key, byte-identical every run)\n\n`npx tsx examples\u002Fbenchmark.ts` — a 16-turn outage-debugging session, exact `o200k_base` BPE token counts (a portable proxy; Claude's tokenizer isn't public), `claude-sonnet-4-6` list pricing — the same workhorse tier as the production table above, not a cheap demo tier. This is the CI smoke test; the summarizer is a transparent deterministic stand-in (it drops ids buried past its head cutoff — the failure mode the Coordinate Closet exists to avoid).\n\n| Strategy | Input Cost | Extra LLM Calls | Fact Retention |\n| :--- | :---: | :---: | :---: |\n| Truncation (rolling window) | $0.0516 | 0 | 44% (7\u002F16) |\n| LLM Summarization (stand-in) | $0.0685 | 6 | 44% (7\u002F16) |\n| **Context Warp Drive** | **$0.0208** | 0 | **94% (15\u002F16)** |\n\nCWD is cheapest (**−70% vs summarization, −60% vs truncation** at Claude-sonnet rates — the ratio holds across tiers since Anthropic's cache discount is model-invariant), makes zero extra model calls, and beats truncation decisively on retention. (A well-prompted *real* summarizer can match retention at higher cost — CWD's durable edge is cost + zero calls + determinism + a hot cache.) The engine is provider-agnostic: set `WARP_BENCH_MODEL` (and `WARP_BENCH_PRICE_*` for an unlisted model) to benchmark against any model, including OpenAI or a cheaper Claude tier.\n\n### How it compares to LLM-based memory tools\n\n| | **Context Warp Drive** | **Mem0** | **Letta (MemGPT)** | **Zep (Graphiti)** |\n|---|---|---|---|---|\n| **Approach** | Deterministic fold | LLM extraction + vector DB | LLM-managed 3-tier memory | LLM extraction + knowledge graph |\n| **Extra LLM calls** | **0** | Per memory operation | Per memory decision | Per entity extraction |\n| **Prompt cache impact** | **Stays hot** (byte-identical prefix) | Invalidated (rewritten prefix) | Invalidated | Invalidated |\n| **Runtime deps** | **Zero** (core engine) | Vector DB required | Full agent runtime replacement | Neo4j + LLM + embeddings |\n| **Provider support** | Anthropic · OpenAI · Gemini | Multi (SDK wrappers) | Python only | Python only |\n| **License** | MIT | Apache 2.0 | Apache 2.0 | Apache 2.0 |\n\nEvery funded competitor uses LLM calls to extract, summarize, or manage memory. Context Warp Drive is the only deterministic approach — zero model calls, zero latency, zero cache invalidation.\n\n---\n\n## Try it in 5 minutes\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fdogtorjonah\u002Fcontext-warp-drive.git\ncd context-warp-drive && npm install\nnpx tsx examples\u002Fbenchmark.ts    # no API key needed — deterministic, byte-identical every run\n```\n\nFor the live benchmark with real Claude calls and provider cache telemetry:\n\n```bash\nANTHROPIC_API_KEY=sk-ant-... npx tsx examples\u002Fbenchmark-live.ts\n```\n\n---\n\n## Why\n\nEvery long agent session hits the same wall: the context window fills up. The usual answers are bad:\n\n- **Truncation** drops the middle of your history — the agent forgets what it was doing.\n- **LLM summarization (\"compaction\")** costs a model call, adds latency, is non-deterministic, and **busts your provider prompt cache** every time it rewrites the prefix.\n\nContext Warp Drive does neither. It **deterministically folds** old turns into compact structural skeletons (one line per tool call + retained reasoning), **conserves the salient exact identifiers** (UUIDs, SHAs, paths, ports) in a budget-scored Coordinate Closet, **freezes** the folded prefix so it's reused byte-identical while the provider cache is warm, and **pages folded content back in** automatically when the agent re-touches a path. No model calls. No truncation. Cache stays hot.\n\n---\n\n## Install\n\nNot published on npm yet. Install from source today:\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fdogtorjonah\u002Fcontext-warp-drive.git\ncd context-warp-drive\nnpm install        # runs `prepare` -> builds dist\u002F automatically\n# optional — only for the reference SQLite episode store:\nnpm install better-sqlite3\n```\n\nThe core (`context-warp-drive\u002Ffold`) has **zero runtime dependencies**. `better-sqlite3` is an optional peer needed only by the reference episodic store.\n\n\u003Cdetails>\n\u003Csummary>Local tarball \u002F future npm install\u003C\u002Fsummary>\n\n`dist\u002F` is gitignored, so build before consuming the package from another project. For a local package install:\n\n```bash\nnpm run build      # explicit fallback\nnpm pack\n# from your consuming project:\nnpm install \u002Fpath\u002Fto\u002Fcontext-warp-drive\u002Fcontext-warp-drive-*.tgz\n```\n\nAfter the first npm publish, installation becomes:\n\n```bash\nnpm install context-warp-drive\n```\n\n\u003C\u002Fdetails>\n\n---\n\n## If you ask an AI to wire it in\n\nPaste this:\n\n> Add `context-warp-drive` from the source checkout or local tarball, then wrap our function-calling message history with `FoldSession.prepare()` before each model call. Preserve raw history separately; send only the prepared `messages` view to the provider. Use `cacheHot` and `stats` for logging.\n\nThen add the provider cache knob:\n\n| Provider | What to do |\n|---|---|\n| Claude \u002F Anthropic | Use `prepareAnthropicCachedRequest()` from `context-warp-drive\u002Fproviders\u002Fanthropic` with `messages`, `sealedBoundary`, `system`, and `tools`. It marks the relay-style breakpoints: tools, stable system head, sealed fold\u002Frebirth boundary, and rolling tail. Default TTL is Anthropic's 5-minute cache shape; pass `ttl: '1h'` only when you want the paid 1-hour cache and merge the returned `requestOptions`\u002F`anthropicBeta` into your SDK or fetch call. Log `usage.cache_read_input_tokens` and `usage.cache_creation_input_tokens`. |\n| OpenAI | No cache marker is required. Keep static tools\u002Fsystem\u002Fcontext first, pass the prepared `messages`, optionally reuse a stable `prompt_cache_key`, and log `usage.prompt_tokens_details.cached_tokens`. |\n| Gemini | Implicit caching is automatic on Gemini 2.5+ when prefixes match. For a large static document\u002Fcorpus, create an explicit Gemini cache separately and pass it as `cachedContent`; keep the folded conversation after that stable prefix. Log `usage_metadata`. |\n| Gemini CLI | Use `context-warp-drive\u002Fproviders\u002Fgemini-cli` to fold the CLI-owned JSONL view, preserving the metadata header and rewriting with `$set.messages` + `$set.lastUpdated`. |\n| Codex CLI | Use `context-warp-drive\u002Fproviders\u002Fcodex-cli` to rebuild a folded Responses item seed for `thread\u002Finject_items` from canonical transcript rows. |\n| Claude Code CLI | Use `context-warp-drive\u002Fproviders\u002Fclaude-cli` to build a folded Claude Code JSONL chain and atomically rewrite `~\u002F.claude\u002Fprojects\u002F\u003Cencoded-cwd>\u002F\u003Csession-id>.jsonl` before `claude --resume`. |\n\nContext Warp Drive keeps the prefix byte-identical. The provider SDK call still owns provider-specific cache settings.\n\n---\n\n## Quickstart\n\n```ts\nimport { FoldSession } from 'context-warp-drive';\n\n\u002F\u002F One per conversation. Folds past the active window + keeps the provider cache hot.\nconst session = new FoldSession();\n\n\u002F\u002F Your full provider-shaped history (Anthropic \u002F OpenAI \u002F Gemini message objects).\nconst history = [\n  { role: 'user', content: 'Investigate the failing test in src\u002Fparser.ts' },\n  \u002F\u002F ... grows every turn ...\n];\n\n\u002F\u002F Every turn, before you call the model:\nconst { messages, cacheHot, stats } = session.prepare(history, {\n  \u002F\u002F Optional but recommended: pass real provider\u002Frelay input-token telemetry\n  \u002F\u002F from the previous turn. At 240k by default, FoldSession forces a fresh\n  \u002F\u002F fold epoch instead of hot-reusing into an oversized prompt.\n  measuredInputTokens: previousUsage?.input_tokens,\n});\n\n\u002F\u002F `messages` is the compacted view to send. When `cacheHot` is true the prefix is\n\u002F\u002F byte-identical to last turn, so the provider prompt cache is reused.\nawait callYourModel(messages); \u002F\u002F Anthropic \u002F OpenAI \u002F Gemini — the message shapes pass through unchanged\nconsole.log(`sent ${messages.length} msgs · cacheHot=${cacheHot} · savings=${stats.savingsPercent ?? 0}%`);\n```\n\nThat's the whole headline. For continuous always-lean folding, pass `ALWAYS_ON_FOLD_CONFIG`; to match your provider's real cache TTL, set `freeze: { enabled: true, ttlMs: 3_600_000, maxTailChars: 150_000 }`. The measured-token pressure guard defaults to `DEFAULT_FOLD_PRESSURE_CEILING_TOKENS` (240,000); pass `pressureCeiling: false` to disable it or `pressureCeiling: 120_000` to tune it.\n\nSee [`examples\u002Fanthropic-loop.ts`](.\u002Fexamples\u002Fanthropic-loop.ts) and [`examples\u002Fopenai-loop.ts`](.\u002Fexamples\u002Fopenai-loop.ts) for full tool loops.\n\n---\n\n### Hard-epoch rebirth seed parity\n\n`FoldSession.prepare()` includes the portable hard-epoch path used by the Voxxo relay: it replaces the provider-visible view with one deterministic rebirth seed message, merges the triggering live user turn exactly once, and reseals that compact seed as the next frozen prefix. It fires automatically when real measured input tokens reach `pressureCeiling`; a harness can also force the same path directly:\n\n```ts\nconst outcome = session.prepare(history, {\n  hardEpoch: true,\n  hardEpochSeed: renderMyHostRebirthPackage(), \u002F\u002F optional; omitted = raw trace seed\n  measuredInputTokens: previousUsage?.input_tokens,\n});\n```\n\nFor Anthropic, feed `outcome.sealedBoundary` to the provider helper every turn:\n\n```ts\nimport { prepareAnthropicCachedRequest } from 'context-warp-drive\u002Fproviders\u002Fanthropic';\n\nconst cached = prepareAnthropicCachedRequest({\n  messages: outcome.messages as AnthropicMessage[],\n  sealedBoundary: outcome.sealedBoundary,\n  system: SYSTEM_PROMPT,\n  tools: TOOLS,\n});\n\nawait client.messages.create(\n  { model, max_tokens: 8192, ...cached.request },\n  cached.requestOptions,\n);\n```\n\n**Bounded is what makes it boundless.** A hard epoch collapses the *provider-visible* view to one compact seed message — it does not discard anything. The raw transcript remains recall backing: fold recall (§4 below) keeps paging folded\u002Fpre-epoch content back in the moment the agent re-touches a path, a claim, or a prior identifier, exactly as it does for an ordinary rolling fold. That's the actual mechanism behind \"long-horizon\": the window itself never grows past its ceiling, so it stays cheap and cache-friendly turn after turn, while forward momentum — what the agent was doing, what it touched, what it decided — survives the reset because recall and episodic memory read from the untouched raw trace, not from the collapsed view. The engine is deliberately bounded; that boundedness is what lets a session run indefinitely instead of eventually blowing the context window.\n\nParity checklist for a custom harness:\n\n- Keep raw history append-only and pass the full raw trace to `prepare()`.\n- Use measured provider token telemetry for `measuredInputTokens`; do not estimate pressure from characters.\n- For intentional same-instance rebirth\u002Freset, pass `hardEpoch: true` plus your rendered host seed, or let the package compute the raw seed from `history`.\n- Persist host-only context such as task rails, file claims, workspace state, chat, and episode cards yourself, then pass those sections into `renderRawRebirthSeed()` when you need relay-like wake text.\n- Keep clone\u002Fmodel-specific identity deltas out of the stable cached prefix. The Anthropic helper splits the system prompt before `## Your Identity` by default; for cheaper clone fanout, put shared seed text before that marker and append per-model deltas after the cached baseline.\n\n---\n\n## Model-aware budgets — `context-warp-drive\u002Fbudget`\n\nUse the budget resolver when you want Warp Drive tuned to the real model window instead of a one-size-fits-all fold line. It knows common provider\u002Fmodel families (Claude, OpenAI\u002FCodex API, Codex CLI, Gemini, GLM, Grok, Mistral, MiniMax, DeepSeek, Kimi, Qwen) and lets new\u002Funknown models opt in with an explicit measured\u002Fconfigured window.\n\n```ts\nimport { resolveContextBudget } from 'context-warp-drive\u002Fbudget';\n\nconst sonnet = resolveContextBudget({ engine: 'claude', model: 'claude-sonnet-4' });\n\u002F\u002F 200k survival profile: tighter pressure ceiling, full-recompute-only eviction.\n\nconst codexCli = resolveContextBudget({ engine: 'codex', model: 'gpt-5.5' });\n\u002F\u002F Codex CLI\u002FOAuth path uses its effective 258k input cap, not the Codex API 1M window.\n\nconst arbitraryModel = resolveContextBudget({\n  engine: 'my-provider',\n  model: 'new-million-context-model',\n  contextWindowTokens: 1_000_000,\n  targetBandTokens: 150_000,\n});\n```\n\nBudget outputs are mechanical ceilings and knobs: `contextWindowTokens`, `messageCeilingTokens`, `pressureCeilingTokens`, `prefixSaturationTokens`, `bandTokens`, `tailEpochCapTokens`, compression profile, and eviction policy. Token pressure uses supplied\u002Fmeasured token telemetry or explicit model windows — it does **not** infer live token pressure from character counts.\n\n---\n\n## Portable Task Rail — `context-warp-drive\u002Ftask-rail`\n\nLong-horizon agents need more than memory compression: they need an execution spine that survives folding, rebirth, process restarts, or a custom UI. The Task Rail export is a pure state machine for plan steps, sprint\u002Fshoot execution, ACKs, progress, and JSON serialization.\n\nIt is deliberately **not** a tool server. No MCP wrapper, no relay persistence, no squad permissions, no chat\u002FAtlas coupling. You own the wrapper: CLI, MCP, browser UI, local JSON, SQLite, or your own agent runtime.\n\n```ts\nimport {\n  startTaskRail,\n  sprint,\n  ackStep,\n  shoot,\n  serializeTaskRail,\n  restoreTaskRail,\n} from 'context-warp-drive\u002Ftask-rail';\n\nconst rail = startTaskRail({\n  title: 'Ship the feature',\n  objective: 'Keep execution state outside the prompt.',\n  locked: true,\n  steps: [\n    { instruction: 'Inspect the failing path.' },\n    { instruction: 'Patch the smallest correct surface.' },\n    { instruction: 'Validate and write the handoff.' },\n  ],\n});\n\nconst batch = sprint(rail, { sprintCount: 2 });\nackStep(rail, batch.steps![0].id, 'done', { evidence: 'source read' });\nconst next = shoot(rail);\n\nconst saved = JSON.stringify(serializeTaskRail(rail));\nconst restored = restoreTaskRail(JSON.parse(saved));\n```\n\nPair it with FoldSession like this: raw transcript stays in your storage, folded prompt view stays lean, and task rail tracks what the agent is supposed to do next.\n\n> **Draft operations** (`TASK_RAIL_DRAFT_OPERATIONS`, `TaskRailDraft`, conflict\u002Fmerge types) are exported for parity with the full-featured relay wrapper. The draft *types* are here; the merge *engine* lives in the relay-side wrapper. If you need collaborative draft merging, build it on the exported types — the pure state machine only handles locked-rail execution.\n\nSee [`examples\u002Ftask-rail.ts`](.\u002Fexamples\u002Ftask-rail.ts) for a full runnable walkthrough (start → sprint → ack → shoot → serialize → restore, zero dependencies).\n\n## Raw rebirth seed — `context-warp-drive\u002Fraw-rebirth-seed`\n\nWhen a long-running agent chooses a hard epoch, it needs a deterministic wake seed that is computed from the trace, not summarized by a model. The raw rebirth seed renderer exposes that package shape directly: Last User + AI Messages, Current Thread, Raw Trace Coordinate Closet, Active Edit Delta, Task Rail, Activity Log, workspace context, and the orientation footer, with the same default section budgets and allocation priority used by the relay-style hard epoch.\n\n```ts\nimport { buildRawRebirthSeedFromMessages } from 'context-warp-drive\u002Fraw-rebirth-seed';\n\nconst seed = buildRawRebirthSeedFromMessages(history, {\n  predecessorName: 'agent-before-reset',\n  includeTrailingUserTurn: false,\n  workspaceContext: {\n    currentCwd: process.cwd(),\n    currentWorkspace: 'my-agent-runtime',\n  },\n});\n```\n\n`FoldSession` uses this renderer automatically when a pressure hard epoch fires and you do not pass `hardEpochSeed`. If your host has richer trace sections, call `renderRawRebirthSeed()` and pass those strings explicitly. See [`docs\u002Fraw-rebirth-seed.md`](.\u002Fdocs\u002Fraw-rebirth-seed.md) for exact parity boundaries and copy-paste examples.\n\n---\n\n## How it works\n\n### 1. Rolling fold (page-out) — `foldContext`\nFrom the active window backward, every prior turn skeletonizes into one line per tool call (`$ cmd → ok`, `read path`, …) plus budgeted retained reasoning. Only the newest turns stay at full fidelity. The fold is a synthetic user+assistant pair with a self-documenting preamble; it never mutates your raw history (it returns a *view*).\n\n**\"Turn\" is looser than it sounds — long agentic work folds per step, not per user message.** A conversational turn only ends at real user text (`isUserTurnBoundary`); a long single-prompt agentic rail — one kickoff, hundreds of tool-call steps, no further user text — is structurally ONE turn. `planActiveTurnStepFold` detects that marathon pattern and re-segments the oversized active turn at agentic-step boundaries (each assistant tool-call + its result), so `foldContext` can skeletonize the OLD steps of a still-open turn while the newest N steps stay full-fidelity. This is what keeps a long-horizon single-turn agent session bounded without waiting for a user message that may never come.\n\n### 2. Coordinate Closet — exact-value conservation\nFolded turns are skeletonized, **but their exact identifiers are not paraphrased**. `nominateVerbatim` extracts UUIDs, long hashes, absolute paths, digit-bearing key\u002Fvalues (`port=3002`), and issue refs, and conserves them in a `Coordinate Closet (conserved from folded turns): …` block. Opaque ids carry a deterministic context label (`7fd5835b ⟦changelog_id⟧`). A separate capped lane conserves identifiers from operator-pasted user text too.\n\n### 3. Fold freeze (cache-hot reuse) — `evaluateFoldFreeze`\nThe folded prefix is **frozen** and reused **byte-identical** between epochs, so new turns just append to the raw tail and the provider prompt cache stays warm. It only recomputes at an epoch: first call, cold TTL gap, raw-tail cap exceeded, a thinning\u002Fclaim change, or a boundary rewrite. **Maximizing the hot-reuse ratio is the entire point of deterministic folding** — a re-summarizing compactor can never do this.\n\n### 4. Fold recall (ambient page-in) — `buildFoldRecallContext`\nA page table (`buildFoldIndex`) tracks everything the fold paged out. When activity proves relevance — you touch a path again, or claim a file — the folded content **pages back in** as a budgeted recall card, appended append-only onto the freeze tail (cache stays hot) and re-folded at the next epoch. Fully cyclic, with residency TTLs so cards don't thrash.\n\n### 5. Episodic recall (durable cross-session memory) — `context-warp-drive\u002Fepisodes`\nBeyond the in-session fold, sealed work **episodes** (the files touched + the agent's verbatim conclusions) persist to a local store and are recalled by path the next time any session touches a member file. Turnkey portable store included (`createEpisodeStore`, SQLite); the advanced chain-card\u002Fnarration engine ships namespaced as `richEpisodes`.\n\n### 6. Glyph grammar (register tags) — `context-warp-drive\u002Fglyphs`\nEvery agent message opens with one register glyph — 🔍 in-progress · ▶ executing · 🏁 verdict · ⚠️ hazard · ❓ blocked. `parseRegisterGlyph` classifies it; episodic recall uses it as a trust signal so only **settled** conclusions (🏁\u002F⚠️) get harvested into durable memory while transient work (🔍\u002F▶\u002F❓) self-excludes. See [`docs\u002Fglyph-grammar.md`](.\u002Fdocs\u002Fglyph-grammar.md).\n\n### 7. Context budget (model-aware mechanical limits) — `context-warp-drive\u002Fbudget`\nThe budget resolver turns model\u002Fengine\u002Fwindow choices into deterministic fold knobs: active band, message ceiling, pressure ceiling, prefix saturation, tail epoch cap, and compression\u002Feviction profile. Known model tables cover common providers, while explicit `contextWindowTokens` lets any new model opt in without waiting for a package release.\n\n### 8. Task Rail (portable execution state) — `context-warp-drive\u002Ftask-rail`\nTask Rail is the dependency-free long-horizon execution state machine. It tracks steps, sprint\u002Fshoot reservations, ACK status, progress, and JSON serialization so your own tool\u002FUI\u002Fstorage can preserve “what next?” outside the provider prompt.\n\n---\n\n## Provider-agnostic by design\n\nThe engine reads three message shapes natively — pass your history through unchanged:\n\n| Provider | Shape |\n|---|---|\n| Anthropic | `{ role, content: string \\| ContentBlock[] }` with `tool_use` \u002F `tool_result` blocks |\n| OpenAI (+ DeepSeek, Kimi, GLM, Mistral, Grok, MiniMax) | `{ role, content, tool_calls }` + `{ role: 'tool', tool_call_id }` |\n| Gemini | `{ role: 'model', parts: [...] }` with `functionCall` \u002F `functionResponse` |\n\n> **FC APIs and supported CLI transports.** Context Warp Drive folds the\n> *conversational message array* you control directly. For CLI\u002Fagent runtimes\n> that own their own context, use the dedicated provider packs below.\n\nCLI fold packs mirror the Voxxo relay seams for owned-history runtimes:\n`context-warp-drive\u002Fproviders\u002Fgemini-cli` rewrites Gemini CLI JSONL `$set.messages`,\n`context-warp-drive\u002Fproviders\u002Fcodex-cli` emits folded Responses items for\n`thread\u002Finject_items`, and `context-warp-drive\u002Fproviders\u002Fclaude-cli` builds and\nwrites a uuid-linked Claude Code JSONL chain for `claude --resume`.\n\nFor Claude Code, the runnable setup layer is\n`context-warp-drive\u002Fhost\u002Fclaude-cli-loop`. It spawns\n`claude --print --input-format stream-json --output-format stream-json`, learns\nthe session id from the stream, tracks Anthropic-reported usage tokens, computes\ntail vs hard-epoch folds, atomically rewrites the Claude Code project JSONL, and\nrespawns with `--resume \u003Csession-id>`. Use `mode: 'dry-run'` to write a\n`\u003Csession>.jsonl.dryrun` sidecar before letting it touch the live file.\n\n```bash\nnpx tsx examples\u002Fclaude-cli-loop.ts \u002Fpath\u002Fto\u002Fproject\nWARP_CLAUDE_CLI_FOLD=dry-run npx tsx examples\u002Fclaude-cli-loop.ts\n```\n\nIf you want the normal Claude Code terminal UI instead of `--print`, use\n`context-warp-drive\u002Fhost\u002Fclaude-tmux-loop`. It starts plain interactive\n`claude` inside tmux, gives you an attach command, tails\n`~\u002F.claude\u002Fprojects\u002F...\u002F\u003Csession>.jsonl`, folds from provider-measured usage,\nrewrites the JSONL, and restarts the tmux session with `--resume`.\n\n```bash\nnpx tsx examples\u002Fclaude-tmux-loop.ts \u002Fpath\u002Fto\u002Fproject\nWARP_CLAUDE_TMUX_FOLD=dry-run npx tsx examples\u002Fclaude-tmux-loop.ts\n```\n\n---\n\n## API surface\n\n```ts\n\u002F\u002F Core fold engine (zero deps) — also at \"context-warp-drive\u002Ffold\"\nimport {\n  FoldSession,           \u002F\u002F the orchestrator (fold + freeze)\n  DEFAULT_FOLD_PRESSURE_CEILING_TOKENS,\n  foldContext,           \u002F\u002F rolling fold (page-out)\n  ALWAYS_ON_FOLD_CONFIG, DEFAULT_FOLD_CONFIG, type FoldConfig, type FoldMessage, type FoldResult,\n  evaluateFoldFreeze, commitFoldFreeze, createFoldFreezeState, \u002F\u002F freeze layer\n  buildFoldIndex, extractRecallSignals, buildFoldRecallContext, \u002F\u002F recall layer\n  nominateVerbatim, detectTurns,\n} from 'context-warp-drive';\n\n\u002F\u002F Episodic recall — also at \"context-warp-drive\u002Fepisodes\"\nimport {\n  deriveEpisodesFromMessages, recordEpisodes, recallEpisodeCards, \u002F\u002F portable store\n  createEpisodeStore,                                              \u002F\u002F SQLite reference (needs better-sqlite3)\n  richEpisodes,                                                    \u002F\u002F advanced chain-card engine (namespaced)\n} from 'context-warp-drive';\n\n\u002F\u002F Glyph grammar — also at \"context-warp-drive\u002Fglyphs\"\nimport { parseRegisterGlyph, REGISTER_GLYPHS, classifyAssistantRegister } from 'context-warp-drive';\n\n\u002F\u002F Model-aware fold\u002Fpressure knobs — also at \"context-warp-drive\u002Fbudget\"\nimport { resolveContextBudget } from 'context-warp-drive';\n\n\u002F\u002F Fold provenance receipts — digest-only trust boundary for prepared views\nimport { buildPrepareReceipt, verifyPrepareReceipt } from 'context-warp-drive';\n\n\u002F\u002F Portable execution state — also at \"context-warp-drive\u002Ftask-rail\"\nimport { startTaskRail, sprint, shoot, ackStep, serializeTaskRail } from 'context-warp-drive';\n\n\u002F\u002F Gemini CLI JSONL folding adapter\nimport {\n  buildGeminiCliFoldView,\n  readLatestGeminiCliMeasuredTokens,\n  writeFoldedGeminiCliJsonl,\n} from 'context-warp-drive\u002Fproviders\u002Fgemini-cli';\n\n\u002F\u002F Codex CLI fold seed for thread\u002Finject_items\nimport { buildCodexFoldItems } from 'context-warp-drive\u002Fproviders\u002Fcodex-cli';\n\n\u002F\u002F Claude Code CLI JSONL folding adapter\nimport {\n  buildClaudeCliFold,\n  writeFoldedClaudeCliJsonl,\n} from 'context-warp-drive\u002Fproviders\u002Fclaude-cli';\n\n\u002F\u002F Claude Code CLI setup loop: spawn, monitor measured usage, fold, rewrite, resume\nimport { ClaudeCliFoldLoop } from 'context-warp-drive\u002Fhost\u002Fclaude-cli-loop';\n\n\u002F\u002F Claude Code interactive tmux loop: normal terminal UI, JSONL tail, fold, resume\nimport { ClaudeTmuxFoldLoop } from 'context-warp-drive\u002Fhost\u002Fclaude-tmux-loop';\n```\n\n### Claude Code CLI setup loop\n\n```ts\nimport { ClaudeCliFoldLoop } from 'context-warp-drive\u002Fhost\u002Fclaude-cli-loop';\n\nconst loop = new ClaudeCliFoldLoop({\n  cwd: process.cwd(),\n  sessionId: process.env.CLAUDE_SESSION_ID, \u002F\u002F optional; learned from stream-json when omitted\n  model: process.env.CLAUDE_MODEL ?? 'claude-sonnet-4-6',\n  mode: process.env.WARP_CLAUDE_CLI_FOLD === 'dry-run' ? 'dry-run' : 'on',\n  authMode: process.env.CLAUDE_CODE_OAUTH_TOKEN ? 'oauth' : 'inherit',\n  onEpoch: (epoch) => console.error(epoch.reason),\n});\n\nawait loop.start();\nawait loop.sendUserText('Continue the current task.');\n```\n\nThe loop only folds from provider-measured usage telemetry. If you already keep\nyour own canonical transcript, pass `transcript: async () => rows` and\n`captureTranscript: false`; otherwise the loop captures user text, assistant text,\ntool calls, and tool results from Claude Code's stream-json events.\n\n### Claude Code interactive tmux loop\n\n```ts\nimport { ClaudeTmuxFoldLoop } from 'context-warp-drive\u002Fhost\u002Fclaude-tmux-loop';\n\nconst loop = new ClaudeTmuxFoldLoop({\n  cwd: process.cwd(),\n  sessionId: process.env.CLAUDE_SESSION_ID, \u002F\u002F optional; otherwise discovered from JSONL\n  model: process.env.CLAUDE_MODEL ?? 'claude-sonnet-4-6',\n  mode: process.env.WARP_CLAUDE_TMUX_FOLD === 'dry-run' ? 'dry-run' : 'on',\n  authMode: process.env.CLAUDE_CODE_OAUTH_TOKEN ? 'oauth' : 'inherit',\n  onSpawn: (info) => console.error(info.attachCommand),\n});\n\nawait loop.start();\n```\n\nThis loop does not pass `--print`; the user attaches to tmux and uses Claude Code\nnormally. Context Warp observes the on-disk JSONL transcript, so an unwrapped\nClaude process can still be observed by your own code, but automatic kill\u002Frewrite\nresume requires the wrapper to own the tmux session.\n\n---\n\n## Environment switches\n\nAll optional; sensible defaults. `WARP_FOLD_FREEZE` (freeze on\u002Foff) · `WARP_FOLD_FREEZE_TTL_MS` · `WARP_FOLD_FREEZE_MAX_TAIL_CHARS` · `WARP_FOLD_RECALL` · `WARP_FOLD_RECALL_MAX_CARDS` · `WARP_FOLD_RECALL_VERBATIM` · `WARP_FOLD_TARGET_BAND_TOKENS` · `WARP_FOLD_TRIGGER_TOKENS` · `WARP_FOLD_EPISODES_*`. Full table in [`docs\u002Fcontext-folding.md`](.\u002Fdocs\u002Fcontext-folding.md) §8.\n\n---\n\n## Documentation\n\n- [`docs\u002Fcontext-folding.md`](.\u002Fdocs\u002Fcontext-folding.md) — the authoritative engine reference (what folds, Coordinate Closet, freeze epochs, recall, episodic, env switches, source map).\n- [`docs\u002Farchitecture.md`](.\u002Fdocs\u002Farchitecture.md) — how the layers compose and how to wire them into any FC loop.\n- [`docs\u002Fglyph-grammar.md`](.\u002Fdocs\u002Fglyph-grammar.md) — the register-glyph contract and why it powers episodic narration.\n- [`docs\u002Ffold-provenance.md`](.\u002Fdocs\u002Ffold-provenance.md) — prepare receipts: sha256 provenance artifacts that make the deterministic fold\u002Ffreeze invariant externally attestable and give downstream agents a `safe_to_resume`\u002F`stale` verdict without replaying private raw history.\n\n## Tests\n\n```bash\nnpm test   # runs the 380+ test deterministic suite (rolling fold, freeze, recall, task rail)\n```\n\n## JonahT © Jonah Tarashansky\n","Context Warp Drive 是一个用于长上下文管理的轻量级 TypeScript 库，专为函数调用型 AI 代理（function-calling agents）设计。它通过确定性字节级折叠（folding）而非 LLM 摘要或截断来压缩历史上下文，在不触发额外大模型调用的前提下，将长会话维持在模型上下文窗口内；支持 Anthropic、OpenAI 和 Gemini 等主流提供商的原生消息格式，保持提示缓存热度并实现零成本召回。适用于需持续多轮工具调用、高缓存命中率与严格成本控制的生产级 AI 代理系统。",2,"2026-07-09 02:30:05","CREATED_QUERY"]