lynkr 9.7.3 → 9.9.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.
Files changed (80) hide show
  1. package/README.md +63 -25
  2. package/bin/cli.js +16 -1
  3. package/bin/lynkr-init.js +44 -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 +23 -2
  8. package/scripts/audit-log-reader.js +399 -0
  9. package/scripts/build-eval-set.js +256 -0
  10. package/scripts/calibrate-thresholds.js +38 -157
  11. package/scripts/compact-dictionary.js +204 -0
  12. package/scripts/mine-difficulty-anchors.js +288 -0
  13. package/scripts/test-deduplication.js +448 -0
  14. package/scripts/validate-difficulty-classifier.js +123 -0
  15. package/scripts/validate-intent-anchors.js +186 -0
  16. package/scripts/ws7-anchor-replay.js +108 -0
  17. package/skills/lynkr/SKILL.md +195 -0
  18. package/src/api/middleware/loop-guard.js +87 -0
  19. package/src/api/middleware/request-logging.js +5 -64
  20. package/src/api/middleware/session.js +0 -0
  21. package/src/api/openai-router.js +120 -101
  22. package/src/api/providers-handler.js +27 -2
  23. package/src/api/router.js +467 -125
  24. package/src/budget/index.js +2 -19
  25. package/src/cache/semantic.js +9 -0
  26. package/src/clients/databricks.js +455 -142
  27. package/src/clients/gpt-utils.js +11 -105
  28. package/src/clients/openai-format.js +10 -3
  29. package/src/clients/openrouter-utils.js +49 -24
  30. package/src/clients/prompt-cache-injection.js +1 -0
  31. package/src/clients/provider-capabilities.js +1 -1
  32. package/src/clients/responses-format.js +34 -3
  33. package/src/clients/routing.js +15 -0
  34. package/src/config/index.js +36 -2
  35. package/src/context/gcf.js +275 -0
  36. package/src/context/tool-result-compressor.js +932 -47
  37. package/src/dashboard/api.js +1 -0
  38. package/src/logger/index.js +14 -1
  39. package/src/memory/search.js +12 -40
  40. package/src/memory/tools.js +3 -24
  41. package/src/orchestrator/bypass.js +4 -2
  42. package/src/orchestrator/index.js +120 -85
  43. package/src/routing/affinity-store.js +194 -0
  44. package/src/routing/agentic-detector.js +36 -6
  45. package/src/routing/bandit.js +25 -6
  46. package/src/routing/calibration.js +212 -0
  47. package/src/routing/classifier-setup.js +207 -0
  48. package/src/routing/client-profiles.js +292 -0
  49. package/src/routing/complexity-analyzer.js +88 -15
  50. package/src/routing/deescalator.js +148 -0
  51. package/src/routing/degradation.js +109 -0
  52. package/src/routing/difficulty-classifier.js +219 -0
  53. package/src/routing/feedback.js +157 -0
  54. package/src/routing/index.js +931 -90
  55. package/src/routing/intent-score.js +441 -0
  56. package/src/routing/interaction.js +3 -0
  57. package/src/routing/knn-router.js +70 -21
  58. package/src/routing/model-registry.js +28 -7
  59. package/src/routing/model-tiers.js +25 -2
  60. package/src/routing/reward-pipeline.js +68 -2
  61. package/src/routing/risk-analyzer.js +30 -1
  62. package/src/routing/risk-classifier.js +6 -2
  63. package/src/routing/session-affinity.js +162 -34
  64. package/src/routing/telemetry.js +286 -13
  65. package/src/routing/verifier.js +267 -0
  66. package/src/server.js +86 -21
  67. package/src/sessions/cleanup.js +17 -0
  68. package/src/tools/index.js +1 -15
  69. package/src/tools/smart-selection.js +10 -0
  70. package/src/tools/web-client.js +3 -3
  71. package/.eslintrc.cjs +0 -12
  72. package/benchmark-configs/litellm_config.yaml +0 -86
  73. package/benchmark-configs/lynkr.env +0 -48
  74. package/benchmark-configs/portkey-config.json +0 -60
  75. package/benchmark-configs/portkey-docker.sh +0 -23
  76. package/benchmark-tier-routing.js +0 -449
  77. package/funding.json +0 -110
  78. package/src/api/middleware/validation.js +0 -261
  79. package/src/routing/drift-monitor.js +0 -113
  80. package/src/workers/helpers.js +0 -185
