lakonai 0.7.1 → 0.8.0

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
@@ -22,6 +22,8 @@
22
22
 
23
23
  <p align="center">
24
24
  One command. <strong>Three fronts</strong>: terse model output · filtered shell output · blocked junk reads.<br/>
25
+ Filters <strong>30 commands</strong> — git, ls, grep, find, <strong>test runners, lint/build, docker/kubectl/aws</strong> —<br/>
26
+ and <strong>learns to filter new ones automatically the more you use it</strong>.<br/>
25
27
  Plus session-level token tracking and one-day update notifications.<br/>
26
28
  Works across <strong>Claude Code, Codex, Cursor, Windsurf, Cline, Gemini CLI</strong>.
27
29
  </p>
@@ -37,6 +39,7 @@
37
39
  | `git diff HEAD~5` | 13,230 | 798 | **-89%** |
38
40
  | `git log --stat -50` | 4,845 | 439 | **-86%** |
39
41
  | `git status` | 17 | 1 | **-89%** |
42
+ | `npm test` (passing suite) | 4,451 | 358 | **-92%** |
40
43
  | `Read pnpm-lock.yaml` | ~56,000 | **blocked** | **-95%** |
41
44
  | `Grep` (auto `head_limit`) | unbounded | 30 matches | **capped** |
42
45
 
@@ -67,13 +70,15 @@ Your AI coding agent does. It opens with *"Sure! I'd be happy to help…"*, repe
67
70
  | Front | Wasted tokens look like… | lakonai fixes it by… |
68
71
  |--------------------------------|-------------------------------------------------------|-------------------------------------------------------------------------------------|
69
72
  | **Output** (the model) | *"Great question! Let me explain…"* | Installing a terse-response rule. No preamble, no recap, no restating. |
70
- | **Input** (your shell tools) | `git log` dumping 1.8 k tokens of author metadata | Wrapping `git`/`ls`/`grep`/`cat`/`tree`/`head`/`tail` and compressing before context. |
73
+ | **Input** (your shell tools) | `git log` dumping 1.8 k tokens of author metadata | Wrapping **30 commands** — `git`/`ls`/`grep`/`cat`/`find`, **test runners** (jest/pytest/go/cargo), **lint/build** (tsc/eslint/ruff/make), **docker/kubectl/aws** — and compressing before context. |
71
74
  | **Reads** (file ingestion) | Agent runs `Read` on `pnpm-lock.yaml` → 80 k of nothing | A `PreToolUse` hook on `Read` blocks lockfiles & `node_modules`, caps files >800 lines. |
72
75
  | **Search** (Grep tool) | `Grep` returns 800 matches and you re-read every one | A `PreToolUse` hook on `Grep` auto-caps `head_limit` at 30 with a one-shot hint. |
73
76
  | **Analysis** (the rule) | `Read` 5k of logs to count errors in your head | "Think in code" — write `node -e '…filter…count'`, consume only the answer. |
74
77
 
75
78
  Other tools stop at one front. lakonai does all three transparently — your agent doesn't have to remember anything.
76
79
 
80
+ > **★ It gets better the more you use it.** lakonai watches your session history and, when an unfiltered command keeps showing up with heavy output, it **turns on a safe filter for that command automatically** — no config, no manual rules. Similar tools only *report* what you're missing; lakonai just fixes it. (Near-lossless: it collapses repetition and truncates with a marker, never silently dropping a line that could be an error. Opt out with `LAKON_NO_LEARN=1`.)
81
+
77
82
  ---
78
83
 
79
84
  ## Quick start
@@ -108,20 +113,22 @@ You'll see savings stack up immediately in `lakonai gain`.
108
113
 
109
114
  > **Worried?** Every install backs up the target file first. `lakonai revert` puts it back byte-for-byte.
110
115
 
