@ulrichc1/sparn 1.0.1 → 1.1.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 +38 -6
- package/dist/cli/index.cjs +646 -15
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +639 -6
- package/dist/cli/index.js.map +1 -1
- package/dist/daemon/index.cjs +882 -0
- package/dist/daemon/index.cjs.map +1 -0
- package/dist/daemon/index.d.cts +2 -0
- package/dist/daemon/index.d.ts +2 -0
- package/dist/daemon/index.js +880 -0
- package/dist/daemon/index.js.map +1 -0
- package/dist/hooks/post-tool-result.cjs +270 -0
- package/dist/hooks/post-tool-result.cjs.map +1 -0
- package/dist/hooks/post-tool-result.d.cts +1 -0
- package/dist/hooks/post-tool-result.d.ts +1 -0
- package/dist/hooks/post-tool-result.js +269 -0
- package/dist/hooks/post-tool-result.js.map +1 -0
- package/dist/hooks/pre-prompt.cjs +287 -0
- package/dist/hooks/pre-prompt.cjs.map +1 -0
- package/dist/hooks/pre-prompt.d.cts +1 -0
- package/dist/hooks/pre-prompt.d.ts +1 -0
- package/dist/hooks/pre-prompt.js +286 -0
- package/dist/hooks/pre-prompt.js.map +1 -0
- package/dist/index.cjs +961 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +459 -20
- package/dist/index.d.ts +459 -20
- package/dist/index.js +956 -66
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
//
|
|
2
|
-
import
|
|
1
|
+
// node_modules/tsup/assets/esm_shims.js
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { fileURLToPath } from "url";
|
|
4
|
+
var getFilename = () => fileURLToPath(import.meta.url);
|
|
5
|
+
var getDirname = () => path.dirname(getFilename());
|
|
6
|
+
var __dirname = /* @__PURE__ */ getDirname();
|
|
3
7
|
|
|
4
8
|
// src/core/btsp-embedder.ts
|
|
5
9
|
import { randomUUID } from "crypto";
|
|
@@ -214,6 +218,82 @@ function createSparsePruner(config) {
|
|
|
214
218
|
};
|
|
215
219
|
}
|
|
216
220
|
|
|
221
|
+
// src/utils/context-parser.ts
|
|
222
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
223
|
+
function parseClaudeCodeContext(context) {
|
|
224
|
+
const entries = [];
|
|
225
|
+
const now = Date.now();
|
|
226
|
+
const lines = context.split("\n");
|
|
227
|
+
let currentBlock = [];
|
|
228
|
+
let blockType = "other";
|
|
229
|
+
for (const line of lines) {
|
|
230
|
+
const trimmed = line.trim();
|
|
231
|
+
if (trimmed.startsWith("User:") || trimmed.startsWith("Assistant:")) {
|
|
232
|
+
if (currentBlock.length > 0) {
|
|
233
|
+
entries.push(createEntry(currentBlock.join("\n"), blockType, now));
|
|
234
|
+
currentBlock = [];
|
|
235
|
+
}
|
|
236
|
+
blockType = "conversation";
|
|
237
|
+
currentBlock.push(line);
|
|
238
|
+
} else if (trimmed.includes("<function_calls>") || trimmed.includes("<invoke>") || trimmed.includes("<tool_use>")) {
|
|
239
|
+
if (currentBlock.length > 0) {
|
|
240
|
+
entries.push(createEntry(currentBlock.join("\n"), blockType, now));
|
|
241
|
+
currentBlock = [];
|
|
242
|
+
}
|
|
243
|
+
blockType = "tool";
|
|
244
|
+
currentBlock.push(line);
|
|
245
|
+
} else if (trimmed.includes("<function_results>") || trimmed.includes("</function_results>")) {
|
|
246
|
+
if (currentBlock.length > 0 && blockType !== "result") {
|
|
247
|
+
entries.push(createEntry(currentBlock.join("\n"), blockType, now));
|
|
248
|
+
currentBlock = [];
|
|
249
|
+
}
|
|
250
|
+
blockType = "result";
|
|
251
|
+
currentBlock.push(line);
|
|
252
|
+
} else if (currentBlock.length > 0) {
|
|
253
|
+
currentBlock.push(line);
|
|
254
|
+
} else if (trimmed.length > 0) {
|
|
255
|
+
currentBlock.push(line);
|
|
256
|
+
blockType = "other";
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
if (currentBlock.length > 0) {
|
|
260
|
+
entries.push(createEntry(currentBlock.join("\n"), blockType, now));
|
|
261
|
+
}
|
|
262
|
+
return entries.filter((e) => e.content.trim().length > 0);
|
|
263
|
+
}
|
|
264
|
+
function createEntry(content, type, baseTime) {
|
|
265
|
+
const tags = [type];
|
|
266
|
+
let initialScore = 0.5;
|
|
267
|
+
if (type === "conversation") initialScore = 0.8;
|
|
268
|
+
if (type === "tool") initialScore = 0.7;
|
|
269
|
+
if (type === "result") initialScore = 0.4;
|
|
270
|
+
return {
|
|
271
|
+
id: randomUUID2(),
|
|
272
|
+
content,
|
|
273
|
+
hash: hashContent(content),
|
|
274
|
+
timestamp: baseTime,
|
|
275
|
+
score: initialScore,
|
|
276
|
+
state: initialScore > 0.7 ? "active" : initialScore > 0.3 ? "ready" : "silent",
|
|
277
|
+
ttl: 24 * 3600,
|
|
278
|
+
// 24 hours default
|
|
279
|
+
accessCount: 0,
|
|
280
|
+
tags,
|
|
281
|
+
metadata: { type },
|
|
282
|
+
isBTSP: false
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
function parseGenericContext(context) {
|
|
286
|
+
const entries = [];
|
|
287
|
+
const now = Date.now();
|
|
288
|
+
const blocks = context.split(/\n\n+/);
|
|
289
|
+
for (const block of blocks) {
|
|
290
|
+
const trimmed = block.trim();
|
|
291
|
+
if (trimmed.length === 0) continue;
|
|
292
|
+
entries.push(createEntry(trimmed, "other", now));
|
|
293
|
+
}
|
|
294
|
+
return entries;
|
|
295
|
+
}
|
|
296
|
+
|
|
217
297
|
// src/adapters/claude-code.ts
|
|
218
298
|
var CLAUDE_CODE_PROFILE = {
|
|
219
299
|
// More aggressive pruning for tool results (they can be verbose)
|
|
@@ -333,68 +413,6 @@ function createClaudeCodeAdapter(memory, config) {
|
|
|
333
413
|
optimize
|
|
334
414
|
};
|
|
335
415
|
}
|
|
336
|
-
function parseClaudeCodeContext(context) {
|
|
337
|
-
const entries = [];
|
|
338
|
-
const now = Date.now();
|
|
339
|
-
const lines = context.split("\n");
|
|
340
|
-
let currentBlock = [];
|
|
341
|
-
let blockType = "other";
|
|
342
|
-
for (const line of lines) {
|
|
343
|
-
const trimmed = line.trim();
|
|
344
|
-
if (trimmed.startsWith("User:") || trimmed.startsWith("Assistant:")) {
|
|
345
|
-
if (currentBlock.length > 0) {
|
|
346
|
-
entries.push(createEntry(currentBlock.join("\n"), blockType, now));
|
|
347
|
-
currentBlock = [];
|
|
348
|
-
}
|
|
349
|
-
blockType = "conversation";
|
|
350
|
-
currentBlock.push(line);
|
|
351
|
-
} else if (trimmed.includes("<function_calls>") || trimmed.includes("<invoke>") || trimmed.includes("<tool_use>")) {
|
|
352
|
-
if (currentBlock.length > 0) {
|
|
353
|
-
entries.push(createEntry(currentBlock.join("\n"), blockType, now));
|
|
354
|
-
currentBlock = [];
|
|
355
|
-
}
|
|
356
|
-
blockType = "tool";
|
|
357
|
-
currentBlock.push(line);
|
|
358
|
-
} else if (trimmed.includes("<function_results>") || trimmed.includes("</function_results>")) {
|
|
359
|
-
if (currentBlock.length > 0 && blockType !== "result") {
|
|
360
|
-
entries.push(createEntry(currentBlock.join("\n"), blockType, now));
|
|
361
|
-
currentBlock = [];
|
|
362
|
-
}
|
|
363
|
-
blockType = "result";
|
|
364
|
-
currentBlock.push(line);
|
|
365
|
-
} else if (currentBlock.length > 0) {
|
|
366
|
-
currentBlock.push(line);
|
|
367
|
-
} else if (trimmed.length > 0) {
|
|
368
|
-
currentBlock.push(line);
|
|
369
|
-
blockType = "other";
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
if (currentBlock.length > 0) {
|
|
373
|
-
entries.push(createEntry(currentBlock.join("\n"), blockType, now));
|
|
374
|
-
}
|
|
375
|
-
return entries.filter((e) => e.content.trim().length > 0);
|
|
376
|
-
}
|
|
377
|
-
function createEntry(content, type, baseTime) {
|
|
378
|
-
const tags = [type];
|
|
379
|
-
let initialScore = 0.5;
|
|
380
|
-
if (type === "conversation") initialScore = 0.8;
|
|
381
|
-
if (type === "tool") initialScore = 0.7;
|
|
382
|
-
if (type === "result") initialScore = 0.4;
|
|
383
|
-
return {
|
|
384
|
-
id: randomUUID2(),
|
|
385
|
-
content,
|
|
386
|
-
hash: hashContent(content),
|
|
387
|
-
timestamp: baseTime,
|
|
388
|
-
score: initialScore,
|
|
389
|
-
state: initialScore > 0.7 ? "active" : initialScore > 0.3 ? "ready" : "silent",
|
|
390
|
-
ttl: 24 * 3600,
|
|
391
|
-
// 24 hours default
|
|
392
|
-
accessCount: 0,
|
|
393
|
-
tags,
|
|
394
|
-
metadata: { type },
|
|
395
|
-
isBTSP: false
|
|
396
|
-
};
|
|
397
|
-
}
|
|
398
416
|
|
|
399
417
|
// src/adapters/generic.ts
|
|
400
418
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
@@ -472,6 +490,459 @@ function createGenericAdapter(memory, config) {
|
|
|
472
490
|
};
|
|
473
491
|
}
|
|
474
492
|
|
|
493
|
+
// src/core/budget-pruner.ts
|
|
494
|
+
function createBudgetPruner(config) {
|
|
495
|
+
const { tokenBudget, decay } = config;
|
|
496
|
+
const engramScorer = createEngramScorer(decay);
|
|
497
|
+
function tokenize(text) {
|
|
498
|
+
return text.toLowerCase().split(/\s+/).filter((word) => word.length > 0);
|
|
499
|
+
}
|
|
500
|
+
function calculateTF(term, tokens) {
|
|
501
|
+
const count = tokens.filter((t) => t === term).length;
|
|
502
|
+
return Math.sqrt(count);
|
|
503
|
+
}
|
|
504
|
+
function calculateIDF(term, allEntries) {
|
|
505
|
+
const totalDocs = allEntries.length;
|
|
506
|
+
const docsWithTerm = allEntries.filter((entry) => {
|
|
507
|
+
const tokens = tokenize(entry.content);
|
|
508
|
+
return tokens.includes(term);
|
|
509
|
+
}).length;
|
|
510
|
+
if (docsWithTerm === 0) return 0;
|
|
511
|
+
return Math.log(totalDocs / docsWithTerm);
|
|
512
|
+
}
|
|
513
|
+
function calculateTFIDF(entry, allEntries) {
|
|
514
|
+
const tokens = tokenize(entry.content);
|
|
515
|
+
if (tokens.length === 0) return 0;
|
|
516
|
+
const uniqueTerms = [...new Set(tokens)];
|
|
517
|
+
let totalScore = 0;
|
|
518
|
+
for (const term of uniqueTerms) {
|
|
519
|
+
const tf = calculateTF(term, tokens);
|
|
520
|
+
const idf = calculateIDF(term, allEntries);
|
|
521
|
+
totalScore += tf * idf;
|
|
522
|
+
}
|
|
523
|
+
return totalScore / tokens.length;
|
|
524
|
+
}
|
|
525
|
+
function getStateMultiplier(entry) {
|
|
526
|
+
if (entry.isBTSP) return 2;
|
|
527
|
+
switch (entry.state) {
|
|
528
|
+
case "active":
|
|
529
|
+
return 2;
|
|
530
|
+
case "ready":
|
|
531
|
+
return 1;
|
|
532
|
+
case "silent":
|
|
533
|
+
return 0.5;
|
|
534
|
+
default:
|
|
535
|
+
return 1;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
function priorityScore(entry, allEntries) {
|
|
539
|
+
const tfidf = calculateTFIDF(entry, allEntries);
|
|
540
|
+
const currentScore = engramScorer.calculateScore(entry);
|
|
541
|
+
const engramDecay = 1 - currentScore;
|
|
542
|
+
const stateMultiplier = getStateMultiplier(entry);
|
|
543
|
+
return tfidf * (1 - engramDecay) * stateMultiplier;
|
|
544
|
+
}
|
|
545
|
+
function pruneToFit(entries, budget = tokenBudget) {
|
|
546
|
+
if (entries.length === 0) {
|
|
547
|
+
return {
|
|
548
|
+
kept: [],
|
|
549
|
+
removed: [],
|
|
550
|
+
originalTokens: 0,
|
|
551
|
+
prunedTokens: 0,
|
|
552
|
+
budgetUtilization: 0
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
const originalTokens = entries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
|
|
556
|
+
const btspEntries = entries.filter((e) => e.isBTSP);
|
|
557
|
+
const regularEntries = entries.filter((e) => !e.isBTSP);
|
|
558
|
+
const btspTokens = btspEntries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
|
|
559
|
+
const scored = regularEntries.map((entry) => ({
|
|
560
|
+
entry,
|
|
561
|
+
score: priorityScore(entry, entries),
|
|
562
|
+
tokens: estimateTokens(entry.content)
|
|
563
|
+
}));
|
|
564
|
+
scored.sort((a, b) => b.score - a.score);
|
|
565
|
+
const kept = [...btspEntries];
|
|
566
|
+
const removed = [];
|
|
567
|
+
let currentTokens = btspTokens;
|
|
568
|
+
for (const item of scored) {
|
|
569
|
+
if (currentTokens + item.tokens <= budget) {
|
|
570
|
+
kept.push(item.entry);
|
|
571
|
+
currentTokens += item.tokens;
|
|
572
|
+
} else {
|
|
573
|
+
removed.push(item.entry);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
const budgetUtilization = budget > 0 ? currentTokens / budget : 0;
|
|
577
|
+
return {
|
|
578
|
+
kept,
|
|
579
|
+
removed,
|
|
580
|
+
originalTokens,
|
|
581
|
+
prunedTokens: currentTokens,
|
|
582
|
+
budgetUtilization
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
return {
|
|
586
|
+
pruneToFit,
|
|
587
|
+
priorityScore
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
function createBudgetPrunerFromConfig(realtimeConfig, decayConfig, statesConfig) {
|
|
591
|
+
return createBudgetPruner({
|
|
592
|
+
tokenBudget: realtimeConfig.tokenBudget,
|
|
593
|
+
decay: decayConfig,
|
|
594
|
+
states: statesConfig
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// src/core/metrics.ts
|
|
599
|
+
function createMetricsCollector() {
|
|
600
|
+
const optimizations = [];
|
|
601
|
+
let daemonMetrics = {
|
|
602
|
+
startTime: Date.now(),
|
|
603
|
+
sessionsWatched: 0,
|
|
604
|
+
totalOptimizations: 0,
|
|
605
|
+
totalTokensSaved: 0,
|
|
606
|
+
averageLatency: 0,
|
|
607
|
+
memoryUsage: 0
|
|
608
|
+
};
|
|
609
|
+
let cacheHits = 0;
|
|
610
|
+
let cacheMisses = 0;
|
|
611
|
+
function recordOptimization(metric) {
|
|
612
|
+
optimizations.push(metric);
|
|
613
|
+
daemonMetrics.totalOptimizations++;
|
|
614
|
+
daemonMetrics.totalTokensSaved += metric.tokensBefore - metric.tokensAfter;
|
|
615
|
+
if (metric.cacheHitRate > 0) {
|
|
616
|
+
const hits = Math.round(metric.entriesProcessed * metric.cacheHitRate);
|
|
617
|
+
cacheHits += hits;
|
|
618
|
+
cacheMisses += metric.entriesProcessed - hits;
|
|
619
|
+
}
|
|
620
|
+
daemonMetrics.averageLatency = (daemonMetrics.averageLatency * (daemonMetrics.totalOptimizations - 1) + metric.duration) / daemonMetrics.totalOptimizations;
|
|
621
|
+
if (optimizations.length > 1e3) {
|
|
622
|
+
optimizations.shift();
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
function updateDaemon(metric) {
|
|
626
|
+
daemonMetrics = {
|
|
627
|
+
...daemonMetrics,
|
|
628
|
+
...metric
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
function calculatePercentile(values, percentile) {
|
|
632
|
+
if (values.length === 0) return 0;
|
|
633
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
634
|
+
const index = Math.ceil(percentile / 100 * sorted.length) - 1;
|
|
635
|
+
return sorted[index] || 0;
|
|
636
|
+
}
|
|
637
|
+
function getSnapshot() {
|
|
638
|
+
const totalRuns = optimizations.length;
|
|
639
|
+
const totalDuration = optimizations.reduce((sum, m) => sum + m.duration, 0);
|
|
640
|
+
const totalTokensSaved = optimizations.reduce(
|
|
641
|
+
(sum, m) => sum + (m.tokensBefore - m.tokensAfter),
|
|
642
|
+
0
|
|
643
|
+
);
|
|
644
|
+
const totalTokensBefore = optimizations.reduce((sum, m) => sum + m.tokensBefore, 0);
|
|
645
|
+
const averageReduction = totalTokensBefore > 0 ? totalTokensSaved / totalTokensBefore : 0;
|
|
646
|
+
const durations = optimizations.map((m) => m.duration);
|
|
647
|
+
const totalCacheQueries = cacheHits + cacheMisses;
|
|
648
|
+
const hitRate = totalCacheQueries > 0 ? cacheHits / totalCacheQueries : 0;
|
|
649
|
+
return {
|
|
650
|
+
timestamp: Date.now(),
|
|
651
|
+
optimization: {
|
|
652
|
+
totalRuns,
|
|
653
|
+
totalDuration,
|
|
654
|
+
totalTokensSaved,
|
|
655
|
+
averageReduction,
|
|
656
|
+
p50Latency: calculatePercentile(durations, 50),
|
|
657
|
+
p95Latency: calculatePercentile(durations, 95),
|
|
658
|
+
p99Latency: calculatePercentile(durations, 99)
|
|
659
|
+
},
|
|
660
|
+
cache: {
|
|
661
|
+
hitRate,
|
|
662
|
+
totalHits: cacheHits,
|
|
663
|
+
totalMisses: cacheMisses,
|
|
664
|
+
size: optimizations.reduce((sum, m) => sum + m.entriesKept, 0)
|
|
665
|
+
},
|
|
666
|
+
daemon: {
|
|
667
|
+
uptime: Date.now() - daemonMetrics.startTime,
|
|
668
|
+
sessionsWatched: daemonMetrics.sessionsWatched,
|
|
669
|
+
memoryUsage: daemonMetrics.memoryUsage
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
function exportMetrics() {
|
|
674
|
+
return JSON.stringify(getSnapshot(), null, 2);
|
|
675
|
+
}
|
|
676
|
+
function reset() {
|
|
677
|
+
optimizations.length = 0;
|
|
678
|
+
cacheHits = 0;
|
|
679
|
+
cacheMisses = 0;
|
|
680
|
+
daemonMetrics = {
|
|
681
|
+
startTime: Date.now(),
|
|
682
|
+
sessionsWatched: 0,
|
|
683
|
+
totalOptimizations: 0,
|
|
684
|
+
totalTokensSaved: 0,
|
|
685
|
+
averageLatency: 0,
|
|
686
|
+
memoryUsage: 0
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
return {
|
|
690
|
+
recordOptimization,
|
|
691
|
+
updateDaemon,
|
|
692
|
+
getSnapshot,
|
|
693
|
+
export: exportMetrics,
|
|
694
|
+
reset
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
var globalMetrics = null;
|
|
698
|
+
function getMetrics() {
|
|
699
|
+
if (!globalMetrics) {
|
|
700
|
+
globalMetrics = createMetricsCollector();
|
|
701
|
+
}
|
|
702
|
+
return globalMetrics;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// src/core/incremental-optimizer.ts
|
|
706
|
+
function createIncrementalOptimizer(config) {
|
|
707
|
+
const pruner = createBudgetPruner(config);
|
|
708
|
+
const { fullOptimizationInterval } = config;
|
|
709
|
+
let state = {
|
|
710
|
+
entryCache: /* @__PURE__ */ new Map(),
|
|
711
|
+
documentFrequency: /* @__PURE__ */ new Map(),
|
|
712
|
+
totalDocuments: 0,
|
|
713
|
+
updateCount: 0,
|
|
714
|
+
lastFullOptimization: Date.now()
|
|
715
|
+
};
|
|
716
|
+
function tokenize(text) {
|
|
717
|
+
return text.toLowerCase().split(/\s+/).filter((word) => word.length > 0);
|
|
718
|
+
}
|
|
719
|
+
function updateDocumentFrequency(entries, remove = false) {
|
|
720
|
+
for (const entry of entries) {
|
|
721
|
+
const tokens = tokenize(entry.content);
|
|
722
|
+
const uniqueTerms = [...new Set(tokens)];
|
|
723
|
+
for (const term of uniqueTerms) {
|
|
724
|
+
const current = state.documentFrequency.get(term) || 0;
|
|
725
|
+
const updated = remove ? Math.max(0, current - 1) : current + 1;
|
|
726
|
+
if (updated === 0) {
|
|
727
|
+
state.documentFrequency.delete(term);
|
|
728
|
+
} else {
|
|
729
|
+
state.documentFrequency.set(term, updated);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
state.totalDocuments += remove ? -entries.length : entries.length;
|
|
734
|
+
state.totalDocuments = Math.max(0, state.totalDocuments);
|
|
735
|
+
}
|
|
736
|
+
function getCachedEntry(hash) {
|
|
737
|
+
const cached = state.entryCache.get(hash);
|
|
738
|
+
if (!cached) return null;
|
|
739
|
+
return cached.entry;
|
|
740
|
+
}
|
|
741
|
+
function cacheEntry(entry, score) {
|
|
742
|
+
state.entryCache.set(entry.hash, {
|
|
743
|
+
entry,
|
|
744
|
+
score,
|
|
745
|
+
timestamp: Date.now()
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
function optimizeIncremental(newEntries, budget) {
|
|
749
|
+
const startTime = Date.now();
|
|
750
|
+
state.updateCount++;
|
|
751
|
+
if (state.updateCount >= fullOptimizationInterval) {
|
|
752
|
+
const allEntries2 = Array.from(state.entryCache.values()).map((c) => c.entry);
|
|
753
|
+
return optimizeFull([...allEntries2, ...newEntries], budget);
|
|
754
|
+
}
|
|
755
|
+
const uncachedEntries = [];
|
|
756
|
+
const cachedEntries = [];
|
|
757
|
+
for (const entry of newEntries) {
|
|
758
|
+
const cached = getCachedEntry(entry.hash);
|
|
759
|
+
if (cached) {
|
|
760
|
+
cachedEntries.push(cached);
|
|
761
|
+
} else {
|
|
762
|
+
uncachedEntries.push(entry);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
if (uncachedEntries.length > 0) {
|
|
766
|
+
updateDocumentFrequency(uncachedEntries, false);
|
|
767
|
+
}
|
|
768
|
+
const allEntries = [...cachedEntries, ...uncachedEntries];
|
|
769
|
+
for (const entry of uncachedEntries) {
|
|
770
|
+
const score = pruner.priorityScore(entry, allEntries);
|
|
771
|
+
cacheEntry(entry, score);
|
|
772
|
+
}
|
|
773
|
+
const currentEntries = Array.from(state.entryCache.values()).map((c) => c.entry);
|
|
774
|
+
const tokensBefore = currentEntries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
|
|
775
|
+
const result = pruner.pruneToFit(currentEntries, budget);
|
|
776
|
+
const tokensAfter = result.kept.reduce((sum, e) => sum + estimateTokens(e.content), 0);
|
|
777
|
+
for (const removed of result.removed) {
|
|
778
|
+
state.entryCache.delete(removed.hash);
|
|
779
|
+
}
|
|
780
|
+
if (result.removed.length > 0) {
|
|
781
|
+
updateDocumentFrequency(result.removed, true);
|
|
782
|
+
}
|
|
783
|
+
const duration = Date.now() - startTime;
|
|
784
|
+
const cacheHitRate = newEntries.length > 0 ? cachedEntries.length / newEntries.length : 0;
|
|
785
|
+
getMetrics().recordOptimization({
|
|
786
|
+
timestamp: Date.now(),
|
|
787
|
+
duration,
|
|
788
|
+
tokensBefore,
|
|
789
|
+
tokensAfter,
|
|
790
|
+
entriesProcessed: newEntries.length,
|
|
791
|
+
entriesKept: result.kept.length,
|
|
792
|
+
cacheHitRate,
|
|
793
|
+
memoryUsage: process.memoryUsage().heapUsed
|
|
794
|
+
});
|
|
795
|
+
return result;
|
|
796
|
+
}
|
|
797
|
+
function optimizeFull(allEntries, budget) {
|
|
798
|
+
const startTime = Date.now();
|
|
799
|
+
const tokensBefore = allEntries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
|
|
800
|
+
state.entryCache.clear();
|
|
801
|
+
state.documentFrequency.clear();
|
|
802
|
+
state.totalDocuments = 0;
|
|
803
|
+
state.updateCount = 0;
|
|
804
|
+
state.lastFullOptimization = Date.now();
|
|
805
|
+
updateDocumentFrequency(allEntries, false);
|
|
806
|
+
for (const entry of allEntries) {
|
|
807
|
+
const score = pruner.priorityScore(entry, allEntries);
|
|
808
|
+
cacheEntry(entry, score);
|
|
809
|
+
}
|
|
810
|
+
const result = pruner.pruneToFit(allEntries, budget);
|
|
811
|
+
const tokensAfter = result.kept.reduce((sum, e) => sum + estimateTokens(e.content), 0);
|
|
812
|
+
for (const removed of result.removed) {
|
|
813
|
+
state.entryCache.delete(removed.hash);
|
|
814
|
+
}
|
|
815
|
+
if (result.removed.length > 0) {
|
|
816
|
+
updateDocumentFrequency(result.removed, true);
|
|
817
|
+
}
|
|
818
|
+
const duration = Date.now() - startTime;
|
|
819
|
+
getMetrics().recordOptimization({
|
|
820
|
+
timestamp: Date.now(),
|
|
821
|
+
duration,
|
|
822
|
+
tokensBefore,
|
|
823
|
+
tokensAfter,
|
|
824
|
+
entriesProcessed: allEntries.length,
|
|
825
|
+
entriesKept: result.kept.length,
|
|
826
|
+
cacheHitRate: 0,
|
|
827
|
+
// Full optimization has no cache hits
|
|
828
|
+
memoryUsage: process.memoryUsage().heapUsed
|
|
829
|
+
});
|
|
830
|
+
return result;
|
|
831
|
+
}
|
|
832
|
+
function getState() {
|
|
833
|
+
return {
|
|
834
|
+
entryCache: new Map(state.entryCache),
|
|
835
|
+
documentFrequency: new Map(state.documentFrequency),
|
|
836
|
+
totalDocuments: state.totalDocuments,
|
|
837
|
+
updateCount: state.updateCount,
|
|
838
|
+
lastFullOptimization: state.lastFullOptimization
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
function restoreState(restoredState) {
|
|
842
|
+
state = {
|
|
843
|
+
entryCache: new Map(restoredState.entryCache),
|
|
844
|
+
documentFrequency: new Map(restoredState.documentFrequency),
|
|
845
|
+
totalDocuments: restoredState.totalDocuments,
|
|
846
|
+
updateCount: restoredState.updateCount,
|
|
847
|
+
lastFullOptimization: restoredState.lastFullOptimization
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
function reset() {
|
|
851
|
+
state = {
|
|
852
|
+
entryCache: /* @__PURE__ */ new Map(),
|
|
853
|
+
documentFrequency: /* @__PURE__ */ new Map(),
|
|
854
|
+
totalDocuments: 0,
|
|
855
|
+
updateCount: 0,
|
|
856
|
+
lastFullOptimization: Date.now()
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
function getStats() {
|
|
860
|
+
return {
|
|
861
|
+
cachedEntries: state.entryCache.size,
|
|
862
|
+
uniqueTerms: state.documentFrequency.size,
|
|
863
|
+
totalDocuments: state.totalDocuments,
|
|
864
|
+
updateCount: state.updateCount,
|
|
865
|
+
lastFullOptimization: state.lastFullOptimization
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
return {
|
|
869
|
+
optimizeIncremental,
|
|
870
|
+
optimizeFull,
|
|
871
|
+
getState,
|
|
872
|
+
restoreState,
|
|
873
|
+
reset,
|
|
874
|
+
getStats
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// src/core/context-pipeline.ts
|
|
879
|
+
function createContextPipeline(config) {
|
|
880
|
+
const optimizer = createIncrementalOptimizer(config);
|
|
881
|
+
const { windowSize, tokenBudget } = config;
|
|
882
|
+
let totalIngested = 0;
|
|
883
|
+
let evictedEntries = 0;
|
|
884
|
+
let currentEntries = [];
|
|
885
|
+
let budgetUtilization = 0;
|
|
886
|
+
function ingest(content, metadata = {}) {
|
|
887
|
+
const newEntries = parseClaudeCodeContext(content);
|
|
888
|
+
if (newEntries.length === 0) return 0;
|
|
889
|
+
const entriesWithMetadata = newEntries.map((entry) => ({
|
|
890
|
+
...entry,
|
|
891
|
+
metadata: { ...entry.metadata, ...metadata }
|
|
892
|
+
}));
|
|
893
|
+
const result = optimizer.optimizeIncremental(entriesWithMetadata, tokenBudget);
|
|
894
|
+
totalIngested += newEntries.length;
|
|
895
|
+
evictedEntries += result.removed.length;
|
|
896
|
+
currentEntries = result.kept;
|
|
897
|
+
budgetUtilization = result.budgetUtilization;
|
|
898
|
+
if (currentEntries.length > windowSize) {
|
|
899
|
+
const sorted = [...currentEntries].sort((a, b) => b.timestamp - a.timestamp);
|
|
900
|
+
const toKeep = sorted.slice(0, windowSize);
|
|
901
|
+
const toRemove = sorted.slice(windowSize);
|
|
902
|
+
currentEntries = toKeep;
|
|
903
|
+
evictedEntries += toRemove.length;
|
|
904
|
+
}
|
|
905
|
+
return newEntries.length;
|
|
906
|
+
}
|
|
907
|
+
function getContext() {
|
|
908
|
+
const sorted = [...currentEntries].sort((a, b) => a.timestamp - b.timestamp);
|
|
909
|
+
return sorted.map((e) => e.content).join("\n\n");
|
|
910
|
+
}
|
|
911
|
+
function getEntries() {
|
|
912
|
+
return [...currentEntries].sort((a, b) => a.timestamp - b.timestamp);
|
|
913
|
+
}
|
|
914
|
+
function getStats() {
|
|
915
|
+
const optimizerStats = optimizer.getStats();
|
|
916
|
+
const currentTokens = currentEntries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
|
|
917
|
+
return {
|
|
918
|
+
totalIngested,
|
|
919
|
+
currentEntries: currentEntries.length,
|
|
920
|
+
currentTokens,
|
|
921
|
+
budgetUtilization,
|
|
922
|
+
evictedEntries,
|
|
923
|
+
optimizer: {
|
|
924
|
+
cachedEntries: optimizerStats.cachedEntries,
|
|
925
|
+
uniqueTerms: optimizerStats.uniqueTerms,
|
|
926
|
+
updateCount: optimizerStats.updateCount
|
|
927
|
+
}
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
function clear() {
|
|
931
|
+
totalIngested = 0;
|
|
932
|
+
evictedEntries = 0;
|
|
933
|
+
currentEntries = [];
|
|
934
|
+
budgetUtilization = 0;
|
|
935
|
+
optimizer.reset();
|
|
936
|
+
}
|
|
937
|
+
return {
|
|
938
|
+
ingest,
|
|
939
|
+
getContext,
|
|
940
|
+
getEntries,
|
|
941
|
+
getStats,
|
|
942
|
+
clear
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
|
|
475
946
|
// src/core/kv-memory.ts
|
|
476
947
|
import { copyFileSync, existsSync } from "fs";
|
|
477
948
|
import Database from "better-sqlite3";
|
|
@@ -841,6 +1312,405 @@ function createSleepCompressor() {
|
|
|
841
1312
|
};
|
|
842
1313
|
}
|
|
843
1314
|
|
|
1315
|
+
// src/daemon/daemon-process.ts
|
|
1316
|
+
import { fork } from "child_process";
|
|
1317
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
|
|
1318
|
+
import { dirname, join } from "path";
|
|
1319
|
+
function createDaemonCommand() {
|
|
1320
|
+
function isDaemonRunning(pidFile) {
|
|
1321
|
+
if (!existsSync2(pidFile)) {
|
|
1322
|
+
return { running: false };
|
|
1323
|
+
}
|
|
1324
|
+
try {
|
|
1325
|
+
const pidStr = readFileSync(pidFile, "utf-8").trim();
|
|
1326
|
+
const pid = Number.parseInt(pidStr, 10);
|
|
1327
|
+
if (Number.isNaN(pid)) {
|
|
1328
|
+
return { running: false };
|
|
1329
|
+
}
|
|
1330
|
+
try {
|
|
1331
|
+
process.kill(pid, 0);
|
|
1332
|
+
return { running: true, pid };
|
|
1333
|
+
} catch {
|
|
1334
|
+
unlinkSync(pidFile);
|
|
1335
|
+
return { running: false };
|
|
1336
|
+
}
|
|
1337
|
+
} catch {
|
|
1338
|
+
return { running: false };
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
function writePidFile(pidFile, pid) {
|
|
1342
|
+
const dir = dirname(pidFile);
|
|
1343
|
+
if (!existsSync2(dir)) {
|
|
1344
|
+
mkdirSync(dir, { recursive: true });
|
|
1345
|
+
}
|
|
1346
|
+
writeFileSync(pidFile, String(pid), "utf-8");
|
|
1347
|
+
}
|
|
1348
|
+
function removePidFile(pidFile) {
|
|
1349
|
+
if (existsSync2(pidFile)) {
|
|
1350
|
+
unlinkSync(pidFile);
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
async function start(config) {
|
|
1354
|
+
const { pidFile, logFile } = config.realtime;
|
|
1355
|
+
const status2 = isDaemonRunning(pidFile);
|
|
1356
|
+
if (status2.running) {
|
|
1357
|
+
return {
|
|
1358
|
+
success: false,
|
|
1359
|
+
pid: status2.pid,
|
|
1360
|
+
message: `Daemon already running (PID ${status2.pid})`,
|
|
1361
|
+
error: "Already running"
|
|
1362
|
+
};
|
|
1363
|
+
}
|
|
1364
|
+
try {
|
|
1365
|
+
const daemonPath = join(__dirname, "index.js");
|
|
1366
|
+
const child = fork(daemonPath, [], {
|
|
1367
|
+
detached: true,
|
|
1368
|
+
stdio: "ignore",
|
|
1369
|
+
env: {
|
|
1370
|
+
...process.env,
|
|
1371
|
+
SPARN_CONFIG: JSON.stringify(config),
|
|
1372
|
+
SPARN_PID_FILE: pidFile,
|
|
1373
|
+
SPARN_LOG_FILE: logFile
|
|
1374
|
+
}
|
|
1375
|
+
});
|
|
1376
|
+
child.unref();
|
|
1377
|
+
if (child.pid) {
|
|
1378
|
+
writePidFile(pidFile, child.pid);
|
|
1379
|
+
return {
|
|
1380
|
+
success: true,
|
|
1381
|
+
pid: child.pid,
|
|
1382
|
+
message: `Daemon started (PID ${child.pid})`
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
return {
|
|
1386
|
+
success: false,
|
|
1387
|
+
message: "Failed to start daemon (no PID)",
|
|
1388
|
+
error: "No PID"
|
|
1389
|
+
};
|
|
1390
|
+
} catch (error) {
|
|
1391
|
+
return {
|
|
1392
|
+
success: false,
|
|
1393
|
+
message: "Failed to start daemon",
|
|
1394
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
async function stop(config) {
|
|
1399
|
+
const { pidFile } = config.realtime;
|
|
1400
|
+
const status2 = isDaemonRunning(pidFile);
|
|
1401
|
+
if (!status2.running || !status2.pid) {
|
|
1402
|
+
return {
|
|
1403
|
+
success: true,
|
|
1404
|
+
message: "Daemon not running"
|
|
1405
|
+
};
|
|
1406
|
+
}
|
|
1407
|
+
try {
|
|
1408
|
+
process.kill(status2.pid, "SIGTERM");
|
|
1409
|
+
const maxWait = 5e3;
|
|
1410
|
+
const interval = 100;
|
|
1411
|
+
let waited = 0;
|
|
1412
|
+
while (waited < maxWait) {
|
|
1413
|
+
try {
|
|
1414
|
+
process.kill(status2.pid, 0);
|
|
1415
|
+
await new Promise((resolve) => setTimeout(resolve, interval));
|
|
1416
|
+
waited += interval;
|
|
1417
|
+
} catch {
|
|
1418
|
+
removePidFile(pidFile);
|
|
1419
|
+
return {
|
|
1420
|
+
success: true,
|
|
1421
|
+
message: `Daemon stopped (PID ${status2.pid})`
|
|
1422
|
+
};
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
try {
|
|
1426
|
+
process.kill(status2.pid, "SIGKILL");
|
|
1427
|
+
removePidFile(pidFile);
|
|
1428
|
+
return {
|
|
1429
|
+
success: true,
|
|
1430
|
+
message: `Daemon force killed (PID ${status2.pid})`
|
|
1431
|
+
};
|
|
1432
|
+
} catch {
|
|
1433
|
+
removePidFile(pidFile);
|
|
1434
|
+
return {
|
|
1435
|
+
success: true,
|
|
1436
|
+
message: `Daemon stopped (PID ${status2.pid})`
|
|
1437
|
+
};
|
|
1438
|
+
}
|
|
1439
|
+
} catch (error) {
|
|
1440
|
+
return {
|
|
1441
|
+
success: false,
|
|
1442
|
+
message: "Failed to stop daemon",
|
|
1443
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1444
|
+
};
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
async function status(config) {
|
|
1448
|
+
const { pidFile } = config.realtime;
|
|
1449
|
+
const daemonStatus = isDaemonRunning(pidFile);
|
|
1450
|
+
if (!daemonStatus.running || !daemonStatus.pid) {
|
|
1451
|
+
return {
|
|
1452
|
+
running: false,
|
|
1453
|
+
message: "Daemon not running"
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
const metrics = getMetrics().getSnapshot();
|
|
1457
|
+
return {
|
|
1458
|
+
running: true,
|
|
1459
|
+
pid: daemonStatus.pid,
|
|
1460
|
+
uptime: metrics.daemon.uptime,
|
|
1461
|
+
sessionsWatched: metrics.daemon.sessionsWatched,
|
|
1462
|
+
tokensSaved: metrics.optimization.totalTokensSaved,
|
|
1463
|
+
message: `Daemon running (PID ${daemonStatus.pid})`
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
return {
|
|
1467
|
+
start,
|
|
1468
|
+
stop,
|
|
1469
|
+
status
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
// src/daemon/file-tracker.ts
|
|
1474
|
+
import { readFileSync as readFileSync2, statSync } from "fs";
|
|
1475
|
+
function createFileTracker() {
|
|
1476
|
+
const positions = /* @__PURE__ */ new Map();
|
|
1477
|
+
function readNewLines(filePath) {
|
|
1478
|
+
try {
|
|
1479
|
+
const stats = statSync(filePath);
|
|
1480
|
+
const currentSize = stats.size;
|
|
1481
|
+
const currentModified = stats.mtimeMs;
|
|
1482
|
+
let pos = positions.get(filePath);
|
|
1483
|
+
if (!pos) {
|
|
1484
|
+
pos = {
|
|
1485
|
+
path: filePath,
|
|
1486
|
+
position: 0,
|
|
1487
|
+
partialLine: "",
|
|
1488
|
+
lastModified: currentModified,
|
|
1489
|
+
lastSize: 0
|
|
1490
|
+
};
|
|
1491
|
+
positions.set(filePath, pos);
|
|
1492
|
+
}
|
|
1493
|
+
if (currentSize < pos.lastSize || currentSize === pos.position) {
|
|
1494
|
+
if (currentSize < pos.lastSize) {
|
|
1495
|
+
pos.position = 0;
|
|
1496
|
+
pos.partialLine = "";
|
|
1497
|
+
}
|
|
1498
|
+
return [];
|
|
1499
|
+
}
|
|
1500
|
+
const buffer = Buffer.alloc(currentSize - pos.position);
|
|
1501
|
+
const fd = readFileSync2(filePath);
|
|
1502
|
+
fd.copy(buffer, 0, pos.position, currentSize);
|
|
1503
|
+
const newContent = (pos.partialLine + buffer.toString("utf-8")).split("\n");
|
|
1504
|
+
const partialLine = newContent.pop() || "";
|
|
1505
|
+
pos.position = currentSize;
|
|
1506
|
+
pos.partialLine = partialLine;
|
|
1507
|
+
pos.lastModified = currentModified;
|
|
1508
|
+
pos.lastSize = currentSize;
|
|
1509
|
+
return newContent.filter((line) => line.trim().length > 0);
|
|
1510
|
+
} catch (_error) {
|
|
1511
|
+
return [];
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
function getPosition(filePath) {
|
|
1515
|
+
return positions.get(filePath) || null;
|
|
1516
|
+
}
|
|
1517
|
+
function resetPosition(filePath) {
|
|
1518
|
+
positions.delete(filePath);
|
|
1519
|
+
}
|
|
1520
|
+
function clearAll() {
|
|
1521
|
+
positions.clear();
|
|
1522
|
+
}
|
|
1523
|
+
function getTrackedFiles() {
|
|
1524
|
+
return Array.from(positions.keys());
|
|
1525
|
+
}
|
|
1526
|
+
return {
|
|
1527
|
+
readNewLines,
|
|
1528
|
+
getPosition,
|
|
1529
|
+
resetPosition,
|
|
1530
|
+
clearAll,
|
|
1531
|
+
getTrackedFiles
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
// src/daemon/session-watcher.ts
|
|
1536
|
+
import { readdirSync, statSync as statSync2, watch } from "fs";
|
|
1537
|
+
import { homedir } from "os";
|
|
1538
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
1539
|
+
function createSessionWatcher(config) {
|
|
1540
|
+
const { config: sparnConfig, onOptimize, onError } = config;
|
|
1541
|
+
const { realtime, decay, states } = sparnConfig;
|
|
1542
|
+
const pipelines = /* @__PURE__ */ new Map();
|
|
1543
|
+
const fileTracker = createFileTracker();
|
|
1544
|
+
const watchers = [];
|
|
1545
|
+
const debounceTimers = /* @__PURE__ */ new Map();
|
|
1546
|
+
function getProjectsDir() {
|
|
1547
|
+
return join2(homedir(), ".claude", "projects");
|
|
1548
|
+
}
|
|
1549
|
+
function getSessionId(filePath) {
|
|
1550
|
+
const filename = filePath.split(/[/\\]/).pop() || "";
|
|
1551
|
+
return filename.replace(/\.jsonl$/, "");
|
|
1552
|
+
}
|
|
1553
|
+
function getPipeline(sessionId) {
|
|
1554
|
+
let pipeline = pipelines.get(sessionId);
|
|
1555
|
+
if (!pipeline) {
|
|
1556
|
+
pipeline = createContextPipeline({
|
|
1557
|
+
tokenBudget: realtime.tokenBudget,
|
|
1558
|
+
decay,
|
|
1559
|
+
states,
|
|
1560
|
+
windowSize: realtime.windowSize,
|
|
1561
|
+
fullOptimizationInterval: 50
|
|
1562
|
+
// Full re-optimization every 50 incremental updates
|
|
1563
|
+
});
|
|
1564
|
+
pipelines.set(sessionId, pipeline);
|
|
1565
|
+
}
|
|
1566
|
+
return pipeline;
|
|
1567
|
+
}
|
|
1568
|
+
function handleFileChange(filePath) {
|
|
1569
|
+
const existingTimer = debounceTimers.get(filePath);
|
|
1570
|
+
if (existingTimer) {
|
|
1571
|
+
clearTimeout(existingTimer);
|
|
1572
|
+
}
|
|
1573
|
+
const timer = setTimeout(() => {
|
|
1574
|
+
try {
|
|
1575
|
+
const newLines = fileTracker.readNewLines(filePath);
|
|
1576
|
+
if (newLines.length === 0) return;
|
|
1577
|
+
const content = newLines.join("\n");
|
|
1578
|
+
const sessionId = getSessionId(filePath);
|
|
1579
|
+
const pipeline = getPipeline(sessionId);
|
|
1580
|
+
pipeline.ingest(content, { sessionId, filePath });
|
|
1581
|
+
const stats = pipeline.getStats();
|
|
1582
|
+
if (stats.currentTokens >= realtime.autoOptimizeThreshold) {
|
|
1583
|
+
getMetrics().updateDaemon({
|
|
1584
|
+
sessionsWatched: pipelines.size,
|
|
1585
|
+
memoryUsage: process.memoryUsage().heapUsed
|
|
1586
|
+
});
|
|
1587
|
+
if (onOptimize) {
|
|
1588
|
+
const sessionStats = computeSessionStats(sessionId, pipeline);
|
|
1589
|
+
onOptimize(sessionId, sessionStats);
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
} catch (error) {
|
|
1593
|
+
if (onError) {
|
|
1594
|
+
onError(error instanceof Error ? error : new Error(String(error)));
|
|
1595
|
+
}
|
|
1596
|
+
} finally {
|
|
1597
|
+
debounceTimers.delete(filePath);
|
|
1598
|
+
}
|
|
1599
|
+
}, realtime.debounceMs);
|
|
1600
|
+
debounceTimers.set(filePath, timer);
|
|
1601
|
+
}
|
|
1602
|
+
function findJsonlFiles(dir) {
|
|
1603
|
+
const files = [];
|
|
1604
|
+
try {
|
|
1605
|
+
const entries = readdirSync(dir);
|
|
1606
|
+
for (const entry of entries) {
|
|
1607
|
+
const fullPath = join2(dir, entry);
|
|
1608
|
+
const stat = statSync2(fullPath);
|
|
1609
|
+
if (stat.isDirectory()) {
|
|
1610
|
+
files.push(...findJsonlFiles(fullPath));
|
|
1611
|
+
} else if (entry.endsWith(".jsonl")) {
|
|
1612
|
+
const matches = realtime.watchPatterns.some((pattern) => {
|
|
1613
|
+
const regex = new RegExp(
|
|
1614
|
+
pattern.replace(/\*\*/g, ".*").replace(/\*/g, "[^/\\\\]*").replace(/\./g, "\\.")
|
|
1615
|
+
);
|
|
1616
|
+
return regex.test(fullPath);
|
|
1617
|
+
});
|
|
1618
|
+
if (matches) {
|
|
1619
|
+
files.push(fullPath);
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
} catch (_error) {
|
|
1624
|
+
}
|
|
1625
|
+
return files;
|
|
1626
|
+
}
|
|
1627
|
+
function computeSessionStats(sessionId, pipeline) {
|
|
1628
|
+
const stats = pipeline.getStats();
|
|
1629
|
+
const entries = pipeline.getEntries();
|
|
1630
|
+
const totalTokens = entries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
|
|
1631
|
+
return {
|
|
1632
|
+
sessionId,
|
|
1633
|
+
totalTokens: stats.totalIngested,
|
|
1634
|
+
optimizedTokens: stats.currentTokens,
|
|
1635
|
+
reduction: totalTokens > 0 ? (totalTokens - stats.currentTokens) / totalTokens : 0,
|
|
1636
|
+
entryCount: stats.currentEntries,
|
|
1637
|
+
budgetUtilization: stats.budgetUtilization
|
|
1638
|
+
};
|
|
1639
|
+
}
|
|
1640
|
+
async function start() {
|
|
1641
|
+
const projectsDir = getProjectsDir();
|
|
1642
|
+
const jsonlFiles = findJsonlFiles(projectsDir);
|
|
1643
|
+
const watchedDirs = /* @__PURE__ */ new Set();
|
|
1644
|
+
for (const file of jsonlFiles) {
|
|
1645
|
+
const dir = dirname2(file);
|
|
1646
|
+
if (!watchedDirs.has(dir)) {
|
|
1647
|
+
const watcher = watch(dir, { recursive: false }, (_eventType, filename) => {
|
|
1648
|
+
if (filename?.endsWith(".jsonl")) {
|
|
1649
|
+
const fullPath = join2(dir, filename);
|
|
1650
|
+
handleFileChange(fullPath);
|
|
1651
|
+
}
|
|
1652
|
+
});
|
|
1653
|
+
watchers.push(watcher);
|
|
1654
|
+
watchedDirs.add(dir);
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
const projectsWatcher = watch(projectsDir, { recursive: true }, (_eventType, filename) => {
|
|
1658
|
+
if (filename?.endsWith(".jsonl")) {
|
|
1659
|
+
const fullPath = join2(projectsDir, filename);
|
|
1660
|
+
handleFileChange(fullPath);
|
|
1661
|
+
}
|
|
1662
|
+
});
|
|
1663
|
+
watchers.push(projectsWatcher);
|
|
1664
|
+
getMetrics().updateDaemon({
|
|
1665
|
+
startTime: Date.now(),
|
|
1666
|
+
sessionsWatched: jsonlFiles.length,
|
|
1667
|
+
memoryUsage: process.memoryUsage().heapUsed
|
|
1668
|
+
});
|
|
1669
|
+
}
|
|
1670
|
+
function stop() {
|
|
1671
|
+
for (const watcher of watchers) {
|
|
1672
|
+
watcher.close();
|
|
1673
|
+
}
|
|
1674
|
+
watchers.length = 0;
|
|
1675
|
+
for (const timer of debounceTimers.values()) {
|
|
1676
|
+
clearTimeout(timer);
|
|
1677
|
+
}
|
|
1678
|
+
debounceTimers.clear();
|
|
1679
|
+
pipelines.clear();
|
|
1680
|
+
fileTracker.clearAll();
|
|
1681
|
+
}
|
|
1682
|
+
function getStats() {
|
|
1683
|
+
const stats = [];
|
|
1684
|
+
for (const [sessionId, pipeline] of pipelines.entries()) {
|
|
1685
|
+
stats.push(computeSessionStats(sessionId, pipeline));
|
|
1686
|
+
}
|
|
1687
|
+
return stats;
|
|
1688
|
+
}
|
|
1689
|
+
function getSessionStats(sessionId) {
|
|
1690
|
+
const pipeline = pipelines.get(sessionId);
|
|
1691
|
+
if (!pipeline) return null;
|
|
1692
|
+
return computeSessionStats(sessionId, pipeline);
|
|
1693
|
+
}
|
|
1694
|
+
function optimizeSession(sessionId) {
|
|
1695
|
+
const pipeline = pipelines.get(sessionId);
|
|
1696
|
+
if (!pipeline) return;
|
|
1697
|
+
const entries = pipeline.getEntries();
|
|
1698
|
+
pipeline.clear();
|
|
1699
|
+
pipeline.ingest(entries.map((e) => e.content).join("\n\n"));
|
|
1700
|
+
if (onOptimize) {
|
|
1701
|
+
const stats = computeSessionStats(sessionId, pipeline);
|
|
1702
|
+
onOptimize(sessionId, stats);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
return {
|
|
1706
|
+
start,
|
|
1707
|
+
stop,
|
|
1708
|
+
getStats,
|
|
1709
|
+
getSessionStats,
|
|
1710
|
+
optimizeSession
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
|
|
844
1714
|
// src/types/config.ts
|
|
845
1715
|
var DEFAULT_CONFIG = {
|
|
846
1716
|
pruning: {
|
|
@@ -861,7 +1731,17 @@ var DEFAULT_CONFIG = {
|
|
|
861
1731
|
sounds: false,
|
|
862
1732
|
verbose: false
|
|
863
1733
|
},
|
|
864
|
-
autoConsolidate: null
|
|
1734
|
+
autoConsolidate: null,
|
|
1735
|
+
realtime: {
|
|
1736
|
+
tokenBudget: 5e4,
|
|
1737
|
+
autoOptimizeThreshold: 8e4,
|
|
1738
|
+
watchPatterns: ["**/*.jsonl"],
|
|
1739
|
+
pidFile: ".sparn/daemon.pid",
|
|
1740
|
+
logFile: ".sparn/daemon.log",
|
|
1741
|
+
debounceMs: 5e3,
|
|
1742
|
+
incremental: true,
|
|
1743
|
+
windowSize: 500
|
|
1744
|
+
}
|
|
865
1745
|
};
|
|
866
1746
|
|
|
867
1747
|
// src/utils/logger.ts
|
|
@@ -886,15 +1766,25 @@ function createLogger(verbose = false) {
|
|
|
886
1766
|
export {
|
|
887
1767
|
DEFAULT_CONFIG,
|
|
888
1768
|
createBTSPEmbedder,
|
|
1769
|
+
createBudgetPruner,
|
|
1770
|
+
createBudgetPrunerFromConfig,
|
|
889
1771
|
createClaudeCodeAdapter,
|
|
890
1772
|
createConfidenceStates,
|
|
1773
|
+
createContextPipeline,
|
|
1774
|
+
createDaemonCommand,
|
|
891
1775
|
createEngramScorer,
|
|
1776
|
+
createEntry,
|
|
1777
|
+
createFileTracker,
|
|
892
1778
|
createGenericAdapter,
|
|
1779
|
+
createIncrementalOptimizer,
|
|
893
1780
|
createKVMemory,
|
|
894
1781
|
createLogger,
|
|
1782
|
+
createSessionWatcher,
|
|
895
1783
|
createSleepCompressor,
|
|
896
1784
|
createSparsePruner,
|
|
897
1785
|
estimateTokens,
|
|
898
|
-
hashContent
|
|
1786
|
+
hashContent,
|
|
1787
|
+
parseClaudeCodeContext,
|
|
1788
|
+
parseGenericContext
|
|
899
1789
|
};
|
|
900
1790
|
//# sourceMappingURL=index.js.map
|