@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/dist/index.cjs CHANGED
@@ -32,22 +32,29 @@ var src_exports = {};
32
32
  __export(src_exports, {
33
33
  DEFAULT_CONFIG: () => DEFAULT_CONFIG,
34
34
  createBTSPEmbedder: () => createBTSPEmbedder,
35
+ createBudgetPruner: () => createBudgetPruner,
36
+ createBudgetPrunerFromConfig: () => createBudgetPrunerFromConfig,
35
37
  createClaudeCodeAdapter: () => createClaudeCodeAdapter,
36
38
  createConfidenceStates: () => createConfidenceStates,
39
+ createContextPipeline: () => createContextPipeline,
40
+ createDaemonCommand: () => createDaemonCommand,
37
41
  createEngramScorer: () => createEngramScorer,
42
+ createEntry: () => createEntry,
43
+ createFileTracker: () => createFileTracker,
38
44
  createGenericAdapter: () => createGenericAdapter,
45
+ createIncrementalOptimizer: () => createIncrementalOptimizer,
39
46
  createKVMemory: () => createKVMemory,
40
47
  createLogger: () => createLogger,
48
+ createSessionWatcher: () => createSessionWatcher,
41
49
  createSleepCompressor: () => createSleepCompressor,
42
50
  createSparsePruner: () => createSparsePruner,
43
51
  estimateTokens: () => estimateTokens,
44
- hashContent: () => hashContent
52
+ hashContent: () => hashContent,
53
+ parseClaudeCodeContext: () => parseClaudeCodeContext,
54
+ parseGenericContext: () => parseGenericContext
45
55
  });
46
56
  module.exports = __toCommonJS(src_exports);
47
57
 
48
- // src/adapters/claude-code.ts
49
- var import_node_crypto3 = require("crypto");
50
-
51
58
  // src/core/btsp-embedder.ts
52
59
  var import_node_crypto2 = require("crypto");
53
60
 
@@ -261,6 +268,82 @@ function createSparsePruner(config) {
261
268
  };
262
269
  }
263
270
 
271
+ // src/utils/context-parser.ts
272
+ var import_node_crypto3 = require("crypto");
273
+ function parseClaudeCodeContext(context) {
274
+ const entries = [];
275
+ const now = Date.now();
276
+ const lines = context.split("\n");
277
+ let currentBlock = [];
278
+ let blockType = "other";
279
+ for (const line of lines) {
280
+ const trimmed = line.trim();
281
+ if (trimmed.startsWith("User:") || trimmed.startsWith("Assistant:")) {
282
+ if (currentBlock.length > 0) {
283
+ entries.push(createEntry(currentBlock.join("\n"), blockType, now));
284
+ currentBlock = [];
285
+ }
286
+ blockType = "conversation";
287
+ currentBlock.push(line);
288
+ } else if (trimmed.includes("<function_calls>") || trimmed.includes("<invoke>") || trimmed.includes("<tool_use>")) {
289
+ if (currentBlock.length > 0) {
290
+ entries.push(createEntry(currentBlock.join("\n"), blockType, now));
291
+ currentBlock = [];
292
+ }
293
+ blockType = "tool";
294
+ currentBlock.push(line);
295
+ } else if (trimmed.includes("<function_results>") || trimmed.includes("</function_results>")) {
296
+ if (currentBlock.length > 0 && blockType !== "result") {
297
+ entries.push(createEntry(currentBlock.join("\n"), blockType, now));
298
+ currentBlock = [];
299
+ }
300
+ blockType = "result";
301
+ currentBlock.push(line);
302
+ } else if (currentBlock.length > 0) {
303
+ currentBlock.push(line);
304
+ } else if (trimmed.length > 0) {
305
+ currentBlock.push(line);
306
+ blockType = "other";
307
+ }
308
+ }
309
+ if (currentBlock.length > 0) {
310
+ entries.push(createEntry(currentBlock.join("\n"), blockType, now));
311
+ }
312
+ return entries.filter((e) => e.content.trim().length > 0);
313
+ }
314
+ function createEntry(content, type, baseTime) {
315
+ const tags = [type];
316
+ let initialScore = 0.5;
317
+ if (type === "conversation") initialScore = 0.8;
318
+ if (type === "tool") initialScore = 0.7;
319
+ if (type === "result") initialScore = 0.4;
320
+ return {
321
+ id: (0, import_node_crypto3.randomUUID)(),
322
+ content,
323
+ hash: hashContent(content),
324
+ timestamp: baseTime,
325
+ score: initialScore,
326
+ state: initialScore > 0.7 ? "active" : initialScore > 0.3 ? "ready" : "silent",
327
+ ttl: 24 * 3600,
328
+ // 24 hours default
329
+ accessCount: 0,
330
+ tags,
331
+ metadata: { type },
332
+ isBTSP: false
333
+ };
334
+ }
335
+ function parseGenericContext(context) {
336
+ const entries = [];
337
+ const now = Date.now();
338
+ const blocks = context.split(/\n\n+/);
339
+ for (const block of blocks) {
340
+ const trimmed = block.trim();
341
+ if (trimmed.length === 0) continue;
342
+ entries.push(createEntry(trimmed, "other", now));
343
+ }
344
+ return entries;
345
+ }
346
+
264
347
  // src/adapters/claude-code.ts
265
348
  var CLAUDE_CODE_PROFILE = {
266
349
  // More aggressive pruning for tool results (they can be verbose)
@@ -380,68 +463,6 @@ function createClaudeCodeAdapter(memory, config) {
380
463
  optimize
381
464
  };
382
465
  }
