lakonai 1.3.0 → 1.4.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
@@ -20,7 +20,7 @@
20
20
  <img src="https://img.shields.io/badge/node-%E2%89%A518-0F0F0F" alt="node ≥18" />
21
21
  <img src="https://img.shields.io/badge/deps-0-0F0F0F" alt="zero dependencies" />
22
22
  <img src="https://img.shields.io/badge/agents-6-0F0F0F" alt="6 AI agents" />
23
- <img src="https://img.shields.io/badge/tests-998-0F0F0F" alt="998 tests" />
23
+ <img src="https://img.shields.io/badge/tests-1075-0F0F0F" alt="1075 tests" />
24
24
  </p>
25
25
 
26
26
  <p align="center">
@@ -39,6 +39,22 @@
39
39
 
40
40
  ## Real savings, measured
41
41
 
42
+ ### End-to-end, reproducible
43
+
44
+ <p align="center">
45
+ <img src="./docs/assets/savings-e2e.svg" width="820" alt="lakonai e2e: 86.3% fewer tokens overall across 10 real commands on a fixture repo — grep 96.9%, git diff 88.8%, git log 86.6%, ls 80%, git status 36.2%, find 31.5%, make 15%, sed read 0%" />
46
+ </p>
47
+
48
+ `tests/savings-e2e.test.js` builds a git repository on disk and runs each command
49
+ twice — raw, and through the real CLI (or the real PreToolUse hook + `sh` for the
50
+ `cd … &&` row). CI fails if a command drops below its floor **or** loses a line
51
+ that matters (the newest commit, the changed lines, the build warning). File
52
+ reads (`sed -n`, `cat`) are content the agent asked for, so they stay ~untouched.
53
+ Numbers and method: [docs/benchmark-e2e.md](./docs/benchmark-e2e.md). Regenerate the
54
+ chart with `npm run bench:e2e`.
55
+
56
+ ### From live projects
57
+
42
58
  All numbers from live projects using `lakonai@1.1.1`.
43
59
 
44
60
  **CLI filters** — output compressed before it reaches the model (React + TipTap + Yjs microfrontend, 2,185 files):
@@ -248,7 +264,7 @@ Query it: lakonai peek 30930a0c --grep "error"
248
264
 
249
265
  | Feature | Claude Code | Codex | Cursor / Windsurf / Cline | Gemini |
250
266
  |---------|:-----------:|:-----:|:-------------------------:|:------:|
251
- | CLI filters | ✅ hook | ✅ shim | ✅ shim | ✅ shim |
267
+ | CLI filters | ✅ hook | ✅ hook ¹ | ✅ shim | ✅ shim |
252
268
  | Read/Grep guard | ✅ | ✅ shim | ✅ shim | ✅ shim |
253
269
  | Overflow sandbox | ✅ | — | — | — |
254
270
  | Proxy compression | ✅ | — | — | — |
@@ -258,6 +274,10 @@ Query it: lakonai peek 30930a0c --grep "error"
258
274
  | Auto-learn new commands | ✅ | ✅ | ✅ | ✅ |
259
275
  | Answer budget (per-turn) | ✅ hook | ✅ proxy | ✅ proxy | ✅ proxy |
260
276
 
277
+ ¹ Codex CLI 0.16x+ runs the same PreToolUse hook from `~/.codex/hooks.json`. Codex skips new hooks until you trust them once with `/hooks`.
278
+
279
+ The Bash hook rewrites `cmd` and `cd <dir> && cmd` to go through `lakonai`. It answers "allow", so it only rewrites a command it can fully see: chains (`&&`, `;`, `||`), `$(…)`, redirects into files, and pipes into anything but `head`/`tail` run unchanged through your normal permission rules.
280
+
261
281
  **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.
262
282
 
263
283
  ---
@@ -347,16 +367,16 @@ Input is measured and deterministic. Output is estimated by your local AI CLI (n
347
367
 
348
368
  ## Test suite
349
369
 
350
- 998 tests across 61 suites — all passing, no mocks on I/O boundaries.
370
+ 1075 tests across 68 suites — all passing, no mocks on I/O boundaries.
351
371
 
352
372
  | Type | Suites | Tests |
353
373
  |------|--------|-------|
354
- | Unit | 14 | 194 |
355
- | Integration (module + real FS / real HTTP) | 32 | 614 |
356
- | E2E / CLI (spawn + real process) | 15 | 190 |
357
- | **Total** | **61** | **998** |
374
+ | Unit | 16 | 218 |
375
+ | Integration (module + real FS / real HTTP) | 36 | 642 |
376
+ | E2E / CLI (spawn + real process) | 16 | 215 |
377
+ | **Total** | **68** | **1075** |
358
378
 
359
- Coverage: **90% statements · 85% branches · 93% functions** (gate: 80% global; target 100% per new file)
379
+ Coverage: **90% statements · 86% branches · 93% functions** (gate: 80% global; target 100% per new file)
360
380
 
361
381
  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).
