lakonai 0.16.5 → 1.0.1

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.
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
  <h3 align="center">Speak less. Ship more.</h3>
8
8
 
9
9
  <p align="center">
10
- <strong>Cut LLM tokens by up to 94% - without losing a single identifier.</strong>
10
+ <strong>Cut LLM tokens by up to 94% — without losing a single identifier.</strong>
11
11
  </p>
12
12
 
13
13
  <p align="center"><em>Spartan replies for AI agents.</em></p>
@@ -18,42 +18,59 @@
18
18
  <img src="https://img.shields.io/badge/node-%E2%89%A518-0F0F0F" alt="node ≥18" />
19
19
  <img src="https://img.shields.io/badge/deps-0-0F0F0F" alt="zero dependencies" />
20
20
  <img src="https://img.shields.io/badge/agents-6-0F0F0F" alt="6 AI agents" />
21
+ <img src="https://img.shields.io/badge/tests-725-0F0F0F" alt="725 tests" />
21
22
  </p>
22
23
 
23
24
  <p align="center">
24
- One install. <strong>Four fronts</strong> of token waste, closed at once:<br/>
25
- <strong>what the model writes</strong> · <strong>what your shell dumps in</strong> · <strong>what it reads</strong> · <strong>the catalogs &amp; memory loaded every session</strong>.<br/>
26
- Works across <strong>Claude Code, Codex, Cursor, Windsurf, Cline, Gemini CLI</strong> - no API key.
25
+ One install. Zero configuration. Every token wasted by your agent — <strong>closed</strong>.<br/>
26
+ Works across <strong>Claude Code, Codex, Cursor, Windsurf, Cline, Gemini CLI</strong>.<br/>
27
+ <strong>Optimized for Claude Code</strong> — four dedicated layers, measured in production.
27
28
  </p>
28
29
 
29
30
  ---
30
31
 
31
- ## Savings, measured
32
+ ## Real savings, measured
32
33
 
33
- | Command | Raw tokens | Filtered | Saved |
34
- | --------------------- | ---------: | ----------: | -------: |
35
- | `git log -p -10` | 10,497 | 78 | **-94%** |
36
- | `ls -laR` (deep dir) | 23,624 | 117 | **-94%** |
37
- | `npm test` (passing) | 4,451 | 358 | **-92%** |
38
- | `git diff HEAD~5` | 13,230 | 798 | **-89%** |
39
- | `Read pnpm-lock.yaml` | ~56,000 | **blocked** | **-95%** |
34
+ **CLI filters** — stripped before output reaches the model:
40
35
 
41
- Conservative - peaks go higher. `lakonai gain` shows your own.
36
+ | Command | Raw tokens | Filtered | Saved |
37
+ | -------------------- | ---------: | --------: | -------: |
38
+ | `git log -p -10` | 10,497 | 78 | **-94%** |
39
+ | `ls -laR` (deep) | 23,624 | 117 | **-94%** |
40
+ | `npm test` (passing) | 4,451 | 358 | **-92%** |
41
+ | `git diff HEAD~5` | 13,230 | 798 | **-89%** |
42
+ | `Read pnpm-lock.yaml`| ~56,000 | **blocked**| **-95%** |
43
+
44
+ **Proxy compression** — what actually reaches the Anthropic API (real session, 49 requests):
45
+
46
+ | Content type | Without lakonai | With lakonai | Saved |
47
+ | ------------------- | --------------: | -----------: | -------: |
48
+ | npm test (652 tests)| 5,168 tok | 85 tok | **-98%** |
49
+ | Build log (80 lines)| 1,298 tok | 8 tok | **-99%** |
50
+ | JSON API (120 users)| 2,386 tok | 104 tok | **-96%** |
51
+ | Git diff | ~3,000 tok | ~2,880 tok | **-4%**|
52
+ | Source file read | via graph read-guard → **-87%** | |
53
+
54
+ **Typical coding session:** ~53% savings from proxy alone, ~75% with graph read-guard.
55
+
56
+ `lakonai gain` shows your own numbers. `/lakonai:stats` shows all layers at once.
42
57
 
43
58
  ---
44
59
 
45
- ## What it does - four fronts
60
+ ## Eight fronts, one install
46
61
 