111
- > **Upgrading from `lakon`?** The package was renamed to **lakonai** in 0.7.0. The `lakon` and `lak` commands still work as aliases, your `~/.lakon/` log + backups carry over untouched, and `lakonai install` rewrites your existing config block to the new brand. No migration needed.
116
+ > **Upgrading from `lakon`?** The package was renamed to **lakonai** in 0.7.0; the legacy `lakon` / `lak` command aliases were since removed — use `lakonai`. Your `~/.lakon/` log + backups carry over untouched, and `lakonai install` rewrites your existing config block to the new brand.
112
117
 
113
118
  ---
114
119
 
115
120
  ## Use the filter directly
116
121
 
117
- The CLI works as a standalone tool too. Run any shell command through `lakonai` (or the short alias `lak`) to filter its output:
122
+ The CLI works as a standalone tool too. Run any shell command through `lakonai` to filter its output:
118
123
 
119
124
  ```bash
120
125
  lakonai git status # compressed git status
121
126
  lakonai git log -50 # one line per commit (hash + subject)
122
127
  lakonai git diff # only +/- lines, no noise
123
128
  lakonai ls -la # size + name only
124
- lakonai grep -r foo src/ # truncates at 40 matches
129
+ lakonai grep -r foo src/ # truncates at 15 matches
130
+ lakonai npm test # passing suite collapses to its summary line
131
+ lakonai find . -name '*.ts' # groups matches by directory
125
132
  ```
126
133
 
127
134
  Unsupported commands run unchanged.
@@ -191,8 +198,6 @@ saved: 85%
191
198
  | `lakonai reset` | Wipe the savings log |
192
199
  | `lakonai version` / `--version` / `-v` | Print the installed lakonai version |
193
200
 
194
- `lak` is the short alias for `lakonai`. `lakon` is kept as a legacy alias so existing setups keep working.
195
-
196
201
  ---
197
202
 
198
203
  ## Supported filters
@@ -206,9 +211,25 @@ saved: 85%
206
211
  | `cat` | Collapses blank-line runs, cap 200 lines |
207
212
  | `head` / `tail` | Cap 50 lines |
208
213
  | `grep` / `rg` / `ag` | Cap 15 matches with "tighten the pattern" hint |
214
+ | `find` | Groups matched paths by directory, drops permission-denied noise |
215
+ | test runners | jest/vitest/mocha/pytest/ava, `npm/pnpm/yarn/bun test`, `go test`, `cargo test` — collapse passes, keep failures + summary |
216
+ | lint / build | `tsc`, `eslint`, `ruff`, `cargo clippy`, `make` — strip noise, "ok" when clean |
217
+ | pkg / cloud | `npm/pnpm/yarn/bun install`, `diff`, `docker`, `kubectl`, `aws` — strip progress/noise, cap |
218
+
219
+ The last three groups are powered by a declarative engine (`src/filters/defs.js`)
220
+ plus a couple of structured filters; adding a new command is usually one data entry.
209
221
 
210
222
  Unsupported commands run unchanged (passthrough), still tracked at 0 % savings.
211
223
 
224
+ ### Gets better the more you use it (auto-learning)
225
+
226
+ lakonai watches your session history (the Claude Code transcript) and, when an
227
+ **unfiltered** command keeps showing up with heavy output, it **enables a
228
+ conservative filter for it automatically** — no config, no manual rules. The
229
+ auto-filter is near-lossless (collapses repeated/blank lines, truncates only
230
+ with an announced marker) so it never hides a real error. Disable with
231
+ `LAKON_NO_LEARN=1`.
232
+
212
233
  ### Read tool guard (Claude Code)
213
234
 
214
235
  The `Read` hook automatically:
@@ -328,16 +349,16 @@ Every token your agent emits or reads is paid for — in latency, in money, in c
328
349
  ## Development
329
350
 