383
- function parseClaudeCodeContext(context) {
384
- const entries = [];
385
- const now = Date.now();
386
- const lines = context.split("\n");
387
- let currentBlock = [];
388
- let blockType = "other";
389
- for (const line of lines) {
390
- const trimmed = line.trim();
391
- if (trimmed.startsWith("User:") || trimmed.startsWith("Assistant:")) {
392
- if (currentBlock.length > 0) {
393
- entries.push(createEntry(currentBlock.join("\n"), blockType, now));
394
- currentBlock = [];
395
- }
396
- blockType = "conversation";
397
- currentBlock.push(line);
398
- } else if (trimmed.includes("<function_calls>") || trimmed.includes("<invoke>") || trimmed.includes("<tool_use>")) {
399
- if (currentBlock.length > 0) {
400
- entries.push(createEntry(currentBlock.join("\n"), blockType, now));
401
- currentBlock = [];
402
- }
403
- blockType = "tool";
404
- currentBlock.push(line);
405
- } else if (trimmed.includes("<function_results>") || trimmed.includes("</function_results>")) {
406
- if (currentBlock.length > 0 && blockType !== "result") {
407
- entries.push(createEntry(currentBlock.join("\n"), blockType, now));
408
- currentBlock = [];
409
- }
410
- blockType = "result";
411
- currentBlock.push(line);
412
- } else if (currentBlock.length > 0) {
413
- currentBlock.push(line);
414
- } else if (trimmed.length > 0) {
415
- currentBlock.push(line);
416
- blockType = "other";
417
- }
418
- }
419
- if (currentBlock.length > 0) {
420
- entries.push(createEntry(currentBlock.join("\n"), blockType, now));
421
- }
422
- return entries.filter((e) => e.content.trim().length > 0);
423
- }
424
- function createEntry(content, type, baseTime) {
425
- const tags = [type];
426
- let initialScore = 0.5;
427
- if (type === "conversation") initialScore = 0.8;
428
- if (type === "tool") initialScore = 0.7;
429
- if (type === "result") initialScore = 0.4;
430
- return {
431
- id: (0, import_node_crypto3.randomUUID)(),
432
- content,
433
- hash: hashContent(content),
434
- timestamp: baseTime,
435
- score: initialScore,
436
- state: initialScore > 0.7 ? "active" : initialScore > 0.3 ? "ready" : "silent",
437
- ttl: 24 * 3600,
438
- // 24 hours default
439
- accessCount: 0,
440
- tags,
441
- metadata: { type },
442
- isBTSP: false
443
- };
444
- }
445
466
 
446
467
  // src/adapters/generic.ts
447
468
  var import_node_crypto4 = require("crypto");
@@ -519,6 +540,459 @@ function createGenericAdapter(memory, config) {
519
540
  };
520
541
  }
521
542
 