47
- | Front | Wasted tokens look like… | lakonai fixes it by… |
48
- | --------------------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------- |
49
- | **Output** (the model) | _"Great question! Let me explain…"_ | A terse-response rule - no preamble, no recap. |
50
- | **Input** (your shell) | `git log` dumping 1.8k tokens of metadata | Filtering **30 commands** (git/ls/grep/tests/lint/docker…) before they hit context. |
51
- | **Reads** (files) | `Read pnpm-lock.yaml` → 80k of nothing | A hook that blocks lockfiles/`node_modules`, caps huge files, and caps `Grep`. |
52
- | **Context** (every session) | MCP catalogs + your `CLAUDE.md`, re-paid every turn | Auto-compressing MCP catalogs; opt-in `compress-memory`. |
62
+ | Front | What it fixes | How |
63
+ |-------|--------------|-----|
64
+ | **Output** | _"Great question! Let me explain…"_ | Terse-response rule — no preamble, no recap. Auto-clarity for edge cases. |
65
+ | **Shell input** | `git log` dumping 1.8k tokens of metadata | Filters **30+ commands** (git/ls/grep/tests/lint/docker/kubectl/aws…) before they hit context |
66
+ | **Reads** | `Read pnpm-lock.yaml` → 80k of nothing | Hook blocks lockfiles/`node_modules`, caps huge files and `Grep` |
67
+ | **Overflow** | 4k-line build logs no filter knows | Parks on disk, hands the agent a digest — `lakonai peek` reads it back |
68
+ | **Proxy** | Every API request carries raw bloat | Local HTTP proxy compresses request bodies before they reach Anthropic |
69
+ | **Graph** | File reads load entire source files | AST knowledge graph: serves a compact subgraph instead of the raw file (-87%) |
70
+ | **Pixel** | Skill files are verbose markdown | Converts skill bodies to PNG — vision tokens cheaper than text tokens |
71
+ | **Context** | MCP catalogs + memory re-paid every turn | Auto-compresses MCP catalogs; `compress-memory` via local AI CLI |
53
72
 
54
- Most tools stop at one front. lakonai works all four - and **gets better the more
55
- you use it**: it auto-learns new heavy commands and turns on a safe filter for them,
56
- no config. ([full reference →](docs/reference.md))
73
+ Auto-learning runs underneath all of this: lakonai detects new heavy commands and enables a safe filter automatically, no config. ([full reference →](docs/reference.md))
57
74
 
58
75
  ---
59
76
 
@@ -61,46 +78,132 @@ no config. ([full reference →](docs/reference.md))
61
78
 
62
79
  ```bash
63
80
  npm install -g lakonai
64
- lakonai install # global agents (Claude Code / Codex / Gemini)
65
- lakonai install --here # + per-project rules (Cursor / Windsurf / Cline)
81
+ lakonai install
82
+ ```
83
+
84
+ That's it. From the next session your agent is terse, shell output is filtered, junk reads are blocked, the proxy compresses API traffic, and the graph intercepts file reads. Watch it in `lakonai gain`.
85
+
86
+ ---
87
+
88
+ ## Layers, explained
89
+
90
+ ### Layer 1 — CLI filters (all agents)
91
+
92
+ Thirty-plus command filters run as a PATH shim or Claude Code hook before output ever reaches context. `git log -p` becomes three lines. A passing `npm test` suite becomes one.
93
+
94
+ ```bash
95
+ lakonai git log -p # → summary only
96
+ lakonai npm test # → final counts only
97
+ lakonai ls -la # → files without noise
98
+ ```
99
+
100
+ ### Layer 2 — Graph read-guard (Claude Code)
101
+
102
+ `lakonai graph build` parses your codebase into an AST knowledge graph — zero LLM, pure regex, works in under a second for most projects. When Claude Code reads a source file, the read-guard intercepts and returns a compact subgraph (symbols, edges, community) instead of the full text.
103
+
104
+ ```
105
+ 102 files → 512 nodes → 573 edges built in <0.1s
106
+ file read: 2,835 tok raw → 300 tok subgraph (-89%)
66
107
  ```
67
108
 
68
- That's it - from the next session your agent is terse, its shell output filtered,
69
- junk reads blocked, and MCP catalogs compressed. Watch it in `lakonai gain`.
109
+ ```bash
110
+ lakonai graph build # build / rebuild
111
+ lakonai graph query "what calls parseFile?"
112
+ lakonai graph explain src/foo.js
113
+ lakonai graph path src/a.js src/b.js
114
+ lakonai graph html # open interactive viz
115
+ lakonai graph watch # rebuild on file change
116
+ ```
117
+
118
+ The graph JSON is auto-added to `.gitignore`. Set `LAKON_GRAPH_CAT=0` to bypass.
70
119
 