330
351
  ```bash
331
- git clone https://github.com/bargadev/lakonai-lib
332
- cd lakonai-lib
333
- npm install # only devDeps (c8 for coverage); zero runtime deps
334
- node --test tests/ # run the suite
352
+ git clone https://github.com/bargadev/lakonai
353
+ cd lakonai
354
+ npm install # only devDeps (jest for tests/coverage); zero runtime deps
355
+ npm test # run the Jest suite
335
356
  npm run test:coverage # text + HTML coverage report (coverage/index.html)
336
- npm run test:coverage:check # fail if any metric drops below 100%
357
+ npm run test:coverage:check # enforce the coverage threshold
337
358
  node bin/lakonai.js --help
338
359
  ```
339
360
 
340
- Suite: **187 tests**. Coverage gate: **100% lines / 100% branches / 100% functions / 100% statements**. Zero runtime dependencies. Node ≥ 18.
361
+ Suite: **270 tests**. Coverage gate: **100% lines / 100% branches / 100% functions / 100% statements**. Zero runtime dependencies. Node ≥ 18.
341
362
 
342
363
  ---
343
364
 
package/bin/lakonai.js CHANGED
@@ -2,7 +2,7 @@
2
2
  'use strict';
3
3
 
4
4
  const { spawnSync } = require('child_process');
5
- const { filterCommand, isSupported, countTokensApprox } = require('../src/filters');
5
+ const { filterCommand, isSupported, needsStderr, countTokensApprox } = require('../src/filters');
6
6
  const { install, uninstall, revert, listPlatforms, backupsReport } = require('../src/install');
7
7
  const tracking = require('../src/tracking');
8
8
  const versionCheck = require('../src/hooks/version-check');
@@ -11,8 +11,6 @@ const HELP = `lakonai — spartan replies for AI agents
11
11
 
12
12
  Usage:
13
13
  lakonai <cmd> [args...] Run <cmd> and filter its output (tracks savings)
14
- lak <cmd> [args...] (short alias)
15
- lakon <cmd> [args...] (legacy alias, kept for back-compat)
16
14
 
17
15
  lakonai install Install rule + hooks for detected GLOBAL platforms
18
16
  (Claude Code / Codex / Gemini — touches ~/ only)
@@ -31,7 +29,11 @@ Usage:
31
29
  lakonai version Print the installed lakonai version
32
30
  lakonai --help This help
33
31
 
34
- Supported filters: git (log/status/diff/show), ls, tree, cat, head, tail, grep, rg, ag.
32
+ Supported filters:
33
+ files/search git (log/status/diff/show), ls, tree, cat, head, tail, grep, rg, ag, find
34
+ test runners jest, vitest, mocha, pytest, ava; npm/pnpm/yarn/bun test, go test, cargo test
35
+ lint/build tsc, eslint, ruff, cargo clippy, make
36
+ pkg/cloud npm/pnpm/yarn/bun install, diff, docker, kubectl, aws
35
37
  Unsupported commands run unchanged (passthrough, still tracked as 0% savings).
36
38
 
37
39
  Multi-profile Claude Code (e.g. claude-my / claude-arco wrappers):
@@ -44,16 +46,18 @@ Update notifications:
44
46
  `;
45
47
 