362
382
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lakonai",
3
- "version": "1.3.0",
3
+ "version": "1.4.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",
@@ -50,7 +50,8 @@
50
50
  "test:e2e": "jest --testPathPattern='(cli|e2e-proxy|integration)\\.test\\.js$'",
51
51
  "test:coverage": "jest --coverage",
52
52
  "test:coverage:check": "jest --coverage",
53
- "bench": "node -e \"process.stdout.write(require('./src/bench').format(require('./src/bench').runBench()))\""
53
+ "bench": "node -e \"process.stdout.write(require('./src/bench').format(require('./src/bench').runBench()))\"",
54
+ "bench:e2e": "node scripts/savings-chart.js"
54
55
  },
55
56
  "engines": {
56
57
  "node": ">=18"
package/src/doctor.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  // `lakonai doctor` — per-platform health check: is the CLI on PATH, is the rule
4
- // installed, and (for Claude Code) are the hooks registered? Gives an honest,
4
+ // installed, and (for Claude Code and Codex) are the hooks registered? Gives an honest,
5
5
  // per-platform view of what's actually active.
6
6
 
7
7
  const fs = require('fs');
@@ -37,7 +37,7 @@ function report(home) {
37
37
  detected: !!p.detect(h),
38
38
  ruleInstalled: platforms.hasBlock(p.rulePath(h)),
39
39
  };
40
- if (p.hasHooks) row.hooksInstalled = hooksInstalled(h);
40
+ if (p.hasHooks) row.hooksInstalled = p.hooksInstalled ? p.hooksInstalled(h) : hooksInstalled(h);
41
41
  return row;
42
42
  });
43
43
  return { cli: cliOnPath(), platforms: rows };
@@ -55,6 +55,7 @@ module.exports = [
55
55
  match: '^make\\b',
56
56
  stripLines: ['^make\\[\\d+\\]:', '^\\s*$', '^Nothing to be done'],
57
57
  maxLines: 60,
58
+ pinLines: ['\\b(error|warning|Error|Warning|ERROR|WARNING|undefined reference)\\b', '^make(\\[\\d+\\])?: \\*\\*\\*'],
58
59
  onEmpty: 'make: ok',
59
60
  },