543
+ // src/core/budget-pruner.ts
544
+ function createBudgetPruner(config) {
545
+ const { tokenBudget, decay } = config;
546
+ const engramScorer = createEngramScorer(decay);
547
+ function tokenize(text) {
548
+ return text.toLowerCase().split(/\s+/).filter((word) => word.length > 0);
549
+ }
550
+ function calculateTF(term, tokens) {
551
+ const count = tokens.filter((t) => t === term).length;
552
+ return Math.sqrt(count);
553
+ }
554
+ function calculateIDF(term, allEntries) {
555
+ const totalDocs = allEntries.length;
556
+ const docsWithTerm = allEntries.filter((entry) => {
557
+ const tokens = tokenize(entry.content);
558
+ return tokens.includes(term);
559
+ }).length;
560
+ if (docsWithTerm === 0) return 0;
561
+ return Math.log(totalDocs / docsWithTerm);
562
+ }
563
+ function calculateTFIDF(entry, allEntries) {
564
+ const tokens = tokenize(entry.content);
565
+ if (tokens.length === 0) return 0;
566
+ const uniqueTerms = [...new Set(tokens)];
567
+ let totalScore = 0;
568
+ for (const term of uniqueTerms) {
569
+ const tf = calculateTF(term, tokens);
570
+ const idf = calculateIDF(term, allEntries);
571
+ totalScore += tf * idf;
572
+ }
573
+ return totalScore / tokens.length;
574
+ }
575
+ function getStateMultiplier(entry) {
576
+ if (entry.isBTSP) return 2;
577
+ switch (entry.state) {
578
+ case "active":
579
+ return 2;
580
+ case "ready":
581
+ return 1;
582
+ case "silent":
583
+ return 0.5;
584
+ default:
585
+ return 1;
586
+ }
587
+ }
588
+ function priorityScore(entry, allEntries) {
589
+ const tfidf = calculateTFIDF(entry, allEntries);
590
+ const currentScore = engramScorer.calculateScore(entry);
591
+ const engramDecay = 1 - currentScore;
592
+ const stateMultiplier = getStateMultiplier(entry);
593
+ return tfidf * (1 - engramDecay) * stateMultiplier;
594
+ }
595
+ function pruneToFit(entries, budget = tokenBudget) {
596
+ if (entries.length === 0) {
597
+ return {
598
+ kept: [],
599
+ removed: [],
600
+ originalTokens: 0,
601
+ prunedTokens: 0,
602
+ budgetUtilization: 0
603
+ };
604
+ }
605
+ const originalTokens = entries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
606
+ const btspEntries = entries.filter((e) => e.isBTSP);
607
+ const regularEntries = entries.filter((e) => !e.isBTSP);
608
+ const btspTokens = btspEntries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
609
+ const scored = regularEntries.map((entry) => ({
610
+ entry,
611
+ score: priorityScore(entry, entries),
612
+ tokens: estimateTokens(entry.content)
613
+ }));
614
+ scored.sort((a, b) => b.score - a.score);
615
+ const kept = [...btspEntries];
616
+ const removed = [];
617
+ let currentTokens = btspTokens;
618
+ for (const item of scored) {
619
+ if (currentTokens + item.tokens <= budget) {
620
+ kept.push(item.entry);
621
+ currentTokens += item.tokens;
622
+ } else {
623
+ removed.push(item.entry);
624
+ }
625
+ }
626
+ const budgetUtilization = budget > 0 ? currentTokens / budget : 0;
627
+ return {
628
+ kept,
629
+ removed,
630
+ originalTokens,
631
+ prunedTokens: currentTokens,
632
+ budgetUtilization
633
+ };
634
+ }
635
+ return {
636
+ pruneToFit,
637
+ priorityScore
638
+ };
639
+ }
640
+ function createBudgetPrunerFromConfig(realtimeConfig, decayConfig, statesConfig) {
641
+ return createBudgetPruner({
642
+ tokenBudget: realtimeConfig.tokenBudget,
643
+ decay: decayConfig,
644
+ states: statesConfig
645
+ });
646
+ }
647
+
648
+ // src/core/metrics.ts
649
+ function createMetricsCollector() {
650
+ const optimizations = [];
651
+ let daemonMetrics = {
652
+ startTime: Date.now(),
653
+ sessionsWatched: 0,
654
+ totalOptimizations: 0,
655
+ totalTokensSaved: 0,
656
+ averageLatency: 0,
657
+ memoryUsage: 0
658
+ };
659
+ let cacheHits = 0;
660
+ let cacheMisses = 0;
661
+ function recordOptimization(metric) {
662
+ optimizations.push(metric);
663
+ daemonMetrics.totalOptimizations++;
664
+ daemonMetrics.totalTokensSaved += metric.tokensBefore - metric.tokensAfter;
665
+ if (metric.cacheHitRate > 0) {
666
+ const hits = Math.round(metric.entriesProcessed * metric.cacheHitRate);
667
+ cacheHits += hits;
668
+ cacheMisses += metric.entriesProcessed - hits;
669
+ }
670
+ daemonMetrics.averageLatency = (daemonMetrics.averageLatency * (daemonMetrics.totalOptimizations - 1) + metric.duration) / daemonMetrics.totalOptimizations;
671
+ if (optimizations.length > 1e3) {
672
+ optimizations.shift();
673
+ }
674
+ }
675
+ function updateDaemon(metric) {
676
+ daemonMetrics = {
677
+ ...daemonMetrics,
678
+ ...metric
679
+ };
680
+ }
681
+ function calculatePercentile(values, percentile) {
682
+ if (values.length === 0) return 0;
683
+ const sorted = [...values].sort((a, b) => a - b);
684
+ const index = Math.ceil(percentile / 100 * sorted.length) - 1;
685
+ return sorted[index] || 0;
686
+ }
687
+ function getSnapshot() {
688
+ const totalRuns = optimizations.length;
689
+ const totalDuration = optimizations.reduce((sum, m) => sum + m.duration, 0);
690
+ const totalTokensSaved = optimizations.reduce(
691
+ (sum, m) => sum + (m.tokensBefore - m.tokensAfter),
692
+ 0
693
+ );
694
+ const totalTokensBefore = optimizations.reduce((sum, m) => sum + m.tokensBefore, 0);
695
+ const averageReduction = totalTokensBefore > 0 ? totalTokensSaved / totalTokensBefore : 0;
696
+ const durations = optimizations.map((m) => m.duration);
697
+ const totalCacheQueries = cacheHits + cacheMisses;
698
+ const hitRate = totalCacheQueries > 0 ? cacheHits / totalCacheQueries : 0;
699
+ return {
700
+ timestamp: Date.now(),
701
+ optimization: {
702
+ totalRuns,
703
+ totalDuration,
704
+ totalTokensSaved,
705
+ averageReduction,
706
+ p50Latency: calculatePercentile(durations, 50),
707
+ p95Latency: calculatePercentile(durations, 95),
708
+ p99Latency: calculatePercentile(durations, 99)
709
+ },
710
+ cache: {
711
+ hitRate,
712
+ totalHits: cacheHits,
713
+ totalMisses: cacheMisses,
714
+ size: optimizations.reduce((sum, m) => sum + m.entriesKept, 0)
715
+ },
716
+ daemon: {
717
+ uptime: Date.now() - daemonMetrics.startTime,
718
+ sessionsWatched: daemonMetrics.sessionsWatched,
719
+ memoryUsage: daemonMetrics.memoryUsage
720
+ }
721
+ };
722
+ }
723
+ function exportMetrics() {
724
+ return JSON.stringify(getSnapshot(), null, 2);
725
+ }
726
+ function reset() {
727
+ optimizations.length = 0;
728
+ cacheHits = 0;
729
+ cacheMisses = 0;
730
+ daemonMetrics = {
731
+ startTime: Date.now(),
732
+ sessionsWatched: 0,
733
+ totalOptimizations: 0,
734
+ totalTokensSaved: 0,
735
+ averageLatency: 0,
736
+ memoryUsage: 0
737
+ };
738
+ }
739
+ return {
740
+ recordOptimization,
741
+ updateDaemon,
742
+ getSnapshot,
743
+ export: exportMetrics,
744
+ reset
745
+ };
746
+ }
747
+ var globalMetrics = null;
748
+ function getMetrics() {
749
+ if (!globalMetrics) {
750
+ globalMetrics = createMetricsCollector();
751
+ }
752
+ return globalMetrics;
753
+ }
754
+
755
+ // src/core/incremental-optimizer.ts
756
+ function createIncrementalOptimizer(config) {
757
+ const pruner = createBudgetPruner(config);
758
+ const { fullOptimizationInterval } = config;
759
+ let state = {
760
+ entryCache: /* @__PURE__ */ new Map(),
761
+ documentFrequency: /* @__PURE__ */ new Map(),
762
+ totalDocuments: 0,
763
+ updateCount: 0,
764
+ lastFullOptimization: Date.now()
765
+ };
766
+ function tokenize(text) {
767
+ return text.toLowerCase().split(/\s+/).filter((word) => word.length > 0);
768
+ }
769
+ function updateDocumentFrequency(entries, remove = false) {
770
+ for (const entry of entries) {
771
+ const tokens = tokenize(entry.content);
772
+ const uniqueTerms = [...new Set(tokens)];
773
+ for (const term of uniqueTerms) {
774
+ const current = state.documentFrequency.get(term) || 0;
775
+ const updated = remove ? Math.max(0, current - 1) : current + 1;
776
+ if (updated === 0) {
777
+ state.documentFrequency.delete(term);
778
+ } else {
779
+ state.documentFrequency.set(term, updated);
780
+ }
781
+ }
782
+ }
783
+ state.totalDocuments += remove ? -entries.length : entries.length;
784
+ state.totalDocuments = Math.max(0, state.totalDocuments);
785
+ }
786
+ function getCachedEntry(hash) {
787
+ const cached = state.entryCache.get(hash);
788
+ if (!cached) return null;
789
+ return cached.entry;
790
+ }
791
+ function cacheEntry(entry, score) {
792
+ state.entryCache.set(entry.hash, {
793
+ entry,
794
+ score,
795
+ timestamp: Date.now()
796
+ });
797
+ }
798
+ function optimizeIncremental(newEntries, budget) {
799
+ const startTime = Date.now();
800
+ state.updateCount++;
801
+ if (state.updateCount >= fullOptimizationInterval) {
802
+ const allEntries2 = Array.from(state.entryCache.values()).map((c) => c.entry);
803
+ return optimizeFull([...allEntries2, ...newEntries], budget);
804
+ }
805
+ const uncachedEntries = [];
806
+ const cachedEntries = [];
807
+ for (const entry of newEntries) {
808
+ const cached = getCachedEntry(entry.hash);
809
+ if (cached) {
810
+ cachedEntries.push(cached);
811
+ } else {
812
+ uncachedEntries.push(entry);
813
+ }
814
+ }
815
+ if (uncachedEntries.length > 0) {
816
+ updateDocumentFrequency(uncachedEntries, false);
817
+ }
818
+ const allEntries = [...cachedEntries, ...uncachedEntries];
819
+ for (const entry of uncachedEntries) {
820
+ const score = pruner.priorityScore(entry, allEntries);
821
+ cacheEntry(entry, score);
822
+ }
823
+ const currentEntries = Array.from(state.entryCache.values()).map((c) => c.entry);
824
+ const tokensBefore = currentEntries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
825
+ const result = pruner.pruneToFit(currentEntries, budget);
826
+ const tokensAfter = result.kept.reduce((sum, e) => sum + estimateTokens(e.content), 0);
827
+ for (const removed of result.removed) {
828
+ state.entryCache.delete(removed.hash);
829
+ }
830
+ if (result.removed.length > 0) {
831
+ updateDocumentFrequency(result.removed, true);
832
+ }
833
+ const duration = Date.now() - startTime;
834
+ const cacheHitRate = newEntries.length > 0 ? cachedEntries.length / newEntries.length : 0;
835
+ getMetrics().recordOptimization({
836
+ timestamp: Date.now(),
837
+ duration,
838
+ tokensBefore,
839
+ tokensAfter,
840
+ entriesProcessed: newEntries.length,
841
+ entriesKept: result.kept.length,
842
+ cacheHitRate,
843
+ memoryUsage: process.memoryUsage().heapUsed
844
+ });
845
+ return result;
846
+ }
847
+ function optimizeFull(allEntries, budget) {
848
+ const startTime = Date.now();
849
+ const tokensBefore = allEntries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
850
+ state.entryCache.clear();
851
+ state.documentFrequency.clear();
852
+ state.totalDocuments = 0;
853
+ state.updateCount = 0;
854
+ state.lastFullOptimization = Date.now();
855
+ updateDocumentFrequency(allEntries, false);
856
+ for (const entry of allEntries) {
857
+ const score = pruner.priorityScore(entry, allEntries);
858
+ cacheEntry(entry, score);
859
+ }
860
+ const result = pruner.pruneToFit(allEntries, budget);
861
+ const tokensAfter = result.kept.reduce((sum, e) => sum + estimateTokens(e.content), 0);
862
+ for (const removed of result.removed) {
863
+ state.entryCache.delete(removed.hash);
864
+ }
865
+ if (result.removed.length > 0) {
866
+ updateDocumentFrequency(result.removed, true);
867
+ }
868
+ const duration = Date.now() - startTime;
869
+ getMetrics().recordOptimization({
870
+ timestamp: Date.now(),
871
+ duration,
872
+ tokensBefore,
873
+ tokensAfter,
874
+ entriesProcessed: allEntries.length,
875
+ entriesKept: result.kept.length,
876
+ cacheHitRate: 0,
877
+ // Full optimization has no cache hits
878
+ memoryUsage: process.memoryUsage().heapUsed
879
+ });
880
+ return result;
881
+ }
882
+ function getState() {
883
+ return {
884
+ entryCache: new Map(state.entryCache),
885
+ documentFrequency: new Map(state.documentFrequency),
886
+ totalDocuments: state.totalDocuments,
887
+ updateCount: state.updateCount,
888
+ lastFullOptimization: state.lastFullOptimization
889
+ };
890
+ }
891
+ function restoreState(restoredState) {
892
+ state = {
893
+ entryCache: new Map(restoredState.entryCache),
894
+ documentFrequency: new Map(restoredState.documentFrequency),
895
+ totalDocuments: restoredState.totalDocuments,
896
+ updateCount: restoredState.updateCount,
897
+ lastFullOptimization: restoredState.lastFullOptimization
898
+ };
899
+ }
900
+ function reset() {
901
+ state = {
902
+ entryCache: /* @__PURE__ */ new Map(),
903
+ documentFrequency: /* @__PURE__ */ new Map(),
904
+ totalDocuments: 0,
905
+ updateCount: 0,
906
+ lastFullOptimization: Date.now()
907
+ };
908
+ }
909
+ function getStats() {
910
+ return {
911
+ cachedEntries: state.entryCache.size,
912
+ uniqueTerms: state.documentFrequency.size,
913
+ totalDocuments: state.totalDocuments,
914
+ updateCount: state.updateCount,
915
+ lastFullOptimization: state.lastFullOptimization
916
+ };
917
+ }
918
+ return {
919
+ optimizeIncremental,
920
+ optimizeFull,
921
+ getState,
922
+ restoreState,
923
+ reset,
924
+ getStats
925
+ };
926
+ }
927
+
928
+ // src/core/context-pipeline.ts
929
+ function createContextPipeline(config) {
930
+ const optimizer = createIncrementalOptimizer(config);
931
+ const { windowSize, tokenBudget } = config;
932
+ let totalIngested = 0;
933
+ let evictedEntries = 0;
934
+ let currentEntries = [];
935
+ let budgetUtilization = 0;
936
+ function ingest(content, metadata = {}) {
937
+ const newEntries = parseClaudeCodeContext(content);
938
+ if (newEntries.length === 0) return 0;
939
+ const entriesWithMetadata = newEntries.map((entry) => ({
940
+ ...entry,
941
+ metadata: { ...entry.metadata, ...metadata }
942
+ }));
943
+ const result = optimizer.optimizeIncremental(entriesWithMetadata, tokenBudget);
944
+ totalIngested += newEntries.length;
945
+ evictedEntries += result.removed.length;
946
+ currentEntries = result.kept;
947
+ budgetUtilization = result.budgetUtilization;
948
+ if (currentEntries.length > windowSize) {
949
+ const sorted = [...currentEntries].sort((a, b) => b.timestamp - a.timestamp);
950
+ const toKeep = sorted.slice(0, windowSize);
951
+ const toRemove = sorted.slice(windowSize);
952
+ currentEntries = toKeep;
953
+ evictedEntries += toRemove.length;
954
+ }
955
+ return newEntries.length;
956
+ }
957
+ function getContext() {
958
+ const sorted = [...currentEntries].sort((a, b) => a.timestamp - b.timestamp);
959
+ return sorted.map((e) => e.content).join("\n\n");
960
+ }
961
+ function getEntries() {
962
+ return [...currentEntries].sort((a, b) => a.timestamp - b.timestamp);
963
+ }
964
+ function getStats() {
965
+ const optimizerStats = optimizer.getStats();
966
+ const currentTokens = currentEntries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
967
+ return {
968
+ totalIngested,
969
+ currentEntries: currentEntries.length,
970
+ currentTokens,
971
+ budgetUtilization,
972
+ evictedEntries,
973
+ optimizer: {
974
+ cachedEntries: optimizerStats.cachedEntries,
975
+ uniqueTerms: optimizerStats.uniqueTerms,
976
+ updateCount: optimizerStats.updateCount
977
+ }
978
+ };
979
+ }
980
+ function clear() {
981
+ totalIngested = 0;
982
+ evictedEntries = 0;
983
+ currentEntries = [];
984
+ budgetUtilization = 0;
985
+ optimizer.reset();
986
+ }
987
+ return {
988
+ ingest,
989
+ getContext,
990
+ getEntries,
991
+ getStats,
992
+ clear
993
+ };
994
+ }
995
+
522
996
  // src/core/kv-memory.ts
