genesis-ai-cli 7.4.5

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.
Files changed (227) hide show
  1. package/.env.example +78 -0
  2. package/README.md +282 -0
  3. package/dist/src/active-inference/actions.d.ts +75 -0
  4. package/dist/src/active-inference/actions.js +250 -0
  5. package/dist/src/active-inference/autonomous-loop.d.ts +103 -0
  6. package/dist/src/active-inference/autonomous-loop.js +289 -0
  7. package/dist/src/active-inference/core.d.ts +85 -0
  8. package/dist/src/active-inference/core.js +555 -0
  9. package/dist/src/active-inference/demo-autonomous-loop.d.ts +8 -0
  10. package/dist/src/active-inference/demo-autonomous-loop.js +338 -0
  11. package/dist/src/active-inference/demo-value-integration.d.ts +8 -0
  12. package/dist/src/active-inference/demo-value-integration.js +174 -0
  13. package/dist/src/active-inference/index.d.ts +32 -0
  14. package/dist/src/active-inference/index.js +88 -0
  15. package/dist/src/active-inference/integration.d.ts +114 -0
  16. package/dist/src/active-inference/integration.js +698 -0
  17. package/dist/src/active-inference/memory-integration.d.ts +51 -0
  18. package/dist/src/active-inference/memory-integration.js +232 -0
  19. package/dist/src/active-inference/observations.d.ts +67 -0
  20. package/dist/src/active-inference/observations.js +147 -0
  21. package/dist/src/active-inference/test-active-inference.d.ts +8 -0
  22. package/dist/src/active-inference/test-active-inference.js +320 -0
  23. package/dist/src/active-inference/test-value-integration.d.ts +6 -0
  24. package/dist/src/active-inference/test-value-integration.js +168 -0
  25. package/dist/src/active-inference/types.d.ts +150 -0
  26. package/dist/src/active-inference/types.js +59 -0
  27. package/dist/src/active-inference/value-integration.d.ts +164 -0
  28. package/dist/src/active-inference/value-integration.js +459 -0
  29. package/dist/src/agents/base-agent.d.ts +53 -0
  30. package/dist/src/agents/base-agent.js +178 -0
  31. package/dist/src/agents/builder.d.ts +67 -0
  32. package/dist/src/agents/builder.js +537 -0
  33. package/dist/src/agents/critic.d.ts +35 -0
  34. package/dist/src/agents/critic.js +322 -0
  35. package/dist/src/agents/ethicist.d.ts +54 -0
  36. package/dist/src/agents/ethicist.js +393 -0
  37. package/dist/src/agents/explorer.d.ts +26 -0
  38. package/dist/src/agents/explorer.js +216 -0
  39. package/dist/src/agents/feeling.d.ts +41 -0
  40. package/dist/src/agents/feeling.js +320 -0
  41. package/dist/src/agents/index.d.ts +111 -0
  42. package/dist/src/agents/index.js +222 -0
  43. package/dist/src/agents/memory.d.ts +69 -0
  44. package/dist/src/agents/memory.js +404 -0
  45. package/dist/src/agents/message-bus.d.ts +88 -0
  46. package/dist/src/agents/message-bus.js +267 -0
  47. package/dist/src/agents/narrator.d.ts +90 -0
  48. package/dist/src/agents/narrator.js +473 -0
  49. package/dist/src/agents/planner.d.ts +38 -0
  50. package/dist/src/agents/planner.js +341 -0
  51. package/dist/src/agents/predictor.d.ts +73 -0
  52. package/dist/src/agents/predictor.js +506 -0
  53. package/dist/src/agents/sensor.d.ts +88 -0
  54. package/dist/src/agents/sensor.js +377 -0
  55. package/dist/src/agents/test-agents.d.ts +6 -0
  56. package/dist/src/agents/test-agents.js +73 -0
  57. package/dist/src/agents/types.d.ts +194 -0
  58. package/dist/src/agents/types.js +7 -0
  59. package/dist/src/brain/index.d.ts +185 -0
  60. package/dist/src/brain/index.js +843 -0
  61. package/dist/src/brain/trace.d.ts +91 -0
  62. package/dist/src/brain/trace.js +327 -0
  63. package/dist/src/brain/types.d.ts +165 -0
  64. package/dist/src/brain/types.js +51 -0
  65. package/dist/src/cli/chat.d.ts +237 -0
  66. package/dist/src/cli/chat.js +1959 -0
  67. package/dist/src/cli/dispatcher.d.ts +182 -0
  68. package/dist/src/cli/dispatcher.js +718 -0
  69. package/dist/src/cli/human-loop.d.ts +170 -0
  70. package/dist/src/cli/human-loop.js +543 -0
  71. package/dist/src/cli/index.d.ts +12 -0
  72. package/dist/src/cli/index.js +28 -0
  73. package/dist/src/cli/interactive.d.ts +141 -0
  74. package/dist/src/cli/interactive.js +757 -0
  75. package/dist/src/cli/ui.d.ts +205 -0
  76. package/dist/src/cli/ui.js +632 -0
  77. package/dist/src/consciousness/attention-schema.d.ts +154 -0
  78. package/dist/src/consciousness/attention-schema.js +432 -0
  79. package/dist/src/consciousness/global-workspace.d.ts +149 -0
  80. package/dist/src/consciousness/global-workspace.js +422 -0
  81. package/dist/src/consciousness/index.d.ts +186 -0
  82. package/dist/src/consciousness/index.js +476 -0
  83. package/dist/src/consciousness/phi-calculator.d.ts +119 -0
  84. package/dist/src/consciousness/phi-calculator.js +445 -0
  85. package/dist/src/consciousness/phi-decisions.d.ts +169 -0
  86. package/dist/src/consciousness/phi-decisions.js +383 -0
  87. package/dist/src/consciousness/phi-monitor.d.ts +153 -0
  88. package/dist/src/consciousness/phi-monitor.js +465 -0
  89. package/dist/src/consciousness/types.d.ts +260 -0
  90. package/dist/src/consciousness/types.js +44 -0
  91. package/dist/src/daemon/dream-mode.d.ts +115 -0
  92. package/dist/src/daemon/dream-mode.js +470 -0
  93. package/dist/src/daemon/index.d.ts +162 -0
  94. package/dist/src/daemon/index.js +542 -0
  95. package/dist/src/daemon/maintenance.d.ts +139 -0
  96. package/dist/src/daemon/maintenance.js +549 -0
  97. package/dist/src/daemon/process.d.ts +82 -0
  98. package/dist/src/daemon/process.js +442 -0
  99. package/dist/src/daemon/scheduler.d.ts +90 -0
  100. package/dist/src/daemon/scheduler.js +494 -0
  101. package/dist/src/daemon/types.d.ts +213 -0
  102. package/dist/src/daemon/types.js +50 -0
  103. package/dist/src/epistemic/index.d.ts +74 -0
  104. package/dist/src/epistemic/index.js +225 -0
  105. package/dist/src/grounding/epistemic-stack.d.ts +100 -0
  106. package/dist/src/grounding/epistemic-stack.js +408 -0
  107. package/dist/src/grounding/feedback.d.ts +98 -0
  108. package/dist/src/grounding/feedback.js +276 -0
  109. package/dist/src/grounding/index.d.ts +123 -0
  110. package/dist/src/grounding/index.js +224 -0
  111. package/dist/src/grounding/verifier.d.ts +149 -0
  112. package/dist/src/grounding/verifier.js +484 -0
  113. package/dist/src/healing/detector.d.ts +110 -0
  114. package/dist/src/healing/detector.js +436 -0
  115. package/dist/src/healing/fixer.d.ts +138 -0
  116. package/dist/src/healing/fixer.js +572 -0
  117. package/dist/src/healing/index.d.ts +23 -0
  118. package/dist/src/healing/index.js +43 -0
  119. package/dist/src/hooks/index.d.ts +135 -0
  120. package/dist/src/hooks/index.js +317 -0
  121. package/dist/src/index.d.ts +23 -0
  122. package/dist/src/index.js +1266 -0
  123. package/dist/src/kernel/index.d.ts +155 -0
  124. package/dist/src/kernel/index.js +795 -0
  125. package/dist/src/kernel/invariants.d.ts +153 -0
  126. package/dist/src/kernel/invariants.js +355 -0
  127. package/dist/src/kernel/test-kernel.d.ts +6 -0
  128. package/dist/src/kernel/test-kernel.js +108 -0
  129. package/dist/src/kernel/test-real-mcp.d.ts +10 -0
  130. package/dist/src/kernel/test-real-mcp.js +295 -0
  131. package/dist/src/llm/index.d.ts +146 -0
  132. package/dist/src/llm/index.js +428 -0
  133. package/dist/src/llm/router.d.ts +136 -0
  134. package/dist/src/llm/router.js +510 -0
  135. package/dist/src/mcp/index.d.ts +85 -0
  136. package/dist/src/mcp/index.js +657 -0
  137. package/dist/src/mcp/resilient.d.ts +139 -0
  138. package/dist/src/mcp/resilient.js +417 -0
  139. package/dist/src/memory/cache.d.ts +118 -0
  140. package/dist/src/memory/cache.js +356 -0
  141. package/dist/src/memory/cognitive-workspace.d.ts +231 -0
  142. package/dist/src/memory/cognitive-workspace.js +521 -0
  143. package/dist/src/memory/consolidation.d.ts +99 -0
  144. package/dist/src/memory/consolidation.js +443 -0
  145. package/dist/src/memory/episodic.d.ts +114 -0
  146. package/dist/src/memory/episodic.js +394 -0
  147. package/dist/src/memory/forgetting.d.ts +134 -0
  148. package/dist/src/memory/forgetting.js +324 -0
  149. package/dist/src/memory/index.d.ts +211 -0
  150. package/dist/src/memory/index.js +367 -0
  151. package/dist/src/memory/indexer.d.ts +123 -0
  152. package/dist/src/memory/indexer.js +479 -0
  153. package/dist/src/memory/procedural.d.ts +136 -0
  154. package/dist/src/memory/procedural.js +479 -0
  155. package/dist/src/memory/semantic.d.ts +132 -0
  156. package/dist/src/memory/semantic.js +497 -0
  157. package/dist/src/memory/types.d.ts +193 -0
  158. package/dist/src/memory/types.js +15 -0
  159. package/dist/src/orchestrator.d.ts +65 -0
  160. package/dist/src/orchestrator.js +317 -0
  161. package/dist/src/persistence/index.d.ts +257 -0
  162. package/dist/src/persistence/index.js +763 -0
  163. package/dist/src/pipeline/executor.d.ts +51 -0
  164. package/dist/src/pipeline/executor.js +695 -0
  165. package/dist/src/pipeline/index.d.ts +7 -0
  166. package/dist/src/pipeline/index.js +11 -0
  167. package/dist/src/self-production.d.ts +67 -0
  168. package/dist/src/self-production.js +205 -0
  169. package/dist/src/subagents/executor.d.ts +58 -0
  170. package/dist/src/subagents/executor.js +283 -0
  171. package/dist/src/subagents/index.d.ts +37 -0
  172. package/dist/src/subagents/index.js +53 -0
  173. package/dist/src/subagents/registry.d.ts +23 -0
  174. package/dist/src/subagents/registry.js +167 -0
  175. package/dist/src/subagents/types.d.ts +79 -0
  176. package/dist/src/subagents/types.js +14 -0
  177. package/dist/src/tools/bash.d.ts +139 -0
  178. package/dist/src/tools/bash.js +583 -0
  179. package/dist/src/tools/edit.d.ts +125 -0
  180. package/dist/src/tools/edit.js +424 -0
  181. package/dist/src/tools/git.d.ts +179 -0
  182. package/dist/src/tools/git.js +504 -0
  183. package/dist/src/tools/index.d.ts +21 -0
  184. package/dist/src/tools/index.js +163 -0
  185. package/dist/src/types.d.ts +145 -0
  186. package/dist/src/types.js +7 -0
  187. package/dist/src/world-model/decoder.d.ts +163 -0
  188. package/dist/src/world-model/decoder.js +517 -0
  189. package/dist/src/world-model/digital-twin.d.ts +219 -0
  190. package/dist/src/world-model/digital-twin.js +695 -0
  191. package/dist/src/world-model/encoder.d.ts +141 -0
  192. package/dist/src/world-model/encoder.js +564 -0
  193. package/dist/src/world-model/index.d.ts +221 -0
  194. package/dist/src/world-model/index.js +772 -0
  195. package/dist/src/world-model/predictor.d.ts +161 -0
  196. package/dist/src/world-model/predictor.js +681 -0
  197. package/dist/src/world-model/test-value-jepa.d.ts +8 -0
  198. package/dist/src/world-model/test-value-jepa.js +430 -0
  199. package/dist/src/world-model/types.d.ts +341 -0
  200. package/dist/src/world-model/types.js +69 -0
  201. package/dist/src/world-model/value-jepa.d.ts +247 -0
  202. package/dist/src/world-model/value-jepa.js +622 -0
  203. package/dist/test/brain.test.d.ts +11 -0
  204. package/dist/test/brain.test.js +358 -0
  205. package/dist/test/cli/dispatcher.test.d.ts +4 -0
  206. package/dist/test/cli/dispatcher.test.js +332 -0
  207. package/dist/test/cli/human-loop.test.d.ts +4 -0
  208. package/dist/test/cli/human-loop.test.js +270 -0
  209. package/dist/test/grounding/feedback.test.d.ts +4 -0
  210. package/dist/test/grounding/feedback.test.js +462 -0
  211. package/dist/test/grounding/verifier.test.d.ts +4 -0
  212. package/dist/test/grounding/verifier.test.js +442 -0
  213. package/dist/test/grounding.test.d.ts +6 -0
  214. package/dist/test/grounding.test.js +246 -0
  215. package/dist/test/healing/detector.test.d.ts +4 -0
  216. package/dist/test/healing/detector.test.js +266 -0
  217. package/dist/test/healing/fixer.test.d.ts +4 -0
  218. package/dist/test/healing/fixer.test.js +369 -0
  219. package/dist/test/integration.test.d.ts +5 -0
  220. package/dist/test/integration.test.js +290 -0
  221. package/dist/test/tools/bash.test.d.ts +4 -0
  222. package/dist/test/tools/bash.test.js +348 -0
  223. package/dist/test/tools/edit.test.d.ts +4 -0
  224. package/dist/test/tools/edit.test.js +350 -0
  225. package/dist/test/tools/git.test.d.ts +4 -0
  226. package/dist/test/tools/git.test.js +350 -0
  227. package/package.json +60 -0