60
61
  {
@@ -38,6 +38,7 @@ function compileDef(def) {
38
38
  headLines: def.headLines || null,
39
39
  tailLines: def.tailLines || null,
40
40
  maxLines: def.maxLines || null,
41
+ pinLines: (def.pinLines || []).map((p) => new RegExp(p)),
41
42
  onEmpty: def.onEmpty != null ? def.onEmpty : '',
42
43
  filterStderr: !!def.filterStderr,
43
44
  };
@@ -87,6 +88,14 @@ function applyDef(def, raw) {
87
88
  .join('\n');
88
89
  }
89
90
 
91
+ // A line cap keeps the head, but a build log puts its verdict at the end.
92
+ // Lines matching pinLines survive any cap: they are re-appended after the
93
+ // truncation marker, in order, so a warning on line 400 is never cut.
94
+ const cap = def.headLines || (!def.tailLines && def.maxLines) || null;
95
+ const pinned = cap && def.pinLines.length
96
+ ? text.split('\n').slice(cap).filter((l) => def.pinLines.some((re) => re.test(l)))
97
+ : [];
98
+
90
99
  if (def.headLines) {
91
100
  text = truncateLines(text, def.headLines);
92
101
  } else if (def.tailLines) {
@@ -98,6 +107,7 @@ function applyDef(def, raw) {
98
107
  }
99
108
 
100
109
  if (def.maxLines) text = truncateLines(text, def.maxLines);
110
+ if (pinned.length) text += '\n' + pinned.join('\n');
101
111
 
102
112
  return text.trim() === '' ? def.onEmpty : text;
103
113
  }
@@ -103,6 +103,26 @@ function filterDiff(raw) {
103
103
  return truncateLines(joined, 120);
104
104
  }
105
105
 
106
+ // Global options that sit between `git` and its subcommand. Agents run
107
+ // `git -C <repo> diff` constantly; reading args[0] saw "-C" and the diff
108
+ // filter never ran. Options listed in WITH_VALUE consume the next argument.
109
+ const WITH_VALUE = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--config-env']);
110
+
111
+ function subcommand(args) {
112
+ if (!Array.isArray(args)) return undefined;
113
+ for (let i = 0; i < args.length; i++) {
114
+ const a = args[i];
115
+ if (typeof a !== 'string') return undefined;
116
+ if (WITH_VALUE.has(a)) {
117
+ i++;
118
+ continue;
119
+ }
120
+ if (a.startsWith('-')) continue; // --no-pager, -P, --git-dir=…, --bare
121
+ return a;
122
+ }
123
+ return undefined;
124
+ }
125
+
106
126
  function filter(subcmd, raw) {
107
127
  switch (subcmd) {
108
128
  case 'log': return filterLog(raw);
@@ -113,4 +133,4 @@ function filter(subcmd, raw) {
113
133
  }
114
134
  }
115
135
 
116
- module.exports = { filter, filterLog, filterStatus, filterDiff };
136
+ module.exports = { filter, subcommand, filterLog, filterStatus, filterDiff };
@@ -12,12 +12,16 @@ const learn = require('../learn');
12
12
  const { countTokensApprox } = require('./utils');
13
13
 
14
14
  const HANDLERS = {
15
- git: (args, raw) => git.filter(args[0], raw),
15
+ git: (args, raw) => git.filter(git.subcommand(args), raw),
16
16
  ls: (_args, raw) => ls.filter(raw),
17
17
  tree: (_args, raw) => ls.filter(raw),
18
18
  cat: (_args, raw) => cat.filter(raw),
19
19
  head: (_args, raw) => cat.filter(raw, { maxLines: 50 }),
20
20
  tail: (_args, raw) => cat.filter(raw, { maxLines: 50 }),
21
+ // `sed -n 'a,bp' file` is how Codex and Claude read a slice of a file. The
22
+ // range is the agent's explicit choice, so never truncate it (the output
23
+ // spill still parks a runaway read); only ANSI and blank runs go.
24
+ sed: (_args, raw) => cat.filter(raw, { maxLines: Infinity }),
21
25
  grep: (_args, raw) => grep.filter(raw),
22
26
  rg: (_args, raw) => grep.filter(raw),
23
27
  ag: (_args, raw) => grep.filter(raw),
@@ -2,17 +2,70 @@
2
2
  'use strict';
3
3
 
4
4
  const { supportedFirstWords } = require('../filters');
5
+ const { topLevelOps, splitCdPrefix } = require('../shell');
5
6
 
6
7
  const FILTERED_CMDS = supportedFirstWords();
7
8
 
9
+ // Commands that may sit after a `|` without changing what the filter is for:
10
+ // they only cut the (already filtered) display. `| wc -l`, `| jq`, `| sh` or
11
+ // `| git apply` would consume filtered bytes as if they were the real output.
12
+ const PIPE_SINKS = new Set(['head', 'tail']);
13
+
14
+ // Redirections that never capture the filtered stdout into a file.
15
+ const HARMLESS_OPS = new Set(['dup', 'null']);
16
+
17
+ // Forms whose output is empty: rewriting them saves nothing, and the hook
18
+ // answers "allow", so leave them to the normal permission flow.
19
+ function isNoOutputForm(firstWord, rest) {
20
+ if (firstWord === 'sed') return /(^|\s)(-i|--in-place)/.test(rest);
21
+ return false;
22
+ }
23
+
24
+ // Rewrite a single command (no `cd` prefix). The hook approves what it
25
+ // rewrites, so it must only ever rewrite the command it can see: anything that
26
+ // chains another command (`&&`, `;`, `||`, `&`, newline), substitutes one
27
+ // (`$(…)`, backticks), writes the filtered output to a file (`>`), or pipes it
28
+ // into a consumer other than head/tail is left alone.
29
+ function rewriteSimple(command) {
30
+ const firstWord = command.split(/\s+/)[0];
31
+ if (!FILTERED_CMDS.has(firstWord)) return null;
32
+ if (isNoOutputForm(firstWord, command.slice(firstWord.length))) return null;
33
+ const ops = topLevelOps(command);
34
+ if (!ops) return null;
35
+ for (const { op, i } of ops) {
36
+ if (HARMLESS_OPS.has(op)) continue;
37
+ if (op !== '|') return null;
38
+ const sink = command.slice(i + 1).trim().split(/\s+/)[0];
39
+ if (!PIPE_SINKS.has(sink)) return null;
40
+ }
41
+ return `lakonai ${command}`;
42
+ }
43
+
8
44
  function rewriteIfNeeded(command) {
9
45
  if (typeof command !== 'string') return null;
10
46
  const trimmed = command.trim();
11
47
  if (!trimmed) return null;
12
48
  if (/^lakonai(\s|$)/.test(trimmed)) return null;
13
- const firstWord = trimmed.split(/\s+/)[0];
14
- if (!FILTERED_CMDS.has(firstWord)) return null;
15
- return `lakonai ${trimmed}`;
49
+ // `cd <dir> && cmd` is the dominant shape agents emit. Rewrite the command
50
+ // behind the prefix; `cd` itself has nothing to filter.
51
+ const cd = splitCdPrefix(trimmed);
52
+ if (cd) {
53
+ const inner = rewriteIfNeeded(cd.rest);
54
+ return inner ? `cd ${cd.dir} ${cd.op} ${inner}` : null;
55
+ }
56
+ return rewriteSimple(trimmed);
57
+ }
58
+
59
+ // The PreToolUse answer. Claude Code and Codex CLI share this shape: `allow`
60
+ // plus `updatedInput` (Codex rejects `updatedInput` without `allow`).
61
+ function buildResponse(toolInput, rewritten) {
62
+ return {
63
+ hookSpecificOutput: {
64
+ hookEventName: 'PreToolUse',
65
+ permissionDecision: 'allow',
66
+ updatedInput: { ...toolInput, command: rewritten },
67
+ },
68
+ };
16
69
  }
17
70
 
18
71
  /* istanbul ignore next */
@@ -36,17 +89,7 @@ async function main() {
36
89
  const rewritten = rewriteIfNeeded(command);
37
90
  if (!rewritten) process.exit(0);
38
91
 
39
- const response = {
40
- hookSpecificOutput: {
41
- hookEventName: 'PreToolUse',
42
- permissionDecision: 'allow',
43
- updatedInput: {
44
- ...data.tool_input,
45
- command: rewritten,
46
- },
47
- },
48
- };
49
- process.stdout.write(JSON.stringify(response));
92
+ process.stdout.write(JSON.stringify(buildResponse(data.tool_input, rewritten)));
50
93
  process.exit(0);
51
94
  } catch {
52
95
  process.exit(0);
@@ -56,4 +99,4 @@ async function main() {
56
99
  /* istanbul ignore next */
57
100
  if (require.main === module) main();
58
101
 
59
- module.exports = { rewriteIfNeeded, FILTERED_CMDS };
102
+ module.exports = { rewriteIfNeeded, rewriteSimple, buildResponse, FILTERED_CMDS, PIPE_SINKS };
@@ -0,0 +1,128 @@
1
+ 'use strict';
2
+
3
+ // Codex CLI hooks. Codex (0.16x+) reads Claude-compatible hooks from
4
+ // `~/.codex/hooks.json`: a PreToolUse handler matched on `Bash` gets
5
+ // `tool_input.command` and may answer `permissionDecision: "allow"` with
6
+ // `updatedInput.command`, which is exactly what bash-rewrite emits. So Codex
7
+ // gets the same automatic `lakonai` prefix as Claude Code, with no PATH shim.
8
+ //
9
+ // Codex only runs a non-managed hook after the user reviews and trusts it
10
+ // (`/hooks` in the TUI); until then it is skipped, never half-applied.
11
+
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const { backupFile } = require('./backup');
15
+ const { writeFileAtomic } = require('./atomic');
16
+
17
+ const HOOKS = [
18
+ {
19
+ basename: 'lakon-bash-rewrite.js',
20
+ src: path.join(__dirname, '..', 'hooks', 'bash-rewrite.js'),
21
+ event: 'PreToolUse',
22
+ matcher: '^Bash$',
23
+ },
24
+ ];
25
+
26
+ const BASENAMES = HOOKS.map((h) => h.basename);
27
+
28
+ function codexDir(home) {
29
+ return path.join(home, '.codex');
30
+ }
31
+
32
+ function hooksJsonPath(home) {
33
+ return path.join(codexDir(home), 'hooks.json');
34
+ }
35
+
36
+ function launcherPath(home, basename) {
37
+ return path.join(codexDir(home), 'hooks', basename);
38
+ }
39
+
40
+ function readHooksJson(home) {
41
+ const p = hooksJsonPath(home);
42
+ if (!fs.existsSync(p)) return { ok: true, data: {} };
43
+ try {
44
+ const data = JSON.parse(fs.readFileSync(p, 'utf8'));
45
+ return { ok: true, data: data && typeof data === 'object' ? data : {} };
46
+ } catch (err) {
47
+ return { ok: false, error: err.message };
48
+ }
49
+ }
50
+
51
+ const ownsHandler = (h) => !!h && typeof h.command === 'string' && BASENAMES.some((b) => h.command.includes(b));
52
+
53
+ // Drop every lakonai handler; returns the cleaned data (empty groups removed).
54
+ function stripOurs(data) {
55
+ if (!data.hooks || typeof data.hooks !== 'object') return data;
56
+ for (const event of Object.keys(data.hooks)) {
57
+ if (!Array.isArray(data.hooks[event])) continue;
58
+ data.hooks[event] = data.hooks[event]
59
+ .map((group) => {
60
+ if (!group || !Array.isArray(group.hooks)) return group;
61
+ const keep = group.hooks.filter((h) => !ownsHandler(h));
62
+ return keep.length ? { ...group, hooks: keep } : null;
63
+ })
64
+ .filter(Boolean);
65
+ if (!data.hooks[event].length) delete data.hooks[event];
66
+ }
67
+ if (!Object.keys(data.hooks).length) delete data.hooks;
68
+ return data;
69
+ }
70
+
71
+ function installCodexHooks(home) {
72
+ const { ok, data, error } = readHooksJson(home);
73
+ if (!ok) return { installed: false, note: `hooks.json could not be parsed (${error})` };
74
+ const p = hooksJsonPath(home);
75
+ if (fs.existsSync(p)) backupFile('codex', p);
76
+
77
+ stripOurs(data); // idempotent: re-install replaces, never duplicates
78
+ data.hooks = data.hooks || {};
79
+ for (const h of HOOKS) {
80
+ const dest = launcherPath(home, h.basename);
81
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
82
+ fs.writeFileSync(
83
+ dest,
84
+ `#!/usr/bin/env node\n// lakonai hook launcher (generated)\nrequire('module')._load(${JSON.stringify(h.src)}, null, true);\n`
85
+ );
86
+ fs.chmodSync(dest, 0o755);
87
+ data.hooks[h.event] = data.hooks[h.event] || [];
88
+ data.hooks[h.event].push({
89
+ matcher: h.matcher,
90
+ hooks: [{ type: 'command', command: dest, timeout: 10 }],
91
+ });
92
+ }
93
+ writeFileAtomic(p, JSON.stringify(data, null, 2) + '\n');
94
+ return { installed: true, path: p };
95
+ }
96
+
97
+ function uninstallCodexHooks(home) {
98
+ const { ok, data } = readHooksJson(home);
99
+ const p = hooksJsonPath(home);
100
+ if (ok && fs.existsSync(p)) {
101
+ stripOurs(data);
102
+ if (Object.keys(data).length) writeFileAtomic(p, JSON.stringify(data, null, 2) + '\n');
103
+ else fs.unlinkSync(p);
104
+ }
105
+ for (const b of BASENAMES) {
106
+ try {
107
+ fs.unlinkSync(launcherPath(home, b));
108
+ } catch {
109
+ /* already gone */
110
+ }
111
+ }
112
+ }
113
+
114
+ function codexHooksInstalled(home) {
115
+ const { ok, data } = readHooksJson(home);
116
+ if (!ok || !data.hooks) return false;
117
+ return JSON.stringify(data.hooks).includes('lakon-bash-rewrite.js');
118
+ }
119
+
120
+ module.exports = {
121
+ installCodexHooks,
122
+ uninstallCodexHooks,
123
+ codexHooksInstalled,
124
+ hooksJsonPath,
125
+ launcherPath,
126
+ stripOurs,
127
+ HOOKS,
128
+ };
@@ -5,6 +5,7 @@ const path = require('path');
5
5
  const { backupFile, restoreAllBackups } = require('./backup');
6
6
  const { installHook, uninstallHook } = require('./claude-hook');
7
7
  const { installCommands, uninstallCommands } = require('./claude-commands');
8
+ const { installCodexHooks, uninstallCodexHooks, codexHooksInstalled } = require('./codex-hook');
8
9
  const { wrapMcp, unwrapMcp } = require('./mcp');
9
10
  const { writeFileAtomic } = require('./atomic');
10
11
  const { claudeConfigDir } = require('./paths');
@@ -113,9 +114,22 @@ const PLATFORMS = [
113
114
  label: 'Codex CLI',
114
115
  scope: 'global',
115
116
  rulePath: (home) => path.join(home, '.codex', 'AGENTS.md'),
117
+ hasHooks: true,
118
+ hooksInstalled: (home) => codexHooksInstalled(home),
116
119
  detect: (home) => dirExists(path.join(home, '.codex')),
117
- install: ({ home, rule, id }) => upsertBlock(id, path.join(home, '.codex', 'AGENTS.md'), rule),
118
- uninstall: ({ home }) => stripBlock(path.join(home, '.codex', 'AGENTS.md')),
120
+ install: ({ home, rule, id }) => {
121
+ const rulePath = upsertBlock(id, path.join(home, '.codex', 'AGENTS.md'), rule);
122
+ const hooks = installCodexHooks(home);
123
+ /* istanbul ignore next -- the parse-failure note is covered in codex-hook tests */
124
+ const suffix = hooks.installed
125
+ ? '+ PreToolUse hook (trust it once with /hooks in Codex)'
126
+ : `(hook: ${hooks.note})`;
127
+ return `${rulePath} ${suffix}`;
128
+ },
129
+ uninstall: ({ home }) => {
130
+ uninstallCodexHooks(home);
131
+ return stripBlock(path.join(home, '.codex', 'AGENTS.md'));
132
+ },
119
133
  },
120
134
  {
121
135
  id: 'cursor',
@@ -3,6 +3,7 @@
3
3
  const fs = require('fs');
4
4
  const path = require('path');
5
5
  const os = require('os');
6
+ const { isLearnable } = require('./learn');
6
7
 
7
8
  const DAY_MS = 24 * 60 * 60 * 1000;
8
9
  const REPORT_TTL_MS = DAY_MS;
@@ -61,7 +62,7 @@ function readLogSinks() {
61
62
  function readUnfilteredSinks(isBuiltin) {
62
63
  const stats = readJson(statsPath(), {});
63
64
  return Object.entries(stats)
64
- .filter(([cmd]) => !isBuiltin(cmd))
65
+ .filter(([cmd]) => !isBuiltin(cmd) && isLearnable(cmd))
65
66
  .map(([cmd, s]) => ({
66
67
  cmd,
67
68
  calls: s.count,
package/src/learn.js CHANGED
@@ -15,6 +15,7 @@ const fs = require('fs');
15
15
  const path = require('path');
16
16
  const os = require('os');
17
17
  const { countTokensApprox } = require('./filters/utils');
18
+ const { splitCdPrefix } = require('./shell');
18
19
 
19
20
  const MIN_CALLS = Number(process.env.LAKON_LEARN_MIN_CALLS) || 3;
20
21
  const MIN_AVG_TOKENS = Number(process.env.LAKON_LEARN_MIN_TOKENS) || 300;
@@ -44,12 +45,44 @@ function writeJson(file, data) {
44
45
  }
45
46
  }
46
47
 
47
- // Base command of a shell string, skipping env assignments / sudo / env.
48
+ // A learnable command is a bare executable name. Paths, quoted fragments,
49
+ // flags and split-up arguments (`Support/…` from an unquoted
50
+ // `Application Support`, `-n`, `foo;`) were landing in learned.json.
51
+ const VALID_NAME = /^[A-Za-z0-9_][\w.+-]*$/;
52
+
53
+ // Never learned, even when they are loud:
54
+ // - shell builtins / keywords and lakonai itself — nothing to filter, or
55
+ // the output is already filtered;
56
+ // - agent tool names logged by the guards (Read, Grep, …);
57
+ // - interpreters and file mutators — a learned command is rewritten by the
58
+ // PreToolUse hook, which answers "allow", and `node -e …` or `rm` must
59
+ // keep going through the user's own permission rules.
60
+ const NEVER_LEARN = new Set([
61
+ 'cd', 'echo', 'printf', 'export', 'source', 'set', 'unset', 'eval', 'exec', 'exit',
62
+ 'command', 'builtin', 'type', 'which', 'alias', 'true', 'false', 'test',
63
+ 'for', 'while', 'until', 'if', 'then', 'else', 'fi', 'do', 'done', 'case', 'esac',
64
+ 'sleep', 'wait', 'read', 'pwd', 'time', 'lakonai',
65
+ 'Read', 'Grep', 'Glob', 'Bash', 'Edit', 'Write',
66
+ 'node', 'python', 'python3', 'ruby', 'perl', 'php', 'deno', 'bun',
67
+ 'bash', 'sh', 'zsh', 'fish', 'osascript',
68
+ 'rm', 'mv', 'cp', 'ln', 'chmod', 'chown', 'mkdir', 'rmdir', 'touch', 'kill', 'pkill',
69
+ 'dd', 'tee', 'xargs', 'sudo', 'env',
70
+ ]);
71
+
72
+ function isLearnable(cmd) {
73
+ return typeof cmd === 'string' && VALID_NAME.test(cmd) && !NEVER_LEARN.has(cmd);
74
+ }
75
+
76
+ // Base command of a shell string: skips `cd <dir> &&` prefixes, env
77
+ // assignments and sudo/env, and returns '' for anything that is not learnable.
48
78
  function baseCommand(command) {
49
- const tokens = String(command).trim().split(/\s+/);
79
+ let s = String(command).trim();
80
+ for (let cd = splitCdPrefix(s); cd; cd = splitCdPrefix(s)) s = cd.rest;
81
+ const tokens = s.split(/\s+/);
50
82
  let i = 0;
51
83
  while (i < tokens.length && (/^\w+=/.test(tokens[i]) || tokens[i] === 'sudo' || tokens[i] === 'env')) i++;
52
- return tokens[i] || '';
84
+ const cmd = tokens[i] || '';
85
+ return isLearnable(cmd) ? cmd : '';
53
86
  }
54
87
 
55
88
  // Parse a Claude Code transcript (JSONL) into [{ cmd, tokens }] for every Bash
@@ -97,7 +130,7 @@ function promote(stats, isBuiltin) {
97
130
  const learned = new Set(readJson(learnedPath(), []));
98
131
  let changed = false;
99
132
  for (const [cmd, s] of Object.entries(stats)) {
100
- if (learned.has(cmd) || isBuiltin(cmd)) continue;
133
+ if (learned.has(cmd) || isBuiltin(cmd) || !isLearnable(cmd)) continue;
101
134
  if (s.count >= MIN_CALLS && s.tokens / s.count >= MIN_AVG_TOKENS) {
102
135
  learned.add(cmd);
103
136
  changed = true;
@@ -154,7 +187,7 @@ function analyzeLog(isBuiltin) {
154
187
  continue;
155
188
  }
156
189
  const cmd = e && typeof e.cmd === 'string' ? e.cmd : null;
157
- if (!cmd || cmd === 'session' || isBuiltin(cmd)) continue;
190
+ if (!cmd || cmd === 'session' || isBuiltin(cmd) || !isLearnable(cmd)) continue;
158
191
  const s = stats[cmd] || { count: 0, tokens: 0 };
159
192
  s.count += 1;
160
193
  s.tokens += e.raw || 0;
@@ -179,7 +212,12 @@ function maybeLearnFromLog(isBuiltin, now = Date.now()) {
179
212
 
180
213
  let _learnedCache;
181
214
  function learnedCommands() {
182
- if (_learnedCache === undefined) _learnedCache = new Set(readJson(learnedPath(), []));
215
+ // Filter on read, so entries learned by older versions (paths, `node`)
216
+ // stop being rewritten without anyone editing learned.json by hand.
217
+ if (_learnedCache === undefined) {
218
+ const raw = readJson(learnedPath(), []);
219
+ _learnedCache = new Set(Array.isArray(raw) ? raw.filter(isLearnable) : []);
220
+ }
183
221
  return _learnedCache;
184
222
  }
185
223
  function isLearned(cmd) {
@@ -192,6 +230,8 @@ function _resetCache() {
192
230
 
193
231
  module.exports = {
194
232
  baseCommand,
233
+ isLearnable,
234
+ NEVER_LEARN,
195
235
  extractBashUsage,
196
236
  promote,
197
237
  analyzeTranscript,
package/src/shell.js ADDED
@@ -0,0 +1,141 @@
1
+ 'use strict';
2
+
3
+ // A deliberately small shell lexer. lakonai never executes or rewrites shell
4
+ // syntax it does not understand: these helpers only answer two questions about
5
+ // a command string — "which control operators appear at the top level (outside
6
+ // quotes)?" and "does it start with a `cd <dir> &&` prefix?". Anything the
7
+ // lexer cannot account for (an unbalanced quote) makes the caller back off.
8
+
9
+ // Operators reported at the top level of a command:
10
+ // '&&' '||' ';' '&' '\n' '|' — command separators / pipes
11
+ // '$(' '`' — command substitution (also inside "…")
12
+ // '>' '<' — a redirection that touches a file
13
+ // 'dup' — an fd duplication such as `2>&1`
14
+ // 'null' — a redirection to /dev/null
15
+ // Returns [{ op, i }] in source order, or null for an unbalanced quote.
16
+ function topLevelOps(s) {
17
+ const ops = [];
18
+ let i = 0;
19
+ let quote = null;
20
+ while (i < s.length) {
21
+ const c = s[i];
22
+ if (quote === "'") {
23
+ if (c === "'") quote = null;
24
+ i++;
25
+ continue;
26
+ }
27
+ if (quote === '"') {
28
+ if (c === '\\') {
29
+ i += 2;
30
+ continue;
31
+ }
32
+ if (c === '"') quote = null;
33
+ else if (c === '`') ops.push({ op: '`', i });
34
+ else if (c === '$' && s[i + 1] === '(') ops.push({ op: '$(', i });
35
+ i++;
36
+ continue;
37
+ }
38
+ if (c === '\\') {
39
+ i += 2;
40
+ continue;
41
+ }
42
+ if (c === "'" || c === '"') {
43
+ quote = c;
44
+ i++;
45
+ continue;
46
+ }
47
+ if (c === '`') {
48
+ ops.push({ op: '`', i });
49
+ i++;
50
+ continue;
51
+ }
52
+ if (c === '$' && s[i + 1] === '(') {
53
+ ops.push({ op: '$(', i });
54
+ i += 2;
55
+ continue;
56
+ }
57
+ if (c === ';' || c === '\n') {
58
+ ops.push({ op: c, i });
59
+ i++;
60
+ continue;
61
+ }
62
+ if (c === '&' || c === '|') {
63
+ if (s[i + 1] === c) {
64
+ ops.push({ op: c + c, i });
65
+ i += 2;
66
+ } else {
67
+ ops.push({ op: c, i });
68
+ i++;
69
+ }
70
+ continue;
71
+ }
72
+ if (c === '>') {
73
+ const rest = s.slice(i + 1);
74
+ const dup = /^&[0-9]/.exec(rest);
75
+ if (dup && /[0-9]/.test(s[i - 1] || '')) {
76
+ ops.push({ op: 'dup', i });
77
+ i += 1 + dup[0].length;
78
+ continue;
79
+ }
80
+ const devnull = /^\s*\/dev\/null(?=\s|$)/.exec(rest);
81
+ if (devnull) {
82
+ ops.push({ op: 'null', i });
83
+ i += 1 + devnull[0].length;
84
+ continue;
85
+ }
86
+ ops.push({ op: '>', i });
87
+ i++;
88
+ continue;
89
+ }
90
+ if (c === '<') {
91
+ ops.push({ op: '<', i });
92
+ i++;
93
+ continue;
94
+ }
95
+ i++;
96
+ }
97
+ return quote ? null : ops;
98
+ }
99
+
100
+ // True when `s` is exactly one shell word: no top-level whitespace, quotes
101
+ // balanced. `"my dir"` and `my\ dir` are one word; `a b` is two.
102
+ function isSingleWord(s) {
103
+ if (!s) return false;
104
+ let quote = null;
105
+ for (let i = 0; i < s.length; i++) {
106
+ const c = s[i];
107
+ if (quote) {
108
+ if (c === '\\' && quote === '"') i++;
109
+ else if (c === quote) quote = null;
110
+ continue;
111
+ }
112
+ if (c === '\\') {
113
+ i++;
114
+ continue;
115
+ }
116
+ if (c === "'" || c === '"') quote = c;
117
+ else if (/\s/.test(c)) return false;
118
+ }
119
+ return !quote;
120
+ }
121
+
122
+ // Split a leading `cd <dir> && rest` / `cd <dir>; rest` into its parts. Agents
123
+ // prefix most commands this way, and a first-word match alone never sees the
124
+ // command that actually produces the output. Returns { dir, op, rest } or null
125
+ // when the command does not start with exactly that shape.
126
+ function splitCdPrefix(command) {
127
+ const s = String(command).trim();
128
+ const m = /^cd[ \t]+/.exec(s);
129
+ if (!m) return null;
130
+ const ops = topLevelOps(s);
131
+ if (!ops || !ops.length) return null;
132
+ const first = ops[0];
133
+ if (first.op !== '&&' && first.op !== ';') return null;
134
+ const dir = s.slice(m[0].length, first.i).trim();
135
+ if (!isSingleWord(dir)) return null;
136
+ const rest = s.slice(first.i + first.op.length).trim();
137
+ if (!rest) return null;
138
+ return { dir, op: first.op, rest };
139
+ }
140
+
141
+ module.exports = { topLevelOps, isSingleWord, splitCdPrefix };
package/src/tracking.js CHANGED
@@ -17,6 +17,18 @@ function logPath() {
17
17
  return path.join(dataDir(), 'log.jsonl');
18
18
  }
19
19
 
20
+ // Which agent ran the command. Every agent spawns its shell with its own
21
+ // marker: Claude Code sets CLAUDECODE=1; Codex CLI sets CODEX_THREAD_ID /
22
+ // CODEX_TOOL_CALL_ID (CODEX_SANDBOX* under its sandbox); Gemini CLI sets
23
+ // GEMINI_CLI=1. LAKON_AGENT overrides, for agents with no marker.
24
+ function detectAgent(env = process.env) {
25
+ if (env.LAKON_AGENT) return String(env.LAKON_AGENT);
26
+ if (env.CLAUDECODE === '1') return 'claude';
27
+ if (env.CODEX_THREAD_ID || env.CODEX_TOOL_CALL_ID || env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED) return 'codex';
28
+ if (env.GEMINI_CLI === '1') return 'gemini';
29
+ return 'other';
30
+ }
31
+
20
32
  function record({ cmd, args, rawTokens, filteredTokens }) {
21
33
  if (process.env.LAKON_NO_TRACK === '1') return;
22
34
  try {
@@ -28,6 +40,7 @@ function record({ cmd, args, rawTokens, filteredTokens }) {
28
40
  raw: rawTokens,
29
41
  out: filteredTokens,
30
42
  saved: Math.max(0, rawTokens - filteredTokens),
43
+ agent: detectAgent(),
31
44
  };
32
45
  fs.appendFileSync(logPath(), JSON.stringify(entry) + '\n');
33
46
  /* istanbul ignore next */
@@ -112,6 +125,22 @@ function responseStats(entries) {
112
125
  };
113
126
  }
114
127
 
128
+ // Savings per agent. Entries written before the agent field existed are
129
+ // grouped as 'unknown' rather than guessed.
130
+ function byAgent(entries) {
131
+ const map = new Map();
132
+ for (const e of entries) {
133
+ if (isSessionEntry(e)) continue;
134
+ const k = e.agent || 'unknown';
135
+ if (!map.has(k)) map.set(k, { agent: k, calls: 0, raw: 0, saved: 0 });
136
+ const acc = map.get(k);
137
+ acc.calls += 1;
138
+ acc.raw += e.raw || 0;
139
+ acc.saved += e.saved || 0;
140
+ }
141
+ return [...map.values()].sort((a, b) => b.saved - a.saved);
142
+ }
143
+
115
144
  function pct(saved, raw) {
116
145
  if (!raw) return 0;
117
146
  return Math.round((saved / raw) * 100);
@@ -177,6 +206,12 @@ function report() {
177
206
  );
178
207
  }
179
208
 
209
+ const agents = byAgent(entries).filter((a) => a.agent !== 'unknown');
210
+ if (agents.length) {
211
+ lines.push('');
212
+ lines.push(' ' + dim('by agent: ') + agents.map((a) => `${a.agent} ${green(tok(a.saved))} ${dim(`(${pct(a.saved, a.raw)}%)`)}`).join(dim(' · ')));
213
+ }
214
+
180
215
  const top = byCommand(entries).slice(0, 5);
181
216
  if (top.length) {
182
217
  lines.push('');
@@ -191,4 +226,4 @@ function reset() {
191
226
  catch { return false; }
192
227
  }
193
228
 
194
- module.exports = { record, report, reset, readEntries, logPath, responseStats };
229
+ module.exports = { record, report, reset, readEntries, logPath, responseStats, detectAgent, byAgent };