From 720532c020ec5f236d188e2daf29e240255c32d6 Mon Sep 17 00:00:00 2001 From: Rohit Ghumare Date: Fri, 23 Jan 2026 14:24:16 +0000 Subject: [PATCH 1/9] feat: add session memory system for cross-agent learning Implements a lightweight, local-first memory system that works across all 17 AI coding agents. Key features: - YAML-based storage (no databases or external services) - Three memory layers: Session, Project, and Global - AI-powered compression of observations into learnings - Cross-agent memory injection with relevance matching - Progressive disclosure for token efficiency Core modules: - ObservationStore: Capture raw session observations - LearningStore: Persist compressed learnings - MemoryCompressor: AI/rule-based compression engine - MemoryInjector: Context-aware memory retrieval - MemoryObserver: Automatic observation capture CLI commands (skillkit memory): - status, search, list, show, compress, export - import, clear, add, rate, config TUI integration: - New Memory screen with tabs (Learnings/Observations/Search) - useMemory hook for state management - Updated navigation and keybindings Code quality improvements: - Replaced nested ternaries with explicit functions - Added named constants for magic numbers - Simplified navigation with lookup map --- apps/skillkit/src/cli.ts | 20 + packages/cli/src/commands/index.ts | 8 + packages/cli/src/commands/memory.ts | 815 ++++++++++++ packages/core/src/index.ts | 21 + .../src/memory/__tests__/compressor.test.ts | 500 ++++++++ .../src/memory/__tests__/injector.test.ts | 533 ++++++++ .../memory/__tests__/learning-store.test.ts | 647 ++++++++++ .../src/memory/__tests__/memory-index.test.ts | 487 +++++++ .../__tests__/observation-store.test.ts | 444 +++++++ .../src/memory/__tests__/observer.test.ts | 421 ++++++ packages/core/src/memory/compressor.ts | 1126 +++++++++++++++++ .../core/src/memory/engine-integration.ts | 235 ++++ packages/core/src/memory/index.ts | 50 + packages/core/src/memory/initializer.ts | 78 ++ packages/core/src/memory/injector.ts | 716 +++++++++++ packages/core/src/memory/learning-store.ts | 210 +++ packages/core/src/memory/memory-index.ts | 279 ++++ packages/core/src/memory/observation-store.ts | 168 +++ packages/core/src/memory/observer.ts | 636 ++++++++++ packages/core/src/memory/types.ts | 117 ++ packages/tui/src/App.tsx | 42 +- packages/tui/src/components/Sidebar.tsx | 43 +- packages/tui/src/hooks/index.ts | 1 + packages/tui/src/hooks/useMemory.ts | 141 +++ packages/tui/src/screens/Execute.tsx | 131 ++ packages/tui/src/screens/Memory.tsx | 284 +++++ packages/tui/src/screens/index.ts | 5 + packages/tui/src/theme.ts | 6 + 28 files changed, 8143 insertions(+), 21 deletions(-) create mode 100644 packages/cli/src/commands/memory.ts create mode 100644 packages/core/src/memory/__tests__/compressor.test.ts create mode 100644 packages/core/src/memory/__tests__/injector.test.ts create mode 100644 packages/core/src/memory/__tests__/learning-store.test.ts create mode 100644 packages/core/src/memory/__tests__/memory-index.test.ts create mode 100644 packages/core/src/memory/__tests__/observation-store.test.ts create mode 100644 packages/core/src/memory/__tests__/observer.test.ts create mode 100644 packages/core/src/memory/compressor.ts create mode 100644 packages/core/src/memory/engine-integration.ts create mode 100644 packages/core/src/memory/index.ts create mode 100644 packages/core/src/memory/initializer.ts create mode 100644 packages/core/src/memory/injector.ts create mode 100644 packages/core/src/memory/learning-store.ts create mode 100644 packages/core/src/memory/memory-index.ts create mode 100644 packages/core/src/memory/observation-store.ts create mode 100644 packages/core/src/memory/observer.ts create mode 100644 packages/core/src/memory/types.ts create mode 100644 packages/tui/src/hooks/useMemory.ts create mode 100644 packages/tui/src/screens/Execute.tsx create mode 100644 packages/tui/src/screens/Memory.tsx diff --git a/apps/skillkit/src/cli.ts b/apps/skillkit/src/cli.ts index 8474b4ff..d329860f 100644 --- a/apps/skillkit/src/cli.ts +++ b/apps/skillkit/src/cli.ts @@ -19,6 +19,16 @@ import { TranslateCommand, ContextCommand, RecommendCommand, + StatusCommand, + PauseCommand, + ResumeCommand, + WorkflowRunCommand, + WorkflowListCommand, + WorkflowCreateCommand, + RunCommand, + TestCommand, + MarketplaceCommand, + MemoryCommand, } from '@skillkit/cli'; const __filename = fileURLToPath(import.meta.url); @@ -51,5 +61,15 @@ cli.register(UICommand); cli.register(TranslateCommand); cli.register(ContextCommand); cli.register(RecommendCommand); +cli.register(StatusCommand); +cli.register(PauseCommand); +cli.register(ResumeCommand); +cli.register(WorkflowRunCommand); +cli.register(WorkflowListCommand); +cli.register(WorkflowCreateCommand); +cli.register(RunCommand); +cli.register(TestCommand); +cli.register(MarketplaceCommand); +cli.register(MemoryCommand); cli.runExit(process.argv.slice(2)); diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts index 63ba53d4..33d394cd 100644 --- a/packages/cli/src/commands/index.ts +++ b/packages/cli/src/commands/index.ts @@ -13,3 +13,11 @@ export { UICommand } from './ui.js'; export { TranslateCommand } from './translate.js'; export { ContextCommand } from './context.js'; export { RecommendCommand } from './recommend.js'; +export { StatusCommand } from './status.js'; +export { PauseCommand } from './pause.js'; +export { ResumeCommand } from './resume.js'; +export { WorkflowRunCommand, WorkflowListCommand, WorkflowCreateCommand } from './workflow/index.js'; +export { RunCommand } from './run.js'; +export { TestCommand } from './test.js'; +export { MarketplaceCommand } from './marketplace.js'; +export { MemoryCommand } from './memory.js'; diff --git a/packages/cli/src/commands/memory.ts b/packages/cli/src/commands/memory.ts new file mode 100644 index 00000000..e7e5b17e --- /dev/null +++ b/packages/cli/src/commands/memory.ts @@ -0,0 +1,815 @@ +import { Command, Option } from 'clipanion'; +import chalk from 'chalk'; +import { + ObservationStore, + LearningStore, + getMemoryPaths, + initializeMemoryDirectory, + getMemoryStatus, + createMemoryCompressor, + createMemoryInjector, + type Learning, +} from '@skillkit/core'; + +/** + * Memory command - manage session memory across AI agents + */ +export class MemoryCommand extends Command { + static override paths = [['memory'], ['mem']]; + + static override usage = Command.Usage({ + description: 'Manage session memory across AI coding agents', + details: ` + The memory command helps you view, search, and manage learnings + captured from coding sessions across all AI agents. + + Subcommands: + - status: Show current memory status + - search: Search memories by query + - list: List all learnings + - show: Show a specific learning + - compress: Compress observations into learnings + - export: Export a learning as a skill + - import: Import memories from another project + - clear: Clear session observations + - add: Manually add a learning + - rate: Rate a learning's effectiveness + - config: Configure memory settings + `, + examples: [ + ['Show memory status', '$0 memory status'], + ['Search memories', '$0 memory search "authentication"'], + ['Search global memories', '$0 memory search --global "react hooks"'], + ['List project learnings', '$0 memory list'], + ['List global learnings', '$0 memory list --global'], + ['Show a learning', '$0 memory show '], + ['Compress observations', '$0 memory compress'], + ['Export as skill', '$0 memory export --name my-skill'], + ['Clear session', '$0 memory clear'], + ['Add manual learning', '$0 memory add --title "..." --content "..."'], + ['Rate effectiveness', '$0 memory rate 85'], + ], + }); + + // Subcommand (status, search, list, show, compress, export, import, clear, add, rate, config) + action = Option.String({ required: false }); + + // Second argument (query for search, id for show/export/rate, rating for rate) + arg = Option.String({ required: false }); + + // Global scope + global = Option.Boolean('--global,-g', false, { + description: 'Use global memories instead of project', + }); + + // Tags filter + tags = Option.String('--tags,-t', { + description: 'Filter by tags (comma-separated)', + }); + + // Limit results + limit = Option.String('--limit,-l', { + description: 'Maximum number of results', + }); + + // Title for add + title = Option.String('--title', { + description: 'Title for new learning', + }); + + // Content for add + content = Option.String('--content,-c', { + description: 'Content for new learning', + }); + + // Name for export + name = Option.String('--name,-n', { + description: 'Name for exported skill', + }); + + // Output file + output = Option.String('--output,-o', { + description: 'Output file path', + }); + + // Input file + input = Option.String('--input,-i', { + description: 'Input file path', + }); + + // Keep learnings when clearing + keepLearnings = Option.Boolean('--keep-learnings', false, { + description: 'Keep learnings when clearing', + }); + + // Dry run + dryRun = Option.Boolean('--dry-run', false, { + description: 'Preview without making changes', + }); + + // JSON output + json = Option.Boolean('--json,-j', false, { + description: 'Output in JSON format', + }); + + // Verbose output + verbose = Option.Boolean('--verbose,-v', false, { + description: 'Show detailed output', + }); + + async execute(): Promise { + const action = this.action || 'status'; + + switch (action) { + case 'status': + return this.showStatus(); + case 'search': + return this.searchMemories(); + case 'list': + return this.listLearnings(); + case 'show': + return this.showLearning(); + case 'compress': + return this.compressObservations(); + case 'export': + return this.exportLearning(); + case 'import': + return this.importMemories(); + case 'clear': + return this.clearMemory(); + case 'add': + return this.addLearning(); + case 'rate': + return this.rateLearning(); + case 'config': + return this.showConfig(); + default: + console.error(chalk.red(`Unknown action: ${action}`)); + console.log(chalk.gray('Available actions: status, search, list, show, compress, export, import, clear, add, rate, config')); + return 1; + } + } + + /** + * Show memory status + */ + private async showStatus(): Promise { + const projectPath = process.cwd(); + const status = getMemoryStatus(projectPath); + const paths = getMemoryPaths(projectPath); + + // Get counts from stores + const observationStore = new ObservationStore(projectPath); + const projectLearningStore = new LearningStore('project', projectPath); + const globalLearningStore = new LearningStore('global'); + + const sessionObservations = status.hasObservations ? observationStore.count() : 0; + const projectLearnings = status.hasLearnings ? projectLearningStore.count() : 0; + const globalLearnings = status.hasGlobalLearnings ? globalLearningStore.count() : 0; + const sessionId = status.hasObservations ? observationStore.getSessionId() : null; + + if (this.json) { + console.log(JSON.stringify({ + ...status, + sessionObservations, + projectLearnings, + globalLearnings, + sessionId, + paths, + }, null, 2)); + return 0; + } + + console.log(chalk.bold('\nMemory Status\n')); + + // Session observations + console.log(chalk.cyan('Session:')); + console.log(` Observations: ${sessionObservations}`); + if (sessionId) { + console.log(` Session ID: ${chalk.gray(sessionId.slice(0, 8))}`); + } + console.log(); + + // Project learnings + console.log(chalk.cyan('Project:')); + console.log(` Learnings: ${projectLearnings}`); + console.log(` Path: ${chalk.gray(status.projectMemoryExists ? paths.projectMemoryDir : 'Not initialized')}`); + console.log(); + + // Global learnings + console.log(chalk.cyan('Global:')); + console.log(` Learnings: ${globalLearnings}`); + console.log(` Path: ${chalk.gray(status.globalMemoryExists ? paths.globalMemoryDir : 'Not initialized')}`); + console.log(); + + // Recommendations + if (sessionObservations >= 50) { + console.log(chalk.yellow('💡 You have many uncompressed observations. Consider running:')); + console.log(chalk.gray(' skillkit memory compress')); + } + + return 0; + } + + /** + * Search memories + */ + private async searchMemories(): Promise { + const query = this.arg; + if (!query) { + console.error(chalk.red('Error: Search query is required')); + console.log(chalk.gray('Usage: skillkit memory search "your query"')); + return 1; + } + + const projectPath = process.cwd(); + const injector = createMemoryInjector(projectPath); + + const results = injector.search(query, { + includeGlobal: this.global, + tags: this.tags?.split(',').map((t) => t.trim()), + maxLearnings: this.limit ? parseInt(this.limit, 10) : 10, + minRelevance: 0, + }); + + if (this.json) { + console.log(JSON.stringify(results, null, 2)); + return 0; + } + + if (results.length === 0) { + console.log(chalk.yellow(`No memories found for: "${query}"`)); + return 0; + } + + console.log(chalk.bold(`\nFound ${results.length} memories:\n`)); + + for (const { learning, relevanceScore, matchedBy } of results) { + console.log(`${chalk.cyan('●')} ${chalk.bold(learning.title)}`); + console.log(` ID: ${chalk.gray(learning.id.slice(0, 8))}`); + console.log(` Relevance: ${this.formatScore(relevanceScore)}%`); + console.log(` Tags: ${learning.tags.join(', ')}`); + console.log(` Scope: ${learning.scope}`); + + if (this.verbose) { + console.log(` Matched: ${this.formatMatchedBy(matchedBy)}`); + console.log(` Created: ${new Date(learning.createdAt).toLocaleDateString()}`); + console.log(` Uses: ${learning.useCount}`); + } + + // Show excerpt + const excerpt = learning.content.slice(0, 100); + console.log(` ${chalk.gray(excerpt)}${learning.content.length > 100 ? '...' : ''}`); + console.log(); + } + + return 0; + } + + /** + * List all learnings + */ + private async listLearnings(): Promise { + const projectPath = process.cwd(); + const store = new LearningStore( + this.global ? 'global' : 'project', + this.global ? undefined : projectPath + ); + + let learnings = store.getAll(); + + // Filter by tags if specified + if (this.tags) { + const tagList = this.tags.split(',').map((t) => t.trim().toLowerCase()); + learnings = learnings.filter((l) => + l.tags.some((t) => tagList.includes(t.toLowerCase())) + ); + } + + // Limit results + const limit = this.limit ? parseInt(this.limit, 10) : learnings.length; + learnings = learnings.slice(0, limit); + + if (this.json) { + console.log(JSON.stringify(learnings, null, 2)); + return 0; + } + + const scope = this.global ? 'Global' : 'Project'; + console.log(chalk.bold(`\n${scope} Learnings (${learnings.length}):\n`)); + + if (learnings.length === 0) { + console.log(chalk.gray('No learnings found.')); + console.log(chalk.gray('\nCapture learnings by running skills or add manually:')); + console.log(chalk.gray(' skillkit memory add --title "..." --content "..."')); + return 0; + } + + for (const learning of learnings) { + const effectiveness = learning.effectiveness !== undefined + ? ` [${this.formatScore(learning.effectiveness)}%]` + : ''; + + console.log(`${chalk.cyan('●')} ${learning.title}${chalk.green(effectiveness)}`); + console.log(` ${chalk.gray(learning.id.slice(0, 8))} | ${learning.tags.join(', ')} | ${learning.useCount} uses`); + + if (this.verbose) { + const excerpt = learning.content.slice(0, 80); + console.log(` ${chalk.gray(excerpt)}${learning.content.length > 80 ? '...' : ''}`); + } + } + + console.log(); + return 0; + } + + /** + * Show a specific learning + */ + private async showLearning(): Promise { + const id = this.arg; + if (!id) { + console.error(chalk.red('Error: Learning ID is required')); + console.log(chalk.gray('Usage: skillkit memory show ')); + return 1; + } + + const projectPath = process.cwd(); + + // Try project store first + let learning = new LearningStore('project', projectPath).getById(id); + + // Try global store + if (!learning) { + learning = new LearningStore('global').getById(id); + } + + // Try matching by prefix + if (!learning) { + const projectLearnings = new LearningStore('project', projectPath).getAll(); + const globalLearnings = new LearningStore('global').getAll(); + const all = [...projectLearnings, ...globalLearnings]; + + learning = all.find((l) => l.id.startsWith(id)); + } + + if (!learning) { + console.error(chalk.red(`Learning not found: ${id}`)); + return 1; + } + + if (this.json) { + console.log(JSON.stringify(learning, null, 2)); + return 0; + } + + console.log(chalk.bold(`\n${learning.title}\n`)); + console.log(chalk.gray(`ID: ${learning.id}`)); + console.log(chalk.gray(`Scope: ${learning.scope}`)); + console.log(chalk.gray(`Source: ${learning.source}`)); + console.log(chalk.gray(`Tags: ${learning.tags.join(', ')}`)); + + if (learning.frameworks?.length) { + console.log(chalk.gray(`Frameworks: ${learning.frameworks.join(', ')}`)); + } + + if (learning.patterns?.length) { + console.log(chalk.gray(`Patterns: ${learning.patterns.join(', ')}`)); + } + + console.log(chalk.gray(`Created: ${new Date(learning.createdAt).toLocaleString()}`)); + console.log(chalk.gray(`Updated: ${new Date(learning.updatedAt).toLocaleString()}`)); + console.log(chalk.gray(`Uses: ${learning.useCount}`)); + + if (learning.effectiveness !== undefined) { + console.log(chalk.gray(`Effectiveness: ${this.formatScore(learning.effectiveness)}%`)); + } + + console.log(chalk.bold('\nContent:\n')); + console.log(learning.content); + console.log(); + + return 0; + } + + /** + * Compress observations into learnings + */ + private async compressObservations(): Promise { + const projectPath = process.cwd(); + + // Initialize memory directory if needed + initializeMemoryDirectory(projectPath); + + const observationStore = new ObservationStore(projectPath); + const observations = observationStore.getAll(); + + if (observations.length === 0) { + console.log(chalk.yellow('No observations to compress.')); + return 0; + } + + console.log(chalk.cyan(`Found ${observations.length} observations to compress...\n`)); + + if (this.dryRun) { + console.log(chalk.gray('(Dry run - no changes will be made)\n')); + } + + const compressor = createMemoryCompressor(projectPath); + const { learnings, result } = await compressor.compressAndStore(observations, { + minObservations: 2, + additionalTags: this.tags?.split(',').map((t) => t.trim()), + }); + + console.log(chalk.green(`✓ Compressed ${result.stats.inputCount} observations into ${result.stats.outputCount} learnings\n`)); + + if (learnings.length > 0) { + console.log(chalk.bold('New Learnings:')); + for (const learning of learnings) { + console.log(` ${chalk.cyan('●')} ${learning.title}`); + console.log(` Tags: ${learning.tags.join(', ')}`); + } + console.log(); + } + + if (!this.dryRun && result.processedObservationIds.length > 0) { + // Remove processed observations + const deleted = observationStore.deleteMany(result.processedObservationIds); + console.log(chalk.gray(`Cleared ${deleted} processed observations.`)); + } + + return 0; + } + + /** + * Export a learning as a skill + */ + private async exportLearning(): Promise { + const id = this.arg; + if (!id) { + console.error(chalk.red('Error: Learning ID is required')); + console.log(chalk.gray('Usage: skillkit memory export --name my-skill')); + return 1; + } + + const projectPath = process.cwd(); + + // Find the learning + let learning = new LearningStore('project', projectPath).getById(id); + if (!learning) { + learning = new LearningStore('global').getById(id); + } + + // Try matching by prefix + if (!learning) { + const projectLearnings = new LearningStore('project', projectPath).getAll(); + const globalLearnings = new LearningStore('global').getAll(); + const all = [...projectLearnings, ...globalLearnings]; + learning = all.find((l) => l.id.startsWith(id)); + } + + if (!learning) { + console.error(chalk.red(`Learning not found: ${id}`)); + return 1; + } + + // Generate skill name + const skillName = this.name || this.slugify(learning.title); + + // Generate skill content + const skillContent = this.generateSkillContent(learning, skillName); + + if (this.dryRun) { + console.log(chalk.gray('(Dry run preview)\n')); + console.log(skillContent); + return 0; + } + + // Determine output path + const outputPath = this.output || `.skillkit/exports/${skillName}/SKILL.md`; + const { dirname } = await import('node:path'); + const { existsSync, mkdirSync, writeFileSync } = await import('node:fs'); + + const outputDir = dirname(outputPath); + if (!existsSync(outputDir)) { + mkdirSync(outputDir, { recursive: true }); + } + + writeFileSync(outputPath, skillContent, 'utf-8'); + + console.log(chalk.green(`✓ Exported learning as skill: ${skillName}`)); + console.log(chalk.gray(` Path: ${outputPath}`)); + + return 0; + } + + /** + * Import memories from another project + */ + private async importMemories(): Promise { + const inputPath = this.input || this.arg; + if (!inputPath) { + console.error(chalk.red('Error: Input path is required')); + console.log(chalk.gray('Usage: skillkit memory import --input ')); + return 1; + } + + const { existsSync, readFileSync } = await import('node:fs'); + const { resolve } = await import('node:path'); + + const fullPath = resolve(inputPath); + if (!existsSync(fullPath)) { + console.error(chalk.red(`File not found: ${fullPath}`)); + return 1; + } + + const projectPath = process.cwd(); + const store = new LearningStore( + this.global ? 'global' : 'project', + this.global ? undefined : projectPath + ); + + try { + const content = readFileSync(fullPath, 'utf-8'); + const { parse: parseYaml } = await import('yaml'); + const data = parseYaml(content) as { learnings?: Learning[] }; + + if (!data.learnings || !Array.isArray(data.learnings)) { + console.error(chalk.red('Invalid memory file format')); + return 1; + } + + let imported = 0; + for (const learning of data.learnings) { + if (this.dryRun) { + console.log(chalk.gray(`Would import: ${learning.title}`)); + } else { + store.add({ + source: 'imported', + title: learning.title, + content: learning.content, + tags: learning.tags, + frameworks: learning.frameworks, + patterns: learning.patterns, + }); + imported++; + } + } + + if (this.dryRun) { + console.log(chalk.gray(`\n(Dry run - ${data.learnings.length} learnings would be imported)`)); + } else { + console.log(chalk.green(`✓ Imported ${imported} learnings`)); + } + + return 0; + } catch (error) { + console.error(chalk.red(`Import failed: ${error}`)); + return 1; + } + } + + /** + * Clear session observations + */ + private async clearMemory(): Promise { + const projectPath = process.cwd(); + + if (this.dryRun) { + const observationStore = new ObservationStore(projectPath); + const learningStore = new LearningStore('project', projectPath); + + console.log(chalk.gray('(Dry run preview)\n')); + console.log(`Would clear ${observationStore.count()} observations`); + if (!this.keepLearnings) { + console.log(`Would clear ${learningStore.count()} learnings`); + } + return 0; + } + + const observationStore = new ObservationStore(projectPath); + observationStore.clear(); + console.log(chalk.green('✓ Cleared session observations')); + + if (!this.keepLearnings) { + const learningStore = new LearningStore('project', projectPath); + learningStore.clear(); + console.log(chalk.green('✓ Cleared project learnings')); + } + + return 0; + } + + /** + * Add a manual learning + */ + private async addLearning(): Promise { + if (!this.title) { + console.error(chalk.red('Error: --title is required')); + console.log(chalk.gray('Usage: skillkit memory add --title "..." --content "..."')); + return 1; + } + + if (!this.content) { + console.error(chalk.red('Error: --content is required')); + console.log(chalk.gray('Usage: skillkit memory add --title "..." --content "..."')); + return 1; + } + + const projectPath = process.cwd(); + const store = new LearningStore( + this.global ? 'global' : 'project', + this.global ? undefined : projectPath + ); + + const tags = this.tags?.split(',').map((t) => t.trim()) || []; + + const learning = store.add({ + source: 'manual', + title: this.title, + content: this.content, + tags, + }); + + console.log(chalk.green(`✓ Added learning: ${learning.title}`)); + console.log(chalk.gray(` ID: ${learning.id}`)); + + return 0; + } + + /** + * Rate a learning's effectiveness + */ + private async rateLearning(): Promise { + const id = this.arg; + if (!id) { + console.error(chalk.red('Error: Learning ID is required')); + console.log(chalk.gray('Usage: skillkit memory rate ')); + return 1; + } + + // Find the rating (could be second positional or parse from id) + const rating = parseInt(this.content || '0', 10); + if (isNaN(rating) || rating < 0 || rating > 100) { + console.error(chalk.red('Error: Rating must be 0-100')); + console.log(chalk.gray('Usage: skillkit memory rate --content ')); + return 1; + } + + const projectPath = process.cwd(); + + // Try project store first + const projectStore = new LearningStore('project', projectPath); + let learning = projectStore.getById(id); + let store = projectStore; + + if (!learning) { + const globalStore = new LearningStore('global'); + learning = globalStore.getById(id); + store = globalStore; + } + + // Try prefix match + if (!learning) { + const projectLearnings = projectStore.getAll(); + const globalStore = new LearningStore('global'); + const globalLearnings = globalStore.getAll(); + + learning = projectLearnings.find((l) => l.id.startsWith(id)); + if (learning) { + store = projectStore; + } else { + learning = globalLearnings.find((l) => l.id.startsWith(id)); + if (learning) { + store = globalStore; + } + } + } + + if (!learning) { + console.error(chalk.red(`Learning not found: ${id}`)); + return 1; + } + + store.setEffectiveness(learning.id, rating); + console.log(chalk.green(`✓ Rated "${learning.title}" as ${rating}% effective`)); + + return 0; + } + + /** + * Show memory configuration + */ + private async showConfig(): Promise { + const projectPath = process.cwd(); + const paths = getMemoryPaths(projectPath); + + if (this.json) { + console.log(JSON.stringify(paths, null, 2)); + return 0; + } + + console.log(chalk.bold('\nMemory Configuration\n')); + + console.log(chalk.cyan('Paths:')); + console.log(` Project observations: ${chalk.gray(paths.observationsFile)}`); + console.log(` Project learnings: ${chalk.gray(paths.learningsFile)}`); + console.log(` Project index: ${chalk.gray(paths.indexFile)}`); + console.log(` Global learnings: ${chalk.gray(paths.globalLearningsFile)}`); + console.log(` Global index: ${chalk.gray(paths.globalIndexFile)}`); + console.log(); + + return 0; + } + + /** + * Format relevance/effectiveness score with color + */ + private formatScore(score: number): string { + if (score >= 80) return chalk.green(score.toString()); + if (score >= 50) return chalk.yellow(score.toString()); + return chalk.red(score.toString()); + } + + /** + * Format matched by info + */ + private formatMatchedBy(matchedBy: { + frameworks: string[]; + tags: string[]; + keywords: string[]; + patterns: string[]; + }): string { + const parts: string[] = []; + if (matchedBy.frameworks.length > 0) { + parts.push(`frameworks: ${matchedBy.frameworks.join(', ')}`); + } + if (matchedBy.tags.length > 0) { + parts.push(`tags: ${matchedBy.tags.join(', ')}`); + } + if (matchedBy.keywords.length > 0) { + parts.push(`keywords: ${matchedBy.keywords.slice(0, 3).join(', ')}`); + } + if (matchedBy.patterns.length > 0) { + parts.push(`patterns: ${matchedBy.patterns.join(', ')}`); + } + return parts.join(' | ') || 'general'; + } + + /** + * Convert title to slug + */ + private slugify(text: string): string { + return text + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') + .slice(0, 50); + } + + /** + * Generate skill content from learning + */ + private generateSkillContent(learning: Learning, skillName: string): string { + const lines: string[] = [ + '---', + `name: ${skillName}`, + `description: ${learning.title}`, + `version: 1.0.0`, + `tags: [${learning.tags.join(', ')}]`, + `source: skillkit-memory`, + `sourceType: local`, + ]; + + if (learning.frameworks?.length) { + lines.push(`compatibility:`); + lines.push(` frameworks: [${learning.frameworks.join(', ')}]`); + } + + lines.push('---', '', `# ${learning.title}`, ''); + + if (learning.patterns?.length) { + lines.push(`## Patterns`, ''); + for (const pattern of learning.patterns) { + lines.push(`- ${pattern}`); + } + lines.push(''); + } + + lines.push(`## Content`, '', learning.content, ''); + + lines.push( + '---', + '', + '*Exported from SkillKit session memory*', + `*Created: ${new Date(learning.createdAt).toLocaleDateString()}*`, + `*Uses: ${learning.useCount}*` + ); + + if (learning.effectiveness !== undefined) { + lines.push(`*Effectiveness: ${learning.effectiveness}%*`); + } + + return lines.join('\n'); + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 17884746..a4973234 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -18,3 +18,24 @@ export * from './context/index.js'; // Recommendation Engine (Smart Recommendations) export * from './recommend/index.js'; + +// Session Management (Pause/Resume Support) +export * from './session/index.js'; + +// Workflow Orchestration (Skill Composition) +export * from './workflow/index.js'; + +// Skill Execution Engine +export * from './executor/index.js'; + +// Skill Testing Framework +export * from './testing/index.js'; + +// Skill Marketplace (Aggregated Index) +export * from './marketplace/index.js'; + +// CI/CD Integration (Templates & Utilities) +export * from './cicd/index.js'; + +// Memory System (Cross-Agent Session Memory) +export * from './memory/index.js'; diff --git a/packages/core/src/memory/__tests__/compressor.test.ts b/packages/core/src/memory/__tests__/compressor.test.ts new file mode 100644 index 00000000..d5198967 --- /dev/null +++ b/packages/core/src/memory/__tests__/compressor.test.ts @@ -0,0 +1,500 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { + RuleBasedCompressor, + APIBasedCompressor, + MemoryCompressor, + LearningConsolidator, + createRuleBasedCompressor, + createAPIBasedCompressor, + createMemoryCompressor, +} from '../compressor.js'; +import type { Observation, Learning } from '../types.js'; + +vi.mock('node:fs', () => ({ + existsSync: vi.fn(), + readFileSync: vi.fn(), + writeFileSync: vi.fn(), + mkdirSync: vi.fn(), +})); + +// Helper to create mock observations +const createObservation = (overrides: Partial = {}): Observation => ({ + id: `obs-${Math.random().toString(36).slice(2, 9)}`, + timestamp: new Date().toISOString(), + sessionId: 'test-session', + agent: 'claude-code', + type: 'tool_use', + content: { + action: 'Test action', + context: 'Test context', + }, + relevance: 60, + ...overrides, +}); + +// Helper to create mock learnings +const createLearning = (overrides: Partial = {}): Learning => ({ + id: `learn-${Math.random().toString(36).slice(2, 9)}`, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + source: 'session', + title: 'Test Learning', + content: 'Test content for learning', + scope: 'project', + tags: ['test'], + useCount: 0, + ...overrides, +}); + +describe('RuleBasedCompressor', () => { + let compressor: RuleBasedCompressor; + + beforeEach(() => { + compressor = new RuleBasedCompressor(); + vi.clearAllMocks(); + }); + + describe('getType', () => { + it('should return rule-based', () => { + expect(compressor.getType()).toBe('rule-based'); + }); + }); + + describe('compress', () => { + it('should return empty result when observations below threshold', async () => { + const observations = [createObservation(), createObservation()]; + + const result = await compressor.compress(observations, { minObservations: 5 }); + + expect(result.learnings).toHaveLength(0); + expect(result.skippedObservationIds).toHaveLength(2); + }); + + it('should extract error-solution pairs', async () => { + const observations = [ + createObservation({ + type: 'error', + content: { + action: 'Build failed', + context: 'Running npm build', + error: 'TypeError: Cannot read property of undefined', + }, + relevance: 85, + }), + createObservation({ + type: 'solution', + content: { + action: 'Added null check', + context: 'Fixed the TypeError', + solution: 'Added optional chaining operator', + }, + relevance: 90, + }), + createObservation({ + type: 'tool_use', + content: { + action: 'Some other action', + context: 'Context', + }, + relevance: 50, + }), + ]; + + const result = await compressor.compress(observations, { minObservations: 2 }); + + expect(result.learnings.length).toBeGreaterThanOrEqual(1); + const errorSolutionLearning = result.learnings.find((l) => + l.title.includes('Error Resolution') + ); + expect(errorSolutionLearning).toBeDefined(); + }); + + it('should extract decision patterns', async () => { + const observations = [ + createObservation({ + type: 'decision', + content: { + action: 'Use TypeScript', + context: 'Choosing programming language', + }, + relevance: 75, + }), + createObservation({ + type: 'decision', + content: { + action: 'Use React hooks', + context: 'State management approach', + }, + relevance: 75, + }), + createObservation({ + type: 'tool_use', + content: { + action: 'Filler', + context: 'Context', + }, + relevance: 50, + }), + ]; + + const result = await compressor.compress(observations, { minObservations: 2 }); + + expect(result.learnings.length).toBeGreaterThanOrEqual(1); + const decisionLearning = result.learnings.find((l) => l.title.includes('Decision')); + expect(decisionLearning).toBeDefined(); + }); + + it('should filter by minimum importance', async () => { + const observations = [ + createObservation({ + type: 'tool_use', + content: { action: 'Low importance action', context: 'Context' }, + relevance: 50, + }), + createObservation({ + type: 'tool_use', + content: { action: 'Another action', context: 'Context' }, + relevance: 50, + }), + createObservation({ + type: 'tool_use', + content: { action: 'Third action', context: 'Context' }, + relevance: 50, + }), + ]; + + const result = await compressor.compress(observations, { + minObservations: 2, + minImportance: 9, // Very high threshold + }); + + // Tool use patterns have low importance, so should be filtered + expect(result.learnings.length).toBe(0); + }); + + it('should limit output to maxLearnings', async () => { + const observations = [ + createObservation({ + type: 'error', + content: { action: 'Error 1', context: 'Context', error: 'Error 1' }, + relevance: 85, + }), + createObservation({ + type: 'error', + content: { action: 'Error 2', context: 'Context', error: 'Error 2' }, + relevance: 85, + }), + createObservation({ + type: 'error', + content: { action: 'Error 3', context: 'Context', error: 'Error 3' }, + relevance: 85, + }), + createObservation({ + type: 'solution', + content: { action: 'Solution 1', context: 'Context', solution: 'Solution' }, + relevance: 90, + }), + ]; + + const result = await compressor.compress(observations, { + minObservations: 2, + maxLearnings: 2, + }); + + expect(result.learnings.length).toBeLessThanOrEqual(2); + }); + + it('should add additional tags to learnings', async () => { + const observations = [ + createObservation({ + type: 'error', + content: { action: 'Error', context: 'Context', error: 'Some error' }, + relevance: 85, + }), + createObservation({ + type: 'solution', + content: { action: 'Fix', context: 'Context', solution: 'Fixed it' }, + relevance: 90, + }), + createObservation({ + type: 'tool_use', + content: { action: 'Action', context: 'Context' }, + relevance: 50, + }), + ]; + + const result = await compressor.compress(observations, { + minObservations: 2, + additionalTags: ['project-x', 'sprint-1'], + }); + + if (result.learnings.length > 0) { + expect(result.learnings[0].tags).toContain('project-x'); + expect(result.learnings[0].tags).toContain('sprint-1'); + } + }); + + it('should calculate compression stats', async () => { + const observations = [ + createObservation({ type: 'error', relevance: 85 }), + createObservation({ type: 'solution', relevance: 90 }), + createObservation({ type: 'tool_use', relevance: 50 }), + ]; + + const result = await compressor.compress(observations, { minObservations: 2 }); + + expect(result.stats.inputCount).toBe(3); + expect(result.stats.outputCount).toBe(result.learnings.length); + expect(result.stats.compressionRatio).toBeDefined(); + }); + }); +}); + +describe('APIBasedCompressor', () => { + let compressor: APIBasedCompressor; + + beforeEach(() => { + compressor = new APIBasedCompressor({ + provider: 'anthropic', + apiKey: 'test-key', + model: 'claude-3-haiku-20240307', + }); + vi.clearAllMocks(); + }); + + describe('getType', () => { + it('should return api', () => { + expect(compressor.getType()).toBe('api'); + }); + }); + + describe('compress', () => { + it('should return empty result when observations below threshold', async () => { + const observations = [createObservation()]; + + const result = await compressor.compress(observations, { minObservations: 5 }); + + expect(result.learnings).toHaveLength(0); + }); + + it('should fall back to rule-based on API failure', async () => { + // Mock fetch to fail + global.fetch = vi.fn().mockRejectedValue(new Error('API error')); + + const observations = [ + createObservation({ type: 'error', relevance: 85 }), + createObservation({ type: 'solution', relevance: 90 }), + createObservation({ type: 'tool_use', relevance: 50 }), + ]; + + const result = await compressor.compress(observations, { minObservations: 2 }); + + // Should not throw, should return result from fallback + expect(result.stats.inputCount).toBe(3); + }); + }); +}); + +describe('MemoryCompressor', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(existsSync).mockReturnValue(false); + }); + + describe('constructor', () => { + it('should create with default engine', () => { + const compressor = new MemoryCompressor('/test/project'); + expect(compressor.getEngineType()).toBe('rule-based'); + }); + + it('should accept custom engine', () => { + const apiEngine = new APIBasedCompressor({ + provider: 'openai', + apiKey: 'test', + }); + const compressor = new MemoryCompressor('/test/project', { engine: apiEngine }); + expect(compressor.getEngineType()).toBe('api'); + }); + }); + + describe('setEngine', () => { + it('should allow changing the engine', () => { + const compressor = new MemoryCompressor('/test/project'); + expect(compressor.getEngineType()).toBe('rule-based'); + + compressor.setEngine( + new APIBasedCompressor({ + provider: 'anthropic', + apiKey: 'test', + }) + ); + expect(compressor.getEngineType()).toBe('api'); + }); + }); + + describe('compressAndStore', () => { + it('should compress and store learnings', async () => { + const compressor = createMemoryCompressor('/test/project', { + projectName: 'test-project', + }); + + const observations = [ + createObservation({ + type: 'error', + content: { action: 'Error', context: 'Context', error: 'Test error' }, + relevance: 85, + }), + createObservation({ + type: 'solution', + content: { action: 'Fix', context: 'Fixed error', solution: 'Applied fix' }, + relevance: 90, + }), + createObservation({ type: 'tool_use', relevance: 50 }), + ]; + + const { learnings, result } = await compressor.compressAndStore(observations, { + minObservations: 2, + }); + + expect(result.stats.inputCount).toBe(3); + // Learnings should have been created + expect(learnings.length).toBe(result.learnings.length); + }); + }); +}); + +describe('LearningConsolidator', () => { + let consolidator: LearningConsolidator; + + beforeEach(() => { + consolidator = new LearningConsolidator(); + vi.clearAllMocks(); + vi.mocked(existsSync).mockReturnValue(false); + }); + + describe('findSimilar', () => { + it('should find similar learnings', () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'React hooks best practices', + tags: ['react', 'hooks'], + patterns: ['best-practices'], + content: 'When using React hooks, always follow the rules of hooks.', + }), + createLearning({ + id: 'l2', + title: 'React hooks patterns', + tags: ['react', 'hooks', 'patterns'], + patterns: ['best-practices'], + content: 'React hooks provide a way to use state in functional components.', + }), + createLearning({ + id: 'l3', + title: 'TypeScript generics guide', + tags: ['typescript', 'generics'], + patterns: ['type-safety'], + content: 'TypeScript generics allow you to write reusable type-safe code.', + }), + ]; + + const pairs = consolidator.findSimilar(learnings, 0.5); + + // The two React hooks learnings should be similar + expect(pairs.length).toBeGreaterThanOrEqual(1); + const reactPair = pairs.find( + ([a, b]) => + (a.id === 'l1' && b.id === 'l2') || (a.id === 'l2' && b.id === 'l1') + ); + expect(reactPair).toBeDefined(); + }); + + it('should not find similar for distinct learnings', () => { + const learnings = [ + createLearning({ + title: 'React tutorial', + tags: ['react', 'frontend'], + content: 'React is a library for building user interfaces.', + }), + createLearning({ + title: 'Python basics', + tags: ['python', 'backend'], + content: 'Python is a versatile programming language.', + }), + ]; + + const pairs = consolidator.findSimilar(learnings, 0.8); + + expect(pairs).toHaveLength(0); + }); + }); + + describe('merge', () => { + it('should merge two learnings', () => { + const l1 = createLearning({ + title: 'React hooks patterns', + content: 'Content 1 about hooks', + tags: ['react', 'hooks'], + frameworks: ['react'], + patterns: ['hooks'], + useCount: 5, + effectiveness: 80, + }); + + const l2 = createLearning({ + title: 'React hooks best practices', + content: 'Content 2 about best practices for hooks in React applications', + tags: ['react', 'best-practices'], + frameworks: ['react', 'nextjs'], + patterns: ['hooks', 'state-management'], + useCount: 3, + effectiveness: 70, + }); + + const merged = consolidator.merge(l1, l2); + + // Should combine tags + expect(merged.tags).toContain('react'); + expect(merged.tags).toContain('hooks'); + expect(merged.tags).toContain('best-practices'); + + // Should combine frameworks + expect(merged.frameworks).toContain('react'); + expect(merged.frameworks).toContain('nextjs'); + + // Should combine patterns + expect(merged.patterns).toContain('hooks'); + expect(merged.patterns).toContain('state-management'); + + // Should combine use count + expect(merged.useCount).toBe(8); + + // Should keep higher effectiveness + expect(merged.effectiveness).toBe(80); + }); + }); +}); + +describe('Factory functions', () => { + it('createRuleBasedCompressor should create instance', () => { + const compressor = createRuleBasedCompressor(); + expect(compressor).toBeInstanceOf(RuleBasedCompressor); + expect(compressor.getType()).toBe('rule-based'); + }); + + it('createAPIBasedCompressor should create instance', () => { + const compressor = createAPIBasedCompressor({ + provider: 'anthropic', + apiKey: 'test-key', + }); + expect(compressor).toBeInstanceOf(APIBasedCompressor); + expect(compressor.getType()).toBe('api'); + }); + + it('createMemoryCompressor should create instance', () => { + vi.mocked(existsSync).mockReturnValue(false); + const compressor = createMemoryCompressor('/test/project'); + expect(compressor).toBeInstanceOf(MemoryCompressor); + }); +}); diff --git a/packages/core/src/memory/__tests__/injector.test.ts b/packages/core/src/memory/__tests__/injector.test.ts new file mode 100644 index 00000000..efb818ae --- /dev/null +++ b/packages/core/src/memory/__tests__/injector.test.ts @@ -0,0 +1,533 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { MemoryInjector, createMemoryInjector } from '../injector.js'; +import type { Learning } from '../types.js'; +import type { ProjectContext } from '../../context/types.js'; + +vi.mock('node:fs', () => ({ + existsSync: vi.fn(), + readFileSync: vi.fn(), + writeFileSync: vi.fn(), + mkdirSync: vi.fn(), +})); + +// Helper to create mock learnings +const createLearning = (overrides: Partial = {}): Learning => ({ + id: `learn-${Math.random().toString(36).slice(2, 9)}`, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + source: 'session', + title: 'Test Learning', + content: 'Test content for learning that provides useful information about best practices.', + scope: 'project', + tags: ['test'], + useCount: 0, + ...overrides, +}); + +// Helper to create mock project context +const createProjectContext = (overrides: Partial = {}): ProjectContext => ({ + version: 1, + project: { + name: 'test-project', + description: 'A test project', + type: 'web-app', + }, + stack: { + languages: [{ name: 'TypeScript', confidence: 100 }], + frameworks: [{ name: 'React', confidence: 100 }, { name: 'Next.js', confidence: 90 }], + libraries: [], + styling: [{ name: 'Tailwind', confidence: 100 }], + testing: [{ name: 'Vitest', confidence: 100 }], + databases: [], + tools: [], + runtime: [{ name: 'Node.js', confidence: 100 }], + }, + ...overrides, +}); + +// Mock YAML content for project learnings +const createMockLearningsYaml = (learnings: Learning[]) => ({ + version: 1, + learnings, +}); + +describe('MemoryInjector', () => { + let injector: MemoryInjector; + + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(existsSync).mockReturnValue(false); + }); + + describe('constructor', () => { + it('should create instance without project context', () => { + injector = new MemoryInjector('/test/project'); + expect(injector).toBeInstanceOf(MemoryInjector); + }); + + it('should create instance with project context', () => { + const context = createProjectContext(); + injector = new MemoryInjector('/test/project', 'test-project', context); + expect(injector).toBeInstanceOf(MemoryInjector); + }); + }); + + describe('setProjectContext', () => { + it('should set project context', () => { + injector = new MemoryInjector('/test/project'); + const context = createProjectContext(); + injector.setProjectContext(context); + // No direct way to verify, but it should not throw + }); + }); + + describe('getRelevantMemories', () => { + it('should return empty array when no learnings exist', async () => { + injector = new MemoryInjector('/test/project'); + const memories = await injector.getRelevantMemories(); + expect(memories).toHaveLength(0); + }); + + it('should return learnings with relevance scores', async () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'React hooks best practices', + tags: ['react', 'hooks'], + frameworks: ['react'], + useCount: 5, + }), + ]; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + const context = createProjectContext(); + injector = new MemoryInjector('/test/project', 'test-project', context); + + const memories = await injector.getRelevantMemories(); + + expect(memories.length).toBeGreaterThanOrEqual(0); + }); + + it('should filter by minimum relevance', async () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'Unrelated learning', + tags: ['unrelated'], + useCount: 0, + }), + ]; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + injector = new MemoryInjector('/test/project'); + + const memories = await injector.getRelevantMemories({ minRelevance: 90 }); + + expect(memories).toHaveLength(0); + }); + + it('should limit results to maxLearnings', async () => { + const learnings = Array.from({ length: 20 }, (_, i) => + createLearning({ + id: `l${i}`, + title: `Learning ${i}`, + tags: ['common-tag'], + useCount: i, + }) + ); + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + injector = new MemoryInjector('/test/project'); + + const memories = await injector.getRelevantMemories({ + maxLearnings: 5, + minRelevance: 0, + }); + + expect(memories.length).toBeLessThanOrEqual(5); + }); + + it('should match by current task keywords', async () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'Authentication patterns', + content: 'How to implement JWT authentication in Node.js applications.', + tags: ['auth', 'jwt', 'security'], + }), + createLearning({ + id: 'l2', + title: 'CSS Grid layout', + content: 'Guide to using CSS Grid for responsive layouts.', + tags: ['css', 'layout'], + }), + ]; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + injector = new MemoryInjector('/test/project'); + + const memories = await injector.getRelevantMemories({ + currentTask: 'implement JWT authentication', + minRelevance: 0, + }); + + // Auth learning should rank higher + if (memories.length > 0) { + const authMemory = memories.find((m) => m.learning.id === 'l1'); + const cssMemory = memories.find((m) => m.learning.id === 'l2'); + + if (authMemory && cssMemory) { + expect(authMemory.relevanceScore).toBeGreaterThan(cssMemory.relevanceScore); + } + } + }); + }); + + describe('inject', () => { + it('should return empty result when no learnings exist', async () => { + injector = new MemoryInjector('/test/project'); + + const result = await injector.inject(); + + expect(result.memories).toHaveLength(0); + expect(result.formattedContent).toBe(''); + expect(result.totalTokens).toBe(0); + expect(result.stats.injected).toBe(0); + }); + + it('should respect token budget', async () => { + const learnings = Array.from({ length: 10 }, (_, i) => + createLearning({ + id: `l${i}`, + title: `Learning ${i}`, + content: 'A'.repeat(500), // Long content + tags: ['test'], + useCount: 10 - i, + }) + ); + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + injector = new MemoryInjector('/test/project'); + + const result = await injector.inject({ + maxTokens: 100, + minRelevance: 0, + }); + + expect(result.totalTokens).toBeLessThanOrEqual(100); + }); + + it('should format content as markdown by default', async () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'Test Learning', + content: 'Test content', + tags: ['test'], + useCount: 5, + }), + ]; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + injector = new MemoryInjector('/test/project'); + + const result = await injector.inject({ minRelevance: 0 }); + + if (result.memories.length > 0) { + expect(result.formattedContent).toContain('# Relevant Memories'); + expect(result.formattedContent).toContain('## Test Learning'); + } + }); + }); + + describe('injectForAgent', () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'Test Learning', + content: 'Test content for agent', + tags: ['test'], + frameworks: ['react'], + useCount: 5, + }), + ]; + + beforeEach(() => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + }); + + it('should format for claude-code with XML tags', async () => { + injector = new MemoryInjector('/test/project'); + + const result = await injector.injectForAgent('claude-code', { minRelevance: 0 }); + + if (result.memories.length > 0) { + expect(result.formattedContent).toContain(''); + expect(result.formattedContent).toContain(''); + } + }); + + it('should format for cursor with MDC format', async () => { + injector = new MemoryInjector('/test/project'); + + const result = await injector.injectForAgent('cursor', { minRelevance: 0 }); + + if (result.memories.length > 0) { + expect(result.formattedContent).toContain('---'); + expect(result.formattedContent).toContain('description:'); + expect(result.formattedContent).toContain('# Session Memories'); + } + }); + + it('should format for github-copilot with HTML comments', async () => { + injector = new MemoryInjector('/test/project'); + + const result = await injector.injectForAgent('github-copilot', { minRelevance: 0 }); + + if (result.memories.length > 0) { + expect(result.formattedContent).toContain(''); + } + }); + + it('should use default markdown for unknown agents', async () => { + injector = new MemoryInjector('/test/project'); + + const result = await injector.injectForAgent('universal', { minRelevance: 0 }); + + if (result.memories.length > 0) { + expect(result.formattedContent).toContain('# Relevant Memories'); + } + }); + }); + + describe('getSummaries', () => { + it('should return memory summaries', () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'Test Learning', + tags: ['test', 'example'], + }), + ]; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + injector = new MemoryInjector('/test/project'); + + const summaries = injector.getSummaries(); + + expect(summaries.length).toBeGreaterThanOrEqual(0); + if (summaries.length > 0) { + expect(summaries[0]).toHaveProperty('id'); + expect(summaries[0]).toHaveProperty('title'); + expect(summaries[0]).toHaveProperty('tags'); + expect(summaries[0]).toHaveProperty('relevance'); + } + }); + }); + + describe('getPreviews', () => { + it('should return memory previews for given IDs', () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'Test Learning', + content: 'Full content that is longer than the excerpt limit would allow.', + tags: ['test'], + }), + ]; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + injector = new MemoryInjector('/test/project'); + + const previews = injector.getPreviews(['l1']); + + if (previews.length > 0) { + expect(previews[0]).toHaveProperty('excerpt'); + expect(previews[0].excerpt.length).toBeLessThanOrEqual(200); + } + }); + + it('should return empty for non-existent IDs', () => { + vi.mocked(existsSync).mockReturnValue(false); + + injector = new MemoryInjector('/test/project'); + + const previews = injector.getPreviews(['non-existent']); + + expect(previews).toHaveLength(0); + }); + }); + + describe('getFullMemories', () => { + it('should return full memory content', () => { + const fullContent = 'This is the full content of the learning that should be returned.'; + const learnings = [ + createLearning({ + id: 'l1', + title: 'Test Learning', + content: fullContent, + tags: ['test'], + }), + ]; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + injector = new MemoryInjector('/test/project'); + + const fullMemories = injector.getFullMemories(['l1']); + + if (fullMemories.length > 0) { + expect(fullMemories[0].content).toBe(fullContent); + } + }); + }); + + describe('search', () => { + it('should search memories by query', () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'React hooks patterns', + content: 'How to use useEffect and useState effectively.', + tags: ['react', 'hooks'], + }), + createLearning({ + id: 'l2', + title: 'Python data analysis', + content: 'Using pandas for data manipulation.', + tags: ['python', 'data'], + }), + ]; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + injector = new MemoryInjector('/test/project'); + + const results = injector.search('react hooks'); + + // React learning should be found + const reactResult = results.find((r) => r.learning.id === 'l1'); + if (results.length > 0 && reactResult) { + expect(reactResult.matchedBy.keywords.length).toBeGreaterThanOrEqual(0); + } + }); + + it('should respect minRelevance in search', () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'Unrelated topic', + content: 'Nothing to do with the search.', + tags: ['other'], + }), + ]; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue( + JSON.stringify(createMockLearningsYaml(learnings)) + ); + + injector = new MemoryInjector('/test/project'); + + const results = injector.search('completely different query', { minRelevance: 80 }); + + expect(results).toHaveLength(0); + }); + }); + + describe('formatForAgent', () => { + it('should escape XML special characters for Claude', () => { + const learnings = [ + createLearning({ + id: 'l1', + title: 'Test