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,555 @@
1
+ "use strict";
2
+ /**
3
+ * Genesis 6.1 - Active Inference Core
4
+ *
5
+ * Pure mathematics for Active Inference (pymdp-style)
6
+ *
7
+ * Based on:
8
+ * - Free Energy Principle (Friston)
9
+ * - pymdp library (Python Active Inference)
10
+ * - RxInfer.jl (reactive message passing)
11
+ *
12
+ * Key functions:
13
+ * - inferStates: Update beliefs given observations
14
+ * - inferPolicies: Select policy by minimizing Expected Free Energy
15
+ * - sampleAction: Sample action from policy
16
+ *
17
+ * NO external dependencies - pure TypeScript math.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.ActiveInferenceEngine = void 0;
21
+ exports.createActiveInferenceEngine = createActiveInferenceEngine;
22
+ const types_js_1 = require("./types.js");
23
+ // ============================================================================
24
+ // Math Utilities
25
+ // ============================================================================
26
+ /**
27
+ * Softmax function: converts log-probabilities to probabilities
28
+ */
29
+ function softmax(logits, temperature = 1.0) {
30
+ const maxLogit = Math.max(...logits);
31
+ const exps = logits.map(l => Math.exp((l - maxLogit) / temperature));
32
+ const sum = exps.reduce((a, b) => a + b, 0);
33
+ return exps.map(e => e / sum);
34
+ }
35
+ /**
36
+ * Normalize a probability distribution
37
+ */
38
+ function normalize(probs) {
39
+ const sum = probs.reduce((a, b) => a + b, 0);
40
+ if (sum === 0)
41
+ return probs.map(() => 1 / probs.length);
42
+ return probs.map(p => p / sum);
43
+ }
44
+ /**
45
+ * Entropy of a probability distribution
46
+ */
47
+ function entropy(probs) {
48
+ return -probs.reduce((acc, p) => {
49
+ if (p > 1e-10) {
50
+ return acc + p * Math.log(p);
51
+ }
52
+ return acc;
53
+ }, 0);
54
+ }
55
+ /**
56
+ * KL divergence: D_KL(P || Q)
57
+ * Reserved for future variational free energy computation
58
+ */
59
+ function _klDivergence(p, q) {
60
+ return p.reduce((acc, pi, i) => {
61
+ if (pi > 1e-10 && q[i] > 1e-10) {
62
+ return acc + pi * Math.log(pi / q[i]);
63
+ }
64
+ return acc;
65
+ }, 0);
66
+ }
67
+ /**
68
+ * Dot product
69
+ */
70
+ function dot(a, b) {
71
+ return a.reduce((acc, ai, i) => acc + ai * b[i], 0);
72
+ }
73
+ /**
74
+ * Matrix-vector multiplication
75
+ */
76
+ function matVec(matrix, vec) {
77
+ return matrix.map(row => dot(row, vec));
78
+ }
79
+ /**
80
+ * Log of a value with numerical stability
81
+ */
82
+ function safeLog(x) {
83
+ return Math.log(Math.max(x, 1e-10));
84
+ }
85
+ // ============================================================================
86
+ // Default Generative Model (Priors)
87
+ // ============================================================================
88
+ function createDefaultAMatrix() {
89
+ // A matrix: P(observation | hidden_state)
90
+ // Each row sums to 1
91
+ // Energy observation given viability (strong mapping)
92
+ const energyA = [
93
+ [0.8, 0.15, 0.04, 0.005, 0.005], // obs=depleted
94
+ [0.15, 0.7, 0.1, 0.04, 0.01], // obs=low
95
+ [0.04, 0.1, 0.72, 0.1, 0.04], // obs=medium
96
+ [0.01, 0.04, 0.1, 0.7, 0.15], // obs=high
97
+ [0.005, 0.005, 0.04, 0.15, 0.8], // obs=full
98
+ ];
99
+ // Phi observation given worldState
100
+ const phiA = [
101
+ [0.7, 0.1, 0.15, 0.05], // obs=dormant
102
+ [0.2, 0.5, 0.2, 0.1], // obs=low
103
+ [0.08, 0.3, 0.5, 0.12], // obs=medium
104
+ [0.02, 0.1, 0.15, 0.73], // obs=high
105
+ ];
106
+ // Tool observation given coupling
107
+ const toolA = [
108
+ [0.7, 0.5, 0.2, 0.1, 0.05], // obs=failed
109
+ [0.25, 0.4, 0.5, 0.4, 0.25], // obs=partial
110
+ [0.05, 0.1, 0.3, 0.5, 0.7], // obs=success
111
+ ];
112
+ // Coherence observation given worldState
113
+ const coherenceA = [
114
+ [0.3, 0.1, 0.3, 0.7], // obs=broken
115
+ [0.4, 0.3, 0.5, 0.25], // obs=degraded
116
+ [0.3, 0.6, 0.2, 0.05], // obs=consistent
117
+ ];
118
+ // Task observation given goalProgress
119
+ const taskA = [
120
+ [0.8, 0.3, 0.1, 0.05], // obs=none
121
+ [0.15, 0.5, 0.2, 0.05], // obs=pending
122
+ [0.04, 0.15, 0.6, 0.1], // obs=active
123
+ [0.01, 0.05, 0.1, 0.8], // obs=completed
124
+ ];
125
+ return {
126
+ energy: energyA,
127
+ phi: phiA,
128
+ tool: toolA,
129
+ coherence: coherenceA,
130
+ task: taskA,
131
+ };
132
+ }
133
+ function createDefaultBMatrix() {
134
+ // B matrix: P(next_state | current_state, action)
135
+ // B[next][current][action]
136
+ const numActions = types_js_1.ACTION_COUNT;
137
+ // Helper to create identity-like transition (mostly stays same)
138
+ function createIdentityTransition(dim) {
139
+ const B = [];
140
+ for (let next = 0; next < dim; next++) {
141
+ B[next] = [];
142
+ for (let curr = 0; curr < dim; curr++) {
143
+ B[next][curr] = [];
144
+ for (let act = 0; act < numActions; act++) {
145
+ // Default: high probability of staying same
146
+ B[next][curr][act] = next === curr ? 0.7 : 0.3 / (dim - 1);
147
+ }
148
+ }
149
+ }
150
+ return B;
151
+ }
152
+ const viabilityB = createIdentityTransition(types_js_1.HIDDEN_STATE_DIMS.viability);
153
+ const worldStateB = createIdentityTransition(types_js_1.HIDDEN_STATE_DIMS.worldState);
154
+ const couplingB = createIdentityTransition(types_js_1.HIDDEN_STATE_DIMS.coupling);
155
+ const goalProgressB = createIdentityTransition(types_js_1.HIDDEN_STATE_DIMS.goalProgress);
156
+ // Customize transitions for specific actions
157
+ // Action 0: sense.mcp - improves coupling
158
+ for (let curr = 0; curr < 5; curr++) {
159
+ for (let next = 0; next < 5; next++) {
160
+ // Increase coupling
161
+ couplingB[next][curr][0] = next === Math.min(curr + 1, 4) ? 0.6 : 0.1;
162
+ }
163
+ }
164
+ // Action 1: recall.memory - improves worldState understanding
165
+ for (let curr = 0; curr < 4; curr++) {
166
+ for (let next = 0; next < 4; next++) {
167
+ worldStateB[next][curr][1] = next === 1 ? 0.6 : 0.13; // Move toward stable
168
+ }
169
+ }
170
+ // Action 2: plan.goals - improves goalProgress
171
+ for (let curr = 0; curr < 4; curr++) {
172
+ for (let next = 0; next < 4; next++) {
173
+ goalProgressB[next][curr][2] = next === Math.min(curr + 1, 3) ? 0.5 : 0.17;
174
+ }
175
+ }
176
+ // Action 4: execute.task - major goalProgress boost
177
+ for (let curr = 0; curr < 4; curr++) {
178
+ for (let next = 0; next < 4; next++) {
179
+ goalProgressB[next][curr][4] = next === 3 ? 0.4 : 0.2; // Jump to achieved
180
+ }
181
+ }
182
+ // Action 5: dream.cycle - consolidates worldState
183
+ for (let curr = 0; curr < 4; curr++) {
184
+ for (let next = 0; next < 4; next++) {
185
+ worldStateB[next][curr][5] = next === 1 ? 0.5 : 0.17; // Move toward stable
186
+ }
187
+ }
188
+ // Action 6: rest.idle - slight viability recovery
189
+ for (let curr = 0; curr < 5; curr++) {
190
+ for (let next = 0; next < 5; next++) {
191
+ viabilityB[next][curr][6] = next === Math.min(curr + 1, 4) ? 0.4 : 0.15;
192
+ }
193
+ }
194
+ // Action 7: recharge - major viability boost
195
+ for (let curr = 0; curr < 5; curr++) {
196
+ for (let next = 0; next < 5; next++) {
197
+ viabilityB[next][curr][7] = next === 4 ? 0.7 : 0.075; // Jump to optimal
198
+ }
199
+ }
200
+ // Normalize B matrices
201
+ function normalizeB(B) {
202
+ const dim = B.length;
203
+ for (let curr = 0; curr < dim; curr++) {
204
+ for (let act = 0; act < numActions; act++) {
205
+ const col = B.map(next => next[curr][act]);
206
+ const sum = col.reduce((a, b) => a + b, 0);
207
+ if (sum > 0) {
208
+ for (let next = 0; next < dim; next++) {
209
+ B[next][curr][act] /= sum;
210
+ }
211
+ }
212
+ }
213
+ }
214
+ return B;
215
+ }
216
+ return {
217
+ viability: normalizeB(viabilityB),
218
+ worldState: normalizeB(worldStateB),
219
+ coupling: normalizeB(couplingB),
220
+ goalProgress: normalizeB(goalProgressB),
221
+ };
222
+ }
223
+ function createDefaultCMatrix() {
224
+ // C matrix: log P(preferred observation)
225
+ // Positive = attractive, Negative = aversive
226
+ return {
227
+ // Strongly prefer high energy
228
+ energy: [-10, -5, 0, 2, 4],
229
+ // Prefer high consciousness
230
+ phi: [-5, -1, 1, 3],
231
+ // Prefer successful tool calls
232
+ tool: [-3, 0, 2],
233
+ // Prefer coherent world model
234
+ coherence: [-4, 0, 2],
235
+ // Strongly prefer task completion
236
+ task: [-2, 0, 1, 5],
237
+ };
238
+ }
239
+ function createDefaultDMatrix() {
240
+ // D matrix: Prior beliefs about initial state
241
+ // Uniform priors
242
+ return {
243
+ viability: normalize([1, 1, 2, 1, 1]), // Slight bias toward medium
244
+ worldState: normalize([2, 1, 1, 1]), // Slight bias toward unknown
245
+ coupling: normalize([2, 1, 1, 1, 1]), // Slight bias toward none
246
+ goalProgress: normalize([1, 2, 1, 1]), // Slight bias toward slow
247
+ };
248
+ }
249
+ // ============================================================================
250
+ // Active Inference Engine
251
+ // ============================================================================
252
+ class ActiveInferenceEngine {
253
+ config;
254
+ // Generative model
255
+ A;
256
+ B;
257
+ C;
258
+ D;
259
+ // Current beliefs
260
+ beliefs;
261
+ // Event handlers
262
+ eventHandlers = [];
263
+ // Statistics
264
+ stats = {
265
+ inferenceCount: 0,
266
+ totalSurprise: 0,
267
+ actionsTaken: new Map(),
268
+ };
269
+ constructor(config = {}) {
270
+ this.config = { ...types_js_1.DEFAULT_CONFIG, ...config };
271
+ // Initialize generative model
272
+ this.A = createDefaultAMatrix();
273
+ this.B = createDefaultBMatrix();
274
+ this.C = createDefaultCMatrix();
275
+ this.D = createDefaultDMatrix();
276
+ // Initialize beliefs to priors
277
+ this.beliefs = {
278
+ viability: [...this.D.viability],
279
+ worldState: [...this.D.worldState],
280
+ coupling: [...this.D.coupling],
281
+ goalProgress: [...this.D.goalProgress],
282
+ };
283
+ }
284
+ // ============================================================================
285
+ // Core Inference Functions
286
+ // ============================================================================
287
+ /**
288
+ * Update beliefs given observations (state inference)
289
+ *
290
+ * Uses Bayesian inference:
291
+ * P(s|o) ∝ P(o|s) * P(s)
292
+ *
293
+ * Iterates to find fixed point (variational inference)
294
+ */
295
+ inferStates(observation) {
296
+ const prior = this.beliefs;
297
+ // Compute likelihoods for each factor
298
+ const likelihoods = this.computeLikelihoods(observation);
299
+ // Update each factor independently (mean-field approximation)
300
+ const posterior = {
301
+ viability: this.updateFactor(prior.viability, likelihoods.viability),
302
+ worldState: this.updateFactor(prior.worldState, likelihoods.worldState),
303
+ coupling: this.updateFactor(prior.coupling, likelihoods.coupling),
304
+ goalProgress: this.updateFactor(prior.goalProgress, likelihoods.goalProgress),
305
+ };
306
+ // Iterate for convergence
307
+ for (let i = 0; i < this.config.inferenceIterations; i++) {
308
+ posterior.viability = this.updateFactor(posterior.viability, likelihoods.viability);
309
+ posterior.worldState = this.updateFactor(posterior.worldState, likelihoods.worldState);
310
+ posterior.coupling = this.updateFactor(posterior.coupling, likelihoods.coupling);
311
+ posterior.goalProgress = this.updateFactor(posterior.goalProgress, likelihoods.goalProgress);
312
+ }
313
+ // Store updated beliefs
314
+ this.beliefs = posterior;
315
+ this.stats.inferenceCount++;
316
+ // Compute and track surprise
317
+ const surprise = this.computeSurprise(observation);
318
+ this.stats.totalSurprise += surprise;
319
+ // Emit event
320
+ this.emit({
321
+ type: 'beliefs_updated',
322
+ timestamp: new Date(),
323
+ data: { beliefs: posterior, surprise },
324
+ });
325
+ if (surprise > 5) {
326
+ this.emit({
327
+ type: 'surprise_high',
328
+ timestamp: new Date(),
329
+ data: { surprise, observation },
330
+ });
331
+ }
332
+ return posterior;
333
+ }
334
+ /**
335
+ * Infer policies by minimizing Expected Free Energy (EFE)
336
+ *
337
+ * EFE = ambiguity + risk
338
+ * = E[H(o|s,π)] + D_KL[Q(s|π) || P(s)]
339
+ *
340
+ * Lower EFE = better policy
341
+ */
342
+ inferPolicies() {
343
+ const efe = [];
344
+ // Compute EFE for each action
345
+ for (let a = 0; a < types_js_1.ACTION_COUNT; a++) {
346
+ efe[a] = this.computeEFE(a);
347
+ }
348
+ // Convert to policy via softmax (lower EFE = higher probability)
349
+ const negEfe = efe.map(e => -e);
350
+ const policy = softmax(negEfe, this.config.actionTemperature);
351
+ this.emit({
352
+ type: 'policy_inferred',
353
+ timestamp: new Date(),
354
+ data: { efe, policy },
355
+ });
356
+ return policy;
357
+ }
358
+ /**
359
+ * Sample action from policy
360
+ */
361
+ sampleAction(policy) {
362
+ // Sample from categorical distribution
363
+ const r = Math.random();
364
+ let cumsum = 0;
365
+ let selectedIdx = 0;
366
+ for (let i = 0; i < policy.length; i++) {
367
+ cumsum += policy[i];
368
+ if (r < cumsum) {
369
+ selectedIdx = i;
370
+ break;
371
+ }
372
+ }
373
+ const action = types_js_1.ACTIONS[selectedIdx];
374
+ // Track statistics
375
+ const count = this.stats.actionsTaken.get(action) || 0;
376
+ this.stats.actionsTaken.set(action, count + 1);
377
+ this.emit({
378
+ type: 'action_selected',
379
+ timestamp: new Date(),
380
+ data: { action, probability: policy[selectedIdx] },
381
+ });
382
+ return action;
383
+ }
384
+ /**
385
+ * Full inference cycle: observe → infer → act
386
+ */
387
+ step(observation) {
388
+ // 1. Update beliefs
389
+ this.inferStates(observation);
390
+ // 2. Infer policy
391
+ const policy = this.inferPolicies();
392
+ // 3. Sample action
393
+ const action = this.sampleAction(policy);
394
+ return action;
395
+ }
396
+ // ============================================================================
397
+ // Helper Functions
398
+ // ============================================================================
399
+ computeLikelihoods(observation) {
400
+ // Compute P(observation | state) for each factor
401
+ // Energy observation → viability likelihood
402
+ const viabilityLik = this.A.energy[observation.energy].map(p => safeLog(p));
403
+ // Phi observation → worldState likelihood (proxy)
404
+ const worldStateLik = this.A.phi[observation.phi].map(p => safeLog(p));
405
+ // Tool observation → coupling likelihood
406
+ const couplingLik = this.A.tool[observation.tool].map(p => safeLog(p));
407
+ // Task observation → goalProgress likelihood
408
+ const goalProgressLik = this.A.task[observation.task].map(p => safeLog(p));
409
+ // Coherence affects worldState
410
+ const coherenceLik = this.A.coherence[observation.coherence];
411
+ for (let i = 0; i < worldStateLik.length; i++) {
412
+ worldStateLik[i] += safeLog(coherenceLik[i] || 0.1);
413
+ }
414
+ return {
415
+ viability: viabilityLik,
416
+ worldState: worldStateLik,
417
+ coupling: couplingLik,
418
+ goalProgress: goalProgressLik,
419
+ };
420
+ }
421
+ updateFactor(prior, logLikelihood) {
422
+ // Posterior ∝ likelihood * prior
423
+ const logPrior = prior.map(p => safeLog(p));
424
+ const logPosterior = logLikelihood.map((ll, i) => ll + logPrior[i]);
425
+ return softmax(logPosterior, 1.0);
426
+ }
427
+ computeEFE(actionIdx) {
428
+ // Expected Free Energy for a single action
429
+ // 1. Predicted next state distribution Q(s'|a)
430
+ const predictedViability = this.predictNextState(this.beliefs.viability, this.B.viability, actionIdx);
431
+ const predictedWorldState = this.predictNextState(this.beliefs.worldState, this.B.worldState, actionIdx);
432
+ const predictedCoupling = this.predictNextState(this.beliefs.coupling, this.B.coupling, actionIdx);
433
+ const predictedGoalProgress = this.predictNextState(this.beliefs.goalProgress, this.B.goalProgress, actionIdx);
434
+ // 2. Expected observations under predicted states
435
+ const expectedEnergy = matVec(this.A.energy, predictedViability);
436
+ const expectedPhi = matVec(this.A.phi, predictedWorldState);
437
+ const expectedTool = matVec(this.A.tool, predictedCoupling);
438
+ const expectedTask = matVec(this.A.task, predictedGoalProgress);
439
+ // 3. Ambiguity: entropy of predicted observations
440
+ const ambiguity = entropy(expectedEnergy) +
441
+ entropy(expectedPhi) +
442
+ entropy(expectedTool) +
443
+ entropy(expectedTask);
444
+ // 4. Risk: negative expected utility (preferences)
445
+ const risk = -dot(expectedEnergy, this.C.energy) +
446
+ -dot(expectedPhi, this.C.phi) +
447
+ -dot(expectedTool, this.C.tool) +
448
+ -dot(expectedTask, this.C.task);
449
+ // EFE = ambiguity + risk
450
+ return ambiguity + risk;
451
+ }
452
+ predictNextState(currentBeliefs, transitionMatrix, actionIdx) {
453
+ // P(s'|a) = sum_s P(s'|s,a) * P(s)
454
+ const dim = currentBeliefs.length;
455
+ const predicted = new Array(dim).fill(0);
456
+ for (let next = 0; next < dim; next++) {
457
+ for (let curr = 0; curr < dim; curr++) {
458
+ predicted[next] += transitionMatrix[next][curr][actionIdx] * currentBeliefs[curr];
459
+ }
460
+ }
461
+ return normalize(predicted);
462
+ }
463
+ computeSurprise(observation) {
464
+ // Surprise = -log P(o|beliefs)
465
+ const expectedEnergy = matVec(this.A.energy, this.beliefs.viability);
466
+ const expectedPhi = matVec(this.A.phi, this.beliefs.worldState);
467
+ const expectedTool = matVec(this.A.tool, this.beliefs.coupling);
468
+ const expectedTask = matVec(this.A.task, this.beliefs.goalProgress);
469
+ const surprise = -safeLog(expectedEnergy[observation.energy]) +
470
+ -safeLog(expectedPhi[observation.phi]) +
471
+ -safeLog(expectedTool[observation.tool]) +
472
+ -safeLog(expectedTask[observation.task]);
473
+ return surprise;
474
+ }
475
+ // ============================================================================
476
+ // Public Getters
477
+ // ============================================================================
478
+ getBeliefs() {
479
+ return { ...this.beliefs };
480
+ }
481
+ getStats() {
482
+ return {
483
+ inferenceCount: this.stats.inferenceCount,
484
+ averageSurprise: this.stats.inferenceCount > 0
485
+ ? this.stats.totalSurprise / this.stats.inferenceCount
486
+ : 0,
487
+ actionCounts: Object.fromEntries(this.stats.actionsTaken),
488
+ };
489
+ }
490
+ getMostLikelyState() {
491
+ const argmax = (arr) => arr.indexOf(Math.max(...arr));
492
+ return {
493
+ viability: ['critical', 'low', 'medium', 'high', 'optimal'][argmax(this.beliefs.viability)],
494
+ worldState: ['unknown', 'stable', 'changing', 'hostile'][argmax(this.beliefs.worldState)],
495
+ coupling: ['none', 'weak', 'medium', 'strong', 'synced'][argmax(this.beliefs.coupling)],
496
+ goalProgress: ['blocked', 'slow', 'onTrack', 'achieved'][argmax(this.beliefs.goalProgress)],
497
+ };
498
+ }
499
+ // ============================================================================
500
+ // Event Handling
501
+ // ============================================================================
502
+ on(handler) {
503
+ this.eventHandlers.push(handler);
504
+ return () => {
505
+ const idx = this.eventHandlers.indexOf(handler);
506
+ if (idx >= 0)
507
+ this.eventHandlers.splice(idx, 1);
508
+ };
509
+ }
510
+ emit(event) {
511
+ for (const handler of this.eventHandlers) {
512
+ try {
513
+ handler(event);
514
+ }
515
+ catch (e) {
516
+ console.error('AI event handler error:', e);
517
+ }
518
+ }
519
+ }
520
+ // ============================================================================
521
+ // Model Updates (Online Learning)
522
+ // ============================================================================
523
+ /**
524
+ * Update A matrix based on observation-state pairs (supervised)
525
+ */
526
+ updateAMatrix(observation, trueState) {
527
+ // Simple counting update for A matrix
528
+ // In practice, would use proper Dirichlet updates
529
+ if (trueState.viability) {
530
+ const stateIdx = trueState.viability.indexOf(Math.max(...trueState.viability));
531
+ this.A.energy[observation.energy][stateIdx] += this.config.learningRateA;
532
+ // Re-normalize
533
+ const sum = this.A.energy[observation.energy].reduce((a, b) => a + b, 0);
534
+ this.A.energy[observation.energy] = this.A.energy[observation.energy].map(p => p / sum);
535
+ }
536
+ }
537
+ /**
538
+ * Reset beliefs to priors
539
+ */
540
+ resetBeliefs() {
541
+ this.beliefs = {
542
+ viability: [...this.D.viability],
543
+ worldState: [...this.D.worldState],
544
+ coupling: [...this.D.coupling],
545
+ goalProgress: [...this.D.goalProgress],
546
+ };
547
+ }
548
+ }
549
+ exports.ActiveInferenceEngine = ActiveInferenceEngine;
550
+ // ============================================================================
551
+ // Factory
552
+ // ============================================================================
553
+ function createActiveInferenceEngine(config) {
554
+ return new ActiveInferenceEngine(config);
555
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Demo: Autonomous Loop with Value Integration
3
+ *
4
+ * Runs the autonomous inference loop with value-augmented policy selection.
5
+ *
6
+ * Run: node dist/src/active-inference/demo-autonomous-loop.js
7
+ */
8
+ export {};