523
997
  var import_node_fs = require("fs");
524
998
  var import_better_sqlite3 = __toESM(require("better-sqlite3"), 1);
@@ -888,6 +1362,405 @@ function createSleepCompressor() {
888
1362
  };
889
1363
  }
890
1364
 
1365
+ // src/daemon/daemon-process.ts
1366
+ var import_node_child_process = require("child_process");
1367
+ var import_node_fs2 = require("fs");
1368
+ var import_node_path = require("path");
1369
+ function createDaemonCommand() {
1370
+ function isDaemonRunning(pidFile) {
1371
+ if (!(0, import_node_fs2.existsSync)(pidFile)) {
1372
+ return { running: false };
1373
+ }
1374
+ try {
1375
+ const pidStr = (0, import_node_fs2.readFileSync)(pidFile, "utf-8").trim();
1376
+ const pid = Number.parseInt(pidStr, 10);
1377
+ if (Number.isNaN(pid)) {
1378
+ return { running: false };
1379
+ }
1380
+ try {
1381
+ process.kill(pid, 0);
1382
+ return { running: true, pid };
1383
+ } catch {
1384
+ (0, import_node_fs2.unlinkSync)(pidFile);
1385
+ return { running: false };
1386
+ }
1387
+ } catch {
1388
+ return { running: false };
1389
+ }
1390
+ }
1391
+ function writePidFile(pidFile, pid) {
1392
+ const dir = (0, import_node_path.dirname)(pidFile);
1393
+ if (!(0, import_node_fs2.existsSync)(dir)) {
1394
+ (0, import_node_fs2.mkdirSync)(dir, { recursive: true });
1395
+ }
1396
+ (0, import_node_fs2.writeFileSync)(pidFile, String(pid), "utf-8");
1397
+ }
1398
+ function removePidFile(pidFile) {
1399
+ if ((0, import_node_fs2.existsSync)(pidFile)) {
1400
+ (0, import_node_fs2.unlinkSync)(pidFile);
1401
+ }
1402
+ }
1403
+ async function start(config) {
1404
+ const { pidFile, logFile } = config.realtime;
1405
+ const status2 = isDaemonRunning(pidFile);
1406
+ if (status2.running) {
1407
+ return {
1408
+ success: false,
1409
+ pid: status2.pid,
1410
+ message: `Daemon already running (PID ${status2.pid})`,
1411
+ error: "Already running"
1412
+ };
1413
+ }
1414
+ try {
1415
+ const daemonPath = (0, import_node_path.join)(__dirname, "index.js");
1416
+ const child = (0, import_node_child_process.fork)(daemonPath, [], {
1417
+ detached: true,
1418
+ stdio: "ignore",
1419
+ env: {
1420
+ ...process.env,
1421
+ SPARN_CONFIG: JSON.stringify(config),
1422
+ SPARN_PID_FILE: pidFile,
1423
+ SPARN_LOG_FILE: logFile
1424
+ }
1425
+ });
1426
+ child.unref();
1427
+ if (child.pid) {
1428
+ writePidFile(pidFile, child.pid);
1429
+ return {
1430
+ success: true,
1431
+ pid: child.pid,
1432
+ message: `Daemon started (PID ${child.pid})`
1433
+ };
1434
+ }
1435
+ return {
1436
+ success: false,
1437
+ message: "Failed to start daemon (no PID)",
1438
+ error: "No PID"
1439
+ };
1440
+ } catch (error) {
1441
+ return {
1442
+ success: false,
1443
+ message: "Failed to start daemon",
1444
+ error: error instanceof Error ? error.message : String(error)
1445
+ };
1446
+ }
1447
+ }
1448
+ async function stop(config) {
1449
+ const { pidFile } = config.realtime;
1450
+ const status2 = isDaemonRunning(pidFile);
1451
+ if (!status2.running || !status2.pid) {
1452
+ return {
1453
+ success: true,
1454
+ message: "Daemon not running"
1455
+ };
1456
+ }
1457
+ try {
1458
+ process.kill(status2.pid, "SIGTERM");
1459
+ const maxWait = 5e3;
1460
+ const interval = 100;
1461
+ let waited = 0;
1462
+ while (waited < maxWait) {
1463
+ try {
1464
+ process.kill(status2.pid, 0);
1465
+ await new Promise((resolve) => setTimeout(resolve, interval));
1466
+ waited += interval;
1467
+ } catch {
1468
+ removePidFile(pidFile);
1469
+ return {
1470
+ success: true,
1471
+ message: `Daemon stopped (PID ${status2.pid})`
1472
+ };
1473
+ }
1474
+ }
1475
+ try {
1476
+ process.kill(status2.pid, "SIGKILL");
1477
+ removePidFile(pidFile);
1478
+ return {
1479
+ success: true,
1480
+ message: `Daemon force killed (PID ${status2.pid})`
1481
+ };
1482
+ } catch {
1483
+ removePidFile(pidFile);
1484
+ return {
1485
+ success: true,
1486
+ message: `Daemon stopped (PID ${status2.pid})`
1487
+ };
1488
+ }
1489
+ } catch (error) {
1490
+ return {
1491
+ success: false,
1492
+ message: "Failed to stop daemon",
1493
+ error: error instanceof Error ? error.message : String(error)
1494
+ };
1495
+ }
1496
+ }
1497
+ async function status(config) {
1498
+ const { pidFile } = config.realtime;
1499
+ const daemonStatus = isDaemonRunning(pidFile);
1500
+ if (!daemonStatus.running || !daemonStatus.pid) {
1501
+ return {
1502
+ running: false,
1503
+ message: "Daemon not running"
1504
+ };
1505
+ }
1506
+ const metrics = getMetrics().getSnapshot();
1507
+ return {
1508
+ running: true,
1509
+ pid: daemonStatus.pid,
1510
+ uptime: metrics.daemon.uptime,
1511
+ sessionsWatched: metrics.daemon.sessionsWatched,
1512
+ tokensSaved: metrics.optimization.totalTokensSaved,
1513
+ message: `Daemon running (PID ${daemonStatus.pid})`
1514
+ };
1515
+ }
1516
+ return {
1517
+ start,
1518
+ stop,
1519
+ status
1520
+ };
1521
+ }
1522
+
1523
+ // src/daemon/file-tracker.ts
1524
+ var import_node_fs3 = require("fs");
1525
+ function createFileTracker() {
1526
+ const positions = /* @__PURE__ */ new Map();
1527
+ function readNewLines(filePath) {
1528
+ try {
1529
+ const stats = (0, import_node_fs3.statSync)(filePath);
1530
+ const currentSize = stats.size;
1531
+ const currentModified = stats.mtimeMs;
1532
+ let pos = positions.get(filePath);
1533
+ if (!pos) {
1534
+ pos = {
1535
+ path: filePath,
1536
+ position: 0,
1537
+ partialLine: "",
1538
+ lastModified: currentModified,
1539
+ lastSize: 0
1540
+ };
1541
+ positions.set(filePath, pos);
1542
+ }
1543
+ if (currentSize < pos.lastSize || currentSize === pos.position) {
1544
+ if (currentSize < pos.lastSize) {
1545
+ pos.position = 0;
1546
+ pos.partialLine = "";
1547
+ }
1548
+ return [];
1549
+ }
1550
+ const buffer = Buffer.alloc(currentSize - pos.position);
1551
+ const fd = (0, import_node_fs3.readFileSync)(filePath);
1552
+ fd.copy(buffer, 0, pos.position, currentSize);
1553
+ const newContent = (pos.partialLine + buffer.toString("utf-8")).split("\n");
1554
+ const partialLine = newContent.pop() || "";
1555
+ pos.position = currentSize;
1556
+ pos.partialLine = partialLine;
1557
+ pos.lastModified = currentModified;
1558
+ pos.lastSize = currentSize;
1559
+ return newContent.filter((line) => line.trim().length > 0);
1560
+ } catch (_error) {
1561
+ return [];
1562
+ }
1563
+ }
1564
+ function getPosition(filePath) {
1565
+ return positions.get(filePath) || null;
1566
+ }
1567
+ function resetPosition(filePath) {
1568
+ positions.delete(filePath);
1569
+ }
1570
+ function clearAll() {
1571
+ positions.clear();
1572
+ }
1573
+ function getTrackedFiles() {
1574
+ return Array.from(positions.keys());
1575
+ }
1576
+ return {
1577
+ readNewLines,
1578
+ getPosition,
1579
+ resetPosition,
1580
+ clearAll,
1581
+ getTrackedFiles
1582
+ };
1583
+ }
1584
+
1585
+ // src/daemon/session-watcher.ts
1586
+ var import_node_fs4 = require("fs");
1587
+ var import_node_os = require("os");
1588
+ var import_node_path2 = require("path");
1589
+ function createSessionWatcher(config) {
1590
+ const { config: sparnConfig, onOptimize, onError } = config;
1591
+ const { realtime, decay, states } = sparnConfig;
1592
+ const pipelines = /* @__PURE__ */ new Map();
1593
+ const fileTracker = createFileTracker();
1594
+ const watchers = [];
1595
+ const debounceTimers = /* @__PURE__ */ new Map();
1596
+ function getProjectsDir() {
1597
+ return (0, import_node_path2.join)((0, import_node_os.homedir)(), ".claude", "projects");
1598
+ }
1599
+ function getSessionId(filePath) {
1600
+ const filename = filePath.split(/[/\\]/).pop() || "";
1601
+ return filename.replace(/\.jsonl$/, "");
1602
+ }
1603
+ function getPipeline(sessionId) {
1604
+ let pipeline = pipelines.get(sessionId);
1605
+ if (!pipeline) {
1606
+ pipeline = createContextPipeline({
1607
+ tokenBudget: realtime.tokenBudget,
1608
+ decay,
1609
+ states,
1610
+ windowSize: realtime.windowSize,
1611
+ fullOptimizationInterval: 50
1612
+ // Full re-optimization every 50 incremental updates
1613
+ });
1614
+ pipelines.set(sessionId, pipeline);
1615
+ }
1616
+ return pipeline;
1617
+ }
1618
+ function handleFileChange(filePath) {
1619
+ const existingTimer = debounceTimers.get(filePath);
1620
+ if (existingTimer) {
1621
+ clearTimeout(existingTimer);
1622
+ }
1623
+ const timer = setTimeout(() => {
1624
+ try {
1625
+ const newLines = fileTracker.readNewLines(filePath);
1626
+ if (newLines.length === 0) return;
1627
+ const content = newLines.join("\n");
1628
+ const sessionId = getSessionId(filePath);
1629
+ const pipeline = getPipeline(sessionId);
1630
+ pipeline.ingest(content, { sessionId, filePath });
1631
+ const stats = pipeline.getStats();
1632
+ if (stats.currentTokens >= realtime.autoOptimizeThreshold) {
1633
+ getMetrics().updateDaemon({
1634
+ sessionsWatched: pipelines.size,
1635
+ memoryUsage: process.memoryUsage().heapUsed
1636
+ });
1637
+ if (onOptimize) {
1638
+ const sessionStats = computeSessionStats(sessionId, pipeline);
1639
+ onOptimize(sessionId, sessionStats);
1640
+ }
1641
+ }
1642
+ } catch (error) {
1643
+ if (onError) {
1644
+ onError(error instanceof Error ? error : new Error(String(error)));
1645
+ }
1646
+ } finally {
1647
+ debounceTimers.delete(filePath);
1648
+ }
1649
+ }, realtime.debounceMs);
1650
+ debounceTimers.set(filePath, timer);
1651
+ }
1652
+ function findJsonlFiles(dir) {
1653
+ const files = [];
1654
+ try {
1655
+ const entries = (0, import_node_fs4.readdirSync)(dir);
1656
+ for (const entry of entries) {
1657
+ const fullPath = (0, import_node_path2.join)(dir, entry);
1658
+ const stat = (0, import_node_fs4.statSync)(fullPath);
1659
+ if (stat.isDirectory()) {
1660
+ files.push(...findJsonlFiles(fullPath));
1661
+ } else if (entry.endsWith(".jsonl")) {
1662
+ const matches = realtime.watchPatterns.some((pattern) => {
1663
+ const regex = new RegExp(
1664
+ pattern.replace(/\*\*/g, ".*").replace(/\*/g, "[^/\\\\]*").replace(/\./g, "\\.")
1665
+ );
1666
+ return regex.test(fullPath);
1667
+ });
1668
+ if (matches) {
1669
+ files.push(fullPath);
1670
+ }
1671
+ }
1672
+ }
1673
+ } catch (_error) {
1674
+ }
1675
+ return files;
1676
+ }
1677
+ function computeSessionStats(sessionId, pipeline) {
1678
+ const stats = pipeline.getStats();
1679
+ const entries = pipeline.getEntries();
1680
+ const totalTokens = entries.reduce((sum, e) => sum + estimateTokens(e.content), 0);
1681
+ return {
1682
+ sessionId,
1683
+ totalTokens: stats.totalIngested,
1684
+ optimizedTokens: stats.currentTokens,
1685
+ reduction: totalTokens > 0 ? (totalTokens - stats.currentTokens) / totalTokens : 0,
1686
+ entryCount: stats.currentEntries,
1687
+ budgetUtilization: stats.budgetUtilization
1688
+ };
1689
+ }
1690
+ async function start() {
1691
+ const projectsDir = getProjectsDir();
1692
+ const jsonlFiles = findJsonlFiles(projectsDir);
1693
+ const watchedDirs = /* @__PURE__ */ new Set();
1694
+ for (const file of jsonlFiles) {
1695
+ const dir = (0, import_node_path2.dirname)(file);
1696
+ if (!watchedDirs.has(dir)) {
1697
+ const watcher = (0, import_node_fs4.watch)(dir, { recursive: false }, (_eventType, filename) => {
1698
+ if (filename?.endsWith(".jsonl")) {
1699
+ const fullPath = (0, import_node_path2.join)(dir, filename);
1700
+ handleFileChange(fullPath);
1701
+ }
1702
+ });
1703
+ watchers.push(watcher);
1704
+ watchedDirs.add(dir);
1705
+ }
1706
+ }
1707
+ const projectsWatcher = (0, import_node_fs4.watch)(projectsDir, { recursive: true }, (_eventType, filename) => {
1708
+ if (filename?.endsWith(".jsonl")) {
1709
+ const fullPath = (0, import_node_path2.join)(projectsDir, filename);
1710
+ handleFileChange(fullPath);
1711
+ }
1712
+ });
1713
+ watchers.push(projectsWatcher);
1714
+ getMetrics().updateDaemon({
1715
+ startTime: Date.now(),
1716
+ sessionsWatched: jsonlFiles.length,
1717
+ memoryUsage: process.memoryUsage().heapUsed
1718
+ });
1719
+ }
1720
+ function stop() {
1721
+ for (const watcher of watchers) {
1722
+ watcher.close();
1723
+ }
1724
+ watchers.length = 0;
1725
+ for (const timer of debounceTimers.values()) {
1726
+ clearTimeout(timer);
1727
+ }
1728
+ debounceTimers.clear();
1729
+ pipelines.clear();
1730
+ fileTracker.clearAll();
1731
+ }
1732
+ function getStats() {
1733
+ const stats = [];
1734
+ for (const [sessionId, pipeline] of pipelines.entries()) {
1735
+ stats.push(computeSessionStats(sessionId, pipeline));
1736
+ }
1737
+ return stats;
1738
+ }
1739
+ function getSessionStats(sessionId) {
1740
+ const pipeline = pipelines.get(sessionId);
1741
+ if (!pipeline) return null;
1742
+ return computeSessionStats(sessionId, pipeline);
1743
+ }
1744
+ function optimizeSession(sessionId) {
1745
+ const pipeline = pipelines.get(sessionId);
1746
+ if (!pipeline) return;
1747
+ const entries = pipeline.getEntries();
1748
+ pipeline.clear();
1749
+ pipeline.ingest(entries.map((e) => e.content).join("\n\n"));
1750
+ if (onOptimize) {
1751
+ const stats = computeSessionStats(sessionId, pipeline);
1752
+ onOptimize(sessionId, stats);
1753
+ }
1754
+ }
1755
+ return {
1756
+ start,
1757
+ stop,
1758
+ getStats,
1759
+ getSessionStats,
1760
+ optimizeSession
1761
+ };
1762
+ }
1763
+
891
1764
  // src/types/config.ts