71
- Two extras worth knowing:
120
+ ### Layer 3 — Proxy compression (Claude Code)
72
121
 
73
- - **`lakonai shim`** - makes shell filtering automatic on **every** agent (not just
74
- Claude Code) by routing `ls`/`grep`/`find`/… through lakonai at the PATH level.
75
- - **`lakonai compress-memory CLAUDE.md`** - shrinks your memory file with a **local
76
- AI CLI you already have, no API key** (backed up, validated byte-for-byte).
122
+ A local HTTP proxy on port 7474 sits between Claude Code and `api.anthropic.com`. It compresses request bodies before they're sent — the model sees fewer tokens, you pay less.
123
+
124
+ ```
125
+ build logs → -99% (repetitive lines collapsed)
126
+ minified JSON → -96% (schema-extracted summary)
127
+ test output → -98% (counts only, no per-test lines)
128
+ diffs → -4% (conservative; context preserved)
129
+ source code → 0% (covered by graph instead)
130
+ ```
131
+
132
+ The proxy starts automatically on `lakonai install` and runs silently. No API key exposed. Stats accumulate in `~/.lakon/proxy-stats.json`.
133
+
134
+ ### Layer 4 — Pixel (Claude Code + Codex)
135
+
136
+ Skill markdown is verbose. A 3k-token skill file becomes a 170-token PNG tile. Vision tokens are cheaper than text tokens past the ~255-token break-even point.
137
+
138
+ ```bash
139
+ lakonai pixel --dry-run # estimate savings, no writes
140
+ lakonai pixel # convert profitable skills (requires: npm install canvas)
141
+ lakonai pixel --agent claude # Claude Code skills only
142
+ lakonai pixel --revert # byte-identical restore from backup
143
+ ```
144
+
145
+ ### Overflow sandbox (all agents)
146
+
147
+ When a command's output still exceeds budget after filtering, lakonai parks the full text in `~/.lakon/sandbox/` and gives the agent a digest: head, tail, exit code, how to query. Nothing is lost — it stops being re-paid.
148
+
149
+ ```
150
+ lakonai: 4000 lines / 249KB parked in sandbox 30930a0c
151
+ $ node build.js → exit 0
152
+
153
+ [build] compiling module 0 …
154
+ … 3980 lines elided …
155
+ [build] compiling module 3999 …
156
+
157
+ Query it: lakonai peek 30930a0c --grep "error"
158
+ ```
77
159
 
78
160
  ---
79
161
 
80
- ## Output savings: the rule trims the model's prose too
162
+ ## Agent support
81
163
 
82
- The input side (filtered shell output, blocked reads, compressed catalogs) is
83
- deterministic. But the terse rule also makes the **model itself** write less.
84
- `lakonai gain` measures it by running the same prompts through your local AI CLI
85
- twice - once rule-free, once with the terse rule as a system prompt - and
86
- comparing output tokens.
164
+ | Feature | Claude Code | Codex | Cursor / Windsurf / Cline | Gemini |
165
+ |---------|:-----------:|:-----:|:-------------------------:|:------:|
166
+ | CLI filters | ✅ hook | ✅ shim | ✅ shim | ✅ shim |
167
+ | Read/Grep guard | ✅ | ✅ shim | ✅ shim | ✅ shim |
168
+ | Overflow sandbox | ✅ | — | — | — |
169
+ | Proxy compression | ✅ | — | — | — |
170
+ | Graph read-guard | ✅ | — | — | — |
171
+ | Pixel (skill PNG) | ✅ | ✅ | — | — |
172
+ | MCP catalog compression | ✅ | — | — | — |
173
+ | Auto-learn new commands | ✅ | ✅ | ✅ | ✅ |
87
174
 
88
- On a rule-free Claude baseline, explain / how-do-I / write-a-function prompts run
89
- **~52% leaner** with the rule (1332 → 634 tokens across 4 prompts).
175
+ **Primary target: Claude Code.** The proxy and graph layers intercept the Anthropic protocol and are Claude-Code-specific. CLI filters and the universal shim work on every agent. Every install is idempotent and reversible.
90
176
 