@@ -0,0 +1,521 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 6.3 - Cognitive Workspace (Memory 2.0)
4
+ *
5
+ * Working memory with attention-based selection and anticipatory retrieval.
6
+ *
7
+ * Based on:
8
+ * - Baddeley's Working Memory Model (central executive + buffers)
9
+ * - Global Workspace Theory (Baars) - capacity-limited broadcast
10
+ * - Active Inference (anticipatory recall)
11
+ *
12
+ * Key features:
13
+ * - Capacity-limited buffer (like human 7±2 items)
14
+ * - Attention-based selection and eviction
15
+ * - Anticipatory pre-loading based on context
16
+ * - Integration with episodic/semantic/procedural stores
17
+ *
18
+ * Architecture:
19
+ * ```
20
+ * Context → anticipate() → Pre-load
21
+ * ↓
22
+ * [Working Memory Buffer]
23
+ * ↓
24
+ * curate() → Select/Evict
25
+ * ↓
26
+ * [Active Items for Reasoning]
27
+ * ```
28
+ */
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.CognitiveWorkspace = exports.DEFAULT_WORKSPACE_CONFIG = void 0;
31
+ exports.createCognitiveWorkspace = createCognitiveWorkspace;
32
+ exports.getCognitiveWorkspace = getCognitiveWorkspace;
33
+ exports.resetCognitiveWorkspace = resetCognitiveWorkspace;
34
+ exports.DEFAULT_WORKSPACE_CONFIG = {
35
+ maxItems: 7,
36
+ maxTokens: 8192,
37
+ decayRate: 0.01,
38
+ boostOnAccess: 0.3,
39
+ minActivation: 0.1,
40
+ anticipationDepth: 5,
41
+ associationStrength: 0.3,
42
+ curationInterval: 5000,
43
+ autoCurate: true,
44
+ };
45
+ // ============================================================================
46
+ // Cognitive Workspace
47
+ // ============================================================================
48
+ /**
49
+ * Working memory with attention-based selection and anticipatory retrieval
50
+ */
51
+ class CognitiveWorkspace {
52
+ config;
53
+ // Working memory buffer
54
+ buffer = new Map();
55
+ // Memory stores (injected)
56
+ episodicStore;
57
+ semanticStore;
58
+ proceduralStore;
59
+ // Metrics
60
+ metrics = {
61
+ totalRecalls: 0,
62
+ cacheHits: 0,
63
+ storeHits: 0,
64
+ newCreations: 0,
65
+ anticipationHits: 0,
66
+ anticipationMisses: 0,
67
+ reuseRate: 0,
68
+ anticipationAccuracy: 0,
69
+ };
70
+ // Anticipation tracking
71
+ anticipatedIds = new Set();
72
+ // Auto-curation timer
73
+ curationTimer;
74
+ constructor(config = {}) {
75
+ this.config = { ...exports.DEFAULT_WORKSPACE_CONFIG, ...config };
76
+ if (this.config.autoCurate) {
77
+ this.startAutoCuration();
78
+ }
79
+ }
80
+ // ============================================================================
81
+ // Store Integration
82
+ // ============================================================================
83
+ /**
84
+ * Connect to memory stores for retrieval
85
+ */
86
+ connectStores(stores) {
87
+ this.episodicStore = stores.episodic;
88
+ this.semanticStore = stores.semantic;
89
+ this.proceduralStore = stores.procedural;
90
+ }
91
+ // ============================================================================
92
+ // Anticipatory Retrieval
93
+ // ============================================================================
94
+ /**
95
+ * Anticipate needed memories based on context
96
+ *
97
+ * Uses context cues to predict which memories will be needed,
98
+ * and pre-loads them into working memory.
99
+ */
100
+ async anticipate(context) {
101
+ const anticipated = [];
102
+ // Build search query from context
103
+ const searchTerms = [];
104
+ if (context.task)
105
+ searchTerms.push(context.task);
106
+ if (context.goal)
107
+ searchTerms.push(context.goal);
108
+ if (context.keywords)
109
+ searchTerms.push(...context.keywords);
110
+ if (context.recentTopics)
111
+ searchTerms.push(...context.recentTopics.slice(-3));
112
+ const query = searchTerms.join(' ');
113
+ if (query && query.length > 0) {
114
+ // Search each store
115
+ if (this.episodicStore) {
116
+ const episodes = this.episodicStore.search(query, this.config.anticipationDepth);
117
+ anticipated.push(...episodes);
118
+ }
119
+ if (this.semanticStore) {
120
+ const facts = this.semanticStore.search(query, this.config.anticipationDepth);
121
+ anticipated.push(...facts);
122
+ }
123
+ if (this.proceduralStore) {
124
+ const skills = this.proceduralStore.search(query, this.config.anticipationDepth);
125
+ anticipated.push(...skills);
126
+ }
127
+ }
128
+ // Add by tags if provided
129
+ if (context.tags && context.tags.length > 0) {
130
+ const tagQuery = context.tags.join(' ');
131
+ if (this.episodicStore) {
132
+ anticipated.push(...this.episodicStore.search(tagQuery, 3));
133
+ }
134
+ }
135
+ // Calculate relevance scores
136
+ const items = [];
137
+ for (const memory of anticipated) {
138
+ // Skip if already in buffer
139
+ if (this.buffer.has(memory.id))
140
+ continue;
141
+ const relevance = this.calculateRelevance(memory, context);
142
+ if (relevance < 0.2)
143
+ continue; // Skip low relevance
144
+ const item = this.addToBuffer(memory, 'anticipate', relevance);
145
+ items.push(item);
146
+ // Track for anticipation metrics
147
+ this.anticipatedIds.add(memory.id);
148
+ }
149
+ return items;
150
+ }
151
+ /**
152
+ * Calculate relevance of a memory to the current context
153
+ */
154
+ calculateRelevance(memory, context) {
155
+ let relevance = 0.5; // Base relevance
156
+ let factors = 1;
157
+ // Task/goal match
158
+ if (context.task || context.goal) {
159
+ const target = (context.task || '') + ' ' + (context.goal || '');
160
+ const content = JSON.stringify(memory).toLowerCase();
161
+ const targetTerms = target.toLowerCase().split(/\s+/);
162
+ const matches = targetTerms.filter(t => t.length > 2 && content.includes(t)).length;
163
+ relevance += (matches / Math.max(targetTerms.length, 1)) * 0.3;
164
+ factors++;
165
+ }
166
+ // Keyword match
167
+ if (context.keywords && context.keywords.length > 0) {
168
+ const content = JSON.stringify(memory).toLowerCase();
169
+ const matches = context.keywords.filter(k => content.includes(k.toLowerCase())).length;
170
+ relevance += (matches / context.keywords.length) * 0.2;
171
+ factors++;
172
+ }
173
+ // Tag match
174
+ if (context.tags && context.tags.length > 0) {
175
+ const memoryTags = memory.tags || [];
176
+ const matches = context.tags.filter(t => memoryTags.includes(t)).length;
177
+ relevance += (matches / context.tags.length) * 0.3;
178
+ factors++;
179
+ }
180
+ // Recency boost for episodic
181
+ if (memory.type === 'episodic') {
182
+ const episodic = memory;
183
+ const ageHours = (Date.now() - episodic.when.timestamp.getTime()) / (1000 * 60 * 60);
184
+ if (ageHours < 1)
185
+ relevance += 0.2;
186
+ else if (ageHours < 24)
187
+ relevance += 0.1;
188
+ }
189
+ // Importance factor
190
+ relevance += memory.importance * 0.2;
191
+ return Math.min(1, relevance / factors);
192
+ }
193
+ // ============================================================================
194
+ // Working Memory Operations
195
+ // ============================================================================
196
+ /**
197
+ * Add a memory to working memory buffer
198
+ */
199
+ addToBuffer(memory, source = 'manual', relevance = 0.5) {
200
+ // Check if already in buffer
201
+ const existing = this.buffer.get(memory.id);
202
+ if (existing) {
203
+ this.access(memory.id);
204
+ return existing;
205
+ }
206
+ const item = {
207
+ id: memory.id,
208
+ memory,
209
+ activation: 1.0, // Start at full activation
210
+ relevance,
211
+ accessCount: 1,
212
+ addedAt: new Date(),
213
+ lastAccessed: new Date(),
214
+ source,
215
+ };
216
+ this.buffer.set(memory.id, item);
217
+ // Maintain capacity
218
+ this.maintainCapacity();
219
+ return item;
220
+ }
221
+ /**
222
+ * Access a memory in working memory (boosts activation)
223
+ */
224
+ access(id) {
225
+ const item = this.buffer.get(id);
226
+ if (!item) {
227
+ this.metrics.totalRecalls++;
228
+ return undefined;
229
+ }
230
+ // Boost activation
231
+ item.activation = Math.min(1, item.activation + this.config.boostOnAccess);
232
+ item.accessCount++;
233
+ item.lastAccessed = new Date();
234
+ // Track metrics
235
+ this.metrics.totalRecalls++;
236
+ this.metrics.cacheHits++;
237
+ // Track anticipation hit
238
+ if (this.anticipatedIds.has(id)) {
239
+ this.metrics.anticipationHits++;
240
+ this.anticipatedIds.delete(id);
241
+ }
242
+ this.updateMetrics();
243
+ return item;
244
+ }
245
+ /**
246
+ * Recall a memory (from buffer or stores)
247
+ */
248
+ recall(id) {
249
+ // Check buffer first
250
+ const bufferItem = this.access(id);
251
+ if (bufferItem) {
252
+ return bufferItem.memory;
253
+ }
254
+ // Search stores
255
+ let memory;
256
+ if (this.episodicStore) {
257
+ memory = this.episodicStore.get(id);
258
+ }
259
+ if (!memory && this.semanticStore) {
260
+ // Semantic store uses concept lookup, skip ID lookup
261
+ }
262
+ if (!memory && this.proceduralStore) {
263
+ // Procedural store uses name lookup, skip ID lookup
264
+ }
265
+ if (memory) {
266
+ this.metrics.storeHits++;
267
+ this.addToBuffer(memory, 'recall', 0.7);
268
+ this.updateMetrics();
269
+ return memory;
270
+ }
271
+ this.updateMetrics();
272
+ return undefined;
273
+ }
274
+ /**
275
+ * Get all items currently in working memory
276
+ */
277
+ getActive() {
278
+ return Array.from(this.buffer.values())
279
+ .sort((a, b) => b.activation - a.activation);
280
+ }
281
+ /**
282
+ * Get items by type
283
+ */
284
+ getByType(type) {
285
+ return this.getActive().filter(item => item.memory.type === type);
286
+ }
287
+ /**
288
+ * Check if a memory is in working memory
289
+ */
290
+ isActive(id) {
291
+ return this.buffer.has(id);
292
+ }
293
+ /**
294
+ * Get working memory size
295
+ */
296
+ size() {
297
+ return this.buffer.size;
298
+ }
299
+ // ============================================================================
300
+ // Curation
301
+ // ============================================================================
302
+ /**
303
+ * Curate working memory: decay activations and evict low-activation items
304
+ */
305
+ curate() {
306
+ const now = Date.now();
307
+ let decayed = 0;
308
+ const evicted = [];
309
+ for (const [id, item] of this.buffer) {
310
+ // Decay activation based on time since last access
311
+ const timeSinceAccess = (now - item.lastAccessed.getTime()) / 1000;
312
+ const decay = this.config.decayRate * timeSinceAccess;
313
+ item.activation = Math.max(0, item.activation - decay);
314
+ decayed++;
315
+ // Evict if below threshold
316
+ if (item.activation < this.config.minActivation) {
317
+ this.buffer.delete(id);
318
+ evicted.push(id);
319
+ // Track anticipation miss
320
+ if (this.anticipatedIds.has(id)) {
321
+ this.metrics.anticipationMisses++;
322
+ this.anticipatedIds.delete(id);
323
+ }
324
+ }
325
+ }
326
+ this.updateMetrics();
327
+ return { decayed, evicted };
328
+ }
329
+ /**
330
+ * Start automatic curation
331
+ */
332
+ startAutoCuration() {
333
+ if (this.curationTimer)
334
+ return;
335
+ this.curationTimer = setInterval(() => {
336
+ this.curate();
337
+ }, this.config.curationInterval);
338
+ }
339
+ /**
340
+ * Stop automatic curation
341
+ */
342
+ stopAutoCuration() {
343
+ if (this.curationTimer) {
344
+ clearInterval(this.curationTimer);
345
+ this.curationTimer = undefined;
346
+ }
347
+ }
348
+ // ============================================================================
349
+ // Capacity Management
350
+ // ============================================================================
351
+ /**
352
+ * Maintain working memory capacity by evicting low-activation items
353
+ */
354
+ maintainCapacity() {
355
+ // Check item count
356
+ while (this.buffer.size > this.config.maxItems) {
357
+ this.evictLowest();
358
+ }
359
+ // Check token estimate (rough: 100 chars ≈ 25 tokens)
360
+ let totalTokens = 0;
361
+ for (const item of this.buffer.values()) {
362
+ const content = JSON.stringify(item.memory);
363
+ totalTokens += Math.ceil(content.length / 4);
364
+ }
365
+ while (totalTokens > this.config.maxTokens && this.buffer.size > 0) {
366
+ const evicted = this.evictLowest();
367
+ if (evicted) {
368
+ const content = JSON.stringify(evicted.memory);
369
+ totalTokens -= Math.ceil(content.length / 4);
370
+ }
371
+ else {
372
+ break;
373
+ }
374
+ }
375
+ }
376
+ /**
377
+ * Evict the item with lowest activation
378
+ */
379
+ evictLowest() {
380
+ let lowest;
381
+ let lowestScore = Infinity;
382
+ for (const item of this.buffer.values()) {
383
+ // Score = activation * relevance * importance
384
+ const score = item.activation * item.relevance * item.memory.importance;
385
+ if (score < lowestScore) {
386
+ lowestScore = score;
387
+ lowest = item;
388
+ }
389
+ }
390
+ if (lowest) {
391
+ this.buffer.delete(lowest.id);
392
+ // Track anticipation miss
393
+ if (this.anticipatedIds.has(lowest.id)) {
394
+ this.metrics.anticipationMisses++;
395
+ this.anticipatedIds.delete(lowest.id);
396
+ }
397
+ }
398
+ return lowest;
399
+ }
400
+ // ============================================================================
401
+ // Metrics
402
+ // ============================================================================
403
+ /**
404
+ * Update computed metrics
405
+ */
406
+ updateMetrics() {
407
+ const total = this.metrics.totalRecalls;
408
+ if (total > 0) {
409
+ this.metrics.reuseRate = (this.metrics.cacheHits + this.metrics.storeHits) / total;
410
+ }
411
+ const anticipationTotal = this.metrics.anticipationHits + this.metrics.anticipationMisses;
412
+ if (anticipationTotal > 0) {
413
+ this.metrics.anticipationAccuracy = this.metrics.anticipationHits / anticipationTotal;
414
+ }
415
+ }
416
+ /**
417
+ * Get memory reuse metrics
418
+ */
419
+ getMetrics() {
420
+ return { ...this.metrics };
421
+ }
422
+ /**
423
+ * Record a new memory creation (for metrics)
424
+ */
425
+ recordNewCreation() {
426
+ this.metrics.newCreations++;
427
+ this.metrics.totalRecalls++;
428
+ this.updateMetrics();
429
+ }
430
+ /**
431
+ * Reset metrics
432
+ */
433
+ resetMetrics() {
434
+ this.metrics = {
435
+ totalRecalls: 0,
436
+ cacheHits: 0,
437
+ storeHits: 0,
438
+ newCreations: 0,
439
+ anticipationHits: 0,
440
+ anticipationMisses: 0,
441
+ reuseRate: 0,
442
+ anticipationAccuracy: 0,
443
+ };
444
+ }
445
+ // ============================================================================
446
+ // Workspace State
447
+ // ============================================================================
448
+ /**
449
+ * Get workspace statistics
450
+ */
451
+ getStats() {
452
+ const items = this.getActive();
453
+ let totalActivation = 0;
454
+ let totalRelevance = 0;
455
+ let totalTokens = 0;
456
+ const byType = { episodic: 0, semantic: 0, procedural: 0 };
457
+ const bySource = {
458
+ anticipate: 0, recall: 0, association: 0, manual: 0
459
+ };
460
+ for (const item of items) {
461
+ totalActivation += item.activation;
462
+ totalRelevance += item.relevance;
463
+ totalTokens += Math.ceil(JSON.stringify(item.memory).length / 4);
464
+ byType[item.memory.type]++;
465
+ bySource[item.source]++;
466
+ }
467
+ return {
468
+ itemCount: items.length,
469
+ maxItems: this.config.maxItems,
470
+ estimatedTokens: totalTokens,
471
+ maxTokens: this.config.maxTokens,
472
+ avgActivation: items.length > 0 ? totalActivation / items.length : 0,
473
+ avgRelevance: items.length > 0 ? totalRelevance / items.length : 0,
474
+ byType,
475
+ bySource,
476
+ };
477
+ }
478
+ /**
479
+ * Clear working memory
480
+ */
481
+ clear() {
482
+ // Track all anticipated items as misses
483
+ for (const id of this.anticipatedIds) {
484
+ if (this.buffer.has(id)) {
485
+ this.metrics.anticipationMisses++;
486
+ }
487
+ }
488
+ this.anticipatedIds.clear();
489
+ this.buffer.clear();
490
+ }
491
+ /**
492
+ * Shutdown workspace
493
+ */
494
+ shutdown() {
495
+ this.stopAutoCuration();
496
+ this.clear();
497
+ }
498
+ }
499
+ exports.CognitiveWorkspace = CognitiveWorkspace;
500
+ // ============================================================================
501
+ // Factory
502
+ // ============================================================================
503
+ function createCognitiveWorkspace(config) {
504
+ return new CognitiveWorkspace(config);
505
+ }
506
+ // ============================================================================
507
+ // Singleton
508
+ // ============================================================================
509
+ let workspaceInstance = null;
510
+ function getCognitiveWorkspace(config) {
511
+ if (!workspaceInstance) {
512
+ workspaceInstance = createCognitiveWorkspace(config);
513
+ }
514
+ return workspaceInstance;
515
+ }
516
+ function resetCognitiveWorkspace() {
517
+ if (workspaceInstance) {
518
+ workspaceInstance.shutdown();
519
+ workspaceInstance = null;
520
+ }
521
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Genesis 6.0 - Memory Consolidation Service
3
+ *
4
+ * Implements sleep-based memory consolidation:
5
+ * - Episodic → Semantic (pattern extraction)
6
+ * - Episodic → Procedural (skill learning)
7
+ * - Forgetting weak memories
8
+ * - Merging similar memories
9
+ *
10
+ * Inspired by:
11
+ * - Memory consolidation during sleep (Walker & Stickgold, 2006)
12
+ * - Systems consolidation theory (McClelland et al., 1995)
13
+ * - Schema theory (Bartlett, 1932)
14
+ */
15
+ import { ConsolidationResult, ConsolidationConfig, MemoryEvent } from './types.js';
16
+ import { EpisodicStore } from './episodic.js';
17
+ import { SemanticStore } from './semantic.js';
18
+ import { ProceduralStore } from './procedural.js';
19
+ import { calculateForgettingStats } from './forgetting.js';
20
+ export declare class ConsolidationService {
21
+ private episodicStore;
22
+ private semanticStore;
23
+ private proceduralStore;
24
+ private config;
25
+ private backgroundTimer;
26
+ private isConsolidating;
27
+ private lastConsolidation;
28
+ private consolidationHistory;
29
+ private eventLog;
30
+ constructor(episodicStore: EpisodicStore, semanticStore: SemanticStore, proceduralStore: ProceduralStore, config?: Partial<ConsolidationConfig>);
31
+ /**
32
+ * Run full consolidation cycle (sleep mode)
33
+ */
34
+ sleep(): Promise<ConsolidationResult>;
35
+ /**
36
+ * Run quick consolidation (background)
37
+ */
38
+ backgroundConsolidate(): Promise<ConsolidationResult>;
39
+ /**
40
+ * Run immediate consolidation for specific memories
41
+ */
42
+ immediateConsolidate(episodeIds: string[]): Promise<ConsolidationResult>;
43
+ /**
44
+ * Core consolidation logic
45
+ */
46
+ private consolidate;
47
+ /**
48
+ * Process a batch of episodes
49
+ */
50
+ private processEpisodes;
51
+ /**
52
+ * Group similar episodes together
53
+ */
54
+ private groupSimilarEpisodes;
55
+ /**
56
+ * Calculate similarity between two episodes
57
+ */
58
+ private episodeSimilarity;
59
+ /**
60
+ * Extract a semantic fact from a group of similar episodes
61
+ */
62
+ private extractFact;
63
+ /**
64
+ * Extract a procedural skill from a group of similar episodes
65
+ */
66
+ private extractProcedure;
67
+ /**
68
+ * Merge multiple similar episodes into one
69
+ */
70
+ private mergeEpisodes;
71
+ /**
72
+ * Start background consolidation timer
73
+ */
74
+ startBackground(): void;
75
+ /**
76
+ * Stop background consolidation
77
+ */
78
+ stopBackground(): void;
79
+ /**
80
+ * Check if background consolidation is running
81
+ */
82
+ isBackgroundRunning(): boolean;
83
+ private logEvent;
84
+ getStats(): {
85
+ lastConsolidation: Date | null;
86
+ isConsolidating: boolean;
87
+ backgroundRunning: boolean;
88
+ totalConsolidations: number;
89
+ recentResults: ConsolidationResult[];
90
+ memoryStats: {
91
+ episodic: ReturnType<typeof calculateForgettingStats>;
92
+ semantic: ReturnType<typeof calculateForgettingStats>;
93
+ procedural: ReturnType<typeof calculateForgettingStats>;
94
+ };
95
+ };
96
+ getHistory(limit?: number): ConsolidationResult[];
97
+ getEventLog(limit?: number): MemoryEvent[];
98
+ }
99
+ export declare function createConsolidationService(episodicStore: EpisodicStore, semanticStore: SemanticStore, proceduralStore: ProceduralStore, config?: Partial<ConsolidationConfig>): ConsolidationService;