@ulrichc1/sparn 1.2.1 → 1.2.2
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 +1 -1
- package/dist/cli/index.cjs +2 -2
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +2 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/hooks/post-tool-result.cjs +66 -11
- package/dist/hooks/post-tool-result.cjs.map +1 -1
- package/dist/hooks/post-tool-result.js +66 -11
- package/dist/hooks/post-tool-result.js.map +1 -1
- package/dist/hooks/pre-prompt.cjs +38 -3
- package/dist/hooks/pre-prompt.cjs.map +1 -1
- package/dist/hooks/pre-prompt.js +39 -4
- package/dist/hooks/pre-prompt.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/mcp/index.cjs +2 -2
- package/dist/mcp/index.cjs.map +1 -1
- package/dist/mcp/index.js +2 -2
- package/dist/mcp/index.js.map +1 -1
- package/package.json +1 -1
package/dist/mcp/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/mcp/index.ts","../../src/core/kv-memory.ts","../../src/mcp/server.ts","../../src/adapters/generic.ts","../../src/core/btsp-embedder.ts","../../src/utils/hash.ts","../../src/core/confidence-states.ts","../../src/core/engram-scorer.ts","../../src/utils/tokenizer.ts","../../src/core/sparse-pruner.ts","../../src/core/sleep-compressor.ts","../../src/types/config.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * Sparn MCP Server Entry Point\n *\n * Starts the Sparn MCP server using stdio transport.\n * This is the main entry point for MCP client integrations\n * (Claude Desktop, VS Code, etc.).\n *\n * Usage:\n * node dist/mcp/index.js\n * node dist/mcp/index.cjs\n *\n * Environment variables:\n * SPARN_DB_PATH - Custom path for the SQLite database (default: .sparn/memory.db)\n */\n\nimport { mkdirSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { createKVMemory } from '../core/kv-memory.js';\nimport { createSparnMcpServer } from './server.js';\n\nasync function main(): Promise<void> {\n const dbPath = resolve(process.env['SPARN_DB_PATH'] ?? '.sparn/memory.db');\n\n // Ensure the database directory exists\n mkdirSync(dirname(dbPath), { recursive: true });\n\n const memory = await createKVMemory(dbPath);\n\n const server = createSparnMcpServer({ memory });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n\n // Log to stderr (stdout is reserved for MCP JSON-RPC messages)\n console.error('Sparn MCP server running on stdio');\n\n // Graceful shutdown\n const shutdown = async () => {\n console.error('Shutting down Sparn MCP server...');\n await server.close();\n await memory.close();\n process.exit(0);\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n}\n\nmain().catch((error) => {\n console.error('Fatal error in Sparn MCP server:', error);\n process.exit(1);\n});\n","/**\n * KV Memory Store Module\n * Implements hippocampal key-value storage with dual index/value tables.\n * Maps to: Hippocampal Key-Value — the hippocampus separates what to store from how to retrieve it.\n */\n\nimport { copyFileSync, existsSync } from 'node:fs';\nimport Database from 'better-sqlite3';\nimport type { MemoryEntry, MemoryQueryFilters } from '../types/memory.js';\n\n/**\n * Optimization statistics record.\n */\nexport interface OptimizationStats {\n id: number;\n timestamp: number;\n tokens_before: number;\n tokens_after: number;\n entries_pruned: number;\n duration_ms: number;\n}\n\n/**\n * KV Memory interface.\n */\nexport interface KVMemory {\n /** Store a memory entry */\n put(entry: MemoryEntry): Promise<void>;\n\n /** Retrieve a memory entry by ID */\n get(id: string): Promise<MemoryEntry | null>;\n\n /** Query entries by filters */\n query(filters: MemoryQueryFilters): Promise<MemoryEntry[]>;\n\n /** Delete a memory entry */\n delete(id: string): Promise<void>;\n\n /** List all entry IDs */\n list(): Promise<string[]>;\n\n /** Compact database (remove expired entries) */\n compact(): Promise<number>;\n\n /** Close database connection */\n close(): Promise<void>;\n\n /** Record optimization statistics */\n recordOptimization(stats: Omit<OptimizationStats, 'id'>): Promise<void>;\n\n /** Get all optimization statistics */\n getOptimizationStats(): Promise<OptimizationStats[]>;\n\n /** Clear all optimization statistics */\n clearOptimizationStats(): Promise<void>;\n}\n\n/**\n * Create a timestamped backup of the database\n * @param dbPath - Path to database file\n * @returns Path to backup file\n */\nfunction createBackup(dbPath: string): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n const backupPath = `${dbPath}.backup-${timestamp}`;\n\n try {\n copyFileSync(dbPath, backupPath);\n console.log(`✓ Database backed up to: ${backupPath}`);\n return backupPath;\n } catch (error) {\n console.error(`Warning: Could not create backup: ${error}`);\n return '';\n }\n}\n\n/**\n * Create KV Memory store with SQLite backend.\n *\n * Initializes database with dual table schema:\n * - entries_index: Fast lookups (id, hash, timestamp, score, ttl, state, accessCount, isBTSP)\n * - entries_value: Content storage (id, content, tags, metadata)\n *\n * @param dbPath - Path to SQLite database file\n * @returns KVMemory instance\n */\nexport async function createKVMemory(dbPath: string): Promise<KVMemory> {\n // Detect database corruption and create backup\n let db: Database.Database;\n try {\n db = new Database(dbPath);\n\n // Quick integrity check\n const integrityCheck = db.pragma('quick_check', { simple: true });\n if (integrityCheck !== 'ok') {\n console.error('⚠ Database corruption detected!');\n\n // Create backup before attempting recovery\n if (existsSync(dbPath)) {\n const backupPath = createBackup(dbPath);\n if (backupPath) {\n console.log(`Backup created at: ${backupPath}`);\n }\n }\n\n // Try to recover\n console.log('Attempting database recovery...');\n db.close();\n db = new Database(dbPath);\n }\n } catch (error) {\n console.error('⚠ Database error detected:', error);\n\n // Create backup if database exists\n if (existsSync(dbPath)) {\n createBackup(dbPath);\n console.log('Creating new database...');\n }\n\n db = new Database(dbPath);\n }\n\n // Enable WAL mode for better concurrency\n db.pragma('journal_mode = WAL');\n\n // Create entries_index table\n db.exec(`\n CREATE TABLE IF NOT EXISTS entries_index (\n id TEXT PRIMARY KEY NOT NULL,\n hash TEXT UNIQUE NOT NULL,\n timestamp INTEGER NOT NULL,\n score REAL NOT NULL DEFAULT 0.0 CHECK(score >= 0.0 AND score <= 1.0),\n ttl INTEGER NOT NULL CHECK(ttl >= 0),\n state TEXT NOT NULL CHECK(state IN ('silent', 'ready', 'active')),\n accessCount INTEGER NOT NULL DEFAULT 0 CHECK(accessCount >= 0),\n isBTSP INTEGER NOT NULL DEFAULT 0 CHECK(isBTSP IN (0, 1)),\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))\n );\n `);\n\n // Create entries_value table\n db.exec(`\n CREATE TABLE IF NOT EXISTS entries_value (\n id TEXT PRIMARY KEY NOT NULL,\n content TEXT NOT NULL,\n tags TEXT,\n metadata TEXT,\n FOREIGN KEY (id) REFERENCES entries_index(id) ON DELETE CASCADE\n );\n `);\n\n // Create optimization_stats table\n db.exec(`\n CREATE TABLE IF NOT EXISTS optimization_stats (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n timestamp INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n tokens_before INTEGER NOT NULL,\n tokens_after INTEGER NOT NULL,\n entries_pruned INTEGER NOT NULL,\n duration_ms INTEGER NOT NULL\n );\n `);\n\n // Create indexes\n db.exec(`\n CREATE INDEX IF NOT EXISTS idx_entries_state ON entries_index(state);\n CREATE INDEX IF NOT EXISTS idx_entries_score ON entries_index(score DESC);\n CREATE INDEX IF NOT EXISTS idx_entries_hash ON entries_index(hash);\n CREATE INDEX IF NOT EXISTS idx_entries_timestamp ON entries_index(timestamp DESC);\n CREATE INDEX IF NOT EXISTS idx_stats_timestamp ON optimization_stats(timestamp DESC);\n `);\n\n // Prepare statements for better performance\n const putIndexStmt = db.prepare(`\n INSERT OR REPLACE INTO entries_index\n (id, hash, timestamp, score, ttl, state, accessCount, isBTSP)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const putValueStmt = db.prepare(`\n INSERT OR REPLACE INTO entries_value\n (id, content, tags, metadata)\n VALUES (?, ?, ?, ?)\n `);\n\n const getStmt = db.prepare(`\n SELECT\n i.id, i.hash, i.timestamp, i.score, i.ttl, i.state, i.accessCount, i.isBTSP,\n v.content, v.tags, v.metadata\n FROM entries_index i\n JOIN entries_value v ON i.id = v.id\n WHERE i.id = ?\n `);\n\n const deleteIndexStmt = db.prepare('DELETE FROM entries_index WHERE id = ?');\n const deleteValueStmt = db.prepare('DELETE FROM entries_value WHERE id = ?');\n\n return {\n async put(entry: MemoryEntry): Promise<void> {\n const transaction = db.transaction(() => {\n putIndexStmt.run(\n entry.id,\n entry.hash,\n entry.timestamp,\n entry.score,\n entry.ttl,\n entry.state,\n entry.accessCount,\n entry.isBTSP ? 1 : 0,\n );\n\n putValueStmt.run(\n entry.id,\n entry.content,\n JSON.stringify(entry.tags),\n JSON.stringify(entry.metadata),\n );\n });\n\n transaction();\n },\n\n async get(id: string): Promise<MemoryEntry | null> {\n const row = getStmt.get(id) as unknown;\n\n if (!row) {\n return null;\n }\n\n const r = row as {\n id: string;\n hash: string;\n timestamp: number;\n score: number;\n ttl: number;\n state: string;\n accessCount: number;\n isBTSP: number;\n content: string;\n tags: string | null;\n metadata: string | null;\n };\n\n return {\n id: r.id,\n content: r.content,\n hash: r.hash,\n timestamp: r.timestamp,\n score: r.score,\n ttl: r.ttl,\n state: r.state as 'silent' | 'ready' | 'active',\n accessCount: r.accessCount,\n tags: r.tags ? JSON.parse(r.tags) : [],\n metadata: r.metadata ? JSON.parse(r.metadata) : {},\n isBTSP: r.isBTSP === 1,\n };\n },\n\n async query(filters: MemoryQueryFilters): Promise<MemoryEntry[]> {\n let sql = `\n SELECT\n i.id, i.hash, i.timestamp, i.score, i.ttl, i.state, i.accessCount, i.isBTSP,\n v.content, v.tags, v.metadata\n FROM entries_index i\n JOIN entries_value v ON i.id = v.id\n WHERE 1=1\n `;\n\n const params: unknown[] = [];\n\n if (filters.state) {\n sql += ' AND i.state = ?';\n params.push(filters.state);\n }\n\n if (filters.minScore !== undefined) {\n sql += ' AND i.score >= ?';\n params.push(filters.minScore);\n }\n\n if (filters.maxScore !== undefined) {\n sql += ' AND i.score <= ?';\n params.push(filters.maxScore);\n }\n\n if (filters.isBTSP !== undefined) {\n sql += ' AND i.isBTSP = ?';\n params.push(filters.isBTSP ? 1 : 0);\n }\n\n sql += ' ORDER BY i.score DESC';\n\n if (filters.limit) {\n sql += ' LIMIT ?';\n params.push(filters.limit);\n }\n\n if (filters.offset) {\n sql += ' OFFSET ?';\n params.push(filters.offset);\n }\n\n const stmt = db.prepare(sql);\n const rows = stmt.all(...params) as unknown[];\n\n return rows.map((row) => {\n const r = row as {\n id: string;\n hash: string;\n timestamp: number;\n score: number;\n ttl: number;\n state: string;\n accessCount: number;\n isBTSP: number;\n content: string;\n tags: string | null;\n metadata: string | null;\n };\n\n return {\n id: r.id,\n content: r.content,\n hash: r.hash,\n timestamp: r.timestamp,\n score: r.score,\n ttl: r.ttl,\n state: r.state as 'silent' | 'ready' | 'active',\n accessCount: r.accessCount,\n tags: r.tags ? JSON.parse(r.tags) : [],\n metadata: r.metadata ? JSON.parse(r.metadata) : {},\n isBTSP: r.isBTSP === 1,\n };\n });\n },\n\n async delete(id: string): Promise<void> {\n const transaction = db.transaction(() => {\n deleteIndexStmt.run(id);\n deleteValueStmt.run(id);\n });\n\n transaction();\n },\n\n async list(): Promise<string[]> {\n const stmt = db.prepare('SELECT id FROM entries_index');\n const rows = stmt.all() as { id: string }[];\n return rows.map((r) => r.id);\n },\n\n async compact(): Promise<number> {\n const before = db.prepare('SELECT COUNT(*) as count FROM entries_index').get() as {\n count: number;\n };\n\n // Remove fully decayed entries (this will be enhanced in sleep-compressor)\n db.exec('DELETE FROM entries_index WHERE ttl <= 0');\n\n db.exec('VACUUM');\n\n const after = db.prepare('SELECT COUNT(*) as count FROM entries_index').get() as {\n count: number;\n };\n\n return before.count - after.count;\n },\n\n async close(): Promise<void> {\n db.close();\n },\n\n async recordOptimization(stats: Omit<OptimizationStats, 'id'>): Promise<void> {\n const stmt = db.prepare(`\n INSERT INTO optimization_stats (timestamp, tokens_before, tokens_after, entries_pruned, duration_ms)\n VALUES (?, ?, ?, ?, ?)\n `);\n\n stmt.run(\n stats.timestamp,\n stats.tokens_before,\n stats.tokens_after,\n stats.entries_pruned,\n stats.duration_ms,\n );\n },\n\n async getOptimizationStats(): Promise<OptimizationStats[]> {\n const stmt = db.prepare(`\n SELECT id, timestamp, tokens_before, tokens_after, entries_pruned, duration_ms\n FROM optimization_stats\n ORDER BY timestamp DESC\n `);\n\n const rows = stmt.all() as OptimizationStats[];\n return rows;\n },\n\n async clearOptimizationStats(): Promise<void> {\n db.exec('DELETE FROM optimization_stats');\n },\n };\n}\n","/**\n * Sparn MCP Server - Model Context Protocol server implementation\n *\n * Exposes Sparn's neuroscience-inspired context optimization as MCP tools,\n * enabling integration with Claude Desktop, VS Code, and other MCP clients.\n *\n * Tools:\n * - sparn_optimize: Optimize context with configurable options\n * - sparn_stats: Get optimization statistics\n * - sparn_consolidate: Run memory consolidation (sleep replay)\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { createGenericAdapter } from '../adapters/generic.js';\nimport type { KVMemory } from '../core/kv-memory.js';\nimport { createSleepCompressor } from '../core/sleep-compressor.js';\nimport type { SparnConfig } from '../types/config.js';\nimport { DEFAULT_CONFIG } from '../types/config.js';\n\n/**\n * Options for creating the Sparn MCP server.\n */\nexport interface SparnMcpServerOptions {\n /** KV memory store instance */\n memory: KVMemory;\n /** Sparn configuration (defaults to DEFAULT_CONFIG) */\n config?: SparnConfig;\n}\n\n/**\n * Create and configure the Sparn MCP server with all tools registered.\n *\n * @param options - Server options including memory store and config\n * @returns Configured McpServer instance ready to connect to a transport\n */\nexport function createSparnMcpServer(options: SparnMcpServerOptions): McpServer {\n const { memory, config = DEFAULT_CONFIG } = options;\n\n const server = new McpServer({\n name: 'sparn',\n version: '1.1.1',\n });\n\n registerOptimizeTool(server, memory, config);\n registerStatsTool(server, memory);\n registerConsolidateTool(server, memory);\n\n return server;\n}\n\n/**\n * Register the sparn_optimize tool.\n *\n * Optimizes input context using the neuroscience-inspired pipeline:\n * BTSP detection, engram scoring, confidence states, and sparse pruning.\n */\nfunction registerOptimizeTool(server: McpServer, memory: KVMemory, config: SparnConfig): void {\n server.registerTool(\n 'sparn_optimize',\n {\n title: 'Sparn Optimize',\n description:\n 'Optimize context using neuroscience-inspired pruning. ' +\n 'Applies BTSP detection, engram scoring, confidence states, ' +\n 'and sparse pruning to reduce token usage while preserving important information.',\n inputSchema: {\n context: z.string().describe('The context text to optimize'),\n dryRun: z\n .boolean()\n .optional()\n .default(false)\n .describe('If true, do not persist changes to the memory store'),\n verbose: z\n .boolean()\n .optional()\n .default(false)\n .describe('If true, include per-entry details in the response'),\n threshold: z\n .number()\n .min(0)\n .max(100)\n .optional()\n .describe('Custom pruning threshold (1-100, overrides config)'),\n },\n },\n async ({ context, dryRun, verbose, threshold }) => {\n try {\n const effectiveConfig = threshold\n ? { ...config, pruning: { ...config.pruning, threshold } }\n : config;\n\n const adapter = createGenericAdapter(memory, effectiveConfig);\n const result = await adapter.optimize(context, {\n dryRun,\n verbose,\n threshold,\n });\n\n const response = {\n optimizedContext: result.optimizedContext,\n tokensBefore: result.tokensBefore,\n tokensAfter: result.tokensAfter,\n reduction: `${(result.reduction * 100).toFixed(1)}%`,\n entriesProcessed: result.entriesProcessed,\n entriesKept: result.entriesKept,\n durationMs: result.durationMs,\n stateDistribution: result.stateDistribution,\n ...(verbose && result.details ? { details: result.details } : {}),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(response, null, 2),\n },\n ],\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true,\n };\n }\n },\n );\n}\n\n/**\n * Register the sparn_stats tool.\n *\n * Returns optimization statistics from the memory store, including\n * total commands run, tokens saved, and average reduction.\n */\nfunction registerStatsTool(server: McpServer, memory: KVMemory): void {\n server.registerTool(\n 'sparn_stats',\n {\n title: 'Sparn Stats',\n description:\n 'Get optimization statistics including total commands run, ' +\n 'tokens saved, and average reduction percentage.',\n inputSchema: {\n reset: z\n .boolean()\n .optional()\n .default(false)\n .describe('If true, reset all optimization statistics'),\n },\n },\n async ({ reset }) => {\n try {\n if (reset) {\n await memory.clearOptimizationStats();\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n {\n message: 'Optimization statistics have been reset.',\n totalCommands: 0,\n totalTokensSaved: 0,\n averageReduction: '0.0%',\n },\n null,\n 2,\n ),\n },\n ],\n };\n }\n\n const stats = await memory.getOptimizationStats();\n const totalCommands = stats.length;\n\n const totalTokensSaved = stats.reduce(\n (sum, s) => sum + (s.tokens_before - s.tokens_after),\n 0,\n );\n\n const averageReduction =\n totalCommands > 0\n ? stats.reduce((sum, s) => {\n const reduction =\n s.tokens_before > 0 ? (s.tokens_before - s.tokens_after) / s.tokens_before : 0;\n return sum + reduction;\n }, 0) / totalCommands\n : 0;\n\n const recentOptimizations = stats.slice(0, 10).map((s) => ({\n timestamp: new Date(s.timestamp).toISOString(),\n tokensBefore: s.tokens_before,\n tokensAfter: s.tokens_after,\n entriesPruned: s.entries_pruned,\n durationMs: s.duration_ms,\n reduction: `${(\n ((s.tokens_before - s.tokens_after) / Math.max(s.tokens_before, 1)) * 100\n ).toFixed(1)}%`,\n }));\n\n const response = {\n totalCommands,\n totalTokensSaved,\n averageReduction: `${(averageReduction * 100).toFixed(1)}%`,\n recentOptimizations,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(response, null, 2),\n },\n ],\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true,\n };\n }\n },\n );\n}\n\n/**\n * Register the sparn_consolidate tool.\n *\n * Runs the sleep-compressor consolidation process, which removes\n * decayed entries and merges duplicates in the memory store.\n */\nfunction registerConsolidateTool(server: McpServer, memory: KVMemory): void {\n server.registerTool(\n 'sparn_consolidate',\n {\n title: 'Sparn Consolidate',\n description:\n 'Run memory consolidation (sleep replay). ' +\n 'Removes decayed entries and merges duplicates to reclaim space. ' +\n 'Inspired by the neuroscience principle of sleep-based memory consolidation.',\n },\n async () => {\n try {\n const allIds = await memory.list();\n const allEntries = await Promise.all(\n allIds.map(async (id) => {\n const entry = await memory.get(id);\n return entry;\n }),\n );\n\n const entries = allEntries.filter((e) => e !== null);\n\n const compressor = createSleepCompressor();\n const result = compressor.consolidate(entries);\n\n // Apply changes to memory store\n for (const removed of result.removed) {\n await memory.delete(removed.id);\n }\n\n for (const kept of result.kept) {\n await memory.put(kept);\n }\n\n // Run VACUUM to reclaim disk space\n await memory.compact();\n\n const response = {\n entriesBefore: result.entriesBefore,\n entriesAfter: result.entriesAfter,\n decayedRemoved: result.decayedRemoved,\n duplicatesRemoved: result.duplicatesRemoved,\n compressionRatio: `${(result.compressionRatio * 100).toFixed(1)}%`,\n durationMs: result.durationMs,\n vacuumCompleted: true,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(response, null, 2),\n },\n ],\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true,\n };\n }\n },\n );\n}\n","/**\n * Generic Adapter - Agent-agnostic optimization pipeline\n *\n * Orchestrates all 6 neuroscience modules to optimize context memory.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { createBTSPEmbedder } from '../core/btsp-embedder.js';\nimport { createConfidenceStates } from '../core/confidence-states.js';\nimport { createEngramScorer } from '../core/engram-scorer.js';\nimport type { KVMemory } from '../core/kv-memory.js';\nimport { createSparsePruner } from '../core/sparse-pruner.js';\nimport type { AgentAdapter, OptimizationResult, OptimizeOptions } from '../types/adapter.js';\nimport type { SparnConfig } from '../types/config.js';\nimport type { MemoryEntry } from '../types/memory.js';\nimport { hashContent } from '../utils/hash.js';\nimport { estimateTokens } from '../utils/tokenizer.js';\n\n/**\n * Create a generic adapter instance\n * @param memory - KV memory store\n * @param config - Sparn configuration\n * @returns AgentAdapter instance\n */\nexport function createGenericAdapter(memory: KVMemory, config: SparnConfig): AgentAdapter {\n const pruner = createSparsePruner(config.pruning);\n const scorer = createEngramScorer(config.decay);\n const states = createConfidenceStates(config.states);\n const btsp = createBTSPEmbedder();\n\n async function optimize(\n context: string,\n options: OptimizeOptions = {},\n ): Promise<OptimizationResult> {\n const startTime = Date.now();\n\n // Parse context into entries (line-based for simplicity)\n const lines = context.split('\\n').filter((line) => line.trim().length > 0);\n const entries: MemoryEntry[] = lines.map((content) => ({\n id: randomUUID(),\n content,\n hash: hashContent(content),\n timestamp: Date.now(),\n score: btsp.detectBTSP(content) ? 1.0 : 0.5, // BTSP gets high initial score\n ttl: config.decay.defaultTTL * 3600, // Convert hours to seconds\n state: 'ready' as const,\n accessCount: 0,\n tags: [],\n metadata: {},\n isBTSP: btsp.detectBTSP(content),\n }));\n\n // Calculate original token count\n const tokensBefore = entries.reduce((sum, e) => sum + estimateTokens(e.content), 0);\n\n // Step 1: Update scores with decay\n const scoredEntries = entries.map((entry) => ({\n ...entry,\n score: scorer.calculateScore(entry),\n }));\n\n // Step 2: Transition states based on scores\n const statedEntries = scoredEntries.map((entry) => states.transition(entry));\n\n // Step 3: Apply sparse pruning\n const pruneResult = pruner.prune(statedEntries);\n\n // Step 4: Keep active and ready entries, discard silent\n const optimizedEntries = pruneResult.kept.filter(\n (e) => e.state === 'active' || e.state === 'ready',\n );\n\n // Calculate final token count\n const tokensAfter = optimizedEntries.reduce((sum, e) => sum + estimateTokens(e.content), 0);\n\n // Reconstruct optimized context\n const optimizedContext = optimizedEntries.map((e) => e.content).join('\\n');\n\n // Store entries in memory (if not dry run)\n if (!options.dryRun) {\n for (const entry of optimizedEntries) {\n await memory.put(entry);\n }\n\n // Record optimization statistics\n await memory.recordOptimization({\n timestamp: Date.now(),\n tokens_before: tokensBefore,\n tokens_after: tokensAfter,\n entries_pruned: entries.length - optimizedEntries.length,\n duration_ms: Date.now() - startTime,\n });\n }\n\n // Get state distribution\n const distribution = states.getDistribution(optimizedEntries);\n\n const result: OptimizationResult = {\n optimizedContext,\n tokensBefore,\n tokensAfter,\n reduction: tokensBefore > 0 ? (tokensBefore - tokensAfter) / tokensBefore : 0,\n entriesProcessed: entries.length,\n entriesKept: optimizedEntries.length,\n stateDistribution: distribution,\n durationMs: Date.now() - startTime,\n };\n\n // Add verbose details if requested\n if (options.verbose) {\n result.details = optimizedEntries.map((e) => ({\n id: e.id,\n score: e.score,\n state: e.state,\n isBTSP: e.isBTSP,\n tokens: estimateTokens(e.content),\n }));\n }\n\n return result;\n }\n\n return {\n optimize,\n };\n}\n","/**\n * BTSP Embedder - Implements behavioral timescale synaptic plasticity\n *\n * Neuroscience: One-shot learning from critical events (errors, conflicts).\n * Application: Detect high-importance patterns and mark for permanent retention.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { MemoryEntry } from '../types/memory.js';\nimport { hashContent } from '../utils/hash.js';\n\nexport interface BTSPEmbedder {\n /**\n * Detect if content contains BTSP patterns (errors, stack traces, conflicts, git diffs)\n * @param content - Content to analyze\n * @returns True if BTSP pattern detected\n */\n detectBTSP(content: string): boolean;\n\n /**\n * Create a new memory entry marked as BTSP (one-shot learned)\n * @param content - Entry content\n * @param tags - Optional tags\n * @param metadata - Optional metadata\n * @returns BTSP-marked memory entry\n */\n createBTSPEntry(\n content: string,\n tags?: string[],\n metadata?: Record<string, unknown>,\n ): MemoryEntry;\n}\n\n/**\n * Create a BTSP embedder instance\n * @returns BTSPEmbedder instance\n */\nexport function createBTSPEmbedder(): BTSPEmbedder {\n // Patterns that indicate critical events\n const BTSP_PATTERNS = [\n // Error patterns\n /\\b(error|exception|failure|fatal|critical|panic)\\b/i,\n /\\b(TypeError|ReferenceError|SyntaxError|RangeError|URIError)\\b/,\n /\\bENOENT|EACCES|ECONNREFUSED|ETIMEDOUT\\b/,\n\n // Stack trace patterns\n /^\\s+at\\s+.*\\(.*:\\d+:\\d+\\)/m, // JavaScript stack trace\n /^\\s+at\\s+.*\\.[a-zA-Z]+:\\d+/m, // Python/Ruby stack trace\n\n // Git diff new files\n /^new file mode \\d+$/m,\n /^--- \\/dev\\/null$/m,\n\n // Merge conflict markers\n /^<<<<<<< /m,\n /^=======/m,\n /^>>>>>>> /m,\n ];\n\n function detectBTSP(content: string): boolean {\n return BTSP_PATTERNS.some((pattern) => pattern.test(content));\n }\n\n function createBTSPEntry(\n content: string,\n tags: string[] = [],\n metadata: Record<string, unknown> = {},\n ): MemoryEntry {\n return {\n id: randomUUID(),\n content,\n hash: hashContent(content),\n timestamp: Date.now(),\n score: 1.0, // Maximum initial score\n ttl: 365 * 24 * 3600, // 1 year in seconds (long retention)\n state: 'active', // Always active\n accessCount: 0,\n tags: [...tags, 'btsp'],\n metadata,\n isBTSP: true,\n };\n }\n\n return {\n detectBTSP,\n createBTSPEntry,\n };\n}\n","/**\n * Content hashing utilities.\n * Uses SHA-256 for deduplication.\n */\n\nimport { createHash } from 'node:crypto';\n\n/**\n * Generate SHA-256 hash of content for deduplication.\n *\n * @param content - Content to hash\n * @returns 64-character hex string (SHA-256)\n *\n * @example\n * ```typescript\n * const hash = hashContent('Hello world');\n * console.log(hash.length); // 64\n * ```\n */\nexport function hashContent(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n","/**\n * Confidence States - Implements multi-state synapses\n *\n * Neuroscience: Synapses exist in three states: silent, ready (potentiated), active.\n * Application: Classify memory entries by score into silent/ready/active states.\n */\n\nimport type { ConfidenceState, MemoryEntry, StateDistribution } from '../types/memory.js';\n\nexport interface ConfidenceStatesConfig {\n /** Score threshold for active state (e.g., 0.7) */\n activeThreshold: number;\n /** Score threshold for ready state (e.g., 0.3) */\n readyThreshold: number;\n}\n\nexport interface ConfidenceStates {\n /**\n * Calculate state based on entry score and BTSP flag\n * @param entry - Memory entry\n * @returns Confidence state\n */\n calculateState(entry: MemoryEntry): ConfidenceState;\n\n /**\n * Transition entry to correct state based on its score\n * @param entry - Entry to transition\n * @returns Entry with updated state\n */\n transition(entry: MemoryEntry): MemoryEntry;\n\n /**\n * Get distribution of states across all entries\n * @param entries - All memory entries\n * @returns State distribution with counts\n */\n getDistribution(entries: MemoryEntry[]): StateDistribution;\n}\n\n/**\n * Create a confidence states manager\n * @param config - States configuration\n * @returns ConfidenceStates instance\n */\nexport function createConfidenceStates(config: ConfidenceStatesConfig): ConfidenceStates {\n const { activeThreshold, readyThreshold } = config;\n\n function calculateState(entry: MemoryEntry): ConfidenceState {\n // BTSP entries are always active\n if (entry.isBTSP) {\n return 'active';\n }\n\n // State based on score thresholds\n // Active: score > 0.7\n if (entry.score > activeThreshold) {\n return 'active';\n }\n\n // Ready: 0.3 <= score <= 0.7\n if (entry.score >= readyThreshold) {\n return 'ready';\n }\n\n // Silent: score < 0.3\n return 'silent';\n }\n\n function transition(entry: MemoryEntry): MemoryEntry {\n const newState = calculateState(entry);\n\n return {\n ...entry,\n state: newState,\n };\n }\n\n function getDistribution(entries: MemoryEntry[]): StateDistribution {\n const distribution: StateDistribution = {\n silent: 0,\n ready: 0,\n active: 0,\n total: entries.length,\n };\n\n for (const entry of entries) {\n const state = calculateState(entry);\n distribution[state]++;\n }\n\n return distribution;\n }\n\n return {\n calculateState,\n transition,\n getDistribution,\n };\n}\n","/**\n * Engram Scorer - Implements engram theory (memory decay)\n *\n * Neuroscience: Memories fade over time without reinforcement.\n * Application: Apply exponential decay formula to memory scores based on age and access count.\n *\n * Formula: decay = 1 - e^(-age/TTL)\n * Score adjustment: score_new = score_old * (1 - decay) + (accessCount bonus)\n */\n\nimport type { MemoryEntry } from '../types/memory.js';\n\nexport interface EngramScorerConfig {\n /** Default TTL in hours for new entries */\n defaultTTL: number;\n /** Decay threshold (0.0-1.0) above which entries are marked for pruning */\n decayThreshold: number;\n}\n\nexport interface EngramScorer {\n /**\n * Calculate current score for an entry based on decay and access count\n * @param entry - Memory entry to score\n * @param currentTime - Current timestamp in milliseconds (for testing)\n * @returns Updated score (0.0-1.0)\n */\n calculateScore(entry: MemoryEntry, currentTime?: number): number;\n\n /**\n * Refresh TTL to default value\n * @param entry - Entry to refresh\n * @returns Entry with refreshed TTL and timestamp\n */\n refreshTTL(entry: MemoryEntry): MemoryEntry;\n\n /**\n * Calculate decay factor (0.0-1.0) based on age and TTL\n * @param ageInSeconds - Age of entry in seconds\n * @param ttlInSeconds - TTL in seconds\n * @returns Decay factor (0.0 = fresh, 1.0 = fully decayed)\n */\n calculateDecay(ageInSeconds: number, ttlInSeconds: number): number;\n}\n\n/**\n * Create an engram scorer instance\n * @param config - Scorer configuration\n * @returns EngramScorer instance\n */\nexport function createEngramScorer(config: EngramScorerConfig): EngramScorer {\n const { defaultTTL } = config;\n\n function calculateDecay(ageInSeconds: number, ttlInSeconds: number): number {\n if (ttlInSeconds === 0) return 1.0; // Instant decay\n if (ageInSeconds <= 0) return 0.0; // Fresh entry\n\n // Exponential decay: 1 - e^(-age/TTL)\n const ratio = ageInSeconds / ttlInSeconds;\n const decay = 1 - Math.exp(-ratio);\n\n // Clamp to [0.0, 1.0]\n return Math.max(0, Math.min(1, decay));\n }\n\n function calculateScore(entry: MemoryEntry, currentTime: number = Date.now()): number {\n // Calculate age in seconds\n const ageInMilliseconds = currentTime - entry.timestamp;\n const ageInSeconds = Math.max(0, ageInMilliseconds / 1000);\n\n // Calculate decay factor\n const decay = calculateDecay(ageInSeconds, entry.ttl);\n\n // Base score reduced by decay\n let score = entry.score * (1 - decay);\n\n // Access count bonus (diminishing returns via log)\n if (entry.accessCount > 0) {\n const accessBonus = Math.log(entry.accessCount + 1) * 0.1;\n score = Math.min(1.0, score + accessBonus);\n }\n\n // BTSP entries maintain high score\n if (entry.isBTSP) {\n score = Math.max(score, 0.9);\n }\n\n return Math.max(0, Math.min(1, score));\n }\n\n function refreshTTL(entry: MemoryEntry): MemoryEntry {\n return {\n ...entry,\n ttl: defaultTTL * 3600, // Convert hours to seconds\n timestamp: Date.now(),\n };\n }\n\n return {\n calculateScore,\n refreshTTL,\n calculateDecay,\n };\n}\n","/**\n * Token estimation utilities.\n * Uses whitespace heuristic (~90% accuracy vs GPT tokenizer).\n */\n\n/**\n * Estimate token count for text using heuristic.\n *\n * Approximation: 1 token ≈ 4 chars or 0.75 words\n * Provides ~90% accuracy compared to GPT tokenizer, sufficient for optimization heuristics.\n *\n * @param text - Text to count\n * @returns Estimated token count\n *\n * @example\n * ```typescript\n * const tokens = estimateTokens('Hello world');\n * console.log(tokens); // ~2\n * ```\n */\nexport function estimateTokens(text: string): number {\n if (!text || text.length === 0) {\n return 0;\n }\n\n // Split on whitespace to get words\n const words = text.split(/\\s+/).filter((w) => w.length > 0);\n const wordCount = words.length;\n\n // Character-based estimate\n const charCount = text.length;\n const charEstimate = Math.ceil(charCount / 4);\n\n // Word-based estimate\n const wordEstimate = Math.ceil(wordCount * 0.75);\n\n // Return the maximum of both estimates (more conservative)\n return Math.max(wordEstimate, charEstimate);\n}\n","/**\n * Sparse Pruner - Implements sparse coding principle\n *\n * Neuroscience: Only 2-5% of neurons fire at any given time.\n * Application: Keep only top 5% most relevant context entries by TF-IDF score.\n */\n\nimport type { MemoryEntry } from '../types/memory.js';\nimport type { PruneResult } from '../types/pruner.js';\nimport { estimateTokens } from '../utils/tokenizer.js';\n\nexport interface SparsePrunerConfig {\n /** Percentage threshold for pruning (e.g., 5 = keep top 5%) */\n threshold: number;\n}\n\nexport interface SparsePruner {\n /**\n * Prune entries to keep only top N% by relevance score\n * @param entries - Memory entries to prune\n * @returns Result with kept/removed entries and token counts\n */\n prune(entries: MemoryEntry[]): PruneResult;\n\n /**\n * Calculate TF-IDF relevance score for a single entry\n * @param entry - Entry to score\n * @param allEntries - All entries for IDF calculation\n * @returns Relevance score (0.0-1.0)\n */\n scoreEntry(entry: MemoryEntry, allEntries: MemoryEntry[]): number;\n}\n\n/**\n * Create a sparse pruner instance\n * @param config - Pruner configuration\n * @returns SparsePruner instance\n */\nexport function createSparsePruner(config: SparsePrunerConfig): SparsePruner {\n const { threshold } = config;\n\n function tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/\\s+/)\n .filter((word) => word.length > 0);\n }\n\n function calculateTF(term: string, tokens: string[]): number {\n const count = tokens.filter((t) => t === term).length;\n // Sqrt capping to prevent common words from dominating\n return Math.sqrt(count);\n }\n\n function calculateIDF(term: string, allEntries: MemoryEntry[]): number {\n const totalDocs = allEntries.length;\n const docsWithTerm = allEntries.filter((entry) => {\n const tokens = tokenize(entry.content);\n return tokens.includes(term);\n }).length;\n\n if (docsWithTerm === 0) return 0;\n\n return Math.log(totalDocs / docsWithTerm);\n }\n\n function scoreEntry(entry: MemoryEntry, allEntries: MemoryEntry[]): number {\n const tokens = tokenize(entry.content);\n if (tokens.length === 0) return 0;\n\n const uniqueTerms = [...new Set(tokens)];\n let totalScore = 0;\n\n for (const term of uniqueTerms) {\n const tf = calculateTF(term, tokens);\n const idf = calculateIDF(term, allEntries);\n totalScore += tf * idf;\n }\n\n // Normalize by entry length\n return totalScore / tokens.length;\n }\n\n function prune(entries: MemoryEntry[]): PruneResult {\n if (entries.length === 0) {\n return {\n kept: [],\n removed: [],\n originalTokens: 0,\n prunedTokens: 0,\n };\n }\n\n // Calculate original token count\n const originalTokens = entries.reduce((sum, e) => sum + estimateTokens(e.content), 0);\n\n // Score all entries\n const scored = entries.map((entry) => ({\n entry,\n score: scoreEntry(entry, entries),\n }));\n\n // Sort by score descending\n scored.sort((a, b) => b.score - a.score);\n\n // Keep top N% (minimum 1 entry)\n const keepCount = Math.max(1, Math.ceil(entries.length * (threshold / 100)));\n const kept = scored.slice(0, keepCount).map((s) => s.entry);\n const removed = scored.slice(keepCount).map((s) => s.entry);\n\n // Calculate pruned token count\n const prunedTokens = kept.reduce((sum, e) => sum + estimateTokens(e.content), 0);\n\n return {\n kept,\n removed,\n originalTokens,\n prunedTokens,\n };\n }\n\n return {\n prune,\n scoreEntry,\n };\n}\n","/**\n * Sleep Compressor - Implements sleep replay principle\n *\n * Neuroscience: During sleep, the brain consolidates memories by replaying important ones\n * and discarding irrelevant information.\n * Application: Periodic consolidation removes decayed entries and merges duplicates.\n */\n\nimport type { ConsolidateResult, DuplicateGroup } from '../types/consolidate.js';\nimport type { MemoryEntry } from '../types/memory.js';\nimport { createEngramScorer } from './engram-scorer.js';\n\nexport interface SleepCompressor {\n /**\n * Consolidate entries: remove decayed, merge duplicates\n * @param entries - All memory entries\n * @returns Consolidation result\n */\n consolidate(entries: MemoryEntry[]): ConsolidateResult;\n\n /**\n * Find duplicate entries (exact hash or near-duplicate by similarity)\n * @param entries - Memory entries\n * @returns Groups of duplicates\n */\n findDuplicates(entries: MemoryEntry[]): DuplicateGroup[];\n\n /**\n * Merge duplicate entries, keeping highest score\n * @param groups - Duplicate groups\n * @returns Merged entries\n */\n mergeDuplicates(groups: DuplicateGroup[]): MemoryEntry[];\n}\n\n/**\n * Create a sleep compressor instance\n * @returns SleepCompressor instance\n */\nexport function createSleepCompressor(): SleepCompressor {\n const scorer = createEngramScorer({ defaultTTL: 24, decayThreshold: 0.95 });\n\n function consolidate(entries: MemoryEntry[]): ConsolidateResult {\n const startTime = Date.now();\n const originalCount = entries.length;\n\n // Step 1: Remove fully decayed entries (decay ≥ 0.95)\n const now = Date.now();\n const nonDecayed = entries.filter((entry) => {\n const ageInSeconds = (now - entry.timestamp) / 1000;\n const decay = scorer.calculateDecay(ageInSeconds, entry.ttl);\n return decay < 0.95; // Keep entries with decay < 0.95\n });\n\n const decayedRemoved = originalCount - nonDecayed.length;\n\n // Step 2: Find and merge duplicates\n const duplicateGroups = findDuplicates(nonDecayed);\n const merged = mergeDuplicates(duplicateGroups);\n\n // Step 3: Keep non-duplicates\n const duplicateIds = new Set(duplicateGroups.flatMap((g) => g.entries.map((e) => e.id)));\n const nonDuplicates = nonDecayed.filter((e) => !duplicateIds.has(e.id));\n\n // Combine merged duplicates with non-duplicates\n const kept = [...merged, ...nonDuplicates];\n const removed = entries.filter((e) => !kept.some((k) => k.id === e.id));\n\n const duplicatesRemoved = duplicateGroups.reduce((sum, g) => sum + (g.entries.length - 1), 0);\n\n return {\n kept,\n removed,\n entriesBefore: originalCount,\n entriesAfter: kept.length,\n decayedRemoved,\n duplicatesRemoved,\n compressionRatio: originalCount > 0 ? kept.length / originalCount : 0,\n durationMs: Date.now() - startTime,\n };\n }\n\n function findDuplicates(entries: MemoryEntry[]): DuplicateGroup[] {\n const groups: DuplicateGroup[] = [];\n const processed = new Set<string>();\n\n // Find exact hash matches\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (!entry || processed.has(entry.id)) continue;\n\n const duplicates = entries.filter((e, idx) => idx !== i && e.hash === entry.hash);\n\n if (duplicates.length > 0) {\n const group: DuplicateGroup = {\n entries: [entry, ...duplicates],\n similarity: 1.0, // Exact match\n };\n groups.push(group);\n\n // Mark as processed\n processed.add(entry.id);\n for (const dup of duplicates) {\n processed.add(dup.id);\n }\n }\n }\n\n // Find near-duplicates (cosine similarity ≥ 0.85)\n for (let i = 0; i < entries.length; i++) {\n const entryI = entries[i];\n if (!entryI || processed.has(entryI.id)) continue;\n\n for (let j = i + 1; j < entries.length; j++) {\n const entryJ = entries[j];\n if (!entryJ || processed.has(entryJ.id)) continue;\n\n const similarity = cosineSimilarity(entryI.content, entryJ.content);\n\n if (similarity >= 0.85) {\n const group: DuplicateGroup = {\n entries: [entryI, entryJ],\n similarity,\n };\n groups.push(group);\n\n processed.add(entryI.id);\n processed.add(entryJ.id);\n break; // Move to next i\n }\n }\n }\n\n return groups;\n }\n\n function mergeDuplicates(groups: DuplicateGroup[]): MemoryEntry[] {\n const merged: MemoryEntry[] = [];\n\n for (const group of groups) {\n // Keep entry with highest score\n const sorted = [...group.entries].sort((a, b) => b.score - a.score);\n const best = sorted[0];\n if (!best) continue; // Skip empty groups\n\n // Sum access counts\n const totalAccessCount = group.entries.reduce((sum, e) => sum + e.accessCount, 0);\n\n // Merge tags\n const allTags = new Set(group.entries.flatMap((e) => e.tags));\n\n merged.push({\n ...best,\n accessCount: totalAccessCount,\n tags: Array.from(allTags),\n });\n }\n\n return merged;\n }\n\n /**\n * Calculate cosine similarity between two text strings\n * @param text1 - First text\n * @param text2 - Second text\n * @returns Similarity score (0.0-1.0)\n */\n function cosineSimilarity(text1: string, text2: string): number {\n const words1 = tokenize(text1);\n const words2 = tokenize(text2);\n\n // Build vocabulary\n const vocab = new Set([...words1, ...words2]);\n\n // Build word frequency vectors\n const vec1: Record<string, number> = {};\n const vec2: Record<string, number> = {};\n\n for (const word of vocab) {\n vec1[word] = words1.filter((w) => w === word).length;\n vec2[word] = words2.filter((w) => w === word).length;\n }\n\n // Calculate dot product and magnitudes\n let dotProduct = 0;\n let mag1 = 0;\n let mag2 = 0;\n\n for (const word of vocab) {\n const count1 = vec1[word] ?? 0;\n const count2 = vec2[word] ?? 0;\n dotProduct += count1 * count2;\n mag1 += count1 * count1;\n mag2 += count2 * count2;\n }\n\n mag1 = Math.sqrt(mag1);\n mag2 = Math.sqrt(mag2);\n\n if (mag1 === 0 || mag2 === 0) return 0;\n\n return dotProduct / (mag1 * mag2);\n }\n\n function tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/\\s+/)\n .filter((word) => word.length > 0);\n }\n\n return {\n consolidate,\n findDuplicates,\n mergeDuplicates,\n };\n}\n","/**\n * Configuration types for Sparn behavior customization.\n */\n\n/**\n * Agent adapter type.\n */\nexport type AgentType = 'claude-code' | 'generic';\n\n/**\n * Pruning configuration.\n */\nexport interface PruningConfig {\n /** Percentage of top-scored entries to keep (1-100, default: 5) */\n threshold: number;\n\n /** Aggressiveness scale 0-100 (affects TF-IDF weighting, default: 50) */\n aggressiveness: number;\n}\n\n/**\n * Decay configuration.\n */\nexport interface DecayConfig {\n /** Default TTL in hours (default: 24) */\n defaultTTL: number;\n\n /** Decay threshold for pruning (0.0-1.0, default: 0.95) */\n decayThreshold: number;\n}\n\n/**\n * Confidence state threshold configuration.\n */\nexport interface StatesConfig {\n /** Score threshold for active state (default: 0.7) */\n activeThreshold: number;\n\n /** Score threshold for ready state (default: 0.3) */\n readyThreshold: number;\n}\n\n/**\n * UI configuration.\n */\nexport interface UIConfig {\n /** Enable colored output (default: true) */\n colors: boolean;\n\n /** Enable sound effects (default: false) */\n sounds: boolean;\n\n /** Verbose logging (default: false) */\n verbose: boolean;\n}\n\n/**\n * Real-time optimization configuration.\n */\nexport interface RealtimeConfig {\n /** Target token budget for optimized context (default: 50000) */\n tokenBudget: number;\n\n /** Token threshold that triggers auto-optimization (default: 80000) */\n autoOptimizeThreshold: number;\n\n /** File patterns to watch for changes (default: ['**\\/*.jsonl']) */\n watchPatterns: string[];\n\n /** Daemon PID file path (default: '.sparn/daemon.pid') */\n pidFile: string;\n\n /** Daemon log file path (default: '.sparn/daemon.log') */\n logFile: string;\n\n /** Debounce delay in milliseconds for file changes (default: 5000) */\n debounceMs: number;\n\n /** Enable incremental optimization (default: true) */\n incremental: boolean;\n\n /** Sliding window size for context entries (default: 500) */\n windowSize: number;\n\n /** Consolidation interval in hours, or null for disabled (default: null) */\n consolidationInterval: number | null;\n}\n\n/**\n * Complete Sparn configuration.\n */\nexport interface SparnConfig {\n pruning: PruningConfig;\n decay: DecayConfig;\n states: StatesConfig;\n agent: AgentType;\n ui: UIConfig;\n /** Auto-consolidation interval in hours, or null for manual */\n autoConsolidate: number | null;\n /** Real-time optimization settings */\n realtime: RealtimeConfig;\n}\n\n/**\n * Default configuration values.\n */\nexport const DEFAULT_CONFIG: SparnConfig = {\n pruning: {\n threshold: 5,\n aggressiveness: 50,\n },\n decay: {\n defaultTTL: 24,\n decayThreshold: 0.95,\n },\n states: {\n activeThreshold: 0.7,\n readyThreshold: 0.3,\n },\n agent: 'generic',\n ui: {\n colors: true,\n sounds: false,\n verbose: false,\n },\n autoConsolidate: null,\n realtime: {\n tokenBudget: 50000,\n autoOptimizeThreshold: 80000,\n watchPatterns: ['**/*.jsonl'],\n pidFile: '.sparn/daemon.pid',\n logFile: '.sparn/daemon.log',\n debounceMs: 5000,\n incremental: true,\n windowSize: 500,\n consolidationInterval: null,\n },\n};\n"],"mappings":";;;AAiBA,SAAS,iBAAiB;AAC1B,SAAS,SAAS,eAAe;AACjC,SAAS,4BAA4B;;;ACbrC,SAAS,cAAc,kBAAkB;AACzC,OAAO,cAAc;AAuDrB,SAAS,aAAa,QAAwB;AAC5C,QAAM,aAAY,oBAAI,KAAK,GAAE,YAAY,EAAE,QAAQ,SAAS,GAAG;AAC/D,QAAM,aAAa,GAAG,MAAM,WAAW,SAAS;AAEhD,MAAI;AACF,iBAAa,QAAQ,UAAU;AAC/B,YAAQ,IAAI,iCAA4B,UAAU,EAAE;AACpD,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,MAAM,qCAAqC,KAAK,EAAE;AAC1D,WAAO;AAAA,EACT;AACF;AAYA,eAAsB,eAAe,QAAmC;AAEtE,MAAI;AACJ,MAAI;AACF,SAAK,IAAI,SAAS,MAAM;AAGxB,UAAM,iBAAiB,GAAG,OAAO,eAAe,EAAE,QAAQ,KAAK,CAAC;AAChE,QAAI,mBAAmB,MAAM;AAC3B,cAAQ,MAAM,sCAAiC;AAG/C,UAAI,WAAW,MAAM,GAAG;AACtB,cAAM,aAAa,aAAa,MAAM;AACtC,YAAI,YAAY;AACd,kBAAQ,IAAI,sBAAsB,UAAU,EAAE;AAAA,QAChD;AAAA,MACF;AAGA,cAAQ,IAAI,iCAAiC;AAC7C,SAAG,MAAM;AACT,WAAK,IAAI,SAAS,MAAM;AAAA,IAC1B;AAAA,EACF,SAAS,OAAO;AACd,YAAQ,MAAM,mCAA8B,KAAK;AAGjD,QAAI,WAAW,MAAM,GAAG;AACtB,mBAAa,MAAM;AACnB,cAAQ,IAAI,0BAA0B;AAAA,IACxC;AAEA,SAAK,IAAI,SAAS,MAAM;AAAA,EAC1B;AAGA,KAAG,OAAO,oBA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AAA,MACF,SAAS,OAAO;AACd,cAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,eAAO;AAAA,UACL,SAAS;AAAA,YACP;AAAA,cACE,MAAM;AAAA,cACN,MAAM,KAAK,UAAU,EAAE,OAAO,QAAQ,CAAC;AAAA,YACzC;AAAA,UACF;AAAA,UACA,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AFnSA,eAAe,OAAsB;AACnC,QAAM,SAAS,QAAQ,QAAQ,IAAI,eAAe,KAAK,kBAAkB;AAGzE,YAAU,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AAE9C,QAAM,SAAS,MAAM,eAAe,MAAM;AAE1C,QAAM,SAAS,qBAAqB,EAAE,OAAO,CAAC;AAE9C,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAG9B,UAAQ,MAAM,mCAAmC;AAGjD,QAAM,WAAW,YAAY;AAC3B,YAAQ,MAAM,mCAAmC;AACjD,UAAM,OAAO,MAAM;AACnB,UAAM,OAAO,MAAM;AACnB,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,UAAQ,GAAG,UAAU,QAAQ;AAC7B,UAAQ,GAAG,WAAW,QAAQ;AAChC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAM,oCAAoC,KAAK;AACvD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["randomUUID","randomUUID"]}
|
|
1
|
+
{"version":3,"sources":["../../src/mcp/index.ts","../../src/core/kv-memory.ts","../../src/mcp/server.ts","../../src/adapters/generic.ts","../../src/core/btsp-embedder.ts","../../src/utils/hash.ts","../../src/core/confidence-states.ts","../../src/core/engram-scorer.ts","../../src/utils/tokenizer.ts","../../src/core/sparse-pruner.ts","../../src/core/sleep-compressor.ts","../../src/types/config.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * Sparn MCP Server Entry Point\n *\n * Starts the Sparn MCP server using stdio transport.\n * This is the main entry point for MCP client integrations\n * (Claude Desktop, VS Code, etc.).\n *\n * Usage:\n * node dist/mcp/index.js\n * node dist/mcp/index.cjs\n *\n * Environment variables:\n * SPARN_DB_PATH - Custom path for the SQLite database (default: .sparn/memory.db)\n */\n\nimport { mkdirSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { createKVMemory } from '../core/kv-memory.js';\nimport { createSparnMcpServer } from './server.js';\n\nasync function main(): Promise<void> {\n const dbPath = resolve(process.env['SPARN_DB_PATH'] ?? '.sparn/memory.db');\n\n // Ensure the database directory exists\n mkdirSync(dirname(dbPath), { recursive: true });\n\n const memory = await createKVMemory(dbPath);\n\n const server = createSparnMcpServer({ memory });\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n\n // Log to stderr (stdout is reserved for MCP JSON-RPC messages)\n console.error('Sparn MCP server running on stdio');\n\n // Graceful shutdown\n const shutdown = async () => {\n console.error('Shutting down Sparn MCP server...');\n await server.close();\n await memory.close();\n process.exit(0);\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n}\n\nmain().catch((error) => {\n console.error('Fatal error in Sparn MCP server:', error);\n process.exit(1);\n});\n","/**\n * KV Memory Store Module\n * Implements hippocampal key-value storage with dual index/value tables.\n * Maps to: Hippocampal Key-Value — the hippocampus separates what to store from how to retrieve it.\n */\n\nimport { copyFileSync, existsSync } from 'node:fs';\nimport Database from 'better-sqlite3';\nimport type { MemoryEntry, MemoryQueryFilters } from '../types/memory.js';\n\n/**\n * Optimization statistics record.\n */\nexport interface OptimizationStats {\n id: number;\n timestamp: number;\n tokens_before: number;\n tokens_after: number;\n entries_pruned: number;\n duration_ms: number;\n}\n\n/**\n * KV Memory interface.\n */\nexport interface KVMemory {\n /** Store a memory entry */\n put(entry: MemoryEntry): Promise<void>;\n\n /** Retrieve a memory entry by ID */\n get(id: string): Promise<MemoryEntry | null>;\n\n /** Query entries by filters */\n query(filters: MemoryQueryFilters): Promise<MemoryEntry[]>;\n\n /** Delete a memory entry */\n delete(id: string): Promise<void>;\n\n /** List all entry IDs */\n list(): Promise<string[]>;\n\n /** Compact database (remove expired entries) */\n compact(): Promise<number>;\n\n /** Close database connection */\n close(): Promise<void>;\n\n /** Record optimization statistics */\n recordOptimization(stats: Omit<OptimizationStats, 'id'>): Promise<void>;\n\n /** Get all optimization statistics */\n getOptimizationStats(): Promise<OptimizationStats[]>;\n\n /** Clear all optimization statistics */\n clearOptimizationStats(): Promise<void>;\n}\n\n/**\n * Create a timestamped backup of the database\n * @param dbPath - Path to database file\n * @returns Path to backup file\n */\nfunction createBackup(dbPath: string): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n const backupPath = `${dbPath}.backup-${timestamp}`;\n\n try {\n copyFileSync(dbPath, backupPath);\n console.log(`✓ Database backed up to: ${backupPath}`);\n return backupPath;\n } catch (error) {\n console.error(`Warning: Could not create backup: ${error}`);\n return '';\n }\n}\n\n/**\n * Create KV Memory store with SQLite backend.\n *\n * Initializes database with dual table schema:\n * - entries_index: Fast lookups (id, hash, timestamp, score, ttl, state, accessCount, isBTSP)\n * - entries_value: Content storage (id, content, tags, metadata)\n *\n * @param dbPath - Path to SQLite database file\n * @returns KVMemory instance\n */\nexport async function createKVMemory(dbPath: string): Promise<KVMemory> {\n // Detect database corruption and create backup\n let db: Database.Database;\n try {\n db = new Database(dbPath);\n\n // Quick integrity check\n const integrityCheck = db.pragma('quick_check', { simple: true });\n if (integrityCheck !== 'ok') {\n console.error('⚠ Database corruption detected!');\n\n // Create backup before attempting recovery\n if (existsSync(dbPath)) {\n const backupPath = createBackup(dbPath);\n if (backupPath) {\n console.log(`Backup created at: ${backupPath}`);\n }\n }\n\n // Try to recover\n console.log('Attempting database recovery...');\n db.close();\n db = new Database(dbPath);\n }\n } catch (error) {\n console.error('⚠ Database error detected:', error);\n\n // Create backup if database exists\n if (existsSync(dbPath)) {\n createBackup(dbPath);\n console.log('Creating new database...');\n }\n\n db = new Database(dbPath);\n }\n\n // Enable WAL mode for better concurrency\n db.pragma('journal_mode = WAL');\n\n // Create entries_index table\n db.exec(`\n CREATE TABLE IF NOT EXISTS entries_index (\n id TEXT PRIMARY KEY NOT NULL,\n hash TEXT UNIQUE NOT NULL,\n timestamp INTEGER NOT NULL,\n score REAL NOT NULL DEFAULT 0.0 CHECK(score >= 0.0 AND score <= 1.0),\n ttl INTEGER NOT NULL CHECK(ttl >= 0),\n state TEXT NOT NULL CHECK(state IN ('silent', 'ready', 'active')),\n accessCount INTEGER NOT NULL DEFAULT 0 CHECK(accessCount >= 0),\n isBTSP INTEGER NOT NULL DEFAULT 0 CHECK(isBTSP IN (0, 1)),\n created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))\n );\n `);\n\n // Create entries_value table\n db.exec(`\n CREATE TABLE IF NOT EXISTS entries_value (\n id TEXT PRIMARY KEY NOT NULL,\n content TEXT NOT NULL,\n tags TEXT,\n metadata TEXT,\n FOREIGN KEY (id) REFERENCES entries_index(id) ON DELETE CASCADE\n );\n `);\n\n // Create optimization_stats table\n db.exec(`\n CREATE TABLE IF NOT EXISTS optimization_stats (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n timestamp INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),\n tokens_before INTEGER NOT NULL,\n tokens_after INTEGER NOT NULL,\n entries_pruned INTEGER NOT NULL,\n duration_ms INTEGER NOT NULL\n );\n `);\n\n // Create indexes\n db.exec(`\n CREATE INDEX IF NOT EXISTS idx_entries_state ON entries_index(state);\n CREATE INDEX IF NOT EXISTS idx_entries_score ON entries_index(score DESC);\n CREATE INDEX IF NOT EXISTS idx_entries_hash ON entries_index(hash);\n CREATE INDEX IF NOT EXISTS idx_entries_timestamp ON entries_index(timestamp DESC);\n CREATE INDEX IF NOT EXISTS idx_stats_timestamp ON optimization_stats(timestamp DESC);\n `);\n\n // Prepare statements for better performance\n const putIndexStmt = db.prepare(`\n INSERT OR REPLACE INTO entries_index\n (id, hash, timestamp, score, ttl, state, accessCount, isBTSP)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const putValueStmt = db.prepare(`\n INSERT OR REPLACE INTO entries_value\n (id, content, tags, metadata)\n VALUES (?, ?, ?, ?)\n `);\n\n const getStmt = db.prepare(`\n SELECT\n i.id, i.hash, i.timestamp, i.score, i.ttl, i.state, i.accessCount, i.isBTSP,\n v.content, v.tags, v.metadata\n FROM entries_index i\n JOIN entries_value v ON i.id = v.id\n WHERE i.id = ?\n `);\n\n const deleteIndexStmt = db.prepare('DELETE FROM entries_index WHERE id = ?');\n const deleteValueStmt = db.prepare('DELETE FROM entries_value WHERE id = ?');\n\n return {\n async put(entry: MemoryEntry): Promise<void> {\n const transaction = db.transaction(() => {\n putIndexStmt.run(\n entry.id,\n entry.hash,\n entry.timestamp,\n entry.score,\n entry.ttl,\n entry.state,\n entry.accessCount,\n entry.isBTSP ? 1 : 0,\n );\n\n putValueStmt.run(\n entry.id,\n entry.content,\n JSON.stringify(entry.tags),\n JSON.stringify(entry.metadata),\n );\n });\n\n transaction();\n },\n\n async get(id: string): Promise<MemoryEntry | null> {\n const row = getStmt.get(id) as unknown;\n\n if (!row) {\n return null;\n }\n\n const r = row as {\n id: string;\n hash: string;\n timestamp: number;\n score: number;\n ttl: number;\n state: string;\n accessCount: number;\n isBTSP: number;\n content: string;\n tags: string | null;\n metadata: string | null;\n };\n\n return {\n id: r.id,\n content: r.content,\n hash: r.hash,\n timestamp: r.timestamp,\n score: r.score,\n ttl: r.ttl,\n state: r.state as 'silent' | 'ready' | 'active',\n accessCount: r.accessCount,\n tags: r.tags ? JSON.parse(r.tags) : [],\n metadata: r.metadata ? JSON.parse(r.metadata) : {},\n isBTSP: r.isBTSP === 1,\n };\n },\n\n async query(filters: MemoryQueryFilters): Promise<MemoryEntry[]> {\n let sql = `\n SELECT\n i.id, i.hash, i.timestamp, i.score, i.ttl, i.state, i.accessCount, i.isBTSP,\n v.content, v.tags, v.metadata\n FROM entries_index i\n JOIN entries_value v ON i.id = v.id\n WHERE 1=1\n `;\n\n const params: unknown[] = [];\n\n if (filters.state) {\n sql += ' AND i.state = ?';\n params.push(filters.state);\n }\n\n if (filters.minScore !== undefined) {\n sql += ' AND i.score >= ?';\n params.push(filters.minScore);\n }\n\n if (filters.maxScore !== undefined) {\n sql += ' AND i.score <= ?';\n params.push(filters.maxScore);\n }\n\n if (filters.isBTSP !== undefined) {\n sql += ' AND i.isBTSP = ?';\n params.push(filters.isBTSP ? 1 : 0);\n }\n\n sql += ' ORDER BY i.score DESC';\n\n if (filters.limit) {\n sql += ' LIMIT ?';\n params.push(filters.limit);\n }\n\n if (filters.offset) {\n sql += ' OFFSET ?';\n params.push(filters.offset);\n }\n\n const stmt = db.prepare(sql);\n const rows = stmt.all(...params) as unknown[];\n\n return rows.map((row) => {\n const r = row as {\n id: string;\n hash: string;\n timestamp: number;\n score: number;\n ttl: number;\n state: string;\n accessCount: number;\n isBTSP: number;\n content: string;\n tags: string | null;\n metadata: string | null;\n };\n\n return {\n id: r.id,\n content: r.content,\n hash: r.hash,\n timestamp: r.timestamp,\n score: r.score,\n ttl: r.ttl,\n state: r.state as 'silent' | 'ready' | 'active',\n accessCount: r.accessCount,\n tags: r.tags ? JSON.parse(r.tags) : [],\n metadata: r.metadata ? JSON.parse(r.metadata) : {},\n isBTSP: r.isBTSP === 1,\n };\n });\n },\n\n async delete(id: string): Promise<void> {\n const transaction = db.transaction(() => {\n deleteIndexStmt.run(id);\n deleteValueStmt.run(id);\n });\n\n transaction();\n },\n\n async list(): Promise<string[]> {\n const stmt = db.prepare('SELECT id FROM entries_index');\n const rows = stmt.all() as { id: string }[];\n return rows.map((r) => r.id);\n },\n\n async compact(): Promise<number> {\n const before = db.prepare('SELECT COUNT(*) as count FROM entries_index').get() as {\n count: number;\n };\n\n // Remove fully decayed entries (this will be enhanced in sleep-compressor)\n db.exec('DELETE FROM entries_index WHERE ttl <= 0');\n\n db.exec('VACUUM');\n\n const after = db.prepare('SELECT COUNT(*) as count FROM entries_index').get() as {\n count: number;\n };\n\n return before.count - after.count;\n },\n\n async close(): Promise<void> {\n db.close();\n },\n\n async recordOptimization(stats: Omit<OptimizationStats, 'id'>): Promise<void> {\n const stmt = db.prepare(`\n INSERT INTO optimization_stats (timestamp, tokens_before, tokens_after, entries_pruned, duration_ms)\n VALUES (?, ?, ?, ?, ?)\n `);\n\n stmt.run(\n stats.timestamp,\n stats.tokens_before,\n stats.tokens_after,\n stats.entries_pruned,\n stats.duration_ms,\n );\n },\n\n async getOptimizationStats(): Promise<OptimizationStats[]> {\n const stmt = db.prepare(`\n SELECT id, timestamp, tokens_before, tokens_after, entries_pruned, duration_ms\n FROM optimization_stats\n ORDER BY timestamp DESC\n `);\n\n const rows = stmt.all() as OptimizationStats[];\n return rows;\n },\n\n async clearOptimizationStats(): Promise<void> {\n db.exec('DELETE FROM optimization_stats');\n },\n };\n}\n","/**\n * Sparn MCP Server - Model Context Protocol server implementation\n *\n * Exposes Sparn's neuroscience-inspired context optimization as MCP tools,\n * enabling integration with Claude Desktop, VS Code, and other MCP clients.\n *\n * Tools:\n * - sparn_optimize: Optimize context with configurable options\n * - sparn_stats: Get optimization statistics\n * - sparn_consolidate: Run memory consolidation (sleep replay)\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { createGenericAdapter } from '../adapters/generic.js';\nimport type { KVMemory } from '../core/kv-memory.js';\nimport { createSleepCompressor } from '../core/sleep-compressor.js';\nimport type { SparnConfig } from '../types/config.js';\nimport { DEFAULT_CONFIG } from '../types/config.js';\n\n/**\n * Options for creating the Sparn MCP server.\n */\nexport interface SparnMcpServerOptions {\n /** KV memory store instance */\n memory: KVMemory;\n /** Sparn configuration (defaults to DEFAULT_CONFIG) */\n config?: SparnConfig;\n}\n\n/**\n * Create and configure the Sparn MCP server with all tools registered.\n *\n * @param options - Server options including memory store and config\n * @returns Configured McpServer instance ready to connect to a transport\n */\nexport function createSparnMcpServer(options: SparnMcpServerOptions): McpServer {\n const { memory, config = DEFAULT_CONFIG } = options;\n\n const server = new McpServer({\n name: 'sparn',\n version: '1.1.1',\n });\n\n registerOptimizeTool(server, memory, config);\n registerStatsTool(server, memory);\n registerConsolidateTool(server, memory);\n\n return server;\n}\n\n/**\n * Register the sparn_optimize tool.\n *\n * Optimizes input context using the neuroscience-inspired pipeline:\n * BTSP detection, engram scoring, confidence states, and sparse pruning.\n */\nfunction registerOptimizeTool(server: McpServer, memory: KVMemory, config: SparnConfig): void {\n server.registerTool(\n 'sparn_optimize',\n {\n title: 'Sparn Optimize',\n description:\n 'Optimize context using neuroscience-inspired pruning. ' +\n 'Applies BTSP detection, engram scoring, confidence states, ' +\n 'and sparse pruning to reduce token usage while preserving important information.',\n inputSchema: {\n context: z.string().describe('The context text to optimize'),\n dryRun: z\n .boolean()\n .optional()\n .default(false)\n .describe('If true, do not persist changes to the memory store'),\n verbose: z\n .boolean()\n .optional()\n .default(false)\n .describe('If true, include per-entry details in the response'),\n threshold: z\n .number()\n .min(0)\n .max(100)\n .optional()\n .describe('Custom pruning threshold (1-100, overrides config)'),\n },\n },\n async ({ context, dryRun, verbose, threshold }) => {\n try {\n const effectiveConfig = threshold\n ? { ...config, pruning: { ...config.pruning, threshold } }\n : config;\n\n const adapter = createGenericAdapter(memory, effectiveConfig);\n const result = await adapter.optimize(context, {\n dryRun,\n verbose,\n threshold,\n });\n\n const response = {\n optimizedContext: result.optimizedContext,\n tokensBefore: result.tokensBefore,\n tokensAfter: result.tokensAfter,\n reduction: `${(result.reduction * 100).toFixed(1)}%`,\n entriesProcessed: result.entriesProcessed,\n entriesKept: result.entriesKept,\n durationMs: result.durationMs,\n stateDistribution: result.stateDistribution,\n ...(verbose && result.details ? { details: result.details } : {}),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(response, null, 2),\n },\n ],\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true,\n };\n }\n },\n );\n}\n\n/**\n * Register the sparn_stats tool.\n *\n * Returns optimization statistics from the memory store, including\n * total commands run, tokens saved, and average reduction.\n */\nfunction registerStatsTool(server: McpServer, memory: KVMemory): void {\n server.registerTool(\n 'sparn_stats',\n {\n title: 'Sparn Stats',\n description:\n 'Get optimization statistics including total commands run, ' +\n 'tokens saved, and average reduction percentage.',\n inputSchema: {\n reset: z\n .boolean()\n .optional()\n .default(false)\n .describe('If true, reset all optimization statistics'),\n },\n },\n async ({ reset }) => {\n try {\n if (reset) {\n await memory.clearOptimizationStats();\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n {\n message: 'Optimization statistics have been reset.',\n totalCommands: 0,\n totalTokensSaved: 0,\n averageReduction: '0.0%',\n },\n null,\n 2,\n ),\n },\n ],\n };\n }\n\n const stats = await memory.getOptimizationStats();\n const totalCommands = stats.length;\n\n const totalTokensSaved = stats.reduce(\n (sum, s) => sum + (s.tokens_before - s.tokens_after),\n 0,\n );\n\n const averageReduction =\n totalCommands > 0\n ? stats.reduce((sum, s) => {\n const reduction =\n s.tokens_before > 0 ? (s.tokens_before - s.tokens_after) / s.tokens_before : 0;\n return sum + reduction;\n }, 0) / totalCommands\n : 0;\n\n const recentOptimizations = stats.slice(0, 10).map((s) => ({\n timestamp: new Date(s.timestamp).toISOString(),\n tokensBefore: s.tokens_before,\n tokensAfter: s.tokens_after,\n entriesPruned: s.entries_pruned,\n durationMs: s.duration_ms,\n reduction: `${(\n ((s.tokens_before - s.tokens_after) / Math.max(s.tokens_before, 1)) * 100\n ).toFixed(1)}%`,\n }));\n\n const response = {\n totalCommands,\n totalTokensSaved,\n averageReduction: `${(averageReduction * 100).toFixed(1)}%`,\n recentOptimizations,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(response, null, 2),\n },\n ],\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true,\n };\n }\n },\n );\n}\n\n/**\n * Register the sparn_consolidate tool.\n *\n * Runs the sleep-compressor consolidation process, which removes\n * decayed entries and merges duplicates in the memory store.\n */\nfunction registerConsolidateTool(server: McpServer, memory: KVMemory): void {\n server.registerTool(\n 'sparn_consolidate',\n {\n title: 'Sparn Consolidate',\n description:\n 'Run memory consolidation (sleep replay). ' +\n 'Removes decayed entries and merges duplicates to reclaim space. ' +\n 'Inspired by the neuroscience principle of sleep-based memory consolidation.',\n },\n async () => {\n try {\n const allIds = await memory.list();\n const allEntries = await Promise.all(\n allIds.map(async (id) => {\n const entry = await memory.get(id);\n return entry;\n }),\n );\n\n const entries = allEntries.filter((e) => e !== null);\n\n const compressor = createSleepCompressor();\n const result = compressor.consolidate(entries);\n\n // Apply changes to memory store\n for (const removed of result.removed) {\n await memory.delete(removed.id);\n }\n\n for (const kept of result.kept) {\n await memory.put(kept);\n }\n\n // Run VACUUM to reclaim disk space\n await memory.compact();\n\n const response = {\n entriesBefore: result.entriesBefore,\n entriesAfter: result.entriesAfter,\n decayedRemoved: result.decayedRemoved,\n duplicatesRemoved: result.duplicatesRemoved,\n compressionRatio: `${(result.compressionRatio * 100).toFixed(1)}%`,\n durationMs: result.durationMs,\n vacuumCompleted: true,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(response, null, 2),\n },\n ],\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true,\n };\n }\n },\n );\n}\n","/**\n * Generic Adapter - Agent-agnostic optimization pipeline\n *\n * Orchestrates all 6 neuroscience modules to optimize context memory.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { createBTSPEmbedder } from '../core/btsp-embedder.js';\nimport { createConfidenceStates } from '../core/confidence-states.js';\nimport { createEngramScorer } from '../core/engram-scorer.js';\nimport type { KVMemory } from '../core/kv-memory.js';\nimport { createSparsePruner } from '../core/sparse-pruner.js';\nimport type { AgentAdapter, OptimizationResult, OptimizeOptions } from '../types/adapter.js';\nimport type { SparnConfig } from '../types/config.js';\nimport type { MemoryEntry } from '../types/memory.js';\nimport { hashContent } from '../utils/hash.js';\nimport { estimateTokens } from '../utils/tokenizer.js';\n\n/**\n * Create a generic adapter instance\n * @param memory - KV memory store\n * @param config - Sparn configuration\n * @returns AgentAdapter instance\n */\nexport function createGenericAdapter(memory: KVMemory, config: SparnConfig): AgentAdapter {\n const pruner = createSparsePruner(config.pruning);\n const scorer = createEngramScorer(config.decay);\n const states = createConfidenceStates(config.states);\n const btsp = createBTSPEmbedder();\n\n async function optimize(\n context: string,\n options: OptimizeOptions = {},\n ): Promise<OptimizationResult> {\n const startTime = Date.now();\n\n // Parse context into entries (line-based for simplicity)\n const lines = context.split('\\n').filter((line) => line.trim().length > 0);\n const entries: MemoryEntry[] = lines.map((content) => ({\n id: randomUUID(),\n content,\n hash: hashContent(content),\n timestamp: Date.now(),\n score: btsp.detectBTSP(content) ? 1.0 : 0.5, // BTSP gets high initial score\n ttl: config.decay.defaultTTL * 3600, // Convert hours to seconds\n state: 'ready' as const,\n accessCount: 0,\n tags: [],\n metadata: {},\n isBTSP: btsp.detectBTSP(content),\n }));\n\n // Calculate original token count\n const tokensBefore = entries.reduce((sum, e) => sum + estimateTokens(e.content), 0);\n\n // Step 1: Update scores with decay\n const scoredEntries = entries.map((entry) => ({\n ...entry,\n score: scorer.calculateScore(entry),\n }));\n\n // Step 2: Transition states based on scores\n const statedEntries = scoredEntries.map((entry) => states.transition(entry));\n\n // Step 3: Apply sparse pruning\n const pruneResult = pruner.prune(statedEntries);\n\n // Step 4: Keep active and ready entries, discard silent\n const optimizedEntries = pruneResult.kept.filter(\n (e) => e.state === 'active' || e.state === 'ready',\n );\n\n // Calculate final token count\n const tokensAfter = optimizedEntries.reduce((sum, e) => sum + estimateTokens(e.content), 0);\n\n // Reconstruct optimized context\n const optimizedContext = optimizedEntries.map((e) => e.content).join('\\n');\n\n // Store entries in memory (if not dry run)\n if (!options.dryRun) {\n for (const entry of optimizedEntries) {\n await memory.put(entry);\n }\n\n // Record optimization statistics\n await memory.recordOptimization({\n timestamp: Date.now(),\n tokens_before: tokensBefore,\n tokens_after: tokensAfter,\n entries_pruned: entries.length - optimizedEntries.length,\n duration_ms: Date.now() - startTime,\n });\n }\n\n // Get state distribution\n const distribution = states.getDistribution(optimizedEntries);\n\n const result: OptimizationResult = {\n optimizedContext,\n tokensBefore,\n tokensAfter,\n reduction: tokensBefore > 0 ? (tokensBefore - tokensAfter) / tokensBefore : 0,\n entriesProcessed: entries.length,\n entriesKept: optimizedEntries.length,\n stateDistribution: distribution,\n durationMs: Date.now() - startTime,\n };\n\n // Add verbose details if requested\n if (options.verbose) {\n result.details = optimizedEntries.map((e) => ({\n id: e.id,\n score: e.score,\n state: e.state,\n isBTSP: e.isBTSP,\n tokens: estimateTokens(e.content),\n }));\n }\n\n return result;\n }\n\n return {\n optimize,\n };\n}\n","/**\n * BTSP Embedder - Implements behavioral timescale synaptic plasticity\n *\n * Neuroscience: One-shot learning from critical events (errors, conflicts).\n * Application: Detect high-importance patterns and mark for permanent retention.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { MemoryEntry } from '../types/memory.js';\nimport { hashContent } from '../utils/hash.js';\n\nexport interface BTSPEmbedder {\n /**\n * Detect if content contains BTSP patterns (errors, stack traces, conflicts, git diffs)\n * @param content - Content to analyze\n * @returns True if BTSP pattern detected\n */\n detectBTSP(content: string): boolean;\n\n /**\n * Create a new memory entry marked as BTSP (one-shot learned)\n * @param content - Entry content\n * @param tags - Optional tags\n * @param metadata - Optional metadata\n * @returns BTSP-marked memory entry\n */\n createBTSPEntry(\n content: string,\n tags?: string[],\n metadata?: Record<string, unknown>,\n ): MemoryEntry;\n}\n\n/**\n * Create a BTSP embedder instance\n * @returns BTSPEmbedder instance\n */\nexport function createBTSPEmbedder(): BTSPEmbedder {\n // Patterns that indicate critical events\n const BTSP_PATTERNS = [\n // Error patterns\n /\\b(error|exception|failure|fatal|critical|panic)\\b/i,\n /\\b(TypeError|ReferenceError|SyntaxError|RangeError|URIError)\\b/,\n /\\bENOENT|EACCES|ECONNREFUSED|ETIMEDOUT\\b/,\n\n // Stack trace patterns\n /^\\s+at\\s+.*\\(.*:\\d+:\\d+\\)/m, // JavaScript stack trace\n /^\\s+at\\s+.*\\.[a-zA-Z]+:\\d+/m, // Python/Ruby stack trace\n\n // Git diff new files\n /^new file mode \\d+$/m,\n /^--- \\/dev\\/null$/m,\n\n // Merge conflict markers\n /^<<<<<<< /m,\n /^=======/m,\n /^>>>>>>> /m,\n ];\n\n function detectBTSP(content: string): boolean {\n return BTSP_PATTERNS.some((pattern) => pattern.test(content));\n }\n\n function createBTSPEntry(\n content: string,\n tags: string[] = [],\n metadata: Record<string, unknown> = {},\n ): MemoryEntry {\n return {\n id: randomUUID(),\n content,\n hash: hashContent(content),\n timestamp: Date.now(),\n score: 1.0, // Maximum initial score\n ttl: 365 * 24 * 3600, // 1 year in seconds (long retention)\n state: 'active', // Always active\n accessCount: 0,\n tags: [...tags, 'btsp'],\n metadata,\n isBTSP: true,\n };\n }\n\n return {\n detectBTSP,\n createBTSPEntry,\n };\n}\n","/**\n * Content hashing utilities.\n * Uses SHA-256 for deduplication.\n */\n\nimport { createHash } from 'node:crypto';\n\n/**\n * Generate SHA-256 hash of content for deduplication.\n *\n * @param content - Content to hash\n * @returns 64-character hex string (SHA-256)\n *\n * @example\n * ```typescript\n * const hash = hashContent('Hello world');\n * console.log(hash.length); // 64\n * ```\n */\nexport function hashContent(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n","/**\n * Confidence States - Implements multi-state synapses\n *\n * Neuroscience: Synapses exist in three states: silent, ready (potentiated), active.\n * Application: Classify memory entries by score into silent/ready/active states.\n */\n\nimport type { ConfidenceState, MemoryEntry, StateDistribution } from '../types/memory.js';\n\nexport interface ConfidenceStatesConfig {\n /** Score threshold for active state (e.g., 0.7) */\n activeThreshold: number;\n /** Score threshold for ready state (e.g., 0.3) */\n readyThreshold: number;\n}\n\nexport interface ConfidenceStates {\n /**\n * Calculate state based on entry score and BTSP flag\n * @param entry - Memory entry\n * @returns Confidence state\n */\n calculateState(entry: MemoryEntry): ConfidenceState;\n\n /**\n * Transition entry to correct state based on its score\n * @param entry - Entry to transition\n * @returns Entry with updated state\n */\n transition(entry: MemoryEntry): MemoryEntry;\n\n /**\n * Get distribution of states across all entries\n * @param entries - All memory entries\n * @returns State distribution with counts\n */\n getDistribution(entries: MemoryEntry[]): StateDistribution;\n}\n\n/**\n * Create a confidence states manager\n * @param config - States configuration\n * @returns ConfidenceStates instance\n */\nexport function createConfidenceStates(config: ConfidenceStatesConfig): ConfidenceStates {\n const { activeThreshold, readyThreshold } = config;\n\n function calculateState(entry: MemoryEntry): ConfidenceState {\n // BTSP entries are always active\n if (entry.isBTSP) {\n return 'active';\n }\n\n // State based on score thresholds\n // Active: score > 0.7\n if (entry.score > activeThreshold) {\n return 'active';\n }\n\n // Ready: 0.3 <= score <= 0.7\n if (entry.score >= readyThreshold) {\n return 'ready';\n }\n\n // Silent: score < 0.3\n return 'silent';\n }\n\n function transition(entry: MemoryEntry): MemoryEntry {\n const newState = calculateState(entry);\n\n return {\n ...entry,\n state: newState,\n };\n }\n\n function getDistribution(entries: MemoryEntry[]): StateDistribution {\n const distribution: StateDistribution = {\n silent: 0,\n ready: 0,\n active: 0,\n total: entries.length,\n };\n\n for (const entry of entries) {\n const state = calculateState(entry);\n distribution[state]++;\n }\n\n return distribution;\n }\n\n return {\n calculateState,\n transition,\n getDistribution,\n };\n}\n","/**\n * Engram Scorer - Implements engram theory (memory decay)\n *\n * Neuroscience: Memories fade over time without reinforcement.\n * Application: Apply exponential decay formula to memory scores based on age and access count.\n *\n * Formula: decay = 1 - e^(-age/TTL)\n * Score adjustment: score_new = score_old * (1 - decay) + (accessCount bonus)\n */\n\nimport type { MemoryEntry } from '../types/memory.js';\n\nexport interface EngramScorerConfig {\n /** Default TTL in hours for new entries */\n defaultTTL: number;\n /** Decay threshold (0.0-1.0) above which entries are marked for pruning */\n decayThreshold: number;\n}\n\nexport interface EngramScorer {\n /**\n * Calculate current score for an entry based on decay and access count\n * @param entry - Memory entry to score\n * @param currentTime - Current timestamp in milliseconds (for testing)\n * @returns Updated score (0.0-1.0)\n */\n calculateScore(entry: MemoryEntry, currentTime?: number): number;\n\n /**\n * Refresh TTL to default value\n * @param entry - Entry to refresh\n * @returns Entry with refreshed TTL and timestamp\n */\n refreshTTL(entry: MemoryEntry): MemoryEntry;\n\n /**\n * Calculate decay factor (0.0-1.0) based on age and TTL\n * @param ageInSeconds - Age of entry in seconds\n * @param ttlInSeconds - TTL in seconds\n * @returns Decay factor (0.0 = fresh, 1.0 = fully decayed)\n */\n calculateDecay(ageInSeconds: number, ttlInSeconds: number): number;\n}\n\n/**\n * Create an engram scorer instance\n * @param config - Scorer configuration\n * @returns EngramScorer instance\n */\nexport function createEngramScorer(config: EngramScorerConfig): EngramScorer {\n const { defaultTTL } = config;\n\n function calculateDecay(ageInSeconds: number, ttlInSeconds: number): number {\n if (ttlInSeconds === 0) return 1.0; // Instant decay\n if (ageInSeconds <= 0) return 0.0; // Fresh entry\n\n // Exponential decay: 1 - e^(-age/TTL)\n const ratio = ageInSeconds / ttlInSeconds;\n const decay = 1 - Math.exp(-ratio);\n\n // Clamp to [0.0, 1.0]\n return Math.max(0, Math.min(1, decay));\n }\n\n function calculateScore(entry: MemoryEntry, currentTime: number = Date.now()): number {\n // Calculate age in seconds\n const ageInMilliseconds = currentTime - entry.timestamp;\n const ageInSeconds = Math.max(0, ageInMilliseconds / 1000);\n\n // Calculate decay factor\n const decay = calculateDecay(ageInSeconds, entry.ttl);\n\n // Base score reduced by decay\n let score = entry.score * (1 - decay);\n\n // Access count bonus (diminishing returns via log)\n if (entry.accessCount > 0) {\n const accessBonus = Math.log(entry.accessCount + 1) * 0.1;\n score = Math.min(1.0, score + accessBonus);\n }\n\n // BTSP entries maintain high score\n if (entry.isBTSP) {\n score = Math.max(score, 0.9);\n }\n\n return Math.max(0, Math.min(1, score));\n }\n\n function refreshTTL(entry: MemoryEntry): MemoryEntry {\n return {\n ...entry,\n ttl: defaultTTL * 3600, // Convert hours to seconds\n timestamp: Date.now(),\n };\n }\n\n return {\n calculateScore,\n refreshTTL,\n calculateDecay,\n };\n}\n","/**\n * Token estimation utilities.\n * Uses whitespace heuristic (~90% accuracy vs GPT tokenizer).\n */\n\n/**\n * Estimate token count for text using heuristic.\n *\n * Approximation: 1 token ≈ 4 chars or 0.75 words\n * Provides ~90% accuracy compared to GPT tokenizer, sufficient for optimization heuristics.\n *\n * @param text - Text to count\n * @returns Estimated token count\n *\n * @example\n * ```typescript\n * const tokens = estimateTokens('Hello world');\n * console.log(tokens); // ~2\n * ```\n */\nexport function estimateTokens(text: string): number {\n if (!text || text.length === 0) {\n return 0;\n }\n\n // Split on whitespace to get words\n const words = text.split(/\\s+/).filter((w) => w.length > 0);\n const wordCount = words.length;\n\n // Character-based estimate\n const charCount = text.length;\n const charEstimate = Math.ceil(charCount / 4);\n\n // Word-based estimate\n const wordEstimate = Math.ceil(wordCount * 0.75);\n\n // Return the maximum of both estimates (more conservative)\n return Math.max(wordEstimate, charEstimate);\n}\n","/**\n * Sparse Pruner - Implements sparse coding principle\n *\n * Neuroscience: Only 2-5% of neurons fire at any given time.\n * Application: Keep only top 5% most relevant context entries by TF-IDF score.\n */\n\nimport type { MemoryEntry } from '../types/memory.js';\nimport type { PruneResult } from '../types/pruner.js';\nimport { estimateTokens } from '../utils/tokenizer.js';\n\nexport interface SparsePrunerConfig {\n /** Percentage threshold for pruning (e.g., 5 = keep top 5%) */\n threshold: number;\n}\n\nexport interface SparsePruner {\n /**\n * Prune entries to keep only top N% by relevance score\n * @param entries - Memory entries to prune\n * @returns Result with kept/removed entries and token counts\n */\n prune(entries: MemoryEntry[]): PruneResult;\n\n /**\n * Calculate TF-IDF relevance score for a single entry\n * @param entry - Entry to score\n * @param allEntries - All entries for IDF calculation\n * @returns Relevance score (0.0-1.0)\n */\n scoreEntry(entry: MemoryEntry, allEntries: MemoryEntry[]): number;\n}\n\n/**\n * Create a sparse pruner instance\n * @param config - Pruner configuration\n * @returns SparsePruner instance\n */\nexport function createSparsePruner(config: SparsePrunerConfig): SparsePruner {\n const { threshold } = config;\n\n function tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/\\s+/)\n .filter((word) => word.length > 0);\n }\n\n function calculateTF(term: string, tokens: string[]): number {\n const count = tokens.filter((t) => t === term).length;\n // Sqrt capping to prevent common words from dominating\n return Math.sqrt(count);\n }\n\n function calculateIDF(term: string, allEntries: MemoryEntry[]): number {\n const totalDocs = allEntries.length;\n const docsWithTerm = allEntries.filter((entry) => {\n const tokens = tokenize(entry.content);\n return tokens.includes(term);\n }).length;\n\n if (docsWithTerm === 0) return 0;\n\n return Math.log(totalDocs / docsWithTerm);\n }\n\n function scoreEntry(entry: MemoryEntry, allEntries: MemoryEntry[]): number {\n const tokens = tokenize(entry.content);\n if (tokens.length === 0) return 0;\n\n const uniqueTerms = [...new Set(tokens)];\n let totalScore = 0;\n\n for (const term of uniqueTerms) {\n const tf = calculateTF(term, tokens);\n const idf = calculateIDF(term, allEntries);\n totalScore += tf * idf;\n }\n\n // Normalize by entry length\n return totalScore / tokens.length;\n }\n\n function prune(entries: MemoryEntry[]): PruneResult {\n if (entries.length === 0) {\n return {\n kept: [],\n removed: [],\n originalTokens: 0,\n prunedTokens: 0,\n };\n }\n\n // Calculate original token count\n const originalTokens = entries.reduce((sum, e) => sum + estimateTokens(e.content), 0);\n\n // Score all entries\n const scored = entries.map((entry) => ({\n entry,\n score: scoreEntry(entry, entries),\n }));\n\n // Sort by score descending\n scored.sort((a, b) => b.score - a.score);\n\n // Keep top N% (minimum 1 entry)\n const keepCount = Math.max(1, Math.ceil(entries.length * (threshold / 100)));\n const kept = scored.slice(0, keepCount).map((s) => s.entry);\n const removed = scored.slice(keepCount).map((s) => s.entry);\n\n // Calculate pruned token count\n const prunedTokens = kept.reduce((sum, e) => sum + estimateTokens(e.content), 0);\n\n return {\n kept,\n removed,\n originalTokens,\n prunedTokens,\n };\n }\n\n return {\n prune,\n scoreEntry,\n };\n}\n","/**\n * Sleep Compressor - Implements sleep replay principle\n *\n * Neuroscience: During sleep, the brain consolidates memories by replaying important ones\n * and discarding irrelevant information.\n * Application: Periodic consolidation removes decayed entries and merges duplicates.\n */\n\nimport type { ConsolidateResult, DuplicateGroup } from '../types/consolidate.js';\nimport type { MemoryEntry } from '../types/memory.js';\nimport { createEngramScorer } from './engram-scorer.js';\n\nexport interface SleepCompressor {\n /**\n * Consolidate entries: remove decayed, merge duplicates\n * @param entries - All memory entries\n * @returns Consolidation result\n */\n consolidate(entries: MemoryEntry[]): ConsolidateResult;\n\n /**\n * Find duplicate entries (exact hash or near-duplicate by similarity)\n * @param entries - Memory entries\n * @returns Groups of duplicates\n */\n findDuplicates(entries: MemoryEntry[]): DuplicateGroup[];\n\n /**\n * Merge duplicate entries, keeping highest score\n * @param groups - Duplicate groups\n * @returns Merged entries\n */\n mergeDuplicates(groups: DuplicateGroup[]): MemoryEntry[];\n}\n\n/**\n * Create a sleep compressor instance\n * @returns SleepCompressor instance\n */\nexport function createSleepCompressor(): SleepCompressor {\n const scorer = createEngramScorer({ defaultTTL: 24, decayThreshold: 0.95 });\n\n function consolidate(entries: MemoryEntry[]): ConsolidateResult {\n const startTime = Date.now();\n const originalCount = entries.length;\n\n // Step 1: Remove fully decayed entries (decay ≥ 0.95)\n const now = Date.now();\n const nonDecayed = entries.filter((entry) => {\n const ageInSeconds = (now - entry.timestamp) / 1000;\n const decay = scorer.calculateDecay(ageInSeconds, entry.ttl);\n return decay < 0.95; // Keep entries with decay < 0.95\n });\n\n const decayedRemoved = originalCount - nonDecayed.length;\n\n // Step 2: Find and merge duplicates\n const duplicateGroups = findDuplicates(nonDecayed);\n const merged = mergeDuplicates(duplicateGroups);\n\n // Step 3: Keep non-duplicates\n const duplicateIds = new Set(duplicateGroups.flatMap((g) => g.entries.map((e) => e.id)));\n const nonDuplicates = nonDecayed.filter((e) => !duplicateIds.has(e.id));\n\n // Combine merged duplicates with non-duplicates\n const kept = [...merged, ...nonDuplicates];\n const removed = entries.filter((e) => !kept.some((k) => k.id === e.id));\n\n const duplicatesRemoved = duplicateGroups.reduce((sum, g) => sum + (g.entries.length - 1), 0);\n\n return {\n kept,\n removed,\n entriesBefore: originalCount,\n entriesAfter: kept.length,\n decayedRemoved,\n duplicatesRemoved,\n compressionRatio: originalCount > 0 ? kept.length / originalCount : 0,\n durationMs: Date.now() - startTime,\n };\n }\n\n function findDuplicates(entries: MemoryEntry[]): DuplicateGroup[] {\n const groups: DuplicateGroup[] = [];\n const processed = new Set<string>();\n\n // Find exact hash matches\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (!entry || processed.has(entry.id)) continue;\n\n const duplicates = entries.filter((e, idx) => idx !== i && e.hash === entry.hash);\n\n if (duplicates.length > 0) {\n const group: DuplicateGroup = {\n entries: [entry, ...duplicates],\n similarity: 1.0, // Exact match\n };\n groups.push(group);\n\n // Mark as processed\n processed.add(entry.id);\n for (const dup of duplicates) {\n processed.add(dup.id);\n }\n }\n }\n\n // Find near-duplicates (cosine similarity ≥ 0.85)\n for (let i = 0; i < entries.length; i++) {\n const entryI = entries[i];\n if (!entryI || processed.has(entryI.id)) continue;\n\n for (let j = i + 1; j < entries.length; j++) {\n const entryJ = entries[j];\n if (!entryJ || processed.has(entryJ.id)) continue;\n\n const similarity = cosineSimilarity(entryI.content, entryJ.content);\n\n if (similarity >= 0.85) {\n const group: DuplicateGroup = {\n entries: [entryI, entryJ],\n similarity,\n };\n groups.push(group);\n\n processed.add(entryI.id);\n processed.add(entryJ.id);\n break; // Move to next i\n }\n }\n }\n\n return groups;\n }\n\n function mergeDuplicates(groups: DuplicateGroup[]): MemoryEntry[] {\n const merged: MemoryEntry[] = [];\n\n for (const group of groups) {\n // Keep entry with highest score\n const sorted = [...group.entries].sort((a, b) => b.score - a.score);\n const best = sorted[0];\n if (!best) continue; // Skip empty groups\n\n // Sum access counts\n const totalAccessCount = group.entries.reduce((sum, e) => sum + e.accessCount, 0);\n\n // Merge tags\n const allTags = new Set(group.entries.flatMap((e) => e.tags));\n\n merged.push({\n ...best,\n accessCount: totalAccessCount,\n tags: Array.from(allTags),\n });\n }\n\n return merged;\n }\n\n /**\n * Calculate cosine similarity between two text strings\n * @param text1 - First text\n * @param text2 - Second text\n * @returns Similarity score (0.0-1.0)\n */\n function cosineSimilarity(text1: string, text2: string): number {\n const words1 = tokenize(text1);\n const words2 = tokenize(text2);\n\n // Build vocabulary\n const vocab = new Set([...words1, ...words2]);\n\n // Build word frequency vectors\n const vec1: Record<string, number> = {};\n const vec2: Record<string, number> = {};\n\n for (const word of vocab) {\n vec1[word] = words1.filter((w) => w === word).length;\n vec2[word] = words2.filter((w) => w === word).length;\n }\n\n // Calculate dot product and magnitudes\n let dotProduct = 0;\n let mag1 = 0;\n let mag2 = 0;\n\n for (const word of vocab) {\n const count1 = vec1[word] ?? 0;\n const count2 = vec2[word] ?? 0;\n dotProduct += count1 * count2;\n mag1 += count1 * count1;\n mag2 += count2 * count2;\n }\n\n mag1 = Math.sqrt(mag1);\n mag2 = Math.sqrt(mag2);\n\n if (mag1 === 0 || mag2 === 0) return 0;\n\n return dotProduct / (mag1 * mag2);\n }\n\n function tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/\\s+/)\n .filter((word) => word.length > 0);\n }\n\n return {\n consolidate,\n findDuplicates,\n mergeDuplicates,\n };\n}\n","/**\n * Configuration types for Sparn behavior customization.\n */\n\n/**\n * Agent adapter type.\n */\nexport type AgentType = 'claude-code' | 'generic';\n\n/**\n * Pruning configuration.\n */\nexport interface PruningConfig {\n /** Percentage of top-scored entries to keep (1-100, default: 5) */\n threshold: number;\n\n /** Aggressiveness scale 0-100 (affects TF-IDF weighting, default: 50) */\n aggressiveness: number;\n}\n\n/**\n * Decay configuration.\n */\nexport interface DecayConfig {\n /** Default TTL in hours (default: 24) */\n defaultTTL: number;\n\n /** Decay threshold for pruning (0.0-1.0, default: 0.95) */\n decayThreshold: number;\n}\n\n/**\n * Confidence state threshold configuration.\n */\nexport interface StatesConfig {\n /** Score threshold for active state (default: 0.7) */\n activeThreshold: number;\n\n /** Score threshold for ready state (default: 0.3) */\n readyThreshold: number;\n}\n\n/**\n * UI configuration.\n */\nexport interface UIConfig {\n /** Enable colored output (default: true) */\n colors: boolean;\n\n /** Enable sound effects (default: false) */\n sounds: boolean;\n\n /** Verbose logging (default: false) */\n verbose: boolean;\n}\n\n/**\n * Real-time optimization configuration.\n */\nexport interface RealtimeConfig {\n /** Target token budget for optimized context (default: 50000) */\n tokenBudget: number;\n\n /** Token threshold that triggers auto-optimization (default: 60000) */\n autoOptimizeThreshold: number;\n\n /** File patterns to watch for changes (default: ['**\\/*.jsonl']) */\n watchPatterns: string[];\n\n /** Daemon PID file path (default: '.sparn/daemon.pid') */\n pidFile: string;\n\n /** Daemon log file path (default: '.sparn/daemon.log') */\n logFile: string;\n\n /** Debounce delay in milliseconds for file changes (default: 5000) */\n debounceMs: number;\n\n /** Enable incremental optimization (default: true) */\n incremental: boolean;\n\n /** Sliding window size for context entries (default: 500) */\n windowSize: number;\n\n /** Consolidation interval in hours, or null for disabled (default: null) */\n consolidationInterval: number | null;\n}\n\n/**\n * Complete Sparn configuration.\n */\nexport interface SparnConfig {\n pruning: PruningConfig;\n decay: DecayConfig;\n states: StatesConfig;\n agent: AgentType;\n ui: UIConfig;\n /** Auto-consolidation interval in hours, or null for manual */\n autoConsolidate: number | null;\n /** Real-time optimization settings */\n realtime: RealtimeConfig;\n}\n\n/**\n * Default configuration values.\n */\nexport const DEFAULT_CONFIG: SparnConfig = {\n pruning: {\n threshold: 5,\n aggressiveness: 50,\n },\n decay: {\n defaultTTL: 24,\n decayThreshold: 0.95,\n },\n states: {\n activeThreshold: 0.7,\n readyThreshold: 0.3,\n },\n agent: 'generic',\n ui: {\n colors: true,\n sounds: false,\n verbose: false,\n },\n autoConsolidate: null,\n realtime: {\n tokenBudget: 40000,\n autoOptimizeThreshold: 60000,\n watchPatterns: ['**/*.jsonl'],\n pidFile: '.sparn/daemon.pid',\n logFile: '.sparn/daemon.log',\n debounceMs: 5000,\n incremental: true,\n windowSize: 500,\n consolidationInterval: null,\n },\n};\n"],"mappings":";;;AAiBA,SAAS,iBAAiB;AAC1B,SAAS,SAAS,eAAe;AACjC,SAAS,4BAA4B;;;ACbrC,SAAS,cAAc,kBAAkB;AACzC,OAAO,cAAc;AAuDrB,SAAS,aAAa,QAAwB;AAC5C,QAAM,aAAY,oBAAI,KAAK,GAAE,YAAY,EAAE,QAAQ,SAAS,GAAG;AAC/D,QAAM,aAAa,GAAG,MAAM,WAAW,SAAS;AAEhD,MAAI;AACF,iBAAa,QAAQ,UAAU;AAC/B,YAAQ,IAAI,iCAA4B,UAAU,EAAE;AACpD,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,MAAM,qCAAqC,KAAK,EAAE;AAC1D,WAAO;AAAA,EACT;AACF;AAYA,eAAsB,eAAe,QAAmC;AAEtE,MAAI;AACJ,MAAI;AACF,SAAK,IAAI,SAAS,MAAM;AAGxB,UAAM,iBAAiB,GAAG,OAAO,eAAe,EAAE,QAAQ,KAAK,CAAC;AAChE,QAAI,mBAAmB,MAAM;AAC3B,cAAQ,MAAM,sCAAiC;AAG/C,UAAI,WAAW,MAAM,GAAG;AACtB,cAAM,aAAa,aAAa,MAAM;AACtC,YAAI,YAAY;AACd,kBAAQ,IAAI,sBAAsB,UAAU,EAAE;AAAA,QAChD;AAAA,MACF;AAGA,cAAQ,IAAI,iCAAiC;AAC7C,SAAG,MAAM;AACT,WAAK,IAAI,SAAS,MAAM;AAAA,IAC1B;AAAA,EACF,SAAS,OAAO;AACd,YAAQ,M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