91
- Read that as a **best case on prose turns**, not your day-to-day average:
177
+ ---
92
178
 
93
- - it's a small, fixed corpus of chatty prompts - exactly where preamble balloons;
94
- - model output varies run to run (the figure is a single weekly sample, not an average);
95
- - agentic turns (code edits, tool calls, diffs) are mostly code, not prose, so the
96
- rule trims far less there.
179
+ ## Slash commands
97
180
 
98
- Your real workload lands somewhere between the deterministic **input** savings
99
- (~46%) and this prose ceiling, pulled down by however much of your work is
100
- code and tooling rather than explanation.
181
+ After `lakonai install`, these are available in Claude Code:
101
182
 
102
- > `lakonai gain` shows both: the measured, deterministic input number and the
103
- > estimated output number - labelled as an estimate, never inflated into a headline.
183
+ | Command | What it shows |
184
+ |---------|--------------|
185
+ | `/lakonai:gain` | Token savings — input (measured) and output (estimated) |
186
+ | `/lakonai:stats` | All layers: filters + proxy breakdown by content type |
187
+
188
+ ---
189
+
190
+ ## Full CLI reference
191
+
192
+ | Command | What it does |
193
+ |---------|-------------|
194
+ | `lakonai install [--here]` | Install rule + hooks (globals; `--here` adds per-project) |
195
+ | `lakonai upgrade` | Update to latest + refresh the rule block |
196
+ | `lakonai uninstall` / `revert` | Strip the lakonai block / restore from backup |
197
+ | `lakonai shim [--off]` | Universal PATH shim — automatic filtering on every agent |
198
+ | `lakonai graph <sub>` | Build / query / watch the AST knowledge graph |
199
+ | `lakonai pixel [--dry-run\|--revert\|--agent]` | Convert skill files to PNG |
200
+ | `lakonai compress-memory <file>` | Shrink a memory file via your local AI CLI |
201
+ | `lakonai peek [id]` | Read output parked in sandbox (`--grep/--offset/--limit`) |
202
+ | `lakonai gain` | Token savings across all measured fronts |
203
+ | `lakonai inspect <cmd>` | Debug what filter applies to a command |
204
+ | `lakonai doctor` | Health check: CLI on PATH, hooks, rule |
205
+
206
+ Full flags, filters, env vars, internals: **[docs/reference.md](docs/reference.md)**.
104
207
 
105
208
  ---
106
209
 
@@ -117,59 +220,73 @@ lakonai - saved 196.8k tok (46% smaller) across 1910 commands
117
220
  output (terse rule): ~52% fewer tokens (1332 → 634, 4 prompts) [claude]
