lynkr 9.7.3 → 9.9.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.
Files changed (74) hide show
  1. package/README.md +29 -19
  2. package/bin/cli.js +11 -0
  3. package/bin/lynkr-init.js +14 -1
  4. package/bin/lynkr-usage.js +78 -0
  5. package/bin/wrap.js +60 -35
  6. package/config/difficulty-anchors.json +22 -0
  7. package/package.json +24 -3
  8. package/scripts/audit-log-reader.js +399 -0
  9. package/scripts/calibrate-thresholds.js +38 -157
  10. package/scripts/compact-dictionary.js +204 -0
  11. package/scripts/test-deduplication.js +448 -0
  12. package/scripts/ws7-anchor-replay.js +108 -0
  13. package/skills/lynkr/SKILL.md +195 -0
  14. package/src/api/middleware/loop-guard.js +87 -0
  15. package/src/api/middleware/request-logging.js +5 -64
  16. package/src/api/middleware/session.js +0 -0
  17. package/src/api/openai-router.js +120 -101
  18. package/src/api/providers-handler.js +27 -2
  19. package/src/api/router.js +450 -125
  20. package/src/budget/index.js +2 -19
  21. package/src/cache/semantic.js +9 -0
  22. package/src/clients/databricks.js +455 -142
  23. package/src/clients/gpt-utils.js +11 -105
  24. package/src/clients/openai-format.js +10 -3
  25. package/src/clients/openrouter-utils.js +49 -24
  26. package/src/clients/prompt-cache-injection.js +1 -0
  27. package/src/clients/provider-capabilities.js +1 -1
  28. package/src/clients/responses-format.js +34 -3
  29. package/src/clients/routing.js +15 -0
  30. package/src/config/index.js +36 -2
  31. package/src/context/gcf.js +275 -0
  32. package/src/context/tool-result-compressor.js +51 -9
  33. package/src/dashboard/api.js +1 -0
  34. package/src/logger/index.js +14 -1
  35. package/src/memory/search.js +12 -40
  36. package/src/memory/tools.js +3 -24
  37. package/src/orchestrator/bypass.js +4 -2
  38. package/src/orchestrator/index.js +120 -85
  39. package/src/routing/affinity-store.js +194 -0
  40. package/src/routing/agentic-detector.js +36 -6
  41. package/src/routing/bandit.js +25 -6
  42. package/src/routing/calibration.js +212 -0
  43. package/src/routing/client-profiles.js +292 -0
  44. package/src/routing/complexity-analyzer.js +48 -11
  45. package/src/routing/deescalator.js +148 -0
  46. package/src/routing/degradation.js +109 -0
  47. package/src/routing/feedback.js +157 -0
  48. package/src/routing/index.js +897 -87
  49. package/src/routing/intent-score.js +339 -0
  50. package/src/routing/interaction.js +3 -0
  51. package/src/routing/knn-router.js +70 -21
  52. package/src/routing/model-registry.js +28 -7
  53. package/src/routing/model-tiers.js +25 -2
  54. package/src/routing/reward-pipeline.js +68 -2
  55. package/src/routing/risk-analyzer.js +30 -1
  56. package/src/routing/risk-classifier.js +6 -2
  57. package/src/routing/session-affinity.js +162 -34
  58. package/src/routing/telemetry.js +286 -13
  59. package/src/routing/verifier.js +267 -0
  60. package/src/server.js +66 -21
  61. package/src/sessions/cleanup.js +17 -0
  62. package/src/tools/index.js +1 -15
  63. package/src/tools/smart-selection.js +10 -0
  64. package/src/tools/web-client.js +3 -3
  65. package/.eslintrc.cjs +0 -12
  66. package/benchmark-configs/litellm_config.yaml +0 -86
  67. package/benchmark-configs/lynkr.env +0 -48
  68. package/benchmark-configs/portkey-config.json +0 -60
  69. package/benchmark-configs/portkey-docker.sh +0 -23
  70. package/benchmark-tier-routing.js +0 -449
  71. package/funding.json +0 -110
  72. package/src/api/middleware/validation.js +0 -261
  73. package/src/routing/drift-monitor.js +0 -113
  74. package/src/workers/helpers.js +0 -185
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Compact LLM Audit Dictionary
5
+ *
6
+ * Removes redundant UPDATE entries from the dictionary file, keeping only:
7
+ * - One entry per hash with full content
8
+ * - Latest metadata (useCount, lastSeen)
9
+ *
10
+ * Usage:
11
+ * node scripts/compact-dictionary.js [options]
12
+ *
13
+ * Options:
14
+ * --dict-path <path> Path to dictionary file (default: logs/llm-audit-dictionary.jsonl)
15
+ * --backup Create backup before compacting (default: true)
16
+ * --dry-run Show what would be done without making changes
17
+ * --help Show this help message
18
+ */
19
+
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+ const readline = require('readline');
23
+
24
+ // Parse command line arguments
25
+ function parseArgs() {
26
+ const args = process.argv.slice(2);
27
+ const options = {
28
+ dictPath: 'logs/llm-audit-dictionary.jsonl',
29
+ backup: true,
30
+ dryRun: false,
31
+ };
32
+
33
+ for (let i = 0; i < args.length; i++) {
34
+ const arg = args[i];
35
+ switch (arg) {
36
+ case '--dict-path':
37
+ options.dictPath = args[++i];
38
+ break;
39
+ case '--backup':
40
+ options.backup = true;
41
+ break;
42
+ case '--no-backup':
43
+ options.backup = false;
44
+ break;
45
+ case '--dry-run':
46
+ options.dryRun = true;
47
+ break;
48
+ case '--help':
49
+ console.log(`
50
+ Compact LLM Audit Dictionary
51
+
52
+ Removes redundant UPDATE entries from the dictionary file.
53
+
54
+ Usage:
55
+ node scripts/compact-dictionary.js [options]
56
+
57
+ Options:
58
+ --dict-path <path> Path to dictionary file (default: logs/llm-audit-dictionary.jsonl)
59
+ --backup Create backup before compacting (default: true)
60
+ --no-backup Skip creating backup
61
+ --dry-run Show what would be done without making changes
62
+ --help Show this help message
63
+
64
+ Example:
65
+ node scripts/compact-dictionary.js --dict-path logs/llm-audit-dictionary.jsonl --dry-run
66
+ `);
67
+ process.exit(0);
68
+ default:
69
+ if (arg.startsWith('--')) {
70
+ console.error(`Unknown option: ${arg}`);
71
+ process.exit(1);
72
+ }
73
+ }
74
+ }
75
+
76
+ return options;
77
+ }
78
+
79
+ // Read and compact dictionary
80
+ async function compactDictionary(dictPath) {
81
+ if (!fs.existsSync(dictPath)) {
82
+ throw new Error(`Dictionary file not found: ${dictPath}`);
83
+ }
84
+
85
+ console.log(`Reading dictionary: ${dictPath}`);
86
+
87
+ // Map: hash -> entry object
88
+ // For each hash, we'll keep the latest metadata merged with content
89
+ const entries = new Map();
90
+ let totalLines = 0;
91
+ let malformedLines = 0;
92
+
93
+ // Read all entries
94
+ const fileStream = fs.createReadStream(dictPath);
95
+ const rl = readline.createInterface({
96
+ input: fileStream,
97
+ crlfDelay: Infinity,
98
+ });
99
+
100
+ for await (const line of rl) {
101
+ totalLines++;
102
+ if (!line.trim()) continue;
103
+
104
+ try {
105
+ const entry = JSON.parse(line);
106
+ if (!entry.hash) {
107
+ malformedLines++;
108
+ continue;
109
+ }
110
+
111
+ const hash = entry.hash;
112
+
113
+ // Check if we already have an entry for this hash
114
+ if (entries.has(hash)) {
115
+ const existing = entries.get(hash);
116
+
117
+ // Merge: keep content from entry that has it, use latest metadata
118
+ const merged = {
119
+ hash,
120
+ firstSeen: existing.firstSeen || entry.firstSeen,
121
+ useCount: entry.useCount || existing.useCount,
122
+ lastSeen: entry.lastSeen || existing.lastSeen,
123
+ content: existing.content || entry.content,
124
+ };
125
+
126
+ entries.set(hash, merged);
127
+ } else {
128
+ // First time seeing this hash
129
+ entries.set(hash, entry);
130
+ }
131
+ } catch (err) {
132
+ malformedLines++;
133
+ console.warn(`Skipping malformed line ${totalLines}: ${err.message}`);
134
+ }
135
+ }
136
+
137
+ const compactedCount = entries.size;
138
+ const removedCount = totalLines - malformedLines - compactedCount;
139
+
140
+ return {
141
+ entries,
142
+ stats: {
143
+ totalLines,
144
+ malformedLines,
145
+ uniqueHashes: compactedCount,
146
+ removedEntries: removedCount,
147
+ },
148
+ };
149
+ }
150
+
151
+ // Write compacted dictionary
152
+ async function writeCompactedDictionary(dictPath, entries, backup = true) {
153
+ // Create backup if requested
154
+ if (backup) {
155
+ const backupPath = `${dictPath}.backup.${Date.now()}`;
156
+ console.log(`Creating backup: ${backupPath}`);
157
+ fs.copyFileSync(dictPath, backupPath);
158
+ }
159
+
160
+ // Write compacted entries
161
+ console.log(`Writing compacted dictionary: ${dictPath}`);
162
+ const lines = Array.from(entries.values()).map((entry) => JSON.stringify(entry));
163
+ fs.writeFileSync(dictPath, lines.join('\n') + '\n');
164
+ }
165
+
166
+ // Main
167
+ async function main() {
168
+ try {
169
+ const options = parseArgs();
170
+ const dictPath = path.resolve(options.dictPath);
171
+
172
+ console.log('=== LLM Audit Dictionary Compaction ===\n');
173
+
174
+ // Read and compact
175
+ const { entries, stats } = await compactDictionary(dictPath);
176
+
177
+ // Report statistics
178
+ console.log('\nCompaction Statistics:');
179
+ console.log(` Total lines in dictionary: ${stats.totalLines}`);
180
+ console.log(` Malformed lines skipped: ${stats.malformedLines}`);
181
+ console.log(` Unique content hashes: ${stats.uniqueHashes}`);
182
+ console.log(` Redundant entries removed: ${stats.removedEntries}`);
183
+
184
+ const reductionPercent =
185
+ stats.totalLines > 0
186
+ ? ((stats.removedEntries / stats.totalLines) * 100).toFixed(1)
187
+ : 0;
188
+ console.log(` Size reduction: ${reductionPercent}%\n`);
189
+
190
+ if (options.dryRun) {
191
+ console.log('DRY RUN: No changes made to dictionary file.');
192
+ console.log(`Would have written ${stats.uniqueHashes} entries.\n`);
193
+ } else {
194
+ // Write compacted dictionary
195
+ await writeCompactedDictionary(dictPath, entries, options.backup);
196
+ console.log('✓ Dictionary compaction complete!\n');
197
+ }
198
+ } catch (err) {
199
+ console.error('Error:', err.message);
200
+ process.exit(1);
201
+ }
202
+ }
203
+
204
+ main();
@@ -0,0 +1,448 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Test script for deduplication functionality
5
+ * Creates mock log entries and verifies deduplication works correctly
6
+ */
7
+
8
+ const fs = require("fs");
9
+ const path = require("path");
10
+ const { ContentDeduplicator } = require("../src/logger/deduplicator");
11
+
12
+ // Test configuration
13
+ const TEST_DICT_PATH = path.join(process.cwd(), "logs", "test-dictionary.jsonl");
14
+ const TEST_LOG_PATH = path.join(process.cwd(), "logs", "test-audit.log");
15
+
16
+ // Clean up test files if they exist
17
+ function cleanup() {
18
+ if (fs.existsSync(TEST_DICT_PATH)) {
19
+ fs.unlinkSync(TEST_DICT_PATH);
20
+ }
21
+ if (fs.existsSync(TEST_LOG_PATH)) {
22
+ fs.unlinkSync(TEST_LOG_PATH);
23
+ }
24
+ }
25
+
26
+ // Test 1: Basic deduplication
27
+ function testBasicDeduplication() {
28
+ console.log("\n=== Test 1: Basic Deduplication ===");
29
+
30
+ const deduplicator = new ContentDeduplicator(TEST_DICT_PATH, {
31
+ minSize: 50, // Lower threshold for testing
32
+ cacheSize: 10,
33
+ });
34
+
35
+ const content1 = "This is a test content that is longer than 50 characters and should be deduplicated.";
36
+ const content2 = "This is a test content that is longer than 50 characters and should be deduplicated.";
37
+ const content3 = "Short";
38
+
39
+ // First content should be stored
40
+ const ref1 = deduplicator.storeContent(content1);
41
+ console.log("✓ Stored content1:", ref1);
42
+
43
+ // Second identical content should return same reference
44
+ const ref2 = deduplicator.storeContent(content2);
45
+ console.log("✓ Stored content2 (should be same hash):", ref2);
46
+
47
+ // Verify same hash
48
+ if (ref1.$ref !== ref2.$ref) {
49
+ console.error("✗ FAIL: Different hashes for identical content!");
50
+ return false;
51
+ }
52
+ console.log("✓ PASS: Identical content produces same hash");
53
+
54
+ // Short content should not be deduplicated (below threshold)
55
+ const shouldNotDedup = deduplicator.shouldDeduplicate(content3, 50);
56
+ if (shouldNotDedup) {
57
+ console.error("✗ FAIL: Short content should not be deduplicated!");
58
+ return false;
59
+ }
60
+ console.log("✓ PASS: Short content not deduplicated");
61
+
62
+ return true;
63
+ }
64
+
65
+ // Test 2: Content restoration
66
+ function testContentRestoration() {
67
+ console.log("\n=== Test 2: Content Restoration ===");
68
+
69
+ const deduplicator = new ContentDeduplicator(TEST_DICT_PATH, {
70
+ minSize: 50,
71
+ cacheSize: 10,
72
+ });
73
+
74
+ const originalContent = "This is original content that needs to be restored from the dictionary file.";
75
+
76
+ // Store and get reference
77
+ const ref = deduplicator.storeContent(originalContent);
78
+ console.log("✓ Stored content with ref:", ref.$ref);
79
+
80
+ // Retrieve content
81
+ const retrieved = deduplicator.getContent(ref.$ref);
82
+ console.log("✓ Retrieved content length:", retrieved?.length);
83
+
84
+ // Verify content matches
85
+ if (retrieved !== originalContent) {
86
+ console.error("✗ FAIL: Retrieved content doesn't match original!");
87
+ console.error("Expected:", originalContent);
88
+ console.error("Got:", retrieved);
89
+ return false;
90
+ }
91
+ console.log("✓ PASS: Content restored correctly");
92
+
93
+ return true;
94
+ }
95
+
96
+ // Test 3: Entry deduplication and restoration
97
+ function testEntryProcessing() {
98
+ console.log("\n=== Test 3: Entry Deduplication and Restoration ===");
99
+
100
+ const deduplicator = new ContentDeduplicator(TEST_DICT_PATH, {
101
+ minSize: 50,
102
+ cacheSize: 10,
103
+ });
104
+
105
+ const systemPrompt = "You are a helpful AI assistant. This is a long system prompt that should be deduplicated.";
106
+ const userMessage = "This is a user message that is long enough to be deduplicated by the deduplication system.";
107
+
108
+ const entry = {
109
+ type: "llm_request",
110
+ correlationId: "test-123",
111
+ systemPrompt: systemPrompt,
112
+ userMessages: userMessage,
113
+ model: "test-model",
114
+ };
115
+
116
+ // Deduplicate entry
117
+ const deduplicated = deduplicator.deduplicateEntry(entry, ["systemPrompt", "userMessages"]);
118
+ console.log("✓ Deduplicated entry:", JSON.stringify(deduplicated, null, 2));
119
+
120
+ // Verify fields are now references
121
+ if (typeof deduplicated.systemPrompt !== "object" || !deduplicated.systemPrompt.$ref) {
122
+ console.error("✗ FAIL: systemPrompt was not deduplicated!");
123
+ return false;
124
+ }
125
+ if (typeof deduplicated.userMessages !== "object" || !deduplicated.userMessages.$ref) {
126
+ console.error("✗ FAIL: userMessages was not deduplicated!");
127
+ return false;
128
+ }
129
+ console.log("✓ PASS: Fields converted to references");
130
+
131
+ // Restore entry
132
+ const restored = deduplicator.restoreEntry(deduplicated);
133
+ console.log("✓ Restored entry keys:", Object.keys(restored));
134
+
135
+ // Verify restoration
136
+ if (restored.systemPrompt !== systemPrompt) {
137
+ console.error("✗ FAIL: systemPrompt not restored correctly!");
138
+ console.error("Expected:", systemPrompt);
139
+ console.error("Got:", restored.systemPrompt);
140
+ return false;
141
+ }
142
+ if (restored.userMessages !== userMessage) {
143
+ console.error("✗ FAIL: userMessages not restored correctly!");
144
+ console.error("Expected:", userMessage);
145
+ console.error("Got:", restored.userMessages);
146
+ return false;
147
+ }
148
+ console.log("✓ PASS: Entry restored correctly");
149
+
150
+ return true;
151
+ }
152
+
153
+ // Test 4: Dictionary persistence
154
+ function testDictionaryPersistence() {
155
+ console.log("\n=== Test 4: Dictionary Persistence ===");
156
+
157
+ // Create first deduplicator and store content
158
+ const deduplicator1 = new ContentDeduplicator(TEST_DICT_PATH, {
159
+ minSize: 50,
160
+ cacheSize: 10,
161
+ });
162
+
163
+ const content = "This is test content for persistence verification across deduplicator instances.";
164
+ const ref = deduplicator1.storeContent(content);
165
+ console.log("✓ Stored content with first deduplicator:", ref.$ref);
166
+
167
+ // Wait for async write to complete
168
+ setTimeout(() => {
169
+ // Create second deduplicator (should load from dictionary)
170
+ const deduplicator2 = new ContentDeduplicator(TEST_DICT_PATH, {
171
+ minSize: 50,
172
+ cacheSize: 10,
173
+ });
174
+
175
+ // Try to retrieve with second deduplicator
176
+ const retrieved = deduplicator2.getContent(ref.$ref);
177
+
178
+ if (retrieved !== content) {
179
+ console.error("✗ FAIL: Content not persisted to dictionary!");
180
+ console.error("Expected:", content);
181
+ console.error("Got:", retrieved);
182
+ return false;
183
+ }
184
+ console.log("✓ PASS: Dictionary persisted and loaded correctly");
185
+
186
+ // Show dictionary stats
187
+ const stats = deduplicator2.getStats();
188
+ console.log("\nDeduplication Stats:");
189
+ console.log(` Cache size: ${stats.cacheSize}`);
190
+ console.log(` Unique blocks: ${stats.uniqueContentBlocks}`);
191
+ console.log(` Total references: ${stats.totalReferences}`);
192
+
193
+ return true;
194
+ }, 100);
195
+ }
196
+
197
+ // Test 5: Size calculation and verification
198
+ function testSizeCalculation() {
199
+ console.log("\n=== Test 5: Size Calculation ===");
200
+
201
+ const deduplicator = new ContentDeduplicator(TEST_DICT_PATH, {
202
+ minSize: 50,
203
+ cacheSize: 10,
204
+ });
205
+
206
+ const content = "This is a test content string that will be deduplicated and have its size calculated.";
207
+ const ref = deduplicator.storeContent(content);
208
+
209
+ console.log("✓ Content length:", content.length);
210
+ console.log("✓ Reference size field:", ref.size);
211
+
212
+ if (ref.size !== content.length) {
213
+ console.error("✗ FAIL: Size mismatch!");
214
+ return false;
215
+ }
216
+ console.log("✓ PASS: Size calculated correctly");
217
+
218
+ // Calculate space saved
219
+ const refSize = JSON.stringify(ref).length;
220
+ const originalSize = content.length;
221
+ const saved = originalSize - refSize;
222
+ const savedPercent = ((saved / originalSize) * 100).toFixed(1);
223
+
224
+ console.log(`\nSpace saved: ${saved} bytes (${savedPercent}%)`);
225
+ console.log(` Original: ${originalSize} bytes`);
226
+ console.log(` Reference: ${refSize} bytes`);
227
+
228
+ return true;
229
+ }
230
+
231
+ // Test 6: Content sanitization (empty User: entries removal)
232
+ function testContentSanitization() {
233
+ console.log("\n=== Test 6: Content Sanitization (Empty User: Removal) ===");
234
+
235
+ const deduplicator = new ContentDeduplicator(TEST_DICT_PATH, {
236
+ minSize: 50,
237
+ cacheSize: 10,
238
+ sanitize: true, // Enable sanitization
239
+ });
240
+
241
+ // Content with multiple empty "User:" entries
242
+ const dirtyContent = `Claude: I'll implement...
243
+
244
+ User:
245
+
246
+ Claude: Now I'll implement...
247
+
248
+ User:
249
+
250
+ User:
251
+
252
+ User:
253
+
254
+ Respond with the title for the conversation and nothing else.`;
255
+
256
+ console.log("✓ Original content length:", dirtyContent.length);
257
+ console.log("✓ Empty 'User:' entries in original:", (dirtyContent.match(/User:\s*\n/g) || []).length);
258
+
259
+ // Store the content (should be sanitized internally)
260
+ const ref = deduplicator.storeContent(dirtyContent);
261
+ console.log("✓ Stored content with ref:", ref.$ref);
262
+
263
+ // Retrieve it back
264
+ const retrieved = deduplicator.getContent(ref.$ref);
265
+ console.log("✓ Retrieved content length:", retrieved?.length);
266
+
267
+ // Count empty "User:" entries in retrieved content
268
+ // Pattern: "User:" followed by newline(s) and then "Claude:" or another "User:" or end
269
+ const emptyUserMatches = retrieved.match(/User:\s*\n+(?=(Claude:|User:|$))/g) || [];
270
+ console.log("✓ Empty 'User:' entries in retrieved:", emptyUserMatches.length);
271
+
272
+ // Verify empty User: entries were removed
273
+ if (emptyUserMatches.length > 0) {
274
+ console.error("✗ FAIL: Empty User: entries not removed!");
275
+ console.error("Retrieved content:", retrieved);
276
+ return false;
277
+ }
278
+
279
+ // Verify content still contains Claude: entries
280
+ if (!retrieved.includes("Claude:")) {
281
+ console.error("✗ FAIL: Claude: entries were incorrectly removed!");
282
+ return false;
283
+ }
284
+
285
+ // Verify the last line is preserved
286
+ if (!retrieved.includes("Respond with the title")) {
287
+ console.error("✗ FAIL: Content was over-sanitized!");
288
+ return false;
289
+ }
290
+
291
+ console.log("✓ PASS: Empty User: entries removed, content preserved");
292
+
293
+ // Test with sanitization disabled
294
+ const dedupNoSanitize = new ContentDeduplicator(TEST_DICT_PATH, {
295
+ minSize: 50,
296
+ cacheSize: 10,
297
+ sanitize: false, // Disable sanitization
298
+ });
299
+
300
+ const refNoSanitize = dedupNoSanitize.storeContent(dirtyContent);
301
+ const retrievedNoSanitize = dedupNoSanitize.getContent(refNoSanitize.$ref);
302
+
303
+ // Should have empty User: entries when sanitization is disabled
304
+ const emptyUserNoSanitize = retrievedNoSanitize.match(/User:\s*\n+(?=(Claude:|User:|$))/g) || [];
305
+ if (emptyUserNoSanitize.length === 0) {
306
+ console.error("✗ FAIL: Content was sanitized even with sanitize=false!");
307
+ return false;
308
+ }
309
+
310
+ console.log("✓ PASS: Sanitization can be disabled");
311
+
312
+ return true;
313
+ }
314
+
315
+ // Test 7: Content sanitization preserves non-empty User: entries
316
+ function testSanitizationPreservesContent() {
317
+ console.log("\n=== Test 7: Sanitization Preserves Non-Empty User: Entries ===");
318
+
319
+ const deduplicator = new ContentDeduplicator(TEST_DICT_PATH, {
320
+ minSize: 50,
321
+ cacheSize: 10,
322
+ sanitize: true,
323
+ });
324
+
325
+ // Content with both empty and non-empty User: entries
326
+ const mixedContent = `Claude: I'll help you.
327
+
328
+ User: Can you explain this?
329
+
330
+ Claude: Sure, here's the explanation.
331
+
332
+ User:
333
+
334
+ User: Another question here.
335
+
336
+ Claude: Here's the answer.`;
337
+
338
+ console.log("✓ Original has both empty and non-empty User: entries");
339
+
340
+ const ref = deduplicator.storeContent(mixedContent);
341
+ const retrieved = deduplicator.getContent(ref.$ref);
342
+
343
+ // Check that non-empty User: entries are preserved
344
+ if (!retrieved.includes("User: Can you explain this?")) {
345
+ console.error("✗ FAIL: Non-empty User: entry was removed!");
346
+ return false;
347
+ }
348
+
349
+ if (!retrieved.includes("User: Another question here.")) {
350
+ console.error("✗ FAIL: Non-empty User: entry was removed!");
351
+ return false;
352
+ }
353
+
354
+ // Check that empty User: entries are removed
355
+ const lines = retrieved.split('\n');
356
+ let hasEmptyUser = false;
357
+ for (let i = 0; i < lines.length; i++) {
358
+ const line = lines[i].trim();
359
+ if (line === 'User:' || line === 'User: ') {
360
+ const nextLine = i + 1 < lines.length ? lines[i + 1].trim() : '';
361
+ if (nextLine === '' || nextLine === 'Claude:' || nextLine === 'User:') {
362
+ hasEmptyUser = true;
363
+ break;
364
+ }
365
+ }
366
+ }
367
+
368
+ if (hasEmptyUser) {
369
+ console.error("✗ FAIL: Empty User: entries not removed from mixed content!");
370
+ return false;
371
+ }
372
+
373
+ console.log("✓ PASS: Non-empty User: entries preserved, empty ones removed");
374
+
375
+ return true;
376
+ }
377
+
378
+ // Main test runner
379
+ async function runTests() {
380
+ console.log("=".repeat(60));
381
+ console.log("LLM Audit Log Deduplication Test Suite");
382
+ console.log("=".repeat(60));
383
+
384
+ // Clean up before tests
385
+ cleanup();
386
+
387
+ const tests = [
388
+ testBasicDeduplication,
389
+ testContentRestoration,
390
+ testEntryProcessing,
391
+ testSizeCalculation,
392
+ testContentSanitization,
393
+ testSanitizationPreservesContent,
394
+ ];
395
+
396
+ let passed = 0;
397
+ let failed = 0;
398
+
399
+ for (const test of tests) {
400
+ try {
401
+ const result = test();
402
+ if (result) {
403
+ passed++;
404
+ } else {
405
+ failed++;
406
+ }
407
+ } catch (err) {
408
+ console.error(`✗ Test failed with error: ${err.message}`);
409
+ console.error(err.stack);
410
+ failed++;
411
+ }
412
+ }
413
+
414
+ // Run async test separately
415
+ setTimeout(() => {
416
+ testDictionaryPersistence();
417
+
418
+ console.log("\n" + "=".repeat(60));
419
+ console.log("Test Results");
420
+ console.log("=".repeat(60));
421
+ console.log(`Passed: ${passed}/${passed + failed}`);
422
+ console.log(`Failed: ${failed}/${passed + failed}`);
423
+
424
+ if (failed === 0) {
425
+ console.log("\n✓ All tests passed!");
426
+ console.log("\nDictionary file created at:", TEST_DICT_PATH);
427
+ console.log("You can inspect it with: cat", TEST_DICT_PATH);
428
+ } else {
429
+ console.log("\n✗ Some tests failed!");
430
+ process.exit(1);
431
+ }
432
+
433
+ // Clean up after tests
434
+ console.log("\nCleaning up test files...");
435
+ cleanup();
436
+ console.log("✓ Test files removed");
437
+ }, 200);
438
+ }
439
+
440
+ // Run tests
441
+ if (require.main === module) {
442
+ runTests().catch((err) => {
443
+ console.error("Test suite failed:", err);
444
+ process.exit(1);
445
+ });
446
+ }
447
+
448
+ module.exports = { runTests };