Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

checkpoint: File edit:

rUv5ec4ce39a468
diff --git a/package.json b/package.json
index 7b22fef25f..d5ce328755 100644
--- a/package.json
+++ b/package.json
@@ -20,6 +20,7 @@
"zod": "^3.22.4"
},
"devDependencies": {
+ "@types/bcrypt": "^5.0.2",
"@types/node": "^20.0.0",
"tsx": "^4.0.0",
"typescript": "^5.0.0",
diff --git a/v3/__tests__/integration/agentic-flow-bridge.test.ts b/v3/__tests__/integration/agentic-flow-bridge.test.ts
new file mode 100644
index 0000000000..37b3ccb866
--- /dev/null
+++ b/v3/__tests__/integration/agentic-flow-bridge.test.ts
@@ -0,0 +1,398 @@
+/**
+ * AgenticFlowBridge Test Suite
+ *
+ * Comprehensive tests for the agentic-flow integration bridge.
+ * Tests initialization, component management, and lifecycle.
+ *
+ * @module v3/__tests__/integration/agentic-flow-bridge.test
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ AgenticFlowBridge,
+ createAgenticFlowBridge,
+ getDefaultBridge,
+ resetDefaultBridge,
+} from '../../integration/agentic-flow-bridge.js';
+import type { IntegrationConfig, FeatureFlags } from '../../integration/types.js';
+
+describe('AgenticFlowBridge', () => {
+ let bridge: AgenticFlowBridge;
+
+ beforeEach(() => {
+ bridge = new AgenticFlowBridge();
+ });
+
+ afterEach(async () => {
+ if (bridge) {
+ await bridge.shutdown();
+ }
+ await resetDefaultBridge();
+ });
+
+ describe('initialization', () => {
+ it('should initialize with default configuration', async () => {
+ await bridge.initialize();
+
+ const status = bridge.getStatus();
+ expect(status.initialized).toBe(true);
+ expect(status.connectedComponents).toContain('sdk');
+ });
+
+ it('should initialize with custom configuration', async () => {
+ const customConfig: Partial<IntegrationConfig> = {
+ features: {
+ enableSONA: true,
+ enableFlashAttention: false,
+ enableAgentDB: true,
+ enableTrajectoryTracking: true,
+ enableGNN: false,
+ enableIntelligenceBridge: true,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: true,
+ },
+ debug: true,
+ };
+
+ await bridge.initialize(customConfig);
+
+ const flags = bridge.getFeatureFlags();
+ expect(flags.enableSONA).toBe(true);
+ expect(flags.enableFlashAttention).toBe(false);
+ });
+
+ it('should be idempotent - multiple initialize calls are safe', async () => {
+ await bridge.initialize();
+ await bridge.initialize();
+ await bridge.initialize();
+
+ const status = bridge.getStatus();
+ expect(status.initialized).toBe(true);
+ });
+
+ it('should emit initialized event', async () => {
+ const handler = vi.fn();
+ bridge.on('initialized', handler);
+
+ await bridge.initialize();
+
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(handler).toHaveBeenCalledWith(
+ expect.objectContaining({
+ duration: expect.any(Number),
+ components: expect.any(Array),
+ })
+ );
+ });
+ });
+
+ describe('runtime detection', () => {
+ it('should detect runtime information', async () => {
+ await bridge.initialize();
+
+ const status = bridge.getStatus();
+ expect(status.runtime).toBeDefined();
+ expect(status.runtime.platform).toMatch(/linux|darwin|win32/);
+ expect(status.runtime.arch).toMatch(/x64|arm64|ia32/);
+ expect(status.runtime.nodeVersion).toMatch(/^v\d+/);
+ });
+
+ it('should determine performance tier', async () => {
+ await bridge.initialize();
+
+ const status = bridge.getStatus();
+ expect(['optimal', 'good', 'fallback']).toContain(
+ status.runtime.performanceTier
+ );
+ });
+ });
+
+ describe('component management', () => {
+ it('should provide SONA adapter when enabled', async () => {
+ await bridge.initialize({
+ features: {
+ enableSONA: true,
+ enableFlashAttention: false,
+ enableAgentDB: false,
+ enableTrajectoryTracking: false,
+ enableGNN: false,
+ enableIntelligenceBridge: false,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: false,
+ },
+ });
+
+ const sona = await bridge.getSONAAdapter();
+ expect(sona).toBeDefined();
+ });
+
+ it('should throw when SONA is disabled', async () => {
+ await bridge.initialize({
+ features: {
+ enableSONA: false,
+ enableFlashAttention: true,
+ enableAgentDB: true,
+ enableTrajectoryTracking: false,
+ enableGNN: false,
+ enableIntelligenceBridge: false,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: false,
+ },
+ });
+
+ await expect(bridge.getSONAAdapter()).rejects.toThrow('disabled');
+ });
+
+ it('should provide Attention coordinator when enabled', async () => {
+ await bridge.initialize({
+ features: {
+ enableSONA: false,
+ enableFlashAttention: true,
+ enableAgentDB: false,
+ enableTrajectoryTracking: false,
+ enableGNN: false,
+ enableIntelligenceBridge: false,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: false,
+ },
+ });
+
+ const attention = await bridge.getAttentionCoordinator();
+ expect(attention).toBeDefined();
+ });
+
+ it('should throw when Attention is disabled', async () => {
+ await bridge.initialize({
+ features: {
+ enableSONA: true,
+ enableFlashAttention: false,
+ enableAgentDB: true,
+ enableTrajectoryTracking: false,
+ enableGNN: false,
+ enableIntelligenceBridge: false,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: false,
+ },
+ });
+
+ await expect(bridge.getAttentionCoordinator()).rejects.toThrow('disabled');
+ });
+
+ it('should provide SDK bridge', async () => {
+ await bridge.initialize();
+
+ const sdk = await bridge.getSDKBridge();
+ expect(sdk).toBeDefined();
+ });
+ });
+
+ describe('feature management', () => {
+ it('should check if feature is enabled', async () => {
+ await bridge.initialize({
+ features: {
+ enableSONA: true,
+ enableFlashAttention: false,
+ enableAgentDB: true,
+ enableTrajectoryTracking: true,
+ enableGNN: true,
+ enableIntelligenceBridge: true,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: true,
+ },
+ });
+
+ expect(bridge.isFeatureEnabled('enableSONA')).toBe(true);
+ expect(bridge.isFeatureEnabled('enableFlashAttention')).toBe(false);
+ });
+
+ it('should enable feature dynamically', async () => {
+ await bridge.initialize({
+ features: {
+ enableSONA: false,
+ enableFlashAttention: true,
+ enableAgentDB: true,
+ enableTrajectoryTracking: false,
+ enableGNN: false,
+ enableIntelligenceBridge: false,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: false,
+ },
+ });
+
+ expect(bridge.isFeatureEnabled('enableSONA')).toBe(false);
+
+ await bridge.enableFeature('enableSONA');
+
+ expect(bridge.isFeatureEnabled('enableSONA')).toBe(true);
+ });
+
+ it('should disable feature dynamically', async () => {
+ await bridge.initialize({
+ features: {
+ enableSONA: true,
+ enableFlashAttention: true,
+ enableAgentDB: true,
+ enableTrajectoryTracking: true,
+ enableGNN: true,
+ enableIntelligenceBridge: true,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: true,
+ },
+ });
+
+ expect(bridge.isFeatureEnabled('enableSONA')).toBe(true);
+
+ await bridge.disableFeature('enableSONA');
+
+ expect(bridge.isFeatureEnabled('enableSONA')).toBe(false);
+ });
+
+ it('should emit feature-enabled event', async () => {
+ await bridge.initialize({
+ features: {
+ enableSONA: false,
+ enableFlashAttention: true,
+ enableAgentDB: true,
+ enableTrajectoryTracking: false,
+ enableGNN: false,
+ enableIntelligenceBridge: false,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: false,
+ },
+ });
+
+ const handler = vi.fn();
+ bridge.on('feature-enabled', handler);
+
+ await bridge.enableFeature('enableSONA');
+
+ expect(handler).toHaveBeenCalledWith({ feature: 'enableSONA' });
+ });
+ });
+
+ describe('health check', () => {
+ it('should perform health check on all components', async () => {
+ await bridge.initialize();
+
+ const health = await bridge.healthCheck();
+
+ expect(health['sdk']).toBeDefined();
+ expect(health['sdk'].status).toBe('healthy');
+ });
+
+ it('should report unhealthy components', async () => {
+ await bridge.initialize();
+
+ // Get health with all components
+ const health = await bridge.healthCheck();
+
+ for (const component of Object.values(health)) {
+ expect(['healthy', 'degraded', 'unhealthy']).toContain(component.status);
+ }
+ });
+ });
+
+ describe('reconfiguration', () => {
+ it('should reconfigure bridge settings', async () => {
+ await bridge.initialize({
+ features: {
+ enableSONA: true,
+ enableFlashAttention: true,
+ enableAgentDB: true,
+ enableTrajectoryTracking: true,
+ enableGNN: true,
+ enableIntelligenceBridge: true,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: true,
+ },
+ });
+
+ await bridge.reconfigure({
+ debug: true,
+ });
+
+ // Should emit reconfigured event
+ const handler = vi.fn();
+ bridge.on('reconfigured', handler);
+
+ await bridge.reconfigure({
+ debug: false,
+ });
+
+ expect(handler).toHaveBeenCalled();
+ });
+ });
+
+ describe('shutdown', () => {
+ it('should shutdown gracefully', async () => {
+ await bridge.initialize();
+
+ const shutdownHandler = vi.fn();
+ bridge.on('shutdown', shutdownHandler);
+
+ await bridge.shutdown();
+
+ expect(shutdownHandler).toHaveBeenCalled();
+
+ const status = bridge.getStatus();
+ expect(status.initialized).toBe(false);
+ });
+
+ it('should clear all components on shutdown', async () => {
+ await bridge.initialize({
+ features: {
+ enableSONA: true,
+ enableFlashAttention: true,
+ enableAgentDB: true,
+ enableTrajectoryTracking: true,
+ enableGNN: true,
+ enableIntelligenceBridge: true,
+ enableQUICTransport: false,
+ enableNightlyLearning: false,
+ enableAutoConsolidation: true,
+ },
+ });
+
+ await bridge.shutdown();
+
+ const status = bridge.getStatus();
+ expect(status.connectedComponents).toHaveLength(0);
+ });
+ });
+
+ describe('factory functions', () => {
+ it('should create bridge with createAgenticFlowBridge', async () => {
+ const newBridge = await createAgenticFlowBridge();
+
+ const status = newBridge.getStatus();
+ expect(status.initialized).toBe(true);
+
+ await newBridge.shutdown();
+ });
+
+ it('should provide singleton with getDefaultBridge', async () => {
+ const bridge1 = await getDefaultBridge();
+ const bridge2 = await getDefaultBridge();
+
+ expect(bridge1).toBe(bridge2);
+ });
+
+ it('should reset singleton with resetDefaultBridge', async () => {
+ const bridge1 = await getDefaultBridge();
+ await resetDefaultBridge();
+ const bridge2 = await getDefaultBridge();
+
+ expect(bridge1).not.toBe(bridge2);
+ });
+ });
+});
diff --git a/v3/__tests__/integration/sona-adapter.test.ts b/v3/__tests__/integration/sona-adapter.test.ts
new file mode 100644
index 0000000000..2b0a2cf930
--- /dev/null
+++ b/v3/__tests__/integration/sona-adapter.test.ts
@@ -0,0 +1,510 @@
+/**
+ * SONAAdapter Test Suite
+ *
+ * Comprehensive tests for the SONA learning adapter.
+ * Tests trajectory tracking, pattern storage, and learning modes.
+ *
+ * @module v3/__tests__/integration/sona-adapter.test
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ SONAAdapter,
+ createSONAAdapter,
+} from '../../integration/sona-adapter.js';
+import type { SONAConfiguration, SONALearningMode } from '../../integration/types.js';
+
+describe('SONAAdapter', () => {
+ let adapter: SONAAdapter;
+
+ beforeEach(async () => {
+ adapter = new SONAAdapter();
+ await adapter.initialize();
+ });
+
+ afterEach(async () => {
+ if (adapter) {
+ await adapter.shutdown();
+ }
+ });
+
+ describe('initialization', () => {
+ it('should initialize with default configuration', async () => {
+ const newAdapter = new SONAAdapter();
+ await newAdapter.initialize();
+
+ expect(newAdapter.getMode()).toBe('balanced');
+
+ await newAdapter.shutdown();
+ });
+
+ it('should initialize with custom configuration', async () => {
+ const newAdapter = new SONAAdapter({
+ mode: 'real-time',
+ learningRate: 0.01,
+ maxPatterns: 5000,
+ });
+ await newAdapter.initialize();
+
+ expect(newAdapter.getMode()).toBe('real-time');
+
+ await newAdapter.shutdown();
+ });
+
+ it('should emit initialized event', async () => {
+ const newAdapter = new SONAAdapter();
+ const handler = vi.fn();
+ newAdapter.on('initialized', handler);
+
+ await newAdapter.initialize();
+
+ expect(handler).toHaveBeenCalledWith({ mode: 'balanced' });
+
+ await newAdapter.shutdown();
+ });
+ });
+
+ describe('learning modes', () => {
+ const modes: SONALearningMode[] = [
+ 'real-time',
+ 'balanced',
+ 'research',
+ 'edge',
+ 'batch',
+ ];
+
+ it.each(modes)('should switch to %s mode', async (mode) => {
+ await adapter.setMode(mode);
+ expect(adapter.getMode()).toBe(mode);
+ });
+
+ it('should emit mode-changed event', async () => {
+ const handler = vi.fn();
+ adapter.on('mode-changed', handler);
+
+ await adapter.setMode('research');
+
+ expect(handler).toHaveBeenCalledWith(
+ expect.objectContaining({
+ previousMode: 'balanced',
+ newMode: 'research',
+ })
+ );
+ });
+
+ it('should apply mode-specific configuration', async () => {
+ await adapter.setMode('edge');
+
+ const stats = await adapter.getStats();
+ expect(stats.currentMode).toBe('edge');
+ });
+ });
+
+ describe('trajectory tracking', () => {
+ it('should begin a new trajectory', async () => {
+ const trajectoryId = await adapter.beginTrajectory({
+ taskId: 'test-task-1',
+ description: 'Test trajectory',
+ category: 'testing',
+ });
+
+ expect(trajectoryId).toMatch(/^traj_/);
+ });
+
+ it('should record trajectory steps', async () => {
+ const trajectoryId = await adapter.beginTrajectory({
+ taskId: 'test-task-1',
+ });
+
+ await adapter.recordTrajectoryStep({
+ trajectoryId,
+ action: 'Action 1',
+ observation: 'Observation 1',
+ reward: 0.5,
+ });
+
+ await adapter.recordTrajectoryStep({
+ trajectoryId,
+ action: 'Action 2',
+ observation: 'Observation 2',
+ reward: 0.8,
+ });
+
+ const trajectory = await adapter.endTrajectory({
+ trajectoryId,
+ success: true,
+ });
+
+ expect(trajectory.steps).toHaveLength(2);
+ expect(trajectory.totalReward).toBe(1.3);
+ });
+
+ it('should end trajectory with verdict', async () => {
+ const trajectoryId = await adapter.beginTrajectory({
+ taskId: 'test-task-1',
+ });
+
+ const trajectory = await adapter.endTrajectory({
+ trajectoryId,
+ success: true,
+ verdict: 'positive',
+ reward: 1.0,
+ });
+
+ expect(trajectory.verdict).toBe('positive');
+ expect(trajectory.endTime).toBeDefined();
+ });
+
+ it('should throw for non-existent trajectory', async () => {
+ await expect(
+ adapter.recordTrajectoryStep({
+ trajectoryId: 'non-existent',
+ action: 'test',
+ observation: 'test',
+ reward: 0,
+ })
+ ).rejects.toThrow('not found');
+ });
+
+ it('should emit trajectory events', async () => {
+ const startHandler = vi.fn();
+ const stepHandler = vi.fn();
+ const completeHandler = vi.fn();
+
+ adapter.on('trajectory-started', startHandler);
+ adapter.on('trajectory-step-recorded', stepHandler);
+ adapter.on('trajectory-completed', completeHandler);
+
+ const trajectoryId = await adapter.beginTrajectory({
+ taskId: 'test-task-1',
+ });
+
+ await adapter.recordTrajectoryStep({
+ trajectoryId,
+ action: 'Action',
+ observation: 'Observation',
+ reward: 0.5,
+ });
+
+ await adapter.endTrajectory({
+ trajectoryId,
+ success: true,
+ });
+
+ expect(startHandler).toHaveBeenCalled();
+ expect(stepHandler).toHaveBeenCalled();
+ expect(completeHandler).toHaveBeenCalled();
+ });
+
+ it('should update stats for active trajectories', async () => {
+ const id1 = await adapter.beginTrajectory({ taskId: 'task-1' });
+ const id2 = await adapter.beginTrajectory({ taskId: 'task-2' });
+
+ const stats = await adapter.getStats();
+ expect(stats.activeTrajectories).toBe(2);
+
+ await adapter.endTrajectory({ trajectoryId: id1, success: true });
+
+ const updatedStats = await adapter.getStats();
+ expect(updatedStats.activeTrajectories).toBe(1);
+ expect(updatedStats.completedTrajectories).toBe(1);
+
+ await adapter.endTrajectory({ trajectoryId: id2, success: false });
+ });
+ });
+
+ describe('pattern storage', () => {
+ it('should store a pattern', async () => {
+ const patternId = await adapter.storePattern({
+ pattern: 'Test pattern',
+ solution: 'Test solution',
+ category: 'testing',
+ confidence: 0.9,
+ });
+
+ expect(patternId).toMatch(/^pat_/);
+ });
+
+ it('should retrieve stored pattern', async () => {
+ const patternId = await adapter.storePattern({
+ pattern: 'Test pattern',
+ solution: 'Test solution',
+ category: 'testing',
+ confidence: 0.9,
+ });
+
+ const pattern = await adapter.getPattern(patternId);
+
+ expect(pattern).toBeDefined();
+ expect(pattern!.pattern).toBe('Test pattern');
+ expect(pattern!.solution).toBe('Test solution');
+ expect(pattern!.confidence).toBe(0.9);
+ });
+
+ it('should return null for non-existent pattern', async () => {
+ const pattern = await adapter.getPattern('non-existent');
+ expect(pattern).toBeNull();
+ });
+
+ it('should delete pattern', async () => {
+ const patternId = await adapter.storePattern({
+ pattern: 'Test pattern',
+ solution: 'Test solution',
+ category: 'testing',
+ confidence: 0.9,
+ });
+
+ const deleted = await adapter.deletePattern(patternId);
+ expect(deleted).toBe(true);
+
+ const pattern = await adapter.getPattern(patternId);
+ expect(pattern).toBeNull();
+ });
+
+ it('should clamp confidence to valid range', async () => {
+ const patternId = await adapter.storePattern({
+ pattern: 'Test pattern',
+ solution: 'Test solution',
+ category: 'testing',
+ confidence: 1.5, // Should be clamped to 1.0
+ });
+
+ const pattern = await adapter.getPattern(patternId);
+ expect(pattern!.confidence).toBe(1.0);
+ });
+ });
+
+ describe('pattern search', () => {
+ beforeEach(async () => {
+ // Store some test patterns
+ await adapter.storePattern({
+ pattern: 'authentication login user',
+ solution: 'Use JWT tokens',
+ category: 'security',
+ confidence: 0.9,
+ });
+
+ await adapter.storePattern({
+ pattern: 'authentication oauth provider',
+ solution: 'Use OAuth 2.0',
+ category: 'security',
+ confidence: 0.85,
+ });
+
+ await adapter.storePattern({
+ pattern: 'database query optimization',
+ solution: 'Add indexes',
+ category: 'performance',
+ confidence: 0.95,
+ });
+ });
+
+ it('should find similar patterns', async () => {
+ const results = await adapter.findSimilarPatterns({
+ query: 'authentication user login',
+ topK: 5,
+ });
+
+ expect(results.length).toBeGreaterThan(0);
+ });
+
+ it('should filter by category', async () => {
+ const results = await adapter.findSimilarPatterns({
+ query: 'authentication',
+ category: 'security',
+ topK: 10,
+ });
+
+ for (const pattern of results) {
+ expect(pattern.category).toBe('security');
+ }
+ });
+
+ it('should respect topK limit', async () => {
+ const results = await adapter.findSimilarPatterns({
+ query: 'authentication',
+ topK: 1,
+ });
+
+ expect(results.length).toBeLessThanOrEqual(1);
+ });
+
+ it('should update usage count on retrieval', async () => {
+ const patternId = await adapter.storePattern({
+ pattern: 'test usage tracking',
+ solution: 'test solution',
+ category: 'testing',
+ confidence: 0.9,
+ });
+
+ // Search for the pattern
+ await adapter.findSimilarPatterns({
+ query: 'test usage tracking',
+ topK: 5,
+ });
+
+ const pattern = await adapter.getPattern(patternId);
+ expect(pattern!.usageCount).toBeGreaterThan(0);
+ });
+ });
+
+ describe('learning cycle', () => {
+ it('should force learning cycle', async () => {
+ const handler = vi.fn();
+ adapter.on('learning-cycle-completed', handler);
+
+ await adapter.forceLearningCycle();
+
+ expect(handler).toHaveBeenCalled();
+ });
+
+ it('should update stats after learning cycle', async () => {
+ const statsBefore = await adapter.getStats();
+
+ await adapter.forceLearningCycle();
+
+ const statsAfter = await adapter.getStats();
+ expect(statsAfter.learningCycles).toBe(statsBefore.learningCycles + 1);
+ });
+ });
+
+ describe('pattern import/export', () => {
+ it('should export patterns', async () => {
+ await adapter.storePattern({
+ pattern: 'Export test 1',
+ solution: 'Solution 1',
+ category: 'testing',
+ confidence: 0.9,
+ });
+
+ await adapter.storePattern({
+ pattern: 'Export test 2',
+ solution: 'Solution 2',
+ category: 'testing',
+ confidence: 0.8,
+ });
+
+ const exported = await adapter.exportPatterns();
+
+ expect(exported.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it('should import patterns', async () => {
+ const patterns = [
+ {
+ id: 'import-1',
+ pattern: 'Import test 1',
+ solution: 'Solution 1',
+ category: 'testing',
+ confidence: 0.9,
+ usageCount: 5,
+ createdAt: Date.now(),
+ lastUsedAt: Date.now(),
+ metadata: {},
+ },
+ {
+ id: 'import-2',
+ pattern: 'Import test 2',
+ solution: 'Solution 2',
+ category: 'testing',
+ confidence: 0.8,
+ usageCount: 3,
+ createdAt: Date.now(),
+ lastUsedAt: Date.now(),
+ metadata: {},
+ },
+ ];
+
+ const imported = await adapter.importPatterns(patterns);
+ expect(imported).toBe(2);
+
+ const pattern = await adapter.getPattern('import-1');
+ expect(pattern).toBeDefined();
+ });
+
+ it('should not import duplicate patterns', async () => {
+ const patterns = [
+ {
+ id: 'unique-id',
+ pattern: 'Test',
+ solution: 'Solution',
+ category: 'testing',
+ confidence: 0.9,
+ usageCount: 0,
+ createdAt: Date.now(),
+ lastUsedAt: Date.now(),
+ metadata: {},
+ },
+ ];
+
+ const firstImport = await adapter.importPatterns(patterns);
+ const secondImport = await adapter.importPatterns(patterns);
+
+ expect(firstImport).toBe(1);
+ expect(secondImport).toBe(0);
+ });
+ });
+
+ describe('statistics', () => {
+ it('should return learning statistics', async () => {
+ const stats = await adapter.getStats();
+
+ expect(stats).toHaveProperty('totalPatterns');
+ expect(stats).toHaveProperty('activeTrajectories');
+ expect(stats).toHaveProperty('completedTrajectories');
+ expect(stats).toHaveProperty('averageConfidence');
+ expect(stats).toHaveProperty('learningCycles');
+ expect(stats).toHaveProperty('lastConsolidation');
+ expect(stats).toHaveProperty('memoryUsage');
+ expect(stats).toHaveProperty('currentMode');
+ });
+
+ it('should track average confidence', async () => {
+ await adapter.storePattern({
+ pattern: 'P1',
+ solution: 'S1',
+ category: 'test',
+ confidence: 0.8,
+ });
+
+ await adapter.storePattern({
+ pattern: 'P2',
+ solution: 'S2',
+ category: 'test',
+ confidence: 0.6,
+ });
+
+ const stats = await adapter.getStats();
+ expect(stats.averageConfidence).toBeCloseTo(0.7, 1);
+ });
+ });
+
+ describe('factory function', () => {
+ it('should create initialized adapter', async () => {
+ const newAdapter = await createSONAAdapter({
+ mode: 'research',
+ });
+
+ expect(newAdapter.getMode()).toBe('research');
+
+ await newAdapter.shutdown();
+ });
+ });
+
+ describe('shutdown', () => {
+ it('should complete active trajectories on shutdown', async () => {
+ const id = await adapter.beginTrajectory({ taskId: 'test' });
+
+ await adapter.shutdown();
+
+ // Adapter should be in a clean state
+ const newAdapter = new SONAAdapter();
+ await newAdapter.initialize();
+
+ const stats = await newAdapter.getStats();
+ expect(stats.activeTrajectories).toBe(0);
+
+ await newAdapter.shutdown();
+ });
+ });
+});