118
221
  ```
119
222
 
120
- Input is measured & deterministic; output is estimated by your local AI CLI (no key,
121
- weekly, at a TTY only). Both sides, one number.
223
+ Input is measured and deterministic. Output is estimated by your local AI CLI (no key, weekly). Both sides, one number.
122
224
 
123
225
  ---
124
226
 
125
- ## Commands
227
+ ## vs. similar tools
228
+
229
+ | Feature | lakonai | caveman | graphify | rtk | Manual CLAUDE.md |
230
+ |---------|:-------:|:-------:|:--------:|:---:|:----------------:|
231
+ | Terse-response rule | ✅ | ✅ | — | — | ⚠️ manual |
232
+ | CLI output filters (30+ commands) | ✅ | — | — | ✅ | — |
233
+ | Auto-learning (new heavy commands) | ✅ | — | — | — | — |
234
+ | Lockfile / node_modules guard | ✅ | — | — | — | ⚠️ manual |
235
+ | Overflow sandbox (large outputs) | ✅ | — | — | — | — |
236
+ | Proxy compression (logs/JSON/diffs) | ✅ | ✅ | — | — | — |
237
+ | AST knowledge graph | ✅ | — | ✅ | — | — |
238
+ | Graph read-guard (subgraph on reads) | ✅ | — | — | — | — |
239
+ | BM25 NL graph query (zero LLM) | ✅ | — | ⚠️ LLM | — | — |
240
+ | Community detection (Leiden) | ✅ | — | ✅ | — | — |
241
+ | Interactive graph viz (HTML) | ✅ | — | ✅ | — | — |
242
+ | Skill PNG conversion (pixel) | ✅ | ✅ | — | — | — |
243
+ | MCP catalog compression | ✅ | — | — | — | — |
244
+ | Zero config after install | ✅ | ✅ | — | ⚠️ | ⚠️ |
245
+ | Works with Cursor/Windsurf/Codex | ✅ | ✅ | — | ✅ | ✅ |
246
+ | Optimised for Claude Code | ✅ | ✅ | — | — | — |
247
+ | Pure JS, no native deps for core | ✅ | ✅ | — | ✅ | — |
248
+ | npm install + one command | ✅ | ✅ | — | ⚠️ | — |
249
+
250
+ **caveman** — terse rule, auto-clarity, proxy compression, pixel mode (MIT). Absorbed with credit.
251
+ **graphify** — AST knowledge graph, Leiden community detection, force-directed HTML viz, NL query. Reimplemented in Node.js; lakonai replaces LLM-based query with BM25 (zero cost).
252
+ **rtk** — CLI output filtering approach; lakonai extends with auto-learning and 30+ built-in filters.
253
+ **Manual CLAUDE.md** — works, but you write and maintain it; lakonai installs and updates automatically.
126
254
 
127
- | Command | What it does |
128
- | --------------------------------------------------------- | -------------------------------------------------------------- |
129
- | `lakonai install [--here]` | Install rule + hooks (globals; `--here` adds per-project) |
130
- | `lakonai upgrade` | Update to the latest version + refresh the rule block |
131
- | `lakonai uninstall` / `revert` | Strip the lakonai block / restore from backup |
132
- | `lakonai shim [--off]` | Universal PATH shim - automatic shell filtering on every agent |
133
- | `lakonai compress-memory <file>` / `revert-memory <file>` | Shrink a memory file via your local AI CLI / undo |
134
- | `lakonai gain` | Token savings - input (measured) and output (estimated) |
135
- | `lakonai doctor` | Per-platform health: CLI on PATH, rule, hooks |
255
+ ---
136
256
 
137
- Full flags, filters, env vars and internals: **[docs/reference.md](docs/reference.md)**.
257
+ ## Test suite
138
258
 
139
- ---
259
+ 725 tests across 47 suites — all passing, no mocks on I/O boundaries.
140
260
 
141
- ## Agents - what each one gets
261
+ | Type | Suites | Tests |
262
+ |------|--------|-------|
263
+ | Unit | 13 | 183 |
264
+ | Integration (module + real FS) | 31 | 489 |
265
+ | E2E / CLI (spawn + real process) | 3 | 53 |
266
+ | **Total** | **47** | **725** |
142
267
 
143
- | Agent | Installs | Shell filter | Read/Grep guard | Auto-learn |
144
- | ------------------------- | ---------------------------------------------------- | :----------: | :-------------: | :--------: |
145
- | Claude Code | `~/.claude/CLAUDE.md` + 5 hooks + MCP compress | ✅ hook | ✅ tool + shell | ✅ |
146
- | Codex / Gemini | rule in `~/.codex/AGENTS.md` · `~/.gemini/GEMINI.md` | ✅ shim | ✅ shell reads | ✅ |
147
- | Cursor / Windsurf / Cline | per-project rule (`--here`) | ✅ shim | ✅ shell reads | ✅ |
268
+ Coverage: **95% statements · 89% branches · 97% functions**
148
269
 
149
- Hooks are Claude-Code-only (the only platform with a call-rewriting hook API);
150
- everywhere else `lakonai shim` makes the shell-mediated features automatic. The one
151
- thing not universal is guarding an agent's **own non-shell Read tool** - see the
152
- [honest matrix](docs/reference.md#capability-matrix-per-agent). Every install is
153
- idempotent and reversible (`uninstall`/`revert`, backups first).
270
+ Branch ceiling is ~90% — the remaining gaps are canvas-native rendering, platform-specific `fs.watch` fallback, and the HTTPS transport branch (all marked `/* istanbul ignore next */` with justification).
154
271
 
155
272
  ---
156
273
 
157
274
  ## Why "lakonai"
158
275
 
159
- In 346 BC, Philip II of Macedon warned Sparta: _"If I invade Lakonía, I will raze
160
- your cities."_ The Spartans replied with one word: _"If."_ Their region, **Lakonía**,
161
- gave English the word **laconic** - using as few words as possible.
276
+ In 346 BC, Philip II of Macedon warned Sparta: _"If I invade Lakonía, I will raze your cities."_ The Spartans replied with one word: _"If."_ Their region, **Lakonía**, gave English the word **laconic** — using as few words as possible.
162
277
 
163
- Your AI agent isn't laconic. It opens with _"Sure! I'd be happy to help…"_, repeats
164
- your question, and reads `git log` in full. lakonai trims both sides.
278
+ Your AI agent isn't laconic. It opens with _"Sure! I'd be happy to help…"_, repeats your question, reads `git log` in full, and sends every line of your test suite to the API. lakonai closes all of it.
165
279
 
166
280
  ---
167
281
 
168
282
  ## Credits
169
283
 
170
- Built on ideas from [**caveman**](https://github.com/juliusbrussee/caveman) (terse
171
- rule + auto-clarity) and [**rtk**](https://github.com/rtk-ai/rtk) (CLI output
172
- filtering) - condensed into one zero-dependency package with automatic backups and
173
- savings tracking.
284
+ Built on ideas from three projects:
285
+
286
+ - [**caveman**](https://github.com/juliusbrussee/caveman) (MIT) — terse rule, auto-clarity, proxy compression, pixel mode
287
+ - [**graphify**](https://github.com/Bklieger/graphify) — AST knowledge graph, Leiden community detection, force-directed viz, NL query (reimplemented in Node.js; BM25 replaces LLM query)
288
+ - [**rtk**](https://github.com/rtk-ai/rtk) — CLI output filtering approach, extended with auto-learning and 30+ built-in filters
289
+
290
+ Condensed into one zero-dependency npm package with automatic install, savings tracking, and four layers of compression.
174
291
 
175
- MIT - see [LICENSE](LICENSE).
292
+ MIT — see [LICENSE](LICENSE).
package/bin/lakonai.js CHANGED
@@ -40,6 +40,12 @@ Usage:
40
40
  not just the ones with a hook API. Prepends
41
41
  ~/.lakon/shim to PATH in your shell rc.
42
42
 
43
+ lakonai peek [id] Read output that was parked in the sandbox. No id
44
+ lists what's parked. Flags: --offset N --limit N
45
+ --grep <regex>. Output too big for the context
46
+ budget is spilled to disk automatically and replaced
47
+ with a digest - this is how you read the rest.
48
+
43
49
  lakonai gain Show token savings - INPUT (shell output, measured)
44
50
  AND OUTPUT (how much terser the model writes; measured
45
51
  weekly via your local AI CLI, no API key)
@@ -67,6 +73,56 @@ Update notifications:
67
73
  Disable with LAKON_NO_UPDATE_CHECK=1.
68
74
  `;
