Metadata-Version: 2.1
Name: ctxtrim
Version: 0.1.0
Summary: Zero-dependency, deterministic context middleware for coding agents: shrink tool outputs before they hit the context, audit them for prompt injection, and prove it with a tamper-evident log.
Author: The ctxtrim Authors
License: MIT
Project-URL: Homepage, https://github.com/ctxtrim/ctxtrim
Project-URL: Issues, https://github.com/ctxtrim/ctxtrim/issues
Keywords: llm,agents,context-window,token,prompt-injection,mcp,claude-code,developer-tools
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Filters
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev

# ctxtrim

**Shrink tool outputs before they hit your agent's context — deterministically, auditably, with zero dependencies.**
**在工具输出进入 agent 上下文之前把它瘦身——确定性、可审计、零依赖。**

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Python 3.9+](https://img.shields.io/badge/python-3.9%2B-blue.svg)](pyproject.toml)
[![Tests](https://github.com/jsk-hash/ctxtrim/actions/workflows/ci.yml/badge.svg)](.github/workflows/ci.yml)
[![Dependencies](https://img.shields.io/badge/dependencies-0-success.svg)](pyproject.toml)

![ctxtrim terminal demo](docs/demo.gif)

---

## Why / 为什么

Coding agents burn their context window on redundant tool output: 50 repeated
build lines, 3,000-line unchanged diffs, base64 blobs, pretty-printed JSON.
That means slower agents, higher bills, and worse answers. Existing tools fix
this with proxies and runtimes tied to one agent.

ctxtrim is the missing **library**: pure functions your tool, MCP server, or
agent harness calls before handing text to an LLM. Same input → same output,
every time. Every saved character is accounted for, rule by rule. And because
tool output is untrusted input, ctxtrim also **audits it** for prompt
injection and hidden payloads, and keeps a **tamper-evident log** of what
entered the context.

编码 agent 的上下文窗口被冗余的工具输出吃掉:重复 50 遍的构建日志、3000 行未变更的
diff、base64 大块、格式化过的 JSON。结果是 agent 更慢、更贵、回答更差。现有方案
都是绑定单一 agent 的代理或运行时。

ctxtrim 补上缺失的**库**这一层:你的工具、MCP server、agent harness 在把文本交给
LLM 之前调用它。相同输入必得相同输出,每个字符的去向都有逐条规则留痕。工具输出是
不可信输入,ctxtrim 顺带**审计**提示注入与隐藏载荷,并保存**防篡改日志**。

## Quick start / 快速开始

```bash
pip install ctxtrim        # or: pip install git+https://github.com/ctxtrim/ctxtrim
```

```bash
# shrink a tool output (deterministic, rule-by-rule trail on stderr)
$ ctxtrim shrink build.log --profile balanced
[... compressed output ...]
---
ctxtrim: 1759 -> 372 chars (78.9% saved, 1 strategies)

# respect a hard budget (lossy cut only as a last resort)
$ ctxtrim shrink huge.json --budget 2000 --profile tight

# audit untrusted text before it enters your agent's context
$ ctxtrim audit untrusted.txt
ctxtrim audit: risk score 60/100
  [HIGH] instruction-override x1 lines=3 — Text asks the model to ignore its instructions...

# share one context budget across several tool outputs
$ ctxtrim split --names log,db --need build.log --need db.json --total 4000

# prove later that nothing was edited
$ ctxtrim verify journal.jsonl
journal OK: 3 record(s)
```

### MCP server / 作为 MCP 服务器运行

`ctxtrim serve` speaks MCP (newline-delimited JSON-RPC over stdio), so any
MCP client can call ctxtrim as tools — add one block to your client config:

```json
{ "mcpServers": { "ctxtrim": { "command": "ctxtrim", "args": ["serve"] } } }
```

Tools exposed: `ctxtrim_shrink`, `ctxtrim_audit`, `ctxtrim_split`.

```bash
# or from source
python -m ctxtrim.mcp_server
```

```python
from ctxtrim import compress, audit, allocate_pairs, Journal

res = compress(tool_output, budget=2000, profile="balanced")
res.ratio          # 0.483 — chars saved
res.trail()        # per-strategy accounting, exactly what ran
res.text           # still valid JSON if the input was JSON

findings = audit(untrusted_text)          # prompt-injection & payload heuristics
budgets = allocate_pairs(["log", "db"], [len(a), len(b)], 4000)

Journal("journal.jsonl").append(kind="shrink",
                                input_sha256=sha256(tool_output),
                                output_sha256=sha256(res.text))
```

## Benchmarks / 基准

`python tools/benchmark.py` (bundled & synthetic workloads, budget=2000):

| workload | original | ctxtrim | saved | still parses as JSON |
|---|---:|---:|---:|---|
| build_log.txt | 1,759 | 372 | **78.9%** | — |
| tool_output.json | 3,696 | 1,911 | **48.3%** | ✅ yes |
| test_runner_output | 58,199 | 40,847 | **29.8%** | — |
| diff_400ctx | 13,177 | 323 | **97.5%** | — |

Deterministic end-to-end; the 67-test suite includes a byte-level determinism check.

## How it works / 工作原理

Strategies run in a fixed order; each one is optional and reports its own
savings. Lossless-ish strategies run always; the lossy head/tail cut runs
only under a budget, only in the `tight` profile.

| # | strategy | what it does | lossy? |
|---|---|---|---|
| 1 | blob_placeholder | replaces giant base64/hex runs (>1200 chars) with `[ctxtrim blob N chars sha256=…]` | no* |
| 2 | json_compact | drops null/empty fields, trims arrays to head-10+tail-10 with an elision marker, truncates giant string values — **output stays valid JSON** | near-lossless |
| 3 | log_dedupe | collapses runs of ≥3 identical consecutive lines to `line + [ctxtrim repeat xN]` | no |
| 4 | ws_normalize | strips trailing spaces, collapses blank-line runs, dedents common indent | no |
| 5 | diff_collapse | collapses >8-line runs of unchanged diff context to 3+marker+3 | no* |
| 6 | head_tail | cuts to budget keeping 70% head / 30% tail with an elision marker | **yes** |

Profiles: `safe` (1–4, never loses content), `balanced` (1–5, default),
`tight` (1–6, budget-aware).

\* elided content is replaced by a SHA-256 digest + exact byte count, so the
omission is explicit, not silent.

### Audit rules / 审计规则

`ctxtrim audit` scans untrusted text with deterministic heuristics (regex
only, no model calls): instruction-override phrasing, role hijacking,
spoofed system/chat-template tags, `curl … | sh` style exfiltration,
destructive commands, credential-shaped literals, hidden/bidi Unicode,
large encoded blobs. Findings carry severity, line numbers and a hint.
**Heuristics raise attention; they are not a security guarantee** — that
honesty is part of the design.

### Journal / 审计日志

`Journal` appends JSONL records where each record's SHA-256 covers the record
and the previous record's hash. `verify()` walks the whole chain and reports
exactly which record was edited or removed. Stdlib only, greppable, diffable.

## Security posture / 安全姿态

- **Zero runtime dependencies** — nothing to hijack in a supply chain; CI fails if `dependencies` stops being `[]`.
- **No network, no process spawning, no dynamic execution** — `eval/exec/compile/__import__/subprocess/socket/urllib/pickle/ctypes` are banned from `src/` and a dedicated test enforces it.
- **Deterministic transforms** — reviewed line by line; no model-in-the-loop rewriting of your content.
- See [SECURITY.md](SECURITY.md) for the threat model and reporting policy.

## Comparison / 与同类项目的差异

| | proxies / runtimes (rtk, headroom…) | meme tools | **ctxtrim** |
|---|---|---|---|
| integration | binds to one agent/workflow | chat-only | **embeddable library + standalone CLI** |
| transform | varies, often model-assisted | lossy joke | **deterministic rules, per-rule trail** |
| reproducibility | not guaranteed | no | **same input → same output, tested** |
| injection auditing | no | no | **built-in heuristics** |
| tamper evidence | no | no | **hash-chained journal** |
| dependencies | many | varies | **zero (stdlib only)** |

Complementary, not competitive: use ctxtrim *inside* whatever harness you run.

## Requirements / 环境

Python 3.9 – 3.13, any OS. Nothing else.

## Roadmap / 路线图

- [x] MCP server wrapper (`ctxtrim serve`) exposing shrink/audit/split as tools
- [ ] Claude Code hook recipe (one-file integration guide)
- [ ] pluggable custom strategies via entry points
- [ ] optional token-accurate budgeting (tokenizer adapters, still optional deps)
- [ ] `--report html` static audit report

## Contributing / 参与

PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). Every PR runs the full
suite including the source-security self-audit.

## License / 协议

[MIT](LICENSE) — the most permissive mainstream license. Use it, fork it,
ship it.

## Acknowledgements / 致谢

The problem statement was validated by the 2025–2026 wave of context-cost
tools (rtk, headroom, context-mode, caveman & friends). ctxtrim takes the
idea to the library layer with determinism and auditability as first-class
citizens.
