prompt-compressor 1.0.0 → 1.0.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tom Ketter
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.
package/README.md CHANGED
@@ -4,6 +4,12 @@
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/prompt-compressor)](https://www.npmjs.com/package/prompt-compressor)
6
6
 
7
+ ⭐ **Find it useful? [Star it on GitHub](https://github.com/kettertom/prompt-compressor)** · 🐛 **Found a bug or have an idea? [Open an issue](https://github.com/kettertom/prompt-compressor/issues/new)**
8
+
9
+ **No model. No API key. Deterministic. Zero dependencies. Your data never leaves your machine.** At the default level it cut **23% of tokens across 8 real-world prompt types while keeping 94/94 critical instructions**. See the [benchmark](https://github.com/kettertom/prompt-compressor#benchmark).
10
+
11
+ > 🔧 **Upgrade to 1.0.3 or later.** 1.0.2 and earlier could corrupt ```json blocks at `low` (repeated lines such as `}` or `"qty": 1` were removed as duplicates), and `medium` kept only about 22% of critical facts. Both are fixed and covered by the benchmark and tests.
12
+
7
13
  ## Install
8
14
 
9
15
  ```bash
@@ -25,12 +31,12 @@ console.log(stats);
25
31
 
26
32
  Pick a level — every algorithm at or below that risk runs automatically.
27
33
 
28
- | Level | What runs | Typical saving |
34
+ | Level | What runs | Measured saving ([benchmark](https://github.com/kettertom/prompt-compressor#benchmark)) |
29
35
  |---|---|---|
30
- | `'none'` | Whitespace, unicode normalization, indentation | 5–15% |
31
- | `'very-low'` | + Filler removal, phrase shortening, JSON/SQL minify | 15–30% |
32
- | `'low'` | + Hedging removal, code comments, deduplication, stack trace truncation | 25–45% |
33
- | `'medium'` | + Fuzzy dedup, TF-IDF, TextRank (may drop sentences) | 30–70% |
36
+ | `'none'` | Whitespace, unicode normalization, indentation | 4% avg (0–24%) |
37
+ | `'very-low'` | + Filler removal, phrase shortening, JSON/SQL minify | 9% avg (0–32%) |
38
+ | `'low'` | + Hedging removal, code comments, deduplication, stack trace truncation | **23% avg (2–59%)**, 100% of critical facts kept |
39
+ | `'medium'` | + Near-duplicate removal (fuzzy / n-gram / Levenshtein), TextRank on plain prose only | 24% avg (5–59%), 100% of critical facts kept |
34
40
 
35
41
  ```js
36
42
  compress(text, 'none') // safest
@@ -39,6 +45,8 @@ compress(text, 'low') // recommended default
39
45
  compress(text, 'medium') // most aggressive
40
46
  ```
41
47
 
48
+ > **`medium` = `low` + near-duplicate removal + light summarization of plain prose.** Code blocks, lists, tables, `Key: value` lines, questions, and any sentence with a rule, number, ID or variable are never removed. On the dense prompts in the benchmark it saves about the same as `low` (24% vs 23%) and kept 94/94 critical facts. It helps most on long, chatty prose. *(Before 1.0.3, `medium` chained three summarizers and kept only 22% of critical facts. Upgrade if you used it.)*
49
+
42
50
  ## Custom options
43
51
 
44
52
  Override specific algorithms or parameters:
@@ -56,7 +64,15 @@ const { output, stats } = compress(text, {
56
64
  });
57
65
  ```
58
66
 
59
- ## In a MCP server
67
+ ## Use it as an MCP server (no code)
68
+
69
+ Want your AI assistant to compress prompts for you? Use [`prompt-compressor-mcp`](https://www.npmjs.com/package/prompt-compressor-mcp):
70
+
71
+ ```bash
72
+ claude mcp add prompt-compressor -- npx -y prompt-compressor-mcp
73
+ ```
74
+
75
+ ## Inside your own MCP server
60
76
 
61
77
  ```js
62
78
  import { compress } from 'prompt-compressor';
@@ -143,9 +159,9 @@ compress("Please {{user_name}}, utilize this in order to process {context}", 'lo
143
159
  | `fuzzyDeduplicate` | medium | Jaccard-based near-duplicate removal |
144
160
  | `ngramDeduplicate` | medium | Bigram/trigram near-duplicate removal |
145
161
  | `levenshteinDeduplicate` | medium | Edit-distance near-duplicate removal |
146
- | `tfidfCompress` | medium | Keep top sentences by TF-IDF score |
147
- | `textRankCompress` | medium | Keep top sentences by PageRank centrality |
148
- | `extractiveCompress` | medium | Keep top sentences by Term Frequency |
162
+ | `tfidfCompress` | opt-in | Drop lowest TF-IDF prose sentences (keeps code, lists, rules, numbers) |
163
+ | `textRankCompress` | medium | Drop least central prose sentences (keeps code, lists, rules, numbers) |
164
+ | `extractiveCompress` | opt-in | Drop lowest term-frequency prose sentences (keeps code, lists, rules, numbers) |
149
165
 
150
166
  ## License
151
167
 
package/index.js CHANGED
@@ -52,18 +52,24 @@ export const LEVELS = {
52
52
  'base64Hex', 'stackTraces',
53
53
  'lineDedup', 'sentenceDedup',
54
54
  ],
55
+ // One summarizer only (they used to be chained, compounding to ~25% kept).
56
+ // tfidf / extractive remain available as opt-in options.
55
57
  medium: [
56
58
  'fuzzyDedup', 'ngram', 'levenshtein',
57
- 'tfidf', 'textrank', 'extractive',
59
+ 'textrank',
58
60
  ],
59
61
  };
60
62
 
63
+ // Opt-in steps that are not part of any level by default
64
+ const OPTIONAL_STEPS = ['tfidf', 'extractive'];
65
+
61
66
  // Ordered from safest to riskiest for pipeline execution
62
67
  const ALL_STEPS_ORDERED = [
63
68
  ...LEVELS.none,
64
69
  ...LEVELS['very-low'],
65
70
  ...LEVELS.low,
66
71
  ...LEVELS.medium,
72
+ ...OPTIONAL_STEPS,
67
73
  ];
68
74
 
69
75
  // Steps eligible for each level (cumulative)
@@ -71,15 +77,15 @@ function stepsForLevel(level) {
71
77
  if (level === 'none') return [...LEVELS.none];
72
78
  if (level === 'very-low') return [...LEVELS.none, ...LEVELS['very-low']];
73
79
  if (level === 'low') return [...LEVELS.none, ...LEVELS['very-low'], ...LEVELS.low];
74
- if (level === 'medium') return ALL_STEPS_ORDERED;
80
+ if (level === 'medium') return [...LEVELS.none, ...LEVELS['very-low'], ...LEVELS.low, ...LEVELS.medium];
75
81
  throw new Error(`Unknown level: "${level}". Use 'none', 'very-low', 'low', or 'medium'.`);
76
82
  }
77
83
 
78
84
  // ─── Default params ───────────────────────────────────────────
79
85
  const DEFAULTS = {
80
- extractiveRatio: 0.65,
81
- tfidfRatio: 0.65,
82
- textrankRatio: 0.65,
86
+ extractiveRatio: 0.75,
87
+ tfidfRatio: 0.75,
88
+ textrankRatio: 0.75,
83
89
  fuzzyThreshold: 0.75,
84
90
  ngramSize: 2,
85
91
  ngramThreshold: 0.6,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prompt-compressor",
3
- "version": "1.0.0",
3
+ "version": "1.0.3",
4
4
  "description": "Rule-based prompt compression — reduce LLM token usage without a model, without an API, without sending data anywhere.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -8,14 +8,29 @@
8
8
  "types": "index.d.ts",
9
9
  "exports": {
10
10
  ".": {
11
- "import": "./index.js",
12
- "types": "./index.d.ts"
11
+ "types": "./index.d.ts",
12
+ "import": "./index.js"
13
13
  }
14
14
  },
15
- "files": ["index.js", "index.d.ts", "src/"],
15
+ "files": [
16
+ "index.js",
17
+ "index.d.ts",
18
+ "src/"
19
+ ],
16
20
  "keywords": [
17
- "prompt", "compression", "llm", "tokens", "bedrock", "openai", "anthropic",
18
- "claude", "gpt", "langchain", "mcp", "rag", "nlp"
21
+ "prompt",
22
+ "compression",
23
+ "llm",
24
+ "tokens",
25
+ "bedrock",
26
+ "openai",
27
+ "anthropic",
28
+ "claude",
29
+ "gpt",
30
+ "langchain",
31
+ "mcp",
32
+ "rag",
33
+ "nlp"
19
34
  ],
20
35
  "author": "Tom Ketter",
21
36
  "license": "MIT",
@@ -24,5 +39,13 @@
24
39
  "url": "https://github.com/kettertom/prompt-compressor.git"
25
40
  },
26
41
  "homepage": "https://prompt-compressor.com",
27
- "engines": { "node": ">=16" }
42
+ "engines": {
43
+ "node": ">=16"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/kettertom/prompt-compressor/issues"
47
+ },
48
+ "scripts": {
49
+ "test": "node --test test/*.test.js"
50
+ }
28
51
  }
package/src/algorithms.js CHANGED
@@ -68,26 +68,39 @@ export function stripAnsiCodes(text) {
68
68
  * @risk very-low | @savings 10–20%
69
69
  */
70
70
  export function removeFiller(text) {
71
- const patterns = [
72
- [/please note that\s[^.!?\n]+[.!?]/gi, ""],
73
- [/it is important to note that\s[^.!?\n]+[.!?]/gi, ""],
74
- [/it's important to note that\s[^.!?\n]+[.!?]/gi, ""],
75
- [/for example[,:]?\s[^.!?\n]+[.!?]/gi, ""],
76
- [/e\.g\.[,\s][^.!?\n]+[.!?]/gi, ""],
77
- [/i\.e\.[,\s][^.!?\n]+[.!?]/gi, ""],
78
- [/in other words[,:]?\s[^.!?\n]+[.!?]/gi, ""],
79
- [/as mentioned (above|earlier|before)[,:]?\s[^.!?\n]+[.!?]/gi, ""],
80
- [/note:\s[^.!?\n]+[.!?]/gi, ""],
81
- [/\bkindly\b\s/gi, ""],
82
- [/\bplease\s+be\s+advised\s+that\b/gi, ""],
83
- [/\bfeel free to\b/gi, ""],
84
- [/\bit goes without saying\b[^.!?\n]+[.!?]/gi, ""],
85
- [/\bwhat this means is that\b\s*/gi, ""],
86
- [/\bit should be noted that\b\s*/gi, ""],
71
+ // Lead-in phrases: drop the phrase, KEEP the sentence that follows it.
72
+ // (Earlier versions deleted the whole sentence, which removed real instructions,
73
+ // e.g. "Please note that you must never share PII." disappeared entirely.)
74
+ const leadIns = [
75
+ /\bplease note that[,]?\s+/gi,
76
+ /\bit is important to note that[,]?\s+/gi,
77
+ /\bit's important to note that[,]?\s+/gi,
78
+ /\bit should be noted that[,]?\s+/gi,
79
+ /\bplease be advised that\s+/gi,
80
+ /\bit goes without saying(?: that)?[,]?\s+/gi,
81
+ /\bwhat this means is that\s+/gi,
82
+ /\bin other words[,:]?\s+/gi,
83
+ /\bas mentioned (?:above|earlier|before)[,:]?\s+/gi,
84
+ /\bfor the record[,:]?\s+/gi,
85
+ /(?<![\w-])note:\s+/gi,
86
+ /\bkindly\s+/gi,
87
+ /\bfeel free to\s+/gi,
88
+ ];
89
+ const words = [
90
+ [/\bthe reason for this is(?: that)?\s+/gi, "because "],
87
91
  ];
88
92
  let out = text;
89
- for (const [p, r] of patterns) out = out.replace(p, r);
90
- return out.replace(/\s{2,}/g, " ").replace(/\n{3,}/g, "\n\n").trim();
93
+ for (const p of leadIns) {
94
+ out = out.replace(p, (m, offset, str) => {
95
+ // remember to capitalize the next letter if the phrase started a sentence
96
+ const before = str.slice(0, offset);
97
+ return /(^|[.!?:]\s*|\n\s*)$/.test(before) ? "\u0000CAP" : "";
98
+ });
99
+ }
100
+ for (const [p, r] of words) out = out.replace(p, r);
101
+ out = out.replace(/\u0000CAP(\s*)(\S)/g, (_, ws, ch) => ws + ch.toUpperCase()).replace(/\u0000CAP/g, "");
102
+ // collapse runs of spaces/tabs only — keep newlines and paragraph structure
103
+ return out.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
91
104
  }
92
105
 
93
106
  /**
@@ -158,7 +171,7 @@ export function removeHedging(text) {
158
171
  ];
159
172
  let out = text;
160
173
  for (const [p, r] of patterns) out = out.replace(p, r);
161
- return out.replace(/\s{2,}/g, " ").trim();
174
+ return out.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+\n/g, "\n").trim();
162
175
  }
163
176
 
164
177
  /**
@@ -196,7 +209,7 @@ export function removeParentheticals(text) {
196
209
  ];
197
210
  let out = text;
198
211
  for (const p of patterns) out = out.replace(p, "");
199
- return out.replace(/\s{2,}/g, " ").trim();
212
+ return out.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+\n/g, "\n").trim();
200
213
  }
201
214
 
202
215
  /**
@@ -282,7 +295,7 @@ export function removeNullJsonFields(text) {
282
295
  if (v === null || v === "" || (Array.isArray(v) && v.length === 0)) return undefined;
283
296
  return v;
284
297
  }));
285
- return "```json\n" + JSON.stringify(cleaned, null, 2) + "\n```";
298
+ return "```json\n" + JSON.stringify(cleaned) + "\n```";
286
299
  } catch { return _; }
287
300
  });
288
301
  }
@@ -346,197 +359,244 @@ export function stripBase64AndHex(text) {
346
359
  * Catches: "Return JSON only\nReturn JSON only\nReturn JSON only" → one line.
347
360
  * @risk low | @savings 5–30%
348
361
  */
362
+ // Lines that look like code or JSON legitimately repeat ("}", "qty": 1, return x;)
363
+ const CODE_LIKE_LINE = /^[\s\[\]{}(),;:"'`]*$|^\s*"[^"]*"\s*:|[{\[,;]\s*$|^\s*(?:return|break|continue|end|fi|done|else)\b/;
349
364
  export function deduplicateLines(text) {
350
- const seen = new Set();
351
- return text.split("\n").filter(line => {
352
- const key = line.trim().toLowerCase();
353
- if (key === "") return true;
354
- if (seen.has(key)) return false;
355
- seen.add(key); return true;
356
- }).join("\n");
365
+ return outsideFences(text, (block) => {
366
+ const seen = new Set();
367
+ return block.split("\n").filter(line => {
368
+ const key = line.trim().toLowerCase();
369
+ if (key === "" || CODE_LIKE_LINE.test(line)) return true;
370
+ if (seen.has(key)) return false;
371
+ seen.add(key); return true;
372
+ }).join("\n");
373
+ });
357
374
  }
358
375
 
359
376
  /**
360
377
  * Removes repeated sentences (exact match, case-insensitive).
361
378
  * @risk low | @savings 5–15%
362
379
  */
363
- export function deduplicateSentences(text) {
364
- const sentences = text.split(/(?<=[.!?])\s+/);
380
+ function deduplicateSentencesBlock(text) {
381
+ // Split but keep each separator, so line breaks and paragraphs survive.
382
+ const parts = text.split(/((?<=[.!?])\s+)/);
365
383
  const seen = new Set();
366
- return sentences.filter(s => {
384
+ let out = "";
385
+ for (let i = 0; i < parts.length; i += 2) {
386
+ const s = parts[i], sep = parts[i + 1] ?? "";
367
387
  const key = s.toLowerCase().replace(/[^a-z0-9]/g, "");
368
- if (key.length < 8 || !seen.has(key)) { seen.add(key); return true; }
369
- return false;
370
- }).join(" ").trim();
388
+ if (key.length < 8 || !seen.has(key)) { seen.add(key); out += s + sep; }
389
+ else if (sep.includes("\n") && !/\n\s*$/.test(out)) out = out.replace(/[ \t]*$/, "") + "\n";
390
+ }
391
+ return out.replace(/\n{3,}/g, "\n\n").trim();
392
+ }
393
+ export function deduplicateSentences(text) {
394
+ return outsideFences(text, deduplicateSentencesBlock);
395
+ }
396
+
397
+ // ─── Shared core for the 'medium' steps ─────────────────────
398
+ // Every medium step works on "units" (sentences / lines) and only ever
399
+ // REMOVES units it has positively chosen to drop. Everything else, including
400
+ // short units, line breaks and paragraph breaks, is kept as-is.
401
+ // Units inside ``` fenced blocks, structured lines (lists, headings, tables,
402
+ // "Key: value", JSON-ish, log lines) and "critical" sentences (rules,
403
+ // numbers, IDs, variables, emails, URLs) are never dropped.
404
+
405
+ const UNIT_SPLIT = /((?<=[.!?])[ \t]+|[ \t]*\n\s*)/;
406
+ // Chat transcript lines ("User: …", "Assistant: …") are prose, not structure
407
+ const SPEAKER = /^\s*(?:user|assistant|human|ai|system|customer|agent|bot)\s*:/i;
408
+ const STRUCTURED_RE = /^\s*(?:[-*+•>|#]|\d+[.)]\s|[\[{"'`]|[A-Za-z][\w .'-]{0,30}:\s|\d{4}-\d{2}-\d{2})/;
409
+ const STRUCTURED_LINE = { test: (line) => !SPEAKER.test(line) && STRUCTURED_RE.test(line) };
410
+ const CRITICAL = /\d|\{\{?|\$\{|%\w+%|@|https?:\/\/|`|\b(?:must|never|always|only|not|don't|do not|cannot|can't|required?|forbidden|no later than|deadline|exactly|at least|at most)\b/i;
411
+
412
+ function parseUnits(text) {
413
+ const parts = text.split(UNIT_SPLIT);
414
+ const units = [];
415
+ let lineStart = true, line = "";
416
+ for (let i = 0; i < parts.length; i += 2) {
417
+ const sepBefore = i === 0 ? "" : parts[i - 1];
418
+ if (i > 0 && sepBefore.includes("\n")) { lineStart = true; }
419
+ if (lineStart) {
420
+ // the full line this unit starts
421
+ let j = i, l = parts[i];
422
+ while (j + 2 < parts.length && !parts[j + 1].includes("\n")) { l += parts[j + 1] + parts[j + 2]; j += 2; }
423
+ line = l;
424
+ }
425
+ units.push({ text: parts[i], sepBefore, line });
426
+ lineStart = false;
427
+ }
428
+ return units;
429
+ }
430
+
431
+ function rebuild(units, keep) {
432
+ let out = "", pending = "";
433
+ units.forEach((u, i) => {
434
+ const sep = (pending.match(/\n/g) || []).length > (u.sepBefore.match(/\n/g) || []).length ? pending : u.sepBefore;
435
+ if (keep[i]) { out += (out ? sep : u.sepBefore) + u.text; pending = ""; }
436
+ else { pending = sep; }
437
+ });
438
+ return out.replace(/\n{3,}/g, "\n\n").trim();
439
+ }
440
+
441
+ // Apply fn only outside ``` fenced blocks
442
+ function outsideFences(text, fn) {
443
+ return text.split(/(```[\s\S]*?```)/g).map(p => {
444
+ if (p.startsWith("```") || !p.trim()) return p;
445
+ const lead = p.match(/^\s*/)[0], trail = p.match(/\s*$/)[0];
446
+ return lead + fn(p.trim()) + trail;
447
+ }).join("");
448
+ }
449
+
450
+ // Questions, direct requests and word-based deadlines are the task itself
451
+ const TASK = /\?\s*$|\b(?:could|can|would|will) you\b|\b(?:today|tomorrow|tonight|by (?:the )?end of|eod|eow|asap|due|by (?:monday|tuesday|wednesday|thursday|friday|saturday|sunday))\b/i;
452
+ const isProtected = (u) =>
453
+ !u.text.trim() || STRUCTURED_LINE.test(u.line) || CRITICAL.test(u.text) || TASK.test(u.text);
454
+
455
+ // numbers/IDs must match for two units to count as duplicates
456
+ const numSig = (s) => (s.match(/[\w-]*\d[\w.\/-]*/g) || []).join("|");
457
+
458
+ function dedupBy(text, isDup, minLen) {
459
+ return outsideFences(text, (block) => {
460
+ const units = parseUnits(block);
461
+ const keep = units.map(() => true);
462
+ const seen = [];
463
+ units.forEach((u, i) => {
464
+ const t = u.text.trim();
465
+ if (t.length <= minLen || STRUCTURED_LINE.test(u.line)) return; // too short / structured: never compared, never dropped
466
+ if (seen.some(k => numSig(k) === numSig(t) && isDup(k, t))) keep[i] = false;
467
+ else seen.push(t);
468
+ });
469
+ return rebuild(units, keep);
470
+ });
471
+ }
472
+
473
+ function summarizeBy(text, ratio, scoreFn) {
474
+ return outsideFences(text, (block) => {
475
+ const units = parseUnits(block);
476
+ const cand = units.map((u, i) => ({ u, i })).filter(({ u }) => !isProtected(u) && u.text.trim().length > 20);
477
+ if (cand.length < 3) return block;
478
+ const drop = Math.floor(cand.length * (1 - ratio));
479
+ if (drop <= 0) return block;
480
+ const scores = scoreFn(cand.map(c => c.u.text));
481
+ const dropIdx = new Set(cand.map((c, k) => ({ i: c.i, s: scores[k] }))
482
+ .sort((a, b) => a.s - b.s).slice(0, drop).map(x => x.i));
483
+ return rebuild(units, units.map((_, i) => !dropIdx.has(i)));
484
+ });
371
485
  }
372
486
 
487
+ const words = (s, min = 3) => s.toLowerCase().match(new RegExp(`\\b\\w{${min},}\\b`, "g")) || [];
488
+
373
489
  /**
374
490
  * Removes near-duplicate sentences using Jaccard similarity on word sets.
491
+ * Keeps line structure; sentences that differ in numbers/IDs are never duplicates.
375
492
  * @param threshold - similarity threshold (0–1), default 0.75
376
- * @risk medium | @savings 5–20%
493
+ * @risk medium | @savings 0–20%
377
494
  */
378
495
  export function fuzzyDeduplicate(text, threshold = 0.75) {
379
- const sentences = text.split(/(?<=[.!?])\s+/).filter(s => s.trim().length > 20);
380
- if (sentences.length < 4) return text;
381
- function jaccard(a, b) {
382
- const sa = new Set(a.toLowerCase().match(/\b\w{3,}\b/g) || []);
383
- const sb = new Set(b.toLowerCase().match(/\b\w{3,}\b/g) || []);
496
+ const jaccard = (a, b) => {
497
+ const sa = new Set(words(a)), sb = new Set(words(b));
384
498
  const inter = [...sa].filter(w => sb.has(w)).length;
385
499
  const union = new Set([...sa, ...sb]).size;
386
500
  return union === 0 ? 0 : inter / union;
387
- }
388
- const kept = [];
389
- for (const s of sentences) {
390
- if (!kept.some(k => jaccard(k, s) >= threshold)) kept.push(s);
391
- }
392
- return kept.join(" ").trim();
501
+ };
502
+ return dedupBy(text, (a, b) => jaccard(a, b) >= threshold, 20);
393
503
  }
394
504
 
395
505
  /**
396
- * Near-duplicate removal using bigram/trigram overlap.
397
- * Better than Jaccard for paraphrases: "Return only JSON" vs "Only return JSON".
398
- * @param n - gram size (default 2)
399
- * @param threshold - similarity threshold (default 0.6)
400
- * @risk medium | @savings 5–20%
506
+ * N-gram overlap deduplication. Keeps line structure; numbers/IDs must match.
507
+ * @risk medium | @savings 0–15%
401
508
  */
402
509
  export function ngramDeduplicate(text, n = 2, threshold = 0.6) {
403
- const sentences = text.split(/(?<=[.!?])\s+/).filter(s => s.trim().length > 15);
404
- if (sentences.length <= 2) return text;
405
- function grams(s) {
406
- const words = s.toLowerCase().match(/\b\w+\b/g) || [];
510
+ const grams = (s) => {
511
+ const w = s.toLowerCase().match(/\b\w+\b/g) || [];
407
512
  const gs = new Set();
408
- for (let i = 0; i <= words.length - n; i++) gs.add(words.slice(i, i + n).join(" "));
513
+ for (let i = 0; i <= w.length - n; i++) gs.add(w.slice(i, i + n).join(" "));
409
514
  return gs;
410
- }
411
- const gramSets = sentences.map(grams);
412
- const kept = [];
413
- for (let i = 0; i < sentences.length; i++) {
414
- const isDup = kept.some((_, ki) => {
415
- const a = gramSets[i], b = gramSets[kept[ki]];
416
- const inter = [...a].filter(g => b.has(g)).length;
417
- const union = new Set([...a, ...b]).size;
418
- return union > 0 && inter / union >= threshold;
419
- });
420
- if (!isDup) kept.push(i);
421
- }
422
- return kept.map(i => sentences[i]).join(" ").trim();
515
+ };
516
+ return dedupBy(text, (a, b) => {
517
+ const ga = grams(a), gb = grams(b);
518
+ const inter = [...ga].filter(g => gb.has(g)).length;
519
+ const union = new Set([...ga, ...gb]).size;
520
+ return union > 0 && inter / union >= threshold;
521
+ }, 15);
423
522
  }
424
523
 
425
524
  /**
426
525
  * Edit-distance deduplication. Catches "Return JSON only." vs "Return JSON only!"
526
+ * Keeps line structure; numbers/IDs must match.
427
527
  * @param threshold - max normalized edit distance (default 0.15)
428
- * @risk medium | @savings 3–15%
528
+ * @risk medium | @savings 0–15%
429
529
  */
430
530
  export function levenshteinDeduplicate(text, threshold = 0.15) {
431
- function lev(a, b) {
531
+ const lev = (a, b) => {
432
532
  const m = a.length, n = b.length;
433
533
  if (Math.abs(m - n) > Math.max(m, n) * 0.4) return Math.max(m, n);
434
534
  const dp = Array.from({ length: m + 1 }, (_, i) => [i]);
435
535
  for (let j = 0; j <= n; j++) dp[0][j] = j;
436
536
  for (let i = 1; i <= m; i++)
437
537
  for (let j = 1; j <= n; j++)
438
- dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] : 1 + Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);
538
+ dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
439
539
  return dp[m][n];
440
- }
441
- const sentences = text.split(/(?<=[.!?])\s+/).filter(s => s.trim().length > 10);
442
- if (sentences.length <= 2) return text;
443
- const kept = [];
444
- for (const s of sentences) {
445
- if (!kept.some(k => lev(s.toLowerCase(), k.toLowerCase()) / Math.max(s.length, k.length) <= threshold))
446
- kept.push(s);
447
- }
448
- return kept.join(" ").trim();
540
+ };
541
+ return dedupBy(text, (a, b) => lev(a.toLowerCase(), b.toLowerCase()) / Math.max(a.length, b.length) <= threshold, 10);
449
542
  }
450
543
 
451
544
  // ════════════════════════════════════════════════════════════
452
545
  // ADVANCED (EXTRACTIVE)
546
+ // Only plain prose is summarized. Code blocks, structured lines and
547
+ // critical sentences (rules, numbers, IDs, variables) are always kept.
453
548
  // ════════════════════════════════════════════════════════════
454
549
 
455
550
  /**
456
- * Keeps top N% sentences scored by Term Frequency.
457
- * @param ratio - fraction of sentences to keep (default 0.65)
458
- * @risk medium | @savings 20–50%
551
+ * Drops the lowest-scoring prose sentences by term frequency.
552
+ * @param ratio - fraction of droppable prose sentences to keep (default 0.75)
553
+ * @risk medium | @savings 0–30%
459
554
  */
460
- export function extractiveCompress(text, ratio = 0.65) {
461
- const sentences = text.split(/(?<=[.!?\n])\s+/).map(s => s.trim()).filter(s => s.length > 20);
462
- if (sentences.length <= 3) return text;
463
- const freq = {};
464
- const allWords = text.toLowerCase().match(/\b\w{4,}\b/g) || [];
465
- for (const w of allWords) freq[w] = (freq[w] || 0) + 1;
466
- const scored = sentences.map((s, i) => {
467
- const words = s.toLowerCase().match(/\b\w{4,}\b/g) || [];
468
- const score = words.reduce((acc, w) => acc + (freq[w] || 0), 0) / (words.length || 1);
469
- return { s, score, i };
555
+ export function extractiveCompress(text, ratio = 0.75) {
556
+ return summarizeBy(text, ratio, (sents) => {
557
+ const freq = {};
558
+ for (const w of words(sents.join(" "), 4)) freq[w] = (freq[w] || 0) + 1;
559
+ return sents.map(s => { const w = words(s, 4); return w.reduce((a, x) => a + (freq[x] || 0), 0) / (w.length || 1); });
470
560
  });
471
- const keepCount = Math.max(2, Math.round(sentences.length * ratio));
472
- return scored.sort((a, b) => b.score - a.score).slice(0, keepCount)
473
- .sort((a, b) => a.i - b.i).map(x => x.s).join(" ").trim();
474
561
  }
475
562
 
476
563
  /**
477
- * TF-IDF sentence scoring — penalizes words common across all sentences.
478
- * Better than pure TF for prompts with boilerplate patterns.
479
- * @param ratio - fraction of sentences to keep (default 0.65)
480
- * @risk medium | @savings 20–50%
564
+ * Drops the lowest-scoring prose sentences by TF-IDF.
565
+ * @param ratio - fraction of droppable prose sentences to keep (default 0.75)
566
+ * @risk medium | @savings 0–30%
481
567
  */
482
- export function tfidfCompress(text, ratio = 0.65) {
483
- const sentences = text.split(/(?<=[.!?\n])\s+/).map(s => s.trim()).filter(s => s.length > 20);
484
- if (sentences.length <= 3) return text;
485
- const n = sentences.length;
486
- const docFreq = {};
487
- const sentWords = sentences.map(s => {
488
- const words = s.toLowerCase().match(/\b\w{3,}\b/g) || [];
489
- [...new Set(words)].forEach(w => { docFreq[w] = (docFreq[w] || 0) + 1; });
490
- return words;
491
- });
492
- const scored = sentences.map((s, i) => {
493
- const words = sentWords[i];
494
- if (!words.length) return { s, score: 0, i };
495
- const freq = {};
496
- words.forEach(w => { freq[w] = (freq[w] || 0) + 1; });
497
- const score = words.reduce((acc, w) => {
498
- const tf = freq[w] / words.length;
499
- const idf = Math.log((n + 1) / ((docFreq[w] || 0) + 1));
500
- return acc + tf * idf;
501
- }, 0) / words.length;
502
- return { s, score, i };
568
+ export function tfidfCompress(text, ratio = 0.75) {
569
+ return summarizeBy(text, ratio, (sents) => {
570
+ const n = sents.length, df = {};
571
+ const sw = sents.map(s => { const w = words(s); new Set(w).forEach(x => { df[x] = (df[x] || 0) + 1; }); return w; });
572
+ return sw.map(w => {
573
+ if (!w.length) return 0;
574
+ const f = {}; w.forEach(x => { f[x] = (f[x] || 0) + 1; });
575
+ return w.reduce((a, x) => a + (f[x] / w.length) * Math.log((n + 1) / ((df[x] || 0) + 1)), 0) / w.length;
576
+ });
503
577
  });
504
- const keepCount = Math.max(2, Math.round(n * ratio));
505
- return scored.sort((a, b) => b.score - a.score).slice(0, keepCount)
506
- .sort((a, b) => a.i - b.i).map(x => x.s).join(" ").trim();
507
578
  }
508
579
 
509
580
  /**
510
- * TextRank — PageRank-style algorithm on sentence similarity graph.
511
- * Sentences most "central" to the document survive.
512
- * @param ratio - fraction of sentences to keep (default 0.65)
513
- * @risk medium | @savings 20–50%
581
+ * TextRank — PageRank-style ranking on the sentence similarity graph.
582
+ * Drops the least "central" prose sentences.
583
+ * @param ratio - fraction of droppable prose sentences to keep (default 0.75)
584
+ * @risk medium | @savings 0–30%
514
585
  */
515
- export function textRankCompress(text, ratio = 0.65, damping = 0.85, iterations = 20) {
516
- const sentences = text.split(/(?<=[.!?\n])\s+/).map(s => s.trim()).filter(s => s.length > 15);
517
- if (sentences.length <= 3) return text;
518
- const n = sentences.length;
519
- const sets = sentences.map(s => new Set((s.toLowerCase().match(/\b\w{3,}\b/g) || [])));
520
- const sim = (i, j) => {
521
- const a = sets[i], b = sets[j];
522
- if (!a.size || !b.size) return 0;
523
- const inter = [...a].filter(w => b.has(w)).length;
524
- return inter / (Math.log(a.size + 1) + Math.log(b.size + 1));
525
- };
526
- const matrix = Array.from({ length: n }, (_, i) =>
527
- Array.from({ length: n }, (__, j) => i === j ? 0 : sim(i, j))
528
- );
529
- const normalized = matrix.map(row => {
530
- const sum = row.reduce((a, b) => a + b, 0);
531
- return sum === 0 ? row.map(() => 1 / n) : row.map(v => v / sum);
586
+ export function textRankCompress(text, ratio = 0.75, damping = 0.85, iterations = 20) {
587
+ return summarizeBy(text, ratio, (sents) => {
588
+ const n = sents.length;
589
+ const sets = sents.map(s => new Set(words(s)));
590
+ const sim = (i, j) => {
591
+ const a = sets[i], b = sets[j];
592
+ if (!a.size || !b.size) return 0;
593
+ return [...a].filter(w => b.has(w)).length / (Math.log(a.size + 1) + Math.log(b.size + 1));
594
+ };
595
+ const m = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (__, j) => (i === j ? 0 : sim(i, j))));
596
+ const norm = m.map(r => { const s = r.reduce((a, b) => a + b, 0); return s === 0 ? r.map(() => 1 / n) : r.map(v => v / s); });
597
+ let sc = Array(n).fill(1 / n);
598
+ for (let it = 0; it < iterations; it++)
599
+ sc = sc.map((_, i) => (1 - damping) / n + damping * sc.reduce((acc, s, j) => acc + s * norm[j][i], 0));
600
+ return sc;
532
601
  });
533
- let scores = Array(n).fill(1 / n);
534
- for (let iter = 0; iter < iterations; iter++)
535
- scores = scores.map((_, i) =>
536
- (1 - damping) / n + damping * scores.reduce((acc, s, j) => acc + s * normalized[j][i], 0)
537
- );
538
- const keepCount = Math.max(2, Math.round(n * ratio));
539
- return sentences.map((s, i) => ({ s, score: scores[i], i }))
540
- .sort((a, b) => b.score - a.score).slice(0, keepCount)
541
- .sort((a, b) => a.i - b.i).map(x => x.s).join(" ").trim();
542
602
  }
package/src/protect.js CHANGED
@@ -24,11 +24,15 @@ const VAR_PATTERNS = [
24
24
  export function protectVariables(text) {
25
25
  const map = {};
26
26
  let counter = 0;
27
+ const byMatch = new Map();
27
28
  let result = text;
28
29
  for (const pattern of VAR_PATTERNS) {
29
30
  result = result.replace(new RegExp(pattern.source, "g"), match => {
31
+ // Same variable → same placeholder, so duplicate lines still dedupe.
32
+ if (byMatch.has(match)) return byMatch.get(match);
30
33
  const key = `\x00VAR${counter++}\x00`;
31
34
  map[key] = match;
35
+ byMatch.set(match, key);
32
36
  return key;
33
37
  });
34
38
  }