46
48
  function runAndFilter(cmd, args) {
47
- const child = spawnSync(cmd, args, { encoding: 'utf8', stdio: ['inherit', 'pipe', 'inherit'] });
49
+ const merge = needsStderr(cmd, args);
50
+ const stdio = merge ? ['inherit', 'pipe', 'pipe'] : ['inherit', 'pipe', 'inherit'];
51
+ const child = spawnSync(cmd, args, { encoding: 'utf8', stdio });
48
52
  if (child.error) {
49
53
  process.stderr.write(`lakonai: ${child.error.message}\n`);
50
54
  process.exit(127);
51
55
  }
52
- /* c8 ignore next */
53
- const raw = child.stdout || '';
56
+ /* istanbul ignore next -- defensive empty-stream fallbacks */
57
+ const raw = merge ? (child.stdout || '') + (child.stderr || '') : child.stdout || '';
54
58
  const filtered = isSupported(cmd) ? filterCommand(cmd, args, raw) : raw;
55
59
  process.stdout.write(filtered);
56
- /* c8 ignore next */
60
+ /* istanbul ignore next */
57
61
  if (filtered && !filtered.endsWith('\n')) process.stdout.write('\n');
58
62
 
59
63
  tracking.record({
@@ -63,7 +67,7 @@ function runAndFilter(cmd, args) {
63
67
  filteredTokens: countTokensApprox(filtered),
64
68
  });
65
69
 
66
- /* c8 ignore next */
70
+ /* istanbul ignore next */
67
71
  process.exit(child.status ?? 0);
68
72
  }
69
73
 
@@ -73,13 +77,14 @@ function inspectCmd(rest) {
73
77
  process.exit(2);
74
78
  }
75
79
  const [cmd, ...args] = rest;
80
+ const merge = needsStderr(cmd, args);
76
81
  const child = spawnSync(cmd, args, { encoding: 'utf8' });
77
- /* c8 ignore next */
78
- const raw = child.stdout || '';
82
+ /* istanbul ignore next -- defensive empty-stream fallbacks */
83
+ const raw = merge ? (child.stdout || '') + (child.stderr || '') : child.stdout || '';
79
84
  const filtered = isSupported(cmd) ? filterCommand(cmd, args, raw) : raw;
80
85
  const rawTokens = countTokensApprox(raw);
81
86
  const newTokens = countTokensApprox(filtered);
82
- /* c8 ignore next */
87
+ /* istanbul ignore next */
83
88
  const saved = rawTokens === 0 ? 0 : Math.round((1 - newTokens / rawTokens) * 100);
84
89
  process.stdout.write(
85
90
  `cmd: ${cmd} ${args.join(' ')}\n` +
@@ -98,13 +103,13 @@ function maybePrintUpdateHint() {
98
103
  try {
99
104
  const update = versionCheck.getCachedUpdate();
100
105
  if (update) {
101
- /* c8 ignore next */
106
+ /* istanbul ignore next */
102
107
  const color = !process.env.NO_COLOR && process.stderr.isTTY;
103
108
  const msg = versionCheck.formatNotice(update);
104
- /* c8 ignore next */
109
+ /* istanbul ignore next */
105
110
  process.stderr.write(color ? `\n\x1b[33m${msg}\x1b[0m\n` : `\n${msg}\n`);
106
111
  }
107
- /* c8 ignore next 3 */
112
+ /* istanbul ignore next */
108
113
  } catch {
109
114
  // never let update hint break a command
110
115
  }
@@ -118,7 +123,7 @@ async function main() {
118
123
  }
119
124
  if (argv[0] === '--version' || argv[0] === '-v' || argv[0] === 'version') {
120
125
  printVersion();
121
- await versionCheck.checkForUpdate().catch(() => {});
126
+ await versionCheck.checkForUpdate().catch(/* istanbul ignore next */ () => {});
122
127
  maybePrintUpdateHint();
123
128
  return;
124
129
  }
@@ -127,7 +132,7 @@ async function main() {
127
132
 
128
133
  if (first === 'install') {
129
134
  const onlyIdx = rest.indexOf('--only');
130
- /* c8 ignore next */
135
+ /* istanbul ignore next */
131
136
  const only = onlyIdx >= 0 ? rest[onlyIdx + 1] : null;
132
137
  const here = rest.includes('--here');
133
138
  await install({ only, here });
@@ -139,7 +144,7 @@ async function main() {
139
144
  }
140
145
  if (first === 'revert') {
141
146
  const onlyIdx = rest.indexOf('--only');
142
- /* c8 ignore next */
147
+ /* istanbul ignore next */
143
148
  const only = onlyIdx >= 0 ? rest[onlyIdx + 1] : null;
144
149
  await revert({ only });
145
150
  return;
@@ -154,7 +159,7 @@ async function main() {
154
159
  }
155
160
  if (first === 'gain' || first === 'stats') {
156
161
  process.stdout.write(tracking.report());
157
- await versionCheck.checkForUpdate().catch(() => {});
162
+ await versionCheck.checkForUpdate().catch(/* istanbul ignore next */ () => {});
158
163
  maybePrintUpdateHint();
159
164
  return;
160
165
  }
@@ -171,8 +176,12 @@ async function main() {
171
176
  runAndFilter(first, rest);
172
177
  }
173
178
 
174
- /* c8 ignore next 4 */
175
- main().catch((err) => {
176
- process.stderr.write(`lakonai: ${err.message}\n`);
177
- process.exit(1);
178
- });
179
+ /* istanbul ignore next */
180
+ if (require.main === module) {
181
+ main().catch((err) => {
182
+ process.stderr.write(`lakonai: ${err.message}\n`);
183
+ process.exit(1);
184
+ });
185
+ }
186
+
187
+ module.exports = { runAndFilter, inspectCmd, printVersion, main, HELP };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "lakonai",
3
- "version": "0.7.1",
4
- "description": "lakonai — Spartan replies for AI agents. Terse model output + filtered CLI output for Claude Code, Codex, Cursor, Windsurf, Cline, and Gemini.",
3
+ "version": "0.8.0",
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",
7
7
  "claude-code",
@@ -12,26 +12,30 @@
12
12
  "gemini",
13
13
  "llm",
14
14
  "tokens",
15
+ "token-savings",
15
16
  "context-window",
16
17
  "ai-coding",
17
- "agent"
18
+ "agent",
19
+ "cli",
20
+ "output-filter",
21
+ "test-runner",
22
+ "eslint",
23
+ "pytest"
18
24
  ],
19
25
  "license": "MIT",
20
26
  "author": "bargadev",
21
- "homepage": "https://github.com/bargadev/lakonai-lib",
27
+ "homepage": "https://github.com/bargadev/lakonai",
22
28
  "repository": {
23
29
  "type": "git",
24
- "url": "git+https://github.com/bargadev/lakonai-lib.git"
30
+ "url": "git+https://github.com/bargadev/lakonai.git"
25
31
  },
26
32
  "bugs": {
27
- "url": "https://github.com/bargadev/lakonai-lib/issues"
33
+ "url": "https://github.com/bargadev/lakonai/issues"
28
34
  },
29
35
  "type": "commonjs",
30
36
  "main": "src/filters/index.js",
31
37
  "bin": {
32
- "lakonai": "bin/lakonai.js",
33
- "lakon": "bin/lakonai.js",
34
- "lak": "bin/lakonai.js"
38
+ "lakonai": "bin/lakonai.js"
35
39
  },
36
40
  "files": [
37
41
  "bin/",
@@ -41,14 +45,14 @@
41
45
  "LICENSE"
42
46
  ],
43
47
  "scripts": {
44
- "test": "node --test tests/",
45
- "test:coverage": "c8 --reporter=text --reporter=html node --test tests/",
46
- "test:coverage:check": "c8 --check-coverage --lines 100 --branches 100 --functions 100 node --test tests/"
48
+ "test": "jest",
49
+ "test:coverage": "jest --coverage",
50
+ "test:coverage:check": "jest --coverage"
47
51
  },
48
52
  "engines": {
49
53
  "node": ">=18"
50
54
  },
51
55
  "devDependencies": {
52
- "c8": "^11.0.0"
56
+ "jest": "^29.7.0"
53
57
  }
54
58
  }
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ const { stripAnsi, truncateLines, dedupConsecutive } = require('./utils');
4
+
5
+ const DEFAULT_MAX_LINES = 300;
6
+ const BLANK_RUN_RE = /\n[\t ]*\n([\t ]*\n)+/g;
7
+
8
+ // Conservative, near-lossless filter applied to commands the learner promoted
9
+ // automatically. It NEVER drops lines by guessing they're noise — that could
10
+ // hide a real error from the model. It only:
11
+ // - strips ANSI colour codes
12
+ // - collapses runs of blank lines
13
+ // - collapses identical adjacent lines into one annotated with a count
14
+ // - truncates only when huge, and announces the truncation
15
+ function filter(raw, opts = {}) {
16
+ const max = opts.maxLines || DEFAULT_MAX_LINES;
17
+ let text = stripAnsi(raw).replace(BLANK_RUN_RE, '\n\n');
18
+ text = dedupConsecutive(text);
19
+ return truncateLines(text, max);
20
+ }
21
+
22
+ module.exports = { filter };
@@ -0,0 +1,103 @@
1
+ 'use strict';
2
+
3
+ // Declarative filter definitions consumed by engine.js. Each entry:
4
+ // name identifier (for debugging)
5
+ // cmds first-word commands that should be intercepted by the hook
6
+ // match regex (string) tested against the FULL command line
7
+ // plus any pipeline fields from engine.js (stripLines, maxLines, dedup, …).
8
+ // Order matters: the first def whose `match` tests true wins.
9
+
10
+ module.exports = [
11
+ // --- Tier A: lint / typecheck ------------------------------------------
12
+ {
13
+ name: 'tsc',
14
+ cmds: ['tsc'],
15
+ match: '^tsc\\b',
16
+ stripLines: ['^\\s*$'],
17
+ dedup: true,
18
+ maxLines: 60,
19
+ onEmpty: 'tsc: ok',
20
+ },
21
+ {
22
+ name: 'eslint',
23
+ cmds: ['eslint'],
24
+ match: '^eslint\\b',
25
+ stripLines: ['^\\s*$', '^\\s*\\d+ problems? '],
26
+ matchOutput: [{ pattern: '^\\s*$', message: 'eslint: ok', unless: '\\S' }],
27
+ maxLines: 80,
28
+ onEmpty: 'eslint: ok',
29
+ },
30
+ {
31
+ name: 'ruff',
32
+ cmds: ['ruff'],
33
+ match: '^ruff\\b',
34
+ stripLines: ['^\\s*$'],
35
+ matchOutput: [{ pattern: 'All checks passed', message: 'ruff: ok' }],
36
+ maxLines: 80,
37
+ onEmpty: 'ruff: ok',
38
+ },
39
+ {
40
+ name: 'clippy',
41
+ cmds: ['cargo'],
42
+ match: '^cargo clippy\\b',
43
+ stripLines: ['^\\s*Compiling ', '^\\s*Checking ', '^\\s*Finished ', '^\\s*$'],
44
+ matchOutput: [
45
+ { pattern: 'Finished', message: 'clippy: ok', unless: 'warning:|error' },
46
+ ],
47
+ maxLines: 80,
48
+ onEmpty: 'clippy: ok',
49
+ },
50
+
51
+ // --- Tier B: build / package managers / cloud --------------------------
52
+ {
53
+ name: 'make',
54
+ cmds: ['make'],
55
+ match: '^make\\b',
56
+ stripLines: ['^make\\[\\d+\\]:', '^\\s*$', '^Nothing to be done'],
57
+ maxLines: 60,
58
+ onEmpty: 'make: ok',
59
+ },
60
+ {
61
+ name: 'pkg-install',
62
+ cmds: ['npm', 'pnpm', 'yarn', 'bun'],
63
+ match: '^(npm|pnpm|yarn|bun) (install|i|ci|add)\\b',
64
+ stripLines: ['^\\s*$', '^npm warn ', '^\\s*$', 'packages are looking for funding'],
65
+ matchOutput: [
66
+ { pattern: 'added \\d+ packages?|up to date|already up-to-date', message: 'install: ok', unless: 'npm error|ERR!|error ' },
67
+ ],
68
+ maxLines: 40,
69
+ onEmpty: 'install: ok',
70
+ },
71
+ {
72
+ name: 'diff',
73
+ cmds: ['diff'],
74
+ match: '^diff\\b',
75
+ keepLines: ['^[<>+-]', '^@@', '^\\d+[ac,d]'],
76
+ maxLines: 120,
77
+ onEmpty: 'diff: no changes',
78
+ },
79
+ {
80
+ name: 'docker',
81
+ cmds: ['docker'],
82
+ match: '^docker\\b',
83
+ stripLines: ['^\\s*$', 'Pulling fs layer', 'Waiting', 'Downloading', 'Extracting', 'Download complete', 'Pull complete', 'Verifying Checksum'],
84
+ maxLines: 60,
85
+ onEmpty: 'docker: ok',
86
+ },
87
+ {
88
+ name: 'kubectl',
89
+ cmds: ['kubectl'],
90
+ match: '^kubectl\\b',
91
+ stripLines: ['^\\s*$'],
92
+ maxLines: 80,
93
+ onEmpty: 'kubectl: no resources',
94
+ },
95
+ {
96
+ name: 'aws',
97
+ cmds: ['aws'],
98
+ match: '^aws\\b',
99
+ stripLines: ['^\\s*$'],
100
+ maxLines: 100,
101
+ onEmpty: 'aws: (empty)',
102
+ },
103
+ ];
@@ -0,0 +1,117 @@
1
+ 'use strict';
2
+
3
+ // Declarative filter engine — data-driven equivalent of rtk's toml_filter.
4
+ // A filter definition (see defs.js) is matched against the full command string
5
+ // and its raw output is run through this pipeline, in order:
6
+ //
7
+ // 1. stripAnsi — remove ANSI escape codes
8
+ // 2. replace[] — regex substitutions, line-by-line, chained
9
+ // 3. matchOutput[] — short-circuit: blob matches pattern -> return message
10
+ // 4. strip/keepLines — drop or keep lines by regex
11
+ // 5. dedup — collapse identical adjacent lines (a (×N))
12
+ // 6. truncateLineAt — clip each line to N chars
13
+ // 7. head/tailLines — keep first / last N lines
14
+ // 8. maxLines — absolute line cap
15
+ // 9. onEmpty — message when the result is empty
16
+
17
+ const { stripAnsi, truncateLines, dedupConsecutive } = require('./utils');
18
+ const DEFS = require('./defs');
19
+
20
+ let compiled = null;
21
+
22
+ function compileDef(def) {
23
+ return {
24
+ name: def.name,
25
+ cmds: def.cmds || [],
26
+ match: new RegExp(def.match),
27
+ stripAnsi: def.stripAnsi !== false,
28
+ replace: (def.replace || []).map((r) => ({ re: new RegExp(r.pattern, 'g'), to: r.replacement })),
29
+ matchOutput: (def.matchOutput || []).map((m) => ({
30
+ re: new RegExp(m.pattern),
31
+ message: m.message,
32
+ unless: m.unless ? new RegExp(m.unless) : null,
33
+ })),
34
+ stripLines: (def.stripLines || []).map((p) => new RegExp(p)),
35
+ keepLines: (def.keepLines || []).map((p) => new RegExp(p)),
36
+ dedup: !!def.dedup,
37
+ truncateLineAt: def.truncateLineAt || null,
38
+ headLines: def.headLines || null,
39
+ tailLines: def.tailLines || null,
40
+ maxLines: def.maxLines || null,
41
+ onEmpty: def.onEmpty != null ? def.onEmpty : '',
42
+ filterStderr: !!def.filterStderr,
43
+ };
44
+ }
45
+
46
+ function getCompiled() {
47
+ if (!compiled) compiled = DEFS.map(compileDef);
48
+ return compiled;
49
+ }
50
+
51
+ // Find the first def whose match regex tests the full command string.
52
+ function findFilter(command) {
53
+ return getCompiled().find((d) => d.match.test(command)) || null;
54
+ }
55
+
56
+ function applyDef(def, raw) {
57
+ let text = def.stripAnsi ? stripAnsi(raw) : raw;
58
+
59
+ for (const r of def.replace) {
60
+ text = text
61
+ .split('\n')
62
+ .map((line) => line.replace(r.re, r.to))
63
+ .join('\n');
64
+ }
65
+
66
+ for (const m of def.matchOutput) {
67
+ if (m.re.test(text) && !(m.unless && m.unless.test(text))) {
68
+ return m.message;
69
+ }
70
+ }
71
+
72
+ let lines = text.split('\n');
73
+ if (def.keepLines.length) {
74
+ lines = lines.filter((l) => def.keepLines.some((re) => re.test(l)));
75
+ }
76
+ if (def.stripLines.length) {
77
+ lines = lines.filter((l) => !def.stripLines.some((re) => re.test(l)));
78
+ }
79
+
80
+ text = lines.join('\n');
81
+ if (def.dedup) text = dedupConsecutive(text);
82
+
83
+ if (def.truncateLineAt) {
84
+ text = text
85
+ .split('\n')
86
+ .map((l) => (l.length > def.truncateLineAt ? l.slice(0, def.truncateLineAt) + '…' : l))
87
+ .join('\n');
88
+ }
89
+
90
+ if (def.headLines) {
91
+ text = truncateLines(text, def.headLines);
92
+ } else if (def.tailLines) {
93
+ const arr = text.split('\n');
94
+ if (arr.length > def.tailLines) {
95
+ const dropped = arr.length - def.tailLines;
96
+ text = `… +${dropped} earlier lines\n` + arr.slice(-def.tailLines).join('\n');
97
+ }
98
+ }
99
+
100
+ if (def.maxLines) text = truncateLines(text, def.maxLines);
101
+
102
+ return text.trim() === '' ? def.onEmpty : text;
103
+ }
104
+
105
+ // Union of first-word commands across all defs (for FILTERED_CMDS / isSupported).
106
+ function firstWords() {
107
+ const set = new Set();
108
+ for (const d of getCompiled()) for (const c of d.cmds) set.add(c);
109
+ return set;
110
+ }
111
+
112
+ function filterStderrFor(command) {
113
+ const def = findFilter(command);
114
+ return !!(def && def.filterStderr);
115
+ }
116
+
117
+ module.exports = { findFilter, applyDef, firstWords, filterStderrFor, compileDef };
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ const { stripAnsi, truncateLines, groupByDir } = require('./utils');
4
+
5
+ const DEFAULT_MAX_LINES = 120;
6
+
7
+ // Compress `find` output: drop permission-denied noise, then group the matched
8
+ // paths by directory so a flat 400-line dump becomes a per-dir summary.
9
+ function filter(raw, opts = {}) {
10
+ const max = opts.maxLines || DEFAULT_MAX_LINES;
11
+ const lines = stripAnsi(raw)
12
+ .split('\n')
13
+ .filter((l) => l.trim() && !/^find: .*(Permission denied|Operation not permitted)/.test(l));
14
+ if (!lines.length) return 'find: no matches';
15
+ return truncateLines(groupByDir(lines), max);
16
+ }
17
+
18
+ module.exports = { filter };
@@ -23,7 +23,7 @@ function filterLog(raw) {
23
23
  continue;
24
24
  }
25
25
  if (LOG_AUTHOR_RE.test(line) || LOG_DATE_RE.test(line) || line.startsWith('Merge:')) continue;
26
- /* c8 ignore next */
26
+ /* istanbul ignore next */
27
27
  if (pendingHash && !captured && line.trim() && !line.startsWith(' ')) continue;
28
28
  if (pendingHash && !captured && line.trim()) {
29
29
  out.push(`${pendingHash} ${line.trim()}`);
@@ -53,7 +53,7 @@ function filterStatus(raw) {
53
53
  if (STATUS_HEADER_RE.test(line)) continue;
54
54
  if (!line.trim()) continue;
55
55
  const cleaned = line.replace(/^\s+/, '').replace(/^\(use.*/, '').trim();
56
- /* c8 ignore next */
56
+ /* istanbul ignore next */
57
57
  if (!cleaned) continue;
58
58
  if (mode === 'changed') changed.push(cleaned);
59
59
  else if (mode === 'untracked') untracked.push(cleaned);