892
1765
  var DEFAULT_CONFIG = {
893
1766
  pruning: {
@@ -908,7 +1781,17 @@ var DEFAULT_CONFIG = {
908
1781
  sounds: false,
909
1782
  verbose: false
910
1783
  },
911
- autoConsolidate: null
1784
+ autoConsolidate: null,
1785
+ realtime: {
1786
+ tokenBudget: 5e4,
1787
+ autoOptimizeThreshold: 8e4,
1788
+ watchPatterns: ["**/*.jsonl"],
1789
+ pidFile: ".sparn/daemon.pid",
1790
+ logFile: ".sparn/daemon.log",
1791
+ debounceMs: 5e3,
1792
+ incremental: true,
1793
+ windowSize: 500
1794
+ }
912
1795
  };
913
1796
 
914
1797
  // src/utils/logger.ts
@@ -934,15 +1817,25 @@ function createLogger(verbose = false) {
934
1817
  0 && (module.exports = {
935
1818
  DEFAULT_CONFIG,
936
1819
  createBTSPEmbedder,
1820
+ createBudgetPruner,
1821
+ createBudgetPrunerFromConfig,
937
1822
  createClaudeCodeAdapter,
938
1823
  createConfidenceStates,
1824
+ createContextPipeline,
1825
+ createDaemonCommand,
939
1826
  createEngramScorer,
1827
+ createEntry,
1828
+ createFileTracker,
940
1829
  createGenericAdapter,
1830
+ createIncrementalOptimizer,
941
1831
  createKVMemory,
942
1832
  createLogger,
1833
+ createSessionWatcher,
943
1834
  createSleepCompressor,
944
1835
  createSparsePruner,
945
1836
  estimateTokens,
946
- hashContent
1837
+ hashContent,
1838
+ parseClaudeCodeContext,
1839
+ parseGenericContext
947
1840
  });
948
1841
  //# sourceMappingURL=index.cjs.map