cozo-memory 1.1.6 → 1.1.8

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.
@@ -0,0 +1,258 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const cozo_node_1 = require("cozo-node");
4
+ const spreading_activation_1 = require("./spreading-activation");
5
+ const embedding_service_1 = require("./embedding-service");
6
+ async function testSpreadingActivation() {
7
+ console.log('=== SYNAPSE Spreading Activation Test ===\n');
8
+ const db = new cozo_node_1.CozoDb();
9
+ const embeddingService = new embedding_service_1.EmbeddingService();
10
+ const synapseService = new spreading_activation_1.SpreadingActivationService(db, embeddingService, {
11
+ spreadingFactor: 0.8,
12
+ decayFactor: 0.5,
13
+ temporalDecay: 0.01,
14
+ inhibitionBeta: 0.15,
15
+ inhibitionTopM: 7,
16
+ propagationSteps: 3,
17
+ });
18
+ try {
19
+ // Setup: Create test graph
20
+ console.log('--- Setup: Creating test knowledge graph ---');
21
+ // Create entity relation
22
+ await db.run(`
23
+ :create entity {
24
+ id: String,
25
+ name: String,
26
+ type: String,
27
+ =>
28
+ embedding: <F32; 1024>,
29
+ metadata: Any
30
+ }
31
+ `);
32
+ // Create relationship relation
33
+ await db.run(`
34
+ :create relationship {
35
+ from_id: String,
36
+ to_id: String,
37
+ relation_type: String,
38
+ =>
39
+ strength: Float,
40
+ created_at: Int,
41
+ metadata: Any
42
+ }
43
+ `);
44
+ // Create entity_rank relation for PageRank
45
+ await db.run(`
46
+ :create entity_rank {
47
+ entity_id: String,
48
+ =>
49
+ rank: Float
50
+ }
51
+ `);
52
+ const now = Date.now();
53
+ const oneDayAgo = now - (24 * 60 * 60 * 1000);
54
+ const oneWeekAgo = now - (7 * 24 * 60 * 60 * 1000);
55
+ // Create entities
56
+ const entities = [
57
+ { id: 'e1', name: 'TypeScript', type: 'Technology' },
58
+ { id: 'e2', name: 'JavaScript', type: 'Technology' },
59
+ { id: 'e3', name: 'React', type: 'Framework' },
60
+ { id: 'e4', name: 'Node.js', type: 'Runtime' },
61
+ { id: 'e5', name: 'Alice', type: 'Person' },
62
+ { id: 'e6', name: 'Bob', type: 'Person' },
63
+ { id: 'e7', name: 'Frontend Development', type: 'Concept' },
64
+ { id: 'e8', name: 'Backend Development', type: 'Concept' },
65
+ ];
66
+ for (const entity of entities) {
67
+ const embedding = await embeddingService.embed(entity.name);
68
+ await db.run(`
69
+ ?[id, name, type, embedding, metadata] <- [
70
+ [$id, $name, $type, $embedding, {}]
71
+ ]
72
+ :put entity {id, name, type => embedding, metadata}
73
+ `, {
74
+ id: entity.id,
75
+ name: entity.name,
76
+ type: entity.type,
77
+ embedding,
78
+ });
79
+ }
80
+ // Create relationships (with temporal and strength variations)
81
+ const relationships = [
82
+ // TypeScript ecosystem
83
+ { from: 'e1', to: 'e2', type: 'superset_of', strength: 0.9, time: now },
84
+ { from: 'e1', to: 'e3', type: 'used_with', strength: 0.8, time: oneDayAgo },
85
+ { from: 'e1', to: 'e4', type: 'runs_on', strength: 0.7, time: oneDayAgo },
86
+ // React connections
87
+ { from: 'e3', to: 'e2', type: 'built_with', strength: 0.9, time: now },
88
+ { from: 'e3', to: 'e7', type: 'part_of', strength: 0.8, time: now },
89
+ // Node.js connections
90
+ { from: 'e4', to: 'e2', type: 'executes', strength: 0.9, time: now },
91
+ { from: 'e4', to: 'e8', type: 'part_of', strength: 0.8, time: now },
92
+ // People connections
93
+ { from: 'e5', to: 'e1', type: 'expert_in', strength: 0.9, time: now },
94
+ { from: 'e5', to: 'e3', type: 'uses', strength: 0.7, time: oneDayAgo },
95
+ { from: 'e6', to: 'e4', type: 'expert_in', strength: 0.9, time: now },
96
+ { from: 'e6', to: 'e8', type: 'works_on', strength: 0.8, time: now },
97
+ // Weak/old connection (should be dampened by temporal decay)
98
+ { from: 'e7', to: 'e8', type: 'related_to', strength: 0.3, time: oneWeekAgo },
99
+ ];
100
+ for (const rel of relationships) {
101
+ await db.run(`
102
+ ?[from_id, to_id, relation_type, strength, created_at, metadata] <- [
103
+ [$from_id, $to_id, $relation_type, $strength, $created_at, {}]
104
+ ]
105
+ :put relationship {from_id, to_id, relation_type => strength, created_at, metadata}
106
+ `, {
107
+ from_id: rel.from,
108
+ to_id: rel.to,
109
+ relation_type: rel.type,
110
+ strength: rel.strength,
111
+ created_at: rel.time,
112
+ });
113
+ }
114
+ // Create PageRank scores (simulated)
115
+ const pageRanks = [
116
+ { id: 'e1', rank: 0.25 }, // TypeScript - high importance
117
+ { id: 'e2', rank: 0.20 }, // JavaScript - high importance
118
+ { id: 'e3', rank: 0.15 }, // React
119
+ { id: 'e4', rank: 0.15 }, // Node.js
120
+ { id: 'e5', rank: 0.10 }, // Alice
121
+ { id: 'e6', rank: 0.08 }, // Bob
122
+ { id: 'e7', rank: 0.04 }, // Frontend
123
+ { id: 'e8', rank: 0.03 }, // Backend
124
+ ];
125
+ for (const pr of pageRanks) {
126
+ await db.run(`
127
+ ?[entity_id, rank] <- [[$entity_id, $rank]]
128
+ :put entity_rank {entity_id => rank}
129
+ `, { entity_id: pr.id, rank: pr.rank });
130
+ }
131
+ console.log('✓ Created 8 entities and 12 relationships\n');
132
+ // Test 1: Basic Spreading Activation
133
+ console.log('--- Test 1: Basic Spreading Activation ---');
134
+ console.log('Query: "TypeScript programming"');
135
+ const result1 = await synapseService.spreadActivation('TypeScript programming', 3);
136
+ console.log(`Iterations: ${result1.iterations}, Converged: ${result1.converged}`);
137
+ console.log(`Seed nodes: ${result1.seedNodes.join(', ')}`);
138
+ console.log('\nActivation Scores (Top 5):');
139
+ for (const score of result1.scores.slice(0, 5)) {
140
+ const entity = entities.find(e => e.id === score.entityId);
141
+ console.log(` ${entity?.name} (${score.entityId}): ${score.activation.toFixed(4)} [${score.source}, ${score.hops} hops]`);
142
+ }
143
+ console.log();
144
+ // Test 2: Multi-Hop Reasoning
145
+ console.log('--- Test 2: Multi-Hop Reasoning (Bridge Node Effect) ---');
146
+ console.log('Query: "Frontend expert" (should find Alice via TypeScript → React → Frontend)');
147
+ const result2 = await synapseService.spreadActivation('Frontend expert', 2);
148
+ console.log('\nActivation Scores (All activated nodes):');
149
+ for (const score of result2.scores) {
150
+ const entity = entities.find(e => e.id === score.entityId);
151
+ console.log(` ${entity?.name}: ${score.activation.toFixed(4)} [${score.source}]`);
152
+ }
153
+ console.log();
154
+ // Test 3: Temporal Decay Effect
155
+ console.log('--- Test 3: Temporal Decay Effect ---');
156
+ console.log('Recent connections should have higher activation than old ones');
157
+ // Create two similar relationships with different timestamps
158
+ const recentTime = now;
159
+ const oldTime = now - (30 * 24 * 60 * 60 * 1000); // 30 days ago
160
+ await db.run(`
161
+ ?[from_id, to_id, relation_type, strength, created_at, metadata] <- [
162
+ ['e_test_recent', 'e_test_target', 'test_rel', 0.8, $recent_time, {}],
163
+ ['e_test_old', 'e_test_target', 'test_rel', 0.8, $old_time, {}]
164
+ ]
165
+ :put relationship {from_id, to_id, relation_type => strength, created_at, metadata}
166
+ `, { recent_time: recentTime, old_time: oldTime });
167
+ console.log('✓ Created test relationships with different timestamps');
168
+ console.log(' Recent: strength=0.8, age=0 days');
169
+ console.log(' Old: strength=0.8, age=30 days');
170
+ console.log(' Expected: Recent should propagate more activation due to temporal decay\n');
171
+ // Test 4: Lateral Inhibition
172
+ console.log('--- Test 4: Lateral Inhibition ---');
173
+ console.log('High-activation nodes should suppress weaker competitors');
174
+ const result4 = await synapseService.spreadActivation('JavaScript TypeScript React', 5);
175
+ console.log('\nTop-M nodes (should inhibit others):');
176
+ const topM = result4.scores.slice(0, 7);
177
+ for (const score of topM) {
178
+ const entity = entities.find(e => e.id === score.entityId);
179
+ console.log(` ${entity?.name}: ${score.activation.toFixed(4)}`);
180
+ }
181
+ console.log('\nSuppressed nodes (below threshold):');
182
+ const suppressed = result4.scores.slice(7);
183
+ for (const score of suppressed) {
184
+ const entity = entities.find(e => e.id === score.entityId);
185
+ console.log(` ${entity?.name}: ${score.activation.toFixed(4)} (suppressed by inhibition)`);
186
+ }
187
+ console.log();
188
+ // Test 5: Triple Hybrid Retrieval
189
+ console.log('--- Test 5: Triple Hybrid Retrieval ---');
190
+ console.log('Query: "TypeScript development"');
191
+ console.log('Combining: Semantic (50%) + Activation (30%) + PageRank (20%)');
192
+ const result5 = await synapseService.tripleHybridRetrieval('TypeScript development', {
193
+ topK: 5,
194
+ lambdaSemantic: 0.5,
195
+ lambdaActivation: 0.3,
196
+ lambdaStructural: 0.2,
197
+ seedTopK: 3,
198
+ });
199
+ console.log('\nHybrid Scores (Top 5):');
200
+ for (const result of result5) {
201
+ const entity = entities.find(e => e.id === result.entityId);
202
+ console.log(` ${entity?.name}:`);
203
+ console.log(` Combined: ${result.score.toFixed(4)}`);
204
+ console.log(` Breakdown: ${result.breakdown.formula}`);
205
+ console.log(` Semantic: ${result.breakdown.semantic.toFixed(4)}`);
206
+ console.log(` Activation: ${result.breakdown.activation.toFixed(4)}`);
207
+ console.log(` Structural: ${result.breakdown.structural.toFixed(4)}`);
208
+ }
209
+ console.log();
210
+ // Test 6: Fan Effect
211
+ console.log('--- Test 6: Fan Effect (Attention Dilution) ---');
212
+ console.log('Nodes with many outgoing edges should dilute their activation');
213
+ // JavaScript has many connections (high fan)
214
+ // Alice has few connections (low fan)
215
+ const jsConnections = relationships.filter(r => r.from === 'e2').length;
216
+ const aliceConnections = relationships.filter(r => r.from === 'e5').length;
217
+ console.log(`JavaScript (e2) out-degree: ${jsConnections}`);
218
+ console.log(`Alice (e5) out-degree: ${aliceConnections}`);
219
+ console.log('Expected: Alice should spread more activation per edge due to lower fan\n');
220
+ // Test 7: Convergence Analysis
221
+ console.log('--- Test 7: Convergence Analysis ---');
222
+ console.log('Testing activation convergence over iterations');
223
+ const convergenceResults = [];
224
+ for (let steps = 1; steps <= 5; steps++) {
225
+ const service = new spreading_activation_1.SpreadingActivationService(db, embeddingService, {
226
+ propagationSteps: steps,
227
+ });
228
+ const result = await service.spreadActivation('TypeScript', 2);
229
+ convergenceResults.push({
230
+ steps,
231
+ converged: result.converged,
232
+ iterations: result.iterations,
233
+ totalActivation: result.scores.reduce((sum, s) => sum + s.activation, 0),
234
+ });
235
+ }
236
+ console.log('\nSteps | Converged | Iterations | Total Activation');
237
+ console.log('------|-----------|------------|------------------');
238
+ for (const res of convergenceResults) {
239
+ console.log(` ${res.steps} | ${res.converged ? 'Yes' : 'No '} | ${res.iterations} | ${res.totalActivation.toFixed(4)}`);
240
+ }
241
+ console.log();
242
+ console.log('✓ All SYNAPSE spreading activation tests completed successfully!\n');
243
+ console.log('Key Insights:');
244
+ console.log('- Spreading Activation propagates relevance through graph structure');
245
+ console.log('- Lateral Inhibition suppresses weak competitors, focusing on salient nodes');
246
+ console.log('- Fan Effect dilutes activation from high-degree nodes (attention distribution)');
247
+ console.log('- Temporal Decay prioritizes recent connections over old ones');
248
+ console.log('- Triple Hybrid combines geometric (semantic), dynamic (activation), and structural (PageRank) signals');
249
+ console.log('- System converges within 3 iterations, making it efficient for real-time retrieval');
250
+ }
251
+ catch (error) {
252
+ console.error('Test failed:', error);
253
+ }
254
+ finally {
255
+ db.close();
256
+ }
257
+ }
258
+ testSpreadingActivation().catch(console.error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cozo-memory",
3
- "version": "1.1.6",
3
+ "version": "1.1.8",
4
4
  "mcpName": "io.github.tobs-code/cozo-memory",
5
5
  "description": "Local-first persistent memory system for AI agents with hybrid search, graph reasoning, and MCP integration",
6
6
  "main": "dist/index.js",