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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class AdvancedMemoryManager {
|
| 2 |
+
constructor(config = {}) {
|
| 3 |
+
// Configurable embedding models
|
| 4 |
+
this.embeddingModels = {
|
| 5 |
+
default: new SemanticEmbedding(),
|
| 6 |
+
multilingual: new MultilingualEmbedding(),
|
| 7 |
+
specialized: {
|
| 8 |
+
text: new TextSpecificEmbedding(),
|
| 9 |
+
numerical: new NumericalEmbedding()
|
| 10 |
+
}
|
| 11 |
+
};
|
| 12 |
+
|
| 13 |
+
// Adaptive pruning configuration
|
| 14 |
+
this.pruningConfig = {
|
| 15 |
+
strategies: [
|
| 16 |
+
'temporal_decay',
|
| 17 |
+
'importance_score',
|
| 18 |
+
'relationship_density'
|
| 19 |
+
],
|
| 20 |
+
thresholds: {
|
| 21 |
+
maxMemorySize: config.maxMemorySize || 10000,
|
| 22 |
+
compressionTrigger: config.compressionTrigger || 0.8
|
| 23 |
+
}
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
// Advanced indexing for efficient retrieval
|
| 27 |
+
this.semanticIndex = new ApproximateNearestNeighborIndex();
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
async selectOptimalEmbeddingModel(content) {
|
| 31 |
+
// Dynamically select most appropriate embedding model
|
| 32 |
+
if (this.isMultilingualContent(content)) {
|
| 33 |
+
return this.embeddingModels.multilingual;
|
| 34 |
+
}
|
| 35 |
+
if (this.isNumericalContent(content)) {
|
| 36 |
+
return this.embeddingModels.specialized.numerical;
|
| 37 |
+
}
|
| 38 |
+
return this.embeddingModels.default;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
async insert(content, options = {}) {
|
| 42 |
+
const embeddingModel = await this.selectOptimalEmbeddingModel(content);
|
| 43 |
+
const memoryItem = new MemoryItem(content, {
|
| 44 |
+
...options,
|
| 45 |
+
embeddingModel
|
| 46 |
+
});
|
| 47 |
+
|
| 48 |
+
// Advanced indexing and relationship tracking
|
| 49 |
+
this.semanticIndex.add(memoryItem);
|
| 50 |
+
this.trackRelationships(memoryItem);
|
| 51 |
+
|
| 52 |
+
return memoryItem;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
async intelligentRetrieve(query, options = {}) {
|
| 56 |
+
const {
|
| 57 |
+
maxResults = 10,
|
| 58 |
+
similarityThreshold = 0.7,
|
| 59 |
+
includeRelated = true
|
| 60 |
+
} = options;
|
| 61 |
+
|
| 62 |
+
// Semantic and relationship-aware retrieval
|
| 63 |
+
const semanticResults = this.semanticIndex.search(query, {
|
| 64 |
+
maxResults,
|
| 65 |
+
threshold: similarityThreshold
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
if (includeRelated) {
|
| 69 |
+
return this.expandWithRelatedMemories(semanticResults);
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
return semanticResults;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
async performMemoryCompression() {
|
| 76 |
+
const compressionCandidates = this.identifyCompressionCandidates();
|
| 77 |
+
const compressedMemories = compressionCandidates.map(this.compressMemory);
|
| 78 |
+
|
| 79 |
+
return {
|
| 80 |
+
originalCount: compressionCandidates.length,
|
| 81 |
+
compressedCount: compressedMemories.length,
|
| 82 |
+
compressionRatio: compressedMemories.length / compressionCandidates.length
|
| 83 |
+
};
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
const natural = require('natural');
|
| 87 |
+
const tf = require('@tensorflow/tfjs-node');
|
| 88 |
+
const { Word2Vec } = require('word2vec');
|
| 89 |
+
|
| 90 |
+
class SemanticEmbedding {
|
| 91 |
+
constructor() {
|
| 92 |
+
this.model = null;
|
| 93 |
+
this.vectorSize = 100;
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
async initialize() {
|
| 97 |
+
// Placeholder for more advanced embedding initialization
|
| 98 |
+
this.model = await tf.loadLayersModel('path/to/embedding/model');
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
async generateEmbedding(text) {
|
| 102 |
+
// Generate semantic vector representation
|
| 103 |
+
const tokens = natural.tokenize(text.toLowerCase());
|
| 104 |
+
const embedding = await this.model.predict(tokens);
|
| 105 |
+
return embedding;
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
calculateSemanticSimilarity(embedding1, embedding2) {
|
| 109 |
+
// Cosine similarity calculation
|
| 110 |
+
return tf.losses.cosineDistance(embedding1, embedding2);
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
class MemoryItem {
|
| 115 |
+
constructor(content, {
|
| 116 |
+
type = "text",
|
| 117 |
+
isFactual = 0.5,
|
| 118 |
+
source = null,
|
| 119 |
+
confidence = 0.5
|
| 120 |
+
} = {}) {
|
| 121 |
+
this.id = crypto.randomUUID(); // Unique identifier
|
| 122 |
+
this.content = content;
|
| 123 |
+
this.type = type;
|
| 124 |
+
this.isFactual = isFactual;
|
| 125 |
+
this.confidence = confidence;
|
| 126 |
+
this.source = source;
|
| 127 |
+
|
| 128 |
+
this.timestamp = Date.now();
|
| 129 |
+
this.accessCount = 0;
|
| 130 |
+
this.importance = 5;
|
| 131 |
+
|
| 132 |
+
this.embedding = null;
|
| 133 |
+
this.related = new Map(); // Enhanced relationship tracking
|
| 134 |
+
this.tags = new Set();
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
async computeEmbedding(embeddingService) {
|
| 138 |
+
this.embedding = await embeddingService.generateEmbedding(this.content);
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
addRelationship(memoryItem, weight = 1.0) {
|
| 142 |
+
this.related.set(memoryItem.id, {
|
| 143 |
+
memory: memoryItem,
|
| 144 |
+
weight: weight,
|
| 145 |
+
type: this.determineRelationshipType(memoryItem)
|
| 146 |
+
});
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
determineRelationshipType(memoryItem) {
|
| 150 |
+
// Semantic relationship type inference
|
| 151 |
+
const semanticDistance = this.calculateSemanticDistance(memoryItem);
|
| 152 |
+
if (semanticDistance < 0.2) return 'VERY_CLOSE';
|
| 153 |
+
if (semanticDistance < 0.5) return 'RELATED';
|
| 154 |
+
return 'DISTANT';
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
calculateSemanticDistance(memoryItem) {
|
| 158 |
+
// Placeholder for semantic distance calculation
|
| 159 |
+
return Math.random(); // Replace with actual embedding comparison
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
incrementAccess() {
|
| 163 |
+
this.accessCount++;
|
| 164 |
+
this.updateImportance();
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
updateImportance() {
|
| 168 |
+
// Dynamic importance calculation
|
| 169 |
+
this.importance = Math.min(
|
| 170 |
+
10,
|
| 171 |
+
5 + Math.log(this.accessCount + 1)
|
| 172 |
+
);
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
class MemoryTier {
|
| 177 |
+
constructor(name, {
|
| 178 |
+
maxCapacity = Infinity,
|
| 179 |
+
pruneStrategy = 'LRU'
|
| 180 |
+
} = {}) {
|
| 181 |
+
this.name = name;
|
| 182 |
+
this.items = new Map(); // Use Map for efficient lookups
|
| 183 |
+
this.maxCapacity = maxCapacity;
|
| 184 |
+
this.pruneStrategy = pruneStrategy;
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
insert(memoryItem) {
|
| 188 |
+
if (this.items.size >= this.maxCapacity) {
|
| 189 |
+
this.prune();
|
| 190 |
+
}
|
| 191 |
+
this.items.set(memoryItem.id, memoryItem);
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
prune() {
|
| 195 |
+
switch(this.pruneStrategy) {
|
| 196 |
+
case 'LRU':
|
| 197 |
+
const lruItem = Array.from(this.items.values())
|
| 198 |
+
.sort((a, b) => a.timestamp - b.timestamp)[0];
|
| 199 |
+
this.items.delete(lruItem.id);
|
| 200 |
+
break;
|
| 201 |
+
case 'LEAST_IMPORTANT':
|
| 202 |
+
const leastImportant = Array.from(this.items.values())
|
| 203 |
+
.sort((a, b) => a.importance - b.importance)[0];
|
| 204 |
+
this.items.delete(leastImportant.id);
|
| 205 |
+
break;
|
| 206 |
+
}
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
async retrieve(query, embeddingService, topK = 5) {
|
| 210 |
+
const queryEmbedding = await embeddingService.generateEmbedding(query);
|
| 211 |
+
|
| 212 |
+
const scoredResults = Array.from(this.items.values())
|
| 213 |
+
.map(item => ({
|
| 214 |
+
memory: item,
|
| 215 |
+
similarity: embeddingService.calculateSemanticSimilarity(
|
| 216 |
+
item.embedding,
|
| 217 |
+
queryEmbedding
|
| 218 |
+
)
|
| 219 |
+
}))
|
| 220 |
+
.sort((a, b) => b.similarity - a.similarity)
|
| 221 |
+
.slice(0, topK);
|
| 222 |
+
|
| 223 |
+
return scoredResults.map(r => r.memory);
|
| 224 |
+
}
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
class MemoryManager {
|
| 228 |
+
constructor() {
|
| 229 |
+
this.embeddingService = new SemanticEmbedding();
|
| 230 |
+
|
| 231 |
+
this.volatileShortTerm = new MemoryTier("Volatile Short-Term", {
|
| 232 |
+
maxCapacity: 10,
|
| 233 |
+
pruneStrategy: 'LRU'
|
| 234 |
+
});
|
| 235 |
+
|
| 236 |
+
this.persistentLongTerm = new MemoryTier("Persistent Long-Term");
|
| 237 |
+
this.contextWorkingMemory = new MemoryTier("Context/Working Memory", {
|
| 238 |
+
maxCapacity: 5
|
| 239 |
+
});
|
| 240 |
+
|
| 241 |
+
this.allMemories = new Map();
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
async initialize() {
|
| 245 |
+
await this.embeddingService.initialize();
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
async insert(content, options = {}) {
|
| 249 |
+
const memoryItem = new MemoryItem(content, options);
|
| 250 |
+
await memoryItem.computeEmbedding(this.embeddingService);
|
| 251 |
+
|
| 252 |
+
// Insert into all appropriate tiers
|
| 253 |
+
this.volatileShortTerm.insert(memoryItem);
|
| 254 |
+
this.persistentLongTerm.insert(memoryItem);
|
| 255 |
+
this.contextWorkingMemory.insert(memoryItem);
|
| 256 |
+
|
| 257 |
+
this.allMemories.set(memoryItem.id, memoryItem);
|
| 258 |
+
return memoryItem;
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
async retrieve(query, tier = null) {
|
| 262 |
+
if (tier) {
|
| 263 |
+
return tier.retrieve(query, this.embeddingService);
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
// Parallel retrieval across tiers
|
| 267 |
+
const results = await Promise.all([
|
| 268 |
+
this.volatileShortTerm.retrieve(query, this.embeddingService),
|
| 269 |
+
this.persistentLongTerm.retrieve(query, this.embeddingService),
|
| 270 |
+
this.contextWorkingMemory.retrieve(query, this.embeddingService)
|
| 271 |
+
]);
|
| 272 |
+
|
| 273 |
+
// Flatten and deduplicate results
|
| 274 |
+
return [...new Set(results.flat())];
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
async findSemanticallySimilar(memoryItem, threshold = 0.7) {
|
| 278 |
+
const similar = [];
|
| 279 |
+
for (let [, memory] of this.allMemories) {
|
| 280 |
+
if (memory.id !== memoryItem.id) {
|
| 281 |
+
const similarity = this.embeddingService.calculateSemanticSimilarity(
|
| 282 |
+
memory.embedding,
|
| 283 |
+
memoryItem.embedding
|
| 284 |
+
);
|
| 285 |
+
if (similarity >= threshold) {
|
| 286 |
+
similar.push({ memory, similarity });
|
| 287 |
+
}
|
| 288 |
+
}
|
| 289 |
+
}
|
| 290 |
+
return similar.sort((a, b) => b.similarity - a.similarity);
|
| 291 |
+
}
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
// Example Usage
|
| 295 |
+
async function demonstrateMemorySystem() {
|
| 296 |
+
const memoryManager = new MemoryManager();
|
| 297 |
+
await memoryManager.initialize();
|
| 298 |
+
|
| 299 |
+
// Insert memories
|
| 300 |
+
const aiEthicsMem = await memoryManager.insert(
|
| 301 |
+
"AI should be developed with strong ethical considerations",
|
| 302 |
+
{
|
| 303 |
+
type: "concept",
|
| 304 |
+
isFactual: 0.9,
|
| 305 |
+
confidence: 0.8
|
| 306 |
+
}
|
| 307 |
+
);
|
| 308 |
+
|
| 309 |
+
const aiResearchMem = await memoryManager.insert(
|
| 310 |
+
"Machine learning research is advancing rapidly",
|
| 311 |
+
{
|
| 312 |
+
type: "research",
|
| 313 |
+
isFactual: 0.95
|
| 314 |
+
}
|
| 315 |
+
);
|
| 316 |
+
|
| 317 |
+
// Create relationships
|
| 318 |
+
aiEthicsMem.addRelationship(aiResearchMem);
|
| 319 |
+
|
| 320 |
+
// Retrieve memories
|
| 321 |
+
const retrievedMemories = await memoryManager.retrieve("AI ethics");
|
| 322 |
+
console.log("Retrieved Memories:", retrievedMemories);
|
| 323 |
+
|
| 324 |
+
// Find semantically similar memories
|
| 325 |
+
const similarMemories = await memoryManager.findSemanticallySimilar(aiEthicsMem);
|
| 326 |
+
console.log("Similar Memories:", similarMemories);
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
demonstrateMemorySystem();
|
| 330 |
+
|
| 331 |
+
module.exports = { MemoryManager, MemoryItem, MemoryTier };
|
| 332 |
+
class AdvancedMemoryManager {
|
| 333 |
+
constructor(config = {}) {
|
| 334 |
+
// Configurable embedding models
|
| 335 |
+
this.embeddingModels = {
|
| 336 |
+
default: new SemanticEmbedding(),
|
| 337 |
+
multilingual: new MultilingualEmbedding(),
|
| 338 |
+
specialized: {
|
| 339 |
+
text: new TextSpecificEmbedding(),
|
| 340 |
+
numerical: new NumericalEmbedding()
|
| 341 |
+
}
|
| 342 |
+
};
|
| 343 |
+
|
| 344 |
+
// Adaptive pruning configuration
|
| 345 |
+
this.pruningConfig = {
|
| 346 |
+
strategies: [
|
| 347 |
+
'temporal_decay',
|
| 348 |
+
'importance_score',
|
| 349 |
+
'relationship_density'
|
| 350 |
+
],
|
| 351 |
+
thresholds: {
|
| 352 |
+
maxMemorySize: config.maxMemorySize || 10000,
|
| 353 |
+
compressionTrigger: config.compressionTrigger || 0.8
|
| 354 |
+
}
|
| 355 |
+
};
|
| 356 |
+
|
| 357 |
+
// Advanced indexing for efficient retrieval
|
| 358 |
+
this.semanticIndex = new ApproximateNearestNeighborIndex();
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
async selectOptimalEmbeddingModel(content) {
|
| 362 |
+
// Dynamically select most appropriate embedding model
|
| 363 |
+
if (this.isMultilingualContent(content)) {
|
| 364 |
+
return this.embeddingModels.multilingual;
|
| 365 |
+
}
|
| 366 |
+
if (this.isNumericalContent(content)) {
|
| 367 |
+
return this.embeddingModels.specialized.numerical;
|
| 368 |
+
}
|
| 369 |
+
return this.embeddingModels.default;
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
async insert(content, options = {}) {
|
| 373 |
+
const embeddingModel = await this.selectOptimalEmbeddingModel(content);
|
| 374 |
+
const memoryItem = new MemoryItem(content, {
|
| 375 |
+
...options,
|
| 376 |
+
embeddingModel
|
| 377 |
+
});
|
| 378 |
+
|
| 379 |
+
// Advanced indexing and relationship tracking
|
| 380 |
+
this.semanticIndex.add(memoryItem);
|
| 381 |
+
this.trackRelationships(memoryItem);
|
| 382 |
+
|
| 383 |
+
return memoryItem;
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
async intelligentRetrieve(query, options = {}) {
|
| 387 |
+
const {
|
| 388 |
+
maxResults = 10,
|
| 389 |
+
similarityThreshold = 0.7,
|
| 390 |
+
includeRelated = true
|
| 391 |
+
} = options;
|
| 392 |
+
|
| 393 |
+
// Semantic and relationship-aware retrieval
|
| 394 |
+
const semanticResults = this.semanticIndex.search(query, {
|
| 395 |
+
maxResults,
|
| 396 |
+
threshold: similarityThreshold
|
| 397 |
+
});
|
| 398 |
+
|
| 399 |
+
if (includeRelated) {
|
| 400 |
+
return this.expandWithRelatedMemories(semanticResults);
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
return semanticResults;
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
async performMemoryCompression() {
|
| 407 |
+
const compressionCandidates = this.identifyCompressionCandidates();
|
| 408 |
+
const compressedMemories = compressionCandidates.map(this.compressMemory);
|
| 409 |
+
|
| 410 |
+
return {
|
| 411 |
+
originalCount: compressionCandidates.length,
|
| 412 |
+
compressedCount: compressedMemories.length,
|
| 413 |
+
compressionRatio: compressedMemories.length / compressionCandidates.length
|
| 414 |
+
};
|
| 415 |
+
}
|
| 416 |
+
}
|
| 417 |
+
class MemoryTracer {
|
| 418 |
+
constructor() {
|
| 419 |
+
this.generationLog = new Map(); // Track memory generation lineage
|
| 420 |
+
this.redundancyMap = new Map(); // Track potential redundant memories
|
| 421 |
+
this.compressionMetrics = {
|
| 422 |
+
totalMemories: 0,
|
| 423 |
+
uniqueMemories: 0,
|
| 424 |
+
redundancyRate: 0,
|
| 425 |
+
compressionPotential: 0
|
| 426 |
+
};
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
trackGeneration(memoryItem, parentMemories = []) {
|
| 430 |
+
// Create a generation trace
|
| 431 |
+
const generationEntry = {
|
| 432 |
+
id: memoryItem.id,
|
| 433 |
+
timestamp: Date.now(),
|
| 434 |
+
content: memoryItem.content,
|
| 435 |
+
parents: parentMemories.map(m => m.id),
|
| 436 |
+
lineage: [
|
| 437 |
+
...parentMemories.flatMap(p =>
|
| 438 |
+
this.generationLog.get(p.id)?.lineage || []
|
| 439 |
+
),
|
| 440 |
+
memoryItem.id
|
| 441 |
+
]
|
| 442 |
+
};
|
| 443 |
+
|
| 444 |
+
this.generationLog.set(memoryItem.id, generationEntry);
|
| 445 |
+
this.updateRedundancyMetrics(memoryItem);
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
updateRedundancyMetrics(memoryItem) {
|
| 449 |
+
// Semantic similarity check for redundancy
|
| 450 |
+
const similarityThreshold = 0.9;
|
| 451 |
+
let redundancyCount = 0;
|
| 452 |
+
|
| 453 |
+
for (let [, existingMemory] of this.redundancyMap) {
|
| 454 |
+
const similarity = this.calculateSemanticSimilarity(
|
| 455 |
+
existingMemory.content,
|
| 456 |
+
memoryItem.content
|
| 457 |
+
);
|
| 458 |
+
|
| 459 |
+
if (similarity >= similarityThreshold) {
|
| 460 |
+
redundancyCount++;
|
| 461 |
+
this.redundancyMap.set(memoryItem.id, {
|
| 462 |
+
memory: memoryItem,
|
| 463 |
+
similarTo: existingMemory.id,
|
| 464 |
+
similarity: similarity
|
| 465 |
+
});
|
| 466 |
+
}
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
// Update compression metrics
|
| 470 |
+
this.compressionMetrics.totalMemories++;
|
| 471 |
+
this.compressionMetrics.redundancyRate =
|
| 472 |
+
(redundancyCount / this.compressionMetrics.totalMemories);
|
| 473 |
+
this.compressionMetrics.compressionPotential =
|
| 474 |
+
this.calculateCompressionPotential();
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
calculateSemanticSimilarity(content1, content2) {
|
| 478 |
+
// Placeholder for semantic similarity calculation
|
| 479 |
+
// In a real implementation, use embedding-based similarity
|
| 480 |
+
const words1 = new Set(content1.toLowerCase().split(/\s+/));
|
| 481 |
+
const words2 = new Set(content2.toLowerCase().split(/\s+/));
|
| 482 |
+
|
| 483 |
+
const intersection = new Set(
|
| 484 |
+
[...words1].filter(x => words2.has(x))
|
| 485 |
+
);
|
| 486 |
+
|
| 487 |
+
return intersection.size / Math.max(words1.size, words2.size);
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
calculateCompressionPotential() {
|
| 491 |
+
// Advanced compression potential calculation
|
| 492 |
+
const { totalMemories, redundancyRate } = this.compressionMetrics;
|
| 493 |
+
|
| 494 |
+
// Exponential decay of compression potential
|
| 495 |
+
return Math.min(1, Math.exp(-redundancyRate) *
|
| 496 |
+
(1 - 1 / (1 + totalMemories)));
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
compressMemories(memoryManager) {
|
| 500 |
+
const compressibleMemories = [];
|
| 501 |
+
|
| 502 |
+
// Identify memories for potential compression
|
| 503 |
+
for (let [id, redundancyEntry] of this.redundancyMap) {
|
| 504 |
+
if (redundancyEntry.similarity >= 0.9) {
|
| 505 |
+
compressibleMemories.push({
|
| 506 |
+
id: id,
|
| 507 |
+
similarTo: redundancyEntry.similarTo,
|
| 508 |
+
similarity: redundancyEntry.similarity
|
| 509 |
+
});
|
| 510 |
+
}
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
// Compression strategy
|
| 514 |
+
const compressionStrategy = (memories) => {
|
| 515 |
+
// Group similar memories
|
| 516 |
+
const memoryGroups = new Map();
|
| 517 |
+
|
| 518 |
+
memories.forEach(memoryInfo => {
|
| 519 |
+
const groupKey = memoryInfo.similarTo;
|
| 520 |
+
if (!memoryGroups.has(groupKey)) {
|
| 521 |
+
memoryGroups.set(groupKey, []);
|
| 522 |
+
}
|
| 523 |
+
memoryGroups.get(groupKey).push(memoryInfo);
|
| 524 |
+
});
|
| 525 |
+
|
| 526 |
+
// Merge similar memory groups
|
| 527 |
+
const mergedMemories = [];
|
| 528 |
+
for (let [baseId, group] of memoryGroups) {
|
| 529 |
+
const baseMemory = memoryManager.allMemories.get(baseId);
|
| 530 |
+
|
| 531 |
+
// Create a compressed representation
|
| 532 |
+
const compressedContent = this.createCompressedContent(
|
| 533 |
+
group.map(g =>
|
| 534 |
+
memoryManager.allMemories.get(g.id).content
|
| 535 |
+
)
|
| 536 |
+
);
|
| 537 |
+
|
| 538 |
+
// Create a new compressed memory item
|
| 539 |
+
const compressedMemory = new MemoryItem(compressedContent, {
|
| 540 |
+
type: baseMemory.type,
|
| 541 |
+
isFactual: baseMemory.isFactual,
|
| 542 |
+
confidence: Math.max(...group.map(g =>
|
| 543 |
+
memoryManager.allMemories.get(g.id).confidence
|
| 544 |
+
))
|
| 545 |
+
});
|
| 546 |
+
|
| 547 |
+
mergedMemories.push(compressedMemory);
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
return mergedMemories;
|
| 551 |
+
};
|
| 552 |
+
|
| 553 |
+
// Execute compression
|
| 554 |
+
const compressedMemories = compressionStrategy(compressibleMemories);
|
| 555 |
+
|
| 556 |
+
// Update memory manager
|
| 557 |
+
compressedMemories.forEach(memory => {
|
| 558 |
+
memoryManager.insert(memory);
|
| 559 |
+
});
|
| 560 |
+
|
| 561 |
+
// Log compression results
|
| 562 |
+
console.log('Memory Compression Report:', {
|
| 563 |
+
totalCompressed: compressibleMemories.length,
|
| 564 |
+
compressionPotential: this.compressionMetrics.compressionPotential
|
| 565 |
+
});
|
| 566 |
+
|
| 567 |
+
return compressedMemories;
|
| 568 |
+
}
|
| 569 |
+
|
| 570 |
+
createCompressedContent(contents) {
|
| 571 |
+
// Intelligently combine similar memory contents
|
| 572 |
+
const uniqueWords = new Set(
|
| 573 |
+
contents.flatMap(content =>
|
| 574 |
+
content.toLowerCase().split(/\s+/)
|
| 575 |
+
)
|
| 576 |
+
);
|
| 577 |
+
|
| 578 |
+
// Create a concise summary
|
| 579 |
+
return Array.from(uniqueWords).slice(0, 20).join(' ');
|
| 580 |
+
}
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
// Modify MemoryManager to incorporate tracing
|
| 584 |
+
class MemoryManager {
|
| 585 |
+
constructor() {
|
| 586 |
+
// ... existing constructor code ...
|
| 587 |
+
this.memoryTracer = new MemoryTracer();
|
| 588 |
+
}
|
| 589 |
+
|
| 590 |
+
async insert(content, options = {}, parentMemories = []) {
|
| 591 |
+
const memoryItem = new MemoryItem(content, options);
|
| 592 |
+
|
| 593 |
+
// Compute embedding and trace generation
|
| 594 |
+
await memoryItem.computeEmbedding(this.embeddingService);
|
| 595 |
+
this.memoryTracer.trackGeneration(memoryItem, parentMemories);
|
| 596 |
+
|
| 597 |
+
// ... existing insertion code ...
|
| 598 |
+
|
| 599 |
+
return memoryItem;
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
performMemoryCompression() {
|
| 603 |
+
return this.memoryTracer.compressMemories(this);
|
| 604 |
+
}
|
| 605 |
+
}
|
| 606 |
+
const crypto = require('crypto');
|
| 607 |
+
|
| 608 |
+
class MemoryItem {
|
| 609 |
+
constructor(content, options = {}) {
|
| 610 |
+
this.id = crypto.randomUUID();
|
| 611 |
+
this.content = content;
|
| 612 |
+
this.type = options.type || 'text';
|
| 613 |
+
this.isFactual = options.isFactual || 0.5;
|
| 614 |
+
this.confidence = options.confidence || 0.5;
|
| 615 |
+
|
| 616 |
+
this.timestamp = Date.now();
|
| 617 |
+
this.accessCount = 0;
|
| 618 |
+
this.importance = 5;
|
| 619 |
+
|
| 620 |
+
this.embedding = null;
|
| 621 |
+
this.related = new Map();
|
| 622 |
+
this.tags = new Set();
|
| 623 |
+
}
|
| 624 |
+
|
| 625 |
+
addRelationship(memoryItem, weight = 1.0) {
|
| 626 |
+
this.related.set(memoryItem.id, {
|
| 627 |
+
memory: memoryItem,
|
| 628 |
+
weight: weight,
|
| 629 |
+
type: this.determineRelationshipType(memoryItem)
|
| 630 |
+
});
|
| 631 |
+
}
|
| 632 |
+
|
| 633 |
+
determineRelationshipType(memoryItem) {
|
| 634 |
+
// Basic relationship type inference
|
| 635 |
+
const content1 = this.content.toLowerCase();
|
| 636 |
+
const content2 = memoryItem.content.toLowerCase();
|
| 637 |
+
|
| 638 |
+
const sharedWords = content1.split(' ')
|
| 639 |
+
.filter(word => content2.includes(word));
|
| 640 |
+
|
| 641 |
+
const similarityRatio = sharedWords.length /
|
| 642 |
+
Math.max(content1.split(' ').length, content2.split(' ').length);
|
| 643 |
+
|
| 644 |
+
if (similarityRatio > 0.5) return 'VERY_CLOSE';
|
| 645 |
+
if (similarityRatio > 0.2) return 'RELATED';
|
| 646 |
+
return 'DISTANT';
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
incrementAccess() {
|
| 650 |
+
this.accessCount++;
|
| 651 |
+
this.updateImportance();
|
| 652 |
+
}
|
| 653 |
+
|
| 654 |
+
updateImportance() {
|
| 655 |
+
// Dynamic importance calculation
|
| 656 |
+
this.importance = Math.min(
|
| 657 |
+
10,
|
| 658 |
+
5 + Math.log(this.accessCount + 1)
|
| 659 |
+
);
|
| 660 |
+
}
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
module.exports = MemoryItem;
|
| 664 |
+
class MemoryTier {
|
| 665 |
+
constructor(name, options = {}) {
|
| 666 |
+
this.name = name;
|
| 667 |
+
this.items = new Map();
|
| 668 |
+
this.maxCapacity = options.maxCapacity || Infinity;
|
| 669 |
+
this.pruneStrategy = options.pruneStrategy || 'LRU';
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
insert(memoryItem) {
|
| 673 |
+
if (this.items.size >= this.maxCapacity) {
|
| 674 |
+
this.prune();
|
| 675 |
+
}
|
| 676 |
+
this.items.set(memoryItem.id, memoryItem);
|
| 677 |
+
}
|
| 678 |
+
|
| 679 |
+
prune() {
|
| 680 |
+
switch(this.pruneStrategy) {
|
| 681 |
+
case 'LRU':
|
| 682 |
+
const oldestItem = Array.from(this.items.values())
|
| 683 |
+
.sort((a, b) => a.timestamp - b.timestamp)[0];
|
| 684 |
+
this.items.delete(oldestItem.id);
|
| 685 |
+
break;
|
| 686 |
+
case 'LEAST_IMPORTANT':
|
| 687 |
+
const leastImportant = Array.from(this.items.values())
|
| 688 |
+
.sort((a, b) => a.importance - b.importance)[0];
|
| 689 |
+
this.items.delete(leastImportant.id);
|
| 690 |
+
break;
|
| 691 |
+
}
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
retrieve(query) {
|
| 695 |
+
return Array.from(this.items.values())
|
| 696 |
+
.filter(item => item.content.includes(query));
|
| 697 |
+
}
|
| 698 |
+
}
|
| 699 |
+
|
| 700 |
+
module.exports = MemoryTier;
|
| 701 |
+
const MemoryItem = require('./memory-item');
|
| 702 |
+
const MemoryTier = require('./memory-tier');
|
| 703 |
+
const SemanticEmbedding = require('./semantic-embedding');
|
| 704 |
+
|
| 705 |
+
class MemoryManager {
|
| 706 |
+
constructor(config = {}) {
|
| 707 |
+
this.embeddingService = new SemanticEmbedding();
|
| 708 |
+
|
| 709 |
+
this.tiers = {
|
| 710 |
+
volatileShortTerm: new MemoryTier('Volatile Short-Term', {
|
| 711 |
+
maxCapacity: config.shortTermCapacity || 10
|
| 712 |
+
}),
|
| 713 |
+
persistentLongTerm: new MemoryTier('Persistent Long-Term'),
|
| 714 |
+
contextWorkingMemory: new MemoryTier('Context/Working Memory', {
|
| 715 |
+
maxCapacity: config.workingMemoryCapacity || 5
|
| 716 |
+
})
|
| 717 |
+
};
|
| 718 |
+
|
| 719 |
+
this.allMemories = new Map();
|
| 720 |
+
}
|
| 721 |
+
|
| 722 |
+
async insert(content, options = {}) {
|
| 723 |
+
const memoryItem = new MemoryItem(content, options);
|
| 724 |
+
|
| 725 |
+
// Insert into all tiers
|
| 726 |
+
Object.values(this.tiers).forEach(tier => {
|
| 727 |
+
tier.insert(memoryItem);
|
| 728 |
+
});
|
| 729 |
+
|
| 730 |
+
this.allMemories.set(memoryItem.id, memoryItem);
|
| 731 |
+
return memoryItem;
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
async retrieve(query) {
|
| 735 |
+
// Aggregate results from all tiers
|
| 736 |
+
const results = Object.values(this.tiers)
|
| 737 |
+
.flatMap(tier => tier.retrieve(query));
|
| 738 |
+
|
| 739 |
+
// Deduplicate and sort by importance
|
| 740 |
+
return [...new Set(results)]
|
| 741 |
+
.sort((a, b) => b.importance - a.importance);
|
| 742 |
+
}
|
| 743 |
+
|
| 744 |
+
async findSemanticallySimilar(memoryItem, threshold = 0.7) {
|
| 745 |
+
const similar = [];
|
| 746 |
+
|
| 747 |
+
for (let [, memory] of this.allMemories) {
|
| 748 |
+
if (memory.id !== memoryItem.id) {
|
| 749 |
+
const similarity = this.calculateSemanticSimilarity(
|
| 750 |
+
memory.content,
|
| 751 |
+
memoryItem.content
|
| 752 |
+
);
|
| 753 |
+
|
| 754 |
+
if (similarity >= threshold) {
|
| 755 |
+
similar.push({ memory, similarity });
|
| 756 |
+
}
|
| 757 |
+
}
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
return similar.sort((a, b) => b.similarity - a.similarity);
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
calculateSemanticSimilarity(content1, content2) {
|
| 764 |
+
// Simple similarity calculation
|
| 765 |
+
const words1 = new Set(content1.toLowerCase().split(/\s+/));
|
| 766 |
+
const words2 = new Set(content2.toLowerCase().split(/\s+/));
|
| 767 |
+
|
| 768 |
+
const intersection = new Set(
|
| 769 |
+
[...words1].filter(x => words2.has(x))
|
| 770 |
+
);
|
| 771 |
+
|
| 772 |
+
return intersection.size / Math.max(words1.size, words2.size);
|
| 773 |
+
}
|
| 774 |
+
}
|
| 775 |
+
|
| 776 |
+
module.exports = MemoryManager;
|
| 777 |
+
class SemanticEmbedding {
|
| 778 |
+
constructor() {
|
| 779 |
+
this.embeddingCache = new Map();
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
async generateEmbedding(text) {
|
| 783 |
+
// Check cache first
|
| 784 |
+
if (this.embeddingCache.has(text)) {
|
| 785 |
+
return this.embeddingCache.get(text);
|
| 786 |
+
}
|
| 787 |
+
|
| 788 |
+
// Simple embedding generation
|
| 789 |
+
const tokens = text.toLowerCase().split(/\s+/);
|
| 790 |
+
const embedding = tokens.map(token => this.simpleTokenEmbedding(token));
|
| 791 |
+
|
| 792 |
+
// Cache the embedding
|
| 793 |
+
this.embeddingCache.set(text, embedding);
|
| 794 |
+
|
| 795 |
+
return embedding;
|
| 796 |
+
}
|
| 797 |
+
|
| 798 |
+
simpleTokenEmbedding(token) {
|
| 799 |
+
// Very basic embedding - just a numerical representation
|
| 800 |
+
return token.split('').map(char => char.charCodeAt(0));
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
calculateSemanticSimilarity(embedding1, embedding2) {
|
| 804 |
+
// Cosine similarity approximation
|
| 805 |
+
const dotProduct = embedding1.reduce(
|
| 806 |
+
(sum, val, i) => sum + val * (embedding2[i] || 0),
|
| 807 |
+
0
|
| 808 |
+
);
|
| 809 |
+
|
| 810 |
+
const magnitude1 = Math.sqrt(
|
| 811 |
+
embedding1.reduce((sum, val) => sum + val * val, 0)
|
| 812 |
+
);
|
| 813 |
+
|
| 814 |
+
const magnitude2 = Math.sqrt(
|
| 815 |
+
embedding2.reduce((sum, val) => sum + val * val, 0)
|
| 816 |
+
);
|
| 817 |
+
|
| 818 |
+
return dotProduct / (magnitude1 * magnitude2);
|
| 819 |
+
}
|
| 820 |
+
}
|