69
75
 
76
+ // Returns what the agent should see: the filtered text when it fits the budget,
77
+ // otherwise a digest pointing at the parked full output. Falls back to the
78
+ // filtered text if the spill can't be written (read-only home, full disk).
79
+ function maybeSpill({ cmd, args, exitCode, filtered }) {
80
+ const sandbox = require('../src/sandbox');
81
+ const tokens = countTokensApprox(filtered);
82
+ if (!sandbox.shouldSpill(tokens, sandbox.spillThreshold())) return filtered;
83
+ const parked = sandbox.spill({ cmd, args, exitCode, text: filtered });
84
+ /* istanbul ignore next -- disk failure path */
85
+ if (!parked) return filtered;
86
+ return parked.digest;
87
+ }
88
+
89
+ function runPeek(rest) {
90
+ const sandbox = require('../src/sandbox');
91
+ const [id, ...flags] = rest;
92
+ if (!id) {
93
+ const recent = sandbox.list();
94
+ if (!recent.length) {
95
+ process.stdout.write('lakonai: no parked output yet.\n');
96
+ return;
97
+ }
98
+ process.stdout.write(
99
+ 'Parked output (newest first):\n' +
100
+ recent.map((s) => ` ${s.id} ${Math.round(s.bytes / 1024)}KB`).join('\n') +
101
+ '\n'
102
+ );
103
+ return;
104
+ }
105
+ let text;
106
+ try {
107
+ text = sandbox.read(id);
108
+ } catch {
109
+ process.stderr.write(`lakonai: no parked output with id ${id}. Try \`lakonai peek\` to list.\n`);
110
+ process.exit(1);
111
+ }
112
+ const flag = (name) => {
113
+ const i = flags.indexOf(name);
114
+ return i >= 0 ? flags[i + 1] : undefined;
115
+ };
116
+ const pattern = flag('--grep');
117
+ if (pattern != null) {
118
+ process.stdout.write(sandbox.grep(text, pattern) + '\n');
119
+ return;
120
+ }
121
+ const offset = Number(flag('--offset')) || 1;
122
+ const limit = Number(flag('--limit')) || 100;
123
+ process.stdout.write(sandbox.slice(text, { offset, limit }) + '\n');
124
+ }
125
+
70
126
  function runAndFilter(cmd, args) {
71
127
  // Universal Read-guard: refuse junk reads (lockfiles/node_modules) done via the
72
128
  // shell (`cat pnpm-lock.yaml`) on ANY agent that uses the shim - same deny rules
@@ -92,15 +148,21 @@ function runAndFilter(cmd, args) {
92
148
  /* istanbul ignore next -- defensive empty-stream fallbacks */
93
149
  const raw = merge ? (child.stdout || '') + (child.stderr || '') : child.stdout || '';
94
150
  const filtered = isSupported(cmd) ? filterCommand(cmd, args, raw) : raw;
95
- process.stdout.write(filtered);
151
+ // Last line of defence: the filters have already had their go, and it is STILL
152
+ // too big. Park it on disk and hand back a digest, so the bytes cost nothing
153
+ // per turn but stay one `lakonai peek` away.
154
+ const shown = maybeSpill({ cmd, args, exitCode: child.status, filtered });
155
+ process.stdout.write(shown);
96
156
  /* istanbul ignore next */
97
- if (filtered && !filtered.endsWith('\n')) process.stdout.write('\n');
157
+ if (shown && !shown.endsWith('\n')) process.stdout.write('\n');
98
158
 
99
159
  tracking.record({
100
160
  cmd,
101
161
  args,
102
162
  rawTokens: countTokensApprox(raw),
103
- filteredTokens: countTokensApprox(filtered),
163
+ // What the agent actually pays for is `shown`, not `filtered` — on a spill
164
+ // those differ by orders of magnitude, and `gain` must report the truth.
165
+ filteredTokens: countTokensApprox(shown),
104
166
  });
105
167
 
106
168
  // Auto-learning off the universal log (throttled hourly) - runs on EVERY agent,
@@ -334,6 +396,27 @@ async function maybeOfferUpdate() {
334
396
  }
335
397
  }
336
398
 
399
+ function runPixel(args) {
400
+ const pixel = require('../src/pixel/convert');
401
+ const dryRun = args.includes('--dry-run');
402
+ const revert = args.includes('--revert');
403
+ const agentIdx = args.indexOf('--agent');
404
+ const agent = agentIdx >= 0 ? args[agentIdx + 1] : null;
405
+
406
+ if (dryRun) {
407
+ const results = pixel.dryRun({ agent });
408
+ process.stdout.write(pixel.formatDryRun(results));
409
+ return;
410
+ }
411
+ if (revert) {
412
+ const results = pixel.revertAll({ agent });
413
+ process.stdout.write(pixel.formatRevert(results));
414
+ return;
415
+ }
416
+ const results = pixel.convert({ agent });
417
+ process.stdout.write(pixel.formatConvert(results));
418
+ }
419
+
337
420
  async function main() {
338
421
  const argv = process.argv.slice(2);
339
422
  if (!argv.length || argv[0] === '--help' || argv[0] === '-h') {
@@ -401,11 +484,23 @@ async function main() {
401
484
  process.stdout.write(doctor.format(doctor.report()));
402
485
  return;
403
486
  }
487
+ if (first === 'peek') {
488
+ runPeek(rest);
489
+ return;
490
+ }
404
491
  /* istanbul ignore next -- long-running stdio MCP proxy; logic tested via src/mcp-shrink */
405
492
  if (first === '__mcp') {
406
493
  require('../src/mcp-shrink').runProxy(rest);
407
494
  return;
408
495
  }
496
+ if (first === 'graph') {
497
+ require('../src/graph').runGraph(rest);
498
+ return;
499
+ }
500
+ if (first === 'pixel') {
501
+ runPixel(rest);
502
+ return;
503
+ }
409
504
 
410
505
  runAndFilter(first, rest);
411
506
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lakonai",
3
- "version": "0.16.5",
3
+ "version": "1.0.1",
4
4
  "description": "lakonai — save AI context tokens. Filters & compresses CLI output (git, ls, grep, find, test runners, lint/build, docker/kubectl/aws) before it reaches Claude Code, Codex, Cursor, Windsurf, Cline or Gemini — and learns to filter new commands automatically the more you use it.",
5
5
  "keywords": [
6
6
  "claude",
@@ -46,6 +46,9 @@
46
46
  ],
47
47
  "scripts": {
48
48
  "test": "jest",
49
+ "test:unit": "jest --testPathPattern='(?<!integration|e2e-proxy|cli|bash-rewrite|grep-guard|learn-report-integration|mem-llm|session-start|stop-hook)\\.test\\.js$'",
50
+ "test:integration": "jest --testPathPattern='(graph-integration|graph-parser|proxy-server|learn-report-integration|bash-rewrite|grep-guard|session-start|stop-hook)\\.test\\.js$'",
51
+ "test:e2e": "jest --testPathPattern='(cli|e2e-proxy|integration)\\.test\\.js$'",
49
52
  "test:coverage": "jest --coverage",
50
53
  "test:coverage:check": "jest --coverage",
51
54
  "bench": "node -e \"process.stdout.write(require('./src/bench').format(require('./src/bench').runBench()))\""
@@ -53,6 +56,10 @@
53
56
  "engines": {
54
57
  "node": ">=18"
55
58
  },
59
+ "optionalDependencies": {
60
+ "@xenova/transformers": "^2.17.2",
61
+ "canvas": "^2.11.2"
62
+ },
56
63
  "devDependencies": {
57
64
  "jest": "^29.7.0"
58
65
  }
@@ -31,7 +31,13 @@ function filterLog(raw) {
31
31
  pendingHash = null;
32
32
  }
33
33
  }
34
- return truncateLines(out.join('\n'), 50);
34
+ const joined = out.join('\n');
35
+ // This parser only recognises the verbose "commit <sha> / Author: / Date:"
36
+ // shape. `--oneline` and `--format=…` never emit it, so nothing matched and the
37
+ // join returned "" — swallowing the output whole. Those formats are already
38
+ // terse; hand them back untouched. Never answer a command with silence.
39
+ if (!joined && text.trim()) return truncateLines(text.replace(/\s+$/, ''), 50);
40
+ return truncateLines(joined, 50);
35
41
  }
36
42
 
37
43
  function filterStatus(raw) {
@@ -62,7 +68,18 @@ function filterStatus(raw) {
62
68
  const parts = [];
63
69
  if (changed.length) parts.push(`changed:\n${changed.join('\n')}`);
64
70
  if (untracked.length) parts.push(`untracked:\n${untracked.join('\n')}`);
65
- return parts.join('\n\n') || 'clean';
71
+ if (parts.length) return parts.join('\n\n');
72
+
73
+ // Nothing parsed. The section headers this parser keys on only exist in the
74
+ // LONG format — `--short`/`-s`/`--porcelain` emit bare `XY path` lines, so a
75
+ // blind `|| 'clean'` here reported a dirty tree as clean. Only ever say clean
76
+ // when git said so; otherwise hand back what git printed. The short formats are
77
+ // already terse, so passthrough costs nothing.
78
+ if (/nothing to commit|working tree clean|working directory clean/i.test(text)) return 'clean';
79
+ // Trailing-only trim: in porcelain the leading column is significant (" M" is
80
+ // unstaged, "M " is staged), so trimming the start would flip the meaning.
81
+ const rest = text.replace(/\s+$/, '');
82
+ return rest.trim() ? rest : 'clean';
66
83
  }
67
84
 
68
85
  function filterDiff(raw) {
@@ -79,7 +96,11 @@ function filterDiff(raw) {
79
96
  out.push(line);
80
97
  }
81
98
  }
82
- return truncateLines(out.join('\n'), 120);
99
+ const joined = out.join('\n');
100
+ // Same trap as filterLog: `--stat` and `--name-only` carry no hunk markers, so
101
+ // nothing matched and the output vanished. They are already terse — pass through.
102
+ if (!joined && text.trim()) return truncateLines(text.replace(/\s+$/, ''), 120);
103
+ return truncateLines(joined, 120);
83
104
  }
84
105
 
85
106
  function filter(subcmd, raw) {