@@ -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 };
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Validate the LLM difficulty classifier against the eval set.
4
+ *
5
+ * Runs data/difficulty-eval.jsonl through src/routing/difficulty-classifier.js
6
+ * (the SIMPLE tier model — currently minimax-m2.5:cloud via ollama).
7
+ * Reports overall + per-tier accuracy, confusion matrix, and lists the
8
+ * misclassifications so we can eyeball whether classifier or label is wrong.
9
+ *
10
+ * Bar to ship: ≥85% overall, zero MEDIUM→REASONING false positives.
11
+ *
12
+ * Usage: node scripts/validate-difficulty-classifier.js
13
+ */
14
+
15
+ const fs = require("fs");
16
+ const path = require("path");
17
+ const { classifyDifficulty, _clearCacheForTests } = require("../src/routing/difficulty-classifier");
18
+
19
+ const EVAL_FILE = path.join(__dirname, "../data/difficulty-eval.jsonl");
20
+ const RESULTS_FILE = path.join(__dirname, "../data/difficulty-eval-results.jsonl");
21
+ const TIERS = ["SIMPLE", "MEDIUM", "COMPLEX", "REASONING"];
22
+
23
+ async function main() {
24
+ _clearCacheForTests();
25
+ const lines = fs.readFileSync(EVAL_FILE, "utf8").split("\n").filter(Boolean);
26
+ const rows = lines.map(l => JSON.parse(l));
27
+ console.log(`Loaded ${rows.length} eval rows`);
28
+
29
+ // Persist incrementally so a crash mid-run preserves partial data.
30
+ const resultsFd = fs.openSync(RESULTS_FILE, "w");
31
+ const results = [];
32
+ const t0 = Date.now();
33
+ let done = 0;
34
+ for (const row of rows) {
35
+ const r = await classifyDifficulty(row.text);
36
+ const record = {
37
+ ...row,
38
+ predicted: r?.tier ?? null,
39
+ confidence: r?.confidence ?? null,
40
+ };
41
+ results.push(record);
42
+ fs.writeSync(resultsFd, JSON.stringify(record) + "\n");
43
+ done++;
44
+ if (done % 25 === 0) {
45
+ const elapsed = (Date.now() - t0) / 1000;
46
+ process.stdout.write(` ${done}/${rows.length} (${elapsed.toFixed(0)}s, avg ${(elapsed / done * 1000).toFixed(0)}ms/prompt)\n`);
47
+ }
48
+ }
49
+ fs.closeSync(resultsFd);
50
+ console.log(`\nDone in ${((Date.now() - t0) / 1000).toFixed(0)}s (results saved to ${RESULTS_FILE})`);
51
+
52
+ // Overall + per-tier accuracy
53
+ const perTier = {};
54
+ const confusion = {};
55
+ for (const t of TIERS) {
56
+ perTier[t] = { total: 0, correct: 0 };
57
+ confusion[t] = { SIMPLE: 0, MEDIUM: 0, COMPLEX: 0, REASONING: 0, null: 0 };
58
+ }
59
+ let overall = 0;
60
+ let classified = 0;
61
+ let skipped = 0;
62
+ for (const r of results) {
63
+ if (r.predicted === null) { skipped++; continue; }
64
+ classified++;
65
+ perTier[r.tier].total++;
66
+ confusion[r.tier][r.predicted] = (confusion[r.tier][r.predicted] || 0) + 1;
67
+ if (r.predicted === r.tier) { overall++; perTier[r.tier].correct++; }
68
+ }
69
+
70
+ console.log(`\n=== Accuracy ===`);
71
+ console.log(`Overall: ${overall}/${classified} (${(overall / classified * 100).toFixed(1)}%)`);
72
+ console.log(`Skipped (short text / classifier disabled): ${skipped}`);
73
+ console.log(`\nPer-tier:`);
74
+ for (const t of TIERS) {
75
+ const p = perTier[t];
76
+ if (p.total === 0) continue;
77
+ console.log(` ${t}: ${p.correct}/${p.total} (${(p.correct / p.total * 100).toFixed(1)}%)`);
78
+ }
79
+
80
+ // Per-source accuracy: hand labels are trusted; benchmark labels have known
81
+ // difficulty-vs-tier bias (RouterArena's "easy" band ≠ MEDIUM tier; gpt4's
82
+ // mixtral_score ≠ tier). Report separately for an honest signal.
83
+ console.log(`\n=== Per-source ===`);
84
+ const sources = {};
85
+ for (const r of results) {
86
+ if (r.predicted === null) continue;
87
+ const s = r.source || 'unknown';
88
+ if (!sources[s]) sources[s] = { total: 0, correct: 0 };
89
+ sources[s].total++;
90
+ if (r.predicted === r.tier) sources[s].correct++;
91
+ }
92
+ for (const [s, v] of Object.entries(sources)) {
93
+ console.log(` ${s}: ${v.correct}/${v.total} (${(v.correct / v.total * 100).toFixed(1)}%)`);
94
+ }
95
+
96
+ console.log(`\n=== Confusion matrix (rows = true, cols = predicted) ===`);
97
+ console.log(` ${TIERS.map(t => t.padStart(9)).join("")}`);
98
+ for (const t of TIERS) {
99
+ const row = TIERS.map(pred => String(confusion[t][pred] || 0).padStart(9)).join("");
100
+ console.log(`${t.padStart(9)}${row}`);
101
+ }
102
+
103
+ // Critical failure mode: MEDIUM→REASONING (over-routing to expensive tier)
104
+ const overRouted = confusion.MEDIUM?.REASONING || 0;
105
+ const simpleToReasoning = confusion.SIMPLE?.REASONING || 0;
106
+ console.log(`\n=== Critical false positives ===`);
107
+ console.log(`MEDIUM→REASONING: ${overRouted} (must be 0 to ship)`);
108
+ console.log(`SIMPLE→REASONING: ${simpleToReasoning}`);
109
+ console.log(`MEDIUM→COMPLEX: ${confusion.MEDIUM?.COMPLEX || 0}`);
110
+
111
+ // List misclassifications (cap at 20 per tier)
112
+ console.log(`\n=== Misclassifications (up to 5 per tier) ===`);
113
+ for (const t of TIERS) {
114
+ const errors = results.filter(r => r.tier === t && r.predicted && r.predicted !== t).slice(0, 5);
115
+ if (errors.length === 0) continue;
116
+ console.log(`\n${t}:`);
117
+ for (const e of errors) {
118
+ console.log(` → ${e.predicted} (conf ${e.confidence?.toFixed(2)}): ${e.text.slice(0, 90)}`);
119
+ }
120
+ }
121
+ }
122
+
123
+ main().catch(err => { console.error(err); process.exit(1); });