trimtok 4.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trimtok-4.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 P Choke & MIKA
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
trimtok-4.1.0/PKG-INFO ADDED
@@ -0,0 +1,451 @@
1
+ Metadata-Version: 2.4
2
+ Name: trimtok
3
+ Version: 4.1.0
4
+ Summary: Deterministic, lossless-retrievable context compression for autonomous AI agents and MCP clients
5
+ Author: P Choke & SORA
6
+ License-Expression: MIT
7
+ Keywords: mcp,ai-agents,context-compression,token-optimization,cli,sqlite
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: msgspec>=0.18.0
21
+ Requires-Dist: rapidfuzz>=3.0.0
22
+ Requires-Dist: tiktoken>=0.7.0
23
+ Requires-Dist: zstandard>=0.22.0
24
+ Provides-Extra: fast
25
+ Requires-Dist: tiktoken>=0.7.0; extra == "fast"
26
+ Requires-Dist: rapidfuzz>=3.9.0; extra == "fast"
27
+ Requires-Dist: jiter>=0.5.0; extra == "fast"
28
+ Requires-Dist: msgspec>=0.18.0; extra == "fast"
29
+ Requires-Dist: zstandard>=0.22.0; extra == "fast"
30
+ Dynamic: license-file
31
+
32
+ <div align="center">
33
+
34
+ # trimtok
35
+
36
+ **Universal, Local, Deterministic Context Compressor for AI Coding Agents & IDEs**
37
+
38
+ <p><em>88.3% fewer characters across heavy engineering workloads — zero intelligence lost, every byte recoverable in sub-millisecond time.</em></p>
39
+
40
+ <p>
41
+ <a href="#performance--benchmarks"><img src="docs/badges/latency.svg" alt="Latency" /></a>
42
+ <a href="#core-engineering-guarantees"><img src="docs/badges/dependencies.svg" alt="100% Local & Offline" /></a>
43
+ <a href="#content-addressed-context-recovery-ccr"><img src="docs/badges/safety.svg" alt="Fail-open" /></a>
44
+ <a href="#quick-start"><img src="docs/badges/ecosystem.svg" alt="MCP · CLI · Hermes" /></a>
45
+ <a href="LICENSE"><img src="docs/badges/license.svg" alt="License" /></a>
46
+ </p>
47
+
48
+ <p>
49
+ <a href="#why-trimtok">Why trimtok</a> ·
50
+ <a href="#visual-before--after-showcase">Before / After</a> ·
51
+ <a href="#quick-start">Quick Start</a> ·
52
+ <a href="#how-the-dual-stage-pipeline-works">How It Works</a> ·
53
+ <a href="#content-addressed-context-recovery-ccr">CCR Recovery</a> ·
54
+ <a href="#architecture--modules">Architecture</a> ·
55
+ <a href="#performance--benchmarks">Performance</a> ·
56
+ <a href="#configuration--cli-reference">Configuration</a> ·
57
+ <a href="#recommended-ecosystem-combo">Trinity Combo</a>
58
+ </p>
59
+
60
+ </div>
61
+
62
+ ---
63
+
64
+ ## Why trimtok?
65
+
66
+ Autonomous coding agents burn 60%–85% of their context window on **high-volume, low-entropy noise**: 2,000-line passing `pytest` runs, deep framework stack frames (`site-packages`, `node_modules`), unchanged `git diff` context lines, repetitive `grep` matches, and deeply nested JSON tool responses.
67
+
68
+ Naive truncation (`head -n 50` or character slicing) destroys critical failure signals hidden in the middle of logs. Summarizing via a secondary LLM adds seconds of latency and risks hallucinating line numbers or error codes.
69
+
70
+ **trimtok** solves this deterministically, 100% locally and offline, in **~1–2 ms**:
71
+
72
+ - **Stage 1 — Terminal Pipeline (`compress_terminal`):** Strips ANSI/spinner artifacts, prunes intermediate framework stack frames while preserving entrypoints and crash sites, condenses unchanged `git diff` context while keeping file headers and `@@` hunk scopes, folds exact and Drain-template log repeats, and turns repeated test/build commands into a compact **Cross-Turn Stateful Delta**.
73
+ - **Stage 2 — Tool & Code Pipeline (`compress_tool_result`):** Deduplicates repeated spans across turns, groups multi-file `grep` hits under enclosing `def`/`class` scopes, condenses large source files via **AST Code Skeletonization** (keeping imports, signatures, type annotations, and docstrings while folding function bodies), and transcodes nested JSON payloads into lossless **Hierarchical TOON Tables** verified by an in-memory round-trip check.
74
+ - **Safety Rail — Content-Addressed Context Recovery (`CCR`):** Every compressed payload stores its exact, unmodified original in a global SQLite WAL + Zstandard store (`~/.trimtok`), addressable by a short Base62 `#c1` alias with instant section slicing (`errors`, `diff`, `summary`, `tail`), safe regex grep, or full restoration.
75
+
76
+ > [!IMPORTANT]
77
+ > **Zero Intelligence Loss Invariant:** Every error, exception, traceback crash site, compiler diagnostic, HTTP 5xx status, and Thai/English failure line is locked by fault polarity rails (`is_important`) and is **never** dropped or folded away. If any transformation fails to strictly reduce both character count and BPE token count, `trimtok` immediately reverts to the untouched original string.
78
+
79
+ <p align="center">
80
+ <img src="docs/architecture-dark.svg" alt="trimtok architecture" width="100%" />
81
+ </p>
82
+
83
+ ---
84
+
85
+ ## Visual Before & After Showcase
86
+
87
+ ### 1. Cross-Turn Stateful Command Delta (`delta_engine.py`)
88
+ When an agent runs `pytest` a second time after editing code (even with shifted line numbers, updated timings, or flag changes like `pytest -v` vs `pytest -q`):
89
+
90
+ <table>
91
+ <tr>
92
+ <th width="50%">Raw Terminal Output (56,108 chars)</th>
93
+ <th width="50%">trimtok Compressed Output (312 chars — 99.4% saved)</th>
94
+ </tr>
95
+ <tr>
96
+ <td>
97
+
98
+ ```text
99
+ ============================= test session starts =============================
100
+ platform win32 -- Python 3.12.4, pytest-8.3.2, pluggy-1.5.0
101
+ rootdir: /workspace/app
102
+ collected 201 items
103
+
104
+ tests/test_auth.py ............................ [ 13%]
105
+ tests/test_db.py ...................................................... [ 40%]
106
+ tests/test_api.py ..................................................... [ 67%]
107
+ ... (1,950 lines of passing test output & noisy INFO logs) ...
108
+ ================================== FAILURES ===================================
109
+ __________________________________ test_boom __________________________________
110
+ def test_boom():
111
+ > assert compute_status() == 1
112
+ E AssertionError: expected 1 got 2
113
+ =========================== short test summary info ===========================
114
+ FAILED tests/test_1000.py::test_boom - AssertionError: expected 1 got 2
115
+ ======================== 1 failed, 200 passed in 43.2s ========================
116
+ ```
117
+
118
+ </td>
119
+ <td>
120
+
121
+ ```text
122
+ [tt:delta cmd="pytest -q" sim=99% +#1 -#1 !#1 #c2 #c1]
123
+ [tt:legend] Delta vs previous run of the same command: + added, - resolved/removed, ! still failing; refs = full snapshots via trimtok_retrieve.
124
+ --- STILL FAILING / ACTIVE ERRORS (1) ---
125
+ ! FAILED test_1000.py::test_boom - AssertionError: expected 1 got 2
126
+ --- ADDED / CHANGED IN THIS TURN (+1) ---
127
+ + ===== 1 failed, 200 passed in 43.2s =====
128
+ --- RESOLVED / REMOVED (-1) ---
129
+ - ===== 1 failed, 200 passed in 42.1s =====
130
+ ```
131
+
132
+ </td>
133
+ </tr>
134
+ </table>
135
+
136
+ ### 2. Lossless Hierarchical TOON JSON Transcoding (`toon_codec.py`)
137
+ Verbose JSON arrays and API responses are unnested via dot-notation, common URL/path prefixes are factored into `@prefix`, and every table is decoded in-memory to verify recursive strict equality (`_strict_eq`) before emission:
138
+
139
+ <table>
140
+ <tr>
141
+ <th width="50%">Raw JSON Tool Payload</th>
142
+ <th width="50%">Lossless TOON Table (74.3% fewer tokens)</th>
143
+ </tr>
144
+ <tr>
145
+ <td>
146
+
147
+ ```json
148
+ {
149
+ "meta": {"status": "success"},
150
+ "data": {
151
+ "results": [
152
+ {
153
+ "id": 0,
154
+ "title": "Item 0",
155
+ "url": "https://example.com/items/0",
156
+ "tags": ["dev", "lead"]
157
+ },
158
+ {
159
+ "id": 1,
160
+ "title": "Item 1",
161
+ "url": "https://example.com/items/1",
162
+ "tags": ["qa"]
163
+ },
164
+ {
165
+ "id": 2,
166
+ "title": "Item 2",
167
+ "url": "https://example.com/items/2",
168
+ "tags": ["pm", "ops"]
169
+ }
170
+ ]
171
+ }
172
+ }
173
+ ```
174
+
175
+ </td>
176
+ <td>
177
+
178
+ ```text
179
+ [tt:legend] TOON table (lossless): "@prefix(A)=base" = shared path shorthand; "@rows[N]{f1,f2}:" header, then N rows, cells split by "|" (quoted = literal).
180
+ @prefix(~/)=https://example.com/items/
181
+ @meta:{"status":"success"}
182
+ @data.results[3]{id,title,url,tags}:
183
+ 0|Item 0|~/0|["dev","lead"]
184
+ 1|Item 1|~/1|["qa"]
185
+ 2|Item 2|~/2|["pm","ops"]
186
+ ```
187
+
188
+ </td>
189
+ </tr>
190
+ </table>
191
+
192
+ ### 3. Structured Traceback Pruning & AST Code Skeletonization (`pruners.py`)
193
+ Deep stack traces collapse intermediate library frames (`site-packages`, `node_modules`) while keeping 100% of the entrypoint, user project frames, crash frame, and exception line. Large source files keep class/function signatures, type annotations, and docstrings while folding long implementation bodies:
194
+
195
+ ```text
196
+ Traceback (most recent call last):
197
+ File "/app/main.py", line 25, in handle_request
198
+ result = pipeline.process(data)
199
+ [... 14 framework frames in site-packages/starlette & fastapi omitted ...]
200
+ File "/app/pipeline.py", line 58, in process
201
+ return 100 / count
202
+ ZeroDivisionError: division by zero
203
+ ```
204
+
205
+ ---
206
+
207
+ ## Quick Start
208
+
209
+ ### 1. Universal One-Command Auto-Install (Recommended)
210
+
211
+ Install `trimtok` and automatically register its stdio MCP server across every supported AI agent CLI and IDE on your machine:
212
+
213
+ ```bash
214
+ pip install trimtok
215
+ trimtok install
216
+ ```
217
+
218
+ `trimtok install` detects and atomically updates:
219
+ - **Claude Code** (`~/.claude.json` via `claude mcp add-json`) & **Claude Desktop** (`claude_desktop_config.json`)
220
+ - **Google Antigravity & Antigravity IDE** (`~/.gemini/config/mcp_config.json`, `~/.gemini/antigravity/mcp_config.json`)
221
+ - **Gemini CLI** (`~/.gemini/settings.json`) & **Codex CLI** (`~/.codex/config.toml` with TOML validation)
222
+ - **Cursor** (`~/.cursor/mcp.json`), **Windsurf**, **VS Code (Copilot)**, **OpenCode**, and **Cline**
223
+
224
+ > [!TIP]
225
+ > Every client config edit creates an automatic backup (`.pre-mcp-install.bak`) and preserves all existing MCP servers. Run `trimtok clients` anytime to inspect registration status across your machine.
226
+
227
+ ### 2. Standalone CLI Usage
228
+
229
+ ```bash
230
+ # Inspect compression savings and global CCR cache health (~/.trimtok)
231
+ trimtok status
232
+
233
+ # View telemetry breakdown by command shape and retrieval hit rates
234
+ trimtok usage
235
+
236
+ # Compress any noisy log or file directly from shell pipelines
237
+ cat build.log | trimtok compress
238
+ trimtok compress --file pytest_output.txt
239
+
240
+ # Retrieve uncompressed originals or targeted sections by #cN alias
241
+ trimtok retrieve "#c1"
242
+ trimtok retrieve "#c1" --section errors
243
+ trimtok retrieve "#c1" --section diff
244
+
245
+ # Purge expired or all cached originals and vacuum SQLite store
246
+ trimtok purge
247
+ ```
248
+
249
+ ### 3. Hermes Agent Native Plugin
250
+
251
+ ```bash
252
+ # Linux / macOS
253
+ git clone https://github.com/Stxyu-p/trimtok.git ~/.hermes/plugins/trimtok
254
+
255
+ # Windows (PowerShell)
256
+ git clone https://github.com/Stxyu-p/trimtok.git "$env:LOCALAPPDATA\hermes\plugins\trimtok"
257
+
258
+ hermes plugins enable trimtok
259
+ ```
260
+
261
+ ---
262
+
263
+ ## How the Dual-Stage Pipeline Works
264
+
265
+ ```mermaid
266
+ flowchart TD
267
+ In(["Raw Terminal / Tool Output"]) --> SizeGate{"Size >= min_chars<br/>(default 2 KB)?"}
268
+ SizeGate -- "No" --> Pass["Passthrough Untouched"]
269
+ SizeGate -- "Yes" --> Verbatim{"Verbatim Reference Tool?<br/>(e.g. read_file)"}
270
+ Verbatim -- "Yes" --> IndexOnly["Index Spans for Future Turns<br/>& Return Verbatim"]
271
+ Verbatim -- "No" --> StageRoute{"Pipeline Stage"}
272
+
273
+ StageRoute -- "Terminal Output" --> S1["Stage 1: Terminal Pipeline<br/>• Strip ANSI & spinners<br/>• Prune framework tracebacks<br/>• Fold unchanged git diff context<br/>• Drain template & exact repeat fold<br/>• 2-Stage Fuzzy Command Delta"]
274
+ StageRoute -- "Tool / JSON / Code" --> S2["Stage 2: Tool Pipeline<br/>• Scoped grep grouping by def/class<br/>• AST Code Skeletonization<br/>• Cross-turn span & 3-gram dedup<br/>• Lossless TOON JSON transcoding"]
275
+
276
+ S1 --> Gates{"Safety & Quality Gates<br/>1. 100% Fault Lines Preserved?<br/>2. BPE Tokens Strictly Reduced?<br/>3. Within guard_ms Deadline?"}
277
+ S2 --> Gates
278
+
279
+ Gates -- "Any Gate Fails" --> Pass
280
+ Gates -- "All Gates Pass" --> CCR["Store Original in ~/.trimtok<br/>(SQLite WAL + Zstandard)<br/>& Emit Compressed + #cN Ref"]
281
+ ```
282
+
283
+ ### Core Engineering Guarantees
284
+
285
+ | Guarantee | Mechanism |
286
+ | :--- | :--- |
287
+ | **Zero Intelligence Loss** | Error, exception, traceback crash site, HTTP 5xx, and Thai/English failure lines (`signals.py`) are locked by fault rails and never folded or dropped. |
288
+ | **BPE Non-Inflation Gate** | Every candidate output is checked via `estimate_bpe_tokens()`. If compression does not strictly reduce both character count and token count, `trimtok` returns the original input. |
289
+ | **Verbatim File-Edit Safety** | Direct file-reading tools (`read_file`, `view_file`) are indexed into the session corpus to compress *future* duplicate search results, but their own output is returned 100% verbatim so code-editing tools never operate on line stubs. |
290
+ | **Lossless TOON Round-Trip** | `toon_codec.py` decodes every generated columnar table back into Python objects in memory and verifies strict recursive type-and-value equality (`_strict_eq`) before emitting. |
291
+ | **Fail-Open Deadline Guard** | A monotonic `Deadline` timer (`guard_ms`, default `50 ms`) bounds every stage. Any timeout or unexpected exception immediately returns the untouched original text. |
292
+ | **Cross-Turn Freshness Masking** | `post_llm_call` automatically ages out fold pointers older than `mask_keep_turns` (default `2` turns) so the agent never references stale turn stubs. |
293
+
294
+ ---
295
+
296
+ ## Content-Addressed Context Recovery (CCR)
297
+
298
+ Whenever `trimtok` compresses an output, the full unmodified original is persisted in the global **CCR Store** (`~/.trimtok/trimtok_ccr_v2.sqlite3`) using SQLite WAL mode and Zstandard payload compression.
299
+
300
+ ### `trimtok_retrieve` Modes (MCP & CLI)
301
+
302
+ | Retrieval Mode | MCP Arguments | What It Returns |
303
+ | :--- | :--- | :--- |
304
+ | **Section: Errors** | `{"hash": "#c1", "section": "errors", "context_lines": 3}` | Scans original via `is_important()`, merges overlapping `±context_lines` windows, and returns `line_no\|text` fault chunks. |
305
+ | **Section: Diff** | `{"hash": "#c1", "section": "diff", "context_lines": 3}` | Extracts unified diff file headers, `@@` hunk scopes, and `+`/`-` changes with surrounding context. |
306
+ | **Section: Summary** | `{"hash": "#c1", "section": "summary"}` | Returns total line/char counts, error line count, first 15 lines, last 25 lines, and top 20 error lines. |
307
+ | **Section: Tail** | `{"hash": "#c1", "section": "tail", "limit": 50}` | Returns the last `limit` lines (default `50`, max `1,000`) with 1-indexed line numbers. |
308
+ | **Safe Regex Grep** | `{"hash": "#c1", "grep": "ConnectionRefused\|503"}` | Case-insensitive bounded regex search across the uncompressed original (`line_no\|text`). |
309
+ | **Line Pagination** | `{"hash": "#c1", "offset": 100, "limit": 80}` | Slices lines `100..179` (`1-indexed`) with line numbers. |
310
+ | **Full Restore** | `{"hash": "#c1"}` | Restores the complete uncompressed `original_content`. |
311
+
312
+ ---
313
+
314
+ ## Architecture & Modules
315
+
316
+ | Module | Role | Key Responsibilities |
317
+ | :--- | :--- | :--- |
318
+ | `trimtok/core.py` | **Stage 1: Terminal Pipeline** | Output classification, traceback/diff pruning, ANSI/spinner stripping, exact & Drain template folding, command budgets, BPE non-inflation gate, and fault quality gate. |
319
+ | `trimtok/dedup.py` | **Stage 2: Tool Pipeline** | Volatile token normalization, JSON minification, AST code skeletonization, cross-turn span/line folding, 3-gram shingle near-dedup, `HEAD_TAIL` windowing, and TOON transcoding. |
320
+ | `trimtok/pruners.py` | **Structural Pruners** | Unified module housing Python/Node stack-trace pruning, semantic `git diff` context folding, scoped search (`def`/`class`) grouping, and `ast` code skeletonization. |
321
+ | `trimtok/signals.py` | **Fault Rails, BPE & Guard** | English/Thai failure polarity detector (`is_important`), `[tt:...]` marker grammar, `tiktoken` BPE estimator with 64 KB fast sampling, and fail-open `Deadline` guard. |
322
+ | `trimtok/toon_codec.py` | **Lossless TOON Codec** | Multi-level dot-notation wrapper unnesting, shared path `@prefix` extraction, inline compact JSON cells (`<= 120 chars`), and in-memory `_strict_eq()` verification. |
323
+ | `trimtok/delta_engine.py` | **Stateful Command Delta** | Safe command family normalization, 2-stage line alignment ($O(N)$ skeleton + `rapidfuzz`), `STILL FAILING` canary rail, and bounded per-session LRU state. |
324
+ | `trimtok/ccr.py` | **SQLite WAL + Zstd CCR Store** | Single-file `FastCCRStore` with atomic `BEGIN IMMEDIATE` Base62 `#cN` alias generation, Zstandard compression, cross-instance persistence, and TTL eviction. |
325
+ | `trimtok/mcp_server.py` | **Stdio MCP Server** | Exposes `trimtok_compress_terminal`, `trimtok_compress_tool`, `trimtok_retrieve`, and `trimtok_status` over `msgspec`-accelerated JSON-RPC 2.0. |
326
+ | `trimtok/mcp_install.py` | **Universal Client Installer** | Atomically registers/unregisters `trimtok` across 11 AI agent CLIs and IDEs with automatic `.pre-mcp-install.bak` backups. |
327
+
328
+ ---
329
+
330
+ ## Performance & Benchmarks
331
+
332
+ ### Latency Benchmarks (`python tests/test_benchmark.py`)
333
+
334
+ | Execution Path | Workload Scenario | Measured Median | P95 | Budget |
335
+ | :--- | :--- | ---: | ---: | ---: |
336
+ | `compress_terminal` | 4.4 KB repeated build log | **1.62 ms** | 3.53 ms | `< 10.0 ms` |
337
+ | `compress_tool_result` (first-seen) | Pretty JSON + TOON round-trip verify | **10.29 ms** | 15.10 ms | `< 25.0 ms` |
338
+ | `compress_tool_result` (repeat) | Exact-repeat passthrough | **0.08 ms** | 0.20 ms | `< 10.0 ms` |
339
+ | `compress_tool_result` (cross-turn) | 60 shared lines folded against session index | **2.65 ms** | 5.52 ms | `< 10.0 ms` |
340
+ | `fast_json_loads` | 1,000 JSON objects (~100 KB) | **0.70 ms** | — | `< 15.0 ms` |
341
+ | `estimate_bpe_tokens` | ~96 KB text (with 64 KB fast sampling) | **0.66 ms** | — | `< 20.0 ms` |
342
+ | `try_delta` (2-stage fuzzy) | 200-line command output with shifted lines | **1.35 ms** | — | `< 5.0 ms` |
343
+ | `ccr.put` / `ccr.get` | SQLite WAL + Zstd write / warm `#c1` read | **0.22 ms / 0.011 ms** | 0.42 ms / 0.012 ms | `< 5.0 ms` |
344
+
345
+ <details>
346
+ <summary><strong>📊 Click to expand: Full 34-Case Heavy Stress Suite Breakdown (88.3% Total Reduction)</strong></summary>
347
+
348
+ <br/>
349
+
350
+ Verified via `python tests/stress_heavy.py`:
351
+
352
+ | Workload Scenario | Before → After | Reduction |
353
+ | :--- | :--- | ---: |
354
+ | 1 MB repeated tool output (`D12`) | `1,000,000 → 159 chars` | **100.0%** |
355
+ | 500 KB repeated terminal log (`T14`) | `500,000 → 250 chars` | **100.0%** |
356
+ | 5,000-line heartbeat log (`T1`) | `234,999 → 224 chars` | **99.9%** |
357
+ | 2,000-line `pytest` output + 1 failure (`T2`) | `56,108 → 312 chars` | **99.4%** |
358
+ | 5-turn repeated `pytest` loop with Delta (`D16`) | `210,725 → 3,136 chars` | **98.5%** |
359
+ | Cross-turn search vs prior `read_file` (`D5b`) | `47,500 → 1,070 chars` | **97.7%** |
360
+ | 2,000-line Thai + English mixed log (`T11`) | `58,422 → 1,734 chars` | **97.0%** |
361
+ | Scoped multi-file grep search (`D14`) | `42,783 → 1,639 chars` | **96.2%** |
362
+ | 800-file `git diff` output (`T4`) | `46,760 → 2,110 chars` | **95.5%** |
363
+ | 3,000-line error-dense log (`T9`) | `141,779 → 9,214 chars` | **93.5%** |
364
+ | 4,800-line deep stack traceback (`T12`) | `94,656 → 11,230 chars` | **88.1%** |
365
+ | 1,000-row JSON array via TOON (`D15b`) | `101,885 → 26,147 chars` | **74.3%** |
366
+ | Realistic 5-turn mixed session (`SIM`) | `105,839 → 39,904 chars` | **62.3%** |
367
+ | **All 34 stress cases combined** | **`3,559,894 → 417,581 chars`** | **88.3%** (~785k tokens saved) |
368
+
369
+ </details>
370
+
371
+ ---
372
+
373
+ ## Configuration & CLI Reference
374
+
375
+ ### MCP Tools Exposed (`trimtok.mcp_server`)
376
+
377
+ | MCP Tool | Description |
378
+ | :--- | :--- |
379
+ | **`trimtok_compress_terminal`** | Compress noisy shell/terminal output while preserving 100% of errors, tracebacks, and diff hunks; stores original in CCR (`#c1`). |
380
+ | **`trimtok_compress_tool`** | Compress structured tool/JSON/search/code outputs via TOON tables, scoped search grouping, AST skeletonization, and cross-turn span folding. |
381
+ | **`trimtok_retrieve`** | Retrieve uncompressed original content or targeted sections (`errors`, `diff`, `summary`, `tail`, regex `grep`, or line pagination) by `#c1` ref. |
382
+ | **`trimtok_status`** | Inspect token savings, CCR cache stats, or purge expired entries. |
383
+
384
+ <details>
385
+ <summary><strong>⚙️ Click to expand: Full Configuration Schema & Hermes Settings</strong></summary>
386
+
387
+ <br/>
388
+
389
+ | Setting | Type | Default | Description |
390
+ | :--- | :---: | :---: | :--- |
391
+ | `enabled` | `bool` | `true` | Master switch for all hooks (`false` = passthrough). |
392
+ | `guard_ms` | `float` | `50` | Fail-open deadline budget in milliseconds (`1–1000`). |
393
+ | `min_chars` | `int` | `2048` | Minimum character length before compression runs. |
394
+ | `max_lines` | `int` | `120` | Default terminal line-window budget when no command-specific budget applies. |
395
+ | `phase2_enabled` | `bool` | `true` | Enables `transform_tool_result` cross-turn deduplication. |
396
+ | `toon_enabled` | `bool` | `true` | Enables lossless JSON-to-TOON columnar table transcoding. |
397
+ | `delta_enabled` | `bool` | `true` | Enables cross-turn stateful command delta compression. |
398
+ | `delta_threshold` | `float` | `0.65` | Minimum line/skeleton overlap ratio (`0.5–1.0`) required to emit a command delta. |
399
+ | `exclude_commands` | `list[str]` | `[]` | Command prefixes (e.g., `["git log", "docker inspect"]`) that bypass terminal compression. |
400
+ | `exclude_tools` | `list[str]` | `[]` | Tool names that bypass tool-result compression. |
401
+ | `mask_enabled` | `bool` | `true` | Enables `post_llm_call` freshness masking of old turn pointers. |
402
+ | `mask_keep_turns` | `int` | `2` | Number of recent turns kept active before fold pointers expire (`0–32`). |
403
+ | `ccr_max_entries` | `int` | `1000` | Maximum cached originals in CCR before LRU eviction (`10–100000`). |
404
+ | `ccr_max_bytes` | `int` | `52428800` | Maximum total disk budget in bytes (`50 MB` default). |
405
+ | `ccr_ttl_hours` | `int` | `24` | Retention TTL in hours for cached originals (`1–720`). |
406
+
407
+ </details>
408
+
409
+ ---
410
+
411
+ ## Recommended Ecosystem Combo
412
+
413
+ While **trimtok** works standalone as your context compression shield, pairing it with [**MemCore**](https://github.com/Stxyu-p/memcore) and [**Skill Proof**](https://github.com/Stxyu-p/skill-proof) completes the **Global Agent Trinity** — connecting every AI coding client on your machine (**Claude Code, Cursor, Antigravity, Gemini CLI, Codex, VS Code Copilot, Windsurf, OpenCode, Cline, and Hermes**) to three unified local hubs:
414
+
415
+ ```mermaid
416
+ flowchart LR
417
+ Task(["Developer Request"]) --> SP["Skill Proof<br/>~/.skill-proof/skills<br/>(Deterministic Skill Router)"]
418
+ SP --> MC["MemCore<br/>~/.memcore<br/>(Governed Bitemporal Memory)"]
419
+ MC --> Agent["Any AI Coding Agent"]
420
+ Agent --> TT["trimtok<br/>~/.trimtok<br/>(88.3% Context Compression + CCR #c1)"]
421
+ TT --> Agent
422
+ ```
423
+
424
+ | Pillar | Repository | Global Hub | What Installing All 3 Gives You |
425
+ | :--- | :--- | :--- | :--- |
426
+ | **Context Shield** | **[trimtok](https://github.com/Stxyu-p/trimtok)** | `~/.trimtok` | Cuts terminal, traceback, diff, AST code, and JSON token bloat by **88.3%** with instant `#c1` lossless recovery. |
427
+ | **Governed Memory** | **[MemCore](https://github.com/Stxyu-p/memcore)** | `~/.memcore` | Gives every IDE and CLI **one shared bitemporal brain** (`FTS5` + `sqlite-vec` SIMD + `model2vec`) with hard trust labels and source-file staleness tracking. |
428
+ | **Skill Vault & Router** | **[Skill Proof](https://github.com/Stxyu-p/skill-proof)** | `~/.skill-proof/skills` | Consolidates all dispersed `SKILL.md` playbooks into **one deduplicated global vault** and routes tasks in `< 1 ms` with zero routing LLM calls. |
429
+
430
+ ```bash
431
+ # Install & link the complete Global Agent Trinity across all your IDEs and CLIs
432
+ pip install trimtok memcore skill-proof
433
+ trimtok install && memcore init && memcore install && skill-proof install
434
+ skill-proof vault migrate
435
+ ```
436
+
437
+ ---
438
+
439
+ ## Verification & License
440
+
441
+ ```bash
442
+ pytest -q
443
+ python tests/test_core.py
444
+ python tests/test_v3_upgrade.py
445
+ python tests/test_dedup.py
446
+ python tests/test_torture.py
447
+ python tests/test_benchmark.py
448
+ python tests/stress_heavy.py
449
+ ```
450
+
451
+ Distributed under the [MIT License](LICENSE). Designed and maintained by **P Choke & SORA**.