{
  "markdown": "# lossless-context-mcp\n\n[![CI](https://github.com/NORTHTEKDevs/lossless-context-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/NORTHTEKDevs/lossless-context-mcp/actions/workflows/ci.yml)\n\n**The flight recorder for your agent's context.** A persistent, hook-fed ledger of every\nfile version your coding agent was shown — so a compaction can't destroy the working set,\na subagent fleet doesn't pay for the same files N times, and you can *prove* afterward\nexactly what the model saw.\n\n```\n                      ┌──────────────────────┐\n  ledger reads ──────▶│                      │──▶ RESTORE   working set survives /compact\n  (read_file, MCP)    │   flight recorder    │──▶ PACKS     one cache-cached prefix for a fan-out fleet\n  transcript sweeps ─▶│  (content-addressed  │──▶ RECEIPTS  signed, git-bound \"what did it see\"\n  (native Read/Edit)  │   archive on disk)   │──▶ METERING  where the read tokens went, in dollars\n                      └──────────────────────┘\n```\n\n## See it\n\n**Compaction destroys your agent's working set. Not anymore** — sweep at PreCompact,\nmanifest injected after, blind edit *blocked*, working set restored, edit allowed:\n\n![restore demo](docs/demo/restore.gif)\n\n**Two agents, one file — air traffic control.** The second agent is stopped mid-clobber,\nwith the culprit named:\n\n![coordination demo](docs/demo/coordination.gif)\n\nEvery line in these recordings is genuine output from the shipped code — the demos are\ngenerated by [`docs/demo/make-demo.mjs`](docs/demo/make-demo.mjs), which drives the real\nhooks and server and renders what they actually said. Re-run it yourself.\n\n## 1. Restore: compaction can't destroy your working set anymore\n\nWhen Claude Code compacts, roughly two-thirds of a typical context is tool output —\nmostly file contents — and compaction discards it permanently. The model then flails:\nre-reading files it half-remembers, or worse, guessing at contents it no longer has\n([#27242](https://github.com/anthropics/claude-code/issues/27242) is the ask, at 80 👍).\n\nThe flight recorder closes the loop automatically:\n\n1. **PreCompact** — the sweep hook parses the session transcript and archives every file\n   the session touched (native `Read`/`Edit`/`Write` included, not just MCP reads), then\n   writes a ranked working-set manifest. Fast enough to sit on the compaction path — one\n   real 14 MB transcript swept in 361 ms; measure yours:\n   `node bench/sweep-bench.mjs <transcript.jsonl>`.\n2. **SessionStart(compact)** — the inject hook puts a compact manifest back into the\n   fresh context: *\"your working set was these 12 files (edited ones first); restore any\n   of them instead of guessing.\"*\n3. **`restore_context`** — re-emits the working set from current disk state,\n   budget-capped, annotating any file that changed since the model last saw it.\n\nCross-*session* memory tools (claude-mem and friends) summarize what happened for the\nnext session. This is the complementary, mid-session layer: **file-version-exact recovery\nof what you were just working on.**\n\n## 2. Blind-edit guard: the recorder as an active safety net\n\nThe recorder knows exactly which file versions the model has actually seen this context\nepoch. A `PreToolUse` hook uses that to stop the two ugliest edit failures *before the\nwrite lands*:\n\n- **Post-compaction guess-edits** — the model edits a file it hasn't read since its\n  context was compacted/reset, working from a summary's memory of the content. (The\n  harness's own read-before-edit tracking is not documented to survive compaction, and\n  newer models are allowed to edit unread files at all.) Denied, with a one-line reason\n  the model sees: *read it (or restore_context), then retry.* Self-healing — costs\n  exactly one extra read.\n- **Stale-base edits** — the file changed on disk since the model read it (another\n  agent, you, a formatter). Content-hash compared, not mtime-guessed. Denied with the\n  same re-read instruction.\n\nFail-open by construction: any doubt (unparseable transcript, partial reads, files the\nmodel itself just edited, oversized files) → the edit proceeds untouched. Disable\nanytime with `LOSSLESS_GUARD=off`.\n\n## 3. Coordination: air traffic control for concurrent agents\n\nRun two agent sessions on one repo and they clobber each other blind: B edits a file A\nread ten minutes ago; A edits from its stale copy; the merge is garbage and neither\nnotices. Nothing on the market mediates this locally — but the recorder already knows,\nper session, what each agent holds and edits. v2 makes that knowledge active:\n\n- **Edit-in-flight detection** — when one agent process is allowed an edit, it publishes\n  an intent to a local presence plane (`~/.lossless-context/presence/`, one file per\n  process, no daemon, no locks). Another agent editing the same file seconds later is\n  denied with the culprit named: *\"agent session 3f2a91b0 started an edit on this file\n  12s ago and it may not have landed yet.\"* Covers sibling subagents of the same\n  session too.\n- **Cross-session stale-base detection** — when another session's landed edit postdates\n  what your session holds and your last contact left no verifiable hash, the edit is\n  denied with a re-read instruction. When the ordinary drift check fires, the reason now\n  *names who changed the file*.\n- **The radar** — `coordination_status` shows every visible agent session, what it's\n  been editing, and which files have cross-session or in-flight activity.\n\nHonest limits: advisory, not locking. Sessions without the hooks are invisible, a\nsame-second race can still slip through, and presence files are unauthenticated local\nJSON — any local process could fabricate one to cause false *denies* (structurally never\na false allow; presence can only add deny classes). An intent whose edit is then declined\nat the permission prompt lingers up to `LOSSLESS_COORD_INTENT_SECS` (90 s) before\nexpiring. It substantially narrows the concurrent-clobber window; it cannot close it, and\nhow much it catches in practice is not yet measured. `LOSSLESS_COORD=off` disables\ncoordination independently of the guard. (The guard's compaction tracking is\nsession-scoped; only the dedup engine uses the machine-global epoch file, where a\ncross-session bump merely costs one conservative full re-send.)\n\n## 4. Packs: stop paying for the same files in every subagent\n\nFan-outs are where token waste actually lives. Measured across 195 real multi-agent runs:\n**19.6% of all subagent `Read` tokens were duplicate reads of identical content by sibling\nagents** (5.18M of 26.4M tokens) — every sibling starts cold and reads the same CLAUDE.md,\nthe same spec, the same core modules.\n\n`export_pack` ranks the archive's cross-session read history for stable hot files and\nrenders them as one deterministic block for a custom agent-type's **system prompt**. The\nblock is a stable prefix, so the whole fleet hits the provider prompt cache on it. On a\nreal review fan-out this measured **46.55% cheaper** than baseline — and the same pack\ninjected per-task measured 19.6% *worse* (every sibling cache-writes it), which is why\nthe tool tells you where to put it. Both numbers were measured externally on one real\ncorpus, not by a harness in this repo — exact figures, method, and that caveat are in\n[BENCHMARK.md](./BENCHMARK.md). Generate the pack once per run and embed it verbatim:\nranking follows live read history, so repeated `export_pack` calls can differ.\n\n## 5. Blame: what did the agent see when it did that?\n\n`context_blame` (also a CLI: `lossless-context-mcp blame <path>`) answers the debugging\nquestion every agent incident report wishes it could: for a given file, every content\nversion the model was shown (SHA-256 + git blob SHA-1, first/last seen, capture source,\nsessions) and what else was in context around a chosen moment. When an agent produces a\nwrong change, you query the recording instead of arguing with the agent's self-report.\n\n## 6. Receipts: prove what the model saw, bound to git\n\nObservability vendors capture what your agent read into mutable trace stores. Nobody\nsigns it or binds it to repo identity — and agent self-reports are not evidence (ask\nanyone whose agent claimed it \"verified\" something it never read).\n\n`context_receipt` issues an HMAC-SHA256-signed attestation: every file/view shown, the\nSHA-256 of every content version, **the git blob SHA-1 of each version** (so any verifier\nwith a clone can check `git cat-file -e <sha1>` — was this ever committed?), **repo HEAD\nat issue time**, delivery kinds, token totals, and an explicit `coverage` statement of\nwhich capture paths it attests (`mcp`, and `transcript-sweep` with `include_sweep`). By\ndefault it signs with the same key file as trust-mcp receipts, so one key verifies a full\nevidence chain: *what the agent saw + what it did*.\n\n**The honest scope**: a receipt attests what passed through the ledger and sweeps — it\nnever claims coverage of unmediated paths, and says so in its own `coverage.note`.\n\n## 7. Metering (and the token-saver reality check)\n\n`context_stats` shows where the session's file-read tokens went — per repo, per file, in\ndollars, counted with a real tokenizer.\n\n> **Reality check, kept from earlier versions because it's true:** as an intra-session\n> token saver this measures **~0%** on real Claude Code transcripts (+0.4% with the\n> never-lose engine; the native file-state cache already ate the opportunity — full data\n> in [BENCHMARK.md](./BENCHMARK.md)). The savings that DO exist are cross-agent (packs,\n> above). Read-path dedup remains because it is provably lossless and never negative —\n> not because it will save you much on its own.\n\n## Install (two commands)\n\n```bash\nnpm i -g lossless-context-mcp\nlossless-context-mcp init        # wires all hooks into ~/.claude/settings.json\nclaude mcp add lossless-context --scope user -- lossless-context-mcp\n```\n\n`init` is idempotent (re-run it after upgrades — it updates paths instead of\nduplicating), backs up your settings file first, refuses to touch a settings file it\ncan't parse, and never removes hooks that aren't its own. `--dry-run` previews. It wires:\n\n- `sweep-transcript.mjs` (PreCompact + SessionEnd) — captures the working set + exact\n  versions; bumps the dedup epoch on PreCompact; never blocks compaction.\n- `inject-manifest.mjs` (SessionStart, matcher `compact`) — injects the recovered\n  working-set manifest after a compaction.\n- `reset-epoch.mjs` (SessionStart) — keeps read dedup lossless across new sessions.\n- `guard-edit.mjs` (PreToolUse, `Edit|Write|MultiEdit`) — the blind-edit guard\n  (`LOSSLESS_GUARD=off` disables without unwiring).\n\nRestart Claude Code after init. Without the hooks everything still works — you just lose\nautomatic native-tool capture, post-compaction injection, and the guard; the ledger then\nrecords MCP reads only.\n\n## Tools\n\n| Tool | What it does |\n|------|--------------|\n| `read_file(path, symbol?, lines?, force_full?)` | Lossless read: full / unchanged-marker / diff. Optional single-`symbol` or `lines:\"40-90\"` views. Refuses binary files. |\n| `read_files(paths[], force_full?)` | A working set in one call; per-file errors don't fail the batch. |\n| `working_set(limit?)` | Heat-ranked table of what the recorder knows this session (+ last 24h), with staleness vs disk. |\n| `restore_context(files?, budget_tokens?)` | Re-emit the working set after compaction — manifest top-K by default, budget-capped, change-annotated. |\n| `export_pack(repo?, top?, budget_tokens?, days?)` | Deterministic fan-out context pack from cross-session read history, for an agent-type system prompt. |\n| `context_blame(path, at?, window_minutes?)` | Forensics: every version of a file the model was shown, plus co-context around a moment. Also: `lossless-context-mcp blame <path>` from the shell. |\n| `coordination_status()` | The radar: visible agent sessions, their recent edits, cross-session and in-flight files. |\n| `outline(path)` | Cheap structural map of a file (declarations only). |\n| `context_stats()` | Token/dollar breakdown of this session's reads. |\n| `context_receipt(artifact, include_sweep?)` | Signed, git-bound context receipt with explicit coverage. |\n| `verify_context_receipt(receipt, signature)` | Timing-safe, canonicalized verification. |\n\n## Privacy & storage\n\nThe archive lives at `~/.lossless-context/archive` (override: `LOSSLESS_CONTEXT_DIR`),\ncontent-addressed, capped at 512 MiB (`LOSSLESS_ARCHIVE_BYTES`) with LRU eviction; event\nlogs age out after 30 days (`LOSSLESS_EVENTS_DAYS`). **Nothing ever leaves your machine.**\nFiles matching secret patterns (`.env*`, keys/certs, `.ssh`/`.aws` paths, credentials —\nplus your own `LOSSLESS_ARCHIVE_EXCLUDE` globs) are *never* stored — the check covers\nboth the requested path and its resolved real path, so a symlink to a secret doesn't\nbypass it. For excluded files only the path, touch counts, and timestamps are recorded\n(no content, and no content-derived metadata like hashes or sizes, which could enable\noffline confirmation of low-entropy secrets).\n\n## Why the read path can't hurt quality\n\nThe engine only withholds or diffs content it can **prove** the model still has, bounded\nby context epochs (the hooks bump the epoch on compaction, so post-compaction reads are\nalways full). A 400-op randomized invariant test asserts the model's reconstructable view\nequals disk truth after every operation. Anything less provable is sent in full.\n\n## Honest limits\n\n- Restore serves **current disk state** (annotated when it drifted), not a time machine\n  of the conversation; exact historical versions live in the archive for receipts.\n- The transcript format is internal to Claude Code and can change; the sweep is\n  deliberately two-tier (stable-surface discovery + best-effort exact capture) and\n  fail-silent — a format change degrades capture, never breaks a session.\n- Receipts attest mediated paths only, and say so; they are HMAC (shared-key), not\n  third-party-verifiable signatures — Ed25519 receipts are a candidate for a future\n  version if anyone needs them.\n- Pack effectiveness assumes provider prompt caching and a stable prefix; the 46.55%\n  figure is one measured workload, not a promise.\n- Symbol extraction is a heuristic brace/indent pass, not a parser (tree-sitter was\n  evaluated and deferred for WASM/ABI fragility).\n\n## Status\n\n**v2.0.0** — the coordination plane, on top of the full flight recorder: persistent\ncontent-addressed archive, transcript sweep + manifest inject hooks, working-set\nrestore, fan-out packs, git-bound receipts v2, one-command `init`, the blind-edit\nguard, context blame, and cross-agent coordination (in-flight intents, landed-edit\nconflicts, the `coordination_status` radar). 121 tests green including the losslessness\ninvariant; over-the-wire smoke covers sweep → inject → restore → guard → coordination →\nreceipts; real-transcript sweep and guard runs validated on live data. MIT.\n",
  "bytes": 14883,
  "sha": "9e584b5a1ef1ee8c0461d77fb209951ad0637650aed54497e9e141806cefbc4d",
  "repo_slug": "northtekdevs/lossless-context-mcp",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_northtekdevs_lossless_context__b1947ef1/readme"
}