@ulrichc1/sparn 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/PRIVACY.md +350 -0
- package/README.md +683 -0
- package/SECURITY.md +247 -0
- package/dist/cli/index.cjs +1897 -0
- package/dist/cli/index.cjs.map +1 -0
- package/dist/cli/index.d.cts +1 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +1868 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/index.cjs +948 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +567 -0
- package/dist/index.d.ts +567 -0
- package/dist/index.js +900 -0
- package/dist/index.js.map +1 -0
- package/package.json +77 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../node_modules/tsup/assets/cjs_shims.js","../../src/cli/ui/colors.ts","../../src/cli/ui/banner.ts","../../src/core/kv-memory.ts","../../src/types/config.ts","../../src/cli/commands/init.ts","../../src/cli/ui/progress.ts","../../src/utils/hash.ts","../../src/core/btsp-embedder.ts","../../src/core/confidence-states.ts","../../src/core/engram-scorer.ts","../../src/utils/tokenizer.ts","../../src/core/sparse-pruner.ts","../../src/adapters/generic.ts","../../src/cli/commands/optimize.ts","../../src/cli/commands/stats.ts","../../src/cli/commands/relay.ts","../../src/core/sleep-compressor.ts","../../src/cli/commands/consolidate.ts","../../src/cli/commands/config.ts","../../src/cli/index.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","/**\n * Brand color constants.\n * Per Article VIII: Brand Consistency.\n */\n\nimport chalk from 'chalk';\n\n/**\n * Neural Cyan (#00D4AA) - Success, active operations\n */\nexport const neuralCyan = chalk.hex('#00D4AA');\n\n/**\n * Synapse Violet (#7B61FF) - Highlights, graphs, numbers\n */\nexport const synapseViolet = chalk.hex('#7B61FF');\n\n/**\n * Error Red (#FF6B6B) - Failures, pruned items\n */\nexport const errorRed = chalk.hex('#FF6B6B');\n\n/**\n * Brain Pink (#FF6B9D) - Logo color, brain-related messages, key branding\n */\nexport const brainPink = chalk.hex('#FF6B9D');\n\n/**\n * Dimmed text for secondary information\n */\nexport const dim = chalk.dim;\n\n/**\n * Bold text for emphasis\n */\nexport const bold = chalk.bold;\n","/**\n * ASCII banner for Sparn CLI.\n * Displayed on `sparn init` and `sparn --version`.\n */\n\nimport { brainPink, neuralCyan, synapseViolet } from './colors.js';\n\n/**\n * Sparn ASCII banner.\n */\nexport const BANNER = `\n ____ ____ ___ ____ _ __\n / ___\\\\/ __ \\\\/ _ \\\\ / __ \\\\/ | / /\n \\\\__ \\\\/ /_/ / /_\\\\ \\\\/ /_/ / |/ /\n ___/ / ____/ __ _/ _, _/ /| /\n/____/_/ /_/ |_/_/ |_/_/ |_/\n`;\n\n/**\n * Tagline for banner.\n */\nexport const TAGLINE = '๐ง Neuroscience-inspired context optimization';\n\n/**\n * Get formatted banner with color.\n *\n * @param version - Optional version string\n * @returns Formatted banner\n */\nexport function getBanner(version?: string): string {\n const versionStr = version ? synapseViolet(`v${version}`) : '';\n return `${neuralCyan(BANNER)}\\n${brainPink(TAGLINE)}\\n${versionStr ? `${versionStr}\\n` : ''}`;\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 * 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 * 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}\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};\n","/**\n * Init command implementation.\n * Creates .sparn/ directory with config and database.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { access, mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { dump as dumpYAML } from 'js-yaml';\nimport { createKVMemory } from '../../core/kv-memory.js';\nimport { DEFAULT_CONFIG } from '../../types/config.js';\nimport { getBanner } from '../ui/banner.js';\nimport { brainPink, dim, neuralCyan } from '../ui/colors.js';\n\n// Get package.json version from project root\nfunction getVersion(): string {\n try {\n // Try from current working directory first\n const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf-8'));\n return pkg.version;\n } catch {\n // Fallback: calculate from module location\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const pkg = JSON.parse(readFileSync(join(__dirname, '../../../package.json'), 'utf-8'));\n return pkg.version;\n }\n}\n\nconst VERSION = getVersion();\n\n/**\n * Options for init command.\n */\nexport interface InitOptions {\n /** Force overwrite if .sparn/ exists */\n force?: boolean;\n /** Current working directory */\n cwd?: string;\n}\n\n/**\n * Result of init operation.\n */\nexport interface InitResult {\n /** Path to created config file */\n configPath: string;\n\n /** Path to created database */\n dbPath: string;\n\n /** Initialization duration (ms) */\n durationMs: number;\n}\n\n/**\n * Execute init command.\n *\n * Creates .sparn/ directory with:\n * - config.yaml (default configuration)\n * - memory.db (SQLite database)\n *\n * @param options - Init options\n * @returns Init result\n */\nexport async function initCommand(options: InitOptions = {}): Promise<InitResult> {\n const startTime = Date.now();\n const cwd = options.cwd || process.cwd();\n const sparnDir = join(cwd, '.sparn');\n const configPath = join(sparnDir, 'config.yaml');\n const dbPath = join(sparnDir, 'memory.db');\n\n // Check if .sparn/ already exists\n const exists = await checkExists(sparnDir);\n\n if (exists && !options.force) {\n throw new Error(\n '.sparn/ directory already exists. Use --force to overwrite or run from a different directory.',\n );\n }\n\n // Create .sparn/ directory\n await mkdir(sparnDir, { recursive: true });\n\n // Create config.yaml with defaults\n const configYAML = dumpYAML(DEFAULT_CONFIG, {\n indent: 2,\n lineWidth: 100,\n });\n\n const configWithComments = `# Sparn Configuration\n# See https://github.com/ulrichc1/sparn for documentation\n\n${configYAML}`;\n\n await writeFile(configPath, configWithComments, 'utf8');\n\n // Initialize database\n const memory = await createKVMemory(dbPath);\n await memory.close();\n\n const durationMs = Date.now() - startTime;\n\n return {\n configPath,\n dbPath,\n durationMs,\n };\n}\n\n/**\n * Display init success message with banner.\n *\n * @param result - Init result\n */\nexport function displayInitSuccess(result: InitResult): void {\n console.log(getBanner(VERSION));\n\n console.log(`\\n${brainPink('โ'.repeat(60))}`);\n console.log(brainPink(' ๐ง Sparn Initialized Successfully!'));\n console.log(brainPink('โ'.repeat(60)));\n\n console.log(`\\n ${neuralCyan('Config:')} ${dim(result.configPath)}`);\n console.log(` ${neuralCyan('Database:')} ${dim(result.dbPath)}`);\n console.log(` ${neuralCyan('Time:')} ${dim(`${result.durationMs}ms`)}`);\n\n console.log(\n `\\n ${brainPink('โ')} Run ${neuralCyan(\"'sparn optimize'\")} to start optimizing context!`,\n );\n console.log(`${brainPink('โ'.repeat(60))}\\n`);\n}\n\n/**\n * Check if path exists.\n */\nasync function checkExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Progress indicators for long-running operations.\n * Uses ora spinners with branded colors.\n */\n\nimport ora, { type Ora } from 'ora';\nimport { brainPink, neuralCyan, synapseViolet } from './colors.js';\n\n/**\n * Create a spinner for optimization operations.\n *\n * @param text - Initial spinner text\n * @returns Ora spinner instance\n */\nexport function createOptimizeSpinner(text: string): Ora {\n return ora({\n text,\n color: 'cyan',\n spinner: 'dots12',\n });\n}\n\n/**\n * Create a spinner for memory consolidation.\n *\n * @param text - Initial spinner text\n * @returns Ora spinner instance\n */\nexport function createConsolidateSpinner(text: string): Ora {\n return ora({\n text,\n color: 'magenta',\n spinner: 'material',\n });\n}\n\n/**\n * Create a spinner for stats generation.\n *\n * @param text - Initial spinner text\n * @returns Ora spinner instance\n */\nexport function createStatsSpinner(text: string): Ora {\n return ora({\n text,\n color: 'yellow',\n spinner: 'bouncingBar',\n });\n}\n\n/**\n * Create a spinner for initialization.\n *\n * @param text - Initial spinner text\n * @returns Ora spinner instance\n */\nexport function createInitSpinner(text: string): Ora {\n return ora({\n text,\n color: 'green',\n spinner: 'star',\n });\n}\n\n/**\n * Show token savings with visual impact.\n * Displays before โ after with percentage and celebratory message.\n *\n * @param tokensBefore - Tokens before optimization\n * @param tokensAfter - Tokens after optimization\n * @param reduction - Reduction percentage (0.0-1.0)\n */\nexport function showTokenSavings(\n tokensBefore: number,\n tokensAfter: number,\n reduction: number,\n): void {\n const saved = tokensBefore - tokensAfter;\n const reductionPercent = (reduction * 100).toFixed(1);\n\n console.log(`\\n${brainPink('โ'.repeat(60))}`);\n console.log(neuralCyan(' ๐ Token Optimization Results'));\n console.log(brainPink('โ'.repeat(60)));\n\n // Before โ After\n console.log(` ${synapseViolet('Before:')} ${tokensBefore.toLocaleString()} tokens`);\n console.log(` ${neuralCyan('After:')} ${tokensAfter.toLocaleString()} tokens`);\n console.log(brainPink(' โ'.repeat(30)));\n\n // Savings\n console.log(` ${brainPink('Saved:')} ${saved.toLocaleString()} tokens (${reductionPercent}%)`);\n\n // Progress bar\n const barLength = 40;\n const savedBars = Math.floor(reduction * barLength);\n const keptBars = barLength - savedBars;\n const progressBar = neuralCyan('โ'.repeat(keptBars)) + brainPink('โ'.repeat(savedBars));\n console.log(` [${progressBar}] ${reductionPercent}% reduced`);\n\n // Celebratory message\n if (reduction >= 0.9) {\n console.log(`\\n ${brainPink('โจ OUTSTANDING!')} Mind-blowing 90%+ reduction!`);\n } else if (reduction >= 0.7) {\n console.log(`\\n ${neuralCyan('๐ EXCELLENT!')} Strong 70%+ token savings!`);\n } else if (reduction >= 0.5) {\n console.log(`\\n ${synapseViolet('๐ GOOD!')} Solid 50%+ optimization!`);\n } else if (reduction > 0) {\n console.log(`\\n ${neuralCyan('โ')} Tokens optimized successfully!`);\n }\n\n console.log(`${brainPink('โ'.repeat(60))}\\n`);\n}\n\n/**\n * Show consolidation summary with visual impact.\n *\n * @param entriesBefore - Entries before consolidation\n * @param entriesAfter - Entries after consolidation\n * @param decayed - Decayed entries removed\n * @param duplicates - Duplicate entries merged\n * @param durationMs - Duration in milliseconds\n */\nexport function showConsolidationSummary(\n entriesBefore: number,\n entriesAfter: number,\n decayed: number,\n duplicates: number,\n durationMs: number,\n): void {\n const removed = entriesBefore - entriesAfter;\n const compressionRatio = entriesBefore > 0 ? ((removed / entriesBefore) * 100).toFixed(1) : '0.0';\n\n console.log(`\\n${brainPink('โ'.repeat(60))}`);\n console.log(neuralCyan(' ๐งน Memory Consolidation Complete'));\n console.log(brainPink('โ'.repeat(60)));\n\n // Before โ After\n console.log(` ${synapseViolet('Before:')} ${entriesBefore.toLocaleString()} entries`);\n console.log(` ${neuralCyan('After:')} ${entriesAfter.toLocaleString()} entries`);\n console.log(brainPink(' โ'.repeat(30)));\n\n // Details\n console.log(` ${brainPink('Decayed:')} ${decayed.toLocaleString()} removed`);\n console.log(` ${brainPink('Duplicates:')} ${duplicates.toLocaleString()} merged`);\n console.log(` ${neuralCyan('Total:')} ${removed.toLocaleString()} entries freed`);\n console.log(` ${synapseViolet('Time:')} ${durationMs}ms`);\n\n // Progress bar\n const barLength = 40;\n const compressionBars = Math.floor((removed / entriesBefore) * barLength);\n const keptBars = barLength - compressionBars;\n const progressBar = neuralCyan('โ'.repeat(keptBars)) + brainPink('โ'.repeat(compressionBars));\n console.log(` [${progressBar}] ${compressionRatio}% compressed`);\n\n // Celebratory message\n if (removed > 0) {\n console.log(`\\n ${brainPink('โจ')} Memory optimized and ready for peak performance!`);\n } else {\n console.log(`\\n ${neuralCyan('โ')} Memory already optimal!`);\n }\n\n console.log(`${brainPink('โ'.repeat(60))}\\n`);\n}\n\n/**\n * Show initialization success with branded message.\n *\n * @param message - Success message\n */\nexport function showInitSuccess(message: string): void {\n console.log(`\\n${brainPink('โ'.repeat(60))}`);\n console.log(brainPink(' ๐ง Sparn Initialized Successfully!'));\n console.log(brainPink('โ'.repeat(60)));\n console.log(` ${neuralCyan(message)}`);\n console.log(`${brainPink('โ'.repeat(60))}\\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 * 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 * 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 * 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 * Optimize Command - Apply neuroscience-inspired optimization to context\n */\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { createGenericAdapter } from '../../adapters/generic.js';\nimport type { KVMemory } from '../../core/kv-memory.js';\nimport type { OptimizationResult } from '../../types/adapter.js';\nimport { DEFAULT_CONFIG } from '../../types/config.js';\n\nexport interface OptimizeCommandOptions {\n /** Input context (if not provided, reads from stdin) */\n input?: string;\n /** Input file path */\n inputFile?: string;\n /** Output file path (if not provided, writes to stdout) */\n outputFile?: string;\n /** Memory store instance */\n memory: KVMemory;\n /** Dry run mode (don't save to memory) */\n dryRun?: boolean;\n /** Verbose mode (show per-entry details) */\n verbose?: boolean;\n}\n\nexport interface OptimizeCommandResult extends OptimizationResult {\n output: string;\n outputFile?: string;\n}\n\n/**\n * Execute the optimize command\n * @param options - Command options\n * @returns Optimization result\n */\nexport async function optimizeCommand(\n options: OptimizeCommandOptions,\n): Promise<OptimizeCommandResult> {\n const { memory, dryRun = false, verbose = false } = options;\n\n // Read input from file or direct input\n let input: string;\n if (options.inputFile) {\n input = await readFile(options.inputFile, 'utf-8');\n } else if (options.input) {\n input = options.input;\n } else {\n throw new Error('No input provided. Use --input or --input-file');\n }\n\n // Create adapter and optimize\n const adapter = createGenericAdapter(memory, DEFAULT_CONFIG);\n const result = await adapter.optimize(input, { dryRun, verbose });\n\n // Write output to file or return\n if (options.outputFile) {\n await writeFile(options.outputFile, result.optimizedContext, 'utf-8');\n }\n\n return {\n ...result,\n output: result.optimizedContext,\n outputFile: options.outputFile,\n };\n}\n","/**\n * Stats Command - View optimization statistics\n */\n\nimport type { KVMemory } from '../../core/kv-memory.js';\n\nexport interface StatsCommandOptions {\n /** Memory store instance */\n memory: KVMemory;\n /** Display ASCII bar chart */\n graph?: boolean;\n /** Reset statistics */\n reset?: boolean;\n /** Auto-confirm reset (for testing) */\n confirmReset?: boolean;\n /** Output JSON format */\n json?: boolean;\n}\n\nexport interface StatsCommandResult {\n /** Total number of optimization commands run */\n totalCommands: number;\n /** Total tokens saved across all optimizations */\n totalTokensSaved: number;\n /** Average reduction percentage (0.0-1.0) */\n averageReduction: number;\n /** ASCII bar chart (if graph=true) */\n graph?: string;\n /** JSON output (if json=true) */\n json?: string;\n /** Reset was confirmed (if reset=true) */\n resetConfirmed?: boolean;\n}\n\n/**\n * Execute the stats command\n * @param options - Command options\n * @returns Statistics result\n */\nexport async function statsCommand(options: StatsCommandOptions): Promise<StatsCommandResult> {\n const { memory, graph, reset, confirmReset, json } = options;\n\n // Handle reset\n if (reset) {\n if (confirmReset) {\n await memory.clearOptimizationStats();\n return {\n totalCommands: 0,\n totalTokensSaved: 0,\n averageReduction: 0,\n resetConfirmed: true,\n };\n }\n }\n\n // Get optimization stats from database\n const stats = await memory.getOptimizationStats();\n\n // Calculate aggregations\n const totalCommands = stats.length;\n\n const totalTokensSaved = stats.reduce((sum, s) => sum + (s.tokens_before - s.tokens_after), 0);\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 result: StatsCommandResult = {\n totalCommands,\n totalTokensSaved,\n averageReduction,\n };\n\n // Generate ASCII bar chart if requested\n if (graph && totalCommands > 0) {\n result.graph = generateBarChart(stats);\n }\n\n // Generate JSON output if requested\n if (json) {\n result.json = JSON.stringify(\n {\n totalCommands,\n totalTokensSaved,\n averageReduction: Math.round(averageReduction * 1000) / 10, // Convert to percentage\n optimizations: stats.map((s) => ({\n timestamp: s.timestamp,\n tokensBefore: s.tokens_before,\n tokensAfter: s.tokens_after,\n entriesPruned: s.entries_pruned,\n durationMs: s.duration_ms,\n reduction: Math.round(((s.tokens_before - s.tokens_after) / s.tokens_before) * 1000) / 10,\n })),\n },\n null,\n 2,\n );\n }\n\n return result;\n}\n\n/**\n * Generate ASCII bar chart for optimization history\n * @param stats - Optimization statistics\n * @returns ASCII bar chart string\n */\nfunction generateBarChart(\n stats: Array<{ tokens_before: number; tokens_after: number; timestamp: number }>,\n): string {\n const maxBars = 20; // Maximum number of bars to display\n const recentStats = stats.slice(0, maxBars);\n\n const lines: string[] = [];\n lines.push('\\nOptimization History (most recent first):\\n');\n\n // Find max reduction for scaling\n const maxReduction = Math.max(...recentStats.map((s) => s.tokens_before - s.tokens_after));\n\n for (let i = 0; i < recentStats.length; i++) {\n const s = recentStats[i];\n if (!s) continue; // Skip undefined entries\n\n const reduction = s.tokens_before - s.tokens_after;\n const reductionPct = s.tokens_before > 0 ? (reduction / s.tokens_before) * 100 : 0;\n\n // Scale bar length (max 40 chars)\n const barLength = Math.round((reduction / maxReduction) * 40);\n const bar = 'โ'.repeat(barLength);\n\n // Format timestamp\n const date = new Date(s.timestamp);\n const timeStr = date.toLocaleTimeString();\n\n lines.push(`${timeStr} โ ${bar} ${reductionPct.toFixed(1)}%`);\n }\n\n return lines.join('\\n');\n}\n","/**\n * Relay Command - Proxy CLI commands through optimization\n */\n\nimport { spawn } from 'node:child_process';\nimport { createGenericAdapter } from '../../adapters/generic.js';\nimport type { KVMemory } from '../../core/kv-memory.js';\nimport { DEFAULT_CONFIG } from '../../types/config.js';\n\nexport interface RelayCommandOptions {\n /** Command to execute */\n command: string;\n /** Command arguments */\n args: string[];\n /** Memory store instance */\n memory: KVMemory;\n /** Silent mode (suppress summary) */\n silent?: boolean;\n}\n\nexport interface RelayCommandResult {\n /** Exit code from proxied command */\n exitCode: number;\n /** Original command output */\n originalOutput: string;\n /** Optimized output */\n optimizedOutput: string;\n /** Original token count */\n tokensBefore: number;\n /** Optimized token count */\n tokensAfter: number;\n /** Token reduction percentage */\n reduction: number;\n /** One-line summary (if not silent) */\n summary?: string;\n}\n\n/**\n * Execute a command and optimize its output\n * @param options - Command options\n * @returns Relay result\n */\nexport async function relayCommand(options: RelayCommandOptions): Promise<RelayCommandResult> {\n const { command, args, memory, silent = false } = options;\n\n // Execute child process and capture output\n const { stdout, stderr, exitCode } = await executeCommand(command, args);\n\n // Combine stdout and stderr\n const originalOutput = stdout + stderr;\n\n // Optimize the output\n const adapter = createGenericAdapter(memory, DEFAULT_CONFIG);\n const optimizationResult = await adapter.optimize(originalOutput, {\n dryRun: true, // Don't save relay outputs to memory\n verbose: false,\n });\n\n const result: RelayCommandResult = {\n exitCode,\n originalOutput,\n optimizedOutput: optimizationResult.optimizedContext,\n tokensBefore: optimizationResult.tokensBefore,\n tokensAfter: optimizationResult.tokensAfter,\n reduction: optimizationResult.reduction,\n };\n\n // Generate summary if not silent\n if (!silent && result.tokensBefore > 0) {\n const reductionPct = (result.reduction * 100).toFixed(1);\n result.summary = `๐ ${result.tokensBefore} โ ${result.tokensAfter} tokens (${reductionPct}% reduction)`;\n }\n\n return result;\n}\n\n/**\n * Execute a command and capture its output\n * @param command - Command to execute\n * @param args - Command arguments\n * @returns Command output and exit code\n */\nfunction executeCommand(\n command: string,\n args: string[],\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n let stdout = '';\n let stderr = '';\n\n child.stdout?.on('data', (data) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n resolve({\n stdout,\n stderr,\n exitCode: code ?? 0,\n });\n });\n\n child.on('error', (error) => {\n resolve({\n stdout,\n stderr: error.message,\n exitCode: 1,\n });\n });\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 * Consolidate Command - Periodic memory consolidation\n */\n\nimport type { KVMemory } from '../../core/kv-memory.js';\nimport { createSleepCompressor } from '../../core/sleep-compressor.js';\n\nexport interface ConsolidateCommandOptions {\n /** Memory store instance */\n memory: KVMemory;\n}\n\nexport interface ConsolidateCommandResult {\n /** Entries before consolidation */\n entriesBefore: number;\n /** Entries after consolidation */\n entriesAfter: number;\n /** Decayed entries removed */\n decayedRemoved: number;\n /** Duplicate entries merged */\n duplicatesRemoved: number;\n /** Compression ratio (0.0-1.0) */\n compressionRatio: number;\n /** Duration in milliseconds */\n durationMs: number;\n /** VACUUM completed */\n vacuumCompleted: boolean;\n}\n\n/**\n * Execute the consolidate command\n * @param options - Command options\n * @returns Consolidation result\n */\nexport async function consolidateCommand(\n options: ConsolidateCommandOptions,\n): Promise<ConsolidateCommandResult> {\n const { memory } = options;\n\n // Get all entries from memory\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 // Filter out nulls\n const entries = allEntries.filter((e) => e !== null);\n\n // Run consolidation\n const compressor = createSleepCompressor();\n const result = compressor.consolidate(entries);\n\n // Update memory: remove old entries, keep consolidated ones\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 space\n await memory.compact();\n\n return {\n entriesBefore: result.entriesBefore,\n entriesAfter: result.entriesAfter,\n decayedRemoved: result.decayedRemoved,\n duplicatesRemoved: result.duplicatesRemoved,\n compressionRatio: result.compressionRatio,\n durationMs: result.durationMs,\n vacuumCompleted: true,\n };\n}\n","/**\n * Config Command - View or modify configuration\n */\n\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { load as parseYAML, dump as stringifyYAML } from 'js-yaml';\nimport type { SparnConfig } from '../../types/config.js';\n\nexport interface ConfigCommandOptions {\n /** Path to config.yaml file */\n configPath: string;\n /** Subcommand: get or set */\n subcommand?: 'get' | 'set';\n /** Config key (dotted path) */\n key?: string;\n /** Config value (for set) */\n value?: string;\n /** Output JSON format */\n json?: boolean;\n}\n\nexport interface ConfigCommandResult {\n /** Command succeeded */\n success: boolean;\n /** Result message */\n message?: string;\n /** Error message */\n error?: string;\n /** Retrieved value (for get) */\n value?: unknown;\n /** Editor path (for no subcommand) */\n editorPath?: string;\n /** JSON output */\n json?: string;\n}\n\n/**\n * Valid config keys with their validation rules\n */\nconst CONFIG_SCHEMA: Record<\n string,\n {\n path: string[];\n validate: (value: unknown) => boolean;\n errorMessage: string;\n parse: (value: string) => unknown;\n }\n> = {\n 'pruning.threshold': {\n path: ['pruning', 'threshold'],\n validate: (v) => typeof v === 'number' && v >= 1 && v <= 100,\n errorMessage: 'threshold must be between 1-100',\n parse: (v) => Number.parseInt(v, 10),\n },\n 'pruning.aggressiveness': {\n path: ['pruning', 'aggressiveness'],\n validate: (v) => typeof v === 'number' && v >= 0 && v <= 100,\n errorMessage: 'aggressiveness must be between 0-100',\n parse: (v) => Number.parseInt(v, 10),\n },\n 'decay.defaultTTL': {\n path: ['decay', 'defaultTTL'],\n validate: (v) => typeof v === 'number' && v > 0,\n errorMessage: 'defaultTTL must be a positive number (hours)',\n parse: (v) => Number.parseFloat(v),\n },\n 'decay.decayThreshold': {\n path: ['decay', 'decayThreshold'],\n validate: (v) => typeof v === 'number' && v >= 0.0 && v <= 1.0,\n errorMessage: 'decayThreshold must be between 0.0-1.0',\n parse: (v) => Number.parseFloat(v),\n },\n 'states.activeThreshold': {\n path: ['states', 'activeThreshold'],\n validate: (v) => typeof v === 'number' && v >= 0.0 && v <= 1.0,\n errorMessage: 'activeThreshold must be between 0.0-1.0',\n parse: (v) => Number.parseFloat(v),\n },\n 'states.readyThreshold': {\n path: ['states', 'readyThreshold'],\n validate: (v) => typeof v === 'number' && v >= 0.0 && v <= 1.0,\n errorMessage: 'readyThreshold must be between 0.0-1.0',\n parse: (v) => Number.parseFloat(v),\n },\n agent: {\n path: ['agent'],\n validate: (v) => v === 'claude-code' || v === 'generic',\n errorMessage: 'agent must be \"claude-code\" or \"generic\"',\n parse: (v) => v,\n },\n 'ui.colors': {\n path: ['ui', 'colors'],\n validate: (v) => typeof v === 'boolean',\n errorMessage: 'colors must be true or false',\n parse: (v) => v === 'true',\n },\n 'ui.sounds': {\n path: ['ui', 'sounds'],\n validate: (v) => typeof v === 'boolean',\n errorMessage: 'sounds must be true or false',\n parse: (v) => v === 'true',\n },\n 'ui.verbose': {\n path: ['ui', 'verbose'],\n validate: (v) => typeof v === 'boolean',\n errorMessage: 'verbose must be true or false',\n parse: (v) => v === 'true',\n },\n autoConsolidate: {\n path: ['autoConsolidate'],\n validate: (v) => v === null || (typeof v === 'number' && v > 0),\n errorMessage: 'autoConsolidate must be a positive number (hours) or null',\n parse: (v) => (v === 'null' ? null : Number.parseFloat(v)),\n },\n};\n\n/**\n * Execute the config command\n * @param options - Command options\n * @returns Config result\n */\nexport async function configCommand(options: ConfigCommandOptions): Promise<ConfigCommandResult> {\n const { configPath, subcommand, key, value, json } = options;\n\n try {\n // Read config file\n const configYAML = readFileSync(configPath, 'utf-8');\n const config = parseYAML(configYAML) as SparnConfig;\n\n // No subcommand: open editor or return JSON\n if (!subcommand) {\n if (json) {\n return {\n success: true,\n json: JSON.stringify(config, null, 2),\n };\n }\n return {\n success: true,\n editorPath: configPath,\n message: `Config file: ${configPath}`,\n };\n }\n\n // Get subcommand\n if (subcommand === 'get') {\n if (!key) {\n return {\n success: false,\n error: 'Key required for get command',\n };\n }\n\n const schema = CONFIG_SCHEMA[key];\n if (!schema) {\n return {\n success: false,\n error: `Invalid key: ${key}. Run 'sparn config' to see available keys.`,\n };\n }\n\n const retrievedValue = getNestedValue(\n config as unknown as Record<string, unknown>,\n schema.path,\n );\n\n if (json) {\n return {\n success: true,\n value: retrievedValue,\n json: JSON.stringify({ key, value: retrievedValue }, null, 2),\n };\n }\n\n return {\n success: true,\n value: retrievedValue,\n message: String(retrievedValue),\n };\n }\n\n // Set subcommand\n if (subcommand === 'set') {\n if (!key) {\n return {\n success: false,\n error: 'Key required for set command',\n };\n }\n\n if (value === undefined) {\n return {\n success: false,\n error: 'Value required for set command',\n };\n }\n\n const schema = CONFIG_SCHEMA[key];\n if (!schema) {\n return {\n success: false,\n error: `Invalid key: ${key}. Run 'sparn config' to see available keys.`,\n };\n }\n\n // Parse and validate value\n const parsedValue = schema.parse(value);\n if (!schema.validate(parsedValue)) {\n return {\n success: false,\n error: `Invalid value for ${key}: ${schema.errorMessage}`,\n };\n }\n\n // Update config\n setNestedValue(config as unknown as Record<string, unknown>, schema.path, parsedValue);\n\n // Write back to file\n const updatedYAML = stringifyYAML(config);\n writeFileSync(configPath, updatedYAML, 'utf-8');\n\n return {\n success: true,\n message: `Config updated: ${key} = ${parsedValue}`,\n };\n }\n\n return {\n success: false,\n error: `Unknown subcommand: ${subcommand}`,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\n/**\n * Get nested value from object using path array\n * @param obj - Object to query\n * @param path - Path array\n * @returns Nested value\n */\nfunction getNestedValue(obj: Record<string, unknown>, path: string[]): unknown {\n let current: unknown = obj;\n for (const key of path) {\n if (current && typeof current === 'object' && !Array.isArray(current) && key in current) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/**\n * Set nested value in object using path array\n * @param obj - Object to mutate\n * @param path - Path array\n * @param value - Value to set\n */\nfunction setNestedValue(obj: Record<string, unknown>, path: string[], value: unknown): void {\n let current: Record<string, unknown> = obj;\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i];\n if (!key) continue;\n\n if (!current[key] || typeof current[key] !== 'object') {\n current[key] = {};\n }\n current = current[key] as Record<string, unknown>;\n }\n\n const lastKey = path[path.length - 1];\n if (lastKey) {\n current[lastKey] = value;\n }\n}\n","#!/usr/bin/env node\n\n/**\n * Sparn CLI entry point.\n * Implements all CLI commands using Commander.js.\n */\n\nimport { spawn } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Command } from 'commander';\nimport { getBanner } from './ui/banner.js';\n\n// Get package.json version from project root\nfunction getVersion(): string {\n try {\n // Try from current working directory first (most common case)\n const pkg = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf-8'));\n return pkg.version;\n } catch {\n // Fallback: calculate from module location\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const pkg = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));\n return pkg.version;\n }\n}\n\nconst VERSION = getVersion();\n\n// Lazy-loaded imports (loaded only when commands are executed):\n// - createKVMemory (heavy: better-sqlite3)\n// - command implementations (may import heavy modules)\n// - progress spinners (heavy: ora)\n// - colors (chalk is reasonably lightweight, but lazy-load for consistency)\n\n/**\n * Global error handler for uncaught errors\n * Provides graceful degradation and helpful error messages\n */\nasync function handleError(error: Error | unknown, context?: string): Promise<void> {\n // Lazy-load colors\n const { errorRed, synapseViolet } = await import('./ui/colors.js');\n\n const errorMsg = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n // Display user-friendly error message\n console.error(errorRed('\\nโ Error:'), errorMsg);\n\n if (context) {\n console.error(errorRed('Context:'), context);\n }\n\n // Database errors - provide recovery suggestions\n if (errorMsg.includes('SQLITE') || errorMsg.includes('database')) {\n console.error(synapseViolet('\\n๐ก Database issue detected:'));\n console.error(' Try running: rm -rf .sparn/ && sparn init');\n console.error(' This will reinitialize your Sparn database.\\n');\n }\n\n // Permission errors\n if (errorMsg.includes('EACCES') || errorMsg.includes('permission')) {\n console.error(synapseViolet('\\n๐ก Permission issue detected:'));\n console.error(' Check file permissions in .sparn/ directory');\n console.error(' Try: chmod -R u+rw .sparn/\\n');\n }\n\n // File not found errors\n if (errorMsg.includes('ENOENT') || errorMsg.includes('no such file')) {\n console.error(synapseViolet('\\n๐ก File not found:'));\n console.error(' Make sure you have run: sparn init');\n console.error(' Or check that the specified file exists.\\n');\n }\n\n // Memory errors\n if (errorMsg.includes('out of memory') || errorMsg.includes('heap')) {\n console.error(synapseViolet('\\n๐ก Memory issue detected:'));\n console.error(' Try processing smaller chunks of context');\n console.error(' Or increase Node.js memory: NODE_OPTIONS=--max-old-space-size=4096\\n');\n }\n\n // Show stack trace in verbose mode\n if (process.env['SPARN_DEBUG'] === 'true' && stack) {\n console.error(errorRed('\\nStack trace:'));\n console.error(stack);\n } else {\n console.error(' Run with SPARN_DEBUG=true for stack trace\\n');\n }\n\n process.exit(1);\n}\n\n/**\n * Global unhandled rejection handler\n */\nprocess.on('unhandledRejection', (reason) => {\n void handleError(reason, 'Unhandled promise rejection');\n});\n\n/**\n * Global uncaught exception handler\n */\nprocess.on('uncaughtException', (error) => {\n void handleError(error, 'Uncaught exception');\n});\n\nconst program = new Command();\n\nprogram\n .name('sparn')\n .description('Neuroscience-inspired context optimization for AI coding agents')\n .version(VERSION, '-v, --version', 'Output the current version')\n .helpOption('-h, --help', 'Display help for command');\n\n// Init command\nprogram\n .command('init')\n .description('Initialize Sparn in the current project')\n .option('-f, --force', 'Force overwrite if .sparn/ already exists')\n .addHelpText(\n 'after',\n `\nExamples:\n $ sparn init # Initialize in current directory\n $ sparn init --force # Overwrite existing .sparn/ directory\n\nFiles Created:\n .sparn/config.yaml # Configuration with neuroscience parameters\n .sparn/memory.db # SQLite database for context storage\n\nNext Steps:\n After initialization, use 'sparn optimize' to start optimizing context.\n`,\n )\n .action(async (options) => {\n // Lazy-load dependencies\n const { initCommand, displayInitSuccess } = await import('./commands/init.js');\n const { createInitSpinner } = await import('./ui/progress.js');\n const { neuralCyan, errorRed } = await import('./ui/colors.js');\n\n const spinner = createInitSpinner('๐ง Initializing Sparn...');\n try {\n spinner.start();\n spinner.text = '๐ Creating .sparn/ directory...';\n const result = await initCommand({ force: options.force });\n spinner.succeed(neuralCyan('Sparn initialized successfully!'));\n displayInitSuccess(result);\n } catch (error) {\n spinner.fail(errorRed('Initialization failed'));\n console.error('Error:', error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n// Optimize command\nprogram\n .command('optimize')\n .description('Optimize context memory using neuroscience principles')\n .option('-i, --input <file>', 'Input file path')\n .option('-o, --output <file>', 'Output file path')\n .option('--dry-run', 'Run without saving to memory')\n .option('--verbose', 'Show detailed per-entry scores')\n .addHelpText(\n 'after',\n `\nExamples:\n $ sparn optimize -i context.txt -o optimized.txt # Optimize file\n $ cat context.txt | sparn optimize # Optimize from stdin\n $ sparn optimize -i context.txt --dry-run # Preview without saving\n $ sparn optimize -i context.txt --verbose # Show entry scores\n\nHow It Works:\n 1. Sparse Coding: Keeps only 2-5% most relevant context\n 2. Engram Theory: Applies decay to old memories\n 3. Multi-State Synapses: Classifies as silent/ready/active\n 4. BTSP: Locks critical events (errors, stack traces)\n 5. Sleep Replay: Consolidates and compresses\n\nTypical Results:\n โข 60-90% token reduction\n โข Preserved task-critical information\n โข Enhanced AI agent focus\n`,\n )\n .action(async (options) => {\n // Lazy-load dependencies\n const { createKVMemory } = await import('../core/kv-memory.js');\n const { optimizeCommand } = await import('./commands/optimize.js');\n const { createOptimizeSpinner, showTokenSavings } = await import('./ui/progress.js');\n const { neuralCyan, synapseViolet, errorRed } = await import('./ui/colors.js');\n\n const spinner = createOptimizeSpinner('๐ง Initializing optimization...');\n try {\n spinner.start();\n\n // Read from stdin if no input file specified\n let input: string | undefined;\n if (!options.input && process.stdin.isTTY === false) {\n spinner.text = '๐ Reading context from stdin...';\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk);\n }\n input = Buffer.concat(chunks).toString('utf-8');\n } else if (options.input) {\n spinner.text = `๐ Reading context from ${options.input}...`;\n }\n\n // Load memory\n spinner.text = '๐พ Loading memory database...';\n const dbPath = resolve(process.cwd(), '.sparn/memory.db');\n const memory = await createKVMemory(dbPath);\n\n // Run optimization\n spinner.text = 'โก Applying neuroscience principles...';\n const result = await optimizeCommand({\n input,\n inputFile: options.input,\n outputFile: options.output,\n memory,\n dryRun: options.dryRun || false,\n verbose: options.verbose || false,\n });\n\n spinner.succeed(neuralCyan(`Optimization complete in ${result.durationMs}ms!`));\n\n // Display visual impact\n showTokenSavings(result.tokensBefore, result.tokensAfter, result.reduction);\n\n // Show entry stats\n console.log(synapseViolet(' Entry Distribution:'));\n console.log(` โข Processed: ${result.entriesProcessed}`);\n console.log(` โข Kept: ${result.entriesKept}`);\n console.log(` โข Active: ${result.stateDistribution.active}`);\n console.log(` โข Ready: ${result.stateDistribution.ready}`);\n console.log(` โข Silent: ${result.stateDistribution.silent}\\n`);\n\n // Show verbose details if requested\n if (options.verbose && result.details) {\n console.log(neuralCyan(' ๐ Entry Details:'));\n for (const detail of result.details) {\n console.log(\n ` ${detail.id.substring(0, 8)}: score=${detail.score.toFixed(2)}, state=${detail.state}, tokens=${detail.tokens}`,\n );\n }\n console.log();\n }\n\n // Write to stdout if no output file\n if (!options.output) {\n console.log(result.output);\n }\n\n await memory.close();\n } catch (error) {\n spinner.fail(errorRed('Optimization failed'));\n console.error(errorRed('Error:'), error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n// Stats command\nprogram\n .command('stats')\n .description('View optimization statistics')\n .option('--graph', 'Display ASCII bar chart of optimization history')\n .option('--reset', 'Clear all optimization statistics')\n .option('--json', 'Output statistics in JSON format')\n .addHelpText(\n 'after',\n `\nExamples:\n $ sparn stats # View summary statistics\n $ sparn stats --graph # Show ASCII chart of optimization history\n $ sparn stats --json # Output as JSON for automation\n $ sparn stats --reset # Clear all statistics (with confirmation)\n\nTracked Metrics:\n โข Total optimizations performed\n โข Total tokens saved across all runs\n โข Average reduction percentage\n โข Per-run token before/after counts\n โข Optimization duration\n`,\n )\n .action(async (options) => {\n // Lazy-load dependencies\n const { createKVMemory } = await import('../core/kv-memory.js');\n const { statsCommand } = await import('./commands/stats.js');\n const { createStatsSpinner } = await import('./ui/progress.js');\n const { neuralCyan, synapseViolet, errorRed } = await import('./ui/colors.js');\n\n const spinner = options.graph ? createStatsSpinner('๐ Generating statistics...') : null;\n try {\n if (spinner) spinner.start();\n\n // Load memory\n if (spinner) spinner.text = '๐พ Loading optimization history...';\n const dbPath = resolve(process.cwd(), '.sparn/memory.db');\n const memory = await createKVMemory(dbPath);\n\n // Handle reset with confirmation\n let confirmReset = false;\n if (options.reset) {\n if (spinner) spinner.stop();\n console.log(synapseViolet('Warning: This will clear all optimization statistics.'));\n confirmReset = true; // Auto-confirm for now\n }\n\n // Get stats\n if (spinner) spinner.text = '๐ Calculating statistics...';\n const result = await statsCommand({\n memory,\n graph: options.graph || false,\n reset: options.reset || false,\n confirmReset,\n json: options.json || false,\n });\n\n if (spinner) spinner.succeed(neuralCyan('Statistics ready!'));\n\n // Display output\n if (options.json) {\n console.log(result.json);\n } else if (options.reset && result.resetConfirmed) {\n console.log(neuralCyan('\\nโ Statistics cleared\\n'));\n } else {\n // Display stats summary\n console.log(neuralCyan('\\n๐ Optimization Statistics\\n'));\n console.log(` Total optimizations: ${result.totalCommands}`);\n console.log(` Total tokens saved: ${result.totalTokensSaved.toLocaleString()}`);\n console.log(` Average reduction: ${(result.averageReduction * 100).toFixed(1)}%`);\n\n if (options.graph && result.graph) {\n console.log(result.graph);\n }\n\n console.log();\n }\n\n await memory.close();\n } catch (error) {\n if (spinner) spinner.fail(errorRed('Statistics failed'));\n console.error(errorRed('Error:'), error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n// Relay command\nprogram\n .command('relay <command> [args...]')\n .description('Proxy a CLI command through optimization')\n .option('--silent', 'Suppress token savings summary')\n .addHelpText(\n 'after',\n `\nExamples:\n $ sparn relay git log # Run 'git log' and optimize output\n $ sparn relay npm test # Run 'npm test' and optimize output\n $ sparn relay gh pr view 123 # Optimize GitHub CLI output\n $ sparn relay ls -la --silent # Suppress optimization summary\n\nUse Cases:\n โข Wrap verbose CLI commands (git log, gh pr view)\n โข Optimize test runner output\n โข Compress build logs\n โข Filter CI/CD output for AI agent consumption\n\nThe relay command passes the exit code from the wrapped command.\n`,\n )\n .action(async (command, args, options) => {\n // Lazy-load dependencies\n const { createKVMemory } = await import('../core/kv-memory.js');\n const { relayCommand } = await import('./commands/relay.js');\n const { neuralCyan, errorRed } = await import('./ui/colors.js');\n\n try {\n // Load memory\n const dbPath = resolve(process.cwd(), '.sparn/memory.db');\n const memory = await createKVMemory(dbPath);\n\n // Execute relay\n const result = await relayCommand({\n command,\n args: args || [],\n memory,\n silent: options.silent || false,\n });\n\n // Display optimized output\n console.log(result.optimizedOutput);\n\n // Display summary if not silent\n if (result.summary) {\n console.error(neuralCyan(`\\n${result.summary}\\n`));\n }\n\n await memory.close();\n\n // Exit with same code as proxied command\n process.exit(result.exitCode);\n } catch (error) {\n console.error(errorRed('Error:'), error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n// Consolidate command\nprogram\n .command('consolidate')\n .description('Consolidate memory: remove decayed entries and merge duplicates')\n .addHelpText(\n 'after',\n `\nExamples:\n $ sparn consolidate # Run memory consolidation\n\nWhat It Does:\n 1. Remove Decayed Entries: Deletes entries that have fully decayed\n 2. Merge Duplicates: Combines identical content entries\n 3. VACUUM Database: Reclaims disk space from deletions\n 4. Update Statistics: Tracks consolidation metrics\n\nWhen to Run:\n โข After long-running sessions\n โข Before important optimizations\n โข When database size grows large\n โข As part of nightly maintenance\n\nTypical Results:\n โข 20-40% database size reduction\n โข Faster query performance\n โข Cleaner memory organization\n`,\n )\n .action(async () => {\n // Lazy-load dependencies\n const { createKVMemory } = await import('../core/kv-memory.js');\n const { consolidateCommand } = await import('./commands/consolidate.js');\n const { createConsolidateSpinner, showConsolidationSummary } = await import('./ui/progress.js');\n const { neuralCyan, synapseViolet, errorRed } = await import('./ui/colors.js');\n\n const spinner = createConsolidateSpinner('๐งน Initializing memory consolidation...');\n try {\n spinner.start();\n\n // Load memory\n spinner.text = '๐พ Loading memory database...';\n const dbPath = resolve(process.cwd(), '.sparn/memory.db');\n const memory = await createKVMemory(dbPath);\n\n // Run consolidation\n spinner.text = '๐ Identifying decayed entries...';\n const result = await consolidateCommand({ memory });\n\n spinner.succeed(neuralCyan(`Consolidation complete in ${result.durationMs}ms!`));\n\n // Display visual impact\n showConsolidationSummary(\n result.entriesBefore,\n result.entriesAfter,\n result.decayedRemoved,\n result.duplicatesRemoved,\n result.durationMs,\n );\n\n // Database vacuum status\n if (result.vacuumCompleted) {\n console.log(synapseViolet(' โ Database VACUUM completed\\n'));\n } else {\n console.log(errorRed(' โ Database VACUUM failed\\n'));\n }\n\n await memory.close();\n } catch (error) {\n spinner.fail(errorRed('Consolidation failed'));\n console.error(errorRed('Error:'), error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n// Config command\nprogram\n .command('config [subcommand] [key] [value]')\n .description('View or modify configuration')\n .option('--json', 'Output result as JSON')\n .addHelpText(\n 'after',\n `\nExamples:\n $ sparn config # Open config in $EDITOR\n $ sparn config get pruning.threshold # Get specific value\n $ sparn config set pruning.threshold 3 # Set value\n $ sparn config --json # View full config as JSON\n\nConfiguration Keys:\n pruning.threshold # Sparse coding threshold (2-5%)\n decay.halfLife # Engram decay half-life (hours)\n decay.minScore # Minimum decay score (0.0-1.0)\n states.activeThreshold # Active state threshold\n states.readyThreshold # Ready state threshold\n embedding.model # BTSP embedding model\n embedding.dimensions # Embedding vector size\n\nThe config file is located at .sparn/config.yaml\n`,\n )\n .action(async (subcommand, key, value, options) => {\n // Lazy-load dependencies\n const { configCommand } = await import('./commands/config.js');\n const { neuralCyan, errorRed } = await import('./ui/colors.js');\n\n try {\n const configPath = resolve(process.cwd(), '.sparn/config.yaml');\n\n // Execute config command\n const result = await configCommand({\n configPath,\n subcommand: subcommand as 'get' | 'set' | undefined,\n key,\n value,\n json: options.json || false,\n });\n\n if (!result.success) {\n console.error(errorRed('Error:'), result.error);\n process.exit(1);\n }\n\n // Handle editor mode\n if (result.editorPath && !options.json) {\n const editor = process.env['EDITOR'] || 'vim';\n console.log(neuralCyan(`\\n๐ Opening config in ${editor}...\\n`));\n\n // Spawn editor\n const child = spawn(editor, [result.editorPath], {\n stdio: 'inherit',\n });\n\n child.on('close', (code) => {\n if (code === 0) {\n console.log(neuralCyan('\\nโ Config edited\\n'));\n }\n process.exit(code ?? 0);\n });\n\n return;\n }\n\n // Display result\n if (result.json) {\n console.log(result.json);\n } else if (result.message) {\n console.log(result.message);\n }\n } catch (error) {\n console.error(errorRed('Error:'), error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n\n// Show banner on version\nprogram.on('option:version', () => {\n console.log(getBanner(VERSION));\n process.exit(0);\n});\n\n// Parse arguments\nprogram.parse();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAKM,kBAOO;AAZb;AAAA;AAAA;AAKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;AAAA;AAAA;;;ACZ9D;AAAA;AAAA;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ename","dumpYAML","import_node_fs","ora","import_node_crypto","import_node_crypto","import_promises","resolve","parseYAML","stringifyYAML","import_node_fs","import_js_yaml","init_config","import_node_child_process","import_node_fs","import_node_path","import_node_url","getVersion","__filename","VERSION","errorRed","synapseViolet","initCommand","displayInitSuccess","createInitSpinner","neuralCyan","createKVMemory","optimizeCommand","createOptimizeSpinner","showTokenSavings","statsCommand","createStatsSpinner","relayCommand","consolidateCommand","createConsolidateSpinner","showConsolidationSummary","configCommand"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|